text stringlengths 13 6.01M |
|---|
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Json;
using System.Text;
using System.Threading.Tasks;
namespace RestJSONRMP
{
[Activity (Label = "Rest JSON RMP", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
String username = "ben.a.owen@gmail.com";
String password = "k1lkenny";
String restUrl = "https://live.runmyprocess.com/live/118261460635893523/host/141905/service/225679?P_mode=TEST";
// String username = "";
// String password = "";
// String restUrl = "http://";
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
SetContentView (Resource.Layout.Main);
EditText name = FindViewById<EditText> (Resource.Id.nameText);
TextView email = FindViewById<TextView> (Resource.Id.emailValue);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += async (sender, e) => {
email.Text = await FetchEmailAsync(name.Text);
};
}
private async Task<String> FetchEmailAsync (string name)
{
var authData = string.Format("{0}:{1}", username, password);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
var uri = new Uri(string.Format(restUrl));
StringContent stringContent = new StringContent (
"{ \"name\":\""+name+"\" }",
UnicodeEncoding.UTF8,
"application/json");
var content = "";
try
{
var response = await client.PostAsync(uri, stringContent);
if (response.IsSuccessStatusCode)
{
var stringValue = await response.Content.ReadAsStringAsync();
var data = JsonObject.Parse(stringValue);
content = data["email"];
}
}
catch (Exception ex)
{
Console.Out.WriteLine ("ERROR {0}", ex.Message);
}
return content;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
public class PriceListHead:SimpleNamedEntity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get
{
return "Заголовки прайс-листов";
}
}
/// <summary>
/// Идентификатор подразделения
/// </summary>
public long? IdStore
{
get;
set;
}
[DBIgnoreAutoGenerateParam]
public string NameStore
{
get;
set;
}
public int PriceListType
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BenefitDeductionAPI.Models.Employees
{
public class EmployeeDto
{
public string FirstName { get; set; }
public string MiddleName { get; set; } = "";
public string LastName { get; set; }
public int EmployeeId { get; internal set; }
public bool IsExempt { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Parser_Console.Classes
{
public class ValidationInfo
{
public string Afm { get; set; }
public List<string> Kad { get; set; }
public List<string> KadFormatted => Kad.Select(x=>FormatKad(x)).ToList();
private string FormatKad(string kad)
{
string result = kad.Replace(".", "");
while(result.Length < 8)
{
result += "0";
}
return result;
}
}
}
|
using Core.Controller;
using Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media.Imaging;
namespace Quiz.View
{
/// <summary>
/// Interaction logic for ucUser.xaml
/// </summary>
public partial class ucUser : UserControl
{
const string UNRANK = "/Images/Unranked.png";
const string DONG = "/Images/bronze.png";
const string BAC = "/Images/sliver.png";
const string VANG = "/Images/gold.png";
const string BACHKIM = "/Images/platium.png";
const string KIMCUONG = "/Images/diamond.png";
const string CAOTHU = "/Images/master.png";
const string THACHDAU = "/Images/challenger.png";
string[] rank = {"/Images/Unranked.png","/Images/bronze.png","/Images/sliver.png",
"/Images/gold.png","/Images/platium.png","/Images/diamond.png",
"/Images/master.png","/Images/challenger.png"};
string[] danhgia = { "Tệ", "Cần cố gắng", "Tạm được", "Tốt", "Xuất xắc" };
long[] danhgiaDiem = { 2, 4, 6, 8, 9 };
long[] numAnsCorrect = { 10, 50, 100, 300, 700, 1200, 1700, 2400 };
long[] numAns = { 40, 100, 300, 700, 1200, 1700, 2400, 3000 };
long[] Time = { 100, 500, 5000, 15000, 30000, 70000, 150000, 40000 };
long traloidung = 0;
long traloi = 0;
long time = 0;
AchievementHandle achivementHandle = new AchievementHandle();
List<Info> list = new List<Info>();
List<History> history = new List<History>();
public ucUser()
{
InitializeComponent();
list = achivementHandle.GetInfoOfUser(Thongtindangnhap.UserId);
history = achivementHandle.GetHistoryOfUser(Thongtindangnhap.UserId).OrderByDescending(t => t.DateTime).ToList();
setValueRank();
doJob();
doJob2();
}
private void doJob()
{
lbName.Content = Thongtindangnhap.Username;
rankAns.Source = new BitmapImage(new Uri(@"" + rank[getRank(numAns, traloi)], UriKind.Relative));
lbNumAns.Content = traloi.ToString();
rankAnsCorrect.Source = new BitmapImage(new Uri(@"" + rank[getRank(numAnsCorrect, traloidung)], UriKind.Relative));
lbNumAnsCorrect.Content = traloidung.ToString();
rankTimeUse.Source = new BitmapImage(new Uri(@"" + rank[getRank(Time, time)], UriKind.Relative));
lbTimeUse.Content = convert_int2time(Convert.ToInt32(time));
}
private string convert_int2time(int n)
{
string minute = (n / 60).ToString();
string second = (n % 60).ToString();
if (int.Parse(second) < 10) second = "0" + second;
return "" + minute + ":" + second;
}
private void doJob2()
{
List<InfoHistory> _li = new List<InfoHistory>();
foreach (History his in history)
{
InfoHistory infH = new InfoHistory();
infH.SubId = his.SubId;
float diem = ((float)his.NumberCorrect / his.NumberQuest * 10) ?? 0;
infH.Diem = "Điểm số: " + diem.ToString();
infH.Danhgia = "Đánh giá: " + danhgia[getRank(danhgiaDiem, (long)diem)];
if (diem > 6) infH.Color = "Green";
else infH.Color = "Red";
infH.Date = "Ngày làm bài: " + his.DateTime.Day.ToString() + "/" + his.DateTime.Month.ToString() + "/" + his.DateTime.Year.ToString() + " " + his.DateTime.Hour + ":" + his.DateTime.Minute;
_li.Add(infH);
}
listBox.ItemsSource = _li;
}
private int getRank(long[] a, long b)
{
for (int i = 0; i < a.Length; i++)
{
if (b < a[i]) return i;
}
return a.Length - 1;
}
private void setValueRank()
{
for (int i = 0; i < list.Count; i++)
{
Info inf = list[i] as Info;
traloi += inf.NumAnswer;
traloidung += inf.NumAnswerTrue;
time += inf.TimeUse;
}
}
private class InfoHistory
{
public string SubId { set; get; }
public string Diem { set; get; }
public string Danhgia { set; get; }
public string Date { set; get; }
public string Color { set; get; }
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
txtChitiet.Text = "";
History h = history[listBox.SelectedIndex] as History;
txtChitiet.Text = "Môn kiểm tra : " + h.SubId + System.Environment.NewLine;
txtChitiet.Text += "Số câu hỏi : " + h.NumberQuest + System.Environment.NewLine;
txtChitiet.Text += "Số câu trả lời : " + h.NumberAns + System.Environment.NewLine;
txtChitiet.Text += "Số câu trả lời đúng : " + h.NumberCorrect;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Grid a = ucGrid.Parent as Grid;
a.Children.Remove(ucGrid);
}
}
}
|
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Serilog;
using WitsmlExplorer.Api.Repositories;
using WitsmlExplorer.Api.Services;
namespace WitsmlExplorer.Api.Middleware
{
// Source: https://code-maze.com/global-error-handling-aspnetcore/
// ReSharper disable once ClassNeverInstantiated.Global
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ErrorDetails errorDetails500 = new ErrorDetails {StatusCode = (int) HttpStatusCode.InternalServerError, Message = "Something unexpected has happened."};
public ExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await next(httpContext);
}
catch (MessageSecurityException ex)
{
Log.Debug($"Not valid credentials: {ex}");
var errorDetails = new ErrorDetails
{
StatusCode = (int) HttpStatusCode.Unauthorized,
Message = "Not able to authenticate to WITSML server. Double-check your username and password."
};
await HandleExceptionAsync(httpContext, errorDetails);
}
catch (EndpointNotFoundException ex)
{
Log.Debug($"Not able to connect server endpoint. : {ex}");
httpContext.Request.Headers.TryGetValue(WitsmlClientProvider.WitsmlServerUrlHeader, out var serverUrl);
var errorDetails = new ErrorDetails
{
StatusCode = (int) HttpStatusCode.NotFound,
Message = $"Not able to connect to server endpoint: \"{serverUrl}\". Please verify that server URL is correct."
};
await HandleExceptionAsync(httpContext, errorDetails);
}
catch (RepositoryException ex)
{
Log.Error($"Got status code: {ex.StatusCode} and message: {ex.Message}");
await HandleExceptionAsync(httpContext, errorDetails500);
}
catch (Exception ex)
{
Log.Fatal($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, errorDetails500);
}
}
private static Task HandleExceptionAsync(HttpContext context, ErrorDetails errorDetails)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = errorDetails.StatusCode;
return context.Response.WriteAsync(errorDetails.ToString());
}
}
}
|
using System;
namespace SciVacancies.WebApp.Infrastructure.Saga
{
public interface IConstructSagas
{
ISaga Build(Type type, Guid id);
}
} |
using com.Sconit.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
//TODO: Add other using statements here
namespace com.Sconit.Entity.ISI
{
[Serializable]
public partial class TaskStatusView : EntityBase
{
#region O/R Mapping Properties
private string _taskCode;
public string TaskCode
{
get
{
return _taskCode;
}
set
{
_taskCode = value;
}
}
public Boolean IsAutoComplete { get; set; }
public string FocusUser { get; set; }
private DateTime _createDate;
public DateTime CreateDate
{
get
{
return _createDate;
}
set
{
_createDate = value;
}
}
private string _color;
public string Color
{
get
{
return _color;
}
set
{
_color = value;
}
}
private DateTime? _submitDate;
public DateTime? SubmitDate
{
get
{
return _submitDate;
}
set
{
_submitDate = value;
}
}
private string _assignUser;
public string AssignUser
{
get
{
return _assignUser;
}
set
{
_assignUser = value;
}
}
private string _assignUserNm;
public string AssignUserNm
{
get
{
return _assignUserNm;
}
set
{
_assignUserNm = value;
}
}
private string _assignStartUserNm;
public string AssignStartUserNm
{
get
{
return _assignStartUserNm;
}
set
{
_assignStartUserNm = value;
}
}
private string _schedulingStartUser;
public string SchedulingStartUser
{
get
{
return _schedulingStartUser;
}
set
{
_schedulingStartUser = value;
}
}
private string _assignStartUser;
public string AssignStartUser
{
get
{
return _assignStartUser;
}
set
{
_assignStartUser = value;
}
}
private string _startedUser;
public string StartedUser
{
get
{
return _startedUser;
}
set
{
_startedUser = value;
}
}
private DateTime? _assignDate;
public DateTime? AssignDate
{
get
{
return _assignDate;
}
set
{
_assignDate = value;
}
}
private DateTime? _startDate;
public DateTime? StartDate
{
get
{
return _startDate;
}
set
{
_startDate = value;
}
}
private Int32? _id;
public Int32? Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
private string _statusDesc;
public string StatusDesc
{
get
{
return _statusDesc;
}
set
{
_statusDesc = value;
}
}
private DateTime? _statusStartDate;
public DateTime? StatusStartDate
{
get
{
return _statusStartDate;
}
set
{
_statusStartDate = value;
}
}
private DateTime? _statusEndDate;
public DateTime? StatusEndDate
{
get
{
return _statusEndDate;
}
set
{
_statusEndDate = value;
}
}
private string _statusUser;
public string StatusUser
{
get
{
return _statusUser;
}
set
{
_statusUser = value;
}
}
private string _statusUserNm;
public string StatusUserNm
{
get
{
return _statusUserNm;
}
set
{
_statusUserNm = value;
}
}
private DateTime? _statusDate;
public DateTime? StatusDate
{
get
{
return _statusDate;
}
set
{
_statusDate = value;
}
}
private Int32? _statusCount;
public Int32? StatusCount
{
get
{
return _statusCount;
}
set
{
_statusCount = value;
}
}
private Int32? _currentStatusCount;
public Int32? CurrentStatusCount
{
get
{
return _currentStatusCount;
}
set
{
_currentStatusCount = value;
}
}
private string _comment;
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value;
}
}
private string _commentCreateUserNm;
public string CommentCreateUserNm
{
get
{
return _commentCreateUserNm;
}
set
{
_commentCreateUserNm = value;
}
}
private string _commentCreateUser;
public string CommentCreateUser
{
get
{
return _commentCreateUser;
}
set
{
_commentCreateUser = value;
}
}
private Int32? _commentCount;
public Int32? CommentCount
{
get
{
return _commentCount;
}
set
{
_commentCount = value;
}
}
private Int32? _currentCommentCount;
public Int32? CurrentCommentCount
{
get
{
return _currentCommentCount;
}
set
{
_currentCommentCount = value;
}
}
private DateTime? _commentCreateDate;
public DateTime? CommentCreateDate
{
get
{
return _commentCreateDate;
}
set
{
_commentCreateDate = value;
}
}
private string _fileName;
public string FileName
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
private string _path;
public string Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
private string _fileExtension;
public string FileExtension
{
get
{
return _fileExtension;
}
set
{
_fileExtension = value;
}
}
private string _contentType;
public string ContentType
{
get
{
return _contentType;
}
set
{
_contentType = value;
}
}
private DateTime? _attachmentCreateDate;
public DateTime? AttachmentCreateDate
{
get
{
return _attachmentCreateDate;
}
set
{
_attachmentCreateDate = value;
}
}
private string _attachmentCreateUserNm;
public string AttachmentCreateUserNm
{
get
{
return _attachmentCreateUserNm;
}
set
{
_attachmentCreateUserNm = value;
}
}
private Int32? _attachmentCount;
public Int32? AttachmentCount
{
get
{
return _attachmentCount;
}
set
{
_attachmentCount = value;
}
}
private Int32? _currentAttachmentCount;
public Int32? CurrentAttachmentCount
{
get
{
return _currentAttachmentCount;
}
set
{
_currentAttachmentCount = value;
}
}
private Int32? _refTaskCount;
public Int32? RefTaskCount
{
get
{
return _refTaskCount;
}
set
{
_refTaskCount = value;
}
}
private string _taskAddress;
public string TaskAddress
{
get
{
return _taskAddress;
}
set
{
_taskAddress = value;
}
}
private string _seq;
public string Seq
{
get
{
return _seq;
}
set
{
_seq = value;
}
}
private string _phase;
public string Phase
{
get
{
return _phase;
}
set
{
_phase = value;
}
}
private string _status;
public string Status
{
get
{
return _status;
}
set
{
_status = value;
}
}
private string _desc1;
public string Desc1
{
get
{
return _desc1;
}
set
{
_desc1 = value;
}
}
private string _desc2;
public string Desc2
{
get
{
return _desc2;
}
set
{
_desc2 = value;
}
}
private string _taskSubTypeCode;
public string TaskSubTypeCode
{
get
{
return _taskSubTypeCode;
}
set
{
_taskSubTypeCode = value;
}
}
private string _taskSubTypeDesc;
public string TaskSubTypeDesc
{
get
{
return _taskSubTypeDesc;
}
set
{
_taskSubTypeDesc = value;
}
}
private string _subject;
public string Subject
{
get
{
return _subject;
}
set
{
_subject = value;
}
}
private string _priority;
public string Priority
{
get
{
return _priority;
}
set
{
_priority = value;
}
}
private string _flag;
public string Flag
{
get
{
return _flag;
}
set
{
_flag = value;
}
}
private DateTime? _completeDate;
public DateTime? CompleteDate
{
get
{
return _completeDate;
}
set
{
_completeDate = value;
}
}
private string _createUser;
public string CreateUser
{
get
{
return _createUser;
}
set
{
_createUser = value;
}
}
private string _submitUser;
public string SubmitUser
{
get
{
return _submitUser;
}
set
{
_submitUser = value;
}
}
private string _createUserNm;
public string CreateUserNm
{
get
{
return _createUserNm;
}
set
{
_createUserNm = value;
}
}
private string _submitUserNm;
public string SubmitUserNm
{
get
{
return _submitUserNm;
}
set
{
_submitUserNm = value;
}
}
private string _taskSubTypeAssignUser;
public string TaskSubTypeAssignUser
{
get
{
return _taskSubTypeAssignUser;
}
set
{
_taskSubTypeAssignUser = value;
}
}
private string _closeUpUser;
public string CloseUpUser
{
get
{
return _closeUpUser;
}
set
{
_closeUpUser = value;
}
}
private string _startUpUser;
public string StartUpUser
{
get
{
return _startUpUser;
}
set
{
_startUpUser = value;
}
}
private string _assignUpUser;
public string AssignUpUser
{
get
{
return _assignUpUser;
}
set
{
_assignUpUser = value;
}
}
public Boolean IsReport { get; set; }
private Boolean _isAutoAssign;
public Boolean IsAutoAssign
{
get
{
return _isAutoAssign;
}
set
{
_isAutoAssign = value;
}
}
private string _expectedResults;
public string ExpectedResults
{
get
{
return _expectedResults;
}
set
{
_expectedResults = value;
}
}
private DateTime? _planStartDate;
public DateTime? PlanStartDate
{
get
{
return _planStartDate;
}
set
{
_planStartDate = value;
}
}
private DateTime? _planCompleteDate;
public DateTime? PlanCompleteDate
{
get
{
return _planCompleteDate;
}
set
{
_planCompleteDate = value;
}
}
private string _backYards;
public string BackYards
{
get
{
return _backYards;
}
set
{
_backYards = value;
}
}
private string _type;
public string Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
private string _org;
public string Org
{
get
{
return _org;
}
set
{
_org = value;
}
}
private string _eCUser;
public string ECUser
{
get
{
return _eCUser;
}
set
{
_eCUser = value;
}
}
public string ViewUser { get; set; }
private Decimal? _startPercent;
public Decimal? StartPercent
{
get
{
return _startPercent;
}
set
{
_startPercent = value;
}
}
#endregion
public override int GetHashCode()
{
if (TaskCode != null)
{
return TaskCode.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
TaskStatusView another = obj as TaskStatusView;
if (another == null)
{
return false;
}
else
{
return (this.TaskCode == another.TaskCode);
}
}
}
}
|
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Blazored.LocalStorage;
using Blazored.SessionStorage;
namespace Blazor_WASM
{
public class Program
{
public static async Task Main(string[] args)
{
// WebAssemblyHostBuilder: Generate a Wasm for the current application
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// Load or Inject the Router Component for Routing in index.html in HTML element with is as 'app'
builder.RootComponents.Add<App>("#app");
// DI Service Registration
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// Register the Object as Singleton
builder.Services.AddScoped<AppStateContainer>();
// Register Storage Services For the Browser
builder.Services.AddBlazoredSessionStorage();
// Applicartion Build so that the execution (Running) will start in browser
await builder.Build().RunAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity.Core;
using System.Web;
using CNWTT;
using CNWTT.Models.DO;
namespace CNWTT.Models.DAO
{
public class AccessoryDAO
{
private static IList<accessory> list = null;
private static accessory acc = null;
//get accessory from productId
public static accessory getAccessoryProductId(int idA)
{
using (var db = new cnwttEntities())
{
try
{
var acc = db.accessories.Where(acce => acce.product_id == idA).Single();
return acc;
}
catch(InvalidOperationException e) { }
catch (EntityCommandExecutionException e){ }
}
return null;
}
public static bool deleteAccessories_idProduct(int idProduct)
{
using (var db = new cnwttEntities())
{
using (var dbTransaction = db.Database.BeginTransaction())
{
try
{
var acc = db.accessories.Where(a => a.product_id == idProduct).Single();
db.accessories.Remove(acc);
db.SaveChanges();
dbTransaction.Commit();
return true;
}
catch (InvalidOperationException e) { }
catch (EntityCommandExecutionException e) { }
catch (Exception e)
{
dbTransaction.Rollback();
}
}
}
return false;
}
public static bool addAccessory(Accessories a)
{
using (var db = new cnwttEntities())
{
try
{
var acc = new accessory();
acc.color = a.Color;
acc.manufacturer = a.Manufacturer;
acc.product_id = Int32.Parse(a.Product_Id);
db.accessories.Add(acc);
db.SaveChanges();
return true;
}
catch (EntityCommandExecutionException e){ }
}
return false;
}
public static bool editAccessory_idProduct(int idProduct, accessory accessory)
{
using (var db = new cnwttEntities())
{
try
{
var acc = db.accessories.Where(a => a.product_id == idProduct).Single();
acc.color = accessory.color;
acc.manufacturer = accessory.manufacturer;
db.SaveChanges();
return true;
}catch(Exception e) { }
}
return false;
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Nono.Engine
{
internal class Hotheap
{
private HashSet<TaskLine> _heap;
public TaskCollection _tasks;
public Hotheap(TaskCollection tasks)
{
_tasks = tasks;
_heap = tasks.Where(task => Combinations.IsHot(task.Cues, task.Length)).ToHashSet();
}
public bool TryPop(out TaskLine line)
{
line = _heap.OrderBy(x => x.CombinationsCount).FirstOrDefault();
if (line == null)
return false;
_heap.Remove(line);
return true;
}
public void PushDiff(DiffLine diff)
{
var opposite = diff.Index.Orienation.Opposite();
var oppsiteTasks = diff.NonEmptyIndexes.Select(i => _tasks[opposite, i]);
_heap.UnionWith(oppsiteTasks);
}
}
} |
namespace Coldairarrow.Api
{
internal class CacheOptions
{
public CacheType CacheType { get; set; }
public string RedisEndpoint { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
using ServiceQuotes.Domain.Entities;
using ServiceQuotes.Domain.Repositories;
using ServiceQuotes.Infrastructure.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ServiceQuotes.Infrastructure.Repositories
{
public class CustomerAddressRepository : Repository<CustomerAddress>, ICustomerAddressRepository
{
public CustomerAddressRepository(AppDbContext dbContext) : base(dbContext) { }
public async Task<CustomerAddress> GetWithCustomerAndAddress(Guid customerId, Guid addressId)
{
return await _entities
.Include(ca => ca.Customer)
.Include(ca => ca.Address)
.SingleOrDefaultAsync(ca => ca.CustomerId == customerId && ca.AddressId == addressId);
}
public async Task<CustomerAddress> GetByCustomerIdAndName(Guid customerId, string name)
{
return await _entities
.Include(ca => ca.Customer)
.Include(ca => ca.Address)
.SingleOrDefaultAsync(ca => ca.CustomerId == customerId && ca.Name == name);
}
public async Task<IEnumerable<CustomerAddress>> FindWithAddress(Guid customerId, Expression<Func<CustomerAddress, bool>> predicate)
{
return await _entities
.Include(ca => ca.Address)
.Where(ca => ca.CustomerId == customerId)
.Where(predicate)
.ToListAsync();
}
public async Task<List<String>> GetCities(Guid customerId)
{
return await _entities
.Include(ca => ca.Address)
.Where(ca => ca.CustomerId == customerId)
.Select(ca => ca.Address.City)
.Distinct()
.OrderBy(s => s)
.ToListAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _11.VersionAttribute
{
[GetVersion(1,2)]
class MainProg
{
static void Main()
{
try
{
Type type = typeof(MainProg);
object[] allAttributes = type.GetCustomAttributes(false);
foreach (GetVersion versionAttribute in allAttributes)
{
Console.WriteLine("The version of the class is {0} ", versionAttribute);
}
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
}
}
}
|
namespace ApartmentApps.Api.Modules
{
public interface IPortalComponentTyped<TResultViewModel> where TResultViewModel : ComponentViewModel
{
TResultViewModel ExecuteResult();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.Scripts.PlayerFolder;
using UnityEngine;
namespace Assets.Scripts.InventoryFolder
{
public class SlotManagement
{
private enum EDragAndDrop
{
Pick,
Stack,
Drag,
Drop,
None
}
private enum EWhereDrop
{
Inventory,
Stack,
}
private EDragAndDrop _eDragAndDrop;
private Vector2 _grabPosition;
private Item _grabedItem;
private SlotItem _previousSlot;
private int _click;
/* private bool _savePos;
private Vector2 _posit;
private string _result;*/
public SlotManagement()
{
_click = 0;
_grabPosition = Vector2.zero;
_eDragAndDrop = EDragAndDrop.Pick;
}
public void MoveBetweenTwoLists(params List<SlotItem>[] listOfLists)
{
if(listOfLists.Where(s => s != null).All(s => s.Count > 0))
{
if(Input.GetMouseButtonDown(0) && (_eDragAndDrop == EDragAndDrop.Pick || _eDragAndDrop == EDragAndDrop.Stack)) //uchpen předmět
{
foreach(List<SlotItem> slotList in listOfLists.Where(s => s != null).Where(s => s.Count > 0))
{
if(Input.GetKey(KeyCode.LeftShift) && slotList.Any(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Item != null && !s.Item.Grabed))
{
_eDragAndDrop = EDragAndDrop.Stack;
_click++; //přičítání počtu kliků
SlotItem actSlotItem = slotList.Find(s => s != null && s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Item != null); //najdení slotu itemů
Item newItem = new Item(actSlotItem.Item); //vytvoření nového itemu
_grabPosition = DeltaPosition(actSlotItem.Position, MyInput.CurrentMousePosition());
if(actSlotItem.Item.ActualStack > 0)
{
newItem.ActualStack = _click; //zápis stacků do itemu
actSlotItem.Item.ActualStack--; //odečtení staků
}
if(actSlotItem.Item.ActualStack == 0)
RemoveItem(actSlotItem); //odstraň item
_grabedItem = newItem; //nastav jako uchycený item
SetPickStats(newItem, MyInput.CurrentMousePosition() - _grabPosition);
}
//sebrání itemu na který bylo kliknuto
else if(slotList.Any(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Item != null && !s.Item.Grabed) && _grabedItem == null)
SetItemGrabed(slotList.Find(s => s != null && s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Item != null));
}
}
else if(Input.GetKeyUp(KeyCode.LeftShift) && _eDragAndDrop == EDragAndDrop.Stack)
{
//pokud pustím shift a stackuju
_eDragAndDrop = EDragAndDrop.Drop;
_click = 0;
}
if(_eDragAndDrop == EDragAndDrop.Drop)
{
//neustálé nastavování hodnot
SetPickStats(_grabedItem, MyInput.CurrentMousePosition() - _grabPosition);
}
if(Input.GetMouseButtonUp(0) && _eDragAndDrop == EDragAndDrop.Drag)
{
//pokud neni zmáčknuto tlačítko myši a je drag
_eDragAndDrop = EDragAndDrop.Drop;
AddRemoveStats(_previousSlot, false);
}
else if(Input.GetMouseButtonDown(0) && _eDragAndDrop == EDragAndDrop.Drop)
{
bool saved = false;
foreach(List<SlotItem> slotList in listOfLists.Where(s => s != null))
{
//výběr ze všech listů které nejsou null a obsahují kurzor(kolidují s rectem)
if(_grabedItem != null)
{
if(
slotList.Any(s => s.Rect.Contains(MyInput.CurrentMousePosition()) || s.Rect.Overlaps(_grabedItem.Rect)))
{
saved = true;
DropService(slotList);
}
}
}
if(!saved && _eDragAndDrop != EDragAndDrop.Drag)
{ //ošetření aby nebylo drag(tzn. pokud budu dávat na stack a ten stack bude neprázdný a zbydou mi itemy tak je to nezahodí)
_eDragAndDrop = EDragAndDrop.None;
RemoveItem(_previousSlot);
}
}
else if(_eDragAndDrop == EDragAndDrop.None)
{
//pokud je state none automaticky nastaví na pick...
_eDragAndDrop = EDragAndDrop.Pick;
}
}
}
public void DrawStacking()
{
//vykreslení stacků
if(_eDragAndDrop == EDragAndDrop.Stack)
{
GUI.Box(new Rect(MyInput.CurrentMousePosition().x - 20, MyInput.CurrentMousePosition().y - 20, 20, 20), _click.ToString());
}
}
private void DropService(List<SlotItem> slotList)
{
if(slotList.Any(s => s.Rect.Overlaps(_grabedItem.Rect)))
{
if(slotList.Any(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && !s.Occupied && CanIPutToSlot(s, _grabedItem)))
{ //přidání do inventáře
DropItem(slotList.Find(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && !s.Occupied && CanIPutToSlot(s, _grabedItem)), EWhereDrop.Inventory);
}
else if(slotList.Any(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Occupied && CanWeStack(s.Item, _grabedItem)))
{ //stackování
DropItem(slotList.Find(s => s.Rect.Contains(MyInput.CurrentMousePosition()) && s.Occupied && CanWeStack(s.Item, _grabedItem)), EWhereDrop.Stack);
}
else
{ //jinak hození na předchozí pozici
_previousSlot.Item = _grabedItem; //pozice je předchozí
_eDragAndDrop = EDragAndDrop.None; //nastavení na none
SetDropStats(_previousSlot, _grabedItem); //nastavení příslušných atributů
_grabedItem = null;
AddRemoveStats(_previousSlot);
}
}
}
private void DropItem(SlotItem slotItem, EWhereDrop eWhereDrop)
{
if(eWhereDrop == EWhereDrop.Inventory) //pokud vloží někam do inventáře(dropu) někde na volné místo
{
SetDropStats(slotItem, _grabedItem); //nastavení všech potřebných atributů
if(_previousSlot != null && !_previousSlot.Occupied && slotItem != _previousSlot)
{
//zde byl bug kvuli tomu že se nenulovat item na předchozím místě item se tvářil že tam není (graficky) logicky tam byl
_previousSlot.Item = null;
}
_grabedItem = null; //neni nic uchpeno
_eDragAndDrop = EDragAndDrop.None; //state je none
}
else if(eWhereDrop == EWhereDrop.Stack) //pokud vloží někam kde se bude stackovat
{
if(!StackOverflow(slotItem.Item, _grabedItem))
{
slotItem.Item.ActualStack += _grabedItem.ActualStack; //přičtení k aktuálnímu stacku
_eDragAndDrop = EDragAndDrop.None; //state nastaven na none
_grabedItem = null; //není uchopen
}
else
{ //pokud přeteče stackování
int differ = slotItem.Item.Stack - slotItem.Item.ActualStack; //rozdíl staků
slotItem.Item.ActualStack = slotItem.Item.Stack; //nastavení staků na max
_grabedItem.ActualStack -= differ; //odečtení staků z drženého itemu
_eDragAndDrop = EDragAndDrop.Drag; //state je pořád drag
}
}
AddRemoveStats(slotItem);
}
private bool CanIPutToSlot(SlotItem slot, Item item)
{
if(slot.Subtype == ESubtype.None || slot.Type == EType.None)
return true;
if(slot.Type == EType.Armour && item.Subtype == slot.Subtype)
return true;
if(slot.Type == EType.Weapon && item.Type == EType.Weapon)
return true;
return false;
}
private void SetItemGrabed(SlotItem slotItem)
{
_grabedItem = slotItem.Item; //nastavení grab itemu na slotitem
_previousSlot = slotItem; //nastavení předchozího slotu
SetDropStats(slotItem, _grabedItem, false, true);
slotItem.Occupied = false; //inventarový item již neni obsazen
_grabPosition = DeltaPosition(slotItem.Item.Position, MyInput.CurrentMousePosition()); //nastavení defaultní pozice kvůli posunování textury na pozici kurzoru
_eDragAndDrop = EDragAndDrop.Drag; //nastavení na statu na drag
SetPickStats(slotItem.Item, MyInput.CurrentMousePosition() - _grabPosition);
}
private void SetPickStats(Item item, Vector2 position)
{
if(item != null)
{
item.Position = position; //pozicování
_grabedItem.Grabed = true;
item.UpdateRectangePosition(); //updatuje rectangle
}
}
private Vector2 DeltaPosition(Vector2 itemPosition, Vector2 mousePosition)
{
return new Vector2(mousePosition.x - itemPosition.x, mousePosition.y - itemPosition.y); //uloží pozici při úchytu
}
public void DrawMovingItem()
{
if(_grabedItem == null)
return;
_grabedItem.DrawItem();
}
private static bool CanWeStack(Item firstItem, Item secondItem)
{
return (firstItem.Name == secondItem.Name && firstItem.Stack > 1 && (firstItem.ActualStack < firstItem.Stack || secondItem.ActualStack < secondItem.Stack) && firstItem.ActualStack < firstItem.Stack);
}
private void RemoveItem(SlotItem slotItem)
{
_grabedItem = null;
SetDropStats(slotItem, null, false);
}
public static bool AddToSlot(List<SlotItem> slotList, Item item)
{
if(slotList.Where(s => s.Item != null).Any(s => CanWeStack(s.Item, item)))
{
Item stackableItem = slotList.Where(s => s.Item != null).First(s => CanWeStack(s.Item, item)).Item;
if(StackOverflow(stackableItem, item) && CanWeStack(stackableItem, stackableItem))
{
int differ = stackableItem.Stack - stackableItem.ActualStack;
stackableItem.ActualStack = stackableItem.Stack;
Debug.Log(differ);
item.ActualStack = differ;
SlotItem slotItem = slotList.First(s => !s.Occupied);
SetDropStats(slotItem, new Item(item));
return true;
}
else
{
stackableItem.ActualStack += item.ActualStack; //přičtení stacků k itemu
return true;
}
}
else if(slotList.Any(s => !s.Occupied))
{
SlotItem slotItem = slotList.First(s => !s.Occupied);
SetDropStats(slotItem, new Item(item));
return true;
}
else
Debug.Log("ALL SLOTS ARE FULL");
return false;
}
public static void SetDropStats(SlotItem slotItem, Item item, bool occupied = true, bool grabed = false)
{
if(slotItem != null)
{
slotItem.Item = item;
slotItem.Occupied = occupied;
if(item != null)
{
item.Grabed = grabed;
item.Position = slotItem.Position; //pozicování
item.UpdateRectangePosition();
}
}
}
public static bool IfAnySlotListContains(List<SlotItem> slotList, int itemId, int numberOfStack)
{
/*
foreach(SlotItem slotItem in slotList.Where(s => s.Item.ID == itemId))
{
allStacks += slotItem.Item.ActualStack;
}
*/
int allStacks = slotList.Where(s => s.Item != null).Where(s => s.Item.ID == itemId).Sum(slotItem => slotItem.Item.ActualStack);
return numberOfStack <= allStacks;
}
public static void DeleteItemByStacks(List<SlotItem> slotList, int itemId, int numberOfStack)
{
if(IfAnySlotListContains(slotList, itemId, numberOfStack))
{
foreach(SlotItem slotItem in slotList.Where(s => s.Item != null).Where(s => s.Item.ID == itemId))
{
if(!StackUnderflow(slotItem.Item, numberOfStack))
slotItem.Item.ActualStack -= numberOfStack;
else
{
numberOfStack -= slotItem.Item.ActualStack;
slotItem.Item = null;
slotItem.Occupied = false;
}
}
}
}
private static bool StackOverflow(Item firstItem, Item secondItem)
{
return firstItem.ActualStack + secondItem.ActualStack > firstItem.Stack;
}
private static bool StackUnderflow(Item firstItem, Item secondItem)
{
return firstItem.ActualStack - secondItem.ActualStack < 1;
}
private static bool StackUnderflow(Item firstItem, int secondItemStack)
{
return firstItem.ActualStack - secondItemStack < 1;
}
private static bool StackOverflow(Item firstItem, int secondItemStack)
{
return firstItem.ActualStack + secondItemStack > firstItem.Stack;
}
public void AddRemoveStats(SlotItem slotItem, bool add = true)
{
if(slotItem.Type == EType.Armour)
{
foreach(ItemStats itemStats in slotItem.Item.ItemStats.Where(s => s.EStats == EStats.Health))
{
if(add)
Player.OnAddMaxHealth(itemStats.Value);
else
Player.OnAddMaxHealth(-itemStats.Value);
}
}
}
public void PickUp(List<SlotItem> sourceList, List<SlotItem> destinatioList)
{
if(sourceList != null)
if(sourceList.FindAll(s => s.Item != null).Count > 0)
{
Vector2 mousePosition = new Vector2(Input.mousePosition.x, Math.Abs(Input.mousePosition.y - Screen.height)); //vycentrování do levého dolního rohu
if(Input.GetButton("RMouse")) //uchpen předmět
{
if(sourceList.Any(s => s.Rect.Contains(mousePosition) && s.Item != null))
{
SlotItem slotItem = sourceList.Find(s => s.Rect.Contains(mousePosition) && s.Item != null);
if(AddToSlot(destinatioList, slotItem.Item))
{
RemoveItem(slotItem);
slotItem.Item.UpdateRectangePosition();
}
else
Debug.Log("FULL inventory");
Debug.Log("ADD ITEM TO INVENTORY");
}
}
}
}
public void InventoryInteract()
{
if(Input.GetMouseButtonDown(1))
{
SlotItem slotItem = InventorySettings.InventoryItemList.Find(s => s.Rect.Contains(MyInput.CurrentMousePosition()));
if(slotItem != null)
if(slotItem.Item != null)
{
if(slotItem.Item.Type == EType.Consumable)
{
Player.OnAddCurrentHealth(slotItem.Item.ItemStats[0].Value);
if(!StackUnderflow(slotItem.Item, 1))
{
slotItem.Item.ActualStack--;
}
else
{
slotItem.Occupied = false;
slotItem.Item = null;
}
}
}
}
}
}
}
|
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;
namespace ProgramaOperaciones
{
public partial class FormCirculo : Form
{
public FormCirculo()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void buttonCirculo_Click(object sender, EventArgs e)
{
double radio, respuestaCirculo;
double pi = 3.1514;
radio = int.Parse(textBoxCirculoRadio.Text);
respuestaCirculo = pi * radio;
textBoxCirculoRespuesta.Text = respuestaCirculo.ToString();
}
private void buttonRegresar_Click(object sender, EventArgs e)
{
FormPrincipal fp = new FormPrincipal();
fp.StartPosition = FormStartPosition.CenterScreen;
fp.Show();
this.Hide();
}
}
}
|
namespace AkkaOverview.Streaming.ActorSystem
{
public class GetTickMessage
{
public GetTickMessage(string instrument)
{
Instrument = instrument;
}
public string Instrument { get; }
}
}
|
using System;
using System.Collections;
using System.Data;
using System.Text;
using HTB.Database;
using HTB.Database.HTB.StoredProcs;
using HTB.v2.intranetx.util;
using HTBUtilities;
namespace HTB.v2.intranetx.bank
{
public partial class BankAccountMonthlyStatus : System.Web.UI.Page
{
private DateTime _startDate;
private DateTime _endDate;
private double _startingBalance;
private double _transferredOther;
private double _receivedECP;
private double _receivedClient;
private double _receivedTotal;
private double _totalTransferred;
private double _transferredClient;
private double _totalTransactionsAmount;
protected void Page_Load(object sender, EventArgs e)
{
ctlMessage.Clear();
}
#region Event Handlers
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsFormValid())
{
_startDate = GlobalUtilArea.GetDateAtTime(_startDate, "00:00");
_endDate = GlobalUtilArea.GetDateAtTime(_endDate, "23:59");
PopulteGrids();
_startingBalance = GetStartingBalance();
// lblDate.Text = _startDate.ToShortDateString() + " - " + _endDate.ToShortDateString();
lblStartingBalance.Text = GetRedIfNegative(_startingBalance);
lblPaymentsECP.Text = GetRedIfNegative(_receivedECP);
lblPaymentsClient.Text = GetRedIfNegative(_receivedClient);
lblOtherExpenses.Text = GetRedIfNegative(_transferredOther);
lblTransfersToClient.Text = GetRedIfNegative(_transferredClient);
lblTotalPayments.Text = GetRedIfNegative(_receivedTotal);
lblTotalExpenses.Text = GetRedIfNegative(_totalTransferred);
lblMonthlyBalance.Text = GetRedIfNegative(_receivedTotal + _totalTransferred);
lblBalance.Text = GetRedIfNegative(_startingBalance + _receivedTotal + _totalTransferred);
// txtDateFrom.Visible = false;
// lblFrom.Visible = false;
// Datum_CalendarButton.Visible = false;
// txtDateTo.Visible = false;
// lblTo.Visible = false;
// Datum_CalendarButton2.Visible = false;
// txtStartingBalance.Visible = false;
// lblDate.Visible = true;
trStartingBalance.Visible = true;
trPaymentsECP.Visible = true;
trPaymentsClient.Visible = true;
trTransfersToClient.Visible = true;
trProvision.Visible = true;
trTotalPayments.Visible = true;
trTotalExpenses.Visible = true;
trMonthlyBalance.Visible = true;
trBalance.Visible = true;
// btnCalculate.Visible = false;
// btnSave.Visible = HTBUtils.IsLastDayOfMonthForDate(_startDate, _endDate);
// btnNew.Visible = true;
trEmpty1.Visible = true;
trEmpty2.Visible = true;
trEmpty3.Visible = true;
}
}
protected void btnNew_Click(object sender, EventArgs e)
{
Response.Redirect("/v2/intranetx/bank/BankAccountMonthlyStatus.aspx");
}
/*
protected void btnSave_Click(object sender, EventArgs e)
{
if (IsFormValid())
{
try
{
_startDate = GlobalUtilArea.GetDateAtTime(_startDate, "00:00");
_endDate = GlobalUtilArea.GetDateAtTime(_endDate, "23:59");
PopulteGrids();
_startingBalance = GetStartingBalance();
if (HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblBankMonthly WHERE BamStartDate = '" + _startDate.ToShortDateString() + "'", typeof(tblBankMonthly)) != null)
{
ctlMessage.ShowError("The report exists and it cannot be re-written!");
}
else
{
if (!RecordSet.Insert(new tblBankMonthly()
{
BamStartDate = _startDate,
BamEndDate = _endDate,
BamReceived = _receivedTotal,
BamTransferredToClient = _transferredClient,
BamStartBalance = _startingBalance,
BamExpenseOther = _transferredOther,
BamEndBalance = _receivedTotal + _totalTransferred
}))
{
ctlMessage.ShowError("Fehler bei speichern!");
}
else
{
ctlMessage.ShowSuccess("Info Gespeichert!");
}
}
}
catch(Exception ex)
{
ctlMessage.ShowException(ex);
}
}
}
protected void txtDate_TextChanged(object sender, EventArgs e)
{
if(IsFormValid(false))
{
var bm = (tblBankMonthly)HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblBankMonthly WHERE BamEndDate <'" + _startDate.ToShortDateString() + "' ORDER BY BamEndDate DESC", typeof(tblBankMonthly));
if (bm != null)
{
txtStartingBalance.Text = HTBUtils.FormatCurrencyNumber(bm.BamEndBalance);
}
else
{
ctlMessage.ShowInfo("Anfangssaldo nicht gefunden.... bitte eingeben.");
}
}
}
*/
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("/v2/intranetx/bank/BankAccountMonthlyStatus.aspx");
}
#endregion
private void PopulteGrids()
{
var parameters = new ArrayList
{
new StoredProcedureParameter("startDate", SqlDbType.DateTime, _startDate),
new StoredProcedureParameter("endDate", SqlDbType.DateTime, _endDate),
new StoredProcedureParameter("onlyKlient", SqlDbType.Bit, chkOnlyKlient.Checked)
};
ArrayList[] lists = HTBUtils.GetMultipleListsFromStoredProcedure("spGetInkassoMonthlyBankStatus", parameters, new Type[] { typeof(spGetInkassoTransactions)});
PopulateTransactionsGrid(lists[0]);
}
private double GetStartingBalance()
{
double balance = 0;
var parameters = new ArrayList
{
new StoredProcedureParameter("date", SqlDbType.DateTime, _startDate),
new StoredProcedureParameter("amount", SqlDbType.Float, balance, ParameterDirection.Output)
};
HTBUtils.GetStoredProcedureSingleRecord("spGetBankAccountStartingBalance", parameters, typeof(Record));
foreach (object o in parameters)
{
if (o is ArrayList)
{
var outputList = (ArrayList)o;
foreach (StoredProcedureParameter p in outputList)
{
if (p.Name.IndexOf("amount") >= 0)
{
balance = Convert.ToDouble(p.Value);
break;
}
}
}
}
return balance;
}
#region Transaction Grid
private void PopulateTransactionsGrid(ArrayList list)
{
DataTable dt = GetTransactionsDataTableStructure();
_receivedECP = 0;
_receivedClient = 0;
_transferredClient = 0;
_receivedTotal = 0;
_totalTransferred = 0;
_totalTransactionsAmount = 0;
_transferredOther = 0;
foreach (spGetInkassoTransactions rec in list)
{
DataRow dr = dt.NewRow();
var sb = new StringBuilder();
if (rec.InvoiceID > 0)
{
sb.Append("<a href=\"javascript:MM_openBrWindow('/v2/intranetx/aktenink/ShowInvoice.aspx?");
GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, "InvId", rec.InvoiceID.ToString(), false);
sb.Append("','popSetAction','menubar=yes,scrollbars=yes,resizable=yes,width=800,height=800,top=10')\">");
sb.Append(rec.InvoiceID);
sb.Append("</a>");
dr["InvoiceID"] = sb.ToString();
sb.Clear();
if (rec.AppliedAmount > 0)
{
dr["Sender"] = rec.GegnerName;
if (rec.IsECP)
{
sb.Append("ECP");
}
else
{
sb.Append("[Eingang Kunde] ");
sb.Append(rec.KlientName);
if (!string.IsNullOrEmpty(rec.Description))
{
sb.Append("<BR/>");
sb.Append(rec.Description.Replace("\n", "<BR/>"));
}
}
}
else
{
dr["Sender"] = "ECP";
if (rec.IsProvision)
{
sb.Append("[Ausgang Provision] ");
sb.Append(rec.KlientName);
if (!string.IsNullOrEmpty(rec.Description))
{
sb.Append("<BR/>");
sb.Append(rec.Description.Replace("\n", "<BR/>"));
}
}
else
{
sb.Append("[Ausgang Kunde] ");
sb.Append(rec.KlientName);
if (!string.IsNullOrEmpty(rec.Description))
{
sb.Append("<BR/>");
sb.Append(rec.Description.Replace("\n", "<BR/>"));
}
}
}
dr["Receiver"] = sb.ToString();
}
else
{
sb.Clear();
sb.Append(rec.KlientName);
if (!string.IsNullOrEmpty(rec.Description))
{
sb.Append("<BR/>");
sb.Append(rec.Description.Replace("\n", "<BR/>"));
}
dr["InvoiceID"] = " ";
dr["Sender"] = rec.GegnerName;
dr["Receiver"] = sb.ToString();
}
dr["Date"] = rec.TransactionDate.ToShortDateString();
dr["AppliedAmount"] = rec.AppliedAmount < 0 ? "<font color=\"red\">" + HTBUtils.FormatCurrency(rec.AppliedAmount) + "</font>" : HTBUtils.FormatCurrency(rec.AppliedAmount);
dr["InvoiceCustInkAktId"] = rec.InvoiceCustInkAktId.ToString();
dt.Rows.Add(dr);
if (rec.AppliedAmount < 0)
{
_totalTransferred += rec.AppliedAmount;
if (rec.InvoiceID > 0 && !rec.IsProvision)
_transferredClient += rec.AppliedAmount;
else
_transferredOther += rec.AppliedAmount;
}
else
{
_receivedTotal += rec.AppliedAmount;
if (rec.IsECP)
_receivedECP += rec.AppliedAmount;
else
_receivedClient += rec.AppliedAmount;
}
_totalTransactionsAmount += rec.AppliedAmount;
}
gvTransactions.DataSource = dt;
gvTransactions.DataBind();
}
private DataTable GetTransactionsDataTableStructure()
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn("InvoiceID", typeof(string)));
dt.Columns.Add(new DataColumn("Date", typeof(string)));
dt.Columns.Add(new DataColumn("AppliedAmount", typeof(string)));
dt.Columns.Add(new DataColumn("InvoicePaymentTransferToClientDate", typeof(string)));
dt.Columns.Add(new DataColumn("InvoicePaymentTransferToClientAmount", typeof(string)));
dt.Columns.Add(new DataColumn("EcpBalance", typeof(string)));
dt.Columns.Add(new DataColumn("InvoiceCustInkAktId", typeof(string)));
dt.Columns.Add(new DataColumn("Sender", typeof(string)));
dt.Columns.Add(new DataColumn("Receiver", typeof(string)));
return dt;
}
protected string GetTotalReceived()
{
return GetRedIfNegative(_receivedECP);
}
protected string GetTotalTransferred()
{
return GetRedIfNegative(_totalTransferred);
}
protected string GetTotalTransactionsAmount()
{
return GetRedIfNegative(_totalTransactionsAmount);
}
#endregion
private bool IsFormValid(bool validateEndDate = true)
{
_startDate = GlobalUtilArea.GetDefaultDateIfConvertToDateError(txtDateFrom);
if (!HTBUtils.IsDateValid(_startDate))
{
_startDate = GlobalUtilArea.GetDefaultDateIfConvertToDateError(HTBUtils.GetConfigValue("BankStartingBalanceDate"));
txtDateFrom.Text = _startDate.AddDays(1).ToShortDateString();
if (!HTBUtils.IsDateValid(_startDate))
{
ctlMessage.ShowError("Datum [vom] ist ungültig!");
return false;
}
}
DateTime minStartDate = GlobalUtilArea.GetDefaultDateIfConvertToDateError(HTBUtils.GetConfigValue("BankStartingBalanceDate"));
if (_startDate.CompareTo(minStartDate) < 0)
{
ctlMessage.ShowError("Es gibt kein data vor "+minStartDate.AddDays(1).ToShortDateString());
return false;
}
if (validateEndDate)
{
_endDate = GlobalUtilArea.GetDefaultDateIfConvertToDateError(txtDateTo);
if (!HTBUtils.IsDateValid(_endDate))
{
_endDate = DateTime.Now;
}
txtDateTo.Text = _endDate.ToShortDateString();
}
return true;
}
private string GetRedIfNegative(double amount)
{
return (amount < 0) ? "<font color=\"red\">" + HTBUtils.FormatCurrency(amount) + "</font>" : HTBUtils.FormatCurrency(amount);
}
}
} |
using Autofac;
using CoVID.Parser;
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace CoVID
{
public partial class MainPage : Form
{
Autofac.IContainer container;
IDatabase database;
Table table;
int cntr = 0;
public MainPage()
{
CreateInstance();
database.Run(database);
InitializeComponent();
}
#region Functions
private void CreateInstance()
{
this.container = ContainerConfig.Configure();
this.database = container.Resolve<IDatabase>();
this.table = Table.GetTable(new string[] { "Country", "Cases", "Deaths", "Recoveries" });
}
private void Parse()
{
database.DeleteAll();
ParserWorker parser = new ParserWorker(container.Resolve<IParser>(),
container.Resolve<IParserSettings>(), database);
parser.Start();
for (int i = 0; i < 500; i++)
Thread.Sleep(10);
}
private void ComboboxLoad()
{
try
{
string selectQuery = "SELECT * FROM info.countriesinfo2";
var reader = database.GetReader(selectQuery);
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString("country"));
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Check(string v)
{
if (File.Exists(v))
File.Delete(v);
}
#endregion
#region Events
private void bParse_Click(object sender, EventArgs e)
{
using (LoadForm loadForm = new LoadForm(Parse))
{
loadForm.ShowDialog(this);
}
ComboboxLoad();
}
private void bUpdate_Click(object sender, EventArgs e)
{
ComboboxLoad();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectQuery = "SELECT * FROM info.countriesinfo2 where country='"+comboBox1.Text+"'";
var reader = database.GetReader(selectQuery);
while (reader.Read())
{
tBCountry.Text = reader.GetString("country");
tBCases.Text = reader.GetString("cases");
tBDeaths.Text = reader.GetString("deaths");
tBRecoveries.Text = reader.GetString("recoveries");
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bAdd_Click(object sender, EventArgs e)
{
try
{
table.Rows.Add(tBCountry.Text, tBCases.Text, tBDeaths.Text, tBRecoveries.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bImport_Click(object sender, EventArgs e)
{
try
{
Check($"test{cntr}.pdf");
var converter = container.Resolve<IConverter>(new TypedParameter(typeof(Table), table),
new NamedParameter("path", $"test{cntr}.pdf"), new NamedParameter("headerName", "COVID-19"));
converter.Convert();
if (chBPdf.Checked)
{
System.Diagnostics.Process.Start($"test{cntr}.pdf");
}
table.Rows.Clear();
cntr++;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
database.DeleteAll();
database.CloseConnection();
}
#endregion
}
}
|
using Aranda.Users.BackEnd.Dtos;
using Aranda.Users.BackEnd.Models;
using AutoMapper;
namespace Aranda.Users.BackEnd.Mappers
{
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<User, UserDto>()
.ReverseMap();
cfg.CreateMap<User, UserDataDto>()
.ReverseMap();
cfg.CreateMap<Role, RoleDto>()
.ReverseMap();
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MilitaryElite.Interfaces;
namespace MilitaryElite.Soldiers.Privates
{
public class LieutenantGeneral : Private, ILieutenantGeneral
{
public LieutenantGeneral(string id, string firstName, string lastName, decimal salary):
base(id, firstName, lastName,salary)
{
this.Privates = new List<Private>();
}
public List<Private> Privates { get; set; }
public override string ToString()
{
if (Privates.Count == 0)
{
return $"Name: {FirstName} {LastName} Id: {ID} Salary: {Salary:f2}\nPrivates:{String.Join("\n", Privates.Select(x => x.ToString()))}";
}
return $"Name: {FirstName} {LastName} Id: {ID} Salary: {Salary:f2}\nPrivates:\n{String.Join("\n", Privates.Select(x => x.ToString()))}";
}
}
}
|
using System;
using System.IO;
using System.Text;
using Xunit;
// ReSharper disable ConvertToConstant.Local
namespace Atc.Tests.Extensions
{
public class StreamExtensionsTests
{
[Fact]
public void CopyToStream()
{
// Arrange
var input = "Hallo world".ToStream();
// Act
var actual = input.CopyToStream();
// Assert
Assert.Equal("Hallo world", actual.ToStringData());
}
[Fact]
public void CopyToStream_BufferSize()
{
// Arrange
var input = "Hallo world".ToStream();
var bufferSize = 1024;
// Act
var actual = input.CopyToStream(bufferSize);
// Assert
Assert.Equal("Hallo world", actual.ToStringData());
}
[Fact]
public void ToBytes()
{
// Arrange
var input = "Hallo world".ToStream();
// Act
var buffer = input.ToBytes();
var actual = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
// Assert
Assert.Equal("Hallo world", actual);
}
[Fact]
public void ToStringData()
{
// Arrange
var input = "Hallo world".ToStream();
// Act
var actual = input.ToStringData();
// Assert
Assert.Equal("Hallo world", actual);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RazorPowerUp : PowerUpBase
{
public override void addPowerUp(PlayerPowers player)
{
player.addRazor();
Destroy(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace 北京工艺文件管理MVC.Database
{
/// <summary>
/// 机床表
/// </summary>
public class JDJS_PDMS_Device_Info
{
[Key]
public int ID { get; set; }
public string MachNum { get; set; }
public string IP { get; set; }
public int? TypeID { get; set; }
public int? LocationID { get; set; }
public DateTime? CreatTime { get; set; }
public int? CreatPersonID { get; set; }
public DateTime? LastAlterTime { get; set; }
public int? LastAlterPersonID { get; set; }
public string state { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PROnline.Models.Users
{
public class Role
{
//角色ID
[Display(Name = "角色ID")]
public String Id { get; set; }
//中文名
[Display(Name = "注释")]
public String Note { get; set; }
//是否删除
public bool isDelete { get; set; }
//是否删除
public bool CanDelete { get; set; }
//创建日期
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime CreateDate { get; set; }
public bool ModifyDate { get; set; }
//默认角色
//超级管理员
public static string ADMIN = "admin";
//访客
public static string PUBLIC = "public";
//学生
public static string STUDENT = "student";
//老师
public static string TEACHER = "teacher";
//家长
public static string PARENT = "parent";
//系统管理员
public static string MANAGER = "manager";
//督导专家
public static string SUPERVISOR = "supervisor";
//志愿者
public static string VOLUNTEER = "volunteer";
//学校管理员
public static string SCHOOL_MANAGER = "school_manager";
//爱心人士
public static string DONATOR = "donator";
//小组长
public static string TEAM_LEADER = "team_leader";
//服务组织
public static string SERVICE_MANAGER = "service_manager";
//项目管理
public static string PROJECT_MANAGER = "project_manager";
}
} |
using iSukces.Code.Interfaces;
namespace iSukces.Code.Typescript
{
public class TsSingleLineComment : ITsCodeProvider
{
public TsSingleLineComment(string text = null)
{
Text = text;
}
public void WriteCodeTo(ITsCodeWriter writer)
{
if (string.IsNullOrWhiteSpace(Text))
return;
var lines = Text.Trim().SplitToLines();
foreach (var line in lines)
writer.WriteLine("// " + line);
}
public string Text { get; set; }
}
} |
// Copyright 2021 by Hextant Studios. https://HextantStudios.com
// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/
using UnityEditor;
using UnityEngine;
namespace Hextant.Editor
{
using Editor = UnityEditor.Editor;
// SettingsProvider helper used to display settings for a ScriptableObject
// derived class.
public class ScriptableObjectSettingsProvider : SettingsProvider
{
public ScriptableObjectSettingsProvider( ScriptableObject settings,
SettingsScope scope, string displayPath ) :
base( displayPath, scope ) => this.settings = settings;
// The settings instance being edited.
public readonly ScriptableObject settings;
// The SerializedObject settings instance.
public SerializedObject serializedSettings =>
_serializedSettings != null ? _serializedSettings :
_serializedSettings = new SerializedObject( settings );
SerializedObject _serializedSettings;
// Called when the settings are displayed in the UI.
public override void OnActivate( string searchContext,
UnityEngine.UIElements.VisualElement rootElement )
{
_editor = Editor.CreateEditor( settings );
base.OnActivate( searchContext, rootElement );
}
// Called when the settings are no longer displayed in the UI.
public override void OnDeactivate()
{
Editor.DestroyImmediate( _editor );
_editor = null;
base.OnDeactivate();
}
// Displays the settings.
public override void OnGUI( string searchContext )
{
if( settings == null || _editor == null ) return;
// Set label width and indentation to match other settings.
EditorGUIUtility.labelWidth = 250;
GUILayout.BeginHorizontal();
GUILayout.Space( 10 );
GUILayout.BeginVertical();
GUILayout.Space( 10 );
// Draw the editor's GUI.
_editor.OnInspectorGUI();
// Reset label width and indent.
GUILayout.EndVertical();
GUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = 0;
}
// Build the set of keywords on demand from the settings fields.
public override bool HasSearchInterest( string searchContext )
{
if( !_keywordsBuilt )
{
keywords = GetSearchKeywordsFromSerializedObject(
serializedSettings );
_keywordsBuilt = true;
}
return base.HasSearchInterest( searchContext );
}
// True if the keywords set has been built.
bool _keywordsBuilt;
// Cached editor used to render inspector GUI.
Editor _editor;
}
}
|
using IconCreator.Core.Models.Interfaces;
using IconCreator.Core.Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
namespace IconCreator.Core.DataAccess
{
public class IconColorRepository : IRepository<IconColor>
{
public OleDbConnection Connection => throw new NotImplementedException();
public Task ClearTableAsync()
{
throw new NotImplementedException();
}
public Task CreateTableAsync()
{
throw new NotImplementedException();
}
public Task DeleteOnSubmitAsync(IconColor obj)
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
public async Task<IEnumerable<IconColor>> GetAllAsync()
{
var iconColors = new List<IconColor>();
await Task.Run(() => {
iconColors.Add(new IconColor("1", "#1abc9c", "#FFFFFF", "Turquoise"));
iconColors.Add(new IconColor("2", "#16a085", "#FFFFFF", "Green Sea"));
iconColors.Add(new IconColor("3", "#2ecc71", "#FFFFFF", "Emerald"));
iconColors.Add(new IconColor("4", "#27ae60", "#FFFFFF", "Nephritis"));
iconColors.Add(new IconColor("5", "#3498db", "#FFFFFF", "Peter River"));
iconColors.Add(new IconColor("6", "#2980b9", "#FFFFFF", "Belize Hole"));
iconColors.Add(new IconColor("7", "#9b59b6", "#FFFFFF", "Amethyst"));
iconColors.Add(new IconColor("8", "#8e44ad", "#FFFFFF", "Wisteria"));
iconColors.Add(new IconColor("9", "#34495e", "#FFFFFF", "Wet Asphalt"));
iconColors.Add(new IconColor("10", "#4c4c4c", "#FFFFFF", "Midnight Dark"));
iconColors.Add(new IconColor("11", "#f1c40f", "#000000", "Sun Flower"));
iconColors.Add(new IconColor("12", "#f39c12", "#000000", "Orange"));
iconColors.Add(new IconColor("13", "#e67e22", "#FFFFFF", "Carrot"));
iconColors.Add(new IconColor("14", "#d35400", "#FFFFFF", "Pumpkin"));
iconColors.Add(new IconColor("15", "#e74c3c", "#FFFFFF", "Alizarin"));
iconColors.Add(new IconColor("16", "#c0392b", "#FFFFFF", "Pomegranate"));
iconColors.Add(new IconColor("17", "#ecf0f1", "#000000", "Clouds"));
iconColors.Add(new IconColor("18", "#bdc3c7", "#000000", "Silver"));
iconColors.Add(new IconColor("19", "#95a5a6", "#000000", "Concrete"));
iconColors.Add(new IconColor("20", "#7f8c8d", "#FFFFFF", "Asbestos"));
}).ConfigureAwait(false);
return iconColors;
}
public Task<IconColor> GetAsync(string id)
{
throw new NotImplementedException();
}
public Task<IconColor> GetAsync(string pkValue, string pkField = null)
{
throw new NotImplementedException();
}
public Task InsertAllAsync(IEnumerable<IconColor> values)
{
throw new NotImplementedException();
}
public Task InsertAsync(IconColor value)
{
throw new NotImplementedException();
}
public Task InsertOnSubmitAsync(IconColor obj)
{
throw new NotImplementedException();
}
public void SetConnectionString(string connectionString)
{
throw new NotImplementedException();
}
public void Submit()
{
throw new NotImplementedException();
}
public bool SubmitChanges()
{
throw new NotImplementedException();
}
public Task UpdateAllAsync(IEnumerable<IconColor> values)
{
throw new NotImplementedException();
}
public Task UpdateAsync(IconColor value)
{
throw new NotImplementedException();
}
public Task UpdateOnSubmitAsync(IconColor obj)
{
throw new NotImplementedException();
}
}
}
|
using Terraria;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
namespace DuckingAround.Projectiles.Yoyos.Orbiting.Destiny
{
public class DestinyOrbiting2 : ModProjectile
{
public bool yoyosSpawned;
public int Counter;
public override void SetDefaults()
{
projectile.extraUpdates = 0;
projectile.width = 16;
projectile.height = 16;
projectile.friendly = true;
projectile.melee = true;
projectile.penetrate = -1;
projectile.tileCollide = false;
}
public override void AI()
{
Projectile projectile = Main.projectile[(int)this.projectile.localAI[0]];
++this.projectile.timeLeft;
this.projectile.rotation += 0.5f;
if (!projectile.active || projectile.type != ModContent.ProjectileType<DestinyProj>() || projectile.owner != this.projectile.owner)
{
this.projectile.Kill();
}
else
{
if (this.projectile.owner == Main.myPlayer)
{
float x = 36f;
this.projectile.position = projectile.Center + new Vector2(x, 0.0f).RotatedBy((double)this.projectile.ai[1]);
this.projectile.position.X -= (float)(this.projectile.width / 2);
this.projectile.position.Y -= (float)(this.projectile.height / 2);
this.projectile.ai[1] += 0.1570796f;
if ((double)this.projectile.ai[1] > 3.14159274101257)
{
this.projectile.ai[1] -= 6.283185f;
this.projectile.netUpdate = true;
}
}
this.projectile.damage = projectile.damage;
this.projectile.knockBack = projectile.knockBack;
if (++Counter <= 60)
{
return;
}
Counter = 0;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CC.Web.Dao.Core
{
public interface IRepository<T> where T : class
{
/// <summary>
/// 插入实例
/// </summary>
/// <param name="entity">实例</param>
/// <returns></returns>
Guid Insert(T entity);
/// <summary>
/// 插入多条实例
/// </summary>
/// <param name="entities">实例</param>
/// <returns></returns>
IEnumerable<Guid> Insert(IEnumerable<T> entities);
/// <summary>
/// 删除实例(软)
/// </summary>
/// <param name="Id">唯一标识</param>
/// <returns></returns>
void Delete(Guid Id);
/// <summary>
/// 删除实例(软)
/// </summary>
/// <param name="Ids">唯一标识</param>
/// <returns></returns>
void Delete(IEnumerable<Guid> Ids);
/// <summary>
/// 删除实例
/// </summary>
/// <param name="Id">唯一标识</param>
/// <returns></returns>
void Remove(Guid Id);
/// <summary>
/// 删除多条实例
/// </summary>
/// <param name="Ids">唯一标识</param>
/// <returns></returns>
void Remove(IEnumerable<Guid> Ids);
/// <summary>
/// 更新实例
/// </summary>
/// <param name="entity">实例</param>
void Update(T entity);
/// <summary>
/// 更新实例
/// </summary>
/// <param name="entity">实例</param>
void Update(IEnumerable<T> entity);
/// <summary>
/// 根据主键查询
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
T Find(Guid Ids);
/// <summary>
/// 根据主键查询
/// </summary>
/// <param name="Ids"></param>
/// <returns></returns>
IQueryable<T> Find(IEnumerable<Guid> Ids);
/// <summary>
/// 获取表
/// </summary>
IQueryable<T> Table { get; }
/// <summary>
/// 获取表(不跟踪只适用于查询)
/// </summary>
IQueryable<T> TableNoTracking { get; }
}
}
|
using UnityEngine;
[RequireComponent(typeof(ParticleSystem))]
public class SnowParticleEmitterShaker : MonoBehaviour
{
ParticleSystem m_System;
ParticleSystem.Particle[] m_Particles;
public float m_Drift = 0.01f;
private void Awake()
{
EventManager.Listen("ShakeSnowGlobe", ToggleIndoorOutDoor);
m_Drift = 1000f;
}
private void OnDisable()
{
EventManager.StopListen("ShakeSnowGlobe", ToggleIndoorOutDoor);
}
private void ToggleIndoorOutDoor()
{
jiggleMe = true;
}
bool jiggleMe = false;
private void LateUpdate()
{
if (jiggleMe)
{
InitializeIfNeeded();
int numParticlesAlive = m_System.GetParticles(m_Particles);
for (int i = 0; i < numParticlesAlive; i++)
m_Particles[i].velocity += Vector3.up * m_Drift;
m_System.SetParticles(m_Particles, numParticlesAlive);
jiggleMe = false;
}
}
void InitializeIfNeeded()
{
if (m_System == null)
m_System = GetComponent<ParticleSystem>();
if (m_Particles == null || m_Particles.Length < m_System.maxParticles)
m_Particles = new ParticleSystem.Particle[m_System.maxParticles];
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SCR_MotionSoundSource : MonoBehaviour {
float InitialRadius = 1.0f;
float AmplitudeScalar = 1.0f;
float TargetRadius;
List<GameObject> ObjectsInRange;
SphereCollider SoundTriggerVolume;
// Use this for initialization
void Start ()
{
ObjectsInRange = new List<GameObject> ();
}
// Update is called once per frame
void Update ()
{
}
public void BeginEmitSound(float Amplitude, float Range)
{
SoundTriggerVolume.radius = Range;
Vector3 ObjectOffset;
float IlluminationValue;
foreach (GameObject OtherObject in ObjectsInRange)
{
ObjectOffset = OtherObject.transform.position - gameObject.transform.position;
//IlluminationValue = ((Amplitude*Amplitude) - ObjectOffset.sqrMagnitude) / (Amplitude*Amplitude);
//IlluminationValue = Mathf.Clamp (IlluminationValue, 0, Mathf.Infinity);
//HOW FAR COMPARED TO MAX RANGE
IlluminationValue = (Mathf.Clamp(Range - ObjectOffset.magnitude, 0.0f, Mathf.Infinity)* Amplitude);
//X BY THE APLITUDE
OtherObject.GetComponent<SCR_IlluminationController> ().BeginIllumination(IlluminationValue);
}
}
public void BeginEmitSound2(float Amplitude, float Range)
{
Vector3 HalfExtents = new Vector3 (Range / 2.0f, Range / 2.0f, Range / 2.0f);
Collider[] Overlaps = Physics.OverlapBox (gameObject.transform.position - new Vector3(0.0f,-1.0f, 0.0f), HalfExtents);
foreach (Collider collider in Overlaps)
{
if (!collider.CompareTag ("Illuminable")) {continue;}
float IlluminationScalar = 1 - (((collider.transform.position - gameObject.transform.position).sqrMagnitude) / (Range * Range));
//float IlluminationScalar = 1;
collider.GetComponent<SCR_IlluminationController> ().BeginIllumination (IlluminationScalar*Time.deltaTime);
}
}
void OnTriggerEnter(Collider otherCollider)
{
if (otherCollider.transform.CompareTag ("Illuminable"))
{
ObjectsInRange.Add (otherCollider.gameObject);
}
}
void OnTriggerExit(Collider otherCollider)
{
if (otherCollider.transform.CompareTag ("Illuminable"))
{
ObjectsInRange.Remove (otherCollider.gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Final_Exam
{
class Program
{
static void Main(string[] args)
{
// Q20. Determine GCD or two numbers. Ask user for input.
try
{
int num1, num2;
int GCD = 0;
Console.WriteLine("Enter first Integer: ");
num1 = checked(Convert.ToInt32(Console.ReadLine()));
Console.WriteLine("Enter second Integer: ");
num2 = checked(Convert.ToInt32(Console.ReadLine()));
if (num1 > num2)
{
for (int i = 1; i < num1; i++)
{
if (num1 % i == 0 && num2 % i == 0)
{
GCD = i;
}
}
}
else
{
for (int i = 1; i < num2; i++)
{
if (num1 % i == 0 && num2 % i == 0)
{
GCD = i;
}
}
}
Console.WriteLine($"The Greatest Common Divisor of {num1} and {num2} is {GCD}");
}
catch (FormatException fEx)
{
Console.WriteLine(fEx.Message);
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
finally
{
Console.WriteLine("\nThis program has finally terminated");
}
}
}
}
|
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>
/// AdverseReaction
/// </summary>
[FhirResource("AdverseReaction")]
public partial class AdverseReaction : Resource
{
/// <summary>
/// The severity of an adverse reaction.
/// </summary>
public enum ReactionSeverity
{
Severe, // Severe complications arose due to the reaction
Serious, // Serious inconvience to the subject
Moderate, // Moderate inconvience to the subject
Minor, // Minor inconvience to the subject
}
/// <summary>
/// Conversion of ReactionSeverityfrom and into string
/// <summary>
public static class ReactionSeverityHandling
{
public static bool TryParse(string value, out ReactionSeverity result)
{
result = default(ReactionSeverity);
if( value=="severe")
result = ReactionSeverity.Severe;
else if( value=="serious")
result = ReactionSeverity.Serious;
else if( value=="moderate")
result = ReactionSeverity.Moderate;
else if( value=="minor")
result = ReactionSeverity.Minor;
else
return false;
return true;
}
public static string ToString(ReactionSeverity value)
{
if( value==ReactionSeverity.Severe )
return "severe";
else if( value==ReactionSeverity.Serious )
return "serious";
else if( value==ReactionSeverity.Moderate )
return "moderate";
else if( value==ReactionSeverity.Minor )
return "minor";
else
throw new ArgumentException("Unrecognized ReactionSeverity value: " + value.ToString());
}
}
/// <summary>
/// The type of exposure that resulted in an adverse reaction
/// </summary>
public enum ExposureType
{
Drugadmin, // Drug Administration
Immuniz, // Immunization
Coincidental, // In the same area as the substance
}
/// <summary>
/// Conversion of ExposureTypefrom and into string
/// <summary>
public static class ExposureTypeHandling
{
public static bool TryParse(string value, out ExposureType result)
{
result = default(ExposureType);
if( value=="drugadmin")
result = ExposureType.Drugadmin;
else if( value=="immuniz")
result = ExposureType.Immuniz;
else if( value=="coincidental")
result = ExposureType.Coincidental;
else
return false;
return true;
}
public static string ToString(ExposureType value)
{
if( value==ExposureType.Drugadmin )
return "drugadmin";
else if( value==ExposureType.Immuniz )
return "immuniz";
else if( value==ExposureType.Coincidental )
return "coincidental";
else
throw new ArgumentException("Unrecognized ExposureType value: " + value.ToString());
}
}
/// <summary>
/// null
/// </summary>
[FhirComposite("AdverseReactionSymptomComponent")]
public partial class AdverseReactionSymptomComponent : Element
{
/// <summary>
/// Indicates the specific sign or symptom that was observed
/// </summary>
public CodeableConcept Code { get; set; }
/// <summary>
/// The severity of the sign or symptom
/// </summary>
public Code<AdverseReaction.ReactionSeverity> Severity { get; set; }
}
/// <summary>
/// null
/// </summary>
[FhirComposite("AdverseReactionExposureComponent")]
public partial class AdverseReactionExposureComponent : Element
{
/// <summary>
/// When the exposure occurred
/// </summary>
public FhirDateTime ExposureDate { get; set; }
/// <summary>
/// The type of exposure
/// </summary>
public Code<AdverseReaction.ExposureType> ExposureType { get; set; }
/// <summary>
/// Substance that subject was exposed to
/// </summary>
public ResourceReference Substance { get; set; }
}
/// <summary>
/// When the reaction occurred
/// </summary>
public FhirDateTime ReactionDate { get; set; }
/// <summary>
/// The subject of the adverse reaction
/// </summary>
public ResourceReference Subject { get; set; }
/// <summary>
/// Substance presumed to have caused reaction
/// </summary>
public ResourceReference Substance { get; set; }
/// <summary>
/// To say that a reaction to substance did not occur
/// </summary>
public FhirBoolean DidNotOccurFlag { get; set; }
/// <summary>
/// Who recorded the reaction
/// </summary>
public ResourceReference Recorder { get; set; }
/// <summary>
/// The signs and symptoms that were observed as part of the reaction
/// </summary>
public List<AdverseReactionSymptomComponent> Symptom { get; set; }
/// <summary>
/// An exposure to a substance that preceded a reaction occurrence
/// </summary>
public List<AdverseReactionExposureComponent> Exposure { get; set; }
}
}
|
namespace Athenaeum.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class RemovalOfArmoryCharacter : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.ArmoryCharacters", "CharacterId", "dbo.Characters");
DropIndex("dbo.ArmoryCharacters", new[] { "CharacterId" });
DropTable("dbo.ArmoryCharacters");
}
public override void Down()
{
CreateTable(
"dbo.ArmoryCharacters",
c => new
{
ArmoryCharacterId = c.Int(nullable: false, identity: true),
AchievementPoints = c.Int(nullable: false),
Class = c.String(),
PrimarySpec = c.String(),
SecondarySpec = c.String(),
Rating2v2 = c.Int(nullable: false),
Rating3v3 = c.Int(nullable: false),
Rating5v5 = c.Int(nullable: false),
RatingRbg = c.Int(nullable: false),
CharacterId = c.Int(nullable: false),
})
.PrimaryKey(t => t.ArmoryCharacterId);
CreateIndex("dbo.ArmoryCharacters", "CharacterId");
AddForeignKey("dbo.ArmoryCharacters", "CharacterId", "dbo.Characters", "CharacterId", cascadeDelete: true);
}
}
}
|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Stiig;
public partial class editor : System.Web.UI.UserControl
{
public delegate void ucEventdelegate(string post, string subject);
public event ucEventdelegate OnSubmit;
private int Counter = 1;
protected void Page_Load(object sender, EventArgs e)
{
DataAccessLayer dal = new DataAccessLayer();
Repeater1.DataSource = dal.ExecuteDataTable("SELECT * FROM Smileys");
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label label = ((Label)e.Item.FindControl("Label1"));
label.Text = "";
if (Counter == 1)
{
label.Text = "<tr>";
}
label.Text += "<td><a href=\"javascript:smiley('" + DataBinder.Eval(e.Item.DataItem, "Code").ToString() + "')\"><img src=\"" + ResolveClientUrl("~/images/smileys/") + DataBinder.Eval(e.Item.DataItem, "FileName").ToString() + "\" alt=\"" + DataBinder.Eval(e.Item.DataItem, "Name").ToString() + "\"></a></td>";
if (Counter == 5)
{
label.Text += "</tr>";
Counter = 0;
}
Counter++;
}
else if (e.Item.ItemType == ListItemType.Footer)
{
if (Counter != 5)
{
((Label)e.Item.FindControl("Label2")).Visible = true;
}
}
}
private bool _setfocus = false;
public bool SetFocus
{
get { return _setfocus; }
set
{
txtPost.Focus();
_setfocus = value;
}
}
public string Title
{
get { return lblTitle.Text; }
set { lblTitle.Text = value; }
}
public string SubTitle
{
get { return lblSubTitle.Text; }
set { lblSubTitle.Text = value; }
}
public string Subject
{
get { return txtSubject.Text.Trim(); }
set
{
string subject = value;
subject = subject.Replace("<", "<");
subject = subject.Replace(">", ">");
txtSubject.Text = subject;
}
}
public bool SubjectVisible
{
get
{
return lblSubject.Visible;
}
set
{
txtSubject.Visible = value;
lblSubject.Visible = value;
}
}
public string Post
{
get { return txtPost.Text.Trim(); }
set
{
txtPost.Text = Utilities.HTMLToBB(value);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string subject = txtSubject.Text;
subject = subject.Replace("<", "<");
subject = subject.Replace(">", ">");
OnSubmit(txtPost.Text, subject);
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MessagePayload.cs">
// Copyright (c) 2021 Johannes Deml. All rights reserved.
// </copyright>
// <author>
// Johannes Deml
// public@deml.io
// </author>
// --------------------------------------------------------------------------------------------------------------------
namespace NetworkBenchmark
{
public enum MessagePayload
{
/// <summary>
/// Random bytes that always use the seed of 0
/// They are always the same bytes for a gives message size
/// </summary>
Random,
/// <summary>
/// Each byte is 0x00
/// </summary>
Zeros,
/// <summary>
/// Each byte is 0xff
/// </summary>
Ones
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Misc
{
class CreditCardCheck
{
private static bool LuhnAlgo(char[] creditCardNum)
{
long sumVal = 0;
// start from the end of the string
for (int index = creditCardNum.Length - 1; index >= 0; index--)
{
int intValAtIndex = 0;
try
{
intValAtIndex = ConvertCharToInt(creditCardNum[index]);
}
catch (Exception)
{
return false; // The credit card number contains invalid characters
}
int position = 0;
if(creditCardNum.Length%2==0)
{
// This is the case for visa, discover, mastercard
position = index;
}
else
{
// condition for american express
position = index + 1;
}
if(position % 2 == 0)
{
// Process the even positioned value
int evenIndexVal = intValAtIndex * 2;
if(evenIndexVal >=10)
{
// We need to add the 2 digits individually
sumVal += evenIndexVal % 10;
sumVal += 1;
}
else
{
// add the doubled value
sumVal += evenIndexVal;
}
}
else
{
// add the odd positioned value directly
sumVal += intValAtIndex;
}
}
if(sumVal%10==0)
{
return true; // This is a credit card number
}
else
{
return false; //Not a credit card number
}
}
private static int ConvertCharToInt(char charVal)
{
int intVal = charVal - 48;
if (intVal >= 0 && intVal <= 9)
{
return intVal;
}
else
{
throw new Exception("invalid input");
}
}
public static void TestLuhnAlgo()
{
Console.WriteLine("The number {0} is a visa credit card number {1}", "4539638645089136", LuhnAlgo("4539638645089136".ToCharArray()));
Console.WriteLine("The number {0} is a mastercard credit card number {1}", "5484723447330961", LuhnAlgo("5484723447330961".ToCharArray()));
Console.WriteLine("The number {0} is a discover credit card number {1}", "6011738424345378", LuhnAlgo("6011738424345378".ToCharArray()));
Console.WriteLine("The number {0} is a american express credit card number {1}", "349737169114557", LuhnAlgo("349737169114557".ToCharArray()));
Console.WriteLine("The number {0} is a credit card number {1}", "3497371&69114557", LuhnAlgo("3497371&69114557".ToCharArray()));
Console.WriteLine("The number {0} is a credit card number {1}", "6011738224345378", LuhnAlgo("6011738224345378".ToCharArray()));
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using EdjCase.JsonRpc.Router;
using EdjCase.JsonRpc.Router.Abstractions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FiiiChain.DTO;
using FiiiChain.Framework;
using FiiiChain.Business;
using FiiiChain.Messages;
using FiiiChain.Consensus;
using FiiiChain.Entities;
using Microsoft.Extensions.Caching.Memory;
namespace FiiiChain.Wallet.API
{
public class WalletController : BaseRpcController
{
private IMemoryCache _cache;
public WalletController(IMemoryCache memoryCache) { _cache = memoryCache; }
public IRpcMethodResult BackupWallet(string targetAddress)
{
try
{
WalletComponent component = new WalletComponent();
SettingComponent settingComponent = new SettingComponent();
Setting setting = settingComponent.GetSetting();
if (setting.Encrypt)
{
if(string.IsNullOrEmpty(_cache.Get<string>("WalletPassphrase")))
{
throw new CommonException(ErrorCode.Service.Wallet.WALLET_HAS_BEEN_LOCKED);
}
component.BackupWallet(targetAddress, _cache.Get<string>("WalletPassphrase"));
}
else
{
component.BackupWallet(targetAddress, null);
}
return Ok();
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult RestoreWalletBackup(string backupFilePaths, string passphrase = null)
{
try
{
var result = false;
WalletComponent component = new WalletComponent();
result = component.RestoreWalletBackup(backupFilePaths, passphrase);
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult DumpPrivKey(string address)
{
try
{
var account = new AccountComponent().GetAccountById(address);
if(account != null)
{
return Ok(this.decryptPrivateKey(account.PrivateKey));
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult EncryptWallet(string passphrase)
{
try
{
var result = false;
var settting = new SettingComponent().GetSetting();
if(settting.Encrypt)
{
LogHelper.Error("Error occured in EncrypWallet API");
throw new CommonException(ErrorCode.Service.Wallet.CAN_NOT_ENCRYPT_AN_ENCRYPTED_WALLET);
}
result = new WalletComponent().EncryptWallet(passphrase);
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult WalletLock()
{
try
{
var settting = new SettingComponent().GetSetting();
if (!settting.Encrypt)
{
return Ok();
}
_cache.Remove("WalletPassphrase");
return Ok();
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult WalletPassphrase(string passphrase)
{
try
{
var settting = new SettingComponent().GetSetting();
if (!settting.Encrypt)
{
LogHelper.Error("Error occured in WalletPassphrase API");
throw new CommonException(ErrorCode.Service.Wallet.CAN_NOT_ENCRYPT_AN_ENCRYPTED_WALLET);
}
var result = false;
if(new WalletComponent().CheckPassword(passphrase))
{
_cache.Set<string>("WalletPassphrase", passphrase,new MemoryCacheEntryOptions()
{
SlidingExpiration = new TimeSpan(0,5,0)
});
result = true;
}
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult WalletPassphraseChange(string currentPassphrase, string newPassphrase)
{
try
{
var settting = new SettingComponent().GetSetting();
if (!settting.Encrypt)
{
throw new CommonException(ErrorCode.Service.Wallet.CAN_NOT_CHANGE_PASSWORD_IN_AN_UNENCRYPTED_WALLET);
}
WalletComponent wc = new WalletComponent();
wc.ChangePassword(currentPassphrase, newPassphrase);
_cache.Remove("WalletPassphrase");
return Ok();
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
private string decryptPrivateKey(string privateKey)
{
var setting = new SettingComponent().GetSetting();
if (setting.Encrypt)
{
if (!string.IsNullOrWhiteSpace(_cache.Get<string>("WalletPassphrase")))
{
try
{
return AES128.Decrypt(privateKey, _cache.Get<string>("WalletPassphrase"));
}
catch
{
throw new CommonException(ErrorCode.Service.Transaction.WALLET_DECRYPT_FAIL);
}
}
else
{
throw new CommonException(ErrorCode.Service.Transaction.WALLET_DECRYPT_FAIL);
}
}
else
{
return privateKey;
}
}
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.ML;
using Microsoft.Extensions.Logging;
using System.Reflection;
using System.ComponentModel;
using Djkormo.Web;
namespace Djkormo.Web
{
[Route("api/[controller]")]
[ApiController]
public class PredictController : ControllerBase
{
private readonly PredictionEnginePool<ModelInput, ModelOutput> _predictionEnginePool;
//The predictionEnginePool is injected through the constructor
public PredictController(PredictionEnginePool<ModelInput,ModelOutput> predictionEnginePool)
{
_predictionEnginePool = predictionEnginePool;
}
// POST api/predict/model
[HttpPost]
[Route("model")]
public ActionResult<string> Post([FromBody] ModelInput input)
{
if(!ModelState.IsValid)
{
Console.WriteLine("Bad request");
return BadRequest();
}
Console.WriteLine("Beginning prediction...");
Console.WriteLine("ModelInput class:");
Type tinput = input.GetType();
PropertyInfo [] pin = tinput.GetProperties();
foreach (PropertyInfo p in pin)
{
System.Console.WriteLine("{0} : {1} : {2}",p.Name ,p.GetValue(input), p.ToString() );
}
// Getting output from ML model input class(ModelInput) -> prediction class (ModelOutput)
ModelOutput prediction = _predictionEnginePool.Predict(input);
Console.WriteLine("ModelOutput class: ");
Type toutput = prediction.GetType();
PropertyInfo [] pout = toutput.GetProperties();
foreach (PropertyInfo p in pout)
{
System.Console.WriteLine("{0} : {1} : {2}",p.Name ,p.GetValue(prediction),p.ToString() );
}
string output = prediction.Prediction;
Console.WriteLine("Ending prediction...");
// send output value
return Ok(output);
}
}
} |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace AutoClicker
{
public partial class Form1 : Form
{
private GlobalHotkey ghkLeft;
private GlobalHotkey ghkRight;
private Boolean isLeftActive = false;
private Boolean isRightActive = false;
public enum MouseButton
{
LEFT,
RIGHT
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ghkLeft = new GlobalHotkey(GlobalHotkey.CTRL + GlobalHotkey.ALT, Keys.L, this);
ghkRight = new GlobalHotkey(GlobalHotkey.CTRL + GlobalHotkey.ALT, Keys.R, this);
ghkLeft.Register();
ghkRight.Register();
}
private Keys GetKey(IntPtr LParam)
{
return (Keys)(LParam.ToInt32() >> 16);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == GlobalHotkey.WM_HOTKEY_MSG_ID)
{
switch (GetKey(m.LParam))
{
case Keys.L:
Lkey();
break;
case Keys.R:
RKey();
break;
}
}
base.WndProc(ref m);
}
private void Lkey()
{
isLeftActive = !isLeftActive;
if (isLeftActive)
{
if (cbxMantenerIzquierdo.Checked)
{
SetClickState(GlobalMouse.MOUSEEVENTF_LEFTDOWN);
}
else
{
timerIzquierdo.Start();
}
lblEstadoIzquierdo.Text = "Activo";
}
else
{
if (cbxMantenerIzquierdo.Checked)
{
SetClickState(GlobalMouse.MOUSEEVENTF_LEFTUP);
}
else
{
timerIzquierdo.Stop();
}
lblEstadoIzquierdo.Text = "Inactivo";
}
}
private void RKey()
{
isRightActive = !isRightActive;
if (isRightActive)
{
if (cbxMantenerDerecho.Checked)
{
SetClickState(GlobalMouse.MOUSEEVENTF_RIGHTDOWN);
}
else
{
timerDerecho.Start();
}
lblEstadoDerecho.Text = "Activo";
}
else
{
if (cbxMantenerDerecho.Checked)
{
SetClickState(GlobalMouse.MOUSEEVENTF_RIGHTUP);
}
else
{
timerDerecho.Stop();
}
lblEstadoDerecho.Text = "Inactivo";
}
}
private void SetClickState(int clickState)
{
Point currect = new Point();
GlobalMouse.GetCursorPos(ref currect);
GlobalMouse.mouse_event(clickState, currect.X, currect.Y, 0, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ghkLeft.Unregiser();
ghkRight.Unregiser();
AutoClicker.Visible = false;
}
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
Hide();
AutoClicker.Visible = true;
}
}
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
Show();
this.WindowState = FormWindowState.Normal;
AutoClicker.Visible = false;
}
private int lCurrTicks = 0;
private void timerIzquierdo_Tick(object sender, EventArgs e)
{
if(lCurrTicks == 0)
{
SetClickState(GlobalMouse.MOUSEEVENTF_LEFTDOWN);
}
else if(lCurrTicks == NudIzquierdoTiempoPorClicks.Value)
{
SetClickState(GlobalMouse.MOUSEEVENTF_LEFTUP);
}
else if(lCurrTicks == NudIzquierdoTiempoPorClicks.Value + NudIzquierdoTiempoEntreClicks.Value)
{
lCurrTicks = 0;
return;
}
lCurrTicks += 1;
}
private int rCurrTicks = 0;
private void timerDerecho_Tick(object sender, EventArgs e)
{
if (rCurrTicks == 0)
{
SetClickState(GlobalMouse.MOUSEEVENTF_RIGHTDOWN);
}
else if (rCurrTicks == NudDerechoTiempoPorClicks.Value)
{
SetClickState(GlobalMouse.MOUSEEVENTF_RIGHTUP);
}
else if (rCurrTicks == NudDerechoTiempoPorClicks.Value + NudDerechoTiempoEntreClicks.Value)
{
rCurrTicks = 0;
return;
}
rCurrTicks += 1;
}
private void cbxMantenerDerecho_CheckedChanged(object sender, EventArgs e)
{
PanelDerecho.Enabled = !cbxMantenerDerecho.Checked;
}
private void cbxMantenerIzquierdo_CheckedChanged(object sender, EventArgs e)
{
PanelIzquierdo.Enabled = !cbxMantenerIzquierdo.Checked;
}
private void toolStripMenuRestore_Click(object sender, EventArgs e)
{
Show();
this.WindowState = FormWindowState.Normal;
AutoClicker.Visible = false;
}
private void toolStripMenuClose_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AdventOfCode2020
{
// https://adventofcode.com/2020/day/4
// Note only solveing part 2 right now.
public class Day04
{
private IList<string> data;
private IList<Dictionary<string, string>> passports = new List<Dictionary<string, string>>();
private int vaildPassports = 0;
// There was no trailing blank line, so i added one...
public string Run()
{
this.data = InputHelper.ReadOutEachLine("Day4Input");
var currentItem = new Dictionary<string, string>();
for(int rowNumber = 0; rowNumber < data.Count; rowNumber++)
{
if (data[rowNumber] == string.Empty)
{
this.ReviewPassport(currentItem);
currentItem = new Dictionary<string, string>();
continue;
}
foreach (var rowItem in data[rowNumber].Split(" "))
{
var subItem = rowItem.Split(":");
currentItem[subItem[0]] = subItem[1];
}
// "if" the last row is not a blank line...
if(rowNumber == data.Count - 1)
{
this.ReviewPassport(currentItem);
currentItem = new Dictionary<string, string>();
}
}
return vaildPassports.ToString();
}
private void ReviewPassport(Dictionary<string, string> currentItem)
{
bool vaild = true;
// byr (Birth Year) - four digits; at least 1920 and at most 2002.
if (!currentItem.TryGetInt("byr", out var birthYear) || birthYear < 1920 || birthYear > 2002)
{
vaild = false;
}
// iyr (Issue Year) - four digits; at least 2010 and at most 2020.
if (!currentItem.TryGetInt("iyr", out var issueYear) || issueYear < 2010 || issueYear > 2020)
{
vaild = false;
}
// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
if (!currentItem.TryGetInt("eyr", out var experationYear) || experationYear < 2020 || experationYear > 2030)
{
vaild = false;
}
//* hgt (Height) - a number followed by either cm or in
if (currentItem.TryGetValue("hgt", out var heightString))
{
//* If cm, the number must be at least 150 and at most 193.
if (heightString.Contains("cm"))
{
if (int.TryParse(heightString.Replace("cm", ""), out var heightInCm))
{
if(heightInCm < 150 || heightInCm > 193)
{
vaild = false;
}
}
else
{
vaild = false;
}
}
else
{
//* If in, the number must be at least 59 and at most 76.
if (int.TryParse(heightString.Replace("in", ""), out var heightInIn))
{
if (heightInIn < 59 || heightInIn > 76)
{
vaild = false;
}
}
else
{
vaild = false;
}
}
}
else
{
vaild = false;
}
//* hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
Regex hairColorRegex = new Regex(@"^[#]{1}[0-9a-f]{6}$");
if (!currentItem.TryGetValue("hcl", out var hairColor) || !hairColorRegex.IsMatch(hairColor))
{
vaild = false;
}
//* ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
var validEyes = new List<string> { "amb", "blu", "brn", "gry", "grn", "hzl", "oth" };
if (!currentItem.TryGetValue("ecl", out var eyeColor) || !validEyes.Contains(eyeColor))
{
vaild = false;
}
//* pid (Passport ID) - a nine-digit number, including leading zeroes.
Regex passportIdRegex = new Regex(@"^[0-9]{9}$");
if(!currentItem.TryGetValue("pid", out var passPortId) || !passportIdRegex.IsMatch(passPortId))
{
vaild = false;
}
this.vaildPassports += vaild ? 1 : 0;
this.passports.Add(currentItem);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Character : MonoBehaviour
{
public GridElement m_GridElement;
public Transform m_DestinationHolder;
public GameObject m_DestinationPrefab;
public Transform m_PathHolder;
public GameObject[] m_PathPrefabs;
public GameObject m_SelectableElem;
public HealthBar m_HealthBar;
List<Destination> m_vAvailableDestinations;
int m_iMouvementPoints = 0;
bool m_bNavigation = false;
bool m_bSwimming = false;
bool m_bClimbing = false;
bool m_bMovementDone = false;
bool m_bActionDone = false;
// movement
bool m_bMoving = false;
private float m_fSpeed = 4.0f;
private float m_fStartTime;
private Vector3 m_vStartPosition;
private Vector3 m_vEndPosition;
Destination m_OverDestination = null;
Destination m_Destination = null;
Stack<Destination> m_PathToDestination = new Stack<Destination>();
Destination m_CurrentPathDestination = null;
private List<Character> m_vCharacterList;
private worldMap m_WorldMap;
Destination m_LastPosition = null;
// player
public int m_iTeam = 0;
public int m_iPlayerID = 0;
// actions
Weapon m_Weapon;
Action m_SelectedAction = Action.None;
Classes m_Class = Classes.Marauder;
bool m_bActing = false;
Character m_Target = null;
int m_iAttackCount;
float m_fAttackTimer = 0.0f;
// statistics
int m_iVitality = 10;
int m_iStrength = 10;
int m_iAgility = 10;
int m_iIntelligence = 10;
int m_iSpirit = 10;
int m_iArmor = 1;
int m_iResistance = 1;
int m_iDodge = 1;
int m_iLuck = 1;
int m_iHealthPoint = 10;
public bool IsMoving()
{
return m_bMoving;
}
public bool IsActing()
{
return m_bActing;
}
public bool IsTurnFinish()
{
return m_bActionDone && !m_bActing;
}
public bool CanMove()
{
return !m_bMovementDone;
}
public void ResetTurn()
{
m_bActionDone = false;
m_bMovementDone = false;
ComputeAvailableDestinations();
m_SelectableElem.SetActive(true);
}
public void SetAttackFinished()
{
m_bActing = false;
}
void Update()
{
if(m_bMoving)
{
float t = (Time.time - m_fStartTime) * m_fSpeed;
transform.position = Vector3.Lerp(m_vStartPosition, m_vEndPosition, t);
if (t >= 1.0f)
{
if(m_PathToDestination.Count > 0)
{
m_CurrentPathDestination = m_PathToDestination.Pop();
GetComponent<GridElement>().m_iX = m_CurrentPathDestination.m_iX;
GetComponent<GridElement>().m_iY = m_CurrentPathDestination.m_iY;
m_fStartTime = Time.time;
m_vStartPosition = transform.position;
m_vEndPosition = new Vector3(m_CurrentPathDestination.m_iX * 10, m_CurrentPathDestination.m_iY * 10, -0.05f);
}
else
{
/*GetComponent<GridElement>().m_iX = m_CurrentPathDestination.m_iX;
GetComponent<GridElement>().m_iY = m_CurrentPathDestination.m_iY;*/
m_bMoving = false;
m_CurrentPathDestination = null;
m_bMovementDone = true;
//m_bActionDone = true;
}
}
}
if (m_Target != null)
{
if (m_iAttackCount > 0)
{
if (m_fAttackTimer <= 0.0f)
{
m_iAttackCount--;
AttackTarget(m_Target);
if(m_iAttackCount == 0)
{
if (!m_bActing)
{
m_Target.SetAttackFinished();
}
else
{
m_Target.PrepareAttack(this);
}
}
else
{
m_fAttackTimer = 1.0f;
}
}
else
{
m_fAttackTimer -= Time.deltaTime;
}
}
}
}
public void Init(int _iMouvementPoints, int _iPlayerID, int _iTeam, List<Character> _vCharaterList, worldMap _worldMap, bool _bSwimming = false, bool _bClimbing = false, bool _bNavigation = false)
{
m_iMouvementPoints = _iMouvementPoints;
m_iPlayerID = _iPlayerID;
m_iTeam = _iTeam;
m_vCharacterList = _vCharaterList;
m_WorldMap = _worldMap;
m_bSwimming = _bSwimming;
m_bClimbing = _bClimbing;
m_bNavigation = _bNavigation;
m_vAvailableDestinations = new List<Destination>();
m_Weapon = new Weapon();
m_Weapon.Init(2, 3, 1, 1.0f, Caracteristic.Agility);
Classes Class = (Classes)Random.Range(0, 11);
ClassBaseStatistics stats = gameDesignVariables.Instance.GetClassStatistics(Class);
Debug.Log(Class);
m_iVitality = stats.m_iVitality;
m_iStrength = stats.m_iStrength;
m_iAgility = stats.m_iAgility;
m_iIntelligence = stats.m_iIntelligence;
m_iSpirit = stats.m_iSpirit;
m_iArmor = stats.m_iArmor;
m_iResistance = stats.m_iResistance;
m_iLuck = stats.m_iLuck;
m_iDodge = stats.m_iAgility + Mathf.RoundToInt(stats.m_iLuck / 2);
m_iHealthPoint = Mathf.RoundToInt(m_iVitality * 1.1f);
m_HealthBar.Init(m_iHealthPoint);
}
public void ComputeAvailableDestinations()
{
//float beginTime = Time.realtimeSinceStartup;
m_vAvailableDestinations.Clear();
Destination Origin = new Destination(m_GridElement.m_iX, m_GridElement.m_iY, m_iMouvementPoints);
List<Destination> vOldDestinations = new List<Destination>();
vOldDestinations.Add(Origin);
int[,] _tTerrainInfos = m_WorldMap.GetTerrainInfos();
int iMapLimitX = m_WorldMap.GetMapWidth();
int iMapLimitY = m_WorldMap.GetMapHeight();
while (vOldDestinations.Count > 0)
{
List<Destination> vNewDestinations = new List<Destination>();
foreach (Destination dest in vOldDestinations)
{
for (int i = 0; i < 4; i++)
{
int iNewX = dest.m_iX;
int iNewY = dest.m_iY;
bool ok = false;
if (i == 0)
{
if (dest.m_iX > 0)
{
iNewX = dest.m_iX - 1;
ok = true;
}
}
else if (i == 1)
{
if (dest.m_iX < iMapLimitX - 1)
{
iNewX = dest.m_iX + 1;
ok = true;
}
}
else if (i == 2)
{
if (dest.m_iY > 0)
{
iNewY = dest.m_iY - 1;
ok = true;
}
}
else if (i == 3)
{
if (dest.m_iY < iMapLimitY - 1)
{
iNewY = dest.m_iY + 1;
ok = true;
}
}
if (ok)
{
Destination newDestination = new Destination(iNewX, iNewY, 0, dest);
bool onAnotherCharacter = false;
// do not show destinations where another character is
Destination otherCharDestination = new Destination(0, 0, 0);
int iOtherCharTeam = 0;
foreach (Character character in m_vCharacterList)
{
otherCharDestination.m_iX = character.m_GridElement.m_iX;
otherCharDestination.m_iY = character.m_GridElement.m_iY;
if (newDestination == otherCharDestination)
{
iOtherCharTeam = character.m_iTeam;
onAnotherCharacter = true;
break;
}
}
if (newDestination != dest.m_Previous && (iOtherCharTeam == m_iTeam || !onAnotherCharacter))
{
int iTerrainType = _tTerrainInfos[iNewX, iNewY];
int iMPRest = computeCost(iTerrainType, dest.m_iMouvementPoints);
newDestination.m_iMouvementPoints = iMPRest;
if (iMPRest >= 0)
{
Destination EquivalentDestination = m_vAvailableDestinations.Find(destination => destination == newDestination);
if (EquivalentDestination != null)
{
if (newDestination > EquivalentDestination)
{
m_vAvailableDestinations.Remove(EquivalentDestination);
m_vAvailableDestinations.Add(newDestination);
vNewDestinations.Add(newDestination);
}
}
else
{
m_vAvailableDestinations.Add(newDestination);
vNewDestinations.Add(newDestination);
}
}
}
}
}
}
vOldDestinations = vNewDestinations;
}
//Debug.Log(m_vDestinations.Count);
/*foreach (Destination dest in m_vDestinations)
{
Debug.Log(dest.ToString());
}*/
//Debug.Log(Time.realtimeSinceStartup - beginTime);
}
int computeCost(int _iTerrainId, int _iMP)
{
if(_iTerrainId == 2 && !m_bNavigation)
{
return -1;
}
if(_iTerrainId == 4 && !m_bClimbing)
{
return -1;
}
if(_iTerrainId >= 13 && _iTerrainId <= 16 && !m_bSwimming)
{
return -1;
}
return _iMP - m_WorldMap.GetTerrainCost(_iTerrainId);
}
public void ShowDestinations()
{
if (!m_bMovementDone)
{
m_SelectableElem.SetActive(false);
foreach (Destination dest in m_vAvailableDestinations)
{
bool onAnotherCharacter = false;
// do not show destinations where another character is
Destination newDestination = new Destination(0, 0, 0);
foreach (Character character in m_vCharacterList)
{
GridElement elem = character.GetComponent<GridElement>();
newDestination.m_iX = elem.m_iX;
newDestination.m_iY = elem.m_iY;
if(dest == newDestination)
{
onAnotherCharacter = true;
break;
}
}
if(!onAnotherCharacter)
{
GameObject newDestinationGridElement = (GameObject)Instantiate(m_DestinationPrefab, new Vector3(dest.m_iX * 10, dest.m_iY * 10, -0.04f), Quaternion.identity);
newDestinationGridElement.GetComponent<GridElement>().m_iX = dest.m_iX;
newDestinationGridElement.GetComponent<GridElement>().m_iY = dest.m_iY;
newDestinationGridElement.GetComponent<GridElement>().m_iLayer = 10;
newDestinationGridElement.transform.SetParent(m_DestinationHolder);
}
}
}
}
public void HideDestinations()
{
foreach (Transform child in m_DestinationHolder)
{
GameObject.Destroy(child.gameObject);
ClearPath();
}
}
public void SetOverDestination(int _iX, int _iY)
{
Destination OverDestination = m_vAvailableDestinations.Find(destination => destination == new Destination(_iX, _iY, 0));
if(OverDestination != m_OverDestination)
{
m_OverDestination = OverDestination;
ShowPath();
}
}
private void ShowPath()
{
ClearPath();
Destination previousDestination = m_OverDestination.m_Previous;
Destination nextDestination = m_OverDestination;
int iRotation = 0;
int iType = 2;
if(previousDestination.m_iX - nextDestination.m_iX == 1)
{
iRotation = 90;
}
else if (previousDestination.m_iX - nextDestination.m_iX == -1)
{
iRotation = 270;
}
else if (previousDestination.m_iY - nextDestination.m_iY == 1)
{
iRotation = 180;
}
GameObject newEndPathGridElement = (GameObject)Instantiate(m_PathPrefabs[iType], new Vector3(m_OverDestination.m_iX * 10, m_OverDestination.m_iY * 10, -0.05f), Quaternion.identity);
newEndPathGridElement.transform.Rotate(Vector3.forward, iRotation);
newEndPathGridElement.transform.SetParent(m_PathHolder);
while(previousDestination.m_Previous != null)
{
iRotation = 0;
iType = 0;
if (previousDestination.m_iX - nextDestination.m_iX == 1)
{
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == 1)
{
iRotation = 90;
}
if (previousDestination.m_Previous.m_iY - previousDestination.m_iY == 1)
{
iRotation = 180;
iType = 1;
}
if (previousDestination.m_Previous.m_iY - previousDestination.m_iY == -1)
{
iRotation = 270;
iType = 1;
}
}
else if (previousDestination.m_iX - nextDestination.m_iX == -1)
{
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == -1)
{
iRotation = 90;
}
if (previousDestination.m_Previous.m_iY - previousDestination.m_iY == 1)
{
iRotation = 90;
iType = 1;
}
if (previousDestination.m_Previous.m_iY - previousDestination.m_iY == -1)
{
iType = 1;
}
}
else if (previousDestination.m_iY - nextDestination.m_iY == 1)
{
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == -1)
{
iRotation = 270;
iType = 1;
}
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == 1)
{
iRotation = 0;
iType = 1;
}
}
else if (previousDestination.m_iY - nextDestination.m_iY == -1)
{
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == -1)
{
iRotation = 180;
iType = 1;
}
if (previousDestination.m_Previous.m_iX - previousDestination.m_iX == 1)
{
iRotation = 90;
iType = 1;
}
}
GameObject newPathGridElement = (GameObject)Instantiate(m_PathPrefabs[iType], new Vector3(previousDestination.m_iX * 10, previousDestination.m_iY * 10, -0.05f), Quaternion.identity);
newPathGridElement.transform.Rotate(Vector3.forward, iRotation);
newPathGridElement.transform.SetParent(m_PathHolder);
nextDestination = previousDestination;
previousDestination = previousDestination.m_Previous;
}
/*GameObject newPathEndGridElement = (GameObject)Instantiate(m_PathPrefabs[0], new Vector3(previousDestination.m_iX * 10, previousDestination.m_iY * 10, -0.05f), Quaternion.identity);
newPathEndGridElement.transform.SetParent(m_PathHolder);*/
}
private void ClearPath()
{
foreach (Transform child in m_PathHolder)
{
GameObject.Destroy(child.gameObject);
}
}
[RPC]
void StartPath()
{
m_PathToDestination.Clear();
}
[RPC]
void AddPathDestination(int _iX, int _iY)
{
Destination newDestination = new Destination(_iX, _iY, 0);
m_PathToDestination.Push(newDestination);
}
[RPC]
void EndPath()
{
m_CurrentPathDestination = m_PathToDestination.Pop();
GetComponent<GridElement>().m_iX = m_CurrentPathDestination.m_iX;
GetComponent<GridElement>().m_iY = m_CurrentPathDestination.m_iY;
m_fStartTime = Time.time;
m_vStartPosition = transform.position;
m_vEndPosition = new Vector3(m_CurrentPathDestination.m_iX * 10, m_CurrentPathDestination.m_iY * 10, -0.05f);
m_bMoving = true;
}
public bool SetDestination(int _iX, int _iY)
{
m_SelectedAction = Action.None;
m_PathToDestination.Clear();
if (Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("StartPath", RPCMode.Others);
}
m_Destination = m_vAvailableDestinations.Find(destination => destination == new Destination(_iX, _iY, 0));
if (m_Destination != null)
{
m_LastPosition = new Destination(m_GridElement.m_iX, m_GridElement.m_iY, 0);
m_PathToDestination.Push(m_Destination);
if (Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("AddPathDestination", RPCMode.Others, m_Destination.m_iX, m_Destination.m_iY);
}
Destination previousDestination = m_Destination.m_Previous;
while (previousDestination.m_Previous != null)
{
m_PathToDestination.Push(previousDestination);
if(Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("AddPathDestination", RPCMode.Others, previousDestination.m_iX, previousDestination.m_iY);
}
previousDestination = previousDestination.m_Previous;
}
m_CurrentPathDestination = m_PathToDestination.Pop();
GetComponent<GridElement>().m_iX = m_CurrentPathDestination.m_iX;
GetComponent<GridElement>().m_iY = m_CurrentPathDestination.m_iY;
HideDestinations();
m_fStartTime = Time.time;
m_vStartPosition = transform.position;
m_vEndPosition = new Vector3(m_CurrentPathDestination.m_iX * 10, m_CurrentPathDestination.m_iY * 10, -0.05f);
m_bMoving = true;
if (Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("EndPath", RPCMode.Others);
}
}
return m_bMoving;
}
// Action management
public List<Action> getActions()
{
List<Action> Actions = new List<Action>();
foreach(Character character in m_vCharacterList)
{
if(character.m_iTeam != m_iTeam)
{
int distance = Mathf.Abs(character.GetComponent<GridElement>().m_iX - GetComponent<GridElement>().m_iX) + Mathf.Abs(character.GetComponent<GridElement>().m_iY - GetComponent<GridElement>().m_iY);
if(distance >= m_Weapon.m_iMinRange && distance <= m_Weapon.m_iMaxRange)
{
Debug.Log("attack possible");
Actions.Add(Action.Attack);
break;
}
}
}
return Actions;
}
public void ShowActiontTargets(Action _Action)
{
m_SelectedAction = _Action;
int iMinRange = 0;
int iMaxRange = 0;
bool allyAction = false;
if (_Action == Action.Attack)
{
iMinRange = m_Weapon.m_iMinRange;
iMaxRange = m_Weapon.m_iMaxRange;
}
foreach (Character character in m_vCharacterList)
{
if ((character.m_iTeam != m_iTeam && !allyAction) || (character.m_iTeam == m_iTeam && allyAction))
{
GridElement characterGridElem = character.GetComponent<GridElement>();
int distance = Mathf.Abs(characterGridElem.m_iX - GetComponent<GridElement>().m_iX) + Mathf.Abs(characterGridElem.m_iY - GetComponent<GridElement>().m_iY);
if (distance >= iMinRange && distance <= iMaxRange)
{
GameObject newTargetGridElement = (GameObject)Instantiate(m_DestinationPrefab, new Vector3(characterGridElem.m_iX * 10, characterGridElem.m_iY * 10, -0.04f), Quaternion.identity);
if (allyAction)
{
newTargetGridElement.GetComponent<Renderer>().material.color = new Color(0,1,0,0.36f);
}
else
{
newTargetGridElement.GetComponent<Renderer>().material.color = new Color(1, 0, 0, 0.36f);
}
newTargetGridElement.GetComponent<GridElement>().m_iX = characterGridElem.m_iX;
newTargetGridElement.GetComponent<GridElement>().m_iY = characterGridElem.m_iY;
newTargetGridElement.GetComponent<GridElement>().m_iLayer = 10;
newTargetGridElement.transform.SetParent(m_DestinationHolder);
}
}
}
}
public void Act(int _iPosX, int _iPosY)
{
if(m_SelectedAction != Action.None)
{
if(m_SelectedAction == Action.Attack)
{
Character target = null;
foreach (Character character in m_vCharacterList)
{
GridElement characterGridElem = character.GetComponent<GridElement>();
if(characterGridElem.m_iX == _iPosX && characterGridElem.m_iY == _iPosY)
{
target = character;
break;
}
}
if (target != null)
{
m_bActing = true;
PrepareAttack(target);
}
}
else
{
m_SelectedAction = Action.None;
}
m_bActionDone = true;
HideDestinations();
m_LastPosition = null;
}
}
public void PrepareAttack(Character _target)
{
m_iAttackCount = Mathf.Max(1, Mathf.RoundToInt(m_iAgility * m_Weapon.m_iSpeed) / 30);
if(m_bActing)
{
m_fAttackTimer = 0.0f;
}
else
{
m_fAttackTimer = 1.0f;
}
m_Target = _target;
}
void AttackTarget(Character _target)
{
int iAttackDamages = 0;
bool bMagicAttack = false;
if (m_Weapon.m_UsedCaracteristic == Caracteristic.Strength)
{
iAttackDamages = Mathf.RoundToInt(m_iStrength * m_Weapon.m_fDamageMultiplier);
}
else if (m_Weapon.m_UsedCaracteristic == Caracteristic.Agility)
{
iAttackDamages = Mathf.RoundToInt(m_iAgility * m_Weapon.m_fDamageMultiplier);
}
else if (m_Weapon.m_UsedCaracteristic == Caracteristic.Intelligence)
{
iAttackDamages = Mathf.RoundToInt(m_iIntelligence * m_Weapon.m_fDamageMultiplier);
bMagicAttack = true;
}
else if (m_Weapon.m_UsedCaracteristic == Caracteristic.Spirit)
{
iAttackDamages = Mathf.RoundToInt(m_iSpirit * m_Weapon.m_fDamageMultiplier);
bMagicAttack = true;
}
if (Random.Range(0, 100) < (m_iLuck * 2))
{
iAttackDamages *= 2;
}
_target.BeingAttacked(iAttackDamages, bMagicAttack);
}
public void BeingAttacked(int _iAttackDamages, bool _bMagicAttack)
{
if(Random.Range(0,100) < m_iDodge)
{
Debug.Log("Player " + m_iPlayerID + " dodge the attack");
return;
}
if (_bMagicAttack)
{
_iAttackDamages -= m_iResistance;
}
else
{
_iAttackDamages -= m_iArmor;
}
if (_iAttackDamages <= 0)
{
Debug.Log("Player " + m_iPlayerID + " blocked the attack");
return;
}
Debug.Log("Player " + m_iPlayerID + " takes : " + _iAttackDamages + (_bMagicAttack ? " magical " : " physical") + " damages");
if (Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("UpdateHealthPoint", RPCMode.All, -_iAttackDamages);
}
else
{
UpdateHealthPoint(-_iAttackDamages);
}
}
public void UpdateHealthPoint(int _iHealthPointChange)
{
m_iHealthPoint += _iHealthPointChange;
if (m_iHealthPoint < 0)
{
m_iHealthPoint = 0;
}
m_HealthBar.SetHealthPoints(m_iHealthPoint);
}
public void EndMove()
{
m_bMovementDone = true;
}
public void Cancel()
{
if(!m_bActionDone)
{
m_bMoving = false;
m_CurrentPathDestination = null;
m_bMovementDone = false;
if (m_LastPosition != null)
{
m_PathToDestination.Clear();
if (Network.isClient || Network.isServer)
{
GetComponent<NetworkView>().RPC("StartPath", RPCMode.Others);
GetComponent<NetworkView>().RPC("AddPathDestination", RPCMode.Others, m_LastPosition.m_iX, m_LastPosition.m_iY);
GetComponent<NetworkView>().RPC("EndPath", RPCMode.Others);
}
transform.position = new Vector3(m_LastPosition.m_iX * 10, m_LastPosition.m_iY * 10, -0.05f);
GetComponent<GridElement>().m_iX = m_LastPosition.m_iX;
GetComponent<GridElement>().m_iY = m_LastPosition.m_iY;
}
}
}
public void Wait()
{
m_bActionDone = true;
m_CurrentPathDestination = null;
m_LastPosition = null;
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using TruckPad.Services.Models;
using TruckPad.Services.Repository;
namespace TruckPad.Services.Controllers
{
[Route("api/Motoristas")]
[ApiController]
public class MotoristasController : ControllerBase
{
private readonly IMotoristaRepository motoristaRepository;
public MotoristasController(IMotoristaRepository _motoristaRepository)
{
motoristaRepository = _motoristaRepository;
}
// GET: api/Motoristas/GetMotoristas
[HttpGet]
[Route("GetMotoristas")]
public async Task<IActionResult> GetMotoristas()
{
try
{
var motoristas = await motoristaRepository.GetMotoristas();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotorista/1
[HttpGet]
[Route("GetMotorista")]
public async Task<IActionResult> GetMotorista(int? idMotorista)
{
if (idMotorista == null)
{
return BadRequest();
}
try
{
var motorista = await motoristaRepository.GetMotorista(idMotorista);
if (motorista == null)
{
return NotFound();
}
return Ok(motorista);
}
catch (Exception)
{
return BadRequest();
}
}
// PUT: api/Motoristas/UpdateMotorista
[HttpPut]
[Route("UpdateMotorista")]
public async Task<IActionResult> PutMotorista([FromBody]Motorista motorista)
{
if (ModelState.IsValid)
{
try
{
await motoristaRepository.PutMotorista(motorista);
return Ok();
}
catch (Exception ex)
{
if (ex.GetType().FullName == "Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException")
{
return NotFound();
}
return BadRequest();
}
}
return BadRequest();
}
// POST: api/Motoristas/AddMotorista
[HttpPost]
[Route("AddMotorista")]
public async Task<ActionResult<Motorista>> PostMotorista([FromBody] Motorista motorista)
{
if (ModelState.IsValid)
{
try
{
var idMotorista = await motoristaRepository.PostMotorista(motorista);
if (idMotorista > 0)
{
//return Ok(idMotorista);
return CreatedAtAction(nameof(GetMotorista), new { id = motorista.IdMotorista }, motorista);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return BadRequest();
}
}
return BadRequest();
}
// DELETE: api/Motoristas/DeleteMotorista/1
[HttpDelete]
[Route("DeleteMotorista")]
public async Task<IActionResult> DeleteMotorista(int? idMotorista)
{
int result = 0;
if (idMotorista == null)
{
return BadRequest();
}
try
{
result = await motoristaRepository.DeleteMotorista(idMotorista);
if (result == 0)
{
return NotFound();
}
return Ok();
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaSemCargaDestinoOrigem
[HttpGet]
[Route("GetMotoristaSemCargaDestinoOrigem")]
public async Task<IActionResult> GetMotoristaSemCargaDestinoOrigem()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaSemCargaDestinoOrigem();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaOrigemDestino
[HttpGet]
[Route("GetMotoristaOrigemDestino")]
public async Task<IActionResult> GetMotoristaOrigemDestino()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaOrigemDestino();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaParada
[HttpGet]
[Route("GetMotoristaParada")]
public async Task<IActionResult> GetMotoristaParada()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaParada();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaParadaCarregadoPorPeriodo
[HttpGet]
[Route("GetMotoristaParadaCarregadoPorPeriodo")]
public async Task<IActionResult> GetMotoristaParadaCarregadoPorPeriodo()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaParadaCarregadoPorPeriodo();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaTipoVeiculoOrigemDestino
[HttpGet]
[Route("GetMotoristaTipoVeiculoOrigemDestino")]
public async Task<IActionResult> GetMotoristaTipoVeiculoOrigemDestino()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaTipoVeiculoOrigemDestino();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
// GET: api/Motoristas/GetMotoristaVeiculoProprio
[HttpGet]
[Route("GetMotoristaVeiculoProprio")]
public async Task<IActionResult> GetMotoristaVeiculoProprio()
{
try
{
var motoristas = await motoristaRepository.GetMotoristaVeiculoProprio();
if (motoristas == null)
{
return NotFound();
}
return Ok(motoristas);
}
catch (Exception)
{
return BadRequest();
}
}
}
} |
namespace Model
{
/// <summary>
/// Параметры отрезка
/// </summary>
public class LineSegment
{
/// <summary>
/// Координаты первой точки
/// </summary>
public (double X, double Y) FirstPoint { get; }
/// <summary>
/// Координаты второй точки
/// </summary>
public (double X, double Y) SecondPoint { get; }
/// <summary>
/// Конструктор
/// </summary>
/// <param name="firstPoint">Координаты первой точки</param>
/// <param name="secondPoint">Координаты второй точки</param>
public LineSegment
((double, double) firstPoint, (double, double) secondPoint)
{
FirstPoint = firstPoint;
SecondPoint = secondPoint;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ICE_API.models
{
public class Initiatif
{
[Key]
public int InitiatifID { get; set; }
public string Title { get; set; }
public string StartDate { get; set; }
public string About { get; set; }
public string TaskDescription { get; set; }
public bool Confirmed { get; set; }
public string location { get; set; }
public int PersonID { get; set; }
public int StatusID { get; set; }
public int CategoryID { get; set; }
[ForeignKey("PersonID")]
public virtual Person Person { get; set; }
[ForeignKey("StatusID")]
public virtual Status Status { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
}
}
|
#region License
// Copyright (c) 2012 Trafficspaces Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Reference Documentation: http://support.trafficspaces.com/kb/api/api-introduction
#endregion
using Trafficspaces.Api.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace Trafficspaces.Api.Controller {
/// <summary>
/// REST API wrapper.
/// </summary>
public class PlacementConnector : Connector {
/// <summary>
/// Initializes a new client with the specified credentials.
/// </summary>
/// <param name="accountSid">The AccountSid to authenticate with</param>
/// <param name="authTokens">The AuthToken to authenticate with</param>
public PlacementConnector(EndPoint endPoint, string resourcePath)
: base(endPoint, resourcePath) {
}
/// <summary>
/// List placement resources
/// </summary>
///
public Placement FetchAds(Placement placement) {
List<Placement> placements = new List<Placement>() { placement };
placements = List(placements);
return placements[0];
}
public List<Placement> FetchAds(List<Placement> placements, Flags flags = null, string medium = null, string frame = null, string title = null, bool useIframe = false) {
return List(placements, flags, medium, frame, title, useIframe);
}
public List<Placement> List(List<Placement> placements, Flags flags = null, string medium = null, string frame = null, string title = null, bool useIframe = false) {
Dictionary<string, string> placementParameters = new Dictionary<string, string>();
placementParameters.Add("request", getRequestJSONObject(placements, flags, medium, frame, title, useIframe).ToString());
return base.List<Placement>(placementParameters);
}
private JObject getRequestJSONObject(List<Placement> placements, Flags flags = null, string medium = null, string frame = null, string title = null, bool useIframe = false) {
JObject jsonObject = new JObject();
if (placements != null && placements.Count > 0) {
JArray placementsJSONArray = new JArray();
foreach (var placement in placements) {
placementsJSONArray.Add(JObject.Parse(base.jsonSerializer.Serialize(placement)));
}
jsonObject.Add("placements", placementsJSONArray);
}
if (flags != null) {
jsonObject.Add("flags", JObject.Parse(base.jsonSerializer.Serialize(flags)));
}
if (medium != null) {
jsonObject.Add("medium", new JValue(medium));
}
if (frame != null) {
jsonObject.Add("frame", new JValue(frame));
}
if (title != null) {
jsonObject.Add("title", new JValue(title));
}
jsonObject.Add("useiframe", new JValue(useIframe));
return jsonObject;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using DataLayer;
using BusinessLogic;
using MetroRent.Models;
using System.Reflection;
using MetroRent.Extensions;
using Microsoft.AspNet.Identity;
namespace MetroRent.Controllers
{
public class SeekRoomController : Controller
{
private MetroRentDBContext db = new MetroRentDBContext();
// GET: SeekRoom
public ActionResult Index()
{
var query = (from seekRoomRequest in db.SeekRoomRequests
select seekRoomRequest)
.OrderByDescending(seekRoomRequest => seekRoomRequest.RequestCreateTime);
return View(query.ToList());
}
[HttpPost]
public ActionResult IndexSearchKeyWord(string keyWord)
{
if (keyWord.Equals("Description, Name, Phone or Email") || keyWord.Equals(""))
{
var query = (from seekRoomRequest in db.SeekRoomRequests
select seekRoomRequest)
.OrderByDescending(seekRoomRequest => seekRoomRequest.RequestCreateTime);
return View("Index", query.ToList());
}
else
{
var query = (from seekRoomRequest in db.SeekRoomRequests
where seekRoomRequest.Description.Contains(keyWord) ||
seekRoomRequest.ContactPersonName.Contains(keyWord) ||
seekRoomRequest.ContactPersonPhone.Contains(keyWord) ||
seekRoomRequest.ContactPersonEmail.Contains(keyWord)
select seekRoomRequest)
.OrderByDescending(seekRoomRequest => seekRoomRequest.RequestCreateTime);
return View("Index", query.ToList());
}
}
[HttpPost]
public ActionResult Index(string regionFilter)
{
if (regionFilter == null || regionFilter.Equals("99"))
{
var query = (from seekRoomRequest in db.SeekRoomRequests
select seekRoomRequest)
.OrderByDescending(seekRoomRequest => seekRoomRequest.RequestCreateTime);
return View(query.ToList());
}
else
{
Region region = Region.DowntownManhattan;
if (regionFilter.Equals("0"))
{
region = Region.DowntownManhattan;
}
else if (regionFilter.Equals("1"))
{
region = Region.MidtownManhattan;
}
else if (regionFilter.Equals("2"))
{
region = Region.UptownManhattan;
}
else if (regionFilter.Equals("3"))
{
region = Region.UpperManhattan;
}
else if (regionFilter.Equals("4"))
{
region = Region.RooseveltIsland;
}
else if (regionFilter.Equals("5"))
{
region = Region.Brooklyn;
}
else if (regionFilter.Equals("6"))
{
region = Region.Queens;
}
else if (regionFilter.Equals("7"))
{
region = Region.Bronx;
}
else if (regionFilter.Equals("8"))
{
region = Region.StatenIsland;
}
else if (regionFilter.Equals("9"))
{
region = Region.NortheastNewJersey;
}
else if (regionFilter.Equals("10"))
{
region = Region.WestchesterCounty;
}
else if (regionFilter.Equals("11"))
{
region = Region.LongIsland;
}
var query = (from seekRoomRequest in db.SeekRoomRequests
from location in seekRoomRequest.RequestLocations
where location.Region == region
select seekRoomRequest)
.OrderByDescending(seekRoomRequest => seekRoomRequest.RequestCreateTime);
return View(query.ToList());
}
}
// GET: SeekRoom/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SeekRoomRequest seekRoomRequest = db.SeekRoomRequests.Find(id);
var p = db.ProfileImages.Select(aa => aa.filePath);
var profileimg = db.ProfileImages.Where(a => a.Username == seekRoomRequest.Username).Select(b => b.filePath).FirstOrDefault();
if (profileimg == null)
{
profileimg = "~/images/profile/default.png";
}
var recpost= db.SeekRoomRequests
.Where(w=>w.Id!= seekRoomRequest.Id)
.AsEnumerable()
.OrderByDescending(t => t.RequestCreateTime)
.Select(i => new KeyValuePair<int, string>(i.Id, i.Title));
ViewBag.List = recpost.ToList();
ViewBag.ProfileImg = profileimg;
ViewBag.PostId = id;
ViewBag.Controller = "SeekRoom";
if (seekRoomRequest == null)
{
return HttpNotFound();
}
return View(seekRoomRequest);
}
//POST: Send Email
public ActionResult SendEmail(EmailContent content)
{
int id = content.PostId;
using (var db = new MetroRentDBContext())
{
var post = db.SeekRoomRequests.Find(id);
SendEmailLogic.SendEmailtoRoomSeeker(post, content);
}
return RedirectToAction("Details", "SeekRoom", new { Id = id });
}
// GET: SeekRoom/Create
public ActionResult Create()
{
if (!User.Identity.IsAuthenticated)
{
return RedirectToAction("Register", "Account");
}
else
{
SeekRoomRequestViewModel model = new SeekRoomRequestViewModel();
model.CheckBoxItems = new List<RegionEnumModel>();
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.DowntownManhattan });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.MidtownManhattan });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.UptownManhattan });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.UpperManhattan });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.RooseveltIsland });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.Brooklyn });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.Queens });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.Bronx });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.StatenIsland });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.NortheastNewJersey });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.WestchesterCounty });
model.CheckBoxItems.Add(new RegionEnumModel() { Region = Region.LongIsland });
return View(model);
}
}
// POST: SeekRoom/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(SeekRoomRequestViewModel model)
{
if (!User.Identity.IsAuthenticated)
{
return RedirectToAction("Login", "Account");
}
else if (model.CheckBoxItems == null || !model.CheckBoxItems.Where(p => p.IsSelected).Any())
{
ModelState.AddModelError("CheckBoxItems", "Please select atleast one!!!");
return View("Create", model);
}
else if (ModelState.IsValid)
{
SeekRoomRequest request = new SeekRoomRequest();
string currentUserId = User.Identity.GetUserId();
ApplicationDbContext applicationDb = new ApplicationDbContext();
ApplicationUser currentUser = applicationDb.Users.FirstOrDefault(x => x.Id == currentUserId);
if (currentUser.AvatarPath == null)
{
request.ProfileImagePath = "~/Images/Profile/default.png";
}
else
{
request.ProfileImagePath = currentUser.AvatarPath;
}
applicationDb.Dispose();
request.Username = User.Identity.Name;
request.RequestLocations = new List<Location>();
List<string> regionList = new List<string>();
foreach (RegionEnumModel enumModel in model.CheckBoxItems)
{
if (enumModel.IsSelected)
{
Location location = new Location();
location.Region = enumModel.Region;
request.RequestLocations.Add(location);
regionList.Add(enumModel.Region.DisplayName());
}
}
request.Title = "Looking for rooms in ";
for (int i = 0; i < regionList.Count; ++i)
{
request.Title = request.Title + regionList[i];
if ((i != regionList.Count - 1) && regionList.Count != 1)
{
request.Title = request.Title + ", ";
}
if (i == regionList.Count - 2)
{
request.Title = request.Title + "and ";
}
}
request.BudgetLowerBound = model.BudgetLowerBound;
request.BudgetUpperBound = model.BudgetUpperBound;
request.Description = model.Description;
request.Gender = model.Gender;
request.RentalStartDate = model.RentalStartDate;
request.RequestCreateTime = DateTime.Now;
request.ContactPersonName = model.ContactPersonName;
request.ContactPersonPhone = model.ContactPersonPhone;
request.ContactPersonEmail = model.ContactPersonEmail;
request.IsRequestActive = true;
db.SeekRoomRequests.Add(request);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
// GET: SeekRoom/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SeekRoomRequest seekRoomRequest = db.SeekRoomRequests.Find(id);
if (seekRoomRequest == null)
{
return HttpNotFound();
}
return View(seekRoomRequest);
}
// POST: SeekRoom/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Username,Title,BudgetLowerBound,BudgetUpperBound,Description,Gender,RentalStartDate,RequestCreateTime,ContactPersonName,ContactPersonPhone,ContactPersonEmail,IsRequestActive")] SeekRoomRequest seekRoomRequest)
{
if (ModelState.IsValid)
{
db.Entry(seekRoomRequest).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(seekRoomRequest);
}
// GET: SeekRoom/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SeekRoomRequest seekRoomRequest = db.SeekRoomRequests.Find(id);
if (seekRoomRequest == null)
{
return HttpNotFound();
}
return View(seekRoomRequest);
}
// POST: SeekRoom/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SeekRoomRequest seekRoomRequest = db.SeekRoomRequests.Find(id);
db.SeekRoomRequests.Remove(seekRoomRequest);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
#if !NETCOREAPP // Test runner fails when running on netcoreapp
using Sentry.PlatformAbstractions;
using Runtime = Sentry.PlatformAbstractions.Runtime;
namespace Sentry.Tests.Integrations;
public class AppDomainAdapterTests
{
[SkippableFact]
public void UnhandledException_FiredOnExceptionUnhandledInThread()
{
// Test flaky on Mono
Skip.If(Runtime.Current.IsMono());
var evt = new ManualResetEventSlim(false);
AppDomainAdapter.Instance.UnhandledException += (_, _) => evt.Set();
var thread = new Thread(() => throw new Exception())
{
IsBackground = false
};
thread.Start();
Assert.True(evt.Wait(TimeSpan.FromSeconds(3)));
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using BO;
namespace DAL
{
public class Context : DbContext
{
public Context GetContext(Context db)
{
if (db ==null)
{
Context newContext= new Context();
return newContext;
}
else
{
return db;
}
}
public DbSet<BO.Race> Races { get; set; }
public DbSet<BO.Competitor> Competitors { get; set; }
public DbSet<BO.Organizer> Organizers { get; set; }
}
}
|
using SGCFT.Dominio.Entidades;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace SGCFT.Apresentacao.Models
{
public class ModuloViewModel
{
public ModuloViewModel()
{
}
public ModuloViewModel(int id, string titulo)
{
this.Id = id;
this.Titulo = titulo;
}
public int Id { get; set; }
public int IdTreinamento { get; set; }
[Required(ErrorMessage = "Informe o título")]
public string Titulo { get; set; }
public List<TreinamentoViewModel> ListaTreinamentos { get; set; }
public Modulo ConverterParaDominio()
{
Modulo modulo = new Modulo(this.IdTreinamento, this.Titulo);
return modulo;
}
}
} |
namespace TradeProcessing.Model
{
public class ImportTextForm
{
public string FilePath { get; set; }
}
}
|
using System;
using System.Drawing;
using System.Windows.Forms;
using motion;
using VideoSource;
using ASSISTME;
using System.Threading;
using ASSISTME.SNIPS;
using ARGOTH.SNIPS.MON;
using ARGOTH.SNIPS;
using ARGOTH.SNIPS.CNV;
using System.IO;
namespace ARGOTH
{
public partial class MainFRM : Form
{
private static Camera camera = null;
private static int MIN, MAX;
private static FileInfo info;
private static string[] fileEntries;
private static Bitmap filterBmp;
private static CaptureDevice localSource;
private static CaptureDeviceForm form;
private static Thread thread;
SobelGx SOBEL_Gx = new SobelGx(3);
public MainFRM()
{
InitializeComponent();
MIN = 45;
MAX = 95;
}
public void Initialize()
{
form = new CaptureDeviceForm();
if (form.ShowDialog(this) == DialogResult.OK)
{
// create video source
localSource = new CaptureDevice();
localSource.VideoSource = form.Device;
// open it
OpenVideoSource(localSource);
}
}
private void OpenVideoSource(IVideoSource source)
{
// create camera
camera = new Camera(source);
// start camera
camera.Start();
camera.NewFrame += new EventHandler(camera_NewFrame);
}
void camera_NewFrame(object sender, EventArgs e)
{
Invalidate();
if (camera != null)
{
try
{
camera.Lock();
filterBmp = new Bitmap(camera.LastFrame);
PCT_CANVAS.Image = Convolver.Execute(filterBmp, SOBEL_Gx);//Sobel.Execute(YUV.Execute(filterBmp));
MyDelegates.SetControlTextValue(LBL_IMAGE_SIZE, camera.LastFrame.Size);
}
catch (Exception ex)
{
MyDelegates.SetControlTextValue(LBL_IMAGE_SIZE,ex);
}
finally
{
camera.Unlock();
}
if (camera.FramesReceived % 12 == 0)
{
thread = new Thread(Clean);
thread.Start();
}
}
}
private static void Clean()
{
GC.Collect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (camera != null)
camera.Stop();
}
private void BTN_WEB_Click(object sender, EventArgs e)
{
Initialize();
}
/// <p>
/// Evento botón para abrir una imagen y obtener todas las rutas
/// de los archivos en el directorio.
/// <p>
private void BTN_OPEN_IMAGE_Click(object sender, EventArgs e)
{
if (OFD.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
info = new FileInfo(OFD.FileName);
fileEntries = Directory.GetFiles(info.DirectoryName);
filterBmp = new Bitmap(OFD.FileName);
filterBmp = new Bitmap(filterBmp);
Histogram.Execute(filterBmp);
PCT_CANVAS.Image = filterBmp;
}
}
private void BTN_COLOR_FINDER_Click(object sender, EventArgs e)
{
filterBmp = new Bitmap(OFD.FileName);
filterBmp = new Bitmap(filterBmp);
MIN = int.Parse(TXT_MIN.Text);
MAX = int.Parse(TXT_MAX.Text);
PCT_CANVAS.Image = ColorFinder.Execute(filterBmp,MIN,MAX);
PCT_CANVAS.Refresh();
}
private void BTN_PROCESS_FOLDER_Click(object sender, EventArgs e)
{
LBL_STAT.Text = "processing...";
thread = new Thread(ProcessFolder);
thread.Start();
}
/// <p>
/// Recursive method that iterates through the directory files
/// applying the same process
/// <p>
private void ProcessFolder()
{
DirectoryInfo dirInfo = Directory.CreateDirectory(info.DirectoryName + @"\PROCESS");
for (int i = 0; i < fileEntries.Length; i++)
{
try
{
filterBmp = new Bitmap(fileEntries[i]);
ColorFinder.Execute(filterBmp, MIN, MAX).Save(dirInfo.FullName + @"\000" + i + ".PNG");
}
catch (Exception) { }
}
MyDelegates.SetControlTextValue(LBL_STAT, "Done");
}
}
} |
using UnityEngine;
using System.Collections;
public class PlayerMove : MonoBehaviour {
public float moveSpeed;
public float jumpHeight;
bool has_jump;
bool has_double_jump;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
private Animator anim;
// Use this for initialization
void Start () {
has_jump = true;
has_double_jump = true;
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
// Update is called once per frame
void Update()
{
anim.SetBool("Grounded", grounded);
if (Input.GetKeyDown(KeyCode.Space))
{
if (has_jump)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
has_jump = false;
}
else if(has_double_jump)
{
GetComponent<Rigidbody2D>().gravityScale = 0.50f;
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpHeight);
has_double_jump = false;
}
}
if (Input.GetKey(KeyCode.D))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.A))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-moveSpeed, GetComponent<Rigidbody2D>().velocity.y);
}
anim.SetFloat("Speed", Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x));
if (GetComponent<Rigidbody2D>().velocity.x > 0)
transform.localScale = new Vector3(3f, 3f, 1f);
else if (GetComponent<Rigidbody2D>().velocity.x < 0)
transform.localScale = new Vector3(-3f, 3f, 1f);
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "ground")
{
has_jump = true;
has_double_jump = true;
}
}
}
|
using ADP.BusinessLogic;
using ADP.BusinessLogic.Entity;
using ADPProject.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
namespace ADPProject.Controllers
{
public class MasterController : Controller
{
// GET: Master
public ActionResult Index()
{
return View();
}
public ActionResult Employee()
{
RegisterUserModel model = new RegisterUserModel();
return View(model);
}
[HttpPost]
public ActionResult Employee(RegisterUserModel model)
{
if (ModelState.IsValid)
{
try
{
//Insert Employee
UserBusinessLogic.CreateEmployee(model.Nama, model.TempatLahir, model.TanggalLahir, model.NoTelpon, model.Email, model.Jabatan);
//Insert User
UserBusinessLogic.CreateUser(model.Username, model.Password, model.IdRole);
}
catch (System.Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
public ActionResult Project()
{
ProjectModels model = new ProjectModels();
model.StartDate = DateTime.Now.ToString();
return View(model);
}
[HttpPost]
public ActionResult Project(ProjectModels model)
{
if (ModelState.IsValid)
{
try
{
DateTime tgl = Convert.ToDateTime(model.StartDate);
ProjectBusiness.InsertProject(model.Nama, model.Kota, model.Alamat, tgl, model.NoKontrak, model.NoSpk, model.TelpSpk);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
public ActionResult Project()
{
ProjectModels model = new ProjectModels();
model.StartDate = DateTime.Now.ToString();
return View(model);
}
[HttpPost]
public ActionResult Project(ProjectModels model)
{
if (ModelState.IsValid)
{
try
{
DateTime tgl = Convert.ToDateTime(model.StartDate);
ProjectBusiness.InsertProject(model.Nama, model.Kota, model.Alamat, tgl, model.NoKontrak, model.NoSpk, model.TelpSpk);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
[HttpPost]
public JsonResult GetProject(int jtStartIndex = 0, int jtPageSize = 0)
{
try
{
List<Project> lstProject = new List<Project>();
//Get Data List Project From DB
lstProject = ProjectBusiness.GetAllProject();
//Paging
var resultCount = lstProject.Count;
if (resultCount > 0)
lstProject.OrderBy(m => m.Nama).Skip(jtStartIndex).Take(jtPageSize).ToList();
return Json(new { Result = "OK", Records = lstProject, TotalRecordCount = resultCount });
}
catch (System.Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[HttpPost]
public JsonResult EditProject(string id, string nama, string kota, string alamat, string startDate, string noKontrak, string noSpk, string telpSpk)
{
try
{
//Edit Data
DateTime tgl = Convert.ToDateTime(startDate);
ProjectBusiness.UpdateProject(id, nama, kota, alamat, tgl, noKontrak, noSpk, telpSpk);
return Json(new { Result = "OK", Message = "OK" });
}
catch (System.Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
public ActionResult ProjectCustomer(ProjectCustomerModels model)
{
return View(model);
}
}
} |
namespace gView.Framework.Data.Cursors
{
public interface IUrlCursor : ICursor
{
string Url { get; }
}
/*
public interface IFeatureBuffer
{
IFeature CreateFeature();
bool Store();
}
*/
}
|
using AutoMapper;
using LongigantenAPI.Models;
using ORM.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LongigantenAPI.Profiles
{
public class OrderProfile : Profile
{
public OrderProfile()
{
CreateMap<Order, OrderDto>()
.ForMember(d => d.Ordernumber, o => o.MapFrom(s => s.Id))
.ForMember(d => d.OrderDate, o => o.MapFrom(s => s.Created.ToString("yyyy-MM-dd")))
//Creating Mapping conditions
.ForMember(d => d.DeliveryAddressID, o => o.MapFrom(s => s.DeliveryAddress == null ? s.DeliveryAddressID : s.DeliveryAddress.Id))
.ForMember(d => d.DeliveryMethodID, o => o.MapFrom(s => s.DeliveryMethod == null ? s.DeliveryMethodID : s.DeliveryMethod.Id))
.ForMember(d => d.StatusID, o => o.MapFrom(s => s.Status == null ? s.StatusID : s.Status.Id));
CreateMap<OrderForCreateDto, Order>()
.ForMember(d => d.Created, o => o.MapFrom(s => s.OrderDate))
.ForMember(d => d.DeliveryAddressID , o => o.MapFrom(s => s.DeliveryAddressID))
.ForMember(d => d.OrderList, o => o.MapFrom(s => s.OrderList));
CreateMap<OrdersForUpdate, Order>();
CreateMap<Order, OrdersForUpdate>()
.ForMember(d => d.DeliveryAddressID, o => o.MapFrom(s => s.DeliveryAddress == null ? s.DeliveryAddressID : s.DeliveryAddress.Id))
.ForMember(d => d.DeliveryMethodID, o => o.MapFrom(s => s.DeliveryMethod == null ? s.DeliveryMethodID : s.DeliveryMethod.Id))
.ForMember(d => d.StatusID, o => o.MapFrom(s => s.Status == null ? s.StatusID : s.Status.Id));
}
}
}
|
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using Wpf.Dao;
using Wpf.Model;
namespace Wpf.ViewModel
{
public class CarViewModel : ViewModelBase
{
//视图显示类:定义可显示的属性
CarDao carDao = new CarDao();
List<Car> carViewList = new List<Car>();//存储从Dao层来的数据
public ObservableCollection<Car> carView = new ObservableCollection<Car>();//视图层数据对象
public CarViewModel()
{
SelectAll();
UpdateViewData();
DeleteCommand = new RelayCommand<int>(Index => Delete(Index));
UpdateCommand = new RelayCommand<Car>(car => Update(car));
SelectCommand = new RelayCommand<List<string>>(filterList => Select(filterList));
InsertCommand = new RelayCommand<Car>(car => Insert(car));
}
//更新显示数据集
private void UpdateViewData()
{
carView.Clear();
for (int i = 0; i < carViewList.Count(); i++)
{
carView.Add(carViewList[i]);
}
}
// 操作命令
public RelayCommand<int> DeleteCommand { get; set; }
public RelayCommand<Car> UpdateCommand { get; set; }
public RelayCommand<List<string>> SelectCommand { get; set; }
public RelayCommand<Car> InsertCommand { get; set; }
//从Dao层查询数据
public void SelectAll()
{
carViewList.Clear();
carViewList = carDao.SelectAll();
}
// 删除函数
private void Delete(int Index)
{
OKWindow okWindow = new OKWindow("删除数据","确实要删除这条数据吗?");
okWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
okWindow.ShowDialog();
if (okWindow.Ret == true)
{
carDao.Delete(Index);
SelectAll();
UpdateViewData();
}
}
public void Update(Car car)
{
carDao.Update(car);
SelectAll();
UpdateViewData();
}
private void Insert(Car car)
{
carDao.Insert(car);
SelectAll();
UpdateViewData();
}
private void Select(List<string> filterList)
{
carViewList = carDao.SelectAll();
var retList = carViewList.Where(a => a.Type.Contains(filterList[0]) && a.CarNumber.Contains(filterList[1])).ToList();
carViewList.Clear();
carViewList = retList;
UpdateViewData();
}
public ObservableCollection<Car> CarView
{
get { return carView; }
set { carView = value; RaisePropertyChanged(); }
}
}
}
|
using NHibernate;
using Profiling2.Domain.Contracts.Queries.Procs;
using SharpArch.NHibernate;
namespace Profiling2.Infrastructure.Queries.Procs
{
public class MergeStoredProcQueries : NHibernateQuery, IMergeStoredProcQueries
{
public int MergePersons(int toKeepPersonId, int toDeletePersonId, string userId, bool isProfilingChange)
{
return Session.GetNamedQuery("PRF_SP_PersonMerge_NHibernate")
.SetParameter("ToKeepPersonID", toKeepPersonId, NHibernateUtil.Int64)
.SetParameter("ToDeletePersonID", toDeletePersonId, NHibernateUtil.Int64)
.SetParameter("UserID", userId, NHibernateUtil.String)
.SetParameter("IsProfilingChange", isProfilingChange, NHibernateUtil.Boolean)
.UniqueResult<int>();
}
public int MergeUnits(int toKeepUnitId, int toDeleteUnitId, string userId, bool isProfilingChange)
{
return Session.GetNamedQuery("PRF_SP_UnitMerge_NHibernate")
.SetParameter("ToKeepUnitID", toKeepUnitId, NHibernateUtil.Int64)
.SetParameter("ToDeleteUnitID", toDeleteUnitId, NHibernateUtil.Int64)
.SetParameter("UserID", userId, NHibernateUtil.String)
.SetParameter("IsProfilingChange", isProfilingChange, NHibernateUtil.Boolean)
.UniqueResult<int>();
}
public int MergeEvents(int toKeepEventId, int toDeleteEventId, string userId, bool isProfilingChange)
{
return Session.GetNamedQuery("PRF_SP_EventMerge_NHibernate")
.SetParameter("ToKeepEventID", toKeepEventId, NHibernateUtil.Int64)
.SetParameter("ToDeleteEventID", toDeleteEventId, NHibernateUtil.Int64)
.SetParameter("UserID", userId, NHibernateUtil.String)
.SetParameter("IsProfilingChange", isProfilingChange, NHibernateUtil.Boolean)
.UniqueResult<int>();
}
}
}
|
using SOLIDPrinciples.ValidationClass.Example02.GoodSolution;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace SOLIDPrinciplesTest.ValidationClass.Example02
{
public class GoodExampleTest
{
[Fact]
public void GoodExampleDesenvolvedor()
{
Funcionario funcionario = new Funcionario
{
Cargo = Cargo.DESENVOLVEDOR,
Salario = 1000
};
var resultado = funcionario.AplicarRegraDeCalculoParaCargo();
Assert.Equal(900, resultado);
}
[Fact]
public void GoodExampleDba()
{
Funcionario funcionario = new Funcionario
{
Cargo = Cargo.DBA,
Salario = 1000
};
var resultado = funcionario.AplicarRegraDeCalculoParaCargo();
Assert.Equal(850, resultado);
}
[Fact]
public void GoodExampleTester()
{
Funcionario funcionario = new Funcionario
{
Cargo = Cargo.TESTER,
Salario = 10000
};
var resultado = funcionario.AplicarRegraDeCalculoParaCargo();
Assert.Equal(7500, resultado);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using DBDiff.Schema.Model;
namespace DBDiff.Schema.Sybase.Model
{
public abstract class SybaseSchemaBase:SchemaBase
{
protected SybaseSchemaBase(StatusEnum.ObjectTypeEnum objectType)
: base("[", "]", objectType)
{
}
}
}
|
using LoowooTech.Stock.Models;
using NPOI.SS.UserModel;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoowooTech.Stock.Common
{
public static class QuestionManager
{
private static int MAXNUMBER = 65534;
private static readonly object _syncRoot = new object();
public static List<Question> Questions { get; private set; }
static QuestionManager() {
Questions = new List<Question>();
}
public static void Clear()
{
lock(_syncRoot)
{
Questions.Clear();
}
}
public static void AddRange(List<Question> questions)
{
lock(_syncRoot)
{
Questions.AddRange(questions);
}
}
public static void Add(Question question)
{
lock(_syncRoot)
{
Questions.Add(question);
}
}
private static string _modelFile { get; set; }
public static string ModelFile
{
get
{
if (string.IsNullOrEmpty(_modelFile))
{
_modelFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, System.Configuration.ConfigurationManager.AppSettings["Report"]);
}
return _modelFile;
}
}
/// <summary>
/// 作用:生成XLS格式质检报告文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string Save(string filePath)
{
var info = string.Empty;
if (string.IsNullOrEmpty(ModelFile)||!System.IO.File.Exists(ModelFile))
{
info = string.Format("质检报告格式文件为空或者格式文件不存在");
Console.WriteLine(info);
return string.Empty;
}
IWorkbook workbook = ModelFile.OpenExcel();
if (workbook == null)
{
info = "打开质检报告格式文件失败";
Console.WriteLine(info);
return string.Empty;
}
var sheet1 = workbook.GetSheetAt(0);
var sheet2 = workbook.GetSheetAt(1);
var sheet3 = workbook.GetSheetAt(2);
var sheet4 = workbook.GetSheetAt(3);
SaveCollect(sheet1);
SaveList(sheet2);
SaveInfo(sheet3, LogManager.List);
SaveSQLError(sheet4);
var folder = System.IO.Path.GetDirectoryName(filePath);
if (!System.IO.Directory.Exists(folder))
{
System.IO.Directory.CreateDirectory(folder);
}
using (var fs=new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
workbook.Write(fs);
}
return filePath;
}
private static void SaveSQLError(ISheet sheet)
{
var list = Questions.Where(e => e.Project == CheckProject.数据库查询).OrderBy(e => e.Code).ThenBy(e => e.TableName).ToList();
var i = 2;
IRow row = null;
var modelrow = sheet.GetRow(i);
foreach (var item in list.Take(MAXNUMBER))
{
row = sheet.GetRow(i) ?? sheet.CreateRow(i);
var cell = ExcelClass.GetCell(row, 0, modelrow);
cell.SetCellValue(i++);
ExcelClass.GetCell(row, 1, modelrow).SetCellValue(item.Description);
ExcelClass.GetCell(row, 2, modelrow).SetCellValue(item.Code);
}
if (list.Count > MAXNUMBER)
{
row = sheet.GetRow(MAXNUMBER + 1) ?? sheet.CreateRow(MAXNUMBER + 1);
ExcelClass.GetCell(row, 0, modelrow).SetCellValue(string.Format("错误列表超过{0},超过部分不再显示", MAXNUMBER));
}
}
private const string ALLKey = "ALL";
/// <summary>
/// 作用:生成各个检查类别数量汇总表
/// </summary>
/// <param name="sheet"></param>
/// <param name="concurrentBag"></param>
private static void SaveCollect(ISheet sheet)
{
IRow row = null;
var temp = Questions.Where(e => !string.IsNullOrEmpty(e.Code));
for(var i = 1; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i);
if (row == null)
{
break;
}
var cell = row.GetCell(5);
if (cell != null)
{
var str = cell.ToString();
if (!string.IsNullOrEmpty(str) && str.Contains("{") && str.Contains("}"))
{
var key = str.Replace("{", "").Replace("}", "");
var val = key.ToLower()==ALLKey.ToLower()?temp.LongCount(): temp.Where(e => e.Code.ToLower() == key.ToLower()).LongCount();
cell.SetCellValue(val);
}
}
}
}
/// <summary>
/// 作用:生成具体问题明细表格
/// </summary>
/// <param name="sheet"></param>
/// <param name="concurrentBag"></param>
private static void SaveList(ISheet sheet)
{
var list = Questions.Where(e=> e.Project != CheckProject.数据库查询).OrderBy(e => e.Code).ThenBy(e => e.TableName).ToList();
var i = 2;
var serial = 1;
IRow row = null;
var modelrow = sheet.GetRow(i);
foreach (var item in list.Take(MAXNUMBER))
{
row = sheet.GetRow(i) ?? sheet.CreateRow(i);
i++;
var cell = ExcelClass.GetCell(row, 0, modelrow);
cell.SetCellValue(serial++);
ExcelClass.GetCell(row, 1, modelrow).SetCellValue(item.Code);
ExcelClass.GetCell(row, 2, modelrow).SetCellValue(item.Name);
ExcelClass.GetCell(row, 3, modelrow).SetCellValue(item.TableName);
ExcelClass.GetCell(row, 4, modelrow).SetCellValue(item.BSM);
ExcelClass.GetCell(row, 5, modelrow).SetCellValue(item.Description);
ExcelClass.GetCell(row, 6, modelrow).SetCellValue(item.Project.ToString());
}
if (list.Count > MAXNUMBER)
{
row = sheet.GetRow(MAXNUMBER + 1) ?? sheet.CreateRow(MAXNUMBER + 1);
ExcelClass.GetCell(row, 0, modelrow).SetCellValue(string.Format("错误列表超过{0},超过部分不再显示", MAXNUMBER));
}
}
/// <summary>
/// 作用:生成质检过程中存在的问题表格
/// </summary>
/// <param name="sheet"></param>
/// <param name="list"></param>
private static void SaveInfo(ISheet sheet,ConcurrentBag<string> list)
{
var i = 2;
IRow row = null;
var modelrow = sheet.GetRow(1);
foreach(var item in list.Take(MAXNUMBER))
{
row = sheet.GetRow(i) ?? sheet.CreateRow(i);
var cell = ExcelClass.GetCell(row, 0, modelrow);
cell.SetCellValue(i++);
ExcelClass.GetCell(row, 1, modelrow).SetCellValue(item);
}
if (list.Count > MAXNUMBER)
{
row = sheet.GetRow(MAXNUMBER + 1) ?? sheet.CreateRow(MAXNUMBER + 1);
ExcelClass.GetCell(row, 0, modelrow).SetCellValue(string.Format("错误列表超过{0},超过部分不再显示", MAXNUMBER));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.ComponentModel;
using System.Drawing;
namespace AC.ExtendedRenderer.Toolkit.Utils
{
public class ToolStripControlHostFixed : ToolStripControlHost
{
public ToolStripControlHostFixed()
: base(new Control())
{
}
public ToolStripControlHostFixed(Control c)
: base(c)
{
}
}
}
|
using AKCore.DataModel;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace AKCore.Extensions
{
public static class StringExtensions
{
public static IList<Widget> GetWidgetsFromString(this string widgetJson)
{
var widgetList = widgetJson != null ? JsonConvert.DeserializeObject<List<Widget>>(widgetJson) : new List<Widget>();
foreach (var (widget, id) in widgetList.Select((value, i) => (value, i)))
{
widget.Id = id;
}
return widgetList;
}
}
}
|
using System.Collections.Generic;
namespace EddiSpeechService
{
public partial class Translations
{
// Fixes to avoid issues with pronunciation of station model names
private static readonly Dictionary<string, string> STATION_MODEL_FIXES = new Dictionary<string, string>()
{
{ "Orbis Starport", "Or-bis Starport" }, // Stop "Or-bis" from sometimes being pronounced as "Or-bise"
{ "Megaship", "Mega-ship" } // Stop "Mega-Ship" from sometimes being pronounced as "Meg-AH-ship"
};
private static readonly Dictionary<string, string[]> STATION_PRONUNCIATIONS = new Dictionary<string, string[]>()
{
{ "Aachen Town", new string[] { Properties.Phonetics.Aachen, Properties.Phonetics.Town } },
{ "Slough Orbital", new string[] { Properties.Phonetics.Slough, Properties.Phonetics.Orbital } },
};
/// <summary>Fix up station related pronunciations </summary>
private static string getPhoneticStation(string station)
{
// Specific translations
if (STATION_PRONUNCIATIONS.TryGetValue(station, out var stationPronunciation))
{
return replaceWithPronunciation(station, stationPronunciation);
}
// Specific fixing of station model pronunciations
if (STATION_MODEL_FIXES.TryGetValue(station, out var value))
{
station = value;
}
// Strip plus signs and spaces from station name suffixes
if (station.EndsWith("+"))
{
char[] charsToTrim = { '+', ' ' };
station = station.TrimEnd(charsToTrim);
}
return station;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public Animator transition;
public void StartGame()
{
StartCoroutine(LoadNextLevel(SceneManager.GetActiveScene().buildIndex + 1));
}
public void QuitGame()
{
Application.Quit();
}
IEnumerator LoadNextLevel(int levelIndex)
{
transition.SetTrigger("Start");
yield return new WaitForSeconds(1);
SceneManager.LoadScene(levelIndex);
}
}
|
using Phenix.Core;
using Phenix.Core.Mapping;
namespace Phenix.Services.Library
{
/// <summary>
/// Data检索事件数据
/// </summary>
public class FetchEventArgs : ShallEventArgs
{
/// <summary>
/// 初始化
/// </summary>
public FetchEventArgs(ICriterions criterions)
: base()
{
_criterions = criterions;
}
/// <summary>
/// 初始化
/// </summary>
public FetchEventArgs(ICriterions criterions, string result)
: this(criterions)
{
_result = result;
}
#region 属性
private readonly ICriterions _criterions;
/// <summary>
/// 条件集
/// </summary>
public ICriterions Criterions
{
get { return _criterions; }
}
private string _result;
/// <summary>
/// 结果
/// </summary>
public string Result
{
get { return _result; }
set
{
_result = value;
Applied = true;
}
}
#endregion
}
} |
using OpenQA.Selenium;
using System.Collections.Generic;
using System.Linq;
using WebDriverOnCore.WebDriver;
namespace WebDriverOnCore.PageElements.CommonPageSections
{
public class CommonPagesElements
{
public List<IWebElement> SubmitButtons => Driver.CurrentBrowser.FindElements(By.CssSelector(".submit")).ToList();
}
}
|
using System;
namespace KnightsTour
{
public struct Cell
{
public int col { get; set; }
public int row { get; set; }
public Cell(int col, int row) : this()
{
this.col = col;
this.row = row;
}
public static Cell operator +(Cell cell, Knight.Move move)
{
return new Cell(cell.row + move.rows, cell.col + move.cols);
}
public override string ToString()
{
return $"{base.ToString()}: ({col},{row})";
}
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using ApartmentApps.Api;
using ApartmentApps.Api.ViewModels;
using ApartmentApps.Data.DataSheet;
using ApartmentApps.Data.Repository;
using ApartmentApps.Portal.Controllers;
using Ninject;
namespace ApartmentApps.API.Service.Controllers.Api
{
[RoutePrefix("api/Property")]
public class PropertyController : ServiceController<PropertyService, PropertyIndexBindingModel, PropertyIndexBindingModel>
{
public PropertyController(IKernel kernel, PropertyContext context, IUserContext userContext) : base(kernel, context, userContext)
{
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("schema")]
public override HttpResponseMessage Schema()
{
return base.Schema();
}
[System.Web.Http.HttpPost]
[System.Web.Http.Route("fetch")]
public override Task<QueryResult<PropertyIndexBindingModel>> Fetch(Query query)
{
return base.Fetch(query);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("entry")]
public override PropertyIndexBindingModel Entry(string id)
{
return base.Entry(id);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("delete")]
public override Task<IHttpActionResult> Delete(string id)
{
return base.Delete(id);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("save")]
public override Task<IHttpActionResult> Save(PropertyIndexBindingModel entry)
{
return base.Save(entry);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("excel")]
public override IHttpActionResult ToExcel(Query query)
{
return base.ToExcel(query);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("pdf")]
public override Task<IHttpActionResult> ToPDF(Query query)
{
return base.ToPDF(query);
}
[System.Web.Http.HttpGet]
[System.Web.Http.Route("activate")]
public IHttpActionResult Activate(string id)
{
var user = UserContext.CurrentUser;
user.PropertyId = Convert.ToInt32(id);
Context.SaveChanges();
return Ok();
}
}
} |
using MAS_Końcowy.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MAS_Końcowy.Services
{
class MenuService
{
public static IEnumerable<Dish> GetDishes(int menuId)
{
using (var context = new MASContext())
{
return context.Dishes
.Include(c => c.Menu)
.Include(a => a.DishIngredients)
.ThenInclude(b => b.Ingredient)
.Where(d => d.Menu.Id == menuId)
.ToList();
}
}
public static Menu GetMenu(int menuId)
{
using (var context = new MASContext())
{
return context.Menus.Find(menuId);
}
}
public static void Delete(Menu menu)
{
if(menu == null)
{
throw new Exception("Passed argument is null");
}
using (var context = new MASContext())
{
context.Menus.Remove(menu);
context.SaveChanges();
}
}
public static List<Menu> ToList()
{
using (var context = new MASContext())
{
return context.Menus.ToList();
}
}
public static void New()
{
using (var context = new MASContext())
{
context.Menus.Add(new Menu(0.0d));
context.SaveChanges();
}
}
public static void ChangePrices(Menu menu, double newMargin)
{
using (var context = new MASContext())
{
menu.ProfitMargin = newMargin;
context.Menus.Update(menu);
context.SaveChanges();
using (var transaction = context.Database.BeginTransaction())
{
var dishes = GetDishes(menu.Id);
if (dishes != null)
{
foreach (var dish in dishes)
{
DishService.ChangePrice(dish, newMargin);
}
}
transaction.Commit();
}
context.SaveChanges();
}
}
}
}
|
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;
namespace WebAutomation
{
public partial class BrowserOptions : Form
{
public static string broptions = "";
public BrowserOptions()
{
InitializeComponent();
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedItem = "Internet Explorer";
}
public void button1_Click(object sender, EventArgs e)
{
broptions = (string)comboBox1.SelectedItem;
// MessageBox.Show("You need to Specify the browser " + broptions);
bool correctstring = false;
for (int i = 0; i < comboBox1.Items.Count; i++)
{
if (broptions == comboBox1.Items[i].ToString())
{
correctstring = true;
break;
}
}
if (correctstring == false)
{
MessageBox.Show("You need to Specify the browser ");
}
else
{
// MessageBox.Show("You have selected : " + broptions);
}
if (correctstring)
{
BrowserOptions.ActiveForm.Close();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using TY.SPIMS.Controllers.Interfaces;
using TY.SPIMS.Entities;
using TY.SPIMS.POCOs;
using TY.SPIMS.Utilities;
namespace TY.SPIMS.Controllers
{
public class BrandController : IBrandController
{
private readonly IUnitOfWork unitOfWork;
private readonly IActionLogController actionLogController;
private TYEnterprisesEntities db
{
get { return unitOfWork.Context; }
}
public BrandController(IUnitOfWork unitOfWork, IActionLogController actionLogController)
{
this.unitOfWork = unitOfWork;
this.actionLogController = actionLogController;
}
#region CUD Functions
public void InsertBrand(BrandColumnModel model)
{
try
{
using (this.unitOfWork)
{
var item = new Brand()
{
BrandName = model.BrandName,
IsDeleted = model.IsDeleted,
};
this.unitOfWork.Context.AddToBrand(item);
string action = string.Format("Added new Brand - {0}", item.BrandName);
this.actionLogController.AddToLog(action, UserInfo.UserId);
this.unitOfWork.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateBrand(BrandColumnModel model)
{
try
{
using (this.unitOfWork)
{
var item = FetchBrandById(model.Id);
if (item != null)
{
item.BrandName = model.BrandName;
item.IsDeleted = model.IsDeleted;
}
string action = string.Format("Updated Brand - {0}", item.BrandName);
this.actionLogController.AddToLog(action, UserInfo.UserId);
this.unitOfWork.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteBrand(int id)
{
try
{
using (this.unitOfWork)
{
var item = FetchBrandById(id);
if (item != null)
item.IsDeleted = true;
string action = string.Format("Deleted Brand - {0}", item.BrandName);
this.actionLogController.AddToLog(action, UserInfo.UserId);
this.unitOfWork.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Fetch Functions
private IQueryable<Brand> CreateQuery(string filter)
{
var items = db.Brand
.Where(a => a.IsDeleted == false);
if (!string.IsNullOrWhiteSpace(filter))
items = items.Where(a => a.BrandName.Contains(filter));
return items;
}
public SortableBindingList<BrandDisplayModel> FetchBrandWithSearch(string filter)
{
try
{
var query = CreateQuery(filter);
var result = from a in query
select new BrandDisplayModel {
Id = a.Id,
BrandName = a.BrandName,
};
SortableBindingList<BrandDisplayModel> b = new SortableBindingList<BrandDisplayModel>(result);
return b;
}
catch (Exception ex)
{
throw ex;
}
}
public List<Brand> FetchAllBrands()
{
try
{
var query = CreateQuery(string.Empty);
query = query.OrderBy(a => a.BrandName);
return query.ToList();
}
catch (Exception ex)
{
throw ex;
}
}
public Brand FetchBrandById(int id)
{
try
{
var item = (from i in db.Brand
where i.Id == id
select i).FirstOrDefault();
return item;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace CN.Jpush.Android.Service {
[Service(Name = "cn.jpush.android.service.DownloadService", Enabled = true, Exported = false)]
public partial class DownloadService {
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Rendering;
using UnityEngine.UI;
//[UpdateBefore(typeof(Move))]//定义哪一个Sysytm在前面
public class CreatCubeSystem : ComponentSystem
{
struct CreateCubeGroup
{
[ReadOnly]
public SharedComponentDataArray<CreateCube> CreateCube;
public EntityArray Entity;
public ComponentDataArray<Position> Position;
public ComponentDataArray<Scale> scal;
public readonly int Length;
}
[Inject] CreateCubeGroup cubeGroup;
protected override void OnUpdate()
{
for (int i = 0; i < cubeGroup.Length; i++)
{
var spawner = cubeGroup.CreateCube[0];
var sourceEntity = cubeGroup.Entity[0];
var center = cubeGroup.Position[0].Value;
var entities = new NativeArray<Entity>(spawner.count, Allocator.Temp);
EntityManager.Instantiate(spawner.cube, entities);
var pos = new NativeArray<float3>(spawner.count, Allocator.Temp);
setPos(ref pos);
//使用for循环
for (int j = 0; j < spawner.count; j++)
{
EntityManager.SetComponentData(entities[j], new Position { Value = pos[j] });
EntityManager.SetComponentData(entities[j], new Scale { Value = new float3(1, 1f, 1) });
EntityManager.AddSharedComponentData(entities[j], new MeshInstanceRenderer
{
material = spawner.materials[UnityEngine.Random.Range(1,spawner.materials.Count)],
mesh = spawner.mesh
});
}
entities.Dispose();
pos.Dispose();
EntityManager.RemoveComponent<CreateCube>(sourceEntity);
UpdateInjectedComponentGroups();
}
#region
// 使用while循环
while (cubeGroup.Length != 0)
{
//var spawner = cubeGroup.CreateCube[0];
//var sourceEntity = cubeGroup.Entity[0];
//var center = cubeGroup.Position[0].Value;
//var entities = new NativeArray<Entity>(spawner.count, Allocator.Temp);
//EntityManager.Instantiate(spawner.cube, entities);
//entities.Dispose();
//EntityManager.RemoveComponent<CreateCube>(sourceEntity);
//UpdateInjectedComponentGroups();
}
#endregion
}
//获取位置
void setPos(ref NativeArray<float3> pos)
{
var count = pos.Length;
var poss = new float3(0, 0, 0);
int k = 0;
int dates = (int)(math.pow(count, 1/3f));
for (int y = 0; y < dates; y++)
{
for (int x = 0; x < dates; x++)
{
for (int z = 0; z < dates; z++)
{
pos[k] = new float3(x*1, y*1, z*1);
k++;
}
}
}
}
//获取材质
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SimpleFileBrowser;
using UnityEngine;
[Serializable]
public class ConfigurationFile
{
public List<string> models = new List<string>();
public List<int> markers = new List<int>();
}
public class IIS_Core : MonoBehaviour
{
[SerializeField] string host = "localhost";
[SerializeField] string port = "8000";
[SerializeField] string scripts_directory = "cgi-bin";
string loginPage = "login.py";
string updatePage = "update.py";
string registerPage = "registration.py";
string uploadPage = "upload.py";
string downloadPage = "download.py";
string fetchAllPage = "fetch_all.py";
private string update_configPage = "update_config.py";
string username;
string accesskey;
static IIS_Core _instance;
[ContextMenu("TestUpload")]
public void TestMeshUpload()
{
string filename = "C://Users/levin/Desktop/Mesh.obj";
UploadFile(filename);
}
[ContextMenu("TestRegister")]
public void TestRegister()
{
StartCoroutine(Register(username, accesskey));
}
[ContextMenu("TestLogin")]
public void TestLogin()
{
StartCoroutine(Login(username, accesskey));
}
[ContextMenu("TestDownloadFile")]
public void TestDownloadFile()
{
StartCoroutine(DownloadFile("Mesh.obj"));
}
public void SetUsername(string newUsername)
{
username = newUsername;
}
public void SetAccesskey(string newAccesskey)
{
accesskey = newAccesskey;
}
public static void SetUpProfile(string username, string accesskey)
{
IIS_Core.Instance.SetUsername(username);
IIS_Core.Instance.SetAccesskey(accesskey);
}
public static void FetchAllFiles(Action OnSuccess = null, Action<string> OnFailed = null)
{
IIS_Core.Instance.DoFetchAll(OnSuccess, OnFailed);
}
public static void LoginIn(string username, string accesskey, Action<string> OnSuccess = null, Action<string> OnFailed=null)
{
IIS_Core.Instance.DoLogin(username, accesskey, OnSuccess, OnFailed);
}
public static void RegisterUser(string username, string accesskey, Action OnSuccess = null, Action<string> OnFailed = null)
{
IIS_Core.Instance.DoRegister(username, accesskey, OnSuccess, OnFailed);
}
protected void DoRegister(string username, string accesskey, Action OnSuccess = null, Action<string> OnFailed = null)
{
StartCoroutine(Register(username, accesskey, OnSuccess, OnFailed));
}
protected void DoLogin(string username, string accesskey, Action<string> OnSuccess = null, Action<string> OnFailed = null)
{
StartCoroutine(Login(username, accesskey, OnSuccess, OnFailed));
}
protected void DoFetchAll(Action OnSuccess = null, Action<string> OnFailed = null)
{
StartCoroutine(FetchAll(OnSuccess, OnFailed));
}
public static IIS_Core Instance
{
get
{
if (_instance) return _instance;
_instance = FindObjectOfType<IIS_Core>();
if (_instance) return _instance;
var container = new GameObject { name = "IIS_Core" };
_instance = container.AddComponent<IIS_Core>();
return _instance;
}
}
public void OpenFileWindow()
{
FileBrowser.SetFilters(false, new FileBrowser.Filter("Models", ".obj"));
FileBrowser.ShowLoadDialog(OnFileSelected, OnFileSelectionCanceled);
}
void OnFileSelected(string filename)
{
UploadFile(filename);
}
void OnFileSelectionCanceled()
{
Debug.Log("Cancel");
}
IEnumerator Register(string username, string accesskey, Action OnSuccess = null, Action<string> OnFailed = null)
{
var registerWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, registerPage);
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("accesskey", accesskey);
var result = new WWW(registerWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
if (OnFailed != null)
{
OnFailed(result.error);
}
print(result.error);
}
else
{
if (OnSuccess != null)
{
OnSuccess();
}
//DecodeSave(result.text);
print(result.text);
}
}
IEnumerator FetchAll(Action OnSuccess = null, Action<string> OnFailed = null)
{
var loginWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, fetchAllPage);
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("accesskey", accesskey);
var result = new WWW(loginWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
if (OnFailed != null)
{
OnFailed(result.error);
}
print(result.error);
}
else
{
if (OnSuccess != null)
{
OnSuccess();
}
print(result.text);
}
}
public static void UpdateCfg(string filename, int index, Action OnSuccess = null, Action<string> OnFailed = null)
{
IIS_Core.Instance.DoUpdateConfig(filename, index, OnSuccess, OnFailed);
}
protected void DoUpdateConfig(string filename, int index, Action OnSuccess = null, Action<string> OnFailed = null)
{
StartCoroutine(UpdateConfig(filename, index, OnSuccess, OnFailed));
}
IEnumerator UpdateConfig(string filename, int index, Action OnSuccess = null, Action<string> OnFailed = null)
{
var loginWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, update_configPage);
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("accesskey", accesskey);
form.AddField("filename", filename);
form.AddField("markerindex", index);
var result = new WWW(loginWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
if (OnFailed != null)
{
OnFailed(result.error);
}
print(result.error);
}
else
{
if (OnSuccess != null)
{
OnSuccess();
}
print(result.text);
}
}
IEnumerator Login(string username, string accesskey, Action<string> OnSuccess= null, Action<string> OnFailed = null)
{
var loginWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, loginPage);
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("accesskey", accesskey);
var result = new WWW(loginWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
if (OnFailed != null)
{
OnFailed(result.error);
}
print(result.error);
}
else
{
if (OnSuccess != null)
{
OnSuccess(result.text);
}
//DecodeSave(result.text);
print(result.text);
}
}
public static void DownloadModel(string name, Action<string> OnDone = null, Action OnFailed = null)
{
IIS_Core.Instance.DoDownloadModel(name, OnDone, OnFailed);
}
protected void DoDownloadModel(string name, Action<string> OnDone = null, Action OnFailed = null)
{
StartCoroutine(DownloadFile(name, OnDone, OnFailed));
}
IEnumerator DownloadFile(string filename, Action<string> OnDone = null, Action OnFailed = null)
{
WWWForm form = new WWWForm();
form.AddField("username", username);
form.AddField("file", filename);
var downloadWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, downloadPage);
var result = new WWW(downloadWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
print(result.error);
if (OnFailed != null)
OnFailed();
}
else
{
if (OnDone != null)
OnDone(result.text);
//print(result.text);
}
}
IEnumerator UploadFileCoroutine(string localFileName)
{
WWW localFile = new WWW("file:///" + localFileName);
yield return localFile;
if (localFile.error == null)
Debug.Log("Loaded file successfully");
else
{
Debug.Log("Open file error: " + localFile.error);
yield break; // stop the coroutine here
}
WWWForm postForm = new WWWForm();
postForm.AddBinaryData("file", localFile.bytes, Path.GetFileName(localFileName), "text/plain");
postForm.AddField("username", username);
var uploadWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, uploadPage);
WWW upload = new WWW(uploadWWW, postForm);
yield return upload;
if (upload.error == null)
{
Debug.Log(upload.text);
DecodeSave(upload.text, FindObjectOfType<UIView>());
}
else
Debug.Log("Error during upload: " + upload.error);
}
void UploadFile(string localFileName)
{
StartCoroutine(UploadFileCoroutine(localFileName));
}
public IEnumerator Save(string save)
{
WWWForm form = new WWWForm();
form.AddField("cfg", save);
form.AddField("username", username);
var UpdateWWW = string.Format("http://{0}:{1}/{2}/{3}", host, port, scripts_directory, updatePage);
var result = new WWW(UpdateWWW, form);
yield return result;
if (!string.IsNullOrEmpty(result.error))
{
print(result.error);
}
else
{
///DecodeSave(result.text);
print(result.text);
}
}
public void Save(Save s)
{
StartCoroutine(Save(JsonUtility.ToJson(s)));
}
public void DecodeSave(string save, IDrawItems r)
{
if(r == null) return;
var obj = JsonUtility.FromJson<ConfigurationFile>(save);
if (obj == null) return;//exception
r.DrawItems(obj);
}
public static void DecodeAndApplySaveToView(string save, IDrawItems r)
{
IIS_Core.Instance.DecodeSave(save, r);
}
}
|
using UnityEngine;
using UnityAtoms.BaseAtoms;
using UnityAtoms.Mobile;
namespace UnityAtoms.Mobile
{
/// <summary>
/// Variable Instancer of type `TouchUserInput`. Inherits from `AtomVariableInstancer<TouchUserInputVariable, TouchUserInputPair, TouchUserInput, TouchUserInputEvent, TouchUserInputPairEvent, TouchUserInputTouchUserInputFunction>`.
/// </summary>
[EditorIcon("atom-icon-hotpink")]
[AddComponentMenu("Unity Atoms/Variable Instancers/TouchUserInput Variable Instancer")]
public class TouchUserInputVariableInstancer : AtomVariableInstancer<
TouchUserInputVariable,
TouchUserInputPair,
TouchUserInput,
TouchUserInputEvent,
TouchUserInputPairEvent,
TouchUserInputTouchUserInputFunction>
{ }
}
|
using System.Collections.Generic;
namespace EPI.BinaryTree.BinarySearchTree
{
public static class IsBinarySearchTree
{
public static bool CheckBSTPropertyRecursive(BinaryTreeNode<int> node)
{
if (node == null)
{
return true;
}
else if ((node.Left != null && node.Value < node.Left.Value) || (node.Right != null && node.Value > node.Right.Value))
{
return false;
}
return CheckBSTPropertyRecursive(node.Left) && CheckBSTPropertyRecursive(node.Right);
}
public static bool CheckBSTProperty(BinaryTreeNode<int> root)
{
Queue<BinaryTreeNode<int>> nodes = new Queue<BinaryTreeNode<int>>();
if (root != null)
{
nodes.Enqueue(root);
}
while (nodes.Count > 0)
{
var currentNode = nodes.Dequeue();
if (currentNode.Left != null)
{
if (currentNode.Value < currentNode.Left.Value)
{
return false;
}
nodes.Enqueue(currentNode.Left);
}
if (currentNode.Right != null)
{
if (currentNode.Value > currentNode.Right.Value)
{
return false;
}
nodes.Enqueue(currentNode.Right);
}
}
return true;
}
}
}
|
using ApiTemplate.Common.Enums.DateTimes;
using ApiTemplate.Common.Markers.Configurations;
namespace ApiTemplate.Core.Configurations.Identity
{
public class IdentityConfiguration : IAppSetting
{
public bool PasswordRequireDigit { get; set; }
public bool PasswordRequireLowercase { get; set; }
public bool PasswordRequireNonAlphanumeric { get; set; }
public bool PasswordRequireUppercase { get; set; }
public bool LockoutAllowedForNewUsers { get; set; }
public bool UserRequireUniqueEmail { get; set; }
public int PasswordRequiredUniqueChars { get; set; }
public int PasswordMinLength { get; set; }
public int LockoutMaxFailedAccessAttempts { get; set; }
public string UserAllowedUserNameCharacters { get; set; }
public int LockoutDefaultLockoutTimeSpan { get; set; }
public Period LockoutType { get; set; }
}
}
|
using Fleck;
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UNO.Model.Karten;
namespace UNO.Model
{
class Spieler : ISpieler
{
public IWebSocketConnection Socket { get; }
public List<IKarte> Karten { get; } = new List<IKarte>();
public string Name { get; }
public bool Aussetzen { get; set; }
public bool Ziehen { get; set; }
public bool Ki { get; }
public int? CardIndex { get; set; }
public bool Spielstarten { get; set; }
public Spieler(string name, IWebSocketConnection socket)
{
Ki = false;
Name = name;
Socket = socket;
Spielstarten = false;
}
//public event Action ZiehtKarte;
public void ZiehtKarte(Queue<IKarte> stapel)
{
Karten.Add(stapel.Dequeue());
}
public void TeileSpielStand(IKarte gelegteKarte, bool aktiv, List<ISpieler> mitspieler)
{
int startIndexSelber = mitspieler.IndexOf(this);
List<object> objSpieler = new List<object>();
for (int i = startIndexSelber +1; i < mitspieler.Count + startIndexSelber; i++)
{
var toogle = false;
if(mitspieler[i % mitspieler.Count] == mitspieler.First())
{
toogle = true;
}
if(mitspieler[i % mitspieler.Count].Name != Name)
{
objSpieler.Add(new { name = mitspieler[i % mitspieler.Count].Name, karten = mitspieler[i % mitspieler.Count].Karten.Count, aktiv = toogle });
}
}
var obj = new { aktuelleKarte = gelegteKarte, aktiv = aktiv, hand = Karten , name = Name, alleSpieler = objSpieler};
var json = new JavaScriptSerializer().Serialize(obj);
Socket.Send(json);
}
public void OnSend(string message)
{
if (message == "START") {
Spielstarten = true;
} else if(message != "Ping")
{
string s = message;
s = s.Replace("card-", "");
try
{
int cardIndex = Int32.Parse(s);
CardIndex = cardIndex;
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
CardIndex = null;
}
}
}
public void HastGewonnen()
{
var obj = new { gewonnen = true};
var json = new JavaScriptSerializer().Serialize(obj);
Socket.Send(json);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResManager : MonoBehaviour {
#if UNITY_STANDALONE
void Awake () {
int h = Screen.currentResolution.height - 100;
int w = h * 9 / 16;
Screen.SetResolution(w, h, false);
}
#endif
}
|
using AutoMapper;
using RTBid.Core.Domain;
using RTBid.Core.Models;
using RTBid.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Hosting;
using System.Web.Http;
namespace RTBid
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute
(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
// Call the Method below
CreateMaps();
}
public static void CreateMaps()
{
Mapper.CreateMap<Auction, AuctionModel>();
Mapper.CreateMap<Bid, BidModel>();
Mapper.CreateMap<Category, CategoryModel>();
Mapper.CreateMap<Comment, CommentModel>();
Mapper.CreateMap<Product, ProductModel>();
Mapper.CreateMap<Purchase, PurchaseModel>();
Mapper.CreateMap<RTBidUser, RTBidUserModel>();
Mapper.CreateMap<RTBidUser, RTBidUserModel.Profile>();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CardController : MonoBehaviour
{
public BoardManager boardManager;
private Image img;
public Sprite[] faces;
public Sprite back;
public int faceIndex;
public bool matched = false;
void Start()
{
boardManager = GameObject.FindGameObjectWithTag("GameController").GetComponent<BoardManager>();
img = gameObject.GetComponent<Image>();
}
public void Click()
{
if (matched == false)
{
if(img.sprite == back)
{
if (boardManager.canMatch == true)
{
img.sprite = faces[faceIndex];
boardManager.MatchCards(this);
}
}
}
}
public void ShowFace()
{
img.sprite = faces[faceIndex];
}
public void ResetCard()
{
img.sprite = back;
}
}
|
using gView.Framework.IO;
namespace gView.Framework.system
{
public class IntegerSequence : IPersistable
{
private int _number = 0, _inc = 1;
private object lockThis = new object();
public IntegerSequence()
{
}
public IntegerSequence(int startValue)
{
_number = startValue;
}
public IntegerSequence(int startValue, int increment)
: this(startValue)
{
_inc = increment;
}
public int Number
{
get
{
lock (lockThis)
{
_number += _inc;
return _number;
}
}
}
public void SetToIfLower(int number)
{
if (_number < number)
{
_number = number;
}
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
_number = (int)stream.Load("number", 0);
_inc = (int)stream.Load("increment", 0);
}
public void Save(IPersistStream stream)
{
stream.Save("number", _number);
stream.Save("increment", _inc);
}
#endregion
}
}
|
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
namespace tellick_admin.Controllers {
[Route("api/[controller]")]
public class AuthController : Controller
{
[AllowAnonymous]
[HttpPost("login", Name = "Login")]
public IActionResult Login([FromBody] AuthRequest request) {
if (request.Username == "development" && request.Password == "development") { //@todo make it so it works with asp.net identity
var claims = new[] {
new Claim(ClaimTypes.Name, request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.JwtSigningKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: Settings.JwtIssuer,
audience: Settings.JwtAudience,
claims: claims,
expires: DateTime.Now.AddDays(28),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
return BadRequest("Could not verify username and password");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Models
{
public class PaymentDetail
{
public int Id { get; set; }
public int? InvoiceId { get; set; }
public virtual Invoice Invoice { get; set; }
public int? InvoiceDetailId { get; set; }
public virtual InvoiceDetail InvoiceDetail { get; set; }
public int PaymentId { get; set; }
public virtual Payment Payment { get; set; }
}
}
|
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class CharacterSkill
{
public int[] Id_comp { get; set; }
public CharacterSkill()
{
}
}
} |
using NDesk.Options;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SharpApplocker {
internal class Program {
private static bool CheckModes(int threshold, IEnumerable<bool> modes) => modes.Count(b => b) == threshold;
private static void ShowHelp(OptionSet p) {
Console.WriteLine("Usage:");
p.WriteOptionDescriptions(Console.Out);
Console.WriteLine("\n for detailed information please take a look at the MSDN url: https://docs.microsoft.com/en-us/powershell/module/applocker/get-applockerpolicy?view=win10-ps");
}
static void Main(string[] args) {
Info.PrintBanner();
bool help = false;
bool xmlOutput = false;
bool localPolicy = false;
bool domainPolicy = false;
bool effectivePolicy = false;
String ldapPath = "";
var options = new OptionSet(){
{"h|?|help","Show Help\n", o => help = true},
{"l|local","Queries local applocker config\n",o=>localPolicy = true },
{"d|domain","Queries domain applocker config (needs an ldap path)\n", o => domainPolicy = true },
{"e|effective","Queries the effective applocker config on this computer\n", o => effectivePolicy = true },
{"x|xml","Output AppLocker in XML format (default is json) \n", o => xmlOutput = true },
{"ldap=","The ldap filter to query the domain policy from\n", o => ldapPath = o }
};
try {
options.Parse(args);
IEnumerable<bool> modes = new List<bool> { localPolicy, domainPolicy, effectivePolicy };
if(CheckModes(0,modes)) {
ShowHelp(options);
return;
}
if(!CheckModes(1, modes)) {
Console.WriteLine("You can only select one Policy at the time.");
return;
}
if(domainPolicy && String.IsNullOrEmpty(ldapPath)) {
Console.WriteLine("You can only query domain AppLocker configuration if you specify an LDAP filter.");
return;
}
if (help) {
ShowHelp(options);
return;
}
if (localPolicy)
Console.WriteLine(SharpAppLocker.GetAppLockerPolicy(SharpAppLocker.PolicyType.Local, ldapPath, xmlOutput));
else if (domainPolicy)
Console.WriteLine(SharpAppLocker.GetAppLockerPolicy(SharpAppLocker.PolicyType.Domain, ldapPath, xmlOutput));
else if (effectivePolicy)
Console.WriteLine(SharpAppLocker.GetAppLockerPolicy(SharpAppLocker.PolicyType.Effective, ldapPath, xmlOutput));
else
throw new ArgumentException("mode not found");
} catch (Exception e) {
Console.Error.WriteLine(e.Message);
ShowHelp(options);
return;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.master2.model
{
public class MethodTypeCall
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string className;
public string ClassName
{
get { return className; }
set { className = value; }
}
}
public class IncomingCall : MethodTypeCall
{
}
public class OutgoingCall : MethodTypeCall
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace NStandard.Obsolete.Evaluators
{
public class NumericalRTEvaluator : Evaluator<double, string>
{
protected override Dictionary<string, int> OpLevels { get; } = new Dictionary<string, int>
{
["*"] = 3,
["/"] = 3,
["%"] = 3,
["+"] = 4,
["-"] = 4,
};
protected override Dictionary<string, BinaryOpFunc<double>> OpFunctions { get; } = new Dictionary<string, BinaryOpFunc<double>>
{
["*"] = (left, right) => left * right,
["/"] = (left, right) => left / right,
["%"] = (left, right) => left % right,
["+"] = (left, right) => left + right,
["-"] = (left, right) => left - right,
};
#if NET35 || NET40 || NET45 || NET451 || NET46
protected override Dictionary<Tuple<string, string>, SingleOpFunc<double>> BracketFunctions { get; } = new Dictionary<Tuple<string, string>, SingleOpFunc<double>>
{
[Tuple.Create("(", ")")] = null,
};
#else
protected override Dictionary<(string, string), UnaryOpFunc<double>> BracketFunctions { get; } = new Dictionary<(string, string), UnaryOpFunc<double>>
{
[("(", ")")] = null,
};
#endif
private readonly string[] RegexSpecialLetters = { "[", "]", "-", ".", "^", "$", "{", "}", "?", "+", "*", "|", "(", ")" };
public void Resolve(string exp, out double[] operands, out string[] operators)
{
// Similar to NumericalEvaluator.Resolve
var operatorsPart = OpFunctions.Keys
.Concat(BracketFunctions.Keys.Select(x => x.Item1))
.Concat(BracketFunctions.Keys.Select(x => x.Item2))
.OrderByDescending(x => x.Length)
.Select(x => x.RegexReplace(new Regex(@"([\[\]\-\.\^\$\{\}\?\+\*\|\(\)])"), "\\$1"))
.Join("|");
// Different from NumericalEvaluator.Resolve
var resolveRegex = new Regex($@"^(?:\s*(\d+|\d+\.\d+|\-\d+|\-\d+\.\d+|0x[\da-fA-F]+|0[0-7]+|)\s*({operatorsPart}|$))+\s*$");
if (exp.TryResolve(resolveRegex, out var parts))
{
operators = parts[2].Where(x => x != "").ToArray();
operands = parts[1].Take(operators.Length + 1).Select(s =>
{
if (s.IsNullOrWhiteSpace()) return default;
double ret;
if (s.StartsWith("0x")) ret = Convert.ToInt64(s, 16);
else if (s.StartsWith("0")) ret = Convert.ToInt64(s, 8);
else ret = Convert.ToDouble(s);
return ret;
}).ToArray();
}
else throw new ArgumentException($"Invalid expression string( {exp} ).");
}
public double Eval(string exp)
{
Resolve(exp, out var operands, out var operators);
var result = Eval(operands, operators);
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RC.Models;
using RC.Infra;
namespace RC.Controllers
{
public class IncidenteController : RCController
{
private RCContext db = new RCContext();
public ActionResult Create()
{
ViewBag.IdCategoria = new SelectList(db.Categorias, "Id", "Nome");
return View();
}
//
// POST: /Incidente/Create
[HttpPost]
public ActionResult Create(Incidente incidente)
{
try
{
if (ModelState.IsValid)
{
db.Incidentes.Add(incidente);
db.SaveChanges();
Alert = new RCAlert("Novo incidente adicionado.", AlertType.Success);
return RedirectToAction("Create");
}
}
catch (Exception e) { }
ViewBag.IdCategoria = new SelectList(db.Categorias, "Id", "Nome", incidente.IdCategoria);
return View(incidente);
}
//
// GET: /Incidente/Edit/5
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Upgrader.SqLite;
namespace Upgrader.Test.SqLite
{
[TestClass]
public class ForeignKeyCollectionSqLiteTest : ForeignKeyCollectionTest
{
public ForeignKeyCollectionSqLiteTest() : base(new SqLiteDatabase(AssemblyInitialize.SqLiteConnectionString))
{
}
[ExpectedException(typeof(NotSupportedException))]
[TestMethod]
public override void RemoveRemovesForeignKey()
{
base.RemoveRemovesForeignKey();
}
}
}
|
using LightMessagingCore.Boilerplate.Common;
using MassTransit;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Boilerplate.OrderService
{
class Program
{
static void Main(string[] args)
{
Console.Title = "OrderService";
var bus = BusConfigurator.Instance
.ConfigureBus((cfg, host) =>
{
cfg.ReceiveEndpoint(host, ConfigurationManager.AppSettings["OrderQueueName"], e =>
{
e.Consumer<OrderReceivedConsumer>();
});
});
bus.Start();
Console.WriteLine("Listening order command..");
Console.ReadLine();
}
}
}
|
using IPS.Core;
using KartObjects;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace AxiEndPoint.EndPointServer.MessageHandlers
{
public class SetExtDiscountRelation : IMessageHandler
{
private readonly ServerSettings _settings;
public SetExtDiscountRelation(ServerSettings settings)
{
_settings = settings;
}
private const string SET_EXT_DISCOUNT_RELATION = "SetExtDiscountRelation";
string DiscountCardCode;
string MACAddress;
public byte[] Handle(MessageEventArgs args)
{
string[] sa = args.Message.Command.CommandText.Split('^');
if (args.Message.Command.CommandText.StartsWith(SET_EXT_DISCOUNT_RELATION) && (sa.Count() > 0))
{
DiscountCardCode = sa[1];
MACAddress = sa[2];
}
DiscountCard discountCard = null;
if (Loader.DataContext == null)
Loader.DataContext = new FbDataConnection(_settings.ConnectionString);
if (Saver.DataContext==null)
Saver.DataContext = Loader.DataContext ;
if (Loader.DataContext.CheckConnection())
{
try
{
Loader.DataContext.BeginTransaction();
discountCard = Loader.DbLoad<DiscountCard>("CardCode='" + DiscountCardCode + "'").FirstOrDefault();
discountCard.ClientMACaddress = MACAddress;
Saver.SaveToDb<DiscountCard>(discountCard);
Loader.DataContext.CommitTransaction();
ServicePointManager.ServerCertificateValidationCallback =
(sende, certificate, chain, sslPolicyErrors) =>
true;
var client = new RestClient("https://info-point.me:1441/IPS");
var request = new RestRequest("FinishRegCodeOp", Method.POST) { RequestFormat = DataFormat.Json };
var r = new IPSDTO<IPSRegCode>()
{
Object = new IPSRegCode()
{
InfoPointCode=_settings.InfoPointCode,
Code=MACAddress,
LocalCode=DiscountCardCode
}
};
request.AddBody(r);
var response = client.Execute<IPSDTO<IPSRegCode>>(request);
}
catch (Exception)
{
Loader.DataContext.RollBackTransaction();
throw;
}
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, true);
AxiEndPoint.EndPointServer.Logging.Log.Debug(args.ClientIp + "Сохранена дисконтная карта " + discountCard.Id);
return ms.ToArray();
}
}
else return null;
}
public bool SatisfyBy(EndPointClient.Transfer.Message message)
{
return message.Command.CommandText.StartsWith(SET_EXT_DISCOUNT_RELATION);
}
}
}
|
using LHRLA.Core.Helpers;
using LHRLA.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LHRLA.Controllers
{
[SessionAttribute]
public class CaseStatusController : Controller
{
// GET: CaseStatus
[AuthOp]
public ActionResult List()
{
LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess ctd = new LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess();
var list = ctd.GetAllCaseStatus();
//ViewBag.City = null;
return View(list);
}
public ActionResult AddUpdateCaseStatus(tbl_Case_Status request)
{
LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess ctd = new LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess();
var Code = request.Code.ToLower().Trim();
var CaseStatusData = ctd.GetCaseStatusbyIDOnUpdate(request.ID,Code);
var CaseStatusCode = CaseStatusData.Select(o => o.Code).FirstOrDefault();
var CaseStatusExistingData = ctd.GetCaseStatusbyIDOfExistingData(request.ID, Code);
var CaseStatusExistingCode = CaseStatusExistingData.Select(o => o.Code).FirstOrDefault();
var flag = true;
if (request.ID > 0)
{
if (CaseStatusCode != Code)
{
flag = ctd.UpdateCaseStatus(request);
}
else if (CaseStatusExistingCode == Code)
{
flag = ctd.UpdateCaseStatus(request);
}
else
{
return Json(new { IsSuccess = false, ErrorMessage = (flag == false) ? CustomMessages.Success : CustomMessages.GenericErrorMessage, Response = (flag == true) ? Url.Action("Index", "CaseStatus") : null }, JsonRequestBehavior.AllowGet);
}
}
// var flag = request.ID > 0 ? bda.UpdateBranch(request) : bda.AddBranch(request);
else
{
var CheckDuplicate = ctd.CheckDuplicateData(Code);
if (CheckDuplicate.Count > 0)
{
return Json(new { IsSuccess = false, ErrorMessage = (flag == false) ? CustomMessages.DuplicateEmail : CustomMessages.GenericErrorMessage, Response = (flag == false) ? Url.Action("Index", "CaseStatus") : null }, JsonRequestBehavior.AllowGet);
}
else
{
flag = ctd.AddCaseStatus(request);
}
}
// var flag = request.ID > 0 ? ctd.UpdateCaseStatus(request) : ctd.AddCaseStatus(request);
return Json(new { IsSuccess = flag, ErrorMessage = (flag == true) ? CustomMessages.Success : CustomMessages.GenericErrorMessage, Response = (flag == true) ? Url.Action("Index", "CaseStatus") : null }, JsonRequestBehavior.AllowGet);
}
[AuthOp]
public ActionResult Index(int? id)
{
if (id == 0)
{
return View();
}
int Caseid = Convert.ToInt32(id);
LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess ctd = new LHRLA.DAL.DataAccessClasses.CaseStatusDataAccess();
var flag = ctd.GetCaseStatusbyID(Caseid).FirstOrDefault();
return View(flag);
}
}
} |
using System;
using System.Windows.Input;
namespace Battleship.Wpf.GameBoard.Commands
{
public class RelayCommand : ICommand
{
private Action<object> _executeCallback;
private Func<object, bool> _canExecuteCallback;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<object> executeCallback, Func<object, bool> canExecuteCallback = null)
{
_executeCallback = executeCallback ?? throw new ArgumentNullException(nameof(executeCallback));
_canExecuteCallback = canExecuteCallback;
}
public bool CanExecute(object parameter)
{
if (_canExecuteCallback != null)
return _canExecuteCallback.Invoke(parameter);
return true;
}
public void Execute(object parameter)
{
_executeCallback(parameter);
}
}
}
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace FTPServer
{
/// <summary>
/// Server 的摘要描述。
/// </summary>
class Server
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
//IPAddress serverIP = IPAddress.Parse("127.0.0.1") ;
String hostname = Dns.GetHostName() ;
IPAddress serverIP = Dns.Resolve(hostname).AddressList[0] ;
// FTP Server Port = 21
String Port = "21" ;
IPEndPoint serverhost = new IPEndPoint(serverIP, Int32.Parse(Port)) ;
Socket serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp) ;
serverSocket.Bind(serverhost) ;
// Backlog = 100
serverSocket.Listen(100) ;
Console.WriteLine("FTP server started at: " + serverhost.Address.ToString() + ":" + Port) ;
FTPSession ftpSession = new FTPSession(serverSocket) ;
ThreadStart serverThreadStart = new ThreadStart(ftpSession.FTPSessionThread);
Thread serverthread = new Thread(serverThreadStart);
serverthread.Start() ;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString()) ;
}
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.Data.Entity;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Timeclock.Test.TestUtils;
//using TimeClock.Data;
//using TimeClock.Data.Models;
//namespace Timeclock.Test
//{
// internal class TestTimeClockContext : ITimeClockContext
// {
// public TestTimeClockContext()
// {
// this.Employees = new TestDbSet<Employee>();
// }
// public DbSet<Employee> Employees { get; set; }
// public int SaveChangesCount { get; private set; }
// public int SaveChanges()
// {
// this.SaveChangesCount++;
// return 1;
// }
// }
//}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CarritoCompras.Modelo
{
public class Producto
{
public string idproducto { get; set; }
public string descripcion { get; set; }
public string detalle { get; set; }
public string imagen { get; set; }
public string nombre { get; set; }
public float precio { get; set; }
public int stock { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.