text stringlengths 13 6.01M |
|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using Microsoft.Win32;
using Kingdee.CAPP.Common.FileRegister;
namespace Kingdee.CAPP.Uninstall
{
[RunInstaller(true)]
public partial class CADCuxUninstall : System.Configuration.Install.Installer
{
public CADCuxUninstall()
{
InitializeComponent();
}
/// <summary>
/// 卸载时删除已注册的CAP文件
/// 同时删除CAD 文件
/// </summary>
/// <param name="savedState"></param>
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
#region 卸载已注册的CAP文件
RegistryKey capReg = Registry.ClassesRoot.OpenSubKey(".cap");
RegistryKey capFileTypeReg = Registry.ClassesRoot.OpenSubKey(".CA_FileType");
if (capReg != null)
{
Registry.ClassesRoot.DeleteSubKeyTree(".cap");
}
if (capFileTypeReg != null)
{
Registry.ClassesRoot.DeleteSubKeyTree(".CA_FileType");
}
#endregion
/// 重置AutoCAD菜单
FileTypeRegister.ResetAutoCADMenu();
#region 删除Solidworks插件
try
{
Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
string keyname = "SOFTWARE\\SolidWorks\\Addins\\{2eff6d31-932a-4191-ad00-1d705e27a64f}";
hklm.DeleteSubKey(keyname);
keyname = "Software\\SolidWorks\\AddInsStartup\\{2eff6d31-932a-4191-ad00-1d705e27a64f}";
hkcu.DeleteSubKey(keyname);
}
catch (System.NullReferenceException nl)
{
}
catch (System.Exception e)
{
}
#endregion
}
}
}
|
using System;
using System.Runtime.Serialization;
using Xero.Api.Common;
namespace Xero.Api.Core.Model
{
[Serializable]
[DataContract(Namespace = "")]
public sealed class Item : HasUpdatedDate, IHasId
{
[DataMember(Name = "ItemID", EmitDefaultValue = false)]
public Guid Id { get; set; }
[DataMember]
public string Code { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Description { get; set; }
[DataMember(EmitDefaultValue = false)]
public PurchaseDetails PurchaseDetails { get; set; }
[DataMember(EmitDefaultValue = false)]
public SalesDetails SalesDetails { get; set; }
[DataMember]
public string InventoryAssetAccountCode { get; set; }
[DataMember(EmitDefaultValue = false)]
public decimal? QuantityOnHand { get; set; }
[DataMember(EmitDefaultValue = false)]
public bool? IsSold { get; set; }
[DataMember(EmitDefaultValue = false)]
public bool? IsPurchased { get; set; }
[DataMember(EmitDefaultValue = false)]
public string PurchaseDescription { get; set; }
[DataMember(EmitDefaultValue = false)]
public bool IsTrackedAsInventory { get; set; }
[DataMember(EmitDefaultValue = false)]
public decimal? TotalCostPool { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Name { get; set; }
}
}
|
using NGeoNames.Entities;
using System;
using System.Globalization;
namespace NGeoNames.Parsers
{
/// <summary>
/// Provides methods for parsing a <see cref="CountryInfo"/> object from a string-array.
/// </summary>
public class CountryInfoParser : BaseParser<CountryInfo>
{
private static readonly char[] csv = { ',' };
/// <summary>
/// Gets wether the file/stream has (or is expected to have) comments (lines starting with "#").
/// </summary>
public override bool HasComments
{
get { return true; }
}
/// <summary>
/// Gets the number of lines to skip when parsing the file/stream (e.g. 'headers' etc.).
/// </summary>
public override int SkipLines
{
get { return 0; }
}
/// <summary>
/// Gets the number of fields the file/stream is expected to have; anything else will cause a <see cref="ParserException"/>.
/// </summary>
public override int ExpectedNumberOfFields
{
get { return 19; }
}
/// <summary>
/// Parses the specified data into a <see cref="CountryInfo"/> object.
/// </summary>
/// <param name="fields">The fields/data representing a <see cref="CountryInfo"/> to parse.</param>
/// <returns>Returns a new <see cref="CountryInfo"/> object.</returns>
public override CountryInfo Parse(string[] fields)
{
return new CountryInfo
{
ISO_Alpha2 = fields[0],
ISO_Alpha3 = fields[1],
ISO_Numeric = fields[2],
FIPS = fields[3],
Country = fields[4],
Capital = fields[5],
Area = fields[6].Length > 0 ? (float?)float.Parse(fields[6], CultureInfo.InvariantCulture) : null,
Population = int.Parse(fields[7]),
Continent = fields[8],
Tld = fields[9],
CurrencyCode = fields[10],
CurrencyName = fields[11],
Phone = fields[12].Length > 0 && fields[12].StartsWith("+") ? fields[12] : "+" + fields[12],
PostalCodeFormat = fields[13],
PostalCodeRegex = fields[14],
Languages = fields[15].Split(csv, StringSplitOptions.RemoveEmptyEntries),
GeoNameId = fields[16].Length > 0 ? (int?)int.Parse(fields[16], CultureInfo.InvariantCulture) : null,
Neighbours = fields[17].Split(csv, StringSplitOptions.RemoveEmptyEntries),
EquivalentFipsCode = fields[18]
};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerUpgrades : MonoBehaviour {
PlayerController controller;
public Text plasmaMembraneText;
public Text locomotionText;
public Text HomeostasisText;
public int plasmaMembraneLvl = 1;
public int locomotionLvl = 1;
public int homeostasisLvl = 1;
public GameObject attractor;
public GameObject repulsor;
PointEffector2D attractorEffector;
CircleCollider2D repulsorCollider;
PointEffector2D repulsorEffector;
CircleCollider2D attractorCollider;
Move moveScript;
public GameObject UpgradesPanel;
void Start() {
controller = GetComponent<PlayerController> ();
attractorEffector = attractor.GetComponent<PointEffector2D> ();
attractorCollider = attractor.GetComponent<CircleCollider2D> ();
repulsorEffector = repulsor.GetComponent<PointEffector2D> ();
repulsorCollider = repulsor.GetComponent<CircleCollider2D> ();
moveScript = GetComponent<Move> ();
}
public void UpgradePlasmaMembrane() {
int squared = plasmaMembraneLvl * plasmaMembraneLvl;
if (controller.chemical >= squared) {
controller.chemical -= squared;
plasmaMembraneLvl ++;
plasmaMembraneText.text = "Plasma Membrane " + (plasmaMembraneLvl * plasmaMembraneLvl) + "c";
attractorCollider.radius += 1;
attractorEffector.forceMagnitude -= 1;
repulsorCollider.radius += 0.5f;
repulsorEffector.forceMagnitude += 0.6f;
}
}
public void UpgradeLocomotion() {
int squared = locomotionLvl * locomotionLvl;
if (controller.chemical >= squared) {
controller.chemical -= squared;
locomotionLvl ++;
locomotionText.text = "Locomotion " + (locomotionLvl * locomotionLvl) + "c";
moveScript.maxForce += 0.5f;
moveScript.attractionSpeed += 0.1f;
}
}
public void UpgradeHomeostasis() {
int squared = homeostasisLvl * homeostasisLvl;
if (controller.chemical >= squared) {
controller.chemical -= squared;
homeostasisLvl++;
HomeostasisText.text = "Homeostatis: " + (homeostasisLvl * homeostasisLvl) + "c";
}
}
public void Update() {
if (Input.GetKeyUp(KeyCode.X)) {
moveScript.enabled = UpgradesPanel.activeSelf;
UpgradesPanel.SetActive(!UpgradesPanel.activeSelf);
}
}
}
|
using System;
namespace ScriptKit
{
public delegate IntPtr JsNativeFunction(IntPtr calle, bool isConstructCall, IntPtr arguments, ushort argumentCount, IntPtr callbackState);
}
|
using Chess.v4.Models;
using Chess.v4.Models.Enums;
using Common.Responses;
using System.Collections.Generic;
namespace Chess.v4.Engine.Interfaces
{
public interface IMoveService
{
OperationResult<StateInfo> GetStateInfo(GameState newGameState, int piecePosition, int newPiecePosition);
StateInfo GetStateInfo(GameState gameState);
bool HasThreefoldRepition(GameState gameState);
//bool IsEnPassant(Square square, int newPiecePosition, string enPassantTargetSquare);
//bool IsRealCheck(List<Square> squares, IEnumerable<AttackedSquare> attacksThatCheckWhite, Color activeColor, int kingSquare);
OperationResult<bool> IsValidCastleAttempt(GameState gameState, Square square, int destination, IEnumerable<AttackedSquare> attackedSquares);
//bool IsValidPawnMove(Square square, List<Square> oldSquares, Color color, int piecePosition, int newPiecePosition, bool isEnPassant);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Controls;
using System.Globalization;
using System.Resources;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using My_Note.Lang;
using System.Text.RegularExpressions;
namespace My_Note
{
public partial class MainPage : PhoneApplicationPage
{
List<Note> Notes;
// 构造函数
public MainPage()
{
InitializeComponent();
BuildLocalizedApplicationBar();
GetBindList();
}
#region 生成Appbar -BuildLocalizedApplicationBar()
/// <summary>
/// 生成Appbar
/// </summary>
private void BuildLocalizedApplicationBar()
{
// 将页面的 ApplicationBar 设置为 ApplicationBar 的新实例。
ApplicationBar = new ApplicationBar();
ApplicationBar.Opacity = 0.78;
ApplicationBar.IsVisible = true;
ApplicationBar.IsMenuEnabled = true;
// 创建新按钮并将文本值设置为 AppResources 中的本地化字符串。
ApplicationBarIconButton addAppBarButton = new ApplicationBarIconButton(new Uri("/Images/appbar.add.rest.png", UriKind.Relative));
addAppBarButton.Text = AppResources.MainPageAppbarButtonAdd;
addAppBarButton.Click += AppBar_Add_Click;
ApplicationBar.Buttons.Add(addAppBarButton);
// 使用 AppResources 中的本地化字符串创建新菜单项。
ApplicationBarMenuItem SettingAppBarMenuItem = new ApplicationBarMenuItem(AppResources.MainPageAppbarMenuSetting);
SettingAppBarMenuItem.Click += AppBar_Setting_Click;
ApplicationBar.MenuItems.Add(SettingAppBarMenuItem);
}
#endregion
#region 页面载入事件 -PhoneApplicationPage_Loaded
/// <summary>
/// 页面载入事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
#region 墓碑事件
string state = "";
if (settings.Contains("state"))
{
if (settings.TryGetValue<string>("state", out state))
{
if (state == "edit")
{
NavigationService.Navigate(new Uri("/My_Note;component/ViewEdit.xaml", UriKind.Relative));
}
else if (state == "add")
{
NavigationService.Navigate(new Uri("/My_Note;component/Add.xaml", UriKind.Relative));
}
}
}
#endregion
//Dispatcher.BeginInvoke(new Action(() => { GetBindList(); }), null);
}
#endregion
#region Appbar按钮事件
/// <summary>
/// 增加笔记按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppBar_Add_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/My_Note;component/Add.xaml", UriKind.Relative));
}
/// <summary>
/// 设置菜单
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppBar_Setting_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/My_Note;component/Setting/Setting.xaml", UriKind.Relative));
}
#endregion
#region 获取绑定的List<>对象 -GetBindList
/// <summary>
/// 获取绑定的List<>对象
/// </summary>
private void GetBindList()
{
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileList = appStorage.GetFileNames("*.txt");
//fileList = fileList.OrderByDescending(s => int.Parse(Regex.Match(s.Replace('_','\0'), @"\d+").Value)).ToArray();
Notes = new List<Note>();
foreach (string file in fileList)
{
if (file != "__ApplicationSettings")
{
string fileName = file;
BitmapImage image;
if (appStorage.FileExists(file + ".jpg"))
{
image = new BitmapImage();
Stream imagestream = appStorage.OpenFile(file + ".jpg", FileMode.Open, FileAccess.Read);
image.SetSource(imagestream);
}
else
{
image = null;
}
int year = int.Parse(fileName.Substring(0, 4), CultureInfo.InvariantCulture);
int month = int.Parse(fileName.Substring(5, 2), CultureInfo.InvariantCulture);
int day = int.Parse(fileName.Substring(8, 2), CultureInfo.InvariantCulture);
int hour = int.Parse(fileName.Substring(11, 2), CultureInfo.InvariantCulture);
int minute = int.Parse(fileName.Substring(14, 2), CultureInfo.InvariantCulture);
int second = int.Parse(fileName.Substring(17, 2), CultureInfo.InvariantCulture);
DateTime DataCreated = new DateTime(year, month, day, hour, minute, second);
string title = fileName.Substring(20);
title = title.Substring(0, title.Length - 4);
DateTime data = appStorage.GetLastWriteTime(file).DateTime;
Notes.Add(new Note(DataCreated, fileName, title, image, data));
}
}
appStorage.Dispose();
Notes.Sort((x, y) => y.Data.CompareTo(x.Data));
}
#endregion
#region 绑定笔记列表 -BindList
/// <summary>
/// 绑定笔记列表
/// </summary>
private void BindList()
{
//var source = from item in ListSource where(NoteListBox.Items.Count<ListSource.Count()) select item;
if (NoteListBox.Items.Count == 0&&Notes.Count!=0)
{
foreach (var item in Notes)
{
NoteListBox.Items.Add(item);
}
}
//NoteListBox.ItemsSource = ListSource;
}
#endregion
#region 笔记点击事件 -NoteClick_Click
/// <summary>
/// 笔记点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NoteClick_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton hb = (HyperlinkButton)sender;
string uri = hb.Tag.ToString();
NavigationService.Navigate(new Uri("/My_Note;component/ViewEdit.xaml?id=" + uri, UriKind.Relative));
}
#endregion
#region 重写返回事件 -OnBackKeyPress
/// <summary>
/// 重写返回事件
/// </summary>
/// <param name="e"></param>
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
ResourceManager rm = new ResourceManager(typeof(My_Note.Lang.AppResources));
if (MessageBox.Show(rm.GetString("ExitMessageText"), rm.GetString("ExitText"), MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
else
{
//new Microsoft.Xna.Framework.Game().Exit();
}
}
#endregion
#region 重写界面更新事件 -Page_LayoutUpdated
/// <summary>
/// 重写界面更新事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_LayoutUpdated(object sender, EventArgs e)
{
Dispatcher.BeginInvoke(new Action(() => { BindList(); }), null);
}
#endregion
#region 工具箱按钮
/// <summary>
/// 计算器工具按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolBoxCalButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/My_Note;component/ToolBox/Calculator.xaml", UriKind.Relative));
}
/// <summary>
/// 录音工具按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ToolBoxToolBoxRecVoiceButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/My_Note;component/ToolBox/RecordVoice.xaml", UriKind.Relative));
}
#endregion
}
} |
// <copyright file="FirstTaskTest.cs" company="MyCompany.com">
// Contains the solutions to tasks of the 'Methods in detail' module.
// </copyright>
// <author>Daryn Akhmetov</author>
namespace Methods_in_details_Tests
{
using System;
using Methods_in_detail;
using NUnit.Framework;
/// <summary>
/// This is a test class for FirstTask and is intended
/// to contain all FirstTask Unit Tests.
/// </summary>
[TestFixture]
public class FirstTaskTest
{
/// <summary>
/// A test for ToIEEE754.
/// </summary>
/// <param name="number">Real number to be converted.</param>
/// <returns>IEEE 754 binary representation of the given number.</returns>
[TestCase(-255.255, ExpectedResult = "1100000001101111111010000010100011110101110000101000111101011100")]
[TestCase(255.255, ExpectedResult = "0100000001101111111010000010100011110101110000101000111101011100")]
[TestCase(4294967295.0, ExpectedResult = "0100000111101111111111111111111111111111111000000000000000000000")]
[TestCase(double.MinValue, ExpectedResult = "1111111111101111111111111111111111111111111111111111111111111111")]
[TestCase(double.MaxValue, ExpectedResult = "0111111111101111111111111111111111111111111111111111111111111111")]
[TestCase(double.Epsilon, ExpectedResult = "0000000000000000000000000000000000000000000000000000000000000001")]
[TestCase(double.NaN, ExpectedResult = "1111111111111000000000000000000000000000000000000000000000000000")]
[TestCase(double.NegativeInfinity, ExpectedResult = "1111111111110000000000000000000000000000000000000000000000000000")]
[TestCase(double.PositiveInfinity, ExpectedResult = "0111111111110000000000000000000000000000000000000000000000000000")]
[TestCase(-0.0, ExpectedResult = "1000000000000000000000000000000000000000000000000000000000000000")]
[TestCase(0.0, ExpectedResult = "0000000000000000000000000000000000000000000000000000000000000000")]
[TestCase(0.00001, ExpectedResult = "0011111011100100111110001011010110001000111000110110100011110001")]
[TestCase(1.0000000000000002, ExpectedResult = "0011111111110000000000000000000000000000000000000000000000000001")]
[TestCase(1.0000000000000004, ExpectedResult = "0011111111110000000000000000000000000000000000000000000000000010")]
[TestCase(1, ExpectedResult = "0011111111110000000000000000000000000000000000000000000000000000")]
[TestCase(2, ExpectedResult = "0100000000000000000000000000000000000000000000000000000000000000")]
[TestCase(23, ExpectedResult = "0100000000110111000000000000000000000000000000000000000000000000")]
[TestCase(0.01171875, ExpectedResult = "0011111110001000000000000000000000000000000000000000000000000000")]
[TestCase((double)1 / 3, ExpectedResult = "0011111111010101010101010101010101010101010101010101010101010101")]
[TestCase(Math.PI, ExpectedResult = "0100000000001001001000011111101101010100010001000010110100011000")]
public string ToIEEE754Test(double number)
{
return number.ToIEEE754();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimCorp_test_task
{
public class Investments : IInvestments
{
public List<PaymentHistory> GetTheAmountOfInterestFromTheInvestment(DateTime agreementDate,
double investmentAmount, double interestRate, int investmentDuration)
{
// Interest rate per month
double i = interestRate / 12;
//Number of months in investment
int n = investmentDuration * 12;
// Payment ratio0
double k = i * (Math.Pow(1 + i, n)) / (Math.Pow(1 + i, n)-1);
// Monthly payment amount
double a = k * investmentAmount;
var paymentHistory = new List<PaymentHistory>();
var investmentBalance = investmentAmount;
for (int m = 1; m <= n; m++)
{
var precent = investmentBalance * i;
var payout = a - precent;
investmentBalance -= payout;
paymentHistory.Add(new PaymentHistory {
Date = agreementDate.AddMonths(m),
Payout = payout,
Percent = precent
});
}
return paymentHistory;
}
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using System;
using System.IO;
using System.Text;
namespace gView.Framework.OGC.WFS
{
public class GetFeatureRequest
{
static public string Create(IFeatureClass fc, string typeName, IQueryFilter filter, string srsName, Filter_Capabilities filterCapabilites, GmlVersion version)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms, Encoding.UTF8);
sw.WriteLine(
@"<?xml version=""1.0"" ?>
<wfs:GetFeature
version=""1.0.0""
service=""WFS""
maxfeatures=""5000""
handle=""gView Query""
xmlns=""http://www.opengis.net/wfs""
xmlns:wfs=""http://www.opengis.net/wfs""
xmlns:ogc=""http://www.opengis.net/ogc""
xmlns:gml=""http://www.opengis.net/gml""
xmlns:gv=""http://www.gview.com/server""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xsi:schemaLocation=""http://www.opengis.net/wfs ../wfs/1.1.0/WFS.xsd"">
<wfs:Query typeName=""" + typeName + @"""" + ((srsName != String.Empty) ? " srsName=\"" + srsName + "\"" : "") + " >");
if (filter.SubFields != "*" && filter.SubFields != "#ALL#")
{
foreach (string field in filter.SubFields.Split(' '))
{
sw.Write("<wfs:PropertyName>" + field + "</wfs:PropertyName>");
}
}
else
{
foreach (IField field in fc.Fields.ToEnumerable())
{
sw.Write("<wfs:PropertyName>" + field.name + "</wfs:PropertyName>");
}
}
sw.WriteLine(Filter.ToWFS(fc, filter, filterCapabilites, version));
sw.WriteLine(
@"</wfs:Query>
</wfs:GetFeature>");
sw.Flush();
ms.Position = 0;
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
sw.Close();
string ret = Encoding.UTF8.GetString(bytes).Trim();
return ret;
}
}
}
|
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestHello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
int myInt = 1;
Console.WriteLine(myInt);
float myFloat = 0.42f;
bool myBoolean = true;
string myName = "John";
char myChar = 'a';
StringBuilder address = new StringBuilder();
address.Append("8150");
address.Append(", Marne Road");
address.Append(", Ft Benning, GA 31905");
string concatenatedAddress = address.ToString();
Console.WriteLine(concatenatedAddress);
// Concatenating multiple strings in Visual C# is simple to achieve by using the + operator.
// However, this is considered bad coding practice because strings are immutable.
// This means that every time you concatenate a string, you create a new string in memory
// and the old string is discarded. It is best to use StringBuilder
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string smtText = "The Cloud Apps Developer Program is a great great opportunity to start a new career career";
//Find match of duplicate words
MatchCollection matches = rx.Matches(smtText);
//Report the number of matches found
Console.WriteLine("{0} matches found in: \n {1}", matches.Count, smtText);
// When acquiring input from the user interface of an application,
// data is often provided as strings that you need to validate and then convert
// into a format that your application logic expects.
// Regular expressions provide a mechanism that enables you to validate input.
double d = 5673.74;
int i;
// cast double to int
i = (int)d;
Console.WriteLine(i);
string userEnteredValue = "542.12";
//error: int flightCost = Convert.ToInt32(userEnteredValue);
double flightCost = Convert.ToDouble(userEnteredValue);
//error: long flightCost = Convert.ToUInt32(userEnteredValue);
Console.WriteLine(flightCost);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ServiceEventLogging;
using ServiceEventLogging.Events;
using ServiceEventLoggerTests.Loggers;
using ServiceEventLoggerTests.ServiceEventExtensions;
namespace ServiceEventLoggerTests
{
[TestClass]
public class ServiceEventLoggingTests
{
readonly TestEventLogger logger = new TestEventLogger();
readonly TestEventFileLogger fileLogger = new TestEventFileLogger();
[TestMethod]
public void TestAddLogLinesToFile()
{
fileLogger.LogServiceSuccessEvent(new ServiceEvent
{
DateTime = DateTime.Now,
DebugInfo = "DebugLine",
IpAddress = "127.0.0.0",
Message = "Standard Server Success Event",
ServerName = "SERVER_INFO"
});
fileLogger.LogServiceFailureEvent(new ServiceEvent
{
DateTime = DateTime.Now,
DebugInfo = "DebugLine",
IpAddress = "127.0.0.0",
Message = "Standard Server Failure Event",
ServerName = "SERVER_INFO"
});
}
[TestMethod]
public void TestAddLogLinesCustom()
{
var correlationId = Guid.NewGuid();
var customDataPoint = "My Custom Data Point that is awesome";
var myCustomEvent = CreateCustomServiceEvent(customDataPoint);
myCustomEvent.MyCustomEventDataPoint = customDataPoint;
myCustomEvent.CorrelationId = correlationId;
logger.LogMyServiceDidSomethingCoolEvent(myCustomEvent);
var line = FindLogLine(correlationId, customDataPoint);
}
[TestMethod]
public void TestAddLogLinesCustom_ToFile()
{
var correlationId = Guid.NewGuid();
var customDataPoint = "My Custom Data Point that is awesome";
var myCustomEvent = CreateCustomServiceEvent(customDataPoint);
myCustomEvent.MyCustomEventDataPoint = customDataPoint;
myCustomEvent.CorrelationId = correlationId;
fileLogger.LogMyServiceDidSomethingCoolEvent(myCustomEvent);
}
[TestMethod]
public void TestAddLogLinesToFile_LoopEvents()
{
for (int i = 0; i < 10000; i++)
{
fileLogger.LogServiceSuccessEvent(new ServiceEvent
{
DebugInfo = "DebugLine" + i,
Message = "Server Success Event",
EventId = i % 2 == 0 ? CustomTestEventId.CustomTestEventOne : CustomTestEventId.CustomTestEventTwo,
EventLevel = i % 2 == 0 ? EventLevel.Warning : EventLevel.Informational
});
}
fileLogger.LogServiceSuccessEvent(new ServiceEvent
{
DebugInfo = "DebugLine_final",
Message = "Standard Server Success Event",
EventId = CustomTestEventId.CustomTestEventFinalizer,
EventLevel = EventLevel.Critical
});
}
[TestMethod]
public void TestEventListener_FindLastLogFile()
{
//PrivateType type = new PrivateType(typeof(ServiceEventListener))
PrivateObject o = new PrivateObject(
"ServiceEventLogging.Listener",
"ServiceEventListener");
}
private string FindLogLine(Guid correlationId, string customDataPoint)
{
return this.logger.LogLines.Where(fx =>
{
var lines = fx.Split('|');
return lines[2].Equals(correlationId.ToString(), StringComparison.OrdinalIgnoreCase) &&
lines[lines.Length - 1].Equals(customDataPoint, StringComparison.OrdinalIgnoreCase);
}).First();
}
private MyCustomServiceEvent CreateCustomServiceEvent(string customDataPoint)
{
return new MyCustomServiceEvent
{
DateTime = DateTime.Now,
DebugInfo = "DebugLine",
IpAddress = "127.0.0.0",
Message = "Standard Server Failure Event",
ServerName = "SERVER_INFO",
MyCustomEventDataPoint = customDataPoint
};
}
}
}
|
using System.Xml;
using System.Xml.Serialization;
using Breeze.Helpers;
using Breeze.Screens;
using Breeze.Services.InputService;
using Breeze.AssetTypes.DataBoundTypes;
using Breeze.AssetTypes.XMLClass;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Breeze.AssetTypes
{
public class RectangleAsset : DataboundContainterAsset
{
public RectangleAsset() { }
public RectangleAsset(Color color, int brushSize, FloatRectangle position, Color? backgroundColor = null, int blurAmout = 0, int noisePerc = 7)
{
NoisePerc.Value = noisePerc;
BorderColor.Value = color;
BrushSize.Value = brushSize;
Position.Value = position;
BackgroundColor.Value = backgroundColor;
BlurAmount.Value = blurAmout;
}
public RectangleAsset(Color color, int brushSize, FloatRectangle position, string fillTexture, Color? backgroundColor = null, TileMode tileMode = TileMode.JustStretch, int blurAmout = 0, int noisePerc = 7)
{
NoisePerc.Value = noisePerc;
BorderColor.Value = color;
BrushSize.Value = brushSize;
Position.Value = position;
FillTexture.Value = fillTexture;
BackgroundColor.Value = backgroundColor ?? Color.White;
TilingMode.Value = tileMode;
BlurAmount.Value = blurAmout;
}
[Asset("Noise")]
public DataboundValue<int> NoisePerc { get; set; } = new DataboundValue<int>();
[Asset("Blur")]
public DataboundValue<int> BlurAmount { get; set; } = new DataboundValue<int>(0);
[Asset("TileMode")]
public DataboundValue<TileMode> TilingMode { get; set; } = new DataboundValue<TileMode>();
public DataboundValue<string> FillTexture { get; set; } =new DataboundValue<string>();
public DataboundValue<Color?> BackgroundColor { get; set; } = new DataboundValue<Color?>();
public DataboundValue<Color> BorderColor { get; set; }=new DataboundValue<Color>();
public DataboundValue<int> BrushSize { get; set; }=new DataboundValue<int>();
public DataboundValue<float> Scale { get; set; } = new DataboundValue<float>(1);
public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null)
{
if (clip.HasValue && ParentPosition.HasValue)
{
clip = clip.Value.ConstrainTo(ParentPosition.Value);
}
clip = screen.Translate(clip);
var t = Position.Value();
FloatRectangle tmp = screen.Translate(ActualPosition.AdjustForMargin(Margin)).Value;
if (clip.HasValue)
{
if (tmp.Right < clip.Value.X || tmp.X > clip.Value.Right)
{
return;
}
}
if (BlurAmount.Value() > 0)
{
Solids.GaussianBlur.DoBlur(bgTexture, BlurAmount.Value(), (BackgroundColor.Value().Value * opacity) * ((BlurAmount.Value() / Solids.MaxBlur)), tmp.ToRectangle, ScissorRect, clip, NoisePerc.Value());
}
if (BackgroundColor.Value().HasValue && FillTexture.Value() == null)
{
spriteBatch.DrawSolidRectangle(tmp, BackgroundColor.Value().Value * opacity, clip);
}
if (FillTexture.Value() != null)
{
using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
{
spriteBatch.DrawTexturedRectangle(tmp, BackgroundColor.Value().Value * opacity, Solids.Instance.AssetLibrary.GetTexture(FillTexture.Value()), TilingMode.Value, clip);
}
}
if (BrushSize.Value() > 0)
{
spriteBatch.DrawBorder(tmp, BorderColor.Value() * opacity, BrushSize.Value(), clip);
}
this.ActualSize = new Vector2(Position.Value().Width, Position.Value().Height).PadForMargin(Margin);
SetChildrenOriginToMyOrigin();
}
}
}
|
namespace EPI.Searching
{
/// <summary>
/// Assume you have a sorted array, A of distinct integers, return an index i such that A[i] == i
/// </summary>
public static class BinarySearchEntryEqualToIndex
{
public static int SearchEntryEqualToItsIndex(int[] sortedArrayWithDistinctValues)
{
int left = 0;
int right = sortedArrayWithDistinctValues.Length - 1;
while (left <= right)
{
int mid = left + (right - left)/2;
int delta = sortedArrayWithDistinctValues[mid] - mid;
if (delta == 0) // A[i] == i
{
return mid;
}
else if (delta > 0) // A[i] > i
{
right = mid - 1;
}
else // A[i] < i
{
left = mid + 1;
}
}
return -1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceEventLogging.Events
{
public sealed class ServiceEventSource : EventSource
{
private static ServiceEventSource source = new ServiceEventSource();
public ServiceEventSource()
{
}
[Event(1, Level = EventLevel.LogAlways)]
public void LogServiceEvent(string logLine)
{
this.WriteEvent(1, logLine);
}
public static ServiceEventSource EventSource
{
get
{
return source;
}
}
}
}
|
using System;
namespace CommandPattern.Devices
{
/// <summary>
/// ³µ¿âÃÅ
/// </summary>
public class GarageDoor
{
public void Up()
{
Console.WriteLine("GarageDoor is open.");
}
public void Down()
{
Console.WriteLine("GarageDoor is closed.");
}
}
} |
using Akka.Actor;
using Akka.Configuration;
using NLog;
using NLog.Config;
using NLog.Targets;
using Topshelf;
using Topshelf.HostConfigurators;
namespace ConnelHooley.DirectoryBackupService.Shared
{
internal static class Logging
{
static Logging()
{
var config = new LoggingConfiguration();
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, LogLevel.Fatal, new ConsoleTarget
{
Name = "console",
Layout = "${longdate} | ${level:uppercase=true} | ${message:withException=true:exceptionSeparator= | }",
}));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, LogLevel.Fatal, new FileTarget
{
Name = "file",
Layout = "${longdate} | ${level:uppercase=true} | ${logger} | ${message:withException=true:exceptionSeparator= | }",
FileName = "log.txt"
}));
LogManager.Configuration = config;
}
public static void AddToTopShelf(HostConfigurator x) =>
x.UseNLog(LogManager.LogFactory);
public static Config GetAkkaLoggingConfig() =>
ConfigurationFactory.ParseString(@"
akka {
loggers = [""Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog""])
loglevel = ""DEBUG""
}");
public static Akka.Event.ILoggingAdapter GetAkkaLogger(IActorContext context) =>
Akka.Event.Logging.GetLogger(context);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Models;
using DAL;
namespace HotelTeacher.Adminhyl.News
{
public partial class NewsPublish : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPublish_Click(object sender, EventArgs e)
{
//数据验证
if (this.txtNewsTitle.Text.Trim().Length == 0)
{
this.ltaMsg.Text = "<script>alert('新闻标题不能为空')</script>";
return;
}
//封装对象
News1 objNews = new News1()
{
NewsTitle = this.txtNewsTitle.Text.ToString(),
CategoryId = Convert.ToInt32(this.ddlCategory.Text),
NewsContents = this.txtContent.InnerText.ToString()
};
if (ViewState["NewsID"] != null)
{
objNews.NewsId = Convert.ToInt32(ViewState["NewsID"]);
}
//存入数据库
if (this.btnPublish.Visible)
{
int newsId = new NewService().AddNews(objNews);
if (newsId > 0)
{
this.ltaMsg.Text = "<script>alert('添加成功')</script>";
}
this.txtNewsTitle.Text = "";
this.txtContent.InnerText = "";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
//封装对象
News1 objNews = new News1()
{
NewsTitle = this.txtNewsTitle.Text.ToString(),
CategoryId = Convert.ToInt32(this.ddlCategory.Text),
NewsContents = this.txtContent.InnerText.ToString()
};
if (ViewState["NewsID"] != null)
{
objNews.NewsId = Convert.ToInt32(ViewState["NewsID"]);
}
//存入数据库
if (this.btnPublish.Visible)
{
int newsId = new NewService().ModifyNew(objNews);
{
this.ltaMsg.Text = "<script>alert('修改成功');location.href='NewsManager.aspx'</script>";
}
}
}
}
} |
using System;
using System.Collections.Generic;
namespace KingUtils
{
/// <summary>
/// Extension methods for dictionaries.
/// </summary>
public static class DictionaryExtensions
{
#if !NET5_0_OR_GREATER
/// <summary>
/// Returns the value associated with the specified key, or the default for the value
/// type if no value was found.
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values in the dictionary.</typeparam>
/// <param name="dictionary">A dictionary with keys of type TKey and values of type TValue.</param>
/// <param name="key">The key of the value to get.</param>
/// <returns>
/// A TValue instance.
/// When the method is successful, the returned object is the value associated with the specified key.
/// When the method fails, it returns the default value for TValue.
/// </returns>
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
return GetValueOrDefault(dictionary, key, default);
}
/// <summary>
/// Returns the value associated with the specified key, or the default for the value
/// type if no value was found.
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of values in the dictionary.</typeparam>
/// <param name="dictionary">A dictionary with keys of type TKey and values of type TValue.</param>
/// <param name="key">The key of the value to get.</param>
/// <param name="defaultValue">The default value to return when the dictionary cannot find a value associated with the specified key.</param>
/// <returns>
/// A TValue instance.
/// When the method is successful, the returned object is the value associated with the specified key.
/// When the method fails, it returns defaultValue.
/// </returns>
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}
#endif
}
}
|
using DamianTourBackend.Core.Entities;
using System;
using System.Collections.Generic;
namespace DamianTourBackend.Core.Interfaces
{
public interface IUserRepository
{
User GetBy(string email);
User GetById(Guid id);
void Add(User user);
void Delete(User user);
IEnumerable<User> GetAll();
void Update(User user);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TsFromCsGenerator.Model
{
class Class
{
public string Name { get; set; }
public IEnumerable<Property> Properties { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using theiacore.Models;
using theiacore.Filters;
using ObjectDetect;
namespace theiacore.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
//var stringList = objectdetect.ObjectDetect.GetJsonFormat().AsEnumerable();
//var stringList = ObjectDetect.Program.GetJsonFormat().AsEnumerable();
//var stringList = GetTensorObject.GetJsonFormat("input.jpg");
//var stringList = new List<string>();
return View("Index", Startup.SessionToken);
}
//[GenerateAntiforgeryTokenCookieForAjax]
//public IActionResult About()
//{
// ViewData["Message"] = "Your application description page.";
// return View();
//}
//public IActionResult Contact()
//{
// ViewData["Message"] = "Your contact page.";
// return View();
//}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SimpleRESTChat.Entities.Enumeration
{
public enum UserAvailabilityStatus
{
Busy,
Available,
DoNotDisturb,
Away,
BeRightBack,
Unknown,
Offline,
FreshRegistered,
Deleted
}
}
|
namespace com.Sconit.Service.Report
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
public interface IReportMgr
{
void WriteToClient(string reportTemplateFolder,string template, IList<object> list, String fileName);
//void WriteToClient(String fileName, HSSFWorkbook workbook);
}
}
|
using System;
using AutoService.Core.Contracts;
using AutoService.Core.Validator;
namespace AutoService.Core.Commands
{
public class ListWarehouseItems : ICommand
{
IDatabase database;
private readonly IValidateCore coreValidator;
private readonly IWriter writer;
private readonly IStockManager stockManager;
public ListWarehouseItems(IProcessorLocator processorLocator)
{
if (processorLocator == null) throw new ArgumentNullException();
this.database = processorLocator.GetProcessor<IDatabase>() ?? throw new ArgumentNullException();
this.coreValidator = processorLocator.GetProcessor<IValidateCore>() ?? throw new ArgumentNullException();
this.writer = processorLocator.GetProcessor<IWriter>() ?? throw new ArgumentNullException();
this.stockManager = processorLocator.GetProcessor<IStockManager>() ?? throw new ArgumentNullException();
}
public void ExecuteThisCommand(string[] commandParameters)
{
this.coreValidator.ExactParameterLength(commandParameters, 1);
if (this.database.AvailableStocks.Count == 0)
{
throw new ArgumentException("The are no avalible staocks at the Warehouse. But you can order some. ;-)");
}
writer.Write(this.stockManager.PrintAvailableStock());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
namespace Kingdee.CAPP.Common.FileRegister
{
public class FileTypeRegister
{
///使文件类型与对应的图标及应用程序关联起来。
public static void RegisterFileType(FileTypeRegInfo fileTypeRegInfo)
{
try
{
if (IsFileTypeRegistered(fileTypeRegInfo.ExtendName))
{
return;
}
string relationName = fileTypeRegInfo.ExtendName.Substring(0,
fileTypeRegInfo.ExtendName.Length - 1).ToUpper() + "_FileType";
///Create file type
/// .cap and set value is .ca_FileType
RegistryKey fileTypeKey = Registry.ClassesRoot.CreateSubKey(fileTypeRegInfo.ExtendName);
fileTypeKey.SetValue("", relationName);
fileTypeKey.Close();
/// create relate ioc and run path
RegistryKey relationKey = Registry.ClassesRoot.CreateSubKey(relationName);
relationKey.SetValue("", fileTypeRegInfo.Description);
RegistryKey iconKey = relationKey.CreateSubKey("DefaultIcon");
iconKey.SetValue("", fileTypeRegInfo.IcoPath);
RegistryKey shellKey = relationKey.CreateSubKey("Shell");
RegistryKey openKey = shellKey.CreateSubKey("Open");
RegistryKey commandKey = openKey.CreateSubKey("Command");
commandKey.SetValue("", fileTypeRegInfo.ExePath + " %1");
relationKey.Close();
}
catch
{
throw;
}
}
/// <summary>
/// GetFileTypeRegInfo 得到指定文件类型关联信息
/// </summary>
public static FileTypeRegInfo GetFileTypeRegInfo(string extendName)
{
if (!IsFileTypeRegistered(extendName))
{
return null;
}
FileTypeRegInfo regInfo = new FileTypeRegInfo(extendName);
string relationName = extendName.Substring(1, extendName.Length - 1).ToUpper() + "_FileType";
RegistryKey relationKey = Registry.ClassesRoot.OpenSubKey(relationName);
regInfo.Description = relationKey.GetValue("").ToString();
RegistryKey iconKey = relationKey.OpenSubKey("DefaultIcon");
regInfo.IcoPath = iconKey.GetValue("").ToString();
RegistryKey shellKey = relationKey.OpenSubKey("Shell");
RegistryKey openKey = shellKey.OpenSubKey("Open");
RegistryKey commandKey = openKey.OpenSubKey("Command");
string temp = commandKey.GetValue("").ToString();
regInfo.ExePath = temp.Substring(0, temp.Length - 3);
return regInfo;
}
/// <summary>
/// UpdateFileTypeRegInfo 更新指定文件类型关联信息
/// </summary>
public static bool UpdateFileTypeRegInfo(FileTypeRegInfo regInfo)
{
if (!IsFileTypeRegistered(regInfo.ExtendName))
{
return false;
}
string extendName = regInfo.ExtendName;
string relationName = extendName.Substring(1, extendName.Length - 1).ToUpper() + "_FileType";
RegistryKey relationKey = Registry.ClassesRoot.OpenSubKey(relationName, true);
relationKey.SetValue("", regInfo.Description);
RegistryKey iconKey = relationKey.OpenSubKey("DefaultIcon", true);
iconKey.SetValue("", regInfo.IcoPath);
RegistryKey shellKey = relationKey.OpenSubKey("Shell");
RegistryKey openKey = shellKey.OpenSubKey("Open");
RegistryKey commandKey = openKey.OpenSubKey("Command", true);
commandKey.SetValue("", regInfo.ExePath + " %1");
relationKey.Close();
return true;
}
/// <summary>
/// 判断文件是否已经注册
/// </summary>
/// <param name="extendName"></param>
/// <returns></returns>
public static bool IsFileTypeRegistered(string extendName)
{
RegistryKey softWareKey = Registry.ClassesRoot.OpenSubKey(extendName);
if (softWareKey != null)
{
return true;
}
return false;
}
/// <summary>
/// 注册autocad PlugIn
/// </summary>
/// <param name="plugInPath">插件的路径</param>
/// <returns>是否注册成功</returns>
public static bool RegisterAutoCADPlugIn(string plugInPath)
{
plugInPath = plugInPath + "Plug-In";
RegistryKey cadKey = Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Autodesk\AutoCAD\R18.2\ACAD-A001:804\Applications",true);
if (cadKey == null)
{
return false;
}
try
{
RegistryKey drawRectangleSubKey = cadKey.CreateSubKey("DrawRectangle");
drawRectangleSubKey.SetValue("DESCRIPTION", "DrawRectangle.");
drawRectangleSubKey.SetValue("LOADCTRLS", "2", RegistryValueKind.DWord);
drawRectangleSubKey.SetValue("LOADER", plugInPath + "\\Kingdee.CAPP.Autocad.DrawRectanglePlugIn.dll");
drawRectangleSubKey.SetValue("MANAGED", "1",RegistryValueKind.DWord);
return true;
}
catch { return false; }
}
/// <summary>
/// 判断注册表是否存在
/// </summary>
/// <returns></returns>
public static bool IsRegeditExit()
{
bool _exit = false;
RegistryKey cadKey = Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Autodesk\AutoCAD\R18.2\ACAD-A001:804\Applications", true);
if (cadKey != null)
{
RegistryKey drawRectangleSubKey = cadKey.OpenSubKey("DrawRectangle", true);
if (drawRectangleSubKey != null)
{
_exit = true;
}
}
return _exit;
}
/// <summary>
/// 增加工艺简图菜单
/// </summary>
public static void UpdateAutoCADMenu(string plugInPath)
{
string appPath = plugInPath + "Plug-In\\cadMenuCUIX\\CraftPicture";
string regCADPath = @"Software\Autodesk\AutoCAD\R18.2\ACAD-A001:804\Profiles\<<未命名配置>>\General Configuration";
RegistryKey cadKey = Registry.CurrentUser.OpenSubKey(regCADPath, true);
if(cadKey != null)
{
string cadmenu = cadKey.GetValue("MenuFile").ToString();
if (!cadmenu.Contains(appPath))
{
cadKey.SetValue("MenuFile", appPath, RegistryValueKind.String);
}
}
}
/// <summary>
/// 重置Autocad菜单
/// </summary>
public static void ResetAutoCADMenu()
{
string appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
appPath = appPath + @"\Autodesk\AutoCAD 2012 - Simplified Chinese\R18.2\chs\Support\acad";
string regCADPath = @"Software\Autodesk\AutoCAD\R18.2\ACAD-A001:804\Profiles\<<未命名配置>>\General Configuration";
RegistryKey cadKey = Registry.CurrentUser.OpenSubKey(regCADPath, true);
if (cadKey != null)
{
string cadmenu = cadKey.GetValue("MenuFile").ToString();
if (!cadmenu.Contains(appPath))
{
cadKey.SetValue("MenuFile", appPath, RegistryValueKind.String);
}
}
}
}
}
|
using System.Windows.Automation.Peers;
namespace Crystal.Plot2D.Common
{
public class PlotterAutomationPeer : FrameworkElementAutomationPeer
{
public PlotterAutomationPeer(PlotterBase owner)
: base(owner)
{
}
protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Custom;
protected override string GetClassNameCore() => "Plotter";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum GunType
{
PISTOL,
SHOTGUN,
AK47,
}
public class Gun : MonoBehaviour
{
[SerializeField]
float outerRadius = 2.5f;
[SerializeField]
Transform droog;
[SerializeField]
GunType type;
[SerializeField]
float initialBulletVel = 20.0f;
[SerializeField]
GameObject bulletPref;
[SerializeField]
float maxTimer = 5f;
[SerializeField]
float currTime;
bool onCoolDown = false;
[SerializeField]
Transform start;
float angle;
[SerializeField] AudioClip PistolSound;
[SerializeField] AudioClip ShottySound;
[SerializeField] AudioClip AKSound;
private AudioSource AS;
private float PitchDeviation;
// Update is called once per frame
private void Start()
{
PitchDeviation = Random.Range(-.1f, .1f);
AS = GetComponent<AudioSource>();
}
void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 final = Vector3.zero;
final.z = 0;
if (mousePos.x > droog.position.x + outerRadius)
final.x = droog.position.x + outerRadius;
else if (mousePos.x < droog.position.x - outerRadius)
final.x = droog.position.x - outerRadius;
else
final.x = mousePos.x;
if (mousePos.y > droog.position.y + outerRadius)
final.y = droog.position.y + outerRadius;
else if(mousePos.y < droog.position.y - outerRadius)
final.y = droog.position.y - outerRadius;
else
final.y = mousePos.y;
transform.position = final;
// Screen pos of gun
Vector2 objScreenPos = Camera.main.WorldToViewportPoint(droog.position);
// Screen pos of mouse
Vector2 mouseScreenPos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
// Angle between two positions
angle = AngleBetween(mouseScreenPos, objScreenPos);
if(angle <= 145f && angle >= -145f)
{
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
else
{
transform.rotation = Quaternion.Euler(new Vector3(180f, 0, angle));
}
if(onCoolDown)
currTime += Time.deltaTime;
if(currTime >= maxTimer)
{
currTime = 0f;
onCoolDown = false;
}
}
float AngleBetween(Vector3 left, Vector3 right)
{
return Mathf.Atan2(left.y - right.y, left.x - right.x) * Mathf.Rad2Deg;
}
public void Shoot()
{
Vector2 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = mouseWorldPos - new Vector2(transform.position.x, transform.position.y);
Vector2 unnormDir = dir;
dir.Normalize();
if (!onCoolDown)
{
if (type == GunType.PISTOL)
{
GameObject g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 5;
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
// Play pistol sound
AS.PlayOneShot(PistolSound);
PitchDeviation = Random.Range(-.1f, .1f);
AS.pitch = 1 + PitchDeviation;
onCoolDown = true;
}
else if(type == GunType.SHOTGUN)
{
GameObject g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 7;
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 7;
Vector2 dir2 = new Vector2(unnormDir.x + Random.Range(-1f, 1f), unnormDir.y + Random.Range(-1f, 1f));
dir2.Normalize();
g.GetComponent<Rigidbody2D>().velocity = dir2 * initialBulletVel;
g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 7;
dir2 = new Vector2(unnormDir.x + Random.Range(-1f, 1f), unnormDir.y + Random.Range(-1f, 1f));
dir2.Normalize();
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 7;
dir2 = new Vector2(unnormDir.x + Random.Range(-1f, 1f), unnormDir.y + Random.Range(-0.5f, 0.25f));
dir2.Normalize();
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 7;
dir2 = new Vector2(unnormDir.x + Random.Range(-1f, 1f), unnormDir.y + Random.Range(-1f, 1f));
dir2.Normalize();
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
// Play shotgun sound
AS.PlayOneShot(ShottySound);
PitchDeviation = Random.Range(-.1f, .1f);
AS.pitch = 1 + PitchDeviation;
onCoolDown = true;
}
else if(type == GunType.AK47)
{
GameObject g = Instantiate(bulletPref, start.position, Quaternion.Euler(0,0,angle));
g.GetComponent<Bullet>().damage = 8;
g.GetComponent<Rigidbody2D>().velocity = dir * initialBulletVel;
// Play Ak47 sound
AS.PlayOneShot(AKSound);
PitchDeviation = Random.Range(-.1f, .1f);
AS.pitch = 1 + PitchDeviation;
onCoolDown = true;
}
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace HospitalSystem.Models.Mapping
{
public class charge_recordMap : EntityTypeConfiguration<charge_record>
{
public charge_recordMap()
{
// Primary Key
this.HasKey(t => t.ChargeRecordID);
// Properties
// Table & Column Mappings
this.ToTable("charge_record", "teamwork");
this.Property(t => t.ChargeRecordID).HasColumnName("ChargeRecordID");
this.Property(t => t.PatientID).HasColumnName("PatientID");
this.Property(t => t.PrescriptionID).HasColumnName("PrescriptionID");
this.Property(t => t.ExamineListID).HasColumnName("ExamineListID");
this.Property(t => t.StaffID).HasColumnName("StaffID");
this.Property(t => t.SumPay).HasColumnName("SumPay");
this.Property(t => t.ChargeDate).HasColumnName("ChargeDate");
// Relationships
this.HasOptional(t => t.examine_list)
.WithMany(t => t.charge_record)
.HasForeignKey(d => d.ExamineListID);
this.HasOptional(t => t.patient)
.WithMany(t => t.charge_record)
.HasForeignKey(d => d.PatientID);
this.HasOptional(t => t.prescription)
.WithMany(t => t.charge_record)
.HasForeignKey(d => d.PrescriptionID);
this.HasOptional(t => t.staff)
.WithMany(t => t.charge_record)
.HasForeignKey(d => d.StaffID);
}
}
}
|
using Inter.Runner;
using NUnit.Framework;
namespace Inter.Tests
{
public class CalculatorTest
{
[Test]
public void A_and_B()
{
var calculator = new Calculator();
var res = calculator.Calc(1, 2);
Assert.AreEqual(3, res);
}
}
}
|
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 Microsoft.AspNet.Identity;
using KulujenSeuranta.Models;
using KulujenSeuranta.ViewModels;
using KulujenSeuranta.Interfaces;
using KulujenSeuranta.Services;
namespace KulujenSeuranta.Controllers
{
public class PaymentController : Controller
{
private ApplicationDbContext _db = new ApplicationDbContext();
IPaymentService _paymentService = new PaymentService();
// GET: Payment
[Authorize(Roles = "canRead")]
public ActionResult Index()
{
var paymentsViewModel = new PaymentsViewModel(_paymentService);
// Default search date is always current month & year
paymentsViewModel.SearchDate = new SearchDate { UserInputDate = DateTime.Now.Month + "-" + DateTime.Now.Year };
return View(paymentsViewModel);
}
[Authorize(Roles = "canRead")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SearchDate")] PaymentsViewModel paymentsViewModel)
{
if (paymentsViewModel.SearchDate.UserInputDate == null)
{
return View(paymentsViewModel);
}
return View(paymentsViewModel);
}
// GET: Payment/Details/5
[Authorize(Roles = "canRead")]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payment payment = _paymentService.FindPayment(id);
if (payment == null)
{
return HttpNotFound();
}
return View(payment);
}
// GET: Payment/Create
[Authorize(Roles = "canRead")]
public ActionResult Create()
{
return View();
}
// POST: Payment/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]
[Authorize(Roles = "canEdit")]
public ActionResult Create([Bind(Include = "PaymentId,Sum,Category,Date,User_Id")] Payment payment)
{
_paymentService.AddCurrentUserToPayment(ref payment, User);
ModelState.Clear();
TryValidateModel(payment);
if (ModelState.IsValid)
{
_paymentService.AddPayment(payment);
return RedirectToAction("Index");
}
return View(payment);
}
// GET: Payment/Edit/5
[Authorize(Roles = "canRead")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payment payments = _paymentService.FindPayment(id);
if (payments == null)
{
return HttpNotFound();
}
return View(payments);
}
// POST: Payment/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.
[Authorize(Roles = "canEdit")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PaymentId,Sum,Category,Date,User,Created,CreatedUser,Modified,ModifiedUser")] Payment payment)
{
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = _db.Users.FirstOrDefault(x => x.Id == currentUserId);
payment.User = currentUser;
//_paymentService.AddCurrentUserToPayment(ref payment, User);
ModelState.Clear();
TryValidateModel(payment);
if (ModelState.IsValid)
{
_db.Entry(payment).State = EntityState.Modified;
_db.SaveChanges();
//_paymentService.ModifyPayment(payment);
return RedirectToAction("Index");
}
return View(payment);
}
// GET: Payment/Delete/5
[Authorize(Roles = "canRead")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payment payments = _paymentService.FindPayment(id);
if (payments == null)
{
return HttpNotFound();
}
return View(payments);
}
// POST: Payment/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "canEdit")]
public ActionResult DeleteConfirmed(int id)
{
Payment payment = _paymentService.FindPayment(id);
_paymentService.RemovePayment(payment);
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_paymentService.DisposeDb();
}
base.Dispose(disposing);
}
}
}
|
using Coldairarrow.Business.Sto_ProManage;
using Coldairarrow.Entity.Sto_ProManage;
using Coldairarrow.Util;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using static Coldairarrow.Business.Sto_ProManage.Pro_ProjectMaterielBusiness;
namespace Coldairarrow.Web
{
public class Pro_ProjectMaterielController : BaseMvcController
{
Pro_ProjectMaterielBusiness _pro_ProjectMaterielBusiness = new Pro_ProjectMaterielBusiness();
#region 视图功能
public ActionResult Index()
{
return View();
}
public ActionResult Form(string id)
{
var theData = id.IsNullOrEmpty() ? new Pro_ProjectMateriel() : _pro_ProjectMaterielBusiness.GetTheData(id);
return View(theData);
}
#endregion
#region 获取数据
/// <summary>
/// 获取数据列表
/// </summary>
/// <param name="condition">查询类型</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
public ActionResult GetDataList(string condition, string keyword, Pagination pagination)
{
var dataList = _pro_ProjectMaterielBusiness.GetDataList(condition, keyword, pagination);
return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson());
}
#endregion
#region 提交数据
/// <summary>
/// 保存
/// </summary>
/// <param name="theData">物料数据</param>
public ActionResult AddMateriel(MaterielParam theData)
{
if (theData == null || theData.ProCode == "")
return Error("传入参数错误");
if (theData.MaterielList == null || theData.MaterielList.Count == 0)
return Error("没有添加任何物料");
//直接创建领料单
_pro_ProjectMaterielBusiness.AddData(theData);
return Success();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="theData">删除的数据</param>
public ActionResult DeleteData(string ids)
{
_pro_ProjectMaterielBusiness.DeleteData(ids.ToList<string>());
return Success("删除成功!");
}
#endregion
public ActionResult CreateTempMaterialList(CreateTempMaterielParam parm)
{
var items = new List<Pro_UseMateriel>();
//创建新增材料列表
//1.根据模板ID读取模板
Pro_TemplateItemBusiness tb = new Pro_TemplateItemBusiness();
var tempList = tb.GetDataList("TemplateId", parm.TemplateId, new Pagination() { PageIndex=1,PageRows=int.MaxValue});
tempList.ForEach(item =>
{
items.Add(new Pro_UseMateriel()
{
Id= Guid.NewGuid().ToSequentialGuid(),
ProCode= parm.ProCode,
GuiGe = item.GuiGe,
MatName = item.MatName,
UnitNo = item.UnitNo,
MatNo = item.MatNo,
Quantity = item.Quantity * parm.CreateCount
});
});
return Content(items.ToJson());
}
public class CreateTempMaterielParam
{
// proCode: proCode, templateId: templateId, createCount: createCount
public string ProCode { get; set; }
public string TemplateId { get; set; }
public int CreateCount { get; set; }
}
}
} |
using FrbaOfertas.AbmCliente;
using FrbaOfertas.Helpers;
using FrbaOfertas.Model;
using FrbaOfertas.Model.DataModel;
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 FrbaOfertas.CargaCredito
{
public partial class CargaDeCredito : Form
{
Cliente cliente;
Credito credito;
TipoPagoData tData;
CreditoData cData;
private static string fecha = FrbaOfertas.ConfigurationHelper.FechaActual.ToString();
List<TextBox> noNulos = new List<TextBox>();
List<TextBox> numericos = new List<TextBox>();
List<TextBox> todos = new List<TextBox>();
List<TipoDePago> listPagos = new List<TipoDePago>();
Exception exError = null;
public CargaDeCredito()
{
InitializeComponent();
cred_fecha.Text = fecha;
}
public CargaDeCredito(Cliente cliente )
{
InitializeComponent();
cred_fecha.Text = fecha;
this.cliente = cliente;
clie_nombre.Enabled = false;
seleccionar.Enabled = false;
clie_nombre.Text = cliente.clie_nombre;
}
private void cargarCombo()
{
listPagos = tData.Select(out exError);
listPagos.ForEach(delegate(TipoDePago f)
{
if (f.tipo_pago_nombre != "Efectivo")
tipo_pago.Items.Add(f.tipo_pago_nombre);
});
}
private void CargaDeCredito_Load(object sender, EventArgs e)
{
tData = new TipoPagoData(Conexion.getConexion());
cData = new CreditoData(Conexion.getConexion());
cargarCombo();
noNulos.Add(cred_fecha);
noNulos.Add(clie_nombre);
noNulos.Add(cred_num_tarjeta);
noNulos.Add(cre_empresa_tarjeta);
noNulos.Add(cred_cod_tarjeta);
noNulos.Add(cred_monto);
numericos.Add(cred_num_tarjeta);
numericos.Add(cred_cod_tarjeta);
numericos.Add(cred_monto);
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
todos.Add((TextBox)x);
}
}
}
private void guardar_Click(object sender, EventArgs e)
{
credito = new Credito();
if (!FormHelper.noNullList(noNulos) || !FormHelper.esNumericoList(numericos))
return;
if (tipo_pago.Text.Count() < 1)
{
MessageBox.Show("Selecciones un tipo de pago.");
return;
}
FormHelper.setearAtributos(todos, credito);
if (credito.cred_monto <= 0) {
MessageBox.Show("El monto no puede ser negativo.");
return;
}
credito.id_cliente = cliente.id_cliente;
credito.id_tipo_pago = getPagoSeleccionado().id_tipo_pago;
cData.Create(credito, out exError);
if (exError == null)
{
MessageBox.Show("Se acreditaron $" + credito.cred_monto + " a "+ cliente.clie_nombre +" .", "Carga de credito", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else
MessageBox.Show("Erro al ralizar la carga de credito, " + exError.Message, "Carga de credito", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private TipoDePago getPagoSeleccionado() {
TipoDePago pago = new TipoDePago();
listPagos.ForEach(delegate(TipoDePago f)
{
if (f.tipo_pago_nombre == tipo_pago.Text)
pago = f;
});
return pago;
}
private void seleccionar_Click(object sender, EventArgs e)
{
ClienteList form = new ClienteList(true);
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
this.cliente=form.returnCliente;
clie_nombre.Text = this.cliente.clie_nombre;
}
}
private void clie_nombre_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedListLibrary;
namespace MyLinkedListLibraryTest
{
class Program
{
static void Main(string[] args)
{
var intList = new LinkedListLibrary.LinkedList<int>();
var doubleList = new LinkedListLibrary.LinkedList<double>();
// create data to store in List
int aInt = 12;
int bInt = 36;
int cInt = 42;
int dInt = 52;
int eInt = 62;
double aDouble = 47.13;
double bDouble = 77.53;
double cDouble = 12.34;
double dDouble = 30.31;
double eDouble = 15.39;
// use List insert methods
intList.InsertAtFront(aInt);
intList.InsertAtFront(bInt);
intList.InsertAtFront(cInt);
intList.InsertAtFront(dInt);
intList.InsertAtFront(eInt);
intList.Display();
Console.WriteLine($"Minimum of intList is {intList.Minimum()}\n");
Console.WriteLine($"Last Node of intList is { intList.GetLastNode()}\n\n");
doubleList.InsertAtBack(aDouble);
doubleList.InsertAtFront(bDouble);
doubleList.InsertAtFront(cDouble);
doubleList.InsertAtFront(dDouble);
doubleList.InsertAtFront(eDouble);
doubleList.Display();
Console.WriteLine($"Minimum of doubleList is {doubleList.Minimum()}\n");
Console.WriteLine($"Last Node of doubleList is { doubleList.GetLastNode()}\n");
// remove data from list and display after each removal
//try
//{
// object removedObject = list.RemoveFromFront();
// Console.WriteLine($"{removedObject} removed");
// list.Display();
// removedObject = list.RemoveFromFront();
// Console.WriteLine($"{removedObject} removed");
// list.Display();
// removedObject = list.RemoveFromBack();
// Console.WriteLine($"{removedObject} removed");
// list.Display();
// removedObject = list.RemoveFromBack();
// Console.WriteLine($"{removedObject} removed");
// list.Display();
//}
//catch (EmptyListException emptyListException)
//{
// Console.Error.WriteLine($"\n{emptyListException}");
//}
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebApp.Migrations
{
public partial class AtualizaModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_Pessoas",
table: "Pessoas");
migrationBuilder.RenameTable(
name: "Pessoas",
newName: "Pessoa");
migrationBuilder.AddPrimaryKey(
name: "PK_Pessoa",
table: "Pessoa",
column: "Id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_Pessoa",
table: "Pessoa");
migrationBuilder.RenameTable(
name: "Pessoa",
newName: "Pessoas");
migrationBuilder.AddPrimaryKey(
name: "PK_Pessoas",
table: "Pessoas",
column: "Id");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTracing : MonoBehaviour
{
private GameObject playerCam;
void FixedUpdate()
{
playerCam = GameObject.FindGameObjectWithTag("Player");
if (playerCam != null)
{
transform.position = new Vector3(playerCam.transform.position.x, playerCam.transform.position.y, transform.position.z);
}
}
}
|
using Core.Infrastructure;
namespace Core
{
/// <summary>
/// Represents a common helper
/// </summary>
public partial class CommonHelper
{
#region Properties
/// <summary>
/// Gets or sets the default file provider
/// </summary>
public static IProjectFileProvider DefaultFileProvider { get; set; }
#endregion
}
}
|
using System;
public class Damage
{
public float damage;
public int penetration;
public Damage (float dmg, int pnt)
{
if (dmg < 0) damage= 0; else damage = dmg;
if (dmg < 0) penetration = 0; else penetration = pnt;
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Quantum.Simulation.Simulators;
namespace Microsoft.Quantum.Samples.H2Simulation
{
class Program
{
static async Task Main(string[] args)
{
// We begin by making an instance of the simulator that we will use to run our Q# code.
using (var qsim = new QuantumSimulator()) {
// We call the Q# function H2BondLengths to get the bond lengths at which we want to
// estimate the energy.
var bondLengths = await H2BondLengths.Run(qsim);
// In Q#, we defined the operation that performs the actual estimation;
// we can call it here, giving a structure tuple that corresponds to the
// C# ValueTuple that it takes as its input. Since the Q# operation
// has type (idxBondLength : Int, nBitsPrecision : Int, trotterStepSize : Double) => (Double),
// we pass the index along with that we want six bits of precision and
// step size of 1.
//
// The result of calling H2EstimateEnergyRPE is a Double, so we can minimize over
// that to deal with the possibility that we accidentally entered into the excited
// state instead of the ground state of interest.
Func<int, Double> estAtBondLength = (idx) => Enumerable.Min(
from idxRep in Enumerable.Range(0, 3)
select H2EstimateEnergyRPE.Run(qsim, idx, 6, 1.0).Result
);
// We are now equipped to run the Q# simulation at each bond length
// and print the answers out to the console.
foreach (var idxBond in Enumerable.Range(0, 54))
{
System.Console.WriteLine($"Estimating at bond length {bondLengths[idxBond]}:");
var est = estAtBondLength(idxBond);
System.Console.WriteLine($"\tEst: {est}\n");
}
}
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
}
}
}
|
namespace BudgetHelper.DataTypes
{
public class CategoryMapping
{
public CategoryMapping(string establishmentName, string categoryName)
{
EstablishmentName = string.Copy(establishmentName);
CategoryName = string.Copy(categoryName);
}
public string EstablishmentName { get; }
public string CategoryName { get; }
}
} |
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.FileInfo
{
public class ShareEntity
{
/// <summary>
///编号
/// </summary>
[DataMember]
public int Id;
/// <summary>
///实体编号
/// </summary>
[DataMember]
public string ItemId;
/// <summary>
/// 类型
/// </summary>
[DataMember]
public string Type;
/// <summary>
///发起人
/// </summary>
[DataMember]
public string Creater;
/// <summary>
/// 接收人
/// </summary>
[DataMember]
public string Sendee;
/// <summary>
///用户类型
/// </summary>
[DataMember]
public string UserType;
/// <summary>
///用户所属组织或者项目
/// </summary>
[DataMember]
public string UserOrg;
/// <summary>
///创建时间
/// </summary>
[DataMember]
public string CreateTime;
/// <summary>
///邮箱
/// </summary>
[DataMember]
public string Email;
/// <summary>
/// 电话
/// </summary>
[DataMember]
public string Tel;
/// <summary>
///公司
/// </summary>
[DataMember]
public string Company;
}
}
|
using FluentValidation;
using OnboardingSIGDB1.Domain.Utils;
using System;
namespace OnboardingSIGDB1.Domain.Empresas.Validators
{
public class EmpresaValidator : AbstractValidator<Empresa>
{
public EmpresaValidator()
{
RuleFor(e => e.Nome)
.NotEmpty()
.WithMessage(string.Format(MensagensErro.CampoObrigatorio, "Nome"));
RuleFor(e => e.Nome)
.Length(0, 150)
.WithMessage(string.Format(MensagensErro.TamanhoString, "Nome", 1, 150));
RuleFor(e => e.Cnpj)
.NotEmpty()
.Length(14)
.WithMessage(string.Format($"{MensagensErro.CampoObrigatorio} e deve conter 14 caracteres", "Cnpj"));
RuleFor(e => e.DataFundacao)
.GreaterThan(DateTime.MinValue)
.WithMessage($"A data de fundação deve ser maior que {DateTime.MinValue.ToShortDateString()}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinterIsComing.Models.Spells
{
public class FireBreath:Spell
{
private const int fireBreathEnergy = 30;
public FireBreath(int damage)
: base(damage,fireBreathEnergy )
{
}
}
}
|
using System.Web;
using Profiling2.Domain.Prf.Sources;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels
{
public class SourceFileDataViewModel
{
public int Id { get; set; }
public string SourceName { get; set; }
public HttpPostedFileBase FileData { get; set; }
public SourceFileDataViewModel() { }
public SourceFileDataViewModel(Source s)
{
if (s != null)
{
this.Id = s.Id;
this.SourceName = s.SourceName;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
using Office.Common;
using Office.Data.Entities;
namespace Office.BusinessLogic.Services
{
public class PersonService
{
FaceServiceClient _faceServiceClient = new FaceServiceClient(Config.ApiKey, Config.EndPointUrl);
public PersonService()
{
}
public async Task<IList<Person>> GetAll(string personGroupId)
{
var persons = await _faceServiceClient.ListPersonsAsync(personGroupId);
return persons;
}
public async Task AddPerson(HttpFileCollection files, NewUser user)
{
try
{
var createdUser = await _faceServiceClient.CreatePersonAsync(user.GroupId, user.Name, user.Position);
for(int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
await _faceServiceClient.AddPersonFaceAsync(user.GroupId, createdUser.PersonId, file.InputStream);
}
}
catch(Exception ex)
{
}
}
public async Task DeletePerson(string personGroupId, string personId)
{
var id = new Guid(personId);
await _faceServiceClient.DeletePersonAsync(personGroupId, id);
}
}
}
|
/*****************************************
*
* Base Class for All Entities that are considered
* Characters, Players, NPCs Enemies
*
*****************************************/
using BP12;
using DChild.Gameplay.Combat.StatusEffects;
using Sirenix.OdinInspector;
using UnityEngine;
using BP12.Events;
using DChild.Gameplay.Combat;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
namespace DChild.Gameplay.Objects.Characters
{
[RequireComponent(typeof(Rigidbody2D), typeof(ICharacterTime))]
public abstract class Character : DestructableObject, ICharacter, IDamageable, IStatusEffectReciever, ISentientBeing
{
[SerializeField]
[TabGroup("References")]
protected Transform m_model;
[SerializeField]
[TabGroup("Resistances")]
protected StatusResistances m_statusResistance;
protected GameObject m_statusGO;
private ICharacterTime m_time;
private Direction m_facing;
public string characterName => GetType().Name;
public Scene currentScene => gameObject.scene;
public Transform model => m_model;
public override Vector2 position => m_model.position;
public IIsolatedCharacterTime time => m_time;
public bool isAlive => health.isEmpty == false;
public Direction facing => m_facing;
public abstract IHealth health { get; }
public abstract void EnableBrain(bool isEnable);
public abstract void DealDamageTo(IDamageable damageable);
public virtual void PlaceAt(Vector2 position, Quaternion rotation, bool useLocal = false)
{
if (useLocal)
{
transform.localPosition = position;
transform.localRotation = rotation;
}
else
{
transform.position = position;
transform.rotation = rotation;
}
}
public virtual void SetFacing(Direction facing)
{
if (facing == Direction.Left)
{
transform.localScale = new Vector3(-1, 1, 1);
}
else
{
transform.localScale = Vector3.one;
}
m_facing = facing;
}
public override AttackDamage[] TakeExternalDamage(DamageSource source, params AttackDamage[] damages)
{
int totalDamageRecieved;
var damageReport = ApplyDamage(damages, out totalDamageRecieved);
if (totalDamageRecieved >= 0)
{
OnTakeExternalDamage(source);
}
return damageReport;
}
public override AttackDamage[] TakeInternalDamage(params AttackDamage[] damages)
{
int totalDamageRecieved;
var damageReport = ApplyDamage(damages, out totalDamageRecieved);
if (totalDamageRecieved > 0)
{
OnTakeInternalDamage();
}
return damageReport;
}
public T GetOrCreateStatus<T>() where T : MonoBehaviour, IStatusEffect
{
var status = GetComponentInChildren<T>();
if (status == null)
{
status = m_statusGO.AddComponent<T>();
}
return status;
}
protected override AttackDamage[] ApplyDamage(AttackDamage[] damages, out int totalDamage)
{
var damageReport = base.ApplyDamage(damages, out totalDamage);
ApplyDamage(totalDamage);
return damageReport;
}
protected virtual void ApplyDamage(int damage)
{
if (damage > 0)
{
health.Damage(damage);
}
else if (damage < 0)
{
health.Heal(-damage);
}
}
protected void TurnCharacter()
{
if (m_facing == Direction.Left)
{
SetFacing(Direction.Right);
}
else
{
SetFacing(Direction.Left);
}
}
protected abstract void OnTakeExternalDamage(DamageSource source);
protected abstract void OnTakeInternalDamage();
protected override void Awake()
{
base.Awake();
m_time = GetComponent<ICharacterTime>();
m_facing = transform.localScale.x > 0 ? Direction.Right : Direction.Left;
}
protected virtual void Start()
{
m_statusGO = new GameObject("StatusEffects");
m_statusGO.transform.parent = transform;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public static int greenHitCount;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
GreenSpawner.enemyDeaths++;
greenHitCount++;
}
}
|
using GalwayTourismGuide;
namespace GalwayTourismGuide.Views
{
public sealed partial class HistoryDetailPage : PageBase
{
}
}
|
using Pe.Stracon.SGC.Cross.Core.Base;
namespace Pe.Stracon.SGC.Cross.Core.Exception
{
/// <summary>
/// Infrastructure Exception
/// </summary>
/// <remarks>
/// Creación: GMD 22122014 <br />
/// Modificación: <br />
/// </remarks>
public class InfrastructureLayerException<T> : GenericException<T>
where T : class
{
public InfrastructureLayerException(string message, System.Exception e) : base(message, e) { }
}
}
|
using System;
namespace Fuzzing.Fuzzers.Impl
{
public class IntegerFuzzer : TypeFuzzer<int>
{
private const int IntegerSize = sizeof (int);
public override int Fuzz()
{
var data = new byte[IntegerSize];
RandomNumberGenerator.GetBytes(data);
var result = BitConverter.ToInt32(data, 0);
return result;
}
}
}
|
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace BattleShip
{
public partial class Form1 : Form
{
private PictureBox[] _playerPicBox;
private PictureBox[] _pcPicBox;
private string[] _playerGrid;
private string[] _pcGrid;
private int _playerX;
private int _playerY;
private int _pcX;
private int _pcY;
private int _pcShipsNum;
private int _playerShipsNum;
private int _cpuLastHitCell = -1;
private bool _cpuHasHit = false;
private Queue _cellNeighbors = new Queue();
private Queue _clickedCpuQueue = new Queue();
public Form1()
{
InitializeComponent();
}
private void InitGame()
{
InitGrids();
PlaceShips();
}
private void InitGrids()
{
_playerX = 10;
_playerY = 100;
_pcX = 610;
_pcY = 100;
_pcShipsNum = 6;
_playerShipsNum = 6;
_playerPicBox = new PictureBox[100];
_pcPicBox = new PictureBox[100];
_playerGrid = new string[100];
_pcGrid = new string[100];
for (int i = 0; i < 100; i++)
{
_playerPicBox[i] = new PictureBox();
_playerPicBox[i].Name = "p" + (i + 1);
_playerPicBox[i].ImageLocation = "Water.jpg";
_playerPicBox[i].Location = new Point(_playerX, _playerY);
_playerPicBox[i].Size = new Size(50, 50);
this.Controls.Add(_playerPicBox[i]);
_playerGrid[i] = "W";
_pcPicBox[i] = new PictureBox();
_pcPicBox[i].Name = "c" + (i + 1);
_pcPicBox[i].ImageLocation = "Water.jpg";
_pcPicBox[i].Location = new Point(_pcX, _pcY);
_pcPicBox[i].Size = new Size(50, 50);
_pcPicBox[i].Click += new EventHandler(OnComputerClick);
this.Controls.Add(_pcPicBox[i]);
_pcGrid[i] = "W";
if ((i + 1) % 10 == 0)
{
_playerX = 10;
_playerY += 50;
_pcX = 610;
_pcY += 50;
}
else
{
_playerX += 50;
_pcX += 50;
}
}
}
private void PlaceShips()
{
int[] availableNumbers =
{11, 12, 13, 14, 15, 16, 17, 18,
21, 22, 23, 24, 25, 26, 27, 28,
31, 32, 33, 34, 35, 36, 37, 38,
41, 42, 43, 44, 45, 46, 47, 48,
51, 52, 53, 54, 55, 56, 57, 58,
61, 62, 63, 64, 65, 66, 67, 68,
71, 72, 73, 74, 75, 76, 77, 78,
81, 82, 83, 84, 85, 86, 87, 88};
int shipLocation;
for (int i = 0; i <= 5; i++)
{
while (true)
{
Random rnd = new Random();
shipLocation = availableNumbers[rnd.Next(0, availableNumbers.Length - 1)];
if (i <= 2)
{
if (_playerGrid[shipLocation] == "W" &&
_playerGrid[shipLocation - 1] == "W" &&
_playerGrid[shipLocation + 10] == "W")
break;
}
else
{
if (_pcGrid[shipLocation] == "W" &&
_pcGrid[shipLocation - 1] == "W" &&
_pcGrid[shipLocation + 10] == "W")
break;
}
}
if (shipLocation % 2 == 0)
{
if (i <= 2)
{
_playerGrid[shipLocation - 1] = "S";
_playerGrid[shipLocation] = "S";
_playerPicBox[shipLocation - 1].ImageLocation = "BattleH1.jpg";
_playerPicBox[shipLocation].ImageLocation = "BattleH2.jpg";
}
else
{
_pcGrid[shipLocation - 1] = "S";
_pcGrid[shipLocation] = "S";
}
}
else
{
if (i <= 2)
{
_playerGrid[shipLocation] = "S";
_playerGrid[shipLocation + 10] = "S";
_playerPicBox[shipLocation].ImageLocation = "BattleV1.jpg";
_playerPicBox[shipLocation + 10].ImageLocation = "BattleV2.jpg";
}
else
{
_pcGrid[shipLocation] = "S";
_pcGrid[shipLocation + 10] = "S";
}
}
}
for (int i = 0; i < _pcGrid.Length; i++)
{
Console.Write(_pcGrid[i]);
if (i % 10 == 0) Console.Write("\n");
}
}
private void OnPlayerClick()
{
var cellIndex = -1;
if (_cpuHasHit && _cellNeighbors.Count == 0 )
{
_cellNeighbors.Enqueue(_cpuLastHitCell -1);
_cellNeighbors.Enqueue(_cpuLastHitCell + 1);
_cellNeighbors.Enqueue(_cpuLastHitCell - 10);
_cellNeighbors.Enqueue(_cpuLastHitCell + 10);
}
if (_cpuHasHit)
{
cellIndex = (int)_cellNeighbors.Dequeue();
}
else
{
do
{
Random rnd = new Random();
cellIndex = rnd.Next(0, 99);
} while (_clickedCpuQueue.Contains(cellIndex));
}
if (_playerGrid[cellIndex] == "W")
{
_playerPicBox[cellIndex].ImageLocation = "Miss.jpg";
if (!_cpuHasHit) _cpuLastHitCell = -1;
}
else
{
_playerPicBox[cellIndex].ImageLocation = "Hit.jpg";
_cpuLastHitCell = cellIndex;
if (_cpuHasHit)
{
_cpuHasHit = false;
_cellNeighbors.Clear();
_cpuLastHitCell = -1;
}
else
{
_cpuHasHit = true;
}
_playerShipsNum--;
}
_clickedCpuQueue.Enqueue(cellIndex);
if (_playerShipsNum != 0) return;
MessageBox.Show("CPU WON!!");
this.Controls.Clear();
InitGame();
}
private void OnComputerClick(object sender, EventArgs eventArgs)
{
var clickedCell = (PictureBox) sender;
var cellIndex = Convert.ToInt32(clickedCell.Name.Substring(1, clickedCell.Name.Length - 1)) - 1;
if (_pcGrid[cellIndex] == "W")
{
_pcPicBox[cellIndex].ImageLocation = "Miss.jpg";
}
else
{
_pcPicBox[cellIndex].ImageLocation = "Hit.jpg";
_pcShipsNum--;
}
if (_pcShipsNum == 0)
{
MessageBox.Show("YOU WON!!");
this.Controls.Clear();
InitGame();
}
OnPlayerClick();
}
private void Form1_Load(object sender, EventArgs e)
{
InitGame();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace numberguessgame
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int ComputerGuess;
ComputerGuess = random.Next(1000, 9999);
Console.WriteLine("Random Number Copy="+ComputerGuess);
int Number;
bool Control = false;
int[] ComputerArray = new int[4];
int[] UserArray = new int[4];
//while control not equal true
while (Control != true)
{
//User Enter the Number
Console.Write("Enter The Number=");
Number = Convert.ToInt32(Console.ReadLine());
//if ComputerGuess and Number not equal
if (ComputerGuess !=Number)
{
while (ComputerGuess > 0)
{
for (int i = 0; i < 4; i++)
{
int NumberArray = ComputerGuess % 10;
ComputerArray[4 - i - 1] = NumberArray;
ComputerGuess = ComputerGuess / 10;
}
}
Console.WriteLine("\n");
while (Number > 0)
{
for (int j = 0; j < 4; j++)
{
int UserNumber = Number % 10;
UserArray[4 - j - 1] = UserNumber;
Number = Number / 10;
}
}
int CountPositive = 0, CountNegative = 0;
//Enter the loop
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
//if computerArray equal UserArray and i equal j
if (ComputerArray[i] == UserArray[j] && i == j)
CountPositive++;
if (ComputerArray[i] == UserArray[j] && i != j)
CountNegative--;
}
}
//if countpositive equal 4 , You win
if (CountPositive == 4)
{
Control = true;
Console.WriteLine("\n You Win");
}
Console.WriteLine("\n" + CountPositive + " " + CountNegative);
}
}
Console.ReadLine();
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AuthDemo.Migrations
{
public partial class InsertedRolesTable2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "IdentityUserRole<Guid>");
migrationBuilder.DeleteData(
table: "IdentityRole",
keyColumn: "Id",
keyValue: "64c94c06-99d4-4875-a5e5-bdf436411302");
migrationBuilder.DeleteData(
table: "IdentityRole",
keyColumn: "Id",
keyValue: "a713a9cf-044c-40b2-915d-2a6aa8175a94");
migrationBuilder.CreateTable(
name: "IdentityUserRole<string>",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId });
});
migrationBuilder.InsertData(
table: "IdentityRole",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "263e32eb-7084-4075-bdda-5dd5cf14d794", "f7e3206a-8d5e-4266-b753-12c085e1f1ff", "Visitor", "VISITOR" });
migrationBuilder.InsertData(
table: "IdentityRole",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "0980a1a1-0d41-4f0a-8073-6fb3a502cc84", "a38c32a8-386a-40a9-98c7-d41f778e3871", "Administrator", "ADMINISTRATOR" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "IdentityUserRole<string>");
migrationBuilder.DeleteData(
table: "IdentityRole",
keyColumn: "Id",
keyValue: "0980a1a1-0d41-4f0a-8073-6fb3a502cc84");
migrationBuilder.DeleteData(
table: "IdentityRole",
keyColumn: "Id",
keyValue: "263e32eb-7084-4075-bdda-5dd5cf14d794");
migrationBuilder.CreateTable(
name: "IdentityUserRole<Guid>",
columns: table => new
{
UserId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
RoleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserRole<Guid>", x => new { x.UserId, x.RoleId });
});
migrationBuilder.InsertData(
table: "IdentityRole",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "64c94c06-99d4-4875-a5e5-bdf436411302", "69d175cc-b4e6-438f-a8e1-0b80edf466ac", "Visitor", "VISITOR" });
migrationBuilder.InsertData(
table: "IdentityRole",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "a713a9cf-044c-40b2-915d-2a6aa8175a94", "94e08c40-0283-4f28-99d6-664a52621b58", "Administrator", "ADMINISTRATOR" });
}
}
}
|
using DChild.Gameplay.Combat;
using UnityEngine;
namespace DChild.Gameplay
{
public interface IFXInstantiation : IGameplaySubroutine
{
ParticleFX InstantiateFX(GameObject fx, Vector2 position);
ParticleFX InstantiateStatusFX(string name, Vector2 position);
ParticleFX InstantiateDamageFX(DamageFXType damageFXType, AttackType attackType, bool isCrit, Vector2 position);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class treeMove : MonoBehaviour
{
public GameObject enemy;
public float randomX1,randomX2,randomY,randomR,randomspd;
public float Spd = 1;
int life,key;
void Start()
{
}
// Update is called once per frame
void Update()
{
life = PlayerPrefs.GetInt("life");
treespeed();
}
private void treespeed()
{
key = PlayerPrefs.GetInt("key");
if (PlayerPrefs.GetInt("life") > 0)
{
//Spd = enemy.GetComponent<Control>().hiz;
transform.Translate(0, Time.deltaTime * (Spd * 2.5f), 0);
randomR = Random.Range(1, 4);
randomX1 = Random.Range(1.65f, 2.95f);
randomX2 = Random.Range(-2.95f, -1.65f);
randomY = Random.Range(-9f, -7f);
transform.Translate(0, Time.deltaTime * (Spd * 2.5f), 0);
if (transform.position.y > 6f)
{
randomspd = Random.Range(1f, 2.3f);
Destroy(this.gameObject);
}
if (Time.deltaTime > 50 && Spd == 1)
{
Spd = Spd + 0.5f;
}
if (Time.deltaTime > 100 && Spd == 1.5f)
{
Spd = Spd + 0.5f;
}
if (Time.deltaTime > 250 && Spd == 2f)
{
Spd = Spd + 0.5f;
}
}
else
{
transform.Translate(0, 0, 0);
}
if (key == 0 && transform.position.y < -5)
{
Destroy(this.gameObject);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "tree")
{
Destroy(this.gameObject);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Teleporter : MonoBehaviour
{
public bool isActive = false;
public GameObject cover;
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
Debug.Log("Player touched me.. (" + gameObject.name + ")");
if (Input.GetKeyDown(KeyCode.E))
{
if (isActive)
{
PlayerPrefs.SetInt("Coins", collision.gameObject.GetComponent<Player>().coins);
SceneManager.LoadSceneAsync(2);
Debug.LogError("Teleporting");
}
}
}
}
public void DisableCover()
{
cover.SetActive(false);
isActive = true;
}
}
|
using Microsoft.Xna.Framework;
using ProjectMini.src.assets;
using ProjectMini.src.engine;
using ProjectMini.src.game;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectMini.src.terrain
{
public class Chunk : GameObject
{
public const int v_chunkSize = 10;
public TileVoxel[,] v_voxelArray { get; private set; }
public Chunk(Vector2 position)
{
v_position = position;
v_activated = true;
v_voxelArray = new TileVoxel[v_chunkSize, v_chunkSize];
PopulateVoxelData();
}
protected override void OnDraw()
{
for (int x = 0; x < v_chunkSize; x++)
{
for (int y = 0; y < v_chunkSize; y++)
{
if (v_voxelArray[x, y].v_tileID == 0)
{
Application.Draw(AssetsManager.v_spritesAtlas01, new Vector2((v_voxelArray[x, y].x + 1), (v_voxelArray[x, y].y +1)), new Rectangle(0,48,16,16), new Color(95, 211, 86, 255), 0, Vector2.Zero, new Vector2(-0.064f, -0.064f), Microsoft.Xna.Framework.Graphics.SpriteEffects.None, 0);
}
else
{
Application.Draw(AssetsManager.v_spritesAtlas01, new Vector2((v_voxelArray[x, y].x +1 ), (v_voxelArray[x, y].y +1 )), new Rectangle(0, 48, 16, 16), Color.Red, 0, Vector2.Zero, new Vector2(-0.064f, -0.064f), Microsoft.Xna.Framework.Graphics.SpriteEffects.None, 0);
}
}
}
base.OnDraw();
}
protected override void OnDispose()
{
base.OnDispose();
}
public void PopulateVoxelData()
{
System.Random rand = new Random(Application.instance.GetHashCode() + DateTime.Now.GetHashCode());
for (int x = 0; x < v_chunkSize; x++)
{
for (int y = 0; y < v_chunkSize; y++)
{
v_voxelArray[x, y].x = x + (int)v_position.X;
v_voxelArray[x, y].y = y + (int)v_position.Y;
v_voxelArray[x, y].v_tileID = (byte)rand.Next(0,3);
}
}
}
}
}
|
using InRule.Authoring.Commands;
using InRule.Authoring.Windows;
using InRule.Repository;
namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.GenerateSDKCode
{
public class ShowSDKCodeCommand : DefCommandBase
{
public IIrAuthorShell IrAuthorShell { get; set; }
public ShowSDKCodeCommand(RuleRepositoryDefBase def) : base("ShowSDKCode", "Generate SDK Code", "", def)
{
this.Label = "Show SDK Code for " + Def.GetType().Name;
}
public override void Execute()
{
// copy defs in case they are used by other threads
var win = new SDKCodePopupView(Def);
win.Show();
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApiAngularEcommerce
{
public class Product
{
[Required]
[MinLength(5)]
public string Name { get; set; }
public int ID { get; set; }
[Required]
[MinLength(13)]
public string Description { get; set; }
[Range(5, int.MaxValue)]
[Required]
public double Discount { get; set; }
[Required]
[Range(5, int.MaxValue)]
public double Price { get; set; }
[Required]
public string Image { get; set; }
[Required]
public int Quantity { get; set; }
public virtual Category Category { get; set; }
[JsonIgnore]
public virtual List<Review> Reviews { get; set; }
[JsonIgnore]
public virtual List<ProductCart> Carts { get; set; }
[JsonIgnore]
public virtual List<ProductOrder> Orders { get; set; }
[JsonIgnore]
public virtual List<ProductWishlist> WhishLists{get;set;}
}
} |
using Infra.Model;
using Microsoft.Azure.Cosmos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infra.Repositorios
{
public class TodoItemRepositorioCosmos
{
private string connectionString = "AccountEndpoint=https://todo-cosmos-at-raulpires.documents.azure.com:443/;AccountKey=weYrspCJDwkq2PqWtTKZUGNBry08qIz9qKhpcf0TLcV8edd4iBzRghb552uGguYX7hobhgZfVwO3QAWRuou0hQ==;";
private string Contanier = "todo-container";
private string Db = "todo-db";
private CosmosClient cosmosClient { get; set; }
public TodoItemRepositorioCosmos()
{
this.cosmosClient = new CosmosClient(this.connectionString);
}
public List<TodoItem> GetAll()
{
var container = this.cosmosClient.GetContainer(Db, Contanier);
QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c");
var queryResult = container.GetItemQueryIterator<TodoItem>(queryDefinition);
var todosTodo = new List<TodoItem>();
//percorre a lista por vez, cosmos não traz tudo de uma vez
while(queryResult.HasMoreResults)
{
//resultado de cada varredura
FeedResponse<TodoItem> resultados = queryResult.ReadNextAsync().Result;
//aqui pega o range todo de elementos e passa para a lista criada
todosTodo.AddRange(resultados.Resource);
}
return todosTodo;
}
public TodoItem GetById(Guid id)
{
var container = this.cosmosClient.GetContainer(Db, Contanier);
QueryDefinition queryDefinition = new QueryDefinition($"SELECT * FROM c where c.id = '{id}'");
var queryResult = container.GetItemQueryIterator<TodoItem>(queryDefinition);
TodoItem item = null;
while (queryResult.HasMoreResults)
{
FeedResponse<TodoItem> resultados = queryResult.ReadNextAsync().Result;
item = resultados.Resource.FirstOrDefault();
}
return item;
}
public async Task Save(itemRequest criaItem)
{
var item = new TodoItem();
item.id = Guid.NewGuid();
item.descricao = criaItem.descricao;
item.titulo = criaItem.titulo;
item.responsavel = criaItem.responsavel;
item.estado = Enum.Parse<estado>(criaItem.estado);
var container = this.cosmosClient.GetContainer(Db, Contanier);
await container.CreateItemAsync<TodoItem>(item, new PartitionKey(item.pk));
}
public async Task UpdateToDo(Guid id, itemRequest criaItem)
{
var item = GetById(id);
item.descricao = criaItem.descricao;
item.titulo = criaItem.titulo;
item.responsavel = criaItem.responsavel;
item.estado = Enum.Parse<estado>(criaItem.estado);
var container = this.cosmosClient.GetContainer(Db, Contanier);
await container.ReplaceItemAsync<TodoItem>(item, id.ToString(), new PartitionKey(item.pk));
}
public async Task Remove(TodoItem item)
{
var container = this.cosmosClient.GetContainer(Db, Contanier);
await container.DeleteItemAsync<TodoItem>(item.id.ToString(), new PartitionKey(item.pk));
}
}
}
|
namespace CubicMessages
{
using System;
using System.Text;
using System.Text.RegularExpressions;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
var line = Console.ReadLine();
var m = int.Parse(Console.ReadLine());
var regex = new Regex(@"^(\d+)([a-zA-Z]+)([^a-zA-Z]*)$");
while (true)
{
if (!regex.IsMatch(line))
{
line = Console.ReadLine();
if (line == "Over!")
{
break;
}
m = int.Parse(Console.ReadLine());
continue;
}
var match = regex.Match(line);
var key = match.Groups[2].Value;
var nums = match.Groups[1].Value + match.Groups[3].Value;
var res = new StringBuilder();
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] >= '0' && nums[i] <= '9')
{
var num = nums[i] - '0';
if (num < key.Length)
{
res.Append(key[num]);
}
else
{
res.Append(" ");
}
}
}
Console.WriteLine($"{key} == {res.ToString()}");
line = Console.ReadLine();
if (line == "Over!")
{
break;
}
m = int.Parse(Console.ReadLine());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShapeLibrary
{
public class Rectangle : Quadrilateral, IShapeCalc
{
public Rectangle(string sColour, double Length, double Width) : base(sColour, Length, Width, Length, Width)
{
}
public override double GetArea()
{
return Side1Length * Side2Length;
}
public override string ToString()
{
return "Color: " + Colour + " Side Length: " + Side1Length + " Area: " + GetArea() + " " + " Perimeter" + GetPerimeter();
}
public override double GetPerimeter()
{
return Side1Length + Side1Length + Side2Length + Side2Length;
}
}
}
|
using Microsoft.AspNetCore.Hosting;
using Quizlet_Server.Entities;
using Quizlet_Server.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace Quizlet_Server.Apis
{
[RoutePrefix("api/thes")]
public class ThesController : ApiController
{
private TheService _theService { get; set; }
public ThesController()
{
_theService = new TheService();
}
[Route("{TKId}/{par}")]
[HttpGet]
public async Task<IHttpActionResult> GetDanhSachThe(int TKId, string par)
{
var query = _theService.GetDanhSachThe(TKId);
var data = query.Select(t => new
{
t.TheID,
t.HocPhanID,
t.ThuatNgu,
t.GiaiNghia,
t.Anh,
t.NgayTao,
t.PhatAm,
t.CachSuDung,
}).ToList();
return Ok(data);
}
[Route("{id}")]
[HttpGet]
public async Task<IHttpActionResult> GetTheById(int id)
{
var t = _theService.GetTheById(id);
var data = new
{
t.TheID,
t.HocPhanID,
t.ThuatNgu,
t.GiaiNghia,
t.Anh,
t.NgayTao,
t.PhatAm,
t.CachSuDung,
};
return Ok(data);
}
[Route("")]
[HttpPost]
public async Task<IHttpActionResult> CreateThe(The the)
{
_theService.CreateThe(the);
return Ok(the);
}
[Route("{id}")]
[HttpPut]
public async Task<IHttpActionResult> UpdateThe(int id, The the)
{
_theService.UpdateThe(id, the);
return Ok(the);
}
[Route("{id}")]
[HttpDelete]
public async Task<IHttpActionResult> DeleteThe(int id)
{
_theService.DeleteThe(id);
return Ok();
}
}
}
|
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
namespace SampleUWP
{
// Enumeration used in class and various menu lists below.
public enum MenuSymbolType { text, glyph }; // If text, use resource "fontText"=Segoe UI. if glyph, use resource "fontSymbol"=Segoe MDL2 Assets.
// Class used by various menus below, all List<generic>.
public class MenuItem
{
public MenuSymbolType SymbolType { get; set; }
public string SymbolText { get; set; }
public string MenuText { get; set; }
public Type PageNavigate { get; set; }
}
public sealed partial class MainPage : Page
{
/*
The Menu/Hamburger button on title bar activates a Splitview menu that has a top menu and a bottom menu. Two of list below
establish the contents of those two menus respectively. Edit the two lists below to set what appears on the menus and what page
to navigate to when selected. For 'SymbolType', you can use symbols (glyphs) or text string.
To use symbols, use the Segoe MDL2 Assets font, Menu/Hamburger for instance, the C# unicode character escape sequence is "\uE700".
If entering the same symbol directly into XAML, you use "". The XAML version will not work in the C# code behind.
Guidelines for Segoe MDL2 icons: https://msdn.microsoft.com/en-us/windows/uwp/controls-and-patterns/segoe-ui-symbol-font
Segoe MDL2 Assets - Cheatsheet: http://modernicons.io/segoe-mdl2/cheatsheet/
Unicode in C#: Hamburger=\uE700, Home=\uE80F, Back=\uE72B, Forward=\uE72A, Page=\uE7C3
Unicode in XAML: Hamburger=, Home=, Back=, Forward=, Page=
*/
// Primary menu that shows up below the hamburger button on topMenu defined in MainPage.xaml.
public List<MenuItem> topMenuList = new List<MenuItem> // First item in this list is always the "Home" page.
{
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE80F", MenuText = "Beam Concentrated Load", PageNavigate = typeof(P01)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE7E6", MenuText = "Theme Resources", PageNavigate = typeof(P02)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE8E9", MenuText = "Rich Text Blocks", PageNavigate = typeof(P03)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P04", MenuText = "Grouping LV and GV", PageNavigate = typeof(P04)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P05", MenuText = "Pivot Basic", PageNavigate = typeof(P05)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P06", MenuText = "Binding Samples", PageNavigate = typeof(P06)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P07", MenuText = "Responsive Techniques", PageNavigate = typeof(P07)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P08", MenuText = "Explore Shapes", PageNavigate = typeof(P08)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P09", MenuText = "Win2D Shape Sample", PageNavigate = typeof(P09)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P10", MenuText = "Win2D Geometry Sample", PageNavigate = typeof(P10)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P11", MenuText = "Win2D Practice Drawings", PageNavigate = typeof(P11)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P12", MenuText = "Win2D Animation", PageNavigate = typeof(P12)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P13", MenuText = "Win2D Delegate Print", PageNavigate = typeof(P13)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P14", MenuText = "Win2D Printing Example", PageNavigate = typeof(P14)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P15", MenuText = "ComboBox Samples", PageNavigate = typeof(P15)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P16", MenuText = "Console Code Samples", PageNavigate = typeof(P16)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "P17", MenuText = "Test Numeric Input Types", PageNavigate = typeof(P17)}
};
// Secondary menu that shows up below the hamburger button on botMenu defined in MainPage.xaml.
public List<MenuItem> botMenuList = new List<MenuItem>
{
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE713", MenuText = "Settings", PageNavigate = typeof(S01)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "S02", MenuText = "Window Size Inforamtion", PageNavigate = typeof(S02)}
};
// Another menu that shows up via Binding Samples selected from topMenu below the hamburger button. These items are displayed via a Pivot menu.
public List<MenuItem> bindingMenuList = new List<MenuItem>
{
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "B01", MenuText = "ValueConverters", PageNavigate = typeof(B01)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE001", MenuText = "BindingToAModel", PageNavigate = typeof(B02)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "B03", MenuText = "Indexers", PageNavigate = typeof(B03)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE0A2", MenuText = "DataTemplates", PageNavigate = typeof(B04)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "B05", MenuText = "CollectionViewSource", PageNavigate = typeof(B05)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE005", MenuText = "CollectionChanges", PageNavigate = typeof(B06)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "B07", MenuText = "IncrementalLoading", PageNavigate = typeof(B07)},
new MenuItem() { SymbolType=MenuSymbolType.glyph, SymbolText = "\uE224", MenuText = "UpdateSourceTrigger", PageNavigate = typeof(B08)},
new MenuItem() { SymbolType=MenuSymbolType.text, SymbolText = "B09", MenuText = "Fallback-TargetNull", PageNavigate = typeof(B09)}
};
}
}
|
using Sentry.Extensibility;
namespace Sentry.Protocol.Envelopes;
/// <summary>
/// Represents a task producing an object serializable to JSON format.
/// </summary>
internal sealed class AsyncJsonSerializable : ISerializable
{
/// <summary>
/// Source object.
/// </summary>
public Task<IJsonSerializable> Source { get; }
/// <summary>
/// Initializes an instance of <see cref="AsyncJsonSerializable"/>.
/// </summary>
public static AsyncJsonSerializable CreateFrom<T>(Task<T> source)
where T : IJsonSerializable
{
var task = source.ContinueWith(t => t.Result as IJsonSerializable);
return new AsyncJsonSerializable(task);
}
private AsyncJsonSerializable(Task<IJsonSerializable> source) => Source = source;
/// <inheritdoc />
public async Task SerializeAsync(Stream stream, IDiagnosticLogger? logger, CancellationToken cancellationToken = default)
{
var source = await Source.ConfigureAwait(false);
var writer = new Utf8JsonWriter(stream);
await using (writer.ConfigureAwait(false))
{
source.WriteTo(writer, logger);
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public void Serialize(Stream stream, IDiagnosticLogger? logger)
{
using var writer = new Utf8JsonWriter(stream);
Source.Result.WriteTo(writer, logger);
writer.Flush();
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.Nav
{
public class NavEntity
{
/// <summary>
///ID
/// </summary>
[DataMember]
public string Id;
/// <summary>
/// 地址
/// </summary>
[DataMember]
public string Path;
/// <summary>
/// 类型
/// </summary>
[DataMember]
public string Type;
/// <summary>
/// 中文名称
/// </summary>
[DataMember]
public string ChineseName;
/// <summary>
/// 英文名称
/// </summary>
[DataMember]
public string EnglishName;
/// <summary>
/// 图表地址
/// </summary>
[DataMember]
public string IconPath;
/// <summary>
/// 排序
/// </summary>
[DataMember]
public string Sort;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityClass
{
public class Shippers
{
string _ID;
string _CompanyName;
string _Phone;
public string ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
public string CompanyName
{
get
{
return _CompanyName;
}
set
{
_CompanyName = value;
}
}
public string Phone
{
get
{
return _Phone;
}
set
{
_Phone = value;
}
}
public Shippers()
{
}
public override bool Equals(object obj)
{
Shippers sh = obj as Shippers;
return (sh != null) && sh.ID.Equals(ID);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace TabularTool
{
public class TabularData
{
private string[,] _data;
public bool FirstRowIsHeader { get; set; }
public string this[int x, int y] => _data[x, y];
public int Width => _data.GetLength(0);
public int Height => _data.GetLength(1);
public IEnumerable<string> Column(int x) => Enumerable.Range(0, Height).Select(y => this[x, y]);
public IEnumerable<string> Row(int y) => Enumerable.Range(0, Width).Select(x => this[x, y]);
public IEnumerable<IEnumerable<string>> Columns => Enumerable.Range(0, Width).Select(Column);
public IEnumerable<IEnumerable<string>> Rows => Enumerable.Range(0, Height).Select(Row);
public TabularData() : this(new string[0, 0], false) { }
public TabularData(string[,] data, bool firstRowIsHeader) {
_data = data;
FirstRowIsHeader = firstRowIsHeader;
}
public static TabularData FromRows(IEnumerable<IEnumerable<string>> rows) {
string[][] raw = rows.Select(r => r.ToArray()).ToArray();
int height = raw.Count();
int width = raw.Max(r => r.Count());
string[,] data = new string[width, height];
for (int y = 0; y < height; y++) {
var row = raw[y];
for (int x = 0; x < width; x++) {
data[x, y] = x < row.Count() ? (raw[y][x] ?? "") : "";
}
}
bool firstRowIsHeader = Settings.Get.FirstRowIsHeader;
return new TabularData(data, firstRowIsHeader);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.VIEW;
using com.Sconit.Entity.SYS;
//TODO: Add other using statements here
namespace com.Sconit.Entity.INV
{
public partial class Hu
{
#region Non O/R Mapping Properties
public string ManufacturePartyDescription { get; set; }
public string BinTo { get; set; }
public string OldHus { get; set; }
//public string Flow { get; set; }
#endregion
[Export(ExportName = "ShelfLifeWarning", ExportSeq = 46)]
[Export(ExportName = "OutOfExpireTimeWarning", ExportSeq = 26)]
[Export(ExportName = "ShelfLifeWarningSummary", ExportSeq = 40)]
[Display(Name = "Item_MaterialsGroupDesc", ResourceType = typeof(Resources.MD.Item))]
public string MaterialsGroupDesc { get; set; }
/// <summary>
/// 车型
/// </summary>
[Display(Name = "Hu_Model", ResourceType = typeof(Resources.INV.Hu))]
public string Model { get; set; }
/// <summary>
/// 长度
/// </summary>
[Display(Name = "Hu_Length", ResourceType = typeof(Resources.INV.Hu))]
public double Length { get; set; }
public HuStatus HuStatus { get; set; }
//[Export(ExportName = "ShelfLifeWarning", ExportSeq = 110, ExportTitle = "Hu_HuStatusDescription", ExportTitleResourceType = typeof(@Resources.INV.Hu))]
[Display(Name = "Hu_HuStatusDescription", ResourceType = typeof(Resources.INV.Hu))]
public string ExpireStatus { get; set; }
[com.Sconit.Entity.SYS.CodeDetailDescription(CodeMaster = com.Sconit.CodeMaster.CodeMaster.HuOption, ValueField = "HuOption")]
[Display(Name = "Hu_HuOptionTypeDescription", ResourceType = typeof(Resources.INV.Hu))]
public string HuOptionTypeDescription { get; set; }
[Export(ExportName = "ShelfLifeWarning", ExportSeq = 25)]
[Display(Name = "LocationLotDetail_Location", ResourceType = typeof(Resources.INV.LocationLotDetail))]
public string Location { get; set; }
[Export(ExportName = "Ageing", ExportSeq = 6)]
[Display(Name = "LocationLotDetail_Bin", ResourceType = typeof(Resources.INV.LocationLotDetail))]
public string Bin { get; set; }
[Export(ExportName = "Ageing", ExportSeq = 65)]
[Display(Name = "LocationLotDetail_IsFreeze", ResourceType = typeof(Resources.INV.LocationLotDetail))]
public int IsFreeze { get; set; }
//TotalQty,0 UnAgingQty,0 AgedQty,0 AgingQty
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 30)]
[Display(Name = "Hu_TotalQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal TotalQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 40)]
[Display(Name = "Hu_UnAgingQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal UnAgingQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 60)]
[Display(Name = "Hu_AgedQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal AgedQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 50)]
[Display(Name = "Hu_AgingQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal AgingQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 70)]
[Display(Name = "Hu_SQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal SQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 80)]
[Display(Name = "Hu_NoNeedAgingQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal NoNeedAgingQty { get; set; }
//FreezedQty,NonFreezeQty,QulifiedQty,InspectQty,InQulifiedQty
public com.Sconit.CodeMaster.QualityType QualityType { get; set; }
[Export(ExportName = "Ageing", ExportSeq = 85, ExportTitleResourceType = typeof(Resources.INV.Hu), ExportTitle = "QualityType")]
[com.Sconit.Entity.SYS.CodeDetailDescription(CodeMaster = com.Sconit.CodeMaster.CodeMaster.QualityType, ValueField = "QualityType")]
[Display(Name = "QualityType", ResourceType = typeof(Resources.INV.Hu))]
public string QualityTypeDescription { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 90)]
[Display(Name = "LocationLotDetail_IsFreeze", ResourceType = typeof(Resources.INV.LocationLotDetail))]
public Decimal FreezedQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 100)]
[Display(Name = "Hu_NonFreezeQty", ResourceType = typeof(Resources.INV.Hu))]
public Decimal NonFreezeQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 110)]
[Display(Name = "LocationDetailIOB_EndNml", ResourceType = typeof(Resources.Report.LocationDetailIOB))]
public Decimal QulifiedQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 120)]
[Display(Name = "LocationDetailIOB_EndInp", ResourceType = typeof(Resources.Report.LocationDetailIOB))]
public Decimal InspectQty { get; set; }
[Export(ExportName = "AgeingSumByLocation", ExportSeq = 130)]
[Display(Name = "LocationDetailIOB_EndRej", ResourceType = typeof(Resources.Report.LocationDetailIOB))]
public Decimal InQulifiedQty { get; set; }
[Export(ExportName = "ShelfLifeWarningSummary", ExportSeq = 50)]
[Display(Name = "Hu_Qty0", ResourceType = typeof(Resources.INV.Hu))]
public Decimal Qty0 { get; set; }
[Export(ExportName = "ShelfLifeWarningSummary", ExportSeq = 60)]
[Display(Name = "Hu_Qty1", ResourceType = typeof(Resources.INV.Hu))]
public Decimal Qty1 { get; set; }
[Export(ExportName = "ShelfLifeWarningSummary", ExportSeq = 70)]
[Display(Name = "Hu_Qty2", ResourceType = typeof(Resources.INV.Hu))]
public Decimal Qty2 { get; set; }
[Export(ExportName = "ShelfLifeWarning", ExportSeq = 100)]
[Display(Name = "Hu_ExpireDate", ResourceType = typeof(Resources.INV.Hu))]
public string ExpireDateValue { get; set; }
[Export(ExportName = "ShelfLifeWarning", ExportSeq = 90)]
[Display(Name = "Hu_RemindExpireDate", ResourceType = typeof(Resources.INV.Hu))]
public string RemindExpireDateValue { get; set; }
/// <summary>
/// 拆箱数字符串
/// </summary>
[Display(Name = "Hu_DevanningQty1", ResourceType = typeof(Resources.INV.Hu))]
public Decimal DevanningQty1 { get; set; }
[Display(Name = "Hu_DevanningQty2", ResourceType = typeof(Resources.INV.Hu))]
public Decimal DevanningQty2 { get; set; }
[Display(Name = "Hu_DevanningQty3", ResourceType = typeof(Resources.INV.Hu))]
public Decimal DevanningQty3 { get; set; }
[Display(Name = "Hu_DevanningQty4", ResourceType = typeof(Resources.INV.Hu))]
public Decimal DevanningQty4 { get; set; }
[Display(Name = "Hu_DevanningQty", ResourceType = typeof(Resources.INV.Hu))]
public string DevanningQtyStr { get; set; }
}
} |
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* 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.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Clifton.Core.Assertions;
using Clifton.Core.ExtensionMethods;
using Clifton.Meaning;
namespace MeaningExplorer
{
public static class Renderer
{
private static string CRLF = "\r\n";
public enum Mode
{
NewRecord,
Search,
View,
}
public static string CreatePage(Parser parser, Mode mode = Mode.NewRecord, ContextValueDictionary cvd = null, Guid rootId = default(Guid))
{
StringBuilder sb = new StringBuilder();
List<LookupItem> lookupDictionary = new List<LookupItem>();
sb.StartHtml();
sb.StartHead().
Script("/js/wireUpValueChangeNotifier.js").
Stylesheet("/css/styles.css").
EndHead();
sb.StartBody();
foreach (var group in parser.Groups)
{
// Bizarre alternatives:
//(group.ContextPath.Count() == 0 ? new Action(()=>sb.StartDiv()) : new Action(()=>sb.StartInlineDiv()))();
//var throwAway = group.ContextPath.Count() == 0 ? sb.StartDiv() : sb.StartInlineDiv();
if (group.ContextPath.Count() == 0)
{
// sb.StartDiv();
sb.StartInlineDiv();
}
else
{
sb.StartInlineDiv();
// sb.StartDiv();
}
// if (group.Relationship.GetType() != typeof(NullRelationship))
if (group.Relationship.RelationshipType != typeof(NullRelationship))
{
// TODO: If the mode is search, then we only want to display one instance, and not as a grid.
if (group.Relationship.Maximum < 6 && !group.Relationship.RenderAsGrid)
{
for (int recNum = 0; recNum < group.Relationship.Maximum; recNum++)
{
// multiple instances are stacked vertically.
sb.StartDiv();
// Horizontal stacking:
// sb.StartInlineDiv();
CreateFieldset(parser, sb, lookupDictionary, group, mode, cvd, rootId, recNum, group.Relationship.Minimum);
sb.EndDiv();
}
}
else
{
// TODO: Some arbitrary cutoff would change the fieldset to use a grid instead of discrete text input's.
CreateGrid(parser, sb, group, mode, cvd, rootId, group.Relationship.Minimum, group.Relationship.Maximum);
// CreateFieldset(parser, sb, group, mode, cvd, rootId);
}
}
else
{
CreateFieldset(parser, sb, lookupDictionary, group, mode, cvd, rootId);
}
sb.EndDiv();
// if there's no path, the next group does on the next line, otherwise the groups start stacking horizontally.
if (group.ContextPath.Count() == 0)
{
// https://css-tricks.com/the-how-and-why-of-clearing-floats/
sb.StartDiv().CustomStyle("clear", "both").EndDiv();
}
sb.Append("\r\n");
}
// https://css-tricks.com/the-how-and-why-of-clearing-floats/
sb.StartDiv().CustomStyle("clear", "both").EndDiv();
sb.StartDiv();
switch (mode)
{
case Mode.Search:
sb.StartButton().ID("searchContext").Class("margintop10").Append("Search Context").EndButton();
sb.StartParagraph().Append("<b>Search Results:</b>").EndParagraph();
sb.StartParagraph().StartDiv().ID("searchResults").EndDiv().EndParagraph();
sb.StartParagraph().StartDiv().ID("viewSelectedItem").EndDiv().EndParagraph();
break;
case Mode.NewRecord:
sb.StartButton().ID("newContext").Class("margintop10").Append("New Context").EndButton();
sb.StartParagraph().Append("<b>Dictionary:</b>").EndParagraph();
sb.StartParagraph().StartDiv().ID("dictionary").EndDiv().EndParagraph();
sb.StartParagraph().Append("<b>Type Nodes:</b>").EndParagraph();
sb.StartParagraph().StartDiv().ID("nodes").EndDiv().EndParagraph();
break;
}
sb.EndDiv();
string jsonLookupDict = JsonConvert.SerializeObject(lookupDictionary, Formatting.Indented);
sb.Append(CRLF);
sb.StartScript().Append(CRLF).
Javascript("(function() {wireUpValueChangeNotifier(); wireUpEvents();})();").
Append(CRLF).
Javascript("lookupDictionary = " + jsonLookupDict + ";").
Append(CRLF).
EndScript().
Append(CRLF);
sb.EndBody().EndHtml();
return sb.ToString();
}
private static void CreateGrid(Parser parser, StringBuilder sb, Group group, Mode mode, ContextValueDictionary cvd, Guid rootId, int min, int max)
{
sb.StartFieldSet().Legend(group.Name);
sb.StartTable();
// Create headers
sb.StartRow();
foreach (var field in group.Fields)
{
sb.StartHeader().Append(field.Label).EndHeader();
}
sb.EndRow();
// int recNum = 0;
// For giggles, let's create 20 rows
for (int recNum = 0; recNum < 20.Min(max); recNum++)
{
sb.StartRow();
foreach (var field in group.Fields)
{
string fieldValue = field.ContextValue?.Value ?? "";
List<Guid> instanceIdList = new List<Guid>();
// If viewing an existing record, don't create a new instanceID for the field.
if (mode != Mode.View)
{
// Here we want to bind the field's context path type list, up to the path that contains the context value,
// with ID's for the path types, creating ID's if the path type doesn't exist. This ensures that all data instances
// exist within a single root context.
instanceIdList = parser.CreateInstancePath(field.ContextPath.Select(cp => cp.Type));
}
else
{
Assert.That(cvd != null, "ContextValueDictionary must be provided when viewing existing context data.");
Assert.That(rootId != Guid.Empty, "A non-empty root ID is required when viewing existing context data.");
// In view mode, the context path to the field [context path - 1] should match a dictionary entry,
// then we need to acquire the instance ID for the record number and type of the actual ContextValue.
// If there is no record number entry, the value is assigned to "".
if (cvd.TryGetContextNode(field, rootId, recNum, out ContextNode cn, out List<Guid> instanceIdPath))
{
instanceIdList = instanceIdPath;
fieldValue = cn.ContextValue.Value;
}
else
{
fieldValue = "";
}
}
string cls = mode == Mode.Search ? "contextualValueSearch" : "contextualValue";
cls = cls + (recNum < min ? " requiredValue" : "");
sb.StartColumn().
AppendTextInput().
Class(cls).
ID(String.Join(".", instanceIdList)).
CustomAttribute("cvid", String.Join(".", instanceIdList)).
CustomAttribute("contextPath", String.Join("|", field.ContextPath.Select(p => p.Type.AssemblyQualifiedName))).
CustomAttribute("recordNumber", recNum.ToString()).
CustomAttribute("value", mode == Mode.View ? fieldValue : "").
// Not as pretty as a real tooltip, but works well.
// Also see: https://www.w3schools.com/howto/howto_css_tooltip.asp
CustomAttribute("title", String.Join("
", field.ContextPath.Select(p => p.Type.Name))).
// CustomAttribute("title", String.Join("
", field.ContextPath.Select(p => p.InstanceId))).
EndColumn();
}
sb.EndRow();
}
sb.EndTable();
}
private static void CreateFieldset(Parser parser, StringBuilder sbHtml, List<LookupItem> lookupDictionary, Group group, Mode mode, ContextValueDictionary cvd, Guid rootId, int recNum = 0, int min = 0)
{
sbHtml.StartFieldSet().Legend(group.Name);
List<LookupItem> lookupItems = new List<LookupItem>();
if (mode != Mode.View)
{
lookupItems.AddRange(RenderOptionalLookup(sbHtml, parser, group, cvd));
lookupDictionary.AddRange(lookupItems);
}
sbHtml.StartTable();
foreach (var field in group.Fields)
{
string fieldValue = field.ContextValue?.Value ?? "";
List<Guid> instanceIdList = new List<Guid>();
// If viewing an existing record, don't create a new instanceID for the field.
if (mode != Mode.View)
{
// Here we want to bind the field's context path type list, up to the path that contains the context value,
// with ID's for the path types, creating ID's if the path type doesn't exist. This ensures that all data instances
// exist within a single root context.
instanceIdList = parser.CreateInstancePath(field.ContextPath.Select(cp => cp.Type));
LookupItemLateBinding(field, lookupItems, instanceIdList);
}
else
{
Assert.That(cvd != null, "ContextValueDictionary must be provided when viewing existing context data.");
Assert.That(rootId != Guid.Empty, "A non-empty root ID is required when viewing existing context data.");
// In view mode, the context path to the field [context path - 1] should match a dictionary entry,
// then we need to acquire the instance ID for the record number and type of the actual ContextValue.
// If there is no record number entry, the value is assigned to "".
if (cvd.TryGetContextNode(field, rootId, recNum, out ContextNode cn, out List<Guid> instanceIdPath))
{
instanceIdList = instanceIdPath;
fieldValue = cn.ContextValue.Value;
}
else
{
fieldValue = "";
}
}
sbHtml.StartRow();
string cls = mode == Mode.Search ? "contextualValueSearch" : "contextualValue";
cls = cls + (recNum < min ? " requiredValue" : "");
sbHtml.StartColumn().
AppendLabel(field.Label + ":").
NextColumn().
AppendTextInput().
Class(cls).
ID(String.Join(".", instanceIdList)).
CustomAttribute("cvid", String.Join(".", instanceIdList)).
CustomAttribute("contextPath", String.Join("|", field.ContextPath.Select(p => p.Type.AssemblyQualifiedName))).
CustomAttribute("recordNumber", recNum.ToString()).
CustomAttribute("value", mode == Mode.View ? fieldValue : "").
// Not as pretty as a real tooltip, but works well.
// Also see: https://www.w3schools.com/howto/howto_css_tooltip.asp
CustomAttribute("title", String.Join("
", field.ContextPath.Select(p => p.Type.Name))).
// CustomAttribute("title", String.Join("
", field.ContextPath.Select(p => p.InstanceId))).
EndColumn();
sbHtml.EndRow();
}
sbHtml.EndTable();
sbHtml.EndFieldSet();
sbHtml.Append("\r\n");
}
/// <summary>
/// Adds a "select" section with lookup items that are rendered by the
/// lookup rendering declaration for a particular context, returning the
/// lookup items that were created.
/// </summary>
private static List<LookupItem> RenderOptionalLookup(StringBuilder sb, Parser parser, Group group, ContextValueDictionary cvd)
{
List<LookupItem> lookupItems = new List<LookupItem>();
var groupContextType = group.ContextType;
int lookupId = 0;
// If there's an associated lookup, query the dictionary for instances of this context (no filtering for now!)
// and render the values as declared by the lookup. If no dictionary is provided, lookups are not possible.
if (cvd != null && parser.HasLookup(groupContextType))
{
Lookup lookup = parser.GetLookup(groupContextType);
IReadOnlyList<ContextNode> contextNodes = cvd.GetContextNodes(groupContextType);
if (contextNodes.Count > 0)
{
// 1. Iterate each context node.
// 2. Navigate the children until we get concrete (not null) ContextValue's.
// 3. Get the distinct record numbers of these.
// 4. Itereate the record numbers
// 5. Render the lookup for that context node and record number.
// 6. For each actual IValueEntity (contained in a LookupEntity) acquire the ContextValue and add
// an entry in the lookupItems collection, which will serve as dictionary for how a selected item
// populates its associated input control.
List<(string, int)> lookups = new List<(string, int)>();
foreach (var cn in contextNodes) // 1
{
IReadOnlyList<ContextValue> contextValues = cvd.GetContextValues(cn); // 2
var recnums = contextValues.Select(cv => cv.RecordNumber).Distinct(); // 3
foreach (var recnum in recnums) // 4
{
string record = lookup.Render(cn, cvd, recnum, contextValues); // 5
lookups.Add((record, lookupId));
// 6
var lookupEntities = lookup.GetLookupEntities();
foreach (var lookupEntity in lookupEntities)
{
var contextValue = contextValues.SingleOrDefault(cv => cv.Type == lookupEntity.ValueEntity && cv.RecordNumber == recnum);
if (contextValue != null)
{
// The full instance ID path is path, up to the lookup sub-context, in
// which this sub-context is contained. However, we don't have this value yet!
// It is either generated (new context) or assigned (existing context)
// so we need to defer this until we know the instance ID path we're using.
lookupItems.Add(new LookupItem(contextValue, groupContextType, lookupId));
}
}
++lookupId;
}
}
sb.Append("Lookup: ");
sb.StartSelect().OnChange("populateFromLookup(this)");
// Placeholder so user has to actively select a lookup because because otherwise the first item
// appears selected, and clicking on the option doesn't trigger the event.
sb.Option("Choose item:");
// lk is a tuple (lookup text, lookup ID)
lookups.ForEach(lk => sb.Option(lk.Item1, lk.Item2.ToString()));
sb.EndSelect();
}
}
return lookupItems;
}
private static void LookupItemLateBinding(Field field, List<LookupItem> lookupItems, List<Guid> instanceIdList)
{
// Late binding of lookupItem's FullContextInstancePath:
foreach (var lookupItem in lookupItems.Where(li => li.ContextValue.Type == field.ContextPath.Last().Type))
{
lookupItem.OriginalContextInstancePath.AddRange(instanceIdList);
// Find where in the entire path for this field the lookup value sub-context starts.
int idx = field.ContextPath.IndexOf(cp => cp.Type == lookupItem.ContextType);
// The full context instance ID path starts with these base ID's...
lookupItem.NewContextInstancePath.AddRange(lookupItem.OriginalContextInstancePath.Take(idx));
// ...and finishes with the context ID's for the lookup.
lookupItem.NewContextInstancePath.AddRange(lookupItem.ContextValue.InstancePath.Skip(idx));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Security.Permissions;
using System.Web;
namespace Athenaeum.Models
{
public class Rsvp
{
public int RsvpId { get; set; }
public string UserId { get; set; }
public int EventId { get; set; }
//0 - Tentative, 1 - Accepted
public int Status { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
[ForeignKey("EventId")]
public virtual Event Event { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Imp.Core.Domain.Users;
namespace Imp.Admin.Models.Users
{
public class UserListModel
{
[DisplayName("用户名")]
public string SearchUsername { get; set; }
[DisplayName("姓名")]
public string SearchDisplayName { get; set; }
[DisplayName("角色")]
public IList<RoleModel> AvailableRoles { get; set; }
[DisplayName("角色")]
public string[] SearchRoleIds { get; set; }
}
} |
using BDTest.Maps;
using BDTest.NetCore.Razor.ReportMiddleware.Extensions;
using BDTest.NetCore.Razor.ReportMiddleware.Interfaces;
using BDTest.NetCore.Razor.ReportMiddleware.Models;
namespace BDTest.NetCore.Razor.ReportMiddleware.Implementations;
internal class DataRepository : IDataRepository
{
private readonly IMemoryCacheBdTestDataStore _memoryCacheBdTestDataStore;
private readonly IBDTestDataStore _customDatastore;
public DataRepository(IMemoryCacheBdTestDataStore memoryCacheBdTestDataStore, BDTestReportServerOptions options)
{
_memoryCacheBdTestDataStore = memoryCacheBdTestDataStore;
_customDatastore = options.DataStore;
// Get all records on startup
Task.Run(GetAllTestRunRecords);
}
public async Task<BDTestOutputModel> GetData(string id, CancellationToken cancellationToken)
{
// Check if it's already in-memory
var model = await _memoryCacheBdTestDataStore.GetTestData(id, cancellationToken);
if (model == null && _customDatastore != null)
{
// Search the backup persistent storage
model = await _customDatastore.GetTestData(id, cancellationToken);
}
if (model == null)
{
return null;
}
// Re-cache it to extend the time
await _memoryCacheBdTestDataStore.StoreTestData(id, model);
return model;
}
public async Task<IEnumerable<TestRunSummary>> GetAllTestRunRecords()
{
// Check if it's already in-memory
var memoryCachedModels = (await _memoryCacheBdTestDataStore.GetAllTestRunRecords()).ToList();
if (memoryCachedModels.Any() || _customDatastore == null)
{
return memoryCachedModels;
}
// Search the backup persistent storage
var dataStoredModels = await _customDatastore.GetAllTestRunRecords() ?? Array.Empty<TestRunSummary>();
var dataStoredModelsAsList = dataStoredModels.ToList();
foreach (var testRunRecord in dataStoredModelsAsList)
{
await _memoryCacheBdTestDataStore.StoreTestRunRecord(testRunRecord);
}
return dataStoredModelsAsList.OrderByDescending(record => record.StartedAtDateTime);
}
public async Task StoreData(BDTestOutputModel bdTestOutputModel, string id)
{
if (await _memoryCacheBdTestDataStore.GetTestData(id, default) == null)
{
// Save to in-memory cache for 8 hours for quick fetching
await _memoryCacheBdTestDataStore.StoreTestData(id, bdTestOutputModel);
await _memoryCacheBdTestDataStore.StoreTestRunRecord(bdTestOutputModel.GetOverview());
if (_customDatastore != null)
{
// Save to persistent storage if it's configured!
await _customDatastore.StoreTestData(id, bdTestOutputModel);
await _customDatastore.StoreTestRunRecord(bdTestOutputModel.GetOverview());
}
}
}
public async Task DeleteReport(string id)
{
if (_customDatastore != null)
{
// Save to persistent storage if it's configured!
await _customDatastore.DeleteTestData(id);
await _customDatastore.DeleteTestRunRecord(id);
}
await _memoryCacheBdTestDataStore.DeleteTestData(id);
await _memoryCacheBdTestDataStore.DeleteTestRunRecord(id);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int numberOfWaves = int.Parse(Console.ReadLine());
var plates = new Queue<int>();
var trojanWariors = new Queue<int>();
int[] spartanPlates = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
foreach (var plate in spartanPlates)
{
plates.Enqueue(plate);
}
for (int i = 0; i < numberOfWaves; i++)
{
int[] input = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
//if (numberOfWaves % 3 == 0)
//{
// int additionalPlate = int.Parse(Console.ReadLine());
// plates.Enqueue(additionalPlate);
//}
foreach (var warior in input)
{
trojanWariors.Enqueue(warior);
}
}
while (plates.Any() && trojanWariors.Any())
{
int spartansDefence = plates.Dequeue(); // 10
int trojanAttackers = trojanWariors.Dequeue(); // 1
while(spartansDefence > trojanAttackers)
{
spartansDefence -= trojanAttackers; //9
trojanAttackers = trojanWariors.Dequeue(); //5
}
}
var platesLeft = new List<int>();
var attackersLeft = new List<int>();
foreach (var plate in plates)
{
platesLeft.Add(plate);
}
if(plates.Any())
{
Console.WriteLine("The Spartans successfully repulsed the Trojan attack.");
Console.WriteLine("Plates left: ");
Console.Write(string.Join(", ", platesLeft));
}
foreach (var attacker in trojanWariors)
{
attackersLeft.Add(attacker);
}
if (trojanWariors.Any())
{
Console.WriteLine("The Trojans successfully destroyed the Spartan defense.");
Console.WriteLine("Warriors left: ");
Console.Write(string.Join(", ", attackersLeft));
}
}
}
}
|
using PhotonInMaze.Common.Controller;
using PhotonInMaze.Common.Flow;
using PhotonInMaze.Common.Model;
using PhotonInMaze.Provider;
using System.Collections.Generic;
using UnityEngine;
namespace PhotonInMaze.Maze {
internal class MazeCellManager : FlowBehaviour, IMazeCellManager {
private IMazeCell[,] maze;
private int rows, columns;
float cellLengthSide;
public override void OnInit() {
IMazeConfiguration configuration = MazeObjectsProvider.Instance.GetMazeConfiguration();
rows = configuration.Rows;
columns = configuration.Columns;
cellLengthSide = configuration.CellSideLength;
maze = new MazeCell[rows, columns];
for(int row = 0; row < rows; row++) {
for(int column = 0; column < columns; column++) {
MazeCell cell = new MazeCell(row, column, cellLengthSide);
maze[row, column] = cell;
}
}
}
public override int GetInitOrder() {
return (int) InitOrder.MazeCellManager;
}
public bool IsATrap(HashSet<IMazeCell> visitedCells, IMazeCell currentCell) {
if(currentCell.Row == 0 && currentCell.Column == 0) {
return false;
}
if(visitedCells.Count == 0) {
return true;
}
bool allVisitedIsTrap = true;
HashSet<IMazeCell>.Enumerator enumerator = visitedCells.GetEnumerator();
while(enumerator.MoveNext()) {
allVisitedIsTrap = allVisitedIsTrap && enumerator.Current.IsTrap;
}
return allVisitedIsTrap;
}
public bool IsPathToGoalVisited(HashSet<IMazeCell> visitedCells) {
HashSet<IMazeCell>.Enumerator enumerator = visitedCells.GetEnumerator();
while(enumerator.MoveNext()) {
if(enumerator.Current.IsProperPathToGoal || enumerator.Current.IsGoal) {
return true;
}
}
return false;
}
public IMazeCell GetExitCell() {
return GetMazeCell(rows - 1, columns - 1);
}
public IMazeCell GetStartCell() {
return GetMazeCell(0, 0);
}
public IMazeCell GetMazeCell(int row, int column) {
if(row >= 0 && column >= 0 && row < rows && column < columns) {
return maze[row, column];
} else {
Debug.Log(row + " " + column);
throw new System.ArgumentOutOfRangeException();
}
}
}
} |
//Flora Kolikyan
//200455023
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;
namespace FinalProject
{
//creating CreateForm
public partial class CreateForm : Form
{
//creating arraylist which will store error messages from validation
ArrayList ErrorsList;
//creating dataContext which helps us to connect to database
LinqToSqlConnectionClassDataContext dataContext;
public CreateForm()
{
InitializeComponent();
}
private void CreateForm_Load(object sender, EventArgs e)
{
//we need to add background image for our form
//so, the first step will be adding the image in the Resources.resx. In the Resources.resx we are uploading the files that will be used in the current project
//next step is connecting this image to this form through properties
this.BackgroundImage = Properties.Resources.Background;
//here we are initialize dataContext
dataContext = new LinqToSqlConnectionClassDataContext();
}
// in this function we are create action which will happen when we submit button
private void SubmitButton_Click(object sender, EventArgs e)
{
//here we are initialize ErrorsList
ErrorsList = new ArrayList();
//creating check statement which will help us when we will validate
Boolean ValidData = true;
//there will be validation of all textboxes
//in the textboxes where we will expect only letters we add match with [a-zA-Z] regular expression. Which will avoid any other symbols or numeric.
//in the textboxes where we will expect only numbers we add match with [0-9] regular expression. Which will avoid any other symbols or letters.
//we can concat common regular expressions but as soon as we need unique error messages for each textbox we won't do that.
if (!Regex.Match(FirstNameTextbox.Text, "^[a-zA-Z]*$").Success)
{
//function .Add() help us to add the new position to the arraylist
ErrorsList.Add("First name can contain only letters");
ValidData = false;
}
if (!Regex.Match(LastNameTextbox.Text, "^[a-zA-Z]*$").Success)
{
ErrorsList.Add("Last name can contain only letters");
ValidData = false;
}
if (!Regex.Match(AgeTextbox.Text, "^[0-9]*$").Success)
{
ErrorsList.Add("The age can contain only numbers");
ValidData = false;
}
//for this validation we also look at how many letters should be in the field
if (PositionOnFieldTextBox.Text.Length > 3 || !Regex.Match(PositionOnFieldTextBox.Text, "^[a-zA-Z]*$").Success)
{
ValidData = false;
ErrorsList.Add("The position can only contains 3 letters");
}
//we also need to check if the field contain anything. Bcs textboxes have string type and we don't need convert int we concat all textboxes.
if (string.IsNullOrEmpty(FirstNameTextbox.Text) || string.IsNullOrEmpty(LastNameTextbox.Text) || string.IsNullOrEmpty(CountryTextbox.Text) || string.IsNullOrEmpty(AgeTextbox.Text) || string.IsNullOrEmpty(MatchesAmountTextbox.Text) || string.IsNullOrEmpty(GoalsTextbox.Text) || string.IsNullOrEmpty(AssistsTextbox.Text) || string.IsNullOrEmpty(TeamTextbox.Text) || string.IsNullOrEmpty(NumberTextbox.Text) || string.IsNullOrEmpty(PositionOnFieldTextBox.Text))
{
ValidData = false;
ErrorsList.Add("The fields can't be empty!");
}
//the last validation is checking if the ValidDate is false or true
//if false
if (ValidData == false)
{
//cerating StringBuilder object which saving the stored error messages that created before
StringBuilder builder = new StringBuilder();
//itterating though all arrylist
foreach (string element in ErrorsList)
{
//function .Append help us to gather all messages together
builder.Append(element);
builder.Append("\n");
}
//here we call message box with all errors from validation
MessageBox.Show(builder.ToString());
//function .Clear() will delete previous errors messages from previous validation.
ErrorsList.Clear();
}
else {
players_statistic plstat = new players_statistic();
plstat.player_first_name = FirstNameTextbox.Text;
plstat.player_last_name = LastNameTextbox.Text;
plstat.country_of_birth = CountryTextbox.Text;
plstat.player_age = int.Parse(AgeTextbox.Text);
plstat.assists_made = int.Parse(AssistsTextbox.Text);
plstat.goals_scored = int.Parse(GoalsTextbox.Text);
plstat.player_number = int.Parse(NumberTextbox.Text);
plstat.matches_played = int.Parse(MatchesAmountTextbox.Text);
plstat.player_team = TeamTextbox.Text;
plstat.position_on_field = PositionOnFieldTextBox.Text;
dataContext.players_statistics.InsertOnSubmit(plstat);
dataContext.SubmitChanges();
this.Hide();
var menu = new MainMenu();
//open main menu
menu.ShowDialog();
this.Close();
}
}
}
}
|
namespace cyrka.api.domain.jobs
{
public enum JobTypeUnit {
Undefined = 0,
Piece,
Minute,
Character,
Symbol,
Gigabyte
}
}
|
using System;
using JourniAPI.Services;
using JourniAPI.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using MongoDB.Bson;
namespace JourniAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TripsController : ControllerBase
{
private readonly TripService _tripService;
public TripsController(TripService tripService)
{
_tripService = tripService;
}
[Authorize]
[HttpGet]
public ActionResult<List<Trip>> GetAllTrips()
{
string id = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return _tripService.GetAllTrips(id);
}
[Authorize]
[HttpGet("{tripId}")]
public ActionResult<Trip> GetTrip(string tripId)
{
ObjectId _id = ObjectId.Parse(tripId);
string id = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return _tripService.GetTrip(id, _id);
}
[Authorize]
[HttpPost("{trip._id}")]
public ActionResult<Trip> CreateTrip(Trip trip)
{
string id = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return Ok(_tripService.CreateTrip(id, trip));
}
[Authorize]
[HttpDelete("{tripId}")]
public IActionResult RemoveTrip(string tripId)
{
ObjectId _id = ObjectId.Parse(tripId);
string id = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
_tripService.RemoveTrip(id, _id);
return NoContent();
}
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
namespace CapaDatos
{
public class DStockMedida
{
SqlConnection cn;
public string InsertStockMedida(int cod_med, int cod_pro_stock)
{
string respuesta;
try
{
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("InsertStockMedida", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@cod_med", cod_med);
cmd.Parameters.AddWithValue("@cod_pro_stock", cod_pro_stock);
cmd.ExecuteNonQuery();
}
respuesta = "Producto por medida agregado correctamente.";
}
catch (Exception)
{
respuesta = "No se pudo agregar el producto por medida." + Environment.NewLine +
"Ya existe el producto seleccionado con la medida seleccionada.";
}
cn.Close();
return respuesta;
}
public string DeleteStockMedida(int cod_pro_stock)
{
string respuesta;
try
{
using (cn = Conexion.ConexionDB())
{
SqlCommand cmd = new SqlCommand("DeleteStockMedida", cn)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("@cod_pro_stock", cod_pro_stock);
cmd.ExecuteNonQuery();
}
respuesta = "Producto por medida eliminado correctamente";
}
catch (Exception ex)
{
respuesta = "Error al eliminar producto por medida: " + ex.Message;
}
return respuesta;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MVC4_DavaValidation.Attributes
{
public class CannotContainNumbersAttribute : ValidationAttribute, IClientValidatable
{
private const string _pattern = @"^((?!(?:[0-9])).)*$";
private const string DefaultErrormessage = "{0} cannot contain numbers";
public CannotContainNumbersAttribute()
{
ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? DefaultErrormessage : ErrorMessage;
}
public string Pattern
{
get { return _pattern; }
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return IsValid(value) ? null : new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
public override bool IsValid(object value)
{
if (value != null)
{
var regexValidator = new RegularExpressionAttribute(_pattern);
if (!regexValidator.IsValid(value))
{
return false;
}
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "cannotcontainnumbers",
};
yield return rule;
}
}
} |
namespace BenefitDeduction.EmployeesSalary.Employees
{
public interface ISalaryEmployeeExemptRepository: ISalaryRepository
{
}
} |
namespace EpisodeGrabber.Library {
public static class TraceVerbosity {
public const int Minimal = 1;
public const int Default = 50;
public const int Verbose = 100;
}
public static class TraceTypes {
public const string Error = "Error";
public const string Exception = "Exception";
public const string Default = "Default";
public const string WebRequest = "WebRequest";
public const string OperationStarted = "OperationStarted";
public const string OperationCompleted = "OperationCompleted";
public const string Information = "Information";
}
} |
using System.Threading.Tasks;
using Communicator.Core.Domain;
using Communicator.Infrastructure.Data;
using Communicator.Infrastructure.IRepositories;
using Microsoft.EntityFrameworkCore;
namespace Communicator.Infrastructure.Repositories
{
public class UserWorkTimeRepository : IUserWorkTimeRepository
{
private DataContext _context = new DataContext();
public async Task Add(UserWorkTime userrWorkTime)
{
await _context.UsersWorkTimes.AddAsync(userrWorkTime);
await _context.SaveChangesAsync();
}
public async Task Update(UserWorkTime userWorkTime)
{
_context.Entry(userWorkTime).State=EntityState.Modified;
await _context.SaveChangesAsync();
}
}
}
|
using System;
namespace Jypeli
{
/// <summary>
/// Sisältää tiedon ajasta, joka on kulunut pelin alusta ja viime päivityksestä.
/// </summary>
public struct Time
{
/// <summary>
/// Nolla-aika
/// </summary>
public static readonly Time Zero = new Time();
private TimeSpan _upd;
private TimeSpan _start;
/// <summary>
/// Aika joka on kulunut viime päivityksestä.
/// </summary>
public TimeSpan SinceLastUpdate
{
get { return _upd; }
}
/// <summary>
/// Aika joka on kulunut pelin alusta.
/// </summary>
public TimeSpan SinceStartOfGame
{
get { return _start; }
}
/// <summary>
/// Rakentaa ajan kahdesta TimeSpan-oliosta.
/// </summary>
/// <param name="fromUpdate">Päivityksestä kulunut aika</param>
/// <param name="fromStart">Pelin alusta kulunut aika</param>
internal Time(TimeSpan fromUpdate, TimeSpan fromStart)
{
_upd = fromUpdate;
_start = fromStart;
}
internal void Advance(double dt)
{
_upd = TimeSpan.FromSeconds(dt);
_start += _upd;
}
}
}
|
//Name: SimpleTutorial.cs
//Project: Spectral: The Silicon Domain
//Author(s) Conor Hughes - conormpkhughes@yahoo.com
//Description: Displays a tutorial box for five seconds before hiding again.
using UnityEngine;
using System.Collections;
public class TutorialDoor : MonoBehaviour {
private bool displayTutorialButton, //determines if tutorial button is visible
moveTutorial = false, //
sensorTutorial = false, //
teleportTutorial = false; //
private Transform player; //transform of player
private float playerDistance = 100; //distance between door and player
private RectTransform tutorialButtonTransform, //the tutorial button transform
canvasTransform; //the canvas transform
private Vector2 ViewportPosition, //world pos of object
WorldObject_ScreenPosition; //target pos of ui
private ScreenFade sFade; //instance of screen fade
private GameState gameState; //instance of game state
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player").transform;
canvasTransform = GameObject.Find("Canvas").GetComponent<RectTransform>();
tutorialButtonTransform = GameObject.Find("Tutorial Button").GetComponent<RectTransform>();
sFade = GameObject.Find("Screen Fade").GetComponent<ScreenFade>();
}
// Update is called once per frame
void Update () {
playerDistance = Vector3.Distance(transform.position, player.transform.position);
if(playerDistance < 3)displayTutorialButton = true;
else displayTutorialButton = false;
ScaleButton();
PositionButton();
}
//Shows/Hides the button
void ScaleButton(){
if(displayTutorialButton){
tutorialButtonTransform.localScale = Vector3.Lerp(tutorialButtonTransform.localScale, new Vector3(0.8f, 0.8f, 0.8f), Time.deltaTime * 22);
}
else{
tutorialButtonTransform.localScale = Vector3.Lerp(tutorialButtonTransform.localScale, new Vector3(0, 0, 0), Time.deltaTime * 22);
}
}
//Move the button over the door
void PositionButton(){
if(displayTutorialButton){
ViewportPosition=Camera.main.WorldToViewportPoint(transform.position);
WorldObject_ScreenPosition =new Vector2(
((ViewportPosition.x*canvasTransform.sizeDelta.x)-(canvasTransform.sizeDelta.x*0.5f)),
((ViewportPosition.y*canvasTransform.sizeDelta.y)-(canvasTransform.sizeDelta.y*0.5f)));
tutorialButtonTransform.anchoredPosition=WorldObject_ScreenPosition;
}
}
//Start the tutorial level based on next door
public void StartTutorialLevel(){
GameObject loadObject = Instantiate(Resources.Load("Basic Level Loader")) as GameObject;
if (!gameState) {
gameState = GameObject.Find("GameState").GetComponent<GameState>();
}
gameState.SaveGame ();
if(moveTutorial){
print("Loading Movement Tutorial");
loadObject.GetComponent<BasicLevelLoader>().SetNextLevel("TUTORIAL - Movement");
}
else if(moveTutorial){
print("Loading Teleport Tutorial");
loadObject.GetComponent<BasicLevelLoader>().SetNextLevel("Move Tutorial");
}
else{
print("Loading Sensor Tutorial");
loadObject.GetComponent<BasicLevelLoader>().SetNextLevel("Greenlight Screen");
}
}
}
|
using Entities.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Services.IService
{
public interface IVisitLogService:IBaseService<VisitLog>
{
/// <summary>
/// 获取首页访问记录-带分页 搜索
/// </summary>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="bedate"></param>
/// <param name="positionKey"></param>
/// <param name="totalCount"></param>
/// <returns></returns>
List<VisitLog> GetVisitLogsPage(int page, int limit, string bedate, string positionKey, out int totalCount);
}
}
|
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using Ardunity;
[CustomEditor(typeof(MPR121))]
public class MPR121Editor : ArdunityObjectEditor
{
bool foldout = false;
SerializedProperty script;
SerializedProperty id;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
id = serializedObject.FindProperty("id");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
MPR121 controller = (MPR121)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
foldout = EditorGUILayout.Foldout(foldout, "Sketch Options");
if(foldout)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(id, new GUIContent("id"));
int oldIndex = Mathf.Clamp(controller.address - 0x5A, 0, 3);
int newIndex = EditorGUILayout.Popup("Address:", oldIndex, new string[] { "0x5A", "0x5B", "0x5C", "0x5D" });
if(oldIndex != newIndex)
{
controller.address = 0x5A + newIndex;
if(!Application.isPlaying)
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
}
EditorGUI.indentLevel--;
}
controller.enableUpdate = EditorGUILayout.Toggle("Enable update", controller.enableUpdate);
for(int i=0; i<12; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(string.Format("Ch{0:d}", i), GUILayout.Width(50f));
int index = 0;
if(controller.GetElectrodeState(i))
index = 1;
GUILayout.SelectionGrid(index, new string[] {"FALSE", "TRUE"}, 2);
EditorGUILayout.EndHorizontal();
}
if(Application.isPlaying && controller.enableUpdate)
EditorUtility.SetDirty(target);
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "ARDUINO/Add Controller/Sensor/MPR121";
if(Selection.activeGameObject != null)
menu.AddItem(new GUIContent(menuName), false, func, typeof(MPR121));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
}
|
// ===============================
// AUTHOR : Guillaume Vachon Bureau
// CREATE DATE : 2018-08-29
//==================================
namespace BehaviourTree
{
abstract public class LeafTask : Task
{
public LeafTask(BlackBoard blackBoard) : base(blackBoard)
{
}
public override void ResetTask()
{
_taskStatus = TaskStatus.Sucess;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp10
{
public delegate void Message(string str);
class Game
{
public List<ICar> cars;
public int FinishDistance = 100;
public bool isfinish = false;
public Game()
{
cars = new List<ICar>() { new SportCar("Sport car", 35, 10), new Bus("Bus", 15, 7),
new Sedan("Sedan", 20, 14), new Truck("Truck", 13, 8)};
}
public void ToStart()
{
int Period = 1;
while (true)
{
Console.WriteLine("\t\t\t\t\tIn the " + Period + " Period.\n");
foreach (ICar car in cars)
{
car.ToRide(car.RandomSpeedValue());
Console.WriteLine(car.DistanceAhead());
if (car.Distance >= FinishDistance)
{
isfinish = true;
}
}
if (isfinish) { break; }
Period++;
System.Threading.Thread.Sleep(3000);
}
}
}
}
|
namespace BattleEngine.Output
{
public class MannaChangeEvent : OutputEvent
{
public int ownerId;
public double manna;
}
}
|
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using FrameworkLibraries;
using FrameworkLibraries.Utils;
using FrameworkLibraries.AppLibs.QBDT;
using FrameworkLibraries.ActionLibs.WhiteAPI;
using ScreenShotDemo;
using TestStack.BDDfy;
using TestStack.White.UIItems;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;
namespace Installer_Test.Lib
{
public class WebPatch
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
[DllImport("User32.dll")]
private static extern IntPtr GetForegroundWindow();
public static Property conf = Property.GetPropertyInstance();
public static string Sync_Timeout = conf.get("SyncTimeOut");
public static void ApplyWebPatch(string resultsPath)
{
Logger.logMessage("Application of WebPatch Started..");
ScreenCapture sc = new ScreenCapture();
System.Drawing.Image img = sc.CaptureScreen();
IntPtr pointer = GetForegroundWindow();
try
{
Actions.WaitForWindow("QuickBooks Update", 30000);
if (Actions.CheckDesktopWindowExists("QuickBooks Update"))
{
pointer = GetForegroundWindow();
sc.CaptureWindowToFile(pointer, resultsPath + "Wrong_WebPatch_Error.png", ImageFormat.Png);
Actions.ClickElementByName(Actions.GetDesktopWindow("QuickBooks Update"), "OK");
}
}
catch (Exception e)
{
Logger.logMessage("Wrong Patch" + e.ToString());
}
try
{
Actions.WaitForWindow("QuickBooks Update,Version", 60000);
if (Actions.CheckDesktopWindowExists("QuickBooks Update,Version"))
{
Window patchWin = Actions.GetDesktopWindow("QuickBooks Update,Version");
Actions.WaitForElementEnabled(patchWin, "Install Now", 60000);
Actions.ClickElementByName(patchWin, "Install Now");
Logger.logMessage("Installing webpatch");
}
}
catch (Exception e)
{
Logger.logMessage ("Patch application - Failed");
Logger.logMessage (e.Message);
Logger.logMessage ("--------------------------------------------------------------------");
}
try
{
Actions.WaitForWindow("QuickBooks Update,Version", 60000);
Window patchWin1 = Actions.GetDesktopWindow("QuickBooks Update,Version");
Window updatecomp = Actions.GetChildWindow(patchWin1, "Update complete");
pointer = GetForegroundWindow();
sc.CaptureWindowToFile(pointer, resultsPath + "Patch_Applied_Succes.png", ImageFormat.Png);
Actions.ClickElementByName(updatecomp, "OK");
Logger.logMessage("WebPatch Application - Successful");
Logger.logMessage("-----------------------------------------------------------------------");
}
catch (Exception e)
{
Logger.logMessage("WebPatch Application - Failed");
Logger.logMessage(e.Message);
Logger.logMessage("-----------------------------------------------------------------------");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileLife : MonoBehaviour
{
//Attach this script to a projectile to give it a duration before it is destroyed
public float lifeTime = 2.0f;
private float startTime;
void Start()
{
startTime = Time.time;
}
void Update()
{
if (Time.time - startTime >= lifeTime)
{
Destroy(this.gameObject);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This script controls objects going out of bounds
/// </summary>
public class BoundaryHandler : MonoBehaviour
{
public float fadeSpeed;
private void OnTriggerEnter(Collider other)
{
print(other.name);
if (other.CompareTag("Obstacle"))
{
StartCoroutine(FadeOutObj(other.gameObject));
}
}
private IEnumerator FadeOutObj(GameObject go)
{
MeshRenderer objMesh = go.GetComponent<MeshRenderer>();
if (objMesh == null)
objMesh = go.GetComponentInChildren<MeshRenderer>();
if (objMesh == null)
yield return null;
//Changes the material of the object to be able to fade
//https://answers.unity.com/questions/1004666/change-material-rendering-mode-in-runtime.html?_ga=2.8123764.771745098.1581571457-857422823.1533679413
objMesh.material.SetFloat("_Mode", 2f);
objMesh.material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
objMesh.material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
objMesh.material.SetInt("_ZWrite", 0);
objMesh.material.DisableKeyword("_ALPHATEST_ON");
objMesh.material.EnableKeyword("_ALPHABLEND_ON");
objMesh.material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
objMesh.material.renderQueue = 3000;
//Decreases material color alpha
while (objMesh.material.color.a > 0)
{
Color newColor = objMesh.material.color;
newColor.a -= fadeSpeed * Time.deltaTime;
objMesh.material.color = newColor;
yield return new WaitForEndOfFrame();
}
//Destroys obj once fully faded
Destroy(go);
yield return null;
}
}
|
using EddiConfigService;
using EddiConfigService.Configurations;
using EddiInaraService;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Timers;
using System.Windows.Controls;
namespace EddiInaraResponder
{
/// <summary> Interaction logic for ConfigurationWindow.xaml </summary>
public partial class ConfigurationWindow : INotifyPropertyChanged, INotifyDataErrorInfo
{
// Set up a timer... wait 3 seconds before reconfiguring the InaraService for any change in the API key
private const int delayMilliseconds = 3000;
private readonly Timer inputTimer = new Timer(delayMilliseconds);
public string apiKey
{
get => _apiKey;
set
{
OnPropertyChanged();
_apiKey = value;
}
}
private string _apiKey;
public ConfigurationWindow()
{
// Subscribe to events that require our attention
InaraService.invalidAPIkey += (s, e) => { OnInvalidAPIkey((InaraConfiguration)s); };
inputTimer.Elapsed += InputTimer_Elapsed;
DataContext = this;
InitializeComponent();
var inaraConfiguration = ConfigService.Instance.inaraConfiguration;
inaraApiKeyTextBox.Text = inaraConfiguration.apiKey;
}
private void InaraApiKeyChanged(object sender, TextChangedEventArgs e)
{
if (sender is TextBox textBox)
{
if (textBox.Name == "inaraApiKeyTextBox")
{
SetAPIKeyValidity(true);
inputTimer.Stop();
inputTimer.Start();
}
}
}
private void InputTimer_Elapsed(object sender, ElapsedEventArgs e)
{
inputTimer.Stop();
UpdateConfiguration();
}
private void UpdateConfiguration()
{
var inaraConfiguration = ConfigService.Instance.inaraConfiguration;
// Reset API key validity when it is edited.
inaraConfiguration.isAPIkeyValid = true;
// Update the changed API key in our configuration
inaraConfiguration.apiKey = apiKey;
// Save the updated configuration
ConfigService.Instance.inaraConfiguration = inaraConfiguration;
}
private void OnInvalidAPIkey(InaraConfiguration inaraConfiguration)
{
Dispatcher.Invoke(() =>
{
SetAPIKeyValidity(inaraConfiguration.isAPIkeyValid);
});
}
private void SetAPIKeyValidity(bool isAPIkeyValid)
{
if (isAPIkeyValid)
{
ClearErrors(nameof(apiKey));
}
else
{
ReportError(nameof(apiKey), Properties.InaraResources.invalidKeyErr);
}
inaraApiKeyTextBox.Text = apiKey; // Forces validation to update
}
// Implement INotifyDataErrorInfo for validation
public void ReportError(string propertyName, string errorMessage)
{
if (string.IsNullOrEmpty(propertyName)) { return; }
if (!Errors.ContainsKey(propertyName)) { Errors.Add(propertyName, new List<string>()); }
Errors[propertyName].Add(errorMessage);
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) || (!HasErrors)) { return null; }
if (!Errors.ContainsKey(propertyName)) { Errors.Add(propertyName, new List<string>()); }
return Errors[propertyName];
}
public void ClearErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) || (!HasErrors)) { return; }
if (Errors.ContainsKey(propertyName)) { Errors.Remove(propertyName); }
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}
private readonly Dictionary<string, List<string>> Errors = new Dictionary<string, List<string>>();
public bool HasErrors => Errors.Count > 0;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
// Implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using Coypu;
using Coypu.Drivers;
using Coypu.Drivers.Watin;
using NUnit.Framework;
namespace WebSpecs
{
[TestFixture, Ignore]
public class CoypuTests
{
private BrowserSession browser;
private SessionConfiguration sessionConfiguration;
[SetUp]
public void CreateSessionConfiguration()
{
sessionConfiguration = new SessionConfiguration
{
AppHost = "google.com"
};
}
[Test]
public void Default()
{
TestGoogleSearch();
}
[Test]
public void Firefox35()
{
sessionConfiguration.Browser = Browser.Firefox;
TestGoogleSearch();
}
[Test]
public void InernetExplorer()
{
sessionConfiguration.Browser = Browser.InternetExplorer;
TestGoogleSearch();
}
[Test, RequiresSTA]
public void InternetExplorer_with_WatiN()
{
sessionConfiguration.Driver = typeof(WatiNDriver);
sessionConfiguration.Browser = Browser.InternetExplorer;
TestGoogleSearch();
}
[Test]
public void Chrome()
{
sessionConfiguration.Browser = Browser.Chrome;
TestGoogleSearch();
}
[Test]
public void Phantomjs()
{
sessionConfiguration.Browser = Browser.PhantomJS;
TestGoogleSearch();
}
private void TestGoogleSearch()
{
browser = new BrowserSession(sessionConfiguration);
browser.Visit("/");
Assert.That(browser.Title, Is.EqualTo("Google"));
}
[TearDown]
public void DisposeBrowser()
{
browser.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace BibleBrowserUWP
{
/// <summary>
/// Hold some metadata about a search (degree of completion, current task, etc.)
/// </summary>
public class SearchProgressInfo
{
private float m_Progress;
private string m_status;
private List<SearchResult> m_Results;
private string m_Query;
private DateTime m_TimeStarted;
private DateTime m_TimeEnded;
private bool m_IsCanceled;
private int m_ResultCount;
/// <summary>
/// Constructor that initializes the new search.
/// </summary>
public SearchProgressInfo(string query)
{
m_Query = query;
m_Progress = 0f;
m_ResultCount = 0;
m_status = string.Empty;
m_Results = new List<SearchResult>();
m_TimeStarted = DateTime.Now;
m_TimeEnded = DateTime.Now;
m_IsCanceled = false;
}
/// <summary>
/// Percent of completion from 0 to 1. Updates the search time.
/// </summary>
public float Completion {
get {
return m_Progress;
}
set {
m_Progress = value;
m_TimeEnded = DateTime.Now;
}
}
/// <summary>
/// The amount of time spent searching until the search progress was marked complete.
/// </summary>
public TimeSpan SearchTime {
get {
return m_TimeEnded - m_TimeStarted;
}
}
/// <summary>
/// The search query that initialized this search.
/// </summary>
public string Query {
get {
return m_Query;
}
}
/// <summary>
/// Short description of the work currently being done.
/// </summary>
public string Status {
get {
if(m_Progress < 1f)
return m_status;
else
{
var loader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
// Show the number of results as status
if (m_ResultCount == 0)
{
return loader.GetString("noResultFor") + " " + loader.GetString("quoteLeft") + m_Query + loader.GetString("quoteRight");
}
else if (m_ResultCount == 1)
{
return loader.GetString("oneResultFor") + " " + loader.GetString("quoteLeft") + m_Query + loader.GetString("quoteRight");
}
else if(m_ResultCount >= BibleSearch.TOOMANYRESULTS)
{
return loader.GetString("tooManyResultsFor") + " " + loader.GetString("quoteLeft") + m_Query + loader.GetString("quoteRight");
}
{
return m_ResultCount + " " + loader.GetString("manyResultsFor") + " " + loader.GetString("quoteLeft") + m_Query + loader.GetString("quoteRight");
}
}
}
set {
m_status = value;
}
}
/// <summary>
/// The list of results found, updated dynamically as results are added.
/// </summary>
public List<SearchResult> Results {
get { return m_Results; }
}
/// <summary>
/// Main method to add a search result to the list of search hits.
/// </summary>
/// <param name="match">A reference that matches the search query being run.</param>
public void AddResult(SearchResult match)
{
m_Results.Add(match);
m_ResultCount++;
}
/// <summary>
/// Whether this operation has been ended by the user.
/// </summary>
public bool IsCanceled {
get { return m_IsCanceled; }
set { m_IsCanceled = value; }
}
/// <summary>
/// The number of matches that have been added to the list to date.
/// </summary>
public int ResultCount {
get { return m_ResultCount; }
}
public bool IsComplete {
get { Debug.WriteLine("Progress was::::::: " + m_Progress + (m_Progress >= 1.0f ? true : false)); return m_Progress >= 1.0f ? true : false; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Axis
{
public const string VERTICAL_AXIS = "Vertical";
public const string HORIZONTAL_AXIS = "Horizontal";
}
public class Tags
{
public const string PLAYER_TAG = "Player";
}
public class AnimationTags
{
public const string WALK_PARAMETER = "Walk";
public const string DEFEND_PARAMETER = "Defend";
public const string ATTACK_TRIGGER_1 = "Attack1";
public const string ATTACK_TRIGGER_2 = "Attack2";
internal static string MOVEMENT;
internal static string PUNCH_1_TRIGGER;
internal static string PUNCH_2_TRIGGER;
internal static string KICK_2_TRIGGER;
public static string PUNCH_3_TRIGGER { get; internal set; }
public static string KICK_1_TRIGGER { get; internal set; }
}
|
using UnitTestProject1;
namespace Autofac.Extras.FakeItEasy
{
public static class AutoFakeExtensions
{
public static T Generate<T>(this AutoFake autoFake)
{
RelaxedAutoFakeCreator.SUTType = typeof(T);
return autoFake.Resolve<T>();
}
}
}
|
namespace SubC.Attachments {
using UnityEngine;
using System.Collections.Generic;
[AddComponentMenu("")]
public class ClingyComponent : MonoBehaviour {
public struct ExecutionOrder {
static int counter;
public int executionOrder;
public int id;
public ExecutionOrder(int executionOrder) {
counter ++;
id = counter;
this.executionOrder = executionOrder;
}
}
class ExecutionOrderComparer : IComparer<ExecutionOrder> {
public int Compare(ExecutionOrder a, ExecutionOrder b) {
if (a.executionOrder == b.executionOrder)
return a.id.CompareTo(b.id);
return a.executionOrder.CompareTo(b.executionOrder);
}
}
public SortedList<ExecutionOrder, Attachment> attachments
= new SortedList<ExecutionOrder, Attachment>(new ExecutionOrderComparer());
static ClingyComponent _instance;
public static ClingyComponent instance {
get {
if (!_instance) {
GameObject go = new GameObject();
go.name = "[Clingy]";
Object.DontDestroyOnLoad(go);
_instance = go.AddComponent<ClingyComponent>();
}
return _instance;
}
}
void FixedUpdate() {
foreach (Attachment a in attachments.Values)
a.DoFixedUpdate();
}
void Update() {
foreach (Attachment a in attachments.Values)
a.DoUpdate();
}
void LateUpdate() {
foreach (Attachment a in attachments.Values)
a.DoLateUpdate();
}
public GameObject CreateGameObject() {
GameObject go = new GameObject();
go.transform.SetParent(transform);
return go;
}
}
} |
//Copyright © 2013 Dagorn Julien (julien.dagorn@gmail.com)
//This work is free. You can redistribute it and/or modify it under the
//terms of the Do What The Fuck You Want To Public License, Version 2,
//as published by Sam Hocevar. See the COPYING file for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace ActionGroupManager
{
class Highlighter
{
List<Part> internalHighlight;
public Highlighter()
{
internalHighlight = new List<Part>();
}
public void Update()
{
internalHighlight.ForEach(
(p) =>
{
p.SetHighlightColor(Color.red);
p.SetHighlight(true, true);
});
}
public void Add(Part p)
{
if (internalHighlight.Contains(p))
return;
internalHighlight.Add(p);
p.highlightColor = Color.red;
p.SetHighlight(true, true);
}
public void Add(BaseAction bA)
{
Add(bA.listParent.part);
}
public bool Contains(Part p)
{
return internalHighlight.Contains(p);
}
public void Remove(Part p)
{
if (!internalHighlight.Contains(p))
return;
internalHighlight.Remove(p);
p.SetHighlightDefault();
}
public void Remove(BaseAction bA)
{
if (!internalHighlight.Any(
(e) =>
{
return e == bA.listParent.part;
}))
{
Remove(bA.listParent.part);
}
}
public void Switch(Part p)
{
if (internalHighlight.Contains(p))
Remove(p);
else
Add(p);
}
public void Clear()
{
internalHighlight.ForEach(
(e =>
{
e.SetHighlightDefault();
}));
internalHighlight.Clear();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.