text stringlengths 13 6.01M |
|---|
using System.IO;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
namespace Theatre.Services
{
public interface INavigationService
{
//Task InitializeAsync();
//Task NavigateToAsync<TViewModel>() where TViewModel : ViewModelBase;
//Task NavigateToAsync<TViewModel>(object parameter) where TViewModel : ViewModelBase;
//Task RemoveLastFromBackStackAsync();
//Task RemoveBackStackAsync();
}
} |
using Model;
namespace common
{
public class AdminUtil : System.Web.UI.Page
{
public static Admin HasLogined()
{
return null;
}
}
} |
namespace DistCWebSite.Core.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class CC_InstallationRateAfterInst
{
public int ID { get; set; }
[StringLength(25)]
public string DistributorCode { get; set; }
[StringLength(100)]
public string DistributorName { get; set; }
public int? Disqualification { get; set; }
public int? Qualified { get; set; }
public DateTime? Month { get; set; }
//public decimal? Target { get; set; }
}
}
|
namespace ApiSoftPlan.Models
{
/// <summary>The settings.</summary>
public class Settings
{
/// <summary>Gets or sets the interest.</summary>
public int Interest { get; set; }
/// <summary>The interest calculated.</summary>
public double InterestCalculated => (double)Interest / 100;
/// <summary>Gets or sets the decimal cases.</summary>
public int DecimalCases { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace CQRSWebAPI.DTOs
{
public class ResponseDto
{
public HttpStatusCode HttpStatusCode { get; init; } = HttpStatusCode.OK;
public string ErrorMessaging { get; init; }
}
} |
using System;
namespace SortingArrayOfObjects
{
class Program
{
static void Main(string[] args)
{
#region Sorting an array
// Demo1.Run();
#endregion
#region Implementing IComparable to sort an array of objects
// Demo2.Run();
#endregion
#region Using class that implements IComparer
Demo3.Run();
#endregion
}
}
}
|
using System;
using System.IO;
namespace Week9ICE1
{
class MainClass
{
public static void Main(string[] args)
{
string data = File.ReadAllText("/Users/Parker/Documents/College/MSIS2203/Week9ICE1/GDPdata.csv");
Console.WriteLine(data);
int a = 20 / 3;
Console.WriteLine(a);
for (int r = 0; r < 5; r++)
{
for (int c = 0; c < 4; c++)
{
Console.WriteLine((r + c) + " ");
}
Console.WriteLine();
}
}
}
}
|
using Restaurants.Domain;
namespace Restaurants.Application
{
public interface IPaymentOptionAppService : IAppServiceBase<PaymentOption>
{
}
}
|
using AbstractFactoryPattern.Abstractions;
namespace AbstractFactoryPattern.Ingredients
{
public class FreshClams : IClams
{
public string Name { get; } = "Fresh Clams";
}
}
|
namespace VisualStudioShell.Controls
{
public class TreeNodeDataBase
{
public TreeNodeDataBase(string name)
{
Name = name;
}
public string Name { get; set; }
}
public class TreeNodeData : TreeNodeDataBase
{
public TreeNodeData(string name, bool isFolder, string image = null) : base(name)
{
IsFolder = isFolder;
ImagePath = "/Images/SolutionExplorer/" + image;
}
public string ImagePath { get; set; }
public bool IsFolder { get; set; }
}
}
|
using System.Runtime.Serialization;
namespace XH.APIs.WebAPI.Models.Enterprises
{
[DataContract]
public class HazardDeviceRequestModel
{
[DataMember]
public string Material { get; set; }
[DataMember]
public string Pressure { get; set; }
[DataMember]
public string Temperature { get; set; }
/// <summary>
/// 入口管径
/// </summary>
[DataMember]
public string InletDiameter { get; set; }
/// <summary>
/// 出口管径
/// </summary>
[DataMember]
public string OutletDiameter { get; set; }
/// <summary>
/// 流量
/// </summary>
[DataMember]
public string Flow { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace PatronPrototipo
{
class CAdministrarClones
{
private Dictionary<string, IPrototipo> catalogoClones = new Dictionary<string, IPrototipo>();
public CAdministrarClones()
{
CPersona persona = new CPersona("Ciudadano", 18);
catalogoClones.Add("persona", persona);
CPrecio valores = new CPrecio(1);
catalogoClones.Add("valores", valores);
}
public void adicionarClones(string pLlave, IPrototipo pPrototipo)
{
catalogoClones.Add(pLlave, pPrototipo);
}
public object obtenerClones(string pLlave)
{
return catalogoClones[pLlave].Clonar();
}
}
}
|
using System;
using KeepTeamAutotests;
using KeepTeamAutotests.Model;
using NUnit.Framework;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.IO;
using KeepTeamAutotests.AppLogic;
namespace KeepTeamTests
{
[TestFixture()]
public class CreateCandidateTests : InternalPageTests
{
[SetUp]
public void Login()
{
app.userHelper
.loginAs(app.userHelper.getUserByRole("aCandidatesRW"));
}
[Test, TestCaseSource(typeof(FileHelper), "candidates")]
public void Create_Candidate(Candidate candidate)
{
//клик по кнопке добавления кандидата
app.userHelper.clickAddCandidateButton();
//Добавление кандидата
app.hiringHelper.createCandidate(candidate);
//создание тестовой вакансии для сравнения
Candidate testCandidate = app.hiringHelper.getCandidatePopup(candidate);
//Проверка соответствия двух вакансий.
Assert.IsTrue(app.hiringHelper.CompareCandidate(candidate, testCandidate));
}
[TearDown]
public void DeleteCurrentCandidate()
{
app.hiringHelper.DeleteCurrentCandidate();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FallstudieSem5.Models.Repository;
using Microsoft.EntityFrameworkCore;
namespace FallstudieSem5.Models.Manager
{
public class ObjectManager : IDataRepository<Object>
{
readonly Context _objectContext;
public ObjectManager(Context context)
{
_objectContext = context;
}
public IEnumerable<Object> GetAll()
{
return _objectContext.Objects.ToList();
}
public Object Get(long id)
{
return _objectContext.Objects
.FirstOrDefault(o => o.ObjectId == id);
}
public void Add(Object entity)
{
_objectContext.Objects.Add(entity);
_objectContext.SaveChanges();
}
public void Update(Object @object, Object entity)
{
@object.Description = entity.Description;
_objectContext.SaveChanges();
}
public void Delete(Object @object)
{
_objectContext.Objects.Remove(@object);
_objectContext.SaveChanges();
}
}
}
|
using System.Linq;
using Xamarin.Forms;
using XamLottie.ViewModels;
namespace XamLottie.Views
{
public partial class MainPage : ContentPage
{
MainPageViewModel _vm;
public MainPage()
{
InitializeComponent();
SetBindingContext();
}
async void Done_Tapped(object sender, System.EventArgs e)
{
await MainFrame.FadeTo(.5);
PopupFrame.IsVisible = true;
DoneAnimation.Play();
}
void All_Tapped(object sender, System.EventArgs e)
{
foreach (var task in _vm.Tasks.Where(t => !t.IsComplete))
task.IsComplete = true;
}
async void Ok_Tapped(object sender, System.EventArgs e)
{
await MainFrame.FadeTo(1);
PopupFrame.IsVisible = false;
SetBindingContext();
}
void SetBindingContext()
{
_vm = new MainPageViewModel();
BindingContext = _vm;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IState_Base
{
void OnEnterState();
void OnExitState();
void OnPauseState();
void OnResumeState();
//private void ChangeState(State_Base state)
//{
// GameManager.Instance.ChangeState(state);
//}
} |
using System;
using System.Threading.Tasks;
using AutoFixture;
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using Otiport.API.Contract.Request.Users;
using Otiport.API.Data.Entities.Users;
using Otiport.API.Mappers;
using Otiport.API.Providers;
using Otiport.API.Repositories;
using Otiport.API.Services;
using Otiport.API.Services.Implementations;
using Xunit;
namespace Otiport.Tests.UnitTests.Services
{
public class UserServiceTests : TestBase
{
private readonly Mock<ILogger<UserService>> _loggerMock;
private readonly Mock<IUserMapper> _mapperMock;
private readonly Mock<IUserRepository> _userRepositoryMock;
private readonly IUserService _userService;
private readonly Mock<ITokenProvider> _tokenProviderMock;
private readonly Mock<IConfiguration> _configurationMock;
public UserServiceTests()
{
_userRepositoryMock = MockFor<IUserRepository>();
_mapperMock = MockFor<IUserMapper>();
_loggerMock = MockFor<ILogger<UserService>>();
_tokenProviderMock = MockFor<ITokenProvider>();
_configurationMock = MockFor<IConfiguration>();
_userService = new UserService(_userRepositoryMock.Object, _mapperMock.Object, _loggerMock.Object,
_tokenProviderMock.Object, _configurationMock.Object);
}
[Fact]
public async Task LoginAsync_Should_Return_Result()
{
//Arrange
string accessToken = Guid.NewGuid().ToString();
var loginRequest = FixtureRepository.Create<LoginRequest>();
var userEntity = FixtureRepository.Build<UserEntity>().Without(x => x.Patients).Without(x => x.UserGroup)
.Create();
_userRepositoryMock
.Setup(x => x.GetUserByCredentialsAsync(loginRequest.EmailAddress, loginRequest.Password))
.Returns(Task.FromResult(userEntity));
_tokenProviderMock
.Setup(x => x.GenerateTokenAsync(userEntity.Id, userEntity.EmailAddress, userEntity.UserGroupId))
.Returns(Task.FromResult(accessToken));
//Act
var result = await _userService.LoginAsync(loginRequest);
//Assert
result.IsSuccess.Should().BeTrue();
result.AccessToken.Should().NotBeNullOrEmpty();
result.AccessToken.Should().Be(accessToken);
}
[Fact]
public async Task LoginAsync_Should_Return_NotFound_When_UserEntity_Is_Null()
{
//Arrange
string accessToken = Guid.NewGuid().ToString();
var loginRequest = FixtureRepository.Create<LoginRequest>();
_userRepositoryMock
.Setup(x => x.GetUserByCredentialsAsync(loginRequest.EmailAddress, loginRequest.Password))
.Returns(Task.FromResult(default(UserEntity)));
//Act
var result = await _userService.LoginAsync(loginRequest);
//Assert
result.IsSuccess.Should().BeFalse();
result.AccessToken.Should().BeNullOrEmpty();
}
}
} |
using ArgumentRes.Attributes;
using ArgumentRes.Services.implementations;
using System;
using System.Collections.Generic;
namespace ArgumentHandler
{
internal class Program
{
internal class Arguments
{
[Flag(Key = "c", Description="Number of pings to send")]
[Mandatory]
public int Pings { get; set; }
[Flag(Key = "t", Description = "Tengu Maru is the sea where Tengu comes from. Tengu is a penguin don't you know?")]
[Mandatory]
public string TenguMaru { get; set; }
[Flag(Key = "x", Description = "no value")]
[Mandatory]
public bool IsSet { get; set; }
[Flag(Key = "v", Description = "Victory Name")]
public string VictoryName { get; set; }
[Parameter(Key = "host", Description = "The name of the host")]
public string Host { get; set; }
[Parameter(Key = "...", Description = "Files to process")]
public List<string> FilesToProcess { get; set; }
}
private static void Main(string[] args)
{
var argumentor = new Argumentor<Arguments>();
try
{
var commandLineArguments = argumentor.Parse(args);
Console.WriteLine($"Pings : {commandLineArguments.Pings}");
Console.WriteLine($"TenguMaru : {commandLineArguments.TenguMaru}");
Console.WriteLine($"IsSet : {commandLineArguments.IsSet}");
Console.WriteLine($"VictoryName : {commandLineArguments.VictoryName}");
Console.WriteLine($"Host : {commandLineArguments.Host}");
foreach (var s in commandLineArguments.FilesToProcess)
{
Console.WriteLine($"Argument : {s}");
}
}
catch (Exception e)
{
Console.Write("ERROR ");
Console.WriteLine(e.Message);
Console.WriteLine();
Console.WriteLine(new UsageFormatter<Arguments>().ToString());
}
Console.ReadLine();
return;
}
}
}
|
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class CancelTransportEvent : Event
{
public const string NAME = "Cancel transport";
public const string DESCRIPTION = "Triggered when canceling a taxi or deployment for on foot combat";
public const string SAMPLE = "{ \"timestamp\":\"2021-03-30T22:30:18Z\", \"event\":\"CancelTaxi\", \"Refund\":100 }";
[PublicAPI(@"The type of transport being cancelled (e.g. ""Taxi"", ""Dropship"")")]
public string transporttype { get; }
[PublicAPI("The credits that you were refunded for the cancelled transport)")]
public int? refund { get; }
public CancelTransportEvent(DateTime timestamp, string transporttype, int? refund) : base(timestamp, NAME)
{
this.transporttype = transporttype;
this.refund = refund;
}
}
} |
using System;
using System.Collections.Generic;
namespace DSA_4
{
public class Graph
{
public int MaxEdges { get; private set; }
public int MaxVertexes { get; private set; }
public bool[,] Matrix { get; set; }
/* Constructor */
public Graph(int maxEdges, int maxVertexes)
{
MaxEdges = maxEdges;
MaxVertexes = maxVertexes;
Matrix = new bool[MaxVertexes, MaxEdges];
}
/* Misc methods */
public void Connect(int vertex1, int vertex2)
{
Matrix[vertex1, vertex2] = true;
}
public void Show()
{
for (int vertexIndex = 0; vertexIndex < MaxVertexes; vertexIndex++)
{
for (int edgeIndex = 0; edgeIndex < MaxEdges; edgeIndex++)
{
if (IsMarkedInMatrix(vertexIndex, edgeIndex)) Console.Write(" 1 ");
else Console.Write(" 0 ");
}
Console.WriteLine();
}
}
/* Private helper methods */
private bool IsMarkedInMatrix(int vertexIndex, int edgeIndex)
{
return Matrix[vertexIndex, edgeIndex];
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace Domaci8_9_10
{
[Serializable]
class Placanje
{
private int id;
private string nacinPlacanja;
private DateTime datum;
public int ID
{
get { return id; }
set { id = value; }
}
public string NacinPlacanja
{
get { return nacinPlacanja; }
set
{
if (value == "")
throw new Exception("Morate uneti nacin placanja!!!");
nacinPlacanja = value;
}
}
public DateTime Datum
{
get { return datum; }
set { datum = value; }
}
private string _connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Marko\\Desktop\\Domaci C#\\Domaci8-9-10\\Domaci8-9-10\\prodajaIgara.mdf;Integrated Security=True;User Instance=True";
public void dodajPlacanje()
{
string insertSql = "INSERT INTO T_Placanje " +
"(nacinPlacanja, Datum) VALUES (@nacinPlacanja, @Datum)";
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = insertSql;
command.Parameters.Add(new SqlParameter("@nacinPlacanja", NacinPlacanja));
command.Parameters.Add(new SqlParameter("@Datum", Datum));
connection.Open();
command.ExecuteNonQuery();
}
}
public void azurirajPlacanje()
{
string updateSql =
"UPDATE T_Placanje " +
"SET Nacin = @nacinPlacanja, Datum = @Datum " +
"WHERE idplacanja = @idplacanja";
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = updateSql;
command.Parameters.Add(new SqlParameter("@idplacanja", ID));
command.Parameters.Add(new SqlParameter("@nacinPlacanja", NacinPlacanja));
command.Parameters.Add(new SqlParameter("@Datum", Datum));
connection.Open();
command.ExecuteNonQuery();
}
}
public void obrisiPlacanje()
{
string deleteSql =
"DELETE FROM T_Placanje WHERE idplacanja = @idplacanja;";
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = deleteSql;
command.Parameters.Add(new SqlParameter("@idplacanja", ID));
connection.Open();
command.ExecuteNonQuery();
}
}
public List<Placanje> ucitajPlacanje()
{
List<Placanje> placanja = new List<Placanje>();
string queryString =
"SELECT * FROM T_Placanje;";
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
Placanje plat;
while (reader.Read())
{
plat = new Placanje();
plat.ID = Int32.Parse(reader["idplacanja"].ToString());
plat.nacinPlacanja = reader["nacinPlacanja"].ToString();
plat.Datum = DateTime.Parse(reader["Datum"].ToString());
placanja.Add(plat);
}
}
}
return placanja;
}
}
}
|
using System;
namespace IModelRepository
{
public interface IDBContext:IDisposable
{
ITestContext TestContext { get; set; }
IUserContext UserContext { get; set; }
IQuestionContext QuestionContext { get; set; }
}
}
|
using EduHome.Models.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.Models.Entity
{
public class Subscriber:BaseEntity
{
[Required,DataType(DataType.EmailAddress)]
public string Email { get; set; }
public Nullable<DateTime> CreatedDate { get; set; }
public bool IsDeleted { get; set; }
}
}
|
using System.Runtime.CompilerServices;
namespace iSukces.Code.Interfaces
{
/// <summary>
/// See https://docs.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019
/// </summary>
public enum CsOperatorPrecendence
{
//[ ] ( ) . -> ++ -- (postfix)
//Left to right
Expression,
//sizeof & * + - ~ ! ++ -- (prefix)
//Right to left
Unary,
//typecasts
//Right to left
UnaryTypecast,
//* / %
//Left to right
Multiplicative,
//+ -
// Left to right
Additive,
//<< >>
//Left to right
BitwiseShift,
//< > <= >=
//Left to right
Relational,
//== !=
//Left to right
Equality,
//&
//Left to right
//BitwiseAnd
//^
//Left to right
BitwiseExOr,
//|
// Left to right
BitwiseOr,
//&&
//Left to right
LogicalAnd,
//||
//Left to right
LogicalOr,
//? :
//Right to left
ConditionalExpression,
// = *= /= %=
// += -= <<= >>= &=
// ^= |=
//Right to left
SimpleAndCompoundAssignment,
//,
//Left to right
SequentialEvaluation
}
public enum CsOperatorPrecendenceAlign
{
/// <summary>
/// Like addition: 1+2+3 is equvalent to (1+2)+3
/// </summary>
LeftToRight,
/// <summary>
/// Like = : a=b=c is equvalent to b=c and then a=b
/// </summary>
RightToLeft
}
public enum ExpressionAppend
{
After,
Before
}
public static class CsOperatorPrecendenceUtils
{
public const CsOperatorPrecendence DoubleQuestion = CsOperatorPrecendence.ConditionalExpression;
public static CsOperatorPrecendenceAlign GetAlignment(this CsOperatorPrecendence codePrecedence)
{
var isRightToLeft = codePrecedence == CsOperatorPrecendence.Unary
|| codePrecedence == CsOperatorPrecendence.UnaryTypecast
|| codePrecedence == CsOperatorPrecendence.ConditionalExpression
|| codePrecedence == CsOperatorPrecendence.SimpleAndCompoundAssignment;
return isRightToLeft ? CsOperatorPrecendenceAlign.RightToLeft : CsOperatorPrecendenceAlign.LeftToRight;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AddBrackets(CsOperatorPrecendence codePrecedence,
CsOperatorPrecendence outerExpression, ExpressionAppend append)
{
if (outerExpression > codePrecedence) return false;
if (outerExpression == codePrecedence)
{
var al = GetAlignment(outerExpression);
var skip = al == CsOperatorPrecendenceAlign.LeftToRight ^ append == ExpressionAppend.After;
if (skip)
return false;
}
return true;
}
}
} |
namespace BlazorShared.Models.Room
{
public class ListRoomRequest : BaseRequest
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace test
{
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Text popUpText;
//Methods
public void PopUp(string text, int fSize)
{
popUpBox.SetActive(true);
popUpText.text = text;
popUpText.fontSize = fSize;
}
public void closePopUp()
{
popUpBox.SetActive(false);
}
void Start()
{
popUpBox.SetActive(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using System.Windows.Forms.DataVisualization.Charting;
namespace ComplexSystems {
public class Histogram {
Signal data;
double binSize = 1;
bool cumulative = false;
List<double> positiveBins = new List<double>();
List<double> negativeBins = new List<double>();
public Histogram(Signal data, double binSize) {
this.data = data;
this.binSize = binSize;
for (int i = 0; i < data.Count(); i++) {
IncrementAt((int)Math.Floor(data[i] / binSize));
}
}
/// <summary>Uses Scott's choice algorithm to assign bin width:
/// http://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width</summary>
public Histogram(Signal data) {
this.data = data;
var bS = (3.5 * data.StandardDeviation()) / Math.Pow(data.Count(), .33333333333333);
if(bS <= 0)
bS = .01;
this.binSize = bS;
for (int i = 0; i < data.Count(); i++) {
IncrementAt((int)Math.Floor(data[i] / binSize));
}
}
public Histogram Normalize() {
for (int i = 0; i < positiveBins.Count(); i++) {
positiveBins[i] /= totalNumberOfPoints;
}
for (int i = 0; i < negativeBins.Count(); i++) {
negativeBins[i] /= totalNumberOfPoints;
}
return this;
}
public Histogram(Signal data, double binSize, bool cumulative) {
this.cumulative = cumulative;
this.data = data;
this.binSize = binSize;
for (int i = 0; i < data.Count(); i++) {
IncrementAt((int)Math.Floor(data[i] / binSize));
}
}
private int totalNumberOfPoints = 0;
private void IncrementAt(int idx) {
if (idx > 100000)
throw new Exception();
totalNumberOfPoints++;
if (idx > 0) {
var dif = idx - positiveBins.Count();
for (int i = 0; i <= dif; i++) {
positiveBins.Add(0);
}
positiveBins[idx]++;
} else {
idx *= -1;
var dif =idx - negativeBins.Count() ;
for (int i = 0; i <= dif; i++) {
negativeBins.Add(0);
}
negativeBins[idx]++;
}
}
public void GraphLogLog(string label = "") {
Series ser = new Series(label);
double A;
if (!cumulative) {
for (int i = 0; i < negativeBins.Count(); i++) {
A = -1 * i * binSize;
if(A >0 && negativeBins[i] >0)
ser.Points.AddXY(Math.Log(A), Math.Log(negativeBins[i]));
} for (int j = 0; j < positiveBins.Count(); j++) {
A = j* binSize;
if (A > 0 && positiveBins[j] > 0)
ser.Points.AddXY(Math.Log(A), Math.Log(positiveBins[j]));
}
}
ser.ChartType = SeriesChartType.Point;
//TODO: overload this method so that we have a control to manipulate parameters and redraw the control
ser.Graph();
}
public void Graph(string label = "") {
Series ser = new Series(label);
if (!cumulative) {
for (int i = 0; i < negativeBins.Count(); i++) {
//for (int i = negativeBins.Count() - 1; i >= 0 ; i--) {
ser.Points.AddXY(-1 * (/*negativeBins.Count() - 1 -*/ i) * binSize, negativeBins[i]);
} for (int j = 0; j < positiveBins.Count(); j++) {
ser.Points.AddXY(j * binSize, positiveBins[j]);
}
} else {
double sum = 0;
for (int i = 0; i < negativeBins.Count(); i++) {
sum += negativeBins[i];
ser.Points.AddXY(-1 * (negativeBins.Count() - i), sum);
} for (int j = 0; j < positiveBins.Count(); j++) {
sum += positiveBins[j];
ser.Points.AddXY(j, sum);
}
}
//TODO: overload this method so that we have a control to manipulate parameters and redraw the control
ser.Graph();
}
public double GetEntropy() {
throw new NotImplementedException();
}
//Find the probability density function
//assuming power law, and assuming exponential law
internal Signal GetSignal() {
Signal signal = new Signal();
for (int i = 0; i < negativeBins.Count(); i++)
signal.Add(negativeBins[i]);
for (int i = 0; i < positiveBins.Count(); i++)
signal.Add(positiveBins[i]);
return signal;
}
public void SaveImage(string filename) {
Series ser = new Series();
if (!cumulative) {
for (int i = 0; i < negativeBins.Count(); i++) {
//for (int i = negativeBins.Count() - 1; i >= 0 ; i--) {
ser.Points.AddXY(-1 * (/*negativeBins.Count() - 1 -*/ i) * binSize, negativeBins[i]);
} for (int j = 0; j < positiveBins.Count(); j++) {
ser.Points.AddXY(j * binSize, positiveBins[j]);
}
} else {
double sum = 0;
for (int i = 0; i < negativeBins.Count(); i++) {
sum += negativeBins[i];
ser.Points.AddXY(-1 * (negativeBins.Count() - i), sum);
} for (int j = 0; j < positiveBins.Count(); j++) {
sum += positiveBins[j];
ser.Points.AddXY(j, sum);
}
}
ser.SaveImage(filename);
}
}
}
|
using HCBot.Runner.Data;
using HCBot.Runner.Menu;
using HCBot.Runner.Schedule;
using HCBot.Runner.States;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace HCBot.Runner
{
class Program
{
/// <summary>
/// HCBot
/// HC_dev_bot
/// 665509241:AAFxRlJKv4E-NoYMZvGWuu7o7OleN9a-4hI
/// </summary>
public const string tgUrlBase = "https://api.telegram.org/";
public const string botKey = "665509241:AAFxRlJKv4E-NoYMZvGWuu7o7OleN9a-4hI";
public const string apiBotKey = "bot" + botKey;
private Dictionary<long, UserStateBag> user = new Dictionary<long, UserStateBag>();
public ManualResetEvent botHaltEvent = new ManualResetEvent(false);
IServiceProvider Services { get; set; }
IServiceCollection serviceCollection;
ILogger logger;
static void Main(string[] args)
{
string path;
if (args.Count()!=1)
{
path = string.Empty;
}
else
{
path = args[0];
}
Task.Run(() =>
{
var p = new Program();
p.Run(path);
}).Wait();
}
void Run(string datadir)
{
serviceCollection = new ServiceCollection();
ILoggerFactory loggerFactory =
new LoggerFactory()
.AddConsole()
.AddDebug();
logger = loggerFactory.CreateLogger<Program>();
serviceCollection.AddSingleton<ILogger>(logger);
serviceCollection.AddScoped<IMenuProvider>( sp => new FlatFileMenuProvider(datadir));
serviceCollection.AddScoped<ITrainingScheduleProvider>(sp => new FlatFileTrainingScheduleProvider(datadir));
//serviceCollection.AddScoped<IEnrollRepository>(sp => new EnrollFlatFileRepository(datadir));
serviceCollection.AddScoped<IEnrollRepository>(sp => new EnrollPgSqlRepository());
Services = serviceCollection.BuildServiceProvider();
logger.LogInformation("HCbot started");
var bot = new TelegramBotClient(botKey);
logger.LogInformation("HCbot awaiting halt event");
try
{
bot.StartReceiving();
bot.OnMessage += Bot_OnMessage;
botHaltEvent.WaitOne();
}
catch (Exception e)
{
logger.LogError(e, "Error while WaitOne");
}
finally
{
bot.StopReceiving();
logger.LogInformation("HCbot halt");
}
}
private void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
{
logger.LogInformation($"Message received from {e.Message.Chat.Id} : {e.Message.Text}");
ExecuteCommand(sender as TelegramBotClient, e.Message.From, e.Message.Chat, e.Message.Text);
}
private void ExecuteCommand(ITelegramBotClient bot, User from, Chat chat, string commandName)
{
var uid = from?.Id ?? chat?.Id;
if (commandName=="halt")
{
logger.LogInformation($"Setting halt event");
botHaltEvent.Set();
return;
}
if (!user.ContainsKey(uid.Value))
{
var menu = Services.GetRequiredService<IMenuProvider>().Load();
user.Add(uid.Value, new UserStateBag { Uid=uid.Value, UserState = UserBotState.SerfMenu, BotMenu = menu });
}
new StateFactory(Services).CreateState(user[uid.Value].UserState).ProceedState(bot, user[chat.Id], chat, commandName);
}
}
}
|
namespace Sales.Domain.Models
{
using System.Data.Entity.ModelConfiguration;
using Common.Models;
internal class GalleriesMap : EntityTypeConfiguration<Gallery>
{
public GalleriesMap()
{
}
}
} |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Facade
{
class WTW
{
public float[] _l;
public string[] date;
WebRequest wrGETURL;
string sURL;
//read text and sets values in an int array
public WTW(string start, string end)
{
//set sURL value
date = new string[2] { start, end };
sURL = "https://api.coindesk.com/v1/bpi/historical/close.json?start=" + date[0] + "&end=" + date[1];
_l = new float[2];
//pegar os valores na api e colocar no array _l
wrGETURL = WebRequest.Create(sURL);
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
int i = 0;
string sLine = objReader.ReadLine();
float value1 = float.Parse(sLine.Split(':')[2].Split(',')[0]);
float value2=0;
sLine = sLine.Split('}')[0].ToString();
sLine = sLine.Split('{')[2].ToString();
string[] sLine2 = new string[10000];
i = Int16.Parse((sLine.Split(':')).Length);
value2 = float.Parse(sLine.Split(':')[i].ToString());
/*while (sLine != null)
{
i++;
sLine = objReader.ReadLine();
if (sLine != null)
Console.WriteLine("{0}:{1}", i, sLine);
}*/
Console.ReadLine();
}
}
}
|
using Alabo.Dependency;
using Alabo.Schedules.Job;
using Quartz;
using System;
using System.Threading.Tasks;
namespace Alabo.Web.TaskShell.Job
{
public class BookImportJob : JobBase
{
public override TimeSpan? GetInterval()
{
return TimeSpan.FromDays(3);
}
protected override async Task Execute(IJobExecutionContext context, IScope scope)
{
//var list = new List<BookPathHost>();
//BookPathHost host = new BookPathHost();
//host.Path = @"D:\服务器01(t1.dpnfs.com)";
//host.Host = "http://t1.dpnfs.com:809";
//list.Add(host);
//host = new BookPathHost();
//host.Path = @"D:\服务器02(t2.dpnfs.com)";
//host.Host = "http://t2.dpnfs.com:809";
//list.Add(host);
//foreach (var item in list) {
// scope.Resolve<IBookDonaeInfoService>().Init(item);
//}
//Console.WriteLine("所有书籍导入成功");
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace St.Eg.M2.Ex3.Enumerables
{
public class Foo : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
foreach (var i in new int[] {100, 101, 102})
{
yield return i;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
// var l = new LinkedList<int>();
//l[0] = 1;
var array = new []
{
1, 2, 3, 4, 5,
10*20,
};
var oc = new ObservableCollection<int>(array);
var incc = oc as INotifyCollectionChanged;
incc.CollectionChanged += (sender, eventArgs) =>
{
};
oc.Add(99);
oc.RemoveAt(1);
//foreach (var i in oc) Console.WriteLine(i);
//var l = new List<int>(100);
//Console.WriteLine(array.GetType());
//Console.WriteLine(Array.BinarySearch(array, 3));
//ICollection<int>
//array.ToList().ForEach(i => Console.WriteLine(i));
/*
var array = new [] { 10, 11, 12 };
var ie = array as IEnumerable<int>;
if (ie != null) Console.WriteLine("Hey, I'm enumerable");
var l = new List<int>(array);
var enumerator = l.GetEnumerator(); // ie.GetEnumerator();
var next = enumerator.MoveNext();
while (next)
{
var current = enumerator.Current;
Console.WriteLine(current);
l.Insert(2, -1);
next = enumerator.MoveNext();
}
//foreach (var i in array) Console.WriteLine(i);
//iterateWithEnum(array);
//iterateWithForEach(array);
* */
}
private static void iterateWithEnum(IEnumerable<int> array)
{
// TODO: get the enumerator
var enumerator = array.GetEnumerator();
// TODO: movenext
//var moreItems =
// TODO: while move next
//while (moreItems)
//{
// TODO: get the current item
//var item =
// TODO: print the item
//Console.WriteLine(item);
// TODO: move next
//moreItems = enumerator.MoveNext();
//}
}
private static void iterateWithForEach(int[] array)
{
// TODO: foreach on every item
{
// Console.WriteLine(item);
}
}
}
}
|
// Copyright 2013-2015 Serilog Contributors
//
// 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.
namespace Serilog.Settings.KeyValuePairs;
class SettingValueConversions
{
// should match "The.NameSpace.TypeName::MemberName" optionally followed by
// usual assembly qualifiers like :
// ", MyAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
static Regex StaticMemberAccessorRegex = new("^(?<shortTypeName>[^:]+)::(?<memberName>[A-Za-z][A-Za-z0-9]*)(?<typeNameExtraQualifiers>[^:]*)$");
static Dictionary<Type, Func<string, object>> ExtendedTypeConversions = new()
{
{ typeof(Uri), s => new Uri(s) },
{ typeof(TimeSpan), s => TimeSpan.Parse(s) },
{ typeof(Type),
// Suppress this trimming warning. We'll annotate all the users of this dictionary instead
[UnconditionalSuppressMessage("Trimming", "IL2057")]
(s) => Type.GetType(s, throwOnError: true)!
},
};
[RequiresUnreferencedCode("Finds accessors by name")]
public static object? ConvertToType(string value, Type toType)
{
if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (value == string.Empty)
return null;
// unwrap Nullable<> type since we're not handling null situations
toType = toType.GenericTypeArguments[0];
}
if (toType.IsEnum)
return Enum.Parse(toType, value);
var convertor = ExtendedTypeConversions
.Where(t => t.Key.IsAssignableFrom(toType))
.Select(t => t.Value)
.FirstOrDefault();
if (convertor != null)
return convertor(value);
if ((toType.IsInterface || toType.IsAbstract) && !string.IsNullOrWhiteSpace(value))
{
// check if value looks like a static property or field directive
// like "Namespace.TypeName::StaticProperty, AssemblyName"
if (TryParseStaticMemberAccessor(value, out var accessorTypeName, out var memberName))
{
var accessorType = Type.GetType(accessorTypeName, throwOnError: true)!;
// is there a public static property with that name ?
var publicStaticPropertyInfo = accessorType
.GetProperties(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(x => x.Name == memberName &&
x.GetMethod != null);
if (publicStaticPropertyInfo != null)
{
// static property, no instance to pass
return publicStaticPropertyInfo.GetValue(null);
}
// no property ? look for a public static field
var publicStaticFieldInfo = accessorType
.GetFields(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(x => x.Name == memberName);
if (publicStaticFieldInfo != null)
{
// static field, no instance to pass
return publicStaticFieldInfo.GetValue(null);
}
throw new InvalidOperationException($"Could not find a public static property or field with name `{memberName}` on type `{accessorTypeName}`");
}
// maybe it's the assembly-qualified type name of a concrete implementation
// with a default constructor
var type = Type.GetType(value.Trim(), throwOnError: false);
if (type != null)
{
var ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.FirstOrDefault(ci =>
{
var parameters = ci.GetParameters();
return parameters.Length == 0 || parameters.All(pi => pi.HasDefaultValue);
});
if (ctor == null)
throw new InvalidOperationException($"A default constructor was not found on {type.FullName}.");
var call = ctor.GetParameters().Select(pi => pi.DefaultValue).ToArray();
return ctor.Invoke(call);
}
}
if (toType.IsArray && toType.GetArrayRank() == 1)
{
var elementType = toType.GetElementType()!;
if (string.IsNullOrEmpty(value))
{
return Array.CreateInstance(elementType, 0);
}
var items = value.Split(',');
var length = items.Length;
var result = Array.CreateInstance(elementType, items.Length);
for (var i = 0; i < length; ++i)
{
var item = items[i];
var element = ConvertToType(item, elementType);
result.SetValue(element, i);
}
return result;
}
return Convert.ChangeType(value, toType);
}
internal static bool TryParseStaticMemberAccessor(string input, [NotNullWhen(true)] out string? accessorTypeName, [NotNullWhen(true)] out string? memberName)
{
if (StaticMemberAccessorRegex.IsMatch(input))
{
var match = StaticMemberAccessorRegex.Match(input);
var shortAccessorTypeName = match.Groups["shortTypeName"].Value;
var rawMemberName = match.Groups["memberName"].Value;
var extraQualifiers = match.Groups["typeNameExtraQualifiers"].Value;
memberName = rawMemberName.Trim();
accessorTypeName = shortAccessorTypeName.Trim() + extraQualifiers.TrimEnd();
return true;
}
accessorTypeName = null;
memberName = null;
return false;
}
}
|
using Properties.Core.Interfaces;
using Conditions.Guards;
namespace Properties.Core.Objects
{
public class Video : LifetimeBase, IReferenceable<Video>
{
private VideoType _videoType;
private string _videoUrl;
public int VideoId { get; set; }
public string VideoReference { get; set; }
public VideoType VideoType
{
get { return _videoType; }
set
{
if (_videoType != value)
{
_videoType = value;
IsDirty = true;
}
}
}
public string VideoUrl
{
get { return _videoUrl; }
set
{
if (_videoUrl != value)
{
_videoUrl = value;
IsDirty = true;
}
}
}
public Video()
{
VideoId = 0;
VideoReference = string.Empty;
VideoType = VideoType.Unknown;
VideoUrl = string.Empty;
}
public Video CreateReference(IReferenceGenerator referenceGenerator)
{
Check.If(referenceGenerator).IsNotNull();
VideoReference = referenceGenerator.CreateReference(Constants.ReferenceLength);
return this;
}
}
}
|
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 Microsoft.Win32;
using System.Security.Cryptography;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Runtime.Remoting.Messaging;
namespace Hash
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<string> algos = new List<string>();
enum HashAlgos {MD5, RIPEMD160, SHA1, SHA256, SHA384, SHA512};
string algoritmAles;
HashAlgorithm ha;
public MainWindow()
{
InitializeComponent();
algos.Add("MD5");
algos.Add("RIPEMD160");
algos.Add("SHA1");
algos.Add("SHA1");
algos.Add("SHA256");
algos.Add("SHA384");
algos.Add("SHA512");
//foreach (var alg in algos)
// this.comboAlgos.Items.Add(alg);
string[] algorithms = Enum.GetNames(typeof(HashAlgos));
foreach(var a in algorithms)
this.comboAlgos.Items.Add(a);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
string filename;
bool? ret = ofd.ShowDialog(this);
if (ret.HasValue && ret == true)
{
filename = ofd.FileName;
this.txtFile.Text = filename;
}
}
private void comboAlgos_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
algoritmAles = comboAlgos.SelectedItem.ToString();
Debug.Write("Algoritm ales " + algoritmAles);
btnComputeHash.IsEnabled = true;
}
private async void btnComputeHash_Click(object sender, RoutedEventArgs e)
{
switch (algoritmAles)
{
case "MD5":
ha = MD5CryptoServiceProvider.Create();
break;
case "RIPEMD160":
ha = RIPEMD160Managed.Create();
break;
case "SHA1":
ha = SHA1Managed.Create();
break;
case "SHA256":
ha = SHA256Managed.Create();
break;
case "SHA384":
ha = SHA384Managed.Create();
break;
case "SHA512":
ha = SHA512Managed.Create();
break;
}
string hash = await ComputeHashAsync(ha, this.txtFile.Text);
this.lblHash.Content = "Hash value " + hash;
// Func<HashAlgorithm, string, string> h = ComputeHash2;
// IAsyncResult iar = h.BeginInvoke(ha, this.txtFile.Text, updateUI, null);
}
private void updateUI(IAsyncResult ar)
{
AsyncResult result = (AsyncResult)ar;
var caller = (Func<HashAlgorithm, string, string>)result.AsyncDelegate;
string hash = caller.EndInvoke(ar);
Action update = () => this.lblHash.Content = hash;
Dispatcher.BeginInvoke(update, null);
}
async Task<string> ComputeHashAsync(HashAlgorithm ha, string file)
{
var ret = Task.Run<string>(() =>
{
byte[] hash = ha.ComputeHash(new FileStream(file, FileMode.Open, FileAccess.Read));
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
return sb.ToString();
});
return await ret;
}
public static string ComputeHash2(HashAlgorithm ha, string file)
{
byte[] hash = ha.ComputeHash(new FileStream(file, FileMode.Open, FileAccess.Read));
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
return sb.ToString();
}
}
}
|
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 HiddenWordsLibrary;
namespace HiddenWords
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void convertButton_click(object sender, EventArgs e)
{
outputLabel.Text = Functions.StringToHex(InputBox.Text);
}
private void pictureBrowseButton_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Bitmap loadedPic = new Bitmap(openFileDialog1.FileName);
LoadedPictureTest.Image = loadedPic;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual
{
/// <summary>
/// Representa el objeto response de plantilla párrafo variable
/// </summary>
/// <remarks>
/// Creación : GMD 20150603 <br />
/// Modificación : <br />
/// </remarks>
public class PlantillaParrafoVariableResponse
{
/// <summary>
/// Código de Plantilla Párrafo Variable
/// </summary>
public Guid CodigoPlantillaParrafoVariable { get; set; }
/// <summary>
/// Código de Plantilla Párrafo
/// </summary>
public Guid CodigoPlantillaParrafo { get; set; }
/// <summary>
/// Código de Variable
/// </summary>
public Guid CodigoVariable { get; set; }
/// <summary>
/// Orden
/// </summary>
public Int16 Orden { get; set; }
/// <summary>
/// Código de Tipo de Variable
/// </summary>
public string CodigoTipoVariable { get; set; }
/// <summary>
/// Nombre de Variable
/// </summary>
public string NombreVariable { get; set; }
/// <summary>
/// Descripcion de Variable
/// </summary>
public string DescripcionVariable { get; set; }
/// <summary>
/// Identificador de Variable
/// </summary>
public string IdentificadorVariable { get; set; }
/// <summary>
/// Lista de opciones de la variable si es de tipo lista
/// </summary>
public List<VariableListaResponse> ListaOpcionesVariable { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using WebApp.Data.Models;
namespace WebApp.Services
{
public class TireService
{
private RepositoryContext _dbContext { get; set; }
public TireService(RepositoryContext dbContext)
{
_dbContext = dbContext;
}
public TiresModelsBrands Create(TiresRequestModel model)
{
var brandModel = _dbContext.TiresModelsBrands.FirstOrDefault(x => x.Brand == model.Brand && x.Model == model.Model);
if (brandModel == null)
{
brandModel = TiresModelsBrands.CreateAsgt(model.Brand, model.Model, model.Country, model.Category, model.Characteristics.Min(c => c.Price));
_dbContext.TiresModelsBrands.Add(brandModel);
}
var tires = new List<Tires>();
model.Characteristics.ForEach(x =>
{
tires.Add(new Tires
{
BrandModelId = brandModel.Id,
Id = Guid.NewGuid(),
Diameter = x.Diameter,
LoadIndex = x.LoadIndex,
Price = x.Price,
Profile = x.Profile,
VendorCode = x.VendorCode,
Season = x.Season,
SpeedIndex = x.SpeedIndex,
Spike = x.Spike,
VehicleType = x.VehicleType,
WholesalePrice = x.Price,
Width = x.Width,
FullInfo = $"{model.Model} {model.Brand} {x.Width}/{x.Profile} R{x.Diameter} {x.LoadIndex}{x.SpeedIndex}"
});
});
_dbContext.Tires.AddRange(tires);
//Add preview images
model?.PreviewImages.ForEach(i =>
{
var tireModelBrandImage = TiresImages.CreatePreviewFromRequestModel(i, brandModel.Id);
_dbContext.TiresImages.Add(tireModelBrandImage);
});
//Add images
model?.Images.ForEach(i =>
{
var tireModelBrandImage = TiresImages.CreateFromRequestModel(i, brandModel.Id);
_dbContext.TiresImages.Add(tireModelBrandImage);
});
_dbContext.SaveChanges();
brandModel = _dbContext.TiresModelsBrands.Include(p => p.TiresImages)
.ThenInclude(x => x.Image)
.Include(x => x.Tires)
.FirstOrDefault(p => p.Id == brandModel.Id);
return brandModel;
}
public void Update(Guid id, TiresRequestModel model)
{
var brandModel = _dbContext.TiresModelsBrands.Include(p => p.TiresImages)
.ThenInclude(x => x.Image)
.Include(x => x.Tires)
.FirstOrDefault(x => x.Id == id);
if (brandModel == null)
throw new Exception("Model brand with that id not found");
brandModel.UpdateAsgt(model.Brand, model.Model, model.Country, model.Category, model.Characteristics.Min(c => c.Price));
_dbContext.Tires.RemoveRange(brandModel.Tires);
_dbContext.TiresImages.RemoveRange(brandModel.TiresImages);
var tires = new List<Tires>();
model.Characteristics.ForEach(x =>
{
tires.Add(new Tires
{
BrandModelId = brandModel.Id,
Id = Guid.NewGuid(),
Diameter = x.Diameter,
LoadIndex = x.LoadIndex,
Price = x.Price,
Profile = x.Profile,
VendorCode = x.VendorCode,
Season = x.Season,
SpeedIndex = x.SpeedIndex,
Spike = x.Spike,
VehicleType = x.VehicleType,
WholesalePrice = x.Price,
Width = x.Width,
FullInfo = $"{model.Model} {model.Brand} {x.Width}/{x.Profile} R{x.Diameter} {x.LoadIndex}{x.SpeedIndex}"
});
});
_dbContext.Tires.AddRange(tires);
//Add preview images
model?.PreviewImages.ForEach(i =>
{
var tireModelBrandImage = TiresImages.CreatePreviewFromRequestModel(i, brandModel.Id);
_dbContext.TiresImages.Add(tireModelBrandImage);
});
//Add images
model?.Images.ForEach(i =>
{
var tireModelBrandImage = TiresImages.CreateFromRequestModel(i, brandModel.Id);
_dbContext.TiresImages.Add(tireModelBrandImage);
});
_dbContext.SaveChanges();
}
public void Delete(Guid id)
{
var brandModel = _dbContext.TiresModelsBrands.Include(p => p.TiresImages).ThenInclude(i => i.Image).FirstOrDefault(p => p.Id == id);
if (brandModel == null)
throw new Exception("Brand model with that id not found");
_dbContext.TiresImages.RemoveRange(brandModel.TiresImages);
_dbContext.TiresModelsBrands.Remove(brandModel);
_dbContext.SaveChanges();
}
public void MultiplyPrice(Dictionary<string, string> data)
{
var allocatedCoefficients = _dbContext.Multipliers.ToList();
var allocatedTires = _dbContext.Tires.Include(x => x.BrandModel).ToList();
foreach (var key in data.Keys)
{
double coefficient = double.Parse(data.GetValueOrDefault(key));
var currentCoefficient = allocatedCoefficients.First(c => c.VehicleType == key);
currentCoefficient.Coefficient = coefficient;
allocatedTires.Where(p => p.VehicleType == key)
.ToList()
.ForEach(tire =>
{
tire.Price = Math.Round(tire.WholesalePrice * coefficient);
tire.BrandModel.StartPrice = Math.Round(tire.WholesalePrice * coefficient);
});
}
_dbContext.BulkSaveChanges();
}
}
}
|
using System;
using StardewValley;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PyTK.CustomElementHandler;
using System.Collections.Generic;
using StardewValley.Objects;
using PyTK.Extensions;
namespace Tubes
{
// Static info for our Tube object / terrain feature.
public class TubeInfo
{
public const string fullid = "Pneumatic Tube";
public const string name = "Pneumatic Tube";
public const string category = "Crafting";
public const int price = 100;
public const string description = "Connects machines together with the magic of vacuums.";
public const string crafting = "337 1";
public const int spriteSize = 48;
internal static Texture2D icon;
internal static Texture2D terrainSprites;
internal static CustomObjectData objectData;
internal static CustomObjectData junkObjectData;
internal static void init()
{
icon = TubesMod._helper.Content.Load<Texture2D>(@"Assets/icon.png");
terrainSprites = TubesMod._helper.Content.Load<Texture2D>(@"Assets/terrain.png");
objectData = new CustomObjectData(
TubeInfo.fullid,
$"{TubeInfo.name}/{TubeInfo.price}/-300/{TubeInfo.category} -24/{TubeInfo.name}/{TubeInfo.description}",
TubeInfo.icon,
Color.White,
0,
false,
typeof(TubeObject),
new CraftingData(TubeInfo.fullid, TubeInfo.crafting));
junkObjectData = new CustomObjectData(
$"{TubeInfo.fullid} junk",
$"{TubeInfo.name} junk/{TubeInfo.price}/-300/{TubeInfo.category} -24/{TubeInfo.name}/{TubeInfo.description}",
TubeInfo.icon,
Color.White,
0,
false,
null, // typeof(TubeObject),
null);
}
}
// The Tube object type. This is used whenever the object is not placed on the ground (it's not a terrain feature).
public class TubeObject : StardewValley.Object, ICustomObject, ISaveElement, IDrawFromCustomObjectData
{
public CustomObjectData data { get => TubeInfo.objectData; }
public TubeObject()
{
}
public TubeObject(CustomObjectData data)
: base(data.sdvId, 1)
{
}
public TubeObject(CustomObjectData data, Vector2 tileLocation)
: base(tileLocation, data.sdvId)
{
}
public Dictionary<string, string> getAdditionalSaveData()
{
return new Dictionary<string, string>() { { "name", name }, { "price", price.ToString() }, { "stack", stack.ToString() } };
}
public object getReplacement()
{
return new Chest(true) { playerChoiceColor = Color.Magenta };
}
public void rebuild(Dictionary<string, string> additionalSaveData, object replacement)
{
name = additionalSaveData["name"];
price = additionalSaveData["price"].toInt();
stack = additionalSaveData["stack"].toInt();
}
public Item getOne()
{
return new TubeObject(TubeInfo.objectData) { tileLocation = Vector2.Zero, name = name, price = price };
}
public ICustomObject recreate(Dictionary<string, string> additionalSaveData, object replacement)
{
return new TubeObject(TubeInfo.objectData);
}
public override void drawInMenu(SpriteBatch spriteBatch, Vector2 location, float scaleSize, float transparency, float layerDepth, bool drawStackNumber)
{
spriteBatch.Draw(Game1.shadowTexture, location + new Vector2((Game1.tileSize / 2), (Game1.tileSize * 3 / 4)), new Rectangle?(Game1.shadowTexture.Bounds), Color.White * 0.5f, 0.0f, new Vector2(Game1.shadowTexture.Bounds.Center.X, Game1.shadowTexture.Bounds.Center.Y), 3f, SpriteEffects.None, layerDepth - 0.0001f);
spriteBatch.Draw(TubeInfo.icon, location + new Vector2((Game1.tileSize / 2), (Game1.tileSize / 2)), new Rectangle?(TubeInfo.objectData.sourceRectangle), Color.White * transparency, 0.0f, new Vector2(16 / 2, 16 / 2), Game1.pixelZoom * scaleSize, SpriteEffects.None, layerDepth);
if (drawStackNumber && maximumStackSize() > 1 && (scaleSize > 0.3 && Stack != int.MaxValue) && Stack > 1)
Utility.drawTinyDigits(stack, spriteBatch, location + new Vector2((Game1.tileSize - Utility.getWidthOfTinyDigitString(stack, 3f * scaleSize)) + 3f * scaleSize, (float)(Game1.tileSize - 18.0 * scaleSize + 2.0)), 3f * scaleSize, 1f, Color.White);
}
public override void drawWhenHeld(SpriteBatch spriteBatch, Vector2 objectPosition, StardewValley.Farmer f)
{
spriteBatch.Draw(TubeInfo.icon, objectPosition, TubeInfo.objectData.sourceRectangle, Color.White, 0.0f, Vector2.Zero, Game1.pixelZoom, SpriteEffects.None, Math.Max(0.0f, (f.getStandingY() + 2) / 10000f));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContestsPortal.Domain.Models
{
public class ContestTask
{
public int TaskId { get; set; }
public int? TaskComplexity { get; set; }
/// <summary>
/// Duration in seconds.
/// </summary>
public TimeSpan? TaskDuration { get; set; }
public string TaskTitle { get; set; }
public string TaskContent { get; set; }
public string TaskComment { get; set; }
public int TaskAward { get; set; }
public int IdContest { get; set; }
public int? IdArchivedTask { get; set; }
public virtual Contest Contest { get; set; }
public virtual List<TaskSolution> Solutions { get; set; }
public virtual List<ProgrammingLanguage> Languages { get; set; }
public virtual ArchivedTask ArchivedTask { get; set; }
public ContestTask()
{
Languages = new List<ProgrammingLanguage>();
Solutions = new List<TaskSolution>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
namespace LPC.Web.App_Start
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Bundles/js").Include(
"~/Scripts/modernizr-2.8.3.js",
"~/Scripts/jquery-3.1.1.min.js",
"~/Scripts/bootstrap.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/Site.css",
"~/Content/bootstrap.min.css"));
}
}
} |
using BootcampTwitterKata.Messages;
namespace BootcampTwitterKata
{
public class TwitterCommands : ITwitterCommands
{
public void Insert(int id, string title)
{
}
public void Like(int id)
{
}
public void UnLike(int id)
{
}
public void Delete(Tweet tweet)
{
}
}
}
|
using System;
public interface IProductModel
{
ProductData GetProductData();
void SubscribeToUpdateModel(Action action);
void Buy();
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using UcenikShuffle.Common.Exceptions;
namespace UcenikShuffle.Common
{
public class Shuffler
{
private readonly int _lvCount;
private readonly CancellationTokenSource _cancellationSource;
private readonly List<Group> _groups;
private readonly List<Student> _students;
private readonly List<LvCombination> _shuffleResult;
/// <summary>
/// Defaulf maximum for the amount of student combinations that will be returned by the shuffle operation
/// </summary>
public static readonly int MaxCombinationCount = 100000;
/// <summary>
/// List of groups
/// </summary>
public IReadOnlyList<Group> Groups => _groups;
/// <summary>
/// List of students
/// </summary>
public IReadOnlyList<Student> Students => _students;
/// <summary>
/// Result of the shuffle operation
/// </summary>
public IReadOnlyList<LvCombination> ShuffleResult => GetShuffleResult().ToList();
public Shuffler(int lvCount, IReadOnlyList<int> groupSizes, CancellationTokenSource cancellationSource)
{
//Checking if passed parameters are valid
if (groupSizes == null || groupSizes.Count == 0 || groupSizes.Any(s => s <= 0))
{
throw new GroupSizeException();
}
if (lvCount <= 0)
{
throw new LvCountException();
}
//Initializing variables
_cancellationSource = cancellationSource;
_shuffleResult = new List<LvCombination>();
_lvCount = lvCount;
_groups = groupSizes.ToList().OrderBy(s => s).Select(s => new Group(s)).ToList();
int studentCount = groupSizes.Sum();
_students = new List<Student>();
for (int i = 0; i < studentCount; i++)
{
_students.Add(new Student(i + 1));
}
}
/// <summary>
/// This method is used to create best student sitting combinations based on the fields in this class
/// </summary>
/// <param name="progressPercentage">Completed percentage for the shuffle step which is being executed at that moment</param>
/// <param name="progressText">Text containing data about shuffle step which is being executed at that moment</param>
/// <param name="progressTimeLeft">Estimated time left for shuffle step which is being executed at that moment to finish</param>
/// <returns></returns>
public void Shuffle(IProgress<double> progressPercentage = null, IProgress<string> progressText = null, IProgress<TimeSpan> progressTimeLeft = null)
{
/*BEST COMBINATION ALGORITHM EXPLANATION:
An algorithm which calculates best combination takes 6 parameters into consideration:
1st (most important) parameter is maxSittingCount:
max amount of times a student sat with with another student.
Lower amount is better.
2nd parameter is minSittingCount:
min amount of times a student sat with another student.
Higher is better.
3rd parameter is studentSittingDiff:
(highest sum of student sitting values for a student) - (lowest sum of student sitting value for a student (doesn't need to be the same student)).
Lower number is better since that forces the students to sit in groups of various sizes, instead of alwaays sitting in the biggest/smalled group.
4th parameter is minMaxSum:
sum of (max amount of times a student sat with another student) - (min amount of times that same student student sat with another student) for all students.
Lower is better.
5th parameter is minAndMaxSittingCountCount:
count of student sitting count values (student sitting count values - amount of times students sat with each other) where student sitting count is min or max.
Lower is better since it means that the deviation from average student sitting count is lower.
6th (least important) parameter is groupRepetitionCount:
Sum of amount of times each group in the combination was used in previous combinations
Algorithm is pretty much doing
lvCombinations.OrderBy(1st parameter).OrderBy(2nd parameter).OrderBy(3nd parameter).OrderBy(4th parameter).First(),
but doing it manually since progress could otherwise only be updated once the best combination is found (which can take a lot of time)*/
//Setup
foreach (var student in Students)
{
student.StudentSittingHistory.Clear();
}
_shuffleResult.Clear();
progressPercentage?.Report(0);
progressText?.Report("Računanje svih kombinacija sjedenja");
progressTimeLeft?.Report(new TimeSpan(0));
ulong combinationCount = new LvCombinationCountCalculator(_groups.Select(g => g.Size).ToList(), _students.Count).GetLvCombinationCount();
if (combinationCount > (ulong)MaxCombinationCount)
{
combinationCount = (ulong)MaxCombinationCount;
}
//Going trough each LV
var combinations = GetLvCombinations(progressPercentage, progressTimeLeft, combinationCount);
progressPercentage?.Report(0);
progressText?.Report("Rasporeda se stvara");
progressTimeLeft?.Report(new TimeSpan(0));
for (int lv = 0; lv < _lvCount; lv++)
{
//Getting best student sitting combination for current lv
LvCombination bestCombination = GetBestLvCombination(combinations, lv, progressPercentage, progressTimeLeft);
//Updating shuffle result and progress
UpdateStudentHistory(bestCombination, true);
_shuffleResult.Add(bestCombination);
//If every student sat with other students the same amount of times, there is no need to do further calculations since other lv's would just be repeats of current student sitting combinations
if (GetStudentSittingHistoryValues().Distinct().Count() <= 1)
{
break;
}
}
progressTimeLeft?.Report(new TimeSpan(0));
//DEBUGGING OUTPUT: used for testing purposes
Debug_PrintResult();
}
private static void UpdateStudentHistory(LvCombination combination, bool increment)
{
foreach (var groupCombination in combination.Combination)
{
foreach (var student in groupCombination)
{
foreach (var student2 in groupCombination)
{
if (student == student2)
{
continue;
}
if (student.StudentSittingHistory.ContainsKey(student2) == false)
{
student.StudentSittingHistory.Add(student2, 0);
}
student.StudentSittingHistory[student2] += (increment) ? 1 : -1;
}
}
}
}
private static int GetStudentSittingDiff(LvCombination combination)
{
int minCount = 0;
int maxCount = 0;
bool firstStudent = true;
foreach (var groupCombination in combination.Combination)
{
foreach (var student in groupCombination)
{
int sittingCount = student.StudentSittingHistory.Values.Sum();
if (sittingCount > maxCount)
{
maxCount = sittingCount;
}
if (sittingCount < minCount || firstStudent)
{
minCount = sittingCount;
firstStudent = false;
}
}
}
return maxCount - minCount;
}
private IEnumerable<int> GetMinMaxValues(LvCombination combination)
{
foreach (var group in combination.Combination)
{
foreach (var student in group)
{
int minMax = 0;
if (student.StudentSittingHistory.Count != 0)
{
minMax = student.StudentSittingHistory.Values.Max();
if (student.StudentSittingHistory.Count == Students.Count - 1)
{
minMax -= student.StudentSittingHistory.Values.Min();
}
}
yield return minMax;
}
}
}
private int GetMinAndMaxSittingCountCount(IReadOnlyList<int> studentSittingHistoryValues)
{
int minSittingCount = studentSittingHistoryValues.Min();
int maxSittingCount = studentSittingHistoryValues.Max();
return studentSittingHistoryValues.Where(v => v == minSittingCount || v == maxSittingCount).Count();
}
private int GetGroupRepetitionCount(LvCombination combination)
{
int count = 0;
foreach (var group in combination.Combination)
{
foreach (var _combination in ShuffleResult)
{
foreach (var _group in _combination.Combination)
{
if (group.Count == _group.Count && group.Except(_group).Any() == false)
{
count++;
}
}
}
}
return count;
}
private IEnumerable<int> GetStudentSittingHistoryValues()
{
foreach (var student in Students)
{
//Returning student sitting history values for the current student
foreach (var record in student.StudentSittingHistory)
{
yield return record.Value;
}
//Returning 0's for all students that aren't present in the student sitting history list
for (int i = student.StudentSittingHistory.Count; i < Students.Count - 1; i++)
{
yield return 0;
}
}
}
private List<LvCombination> GetLvCombinations(IProgress<double> progressPercentage, IProgress<TimeSpan> progressTimeLeft, ulong combinationCount)
{
var timeEstimator = new TimeLeftEstimator();
var getCombinationsStopwatch = new Stopwatch();
getCombinationsStopwatch.Start();
ulong loopCount = 0;
//Getting all lv combinations and updating user on progress of the operation
var combinations =
new LvCombinationProcessor(Groups.Select(g => g.Size).ToList(), Students.ToList(), MaxCombinationCount).LvCombinations
.Select(c =>
{
_cancellationSource?.Token.ThrowIfCancellationRequested();
loopCount++;
//Progress is updated every 100 combinations
if (loopCount % 100 == 0)
{
getCombinationsStopwatch.Stop();
progressPercentage?.Report((double)loopCount / combinationCount);
timeEstimator.AddTime(new TimeSpan(getCombinationsStopwatch.ElapsedTicks));
progressTimeLeft?.Report(timeEstimator.GetTimeLeft((long)combinationCount - (long)loopCount) / 100);
getCombinationsStopwatch.Restart();
}
return c;
})
.ToList();
return combinations;
}
private LvCombination GetBestLvCombination(List<LvCombination> combinations, int currentLvIndex, IProgress<double> progressPercentage, IProgress<TimeSpan> progressTimeLeft)
{
LvCombination bestCombination = null;
bool firstCombination = true;
int bestCombinationMaxSittingCount = 0;
int bestCombinationStudentSittingDiff = 0;
int bestCombinationMinMaxSum = 0;
int bestCombinationMinSittingCount = 0;
int bestCombinationMinAndMaxSittingCountCount = 0;
int bestCombinationGroupRepetitionCount = 0;
int loopCount = 0;
var timeEstimator = new TimeLeftEstimator();
var combinationsLoopStopwatch = new Stopwatch();
combinationsLoopStopwatch.Start();
foreach (var combination in combinations)
{
_cancellationSource?.Token.ThrowIfCancellationRequested();
UpdateStudentHistory(combination, true);
var studentSittingHistoryValues = GetStudentSittingHistoryValues().ToList();
bool isBestCombination = firstCombination || IsBestCombination(combination, studentSittingHistoryValues, bestCombinationMaxSittingCount, bestCombinationMinSittingCount, bestCombinationStudentSittingDiff, bestCombinationMinMaxSum, bestCombinationMinAndMaxSittingCountCount, bestCombinationGroupRepetitionCount);
//Updating variables if this is the best combination so far
if (isBestCombination)
{
//Variables are being populated using new data since some of the variables in this foreach loop might not have been updated (since that depends on what criteria the best combination was selected)
bestCombination = combination;
if (studentSittingHistoryValues.Count != 0)
{
bestCombinationMaxSittingCount = studentSittingHistoryValues.Max();
bestCombinationMinSittingCount = studentSittingHistoryValues.Min();
bestCombinationStudentSittingDiff = GetStudentSittingDiff(combination);
bestCombinationMinMaxSum = GetMinMaxValues(combination).Sum();
bestCombinationGroupRepetitionCount = GetGroupRepetitionCount(combination);
bestCombinationMinAndMaxSittingCountCount = GetMinAndMaxSittingCountCount(studentSittingHistoryValues);
firstCombination = false;
}
}
UpdateStudentHistory(combination, false);
loopCount++;
if (loopCount % 1000 == 0 || loopCount == combinations.Count)
{
combinationsLoopStopwatch.Stop();
timeEstimator?.AddTime(new TimeSpan(combinationsLoopStopwatch.ElapsedTicks));
var timeLeft = timeEstimator.GetTimeLeft((combinations.Count - loopCount) / 1000 + (_lvCount - currentLvIndex - 1) * combinations.Count / 1000);
progressTimeLeft?.Report(timeLeft);
progressPercentage?.Report((double)((currentLvIndex + (double)loopCount / combinations.Count) / _lvCount));
combinationsLoopStopwatch.Restart();
}
}
return bestCombination;
}
private bool IsBestCombination(LvCombination combination, List<int> studentSittingHistoryValues, int bestCombinationMaxSittingCount, int bestCombinationMinSittingCount, int bestCombinationStudentSittingDiff, int bestCombinationMinMaxSum, int bestCombinationMinAndMaxSittingCountCount, int bestCombinationGroupRepetitionCount)
{
//Checking if max sitting count is better
int maxSittingCount = studentSittingHistoryValues.Max();
if (maxSittingCount < bestCombinationMaxSittingCount) return true;
if(maxSittingCount > bestCombinationMaxSittingCount) return false;
//Checking if min sitting count is better
int minSittingCount = studentSittingHistoryValues.Min();
if (minSittingCount > bestCombinationMinSittingCount) return true;
else if (minSittingCount < bestCombinationMinSittingCount) return false;
//Checking if min student sitting diff is better
int studentSittingDiff = GetStudentSittingDiff(combination);
if (studentSittingDiff < bestCombinationStudentSittingDiff) return true;
else if (studentSittingDiff > bestCombinationStudentSittingDiff) return false;
//Checking if minMaxDiff is better
int minMaxSum = GetMinMaxValues(combination).Sum();
if (minMaxSum < bestCombinationMinMaxSum) return true;
else if(minMaxSum > bestCombinationMinMaxSum) return false;
//Checking if minMinAndMax sitting count is better or if min sitting count is higher or if max sitting count is lower
int minAndMaxSittingCountCount = GetMinAndMaxSittingCountCount(studentSittingHistoryValues);
if (bestCombinationMinAndMaxSittingCountCount < minAndMaxSittingCountCount) return true;
else if (bestCombinationMinAndMaxSittingCountCount > minAndMaxSittingCountCount) return false;
//Checking is group repetition count is better
int groupRepetitionCount = GetGroupRepetitionCount(combination);
if (groupRepetitionCount < bestCombinationGroupRepetitionCount) return true;
return false;
}
private void Debug_PrintResult()
{
foreach (var student in Students)
{
Debug.WriteLine($"Student {student.Id}");
foreach (var h in student.StudentSittingHistory.OrderBy(h => h.Key.Id))
{
Debug.WriteLine($"{h.Key.Id}: {h.Value}");
}
Debug.WriteLine("");
}
}
private IEnumerable<LvCombination> GetShuffleResult()
{
if(_shuffleResult.Count == 0)
{
yield break;
}
for (int i = 0; i < _lvCount; i++)
{
yield return _shuffleResult[i % _shuffleResult.Count];
}
}
}
} |
using ServiceQuotes.Infrastructure.Context;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ServiceQuotes.Api.Extensions
{
public static class DatabaseExtension
{
public static void AddApplicationDbContext(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
{
if (environment?.EnvironmentName == "Testing")
{
services.AddDbContextPool<AppDbContext>(o =>
{
o.UseSqlite("Data Source=test.db");
});
}
else
{
services.AddDbContextPool<AppDbContext>(o =>
{
o.UseNpgsql(configuration.GetConnectionString("DefaultConnection"));
});
}
}
}
}
|
namespace FormulaBuilder
{
using System;
public interface ICalculator
{
int UseFormulaWithValues(IFormula formula, params IValue[] values);
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.DataAccess.Entity
{
public class SurveyorReport
{
public string task_id { get; set; }
public Guid? task_owner_id { get; set; }
public Guid? assign_acc_id { get; set; }
public Guid? assign_com_id { get; set; }
public int task_process_id { get; set; }
public int task_action_id { get; set; }
public string task_type_id { get; set; }
public string informer_name { get; set; }
public string informer_tel { get; set; }
public int notify_id { get; set; }
public string note { get; set; }
public string cancel_note { get; set; }
public string ins_id { get; set; }
public string driver_name { get; set; }
public string driver_sex { get; set; }
public string driver_license { get; set; }
public string driver_tel_no { get; set; }
public DateTime? schedule_date { get; set; }
public string schedule_plance { get; set; }
public string schedule_latitude { get; set; }
public string schedule_longitude { get; set; }
public DateTime? create_date { get; set; }
public DateTime? update_date { get; set; }
public string create_by { get; set; }
public string update_by { get; set; }
public string assign_name { get; set; }
public string task_type_name { get; set; }
public string task_process_name { get; set; }
public string Ins_name { get; set; }
public string service_area { get; set; }
public double? distance { get; set; }
public string car_license_no { get; set; }
public long? import_id { get; set; }
}
public class SurveyorConfig : EntityTypeConfiguration<SurveyorReport>
{
public SurveyorConfig()
{
MapToStoredProcedures();
Property(t => t.task_id).HasColumnName("task_id");
Property(t => t.informer_name).HasColumnName("informer_name");
Property(t => t.informer_tel).HasColumnName("informer_tel");
Property(t => t.note).HasColumnName("note");
Property(t => t.assign_com_id).HasColumnName("assign_com_id");
Property(t => t.driver_name).HasColumnName("driver_name");
Property(t => t.driver_license).HasColumnName("driver_license");
Property(t => t.driver_sex).HasColumnName("driver_sex");
Property(t => t.driver_tel_no).HasColumnName("driver_tel_no");
Property(t => t.schedule_date).HasColumnName("schedule_date");
Property(t => t.schedule_plance).HasColumnName("schedule_plance");
Property(t => t.schedule_latitude).HasColumnName("schedule_latitude");
Property(t => t.schedule_longitude).HasColumnName("schedule_longitude");
Property(t => t.ins_id).HasColumnName("ins_id");
Property(t => t.cancel_note).HasColumnName("cancel_note");
Property(t => t.create_date).HasColumnName("create_date");
Property(t => t.update_date).HasColumnName("update_date");
Property(t => t.create_by).HasColumnName("create_by");
Property(t => t.update_by).HasColumnName("update_by");
Property(t => t.task_type_id).HasColumnName("task_type_id");
Property(t => t.notify_id).HasColumnName("notify_id");
Property(t => t.task_process_id).HasColumnName("task_process_id");
Property(t => t.task_action_id).HasColumnName("task_action_id");
Property(t => t.task_owner_id).HasColumnName("task_owner_id");
Property(t => t.assign_acc_id).HasColumnName("assign_acc_id");
Property(t => t.import_id).HasColumnName("import_id");
Property(t => t.assign_name).HasColumnName("assign_name");
Property(t => t.task_type_name).HasColumnName("task_type_name");
Property(t => t.task_process_name).HasColumnName("task_process_name");
Property(t => t.Ins_name).HasColumnName("Ins_name");
Property(t => t.service_area).HasColumnName("service_area");
Property(t => t.distance).HasColumnName("distance");
Property(t => t.distance).HasColumnName("car_license_no");
HasKey(t => t.task_id);
}
}
}
|
using System;
using System.Security.Cryptography;
namespace Sartakov.Nsudotnet.Enigma
{
class Program
{
private static void ShowHelp()
{
Console.WriteLine(
@"Usage :
{0} encrypt FILE ALGORITHM OUTPUT_FILE
{0} decrypt FILE ALGORITHM KEY_FILE OUTPUT_FILE", System.AppDomain.CurrentDomain.FriendlyName
);
}
static void Main(string[] args)
{
if (args.Length == 0)
{
ShowHelp();
return;
}
if ((args.Length != 4 || args[0] != "encrypt") && (args.Length != 5 || args[0] != "decrypt"))
{
ShowHelp();
return;
}
SymmetricAlgorithm algorithm;
switch (args[2])
{
case "aes":
algorithm = new AesCryptoServiceProvider();
break;
case "des":
algorithm = new DESCryptoServiceProvider();
break;
case "rc2":
algorithm = new RC2CryptoServiceProvider();
break;
case "rijndael":
algorithm = new RijndaelManaged();
break;
default:
ShowHelp();
return;
}
switch (args[0])
{
case "encrypt":
Enigma.Encrypt(args[1], algorithm, args[3]);
break;
case "decrypt":
Enigma.Decrypt(args[1], algorithm, args[4], args[3]);
break;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exercuse_4
{
class Program
{
static void Main(string[] args)
{
List<int> integers = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
string command = Console.ReadLine();
while (command!="End")
{
var commandArray = command.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToArray();
if (commandArray[0]=="Add")
{
int add = int.Parse(commandArray[1]);
integers.Add(add);
}
if (commandArray[0]=="Remove")
{
int remove = int.Parse(commandArray[1]);
if (remove < 0 || remove > integers.Count - 1)
{
Console.WriteLine("Invalid index");
}
else
{
integers.RemoveAt(remove);
}
}
if (commandArray[0]=="Insert")
{
int add = int.Parse(commandArray[1]);
int addIndex = int.Parse(commandArray[2]);
if (addIndex < 0 || addIndex > integers.Count - 1)
{
Console.WriteLine("Invalid index");
}
else
{
integers.Insert(addIndex, add);
}
}
if (commandArray[0]=="Shift")
{
if (commandArray[1]=="left")
{
int left = int.Parse(commandArray[2]);
integers = ShiftLeft(left,integers);
}
if (commandArray[1]=="right")
{
int right = int.Parse(commandArray[2]);
integers = ShiftRight(right, integers);
}
}
command = Console.ReadLine();
}
Console.WriteLine(string.Join(" ", integers));
}
private static List<int> ShiftLeft(int left, List<int> integers)
{
List<int> numbers = integers;
for (int d = 0; d < left; d++)
{
int original = numbers[0];
for (int i = 0; i < numbers.Count - 1; i++)
{
numbers[i] = numbers[i + 1];
}
numbers[numbers.Count - 1] = original;
}
return numbers;
}
private static List<int> ShiftRight(int right, List<int> integers)
{
List<int> numbers = integers;
for (int d = 0; d < right; d++)
{
int original = numbers[numbers.Count-1];
for (int i = numbers.Count - 1; i > 0 ; i--)
{
numbers[i] = numbers[i -1];
}
numbers[0] = original;
}
return numbers;
}
}
}
|
using FluentAssertions;
using NUnit.Framework;
using Strings;
namespace StringsTests
{
[TestFixture]
public class ReplaceSpacesWithStringShould
{
private ReplaceSpacesWithString _replacer = new ReplaceSpacesWithString();
[TestCase("example string", "example_string")]
public void ReplaceCorrectlyWhenUsingStringbuilder(string withSpaces, string expectedOutputString)
{
_replacer.ReplaceUsingStringBuilder(ref withSpaces);
withSpaces.Should().Be(expectedOutputString);
}
[TestCase("example string", "example_string")]
public void ReplaceCorrectlyWhenUsingBasicArrayOperations(string withSpaces, string expectedOutputString)
{
_replacer.ReplaceUsingBasicStringOps(ref withSpaces);
withSpaces.Should().Be(expectedOutputString);
}
}
}
|
using System.Collections.Generic;
using Profiling2.Domain.Prf;
namespace Profiling2.Domain.Contracts.Tasks
{
public interface IUserTasks
{
AdminUser GetAdminUser(int userId);
AdminUser GetAdminUser(string userId);
IList<AdminUser> GetAllAdminUsers();
AdminUser CreateOrUpdateAdminUser(string id, string name);
/// <summary>
/// Updates a user's ID and Name.
/// </summary>
/// <param name="userId">ID as exists in database.</param>
/// <param name="newUserId">New ID to replace old.</param>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="email"></param>
void UpdateUser(string userId, string newUserId, string firstName, string lastName, string email);
void ArchiveUser(string username);
AdminUser SaveOrUpdateUser(AdminUser user);
AdminRole GetAdminRole(int id);
AdminRole GetAdminRole(string name);
IList<AdminRole> GetAllAdminRoles();
IList<object> GetAdminRolesJson(string term);
IList<object> GetAdminRolesJson();
AdminRole SaveOrUpdateAdminRole(AdminRole role);
AdminPermission GetAdminPermission(int id);
AdminPermission GetAdminPermission(string name);
IList<AdminPermission> GetAllAdminPermissions();
IList<object> GetAdminPermissionsJson(string term);
IList<object> GetAdminPermissionsJson();
bool ValidateUser(string username, string password);
IList<AdminUser> GetUsersWithRole(string role);
IList<AdminUser> GetUsersWithPermission(string permission);
/// <summary>
/// Get user emails by querying database using a new NHibernate Session (useful in background jobs).
/// </summary>
/// <param name="permission"></param>
/// <returns></returns>
IList<string> GetUserEmailsWithPermissionUsingNewSession(string permission);
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jogging.Model
{
public class User
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("role")]
public string Role { get; set; }
[JsonProperty("enabled")]
public bool Enabled { get; set; }
[JsonProperty("sessions")]
public HashSet<Session> Sessions { get; set; }
[JsonIgnore]
public static User DefaultUser = new User() { Name = "User", Password = "user" };
}
}
|
using UnityEngine;
using System.Collections;
public class startGame : MonoBehaviour {
public void changeScene()
{
Application.LoadLevel("game");
}
public void appClose()
{
Application.Quit();
}
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Internal.Common
{
public class SwitchDefinition
{
private SwitchDefinition()
{
}
public string Name { get; private set; }
public string Description { get; set; }
public bool IsFlag { get; private set; }
public bool Required { get; private set; }
public bool Undocumented { get; set; }
public string SwitchFormat { get; set; }
public static SwitchDefinition ParamWithFormat(string name, string description, bool required, string format)
{
return new SwitchDefinition()
{
Name = name,
Description = description,
IsFlag = false,
Required = required,
SwitchFormat = format
};
}
public static SwitchDefinition Param(string name, string description, bool required)
{
return new SwitchDefinition()
{
Name = name,
Description = description,
IsFlag = false,
Required = required
};
}
public static SwitchDefinition Flag(string name, string description)
{
return new SwitchDefinition()
{
Name = name,
Description = description,
IsFlag = true,
Required = false
};
}
}
}
|
namespace gView.GraphicsEngine.Skia
{
class SkiaBitmapPixelData : BitmapPixelData
{
public SkiaBitmapPixelData(BitmapLockMode lockMode)
: base(lockMode)
{
FreeMemory = false;
}
internal bool FreeMemory;
}
}
|
namespace Sped
{
public struct C170
{
private readonly Line _line;
public C170(Line line)
{
_line = line;
}
public string CodProduto => _line.Params[3];
public decimal ValorContabil => decimal.Parse(string.IsNullOrEmpty(_line.Params[7]) ? "0" : _line.Params[7]);
public string Cfop => _line.Params[11];
public decimal BaseCalculo => decimal.Parse(string.IsNullOrEmpty(_line.Params[13]) ? "0" : _line.Params[13]);
public decimal Aliquota => decimal.Parse(string.IsNullOrEmpty(_line.Params[14]) ? "0" : _line.Params[14]);
public decimal Icms => decimal.Parse(string.IsNullOrEmpty(_line.Params[15]) ? "0" : _line.Params[15]);
}
} |
namespace Assets.Scripts.Models.ResourceObjects
{
public class FiberResource : ResourceObject
{
public FiberResource()
{
LocalizationName = "fiber_resource";
IconName = "fiber_icon";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BO
{
public class Cours
{
public int ID { get; set; }
public string Intitule { get; set; }
public string DescriptionPartielle { get; set; }
public string DescriptionComplete { get; set; }
public Auteur Auteur { get; set; }
public string PathImage { get; set; }
public Categorie Categorie { get; set; }
public int nombreInscritp { get; set; } //cette variable me sert dans ma fonction BL.display.select , je l'utilise par facilité
public DateTime DateAjout { get; set; }
}
}
|
using JDWinService.Dal;
using JDWinService.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace JDWinService.Utils
{
public class Common
{
public string K3connectionString = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["K3ConnectionString"].Value; //连接信息
public enum FileType
{
采购订单_物料 = 0,
销售订单 = 1,
采购限价申请 = 2,
销售限价申请 = 3,
请购单_物料 = 4,
请购单变更 = 5,
采购订单变更_物料 = 6,
采购订单变更_NPI = 7,
供应商流程 = 8,
客户新增或变更流程=9
}
public enum PageNum
{
Page1 = 0,
Page2 = 1,
Page3 = 2,
Page4 = 3
}
public void WriteLogs(string content)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string LogName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
string[] sArray = path.Split(new string[] { LogName }, StringSplitOptions.RemoveEmptyEntries);
string aa = sArray[0] + "\\" + LogName + "Log\\";
path = aa;
if (!string.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" + content + "\r\n");
sw.Close();
}
}
}
public void WriteLogs(string FileType, string content)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string LogName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
string[] sArray = path.Split(new string[] { LogName }, StringSplitOptions.RemoveEmptyEntries);
string aa = sArray[0] + "\\" + LogName + "Log\\" + FileType + "\\";
path = aa;
if (!string.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" + content + "\r\n");
sw.Close();
}
}
}
public void WriteLogs(string FileType, string TaskID, string content)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string LogName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
string[] sArray = path.Split(new string[] { LogName }, StringSplitOptions.RemoveEmptyEntries);
string aa = sArray[0] + "\\" + LogName + "Log\\" + FileType + "\\" + TaskID + "\\";
path = aa;
if (!string.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" + content + "\r\n");
sw.Close();
}
}
}
public void UpdateTable(string TableName, string TaskID)
{
string Sql = string.Format(@"update '{0}' set IsUpdate='1' where TaskId='{1}'", TableName, TaskID);
DBUtil.ExecuteSql(Sql);
this.WriteLogs("更新表:" + TableName + ",TaskID:" + TaskID);
}
public Result SendToK3(string loginUrl, string SendJson)
{
HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, SendJson, null, null, Encoding.UTF8, null);
Stream resStream = response.GetResponseStream();
StreamReader sr2 = new StreamReader(resStream, Encoding.UTF8);
string ReturnMsg = sr2.ReadToEnd();
new Common().WriteLogs("K3 返回Code:" + ReturnMsg);
Result result = new Result(ReturnMsg, "");
return result;
}
public SeOrderResult SendToK3InSe(string loginUrl, string SendJson)
{
HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, SendJson, null, null, Encoding.UTF8, null);
Stream resStream = response.GetResponseStream();
StreamReader sr2 = new StreamReader(resStream, Encoding.UTF8);
string ReturnMsg = sr2.ReadToEnd();
new Common().WriteLogs("K3 返回Code:" + ReturnMsg);
return new SeOrderResult(ReturnMsg);
}
//服务字段更新
public DataTable GetUpdateTab(string TableName, string SqlFilter)
{
string sql = string.Format(@"select A.* from {0} A left join BPMInstTasks B
on A.TaskID=B.TaskID where B.State='Approved' and A.IsUpdate='0' {1}", TableName, SqlFilter);
return DBUtil.Query(sql).Tables[0];
}
//应用表单字段
public DataTable GetUpdateAppTab(string TableName, string sqlFilter)
{
string sql = string.Format(@"select * from {0} where Isupdate='0' {1} ", TableName, sqlFilter);
return DBUtil.Query(sql).Tables[0];
}
//获得最大ID
public int GetMaxID(string FieldName, string TableName, string SqlFilter)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
if (!String.IsNullOrEmpty(strsql))
{
strsql = strsql + SqlFilter;
}
object obj = DBUtil.GetSingle(strsql, K3connectionString);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public int GetMaxItemID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = DBUtil.GetSingle(strsql, K3connectionString);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <summary>
/// 插入日志查询列表
/// </summary>
/// <param name="TaskID"></param>
/// <param name="TableName">轮询日志表名</param>
/// <param name="TableItemID">轮询日志表ID</param>
/// <param name="LogType">"API"|"SQL"</param>
/// <param name="Message">返回信息</param>
/// <param name="Success">是否成功</param>
/// <returns></returns>
public void AddLogQueue(int TaskID, string TableName, int TableItemID, string LogType, string Message, bool Success)
{
JD_LogMngQueueDal dal = new JD_LogMngQueueDal();
JD_LogMngFailedDal faildal = new JD_LogMngFailedDal();
BPMInstTasksDal taskdal = new BPMInstTasksDal();
DateTime NowDate = DateTime.Now;
BPMInstTasks taskMol = taskdal.Detail(TaskID);
int LogQueID = dal.Add(new JD_LogMngQueue
{
TaskID = TaskID,
TableItemID = TableItemID,
LogTableName = TableName,
Message = Message,
CreateTime = NowDate,
LogType = LogType,
Year = NowDate.Year,
Month = NowDate.Month,
IsSuccess = (Success == true) ? 1 : 0,
FileName = taskMol.ProcessName,
SNumber = taskMol.SerialNum
});
//如果不成功 插入错误日志
if (!Success)
{
faildal.Add(new JD_LogMngFailed
{
TaskID = TaskID,
TableItemID = TableItemID,
LogTableName = TableName,
CreateTime = NowDate,
FileName = taskMol.ProcessName,
SNumber = taskMol.SerialNum,
LogQueID = LogQueID,
LogType = LogType,
Message = Message
});
}
}
public void AddLogQueue(string FileName, string TableName, int TableItemID, string LogType, string Message, bool Success)
{
JD_LogMngQueueDal dal = new JD_LogMngQueueDal();
JD_LogMngFailedDal faildal = new JD_LogMngFailedDal();
BPMInstTasksDal taskdal = new BPMInstTasksDal();
DateTime NowDate = DateTime.Now;
int LogQueID = dal.Add(new JD_LogMngQueue
{
TaskID = 0,
TableItemID = TableItemID,
LogTableName = TableName,
Message = Message,
CreateTime = NowDate,
LogType = LogType,
Year = NowDate.Year,
Month = NowDate.Month,
IsSuccess = (Success == true) ? 1 : 0,
FileName = FileName,
SNumber = "-"
});
//如果不成功 插入错误日志
if (!Success)
{
faildal.Add(new JD_LogMngFailed
{
TaskID = 0,
TableItemID = TableItemID,
LogTableName = TableName,
CreateTime = NowDate,
FileName = FileName,
SNumber = "-",
LogQueID = LogQueID,
LogType = LogType,
Message = Message
});
}
}
public void AddLogQueue(int TaskID, string TableName, int TableItemID, string LogType, string Message)
{
if (!string.IsNullOrEmpty(Message))
{
AddLogQueue(TaskID, TableName, TableItemID, LogType, Message, false);
}
else
{
AddLogQueue(TaskID, TableName, TableItemID, LogType, "操作成功!", true);
}
}
}
} |
namespace RandomizeWords
{
using System;
using System.Linq;
public class StartUp
{
public static void Main()
{
var input = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var rnd = new Random();
for (int i = 0; i < input.Length - 1; i++)
{
int index = rnd.Next(0, input.Length);
var word = input[index];
var newIndex = rnd.Next(0, input.Length);
input[index] = input[newIndex];
input[newIndex] = word;
}
for (int i = 0; i < input.Length; i++)
{
Console.WriteLine(input[i]);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Unidade9.ExerciciosComplementares
{
class _4
{
public static int i;
public static Random Rand = new Random();
static void Main11(string[] args)
{
int[] vetor = new int[12];
int[] vetor2 = new int[12];
for (i = 0; i < vetor.Length; i++)
{
vetor[i] = Rand.Next(0, 10);
Console.WriteLine("Valores do primeiro vetor: " + vetor[i]);
}
Console.WriteLine("");
for (i = 0; i < vetor.Length; i++)
{
if (vetor[i] == 0)
{
vetor2[i] = 1;
}
else
vetor2[i] = vetor[i];
Console.WriteLine("Valores do Segundo vetor: " + vetor2[i]);
}
}
}
}
|
using System;
using Framework;
namespace IDCard
{
public class IDCard : Product
{
private int _id;
private string _owner;
public IDCard(int id, string owner)
{
this._id = id;
this._owner = owner;
Console.WriteLine($"{_owner}({_id})のカードを作ります");
}
public override void Use()
{
Console.WriteLine($"{_id}:{_owner}のカードを使います");
}
public int GetId()
{
return _id;
}
public string GetOwner()
{
return _owner;
}
}
} |
using System;
namespace EasyConsoleNG.Menus
{
public interface IMenuPage
{
void Display();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ATMConsole
{
public interface IAccountDAC
{
IEnumerable<Account> GetAllAccounts();
}
}
|
using PatientService.DTO;
using PatientService.Model;
using PatientService.Model.ExaminationSpecification;
using PatientService.Model.Specification;
namespace PatientService.Mapper
{
public static class ExaminationSearchMapper
{
public static ISpecification<Examination> ToExaminationSpecification(this ExaminationSearchDTO parameters)
{
ISpecification<Examination> filter = new ExaminationStartDateSpecification(parameters.StartDate);
filter = filter.BinaryOperation(
parameters.EndDateOperator, new ExaminationEndDateSpecification(parameters.EndDate));
filter = filter.BinaryOperation(
parameters.DoctorSurnameOperator, new ExaminationDoctorSurnameSpecification(parameters.DoctorSurname));
filter = filter.BinaryOperation(
parameters.AnamnesisOperator, new ExaminationAnamnesisSpecification(parameters.Anamnesis));
return filter;
}
}
}
|
using System;
using System.Collections.Generic;
using Hl7.Fhir.Support;
using System.Xml.Linq;
/*
Copyright (c) 2011-2012, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
//
// Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08
//
namespace Hl7.Fhir.Model
{
/// <summary>
/// A Diagnostic report - a combination of request information, atomic results, images, interpretation, and formatted reports
/// </summary>
[FhirResource("DiagnosticReport")]
public partial class DiagnosticReport : Resource
{
/// <summary>
/// null
/// </summary>
[FhirComposite("DiagnosticReportRequestDetailComponent")]
public partial class DiagnosticReportRequestDetailComponent : Element
{
/// <summary>
/// Context where request was made
/// </summary>
public ResourceReference Visit { get; set; }
/// <summary>
/// Id assigned by requester
/// </summary>
public Identifier RequestOrderId { get; set; }
/// <summary>
/// Receiver's Id for the request
/// </summary>
public Identifier ReceiverOrderId { get; set; }
/// <summary>
/// Test Requested
/// </summary>
public List<CodeableConcept> RequestTest { get; set; }
/// <summary>
/// Location of requested test (if applicable)
/// </summary>
public CodeableConcept BodySite { get; set; }
/// <summary>
/// Responsible for request
/// </summary>
public ResourceReference Requester { get; set; }
/// <summary>
/// Clinical information provided
/// </summary>
public FhirString ClinicalInfo { get; set; }
}
/// <summary>
/// null
/// </summary>
[FhirComposite("ResultGroupComponent")]
public partial class ResultGroupComponent : Element
{
/// <summary>
/// Name/Code for this group of results
/// </summary>
public CodeableConcept Name { get; set; }
/// <summary>
/// Specimen details for this group
/// </summary>
public ResourceReference Specimen { get; set; }
/// <summary>
/// Nested Report Group
/// </summary>
public List<ResultGroupComponent> Group { get; set; }
/// <summary>
/// An atomic data result
/// </summary>
public List<ResourceReference> Result { get; set; }
}
/// <summary>
/// registered|interim|final|amended|cancelled|withdrawn
/// </summary>
public Code<ObservationStatus> Status { get; set; }
/// <summary>
/// Date this version was released
/// </summary>
public Instant Issued { get; set; }
/// <summary>
/// The subject of the report
/// </summary>
public ResourceReference Subject { get; set; }
/// <summary>
/// Responsible Diagnostic Service
/// </summary>
public ResourceReference Performer { get; set; }
/// <summary>
/// Id for external references to this report
/// </summary>
public Identifier ReportId { get; set; }
/// <summary>
/// What was requested
/// </summary>
public List<DiagnosticReportRequestDetailComponent> RequestDetail { get; set; }
/// <summary>
/// Biochemistry, Haematology etc.
/// </summary>
public CodeableConcept ServiceCategory { get; set; }
/// <summary>
/// Effective time of diagnostic report
/// </summary>
public FhirDateTime DiagnosticTime { get; set; }
/// <summary>
/// Results grouped by specimen/kind/category
/// </summary>
public ResultGroupComponent Results { get; set; }
/// <summary>
/// Key images associated with this report
/// </summary>
public List<ResourceReference> Image { get; set; }
/// <summary>
/// Clinical Interpretation of test results
/// </summary>
public FhirString Conclusion { get; set; }
/// <summary>
/// Codes for the conclusion
/// </summary>
public List<CodeableConcept> CodedDiagnosis { get; set; }
/// <summary>
/// Entire Report as issued
/// </summary>
public List<Attachment> Representation { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class AtkAreaMouseOver : MonoBehaviour {
public bool MouseIsOver = false;
public bool MouseIsDown = false;
void Start () {
}
void Update()
{
}
void OnMouseDown() {
MouseIsDown = true;
if (GameManager.ClickingObject != null) {
GameManager.ClickingObject = "AtkableArea";
HeroGamePlay.walkstatus = "YES";
}
}
}
|
using RestSharp;
namespace Zendesk.LineItems
{
public class LineItemActions : ILineItemActions
{
private RestClient client;
public LineItemActions(RestClient client)
{
this.client = client;
}
}
} |
using BizService.Common;
using IWorkFlow.BaseService;
using IWorkFlow.DataBase;
using IWorkFlow.Host;
using IWorkFlow.ORM;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace BizService
{
class ComClass
{
#region 基础相关
#region 用户部门相关
/// <summary>
/// 根据用户ID获取用户信息
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static UserInfo GetUserInfo(string userId)
{
UserInfo en = new UserInfo();
en.Condition.Add("UserID=" + userId);
en = Utility.Database.QueryObject<UserInfo>(en);
return en;
}
/// <summary>
/// 获取全部部门
/// </summary>
/// <returns></returns>
public static List<Department> GetAllDepts()
{
Department deptEnt = new Department();
deptEnt.OrderInfo = "rankid";
var deptList = Utility.Database.QueryList(deptEnt);
// deptList = deptList.OrderBy(o => o.RankId).ToList<Department>();// 排序
return deptList;
}
public static FX_Department GetDeptByUserId(string userId)
{
//// Department deptEnt = new Department();
//var sql = @"select UserID, EnName, CnName, DPName from FX_UserInfo a, FX_Department b where a.DPID = b.DPID and a.UserID = " + userId;
//DataSet ds = Utility.Database.ExcuteDataSet(sql);
//return ds;
UserInfo uient = new UserInfo();
uient.Condition.Add("UserID=" + userId);
uient = Utility.Database.QueryObject<UserInfo>(uient);
FX_Department dptent = new FX_Department();
dptent.Condition.Add("DPID=" + uient.DPID);
dptent = Utility.Database.QueryObject<FX_Department>(dptent);
return dptent;
}
// 获取部门和用户信息
public static DeptInfoAndUserInfo GetDeptAndUserByUserId(string userId)
{
try
{
var data = new DeptInfoAndUserInfo();
UserInfo uient = new UserInfo();
uient.Condition.Add("UserID=" + userId);
uient = Utility.Database.QueryObject<UserInfo>(uient);
data.userinfo = uient;
FX_Department dptent = new FX_Department();
dptent.Condition.Add("DPID=" + uient.DPID);
dptent = Utility.Database.QueryObject<FX_Department>(dptent);
data.deptinfo = dptent;
return data;
}
catch (Exception ex)
{
ComBase.Logger(ex.Message);
return null;
}
}
public static DataTable GetSighture(string caseId,string type,IDbTransaction tran) {
StringBuilder strSql = new StringBuilder();
//读取签发
strSql.AppendFormat(@"select s.*,u.CnName from B_OA_Sighture as s
LEFT JOIN FX_UserInfo as u on s.userid = u.UserID where s.caseid='{0}' and s.type = '{1}'", caseId, "0");
DataSet ds = Utility.Database.ExcuteDataSet(strSql.ToString(), tran);
return ds.Tables[0];
}
#endregion
#region 权限相关
/// <summary>
/// 获取某个用户的全部权限
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static List<IWorkFlow.BaseService.Privilege> GetPrivilegebyUserId(string userId)
{
return IWorkFlow.BaseService.IWorkPrivilegeManage.QueryPrivilegebyUserID(userId);//.FindAll(g => g.Type == "信访权限集").Select(p => p.ModelKey).Contains("deleteCase");
}
/// <summary>
/// 是否拥有权限
/// </summary>
/// <param name="userId">用户ID</param>
/// <param name="type">权限类型</param>
/// <param name="modelKey">权限值</param>
/// <returns></returns>
public static bool IsHavePrivilege(string userId, string type, string modelKey)
{
var priList = GetPrivilegebyUserId(userId);
return priList.Where(o => o.Type == type && o.ModelKey == modelKey).Count() > 0;
}
#endregion
#region 数据字典(下拉框)数据
/// <summary>
/// 获取数据字典项
/// </summary>
/// <param name="type">数据字典类型</param>
/// <returns></returns>
public static List<BASE_DataDictItem> GetDataDictItemByType(string type)
{
BASE_DataDictType ddType = new BASE_DataDictType();
ddType.Condition.Add(string.Format("TYPE={0}", type));
ddType = Utility.Database.QueryObject(ddType);
if (ddType != null)
{
string pk = ddType.PK;
BASE_DataDictItem ddItem = new BASE_DataDictItem();
ddItem.Condition.Add(string.Format("FK={0}", pk));
return Utility.Database.QueryList(ddItem);
}
return null;
}
/// <summary>
/// 获取数据字典项
/// </summary>
/// <param name="type">类型</param>
/// <param name="isEnabled">是否只取启用的(默认:是)</param>
/// <returns></returns>
public static Dictionary<string, string> GetDataDict(string type, bool isEnabled = true)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
var list = GetDataDictItemByType(type);
if (list != null)
{
foreach (var item in list)
{
if (isEnabled)
{
if (string.IsNullOrWhiteSpace(item.IsEnabled) || item.IsEnabled != "0")
{
dict.Add(item.Value, item.Name);
}
}
else
{
dict.Add(item.Value, item.Name);
}
}
}
return dict;
}
/// <summary>
/// 获取数据字典项
/// </summary>
/// <param name="type">类型</param>
/// <param name="isEnabled">是否只取启用的(默认:是)</param>
/// <returns></returns>
public static Dictionary<string, string> GetDataDictFromXml(string type, bool isEnabled = true)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
ComDataDict dd = new ComDataDict();
var dditem = dd.GetDataDictConfig(type);
if (dditem != null)
{
foreach (var item in dditem.DataDictItems)
{
if (isEnabled)
{
if (item.IsEnabled == null || item.IsEnabled.Value)
{
dict.Add(item.Value, item.Name);
}
}
else
{
dict.Add(item.Value, item.Name);
}
}
}
return dict;
}
#endregion
#region 其他
/// <summary>
/// 获取GUID
/// </summary>
/// <returns></returns>
public static string GetGuid()
{
System.Guid guid = new Guid();
guid = Guid.NewGuid();
return string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), guid.ToString());
}
#endregion
#endregion
#region 业务相关
#endregion
#region 工作流相关
/// <summary>
/// 获取工作流审批意见列表WorkFlowBusact(sqlserver)
/// </summary>
/// <param name="caseId">流程实例ID</param>
/// <returns></returns>
public static List<FX_WorkFlowBusAct> GetFlowCaseOpinion(string caseId)
{
string sql = @"
select *
from (select a.CASEID, --获取发送人审批意见
a.BAID,
a.ACTID,
a.ACTNAME,
a.SENDACTID,
a.SENDACTNAME,
a.SENDER,
a.SENDERNAME,
a.USERID,
a.USERNAME,
a.RECEDATE,
a.RECESTATE,
a.STATE,
a.REMARK,
a.ISREADED,
b.recedate as senddate
from fx_workflowbusact a
join fx_workflowbusact b
on a.caseid = '{0}'
and (a.state = 1 or a.state = 2) --限定已完成状态的
and b.caseid = a.caseid --限定caseid
and a.userid = b.sender --限定发送人
and b.baid =
('BA'+right('000'+CONVERT(varchar,right(a.BAID,3)+1),3)) --限定发送步骤(存在下一个步骤则表示当前步骤为发送步骤)
union all
--获取最后审批人
select a.CASEID,
a.BAID,
a.ACTID,
a.ACTNAME,
a.SENDACTID,
a.SENDACTNAME,
a.SENDER,
a.SENDERNAME,
a.USERID,
a.USERNAME,
a.RECEDATE,
a.RECESTATE,
a.STATE,
a.REMARK,
a.ISREADED,
b.enddate as senddate
from fx_workflowcase b
join fx_workflowbusact a
on b.id = 'C000002'
and b.id = a.caseid
and b.isend = 1--限定办结状态的
and a.userid = b.ender --限定办结人
and baid = ( select top 1 BAID from [FX_WorkFlowBusAct] where caseid = '{0}' order by baid desc)--限定最后步骤
) tball
order by senddate desc --降序排序
";
sql = string.Format(sql, caseId);
DataSet ds = Utility.Database.ExcuteDataSet(sql);
return ConvertHelper<FX_WorkFlowBusAct>.DataTableToList(ds.Tables[0]);
}
/// <summary>
/// 获取工作流审批意见列表WorkFlowBusact(oracle)
/// <param name="caseId">流程实例ID</param>
/// <returns></returns>
public static List<FX_WorkFlowBusAct> GetFlowCaseOpinion_Oracle(string caseId)
{
string sql = @"
select *
from (select a.CASEID, --获取发送人审批意见
a.BAID,
a.ACTID,
a.ACTNAME,
a.SENDACTID,
a.SENDACTNAME,
a.SENDER,
a.SENDERNAME,
a.USERID,
a.USERNAME,
a.RECEDATE,
a.RECESTATE,
a.STATE,
to_char(a.REMARK) as REMARK,
a.ISREADED,
b.recedate as senddate
from fx_workflowbusact a
join fx_workflowbusact b
on a.caseid = '{0}'
and (a.state = 1 or a.state = 2) --限定已完成状态的
and b.caseid = a.caseid --限定caseid
and a.userid = b.sender --限定发送人
and b.baid =
('BA' || LPAD(to_number(SUBSTR(a.baid, 3)) + 1, 3, '0')) --限定发送步骤
union
--获取最后审批人
select a.CASEID,
a.BAID,
a.ACTID,
a.ACTNAME,
a.SENDACTID,
a.SENDACTNAME,
a.SENDER,
a.SENDERNAME,
a.USERID,
a.USERNAME,
a.RECEDATE,
a.RECESTATE,
a.STATE,
to_char(a.REMARK) as REMARK,
a.ISREADED,
b.enddate as senddate
from fx_workflowcase b
join fx_workflowbusact a
on b.id = '{0}'
and b.id = a.caseid
and b.isend = 1--限定办结状态的
and a.userid = b.ender --限定办结人
and baid = (select baid --限定最后步骤
from (select *
from fx_workflowbusact
where caseid = '{0}'
order by baid desc)
where rownum = 1))
order by senddate desc --降序排序
";
sql = string.Format(sql, caseId);
DataSet ds = Utility.Database.ExcuteDataSet(sql);
return ConvertHelper<FX_WorkFlowBusAct>.DataTableToList(ds.Tables[0]);
}
#endregion
}
public class DeptInfoAndUserInfo
{
public UserInfo userinfo;
public FX_Department deptinfo;
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.ListadoContrato
{
/// <summary>
/// Modelo de vista de Contrato Párrafo Bien
/// </summary>
/// <remarks>
/// Creación: GMD 20150803 </br>
/// Modificación: </br>
/// </remarks>
public class ContratoParrafoBienFormulario
{
/// <summary>
/// Constructor usado para la búsqueda de datos
/// </summary>
public ContratoParrafoBienFormulario(List<BienResponse> bien)
{
this.Bien = bien;
}
#region Propiedades
/// <summary>
/// Lista de Bienes
/// </summary>
public List<BienResponse> Bien { get; set; }
//INICIO: Agregado por Julio Carrera - Norma Contable
/// <summary>
/// Listas de Tipos de Tarifa
/// </summary>
public List<SelectListItem> lstTipoTarifa { get; set; }
/// <summary>
/// Listas de Periodos de Alquiler
/// </summary>
public List<SelectListItem> lstPeriodoAlquiler { get; set; }
/// <summary>
/// Código de Tipo de Tarifa
/// </summary>
public string CodigoTipoTarifa { get; set; }
/// <summary>
/// Código Periodo de Alquiler
/// </summary>
public string CodigoPeriodoAlquiler { get; set; }
/// <summary>
/// Código Periodo de Alquiler
/// </summary>
public string CodigoTipoServicio { get; set; }
//FIN: Agregado por Julio Carrera - Norma Contable
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIManager : MonoBehaviour
{
public static UIManager Instance;
public GameObject FakeCharacterWindow;
public GameObject CharacterCreationWindow;
[Header("Settings: ")]
[SerializeField] Image fadeImage;
public float FadeDelay;
[Tooltip("The time it takes to completely fade")] public float FadeDuration;
[SerializeField] AnimationCurve fadeCurve;
bool isFading = false;
Coroutine fadeRoutine;
private void Awake()
{
Instance = this;
fadeImage.color = new Color(fadeImage.color.r, fadeImage.color.g, fadeImage.color.b, 1);
}
private void Start()
{
FadeIn();
}
private void Update()
{
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.Q))
{
CloseWindow(CharacterCreationWindow);
LevelManager.Instance.NextLevel();
}
if (Input.GetKeyDown(KeyCode.Escape))
FadeOut();
if (Input.GetKeyDown(KeyCode.B))
FadeIn();
#endif
}
public void FadeOut()
{
if (fadeRoutine != null) StopCoroutine(fadeRoutine);
fadeRoutine = StartCoroutine(IFadeOut());
}
public void FadeIn()
{
if (fadeRoutine != null) StopCoroutine(fadeRoutine);
fadeRoutine = StartCoroutine(IFadeIn());
}
IEnumerator IFadeOut()
{
float _tweenTime = 0;
isFading = true;
Color _startColor = fadeImage.color;
yield return new WaitForSeconds(FadeDelay);
while (_tweenTime < 1)
{
_tweenTime += Time.deltaTime / FadeDuration;
float _tweenKey = fadeCurve.Evaluate(_tweenTime);
fadeImage.color = LerpAlpha(_startColor, 1, _tweenKey);
yield return null;
}
isFading = false;
yield return null;
}
IEnumerator IFadeIn()
{
float _tweenTime = 0;
isFading = true;
Color _startColor = fadeImage.color;
yield return new WaitForSeconds(FadeDelay);
while (_tweenTime < 1)
{
_tweenTime += Time.deltaTime / FadeDuration;
float _tweenKey = fadeCurve.Evaluate(_tweenTime);
fadeImage.color = LerpAlpha(_startColor, 0, _tweenKey);
yield return null;
}
isFading = false;
yield return null;
}
Color LerpAlpha(Color c, float a, float t)
{
Color _returnColor = Color.Lerp(c, new Color(c.r, c.g, c.b, a), t);
return _returnColor;
}
public void CloseWindow(GameObject _window)
{
_window.SetActive(false);
}
public void OpenWindow(GameObject _window)
{
_window.SetActive(true);
}
}
|
using System;
using Xunit;
using Grpc.Core;
using GrpcMovies;
using Grpc.Net.Client;
using System.Net.Http;
using System.Threading.Tasks;
namespace GrpcMoviesTest
{
public class UnitTest1
{
[Fact]
public void Test1()
{
}
}
}
|
using System;
using System.IO;
namespace OOP_RPG
{
public class FileDatabase
{
private string filePath1 = "Hero.txt", filePath2 = "Achievements.csv", filePath3 = "Weapon.txt", filePath4 = "Armor.txt";
public FileDatabase()
{
filePath1 = Environment.CurrentDirectory + @"\" + filePath1;
filePath2 = Environment.CurrentDirectory + @"\" + filePath2;
filePath2 = Environment.CurrentDirectory + @"\" + filePath3;
filePath2 = Environment.CurrentDirectory + @"\" + filePath4;
}
public string[] ReadHero()
{
if (File.Exists(filePath1))
return File.ReadAllLines(filePath1);
else
return null;
}
public string[] ReadAchievements()
{
if (File.Exists(filePath2))
return File.ReadAllLines(filePath2);
else
return null;
}
/*public string[] ReadSword()
{
if (File.Exists(filePath3))
return File.ReadAllLines(filePath3);
else
return null;
}*/
public void UpdateFile1(string data)
{
File.WriteAllText(filePath1, data);
}
public void UpdateFile2(string data)
{
File.WriteAllText(filePath2, data);
}
public void UpdateFile3(string data)
{
File.WriteAllText(filePath3, data);
}
}
}
|
using MahApps.Metro.Controls;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;
namespace MinecraftToolsBoxSDK
{
public partial class TaskBarButton : Control
{
public ImageSource Source { get; set; }
public object Tip { get; set; }
public StackPanel WindowItems { get; set; } = new StackPanel { Orientation = Orientation.Horizontal };
public MtbPlugin Plugin;
public Badged Badge;
internal TextBlock Bar;
static TaskBarButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TaskBarButton), new FrameworkPropertyMetadata(typeof(TaskBarButton)));
}
protected override void OnToolTipOpening(ToolTipEventArgs e)
{
base.OnToolTipOpening(e);
IMainWindowCommands main = Application.Current.MainWindow as IMainWindowCommands;
int offset = (Parent as StackPanel).Children.IndexOf(this) * 48 + 123 - WindowItems.Children.Count * 108;
main.ShowWindowView(WindowItems, offset < 0 ? 0 : offset);
Application.Current.MainWindow.PreviewMouseMove += TaskBarButton_MouseMove;
}
public void TaskBarButton_MouseMove(object sender, MouseEventArgs e)
{
IMainWindowCommands main = Application.Current.MainWindow as IMainWindowCommands;
Point p1 = e.GetPosition(WindowItems), p2 = e.GetPosition(this);
if (p1.Y < -10 || p1.X < -10 || p1.X > WindowItems.Children.Count * 216 + 10 || (p2.X < 0 || p2.X > 48) && p2.Y > 0)
{
Application.Current.MainWindow.PreviewMouseMove -= TaskBarButton_MouseMove;
main.CloseWindowView();
}
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
DataContext = this;
}
}
public class MyBadged : Badged
{
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
BadgePlacementMode = ControlzEx.BadgePlacementMode.TopRight;
(VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(this) as DependencyObject) as TaskBarButton).Badge = this;
}
}
public class MyTextBlock : TextBlock
{
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
(VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(this) as DependencyObject) as TaskBarButton).Bar = this;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Management_Plus
{
public partial class BackUp : Form
{
public BackUp()
{
InitializeComponent();
}
static BackUp bu=null;
public static BackUp backUp
{
get{
if(bu==null)
{
bu=new BackUp();
bu.FormClosed+=new FormClosedEventHandler(bu_FormClosed);
}
else
{
bu.Activate();
bu.BringToFront();
}
return bu;
}
}
static void bu_FormClosed(object sender, FormClosedEventArgs e)
{
bu=null;
}
private void button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
textBox1.Text = folderBrowserDialog1.SelectedPath.ToString();
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_add_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text != "")
{
string CurrentDatabasePath = "D:\\project database";
string db = "Management Plus.mdb";
string sf = System.IO.Path.Combine(CurrentDatabasePath, db);
string df = System.IO.Path.Combine(textBox1.Text, db);
if (!System.IO.Directory.Exists(textBox1.Text))
{
System.IO.Directory.CreateDirectory(textBox1.Text);
}
System.IO.File.Copy(sf, df, true);
if (System.IO.Directory.Exists(CurrentDatabasePath))
{
string[] dbs = System.IO.Directory.GetFiles(CurrentDatabasePath);
foreach (string f in dbs)
{
db = System.IO.Path.GetFileName(f);
df = System.IO.Path.Combine(textBox1.Text, db);
System.IO.File.Copy(f, df, true);
}
}
else
{
MessageBox.Show("error");
}
textBox1.Clear();
MessageBox.Show("BACKUP SUCCESSFULLY.");
}
else {
MessageBox.Show("Plase Select Path Of Back Up..." , "Info..", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception)
{
MessageBox.Show("Something Gose Wrong......", "Error..", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
using System;
using Newtonsoft.Json;
namespace ZendeskSell.Tasks
{
public class TaskRequest
{
[JsonProperty("resource_type")]
public string ResourceType { get; set; }
[JsonProperty("resource_id")]
public int ResourceID { get; set; }
[JsonProperty("owner_id")]
public int OwnerID { get; set; }
[JsonProperty("due_date")]
public DateTimeOffset DueDate { get; set; }
[JsonProperty("remind_at")]
public DateTimeOffset RemindAt { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ControleEstacionamento.Domain.Entities
{
public class MovimentacaoVeiculo
{
public int MovimentacaoVeiculoId { get; set; }
public string Placa { get; set; }
public string NomeCliente { get; set; }
public DateTime Entrada { get; set; }
public DateTime? Saida { get; set; }
public int? HorasPermanencia { get; set; }
public int? MinutosPermanencia { get; set; }
public double ValorTotal { get; set; }
public virtual Valores Valor { get; set; }
public int ValorId { get; set; }
public MovimentacaoVeiculo()
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.TRANS
{
[Serializable]
public partial class MrpPlanMaster : EntityBase
{
#region O/R Mapping Properties
[Display(Name = "MrpPlanMaster_PlanVersion", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public DateTime PlanVersion { get; set; }//Ö÷¼ü
[Display(Name = "MrpPlanMaster_SnapTime", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public DateTime SnapTime { get; set; }
[Display(Name = "MrpPlanMaster_SourcePlanVersion", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public DateTime SourcePlanVersion { get; set; }
[Display(Name = "MrpPlanMaster_DateIndex", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public string DateIndex { get; set; }
public CodeMaster.ResourceGroup ResourceGroup { get; set; }
[Display(Name = "MrpPlanMaster_Status", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public CodeMaster.MessageType Status { get; set; }
public Int32 CreateUserId { get; set; }
[Display(Name = "MrpPlanMaster_CreateUserName", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public string CreateUserName { get; set; }
[Display(Name = "MrpPlanMaster_CreateDate", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
[Display(Name = "MrpPlanMaster_IsRelease", ResourceType = typeof(Resources.MRP.MrpPlanMaster))]
public bool IsRelease { get; set; }
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DimondCounter : MonoBehaviour {
public Text text;
public Animator animator;
public static int treasureCount;
public int currentCount;
void Awake(){
treasureCount = 0;
currentCount = 0;
text.text = treasureCount.ToString();
}
void Update(){
if (treasureCount != currentCount){
text.text = treasureCount.ToString();
currentCount = treasureCount;
animator.Play("pup");
}
}
}
|
using System;
namespace FactoryMethod.Classes.Pizzas
{
public class ChicagoStyleVeggiePizza : Pizza
{
public ChicagoStyleVeggiePizza()
{
Name = "Chicago Style Veggie Pizza";
Dough = "Extra Trick Veggie Dough";
Sause = "Plum Veggie Sause";
toppings.Add("Shredded Veggie Cheese");
}
public override void cut()
{
Console.WriteLine("Cutting the pizza ingo square slices");
}
}
} |
using System;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.ServiceModel.Web;
using System.Threading;
using System.Linq.Expressions;
using System.ServiceModel;
using System.Reflection;
using Resolver = ExpressionSerialization.TypeResolver;
using System.Dynamic;
using System.ServiceModel.Description;
namespace ExpressionSerialization
{
public class WebHttpClient<TChannel> where TChannel : IQueryService
{
HashSet<Type> _knownTypes;
public IEnumerable<Type> knownTypes { get { return _knownTypes.AsEnumerable(); } }
public Uri baseAddress { get; private set; }
public WebHttpClient(Uri baseAddress, IEnumerable<Type> @knownTypes = null)
{
this.baseAddress = baseAddress;
if (@knownTypes == null)
this._knownTypes = new HashSet<Type>(GetServiceKnownTypes(typeof(TChannel)));
else
this._knownTypes = new HashSet<Type>(GetServiceKnownTypes(typeof(TChannel)).Union(@knownTypes));
}
public TResult SynchronousCall<TResult>(Expression<Func<TChannel, object>> methodcall)
{
return (TResult)this.SynchronousCall(methodcall: methodcall, returnType: typeof(TResult));
}
/// <summary>
/// Specifying the returnType is necessary because sometimes DataContractSerializer cannot deserialize the response
/// without knowing the exact Type of the response.
/// Sometimes DCS fails to deserialize, sometimes it doesn't, but the best practice is to always specify the expected return Type.
///
/// If calling from SL, this call must be made from a thread separate from the main UI thread. For example,
/// enclose this call within a call to ThreadPool.QueueUserWorkItem.
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="methodcall">Lambda Expression that is the call to a method on the WebHttp service.</param>
/// <param name="returnType">expected Type returned in the response</param>
/// <returns></returns>
//public object SynchronousCall<TResult>(Expression<Func<TChannel, TResult>> methodcall, Type returnType = null)
public object SynchronousCall(Expression<Func<TChannel, object>> methodcall, Type returnType)
{
object result = null;
Stream stream = null;
MethodCallExpression m = (System.Linq.Expressions.MethodCallExpression)methodcall.Body;
Type channelType = m.Object.Type;
bool same = returnType == m.Method.ReturnType;
IEnumerable<Type> baseTypes = Resolver.GetBaseTypes(returnType);
foreach (var b in baseTypes)
this._knownTypes.Add(b);
dynamic parameters = GetParameters(m);
string method;
IOperationBehavior webattribute;
OperationContractAttribute operationcontract;
WebMessageFormat requestformat, responseformat;
Uri endpoint = GetOperationInfo(m.Method, baseAddress, out method, out webattribute, out operationcontract, out requestformat, out responseformat);
ManualResetEvent reset = new ManualResetEvent(false);
Action<Stream> completedHandler = (s) =>
{
stream = s;
result = Deserialize(returnType, stream, responseformat);
reset.Set();
};
CreateHttpWebRequest(endpoint, instance: parameters,
callback: completedHandler,
method: method,
requestFormat: requestformat,
responseFormat: responseformat);
reset.WaitOne();
return result;
//TChannel service = default(TChannel);
//return methodcall.Compile().Invoke(service);
}
void CreateHttpWebRequest(Uri absoluteUri,
object instance,
Action<Stream> callback,
string method = "POST",
WebMessageFormat requestFormat = WebMessageFormat.Xml,
WebMessageFormat responseFormat = WebMessageFormat.Xml)
{
Stream postStream;
HttpWebRequest request;
HttpWebResponse response;
#if SILVERLIGHT
request = WebRequest.CreateHttp(absoluteUri);
#else
request = WebRequest.Create(absoluteUri) as HttpWebRequest;
#endif
request.Method = method;
AsyncCallback responseCallback = (ar2) =>
{
HttpWebRequest request2 = (HttpWebRequest)ar2.AsyncState;
response = (HttpWebResponse)request2.EndGetResponse(ar2);
Stream stream = response.GetResponseStream();
callback(stream);
//stream.Position = 0;//NotSupportedException: Specified method is not supported.
};
if (method == "POST" && instance != null)
{
request.ContentType = requestFormat == WebMessageFormat.Json ? "application/json" : "application/xml";
AsyncCallback requestCallback = (ar1) =>
{
postStream = request.EndGetRequestStream(ar1);
Serialize(postStream, instance, requestFormat);
postStream.Close();
request.BeginGetResponse(responseCallback, request);//GetResponse
};
request.BeginGetRequestStream(requestCallback, request);
}
else if (method == "GET")
{
request.ContentLength = 0;
request.BeginGetResponse(responseCallback, request);
}
}
#region serialization
long Serialize(Stream stream, object instance, WebMessageFormat requestFormat)
{
dynamic serializer;//DataContractJsonSerializer or DataContractSerializer (XmlObjectSerializer d.n.e. in SL)
Type elementType = instance.GetType();
this._knownTypes.Add(elementType);
switch (requestFormat)
{
case WebMessageFormat.Json:
serializer = new DataContractJsonSerializer(elementType, _knownTypes);
break;
case WebMessageFormat.Xml:
serializer = new DataContractSerializer(elementType, _knownTypes);
break;
default:
serializer = new DataContractSerializer(elementType, _knownTypes);
break;
}
serializer.WriteObject(stream, instance);
return 0;//return stream.Length;
}
object Deserialize(Type type, Stream stream, WebMessageFormat responseformat = WebMessageFormat.Json)
{
dynamic serializer;
this._knownTypes.Add(type);
switch (responseformat)
{
case WebMessageFormat.Json:
serializer = new DataContractJsonSerializer(type, this._knownTypes);
break;
case WebMessageFormat.Xml:
serializer = new DataContractSerializer(type, this._knownTypes);
break;
default:
serializer = new DataContractJsonSerializer(type, this._knownTypes);
break;
}
return serializer.ReadObject(stream);
}
T Deserialize<T>(Stream stream, WebMessageFormat responseformat = WebMessageFormat.Json)
{
return (T)Deserialize(typeof(T), stream, responseformat);
}
#endregion
static dynamic GetParameters(MethodCallExpression m)
{
if (m.Arguments.Count == 0)
return null;
Expression argexp = m.Arguments[0];
var evald = (ConstantExpression)Evaluator.PartialEval(argexp);
LambdaExpression lambda = Expression.Lambda(evald);
dynamic args = lambda.Compile().DynamicInvoke(new object[0]);
return args;
}
static Uri GetOperationInfo(MethodInfo operation,
Uri baseAddress,
out string method,
out IOperationBehavior webbehavior,//out WebInvokeAttribute webinvoke,
out OperationContractAttribute operationcontract,
out WebMessageFormat requestformat,
out WebMessageFormat responseformat)
{
object[] customAttributes = operation.GetCustomAttributes(false);
webbehavior = customAttributes.Single(a => a is WebInvokeAttribute || a is WebGetAttribute) as IOperationBehavior;
operationcontract = customAttributes.Single(a => a is OperationContractAttribute) as OperationContractAttribute;
if (webbehavior is WebInvokeAttribute)
{
requestformat = ((WebInvokeAttribute)webbehavior).RequestFormat;
responseformat = ((WebInvokeAttribute)webbehavior).ResponseFormat;
Uri relative = new Uri(((WebInvokeAttribute)webbehavior).UriTemplate, UriKind.Relative);
Uri endpoint = new Uri(baseAddress, relative);
method = ((WebInvokeAttribute)webbehavior).Method;
return endpoint;
}
else if (webbehavior is WebGetAttribute)
{
requestformat = ((WebGetAttribute)webbehavior).RequestFormat;
responseformat = ((WebGetAttribute)webbehavior).ResponseFormat;
Uri relative = new Uri(((WebGetAttribute)webbehavior).UriTemplate, UriKind.Relative);
Uri endpoint = new Uri(baseAddress, relative);
method = "GET";
return endpoint;
}
else
throw new NotSupportedException(webbehavior.GetType().FullName + " is not supported.");
}
static IEnumerable<Type> GetServiceKnownTypes(Type service)
{
HashSet<Type> knownTypes = new HashSet<Type>();
object[] customattributes = service.GetCustomAttributes(true);
IEnumerable<ServiceKnownTypeAttribute> kattrs = customattributes.OfType<ServiceKnownTypeAttribute>();
foreach (var k in kattrs)
knownTypes.Add(k.Type);
MethodInfo[] methods = service.GetMethods();
foreach (var m in methods)
{
foreach (var k in m.GetCustomAttributes(true).OfType<ServiceKnownTypeAttribute>())
knownTypes.Add(k.Type);
}
return knownTypes;
}
}
} |
using System;
using SFA.DAS.Authorization.ModelBinding;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.ProviderCommitments.Web.Extensions;
namespace SFA.DAS.ProviderCommitments.Web.Models
{
public class CreateCohortWithDraftApprenticeshipRequest : BaseCreateCohortWithDraftApprenticeshipRequest, IAuthorizationContextModel
{
public long AccountLegalEntityId { get; set; }
}
public class BaseCreateCohortWithDraftApprenticeshipRequest
{
public Guid CacheKey { get; set; }
public long ProviderId { get; set; }
public Guid? ReservationId { get; set; }
public string EmployerAccountLegalEntityPublicHashedId { get; set; }
public string StartMonthYear { get; set; }
public string CourseCode { get; set; }
public DeliveryModel? DeliveryModel { get; set; }
public bool? IsOnFlexiPaymentPilot { get; set; }
public BaseCreateCohortWithDraftApprenticeshipRequest CloneBaseValues()
{
return this.ExplicitClone();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 校园卡管理系统
{
public partial class Form32 : Form
{
public static string account;
public static string str;
public Form32()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
str = textBox1.Text;
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source= GATEWAY-PC;Initial Catalog=xiaoyuanka;User ID=sa;Password=niit#1234";
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from recharge ", connection);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter);
DataSet ds = new DataSet("recharge");
adapter.Fill(ds, "recharge");
//adapter.Fill(ds, "student");
DataRow row = ds.Tables["recharge"].NewRow();
row["account"] = account;
row["amount"] = textBox1.Text;
row["time"] = Convert.ToInt32(textBox2.Text);
ds.Tables["recharge"].Rows.Add(row);
adapter.Update(ds, "recharge");
connection.Close();
using (SqlConnection conn = new SqlConnection(@"Data Source= GATEWAY-PC;Initial Catalog=xiaoyuanka;User ID=sa;Password=niit#1234"))
{
conn.Open();//连接数据库
using (SqlCommand cmd = conn.CreateCommand())
{
SqlParameter sq;
cmd.CommandText = "select * from teacher where account='" + account + "'";
sq = cmd.Parameters.Add(account, SqlDbType.VarChar);
sq.Value =Form32.account;
//查找数据库里是否有该用户名
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
if (@account == reader[0].ToString().Trim())
{
if (reader[6].ToString().Trim() == "挂失")
{
MessageBox.Show("已挂失!");
return;
}
int yue = reader.GetInt32(reader.GetOrdinal("balance"));
int cfe = Int32.Parse(Form32.str);
int bookresultnum = yue + cfe;
cmd.CommandText = "update teacher set balance =" + bookresultnum + " where account='" + account + "'";
reader.Close();
cmd.ExecuteNonQuery();
MessageBox.Show("充值成功!");
this.Close();
}
}
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using Alabo.Domains.Entities;
using Alabo.Framework.Basic.Letters.Domain.Enums;
using Alabo.Users.Entities;
using Alabo.Validations;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Framework.Basic.Letters.Domain.Entities {
/// <summary>
/// 站内信
/// </summary>
[BsonIgnoreExtraElements]
[Table("Attach_Letter")]
[ClassProperty(Name = "站内信")]
public class Letter : AggregateMongodbUserRoot<Letter> {
/// <summary>
/// 消息标题
/// </summary>
[Display(Name = "消息标题")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public string Title { get; set; }
/// <summary>
/// 消息内容
/// </summary>
[Display(Name = "消息内容")]
[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)]
public string Content { get; set; }
/// <summary>
/// 消息类型
/// </summary>
[Display(Name = "消息类型")]
public LetterType Type { get; set; }
/// <summary>
/// 发送方式
/// </summary>
[Display(Name = "发送方式")]
public SendType Send { get; set; }
/// <summary>
/// 发件人用户ID
/// </summary>
[Display(Name = "发件人用户ID")]
public long SenderUserId { get; set; }
/// <summary>
/// 收件人用户ID
/// </summary>
[Display(Name = "收件人用户ID")]
public long ReceiverUserId { get; set; }
/// <summary>
/// 是否可回复
/// </summary>
[Display(Name = "是否可回复")]
public bool IsCanReply { get; set; } = false;
/// <summary>
/// 是否回复
/// </summary>
[Display(Name = "是否回复")]
public bool IsReply { get; set; } = false;
/// <summary>
/// 是否已读
/// </summary>
[Display(Name = "是否已读")]
public bool IsRead { get; set; } = false;
/// <summary>
/// 发件人
/// </summary>
[Display(Name = "发件人")]
[BsonIgnore]
public User SenderUser { get; set; }
/// <summary>
/// 收件人
/// </summary>
[Display(Name = "收件人")]
[BsonIgnore]
public User ReceiverUser { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
//Napisz algorytm sprawdzający czy dany ciąg jest niemalejący.
//Zrób dwie wersje algorytmu dla tablicy i dla listy.
// Oblicz czas wykonania używając klasy Stopwatch.
// Porównaj wyniki dla plików testowych.
class Program
{
// Algorytm jest bardzo podobny do wyszukiwania liniowego z wykładu
// Warunek stopu jest spełniony bo liczba kroków jest co najwyżej n-1
// poniważ pętla for jest regularna a indeks nie zmienia się wewnątrz pętli
static bool CzyNiemalejacy(int[] tab)
{
for (int i = 0; i < tab.Length - 1; i++)
{
if (tab[i + 1] < tab[i])
{
return false;
}
}
return true;
}
static bool CzyNiemalejacy(List<int> tab)
{
for (int i = 0; i < tab.Count - 1; i++)
{
if (tab[i + 1] < tab[i])
{
return false;
}
}
return true;
}
static void Main(string[] args)
{
int[] tab1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] tab2 = { 1, 2, 1, 3, 4, 5, 6, 7 };
Console.WriteLine(CzyNiemalejacy(tab1));
Console.WriteLine(CzyNiemalejacy(tab2));
// UWAGA
// Pliki A1.txt, A2.txt, A3.txt i A4.txt należy wkopiować bezpośrednio do katalogu Debug
// albo samemu zmodyfikować ścieżki
int[] tab3 = new int[10000000];
StreamReader sr = new StreamReader("A4.txt");
string line;
int idx = 0;
while ((line = sr.ReadLine()) != null)
{
tab3[idx++] = Convert.ToInt32(line);
}
sr.Close();
Stopwatch st = new Stopwatch();
st.Start();
bool wynik = CzyNiemalejacy(tab3);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("tablica " + tab3.Length + " elementów a tików " + st.ElapsedTicks);
int[] tab4 = new int[10000000];
sr = new StreamReader("A3.txt");
idx = 0;
while ((line = sr.ReadLine()) != null)
{
tab4[idx++] = Convert.ToInt32(line);
}
sr.Close();
st.Reset();
st.Start();
wynik = CzyNiemalejacy(tab4);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("tablica " + tab4.Length + " elementów a tików " + st.ElapsedTicks);
int[] tab5 = new int[1000000];
sr = new StreamReader("A2.txt");
idx = 0;
while ((line = sr.ReadLine()) != null)
{
tab5[idx++] = Convert.ToInt32(line);
}
sr.Close();
st.Reset();
st.Start();
wynik = CzyNiemalejacy(tab5);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("tablica " + tab5.Length + " elementów a tików " + st.ElapsedTicks);
int[] tab6 = new int[100000];
sr = new StreamReader("A1.txt");
idx = 0;
while ((line = sr.ReadLine()) != null)
{
tab6[idx++] = Convert.ToInt32(line);
}
sr.Close();
st.Reset();
st.Start();
wynik = CzyNiemalejacy(tab6);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("tablica " + tab6.Length + " elementów a tików " + st.ElapsedTicks);
// WNIOSKI
// ALgorytm wyraznie ma złożoność obliczeniową liniową - proporcjonalną do n
// Zadanie 10 razy większe wymaga 10 razy więcej tików
Console.WriteLine();
// teraz jak działa na liście
List<int> l3 = new List<int>();
foreach (int item in tab3)
{
l3.Add(item);
}
st.Reset();
st.Start();
wynik = CzyNiemalejacy(l3);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("lista " + l3.Count + " elementów a tików " + st.ElapsedTicks);
List<int> l5 = new List<int>();
foreach (int item in tab5)
{
l5.Add(item);
}
st.Reset();
st.Start();
wynik = CzyNiemalejacy(l5);
st.Stop();
Console.WriteLine(wynik);
Console.WriteLine("lista " + l5.Count + " elementów a tików " + st.ElapsedTicks);
List<int> l6 = new List<int>();
foreach (int item in tab6)
{
l6.Add(item);
}
st.Reset();
st.Start();
Console.WriteLine(CzyNiemalejacy(l6));
st.Stop();
Console.WriteLine("lista " + l6.Count + " elementów a tików " + st.ElapsedTicks);
// WNIOSKI
// ALgorytm na liscie ma złożoność obliczeniową liniową
// jednakże działa ponad 2 razy wolniej
Console.ReadKey();
}
}
|
using UnityEngine;
namespace FLFlight
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(ShipPhysics))]
[RequireComponent(typeof(ShipInput))]
public class Ship : MonoBehaviour
{
[Tooltip("Set this ship to be the player ship. The player ship can always be accessed through the PlayerShip property.")]
[SerializeField] private bool isPlayer = false;
public static Ship PlayerShip { get; private set; }
public Vector3 Velocity { get { return Physics.Rigidbody.velocity; } }
public ShipInput Input { get; private set; }
public ShipPhysics Physics { get; internal set; }
private void Awake()
{
Input = GetComponent<ShipInput>();
Physics = GetComponent<ShipPhysics>();
}
private void Update()
{
/////////
// Pass the input to the physics to move the ship.
Physics.SetPhysicsInput(new Vector3(Input.Strafe, 0.0f, Input.Throttle), new Vector3(Input.Pitch, Input.Yaw, Input.Roll));
if (isPlayer)
PlayerShip = this;
}
}
}
|
namespace JunimoIntelliBox.Plans
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewValley;
using StardewValley.Buildings;
using StardewValley.Objects;
using System;
using System.Collections.Generic;
public abstract class AbstractMilkingShearingLikePlan: IPlan
{
protected FarmAnimal animal;
protected Building building;
protected List<KeyValuePair<Vector2, Chest>> chests;
protected IMonitor monitor;
public AbstractMilkingShearingLikePlan(IMonitor monitor, FarmAnimal animal, Building building, List<KeyValuePair<Vector2, Chest>> chests)
{
this.animal = animal;
this.building = building;
this.chests = chests;
this.monitor = monitor;
}
public PlanExecutionResult Execute()
{
Item itemCopy = this.CreateItem();
if (itemCopy == null)
{
return PlanExecutionResult.FAILED;
}
Chest chest = this.FindAcceptableChest(itemCopy);
if (chest == null)
{
// Cannot find a chest to hold this item. Execution failed.
return PlanExecutionResult.FAILED;
}
this.RemoveProduct();
this.PlayerGainExperience();
this.AddToChest(chest, itemCopy);
this.OnExecutionSuccessful(itemCopy);
return PlanExecutionResult.SUCCESS;
}
protected abstract void OnExecutionSuccessful(Item itemCopy);
private Item CreateItem()
{
if (this.animal.currentProduce <= 0 || this.animal.age < (int)this.animal.ageWhenMature)
{
return null;
}
StardewValley.Object @object = new StardewValley.Object(Vector2.Zero, this.animal.currentProduce, (string)null, false, true, false, false);
@object.quality.Set(this.animal.produceQuality);
return @object;
}
private Chest FindAcceptableChest(Item animalProduct)
{
for (int i = 0; i < this.chests.Count; i++)
{
KeyValuePair<Vector2, Chest> pair = this.chests[i];
Chest chest = pair.Value;
if (JunimoIntelliBox.Utility.DoesChestHaveRoomForItem(chest, animalProduct))
{
return chest;
}
}
return null;
}
private void RemoveProduct()
{
this.animal.friendshipTowardFarmer.Set(Math.Min(1000, this.animal.friendshipTowardFarmer + 5));
this.animal.currentProduce.Set(-1);
if (this.animal.showDifferentTextureWhenReadyForHarvest)
{
this.animal.sprite.Value.LoadTexture("Animals\\Sheared" + this.animal.type);
}
}
private void AddToChest(Chest chest, Item animalProduct)
{
chest.addItem(animalProduct);
}
private void PlayerGainExperience()
{
Game1.player.gainExperience(0, 5);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OnlineShopping.Models;
namespace OnlineShopping.Controllers
{
public class UserProductController : ApiController
{
private DbproonlineshoppingEntities db = new DbproonlineshoppingEntities();
#region SortFilterSearch
[HttpPost]
public IHttpActionResult GetUserProducts(FilterViewModel filterViewModel)
{
try
{
var products = db.Products.Select(s => new ProductModel()
{
Brand = s.Brand,
ProductDescription = s.ProductDescription,
ProductCode = s.ProductCode,
ProductName = s.ProductName,
CreatedDate = s.CreatedDate,
Quantity = s.Quantity,
ProductID = s.ProductID,
ProductPrice = s.ProductPrice,
CategoryName = s.Category.CategoryName,
ModifiedBy = s.ModifiedBy,
CategoryID = s.CategoryID,
ModifiedDate = s.ModifiedDate,
InStock = s.InStock,
Image = s.Images.Where(w => w.ProductID == s.ProductID).Select(t => t.ProductImage).FirstOrDefault()
}).AsQueryable();
if (filterViewModel.Search != "")
{
products = products.Where(w => w.ProductName.Contains(filterViewModel.Search) || w.ProductDescription.Contains(filterViewModel.Search)).AsQueryable();
}
if (filterViewModel.MinPrice != 0 && filterViewModel.MaxPrice != 0)
{
products = products.Where(w => w.ProductPrice > filterViewModel.MinPrice && w.ProductPrice <= filterViewModel.MaxPrice).AsQueryable();
}
if (filterViewModel.SortBy == "asc" || filterViewModel.SortBy == "")
return Ok(products.OrderBy(o => o.ProductName).ToList());
else
return Ok(products.OrderByDescending(o => o.ProductName).ToList());
}
catch(Exception e)
{
return Ok(e);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Departamento.Map;
namespace Infra.Mapeamentos
{
public class MappingDepartamento : EntityTypeConfiguration<DepartamentoMap>
{
public MappingDepartamento()
{
// Primary Key
this.HasKey(t => t.IdDepartamento);
// Properties
// Table & Column Mappings
this.ToTable("Departamentos");
this.Property(t => t.IdDepartamento).HasColumnName("IdDepartamento");
this.Property(t => t.Descricao).HasColumnName("Descricao");
this.Property(t => t.IdEmpresa).HasColumnName("IdEmpresa");
// Relationships
this.HasMany(t => t.AspNetUsers)
.WithMany(t => t.Departamentos)
.Map(m =>
{
m.ToTable("DepartamentoUsuario");
m.MapLeftKey("IdDepartamento");
m.MapRightKey("UserId");
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SelectionCommittee.BLL.DataTransferObject;
using SelectionCommittee.BLL.Interfaces;
using SelectionCommittee.BLL.Services;
using SelectionCommittee.WEB.Models;
namespace SelectionCommittee.WEB.Controllers
{
[Authorize(Roles = "admin")]
public class AdminController : Controller
{
IServiceCreator _creator = new ServiceCreator("DefaultConnection");
private IFacultyService _faculty;
private ISpecialtyService _specialty;
private ISubjectService _subject;
public AdminController()
{
_faculty = _creator.CreateFacultyService();
_specialty = _creator.CreateSpecialtyService();
_subject = _creator.CreateSubjectService();
}
public ActionResult Faculties()
{
List<DisplayFaculty> faculties = new List<DisplayFaculty>();
foreach (var faculty in _faculty.GetAll())
{
faculties.Add(new DisplayFaculty
{
Id = faculty.Id,
Name = faculty.Name,
Subjects = _subject.GetSubjectsNamesEIE(faculty.FacultySubjects),
CountSpeciality = _specialty.GetByFacultyId(faculty.Id).Count()
});
}
return View(faculties);
}
[HttpGet]
public ActionResult Specialties(int facultyId)
{
ViewBag.FacultyId = facultyId;
return View(_specialty.GetByFacultyId(facultyId));
}
public ActionResult CreateFaculty()
{
CreateFaculty facultyCreate = new CreateFaculty();
facultyCreate.Subjects = _subject.GetSubjectsEIE().ToList();
return View(facultyCreate);
}
[HttpPost]
public ActionResult CreateFaculty(CreateFacultyPost createFacultyPost, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
FacultyDTO faculty = new FacultyDTO
{
Name = createFacultyPost.Name,
Description = createFacultyPost.Description,
FacultySubjects = createFacultyPost.FacultySubjects
};
if (image != null)
{
string filePath = "/Content/Image/Faculties/" + faculty.Name + Path.GetExtension(image.FileName);
image.SaveAs(Server.MapPath(filePath));
faculty.Photo = filePath;
}
_faculty.Create(faculty);
}
return RedirectToAction("Faculties");
}
public ActionResult DeleteFaculty(int facultyId)
{
if (facultyId != 0)
{
string temp = _faculty.GetById(facultyId).Photo;
if(temp!=null)
System.IO.File.Delete(Server.MapPath(temp));
_faculty.Delete(facultyId);
}
return RedirectToAction("Faculties");
}
[HttpGet]
public ActionResult EditFaculty(int facultyId)
{
var faculty = _faculty.GetById(facultyId);
var editFaculty = new EditFaculty
{
Id = faculty.Id,
Name = faculty.Name,
FacultySubjects = faculty.FacultySubjects.ToList(),
Description = faculty.Description,
Photo = faculty.Photo,
Subjects = _subject.GetSubjectsEIE().ToList()
};
return View(editFaculty);
}
[HttpPost]
public ActionResult EditFaculty(EditFaculty editFaculty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
FacultyDTO faculty= new FacultyDTO
{
Id = editFaculty.Id,
Name = editFaculty.Name,
Description = editFaculty.Description,
FacultySubjects = editFaculty.FacultySubjects
};
if (image != null)
{
string filePath = "/Content/Image/Faculties/" + faculty.Name + Path.GetExtension(image.FileName);
if (editFaculty.Photo!=null)
System.IO.File.Delete(Server.MapPath(filePath));
image.SaveAs(Server.MapPath(filePath));
faculty.Photo = filePath;
}
else faculty.Photo = editFaculty.Photo;
_faculty.Update(faculty);
}
return RedirectToAction("Faculties");
}
[HttpGet]
public ActionResult CreateSpecialty(int facultyId)
{
return View(new CreateSpecialty {FacultyId = facultyId});
}
[HttpPost]
public ActionResult CreateSpecialty(CreateSpecialty createSpecialty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
SpecialtyDTO specialty = new SpecialtyDTO
{
Number = createSpecialty.Number,
Name = createSpecialty.Name,
BudgetPlaces = createSpecialty.BudgetPlaces,
TotalPlaces = createSpecialty.TotalPlaces,
Description = createSpecialty.Description,
FacultyId = createSpecialty.FacultyId
};
if (image != null)
{
string filePath = "/Content/Image/Specialties/" + specialty.Name + Path.GetExtension(image.FileName);
image.SaveAs(Server.MapPath(filePath));
specialty.Photo = filePath;
}
_specialty.Create(specialty);
}
return View(new CreateSpecialty {FacultyId = createSpecialty.FacultyId});
}
[HttpGet]
public ActionResult EditSpecialty(int id)
{
var specialty = _specialty.GetById(id);
var editSpecialty = new EditSpecialty
{
Id = specialty.Id,
Number = specialty.Number,
Name = specialty.Name,
Description = specialty.Description,
Photo = specialty.Photo,
FacultyId = specialty.FacultyId,
BudgetPlaces = specialty.BudgetPlaces,
TotalPlaces = specialty.TotalPlaces
};
return View(editSpecialty);
}
[HttpPost]
public ActionResult EditSpecialty(EditSpecialty editSpecialty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
SpecialtyDTO specialty = new SpecialtyDTO
{
Id = editSpecialty.Id,
Number = editSpecialty.Number,
Name = editSpecialty.Name,
Description = editSpecialty.Description,
FacultyId = editSpecialty.FacultyId,
BudgetPlaces = editSpecialty.BudgetPlaces,
TotalPlaces = editSpecialty.TotalPlaces
};
if (image != null)
{
string filePath = "/Content/Image/Specialties/" + specialty.Name + Path.GetExtension(image.FileName);
if (editSpecialty.Photo!=null)
System.IO.File.Delete(Server.MapPath(filePath));
image.SaveAs(Server.MapPath(filePath));
specialty.Photo = filePath;
}
else specialty.Photo = editSpecialty.Photo;
_specialty.Update(specialty);
}
return RedirectToAction("Specialties",new {facultyId = editSpecialty.FacultyId});
}
public ActionResult DeleteSpecialty(int id, int facultyId)
{
if (id != 0)
{
string temp = _specialty.GetById(id).Photo;
if (temp != null)
System.IO.File.Delete(Server.MapPath(temp));
_specialty.Delete(id);
}
return RedirectToAction("Specialties", new { facultyId = facultyId});
}
}
} |
using System.Threading;
using System.Web;
namespace Docller.Core.Common
{
public interface IClientConnection
{
bool IsClientConnected { get; }
void TransmitFile(string fileName);
CancellationToken ClientCancellationToken { get; }
}
class NullClientConnection : IClientConnection
{
public bool IsClientConnected { get { return true; } }
public void TransmitFile(string fileName)
{
//
}
public CancellationToken ClientCancellationToken { get { return new CancellationToken(); } }
}
public class ClientConnection : IClientConnection
{
private readonly HttpResponseBase _response;
public ClientConnection(HttpResponseBase response)
{
_response = response;
}
public bool IsClientConnected
{
get { return _response.IsClientConnected; }
}
public void TransmitFile(string fileName)
{
_response.TransmitFile(fileName);
}
public CancellationToken ClientCancellationToken
{
get { return this._response.ClientDisconnectedToken; }
}
}
} |
using SocketLite.Forms;
using SocketLite.Net;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SocketLite.Server
{
public partial class MainForm : ServerForm
{
NotifyIcon notifyIcon1 = new NotifyIcon();
private static Dictionary<string, TcpClient> clients = new Dictionary<string, TcpClient>();
private AsyncTcpServer tcpServer;
private AsyncContext context;
public MainForm()
{
InitializeComponent();
notifyIcon1.Text = Text;
notifyIcon1.Icon = Icon;
notifyIcon1.DoubleClick += OnNotifyIconDoubleClicked;
SizeChanged += OnSizeChanged;
ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false);
WindowState = FormWindowState.Normal;
context = new AsyncContext(new RichTextBoxLogger(rtbLog, true));
context.Logger.Clear();
}
#region NotifyIcon
void OnSizeChanged(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
notifyIcon1.Visible = true;
Visible = false;
}
}
void OnNotifyIconDoubleClicked(object sender, EventArgs e)
{
Visible = true;
notifyIcon1.Visible = false;
WindowState = FormWindowState.Normal;
}
void OnProgramStarted(object state, bool timeout)
{
notifyIcon1.ShowBalloonTip(2000, "您好", "我在这呢!", ToolTipIcon.Info);
Show();
WindowState = FormWindowState.Normal;
}
#endregion
#region FormEvents
private void MainForm_Load(object sender, EventArgs e)
{
SetButtonEnabled(false);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
var dialog = MessageBox.Show("确定关闭服务?", "确认", MessageBoxButtons.OKCancel);
if (dialog == DialogResult.OK)
{
StopServer();
}
e.Cancel = dialog == DialogResult.Cancel;
}
#endregion
#region TcpServerEvents
private void TcpServer_ClientConnected(object sender, TcpClientConnectedEventArgs e)
{
context.Logger.WriteLog("{0}已连接!", e.TcpClient.Client.RemoteEndPoint);
}
private void TcpServer_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
{
context.Logger.WriteLog("{0}已断开连接!", e.TcpClient.Client.RemoteEndPoint);
}
private void TcpServer_DatagramReceived(object sender, TcpDatagramReceivedEventArgs<byte[]> e)
{
if (e.Datagram != null && e.Datagram.Length > 0)
{
try
{
var message = Encoding.UTF8.GetString(e.Datagram);
var request = Utils.Deserialize<RequestInfo>(message);
if (request.Handler == "Connect")
{
tcpServer.Send(e.TcpClient, request, "连接成功!");
return;
}
var logger = new TcpServerLogger(rtbLog, request, tcpServer, e.TcpClient);
var ctxRequest = new RequestContext(logger);
ctxRequest.Request = request;
Utils.ExecuteAsync(ctxRequest, e1 =>
{
var ctx = e1.Argument as RequestContext;
if (ctx == null)
return;
var handler = RequestHandler.GetHandler(ctx);
if (handler == null)
{
ctx.Logger.WriteLog("不支持{0}的处理者!", ctx.Request.Handler);
return;
}
e1.Result = handler.Execute();
},
e2 =>
{
if (e2.Result != null)
tcpServer.Send(e.TcpClient, Utils.Serialize(e2.Result));
});
}
catch (Exception ex)
{
context.Logger.WriteLog("{0}接收异常,{1}", e.TcpClient.Client.RemoteEndPoint, ex.Message);
}
}
Application.DoEvents();
}
#endregion
#region ButtonEvents
private void BtnStart_Click(object sender, EventArgs e)
{
try
{
if (tcpServer == null)
{
tcpServer = new AsyncTcpServer(ConfigHelper.AppSettings<int>("ServerPort"));
tcpServer.Encoding = Encoding.UTF8;
tcpServer.ClientConnected += TcpServer_ClientConnected;
tcpServer.ClientDisconnected += TcpServer_ClientDisconnected;
tcpServer.DatagramReceived += TcpServer_DatagramReceived;
}
tcpServer.Start();
context.Logger.WriteLog("服务已启动!");
SetButtonEnabled(true);
}
catch (Exception ex)
{
context.Logger.WriteLog("服务启动失败:" + ex.ToString());
}
}
private void BtnStop_Click(object sender, EventArgs e)
{
StopServer();
context.Logger.WriteLog("服务已停止!");
SetButtonEnabled(false);
}
private void BtnClear_Click(object sender, EventArgs e)
{
context.Logger.Clear();
}
#endregion
#region Private
private void SetButtonEnabled(bool started)
{
btnStart.Enabled = !started;
btnStop.Enabled = started;
}
private void StopServer()
{
if (tcpServer != null)
tcpServer.Stop();
}
#endregion
}
}
|
using Terraria;
using Terraria.ModLoader;
namespace StarlightRiver.Buffs
{
public class MossRegen : ModBuff
{
public override void SetDefaults()
{
DisplayName.SetDefault("Mending Moss");
Description.SetDefault("You are being healed!");
}
public override void Update(Player player, ref int buffIndex)
{
player.lifeRegen += 10;
}
}
}
|
using Common.Data;
using Common.Exceptions;
using Common.Extensions;
using Common.Log;
using Contracts.Conforming;
using Entity;
using LFP.Common.DataAccess;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel;
namespace Services.Conforming
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession)]
public class ConformingService : IConformingService
{
#region Private Fields
private string mConnectionString = String.Empty;
private DataAccess mDataAccess = null;
private string mUserName = String.Empty;
#endregion
#region Constructors
public ConformingService()
{
Logging.MinimumLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), ConfigurationManager.AppSettings["LogLevel"]);
}
#endregion
#region Public Methods
public bool AddAirMasterRecord(TrackB data)
{
TrackB b = new TrackB();
try
{
return b.AddUpdateRecord(mConnectionString, data, true);
}
finally
{
b = null;
}
}
public bool AddAMHistory(TrackBHistory data)
{
TrackBHistory history = new TrackBHistory();
try
{
return history.AddAMHistory(mConnectionString, data);
}
finally
{
history = null;
}
}
public bool AddConformingHistory(MovieConformHistory data)
{
MovieConformHistory history = new MovieConformHistory();
try
{
return history.AddRecord(mConnectionString, data);
}
finally
{
history = null;
}
}
public bool AddConformingStructureHistory(ConformingStructureHistoryQC data)
{
ConformingStructureHistoryQC qc = new ConformingStructureHistoryQC();
try
{
return qc.AddRecord(mConnectionString, data);
}
finally
{
qc = null;
}
}
public bool AddConformingStructureNotesHistory(ConformingStructureHistoryNotes data)
{
ConformingStructureHistoryNotes notes = new ConformingStructureHistoryNotes();
try
{
return notes.AddRecord(mConnectionString, data);
}
finally
{
notes = null;
}
}
public bool AddConformingStructureRuntimeHistory(ConformingStructureHistoryRuntimes data)
{
ConformingStructureHistoryRuntimes runtimes = new ConformingStructureHistoryRuntimes();
try
{
return runtimes.AddRecord(mConnectionString, data);
}
finally
{
runtimes = null;
}
}
public bool AddFCPHistory(TrackSHistory data)
{
TrackSHistory history = new TrackSHistory();
try
{
return history.AddRecord(mConnectionString, data);
}
finally
{
history = null;
}
}
public bool AddProjectCompleteHistory(ConformingProjectCompleteHistory data)
{
ConformingProjectCompleteHistory cpch = new ConformingProjectCompleteHistory();
try
{
return cpch.AddRecord(mConnectionString, data);
}
finally
{
cpch = null;
}
}
public bool AddProjectCompleteNotesHistory(ConformingProjectCompleteHistoryNotes data)
{
ConformingProjectCompleteHistoryNotes notes = new ConformingProjectCompleteHistoryNotes();
try
{
return notes.AddRecord(mConnectionString, data);
}
finally
{
notes = null;
}
}
public bool AddUpdateConformFeatures(MovieConformFeatures data, bool isNew)
{
MovieConformFeatures mcf = new MovieConformFeatures();
try
{
return mcf.AddUpdateRecord(mConnectionString, isNew, data);
}
finally
{
mcf = null;
}
}
public bool AddUpdateConformingNotes(int id, string userName, string notes)
{
bool result = true;
MovieConformNotes mcn = new MovieConformNotes();
MovieConformNotesHistory mcnh = new MovieConformNotesHistory();
try
{
MovieConformNotes data = mcn.Exists(mConnectionString, id);
bool isNew = false;
if (data == null)
{
isNew = true;
data = new MovieConformNotes();
data.ID = id;
}
data.Create_Date = DateTime.Now;
data.Username = userName;
data.Notes = notes;
result &= mcn.AddUpdateRecord(mConnectionString, data, isNew);
MovieConformNotesHistory history = new MovieConformNotesHistory();
history.ID = id;
history.Create_Date = DateTime.Now;
history.Username = userName;
history.Notes = notes;
result &= mcnh.AddRecord(mConnectionString, history);
}
finally
{
mcnh = null;
mcn = null;
}
return result;
}
public bool AddUpdateConformingOrderNum(ConformingLoadOrderNum data, bool isNew)
{
ConformingLoadOrderNum order = new ConformingLoadOrderNum();
try
{
return order.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
order = null;
}
}
public bool AddUpdateConformingRecord(MovieConform data, bool isNew)
{
MovieConform conform = new MovieConform();
try
{
return conform.AddUpdate(mConnectionString, data, isNew);
}
finally
{
conform = null;
}
}
public bool AddUpdateConformingStructure(ConformingStructure data, bool isNew)
{
ConformingStructure cs = new ConformingStructure();
try
{
return cs.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
cs = null;
}
}
public bool AddUpdateFCPRecord(TrackS data, bool isNew)
{
TrackS s = new TrackS();
try
{
return s.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
s = null;
}
}
public bool AddUpdateMSRecord(TrafficInternet data, bool isNew)
{
TrafficInternet ti = new TrafficInternet();
try
{
return ti.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
ti = null;
}
}
public bool AddUpdateMSRecordById(int id, string userName)
{
TrafficInternet ti = new TrafficInternet();
try
{
return ti.AddUpdateRecord(mConnectionString, id, userName);
}
finally
{
ti = null;
}
}
public bool AddUpdateProjectComplete(ConformingProjectComplete data, bool isNew)
{
ConformingProjectComplete cpc = new ConformingProjectComplete();
try
{
return cpc.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
cpc = null;
}
}
public bool AddUpdateReportRecord(ConformingEmployeeStatsRport data, bool isNew)
{
ConformingEmployeeStatsRport rpt = new ConformingEmployeeStatsRport();
try
{
return rpt.AddUpdateRecord(mConnectionString, data, isNew);
}
finally
{
rpt = null;
}
}
public bool CanFrameSizeBeSelected(string format)
{
SystemConformingFileFormat2 format2 = new SystemConformingFileFormat2();
try
{
return format2.CanFrameSizeBeSelected(mConnectionString, format);
}
finally
{
format2 = null;
}
}
public bool CheckProjectComplete(int id)
{
ConformingProjectComplete complete = new ConformingProjectComplete();
try
{
return complete.CheckProjectCompleted(mConnectionString, id);
}
finally
{
complete = null;
}
}
public void CreateConformingMethods(string connectionString, string userName)
{
mConnectionString = connectionString;
mUserName = userName;
mDataAccess = new DataAccess(connectionString, userName, Logging.MinimumLogLevel);
}
public bool DeleteReportRecord(int id)
{
ConformingEmployeeStatsRport rpt = new ConformingEmployeeStatsRport();
try
{
return rpt.DeleteRecord(mConnectionString, id);
}
finally
{
rpt = null;
}
}
public TrackB GetAirMaster(int id)
{
TrackB b = new TrackB();
try
{
return b.GetAirMaster(mConnectionString, id);
}
finally
{
b = null;
}
}
public string GetAirMasterLocation(int id)
{
TrackB b = new TrackB();
try
{
return b.GetAirMasterLocation(mConnectionString, id);
}
finally
{
b = null;
}
}
public Tuple<string, DateTime?> GetAirMasterQCInfo(int id)
{
TrackBQC qc = new TrackBQC();
try
{
return qc.GetAirMasterQCInfo(mConnectionString, id);
}
finally
{
qc = null;
}
}
public Tuple<string, string, int> GetAirMasterStatus(int id)
{
TrackB b = new TrackB();
try
{
return b.GetAirMasterStatusConforming(mConnectionString, id);
}
finally
{
b = null;
}
}
public int GetAltHDId(int id)
{
return mDataAccess.GetAltHDId(id);
}
public int GetAltSDId(int id)
{
return mDataAccess.GetAltSDId(id);
}
public List<string> GetAspectRatios()
{
SystemConformingAspect aspect = new SystemConformingAspect();
try
{
return aspect.GetAspects(mConnectionString);
}
finally
{
aspect = null;
}
}
public string GetAssetType(int id)
{
return mDataAccess.GetAssetType(id);
}
public string GetClipboardUserName(int id)
{
ConformingLoadIDNew clidn = new ConformingLoadIDNew();
try
{
return clidn.GetClipboardUserName(mConnectionString, id);
}
finally
{
clidn = null;
}
}
public List<Tuple<int, string, int>> GetClipInfo(int id)
{
ETCBlock etc = new ETCBlock();
try
{
return etc.GetClipInfo(mConnectionString, id);
}
finally
{
etc = null;
}
}
public DataTable GetConformedMasterRecord(int masterId)
{
MovieConform conform = new MovieConform();
try
{
return conform.GetConformedRecord(mConnectionString, masterId);
}
finally
{
conform = null;
}
}
public ConformingLoadOrderNum GetConformingLoadOrderNum(int id, string userName)
{
ConformingLoadOrderNum order = new ConformingLoadOrderNum();
try
{
return order.GetData(mConnectionString, id, userName);
}
finally
{
order = null;
}
}
public Tuple<string, string, int?, int> GetConformingMovie(int id)
{
Movie movie = new Movie();
try
{
return movie.GetConformingMovie(mConnectionString, id);
}
finally
{
movie = null;
}
}
public MovieConform GetConformingRecord(int id)
{
MovieConform conform = new MovieConform();
try
{
return conform.GetRecordForUpdate(mConnectionString, id);
}
finally
{
conform = null;
}
}
public ConformingStructure GetConformingStructure(int id)
{
ConformingStructure structure = new ConformingStructure();
try
{
return structure.GetConformingStructure(mConnectionString, id);
}
finally
{
structure = null;
}
}
public int GetCountByRatingAndType(int id, int rating, string type)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetCountByRatingAndType(mConnectionString, id, rating, type);
}
finally
{
derivative = null;
}
}
public Tuple<string, DateTime> GetDAMStatus(int id)
{
TrackB b = new TrackB();
try
{
return b.GetDAMStatus(mConnectionString, id);
}
finally
{
b = null;
}
}
public DateTime GetDelNOCDate(int id, string type)
{
int altHDId = mDataAccess.GetAltHDId(id);
if (altHDId != id && altHDId != 0)
id = altHDId;
MovieConform conform = new MovieConform();
try
{
DateTime? date = conform.GetDelNOCDate(mConnectionString, id, type);
if (date.HasValue)
return date.Value;
}
finally
{
conform = null;
}
return new DateTime(1900, 1, 1);
}
public bool GetDelCOA(int id)
{
MovieConform conform = new MovieConform();
try
{
int? value = conform.GetDelCOAValue(mConnectionString, id);
return (value.HasValue && value.Value == 1);
}
finally
{
conform = null;
}
}
public int? GetDerivativeId(int id)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetDerivativeId(mConnectionString, id);
}
finally
{
derivative = null;
}
}
public DataTable GetDerivativeNonBTS(int id, string types)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetDerivativeNonBTS(mConnectionString, id, types);
}
finally
{
derivative = null;
}
}
public List<Tuple<int, string>> GetDerivativesForUpdate(int masterId)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetClipDerivatives(mConnectionString, masterId);
}
finally
{
derivative = null;
}
}
public Tuple<DateTime, string> GetEarliestNAD(int id, int xxx)
{
VODBuilderGrid grid = new VODBuilderGrid();
try
{
return grid.GetEarliestNADConforming(mConnectionString, id, xxx);
}
finally
{
grid = null;
}
}
public string GetEditBay(int id)
{
PromotionsStatus status = new PromotionsStatus();
try
{
return status.GetEditBay(mConnectionString, id);
}
finally
{
status = null;
}
}
public List<string> GetEditBays()
{
SystemEditBay seb = new SystemEditBay();
try
{
return seb.GetEditBays(mConnectionString);
}
finally
{
seb = null;
}
}
public string GetEditor(int id)
{
//RESUME HERE in Show_Completed.
return "";
}
public string GetEditors()
{
Users users = new Users();
try
{
return "|NOT ASSIGNED|" + users.GetConformingEditors(mConnectionString);
}
finally
{
users = null;
}
}
public string GetESLocation(int id)
{
TrackC c = new TrackC();
try
{
return c.GetLocation(mConnectionString, id);
}
finally
{
c = null;
}
}
public int GetFCPFailHistoryCount(int id)
{
TrackSHistory history = new TrackSHistory();
try
{
return history.GetFailHistoryCount(mConnectionString, id);
}
finally
{
history = null;
}
}
public List<TrackSQCHistory> GetFCPHistory(int id)
{
TrackSQCHistory sqc = new TrackSQCHistory();
try
{
return sqc.GetFCPHistory(mConnectionString, id);
}
finally
{
sqc = null;
}
}
public TrackSQCHistory GetFCPHistoryRecord(int historyId)
{
TrackSQCHistory sqc = new TrackSQCHistory();
try
{
return sqc.GetFCPHistoryRecord(mConnectionString, historyId);
}
finally
{
sqc = null;
}
}
public bool GetFCPPassed(int id)
{
TrackS s = new TrackS();
try
{
return s.GetFCPPass(mConnectionString, id);
}
finally
{
s = null;
}
}
public TrackS GetFCPRecord(int id)
{
TrackS s = new TrackS();
try
{
return s.GetFCPRecord(mConnectionString, id);
}
finally
{
s = null;
}
}
public string GetFCPRuntime(int id)
{
TrackS s = new TrackS();
try
{
return s.GetFCPRuntime(mConnectionString, id, "TRT", false);
}
finally
{
s = null;
}
}
public string GetFCPStatus(int id, bool useAltId = true)
{
if (useAltId)
{
int altId = mDataAccess.GetAltHDId(id);
if (altId != 0 && altId != id)
id = altId;
}
TrackS s = new TrackS();
try
{
if (useAltId)
return s.GetStatus(mConnectionString, id);
return s.GetStatusDefault(mConnectionString, id);
}
finally
{
s = null;
}
}
public List<string> GetFileFormats()
{
SystemConformingFileFormat format = new SystemConformingFileFormat();
try
{
return format.GetFormats(mConnectionString);
}
finally
{
format = null;
}
}
public List<string> GetFrameRates()
{
SystemConformingFrameRate rate = new SystemConformingFrameRate();
try
{
return rate.GetFrameRates(mConnectionString);
}
finally
{
rate = null;
}
}
public DataTable GetGraphicsPackage(int id)
{
Movie movie = new Movie();
try
{
return movie.GetGraphicsPackage(mConnectionString, id);
}
finally
{
movie = null;
}
}
public List<string> GetHardDrive()
{
SystemHardDrive drive = new SystemHardDrive();
try
{
return drive.GetHardDrive(mConnectionString);
}
finally
{
drive = null;
}
}
public Tuple<int, int> GetHDAndSDHDId(int id)
{
Movie movie = new Movie();
try
{
return movie.GetHDAndSDHDId(mConnectionString, id);
}
finally
{
movie = null;
}
}
public DataTable GetHiddenMovies()
{
DataTable result = new DataTable();
result.Columns.Add(new DataColumn("ID", typeof(int)));
result.Columns.Add(new DataColumn("Title", typeof(string)));
result.Columns.Add(new DataColumn("Type", typeof(string)));
result.Columns.Add(new DataColumn("select", typeof(bool)));
List<int> ids = GetHiddenIds();
foreach (int id in ids)
{
Tuple<string, string> movie = GetHiddenMovie(id);
if (movie == null)
continue;
DataRow row = result.NewRow();
row["ID"] = id;
row["Title"] = movie.Item1;
row["Type"] = movie.Item2;
result.Rows.Add(row);
}
return result;
}
public List<MovieConformHistory> GetHistoryByType(int id, string dataType)
{
MovieConformHistory history = new MovieConformHistory();
try
{
return history.GetHistoryByType(mConnectionString, id, dataType);
}
finally
{
history = null;
}
}
public string GetHustler(int id)
{
Movie movie = new Movie();
try
{
return movie.GetHustler(mConnectionString, id);
}
finally
{
movie = null;
}
}
public int? GetIdByRating(int id, string rating, bool hd)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetIdByRating(mConnectionString, id, rating, hd);
}
finally
{
derivative = null;
}
}
public List<string> GetInterlace()
{
SystemInterlace interlace = new SystemInterlace();
try
{
return interlace.GetInterlace(mConnectionString);
}
finally
{
interlace = null;
}
}
public List<string> GetLanguages()
{
SystemLanguage language = new SystemLanguage();
try
{
return language.GetLanguages(mConnectionString);
}
finally
{
language = null;
}
}
public string GetLanguageAbbreviation(string language)
{
SystemLanguage system = new SystemLanguage();
try
{
return system.GetLanguageAbbreviation(mConnectionString, language);
}
finally
{
system = null;
}
}
public Tuple<int, string> GetMaster(int masterId, int xxx)
{
Movie movie = new Movie();
try
{
return movie.GetMasterByIdAndRating(mConnectionString, masterId, xxx);
}
finally
{
movie = null;
}
}
public int GetMasterId(int id)
{
return mDataAccess.GetMasterId(id);
}
public List<int> GetMasterIds(int id, bool hasGraphicsPackage)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetMasterIdsRealAssets(mConnectionString, id, hasGraphicsPackage);
}
finally
{
derivative = null;
}
}
public MovieConformFeatures GetMovieConformFeatures(int id)
{
MovieConformFeatures mcf = new MovieConformFeatures();
try
{
return mcf.GetData(mConnectionString, id);
}
finally
{
mcf = null;
}
}
public DataTable GetMovieConformingStatus(int id, int rating, string assetType, string types, bool graphicsPackage,
bool sceneComp, bool getMasters)
{
DataTable result = null;
Movie movie = new Movie();
Tuple<string, string> titles = movie.GetTitles(mConnectionString, id);
if (sceneComp)
result = GetSceneComp(id, types, graphicsPackage, sceneComp, titles);
else
{
try
{
result = movie.GetMovieByConformingStatus(mConnectionString, id, rating, assetType, types,
graphicsPackage, sceneComp, getMasters);
}
finally
{
movie = null;
}
}
return result;
}
public DataTable GetMovieConformingStatusGraphicsPackageOnly(int id)
{
Movie movie = new Movie();
try
{
return movie.GetMovieByConformingStatusGraphicsPackageOnly(mConnectionString, id);
}
finally
{
movie = null;
}
}
public MovieConformNotes GetMovieConformNotes(int id)
{
MovieConformNotes notes = new MovieConformNotes();
try
{
return notes.Exists(mConnectionString, id);
}
finally
{
notes = null;
}
}
public Tuple<int, string, int> GetMovieInfo(int id)
{
Movie movie = new Movie();
try
{
return movie.GetConformingMovieInfo(mConnectionString, id);
}
finally
{
movie = null;
}
}
public Tuple<int, string, string, int> GetMovieInfoAlt(int id)
{
Movie movie = new Movie();
try
{
return movie.GetMovieInfoAlt(mConnectionString, id);
}
finally
{
movie = null;
}
}
public Tuple<string, string, DateTime> GetMovieLanguage(int id)
{
Movie movie = new Movie();
try
{
return movie.GetMovieLanguage(mConnectionString, id);
}
finally
{
movie = null;
}
}
public Tuple<int, string> GetMovieRatingType(int id)
{
Movie movie = new Movie();
try
{
return movie.GetMovieRatingType(mConnectionString, id);
}
finally
{
movie = null;
}
}
public TrafficInternet GetMSRecord(int id)
{
TrafficInternet ti = new TrafficInternet();
try
{
return ti.GetMSRecord(mConnectionString, id);
}
finally
{
ti = null;
}
}
public string GetNAD(int id, string type)
{
string result = "";
Schedule schedule = new Schedule();
string sql = "";
try
{
if (type.Equals("Clip") || type.Equals("Wireless Clip"))
{
//select sched_date, channel from schedule join etcblock on schedule.id = etcblock.id
//where etcblock.clipid = @ID and sched_date >= @Date
//order by sched_date
sql = "P_COnforming_Main_GetNAD2_GetClip";
result = schedule.GetNAD2(mConnectionString, id, DateTime.Now, sql);
}
else if (type.Contains("Comp") || type.Equals("Movie"))
{
//select top 1 sched_date, channel from schedule where id = @ID and sched_date >= @Date1 order by sched_date
sql = "P_Staging_GetNAD2";
result = schedule.GetNAD2(mConnectionString, id, DateTime.Now, sql);
}
else
{
//select sched_date from schedule where id in(select movie.id from movie_derivative join movie on
//movie_derivative.id2 = movie.id where movie_derivative.id = @ID and type = 'movie')
//and sched_date >= @Date1 order by sched_date
sql = "P_Conforming_Main_GetEarliestNAD_GetNADMovies";
result = schedule.GetNAD(mConnectionString, id, sql);
}
}
finally
{
schedule = null;
}
return result;
}
public bool GetNADAssignedTo(int id)
{
string type = mDataAccess.GetAssetType(id);
Schedule schedule = new Schedule();
try
{
return schedule.GetNADAssignedTo(mConnectionString, id, type);
}
finally
{
schedule = null;
}
}
public string GetNotes(int id, string track)
{
string result = "";
//select notes from track_{0} where id = @ID
string sql = "P_Conforming_GetNotes_{0}";
SqlParameter parameter = new SqlParameter("@ID", id);
using (Database database = new Database(mConnectionString))
{
try
{
result = database.ExecuteSelectString(String.Format(sql, track),
parameters: new SqlParameter[] { parameter });
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameter = null;
}
}
return result;
}
public List<Tuple<string, DateTime, string>> GetNotesHistory(int id, string type)
{
ConformingStructureHistoryNotes structure = null;
ConformingProjectCompleteHistoryNotes complete = null;
try
{
switch (type)
{
case "structure":
structure = new ConformingStructureHistoryNotes();
return structure.GetNotesHistory(mConnectionString, id);
case "complete":
complete = new ConformingProjectCompleteHistoryNotes();
return complete.GetNotesHistory(mConnectionString, id);
}
}
finally
{
complete = null;
structure = null;
}
return null;
}
public ConformingProjectComplete GetProjectComplete(int id)
{
ConformingProjectComplete project = new ConformingProjectComplete();
try
{
return project.GetRecordByMasterId(mConnectionString, id);
}
finally
{
project = null;
}
}
public int GetRating(int id)
{
Movie movie = new Movie();
try
{
return movie.GetRating(mConnectionString, id);
}
finally
{
movie = null;
}
}
public ConformingEmployeeStatsRport GetReportRecord(int id)
{
ConformingEmployeeStatsRport rpt = new ConformingEmployeeStatsRport();
try
{
return rpt.Exists(mConnectionString, id);
}
finally
{
rpt = null;
}
}
public List<string> GetResolutions()
{
SystemConformingFileFormat2 format = new SystemConformingFileFormat2();
try
{
return format.GetFormats(mConnectionString);
}
finally
{
format = null;
}
}
public DataTable GetSAFQC(int id)
{
TrackBB bb = new TrackBB();
try
{
return bb.SAFQC(mConnectionString, id);
}
finally
{
bb = null;
}
}
public DataTable GetSceneComp(int id, string types, bool graphicsPackage, bool sceneComp, Tuple<string, string> titles)
{
DataTable result = null;
List<int> ids = new List<int>();
MovieDerivative derivative = new MovieDerivative();
try
{
ids = derivative.GetMasterIdsRealAssets(mConnectionString, id, graphicsPackage);
foreach (int masterId in ids)
{
using (DataTable table = derivative.GetDerivativeNonBTS(mConnectionString, masterId, types))
{
if (table.HasRows())
{
if (result == null)
result = table.Clone() as DataTable;
foreach (DataRow row in table.Rows)
{
//Only show internet clips related to this scene comp.
if (sceneComp && row["type"].ToString().Equals("Internet-Clip"))
{
string title = row["title"].ToString();
if (!title.Substring(0, titles.Item1.Length).Equals(titles.Item1))
continue;
}
DataRow dr = result.NewRow();
dr.ItemArray = row.ItemArray;
result.Rows.Add(dr);
}
}
}
}
}
finally
{
derivative = null;
}
return result;
}
public string GetSMBLocation(int id)
{
TrackE e = new TrackE();
try
{
return e.GetStudioMasterBackupLocation(mConnectionString, id);
}
finally
{
e = null;
}
}
public DataTable GetSpanishDerivatives(int derivativeId, int masterId, int hd)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetSpanishDerivatives(mConnectionString, derivativeId, masterId, hd);
}
finally
{
derivative = null;
}
}
public bool GetSpanishQC(int id)
{
Movie movie = new Movie();
try
{
return movie.GetSpanishQC(mConnectionString, id);
}
finally
{
movie = null;
}
}
public string GetStatus(int id, string type)
{
return mDataAccess.GetStatus(id, type);
}
public string GetStatusMaster(int id)
{
string result = "32";
bool found = false;
List<int> ids = GetMasterIds(id, false);
foreach (int movieId in ids)
{
found = true;
if (!mDataAccess.CheckMaterialsComplete(movieId))
return "1";
string status = mDataAccess.GetStatus(id, "Movie");
if (String.IsNullOrEmpty(result.Trim()))
status = "0";
if (Convert.ToInt32(status) < Convert.ToInt32(result))
result = status;
}
if (!found)
{
ids = GetMasterIds(id, true);
foreach (int movieId in ids)
{
found = true;
if (!mDataAccess.CheckMaterialsComplete(movieId))
return "1";
string status = mDataAccess.GetStatus(id, "Movie");
if (String.IsNullOrEmpty(result.Trim()))
status = "0";
if (Convert.ToInt32(status) < Convert.ToInt32(result))
result = status;
}
}
return result;
}
public Tuple<string, string> GetStructure(int id)
{
Movie movie = new Movie();
try
{
return movie.GetStructure(mConnectionString, id);
}
finally
{
movie = null;
}
}
public Tuple<int?, int?> GetStructureQC(int id)
{
ConformingStructure structure = new ConformingStructure();
try
{
return structure.GetStructureQC(mConnectionString, id);
}
finally
{
structure = null;
}
}
public int GetStructureQCPassed(int id)
{
ConformingStructure structure = new ConformingStructure();
try
{
return structure.GetStructureQCPassed(mConnectionString, id);
}
finally
{
structure = null;
}
}
public int GetStudioId(int masterId)
{
Movie movie = new Movie();
try
{
return movie.GetStudioId(mConnectionString, masterId);
}
finally
{
movie = null;
}
}
public List<string> GetSubratings(int id)
{
MovieRatingSub sub = new MovieRatingSub();
try
{
return sub.GetSubratings(mConnectionString, id);
}
finally
{
sub = null;
}
}
public int GetTENCount(int id)
{
Movie movie = new Movie();
try
{
return movie.GetCountByStudio(mConnectionString, id, "27, 556");
}
finally
{
movie = null;
}
}
public int? GetTimelineComplete(int id)
{
int altHDId = mDataAccess.GetAltHDId(id);
if (altHDId != id && altHDId != 0)
id = altHDId;
MovieConform conform = new MovieConform();
try
{
using (DataTable table = conform.GetConformingTimelineComplete(mConnectionString, id))
{
if (table.HasRows() && table.Rows[0]["conformed"].GetType() != typeof(DBNull))
return (int?)Convert.ToInt32(table.Rows[0]["conformed"]);
}
}
finally
{
conform = null;
}
return null;
}
public string GetTitle(int id)
{
return mDataAccess.GetTitle(id);
}
public Tuple<string, string> GetTitles(int id)
{
Movie movie = new Movie();
try
{
return movie.GetTitles(mConnectionString, id);
}
finally
{
movie = null;
}
}
public Tuple<string, string, int> GetTitleTypeRating(int id, string titleType)
{
Movie movie = new Movie();
try
{
return movie.GetTitleTypeRating(mConnectionString, id, titleType);
}
finally
{
movie = null;
}
}
public Tuple<string, int, int> GetTypeStudioHD(int id)
{
Movie movie = new Movie();
try
{
return movie.GetTypeStudioHD(mConnectionString, id);
}
finally
{
movie = null;
}
}
public List<string> GetUpcomingVODPitches(int id)
{
Schedule schedule = new Schedule();
try
{
return schedule.GetUpcomingVODPitchesNoOrder(mConnectionString, id, DateTime.Now);
}
finally
{
schedule = null;
}
}
public List<int> GetWebSliceIds(int id)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetWebSliceIds(mConnectionString, id);
}
finally
{
derivative = null;
}
}
public List<string> GetXmlSources(int id)
{
MovieXmlSources xml = new MovieXmlSources();
try
{
return xml.GetXmlSources(mConnectionString, id);
}
finally
{
xml = null;
}
}
public string GetXXX(int rating)
{
return mDataAccess.GetXXX(rating);
}
public List<int> GetXXEXXIds(int masterId)
{
MovieDerivative derivative = new MovieDerivative();
try
{
return derivative.GetXXEXXIds(mConnectionString, masterId);
}
finally
{
derivative = null;
}
}
public bool HasContentFailure(int id, int itemId)
{
TrackSQC qc = new TrackSQC();
try
{
return qc.HasContentFailure(mConnectionString, id, itemId);
}
finally
{
qc = null;
}
}
public bool HasTechnicalFailure(int id, int itemId)
{
TrackSQC qc = new TrackSQC();
try
{
return qc.HasTechnicalFailure(mConnectionString, id, itemId);
}
finally
{
qc = null;
}
}
public bool HideId(int id)
{
ConformingHide hide = new ConformingHide();
try
{
return hide.HideId(mConnectionString, id);
}
finally
{
hide = null;
}
}
public bool IsClipLoggingComplete(int id)
{
MovieContentLastUser mclu = new MovieContentLastUser();
try
{
return mclu.GetLastLoggedCount(mConnectionString, id) > 0;
}
finally
{
mclu = null;
}
}
public bool IsFCPPassed(int id)
{
TrackSQC qc = new TrackSQC();
try
{
return qc.IsPassed(mConnectionString, id);
}
finally
{
qc = null;
}
}
public bool IsFCPRuntimeEntered(int id)
{
TrackS s = new TrackS();
try
{
return s.IsFCPRuntimeEntered(mConnectionString, id);
}
finally
{
s = null;
}
}
public int? IsFormatDigital(string format)
{
SystemConformingFileFormat ff = new SystemConformingFileFormat();
try
{
return ff.IsFormatDigital(mConnectionString, format);
}
finally
{
ff = null;
}
}
public bool IsHD(int id)
{
return mDataAccess.IsHD(id);
}
public bool IsReadyForTimelineQC(int id)
{
MovieConform conform = new MovieConform();
try
{
return conform.IsReadyForTimelineQC(mConnectionString, id);
}
finally
{
conform = null;
}
}
public bool IsStructureQCComplete(int id)
{
ConformingStructure structure = new ConformingStructure();
try
{
return structure.IsStructureQCComplete(mConnectionString, id);
}
finally
{
structure = null;
}
}
public bool SaveLanguage(int id, string language, string userName)
{
Movie movie = new Movie();
try
{
return movie.SaveLanguage(mConnectionString, id, language, userName);
}
finally
{
movie = null;
}
}
public bool UnhideId(int id)
{
ConformingHide hide = new ConformingHide();
try
{
return hide.UnhideId(mConnectionString, id);
}
finally
{
hide = null;
}
}
public bool Update3DStatus(int id)
{
Movie movie = new Movie();
try
{
return movie.Update3DStatus(mConnectionString, id);
}
finally
{
movie = null;
}
}
public bool UpdateClipboardUserName(string userName, int id)
{
ConformingLoadIDNew clidn = new ConformingLoadIDNew();
try
{
return clidn.UpdateUserName(mConnectionString, userName, id);
}
finally
{
clidn = null;
}
}
public bool UpdatePal(int id)
{
Movie movie = new Movie();
try
{
return movie.UpdatePALStatus(mConnectionString, id);
}
finally
{
movie = null;
}
}
public bool UpdateSpanishQC(int id, int qc)
{
Movie movie = new Movie();
try
{
return movie.UpdateSpanishQC(mConnectionString, id, qc);
}
finally
{
movie = null;
}
}
public bool UpdateTrackYRecord(int id)
{
TrackY y = new TrackY();
try
{
TrackY data = y.CheckRecordExists(mConnectionString, id);
if (data == null)
return false; //No record to update.
data.Location = "FCP Project";
return y.AddUpdateRecord(mConnectionString, data, false);
}
finally
{
y = null;
}
}
public bool UpdateYLocation(int id)
{
TrackY y = new TrackY();
try
{
string location = y.GetDigitalStudioMasterBackupLocation(mConnectionString, id);
if (!String.IsNullOrEmpty(location))
return y.UpdateDigitalStudioMasterBackupLocation(mConnectionString, id, "FCP Project");
return true;
}
finally
{
y = null;
}
}
public bool UseTitleOnAsset()
{
return mDataAccess.GetSystemDefaultValueByName("USE_TITLE_ON_ASSET_FLAG") == "1";
}
#endregion
#region Private Methods
private List<int> GetHiddenIds()
{
ConformingHide hide = new ConformingHide();
try
{
return hide.GetHiddenIds(mConnectionString);
}
finally
{
hide = null;
}
}
private Tuple<string, string> GetHiddenMovie(int id)
{
Movie movie = new Movie();
try
{
return movie.GetTitleAndType(mConnectionString, id);
}
finally
{
movie = null;
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controlador : MonoBehaviour
{
public GeneradorTerrenoProcedural Escenario;
public int nivelActual;
public bool llaveConseguida = false;
public DoorController puerta;
private CamaraSecundaria camaraPuerta;
public Camera camaraPrincipal;
public int posJosX;
public int posJosY;
public Vector3 posJos;
public Vector3 posIniJos;
public bool [] nivelesAccesibles ;
public GameObject[] selectorNivelesBotones;
public int numNiveles;
public int monedas;
private void Awake()
{
}
// Start is called before the first frame update
void Start()
{
monedas = 0;
nivelesAccesibles = new bool[numNiveles];
selectorNivelesBotones = new GameObject[numNiveles];
for (int i = 0; i < numNiveles; i++)
{
if(i == 1)
{
nivelesAccesibles[i] = true;
} else
{
nivelesAccesibles[i] = false;
}
}
posJos = new Vector3(posJosX, posJosY, 0);
posIniJos = posJos;
DontDestroyOnLoad(this.gameObject);
}
// Update is called once per frame
void Update()
{
}
public void puertaAbriendose()
{
puerta.enabled = true;
camaraPuerta.camaraSecun.enabled = true;
camaraPrincipal.enabled = false;
puerta.activarPuerta();
Escenario.congelarMov();
}
public void reestaurarCamara()
{
camaraPuerta.camaraSecun.enabled = false;
camaraPrincipal.enabled = true;
Escenario.descongelarMov();
}
public void pedirNivel()
{
Escenario = FindObjectOfType<GeneradorTerrenoProcedural>();
Escenario.nivel = nivelActual;
}
public void reiniciarControlador()
{
puerta = FindObjectOfType<DoorController>();
camaraPuerta = FindObjectOfType<CamaraSecundaria>();
Camera[] camaras = FindObjectsOfType<Camera>();
Debug.Log(camaras.Length + " num camaras");
foreach (Camera cam in camaras)
{
if(cam.tag == "MainCamera")
{
camaraPrincipal = cam;
}
}
Debug.Log(camaraPuerta);
Debug.Log(camaraPrincipal);
camaraPrincipal.enabled = true;
}
public void actualizarBotonesSelectorNiveles()
{
for (int i = 0; i < numNiveles; i++)
{
if (nivelesAccesibles[i])
{
if(selectorNivelesBotones[i] != null)
{
selectorNivelesBotones[i].SetActive(true);
}
} else
{
if(selectorNivelesBotones[i] != null)
{
selectorNivelesBotones[i].SetActive(false);
}
}
}
}
public void asignarseBotones(GameObject boton, int num)
{
selectorNivelesBotones[num] = boton;
}
public void desbloquearSigNivel()
{
if(nivelActual+1 < numNiveles)
{
nivelesAccesibles[nivelActual + 1] = true;
}
}
public void sumarMonedas(int num)
{
monedas += num;
}
}
|
using System;
namespace NewFeatures._7_0
{
public class Deconstructors
{
public static void Run()
{
var myPoint = new Point();
//multi variable declaration
var (x, y) = myPoint;
// if we don't care about one variable, we can ignore it using "_"
var (a, _) = myPoint;
Console.WriteLine($"{x}");
}
}
public class Point
{
public int X, Y;
public void Deconstruct(out int x, out int y) // how we can write deconstructor
{
x = X;
y = Y;
}
}
} |
using Alabo.Data.People.Users.ViewModels.Admin;
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
namespace Alabo.Cloud.Reports.UserRecommend.Services {
public interface IUserRecommendService : IService {
/// <summary>
/// 获取直推会员、间推、团队的等级分布
/// </summary>
/// <param name="query"></param>
PagedList<UserGradeInfoView> GetUserGradeInfoPageList(object query);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Lab3.Models.FlightsViewModels
{
public class Settings {
[Display(Name = "Using Back up")]
public bool UseTrigger { get; set; }
[Display(Name = "To delete flights from this time")]
public TimeSpan EventTime { get; set; }
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ScriptKit
{
public class JsObject:JsValue
{
public JsObject()
{
IntPtr obj = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsCreateObject(out obj);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
this.Value = obj;
}
public JsObject(object externalData)
{
IntPtr obj = IntPtr.Zero;
GCHandle externalDataGCHandle = GCHandle.Alloc(externalData, GCHandleType.Weak);
JsErrorCode jsErrorCode = NativeMethods.JsCreateExternalObject(GCHandle.ToIntPtr(externalDataGCHandle),
HandleJsFinalizeCallback,
out obj);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
this.Value = obj;
}
private static void HandleJsFinalizeCallback(IntPtr data)
{
GCHandle gcHandle = GCHandle.FromIntPtr(data);
gcHandle.Free();
}
public object ExternalData
{
get
{
IntPtr externalData = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetExternalData(this.Value, out externalData);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
GCHandle handle = GCHandle.FromIntPtr(externalData);
return handle.Target;
}
}
internal JsObject(IntPtr value)
{
this.Value = value;
}
public JsContext Context
{
get
{
return JsRuntime.GetContextOfObject(this);
}
}
public JsObject Prototype
{
get
{
IntPtr prototypeObject;
JsErrorCode jsErrorCode = NativeMethods.JsGetPrototype(this.Value, out prototypeObject);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return new JsObject(prototypeObject);
}
set
{
JsErrorCode jsErrorCode = NativeMethods.JsSetPrototype(this.Value, value.Value);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
}
public string[] OwnPropertyNames
{
get
{
IntPtr propertyNames = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetOwnPropertyNames(this.Value, out propertyNames);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
JsArray jsArray = FromIntPtr(propertyNames) as JsArray;
int length = jsArray.Length;
string[] ownPropertyNames = new string[length];
for (int i = 0; i < length; i++)
{
ownPropertyNames[i] = jsArray[i].ConverToString();
}
return ownPropertyNames;
}
}
public JsSymbol[] OwnPropertySymbols
{
get
{
IntPtr propertySymbols = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetOwnPropertySymbols(this.Value, out propertySymbols);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
JsArray jsArray = FromIntPtr(propertySymbols) as JsArray;
int length = jsArray.Length;
JsSymbol[] ownPropertySymbols = new JsSymbol[length];
for (int i = 0; i < length; i++)
{
ownPropertySymbols[i] = jsArray[i] as JsSymbol;
}
return ownPropertySymbols;
}
}
public bool IsExtensible
{
get
{
bool isExtensible = false;
JsErrorCode jsErrorCode = NativeMethods.JsGetExtensionAllowed(this.Value, out isExtensible);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return isExtensible;
}
}
public void PreventExtension()
{
JsErrorCode jsErrorCode = NativeMethods.JsPreventExtension(this.Value);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
public JsValue this[string propertyName]
{
get
{
IntPtr propertyId= GetPropertyIdFromString(propertyName);
IntPtr result = IntPtr.Zero;
JsErrorCode jsErrorCode= NativeMethods.JsGetProperty(this.Value, propertyId, out result);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return FromIntPtr(result);
}
set
{
IntPtr propertyId = GetPropertyIdFromString(propertyName);
JsErrorCode jsErrorCode = NativeMethods.JsSetProperty(this.Value, propertyId, value.Value, false);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
}
public JsValue this[JsSymbol symbol]
{
get
{
IntPtr propertyId = GetPropertyIdFromSymbol(symbol);
IntPtr result = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetProperty(this.Value, propertyId, out result);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return FromIntPtr(result);
}
set
{
IntPtr propertyId = GetPropertyIdFromSymbol(symbol);
JsErrorCode jsErrorCode = NativeMethods.JsSetProperty(this.Value, propertyId, value.Value, false);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
}
private unsafe static IntPtr GetPropertyIdFromString(string propertyName)
{
Span<byte> bytes = Encoding.UTF8.GetBytes(propertyName);
IntPtr propertyId = IntPtr.Zero;
fixed (byte* pBytes = bytes)
{
JsErrorCode jsErrorCode = NativeMethods.JsCreatePropertyId(new IntPtr(pBytes), new IntPtr(bytes.Length), out propertyId);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
return propertyId;
}
private static IntPtr GetPropertyIdFromSymbol(JsSymbol symbol){
IntPtr propertyIdRef = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetPropertyIdFromSymbol(symbol.Value, out propertyIdRef);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return propertyIdRef;
}
public JsValue this[int index]
{
get
{
IntPtr result;
JsNumber indexNumber = new JsNumber(index);
JsErrorCode jsErrorCode = NativeMethods.JsGetIndexedProperty(this.Value, indexNumber.Value, out result);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return FromIntPtr(result);
}
set
{
JsNumber indexNumber = new JsNumber(index);
JsErrorCode jsErrorCode = NativeMethods.JsSetIndexedProperty(this.Value, indexNumber.Value, value.Value);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
}
public void DefineProperty(string propertyName)
{
//IntPtr propertyId = GetPropertyIdFromString(propertyName);
//NativeMethods.JsDefineProperty(this.Value,propertyId,)
}
public void DeleteProperty(string propertyName)
{
IntPtr propertyId = GetPropertyIdFromString(propertyName);
bool result = false;
JsErrorCode jsErrorCode = NativeMethods.JsDeleteProperty(this.Value, propertyId, false, out result);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
public void DeleteIndexedProperty(int index)
{
JsNumber indexNumber = new JsNumber(index);
JsErrorCode jsErrorCode = NativeMethods.JsDeleteIndexedProperty(this.Value, indexNumber.Value);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
public bool InstanceOf(JsFunction jsFunction)
{
bool result = false;
JsErrorCode jsErrorCode = NativeMethods.JsInstanceOf(this.Value, jsFunction.Value, out result);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return result;
}
public JsValue GetOwnPropertyDescriptor(string propertyName)
{
IntPtr propertyId = GetPropertyIdFromString(propertyName);
IntPtr propertyDescriptor = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsGetOwnPropertyDescriptor(this.Value, propertyId, out propertyDescriptor);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return FromIntPtr(propertyDescriptor);
}
public JsWeakReference CreateWeakReference()
{
IntPtr weakRef = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsCreateWeakReference(this.Value, out weakRef);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return new JsWeakReference(weakRef);
}
public ProxyProperties{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoSingleton<ObjectPool>
{
public string M_ResourceDir = "";
Dictionary<string, SubPool> m_pools = new Dictionary<string, SubPool>();
/// <summary>
/// 生成目标游戏物体
/// </summary>
/// <param name="name">目标游戏物体的名字</param>
/// <param name="parent">目标游戏物体在场景中的父物体</param>
/// <returns></returns>
public GameObject Spawn(string name)
{
SubPool pool = null;
if (!m_pools.ContainsKey(name))
{
RegisterNew(name);
}
pool = m_pools[name];
return pool.Spawn();
}
/// <summary>
/// 如果总对象池中没有包含目标游戏物体的子对象池,为总对象池添加相应的子对象池
/// </summary>
/// <param name="name"></param>
/// <param name="parent"></param>
void RegisterNew(string name)
{
string path = M_ResourceDir + "/" + name;
GameObject go = Resources.Load<GameObject>(path);
SubPool pool = new SubPool(go);
m_pools.Add(pool.M_Name, pool);
}
/// <summary>
/// 为对象池回收目标游戏物体
/// </summary>
/// <param name="go"></param>
public void UnSpawn(GameObject go)
{
foreach (SubPool p in m_pools.Values)
{
if (p.Contain(go))
{
p.UnSpawn(go);
break;
}
}
}
public void UnSpawnAll()
{
foreach (SubPool p in m_pools.Values)
{
p.UnSpawnAll();
}
}
public void Clear()
{
//foreach (SubPool p in m_pools.Values)
//{
// p.DestroyAll();
//}
m_pools.Clear();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.