text
stringlengths
13
6.01M
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Framework.Data { partial class DbWrapperHelper { private static class DbIntercept<TProviderFactory> where TProviderFactory : DbProviderFactory { private static Func<DbProviderFactory, DbProviderFactory> providerFactoryWrapper = null; public static DbProviderFactory WrapDbProviderFactory(DbProviderFactory factory) { var wrapper = providerFactoryWrapper; if (wrapper == null) { var conn = factory.CreateConnection(); var connType = conn.GetType(); conn.Dispose(); var transType = connType.GetMethod(nameof(DbConnection.BeginTransaction), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, Type.EmptyTypes, null).ReturnType; var command = factory.CreateCommand(); var parameter = factory.CreateParameter(); var types = new[] { factory.GetType(), connType, transType, command.GetType(), parameter.GetType(), command.Parameters.GetType() }; command.Dispose(); var interceptType = typeof(DbIntercept<,,,,,>).MakeGenericType(types); //呼叫DbIntercept.InitProviderAndGetWrapper const string methodName = nameof(DbIntercept<DbProviderFactory, DbConnection, DbTransaction, DbCommand, DbParameter, DbParameterCollection>.InitProviderAndGetWrapper); wrapper = (Func<DbProviderFactory, DbProviderFactory>)interceptType.GetMethod(methodName).Invoke(null, new[] { factory }); Interlocked.Exchange(ref providerFactoryWrapper, wrapper); } return wrapper(factory); } } public static class DbIntercept<TProviderFactory, TConnection, TTransaction, TCommand, TParameter, TParameterCollection> where TProviderFactory : DbProviderFactory where TConnection : DbConnection where TTransaction : DbTransaction where TCommand : DbCommand where TParameter : DbParameter where TParameterCollection : DbParameterCollection { public static readonly Func<DbProviderFactory, WrappedProviderFactory> wrapProviderFactory; public static readonly Func<DbConnection, WrappedConnection> wrapConnection; public static readonly Func<DbTransaction, WrappedTransaction> wrapTransaction; public static readonly Func<DbCommand, WrappedCommand> wrapCommand; public static readonly Func<DbParameter, WrappedParameter> wrapParameter; public static readonly Func<DbParameterCollection, WrappedParameterCollection> wrapParameterCollection; private static WrappedProviderFactory providerFactory = null; static DbIntercept() { SetWrapper(typeof(TProviderFactory), out wrapProviderFactory); SetWrapper(typeof(TConnection), out wrapConnection); SetWrapper(typeof(TTransaction), out wrapTransaction); SetWrapper(typeof(TCommand), out wrapCommand); SetWrapper(typeof(TParameter), out wrapParameter); SetWrapper(typeof(TParameterCollection), out wrapParameterCollection); } public static Func<DbProviderFactory, WrappedProviderFactory> InitProviderAndGetWrapper(DbProviderFactory factory) { providerFactory = wrapProviderFactory(factory); return wrapProviderFactory; } #region ProviderFactoryWrapper public abstract class WrappedProviderFactory : DbProviderFactory, IWrappedDb<TProviderFactory> { public abstract TProviderFactory Instance { get; } public override DbConnection CreateConnection() => wrapConnection(Instance.CreateConnection()); public override DbCommand CreateCommand() => wrapCommand(Instance.CreateCommand()); public override DbParameter CreateParameter() => wrapParameter(Instance.CreateParameter()); } #endregion #region WrappedConnection public abstract class WrappedConnection : DbConnectionWrapper, IWrappedDb<TConnection> { public abstract TConnection Instance { get; } protected override DbProviderFactory DbProviderFactory => providerFactory; protected override DbCommand CreateDbCommand() { var command = wrapCommand(Instance.CreateCommand()); command.WrappedConn = this; return command; } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { var trans = wrapTransaction(Instance.BeginTransaction(isolationLevel)); trans.WrappedConn = this; return trans; } } #endregion #region WrappedTransaction public abstract class WrappedTransaction : DbTransaction, IWrappedDb<TTransaction> { internal WrappedConnection WrappedConn = null; public abstract TTransaction Instance { get; } protected override DbConnection DbConnection => WrappedConn; } #endregion #region WrappedCommand public abstract class WrappedCommand : DbCommand, IWrappedDb<TCommand> { internal WrappedConnection WrappedConn= null; internal WrappedTransaction WrappedTrans = null; private WrappedParameterCollection wrappedParams = null; public abstract TCommand Instance { get; } protected override DbConnection DbConnection { get => WrappedConn; set => Instance.Connection = ((WrappedConn = (WrappedConnection)value)).Instance; } protected override DbTransaction DbTransaction { get => WrappedTrans; set => Instance.Transaction = ((WrappedTrans = (WrappedTransaction)value)).Instance; } protected override DbParameterCollection DbParameterCollection => wrappedParams ?? (wrappedParams = wrapParameterCollection(Instance.Parameters)); protected override DbParameter CreateDbParameter() => wrapParameter(Instance.CreateParameter()); protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { var intercept = dbCommandIntercept; return intercept == null ? Instance.ExecuteReader(behavior) : intercept.CommandExecute(Instance, cmd => cmd.ExecuteReader(behavior)); } public override int ExecuteNonQuery() { var intercept = dbCommandIntercept; return intercept == null ? Instance.ExecuteNonQuery() : intercept.CommandExecute(Instance, cmd => cmd.ExecuteNonQuery()); } public override object ExecuteScalar() { var intercept = dbCommandIntercept; return intercept == null ? Instance.ExecuteScalar() : intercept.CommandExecute(Instance, cmd => cmd.ExecuteScalar()); } } #endregion #region WrappedParameter public abstract class WrappedParameter : DbParameter, IWrappedDb<TParameter> { public abstract TParameter Instance { get; } } #endregion #region WrappedParameterCollection public abstract class WrappedParameterCollection : DbParameterCollection, IWrappedDb<TParameterCollection> { public abstract TParameterCollection Instance { get; } private Dictionary<TParameter, WrappedParameter> mappings = new Dictionary<TParameter, WrappedParameter>(); protected override DbParameter GetParameter(int index) => mappings[(TParameter)Instance[index]]; protected override DbParameter GetParameter(string parameterName) => mappings[(TParameter)Instance[parameterName]]; protected override void SetParameter(int index, DbParameter value) { var wrap = (WrappedParameter)value; var old = (TParameter)Instance[index]; Instance[index] = wrap.Instance; mappings.Remove(old); mappings.Add(wrap.Instance, wrap); } protected override void SetParameter(string parameterName, DbParameter value) { var wrap = (WrappedParameter)value; var old = (TParameter)Instance[parameterName]; Instance[parameterName] = wrap.Instance; mappings.Remove(old); mappings.Add(wrap.Instance, wrap); } public override void CopyTo(Array array, int index) => ((ICollection)mappings.Values).CopyTo(array, index); public override int Add(object value) { var wrap = (WrappedParameter)value; mappings.Add(wrap.Instance, wrap); return Instance.Add(wrap.Instance); } public override void AddRange(Array values) { foreach (object obj in values) Add(obj); } public override void Insert(int index, object value) { var wrap = (WrappedParameter)value; mappings.Add(wrap.Instance, wrap); Instance.Insert(index, wrap.Instance); } public override void Remove(object value) { var wrap = (WrappedParameter)value; mappings.Remove(wrap.Instance); Instance.Remove(wrap.Instance); } public override void RemoveAt(int index) { var n = Instance[index]; Instance.RemoveAt(index); mappings.Remove((TParameter)n); } public override void RemoveAt(string parameterName) { var n = Instance[parameterName]; Instance.RemoveAt(parameterName); mappings.Remove((TParameter)n); } public override void Clear() { Instance.Clear(); mappings.Clear(); } public override int IndexOf(object value) => Instance.IndexOf(((WrappedParameter)value).Instance); public override bool Contains(object value) => Instance.Contains(((WrappedParameter)value).Instance); //要按照原本的順序 public override IEnumerator GetEnumerator() => Instance.OfType<TParameter>().Select(x => mappings[x]).ToList().GetEnumerator(); } #endregion } } }
using myBOOK.data; using myBOOK.data.EntityObjects; using myBOOK.data.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace myBOOK.UI { /// <summary> /// Логика взаимодействия для Profile.xaml /// </summary> public partial class Profile : Window { public Users User { get; set; } IRepository repo = Factory.Default.GetRepository(); Converter converter = new Converter(); Task<List<Books>> lst; private void TabItemSizeRegulation() { foreach (var item in tabcontrol.Items) { var i = (TabItem)item; i.Width = window.Width / tabcontrol.Items.Count - 5; } } private async void Updatebookboxes() { var converter = new Converter(); var res = converter.ConvertToBookView(repo.ChooseUserBooksOfCategory(User.Login, UserToBook.Categories.PastRead)); PastBookList.ItemsSource = res; res = converter.ConvertToBookView(repo.ChooseUserBooksOfCategory(User.Login, UserToBook.Categories.FutureRead)); FutureBookList.ItemsSource = res; res = converter.ConvertToBookView(repo.ChooseUserBooksOfCategory(User.Login, UserToBook.Categories.Favourite)); FavouriteBookList.ItemsSource = res; res = repo.ChooseUserScoresToShow(User); ScoreList.ItemsSource = res; lst = Task.Run(() => Recomendations.Show(User.Login)); LoadingInfo.Visibility = Visibility.Visible; while (!lst.IsCompleted) { await Task.Delay(1000); } res = converter.ConvertToBookView(lst.Result); RecomendationList.ItemsSource = res; LoadingInfo.Visibility = Visibility.Hidden; } public Profile(Users user) { InitializeComponent(); User = user; Updatebookboxes(); } private void window_SizeChanged(object sender, SizeChangedEventArgs e) { TabItemSizeRegulation(); } private void AddBook(UserToBook.Categories category) { var w = new AddBookToList(User); w.AddFoundBook += (b) => { if (repo.GetBookFromAddingForm(User, b, category)) { MessageBox.Show("Книга успешно добавлена"); } else { MessageBox.Show("Эта книга уже есть в вашем списке"); } }; w.Show(); w.Closing += (a,b) => Updatebookboxes(); } private void AddPastRead_Click(object sender, RoutedEventArgs e) { AddBook(UserToBook.Categories.PastRead); } private void AddFavourite_Click(object sender, RoutedEventArgs e) { AddBook(UserToBook.Categories.Favourite); } private void AddFutureRead_Click(object sender, RoutedEventArgs e) { AddBook(UserToBook.Categories.FutureRead); } private void Search_Click(object sender, RoutedEventArgs e) { var a = author.Text; var b = bookname.Text; BookList.ItemsSource = repo.SearchABook(b, a); } private void BookList_Selected(object sender, RoutedEventArgs e) { if (BookList.SelectedItem != null) { var b = (Books)BookList.SelectedItem; var lst = repo.ChooseReviewForABook(b.BookName, b.Author); ReviewList.ItemsSource = lst; } } private void MarkAsFavourite_Click(object sender, RoutedEventArgs e) { if (PastBookList.SelectedItem != null) { var b = converter.ConvertToBook((BookView)PastBookList.SelectedItem); if (repo.GetBookFromAddingForm(User, b, UserToBook.Categories.Favourite)) { Updatebookboxes(); MessageBox.Show("Книга успешно добавлена"); } else { MessageBox.Show("Эта книга уже есть в вашем списке"); } } } private void MoveToFutureBooks_Click(object sender, RoutedEventArgs e) { if (RecomendationList.SelectedItem != null) { var b = converter.ConvertToBook((BookView)RecomendationList.SelectedItem); if (repo.GetBookFromAddingForm(User, b, UserToBook.Categories.FutureRead)) { Updatebookboxes(); MessageBox.Show("Книга успешно добавлена"); } else { MessageBox.Show("Эта книга уже есть в вашем списке"); } } } private void ShowBookInfo(Books b) { var w = new BookInfo(b, User); w.Show(); w.Closing += (a, a1) => { Updatebookboxes(); }; } private void ListBox__MouseDoubleClick(object sender, MouseButtonEventArgs e) { var box = (ListBox)sender; if (box.SelectedItem != null) { var b = converter.ConvertToBook((BookView)box.SelectedItem); ShowBookInfo(b); } } private void MenuHelp_Click(object sender, RoutedEventArgs e) { Help help = new Help(); help.ShowDialog(); } private void MenuClose_Click(object sender, RoutedEventArgs e) { Close(); } private void MenuAbout_Click(object sender, RoutedEventArgs e) { About about = new About(); about.ShowDialog(); } private void MenuAuthors_Click(object sender, RoutedEventArgs e) { Authors authors = new Authors(); authors.ShowDialog(); } private void tabcontrol_SelectionChanged(object sender, SelectionChangedEventArgs e) { var t = (TabControl)sender; foreach (var item in t.Items) { ((TabItem)item).Foreground = new SolidColorBrush(Colors.White); } ((TabItem)t.SelectedItem).Foreground = new SolidColorBrush(Colors.Black); } private void DeleteButton_Click(ListBox listbox, UserToBook.Categories category) { if (listbox.SelectedItem != null) { var b = converter.ConvertToBook((BookView)listbox.SelectedItem); repo.DeleteUserToBook(User, b, category); Updatebookboxes(); } } private void DeletePastRead_Click(object sender, RoutedEventArgs e) { DeleteButton_Click(PastBookList, UserToBook.Categories.PastRead); } private void DeleteFavourite_Click(object sender, RoutedEventArgs e) { DeleteButton_Click(FavouriteBookList,UserToBook.Categories.Favourite); } private void DeleteFutureRead_Click(object sender, RoutedEventArgs e) { DeleteButton_Click(FutureBookList,UserToBook.Categories.FutureRead); } } }
namespace useSOLIDin { interface IDisplay { void DisplayMenu(); void DisplayLevelData(Levels levels, int levelNo); void DisplayLevelName(Levels levels, int levelName); void DisplayAllLevels(Levels levels); } }
using System.Collections.Generic; using System.Drawing; using C1.Win.C1FlexGrid; using C1.Win.C1SuperTooltip; namespace MPD { public static class Legend { private static Dictionary<string, Color> mLegendColors = null; public static Dictionary<string, Color> LegendColors { get { CreateLegendColors(); return mLegendColors; } } private static void CreateLegendColors() { if (mLegendColors == null) { mLegendColors = new Dictionary<string, Color>(12); mLegendColors.Add("Yellow", Color.Yellow); mLegendColors.Add("Red", Color.Red); mLegendColors.Add("Orange", Color.FromArgb(254, 158, 16)); mLegendColors.Add("Pink", Color.FromArgb(255, 153, 255)); mLegendColors.Add("Blue", Color.Blue); mLegendColors.Add("LightGreen", Color.FromArgb(135, 255, 135)); mLegendColors.Add("DarkGray", Color.FromArgb(115, 115, 115)); mLegendColors.Add("LightGray", Color.FromArgb(197, 197, 197)); mLegendColors.Add("DarkGreen", Color.FromArgb(0, 150, 0)); mLegendColors.Add("DarkYellow", Color.FromArgb(130, 130, 0)); mLegendColors.Add("LightBlue", Color.FromArgb(0, 176, 240)); mLegendColors.Add("DarkBlue", Color.FromArgb(0, 9, 117)); } } internal static void SetToolTipColor(int row, int col, C1FlexGrid grid, C1SuperTooltip toolTip) { CellStyle cs = grid.GetCellStyle(row, col); if (cs == null) return; string text = ""; switch (cs.BackColor.ToArgb()) { case 0: text = "Black"; break; case 8388608: case 15738920: case 7670016: text = "Blue"; break; case 32768: case 38400: text = "Green"; break; case 8421376: text = "Teal"; break; case 128: case 3937400: text = "Red"; break; case 8388736: text = "Purple"; break; case 32896: case 33410: text = "Brown"; break; case 12632256: case 12961221: text = "Gray"; break; case 8421504: case 7566195: text = "Dark Gray"; break; case 16711680: case 16776960: case 15773696: text = "Light Blue"; break; case 65280: case 8912775: text = "Light Green"; break; case 255: text = "Light Red"; break; case 16711935: case 16751103: case 10506480: text = "Pink"; break; case 65535: text = "Yellow"; break; case 16777215: text = "White"; break; case 3947760: case 1089278: text = "Orange"; break; } toolTip.SetToolTip(grid, text); } } }
using System; using System.Threading.Tasks; using Uintra.Core.Activity; namespace Uintra.Features.Notification.Services { public interface INotifyableService : ITypedService { void Notify(Guid entityId, Enum notificationType); Task NotifyAsync(Guid entityId, Enum notificationType); } }
using System; namespace Infrostructure.Exeption { public class InvalidAspectRatioException : Exception { public InvalidAspectRatioException(string message = "مقدار خالی وارد شده است") : base(message) { } } }
using System.Collections.Generic; using System.Linq; using TY.SPIMS.Entities; using TY.SPIMS.POCOs; namespace TY.SPIMS.Controllers.Interfaces { public interface ICustomerController { IQueryable<Customer> CreateQuery(string filter); void DeleteCustomer(int id); List<CustomerDisplayModel> FetchAllCustomers(); Customer FetchCustomerById(int id); Customer FetchCustomerByName(string customerName); TY.SPIMS.Utilities.SortableBindingList<CustomerDisplayModel> FetchCustomerWithSearch(string filter); void InsertCustomer(CustomerColumnModel model); void UpdateCustomer(CustomerColumnModel model); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Reflection; namespace CRL.Property { /// <summary> /// 属性维护,通过TYPE以区分不同用途 /// </summary> public class PropertyBusiness<TType> : BaseProvider<PropertyName> where TType : class { public static PropertyBusiness<TType> Instance { get { return new PropertyBusiness<TType>(); } } protected override DBExtend dbHelper { get { return GetDbHelper<TType>(); } } public string CreateTable() { DBExtend helper = dbHelper; PropertyName obj1 = new PropertyName(); PropertyValue obj2 = new PropertyValue(); string msg = obj1.CreateTable(helper); msg += obj2.CreateTable(helper); return msg; } public void ClearCache() { nameCache.Clear(); valueCache.Clear(); } static Dictionary<int, PropertyName> nameCache = new Dictionary<int, PropertyName>(); static Dictionary<int, PropertyValue> valueCache = new Dictionary<int, PropertyValue>(); void InItCache() { if (nameCache.Count == 0) { #region 初始缓存 DBExtend helper = dbHelper; List<PropertyName> list = helper.QueryList<PropertyName>(); foreach (PropertyName c in list) { nameCache.Add(c.Id, c); } List<PropertyValue> list2 = helper.QueryList<PropertyValue>(); foreach (PropertyValue c in list2) { valueCache.Add(c.Id, c); } #endregion } } /// <summary> /// 添加名称的值 /// </summary> /// <param name="values"></param> /// <param name="propertyId"></param> public void AddPropertyValue(List<string> values, int propertyId) { DBExtend helper = dbHelper; foreach(string s in values) { PropertyValue v = new PropertyValue(); v.PropertyId = propertyId; v.Name = s.Trim(); //helper.Params.Clear(); int id = helper.InsertFromObj(v); v.Id = id; valueCache.Add(id, v); } } /// <summary> /// 删除一个属性 /// </summary> /// <param name="propertyId"></param> public void DeleteProperty(int propertyId) { DBExtend helper = dbHelper; Delete(propertyId); helper.Delete<PropertyValue>(b => b.PropertyId == propertyId); nameCache.Remove(propertyId); } /// <summary> /// 取得名称对象 /// </summary> /// <param name="id"></param> /// <returns></returns> public PropertyName GetName(int id) { if (!nameCache.ContainsKey(id)) return null; return nameCache[id]; } /// <summary> /// 取得值对象 /// </summary> /// <param name="id"></param> /// <returns></returns> public PropertyValue GetValue(int id) { if (!valueCache.ContainsKey(id)) return null; return valueCache[id]; } /// <summary> /// 取得分类下的名称 /// </summary> /// <param name="categoryCode"></param> /// <param name="type"></param> /// <returns></returns> public List<PropertyName> GetPropertyNames(string categoryCode, PropertyType type) { InItCache(); List<PropertyName> list = new List<PropertyName>(); foreach (KeyValuePair<int, PropertyName> v in nameCache) { if (v.Value.CategoryCode == categoryCode && v.Value.Type == type) { list.Add(v.Value); } } return list.OrderByDescending(b => b.Sort).ToList(); } /// <summary> /// 根据属性ID取所有值 /// </summary> /// <param name="propertyId"></param> /// <returns></returns> public List<PropertyValue> GetPropertyValues(int propertyId) { InItCache(); List<PropertyValue> list = new List<PropertyValue>(); foreach (KeyValuePair<int, PropertyValue> v in valueCache) { if (v.Value.PropertyId == propertyId) { list.Add(v.Value); } } return list; } /// <summary> /// 键值转为STRING /// </summary> /// <param name="keyValue"></param> /// <returns></returns> public string PropertyToString(Dictionary<int,int> keyValue) { string str = ""; foreach (KeyValuePair<int, int> v in keyValue) { str += string.Format("{0}:{1}|", v.Key, v.Value); } str = str.Substring(0, str.Length - 1); return str; } /// <summary> /// 将字符串形式转为对象 /// like 1:11|2:22 /// </summary> /// <param name="propertyString"></param> /// <returns></returns> public Dictionary<PropertyName,PropertyValue> PropertyFromString(string propertyString) { Dictionary<PropertyName, PropertyValue> list = new Dictionary<PropertyName, PropertyValue>(); if (string.IsNullOrEmpty(propertyString)) return list; string[] arry = propertyString.Split('|'); foreach (string s in arry) { if (s == "") continue; string[] arry1 = s.Split(':'); if (arry1.Length < 2) continue; int nameId = Convert.ToInt32(arry1[0]); int valueId = Convert.ToInt32(arry1[1]); PropertyName name; if (nameCache.ContainsKey(nameId)) { name = nameCache[nameId]; } else { name = new PropertyName() { Id = nameId, Name = "未知" }; } PropertyValue value ; if (valueCache.ContainsKey(valueId)) { value = valueCache[valueId]; } else { value = new PropertyValue() { Id = valueId, Name = "未知", PropertyId = nameId }; } list.Add(name,value); } return list; } #region 规格 /// <summary> /// 返回分组的形式,规格选择 /// </summary> /// <param name="skus"></param> /// <param name="styles"></param> /// <returns></returns> public List<TypeItem> GetStylesByGroup(List<SKUItem> skus, out List<StyleItem> styles) { //按规格种类列表 List<TypeItem> items = new List<TypeItem>(); styles = new List<StyleItem>(); TypeItem item; Dictionary<int, List<TypeValue>> all = new Dictionary<int, List<TypeValue>>(); foreach (SKUItem skuItem in skus) { string sku = skuItem.SKU; int innerStyleId = skuItem.StyleId; if (string.IsNullOrEmpty(sku)) { continue; } string[] arry = sku.Split('|'); foreach (string s in arry) { string[] a = s.Split(':'); int typeId = int.Parse(a[0]); int valueId = int.Parse(a[1]); if (!all.ContainsKey(typeId)) { all.Add(typeId, new List<TypeValue>()); } bool exists = false; foreach (TypeValue a1 in all[typeId]) { if (a1.Code == typeId + ":" + valueId) { exists = true; break; } } if (!exists) { TypeValue v = new TypeValue(typeId, valueId, valueCache[valueId].Name); all[typeId].Insert(0, v); } } int stock = skuItem.Num; styles.Insert(0, new StyleItem() { StyleId = innerStyleId, Code = sku, Num = stock }); } foreach (KeyValuePair<int, List<TypeValue>> entry in all) { item = new TypeItem(); item.Name = nameCache[entry.Key].Name; item.Id = entry.Key; item.Values = entry.Value; items.Add(item); } return items; } #region object /// <summary> /// 原始SKU信息 /// </summary> public class SKUItem { public int StyleId; /// <summary> /// sku串 1:11|2:22 /// </summary> public string SKU; /// <summary> /// 数量 /// </summary> public int Num; } /// <summary> /// 种类规格对应的值 /// </summary> public class TypeValue { public TypeValue() { } public TypeValue(int typeId, int vId, string vName) { Id = vId; Name = vName; Code = typeId + ":" + vId; } public int Id { get; set; } public string Name { get; set; } /// <summary> /// 当前编码 /// </summary> public string Code { get; set; } } /// <summary> /// 每个规格 /// </summary> public class StyleItem { public int StyleId { get; set; } /// <summary> /// 样式唯一编码 /// </summary> public string Code { get; set; } /// <summary> /// 库存 /// </summary> public int Num { get; set; } } /// <summary> /// 每个规格种类对应的可选项 /// 颜色:红,黄,蓝 /// </summary> public class TypeItem { public int Id { get; set; } /// <summary> /// 种类名称 /// </summary> public string Name { get; set; } /// <summary> /// 值集合 /// </summary> public List<TypeValue> Values; } #endregion #endregion } }
using PatronPrototipo; using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //creamos el admininstrador CAdministrarClones admin = new CAdministrarClones(); //creamos dos instancias . no se usa palabra new por que el objeto ya existe en el catalogo de prototipo CPersona uno = (CPersona)admin.obtenerClones("persona"); CPersona dos = (CPersona)admin.obtenerClones("persona"); //se verifica que realmente es el mmismo objetos clonado Console.WriteLine(uno); Console.WriteLine(dos); Console.WriteLine("---------------"); //aqui modificamos y personalizamos cada objeto. cada uno tiene propiedades independientes uno.Nombre = "edith"; uno.Edad = 32; dos.Nombre = "oriana"; dos.Edad = 12; Console.WriteLine(uno); Console.WriteLine(dos); Console.WriteLine("---------------"); //creamos un objeto mas dificil de crear CAutomovil auto = new CAutomovil("Nissan", 250000); //lo agregamos al catalogo admin.adicionarClones("Auto", auto); //obtenemos unn prototipo de ese nissan CAutomovil auto2 = (CAutomovil)admin.obtenerClones("Auto"); auto2.Modelo = "honda"; //verificamos que cada una tenga su estado. Console.WriteLine(auto); Console.WriteLine(auto2); Console.WriteLine("-----------------"); //este es un constructos costoso de clonar. donde conviene modificar su uso CPrecio valor = (CPrecio)admin.obtenerClones("valores"); Console.WriteLine(valor); } } }
using System; namespace ADP.BusinessLogic.Entity { public class Project { public string Id { get; set; } public string Nama { get; set; } public string Kota { get; set; } public string Alamat { get; set; } public DateTime StartDate { get; set; } public string strStartDate { get { return StartDate.ToString("dd/MM/yyyy"); } } public string NoKontrak { get; set; } public string NoSpk { get; set; } public string TelpSpk { get; set; } } public class ProjectCustomer { public string Id { get; set; } public string Nama { get; set; } public string Alamat { get; set; } public string Kota { get; set; } public string Telp { get; set; } public string Email { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Text; using Game.Entity.Treasure; using Game.Facade; using Game.Utils; using System.Data; using System.Data.SqlClient; namespace Game.Web.WS { public class ScoreRank { public int RankId; public int UserID; public string UserName; public int SumScore; public int RankType; public int FaceId; } /// <summary> /// Summary description for $codebehindclassname$ /// </summary> [WebService( Namespace = "http://tempuri.org/" )] [WebServiceBinding( ConformsTo = WsiProfiles.BasicProfile1_1 )] public class PhoneRank : IHttpHandler { public class ScoreRankCode : RetureCode { public List<ScoreRank> ScoreRanks = new List<ScoreRank>(); public ScoreRank MyScore = new ScoreRank(); } public void ProcessRequest( HttpContext context ) { context.Response.ContentType = "text/plain"; string action = GameRequest.GetQueryString( "action" ); switch( action ) { case "getscorerank": GetScoreRank(context); break; case "getscoreWeekrank": GetWeekScoreRank(context); break; case "getscorePreDayrank": GetPreDayScoreRank(context); break; case "getscorTodayhrank": GetTodayScoreRank(context); break; default: break; } } void SendRank(DataSet ds, int userID, HttpContext context, DateTime start, DateTime end) { ScoreRankCode newScoreRankCode = new ScoreRankCode(); string xx ="start:"+start.ToString()+" end:"+end.ToString()+ " Count:" + ds.Tables[0].Rows.Count+" "; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { ScoreRank newScoreRank = new ScoreRank(); newScoreRank.RankId = Convert.ToInt32(ds.Tables[0].Rows[i]["RankId"]); newScoreRank.UserID = Convert.ToInt32(ds.Tables[0].Rows[i]["UserID"]); newScoreRank.UserName = ds.Tables[0].Rows[i]["UserName"].ToString(); newScoreRank.SumScore = Convert.ToInt32(ds.Tables[0].Rows[i]["SumScore"]); newScoreRank.RankType = Convert.ToInt32(ds.Tables[0].Rows[i]["RankType"]); System.Object obj = ds.Tables[0].Rows[i]["FaceID"]; if (obj.GetType() != typeof(DBNull)) newScoreRank.FaceId = Convert.ToInt32(obj); newScoreRank.RankId = i+1; newScoreRankCode.ScoreRanks.Add(newScoreRank); if (newScoreRank.UserID == userID) newScoreRankCode.MyScore = newScoreRank; xx = "RankId:" + ds.Tables[0].Rows[i]["RankId"] + " UserID:" + ds.Tables[0].Rows[i]["UserID"] + " UserName:" + ds.Tables[0].Rows[i]["UserName"] + " SumScore:" + ds.Tables[0].Rows[i]["SumScore"] + " RankType:" + ds.Tables[0].Rows[i]["RankType"] + " FaceID:" + ds.Tables[0].Rows[i]["FaceID"]; } newScoreRankCode.msg = xx; CommonTools.SendStringToClient(context, newScoreRankCode); } protected void GetWeekScoreRank(HttpContext context) { try { int userID = GameRequest.GetInt("UserID", 0); DateTime dt = DateTime.Now; //当前时间 DateTime startWeek = dt.AddDays(1 -(int)dt.DayOfWeek); //本周周一 DateTime endWeek = startWeek.AddDays(6); //本周周日 DataSet ds = FacadeManage.aideTreasureFacade.GetRank(startWeek, endWeek, userID); // SendRank(ds, userID, context, startWeek, endWeek); } catch(Exception exp) { ScoreRankCode newScoreRankCode = new ScoreRankCode(); CommonTools.SendStringToClient(context, newScoreRankCode); // context.Response.Write(exp.Message.ToString()+":"+exp.StackTrace.ToString()); } } protected void GetTodayScoreRank(HttpContext context) { try { int userID = GameRequest.GetInt("UserID", 0); DateTime dt = DateTime.Now; //当前时间 DateTime startMonth = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0); DateTime endMonth = startMonth.AddMonths(1).AddDays(-1); //本月月末 DataSet ds = FacadeManage.aideTreasureFacade.GetRank(startMonth, endMonth, userID); SendRank(ds, userID, context, startMonth, endMonth); // // ScoreRankCode newScoreRankCode = new ScoreRankCode(); // for (int i = 0; i < ds.Tables[0].Rows.Count; i++) // { // ScoreRank newScoreRank = new ScoreRank(); // newScoreRank.RankId = Convert.ToInt32(ds.Tables[0].Rows[i]["RankId"]); // newScoreRank.UserID = Convert.ToInt32(ds.Tables[0].Rows[i]["UserID"]); // newScoreRank.UserName = ds.Tables[0].Rows[i]["UserName"].ToString(); // newScoreRank.SumScore = Convert.ToInt32(ds.Tables[0].Rows[i]["SumScore"]); // newScoreRank.RankType = Convert.ToInt32(ds.Tables[0].Rows[i]["RankType"]); // newScoreRank.FaceId = Convert.ToInt32(ds.Tables[0].Rows[i]["FaceID"].ToString()); // // newScoreRankCode.ScoreRanks.Add(newScoreRank); // if (newScoreRank.UserID == userID) // newScoreRankCode.MyScore = newScoreRank; // } // string s = Newtonsoft.Json.JsonConvert.SerializeObject(newScoreRankCode); // newScoreRankCode.msg = startMonth.ToString() + "--" + endMonth.ToString(); // CommonTools.SendStringToClient(context, newScoreRankCode); } catch(Exception exp) { ScoreRankCode newScoreRankCode = new ScoreRankCode(); CommonTools.SendStringToClient(context, newScoreRankCode); // context.Response.Write(exp.Message.ToString()+":"+exp.StackTrace.ToString()); } } protected void GetPreDayScoreRank(HttpContext context) { try { int userID = GameRequest.GetInt("UserID", 0); DateTime dt = DateTime.Now.AddDays(-1); DateTime startYear = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0); //本年年初 DateTime endYear = new DateTime(dt.Year, 12, 31); //本年年末 DataSet ds = FacadeManage.aideTreasureFacade.GetRank(startYear, endYear, userID); SendRank(ds, userID, context, startYear, endYear); // // // ScoreRankCode newScoreRankCode = new ScoreRankCode(); // for (int i = 0; i < ds.Tables[0].Rows.Count; i++) // { // ScoreRank newScoreRank = new ScoreRank(); // newScoreRank.RankId = Convert.ToInt32(ds.Tables[0].Rows[i]["RankId"]); // newScoreRank.UserID = Convert.ToInt32(ds.Tables[0].Rows[i]["UserID"]); // newScoreRank.UserName = ds.Tables[0].Rows[i]["UserName"].ToString(); // newScoreRank.SumScore = Convert.ToInt32(ds.Tables[0].Rows[i]["SumScore"]); // newScoreRank.RankType = Convert.ToInt32(ds.Tables[0].Rows[i]["RankType"]); // newScoreRank.FaceId = Convert.ToInt32(ds.Tables[0].Rows[i]["FaceID"]); // // newScoreRankCode.ScoreRanks.Add(newScoreRank); // if (newScoreRank.UserID == userID) // newScoreRankCode.MyScore = newScoreRank; // } // string s = Newtonsoft.Json.JsonConvert.SerializeObject(newScoreRankCode); // newScoreRankCode.msg = startYear.ToString() + "--" + endYear.ToString(); // CommonTools.SendStringToClient(context, newScoreRankCode); } catch (Exception exp) { ScoreRankCode newScoreRankCode = new ScoreRankCode(); CommonTools.SendStringToClient(context, newScoreRankCode); // context.Response.Write(exp.Message.ToString() + ":" + exp.StackTrace.ToString()); } } /// <summary> /// 获取金币排行榜,前50 /// </summary> /// <param name="context"></param> protected void GetScoreRank( HttpContext context ) { StringBuilder msg = new StringBuilder( ); int pageIndex = GameRequest.GetInt( "pageindex" , 1 ); int pageSize = GameRequest.GetInt( "pagesize" , 10 ); int userID = GameRequest.GetInt("UserID", 0); if( pageIndex <= 0 ) { pageIndex = 1; } if( pageSize <= 0 ) { pageSize = 10; } if( pageSize > 50 ) { pageSize = 50; } //获取用户排行 string sqlQuery = string.Format("SELECT a.*,b.FaceID,b.Experience,b.MemberOrder,b.GameID,b.UserMedal,b.UnderWrite FROM (SELECT ROW_NUMBER() OVER (ORDER BY Score DESC) as ChartID,UserID,Score FROM GameScoreInfo) a,RYAccountsDB.dbo.AccountsInfo b WHERE a.UserID=b.UserID AND a.UserID={0}", userID); DataSet dsUser = FacadeManage.aideTreasureFacade.GetDataSetByWhere( sqlQuery ); int uChart = 0; Int64 uScore = 0; int uFaceID = 0; int uExperience = 0; int memberOrder = 0; int gameID = 0; int userMedal = 0; string underWrite = ""; Int64 score = 0; decimal currency = 0; if (dsUser.Tables[0].Rows.Count != 0) { uChart = Convert.ToInt32(dsUser.Tables[0].Rows[0]["ChartID"]); uScore = Convert.ToInt64(dsUser.Tables[0].Rows[0]["Score"]); uFaceID = Convert.ToInt32(dsUser.Tables[0].Rows[0]["FaceID"]); uExperience = Convert.ToInt32(dsUser.Tables[0].Rows[0]["Experience"]); memberOrder = Convert.ToInt32(dsUser.Tables[0].Rows[0]["MemberOrder"]); gameID = Convert.ToInt32(dsUser.Tables[0].Rows[0]["GameID"]); userMedal = Convert.ToInt32(dsUser.Tables[0].Rows[0]["UserMedal"]); underWrite = dsUser.Tables[0].Rows[0]["UnderWrite"].ToString(); score = GetUserScore(Convert.ToInt32(dsUser.Tables[0].Rows[0]["UserID"])); currency = GetUserCurrency(Convert.ToInt32(dsUser.Tables[0].Rows[0]["UserID"])); } //获取总排行 DataSet ds = FacadeManage.aideTreasureFacade.GetList( "GameScoreInfo", pageIndex, pageSize, " ORDER BY Score DESC", " ", "UserID,Score" ).PageSet; if( ds.Tables[ 0 ].Rows.Count > 0 ) { msg.Append( "[" ); //添加用户排行 msg.Append("{\"NickName\":\"" + Fetch.GetNickNameByUserID(userID) + "\",\"Score\":" + uScore + ",\"UserID\":" + userID + ",\"Rank\":" + uChart + ",\"FaceID\":" + uFaceID + ",\"Experience\":" + Fetch.GetGradeConfig(uExperience) + ",\"MemberOrder\":" + memberOrder + ",\"GameID\":" + gameID + ",\"UserMedal\":" + userMedal + ",\"szSign\":\"" + underWrite + "\",\"Score\":" + score + ",\"Currency\":" + currency + "},"); foreach( DataRow dr in ds.Tables[ 0 ].Rows ) { msg.Append("{\"NickName\":\"" + Fetch.GetNickNameByUserID(Convert.ToInt32(dr["UserID"])) + "\",\"Score\":" + dr["Score"] + ",\"UserID\":" + dr["UserID"] + ",\"FaceID\":" + Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).FaceID + ",\"Experience\":" + Fetch.GetGradeConfig(Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).Experience) + ",\"MemberOrder\":" + Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).MemberOrder + ",\"GameID\":" + Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).GameID + ",\"UserMedal\":" + Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).UserMedal + ",\"szSign\":\"" + Fetch.GetUserGlobalInfo(Convert.ToInt32(dr["UserID"])).UnderWrite + "\",\"Score\":" + GetUserScore(Convert.ToInt32(dr["UserID"])) + ",\"Currency\":" + GetUserCurrency(Convert.ToInt32(dr["UserID"])) + "},"); } msg.Remove( msg.Length - 1 , 1 ); msg.Append( "]" ); } else { msg.Append( "{}" ); } context.Response.Write( msg.ToString( ) ); } /// <summary> /// 获取用户金币 /// </summary> /// <param name="userID"></param> /// <returns></returns> public Int64 GetUserScore(int userID) { GameScoreInfo model = FacadeManage.aideTreasureFacade.GetTreasureInfo2(userID); if (model != null) { return model.Score; } return 0; } /// <summary> /// 获取用户游戏豆 /// </summary> /// <param name="userID"></param> /// <returns></returns> public decimal GetUserCurrency(int userID) { UserCurrencyInfo model = FacadeManage.aideTreasureFacade.GetUserCurrencyInfo(userID); if (model != null) { return model.Currency; } return 0; } public bool IsReusable { get { return false; } } } }
using SearchEnginePositionFinder.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Net; using System.Threading.Tasks; namespace SearchEnginePositionFinderTest.Models { [TestClass] public class SearchEngineReaderTest { TestHelper TestHelp = new TestHelper(); [TestMethod] public void SendCommandToSearchEngine_SearchResultsIsReturned() { bool resultReturned = false; SearchEngineReader searchEngineReader = new SearchEngineReader(TestHelp.SearchSite, TestHelp.SearchEngine); string result = searchEngineReader.GetSearchEngineResults(); if (!String.IsNullOrEmpty(result)) { resultReturned = true; } Assert.AreEqual(true, resultReturned); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace KartObjects { public class ConsReportTable : Entity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Консолидированный отчет"; } } public long IdReport { get; set; } public double ValueReport { get; set; } public long Status { get; set; } public DateTime DateReport { get; set; } public long IdClient { get; set; } [DisplayName("Среднее значение")] public bool Mean { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.UIElements; public class YouDiedScript : MonoBehaviour { public GameObject LButton; public GameObject RButton; public void SetActiveAllButtons() { LButton.SetActive(true); RButton.SetActive(true); } }
using System; using System.Collections.Generic; namespace tyrone_sortingbasics { class Program { static void Main(string[] args) { List<Student> students = Student.getTestStudents(); Console.WriteLine(Student.SortTitle("Not Sorted")); Console.WriteLine(Student.ColumnHeader()); foreach (Student student in students) { Console.WriteLine(student); } Console.WriteLine(Student.SortTitle("Sorted by Last Name and First Name Using Built in IComparable")); Console.WriteLine(Student.ColumnHeader()); students.Sort(); foreach (Student s in students) { Console.WriteLine(s); } Console.WriteLine(Student.SortTitle("Sorted by Course Grade, Last Name, and then First Name Using IComparer")); Console.WriteLine(Student.ColumnHeader()); students.Sort(new StuSortCourseGradeLastFirst()); foreach (Student s in students) { Console.WriteLine(s); } Console.WriteLine(Student.SortTitle("Sorted by Last Name, First Name and then CourseID Using IComparer")); Console.WriteLine(Student.ColumnHeader()); students.Sort(new StuSortLastFirstCourseID()); foreach (Student s in students) { Console.WriteLine(s); } Console.WriteLine(Student.SortTitle("Sorted by Last Name, First Name and then CourseID and then CourseGrade Using IComparer")); Console.WriteLine(Student.ColumnHeader()); students.Sort(new StuSortLastFirstCourseIDCourseGrade()); foreach (Student s in students) { Console.WriteLine(s); } Console.WriteLine("\nPress <ENTER> to quit..."); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kuromori.DataStructure { public class Events { /// <summary> /// The array of all events ( number of which can be changed in the example2 php file /// (switch LIMIT 4 to limit number you want to be used by the app) /// </summary> public Event[] EventSet; public List<Event> getList() { return EventSet.ToList(); } } }
using System; using System.Threading.Tasks; using Entities; using Shared; using System.Collections.Generic; namespace Models { public interface IUserRepository { Task<UserReadDTO> ReadAsync(string name); Task<string> ReadPWHash(string name); Task<UserReadDTO> ReadAsync(int id); Task<List<UserReadDTO>> ReadAllAsync(); Task<int> CreateAsync(UserCreateDTO user); Task<int> DeleteAsync(int id); Task<int> FollowAsync(string follower, string followed); Task<int> UnfollowAsync(string follower, string followed); string HashPassword(string password); } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Xamarin.Forms; using Wonderland.FirebaseAPI; namespace Wonderland { public class shoppingItem { public string title { get; set; } public string fbID { get; set; } } public partial class FourthPage : ContentPage { List<shoppingItem> shopping = new List<shoppingItem>(); public FourthPage() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); loadData(); shoppingList.ItemSelected += clickedRow; } void clickedRow(object sender, SelectedItemChangedEventArgs e) { shoppingItem selectedItem = e.SelectedItem as shoppingItem; FirebasePage.doDelete("Xamarin/Shopping/itemName/" + selectedItem.fbID); shopping.Remove(selectedItem); shoppingList.ItemsSource = null; shoppingList.ItemsSource = shopping; } async void loadData() { try { JObject data = await FirebasePage.doGet("Xamarin/Shopping"); titleLabel.Text = (string)data["listName"]; } catch (Exception err) { } JObject data2 = await FirebasePage.doGet("Xamarin/Shopping/itemName"); System.Diagnostics.Debug.WriteLine(data2); shopping = new List<shoppingItem>(); foreach (var item in data2) { System.Diagnostics.Debug.WriteLine("KEY" + item.Key); System.Diagnostics.Debug.WriteLine("VALUE" + item.Value); var itemData = item.Value as JObject; System.Diagnostics.Debug.WriteLine((string)itemData["items"]); shopping.Add(new shoppingItem() { fbID = item.Key, title = (string)itemData["items"] }); } shoppingList.ItemsSource = null; shoppingList.ItemsSource = shopping; } void createList_Clicked(object sender, System.EventArgs e) { var postData = new Dictionary<string, string>(); postData.Add("listName", listNameEntry.Text); FirebasePage.doPut(postData, "Xamarin/Shopping"); } async void addGroceries_Clicked(object sender, EventArgs e) { var postData = new Dictionary<string, string>(); postData.Add("items", addTitleEntry.Text); await FirebasePage.doPost(postData, "Xamarin/Shopping/itemName"); loadData(); addTitleEntry.Text = ""; } } }
using System; using System.Collections; using System.Collections.Generic; using Quark.Utilities; namespace Quark { /// TODO: let items carry other items in form of a bag public class ItemCollection : Item, IEnumerable<Item>, IDisposable, IBag, IBagRecursive { private Dictionary<string, Item> _items; private int _maxSize = 0; /// <summary> /// Initialize a new item container /// </summary> public ItemCollection(Character carrier = null, int size = 0) { _maxSize = size; Carrier = carrier; _items = new Dictionary<string, Item>(); } ~ItemCollection() { Dispose(); } public IList<Item> Items() { return new List<Item>(_items.Values); } public void Dispose() { Carrier = null; _items.Clear(); _items = null; } public bool AddItem(Item item) { return false; /* if (!CanAdd()) return false; item.SetCarrier(Carrier); if (!item.CanGrab()) return false; if (Has(item)) { Item existing = GetItem(item); existing.CurrentStacks++; existing.CurrentStacks = Math.Min(existing.CurrentStacks, existing.MaxStacks); existing.OnStack(); return true; } _items.Add(item.Identifier, item); item.OnGrab(); return true; */ } public bool HasItem(Item item) { if (_items.ContainsKey(MakeID(item, Carrier))) return true; foreach (Item search in _items.Values) { if (!(search is ItemCollection)) continue; ItemCollection bag = (ItemCollection)search; if (bag.Has(item)) return true; } return false; } public Item GetItem(Item item) { if (!HasItem(item)) return null; return _items[MakeID(item, Carrier)]; } public bool RemoveItem(Item item) { return _items.Remove(MakeID(item, Carrier)); } public int Size { get { return _maxSize; } } public int Empty { get { return _maxSize - _items.Count; } } /// <summary> /// Add a new item to this container /// </summary> /// <param name="item">The item to be added</param> public void Add(Item item) { AddItem(item); } public bool Remove(Item item) { return RemoveItem(item); } public bool Has(Item item) { return HasItem(item); } public bool Equipped(Item item) { return _items.ContainsKey(MakeID(item, Carrier)); } public bool CanAdd() { return _maxSize == 0 || _items.Count < _maxSize; } public IEnumerator<Item> GetEnumerator() { return _items.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public int SizeRecursive { get { int size = _maxSize; foreach (KeyValuePair<string, Item> item in _items) { if (item.Value is IBag) size += ((IBag) item.Value).Size; if (item.Value is IBagRecursive) size += ((IBagRecursive) item.Value).SizeRecursive; } return size; } } public int EmptyRecursive { get { int empty = Empty; foreach (KeyValuePair<string, Item> item in _items) { if (item.Value is IBag) empty += ((IBag)item.Value).Empty; if (item.Value is IBagRecursive) empty += ((IBagRecursive)item.Value).EmptyRecursive; } return empty; } } public bool HasItemRecursive(Item item) { if (HasItem(item)) return true; foreach (KeyValuePair<string, Item> i in _items) { if (i.Value is IBag) if (((IBag) i.Value).HasItem(item)) return true; if (i.Value is IBagRecursive) if (((IBagRecursive) i.Value).HasItemRecursive(item)) return true; } return false; } public bool AddItemRecursive(Item item) { if (AddItem(item)) return true; foreach (KeyValuePair<string, Item> bag in _items) { if (bag.Value is IBag) if (((IBag) bag.Value).AddItem(item)) return true; if (bag.Value is IBagRecursive) if (((IBagRecursive) bag.Value).AddItemRecursive(item)) return true; } return false; } public Item GetItemRecursive(Item item) { Item i; if ((i = GetItem(item)) != null) return i; foreach (KeyValuePair<string, Item> bag in _items) { if (bag.Value is IBag) if ((i = ((IBag)bag.Value).GetItem(item)) != null) return i; if (bag.Value is IBagRecursive) if ((i = ((IBagRecursive)bag.Value).GetItemRecursive(item)) != null) return i; } return null; } public bool RemoveItemRecursive(Item item) { if (RemoveItem(item)) return true; foreach (KeyValuePair<string, Item> bag in _items) { if (bag.Value is IBag) if (((IBag)bag.Value).RemoveItem(item)) return true; if (bag.Value is IBagRecursive) if (((IBagRecursive)bag.Value).RemoveItem(item)) return true; } return false; } public void SetCarrierRecursive(Character carrier) { SetCarrier(carrier); foreach (KeyValuePair<string, Item> bag in _items) { if (bag.Value is IBag) ((IBag)bag.Value).SetCarrier(carrier); if (bag.Value is IBagRecursive) ((IBagRecursive)bag.Value).SetCarrierRecursive(carrier); } } } }
using System; class IsoscelesTriangle { static void Main() { Console.OutputEncoding = System.Text.Encoding.UTF8; char lcFirstVar = '\u00A9'; Console.WriteLine(" {0} ",lcFirstVar); Console.WriteLine(" {0} {1} ",lcFirstVar,lcFirstVar); Console.WriteLine(" {0} {1} ",lcFirstVar,lcFirstVar); Console.WriteLine("{0} {1} {2} {3}",lcFirstVar,lcFirstVar,lcFirstVar,lcFirstVar); Console.WriteLine(new string('-', 15)); int liLines = 4; string lsFirstLine = new string(' ', liLines - 1) + lcFirstVar; Console.WriteLine(lsFirstLine); for (int i = 2, left = liLines - 2, right = 1; i < liLines * 2; i++) { if (i < liLines) { Console.WriteLine(new string(' ', left) + lcFirstVar + new string(' ', right) + lcFirstVar); right += 2; left--; } else { Console.Write(lcFirstVar + " "); } } Console.WriteLine(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PacStudentController : MonoBehaviour { private char lastInput = '.'; private char currentInput = '.'; public Tweener tweener; private float duration = 0.5f; public AudioSource footstepSource; public AudioSource wallSource; public AudioSource pelletSource; public AudioSource deathSource; private bool playing = false; public Animator animator; private bool pause = true; public AudioSource musicSource; public AudioClip defaultMusic; public AudioClip scaredMusic; public AudioClip oneDownMusic; public SaveGameManager saveManager; public GameMenu gameMenu; public bool powerPellet { get; set; } private bool dead = false; public bool ghostKill = false; public GameObject cherry; public static float time = 0; public static int score { get; set; } private Text scoreTxt; private Text gameOverTxt; private Text startTimerTxt; private GameObject scaredTimer; private Text scaredTimerTxt; private Text timeTxt; public int[,] levelMap = { {1,2,2,2,2,2,2,2,2,2,2,2,2,7,7,2,2,2,2,2,2,2,2,2,2,2,2,1}, {2,5,5,5,5,5,5,5,5,5,5,5,5,4,4,5,5,5,5,5,5,5,5,5,5,5,5,2}, {2,5,3,4,4,3,5,3,4,4,4,3,5,4,4,5,3,4,4,4,3,5,3,4,4,3,5,2}, {2,6,4,0,0,4,5,4,0,0,0,4,5,4,4,5,4,0,0,0,4,5,4,0,0,4,6,2}, {2,5,3,4,4,3,5,3,4,4,4,3,5,3,3,5,3,4,4,4,3,5,3,4,4,3,5,2}, {2,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,2}, {2,5,3,4,4,3,5,3,3,5,3,4,4,4,4,4,4,3,5,3,3,5,3,4,4,3,5,2}, {2,5,3,4,4,3,5,4,4,5,3,4,4,3,3,4,4,3,5,4,4,5,3,4,4,3,5,2}, {2,5,5,5,5,5,5,4,4,5,5,5,5,4,4,5,5,5,5,4,4,5,5,5,5,5,5,2}, {1,2,2,2,2,1,5,4,3,4,4,3,0,4,4,0,3,4,4,3,4,5,1,2,2,2,2,1}, {0,0,0,0,0,2,5,4,3,4,4,3,0,3,3,0,3,4,4,3,4,5,2,0,0,0,0,0}, {0,0,0,0,0,2,5,4,4,0,0,0,0,0,0,0,0,0,0,4,4,5,2,0,0,0,0,0}, {0,0,0,0,0,2,5,4,4,0,3,4,4,0,0,4,4,3,0,4,4,5,2,0,0,0,0,0}, {2,2,2,2,2,1,5,3,3,0,4,0,0,0,0,0,0,4,0,3,3,5,1,2,2,2,2,2}, {0,0,0,0,0,0,5,0,0,0,4,0,0,0,0,0,0,4,0,0,0,5,0,0,0,0,0,0}, {2,2,2,2,2,1,5,3,3,0,4,0,0,0,0,0,0,4,0,3,3,5,1,2,2,2,2,2}, {0,0,0,0,0,2,5,4,4,0,3,4,4,0,0,4,4,3,0,4,4,5,2,0,0,0,0,0}, {0,0,0,0,0,2,5,4,4,0,0,0,0,0,0,0,0,0,0,4,4,5,2,0,0,0,0,0}, {0,0,0,0,0,2,5,4,3,4,4,3,0,3,3,0,3,4,4,3,4,5,2,0,0,0,0,0}, {1,2,2,2,2,1,5,4,3,4,4,3,0,4,4,0,3,4,4,3,4,5,1,2,2,2,2,1}, {2,5,5,5,5,5,5,4,4,5,5,5,5,4,4,5,5,5,5,4,4,5,5,5,5,5,5,2}, {2,5,3,4,4,3,5,4,4,5,3,4,4,3,3,4,4,3,5,4,4,5,3,4,4,3,5,2}, {2,5,3,4,4,3,5,3,3,5,3,4,4,4,4,4,4,3,5,3,3,5,3,4,4,3,5,2}, {2,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,2}, {2,5,3,4,4,3,5,3,4,4,4,3,5,3,3,5,3,4,4,4,3,5,3,4,4,3,5,2}, {2,6,4,0,0,4,5,4,0,0,0,4,5,4,4,5,4,0,0,0,4,5,4,0,0,4,6,2}, {2,5,3,4,4,3,5,3,4,4,4,3,5,4,4,5,3,4,4,4,3,5,3,4,4,3,5,2}, {2,5,5,5,5,5,5,5,5,5,5,5,5,4,4,5,5,5,5,5,5,5,5,5,5,5,5,2}, {1,2,2,2,2,2,2,2,2,2,2,2,2,7,7,2,2,2,2,2,2,2,2,2,2,2,2,1}, }; private int[] position; // Start is called before the first frame update void Start() { powerPellet = false; saveManager = GameObject.Find("Managers").GetComponent<SaveGameManager>(); gameMenu = GameObject.Find("Managers").GetComponent<GameMenu>(); position = new int[] { 1, 1 }; scoreTxt = GameObject.Find("ScoreNum").GetComponent<Text>(); gameOverTxt = GameObject.Find("Game Over").GetComponent<Text>(); startTimerTxt = GameObject.Find("StartTimer").GetComponent<Text>(); scaredTimer = GameObject.Find("ScaredTimer"); timeTxt = GameObject.Find("Timer").GetComponent<Text>(); scaredTimerTxt = GameObject.Find("TimerScared").GetComponent<Text>(); scaredTimer.SetActive(false); animator.speed = 0; score = 0; cherry = GameObject.Find("Cherry"); cherry.SetActive(false); StartCoroutine("StartTimer"); } // Update is called once per frame void Update() { if (!pause) { if (Input.GetKeyDown(KeyCode.W)) { lastInput = 'W'; } if (Input.GetKeyDown(KeyCode.A)) { lastInput = 'A'; } if (Input.GetKeyDown(KeyCode.S)) { lastInput = 'S'; } if (Input.GetKeyDown(KeyCode.D)) { lastInput = 'D'; } if (!tweener.TweenExists(transform)) { if (position[0] == 14 && position[1] == 0) { transform.position = new Vector3(transform.position.x + 26, transform.position.y, transform.position.z); position[1] = 26; } if (position[0] == 14 && position[1] == 27) { transform.position = new Vector3(transform.position.x - 26, transform.position.y, transform.position.z); position[1] = 1; } if (dead) { transform.position = new Vector3(1.0f, 28.0f, transform.position.z); animator.Play("PacStudentRight"); position = new int[] { 1, 1 }; dead = false; } TryMove(lastInput); } StartCoroutine(FootstepAudio()); if (lastInput != '.') { StartCoroutine(WallSound()); } if (cherry.activeInHierarchy == false) { cherry.SetActive(true); } timeTxt.text = timeFormat(time); time += Time.deltaTime; } } private void Move(Vector3 target) { if (!tweener.TweenExists(transform)) { tweener.AddTween(transform, transform.position, target, duration); } } private void TryMove(char key) { if (!pause) { if (key.Equals('W')) { if (levelMap[position[0] - 1, position[1]] == 0 || levelMap[position[0] - 1, position[1]] == 5 || levelMap[position[0] - 1, position[1]] == 6) { Move(transform.position + new Vector3(0.0f, 1.0f, 0.0f)); position[0]--; animator.speed = 1; animator.Play("PacStudentUp"); currentInput = lastInput; } else CurrentMove(currentInput); } if (key.Equals('A')) { if (levelMap[position[0], position[1] - 1] == 0 || levelMap[position[0], position[1] - 1] == 5 || levelMap[position[0], position[1] - 1] == 6) { Move(transform.position + new Vector3(-1.0f, 0.0f, 0.0f)); position[1]--; animator.speed = 1; animator.Play("PacStudentLeft"); currentInput = lastInput; } else CurrentMove(currentInput); } if (key.Equals('S')) { if (levelMap[position[0] + 1, position[1]] == 0 || levelMap[position[0] + 1, position[1]] == 5 || levelMap[position[0] + 1, position[1]] == 6) { Move(transform.position + new Vector3(0.0f, -1.0f, 0.0f)); position[0]++; animator.speed = 1; animator.Play("PacStudentDown"); currentInput = lastInput; } else CurrentMove(currentInput); } if (key.Equals('D')) { if (levelMap[position[0], position[1] + 1] == 0 || levelMap[position[0], position[1] + 1] == 5 || levelMap[position[0], position[1] + 1] == 6) { Move(transform.position + new Vector3(1.0f, 0.0f, 0.0f)); position[1]++; animator.speed = 1; animator.Play("PacStudentRight"); currentInput = lastInput; } else CurrentMove(currentInput); } } } private void CurrentMove(char key) { if (!pause) { if (key.Equals('W')) { if (levelMap[position[0] - 1, position[1]] == 0 || levelMap[position[0] - 1, position[1]] == 5 || levelMap[position[0] - 1, position[1]] == 6) { Move(transform.position + new Vector3(0.0f, 1.0f, 0.0f)); position[0]--; animator.speed = 1; animator.Play("PacStudentUp"); } else animator.speed = 0; } if (key.Equals('A')) { if (levelMap[position[0], position[1] - 1] == 0 || levelMap[position[0], position[1] - 1] == 5 || levelMap[position[0], position[1] - 1] == 6) { Move(transform.position + new Vector3(-1.0f, 0.0f, 0.0f)); position[1]--; animator.speed = 1; animator.Play("PacStudentLeft"); } else animator.speed = 0; } if (key.Equals('S')) { if (levelMap[position[0] + 1, position[1]] == 0 || levelMap[position[0] + 1, position[1]] == 5 || levelMap[position[0] + 1, position[1]] == 6) { Move(transform.position + new Vector3(0.0f, -1.0f, 0.0f)); position[0]++; animator.speed = 1; animator.Play("PacStudentDown"); } else animator.speed = 0; } if (key.Equals('D')) { if (levelMap[position[0], position[1] + 1] == 0 || levelMap[position[0], position[1] + 1] == 5 || levelMap[position[0], position[1] + 1] == 6) { Move(transform.position + new Vector3(1.0f, 0.0f, 0.0f)); position[1]++; animator.speed = 1; animator.Play("PacStudentRight"); } else animator.speed = 0; } } } IEnumerator WallSound() { if (!tweener.TweenExists(transform) && playing == false) { playing = true; wallSource.Play(); GameObject.Find("WallHit").GetComponent<ParticleSystem>().Play(); yield return new WaitForSeconds(0.5f); wallSource.Stop(); GameObject.Find("WallHit").GetComponent<ParticleSystem>().Stop(); playing = false; } } IEnumerator FootstepAudio() { if (tweener.TweenExists(transform) && playing == false) { playing = true; footstepSource.Play(); GameObject.Find("Footstep").GetComponent<ParticleSystem>().Play(); yield return new WaitForSeconds(0.5f); footstepSource.Stop(); GameObject.Find("Footstep").GetComponent<ParticleSystem>().Stop(); playing = false; } } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Pellet")) { other.gameObject.SetActive(false); score += 10; scoreTxt.text = score.ToString(); } if (other.gameObject.CompareTag("Cherry")) { cherry.SetActive(false); score += 100; scoreTxt.text = score.ToString(); } if (other.gameObject.CompareTag("PowerPellet")) { other.gameObject.SetActive(false); scaredTimer.SetActive(true); StartCoroutine("ScaredTimer"); } if (other.gameObject.CompareTag("Ghost")) { if (powerPellet == true) { ghostKill = true; //MUSIC CHANGE score += 300; scoreTxt.text = score.ToString(); StartCoroutine("GhostDeathTimer"); //TIMER FOR RESPAWN } else { if (GameObject.Find("Life 3") != null) { StartCoroutine("PacDeath"); GameObject.Find("Life 3").SetActive(false); } else if (GameObject.Find("Life 2") != null) { StartCoroutine("PacDeath"); GameObject.Find("Life 2").SetActive(false); } else if (GameObject.Find("Life 1") != null) { GameObject.Find("Life 1").SetActive(false); gameOverTxt.text = "Game Over"; animator.Play("PacStudentDead"); saveManager.SaveScore(); saveManager.SaveTime(); gameMenu.saved = true; pause = true; Invoke("GameOver", 3.0f); } } } } IEnumerator StartTimer() { animator.speed = 0; startTimerTxt.text = "3"; yield return new WaitForSeconds(1); startTimerTxt.text = "2"; yield return new WaitForSeconds(1); startTimerTxt.text = "1"; yield return new WaitForSeconds(1); startTimerTxt.text = "GO!"; yield return new WaitForSeconds(1); startTimerTxt.text = null; pause = false; musicSource.clip = defaultMusic; musicSource.Play(); cherry.SetActive(true); } IEnumerator ScaredTimer() { powerPellet = true; musicSource.clip = scaredMusic; musicSource.Play(); for (int i = 10; i >= 0; i--) { scaredTimerTxt.text = i.ToString(); yield return new WaitForSeconds(1); } scaredTimer.SetActive(false); musicSource.Stop(); musicSource.clip = defaultMusic; musicSource.Play(); powerPellet = false; } IEnumerator GhostDeathTimer() { for (int i = 5; i >= 0; i--) { yield return new WaitForSeconds(1); } } IEnumerator PacDeath() { pause = true; deathSource.Play(); animator.Play("PacStudentDead"); GameObject.Find("Death").GetComponent<ParticleSystem>().Play(); yield return new WaitForSeconds(3); GameObject.Find("Death").GetComponent<ParticleSystem>().Stop(); deathSource.Stop(); pause = false; animator.speed = 0; lastInput = '.'; currentInput = '.'; dead = true; } private void GameOver() { SceneManager.LoadScene("StartScene"); } public string timeFormat(float time) { int min = (int)time / 60; int sec = (int)time - 60 * min; int ms = (int)(1000 * (time - min * 60 - sec)); return string.Format("{0:00}:{1:00}:{2:000}", min, sec, ms); } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.Data.Metadata; using gView.Framework.FDB; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.system; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace gView.DataSources.Fdb.MSAccess { /// <summary> /// Zusammenfassung für AccessFDBDataset. /// </summary> //[gView.Framework.system.RegisterPlugIn("6F540340-74C9-4b1a-BD4D-B1C5FE946CA1")] public class AccessFDBDataset : DatasetMetadata, IFeatureDataset2, IRasterDataset, IFDBDataset { internal int _dsID = -1; private List<IDatasetElement> _layers; private string _errMsg = ""; private string _connString = ""; private string _dsname = ""; internal AccessFDB _fdb = null; private List<string> _addedLayers; private ISpatialReference _sRef = null; private DatasetState _state = DatasetState.unknown; private ISpatialIndexDef _sIndexDef = new gViewSpatialIndexDef(); public AccessFDBDataset(AccessFDB fdb) { _addedLayers = new List<string>(); _fdb = fdb; } ~AccessFDBDataset() { this.Dispose(); } public void Dispose() { //System.Windows.Forms.MessageBox.Show("Dataset Dispose "+this.DatasetName); if (_fdb != null) { _fdb.Dispose(); _fdb = null; } } #region IFeatureDataset Member async public Task<List<IDatasetElement>> Elements() { if (_fdb == null) { return new List<IDatasetElement>(); } if (_layers == null || _layers.Count == 0) { _layers = await _fdb.DatasetLayers(this); if (_layers != null && _addedLayers.Count != 0) { List<IDatasetElement> list = new List<IDatasetElement>(); foreach (IDatasetElement element in _layers) { if (element is IFeatureLayer) { if (_addedLayers.Contains(((IFeatureLayer)element).FeatureClass.Name)) { list.Add(element); } } else if (element is IRasterLayer) { if (_addedLayers.Contains(((IRasterLayer)element).Title)) { list.Add(element); } } else { if (_addedLayers.Contains(element.Title)) { list.Add(element); } } } _layers = list; } } if (_layers == null) { return new List<IDatasetElement>(); } return _layers; } public bool canRenderImage { get { return false; } } public bool renderImage(IDisplay display) { return false; } public bool renderLayer(IDisplay display, ILayer layer) { return false; } async public Task<IEnvelope> Envelope() { if (_layers == null) { return null; } bool first = true; IEnvelope env = null; foreach (IDatasetElement layer in _layers) { if (!(layer.Class is IFeatureClass)) { continue; } IEnvelope envelope = ((IFeatureClass)layer.Class).Envelope; if (envelope.Width > 1e10 && await ((IFeatureClass)layer.Class).CountFeatures() == 0) { envelope = null; } if (gView.Framework.Geometry.Envelope.IsNull(envelope)) { continue; } if (first) { first = false; env = new Envelope(((IFeatureClass)layer.Class).Envelope); } else { env.Union(((IFeatureClass)layer.Class).Envelope); } } return env; } /* public string imageUrl { get { return ""; } set { } } public string imagePath { get { return _imagePath; } set { } } */ public System.Drawing.Image Bitmap { get { return null; } } public Task<ISpatialReference> GetSpatialReference() { return Task.FromResult(_sRef); // wird sonst Zach, wenns bei jedem Bildaufbau von jedem Thema gelesen werden muß... //if(_sRef!=null) return _sRef; //if(_fdb==null) return null; //return _sRef=_fdb.SpatialReference(_dsname); } public void SetSpatialReference(ISpatialReference sRef) { _sRef = sRef; } #endregion #region IDataset Member public IDatasetEnum DatasetEnum { get { return null; } } public string DatasetName { get { return _dsname; } } public string ConnectionString { get { string c = "mdb=" + ConfigTextStream.ExtractValue(_connString, "mdb") + ";" + "dsname=" + ConfigTextStream.ExtractValue(_connString, "dsname") + ";"; while (c.IndexOf(";;") != -1) { c = c.Replace(";;", ";"); } /* if (_layers != null && _layers.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (IDatasetElement element in _layers) { if (sb.Length != 0) sb.Append("@"); sb.Append(element.Title); } c += "layers=" + sb.ToString(); } else { //c += "layers=" + ConfigTextStream.ExtractValue(_connString, "layers"); } * */ return c; } } async public Task<bool> SetConnectionString(string value) { _connString = value; if (value == null) { return false; } while (_connString.IndexOf(";;") != -1) { _connString = _connString.Replace(";;", ";"); } _dsname = ConfigTextStream.ExtractValue(value, "dsname"); _addedLayers.Clear(); foreach (string layername in ConfigTextStream.ExtractValue(value, "layers").Split('@')) { if (layername == "") { continue; } if (_addedLayers.IndexOf(layername) != -1) { continue; } _addedLayers.Add(layername); } if (_fdb == null) { throw new NullReferenceException("_fdb==null"); } _fdb.DatasetRenamed += new AccessFDB.DatasetRenamedEventHandler(AccessFDB_DatasetRenamed); _fdb.FeatureClassRenamed += new AccessFDB.FeatureClassRenamedEventHandler(AccessFDB_FeatureClassRenamed); _fdb.TableAltered += new AccessFDB.AlterTableEventHandler(SqlFDB_TableAltered); await _fdb.Open(ConfigTextStream.ExtractValue(_connString, "mdb")); return true; } public DatasetState State { get { return _state; } } async public Task<bool> Open() { if (_connString == null || _connString == "" || _dsname == null || _dsname == "" || _fdb == null) { return false; } _dsID = await _fdb.DatasetID(_dsname); if (_dsID == -1) { return false; } _sRef = await _fdb.SpatialReference(_dsname); _sIndexDef = await _fdb.SpatialIndexDef(_dsID); _state = DatasetState.opened; return true; } public string LastErrorMessage { get { return _errMsg; } set { _errMsg = value; } } public string DatasetGroupName { get { return "AccessFDB"; } } public string ProviderName { get { return "Access Feature Database"; } } public string Query_FieldPrefix { get { return "["; } } public string Query_FieldPostfix { get { return "]"; } } public IDatabase Database { get { return _fdb; } } async public Task RefreshClasses() { if (_fdb != null) { await _fdb.RefreshClasses(this); } } #endregion void AccessFDB_FeatureClassRenamed(string oldName, string newName) { if (_layers == null) { return; } foreach (IDatasetElement element in _layers) { if (element.Class is AccessFDBFeatureClass && ((AccessFDBFeatureClass)element.Class).Name == oldName) { ((AccessFDBFeatureClass)element.Class).Name = newName; } } } async void SqlFDB_TableAltered(string table) { if (_layers == null) { return; } foreach (IDatasetElement element in _layers) { if (element.Class is AccessFDBFeatureClass && ((AccessFDBFeatureClass)element.Class).Name == table) { var fields = await _fdb.FeatureClassFields(this._dsID, table); AccessFDBFeatureClass fc = element.Class as AccessFDBFeatureClass; ((FieldCollection)fc.Fields).Clear(); foreach (IField field in fields) { ((FieldCollection)fc.Fields).Add(field); } } } } void AccessFDB_DatasetRenamed(string oldName, string newName) { if (_dsname == oldName) { _dsname = newName; } } async public Task<IDatasetElement> Element(string DatasetElementTitle) { if (_fdb == null) { return null; } IDatasetElement element = await _fdb.DatasetElement(this, DatasetElementTitle); if (element != null && element.Class is AccessFDBFeatureClass) { ((AccessFDBFeatureClass)element.Class).SpatialReference = _sRef; } return element; } public override string ToString() { return _dsname; } #region IPersistable Member public string PersistID { get { return null; } } async public Task<bool> LoadAsync(IPersistStream stream) { string connectionString = (string)stream.Load("connectionstring", ""); if (_fdb != null) { _fdb.Dispose(); _fdb = null; } await this.SetConnectionString(connectionString); return await this.Open(); } public void Save(IPersistStream stream) { stream.SaveEncrypted("connectionstring", this.ConnectionString); } #endregion #region IDataset2 Member async public Task<IDataset2> EmptyCopy() { AccessFDBDataset dataset = new AccessFDBDataset(_fdb); await dataset.SetConnectionString(ConnectionString); await dataset.Open(); return dataset; } async public Task AppendElement(string elementName) { if (_fdb == null) { return; } if (_layers == null) { _layers = new List<IDatasetElement>(); } foreach (IDatasetElement e in _layers) { if (e.Title == elementName) { return; } } IDatasetElement element = await _fdb.DatasetElement(this, elementName); if (element != null) { _layers.Add(element); } } #endregion #region IFDBDataset Member public ISpatialIndexDef SpatialIndexDef { get { return _sIndexDef; } } #endregion } [UseWithinSelectableDatasetElements(true)] internal class AccessFDBFeatureClass : IFeatureClass, IReportProgress, ISpatialTreeInfo, IRefreshable { private AccessFDB _fdb; private IDataset _dataset; private string _name = "", _aliasname = ""; private string m_idfield = "", m_shapeField = ""; private FieldCollection m_fields; private IEnvelope m_envelope = null; private BinarySearchTree _searchTree = null; private GeometryDef _geomDef; public AccessFDBFeatureClass(AccessFDB fdb, IDataset dataset, GeometryDef geomDef) { _fdb = fdb; _dataset = dataset; _geomDef = (geomDef != null) ? geomDef : new GeometryDef(); m_fields = new FieldCollection(); } public AccessFDBFeatureClass(AccessFDB fdb, IDataset dataset, GeometryDef geomDef, BinarySearchTree tree) : this(fdb, dataset, geomDef) { _searchTree = tree; } #region IFeatureClass Member public string Name { get { return _name; } set { _name = value; } } public string Aliasname { get { return _aliasname; } set { _aliasname = value; } } async public Task<int> CountFeatures() { if (_fdb == null) { return -1; } return await _fdb.CountFeatures(_name); } async public Task<IFeatureCursor> GetFeatures(IQueryFilter filter/*, gView.Framework.Data.getFeatureQueryType type*/) { if (_fdb == null) { return null; } if (filter != null) { filter.AddField("FDB_OID"); filter.fieldPrefix = "["; filter.fieldPostfix = "]"; } if (filter is IRowIDFilter) { return await _fdb.QueryIDs(this, filter.SubFieldsAndAlias, ((IRowIDFilter)filter).IDs, filter.FeatureSpatialReference); } else { return await _fdb.Query(this, filter); } } /* public IFeature GetFeature(int id, gView.Framework.Data.getFeatureQueryType type) { if(_fdb==null) return null; string sql="[FDB_OID]="+id.ToString(); QueryFilter filter=new QueryFilter(); filter.WhereClause=sql; switch(type) { case getFeatureQueryType.All: case getFeatureQueryType.Attributes: filter.SubFields = "*"; break; case getFeatureQueryType.Geometry: filter.SubFields = "[FDB_OID],[FDB_SHAPE]"; break; } IFeatureCursor cursor=_fdb.Query(this,filter); if(cursor==null) return null; return cursor.NextFeature; } IFeatureCursor gView.Framework.Data.IFeatureClass.GetFeatures(List<int> ids, gView.Framework.Data.getFeatureQueryType type) { if(_fdb==null) return null; //QueryFilter filter=new QueryFilter(); //StringBuilder sql=new StringBuilder(); //int count=0; //foreach(object id in ids) //{ // if(count!=0) sql.Append(","); // sql.Append(id.ToString()); // count++; //} string SubFields=""; switch(type) { case getFeatureQueryType.All: case getFeatureQueryType.Attributes: SubFields = "*"; break; case getFeatureQueryType.Geometry: SubFields = "[FDB_OID],[FDB_SHAPE]"; break; } return _fdb.QueryIDs(this,SubFields,ids); } */ async public Task<ICursor> Search(IQueryFilter filter) { return await GetFeatures(filter); } async public Task<ISelectionSet> Select(IQueryFilter filter) { filter.SubFields = this.IDFieldName; filter.AddField("FDB_OID"); filter.AddField("FDB_SHAPE"); IFeatureCursor cursor = await _fdb.Query(this, filter); IFeature feat; SpatialIndexedIDSelectionSet selSet = new SpatialIndexedIDSelectionSet(this.Envelope); while ((feat = await cursor.NextFeature()) != null) { //int nid = 0; foreach (FieldValue fv in feat.Fields) { //if (fv.Name == "FDB_NID") //{ // nid = (int)fv.Value; // break; //} } selSet.AddID(feat.OID, feat.Shape); } cursor.Dispose(); return selSet; } public IFieldCollection Fields { get { return m_fields; } } public IField FindField(string name) { if (m_fields == null) { return null; } foreach (IField field in m_fields.ToEnumerable()) { if (field.name == name) { return field; } } return null; } public string IDFieldName { get { return m_idfield; } set { m_idfield = value; } } public string ShapeFieldName { get { return m_shapeField; } set { m_shapeField = value; } } public IEnvelope Envelope { get { return m_envelope; } set { m_envelope = value; } } public IDataset Dataset { get { return _dataset; } } #endregion #region IReportProgress Member public void AddDelegate(object Delegate) { if (_fdb == null) { return; } _fdb.reportProgress += (AccessFDB.ProgressEvent)Delegate; } #endregion public void SetSpatialTreeInfo(gView.Framework.FDB.ISpatialTreeInfo info) { if (info == null) { return; } try { _si_type = info.type; _si_bounds = info.Bounds; _si_spatialRatio = info.SpatialRatio; _si_maxPerNode = info.MaxFeaturesPerNode; } catch { } } #region ISpatialTreeInfo Member private string _si_type = ""; private IEnvelope _si_bounds = null; private double _si_spatialRatio = 0.0; private int _si_maxPerNode = 0; public IEnvelope Bounds { get { return _si_bounds; } } public double SpatialRatio { get { return _si_spatialRatio; } } public string type { get { return _si_type; } } public int MaxFeaturesPerNode { get { return _si_maxPerNode; } } async public Task<List<SpatialIndexNode>> SpatialIndexNodes() { if (_fdb == null) { return null; } return await _fdb.SpatialIndexNodes2(_name); } #endregion #region IGeometryDef Member public bool HasZ { get { return _geomDef.HasZ; } } public bool HasM { get { return _geomDef.HasM; } } public GeometryType GeometryType { get { return _geomDef.GeometryType; } } public ISpatialReference SpatialReference { get { return _geomDef.SpatialReference; } set { _geomDef.SpatialReference = value; } } public gView.Framework.Data.GeometryFieldType GeometryFieldType { get { return GeometryFieldType.Default; } } #endregion #region IRefreshable Member public void RefreshFrom(object obj) { if (!(obj is AccessFDBFeatureClass)) { return; } AccessFDBFeatureClass fc = (AccessFDBFeatureClass)obj; if (fc.Name != this.Name) { return; } this.Envelope = fc.Envelope; this.SpatialReference = fc.SpatialReference; this.IDFieldName = fc.IDFieldName; this.ShapeFieldName = fc.ShapeFieldName; _geomDef.GeometryType = fc.GeometryType; _geomDef.HasZ = fc.HasZ; _geomDef.HasM = fc.HasM; FieldCollection fields = new FieldCollection(fc.Fields); if (fields != null) { fields.PrimaryDisplayField = m_fields.PrimaryDisplayField; } m_fields = fields; } #endregion } }
using FairyGUI; using System.Collections.Generic; public enum EventListenerType { onClick, onRightClick, onTouchBegin, onTouchMove, onTouchEnd, onRollOver, onRollOut, onAddedToStage, onRemovedFromStage, onKeyDown, onClickLink, onPositionChanged, onSizeChanged, onDragStart, onDragMove, onDragEnd, OnGearStop, } public class GUIBase : Window { public string uiName = string.Empty; public string packageName = string.Empty; private GComponent viewComponent; private Dictionary<string, GObject> cacheObjs = new Dictionary<string, GObject>(); protected virtual void OnCreate() { } protected virtual void OnStart() { } protected virtual void OnRegister() { } protected virtual void OnUnRegister() { } protected virtual void OnClose() { } protected virtual void OnDestroy() { } public void Start() { Show(); OnStart(); OnRegister(); } public void Update() { OnUpdate(); } public void Close() { OnUnRegister(); OnClose(); Hide(); } public void Destory() { foreach (var item in cacheObjs) { if (item.Value is GButton) item.Value.RemoveEventListeners(); } cacheObjs.Clear(); cacheObjs = null; Close(); OnDestroy(); this.Dispose(); } protected override void OnInit() { viewComponent = UIPackage.CreateObject(packageName, uiName).asCom; if (viewComponent == null) return; viewComponent.fairyBatching = true; this.contentPane = viewComponent; OnCreate(); } protected GObject GetChildren(string name) { if (viewComponent == null) return null; return viewComponent.GetChild(name); } protected void SetEnable(string url, bool enable) { GObject child = GetChildren(url); if (child == null) return; child.enabled = enable; } protected void SetEventListener(string objname, EventListenerType listenerType, EventCallback1 callback) { GButton button = FindChildren<GButton>(objname); if (button == null) return; switch (listenerType) { case EventListenerType.onClick: button.onClick.Add(callback); break; case EventListenerType.onRightClick: button.onRightClick.Add(callback); break; case EventListenerType.onTouchBegin: button.onTouchBegin.Add(callback); break; case EventListenerType.onTouchMove: button.onTouchMove.Add(callback); break; case EventListenerType.onTouchEnd: button.onTouchEnd.Add(callback); break; case EventListenerType.onRollOver: button.onRollOver.Add(callback); break; case EventListenerType.onRollOut: button.onRollOut.Add(callback); break; case EventListenerType.onAddedToStage: button.onAddedToStage.Add(callback); break; case EventListenerType.onRemovedFromStage: button.onRemovedFromStage.Add(callback); break; case EventListenerType.onKeyDown: button.onKeyDown.Add(callback); break; case EventListenerType.onClickLink: button.onClickLink.Add(callback); break; case EventListenerType.onPositionChanged: button.onPositionChanged.Add(callback); break; case EventListenerType.onSizeChanged: button.onSizeChanged.Add(callback); break; case EventListenerType.onDragStart: button.onDragStart.Add(callback); break; case EventListenerType.onDragMove: button.onDragMove.Add(callback); break; case EventListenerType.onDragEnd: button.onDragEnd.Add(callback); break; case EventListenerType.OnGearStop: button.OnGearStop.Add(callback); break; default: button.onClick.Add(callback); break; } } protected GTextField SetText(string objname,string value) { GTextField textfield = FindChildren<GTextField>(objname); if (textfield != null) textfield.text = value; return textfield; } protected void SetVisible(string objname, bool visible) { GObject obj = GetChildren(objname); if (obj != null && obj.visible != visible) obj.visible = visible; } protected string GetTextInput(string objname) { GTextInput textinput = FindChildren<GTextInput>(objname); if (textinput != null) return textinput.text; return string.Empty; } protected void SetTextInput(string objname, string value) { GTextInput textinput = FindChildren<GTextInput>(objname); if (textinput != null) textinput.text = value; } protected T FindChildren<T>(string objname) where T : GObject { GObject obj; if (!cacheObjs.TryGetValue(objname, out obj)) { obj = GetChildren(objname); cacheObjs.Add(objname, obj); } if (obj == null) return null; return obj as T; } }
using System.Windows.Forms; namespace LoowooTech.VillagePlanning { public partial class LoadForm : Form { public LoadForm() { InitializeComponent(); _instance = this; } private static LoadForm _instance { get; set; } public static LoadForm Instance { get { return _instance; } } } }
using Core.DomainModel; using System; using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; namespace Web.Models { public class TaskViewModel : ICreatedOn { #region Variables public int TaskID { get; set; } [DataType(DataType.Date)] public DateTime CreatedOn { get; set; } public string Headline { get; set; } public string Description { get; set; } public bool Completed { get; set; } public int HoursToComplete { get; set; } [JsonIgnore] public ProjectViewModel Project { get; set; } public int ProjectID { get; set; } #endregion public override string ToString() { return TaskID + " - " + Headline + " - " + CreatedOn + " - " + Completed + " - " + Description; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using HelperClassAll; using Citycykler.Models; namespace CityCykler { public partial class MasterPage : System.Web.UI.MasterPage { DataLinqDB db = new DataLinqDB(); protected void Page_Load(object sender, EventArgs e) { var footer = db.footers.FirstOrDefault(); if (footer != null) { LiteralFooter.Text = footer.text; } //Header random her var F = db.headers.Shuffle(new Random()).Take(1).ToList(); if (F != null) { foreach (var item in F) { Limg.Text = "<img alt='" + item.opretdato + "' src='../img/Cropped/" + item.img + "' />"; } } var imgMissing = "missing.png"; var result = db.modelers.Where(x => x.NyPris > 0 && x.img != imgMissing).Take(3).Shuffle(new Random()).ToList(); RepeaterListTilbud.DataSource = result; RepeaterListTilbud.DataBind(); RepeaterListKategori.DataSource = db.kategoris.OrderBy(i => i.id).ToList(); RepeaterListKategori.DataBind(); setClassActive(); } private void setClassActive() { //Det her er mine andre sider som forside mv. var url = Request.Url.ToString().Split('/').Last().Split('?').First().ToLower().Trim(); switch (url) { case "default.aspx": defaultForside.Attributes["class"] = "active"; break; case "kontakt.aspx": Kontakt.Attributes["class"] = "active"; break; case "nyheder.aspx": Nyheder.Attributes["class"] = "active"; break; case "search.aspx": search.Attributes["class"] = "active"; break; } //Det her til min kategori f.eks cykler, udstyr mv var urlID = HelperClassAll.HelperClass.ReturnGetId(); var category = db.kategoris.FirstOrDefault(x => x.id == urlID); if (category != null) { foreach (RepeaterItem item in RepeaterListKategori.Items) { HtmlControl hc = (HtmlControl)item.FindControl("Vare"); if (hc.Attributes["data-id"] == category.id.ToString()) { hc.Attributes["class"] = "active"; } } } } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using TriangleCollector.Models.Interfaces; namespace TriangleCollector.Models.Exchanges.Binance { public class BinanceClient : IExchangeClient { public IExchange Exchange { get; set; } public string SymbolsRestApi { get; set; } = "https://api.binance.com/api/v3/exchangeInfo"; public string PricesRestApi { get; set; } = "https://api.binance.com/api/v3/ticker/bookTicker"; public string SocketClientApi { get; set; } = "wss://stream.binance.com:9443/ws"; public JsonElement.ArrayEnumerator Tickers { get; set; } public IClientWebSocket Client { get; set; } public int MaxMarketsPerClient { get; } = 20; public int ID = 1; public HashSet<IOrderbook> GetMarketsViaRestApi() { var output = new HashSet<IOrderbook>(); var symbols = JsonDocument.ParseAsync(ProjectOrbit.StaticHttpClient.GetStreamAsync(SymbolsRestApi).Result).Result.RootElement.GetProperty("symbols").EnumerateArray(); foreach (var responseItem in symbols) { if(responseItem.GetProperty("status").ToString() == "TRADING") { var market = new BinanceOrderbook(); market.Symbol = responseItem.GetProperty("symbol").ToString(); market.BaseCurrency = responseItem.GetProperty("baseAsset").ToString(); market.QuoteCurrency = responseItem.GetProperty("quoteAsset").ToString(); market.Exchange = Exchange; output.Add(market); } } var tickerPrices = JsonDocument.ParseAsync(ProjectOrbit.StaticHttpClient.GetStreamAsync(PricesRestApi).Result).Result.RootElement.EnumerateArray(); foreach (var ticker in tickerPrices) { var symbol = ticker.GetProperty("symbol").ToString(); var bidPrice = Decimal.Parse(ticker.GetProperty("bidPrice").ToString()); var bidSize = Decimal.Parse(ticker.GetProperty("bidQty").ToString()); var askPrice = Decimal.Parse(ticker.GetProperty("askPrice").ToString()); var askSize = Decimal.Parse(ticker.GetProperty("askQty").ToString()); if (bidPrice > 0 && askPrice > 0 && bidSize > 0 && askSize > 0) { if(output.Where(m => m.Symbol == symbol).Count() > 0) { output.Where(m => m.Symbol == symbol).First().OfficialBids.TryAdd(bidPrice, bidSize); output.Where(m => m.Symbol == symbol).First().OfficialAsks.TryAdd(askPrice, askSize); } } } output = output.Where(m => m.OfficialAsks.Count > 0 && m.OfficialBids.Count > 0).ToHashSet(); return output; } public async Task<WebSocketAdapter> CreateExchangeClientAsync() { var client = new ClientWebSocket(); var factory = new LoggerFactory(); var adapter = new WebSocketAdapter(factory.CreateLogger<WebSocketAdapter>(), client); client.Options.KeepAliveInterval = new TimeSpan(0, 0, 5); await client.ConnectAsync(new Uri(SocketClientApi), CancellationToken.None); adapter.TimeStarted = DateTime.UtcNow; adapter.Markets = new List<IOrderbook>(); Client = adapter; Exchange.ActiveClients.Add(Client); await Task.Delay(250); // clients with zero subscriptions are being aborted; give 1/4 second to ensure connection is complete return adapter; } public async Task SubscribeViaAggregate() { if (Client.State == WebSocketState.Open) { await Client.SendAsync(new ArraySegment<byte>( Encoding.ASCII.GetBytes($"{{\"method\": \"SUBSCRIBE\",\"params\": [\"!bookTicker\"], \"id\": {ID} }}") ), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false); ID++; Exchange.AggregateStreamOpen = true; } await Task.Delay(500); } public async Task SubscribeViaQueue(IOrderbook market) { if (Client.State == WebSocketState.Open) { await Client.SendAsync(new ArraySegment<byte>( Encoding.ASCII.GetBytes($"{{\"method\": \"SUBSCRIBE\",\"params\": [\"{market.Symbol.ToLower()}@bookTicker\"], \"id\": {ID} }}") ), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false); ID++; Client.Markets.Add(market); } await Task.Delay(250); } } }
using System; using System.Net; using Microsoft.Silverlight.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using ExpressionSerialization; using System.Linq.Expressions; using System.Xml.Linq; using System.Diagnostics; using System.Collections.Generic; using Northwind; using System.Linq; using System.Reflection; using System.Dynamic; namespace UnitTests { [TestClass] public class Walthrough : UnitTests.BaseTests { internal const string TAG = "Walkthrough"; [TestMethod] [Tag("IQueryable")] [Tag(TAG)] public void Test2() { IQueryable<Customer> queryable = GetCustomers().AsQueryable<Customer>(); IQueryable<Customer> query = from c in queryable where c.ID >= 0 select c; XElement xml1 = serializer.Serialize(query.Expression); } [TestMethod] [Tag(TAG)] public void Tests3To25() { Debug.WriteLine("\nTEST - 2"); Expression<Func<int>> e2 = () => 1; XElement xml2 = serializer.Serialize(e2.Body); Expression result2 = serializer.Deserialize(xml2); Debug.WriteLine("{0} should be the same as {1}", e2.Body.ToString(), result2.ToString()); Debug.WriteLine("\nTEST - 3"); Expression<Func<ExpressionType>> e3 = () => ExpressionType.Add; XElement xml3 = serializer.Serialize(e3.Body); Expression result3 = serializer.Deserialize(xml3); Debug.WriteLine("{0} should be the same as {1}", e3.Body.ToString(), result3.ToString()); Debug.WriteLine("\nTEST - 4"); Expression<Func<bool>> e4 = () => true; XElement xml4 = serializer.Serialize(e4.Body); Expression result4 = serializer.Deserialize(xml4); Debug.WriteLine("{0} should be the same as {1}", e4.Body.ToString(), result4.ToString()); Debug.WriteLine("\nTEST - 5"); Expression<Func<decimal, decimal>> e5 = d => d + 1m; XElement xml5 = serializer.Serialize(e5.Body); Expression result5 = serializer.Deserialize(xml5); Debug.WriteLine("{0} should be the same as {1}", e5.Body.ToString(), result5.ToString()); Debug.WriteLine("\nTEST - 6"); Expression<Func<decimal, decimal>> e6 = d => d + 1m; XElement xml6 = serializer.Serialize(e6); Expression result6 = serializer.Deserialize(xml6); Debug.WriteLine("{0} should be the same as {1}", e6.ToString(), result6.ToString()); Debug.WriteLine(((result6 as Expression<Func<decimal, decimal>>).Compile())(3)); Debug.WriteLine("\nTEST - 7"); Expression<Func<string, int>> e7 = s => int.Parse(s); XElement xml7 = serializer.Serialize(e7); Expression result7 = serializer.Deserialize(xml7); Debug.WriteLine("{0} should be the same as {1}", e7.ToString(), result7.ToString()); Debug.WriteLine(((result7 as Expression<Func<string, int>>).Compile())("1234")); Debug.WriteLine("\nTEST - 8"); Expression<Func<string, string>> e8 = s => s.PadLeft(4); XElement xml8 = serializer.Serialize(e8); Expression result8 = serializer.Deserialize(xml8); Debug.WriteLine("{0} should be the same as {1}", e8.ToString(), result8.ToString()); Debug.WriteLine(((result8 as Expression<Func<string, string>>).Compile())("1")); Debug.WriteLine("\nTEST - 9"); Expression<Func<string, int>> e9 = s => Foo<string, int>(s, 1); XElement xml9 = serializer.Serialize(e9); Expression result9 = serializer.Deserialize(xml9); Debug.WriteLine("{0} should be the same as {1}", e9.ToString(), result9.ToString()); Debug.WriteLine(((result9 as Expression<Func<string, int>>).Compile())("abcdac")); Debug.WriteLine("\nTEST - 10"); Expression<Func<string, char[]>> e10 = s => s.Where(c => c != 'a').ToArray(); XElement xml10 = serializer.Serialize(e10); Expression result10 = serializer.Deserialize(xml10); Debug.WriteLine("{0} should be the same as {1}", e10.ToString(), result10.ToString()); Debug.WriteLine(((result10 as Expression<Func<string, char[]>>).Compile())("abcdac")); Debug.WriteLine("\nTEST - 11"); Expression<Func<string, char[]>> e11 = s => (from c in s where c != 'a' select (char)(c + 1)).ToArray(); XElement xml11 = serializer.Serialize(e11); Expression result11 = serializer.Deserialize(xml11); Debug.WriteLine("{0} should be the same as {1}", e11.ToString(), result11.ToString()); Debug.WriteLine(((result11 as Expression<Func<string, char[]>>).Compile())("abcdac")); Debug.WriteLine("\nTEST - 12"); Expression<Func<int, IEnumerable<Order[]>>> e12 = n => from c in GetCustomers() where c.ID < n select c.Orders.ToArray(); XElement xml12 = serializer.Serialize(e12); Expression result12 = serializer.Deserialize(xml12); Debug.WriteLine("{0} should be the same as {1}", e12.ToString(), result12.ToString()); Debug.WriteLine(((result12 as Expression<Func<int, IEnumerable<Order[]>>>).Compile())(5)); Debug.WriteLine("\nTEST - 13"); Expression<Func<List<int>>> e13 = () => new List<int>() { 1, 2, 3 }; XElement xml13 = serializer.Serialize(e13); Expression result13 = serializer.Deserialize(xml13); Debug.WriteLine("{0} should be the same as {1}", e13.ToString(), result13.ToString()); Debug.WriteLine(((result13 as Expression<Func<List<int>>>).Compile())()); Debug.WriteLine("\nTEST - 14"); Expression<Func<List<List<int>>>> e14 = () => new List<List<int>>() { new List<int>() { 1, 2, 3 }, new List<int>() { 2, 3, 4 }, new List<int>() { 3, 4, 5 } }; XElement xml14 = serializer.Serialize(e14); Expression result14 = serializer.Deserialize(xml14); Debug.WriteLine("{0} should be the same as {1}", e14.ToString(), result14.ToString()); Debug.WriteLine(((result14 as Expression<Func<List<List<int>>>>).Compile())()); Debug.WriteLine("\nTEST - 15"); Expression<Func<Customer>> e15 = () => new Customer() { Name = "Bob", Orders = { new Order() { Shipper = { Name = "shipper-A", ID = 2001, Phone = "222-1234" } } } }; XElement xml15 = serializer.Serialize(e15); Expression result15 = serializer.Deserialize(xml15); Debug.WriteLine("{0} should be the same as {1}", e15.ToString(), result15.ToString()); Debug.WriteLine(((result15 as Expression<Func<Customer>>).Compile())()); Debug.WriteLine("\nTEST - 16"); Expression<Func<bool, int>> e16 = b => b ? 1 : 2; XElement xml16 = serializer.Serialize(e16); Expression result16 = serializer.Deserialize(xml16); Debug.WriteLine("{0} should be the same as {1}", e16.ToString(), result16.ToString()); Debug.WriteLine(((result16 as Expression<Func<bool, int>>).Compile())(false)); Debug.WriteLine("\nTEST - 17"); Expression<Func<int, int[]>> e17 = n => new[] { n }; XElement xml17 = serializer.Serialize(e17); Expression result17 = serializer.Deserialize(xml17); Debug.WriteLine("{0} should be the same as {1}", e17.ToString(), result17.ToString()); Debug.WriteLine(((result17 as Expression<Func<int, int[]>>).Compile())(7)); Debug.WriteLine("\nTEST - 18"); Expression<Func<int, int[]>> e18 = n => new int[n]; XElement xml18 = serializer.Serialize(e18); Expression result18 = serializer.Deserialize(xml18); Debug.WriteLine("{0} should be the same as {1}", e18.ToString(), result18.ToString()); Debug.WriteLine(((result18 as Expression<Func<int, int[]>>).Compile())(7)); Debug.WriteLine("\nTEST - 19"); Expression<Func<object, string>> e19 = o => o as string; XElement xml19 = serializer.Serialize(e19); Expression result19 = serializer.Deserialize(xml19); Debug.WriteLine("{0} should be the same as {1}", e19.ToString(), result19.ToString()); Debug.WriteLine(((result19 as Expression<Func<object, string>>).Compile())(7)); Debug.WriteLine("\nTEST - 20"); Expression<Func<object, bool>> e20 = o => o is string; XElement xml20 = serializer.Serialize(e20); Expression result20 = serializer.Deserialize(xml20); Debug.WriteLine("{0} should be the same as {1}", e20.ToString(), result20.ToString()); Debug.WriteLine(((result20 as Expression<Func<object, bool>>).Compile())(7)); Debug.WriteLine("\nTEST - 21"); Expression<Func<IEnumerable<string>>> e21 = () => from m in typeof(string).GetMethods() where !m.IsStatic group m by m.Name into g select g.Key + g.Count().ToString(); XElement xml21 = serializer.Serialize(e21); Expression result21 = serializer.Deserialize(xml21); Debug.WriteLine("{0} should be the same as {1}", e21.ToString(), result21.ToString()); Debug.WriteLine(((result21 as Expression<Func<IEnumerable<string>>>).Compile())()); Debug.WriteLine("\nTEST - 22 (may take a while)"); Expression<Func<IEnumerable<int>>> e22 = () => from a in Enumerable.Range(1, 13) join b in Enumerable.Range(1, 13) on 4 * a equals b from c in Enumerable.Range(1, 13) join d in Enumerable.Range(1, 13) on 5 * c equals d from e in Enumerable.Range(1, 13) join f in Enumerable.Range(1, 13) on 3 * e equals 2 * f join g in Enumerable.Range(1, 13) on 2 * (c + d) equals 3 * g from h in Enumerable.Range(1, 13) join i in Enumerable.Range(1, 13) on 3 * h - 2 * (e + f) equals 3 * i from j in Enumerable.Range(1, 13) join k in Enumerable.Range(1, 13) on 3 * (a + b) + 2 * j - 2 * (g + c + d) equals k from l in Enumerable.Range(1, 13) join m in Enumerable.Range(1, 13) on (h + i + e + f) - l equals 4 * m where (4 * (l + m + h + i + e + f) == 3 * (j + k + g + a + b + c + d)) select a + b + c + d + e + f + g + h + i + j + k + l + m; XElement xml22 = serializer.Serialize(e22); Expression result22 = serializer.Deserialize(xml22); Debug.WriteLine("{0} should be the same as {1}", e22.ToString(), result22.ToString()); Debug.WriteLine(((result22 as Expression<Func<IEnumerable<int>>>).Compile())().FirstOrDefault()); Debug.WriteLine("\nTEST - 23"); Expression<Func<int, int>> e23 = n => ((Func<int, int>)(x => x + 1))(n); XElement xml23 = serializer.Serialize(e23); Expression result23 = serializer.Deserialize(xml23); Debug.WriteLine("{0} should be the same as {1}", e23.ToString(), result23.ToString()); Debug.WriteLine(((result23 as Expression<Func<int, int>>).Compile())(7)); Debug.WriteLine("\nTEST - 24"); Expression<Func<IEnumerable<int>>> e24 = () => from x in Enumerable.Range(1, 10) from y in Enumerable.Range(1, 10) where x < y select x * y; XElement xml24 = serializer.Serialize(e24); Expression result24 = serializer.Deserialize(xml24); Debug.WriteLine("{0} should be the same as {1}", e24.ToString(), result24.ToString()); Debug.WriteLine(((result24 as Expression<Func<IEnumerable<int>>>).Compile())()); Debug.WriteLine("\nTEST - 25"); Expression<Func<DateTime>> e25 = () => new DateTime(10000); XElement xml25 = serializer.Serialize(e25); Expression result25 = serializer.Deserialize(xml25); Debug.WriteLine("{0} should be the same as {1}", e25.ToString(), result25.ToString()); Debug.WriteLine(((result25 as Expression<Func<DateTime>>).Compile())()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entities.FVS { /// <summary> /// 已经响应的安灯事件信息 /// </summary> public class AndonRspedEventInfo { /// <summary> /// 事件标识 /// </summary> public long EventFactID { get; set; } /// <summary> /// 事件类型 /// </summary> public string EventType { get; set; } /// <summary> /// 事件描述 /// </summary> public string EventDescription { get; set; } /// <summary> /// 是否已停产 /// </summary> public bool ProductionDown { get; set; } /// <summary> /// 呼叫时间(hh:mm) /// </summary> public string CallingTime { get; set; } /// <summary> /// 已过时长(分钟) /// </summary> public int TimeElapsed { get; set; } /// <summary> /// 业务操作标识 /// </summary> public int OpID { get; set; } /// <summary> /// 安灯事件隶属关系: /// 0-通知了别人,但我可响应; /// 1-通知我的,还未响应; /// 2-别人已响应,但追加呼叫我的 /// </summary> public int AndonEventOwnership { get; set; } public AndonRspedEventInfo Clone() { return MemberwiseClone() as AndonRspedEventInfo; } public override string ToString() { return EventDescription; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using AjaxControlToolkit; namespace MyHotel.Business.Statistics { public partial class CountersStatisticsForm : BaseWebFormMgmt { protected void Page_Load(object sender, EventArgs e) { if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated) { AddScriptManager(); } else { Response.Redirect("/LoginForm.aspx"); } } } }
// Bar POS, class UserManagmentClass // Versiones: // V0.01 22-May-2018 Moisés: Class implemented namespace BarPOS { public class UserManagementClass : Management { public UsersList Users { get; set; } public int Count { get { return Users.Count; } } public UserManagementClass(UsersList users) { Users = users; Index = 1; } public User GetActualUser() { return Users.Get(Index); } public void Add(User user) { Users.Add(user); Index = Count; } public void Remove() { if (Count > 0) { Users.Remove(Index); } MoveBackward(); } public void Modify(User newUser) { Users.Reeplace(Index, newUser); } public bool Search(string text) { if (text != null) { text = text.ToLower(); bool found = false; for (int i = 1; i <= Count; i++) { User actualUser = Users.Get(i); if (actualUser.ToString().ToLower().Contains(text)) { actualUser.Found = true; found = true; DrawFounds = true; } if (!GetActualUser().Found) { MoveForward(); } } return found; } return false; } public void MoveForward() { if (Index < Count) { Index++; } else { Index = 1; } if (DrawFounds && !Users.Get(Index).Found) { do { if (Index < Count) { Index++; } else { Index = 1; } } while (!Users.Get(Index).Found); } } public void MoveBackward() { if (Index > 1) { Index--; } else { Index = Count; } if (DrawFounds && !Users.Get(Index).Found) { do { if (Index > 1) { Index--; } else { Index = Count; } } while (!Users.Get(Index).Found); } } public string Save() { return Users.Save(); } } }
using LibraryProject.Models; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace LibraryProject.Controllers { public class AccountController : Controller { private string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; [HttpGet] public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Login model) { List<User> userList = new List<User>(); if (ModelState.IsValid) { using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("Select * From Users", con); try { con.Open(); SqlDataReader dr = command.ExecuteReader(); if(dr.HasRows) foreach(DbDataRecord result in dr) { userList.Add(new User() { Id = result.GetInt32(0) , Email = result.GetString(1) , Password = result.GetString(2) , Age = result.GetInt32(3) }); } } catch(Exception) { } } User user = userList.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault(); if(user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "User with this password and login does not exist"); } } return View(model); } //****************************************************************************************************************************************************// [HttpGet] public ActionResult Register() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(Register model) { List<User> userList = new List<User>(); if (ModelState.IsValid) { //Search using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("Select * From Users", con); try { con.Open(); SqlDataReader dr = command.ExecuteReader(); if (dr.HasRows) foreach (DbDataRecord result in dr) { userList.Add(new User() { Id = result.GetInt32(0), Email = result.GetString(1), Password = result.GetString(2), Age = result.GetInt32(3) }); } } catch { } } User user = userList.Where(u => u.Email == model.Name).FirstOrDefault(); if (user == null) { //Write to DB***************************************************************************************************************||||||||||||||||||******************************* string insertUser = String.Format("INSERT INTO Users ([Id], [Email], [Password], [Age]) VALUES('{0}','{1}','{2}',{3})", userList.Count+1, model.Name, model.Password, model.Age); using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(insertUser, con); try { con.Open(); command.ExecuteNonQuery(); } catch(Exception) { } } //Search () if add to list and db without search second time using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("Select * From Users", con); try { con.Open(); SqlDataReader dr = command.ExecuteReader(); if (dr.HasRows) foreach (DbDataRecord result in dr) { userList.Add(new User() { Id = result.GetInt32(0), Email = result.GetString(1), Password = result.GetString(2), Age = result.GetInt32(3) }); } } catch { } } user = userList.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault(); if(user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "User with this password and login exist"); } } return View(model); } public ActionResult Logoff() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); } } }
using System.ComponentModel.DataAnnotations; namespace FIMMonitoring.Domain.Enum { public enum ErrorSource { [Display(Name="From import table")] ImportTable = 0, [Display(Name = "From log file")] LogFile = 1 } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using AutoMapper; using com.Sconit.Entity.CUST; using com.Sconit.Entity.Exception; using com.Sconit.Entity.INP; using com.Sconit.Entity.MD; using com.Sconit.Entity.ORD; using com.Sconit.Entity.SYS; using com.Sconit.PrintModel.ORD; using com.Sconit.Service; using com.Sconit.Utility; using com.Sconit.Web.Models; using com.Sconit.Web.Models.SearchModels.INV; using Telerik.Web.Mvc; using System.Web; namespace com.Sconit.Web.Controllers.ORD { public class CostCenterMiscOrderController : WebAppBaseController { private static string selectCountStatement = "select count(*) from MiscOrderMaster as m"; private static string selectStatement = "select m from MiscOrderMaster as m"; private static string selectInspectResult = @"select r from InspectResult r where r.InspectNo = ? and r.RejectHandleResult=? and r.IsHandle=? and r.JudgeQty > r.HandleQty"; private static string selectRejectDetail = @"select r from RejectDetail as r where r.RejectNo=? and r.HandleQty > r.HandledQty and exists (select 1 from RejectMaster as m where r.RejectNo = m.RejectNo and m.HandleResult =? )"; //public IGenericMgr genericMgr { get; set; } public IMiscOrderMgr miscOrderMgr { get; set; } #region public method #region view [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_View")] public ActionResult Index() { ViewBag.SearchType = "CostCenter"; return View(); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_View")] public ActionResult DetailIndex() { ViewBag.SearchType = "CostCenter"; return View(); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapView")] public ActionResult ScrapIndex() { ViewBag.SearchType = "Scrap"; return View(); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_ScrapView")] public ActionResult ScrapDetailIndex() { ViewBag.SearchType = "ScrapDetail"; return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_View")] public ActionResult List(GridCommand GridCommand, MiscOrderSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(GridCommand, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } ViewBag.SearchType = "CostCenter"; if (searchCacheModel.isBack == true) { ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page; } ViewBag.PageSize = base.ProcessPageSize(GridCommand.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_View")] public ActionResult DetailList(GridCommand GridCommand, MiscOrderSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(GridCommand, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } if (searchCacheModel.isBack == true) { ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page; } ViewBag.SearchType = "CostCenter"; ViewBag.PageSize = base.ProcessPageSize(GridCommand.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapView")] public ActionResult ScrapSearchList(GridCommand GridCommand, MiscOrderSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(GridCommand, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } ViewBag.SearchType = "Scrap"; ViewBag.PageSize = base.ProcessPageSize(GridCommand.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_ScrapView")] public ActionResult ScrapDetailList(GridCommand GridCommand, MiscOrderSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(GridCommand, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } ViewBag.SearchType = "ScrapDetail"; ViewBag.PageSize = base.ProcessPageSize(GridCommand.PageSize); return View(); } public ActionResult ScrapList(GridCommand GridCommand, MiscOrderSearchModel searchModel) { SearchCacheModel searchCacheModel = this.ProcessSearchModel(GridCommand, searchModel); if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject)) { } else { SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions); } ViewBag.SearchType = "Scrap"; ViewBag.PageSize = base.ProcessPageSize(GridCommand.PageSize); return RedirectToAction("ScrapNew"); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_View,Url_CostCenterMiscOrder_ScrapView")] public ActionResult _AjaxList(GridCommand command, MiscOrderSearchModel searchModel) { if (!this.CheckSearchModelIsNull(searchModel)) { return PartialView(new GridModel(new List<MiscOrderMaster>())); } this.GetCommand(ref command, searchModel); SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); return PartialView(GetAjaxPageData<MiscOrderMaster>(searchStatementModel, command)); } #endregion #region new [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New")] public ActionResult New(string referenceNo) { ViewBag.ReferenceDocumentsType = 0; ViewBag.ReferenceNo = referenceNo; var miscOrderMaster = new MiscOrderMaster(); if (!string.IsNullOrWhiteSpace(referenceNo)) { try { miscOrderMaster.ReferenceNo = referenceNo; var snRuleList = this.genericMgr.FindAllIn<SNRule> (" from SNRule where Code in(?", new object[]{ CodeMaster.DocumentsType.REJ , CodeMaster.DocumentsType.INS }); var matchSnRule = snRuleList.FirstOrDefault(p => miscOrderMaster.ReferenceNo.StartsWith(p.PreFixed)); if (matchSnRule != null) { if (matchSnRule.Code == (int)CodeMaster.DocumentsType.INS) { var inspectResult = genericMgr.FindAll<InspectResult>(selectInspectResult, new object[] { miscOrderMaster.ReferenceNo, com.Sconit.CodeMaster.HandleResult.Scrap, false }).First(); miscOrderMaster.Location = inspectResult.CurrentLocation; miscOrderMaster.IsScanHu = !string.IsNullOrWhiteSpace(inspectResult.HuId); } else if (matchSnRule.Code == (int)CodeMaster.DocumentsType.REJ) { var rejectDetail = genericMgr.FindAll<RejectDetail>(selectRejectDetail, new object[] { miscOrderMaster.ReferenceNo, com.Sconit.CodeMaster.HandleResult.Scrap }).First(); miscOrderMaster.Location = rejectDetail.CurrentLocation; miscOrderMaster.IsScanHu = !string.IsNullOrWhiteSpace(rejectDetail.HuId); } ViewBag.ReferenceDocumentsType = matchSnRule.Code; miscOrderMaster.ReferenceDocumentsType = matchSnRule.Code; } } catch (Exception ex) { SaveErrorMessage(Resources.EXT.ControllerLan.Con_CanNotFindRefDetail + ex.Message); } miscOrderMaster.QualityType = CodeMaster.QualityType.Reject; } return View(miscOrderMaster); } [AcceptVerbs(HttpVerbs.Post)] [GridAction] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New")] public ActionResult CreateMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string locations, string qtys) { try { CreateNewMiscOrder(miscOrderMaster, sequences, items, locations, qtys); return View("Edit", miscOrderMaster); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } [AcceptVerbs(HttpVerbs.Post)] [GridAction] [SconitAuthorize(Permissions = "Url_ExProductionOrder_ScrapNew")] public ActionResult CreateScrapMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string locations, string qtys) { try { string[] ItemsArray = items.Split(','); for (int i = 0; i < ItemsArray.Length; i++) { var item = this.genericMgr.FindById<Item>(ItemsArray[i]); if (item.ItemCategory != "ZHJC") { SaveErrorMessage(Resources.EXT.ControllerLan.Con_ExistNonHalfFinishGoodsType); return Json(null); } } CreateNewMiscOrder(miscOrderMaster, sequences, items, locations, qtys, true); return View("ScrapEdit", miscOrderMaster); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } private void CreateNewMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string locations, string qtys, bool isScrap = false) { if (items == string.Empty && !miscOrderMaster.IsScanHu) { throw new BusinessException(Resources.EXT.ControllerLan.Con_DetailBeEmptyCanNotCreate); } MiscOrderMoveType miscOrderMoveType = genericMgr.FindAll<MiscOrderMoveType>( "from MiscOrderMoveType as m where m.MoveType=? and m.SubType=? ", new object[] { miscOrderMaster.MoveType, com.Sconit.CodeMaster.MiscOrderSubType.COST })[0]; //页面不加生效日期 //miscOrderMaster.EffectiveDate = DateTime.Now; miscOrderMaster.Type = miscOrderMoveType.IOType; if (!isScrap) { miscOrderMaster.SubType = miscOrderMoveType.SubType; } miscOrderMaster.MoveType = miscOrderMoveType.MoveType; miscOrderMaster.CancelMoveType = miscOrderMoveType.CancelMoveType; miscOrderMaster.Status = CodeMaster.MiscOrderStatus.Create; //miscOrderMaster.QualityType = CodeMaster.QualityType.Qualified; miscOrderMaster.Region = this.genericMgr.FindById<Location>(miscOrderMaster.Location).Region; if (!miscOrderMaster.IsScanHu) { string[] SequencesArray = sequences.Split(','); string[] ItemsArray = items.Split(','); string[] OrderedQtysArray = qtys.Split(','); string[] LocationsArray = locations.Split(','); IList<MiscOrderDetail> miscOrderDetails = new List<MiscOrderDetail>(); for (int i = 0; i < ItemsArray.Length; i++) { var item = this.genericMgr.FindById<Item>(ItemsArray[i]); MiscOrderDetail od = new MiscOrderDetail(); od.Sequence = Convert.ToInt32(SequencesArray[i]); od.Item = item.Code; od.ItemDescription = item.Description; od.ReferenceItemCode = item.ReferenceCode; od.Uom = item.Uom; od.BaseUom = item.Uom; od.UnitCount = item.UnitCount; od.UnitQty = 1; od.Qty = Convert.ToDecimal(OrderedQtysArray[i]); if (!string.IsNullOrWhiteSpace(LocationsArray[i])) { od.Location = LocationsArray[i]; } miscOrderDetails.Add(od); } miscOrderMaster.MiscOrderDetails = (from p in miscOrderDetails group p by new { p.Item, p.ItemDescription, p.ReferenceItemCode, p.Uom, p.BaseUom, p.UnitCount, p.Location } into g select new MiscOrderDetail { Sequence = g.Max(p => p.Sequence), Item = g.Key.Item, ItemDescription = g.Key.ItemDescription, ReferenceItemCode = g.Key.ReferenceItemCode, Uom = g.Key.Uom, BaseUom = g.Key.BaseUom, UnitCount = g.Key.UnitCount, UnitQty = 1, Location = g.Key.Location, Qty = g.Sum(p => p.Qty), }).ToList(); } if (miscOrderMaster.ReferenceDocumentsType > 0) { miscOrderMgr.QuickCreateMiscOrder(miscOrderMaster, miscOrderMaster.EffectiveDate); } else { miscOrderMgr.CreateMiscOrder(miscOrderMaster); } ViewBag.miscOrderNo = miscOrderMaster.MiscOrderNo; ViewBag.Location = miscOrderMaster.Location; SaveSuccessMessage(Resources.EXT.ControllerLan.Con_CreateSuccessfully); } #endregion #region Save MiscOrderDet for scanned HuIds. [AcceptVerbs(HttpVerbs.Post)] [GridAction] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New")] public string _SaveMiscOrderDetail( [Bind(Prefix = "updated")]IEnumerable<MiscOrderDetail> updatedMiscOrderDetails, [Bind(Prefix = "deleted")]IEnumerable<MiscOrderLocationDetail> deletedMiscOrderDetails, string MiscOrderNo, string moveType) { try { IList<MiscOrderDetail> newMiscOrderDetailList = new List<MiscOrderDetail>(); IList<MiscOrderDetail> updateMiscOrderDetailList = new List<MiscOrderDetail>(); if (updatedMiscOrderDetails != null) { foreach (var miscOrderDetail in updatedMiscOrderDetails) { if (CheckMiscOrderDetail(miscOrderDetail, moveType, (int)com.Sconit.CodeMaster.MiscOrderType.GI)) { updateMiscOrderDetailList.Add(miscOrderDetail); } } } miscOrderMgr.BatchUpdateMiscLocationOrderDetails(MiscOrderNo, newMiscOrderDetailList, updateMiscOrderDetailList, (IList<MiscOrderLocationDetail>)deletedMiscOrderDetails); return MiscOrderNo; } catch (BusinessException ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.Write(ex.GetMessages()[0].GetMessageString()); return string.Empty; } } #endregion #region CheckMiscOrderDetail [GridAction] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New")] public bool CheckMiscOrderDetail(MiscOrderDetail miscOrderDetail, string MoveType, int IOType) { bool isValid = true; if (!string.IsNullOrEmpty(MoveType)) { MiscOrderMoveType miscOrderMoveType = genericMgr.FindAll<MiscOrderMoveType>("from MiscOrderMoveType as m where m.MoveType=? and m.IOType=?", new object[] { MoveType, IOType })[0]; if (miscOrderMoveType.CheckEBELN && miscOrderDetail.EBELN == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_PurchaseOrderNumberCanNotBeEmpty); } else if (miscOrderMoveType.CheckEBELP && miscOrderDetail.EBELP == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_PurchaseOrderRowNumberCanNotBeEmpty); } else if (miscOrderMoveType.CheckReserveLine && miscOrderDetail.ReserveLine == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_ReserveRowCanNotBeEmpty); } else if (miscOrderMoveType.CheckReserveNo && miscOrderDetail.ReserveNo == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_ReserveNumberCanNotBeEmpty); } else if (miscOrderDetail.Qty == 0) { throw new BusinessException(Resources.EXT.ControllerLan.Con_QuantityCanNotBeEmpty); } else if (miscOrderDetail.Item == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_ItemCanNotBeEmpty); } else { //IList<MiscOrderDetail> MiscOrderDetailist = genericMgr.FindAll<MiscOrderDetail>("from MiscOrderDetail as m where m.Item=? and m.MiscOrderNo=?", new object[] { miscOrderDetail.Item, miscOrderDetail.MiscOrderNo }); //if (MiscOrderDetailist.Count > 0 ) //{ // throw new BusinessException("物料已经存在"); //} } } return isValid; } #endregion #region MisOrderDetailScanHu public ActionResult _MiscOrderDetailIsScanHu(string MiscOrderNo, string MoveType, string Status) { //MiscOrderMoveType MiscOrderMoveType = genericMgr.FindAll<MiscOrderMoveType>("from MiscOrderMoveType as m where m.MoveType=? and m.IOType=?", new object[] { MoveType, com.Sconit.CodeMaster.MiscOrderType.GI })[0]; ViewBag.MoveType = MoveType; ViewBag.MiscOrderNo = MiscOrderNo; ViewBag.Status = Status; //ViewBag.ReserveLine = MiscOrderMoveType.CheckReserveLine; //ViewBag.ReserveNo = MiscOrderMoveType.CheckReserveNo; //ViewBag.EBELN = MiscOrderMoveType.CheckEBELN; //ViewBag.EBELP = MiscOrderMoveType.CheckEBELP; return PartialView(); } [GridAction(EnableCustomBinding = true)] public ActionResult _SelectMiscOrderLocationDetail(string MiscOrderNo, string MoveType) { ViewBag.MiscOrderNo = MiscOrderNo; IList<MiscOrderDetail> MiscOrderDetailList = genericMgr.FindAll<MiscOrderDetail>("from MiscOrderDetail as m where m.MiscOrderNo=?", MiscOrderNo); IList<MiscOrderLocationDetail> miscOrderLocationDetailList = genericMgr.FindAll<MiscOrderLocationDetail>("from MiscOrderLocationDetail as m where m.MiscOrderNo=?", MiscOrderNo); foreach (MiscOrderLocationDetail miscOrderLocationDetail in miscOrderLocationDetailList) { MiscOrderDetail miscOrderDetail = MiscOrderDetailList.Where(m => m.Id == miscOrderLocationDetail.MiscOrderDetailId).ToList().First(); //miscOrderLocationDetail.Id = miscOrderDetail.Id; miscOrderLocationDetail.ReferenceItemCode = miscOrderDetail.ReferenceItemCode; miscOrderLocationDetail.ItemDescription = miscOrderDetail.ItemDescription; miscOrderLocationDetail.UnitCount = miscOrderDetail.UnitCount; miscOrderLocationDetail.Location = miscOrderDetail.Location; miscOrderLocationDetail.ReserveNo = miscOrderDetail.ReserveNo; miscOrderLocationDetail.ReserveLine = miscOrderDetail.ReserveLine; miscOrderLocationDetail.EBELN = miscOrderDetail.EBELN; miscOrderLocationDetail.EBELP = miscOrderDetail.EBELP; } return View(new GridModel(miscOrderLocationDetailList)); } #endregion #region MiscOrderDetail [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New,Url_ExProductionOrder_ScrapNew")] public ActionResult _MiscOrderDetail(string miscOrderNo, string location, string referenceNo, int? referenceDocumentsType) { ViewBag.ReferenceDocumentsType = 0; ViewBag.IsScanHu = false; if (!string.IsNullOrEmpty(miscOrderNo)) { MiscOrderMaster miscOrder = genericMgr.FindById<MiscOrderMaster>(miscOrderNo); ViewBag.Status = miscOrder.Status; ViewBag.IsCreate = miscOrder.Status == com.Sconit.CodeMaster.MiscOrderStatus.Create ? true : false; ViewBag.IsScanHu = miscOrder.IsScanHu; } else { ViewBag.IsCreate = true; if (!string.IsNullOrEmpty(referenceNo) && referenceDocumentsType.HasValue) { ViewBag.ReferenceDocumentsType = referenceDocumentsType; } } ViewBag.ReferenceNo = referenceNo; ViewBag.MiscOrderNo = miscOrderNo; ViewBag.Location = location; ViewBag.Coupled = true; return PartialView(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_New,Url_ExProductionOrder_ScrapNew")] public ActionResult _SelectMiscOrderDetail(string miscOrderNo, string location, string referenceNo) { IList<MiscOrderDetail> miscOrderDetailList = new List<MiscOrderDetail>(); try { var multiRows = systemMgr.GetEntityPreferenceValue(Entity.SYS.EntityPreference.CodeEnum.GridDefaultMultiRowsCount); int v; int.TryParse(multiRows, out v); if (!string.IsNullOrEmpty(miscOrderNo)) { v = -1; miscOrderDetailList = genericMgr.FindAll<MiscOrderDetail>("from MiscOrderDetail as m where m.MiscOrderNo=? ", miscOrderNo); } else if (!string.IsNullOrEmpty(referenceNo)) { v = -1; var snRuleList = this.genericMgr.FindAllIn<SNRule> (" from SNRule where Code in(?", new object[]{ CodeMaster.DocumentsType.REJ , CodeMaster.DocumentsType.INS }); var matchSnRule = snRuleList.FirstOrDefault(p => referenceNo.StartsWith(p.PreFixed)); if (matchSnRule == null) { throw new BusinessException(Resources.EXT.ControllerLan.Con_NotSupportTheTypeOrderReference); } if (matchSnRule.Code == (int)CodeMaster.DocumentsType.INS) { miscOrderDetailList = genericMgr.FindAll<InspectResult>(selectInspectResult, new object[] { referenceNo, com.Sconit.CodeMaster.HandleResult.Scrap, false }) .GroupBy(p => new { p.Item, p.Uom, p.CurrentLocation }, (k, g) => new { k, g }) .Select(p => new MiscOrderDetail { Item = p.k.Item, ItemDescription = p.g.First().ItemDescription, ReferenceItemCode = p.g.First().ReferenceItemCode, Uom = p.k.Uom, Location = p.k.CurrentLocation, Qty = p.g.Sum(q => q.TobeHandleQty) * p.g.First().UnitQty }).ToList(); } else if (matchSnRule.Code == (int)CodeMaster.DocumentsType.REJ) { miscOrderDetailList = genericMgr.FindAll<RejectDetail>(selectRejectDetail, new object[] { referenceNo, com.Sconit.CodeMaster.HandleResult.Scrap }) .GroupBy(p => new { p.Item, p.Uom, p.CurrentLocation }, (k, g) => new { k, g }) .Select(p => new MiscOrderDetail { Item = p.k.Item, ItemDescription = p.g.First().ItemDescription, ReferenceItemCode = p.g.First().ReferenceItemCode, Uom = p.k.Uom, Location = p.k.CurrentLocation, Qty = p.g.Sum(q => q.TobeHandleQty) * p.g.First().UnitQty }).ToList(); } ViewBag.DocumentsType = matchSnRule.Code; } int seq = 10; foreach (var miscOrderDetail in miscOrderDetailList) { miscOrderDetail.Sequence = seq; seq += 10; } //int seq = miscOrderDetailList.Count > 0 ? miscOrderDetailList.Max(p => p.Sequence) : 10; if (v > 0) { for (int i = 0; i < v; i++) { var miscOrderDetail = new MiscOrderDetail(); miscOrderDetail.Sequence = seq + i * 10; miscOrderDetailList.Add(miscOrderDetail); } } ViewBag.Location = location; } catch (Exception ex) { SaveErrorMessage(ex); } return PartialView(new GridModel(miscOrderDetailList)); } public ActionResult _WebOrderDetail(string Code) { if (!string.IsNullOrEmpty(Code)) { WebOrderDetail webOrderDetail = new WebOrderDetail(); Item item = genericMgr.FindById<Item>(Code); if (item != null) { webOrderDetail.Item = item.Code; webOrderDetail.ItemDescription = item.Description; webOrderDetail.UnitCount = item.UnitCount; webOrderDetail.Uom = item.Uom; webOrderDetail.ReferenceItemCode = item.ReferenceCode; } return this.Json(webOrderDetail); } return null; } #endregion #region Edit&ScrapEdit [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Edit")] public ActionResult Edit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { MiscOrderMaster miscOrderMaster = this.genericMgr.FindById<MiscOrderMaster>(id); ViewBag.Flow = miscOrderMaster.Flow; ViewBag.Location = miscOrderMaster.Location; if (miscOrderMaster.IsScanHu && this.CurrentUser.Code == "su" && miscOrderMaster.Status == CodeMaster.MiscOrderStatus.Create) { ViewBag.IsShowImportHu = true; } return View(miscOrderMaster); } } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapEdit")] public ActionResult ScrapEdit(string id) { if (string.IsNullOrEmpty(id)) { return HttpNotFound(); } else { MiscOrderMaster miscOrderMaster = this.genericMgr.FindById<MiscOrderMaster>(id); ViewBag.Flow = miscOrderMaster.Flow; ViewBag.Location = miscOrderMaster.Location; return View(miscOrderMaster); } } [HttpPost] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Edit")] public ActionResult EditMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string qtys) { try { var oldMiscOrderMaster = EditnewMiscOrder(miscOrderMaster, sequences, items, qtys); return View("Edit", oldMiscOrderMaster); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } [HttpPost] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapEdit")] public ActionResult ScrapEditMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string qtys) { try { string[] ItemsArray = items.Split(','); for (int i = 0; i < ItemsArray.Length; i++) { var item = this.genericMgr.FindById<Item>(ItemsArray[i]); if (item.ItemCategory != "ZHJC") { SaveErrorMessage(Resources.EXT.ControllerLan.Con_ExistNonHalfFinishGoodsType); return Json(null); } } var oldMiscOrderMaster = EditnewMiscOrder(miscOrderMaster, sequences, items, qtys); return View("ScrapEdit", oldMiscOrderMaster); } catch (Exception ex) { SaveErrorMessage(ex); return Json(null); } } private MiscOrderMaster EditnewMiscOrder(MiscOrderMaster miscOrderMaster, string sequences, string items, string qtys) { #region master 只能改备注字段 MiscOrderMaster oldMiscOrderMaster = this.genericMgr.FindById<MiscOrderMaster>(miscOrderMaster.MiscOrderNo); oldMiscOrderMaster.Note = miscOrderMaster.Note; oldMiscOrderMaster.ReferenceNo = miscOrderMaster.ReferenceNo; oldMiscOrderMaster.EffectiveDate = miscOrderMaster.EffectiveDate; oldMiscOrderMaster.CostCenter = oldMiscOrderMaster.SubType == CodeMaster.MiscOrderSubType.MES26 ? "212" : miscOrderMaster.CostCenter; oldMiscOrderMaster.GeneralLedger = miscOrderMaster.GeneralLedger; if (oldMiscOrderMaster.IsScanHu) { genericMgr.Update(oldMiscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_SavedSuccessfully); ViewBag.Location = oldMiscOrderMaster.Location; return oldMiscOrderMaster; } #endregion #region Detail IList<MiscOrderDetail> oldMiscOrderDetailList = this.genericMgr.FindAll<MiscOrderDetail> ("select d from MiscOrderDetail as d where d.MiscOrderNo=? ", miscOrderMaster.MiscOrderNo); IList<MiscOrderDetail> newMiscOrderDetailList = new List<MiscOrderDetail>(); IList<MiscOrderDetail> updateMiscOrderDetailList = new List<MiscOrderDetail>(); IList<MiscOrderDetail> deletedMiscOrderDetails = new List<MiscOrderDetail>(); IList<MiscOrderDetail> miscOrderDetails = new List<MiscOrderDetail>(); string[] SequencesArray = sequences.Split(','); string[] ItemsArray = items.Split(','); string[] OrderedQtysArray = qtys.Split(','); for (int i = 0; i < ItemsArray.Length; i++) { var item = this.genericMgr.FindById<Item>(ItemsArray[i]); MiscOrderDetail od = new MiscOrderDetail(); od.Sequence = Convert.ToInt32(SequencesArray[i]); od.Item = item.Code; od.ItemDescription = item.Description; od.ReferenceItemCode = item.ReferenceCode; od.Uom = item.Uom; od.BaseUom = item.Uom; od.UnitCount = item.UnitCount; od.UnitQty = 1; od.Qty = Convert.ToDecimal(OrderedQtysArray[i]); miscOrderDetails.Add(od); } var groupMiscOrderDetails = from p in miscOrderDetails group p by new { p.Item, p.ItemDescription, p.ReferenceItemCode, p.Uom, p.BaseUom, p.UnitCount, } into g select new MiscOrderDetail { Sequence = g.Max(p => p.Sequence), Item = g.Key.Item, ItemDescription = g.Key.ItemDescription, ReferenceItemCode = g.Key.ReferenceItemCode, Uom = g.Key.Uom, BaseUom = g.Key.BaseUom, UnitCount = g.Key.UnitCount, UnitQty = 1, Qty = g.Sum(p => p.Qty), }; foreach (var detail in groupMiscOrderDetails) { var oldDetail = oldMiscOrderDetailList.FirstOrDefault(p => p.Item == detail.Item); if (oldDetail == null) { newMiscOrderDetailList.Add(detail); } else if (oldDetail.Qty != detail.Qty) { oldDetail.Qty = detail.Qty; updateMiscOrderDetailList.Add(oldDetail); } } foreach (var oldDetail in oldMiscOrderDetailList) { var detail = groupMiscOrderDetails.FirstOrDefault(p => p.Item == oldDetail.Item); if (detail == null) { deletedMiscOrderDetails.Add(oldDetail); } } #endregion genericMgr.Update(oldMiscOrderMaster); miscOrderMgr.BatchUpdateMiscOrderDetails(oldMiscOrderMaster, newMiscOrderDetailList, updateMiscOrderDetailList, deletedMiscOrderDetails); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_SavedSuccessfully); ViewBag.Location = oldMiscOrderMaster.Location; return oldMiscOrderMaster; } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Confirm")] public ActionResult btnClose(string id) { try { MiscOrderMaster miscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); IList<MiscOrderDetail> miscOrderDetailList = genericMgr.FindAll<MiscOrderDetail> ("from MiscOrderDetail as m where m.MiscOrderNo=?", miscOrderMaster.MiscOrderNo); if (miscOrderDetailList.Count < 1) { SaveErrorMessage(Resources.EXT.ControllerLan.Con_DetailBeEmptyCanNotExecuteConfirm); } else { foreach (var miscOrderDetail in miscOrderDetailList) { CheckMiscOrderDetail(miscOrderMaster, miscOrderDetail); } miscOrderMgr.CloseMiscOrder(miscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_ConfirmSuccessfully); } } catch (Exception ex) { SaveErrorMessage(ex.Message); } return RedirectToAction("Edit/" + id); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapConfirm")] public ActionResult btnCloseScrap(string id) { try { MiscOrderMaster miscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); IList<MiscOrderDetail> miscOrderDetailList = genericMgr.FindAll<MiscOrderDetail> ("from MiscOrderDetail as m where m.MiscOrderNo=?", miscOrderMaster.MiscOrderNo); if (miscOrderDetailList.Count < 1) { SaveErrorMessage(Resources.EXT.ControllerLan.Con_DetailBeEmptyCanNotExecuteConfirm); } else { foreach (var miscOrderDetail in miscOrderDetailList) { CheckMiscOrderDetail(miscOrderMaster, miscOrderDetail); } miscOrderMgr.CloseMiscOrder(miscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_ConfirmSuccessfully); } } catch (BusinessException ex) { SaveErrorMessage(ex.GetMessages()[0].GetMessageString()); } return RedirectToAction("ScrapEdit/" + id); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Edit")] public ActionResult btnDelete(string id) { try { MiscOrderMaster MiscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); miscOrderMgr.DeleteMiscOrder(MiscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_DeletedSuccessfully); } catch (BusinessException ex) { SaveErrorMessage(ex.GetMessages()[0].GetMessageString()); } return RedirectToAction("List"); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapEdit")] public ActionResult btnDeletescrap(string id) { try { MiscOrderMaster MiscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); miscOrderMgr.DeleteMiscOrder(MiscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_DeletedSuccessfully); } catch (BusinessException ex) { SaveErrorMessage(ex.GetMessages()[0].GetMessageString()); } return RedirectToAction("ScrapNew"); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Confirm")] public ActionResult btnCancel(string id) { try { MiscOrderMaster MiscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); miscOrderMgr.CancelMiscOrder(MiscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_CancelledSuccessfully); } catch (Exception ex) { SaveErrorMessage(ex); } return RedirectToAction("Edit/" + id); } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapConfirm")] public ActionResult btnCancelScrap(string id) { try { MiscOrderMaster MiscOrderMaster = genericMgr.FindById<MiscOrderMaster>(id); miscOrderMgr.CancelMiscOrder(MiscOrderMaster); SaveSuccessMessage(Resources.EXT.ControllerLan.Con_CancelledSuccessfully); } catch (Exception ex) { SaveErrorMessage(ex); } return RedirectToAction("ScrapEdit/" + id); } #endregion public void SaveToClient(string miscOrderNo) { try { MiscOrderMaster miscOrderMaster = queryMgr.FindById<MiscOrderMaster>(miscOrderNo); FillCodeDetailDescription<MiscOrderMaster>(miscOrderMaster); IList<MiscOrderDetail> miscOrderDetails = queryMgr.FindAll<MiscOrderDetail> ("from MiscOrderDetail where MiscOrderNo=? ", miscOrderNo); PrintMiscOrderMaster printOrderMaster = Mapper.Map<MiscOrderMaster, PrintMiscOrderMaster>(miscOrderMaster); printOrderMaster.Title = this.genericMgr.FindAll<MiscOrderMoveType> ("from MiscOrderMoveType where MoveType=? ", miscOrderMaster.MoveType).First().Description; printOrderMaster.Title = printOrderMaster.Title; IList<PrintMiscOrderDetail> printOrderDetails = Mapper.Map<IList<MiscOrderDetail>, IList<PrintMiscOrderDetail>>(miscOrderDetails); IList<object> data = new List<object>(); printOrderMaster.CostCenter = string.IsNullOrWhiteSpace(printOrderMaster.CostCenter) ? "" : genericMgr.FindById<CostCenter>(printOrderMaster.CostCenter).Description+"("+printOrderMaster.CostCenter+")"; data.Add(printOrderMaster); data.Add(printOrderDetails); reportGen.WriteToClient("MiscOrder.xls", data, printOrderMaster.MiscOrderNo + ".xls"); } catch (Exception ex) { SaveErrorMessage(ex.Message); } } public string Print(string miscOrderNo) { MiscOrderMaster miscOrderMaster = queryMgr.FindById<MiscOrderMaster>(miscOrderNo); FillCodeDetailDescription<MiscOrderMaster>(miscOrderMaster); IList<MiscOrderDetail> miscOrderDetails = queryMgr.FindAll<MiscOrderDetail> ("from MiscOrderDetail where MiscOrderNo=? ", miscOrderNo); PrintMiscOrderMaster printOrderMaster = Mapper.Map<MiscOrderMaster, PrintMiscOrderMaster>(miscOrderMaster); printOrderMaster.Title = this.genericMgr.FindAll<MiscOrderMoveType> ("from MiscOrderMoveType where MoveType=? ", miscOrderMaster.MoveType).First().Description; printOrderMaster.Title = printOrderMaster.Title; IList<PrintMiscOrderDetail> printOrderDetails = Mapper.Map<IList<MiscOrderDetail>, IList<PrintMiscOrderDetail>>(miscOrderDetails); IList<object> data = new List<object>(); printOrderMaster.CostCenter = string.IsNullOrWhiteSpace(printOrderMaster.CostCenter) ? "" : genericMgr.FindById<CostCenter>(printOrderMaster.CostCenter).Description + "(" + printOrderMaster.CostCenter + ")"; data.Add(printOrderMaster); data.Add(printOrderDetails); string reportFileUrl = reportGen.WriteToFile("MiscOrder.xls", data); return reportFileUrl; } [SconitAuthorize(Permissions = "Url_ExProductionOrder_ScrapNew")] public ActionResult ScrapNew() { return View(); } #endregion #region private method private bool CheckMiscOrderDetail(MiscOrderMaster miscOrderMaster, MiscOrderDetail miscOrderDetail) { if (string.IsNullOrEmpty(miscOrderDetail.Item)) { throw new BusinessException(Resources.EXT.ControllerLan.Con_DetailRowItemCanNotBeEmpty); } if (miscOrderDetail.Qty == 0) { throw new BusinessException(Resources.EXT.ControllerLan.Con_DetailRowGapQuantityCanNotBeEmpty); } if (miscOrderDetail.Qty < 0) { //throw new BusinessException("明细行差异数量不能小于0的数字"); } return true; } private SearchStatementModel PrepareSearchStatement(GridCommand command, MiscOrderSearchModel searchModel) { string whereStatement = string.Format("where m.SubType={0} ", searchModel.SearchType == "CostCenter" ? (int)CodeMaster.MiscOrderSubType.COST : (int)CodeMaster.MiscOrderSubType.MES26); IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("MiscOrderNo", searchModel.MiscOrderNo, HqlStatementHelper.LikeMatchMode.Anywhere, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Status", searchModel.Status, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("MoveType", searchModel.MoveType, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Location", searchModel.Location, "m", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("Note", searchModel.Note, HqlStatementHelper.LikeMatchMode.Anywhere, "m", ref whereStatement, param); //HqlStatementHelper.AddLikeStatement("Remarks3", searchModel.Remarks3, HqlStatementHelper.LikeMatchMode.Anywhere, "m", ref whereStatement, param); //HqlStatementHelper.AddLikeStatement("Remarks4", searchModel.Remarks4, HqlStatementHelper.LikeMatchMode.Anywhere, "m", ref whereStatement, param); HqlStatementHelper.AddEqStatement("CreateUserName", searchModel.CreateUserName, "m", ref whereStatement, param); if (searchModel.StartDate != null & searchModel.EndDate != null) { HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.StartDate, searchModel.EndDate, "m", ref whereStatement, param); } else if (searchModel.StartDate != null & searchModel.EndDate == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartDate, "m", ref whereStatement, param); } else if (searchModel.StartDate == null & searchModel.EndDate != null) { HqlStatementHelper.AddLeStatement("CreateDate", searchModel.EndDate, "m", ref whereStatement, param); } if (command.SortDescriptors.Count > 0) { if (command.SortDescriptors[0].Member == "StatusDescription") { command.SortDescriptors[0].Member = "Status"; } } string sortingStatement = string.Empty; if (command.SortDescriptors.Count == 0) { sortingStatement = " order by CreateDate desc"; } else { sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } #endregion public string Import(string miscOrderNo, string huIds) { try { IList<string> huIdList = huIds.Trim() .Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); miscOrderMgr.BatchUpdateMiscOrderDetails(miscOrderNo, huIdList, null); return Resources.EXT.ControllerLan.Con_ImportSuccessfully; } catch (Exception ex) { return ex.Message; } } [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_Edit")] public ActionResult ImportMiscOrderDetail(IEnumerable<HttpPostedFileBase> attachments, string miscOrderNo) { try { foreach (var file in attachments) { if (miscOrderNo == "NotRelyOnMiscOrdNo") { miscOrderMgr.Import201202MiscOrder(file.InputStream, Resources.EXT.ControllerLan.Con_BatchImportCostCenter, "201", "202", "CostCenter"); } else { miscOrderMgr.CreateMiscOrderDetailFromXls(file.InputStream, miscOrderNo); } SaveSuccessMessage(Resources.EXT.ControllerLan.Con_ImportSuccessfully); } } catch (BusinessException ex) { SaveBusinessExceptionMessage(ex); } catch (Exception ex) { SaveErrorMessage(Resources.EXT.ControllerLan.Con_ImportUnsuccessfully+" - " + ex.Message); } return Content(string.Empty); } #region Export master search [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_ScrapView,Url_CostCenterMiscOrderDet_View")] [GridAction(EnableCustomBinding = true)] public void ExportMstr(MiscOrderSearchModel searchModel) { int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage)); GridCommand command = new GridCommand(); command.Page = 1; command.PageSize = !this.CheckSearchModelIsNull(searchModel) ? 0 : value; this.GetCommand(ref command, searchModel); if (!this.CheckSearchModelIsNull(searchModel)) { return; } SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); ExportToXLS<MiscOrderMaster>("Master.xls", GetAjaxPageData<MiscOrderMaster>(searchStatementModel, command).Data.ToList()); } #endregion #region Detail search [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_CostCenterMiscOrderDet_View")] public ActionResult _AjaxDetailList(GridCommand command, MiscOrderSearchModel searchModel) { this.GetCommand(ref command, searchModel); string sql = PrepareSqlSearchStatement(searchModel); int total = this.genericMgr.FindAllWithNativeSql<int>("select count(*) from (" + sql + ") as r1").First(); string sortingStatement = string.Empty; #region if (command.SortDescriptors.Count != 0) { if (command.SortDescriptors[0].Member == "CreateDate") { command.SortDescriptors[0].Member = "CreateDate"; } else if (command.SortDescriptors[0].Member == "Item") { command.SortDescriptors[0].Member = "Item"; } else if (command.SortDescriptors[0].Member == "MiscOrderNo") { command.SortDescriptors[0].Member = "MiscOrderNo"; } else if (command.SortDescriptors[0].Member == "Location") { command.SortDescriptors[0].Member = "Location"; } else if (command.SortDescriptors[0].Member == "Qty") { command.SortDescriptors[0].Member = "Qty"; } sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); TempData["sortingStatement"] = sortingStatement; } #endregion if (string.IsNullOrWhiteSpace(sortingStatement)) { sortingStatement = " order by CreateDate,MiscOrderNo"; } sql = string.Format("select * from (select RowId=ROW_NUMBER()OVER({0}),r1.* from ({1}) as r1 ) as rt where rt.RowId between {2} and {3}", sortingStatement, sql, (command.Page - 1) * command.PageSize + 1, command.PageSize * command.Page); IList<object[]> searchResult = this.genericMgr.FindAllWithNativeSql<object[]>(sql); IList<MiscOrderDetail> MiscOrderDetailList = new List<MiscOrderDetail>(); if (searchResult != null && searchResult.Count > 0) { #region MiscOrderDetailList = (from tak in searchResult select new MiscOrderDetail { BaseUom = (string)tak[1], CreateDate = (DateTime)tak[2], CreateUserId = (int)tak[3], CreateUserName = (string)tak[4], EBELN = (string)tak[5], EBELP = (string)tak[6], Item = (string)tak[7], ItemDescription = (string)tak[8], LastModifyDate = (DateTime)tak[9], LastModifyUserId = (int)tak[10], LastModifyUserName = (string)tak[11], Location = (string)tak[12], ManufactureParty = (string)tak[13], MiscOrderNo = (string)tak[14], Qty = (decimal)tak[15], ReferenceItemCode = (string)tak[16], Remark = (string)tak[17], ReserveLine = (string)tak[18], ReserveNo = (string)tak[19], Sequence = (int)tak[20], UnitCount = (decimal)tak[21], UnitQty = (decimal)tak[22], Uom = (string)tak[23], WMSSeq = (string)tak[24], WorkHour = (decimal)tak[25], Note = (string)tak[26], EffectiveDate = (DateTime)tak[27], MoveType = (string)tak[28], Flow = (string)tak[29], WBS = (string)tak[30], CostCenter = (string)tak[31], }).ToList(); #endregion } GridModel<MiscOrderDetail> gridModel = new GridModel<MiscOrderDetail>(); gridModel.Total = total; gridModel.Data = MiscOrderDetailList; return PartialView(gridModel); } #endregion #region private string PrepareSqlSearchStatement(MiscOrderSearchModel searchModel) { string whereStatement = @" select d.BaseUom,d.CreateDate,d.CreateUser,d.CreateUserNm,d.EBELN,d.EBELP,d.Item, i.Desc1 As ItemDescription,d.LastModifyDate,d.LastModifyUser,d.LastModifyUserNm,isnull(d.Location,m.Location) As Location,d.ManufactureParty,d.MiscOrderNo,d.Qty ,i.RefCode As ReferenceItemCode,d.Remark,d.ReserveLine,d.ReserveNo,d.Seq,d.UC As UnitCount,d.UnitQty,d.Uom,d.WMSSeq,d.WorkHour ,m.Note,m.effDate,m.MoveType,m.Flow,m.WBS,e.Desc1 As CostCenter from ORD_MiscOrderDet d with(nolock) inner join ORD_MiscOrderMstr m with(nolock) on d.MiscOrderNo=m.MiscOrderNo inner join MD_Item i On d.Item =i.Code left join CUST_CostCenter e on m.CostCenter=e.Code where 1=1 "; if (!string.IsNullOrEmpty(searchModel.MiscOrderNo)) { whereStatement += string.Format(" and m.MiscOrderNo = '{0}'", searchModel.MiscOrderNo); } if (!string.IsNullOrEmpty(searchModel.CostCenter)) { whereStatement += string.Format(" and m.CostCenter = '{0}'", searchModel.CostCenter); } if (!string.IsNullOrEmpty(searchModel.CreateUserName)) { whereStatement += string.Format(" and d.CreateUserNm = '{0}'", searchModel.CreateUserName); } if (!string.IsNullOrEmpty(searchModel.Flow)) { whereStatement += string.Format(" and m.Flow = '{0}'", searchModel.Flow); } if (!string.IsNullOrEmpty(searchModel.Item)) { whereStatement += string.Format(" and d.Item = '{0}'", searchModel.Item); } if (!string.IsNullOrEmpty(searchModel.Note)) { whereStatement += string.Format(" and m.Note = '{0}'", searchModel.Note); } if (searchModel.Location != null) { whereStatement += string.Format(" and m.Location ={0}", searchModel.Location); } if (searchModel.GeneralLedger != null) { whereStatement += string.Format(" and m.GeneralLedger ={0}", searchModel.GeneralLedger); } if (searchModel.Status != null) { whereStatement += string.Format(" and m.Status ={0}", searchModel.Status); } if (searchModel.MoveType != null) { whereStatement += string.Format(" and m.MoveType ={0}", searchModel.MoveType); } whereStatement += string.Format(" and m.SubType ={0}", searchModel.SearchType == "CostCenter" ? (int)CodeMaster.MiscOrderSubType.COST : (int)CodeMaster.MiscOrderSubType.MES26); if (searchModel.StartDate != null && searchModel.EndDate != null) { whereStatement += string.Format(" and m.CreateDate between '{0}' and '{1}' ", searchModel.StartDate, searchModel.EndDate); } else if (searchModel.StartDate != null && searchModel.EndDate == null) { whereStatement += " and m.CreateDate >='" + searchModel.StartDate + "'"; } else if (searchModel.StartDate == null && searchModel.EndDate != null) { whereStatement += " and m.CreateDate <= '" + searchModel.EndDate + "'"; } return whereStatement; } #endregion #region Export Detail [SconitAuthorize(Permissions = "Url_CostCenterMiscOrder_ScrapView,Url_CostCenterMiscOrder_View")] [GridAction(EnableCustomBinding = true)] public void ExportDet(MiscOrderSearchModel searchModel) { int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage)); GridCommand command = new GridCommand(); command.Page = 1; command.PageSize = !this.CheckSearchModelIsNull(searchModel) ? 0 : value; this.GetCommand(ref command, searchModel); if (!this.CheckSearchModelIsNull(searchModel)) { return; } string sql = PrepareSqlSearchStatement(searchModel); int total = this.genericMgr.FindAllWithNativeSql<int>("select count(*) from (" + sql + ") as r1").First(); string sortingStatement = string.Empty; #region sort condition if (command.SortDescriptors.Count != 0) { if (command.SortDescriptors[0].Member == "CreateDate") { command.SortDescriptors[0].Member = "CreateDate"; } else if (command.SortDescriptors[0].Member == "Item") { command.SortDescriptors[0].Member = "Item"; } else if (command.SortDescriptors[0].Member == "MiscOrderNo") { command.SortDescriptors[0].Member = "MiscOrderNo"; } else if (command.SortDescriptors[0].Member == "Location") { command.SortDescriptors[0].Member = "Location"; } else if (command.SortDescriptors[0].Member == "Qty") { command.SortDescriptors[0].Member = "Qty"; } sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); TempData["sortingStatement"] = sortingStatement; } #endregion if (string.IsNullOrWhiteSpace(sortingStatement)) { sortingStatement = " order by CreateDate,MiscOrderNo"; } sql = string.Format("select * from (select RowId=ROW_NUMBER()OVER({0}),r1.* from ({1}) as r1 ) as rt where rt.RowId between {2} and {3}", sortingStatement, sql, (command.Page - 1) * command.PageSize + 1, command.PageSize * command.Page); IList<object[]> searchResult = this.genericMgr.FindAllWithNativeSql<object[]>(sql); IList<MiscOrderDetail> MiscOrderDetailList = new List<MiscOrderDetail>(); if (searchResult != null && searchResult.Count > 0) { #region transform MiscOrderDetailList = (from tak in searchResult select new MiscOrderDetail { BaseUom = (string)tak[1], CreateDate = (DateTime)tak[2], CreateUserId = (int)tak[3], CreateUserName = (string)tak[4], EBELN = (string)tak[5], EBELP = (string)tak[6], Item = (string)tak[7], ItemDescription = (string)tak[8], LastModifyDate = (DateTime)tak[9], LastModifyUserId = (int)tak[10], LastModifyUserName = (string)tak[11], Location = (string)tak[12], ManufactureParty = (string)tak[13], MiscOrderNo = (string)tak[14], Qty = (decimal)tak[15], ReferenceItemCode = (string)tak[16], Remark = (string)tak[17], ReserveLine = (string)tak[18], ReserveNo = (string)tak[19], Sequence = (int)tak[20], UnitCount = (decimal)tak[21], UnitQty = (decimal)tak[22], Uom = (string)tak[23], WMSSeq = (string)tak[24], WorkHour = (decimal)tak[25], Note = (string)tak[26], EffectiveDate = (DateTime)tak[27], MoveType = (string)tak[28], Flow = (string)tak[29], WBS = (string)tak[30], CostCenter = (string)tak[31], }).ToList(); #endregion } GridModel<MiscOrderDetail> gridModel = new GridModel<MiscOrderDetail>(); gridModel.Total = total; gridModel.Data = MiscOrderDetailList; ExportToXLS<MiscOrderDetail>("Detail.xls", gridModel.Data.ToList()); } #endregion } }
namespace TripDestination.Web.MVC.Areas.UserProfile.ViewModels { using Common.Infrastructure.Mapping; using Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; public class TownViewModel : IMapFrom<Town> { public string Name { get; set; } } }
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Atc.CodeAnalysis.CSharp.SyntaxFactories { public static class SyntaxArgumentListFactory { public static ArgumentListSyntax CreateWithOneItem(string argumentName) { if (argumentName == null) { throw new ArgumentNullException(nameof(argumentName)); } return SyntaxFactory.ArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxArgumentFactory.Create(argumentName))); } public static ArgumentListSyntax CreateWithTwoItems( string argumentName1, string argumentName2) { if (argumentName1 == null) { throw new ArgumentNullException(nameof(argumentName1)); } if (argumentName2 == null) { throw new ArgumentNullException(nameof(argumentName2)); } return CreateWithTwoExpressionItems( SyntaxFactory.IdentifierName(argumentName1), SyntaxFactory.IdentifierName(argumentName2)); } public static ArgumentListSyntax CreateWithOneArgumentItem(ArgumentSyntax argument) { if (argument == null) { throw new ArgumentNullException(nameof(argument)); } return SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList<ArgumentSyntax>( new SyntaxNodeOrToken[] { argument, })); } public static ArgumentListSyntax CreateWithTwoArgumentItems( ArgumentSyntax argument1, ArgumentSyntax argument2) { if (argument1 == null) { throw new ArgumentNullException(nameof(argument1)); } if (argument2 == null) { throw new ArgumentNullException(nameof(argument2)); } return SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList<ArgumentSyntax>( new SyntaxNodeOrToken[] { argument1, SyntaxTokenFactory.Comma(), argument2, })); } public static ArgumentListSyntax CreateWithThreeArgumentItems( ArgumentSyntax argument1, ArgumentSyntax argument2, ArgumentSyntax argument3) { if (argument1 == null) { throw new ArgumentNullException(nameof(argument1)); } if (argument2 == null) { throw new ArgumentNullException(nameof(argument2)); } if (argument3 == null) { throw new ArgumentNullException(nameof(argument3)); } return SyntaxFactory.ArgumentList( SyntaxFactory.SeparatedList<ArgumentSyntax>( new SyntaxNodeOrToken[] { argument1, SyntaxTokenFactory.Comma(), argument2, SyntaxTokenFactory.Comma(), argument3, })); } public static ArgumentListSyntax CreateWithOneExpressionItem(ExpressionSyntax argumentExpression1) { if (argumentExpression1 == null) { throw new ArgumentNullException(nameof(argumentExpression1)); } return CreateWithOneArgumentItem( SyntaxFactory.Argument(argumentExpression1)); } public static ArgumentListSyntax CreateWithTwoExpressionItems( ExpressionSyntax argumentExpression1, ExpressionSyntax argumentExpression2) { if (argumentExpression1 == null) { throw new ArgumentNullException(nameof(argumentExpression1)); } if (argumentExpression2 == null) { throw new ArgumentNullException(nameof(argumentExpression2)); } return CreateWithTwoArgumentItems( SyntaxFactory.Argument(argumentExpression1), SyntaxFactory.Argument(argumentExpression2)); } public static ArgumentListSyntax CreateWithThreeExpressionItems( ExpressionSyntax argumentExpression1, ExpressionSyntax argumentExpression2, ExpressionSyntax argumentExpression3) { if (argumentExpression1 == null) { throw new ArgumentNullException(nameof(argumentExpression1)); } if (argumentExpression2 == null) { throw new ArgumentNullException(nameof(argumentExpression2)); } if (argumentExpression3 == null) { throw new ArgumentNullException(nameof(argumentExpression3)); } return CreateWithThreeArgumentItems( SyntaxFactory.Argument(argumentExpression1), SyntaxFactory.Argument(argumentExpression2), SyntaxFactory.Argument(argumentExpression3)); } } }
using System.Globalization; using Framework.Core.Common; namespace Tests.Data.Oberon { public class TestEvent { public bool IsFundraising = false; public string Name = null; public string Description = null; public bool IsFundraisingEvent = false; public string TargetAmountToRaise = null; public string TargetGuestCount = null; public string StartDate = null; public string StartDateHour = null; public string StartDateMinute = null; public string StartDateMeridian = null; public string EndDate = null; public string EndDateHour = null; public string EndDateMinute = null; public string EndDateMeridian = null; public string LocationName = null; public string Address1 = null; public string Address2 = null; public string City = null; public string StateProvince = null; public string PostalCode = null; public string Sponser = null; public string Code = null; public string Id = null; public TestEvent GetTestEvent() { var testEvent = new TestEvent(); testEvent.IsFundraising = false; testEvent.Name = FakeData.RandomLetterString(50); testEvent.Description = FakeData.RandomLetterString(200); testEvent.IsFundraisingEvent = false; testEvent.TargetAmountToRaise = new decimal(FakeData.RandomInteger(500)).ToString(CultureInfo.InvariantCulture); testEvent.TargetGuestCount = FakeData.RandomInteger(200).ToString(CultureInfo.InvariantCulture); testEvent.StartDate = "11/22/2011"; testEvent.StartDateHour = "11"; testEvent.StartDateMinute = "00"; testEvent.StartDateMeridian = "AM"; testEvent.EndDate = "11/22/2011"; testEvent.EndDateHour = "1"; testEvent.EndDateMinute = "00"; testEvent.EndDateMeridian = "PM"; testEvent.LocationName = FakeData.RandomLetterString(50); testEvent.Address1 = FakeData.RandomLetterString(100); testEvent.Address2 = FakeData.RandomLetterString(100); testEvent.City = FakeData.RandomLetterString(100); testEvent.StateProvince = "IL"; testEvent.PostalCode = FakeData.RandomNumberString(5); testEvent.Sponser = null; testEvent.Code = null; testEvent.Id = null; return testEvent; } } }
using System; using CORE.Одномерные; using MathNet.Numerics.Differentiation; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; namespace CORE.Многомерные { public class GenericNewton : OptimisationMethod { private Matrix<double> _hessian; public GenericNewton() : base("Обобщенный Ньютон", 1e-5, null, null) { } public GenericNewton(Vector<double> startVector, Delegate function, double eps = 1e-5, int maxIterations = 50) : base("Обобщенный Ньютон", eps, function, startVector, maxIterations) { } public override void Execute() { var varCount = Fh.Point.Count; //Подготовка _hessian = new DenseMatrix(varCount, varCount); //начальная точка var x1 = Fh.Point; Func<double[], double> castFunc = doubles => Fh.Y(new DenseVector(doubles)); var hessianCalculator = new NumericalHessian(); //Альфа метод if (AlphaMethod == null) AlphaMethod = new BoostedDavidon(Fh.AlphaFunction, Fh.AlphaDiffFunction, Eps); IterationCount = 0; //Основной этап do { if (!Kop1(Fh.Grad(Fh.Point))) break; //Находим ньютоновское направление - p TODO var temp = hessianCalculator.Evaluate(castFunc, x1.ToArray()); for (var i = 0; i < varCount; i++) for (var j = 0; j < varCount; j++) _hessian[i, j] = temp[i, j]; var p = -(_hessian.Inverse())*Fh.Grad(x1); Fh.Dir = p; //Альфа метод AlphaMethod.SetSvenInterval(); AlphaMethod.Execute(); var alpha1 = AlphaMethod.Answer; //Переходим на новую точку x1 = x1 + Fh.Dir*alpha1; Fh.Point = x1; IterationCount++; } while (Kop1(Fh.Dir) && Kop1(Fh.Grad(Fh.Point))); Answer = Fh.Point; } } }
using System; namespace Xama.JTPorts.EasingInterpolator { public class EasingProvider { public static float Get(Ease ease, float elapsedTimeRate) { switch (ease) { case Ease.Linear: return elapsedTimeRate; case Ease.QuadIn: return getPowIn(elapsedTimeRate, 2); case Ease.QuadOut: return GetPowOut(elapsedTimeRate, 2); case Ease.QuadInOut: return GetPowInOut(elapsedTimeRate, 2); case Ease.CubicIn: return getPowIn(elapsedTimeRate, 3); case Ease.CubicOut: return GetPowOut(elapsedTimeRate, 3); case Ease.CubicInOut: return GetPowInOut(elapsedTimeRate, 3); case Ease.QuartIn: return getPowIn(elapsedTimeRate, 4); case Ease.QuartOut: return GetPowOut(elapsedTimeRate, 4); case Ease.QuartInOut: return GetPowInOut(elapsedTimeRate, 4); case Ease.QuintIn: return getPowIn(elapsedTimeRate, 5); case Ease.QuintOut: return GetPowOut(elapsedTimeRate, 5); case Ease.QuintInOut: return GetPowInOut(elapsedTimeRate, 5); case Ease.SineIn: return (float)(1f - Math.Cos(elapsedTimeRate * Math.PI / 2f)); case Ease.SineOut: return (float)Math.Sin(elapsedTimeRate * Math.PI / 2f); case Ease.SineInOut: return (float)(-0.5f * (Math.Cos(Math.PI * elapsedTimeRate) - 1f)); case Ease.BackIn: return (float)(elapsedTimeRate * elapsedTimeRate * ((1.7 + 1f) * elapsedTimeRate - 1.7)); case Ease.BackOut: return (float)(--elapsedTimeRate * elapsedTimeRate * ((1.7 + 1f) * elapsedTimeRate + 1.7) + 1f); case Ease.BackInOut: return GetBackInOut(elapsedTimeRate, 1.7f); case Ease.CircIn: return (float)-(Math.Sqrt(1f - elapsedTimeRate * elapsedTimeRate) - 1); case Ease.CircOut: return (float)Math.Sqrt(1f - (--elapsedTimeRate) * elapsedTimeRate); case Ease.CircInOut: if ((elapsedTimeRate *= 2f) < 1f) { return (float)(-0.5f * (Math.Sqrt(1f - elapsedTimeRate * elapsedTimeRate) - 1f)); } return (float)(0.5f * (Math.Sqrt(1f - (elapsedTimeRate -= 2f) * elapsedTimeRate) + 1f)); case Ease.BounceIn: return GetBounceIn(elapsedTimeRate); case Ease.BounceOut: return GetBounceOut(elapsedTimeRate); case Ease.BounceInOut: if (elapsedTimeRate < 0.5f) { return GetBounceIn(elapsedTimeRate * 2f) * 0.5f; } return GetBounceOut(elapsedTimeRate * 2f - 1f) * 0.5f + 0.5f; case Ease.ElasticIn: return GetElasticIn(elapsedTimeRate, 1, 0.3); case Ease.ElasticOut: return GetElasticOut(elapsedTimeRate, 1, 0.3); case Ease.ElasticInOut: return GetElasticInOut(elapsedTimeRate, 1, 0.45); default: return elapsedTimeRate; } } /// <summary> /// elapsedTimeRate Elapsed time / Total time, pow The exponent to use (ex. 3 would return a cubic ease) returns eased value /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="pow"></param> /// <returns></returns> private static float getPowIn(float elapsedTimeRate, double pow) { return (float)Math.Pow(elapsedTimeRate, pow); } /// <summary> /// Returns eased value. /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="pow"></param> /// <returns></returns> private static float GetPowOut(float elapsedTimeRate, double pow) { return (float)((float)1 - Math.Pow(1 - elapsedTimeRate, pow)); } /// <summary> /// Gets eased value /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="pow"></param> /// <returns></returns> private static float GetPowInOut(float elapsedTimeRate, double pow) { if ((elapsedTimeRate *= 2) < 1) { return (float)(0.5 * Math.Pow(elapsedTimeRate, pow)); } return (float)(1 - 0.5 * Math.Abs(Math.Pow(2 - elapsedTimeRate, pow))); } /// <summary> /// Get eased value from Elapsed time / Total time and the amount The strength of the ease. /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="amount"></param> /// <returns></returns> private static float GetBackInOut(float elapsedTimeRate, double amount) { amount *= 1.525; if ((elapsedTimeRate *= 2) < 1) { return (float)(0.5 * (elapsedTimeRate * elapsedTimeRate * ((amount + 1) * elapsedTimeRate - amount))); } return (float)(0.5 * ((elapsedTimeRate -= 2) * elapsedTimeRate * ((amount + 1) * elapsedTimeRate + amount) + 2)); } /// <summary> /// Bounce in ease value from Elapsed time / Total time /// </summary> /// <param name="elapsedTimeRate"></param> /// <returns></returns> private static float GetBounceIn(float elapsedTimeRate) { return 1f - GetBounceOut(1f - elapsedTimeRate); } /// <summary> /// Bounce out ease value. /// </summary> /// <param name="elapsedTimeRate"></param> /// <returns></returns> private static float GetBounceOut(double elapsedTimeRate) { if (elapsedTimeRate < 1 / 2.75) { return (float)(7.5625 * elapsedTimeRate * elapsedTimeRate); } else if (elapsedTimeRate < 2 / 2.75) { return (float)(7.5625 * (elapsedTimeRate -= 1.5 / 2.75) * elapsedTimeRate + 0.75); } else if (elapsedTimeRate < 2.5 / 2.75) { return (float)(7.5625 * (elapsedTimeRate -= 2.25 / 2.75) * elapsedTimeRate + 0.9375); } else { return (float)(7.5625 * (elapsedTimeRate -= 2.625 / 2.75) * elapsedTimeRate + 0.984375); } } /// <summary> /// /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="amplitude"></param> /// <param name="period"></param> /// <returns></returns> private static float GetElasticIn(float elapsedTimeRate, double amplitude, double period) { if (elapsedTimeRate == 0 || elapsedTimeRate == 1) return elapsedTimeRate; double pi2 = Math.PI * 2; double s = period / pi2 * Math.Asin(1 / amplitude); return (float)-(amplitude * Math.Pow(2f, 10f * (elapsedTimeRate -= 1f)) * Math.Sin((elapsedTimeRate - s) * pi2 / period)); } /// <summary> /// /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="amplitude"></param> /// <param name="period"></param> /// <returns></returns> private static float GetElasticOut(float elapsedTimeRate, double amplitude, double period) { if (elapsedTimeRate == 0 || elapsedTimeRate == 1) return elapsedTimeRate; double pi2 = Math.PI * 2; double s = period / pi2 * Math.Asin(1 / amplitude); return (float)(amplitude * Math.Pow(2, -10 * elapsedTimeRate) * Math.Sin((elapsedTimeRate - s) * pi2 / period) + 1); } /// <summary> /// /// </summary> /// <param name="elapsedTimeRate"></param> /// <param name="amplitude"></param> /// <param name="period"></param> /// <returns></returns> private static float GetElasticInOut(float elapsedTimeRate, double amplitude, double period) { double pi2 = Math.PI * 2; double s = period / pi2 * Math.Asin(1 / amplitude); if ((elapsedTimeRate *= 2) < 1) { return (float)(-0.5f * (amplitude * Math.Pow(2, 10 * (elapsedTimeRate -= 1f)) * Math.Sin((elapsedTimeRate - s) * pi2 / period))); } return (float)(amplitude * Math.Pow(2, -10 * (elapsedTimeRate -= 1)) * Math.Sin((elapsedTimeRate - s) * pi2 / period) * 0.5 + 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Images.Data { public class UserManager { private string _connString; public UserManager(string connString) { _connString = connString; } public void AddUser (string firstName, string lastName, string userName, string password) { string salt = PasswordManager.GenerateSalt(); string hash = PasswordManager.HashPassword(password, salt); DBAction(command => { command.CommandText = "INSERT INTO Users (FirstName, LastName, UserName, PasswordHash, PasswordSalt) VALUES " + "(@firstName, @lastName, @username, @password, @salt)"; command.Parameters.AddWithValue("@firstName", firstName); command.Parameters.AddWithValue("@lastName", lastName); command.Parameters.AddWithValue("@username", userName); command.Parameters.AddWithValue("@password", hash); command.Parameters.AddWithValue("@salt", salt); command.ExecuteNonQuery(); }); } public User GetUser(string username) { User user = new User(); DBAction(cmd => { cmd.CommandText = "SELECT * FROM Users WHERE UserName = @username"; cmd.Parameters.AddWithValue("@username", username); var reader = cmd.ExecuteReader(); if (!reader.Read()) { return; } else { user.UserName = username; user.FirstName = (string)reader["firstname"]; user.LastName = (string)reader["lastname"]; user.Id = (int)reader["id"]; user.PasswordHash = (string)reader["passwordhash"]; user.PasswordSalt = (string)reader["passwordsalt"]; } }); return user; } public User LogIn(string userName, string password) { User u = GetUser(userName); if (u == null) { return null; } if (PasswordManager.isMatch(u.PasswordHash, password, u.PasswordSalt)) { return u; } return null; } private void DBAction(Action<SqlCommand> action) { using (SqlConnection connection = new SqlConnection(_connString)) using (SqlCommand command = connection.CreateCommand()) { connection.Open(); action(command); } } } }
using CurrencyLibs; using CurrencyLibs.US; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class PennyTests { [TestMethod] public void PennyConstructor() { //Arrange Penny p; Penny philPenny; //Act p = new Penny(); philPenny = new Penny(USCoinMintMark.P); //Assert //D is the default mint mark //Current Year is default year Assert.AreEqual(USCoinMintMark.P, philPenny.MintMark); } [TestMethod] public void PennyMonetaryValue() { //Arrange Penny p; //Act p = new Penny(); //Assert Assert.AreEqual(.01, p.MonetaryValue); } //[TestMethod] //public void PennyAbout() //{ // //Arrange // Penny p; // //Act // p = new Penny(); // //Assert // //About output "US Penny is from 2017. It is worth $0.01. It was made in Denver" //} } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace STUFV { public partial class Detail2 : ContentPage { public Detail2 () { InitializeComponent (); } } }
using Common.DbTools; using Common.Model; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Windows; using System.Windows.Input; namespace UI_LokalniKontroler { public partial class MainWindow : Window { public DbGenerator dbg = new DbGenerator(); public DbGroup dbgroup = new DbGroup(); private BindingList<Generator> generators = new BindingList<Generator>(); public MainWindow(string code) { DataContext = this; InitializeComponent(); Data.Code = code; textBlockCode.Text = code; radio_btn_generator.IsChecked = true; generatorsDataGrid.ItemsSource = generators; Thread refresher = new Thread(Refresh); refresher.Start(); } private void ButtonNewGenerator(object sender, RoutedEventArgs e) { DbGroup dbgroup = new DbGroup(); var groups = dbgroup.ReadAll(Data.Code); if (groups.Count == 0) { MessageBox.Show("Please add one group first!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else { AddNewGeneratorWindow add = new AddNewGeneratorWindow(); add.Show(); } } private void ButtonNewGroup(object sender, RoutedEventArgs e) { AddNewGroupWindow add = new AddNewGroupWindow(); add.Show(); } private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) { Window promenaTipa = new ChangeControlTypeAndValueWindow((Generator)generatorsDataGrid.SelectedItem); promenaTipa.Show(); } private void Refresh() { while (true) { var gs = dbg.ReadAllForLC(Data.Code); foreach (var gen in gs) { int id = gen.Id; if (generators.FirstOrDefault(g => g.Id == gen.Id) == null) { //Zato sto se ObservableCollection ne moze menjati u drugom threadu // App.Current.Dispatcher.Invoke((Action)delegate { generators.Add(gen); }); } else { App.Current.Dispatcher.Invoke((Action)delegate { generators.FirstOrDefault(g => g.Id == id).CurrentPower = gen.CurrentPower; generators.FirstOrDefault(g => g.Id == id).Control = gen.Control; }); } } Thread.Sleep(500); } } private void RadioButton_Groups(object sender, RoutedEventArgs e) { //popuniti combo box sa grupama cmb_box_stat.ItemsSource = dbgroup.ReadAll(Data.Code); cmb_box_stat.SelectedIndex = 0; } private void RadioButton_Generators(object sender, RoutedEventArgs e) { //popuniti combo box sa generatorima cmb_box_stat.ItemsSource = dbg.ReadAllIds(Data.Code); cmb_box_stat.SelectedIndex = 0; } private void Btn_pocetni_datum_Click(object sender, RoutedEventArgs e) { if (calendar.SelectedDate != null) txt_box_poc_datum.Text = calendar.SelectedDate.Value.ToString(Data.DateFormat); } private void Btn_krajnji_datum_Click(object sender, RoutedEventArgs e) { if (calendar.SelectedDate != null) txt_box_kraj_datum.Text = calendar.SelectedDate.Value.ToString(Data.DateFormat); } private void Btb_Show_Stats(object sender, RoutedEventArgs e) { try { Calculations calculations = new Calculations(); DateTime dateFrom = DateTime.ParseExact(txt_box_poc_datum.Text, Data.DateFormat, null); DateTime dateTo = DateTime.ParseExact(txt_box_kraj_datum.Text, Data.DateFormat, null); int id = 0; string tmp = string.Empty; if(radio_btn_generator.IsChecked == true) { if(!Int32.TryParse(cmb_box_stat.SelectedValue.ToString(), out id)) { throw new Exception("Selected generator ID is invalid."); } } else { tmp = cmb_box_stat.SelectedValue.ToString(); } if (radio_btn_generator.IsChecked == true) { txt_box_min.Text = calculations.MinGeneratorPower(id, dateFrom, dateTo).ToString("0.##") + " kW"; txt_box_srednja.Text = calculations.MeanGeneratorPower(id, dateFrom, dateTo).ToString("0.##") + " kW"; txt_box_max.Text = calculations.MaxGeneratorPower(id, dateFrom, dateTo).ToString("0.##") + " kW"; } else { txt_box_min.Text = calculations.MinGroupPower(tmp, dateFrom, dateTo).ToString("0.##") + " kW"; txt_box_srednja.Text = calculations.MeanGroupPower(tmp, dateFrom, dateTo).ToString("0.##") + " kW"; txt_box_max.Text = calculations.MaxGroupPower(tmp, dateFrom, dateTo).ToString("0.##") + " kW"; } } catch (Exception exc) { MessageBox.Show("Error while parsing data. Check all fields and try again. " + exc.Message, "Parse Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
using NHibernate.DependencyInjection.Tests.Model; namespace NHibernate.DependencyInjection.Tests { public class EntityInjector : IEntityInjector { public object[] GetConstructorParameters(System.Type type) { if (type == typeof(DependencyInjectionCat)) return new object[] {new CatBehavior()}; return null; } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameStart : MonoBehaviour { public GameObject startbg; public GameObject characterbg; public GameObject checkpointbg; public GameObject player1GO; public GameObject player2GO; public RawImage treeRawImage; public RawImage flowerRawImage; public Texture treeTexture; public Texture flowerTexture; public bool player1CheckBool; public bool player2CheckBool; private void ProlongStart() { if (player1CheckBool && player2CheckBool) { Invoke("MainGameStart", 1f); player1CheckBool = false; player2CheckBool = false; } } public void ProlongExit() { Invoke("Exit", 1f); } private void MainGameStart() { SceneManager.LoadScene("遊戲場景"); } private void Exit() { Application.Quit(); } public void Checkpoint() { startbg.SetActive(false); characterbg.SetActive(true); } private void Change() { if (Input.GetKeyDown(KeyCode.RightArrow)) { flowerRawImage.texture = flowerTexture; } if (Input.GetKeyDown(KeyCode.LeftArrow)) { flowerRawImage.texture = treeTexture; } if (Input.GetKeyDown(KeyCode.D)) { treeRawImage.texture = treeTexture; } if (Input.GetKeyDown(KeyCode.A)) { treeRawImage.texture = flowerTexture; } if (Input.GetKeyDown(KeyCode.Space)) { player1CheckBool = true; player1GO.SetActive(true); } if (Input.GetKeyDown(KeyCode.RightShift)) { player2CheckBool = true; player2GO.SetActive(true); } } private void Update() { ProlongStart(); Change(); } }
using Assets.Common.HorseGame.Board; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Common.HorseGame.States { class PlayTurn : IState { int diceRolled; public void Execute() { if (GameContext.Players.GetPlayer().PlayerMode != PlayerMode.ARBoard) { GameContext.DisplayLabel.text = "Waiting for Player " + GameContext.Players.GetPlayer().index; GameContext.Subscribe("MessageSent", TurnPlayed); } else { GameContext.DisplayLabel.text = "Your turn: roll the dice"; GameContext.Subscribe("DiceRolled", DiceRolled); } } public void TurnPlayed(System.Object Msg) { GameContext.UnSubscribe("MessageSent"); string msg = (string)Msg; string[] parameters = msg.Split(';'); int.TryParse(parameters.FirstOrDefault(p => p.StartsWith("dice")).Substring(5), out diceRolled); if (parameters.Any(p => p.StartsWith("horse"))) { int horse; int.TryParse(parameters.FirstOrDefault(p => p.StartsWith("horse")).Split('=')[1], out horse); Pawn targetHorse = GameContext.Players.GetPlayer().Pawns[horse]; Square destination = GameContext.GoTo(targetHorse.ActualSquare(), diceRolled); Square stableSquare = GameContext.Stables[GameContext.Players.GetPlayer().boardIndex]; if (destination != null) { if (GameContext.isBothHorsesInStable(GameContext.Players.GetPlayer()) && diceRolled == 6) { GameContext.MovePawn(GameContext.Occupied(GameContext.Stables[GameContext.Players.GetPlayer().boardIndex].next), HorseMoveType.SetOnStart); } else if ((targetHorse.ActualSquare().index == stableSquare.index || targetHorse.ActualSquare().index == stableSquare.next.index) && diceRolled == 6) GameContext.MovePawn(targetHorse, HorseMoveType.SetOnStart); else GameContext.MovePawn(targetHorse, HorseMoveType.Move, destination); GameContext.Subscribe("MoveDone", MoveDone); } } else { MoveDone(); } } public void DiceRolled(System.Object Dice) { GameContext.UnSubscribe("DiceRolled"); diceRolled = (int)Dice; bool isMovePossible = false; GameContext.Players.GetPlayer().Pawns.ForEach(p => { isMovePossible = isMovePossible || GameContext.GoTo(p.ActualSquare(), diceRolled) != null;}); if (!isMovePossible) { GameContext.MQTT.Publish("player=2;dice=" + diceRolled, "player/general"); if (diceRolled == 6) GameContext.ActualState = new PlayTurn(); else GameContext.ActualState = new NextPlayer(); return; } GameContext.DisplayLabel.text = "Your turn: move a horse"; GameContext.Subscribe("HorseMoved", MoveHorse); } public void MoveHorse(System.Object HorseIndex) { GameContext.UnSubscribe("HorseMoved"); GameContext.DisplayLabel.text = "You moved"; int horseIndex = (int)HorseIndex; Pawn targetHorse = GameContext.Players.GetPlayer().Pawns[horseIndex]; Square destination = GameContext.GoTo(targetHorse.ActualSquare(), diceRolled); Square stableSquare = GameContext.Stables[GameContext.Players.GetPlayer().boardIndex]; if ((targetHorse.ActualSquare().index == stableSquare.index || targetHorse.ActualSquare().index == stableSquare.next.index) && diceRolled == 6 && destination != null) { GameContext.MovePawn(targetHorse, HorseMoveType.SetOnStart); } else if (destination != null) { GameContext.MovePawn(targetHorse, HorseMoveType.SetOnStart, destination); } GameContext.MQTT.Publish("player=2;horse=" + horseIndex + ";dice=" + diceRolled, "player/general"); if (diceRolled == 6) GameContext.ActualState = new PlayTurn(); else GameContext.ActualState = new NextPlayer(); } public void MoveDone(System.Object parameter = null) { GameContext.UnSubscribe("MoveDone"); if (diceRolled == 6) GameContext.ActualState = new PlayTurn(); else GameContext.ActualState = new NextPlayer(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { // 属性值 public float bulletSpeed = 10.0f; public float bulletLv2Speed = 15.0f; public float bulletLv3Speed = 20.0f; public bool isPlayerBullet; public bool isPlayer1Bullet; public bool isAbleDestroyBarrier; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { transform.Translate(transform.up * bulletSpeed * Time.deltaTime, Space.World); } private void OnTriggerEnter2D(Collider2D collison) { switch (collison.tag) { case ("Tank"): if (!isPlayerBullet) { collison.SendMessage("Die"); Destroy(gameObject); } break; case ("Barrier"): collison.SendMessage("playAudio"); if (isAbleDestroyBarrier) { Destroy(collison.gameObject); } Destroy(gameObject); break; case ("AirBarrier"): Destroy(gameObject); break; case ("Wall"): Destroy(collison.gameObject); Destroy(gameObject); break; case ("Enemy"): if (isPlayerBullet) { if (position.Instance.isSingleMode) { PlayerManger.Instance.playerScore++; collison.SendMessage("Die"); Destroy(gameObject); } else { if (isPlayer1Bullet) { PlayerManager2.Instance2.player1Score++; } else { PlayerManager2.Instance2.player2Score++; } collison.SendMessage("Die"); Destroy(gameObject); } } break; case ("Base"): collison.SendMessage("Die"); Destroy(gameObject); if (position.Instance.isSingleMode) { PlayerManger.Instance.isDefeat = true; } else { PlayerManager2.Instance2.isDefeat = true; } break; case ("Bullet"): Destroy(collison.gameObject); Destroy(gameObject); break; default: break; } } void setBulletSpeedLv2() { bulletSpeed = bulletLv2Speed; } void setBulletSpeedLv3() { bulletSpeed = bulletLv3Speed; } }
using System; using System.Collections.Generic; using ResilienceClasses; using Foundation; using AppKit; namespace CashflowProjection { public class CashflowTableDataSourceDelegate : NSTableViewDelegate { private CashflowTableDataSource dataSource; public CashflowTableDataSourceDelegate(CashflowTableDataSource source) { this.dataSource = source; } public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row) { NSTextField view; // Setup view based on the column selected switch (tableColumn.Title) { case "ID": view = (NSTextField)tableView.MakeView("IDCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "IDCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "Date": view = (NSTextField)tableView.MakeView("DateCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "PayDateCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "Balance": view = (NSTextField)tableView.MakeView("BalanceCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "BalanceCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; view.Alignment = NSTextAlignment.Right; } view.DoubleValue = dataSource.Cashflows[(int)row].Amount(); break; case "Amount": view = (NSTextField)tableView.MakeView("AmountCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "AmountCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; view.Alignment = NSTextAlignment.Right; } view.DoubleValue = dataSource.Cashflows[(int)row].Amount(); break; case "Type": view = (NSTextField)tableView.MakeView("TypeCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "TypeCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "Actual": view = (NSTextField)tableView.MakeView("ActualCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "ActualCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "Notes": view = (NSTextField)tableView.MakeView("NotesCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "NotesCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "Property": view = (NSTextField)tableView.MakeView("PropertyCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "PropertyCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "ExpireDate": view = (NSTextField)tableView.MakeView("DateCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "ExpireDateCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; case "RecordDate": view = (NSTextField)tableView.MakeView("DateCell", this); if (view == null) { view = new NSTextField(); view.Identifier = "RecordDateCell"; view.BackgroundColor = NSColor.Clear; view.Bordered = false; view.Selectable = false; view.Editable = false; } break; default: view = null; break; } return view; } } }
namespace MeeToo.Services.MessageSending.Email { public interface IRazorEmailTemplate : IEmailTemplate { string Key { get; set; } string Template { get; set; } } }
using FluentAssertions; using Nono.Engine.Tests.Extensions; using Xunit; namespace Nono.Engine.Tests { public class CollapseOperationShould { [Fact] public void Run_1_block() { var line = Collapse.Run(new[] { 3 }, " ".AsSpan()); line.Boxes.Should().Equal(" — ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(3); } [Fact] public void Run_5_blocks_tight() { var line = Collapse.Run( new[] { 1, 1, 1, 4, 2 }, " ".AsSpan()); line.Boxes.Should().Equal("1x1x1x1111x11".AsBoxEnumerable()); line.CombinationsCount.Should().Be(1L); } [Fact] public void Run_1_block_with_crossed() { var line = Collapse.Run(new[] { 2 }, " xxxxxxxx xxxxx ".AsSpan()); line.Boxes.Should().Equal(" xxxxxxxx xxxxxx".AsBoxEnumerable()); line.CombinationsCount.Should().Be(4); } [Fact] public void Run_2_blocks() { var line = Collapse.Run(new[] { 2, 1 }, " ".AsSpan()); line.Boxes.Should().Equal(" — ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(3); } [Fact] public void Run_2_blocks_with_crossed() { var line = Collapse.Run(new[] { 2, 1 }, " 00 0".AsSpan()); line.Boxes.Should().Equal("110010".AsBoxEnumerable()); line.CombinationsCount.Should().Be(1); } [Fact] public void Run_3_blocks() { var line = Collapse.Run(new[] { 1, 2, 3 }, " ".AsSpan()); line.Boxes.Should().Equal(" — ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(10); } [Fact] public void Run_4_blocks_with_filled() { var line = Collapse.Run( new[] { 3, 30, 1, 5 }, " — — ".AsSpan()); line.Boxes.Should().Equal(" — ——————————————————————————— —— ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(34); } [Fact] public void Run_10_blocks_with_division() { var line = Collapse.Run( new[] { 4, 6, 1, 3, 2, 2, 3, 4, 1 }, "xxxxx————x——————x— x———xxx——x——xx———x ".AsSpan()); line.Boxes.Should().Equal("xxxxx————x——————x—xx———xxx——x——xx———x ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(36); } [Fact] public void Run_8_blocks_200M_combinations() { var line = Collapse.Run( new[] { 1, 2, 2, 1, 12, 1, 2, 2 }, " x — — —— ".AsSpan()); line.Boxes.Should().Equal(" x — — —— ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(177581035L); } [Fact] public void Run_3_blocks_reduce_count() { var line = Collapse.Run( new[] { 4, 1, 6 }, " — ".AsSpan()); line.Boxes.Should().Equal(" — ".AsBoxEnumerable()); line.CombinationsCount.Should().Be(274L); } } }
using System; /// <summary> /// O padrão observer trabalha com observadores e um sujeito, o qual está encarregado /// de notificar todos os observadores caso requisitado. /// </summary> /// It's so commom that microsoft have a page for them /// https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee817669(v=pandp.10) public sealed class Observer : IDesingPattern { public void RunPattern() { var subject = new ObserverDemo.Subject(); var observerA = new ObserverDemo.Observer { Identifier = "A" }; var observerB = new ObserverDemo.Observer { Identifier = "B" }; subject.Update += observerA.Update; subject.Update += observerB.Update; subject.Notify(); } } public class ObserverDemo { public class Subject { public event Action Update; public void Notify() => Update?.Invoke(); } public class Observer { public string Identifier { get; set; } public void Update() => Console.WriteLine($"My Identifier = {Identifier}"); } }
/****************************************************************************** * File : pLab_KJPOC_ARModeEnabler.cs * Lisence : BSD 3-Clause License * Copyright : Lapland University of Applied Sciences * Authors : Arto Söderström * BSD 3-Clause License * * Copyright (c) 2019, Lapland University of Applied Sciences * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; /// <summary> /// Checks if POIs are close enough to be seen in AR-mode /// </summary> public class pLab_KJPOC_ARModeEnabler : MonoBehaviour { #region Variables [SerializeField] private pLab_PointOfInterestSet pointOfInterestSet; [SerializeField] private pLab_LocationProvider locationProvider; [SerializeField] private pLab_KJPOCMapARTransition mapARTransition; [SerializeField] private float checkInterval = 1f; private bool isEnabled = true; private float timer = 0f; #endregion #region Properties public float CheckInterval { get { return checkInterval; } set { checkInterval = value; } } public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; } } public List<pLab_PointOfInterest> PointOfInterests { get { return pointOfInterestSet != null && pointOfInterestSet.PointOfInterests != null ? pointOfInterestSet.PointOfInterests : new List<pLab_PointOfInterest>(); } } #endregion #region Inherited Methods private void OnEnable() { ARSession.stateChanged += OnARSessionStateChanged; } private void OnDisable() { ARSession.stateChanged -= OnARSessionStateChanged; } private void Update() { if (!isEnabled || locationProvider == null) return; timer += Time.deltaTime; if (timer >= checkInterval) { CheckIfPointOfInterestsClose(); timer = 0f; } } #endregion #region Private Methods /// <summary> /// Checks if any of the point of interests are close to the player, and highlights AR-mode button depending on that. /// </summary> private void CheckIfPointOfInterestsClose() { pLab_LatLon currentPlayerLocation = locationProvider.Location; if (currentPlayerLocation != null) { bool isClose = false; for(int i = 0; i < PointOfInterests.Count; i++) { if (PointOfInterests[i] == null) continue; float distanceBetween = currentPlayerLocation.DistanceToPointPythagoras(PointOfInterests[i].Coordinates); if (distanceBetween <= PointOfInterests[i].TrackingRadius - 5) { // Debug.Log($"{PointOfInterests[i].PoiName} is close ({distanceBetween} m)"); isClose = true; break; } } mapARTransition.ToggleARButtonHighlight(isClose); } } /// <summary> /// Event handler for ARSessionStateChanged-event. Changes IsEnabled-state based on if AR is supported or not /// </summary> /// <param name="evt"></param> private void OnARSessionStateChanged(ARSessionStateChangedEventArgs evt) { if (evt.state == ARSessionState.Unsupported) { isEnabled = false; } else { isEnabled = true; } } #endregion }
namespace Witsml.Data.Measures { public class WitsmlAnglePerLengthMeasure : Measure { } }
using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Net; namespace WebAPI.API { public class Order { public static void Get(HttpListenerContext httpContext) { var orders = new Order[0]; lock (Locker) if (File.Exists("Orders.json")) orders = JsonConvert.DeserializeObject<Order[]>($"[{File.ReadAllText("Orders.json").Replace("\n", ",")}]"); orders.FirstOrDefault(o => o.Id.Equals(httpContext.Request.QueryString["Id"])).SendRestResponse(httpContext.Response); } public static void Post(HttpListenerContext httpContext) { var order = httpContext.Request.GetRequestRestPayload<Order>(); if (!ValidatePost(order.Products, out var message)) { new { Message = message, Success = false }.SendRestResponse(httpContext.Response); return; } lock(Locker) { order.Id = $"o_{Guid.NewGuid().ToString().Replace("-", string.Empty)}"; File.AppendAllLines("Orders.json", new[] {JsonConvert.SerializeObject(order)}); } new { order.Id, Success = true }.SendRestResponse(httpContext.Response); } private static bool ValidatePost(Product[] products, out string message) { message = default; if (products.Sum(p => p.Quantity * p.UnitPrice) > 100) { message = "An order should be rejected if a total value in excess of one hundred Euro"; return false; } if (products.GroupBy(p => p.ProductId, p => p.Quantity, (id, qty) => qty.Sum(q => q)).Any(p => p > 10)) { message = "An order should be rejected if more than ten of any Product is already on order"; return false; } return true; } public string DeliveryAddress { get; set; } public string Id { get; set; } private static readonly object Locker = new object(); public Product[] Products { get; set; } public class Product { public int ProductId { get; set; } public uint Quantity { get; set; } public double UnitPrice { get; set; } } } }
using System; using System.ComponentModel.DataAnnotations; using AGCompressedAir.Domain.Domains.Base; using AGCompressedAir.Windows.Enums; namespace AGCompressedAir.Domain.Domains { public class ServiceDomain : Entity<Guid> { public string Compressor { get; set; } public string SerialNumber { get; set; } public string AirFilter { get; set; } public string OilFilter { get; set; } public string Seperator { get; set; } public string Belt { get; set; } public string Oil { get; set; } public Guid ClientId { get; set; } public ClientDomain Client { get; set; } [DataType(DataType.DateTime)] public DateTime ServiceDate { get; set; } public ServiceInterval ServiceInterval { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PhotographyEvent.Administration { // This page shows users enrolled in our web site and their acrivities public partial class UserManagement : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // shows users list UsersBind(); } } // When userid is clicked, it shows user's activity below the table such as the event the user won // the event the user participated in protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e) { string userId = e.CommandArgument.ToString(); SetUserEventsGrid(userId); lblUser.Text = userId + @"'s participation information"; } /// <summary> /// Gets users list and bind to the table /// </summary> private void UsersBind() { string select = @"select ROW_NUMBER() over(order by userId) as [No], UserId, FirstName, a.EmailAddress, CONVERT(CHAR(10), a.EntryDate, 103) As RegDate, a.IsAdmin From Users as a"; using (System.Data.SqlClient.SqlDataReader reader = Libs.DbHandler.getResultAsDataReader(select, null)) { gvUsers.DataSource = reader; gvUsers.DataBind(); } } /// <summary> /// shows user-related data: event the user won, event the user took part in /// </summary> /// <param name="uid">user id to find activities</param> private void SetUserEventsGrid(string uid) { // finding event user have won string select = @"SELECT EventId, EventName From Events Where Winner = @userId"; Dictionary<string, string> pList = new Dictionary<string, string>(); pList.Add("userId", uid); using (System.Data.SqlClient.SqlDataReader reader = Libs.DbHandler.getResultAsDataReaderDicParam(select, pList)) { gvWonEvent.DataSource = reader; gvWonEvent.DataBind(); } // finds event the user participated select = @"select A.EventId, A.EventName from Events as A Inner Join EventUserPhotos as B On a.EventId = B.EventId Where B.userId = @userId"; pList = new Dictionary<string, string>(); pList.Add("userId", uid); using (System.Data.SqlClient.SqlDataReader reader = Libs.DbHandler.getResultAsDataReaderDicParam(select, pList)) { gvParticipant.DataSource = reader; gvParticipant.DataBind(); } } } }
using Anywhere2Go.Business.Utility; using Anywhere2Go.DataAccess; using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.Object; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.Business.Master { public class ProvinceLogic { MyContext _context = null; public ProvinceLogic() { _context = new MyContext(); } public ProvinceLogic(MyContext context) { _context = context; } public List<SyncProvince> GetProvinces(DateTime? lastSyncedDateTime) { List<Province> result = ApplicationCache.GetMaster<Province>(); if (lastSyncedDateTime == null) { return result.Where(t=>t.isActive==true) .Select(t => new SyncProvince { ProvinceCode = t.provinceCode, ProvinceName = t.provinceName, GeoID = t.geoID, Sort = t.sort, isActive = t.isActive, isAddress = (t.isAddress.HasValue ? t.isAddress.Value : false), isCarRegis = (t.isCarRegis.HasValue ? t.isCarRegis.Value : false) }) .ToList(); } else { return result .Where(x => (x.updateDate ?? x.createDate) > lastSyncedDateTime.Value && x.isActive == true) .OrderBy(x => (x.updateDate ?? x.createDate)) .Select(t => new SyncProvince { ProvinceCode = t.provinceCode, ProvinceName = t.provinceName, GeoID = t.geoID, Sort = t.sort, isActive = t.isActive, isAddress = (t.isAddress.HasValue ? t.isAddress.Value : false), isCarRegis = (t.isCarRegis.HasValue ? t.isCarRegis.Value : false) }) .ToList(); } } public Province GetProvincesByAddress(string strAddress) { List<Province> result = ApplicationCache.GetMaster<Province>(); if (!string.IsNullOrEmpty(strAddress)) { return result.Where(t => t.isActive == true && strAddress.Contains(t.provinceName)).OrderBy(t=>t.provinceName).FirstOrDefault(); } else return new Province() ; } public Province GetProvinceById(string id) { List<Province> result = ApplicationCache.GetMaster<Province>(); return result.Where(t => t.isActive == true && t.provinceCode == id).FirstOrDefault(); } public Province GetProvinceByName(string name) { List<Province> result = ApplicationCache.GetMaster<Province>(); return result.Where(t => t.isActive == true && t.provinceName.Trim().Replace(" ", string.Empty) == name.Trim().Replace(" ",string.Empty)).FirstOrDefault(); } public Aumphur GetAmphurById(string id) { List<Aumphur> result = ApplicationCache.GetMaster<Aumphur>(); return result.Where(t => t.isActive == true && t.aumphurCode == id).FirstOrDefault(); } public District GetDistrictById(string id) { List<District> result = ApplicationCache.GetMaster<District>(); return result.Where(t => t.isActive == true && t.districtCode == id).FirstOrDefault(); } public Aumphur GetAmphurByName(string name) { List<Aumphur> result = ApplicationCache.GetMaster<Aumphur>(); return result.Where(t => t.isActive == true && t.aumphurName.Trim().Replace(" ", string.Empty) == name.Trim().Replace(" ", string.Empty)).FirstOrDefault(); } public District GetDistrictByName(string name) { List<District> result = ApplicationCache.GetMaster<District>(); return result.Where(t => t.isActive == true && t.districtName.Trim().Replace(" ", string.Empty) == name.Trim().Replace(" ", string.Empty)).FirstOrDefault(); } } }
using Agora.EventStore.Eventing; namespace Agora.EventStore.EventStore.InMemory { public class InMemoryAllStream : IAllStream { public void Update(string streamName, IEvent @event) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TechEval.Core; using TechEval.DataContext; namespace TechEval { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddDbContext<Db>(opt => opt .UseSqlServer(Configuration.GetConnectionString("DefaultConnection")) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)); services.AddTransient<IODataDispatcher, ODataDispatcher>(); services.RegisterCommandHandlers(); services.AddControllers(); services .AddQRest() .UseODataSemantics() .UseStandardCompiler(cpl => { cpl.UseCompilerCache = true; }); services.MigrateDb(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseExceptionHandler("/Error"); app.UseRouting(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute(name: "default", pattern: "api/{controller}/{action}"); }); } } }
using UnityEngine; public class GameManager : MonoBehaviour { bool gameHasEnded = false; public void CompleteLevel () { Debug.Log ("Level Won"); } public void EndGame() { if (gameHasEnded == false) { gameHasEnded = true; Debug.Log ("GAME OVER"); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; [System.Serializable] public class CardEffectVO { // verb (add), noun (burn), target (discard pile) public enum Action { Draw, Discard, GainDefense, GainAttack, GainEnergy, ApplyHeal, ApplyPoison, ApplyBurn }; public enum Target { Source, Target, Opponents, Colleagues, DrawPile, DiscardPile }; public Action action; public Target target; public int value; public int duration; public bool isExhaustable = false; public int level; public int[] levelMultipliers; }
using UnityEngine; using UnityEditor; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; using EntityClasses; using MapClasses; public class EntityTests { [Test] public void Entity_Constructor_Clone() { // Use the Assert class to test conditions. Entity entity1 = new Entity { Index = 1, Name = "Test entity 1" }; Entity entity2 = new Entity(entity1); Assert.AreEqual(entity1.Name, entity2.Name); } [Test] public void Entity_TurnLeft() { Direction directionStart = Direction.Up; Direction directionExpected = Direction.Left; Entity entity1 = new Entity { Facing = directionStart }; entity1.TurnLeft(); Assert.AreEqual(directionExpected, entity1.Facing); } [Test] public void Entity_TurnRight() { Direction directionStart = Direction.Up; Direction directionExpected = Direction.Right; Entity entity1 = new Entity { Facing = directionStart }; entity1.TurnRight(); Assert.AreEqual(directionExpected, entity1.Facing); } [Test] public void Entity_GetDirectionDegrees() { Direction direction = Direction.Right; float expectedDegrees = 90f; Entity entity1 = new Entity { Facing = direction }; float degrees = entity1.GetDirectionDegrees(); Assert.AreEqual(expectedDegrees, degrees); } [Test] public void Entity_GetAbsoluteDirection() { Direction facing = Direction.Right; Direction startDirection = Direction.Left; Direction expectedDirection = Direction.Up; Entity entity1 = new Entity { Facing = facing }; Direction direction = entity1.GetDirection(startDirection); Assert.AreEqual(expectedDirection, direction); } [Test] public void Entity_GetBackward() { Direction directionStart = Direction.Right; Direction expectedDirection = Direction.Left; Entity entity1 = new Entity { Facing = directionStart }; Direction direction = entity1.GetBackward(); Assert.AreEqual(expectedDirection, direction); } [Test] public void Entity_GetLeft() { Direction directionStart = Direction.Right; Direction expectedDirection = Direction.Up; Entity entity1 = new Entity { Facing = directionStart }; Direction direction = entity1.GetLeft(); Assert.AreEqual(expectedDirection, direction); } [Test] public void Entity_GetRight() { Direction directionStart = Direction.Right; Direction expectedDirection = Direction.Down; Entity entity1 = new Entity { Facing = directionStart }; Direction direction = entity1.GetRight(); Assert.AreEqual(expectedDirection, direction); } [Test] public void Entity_Heal() { float startHealth = 50; float healAmount = 10; float expectedHealth = 60; Entity entity1 = new Entity { MaxHealth = 100f, CurrentHealth = startHealth }; entity1.Heal(healAmount); Assert.AreEqual(expectedHealth, entity1.CurrentHealth); } [Test] public void Entity_Damage() { float startHealth = 50f; float damageAmount = 10f; float expectedHealth = 40f; Entity entity1 = new Entity { MaxHealth = 100f, CurrentHealth = startHealth }; entity1.Damage(damageAmount); Assert.AreEqual(expectedHealth, entity1.CurrentHealth); } }
using API_ASPNET_CORE.Infraestrutura.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace API_ASPNET_CORE.Configurations { public class DbFacturyDbContext : IDesignTimeDbContextFactory<CursoDbContext> { public CursoDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<CursoDbContext>(); optionsBuilder.UseSqlServer("Server=PAT1287;Database=CURSO;user=sa;password=senhas"); CursoDbContext contexto = new CursoDbContext(optionsBuilder.Options); return contexto; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace gView.Framework.Security { public static class EncodingExtensions { private const string DefaultCharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private const string InvertedCharacterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// <summary> /// Encode a 2-byte number with Base62 /// </summary> /// <param name="original">String</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Base62 string</returns> public static string ToBase62(this short original, bool inverted = false) { var array = BitConverter.GetBytes(original); if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return array.ToBase62(inverted); } /// <summary> /// Encode a 4-byte number with Base62 /// </summary> /// <param name="original">String</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Base62 string</returns> public static string ToBase62(this int original, bool inverted = false) { var array = BitConverter.GetBytes(original); if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return array.ToBase62(inverted); } /// <summary> /// Encode a 8-byte number with Base62 /// </summary> /// <param name="original">String</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Base62 string</returns> public static string ToBase62(this long original, bool inverted = false) { var array = BitConverter.GetBytes(original); if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return array.ToBase62(inverted); } /// <summary> /// Encode a string with Base62 /// </summary> /// <param name="original">String</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Base62 string</returns> public static string ToBase62(this string original, bool inverted = false) { return Encoding.UTF8.GetBytes(original).ToBase62(inverted); } /// <summary> /// Encode a byte array with Base62 /// </summary> /// <param name="original">Byte array</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Base62 string</returns> public static string ToBase62(this byte[] original, bool inverted = false) { var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; var arr = Array.ConvertAll(original, t => (int)t); var converted = BaseConvert(arr, 256, 62); var builder = new StringBuilder(); foreach (var t in converted) { builder.Append(characterSet[t]); } return builder.ToString(); } /// <summary> /// Decode a base62-encoded string /// </summary> /// <param name="base62">Base62 string</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Byte array</returns> public static T FromBase62<T>(this string base62, bool inverted = false) { var array = base62.FromBase62(inverted); switch (Type.GetTypeCode(typeof(T))) { case TypeCode.String: return (T)Convert.ChangeType(Encoding.UTF8.GetString(array), typeof(T)); case TypeCode.Int16: if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return (T)Convert.ChangeType(BitConverter.ToInt16(array, 0), typeof(T)); case TypeCode.Int32: if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return (T)Convert.ChangeType(BitConverter.ToInt32(array, 0), typeof(T)); case TypeCode.Int64: if (BitConverter.IsLittleEndian) { Array.Reverse(array); } return (T)Convert.ChangeType(BitConverter.ToInt64(array, 0), typeof(T)); default: throw new Exception($"Type of {typeof(T)} does not support."); } } /// <summary> /// Decode a base62-encoded string /// </summary> /// <param name="base62">Base62 string</param> /// <param name="inverted">Use inverted character set</param> /// <returns>Byte array</returns> public static byte[] FromBase62(this string base62, bool inverted = false) { var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; var arr = Array.ConvertAll(base62.ToCharArray(), characterSet.IndexOf); var converted = BaseConvert(arr, 62, 256); return Array.ConvertAll(converted, Convert.ToByte); } private static int[] BaseConvert(int[] source, int sourceBase, int targetBase) { var result = new List<int>(); var leadingZeroCount = source.TakeWhile(x => x == 0).Count(); int count; while ((count = source.Length) > 0) { var quotient = new List<int>(); var remainder = 0; for (var i = 0; i != count; i++) { var accumulator = source[i] + remainder * sourceBase; var digit = accumulator / targetBase; remainder = accumulator % targetBase; if (quotient.Count > 0 || digit > 0) { quotient.Add(digit); } } result.Insert(0, remainder); source = quotient.ToArray(); } result.InsertRange(0, Enumerable.Repeat(0, leadingZeroCount)); return result.ToArray(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Alabo.Domains.Entities.Extensions; namespace Alabo.Industry.Shop.Products.Domain.Entities.Extensions { /// <summary> /// 商品扩展详情 /// </summary> public class ProductDetailExtension : EntityExtension { /// <summary> /// 店铺分类 /// </summary> public List<long> StoreClass { get; set; } = new List<long>(); /// <summary> /// 商品标签 /// </summary> public List<long> Tags { get; set; } = new List<long>(); /// <summary> /// 海外商品 /// </summary> [Display(Name = "海外商品")] public bool IsOverseas { get; set; } = false; /// <summary> /// 是否需要收货地址 /// </summary> [Display(Name = "是否需要收货地址")] public bool NeedBuyerAddress { get; set; } = true; /// <summary> /// 商品简介 /// </summary> [Display(Name = "商品简介")] public string Brief { get; set; } /// <summary> /// 表示商品的体积,如果需要使用按体积计费的运费模板,一定要设置这个值。该值的单位为立方米(m3),如果是其他单位,请转换成成立方米 /// </summary> [Display(Name = "体积")] [Range(0, 99999999, ErrorMessage = "商品体积必须为大于等于0的数字")] public decimal Size { get; set; } /// <summary> /// 是否包邮 /// </summary> [Display(Name = "是否包邮")] public bool IsShipping { get; set; } = false; [Display(Name = "备注")] public string Remark { get; set; } /// <summary> /// 商品条形码 /// </summary> [Display(Name = "商品条形码")] public string BarCode { get; set; } /// <summary> /// 是否有折扣 /// </summary> [Display(Name = "是否有折扣")] public int HasDiscount { get; set; } /// <summary> /// 是否有发票 /// </summary> [Display(Name = "是否有发票")] public bool HasInvoice { get; set; } = false; /// <summary> /// 是否有保修 /// </summary> [Display(Name = "是否有保修")] public bool HasWarranty { get; set; } = false; /// <summary> /// 是否是虚拟商品 /// </summary> [Display(Name = "是否是虚拟商品")] public bool IsVirtual { get; set; } = false; /// <summary> /// 售后服务模板 /// </summary> [Display(Name = "售后服务模板")] public Guid AfterSaleId { get; set; } /// <summary> /// 商品副标题 /// </summary> [Display(Name = "商品副标题")] public string ProductSubTitle { get; set; } /// <summary> /// 商品短标题 /// </summary> [Display(Name = "商品短标题")] public string ProductSortTitle { get; set; } /// <summary> /// 审核拒绝消息内容 /// </summary> [Display(Name = "审核拒绝消息内容")] public string AidutMessage { get; set; } } }
using System; namespace Zadanie_3 { class Program { static bool CzyIstnieją(int m, int[] L1, int[] L2) { for (int i = 0; i < L1.Length; i++) { for (int k = 0; k < L2.Length; k++) { if ((L1[i] + L2[k] )== m) return true; } } return false; } static void Main(string[] args) { int [] L1 = new int[]{1,3,5,7,9}; int[] L2 = new int[] { 12,76,445,545,667}; Console.WriteLine("Dla m = {0}: " +CzyIstnieją(454,L1,L2)); Console.WriteLine("Dla m = {0}: " +CzyIstnieją(787,L1,L2)); Console.ReadKey(); } } }
using SoftwareAuthKeyLoader.Kmm; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SoftwareAuthKeyLoader { internal static class Actions { public static int LoadAuthenticationKey(bool targetSpecificSuId, int wacnId, int systemId, int unitId, byte[] key) { Output.DebugLine("LoadAuthenticationKey() :: targetSpecificSuId: {0}, wacnId: 0x{1:X}, systemId: 0x{2:X}, unitId: 0x{3:X}, key (hex): {4}", targetSpecificSuId, wacnId, systemId, unitId, BitConverter.ToString(key)); SuId commandSuId = new SuId(wacnId, systemId, unitId); Output.DebugLine("command suid - {0}", commandSuId.ToString()); LoadAuthenticationKeyCommand commandKmmBody = new LoadAuthenticationKeyCommand(targetSpecificSuId, commandSuId, key); Output.DebugLine("command kmm body - {0}", commandKmmBody.ToString()); KmmFrame commandKmmFrame = new KmmFrame(commandKmmBody); Output.DebugLine("command kmm frame - {0}", commandKmmFrame.ToString()); byte[] toRadio = commandKmmFrame.ToBytes(); byte[] fromRadio; try { fromRadio = Network.QueryRadio(toRadio); } catch (Exception ex) { Output.ErrorLine("unable to connect to radio: {0}", ex.Message); return -1; } KmmFrame responseKmmFrame = new KmmFrame(fromRadio); Output.DebugLine("response kmm frame - {0}", responseKmmFrame.ToString()); KmmBody responseKmmBody = responseKmmFrame.KmmBody; if (responseKmmBody is LoadAuthenticationKeyResponse) { Output.DebugLine("received LoadAuthenticationKeyResponse kmm"); LoadAuthenticationKeyResponse loadAuthenticationKeyResponse = responseKmmBody as LoadAuthenticationKeyResponse; Output.DebugLine("response kmm body - {0}", loadAuthenticationKeyResponse.ToString()); Output.DebugLine("response suid - {0}", loadAuthenticationKeyResponse.SuId.ToString()); if (loadAuthenticationKeyResponse.AssignmentSuccess == true && loadAuthenticationKeyResponse.Status == Status.CommandWasPerformed) { return 0; } else { Output.ErrorLine("abnormal response - assignment success: {0}, status: {1} (0x{2:X2})", loadAuthenticationKeyResponse.AssignmentSuccess, loadAuthenticationKeyResponse.Status.ToString(), (byte)loadAuthenticationKeyResponse.Status); return -1; } } else if (responseKmmBody is NegativeAcknowledgement) { Output.ErrorLine("received NegativeAcknowledgement kmm"); NegativeAcknowledgement negativeAcknowledgement = responseKmmBody as NegativeAcknowledgement; Output.DebugLine("response kmm body - {0}", negativeAcknowledgement.ToString()); return -1; } else { Output.ErrorLine("received unexpected kmm"); return -1; } } public static int DeleteAuthenticationKey(bool targetSpecificSuId, bool deleteAllKeys, int wacnId, int systemId, int unitId) { Output.DebugLine("DeleteAuthenticationKey() :: targetSpecificSuId: {0}, deleteAllKeys: {1}, wacnId: 0x{2:X}, systemId: 0x{3:X}, unitId: 0x{4:X}", targetSpecificSuId, deleteAllKeys, wacnId, systemId, unitId); SuId commandSuId = new SuId(wacnId, systemId, unitId); Output.DebugLine("command suid - {0}", commandSuId.ToString()); DeleteAuthenticationKeyCommand commandKmmBody = new DeleteAuthenticationKeyCommand(targetSpecificSuId, deleteAllKeys, commandSuId); Output.DebugLine("command kmm body - {0}", commandKmmBody.ToString()); KmmFrame commandKmmFrame = new KmmFrame(commandKmmBody); Output.DebugLine("command kmm frame - {0}", commandKmmFrame.ToString()); byte[] toRadio = commandKmmFrame.ToBytes(); byte[] fromRadio; try { fromRadio = Network.QueryRadio(toRadio); } catch (Exception ex) { Output.ErrorLine("unable to connect to radio: {0}", ex.Message); return -1; } KmmFrame responseKmmFrame = new KmmFrame(fromRadio); Output.DebugLine("response kmm frame - {0}", responseKmmFrame.ToString()); KmmBody responseKmmBody = responseKmmFrame.KmmBody; if (responseKmmBody is DeleteAuthenticationKeyResponse) { Output.DebugLine("received DeleteAuthenticationKeyResponse kmm"); DeleteAuthenticationKeyResponse deleteAuthenticationKeyResponse = responseKmmBody as DeleteAuthenticationKeyResponse; Output.DebugLine("response kmm body - {0}", deleteAuthenticationKeyResponse.ToString()); Output.DebugLine("response suid - {0}", deleteAuthenticationKeyResponse.SuId.ToString()); if (deleteAuthenticationKeyResponse.Status == Status.CommandWasPerformed) { return 0; } else { Output.ErrorLine("abnormal response - status: {0} (0x{1:X2})", deleteAuthenticationKeyResponse.Status.ToString(), (byte)deleteAuthenticationKeyResponse.Status); return -1; } } else if (responseKmmBody is NegativeAcknowledgement) { Output.ErrorLine("received NegativeAcknowledgement kmm"); NegativeAcknowledgement negativeAcknowledgement = responseKmmBody as NegativeAcknowledgement; Output.DebugLine("response kmm body - {0}", negativeAcknowledgement.ToString()); return -1; } else { Output.ErrorLine("received unexpected kmm"); return -1; } } public static int ListActiveSuId() { Output.DebugLine("ListActiveSuId()"); InventoryCommandListActiveSuId commandKmmBody = new InventoryCommandListActiveSuId(); Output.DebugLine("command kmm body - {0}", commandKmmBody.ToString()); KmmFrame commandKmmFrame = new KmmFrame(commandKmmBody); Output.DebugLine("command kmm frame - {0}", commandKmmFrame.ToString()); byte[] toRadio = commandKmmFrame.ToBytes(); byte[] fromRadio; try { fromRadio = Network.QueryRadio(toRadio); } catch (Exception ex) { Output.ErrorLine("unable to connect to radio: {0}", ex.Message); return -1; } KmmFrame responseKmmFrame = new KmmFrame(fromRadio); Output.DebugLine("response kmm frame - {0}", responseKmmFrame.ToString()); KmmBody responseKmmBody = responseKmmFrame.KmmBody; if (responseKmmBody is InventoryResponseListActiveSuId) { Output.DebugLine("received InventoryResponseListActiveSuId kmm"); InventoryResponseListActiveSuId inventoryResponseListActiveSuId = responseKmmBody as InventoryResponseListActiveSuId; Output.DebugLine("response kmm body - {0}", inventoryResponseListActiveSuId.ToString()); Output.DebugLine("response suid - {0}", inventoryResponseListActiveSuId.SuId.ToString()); if (inventoryResponseListActiveSuId.Status == Status.CommandWasPerformed) { Output.InfoLine("WACN: 0x{0:X}, System: 0x{1:X}, Unit: 0x{2:X}, Key Assigned: {3}, Is Active: {4}", inventoryResponseListActiveSuId.SuId.WacnId, inventoryResponseListActiveSuId.SuId.SystemId, inventoryResponseListActiveSuId.SuId.UnitId, inventoryResponseListActiveSuId.KeyAssigned, inventoryResponseListActiveSuId.ActiveSuId); return 0; } else { Output.ErrorLine("abnormal response - status: {0} (0x{1:X2})", inventoryResponseListActiveSuId.Status.ToString(), (byte)inventoryResponseListActiveSuId.Status); return -1; } } else if (responseKmmBody is NegativeAcknowledgement) { Output.ErrorLine("received NegativeAcknowledgement kmm"); NegativeAcknowledgement negativeAcknowledgement = responseKmmBody as NegativeAcknowledgement; Output.DebugLine("response kmm body - {0}", negativeAcknowledgement.ToString()); return -1; } else { Output.ErrorLine("received unexpected kmm"); return -1; } } public static int ListSuIdItems() { Output.DebugLine("ListSuIdItems()"); bool needsAnotherRun = true; int inventoryMarker = 0; while (needsAnotherRun) { InventoryCommandListSuIdItems commandKmmBody = new InventoryCommandListSuIdItems(inventoryMarker, 59); Output.DebugLine("command kmm body - {0}", commandKmmBody.ToString()); KmmFrame commandKmmFrame = new KmmFrame(commandKmmBody); Output.DebugLine("command kmm frame - {0}", commandKmmFrame.ToString()); byte[] toRadio = commandKmmFrame.ToBytes(); byte[] fromRadio; try { fromRadio = Network.QueryRadio(toRadio); } catch (Exception ex) { Output.ErrorLine("unable to connect to radio: {0}", ex.Message); return -1; } KmmFrame responseKmmFrame = new KmmFrame(fromRadio); Output.DebugLine("response kmm frame - {0}", responseKmmFrame.ToString()); KmmBody responseKmmBody = responseKmmFrame.KmmBody; if (responseKmmBody is InventoryResponseListSuIdItems) { Output.DebugLine("received InventoryResponseListSuIdItems kmm"); InventoryResponseListSuIdItems inventoryResponseListSuIdItems = responseKmmBody as InventoryResponseListSuIdItems; Output.DebugLine("response kmm body - {0}", inventoryResponseListSuIdItems.ToString()); inventoryMarker = inventoryResponseListSuIdItems.InventoryMarker; Output.DebugLine("inventory marker - {0}", inventoryMarker); if (inventoryMarker > 0) { needsAnotherRun = true; } else { needsAnotherRun = false; } foreach (SuIdStatus responseSuIdStatus in inventoryResponseListSuIdItems.SuIdStatuses) { Output.InfoLine("WACN: 0x{0:X}, System: 0x{1:X}, Unit: 0x{2:X}, Key Assigned: {3}, Is Active: {4}", responseSuIdStatus.SuId.WacnId, responseSuIdStatus.SuId.SystemId, responseSuIdStatus.SuId.UnitId, responseSuIdStatus.KeyAssigned, responseSuIdStatus.ActiveSuId); } } else if (responseKmmBody is NegativeAcknowledgement) { Output.ErrorLine("received NegativeAcknowledgement kmm"); NegativeAcknowledgement negativeAcknowledgement = responseKmmBody as NegativeAcknowledgement; Output.DebugLine("response kmm body - {0}", negativeAcknowledgement.ToString()); return -1; } else { Output.ErrorLine("received unexpected kmm"); return -1; } } return 0; } } }
using eMAM.Data.Models; using eMAM.Service.DbServices.Contracts; using eMAM.Service.DTO; using eMAM.Service.UserServices.Contracts; using eMAM.UI.Areas.SuperAdmin.Models; using eMAM.UI.Mappers; using eMAM.UI.Utills; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; //TODO to finalize namespace eMAM.UI.Areas.Manager.Controllers { public class DashboardController : Controller { private readonly IUserService userService; private readonly UserManager<User> userManager; private readonly IUserViewModelMapper<User, UserViewModel> userMapper; public DashboardController(IUserService userService, UserManager<User> userManager, IUserViewModelMapper<User, UserViewModel> userMapper) { this.userService = userService ?? throw new ArgumentNullException(nameof(userService)); this.userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); this.userMapper = userMapper ?? throw new ArgumentNullException(nameof(userMapper)); } public IActionResult Index() { return View(); } [Area("Manager")] [Route("manager")] [Authorize(Roles = "Manager")] public async Task<IActionResult> Users(int? pageNumber) { var pageSize = 10; var users = this.userService.GetAllUsersQuery(); var page = await PaginatedList<User>.CreateAsync(users, pageNumber ?? 1, pageSize); page.Reverse(); UserViewModel model = new UserViewModel { HasNextPage = page.HasNextPage, HasPreviousPage = page.HasPreviousPage, PageIndex = page.PageIndex, TotalPages = page.TotalPages, }; foreach (var user in page) { var element = await this.userMapper.MapFrom(user); model.UsersList.Add(element); } return View(model); } [Area("Manager")] [Route("manager/ChangeUserRole")] [Authorize(Roles = "Manager")] public async Task<IActionResult> ToggleRoleBetweenUserOperator(string userId) { try { var user = await this.userService.ToggleRoleBetweenUserOperatorAsync(userId); } catch (Exception) { return BadRequest(); } return Ok(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using SkywalkingDemo.Model; using SkywalkingDemo.Repository; namespace SkywalkingDemo.Controllers { [ApiController] [Route("[controller]")] public class TestController : ControllerBase { private readonly ILogger<TestController> _logger; private readonly TestRepository _testRepository; public TestController(ILogger<TestController> logger,TestRepository testRepository) { _logger = logger; _testRepository = testRepository; } [HttpGet] public string Get() { //var list=_testRepository.GetList<AdminInfo>(); var list = _testRepository.GetList<TaskJobInfo>(); return JsonConvert.SerializeObject(list); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CEMAPI.Models { public class CancellationDetails { public int offerId { get; set; } public string cancellationType { get; set; } public string cancellationReason { get; set; } public int termSheetValue { get; set; } public string customerId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DanceSequence : MonoBehaviour { public enum DanceStep { Up, Down, Left, Right } public DanceStep[] DanceSequenceSteps; public Sprite[] spriteUp; public Sprite[] spriteDown; public Sprite[] spriteLeft; public Sprite[] spriteRight; public SpriteRenderer[] stepDisplays; public DiscoController discoController; // Start is called before the first frame update void Start() { //InitializeDanceSequence(); HideSequence(); } public void HideSequence() { Debug.Log("HideSequence"); if (stepDisplays == null) return; foreach (SpriteRenderer rend in stepDisplays) { rend.enabled = false; } } public void ShowSequence() { Debug.Log("ShowSequence"); InitializeDanceSequence(); ResetDanceSequence(); //foreach (SpriteRenderer rend in stepDisplays) //{ // rend.enabled = true; //} } public bool CheckStepValidityAgainstInput(string inputString, int stepIndex) { bool bInputIsValid = false; switch (inputString) { case "Up": bInputIsValid = DanceSequenceSteps[stepIndex] == DanceStep.Up; break; case "Down": bInputIsValid = DanceSequenceSteps[stepIndex] == DanceStep.Down; break; case "Left": bInputIsValid = DanceSequenceSteps[stepIndex] == DanceStep.Left; break; case "Right": bInputIsValid = DanceSequenceSteps[stepIndex] == DanceStep.Right; break; } Debug.Log(bInputIsValid); return bInputIsValid; } public void ValidateStep(int danceStepIndex) { danceStepIndex = Mathf.Min(3, danceStepIndex); SpriteRenderer renderer = stepDisplays[danceStepIndex]; ChangeSpriteFromStepValue(stepDisplays[danceStepIndex], DanceSequenceSteps[danceStepIndex], 1); } public void ResetDanceSequence() { int index = 0; foreach (SpriteRenderer rend in stepDisplays) { ChangeSpriteFromStepValue(rend, DanceSequenceSteps[index], 0); index++; } } private DanceStep GenerateRandomStep() { int rand = Random.Range(0, 4); DanceStep step = DanceStep.Up; switch (rand) { case 0: step = DanceStep.Up; break; case 1: step = DanceStep.Down; break; case 2: step = DanceStep.Left; break; case 3: step = DanceStep.Right; break; } return step; } private void ChangeSpriteFromStepValue(SpriteRenderer renderer, DanceStep step, int type) { switch (step) { case DanceStep.Up: renderer.sprite = spriteUp[type]; break; case DanceStep.Down: renderer.sprite = spriteDown[type]; break; case DanceStep.Left: renderer.sprite = spriteLeft[type]; break; case DanceStep.Right: renderer.sprite = spriteRight[type]; break; } } public void InitializeDanceSequence() { DanceSequenceSteps = new DanceStep[4]; int index = 0; foreach (DanceStep step in DanceSequenceSteps) { DanceSequenceSteps[index] = GenerateRandomStep(); ChangeSpriteFromStepValue(stepDisplays[index], DanceSequenceSteps[index],0); stepDisplays[index].enabled = true; stepDisplays[index].material.SetColor("_Color", discoController.discoColor); index++; } } }
using System; using System.Collections.Generic; namespace Misc { public class Change { private static readonly IDictionary<int, IEnumerable<int>> CoinOptions = new Dictionary<int, IEnumerable<int>> { {100, new List<int> {100, 50, 25, 10, 5, 1} }, { 50, new List<int> { 50, 25, 10, 5, 1} }, { 25, new List<int> { 25, 10, 5, 1 } }, { 10, new List<int> { 10, 5, 1} }, { 5, new List<int> { 5, 1} }, { 1, new List<int> { 1 } }, }; public static int CountOf(int cents, IEnumerable<int> coins = default(IEnumerable<int>)) { if (cents < 0) throw new ArgumentOutOfRangeException(nameof(cents), "Use this method for positive values owed"); if (cents <= 1) return cents; var total = 0; if (coins == default(IEnumerable<int>)) coins = CoinOptions[25]; foreach (var coin in coins) { if (coin <= cents) { total += CountOf(cents - coin, CoinOptions[coin]); if (coin == cents) total++; } } return total; } } }
using AlgorithmProblems.Linked_List.Linked_List_Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Linked_List { /// <summary> /// Do an insertion in the sorted circular linked list /// </summary> class SortedCircularLinkedList { public SingleLinkedListNode<int> Head { get; set; } /// <summary> /// inserts a new value in the sorted linked list /// </summary> /// <param name="value"></param> public void Insert(int value) { if(Head == null) { // this the first element Head = new SingleLinkedListNode<int>(value); Head.NextNode = Head; } else if(Head.Data >= value) { // new node needs to be inserted at the start of the linked list SingleLinkedListNode<int> newHeadNode = new SingleLinkedListNode<int>(value); newHeadNode.NextNode = Head; // make the last node point to the newHeadNode SingleLinkedListNode<int> currentNode = Head; while (currentNode.NextNode != Head) { currentNode = currentNode.NextNode; } currentNode.NextNode = newHeadNode; // make the newHeadNode = Head Head = newHeadNode; } else { // the insertion needs to happen at a different place other than the head SingleLinkedListNode<int> current = Head; while (current.NextNode != Head && current.NextNode.Data < value) { // keep going fwd till the cycle ends or the node becomes greater than value current = current.NextNode; } // do the new node insertion after the current node and assign current.NextNode to newNode.NextNode SingleLinkedListNode<int> nodeToInsert = new SingleLinkedListNode<int>(value); nodeToInsert.NextNode = current.NextNode; current.NextNode = nodeToInsert; } } public void Delete(int value) { if(Head != null) { SingleLinkedListNode<int> currentNode = Head; if (Head.Data == value) { currentNode = Head; // go to the end of the cycle while(currentNode.NextNode != Head) { currentNode = currentNode.NextNode; } // delete the head currentNode.NextNode = Head.NextNode; Head = Head.NextNode; } else { while (currentNode.NextNode != Head) { if (currentNode.NextNode.Data == value) { // we need to delete currentNode.NextNode currentNode.NextNode = currentNode.NextNode.NextNode; break; } currentNode = currentNode.NextNode; } } } } /// <summary> /// Prints the circular linked list /// </summary> public void Print() { SingleLinkedListNode<int> current = Head; if (current != null) { do { Console.Write("{0} ->", current.Data); current = current.NextNode; } while (current != Head); Console.WriteLine(); } } public static void TestCircularLinkedList() { SortedCircularLinkedList scll = new SortedCircularLinkedList(); scll.Insert(5); scll.Insert(6); scll.Insert(8); scll.Insert(1); scll.Insert(3); scll.Insert(9); scll.Insert(3); scll.Print(); scll.Delete(3); scll.Print(); scll.Delete(1); scll.Print(); scll.Delete(9); scll.Print(); } } }
 namespace Thesis { public abstract class ProceduralObject { public UnityEngine.GameObject gameObject; } } // namespace Thesis
using System.Windows.Controls; namespace CODE.Framework.Wpf.Theme.Newsroom.StandardViews { /// <summary> /// Interaction logic for LargeBlockAndTexct02.xaml /// </summary> public partial class LargeBlockAndText02 : Grid { /// <summary> /// Initializes a new instance of the <see cref="LargeBlockAndText02"/> class. /// </summary> public LargeBlockAndText02() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LeanEngine.Entity; using com.Sconit.Entity.SI.SD_TMS; using AutoMapper; namespace com.Sconit.Service.SI.Impl { public class SD_TMSMgrImpl : BaseMgr, ISD_TMSMgr { public IOrderMgr orderMgr { get; set; } public TransportOrderMaster GetTransOrder(string orderNo) { var transOrderMaster = new Entity.TMS.TransportOrderMaster(); if (!string.IsNullOrEmpty(orderNo)) { transOrderMaster = this.genericMgr.FindById<Entity.TMS.TransportOrderMaster>(orderNo); if (transOrderMaster == null || string.IsNullOrEmpty(transOrderMaster.OrderNo)) { throw new BusinessException("运单号错误。"); } var sdTransOrderMaster = Mapper.Map<Entity.TMS.TransportOrderMaster, TransportOrderMaster>(transOrderMaster); transOrderMaster.TransportOrderDetailList = this.genericMgr.FindAll<Entity.TMS.TransportOrderDetail>("from TransportOrderDetail to where to.OrderNo=?", orderNo); if (transOrderMaster.TransportOrderDetailList.Count > 0) { Mapper.Map<IList<Entity.TMS.TransportOrderDetail>, List<TransportOrderDetail>>(transOrderMaster.TransportOrderDetailList).OrderBy(s => s.Sequence).ToList(); } return sdTransOrderMaster; } else { throw new BusinessException("请输入运单号。"); } } public void Ship(string transOrder, List<string> huIds) { orderMgr.ProcessShipPlanResult4Hu(transOrder, huIds, DateTime.Now); } } }
namespace Merchello.UkFest.Web.Models { using Merchello.UkFest.Web.Ditto.ValueResolvers; using Our.Umbraco.Ditto; /// <summary> /// The render view for the basket page. /// </summary> public class BasketView { /// <summary> /// Gets or sets the <see cref="UpdateBasket"/> model. /// </summary> [DittoValueResolver(typeof(UpdateBasketValueResolver))] public UpdateBasket UpdateBasket { get; set; } /// <summary> /// Gets or sets the order summary. /// </summary> [DittoValueResolver(typeof(OrderSummaryValueResolver))] public OrderSummary OrderSummary { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Kupid { public class Komunikator { #region Atributi List<Korisnik> korisnici; List<Chat> razgovori; #endregion #region Properties public List<Korisnik> Korisnici { get => korisnici; } public List<Chat> Razgovori { get => razgovori; } #endregion #region Konstruktor public Komunikator() { korisnici = new List<Korisnik>(); razgovori = new List<Chat>(); } #endregion #region Metode public void RadSaKorisnikom(Korisnik k, int opcija) { if (opcija == 0) { Korisnik postojeci = null; foreach (Korisnik korisnik in korisnici) if (korisnik.Ime == k.Ime) postojeci = korisnik; if (postojeci != null) throw new InvalidOperationException("Korisnik već postoji!"); korisnici.Add(k); } else if (opcija == 1) { Korisnik postojeci = null; foreach (Korisnik korisnik in korisnici) if (korisnik.Ime == k.Ime) postojeci = korisnik; if (postojeci == null) throw new InvalidOperationException("Korisnik ne postoji!"); korisnici.Remove(k); List<Chat> razgovoriZaBrisanje = new List<Chat>(); foreach(Chat c in razgovori) { bool postoji = false; foreach (Korisnik korisnik in c.Korisnici) { if (korisnik.Ime == k.Ime) postoji = true; } if (postoji) razgovoriZaBrisanje.Add(c); } foreach (Chat brisanje in razgovoriZaBrisanje) razgovori.Remove(brisanje); } } public void DodavanjeRazgovora(List<Korisnik> korisnici, bool grupniChat) { if (korisnici == null || korisnici.Count < 2 || (!grupniChat && korisnici.Count > 2)) throw new ArgumentException("Nemoguće dodati razgovor!"); if (grupniChat) razgovori.Add(new GrupniChat(korisnici)); else razgovori.Add(new Chat(korisnici[0], korisnici[1])); } /// <summary> /// Metoda u kojoj se vrši pronalazak svih poruka koje u sebi sadrže traženi sadržaj. /// Ukoliko je sadržaj prazan ili ne postoji nijedan chat, baca se izuzetak. /// U razmatranje se uzimaju i grupni, i individualni chatovi, a ne smije se uzeti u razmatranje /// nijedan chat u kojem se nalazi korisnik sa imenom "admin". /// </summary> public List<Poruka> IzlistavanjeSvihPorukaSaSadržajem(string sadržaj) { if (razgovori.Count < 1 || String.IsNullOrWhiteSpace(sadržaj)) throw new Exception("Izlistavanje nije moguće!"); List<Poruka> poruke = new List<Poruka>(); foreach(Chat razgovor in razgovori) { if (razgovor.Korisnici.Find(k => k.Ime == "admin") != null) continue; foreach (Poruka p in razgovor.Poruke) { if (p.Sadrzaj.Contains(sadržaj)) poruke.Add(p); } } return poruke; } public bool DaLiJeSpajanjeUspjesno(Chat c, IRecenzija r) { if (c is GrupniChat) throw new InvalidOperationException("Grupni chatovi nisu podržani!"); if (c.Poruke.Find(poruka => poruka.IzračunajKompatibilnostKorisnika() == 100) != null && r.DajUtisak() == "Pozitivan") return true; else return false; } public void SpajanjeKorisnika() { bool stvorenRazgovor = false; foreach(Korisnik prvi in korisnici) { foreach(Korisnik drugi in korisnici) { if (prvi.Ime == drugi.Ime) continue; if (razgovori.Find(r => r.Korisnici.Find(k => k.Ime == prvi.Ime) != null && r.Korisnici.Find(k => k.Ime == drugi.Ime) != null) != null) continue; if (prvi.Lokacija == drugi.ZeljenaLokacija || prvi.ZeljenaLokacija == drugi.Lokacija || prvi.Godine == drugi.Godine) { stvorenRazgovor = true; Chat noviChat = new Chat(prvi, drugi); razgovori.Add(noviChat); } } } if (!stvorenRazgovor) throw new ArgumentException("Nemoguće spojiti korisnike!"); } #endregion } }
using System; using System.Collections; 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 learn_180323_wsmessage { public partial class Agv : Form { public Agv() { InitializeComponent(); } Hashtable hs = new Hashtable(); private void Agv_Load(object sender, EventArgs e) { string[] type = new string[] { "心跳", "申请动作完成", "申请路口","释放路口","申请小车左侧上料","小车上料完成", "申请小车左侧下料","小车下料完成","已开始充电","已结束充电","汇流口","工位点" }; int[] num = new int[] { 0, 3, 1, 2, 3, 4, 5,6,7,8,1,2 }; for (int i = 0; i < type.Length; i++) { hs.Add(type[i], num[i]); } comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; comboBox3.DropDownStyle = ComboBoxStyle.DropDownList; comboBox4.DropDownStyle = ComboBoxStyle.DropDownList; panel1.Visible = false; panel2.Visible = false; textBox5.Text ="0"; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text = hs[comboBox1.Text].ToString(); if(int.Parse(textBox1.Text)==0) { panel1.Show(); panel2.Visible = false; } else { panel2.Show(); panel1.Visible = false; } } private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { textBox6.Text = hs[comboBox3.Text].ToString(); } private void comboBox4_SelectedIndexChanged(object sender, EventArgs e) { textBox9.Text = hs[comboBox4.Text].ToString(); } public byte[] pinJieAgvBaoWen() { byte[] data = new byte[100]; data[0] = 0; data[1] = Convert.ToByte(textBox1.Text); byte[] address = Encoding.ASCII.GetBytes(textBox2.Text); for (int i = 3; i < (3 + address.Length); i++) { data[i] = address[i - 3]; } data[13] = data[14] = 0; if (Int16.Parse(textBox1.Text) == 0) { data[2] = 28; byte[] vol=Encoding.ASCII.GetBytes(textBox3.Text); for (int i = 15; i < (15 + vol.Length); i++) { data[i] = vol[i-15]; } byte[] state = Encoding.ASCII.GetBytes(textBox4.Text); data[19] = state[0]; data[20] = state[1]; data[21] = Convert.ToByte(comboBox2.Text); byte[] error= Encoding.ASCII.GetBytes(textBox5.Text); for (int i = 22; i < (22+ error.Length); i++) { data[i] = error[i-22]; } data[27] = CRC(data, 28); } else if (Int16.Parse(textBox3.Text) == 3) { data[2] = 69; data[15] = Convert.ToByte(textBox6.Text); data[16] = Convert.ToByte(textBox9.Text); data[17] = Convert.ToByte(textBox7.Text); byte[] taskNo = Encoding.ASCII.GetBytes(textBox8.Text); for (int i = 18; i < (18 + taskNo.Length); i++) { data[i] = taskNo[i - 18]; } data[68] = CRC(data, 69); } return data; } public byte CRC(byte[] byt, int Length) { byte crc = 0; crc = (byte)(byt[0] ^ byt[1]); for (int i = 2; i < Length - 1; i++) { crc = (byte)(crc ^ byt[i]); } return crc; } private void button1_Click(object sender, EventArgs e) { byte[] agvMessage=pinJieAgvBaoWen(); } } }
using EPI.Searching; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Searching { [TestClass] public class SearchEntryEqualToIndexUnitTest { private readonly int[] _sortedDistinctArray = new[] { -2, 0, 2, 3, 6, 7, 9}; private readonly int[] _sortedArray = new[] { -14, -10, 2, 108, 108, 243, 285, 285, 285, 401 }; private readonly int[] _indexArray = new[] {0, 1, 2, 3, 4, 5, 6}; [TestMethod] public void BinarySearchEntryEqualToItsIndex() { BinarySearchEntryEqualToIndex.SearchEntryEqualToItsIndex(_sortedDistinctArray).Should().Be(3); BinarySearchEntryEqualToIndex.SearchEntryEqualToItsIndex(_sortedArray).Should().Be(2); BinarySearchEntryEqualToIndex.SearchEntryEqualToItsIndex(_indexArray).Should().Be(3); } } }
#define USEFINGERPRINT using System; using System.Collections.Generic; using System.Text; namespace Intermec.Printer.Language.Fingerprint { public class Demo { public static string ESCP_PRODLIST2 { get { string s = ""; s+="\x1B@\x1Bw!\x1Bw!\x1Bw!\x1Bw!LOCATION# 111111 ROUTE# 222222\n"; s+="\x1Bw!REP# 123456 06/26/08 08:52 PAGE 1\n"; s+="\x1Bw!\n"; s+="\x1Bw!\x1Bw& ITEM LIST\n"; s+="\x1Bw&\x1Bw!\n"; s+="\x1Bw! ITEM# DESCRIPTION\n"; s+="\x1Bw!\n"; s+="\x1Bw! 1000 Koala Cola 4/12-6\n"; s+="\x1Bw! 1001 Dt Koala Cola 4/12-6\n"; s+="\x1Bw! 1100 Lemon Lime 4/12-6\n"; s+="\x1Bw! 1101 Orange Soda 4/12-6\n"; s+="\x1Bw! 1200 Root Beer 4/12-6\n"; s+="\x1Bw! 2000 Koala Cola 2/12-12\n"; s+="\x1Bw! 2001 Dt Koala Cola2/12-12\n"; s+="\x1Bw! 2100 Lemon Lime 2/12-12\n"; s+="\x1Bw! 2101 Orange Soda 2/12-12\n"; s+="\x1Bw! 2200 Root Beer 2/12-12\n"; s+="\x1Bw! 3000 Koala Cola 8/1-2L\n"; s+="\x1Bw! 3001 Dt Koala Cola 8/1-2L\n"; s+="\x1Bw! 3100 Lemon Lime 8/1-2L\n"; s+="\x1Bw! 3101 Orange Soda 8/1-2L\n"; s+="\x1Bw! 3200 Root Beer 8/1-2L\n"; s+="\x1Bw!\n"; s+="\x1Bw!\x1Bw& MISC\x1Bw!\n"; s+="\x1Bw!\n"; s+="\x1Bw! 9000 Empty Cans (240)\n"; s+="\x1Bw! 9001 Empty Can Single \n"; s+="\x1Bw! 9002 Empty 2L (80) \n"; s+="\x1Bw!\n"; s += "\x1Bw!\n"; s += "\x1Bw!\n"; s += "\x1Bw!\n"; return s; } } public static string IPL_2_WalmartLabel() { //IPL string s = ""; s+="<STX><SI>W406<ETX>\r\n"; s+="<STX><ESC>C<ETX>\r\n"; s+="<STX><ESC>P<ETX>\r\n"; s+="<STX>E2;F2;<ETX>\r\n"; s+="<STX>L1;f1;o809,745;l740;w4<ETX>\r\n"; s+="<STX>L2;f1;o1012,745;l740;w4<ETX>\r\n"; s+="<STX>L6;f0;o810,445;l203;w4<ETX>\r\n"; s+="<STX>L7;f0;o1015,325;l152;w4<ETX>\r\n"; s+="<STX>H8;f3;o1165,10;c61;b0;h11;w11;d3,SHIP FROM:<ETX>\r\n"; s+="<STX>H9;f3;o1165,335;c61;b0;h11;w11;d3,SHIP TO:<ETX>\r\n"; s+="<STX>H10;f3;o1130,10;c61;b0;h14;w14;d3,Intermec Technologies<ETX>\r\n"; s+="<STX>H11;f3;o1095,10;c61;b0;h14;w14;d3,6001 36th Ave. West<ETX>\r\n"; s+="<STX>H12;f3;o1060,10;c61;b0;h14;w14;d3,Everett, WA 98203<ETX>\r\n"; s+="<STX>H13;f3;o1130,335;c61;b0;h17;w17;d3,Wal-Mart Dist Center #04<ETX>\r\n"; s+="<STX>H14;f3;o1095,335;c61;b0;h17;w17;d3,1901 Hwy 102 East<ETX>\r\n"; s+="<STX>H15;f3;o1060,335;c61;b0;h17;w17;d3,Bentonville, AR<ETX>\r\n"; s+="<STX>H16;f3;o1060,580;c61;b0;h17;w17;d3,72712<ETX>\r\n"; s+="<STX>B17;f3;o925,65;c6,0,0,3;w4;h102;d3,42072712<ETX>\r\n"; s+="<STX>H18;f3;o980,120;c61;b0;h20;w20;d3,(420) 72712<ETX>\r\n"; s+="<STX>H19;f3;o1010,10;c61;b0;h11;w11;d3,SHIP TO POSTAL CODE:<ETX>\r\n"; s+="<STX>H20;f3;o1010,460;c61;b0;h11;w11;d3,CARRIER:<ETX>\r\n"; s+="<STX>H22;f3;o965,460;c61;b0;h20;w20;d3,PRO #:<ETX>\r\n"; s+="<STX>H23;f3;o905,460;c61;b0;h20;w20;d3,B/L #:<ETX>\r\n"; s+="<STX>s2;S2;<ETX>\r\n"; s+="<STX>Ma,2;q1;O0,1165;R;<ETX>\r\n"; s+="<STX>D0<ETX>\r\n"; s+="<STX>R;<ESC>G2<CAN><ETB><ETX>\r\n"; return s; } public static string FP_2_WalmartLabel() { //Fingerprint: string s = ""; s += "CLIP OFF\r\n"; s += "CLIP BARCODE OFF\r\n"; s += "XORMODE OFF\r\n"; s += "AN 7\r\n"; s += "NASC -2\r\n"; s += "MAG 1,1:PP 399,750:DIR 2:FT \"Swiss 721 Bold BT\",8,0,104\r\n"; s += "NI:PT \"SHIP FROM:\"\r\n"; s += "DIR 4:PP 203,20:PL 770,3\r\n"; s += "DIR 1:PP 201,407:PL 203,3\r\n"; s += "PP 3,304:PL 198,3\r\n"; s += "PP 203,420:PL 150,3\r\n"; s += "PP 331,750:DIR 2:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"Intermec Technologies\"\r\n"; s += "PP 299,750:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"6001 36th Ave. West\"\r\n"; s += "PP 268,750:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"Everett, WA 98203\"\r\n"; s += "PP 401,399:FT \"Swiss 721 Bold BT\",8,0,104\r\n"; s += "NI:PT \"SHIP TO:\"\r\n"; s += "PP 331,393:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"Wal-Mart Dist Center #04\"\r\n"; s += "PP 300,393:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"1901 Hwy 102 East\"\r\n"; s += "PP 268,393:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"Bentonville, AR 72712\"\r\n"; s += "PP 192,292:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"CARRIER:\"\r\n"; s += "PP 147,292:FT \"Swiss 721 BT\",10,0,100\r\n"; s += "NI:PT \"PRO #:\"\r\n"; s += "PP 102,292:FT \"Swiss 721 BT\",10,0,100\r\n"; s += "NI:PT \"B/L #:\"\r\n"; s += "PP 191,750:FT \"Swiss 721 BT\",8,0,104\r\n"; s += "NI:PT \"SHIP TO POSTAL CODE:\"\r\n"; s += "PP 111,720\r\n"; s += "BT \"CODE128B\"\r\n"; s += "BM 2\r\n"; s += "BH 80\r\n"; s += "BF OFF\r\n"; s += "PB \" (420) 72712\"\r\n"; s += "PP 134,694:FT \"Swiss 721 Bold BT\",7,0,150\r\n"; s += "NI:PT \" (420) 72712\"\r\n"; s += "PF\r\n"; return s; } public static string smallLabel() { //Fingerprint: string s=""; s+="10 PRPOS 0,0\r\n"; s+="20 DIR 4\r\n"; s+="30 PRPOS 300,30\r\n"; s+="40 FONT \"Swiss 721 BT\",36\r\n"; s+="50 PRTXT \"TEXT PRINTING Hello Printer\"\r\n"; s+="60 PRPOS 30,280\r\n"; s+="70 PRINTFEED 1\r\n"; s+="RUN\r\n"; return s; } public static string getFPcode(string szText) { string sText = szText; string[] txtAr = sText.Split('|'); #if USEFINGERPRINT sText = ""; sText += "10 SETUP \"MEDIA,MEDIA SIZE,LENGTH,600\""; sText += "\r\n"; sText += "20 ON ERROR GOTO 1000"; sText += "\r\n"; sText += "30 CLIP ON"; sText += "\r\n"; sText += "40 DIR 3"; sText += "\r\n"; sText += "50 FONT \"Swiss 721 BT\",20"; sText += "\r\n"; sText += "60 PRPOS 500,100"; sText += "\r\n"; sText += "70 PRTXT \"" + txtAr[0] + "\""; sText += "\r\n"; sText += "80 PRPOS 500,150"; sText += "\r\n"; sText += "90 PRTXT \"" + txtAr[1] + "\""; sText += "\r\n"; sText += "100 PRPOS 500,200"; sText += "\r\n"; sText += "110 PRTXT \"" + txtAr[2] + "\""; sText += "\r\n"; sText += "200 PRPOS 500,350"; sText += "\r\n"; sText += "205 DIR 1"; sText += "\r\n"; sText += "210 ALIGN 9"; sText += "\r\n"; sText += "220 BARSET \"PDF417\",1,1,2,6,5,1,2,0,5,0"; sText += "\r\n"; sText += "230 PRBAR \"" + txtAr[0] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[1] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[2] + "\""; sText += "\r\n"; sText += "300 PRINTFEED 1"; sText += "\r\n"; sText += "310 FORMFEED"; sText += "\r\n"; sText += "320 END"; sText += "\r\n"; sText += "1000 PRINT ERR$(ERR)"; sText += "\r\n"; sText += "1010 RESUME NEXT"; sText += "\r\n"; sText += "RUN"; sText += "\r\n"; #endif return sText; } public static string getInitPB22() { string sText = ""; sText = "VERBOFF\r\n"; sText += "CLOSE\r\n"; sText += "LED 0 OFF:LED 1 OFF\r\n"; sText += "NEW \r\n"; sText += "OPEN \"tmp:setup.sys\" for output as #2\r\n"; sText += "PRINT#2, \"MEDIA,MEDIA SIZE,XSTART,0\"\r\n"; sText += "PRINT#2, \"MEDIA,MEDIA SIZE,WIDTH,384\"\r\n"; sText += "PRINT #2,\"MEDIA,MEDIA SIZE,LENGTH,889\"\r\n"; //756= length(cm)*72 sText += "PRINT #2,\"MEDIA,MEDIA TYPE,LABEL (w GAPS)\"\r\n"; sText += "PRINT #2,\"FEEDADJ,STARTADJ,0\"\r\n"; //-80 sText += "PRINT #2,\"FEEDADJ,STOPADJ,0\"\r\n"; //80 sText += "PRINT #2,\"PRINT DEFS,PRINT SPEED,100\"\r\n"; sText += "PRINT #2,\"MEDIA,CONTRAST,+0%\"\r\n"; sText += "PRINT #2, \"MEDIA,PAPER TYPE,DIRECT THERMAL\"\r\n"; sText += "PRINT #2, \"MEDIA,PAPER TYPE,DIRECT THERMAL,LABEL CONSTANT,85\"\r\n"; sText += "PRINT #2, \"MEDIA,PAPER TYPE,DIRECT THERMAL,LABEL FACTOR,40\"\r\n"; sText += "PRINT #2, \"RFID,OFF\" \r\n"; sText += "CLOSE #2\r\n"; sText += "Setup \"tmp:setup.sys\"\r\n"; sText += "Kill \"tmp:setup.sys\"\r\n"; sText += "new\r\n"; // sText += "OPEN \"tmp:CUT\" FOR OUTPUT AS #2"; sText += "\r\n"; sText += "PRINT #2,\"0\""; sText += "\r\n"; sText += "CLOSE #2"; sText += "\r\n"; sText += "open \"tmp:PAUSE\" for OUTPUT as #3"; sText += "\r\n"; sText += "PRINT #3,\"1\""; sText += "\r\n"; sText += "PRINT #3,\"1\""; sText += "\r\n"; sText += "CLOSE #3"; sText += "\r\n"; sText += "PRINT KEY OFF"; sText += "\r\n"; sText += "CUT OFF"; sText += "\r\n"; sText += "new"; sText += "\r\n"; sText += "VERBOFF"; sText += "\r\n"; sText += "OPTIMIZE \"BATCH\" ON"; sText += "\r\n"; sText += "OPTIMIZE \"PRINT\" OFF"; sText += "\r\n"; sText += "RIBBON SAVE OFF"; sText += "\r\n"; sText += "STORE OFF"; sText += "\r\n"; sText += "Close #1:open \"console:\" for output as #1"; sText += "\r\n"; sText += "print #1:print #1:Close #1"; sText += "\r\n"; return sText; } public static string getFPCode22(string szText) { string sText = szText; string[] txtAr = szText.Split('|'); int iLeft = 10; int iRowX = 10; int iRowDiff = 60; sText = ""; sText += "10 KEY(15) ON:KEY(19) ON"; sText += "\r\n"; sText += "20 open \"tmp:PAUSE\" for INPUT as #3"; sText += "\r\n"; sText += "30 INPUT #3,P$:PAUSE%=VAL(P$)"; sText += "\r\n"; sText += "40 CLOSE #3"; sText += "\r\n"; sText += "50 ON KEY(15) GOSUB 777777:ON KEY(19) GOSUB 777776"; sText += "\r\n"; sText += "60 CLOSE"; sText += "\r\n"; sText += "70 open \"console:\" for output as #1"; sText += "\r\n"; sText += "80 print #1, chr$(155) + \"1;H\";:print #1,\"BUSY \":CLOSE #1"; sText += "\r\n"; sText += "90 TROFF"; sText += "\r\n"; sText += "100 BARADJUST 1000,1000"; sText += "\r\n"; sText += "110 ON ERROR GOTO 150"; sText += "\r\n"; sText += "120 goto 600"; sText += "\r\n"; sText += "150 open \"console:\" for output as #1"; sText += "\r\n"; sText += "155 IF ERR=20 THEN GOTO 175"; sText += "\r\n"; sText += "156 IF ERR=1031 THEN GOTO 190"; sText += "\r\n"; sText += "157 IF ERR=1005 THEN GOTO 190"; sText += "\r\n"; sText += "158 IF ERR=1022 THEN GOTO 190"; sText += "\r\n"; sText += "159 IF ERR=1027 THEN GOTO 190"; sText += "\r\n"; sText += "160 print #1, chr$(155) + \"2;H\";:print #1,\"ERROR: \";err;"; sText += "\r\n"; sText += "165 CLOSE #1:LED 1 ON"; sText += "\r\n"; sText += "170 sound 800,20:resume next"; sText += "\r\n"; sText += "175 print #1,\"Line > 250 char\";chr$(13);"; sText += "\r\n"; sText += "180 CLOSE #1:LED 1 ON"; sText += "\r\n"; sText += "185 sound 800,20:resume next"; sText += "\r\n"; sText += "190 print #1, chr$(155) + \"2;H\";:print #1,\"ERROR: \";err;"; sText += "\r\n"; sText += "195 CLOSE #1 :LED 1 ON"; sText += "\r\n"; sText += "200 sound 800,20:BUSY1"; sText += "\r\n"; sText += "205 STATUS% = PRSTAT"; sText += "\r\n"; sText += "206 IF (STATUS% AND 1) THEN GOTO 205"; sText += "\r\n"; sText += "207 IF (STATUS% AND 4) THEN GOTO 205"; sText += "\r\n"; sText += "208 IF (STATUS% AND 8) THEN GOTO 205"; sText += "\r\n"; sText += "209 LED 1 OFF"; sText += "\r\n"; sText += "210 READY1:FF:FF:PF:resume next"; sText += "\r\n"; sText += "600 LED 1 OFF"; sText += "\r\n"; sText += "1010 GOSUB 10000"; sText += "\r\n"; sText += "1020 FOR A%=1 TO 1"; sText += "\r\n"; sText += "1030 IF PAUSE% < 0 THEN GOTO 1030"; sText += "\r\n"; sText += "1064 PF"; sText += "\r\n"; sText += "1090 next A%"; sText += "\r\n"; sText += "1100 open \"console:\" for output as #1"; sText += "\r\n"; sText += "1110 print #1, VERSION$"; sText += "\r\n"; sText += "1120 CLOSE #1"; sText += "\r\n"; sText += "1130 END"; sText += "\r\n"; sText += "10000 CLIP OFF"; sText += "\r\n"; sText += "10010 CLIP BARCODE OFF"; sText += "\r\n"; sText += "10020 XORMODE OFF"; sText += "\r\n"; sText += "10040 AN 7"; sText += "\r\n"; sText += "10050 NASC -2"; sText += "\r\n"; //first text line sText += "10060 MAG 1,1:PP " + iRowX.ToString() + "," + iLeft.ToString() + ":DIR 4:FT \"Swiss 721 BT\",20,0,101"; iRowX += iRowDiff; sText += "\r\n"; sText += "10070 NI:PT \"" + txtAr[0] + "\""; sText += "\r\n"; sText += "10090 PP " + iRowX.ToString() + "," + iLeft.ToString() + ":FT \"Swiss 721 BT\",20,0,101"; sText += "\r\n"; iRowX += iRowDiff; sText += "10100 NI:PT \"" + txtAr[1] + "\""; sText += "\r\n"; sText += "10120 PP " + iRowX.ToString() + "," + iLeft.ToString() + ":FT \"Swiss 721 BT\",20,0,102"; sText += "\r\n"; iRowX += iRowDiff; sText += "10130 NI:PT \"" + txtAr[2] + "\""; sText += "\r\n"; sText += "10150 PP 200,500"; sText += "\r\n"; sText += "10160 BARSET \"PDF417\",1,1,2,6,2,1,2,0,2,0"; sText += "\r\n"; sText += "10170 BF OFF"; sText += "\r\n"; sText += "10180 PRBAR \"" + txtAr[0] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[1] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[2] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[3] + "\"+CHR$(13)+CHR$(10)+\"" + txtAr[4] + "\""; // print barcode with prename, name, time, company, email sText += "\r\n"; sText += "10200 PP " + iRowX.ToString() + "," + iLeft.ToString() + ":FT \"Swiss 721 BT\",18,0,102"; sText += "\r\n"; iRowX += iRowDiff; sText += "10210 NI:PT \"" + txtAr[3] + "\""; sText += "\r\n"; sText += "10220 RETURN"; sText += "\r\n"; sText += "777776 FORMFEED:return"; sText += "\r\n"; sText += "777777 PAUSE% = PAUSE% * -1:open \"tmp:PAUSE\" for OUTPUT as #3:PRINT #3,STR$(PAUSE%):CLOSE #3:return"; sText += "\r\n"; sText += "Run"; sText += "\r\n"; //sText += "LED 0 ON"; //sText += "\r\n"; //sText += "VERBON"; //sText += "\r\n"; //sText += "PRINT KEY OFF"; //sText += "\r\n"; //sText += "CUT OFF"; //sText += "\r\n"; return sText; } /// <summary> /// /// </summary> /// <param name="sOldPrice"></param> /// <param name="sNewPrice"></param> /// <param name="iLang">not used</param> /// <returns></returns> public static string getPriceMark(string sOldPrice, string sNewPrice, int iLang) { StringBuilder sb = new StringBuilder(); string sReducedText = "...reduziert"; sb.Append("LAYOUT RUN \"c:PRICE_MARKDOWN.LAY\""); sb.Append("\r\n"); sb.Append("INPUT ON"); sb.Append("\r\n"); //sb.Append("...stark reduziert"); sb.Append("" + sReducedText); //starts with 0x02 sb.Append("\r\n"); //sb.Append("9,95"); sb.Append(sOldPrice); sb.Append("\r\n"); //sb.Append("2,85"); sb.Append(sNewPrice); sb.Append("\r\n"); sb.Append("76589"); sb.Append("\r\n"); //if(iLang==0) sb.Append("€"); sb.Append("\r\n"); sb.Append(""); //ends with 0x03 sb.Append("\r\n"); sb.Append("PF"); sb.Append("\r\n"); sb.Append("PRINT KEY OFF"); sb.Append("\r\n"); return sb.ToString(); } public static string getLayouPRN() { StringBuilder sb = new StringBuilder(); sb.Append("SYSVAR(18)=0"); sb.Append("INPUT OFF"); sb.Append("NEW "); sb.Append("OPEN \"tmp:setup.sys\" for output as #2"); sb.Append("PRINT#2, \"MEDIA,MEDIA SIZE,LENGTH,400\""); sb.Append("PRINT#2, \"MEDIA,MEDIA SIZE,XSTART,0\""); sb.Append("PRINT#2, \"MEDIA,MEDIA SIZE,WIDTH,420\""); sb.Append("PRINT#2, \"MEDIA,MEDIA TYPE,LABEL (w GAPS)\""); sb.Append("PRINT#2, \"FEEDADJ,STARTADJ,-40\""); sb.Append("PRINT#2, \"FEEDADJ,STOPADJ,0\""); sb.Append("PRINT#2, \"PRINT DEFS,PRINT SPEED,75\""); sb.Append("PRINT#2, \"MEDIA,PAPER TYPE,DIRECT THERMAL\""); sb.Append("PRINT#2, \"MEDIA,PAPER TYPE,DIRECT THERMAL,LABEL CONSTANT,85\""); sb.Append("PRINT#2, \"MEDIA,PAPER TYPE,DIRECT THERMAL,LABEL FACTOR,40\""); sb.Append("PRINT#2, \"MEDIA,CONTRAST,+0%\""); sb.Append("PRINT#2, \"RFID,OFF\""); sb.Append("CLOSE #2"); sb.Append("Setup \"tmp:setup.sys\""); sb.Append("Kill \"tmp:setup.sys\""); sb.Append("OPTIMIZE \"BATCH\" ON"); sb.Append("LTS& OFF"); sb.Append("SETUP KEY OFF"); sb.Append("SYSVAR(48)=0"); sb.Append("FORMAT INPUT CHR$(2),CHR$(3),CHR$(13)"); sb.Append("LAYOUT INPUT \"tmp:LBLSOFT.LAY\""); sb.Append("CLIP ON"); sb.Append("CLIP BARCODE ON"); sb.Append("XORMODE OFF"); sb.Append("qFnt1$=\"Swiss 721 BT\""); sb.Append("qFnt2$=\"Swiss 721 Bold BT\""); sb.Append("NASC 8"); sb.Append("DIR 1"); sb.Append("AN 1"); sb.Append("PP 3,12:PX 256,375,4"); sb.Append("PP 3,140:PL 180,184"); sb.Append("AN 5"); sb.Append("PP 95,130:FT qFnt1$,14,0,100:II"); sb.Append("PRBOX 140,180,0,VAR1$,2,2,\"\",\"\""); sb.Append("AN 2"); sb.Append("PP 270,210:FT qFnt1$,12,0,100:NI:PT VAR2$"); sb.Append("PRINT PRSTAT(3),PRSTAT(5),PRSTAT(6)"); sb.Append("AN 1"); sb.Append("PP PRSTAT(3)-2,213:PRDIAGONAL PRSTAT(5)+1,PRSTAT(6)-16,2,\"R\""); sb.Append("PP PRSTAT(3),212:FT qFnt1$,10,0,100:NI:PT VAR5$"); sb.Append("AN 2"); sb.Append("PP 265,140:FT qFnt2$,18,0,100:NI:PT VAR3$"); sb.Append("PRINT PRSTAT(3)"); sb.Append("AN 1"); sb.Append("PP PRSTAT(3)+PRSTAT(5),140:FT qFnt1$,15,0,100:NI:PT VAR5$"); sb.Append("AN 2"); sb.Append("PP 185,30:BARSET \"CODE128\",1,1,3,90"); sb.Append("BARFONT OFF"); sb.Append("PB VAR4$"); sb.Append("AN 1"); sb.Append("DIR 4"); sb.Append("PP 375,20:FT qFnt1$,10,0,100:NI:PT VAR4$"); sb.Append("LAYOUT END"); sb.Append("COPY \"TMP:LBLSOFT.LAY\",\"C:PRICE_MARKDOWN.LAY\""); sb.Append("LAYOUT RUN \"C:PRICE_MARKDOWN.LAY\""); sb.Append("INPUT ON"); return sb.ToString(); } } }
using MySql.Data.MySqlClient; using PROYECTOFINAL.Models; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Mvc; namespace PROYECTOFINAL.Controllers { public class CategoriasController : Controller { // GET: Categorias public ActionResult Index() { var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { return View(); } } public ActionResult Agreg() { TempData.Remove("idEditar"); var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { return View(); } } public ActionResult Editar(int id) { TempData.Remove("idEditar"); TempData.Add("idEditar", id); categoriamodel categ = new categoriamodel(); categ = categoria.obtenerCategoria(id); TempData.Remove("idEditar"); return View(categ); } public ActionResult Agregar(FormCollection formulario) { var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { var nombre = Request.Form["nombre"]; idLocal = Convert.ToInt16(Session["idLocal"]); //agrega los productos a la base de datos y despues los lista y retorna a index using (MySqlConnection con = producto.AbrirConexion()) { MySqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "crearCategoria"; cmd.Parameters.AddWithValue("Nomb", nombre); cmd.Parameters.AddWithValue("idLocal", idLocal); int registros = cmd.ExecuteNonQuery(); con.Close(); } return View("Index"); } } [HttpPost] public ActionResult Editar(FormCollection formulario) { var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { var id = Request.Form["idEditar"]; var nombre = Request.Form["nombre"]; using (MySqlConnection con = producto.AbrirConexion()) { MySqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "EditarCategoria"; cmd.Parameters.AddWithValue("idCate", id); cmd.Parameters.AddWithValue("Nomb", nombre); int registros = cmd.ExecuteNonQuery(); con.Close(); } TempData.Remove("idEditar"); return View("Index"); } } public ActionResult Eliminar(int id) { //obtener articulos por categoria si es 0 ejecuto var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { int registros = -1; bool tiene = false; idLocal = Convert.ToInt16(Session["idLocal"]); using (MySqlConnection con = producto.AbrirConexion()) { MySqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "listarProductosxCate"; cmd.Parameters.AddWithValue("cate", id); cmd.Parameters.AddWithValue("loc", idLocal); MySqlDataReader lector = cmd.ExecuteReader(); while (lector.Read()) { tiene = true; } if (tiene == false) { using (MySqlConnection con1 = producto.AbrirConexion()) { MySqlCommand cmd1 = con1.CreateCommand(); cmd1.CommandType = CommandType.StoredProcedure; cmd1.CommandText = "EliminarCategoria"; cmd1.Parameters.AddWithValue("idCateg", id); registros = cmd1.ExecuteNonQuery(); con1.Close(); } return View("Index"); } else { con.Close(); return View("Error"); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Server.Utils; using Server.Services; using Server.Data; namespace Server.Interface { interface IFeeds { WebResult<Channel> AddNewFeed(string connectionKey, Uri uri); WebResult<List<Channel>> GetFeeds(string connectionKey); WebResult<List<Channel>> GetAllFeeds(); WebResult UnfollowFeed(string connectionKey, Channel feed); WebResult RefreshFeed(Channel feed); WebResult<List<Item>> GetFeedItems(string connectionKey, Channel feed); WebResult ReadItem(string connectionKey, Item item); } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ChatTest.App.Models { public class ConversationCreateModel { public string Name { get; set; } [Required] public IEnumerable<string> Participants { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class experienceDisplay : MonoBehaviour { private int experience; private RectTransform slider; private GameObject player; // Start is called before the first frame update void Start() { player = GameObject.Find("Player"); slider = GetComponent<RectTransform>(); experience = 1; } // Update is called once per frame void addExperience(int expUp) { experience += expUp; if (experience < 100) { checkExperience(experience); } else { experience = 1; player.SendMessage("activatePanel"); } slider.localScale = new Vector3(experience, 1, 1); } void checkExperience(int expUp) { if (expUp < 0) { experience += 100; levelDown(); } } void levelDown() { player.SendMessage("downgradeTank"); } void reset() { experience = 1; slider.localScale = new Vector3(experience, 1, 1); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BulletScript: MonoBehaviour { //Bullets need rigidBody trigger, and use trigger collision? //Aim sprite's rotation should tie into this script //Test to see if it triggers upon creation, if so, move it as soon as possible!!!! // Use this for initialization public Text winText; void Start () { winText = GameObject.Find("Text").GetComponent<Text>(); } // Update is called once per frame void Update () { } private void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.CompareTag("Player")){ if(col.gameObject.Equals(GameObject.Find("Player Two"))) { winText.text = "Player 1 wins"; Destroy(GameObject.Find("Player Two")); //this.enabled = false; Destroy(GameObject.Find("Bullet(Clone)")); } else { winText.text = "Player 2 wins!"; Destroy(GameObject.Find("Player")); //this.enabled = false; Destroy(this); } } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Library.API.Models { public class Resource { /// <summary> /// 所有资源的基类 /// </summary> [JsonProperty("_links", Order = 100)] //order属性指定所标识属性序列化的位置 public List<Link> Links { get; } = new List<Link>(); } }
using Xunit.Sdk; namespace Sentry.Testing; public class TestOutputDiagnosticLogger : IDiagnosticLogger { private readonly ITestOutputHelper _testOutputHelper; private readonly SentryLevel _minimumLevel; private readonly ConcurrentQueue<LogEntry> _entries = new(); private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); private readonly string _testName; private static readonly FieldInfo TestFieldInfo = typeof(TestOutputHelper) .GetField("test", BindingFlags.Instance | BindingFlags.NonPublic); public IEnumerable<LogEntry> Entries => _entries; public bool HasErrorOrFatal => _entries .Any(x => x.Level is SentryLevel.Error or SentryLevel.Fatal); public class LogEntry { public SentryLevel Level { get; set; } public string Message { get; set; } public Exception Exception { get; set; } public string RawMessage { get; set; } } public TestOutputDiagnosticLogger(ITestOutputHelper testOutputHelper) : this(testOutputHelper, SentryLevel.Debug) { } public TestOutputDiagnosticLogger(ITestOutputHelper testOutputHelper, SentryLevel minimumLevel) { _testOutputHelper = testOutputHelper; _minimumLevel = minimumLevel; var test = TestFieldInfo.GetValue(_testOutputHelper) as ITest; _testName = test?.DisplayName; } public bool IsEnabled(SentryLevel level) => level >= _minimumLevel; // Note: Log must be declared virtual so we can use it with NSubstitute spies. public virtual void Log(SentryLevel logLevel, string message, Exception exception = null, params object[] args) { // Important: Only format the string if there are args passed. // Otherwise, a pre-formatted string that contains braces can cause a FormatException. var formattedMessage = args.Length == 0 ? message : string.Format(message, args); var entry = new LogEntry { Level = logLevel, Message = formattedMessage, RawMessage = message, Exception = exception }; _entries.Enqueue(entry); var msg = $@"[{logLevel} {_stopwatch.Elapsed:hh\:mm\:ss\.ff}]: {formattedMessage}".Trim(); if (exception != null) { msg += $"{Environment.NewLine} Exception: {exception}"; } try { _testOutputHelper.WriteLine(msg); } catch (InvalidOperationException ex) { // Handle "System.InvalidOperationException: There is no currently active test." Console.Error.WriteLine( $"Error: {ex.Message}{Environment.NewLine}" + $" Test: {_testName}{Environment.NewLine}" + $" Message: {msg}"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class dropzone : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler { public draggable.Slot typeOfItem = draggable.Slot.INVENTORY; //PointerEnter and Exit to check if the layout response to the mouse's position public void OnPointerEnter(PointerEventData eventData) { //Debug.Log("OnPointerEnter"); if(eventData.pointerDrag == null) { return; } draggable d = eventData.pointerDrag.GetComponent<draggable>(); if (d != null) { d.placeholderParent = this.transform; } } public void OnPointerExit(PointerEventData eventData) { //Debug.Log("OnPointerExit"); if (eventData.pointerDrag == null) { return; } draggable d = eventData.pointerDrag.GetComponent<draggable>(); if (d != null && d.placeholderParent==this.transform) { d.placeholderParent = d.parentToReturnTo; } } public void OnDrop(PointerEventData eventData) { //OnDrop cmd triggers before the OnEndDrag does //Debug.Log("OnDrop to " + gameObject.name); Debug.Log(eventData.pointerDrag.name + " was dropped " + gameObject.name); draggable d = eventData.pointerDrag.GetComponent<draggable>(); if (d != null) { //if(typeOfItem == d.typeOfItem || typeOfItem == draggable.Slot.INVENTORY) //{ d.parentToReturnTo = this.transform; //} } } }
using Frank.Scheduler.Models.Messages; using System; using System.Threading.Tasks; namespace Frank.Scheduler.Client.ServiceBus.Interfaces { public interface ISchedulerHandler { Task<SchedulerResult> TriggerScheduledTask(Guid id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassicCraft { public abstract class Spell : Action { public int RessourceCost { get; set; } public bool AffectedByGCD { get; set; } public Spell(Player p, double baseCD, int ressourceCost, bool gcd = true) : base(p, baseCD) { RessourceCost = ressourceCost; AffectedByGCD = gcd; } public void CommonSpell() { CDAction(); if (AffectedByGCD) { Player.StartGCD(); } Player.Ressource -= RessourceCost; } public virtual bool CanUse() { return Player.Ressource >= RessourceCost && Available() && (AffectedByGCD ? Player.HasGCD() : true); } public override string ToString() { return "Undefined Spell"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Otiport.API.Contract.Request.Treatments; using Otiport.API.Contract.Response.Treatments; namespace Otiport.API.Services { public interface ITreatmentService { Task<AddTreatmentResponse> AddTreatmentAsync(AddTreatmentRequest request); Task<DeleteTreatmentResponse> DeleteTreatmentAsync(DeleteTreatmentRequest request); Task<GetTreatmentsResponse> GetTreatmentsAsync(GetTreatmentsRequest request); Task<UpdateTreatmentResponse> UpdateTreatmentsAsync(UpdateTreatmentRequest request); } }
using Microsoft.AspNetCore.Authorization; namespace EQS.AccessControl.API.Authorize { public class AuthorizeRoleAttribute : AuthorizeAttribute { public AuthorizeRoleAttribute(params string[] roles) : base() { Roles = string.Join(",", roles); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Integra.LoadingMonitor.DataProviders; using Integra.LoadingMonitor.Models; using Integra.LoadingMonitor.Services; namespace Inventory.Services { public class OrderLoadingMonitor : IOrderLoadingMonitor { private IDataProvider _dataProvider; private IDataProvider DataProvider { get { if (_dataProvider == null) _dataProvider = AppSettings.Current.GetMonitorDataProvider(); return _dataProvider; } } private ILoadMonitor LoadMonitor { get; } public OrderLoadingMonitor(ILoadMonitor monitor) { LoadMonitor = monitor; } public async Task<IEnumerable<Restaurant>> GetRestaurantsAsync() { await LoadMonitor.ApplyProvider(DataProvider); var models = await LoadMonitor.GetRestaurantsAsync(); return models; } public async Task<IEnumerable<Order>> GetOrdersAsync() { OrderFilter orderFilter = new OrderFilter { DepartmentIds = (await LoadMonitor.GetDepartmentsAsync()).Select(x => x.Id).ToList().AsReadOnly(), OrderStateIds = (await LoadMonitor.GetActiveStatesAsync()).Select(x => x.Id).ToList().AsReadOnly(), Restaurants = (await LoadMonitor.GetRestaurantsAsync()).ToList().AsReadOnly() }; var orders = await LoadMonitor.GetOrdersAsync(orderFilter); return orders; } } }
using FPGADeveloperTools.Common.Model.Ports; using FPGADeveloperTools.Common.Model.TestCases; using FPGADeveloperTools.Common.ViewModel.ModuleFiles; using System; using System.Collections.Generic; using System.Linq; namespace FPGADeveloperTools.Common.ViewModel.TestCases { public class TestCaseViewModel : ViewModelBase { private TestCase testCase; private ModuleFileViewModel module; public TestCase TestCase { get { return this.testCase; } } public List<Port> DataIns { get { return this.TestCase.DataIns; } set { this.TestCase.DataIns = value; OnPropertyChanged("DataIns"); } } public Clock ClockSync { get { return this.TestCase.ClockSync; } set { this.TestCase.ClockSync = value; OnPropertyChanged("ClockSync"); } } public Port ValidIn { get { return this.TestCase.ValidIn; } set { this.TestCase.ValidIn = value; OnPropertyChanged("ValidIn"); } } public string DataVector { get { return this.TestCase.DataVector; } set { this.TestCase.DataVector = value; OnPropertyChanged("DataVector"); this.DataOutVector = this.module.Path.Replace(".sv", "_" + value.Split('\\').LastOrDefault().Replace(".txt","_out.txt")); } } public string DataOutVector { get { return this.TestCase.DataOutVector; } set { this.TestCase.DataOutVector = value; OnPropertyChanged("DataOutVector"); } } public string VldSeq { get { return this.TestCase.VldSeq; } set { this.TestCase.VldSeq = value; OnPropertyChanged("VldSeq"); } } public Port ValidOut { get { return this.TestCase.ValidOut; } set { this.TestCase.ValidOut = value; OnPropertyChanged("ValidOut"); } } public List<Port> DataOuts { get { return this.TestCase.DataOuts; } set { this.TestCase.DataOuts = value; OnPropertyChanged("DataOuts"); } } public string DIs { get { string dis = String.Empty; foreach(Port port in this.DataIns) { dis += port.Name; if (!(port == this.DataIns.LastOrDefault())) dis += ", "; } return dis; } } public string DOs { get { string dos = String.Empty; foreach (Port port in this.DataOuts) { dos += port.Name; if (!(port == this.DataOuts.LastOrDefault())) dos += ", "; } return dos; } } public bool Loop { get { return this.TestCase.Loop; } set { this.TestCase.Loop = value; OnPropertyChanged("Loop"); } } public Radix Radix { get { return this.TestCase.Radix; } set { this.TestCase.Radix = value; OnPropertyChanged("Radix"); } } public int Order { get { return this.TestCase.Order; } set { this.TestCase.Order = value; OnPropertyChanged("Order"); } } public string Description { get { return "@" + this.ClockSync.Name + " | " + this.DIs + " | " + this.DataVector.Split('\\').LastOrDefault().Replace(".txt", "") + " | " + this.DOs; } } public TestCaseViewModel(TestCase testCase) { this.testCase = testCase; } public TestCaseViewModel(TestCase testCase, ModuleFileViewModel module) { this.testCase = testCase; this.module = module; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.IO; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Core; using Windows.System; using System.ComponentModel; using System.Data.SqlClient; namespace VéloMax.bdd { public class ContenuCommandeModele { /* Attributs */ public readonly int numC; public readonly int numM; public Commande commande { get => new Commande(numC); } public Modele modele { get => new Modele(numM); } public int quantModeleC { get { return ControlleurRequetes.ObtenirChampInt("ContenuCommandeModele", "numC", numC, "numM", numM, "quantModeleC"); } set { ControlleurRequetes.ModifierChamp("ContenuCommandeModele", "numC", numM, "numM", numM, "quantModeleC", value); } } /* Instantiation */ public ContenuCommandeModele(int numC, int numM) { this.numC = numC; this.numM = numM; } public ContenuCommandeModele(Commande commande, Modele modele): this(commande.numC, modele.numM) { } public ContenuCommandeModele(int numC, int numM, int quantModeleC) { ControlleurRequetes.Inserer($"INSERT INTO ContenuCommandeModele (numC, numM, quantModeleC) VALUES ({numC}, {numM}, {quantModeleC})"); this.numC = numC; this.numM = numM; } public ContenuCommandeModele(Commande commande, Modele modele, int quantModeleC) : this(commande.numC, modele.numM, quantModeleC) { } /* Suppression */ public void Supprimer() { ControlleurRequetes.SupprimerElement("ContenuCommandeModele", "numC", numC, "numM", numM); } /* Liste */ public static ReadOnlyCollection<ContenuCommandeModele> Lister(int numC) { List<ContenuCommandeModele> list = new List<ContenuCommandeModele>(); ControlleurRequetes.SelectionnePlusieurs($"SELECT numM FROM ContenuCommandeModele WHERE numC={numC}", (MySqlDataReader reader) => { list.Add(new ContenuCommandeModele(numC, reader.GetInt32("numM"))); }); return new ReadOnlyCollection<ContenuCommandeModele>(list); } public static ReadOnlyCollection<ContenuCommandeModele> Lister(Commande commande) { return Lister(commande.numC); } public static ReadOnlyCollection<EtatStockModele> ListerQuantitesVenduesM() { List<EtatStockModele> list = new List<EtatStockModele>(); ControlleurRequetes.SelectionnePlusieurs($"SELECT numM, nomM,SUM(quantModeleC) qteM,quantStockM FROM ContenuCommandeModele NATURAL JOIN Modele GROUP BY numM ORDER BY quantStockM;", (MySqlDataReader reader) => { list.Add(new EtatStockModele(reader.GetInt32("numM"), reader.GetString("nomM"), reader.GetInt32("qteM"), reader.GetInt32("quantStockM"))); }); return new ReadOnlyCollection<EtatStockModele>(list); } } public class EtatStockModele { public int numM { get; set; } public string nomM { get; set; } public int qteM { get; set; } public int quantStockM { get; set; } public bool estStockFaibleM { get; set; } public EtatStockModele(int numM, string nomM, int qteM, int quantStockM) { this.numM = numM; this.nomM = nomM; this.qteM = qteM; this.quantStockM = quantStockM; if (quantStockM <= 5) { this.estStockFaibleM = true; } else { this.estStockFaibleM = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FluentValidation; using Autofac; namespace EBS.Admin.Services { public class AutofacValidatorFactory : ValidatorFactoryBase { private readonly IContainer _container; public AutofacValidatorFactory(IContainer container) { _container = container; } public override IValidator CreateInstance(Type validatorType) { object instance; if (_container.TryResolve(validatorType, out instance)) { return instance as IValidator; } return null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //Sets the target of it's parent when a player enters its field of view public class Sight : MonoBehaviour { public BasicNPC parentAi; void OnTriggerEnter(Collider other) { if (parentAi != null) { if (parentAi.photonView.isMine) { if (other.tag == "Player") { parentAi.setTarget(other.gameObject); } } } } }
using System; using System.Collections.Generic; using System.Text; namespace AppSimplicity.ActiveRecord.Interfaces { public interface IDataManager<T> { T GetById(int identity); List<T> GetAll(); List<T> GetAllActive(); } }
public class BouncingBall { public int Bounces(double h, double bounce, double window) { if (h <= 0) { return -1; } if (bounce <= 0 || bounce >= 1) { return -1; } if (window >= h) { return -1; } int isSeenCount = 0; isSeenCount++; double newHeight = h * bounce; if (newHeight >= window) { isSeenCount++; isSeenCount += Bounces(newHeight, bounce, window); } return isSeenCount; } }