text stringlengths 13 6.01M |
|---|
using Meteooor.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace Meteooor.Helpers
{
public static class GeoCodingHelper
{
public static Coordinate GetCoordinate(string coor1, string coor2)
{
return new Coordinate
{
Latitude = GeoCodingHelper.GetCoordinate(coor1),
Longitude = GeoCodingHelper.GetCoordinate(coor2)
};
}
public static double GetCoordinate(string coor)
{
Regex dmsRe = new Regex(@"([NSEW]) (\d+)° (\d+)");
var match = dmsRe.Match(coor);
if (match.Success)
{
double degrees = double.Parse(match.Groups[2].Value);
double minutes = !string.IsNullOrEmpty(match.Groups[3].Value) ? double.Parse(match.Groups[3].Value) / 60 : 0;
string hemisphere = match.Groups[0].Value;
if (hemisphere == "S" || hemisphere == "W")
{
degrees = Math.Abs(degrees) * -1;
}
if (degrees < 0) {
return degrees - minutes;
} else {
return degrees + minutes;
}
}
return -1;
}
}
} |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using DMS.Presentation;
using DMS.DataAccessObject;
using DMS.BusinessObject;
using DMS.Utils;
using DMS.Controls;
using System.Threading;
using DotNetSkin.SkinControls;
using PureComponents.NicePanel;
namespace DMS
{
/// <summary>
/// Summary description for frmMain
/// </summary>
/// <remarks>
/// Author: Le Tien Phat.
/// </remarks>
public class frmMain : System.Windows.Forms.Form
{
private static log4net.ILog log = log4net.LogManager.GetLogger(typeof(frmMain));
private System.ComponentModel.IContainer components;
//private Control pnlToolBar;
//private Panel pnlToolBar;
#region Window Control
private System.Windows.Forms.MenuItem mnuFile;
private System.Windows.Forms.ToolTip tip;
private System.Windows.Forms.MainMenu mnuMain;
#endregion Window Control
public frmMain()
{
InitializeComponent();
clsAutUserBO bo = new clsAutUserBO();
DataTable dt = bo.GetCommonMenu();
mnuMain = BuildMenu(dt);
this.Menu = mnuMain;
try
{
string filename = clsSystemConfig.ImageFolder + ConfigurationManager.AppSettings["Background"];
if(File.Exists(filename))
{
this.BackgroundImage = Image.FromFile(clsSystemConfig.ImageFolder + ConfigurationManager.AppSettings["Background"]);
this.BackgroundImageLayout = ImageLayout.Stretch;
}
}
catch(Exception ex)
{
log.Error(ex.Message, ex);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.mnuMain = new System.Windows.Forms.MainMenu(this.components);
this.mnuFile = new System.Windows.Forms.MenuItem();
this.tip = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// mnuMain
//
this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.Text = "File";
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(656, 457);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.IsMdiContainer = true;
this.Menu = this.mnuMain;
this.Name = "frmMain";
this.Text = "Distributor Management System";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
[STAThread]
static void Main()
{
if(clsSystemConfig.Init())
{
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US", false);
Application.CurrentCulture = ci;
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "GENERAL", out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
else
{
MessageBox.Show(clsSystemConfig.GetMessage(), "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//private static string TOOLBAR_BUTTON_INDEX = "TOOLBAR_BUTTON_INDEX";
private static string TOOLBAR_NAME = "TOOLBAR_NAME";
private static string FORM_ID = "FORM_ID";
private static string FORM_NAME = "FORM_NAME";
private static string MENU_NAME = "MENU_NAME";
private static string MENU_ZORDER = "MENU_ZORDER";
//private static string DESCRIPTION = "DESCRIPTION";
//private static string MENU_PID = "MENU_PID";
private static string ICON_NAME = "ICON_NAME";
private static string AssemblyName = "DMS.Presentation.";
private static string frmMainName = "frmMain.";
/// <summary>
/// Build dynamic menu
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private MainMenu BuildMenu(DataTable dt)
{
MainMenu mainMenu = new MainMenu();
DataRow[]rows;
rows = dt.Select("MENU_PID = 0", MENU_ZORDER);
MDMenuItem item;
Font font = this.Font;
foreach(DataRow row in rows)
{
item = new MDMenuItem();
item.ID = int.Parse(row[FORM_ID].ToString());
item.Name = row[MENU_NAME].ToString();
item.FormName = AssemblyName + row[FORM_NAME].ToString();
item.Text = clsResources.GetTitle(frmMainName + row[MENU_NAME].ToString());
item.Font = font;
if(item.Name == clsConstants.MENU_WINDOWS)
{
item.MdiList = true;
}
mainMenu.MenuItems.Add(item);
AddSub(item, dt);
}
return mainMenu;
}
/// <summary>
/// Add sub menu item on recursive
/// </summary>
/// <param name="parent"></param>
/// <param name="dt"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void AddSub(MDMenuItem parent, DataTable dt)
{
DataRow[] rows = dt.Select(string.Format("MENU_PID = {0}", parent.ID), MENU_ZORDER);
if (rows.Length > 0)
{
MDMenuItem item;
string folder = clsSystemConfig.IconFolder;
string iconName = null;
Size size = new Size(14, 14);
foreach (DataRow row in rows)
{
item = new MDMenuItem();
item.Font = parent.Font;
item.OwnerDraw = true;
item.Name = row[MENU_NAME].ToString();
iconName = row[ICON_NAME].ToString();
if (iconName.Length > 0)
{
string filename = folder + iconName;
if (File.Exists(filename))
{
try
{
Icon icon = new Icon(filename);
item.Icon = icon;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
}
}
if (item.Name == clsConstants.MENU_SEPARATE)
{
item.OwnerDraw = false;
item.Text = clsConstants.MINUS;
parent.MenuItems.Add(item);
}
else if (item.Name == clsConstants.MAXIMIZED)
{
item.Text = clsResources.GetTitle(frmMainName + row[MENU_NAME].ToString());
parent.MenuItems.Add(item);
item.Checked = clsFormManager.Maximized;
item.Click += new EventHandler(MenuItem_OnClick);
}
else if (item.Name == clsConstants.SYSTEM_STYLE)
{
item.Text = clsResources.GetTitle(frmMainName + row[MENU_NAME].ToString());
parent.MenuItems.Add(item);
item.Checked = clsStyleManager.SystemStyle;
item.Click += new EventHandler(MenuItem_OnClick);
}
else
{
item.ID = int.Parse(row[FORM_ID].ToString());
string formName = row[FORM_NAME].ToString();
if (formName.Length > 0)
item.FormName = AssemblyName + formName;
else
item.FormName = "";
item.Text = clsResources.GetTitle(frmMainName + row[MENU_NAME].ToString());
parent.MenuItems.Add(item);
AddSub(item, dt);
}
}
}
else
{
parent.Click += new EventHandler(MenuItem_OnClick);
}
}
/// <summary>
/// Handle events when click on menu Item (Open window and other action).
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void MenuItem_OnClick(object sender, EventArgs e)
{
string formName = "";
MDMenuItem item = (MDMenuItem)sender;
if(clsConstants.EXIT == item.Name)
{
this.Close();
}
else if (clsConstants.MENU_HELP_TOPIC == item.Name)
{
}
else if (clsConstants.MENU_HELP_ABOUT == item.Name)
{
frmAbout frmAbout = new frmAbout();
frmAbout.ShowDialog();
}
else if (clsConstants.WINDOW_CASCADE == item.Name)
{
this.LayoutMdi(MdiLayout.Cascade);
}
else if (clsConstants.WINDOW_TILE_HOZ == item.Name)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
else if (clsConstants.WINDOW_TILE_VERT == item.Name)
{
this.LayoutMdi(MdiLayout.TileVertical);
}
else if (clsConstants.WINDOW_CLOSE_ALL == item.Name)
{
CloseAllWindow();
}
else if (clsConstants.SYSTEM_STYLE == item.Name)
{
item.Checked = !item.Checked;
clsStyleManager.SystemStyle = item.Checked;
}
else if (clsConstants.COLOR_FOCUS_CONTROL == item.Name)
{
item.Checked = !item.Checked;
clsStyleManager.ColorFocusControl = item.Checked;
}
else if (clsConstants.MAXIMIZED == item.Name)
{
item.Checked = !item.Checked;
clsFormManager.Maximized = item.Checked;
}
else if (clsConstants.SET_ENGLISH_LANGUAGE == item.Name)
{
clsResources.Init(clsConstants.ENGLISH);
clsTitleManager.InitToolBarToolTip(this);
// tip.RemoveAll();
// foreach(Control ctrl in pnlToolBar.Controls)
// {
// tip.SetToolTip(ctrl, clsResources.GetTitle(frmMainName + ctrl.Name));
// }
clsTitleManager.InitTitle(this, this.Menu);
foreach (Form frm in this.MdiChildren)
{
clsTitleManager.InitTitle(frm);
}
}
else if (clsConstants.SET_VIETNAMESE_LANGUAGE == item.Name)
{
clsResources.Init(clsConstants.VIETNAMESE);
clsTitleManager.InitToolBarToolTip(this);
// tip.RemoveAll();
// foreach(Control ctrl in pnlToolBar.Controls)
// {
// tip.SetToolTip(ctrl, clsResources.GetTitle(frmMainName + ctrl.Name));
// }
clsTitleManager.InitTitle(this, this.Menu);
foreach (Form frm in this.MdiChildren)
{
clsTitleManager.InitTitle(frm);
}
}
else if (clsConstants.LOG_OUT == item.Name)
{
if (MessageBox.Show(clsResources.GetMessage("messages.logout"), clsResources.GetMessage("messages.general"), MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
CloseAllWindow();
this.Text = clsResources.GetTitle("frmMain.Title");
this.Menu = mnuMain;
//pnlToolBar.Visible = false;
clsCommon.RemoveAllToolBar(this);
mnuLogin_Click(null, null);
}
}
else
{
formName = item.FormName;
if (formName.Length > 0 && formName != AssemblyName)
{
if (formName == "DMS.Presentation.frmLogin")
{
mnuLogin_Click(null, null);
}
else
{
Form frm = null;
try
{
frm = (Form)Activator.CreateInstance(Type.GetType(formName), null);
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
MessageBox.Show(clsResources.GetMessage("errors.form.create", formName));
}
if (frm != null)
{
clsFormManager.ShowMDIChild(frm);
}
}
}
}
}
/// <summary>
/// Create tool bar
/// </summary>
/// <param name="dt"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
public void CreateToolBar(DataTable dt)
{
clsCommon.RemoveAllToolBar(this);
ArrayList ctrls = new ArrayList();
string otbName = null;
string tbName = "";
string description = null;
string iconName = null;
string filename;
string folder = clsSystemConfig.IconFolder;
Size size = new Size(180, 10);
ToolBar tb = null;
MDToolBarButton tbb = null;
ImageList imgs = null;
DataRow[] rows = dt.Select("TOOLBAR_BUTTON_INDEX >= 0", "TOOLBAR_NAME, TOOLBAR_BUTTON_INDEX");
int index = 0;
foreach (DataRow row in rows)
{
tbb = new MDToolBarButton();
tbName = row[TOOLBAR_NAME].ToString();
iconName = row[ICON_NAME].ToString();
if (tbName != otbName)
{
tb = new ToolBar();
tb.TextAlign = ToolBarTextAlign.Right;
tb.Dock = DockStyle.Left;
tb.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
tb.AutoSize = false;
//tb.Height = size.Height;
tb.Width = size.Width;
tb.ButtonSize = size;
tb.Appearance = ToolBarAppearance.Flat;
tb.BorderStyle = System.Windows.Forms.BorderStyle.None;
imgs = new ImageList();
imgs.ColorDepth = ColorDepth.Depth32Bit;
//imgs.ImageSize = new Size(14,14);
index = 0;
// Create panel in order to toolbar can inherit backcolor
Panel pnl = new Panel();
pnl.BackColor =
System.Drawing.Color.FromArgb(((System.Byte)(142)), ((System.Byte)(179)), ((System.Byte)(231)));
pnl.ForeColor = Color.Green;
pnl.BorderStyle = System.Windows.Forms.BorderStyle.None;
pnl.Size = new Size(180, 1000);
pnl.Controls.Add(tb);
// This toolbar holds panel
ToolBar tbx = new ToolBar();
tbx.Dock = DockStyle.Left;
tbx.BorderStyle = System.Windows.Forms.BorderStyle.None;
tbx.Controls.Add(pnl);
tbx.AutoSize = false;
tbx.Size = pnl.Size;
ctrls.Add(tbx);
otbName = tbName;
tb.ImageList = imgs;
tb.ButtonClick += new ToolBarButtonClickEventHandler(ToolBarButtonOnClick);
}
tbb.Name = row[MENU_NAME].ToString();
tbb.FormName = AssemblyName + row[FORM_NAME].ToString();
description = clsResources.GetTitle(frmMainName + tbb.Name);
tbb.Text = description;
if (iconName.Length > 0)
{
filename = folder + iconName;
if (File.Exists(filename))
{
try
{
Icon icon = new Icon(filename);
imgs.Images.Add(icon);
tbb.ImageIndex = index;
index++;
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
}
}
}
tb.Buttons.Add(tbb);
}
foreach (Control ctrl in ctrls)
this.Controls.Add(ctrl);
}
/// <summary>
/// Close all MDI Children Windows
/// </summary>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
public void CloseAllWindow()
{
while(this.MdiChildren.Length > 0)
{
foreach(Form frm in this.MdiChildren)
{
if(frm.Visible)
frm.Close();
}
}
}
/// <summary>
/// Open login form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void mnuLogin_Click(object sender, System.EventArgs e)
{
int LoginResult = clsConstants.PASSWORD_WRONG;
frmLogin frm = new frmLogin();
if (frm.ShowDialog() == DialogResult.OK)
{
LoginResult = frm.LoginResult;
}
if (LoginResult == clsConstants.LOGIN_SUCCESS)
{
//SingleInstance.SingleApplication.Run(new frmMain());
clsAutUserBO bo = new clsAutUserBO();
DataTable dt = bo.GetAuthority();
this.Menu = BuildMenu(dt);
CreateToolBar(dt);
bo.ClearAuthority();
this.Text = clsResources.GetTitle("frmMain.Title") + " - " + clsResources.GetMessage("messages.username.title", clsSystemConfig.UserName);
clsFormManager.MainForm = this;
}
}
/// <summary>
/// Open login form on load events
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void frmMain_Load(object sender, System.EventArgs e)
{
mnuLogin_Click(null, null);
}
/// <summary>
/// Question before exit application. Do not exit application if user chooses "No".
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(MessageBox.Show(clsResources.GetMessage("messages.exit"), clsResources.GetMessage("messages.general"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Application.Exit();
}
else
{
e.Cancel = true;
}
}
/// <summary>
/// Handle event when click on Tool bar button (Open new window).
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// Author: Le Tien Phat.
/// Created date: 14/05/2011
/// </remarks>
private void ToolBarButtonOnClick(object sender, ToolBarButtonClickEventArgs e)
{
MDToolBarButton tbb = e.Button as MDToolBarButton;
if(tbb == null)
return;
string formName = tbb.FormName;
Form frm = null;
try
{
if(formName != AssemblyName)
frm = (Form)Activator.CreateInstance(Type.GetType(formName), null);
}
catch(Exception ex)
{
log.Error(ex.Message, ex);
MessageBox.Show(clsResources.GetMessage("errors.form.create", formName));
}
if(frm != null)
{
clsFormManager.ShowMDIChild(frm);
}
}
}
} |
using System;
using Newtonsoft.Json;
namespace SecureNetRestApiSDK.Api.Models
{
/// <summary>
/// Data from a Vault payment account.
/// </summary>
public class PaymentVaultToken
{
#region Properties
/// <summary>
/// Customer identifier.
/// </summary>
[JsonProperty("customerId")]
public String CustomerId { get; set; }
/// <summary>
/// Payment method to be used for billing.
/// </summary>
[JsonProperty("paymentMethodId")]
public String PaymentMethodId { get; set; }
/// <summary>
/// Public Key used to identify the mechant.
/// </summary>
[JsonProperty("publicKey")]
public String PublicKey { get; set; }
/// <summary>
/// Payment type that is stored or about to be stored in the Vault.
/// </summary>
[JsonProperty("paymentType")]
public String PaymentType { get; set; }
#endregion
}
}
|
using System;
using Xamarin.Forms;
using SkiaSharp;
using SkiaSharp.Views.Forms;
using FrameGenerator;
using System.Collections.Generic;
using System.Threading;
using TtyRecDecoder;
using System.IO;
namespace SkiaSharpFormsDemos.Bitmaps
{
public class ImageView : ContentPage
{
private const int TimeStepLengthMS = 5000;
private readonly MainGenerator frameGenerator;
private readonly List<DateTime> PreviousFrames = new List<DateTime>();
private readonly Stream fileStream;
private DateTime PreviousFrame = DateTime.Now;
private TimeSpan MaxDelayBetweenPackets = new TimeSpan(0, 0, 0, 0, 500);//millisecondss
private int FrameStepCount;
private int ConsoleSwitchLevel = 1;
public static Thread m_Thread;
public TtyRecKeyframeDecoder ttyrecDecoder = null;
public double PlaybackSpeed, PausedSpeed;
public TimeSpan Seek;
SKBitmap bmp = new SKBitmap();
SKCanvasView canvasView = new SKCanvasView();
public MemoryStream destination = new MemoryStream();
private bool run = true;
public ImageView(Stream file)
{
Title = "Fill Rectangle";
frameGenerator = new MainGenerator(System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), @"Extra"));
canvasView.PaintSurface += OnCanvasViewPaintSurface;
Content = canvasView;
fileStream = file;
Main();
}
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;
canvas.Clear();
canvas.DrawBitmap(bmp, info.Rect);
}
void DoOpenFiles()
{
var delay = TimeSpan.Zero;
//if (files.Length > 1)
//{
// // multiselect!
// var fof = new FileOrderingForm(files);
// if (fof.ShowDialog(this) != DialogResult.OK) return;
// files = fof.FileOrder.ToArray();
// delay = TimeSpan.FromSeconds(fof.SecondsBetweenFiles);
//}
fileStream.CopyTo(destination);
var streams = new List<Stream> { destination };
ttyrecDecoder = new TtyRecKeyframeDecoder(80, 24, streams, delay, MaxDelayBetweenPackets);
PlaybackSpeed = +1;
Seek = TimeSpan.Zero;
}
//private IEnumerable<Stream> TtyrecToStream()
//{
// return files.Select(f =>
// {
// if (Path.GetExtension(f) == ".ttyrec") return File.OpenRead(f);
// Stream streamCompressed = File.OpenRead(f);
// Stream streamUncompressed = new MemoryStream();
// if (Path.GetExtension(f) == ".bz2")
// {
// try
// {
// BZip2.Decompress(streamCompressed, streamUncompressed, false);
// }
// catch
// {
// // MessageBox.Show("The file is corrupted or not supported");
// }
// return streamUncompressed;
// }
// if (Path.GetExtension(f) == ".gz")
// {
// try
// {
// GZip.Decompress(streamCompressed, streamUncompressed, false);
// }
// catch
// {
// //MessageBox.Show("The file is corrupted or not supported");
// }
// return streamUncompressed;
// }
// return null;
// });
//}
//private IEnumerable<Stream> TtyrecToStream(Dictionary<string, Stream> s)
//{
// return s.Select(f =>
// {
// if (f.Key == "ttyrec") return f.Value;
// Stream streamCompressed = f.Value;
// Stream streamUncompressed = new MemoryStream();
// if (f.Key == "bz2")
// {
// try
// {
// BZip2.Decompress(streamCompressed, streamUncompressed, false);
// }
// catch
// {
// MessageBox.Show("The file is corrupted or not supported");
// }
// return streamUncompressed;
// }
// if (f.Key == "gz")
// {
// try
// {
// GZip.Decompress(streamCompressed, streamUncompressed, false);
// }
// catch
// {
// MessageBox.Show("The file is corrupted or not supported");
// }
// return streamUncompressed;
// }
// return null;
// });
//}
void MainLoop()
{
var now = DateTime.Now;
PreviousFrames.Add(now);
PreviousFrames.RemoveAll(f => f.AddSeconds(1) < now);
var dt = Math.Max(0, Math.Min(0.1, (now - PreviousFrame).TotalSeconds));
PreviousFrame = now;
if (ttyrecDecoder != null)
{
Seek += TimeSpan.FromSeconds(dt * PlaybackSpeed);
if (Seek > ttyrecDecoder.Length)
{
Seek = ttyrecDecoder.Length;
}
if (Seek < TimeSpan.Zero)
{
Seek = TimeSpan.Zero;
}
if (FrameStepCount != 0)
{
ttyrecDecoder.FrameStep(FrameStepCount); //step frame index by count
Seek = ttyrecDecoder.CurrentFrame.SinceStart;
FrameStepCount = 0;
}
else
{
ttyrecDecoder.Seek(Seek);
}
var frame = ttyrecDecoder.CurrentFrame.Data;
if (frame != null)
{
if (!frameGenerator.isGeneratingFrame)
{
frameGenerator.isGeneratingFrame = true;
#if false
ThreadPool.UnsafeQueueUserWorkItem(o =>
{
try
{
bmp = frameGenerator.GenerateImage(frame, ConsoleSwitchLevel);
canvasView.InvalidateSurface();
frameGenerator.isGeneratingFrame = false;
frame = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//generator.GenerateImage(savedFrame);
frameGenerator.isGeneratingFrame = false;
}
}, null);
#else //non threaded image generation (slow)
bmp = frameGenerator.GenerateImage(frame, ConsoleSwitchLevel);
canvasView.InvalidateSurface();
frameGenerator.isGeneratingFrame = false;
#endif
}
}
}
}
void Loop()
{
while (run)
{
MainLoop();
}
}
void Main()
{
DoOpenFiles();
Thread m_Thread = new Thread(() => Loop());
m_Thread.Start();
}
}
} |
namespace Airelax.Application.Houses.Dtos.Response
{
public class FeeDto
{
public decimal CleanFee { get; set; } = 0;
public decimal ServiceFee { get; set; } = 0;
public decimal TaxFee { get; set; } = 0;
}
} |
using System;
[AttributeUsage(AttributeTargets.Method)]
public sealed class GAttribute0 : Attribute
{
}
|
using UnityEngine;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Event of type `CollisionGameObjectPair`. Inherits from `AtomEvent<CollisionGameObjectPair>`.
/// </summary>
[EditorIcon("atom-icon-cherry")]
[CreateAssetMenu(menuName = "Unity Atoms/Events/CollisionGameObjectPair", fileName = "CollisionGameObjectPairEvent")]
public sealed class CollisionGameObjectPairEvent : AtomEvent<CollisionGameObjectPair>
{
}
}
|
namespace Microsoft.UnifiedPlatform.Service.Common.Configuration
{
public interface IConfigurationProviderChainBuilder
{
BaseConfigurationProvider Build();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
m_Source = gameObject.AddComponent<AudioSource>();
}
private AudioSource m_Source;
public GameObject model;
public Wall _wall;
public bool _locked = false;
public float _shutSpeed = 0.3f;
public Transform _door;
public Transform _doorOpen;
public Transform _doorClosed;
float _timer = 0.0f;
[HideInInspector]
public bool isValidSpawn = true;
[HideInInspector]
public bool isActiveDoor = false;
public void hideModel()
{
if (isActiveDoor)
return;
isValidSpawn = false;
model.SetActive(false);
}
public void toggleLockDoor()
{
AudioClip clip = Resources.Load("Sounds/Door_Close") as AudioClip;
m_Source.PlayOneShot(clip, 0.05f);
_timer = 0.0f;
_locked = !_locked;
}
public void showModel()
{
isActiveDoor = true;
isValidSpawn = false;
model.SetActive(true);
}
public void Update()
{
if (_timer < _shutSpeed)
_timer += Time.deltaTime;
if (_locked)
_door.position = Vector3.Lerp(_door.position, _doorClosed.position, _timer / _shutSpeed);
else
_door.position = Vector3.Lerp(_door.position, _doorOpen.position, _timer / _shutSpeed);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArizaTakipYazılımSistemi.Model;
namespace ArizaTakipYazılımSistemi.Degiskenler
{
class Admin
{
public static Personel personel { get; set; }
public static Boolean kullanici = true;
public static Bolum bolum { get; set; }
public static Unvan unvan { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Euler_Logic.Problems.AdventOfCode.Y2021 {
public class Problem21 : AdventOfCodeBase {
private int[] _positions;
private Dictionary<int, ulong> _combos;
public override string ProblemName {
get { return "Advent of Code 2021: 21"; }
}
public override string GetAnswer() {
GetPositions(Input());
return Answer2().ToString();
}
private int Answer1() {
return Simulate();
}
private ulong Answer2() {
_combos = GetDiceCombos();
int max = 21;
var wins = new ulong[2];
var turnWins = new ulong[2, 21];
Recurisve(_positions, new int[2], wins, 0, max, turnWins, 1, 1);
return Math.Max(wins[0], wins[1]);
}
private void Recurisve(int[] position, int[] score, ulong[] wins, int player, int max, ulong[,] turnWins, int turn, ulong multiply) {
foreach (var keyValue in _combos) {
var result = keyValue.Key;
int oldPosition = position[player];
int oldScore = score[player];
position[player] = (position[player] + result) % 10;
score[player] += position[player] + 1;
if (score[player] >= max) {
wins[player] += keyValue.Value * multiply;
turnWins[player, turn] += keyValue.Value * multiply;
} else {
Recurisve(position, score, wins, (player + 1) % 2, max, turnWins, turn + player, multiply * keyValue.Value);
}
position[player] = oldPosition;
score[player] = oldScore;
}
}
private Dictionary<int, ulong> GetDiceCombos() {
var combos = new Dictionary<int, ulong>();
for (int dice1 = 1; dice1 <= 3; dice1++) {
for (int dice2 = 1; dice2 <= 3; dice2++) {
for (int dice3 = 1; dice3 <= 3; dice3++) {
int sum = dice1 + dice2 + dice3;
if (!combos.ContainsKey(sum)) {
combos.Add(sum, 1);
} else {
combos[sum]++;
}
}
}
}
return combos;
}
private int Simulate() {
var scores = new int[2];
int currentPlayer = 0;
int die = 0;
int rollCount = 0;
do {
int next = ((die + 1) % 100) + ((die + 2) % 100) + ((die + 3) % 100);
rollCount += 3;
die = (die + 3) % 100;
_positions[currentPlayer] = (_positions[currentPlayer] + next) % 10;
scores[currentPlayer] += _positions[currentPlayer] + 1;
if (scores[currentPlayer] >= 1000) {
return rollCount * scores[(currentPlayer + 1) % 2];
}
currentPlayer = (currentPlayer + 1) % 2;
} while (true);
}
private void GetPositions(List<string> input) {
_positions = new int[2];
_positions[0] = Convert.ToInt32(input[0].Split(' ')[4]) - 1;
_positions[1] = Convert.ToInt32(input[1].Split(' ')[4]) - 1;
}
}
}
|
//
// Copyright (c) Autodesk, Inc. All rights reserved.
//
// This computer source code and related instructions and comments are the
// unpublished confidential and proprietary information of Autodesk, Inc.
// and are protected under Federal copyright and state trade secret law.
// They may not be disclosed to, copied or used by any third party without
// the prior written consent of Autodesk, Inc.
//
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if !UNITY_EDITOR && UNITY_WSA
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR.WSA.WebCam;
#else
using UnityEngine.VR.WSA.WebCam;
#endif
#endif
namespace Autodesk.Forge.ARKit {
#if !UNITY_EDITOR && UNITY_WSA
public partial class QRCodeZxingWebDecoder : QRCodeDecoderBase {
#region Fields
protected PhotoCapture _photoCapture =null ;
private Resolution _cameraResolution ;
#endregion
#region Unity APIs
//protected virtual void OnEnable ()
//protected virtual void OnDisable ()
protected override void Update () {
}
#endregion
#region Methods
protected override bool InitCamera () {
_cameraResolution =PhotoCapture.SupportedResolutions.OrderByDescending ((res) => res.width * res.height).First () ;
PhotoCapture.CreateAsync (false, delegate (PhotoCapture captureObject) {
_photoCapture =captureObject ;
CameraParameters cameraParameters =new CameraParameters () ;
cameraParameters.hologramOpacity =1.0f ;
cameraParameters.cameraResolutionWidth =_cameraResolution.width ;
cameraParameters.cameraResolutionHeight =_cameraResolution.height ;
cameraParameters.pixelFormat =CapturePixelFormat.BGRA32 ; // CapturePixelFormat.JPEG/CapturePixelFormat.PNG;
// Start the photo mode and start taking pictures
_photoCapture.StartPhotoModeAsync (cameraParameters, delegate (PhotoCapture.PhotoCaptureResult result) {
//InvokeRepeating ("ProcessCameraFrame", 0, _pictureInterval) ;
Invoke ("ProcessCameraFrame", 0) ;
}) ;
}) ;
return (true) ;
}
protected override void StopCamera () {
if ( _photoCapture == null )
return ;
_photoCapture.StopPhotoModeAsync (delegate (PhotoCapture.PhotoCaptureResult res) {
_photoCapture.Dispose () ;
_photoCapture =null ;
}) ;
}
protected override void ProcessCameraFrame () {
if ( _photoCapture != null ) {
_photoCapture.TakePhotoAsync (delegate (PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame) {
if ( _photoTaken != null ) {
//UnityEngine.WSA.Application.InvokeOnAppThread (() => {
_photoTaken.Play () ;
//}, false) ;
}
List<byte> buffer =new List<byte> () ;
photoCaptureFrame.CopyRawImageDataIntoBuffer (buffer) ;
Texture2D tex =new Texture2D (_cameraResolution.width, _cameraResolution.height) ;
photoCaptureFrame.UploadImageDataToTexture (tex) ; // not supported by JPEG
tex.Apply () ;
byte[] jpeg =ImageConversion.EncodeToJPG (tex) ;
if ( _image != null ) {
//UnityEngine.WSA.Application.InvokeOnAppThread (() => {
_image.texture =tex ;
// photoCaptureFrame.UploadImageDataToTexture (_image.texture as Texture2D) ;
//}, false) ;
}
//static byte[] EncodeToJPG(Texture2D tex);
// Check if we can receive the position where the photo was taken
Matrix4x4 cameraToWorldMatrix ;
if ( !photoCaptureFrame.TryGetCameraToWorldMatrix (out cameraToWorldMatrix) )
cameraToWorldMatrix =Matrix4x4.identity ;
// Start a coroutine to handle the server request
StartCoroutine (UploadAndHandlePhoto (jpeg, cameraToWorldMatrix)) ;
}) ;
}
}
protected override bool ReturnOrLoop (string json, Vector3 position, Quaternion rotation) {
if ( json != null || (json == null && _searchUntilFound == false) ) {
//UnityEngine.WSA.Application.InvokeOnAppThread (() => {
if ( _decodeSuccessful != null && json != null )
_decodeSuccessful.Play () ;
else if ( _decodeFailed != null && json == null )
_decodeFailed.Play () ;
gameObject.SetActive (false) ;
_qrDecoded.Invoke (json, position, rotation) ;
//}, false) ;
return (true) ;
} else {
Invoke ("ProcessCameraFrame", 0) ;
return (false) ;
}
}
#endregion
}
#endif
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Player : MonoBehaviour
{
private float timer = 0f;
private float timeToMatchMovementDirection = .5f;
private Quaternion lookDirection;
private Vector3 lastShot;
[Header("Movement")]
private CharacterController character;
public Vector3 moveDirection;
public float speed = 3f;
[Header("Bullet")]
public Vector3 shotDirection;
public List<GameObject> bullets;
public int bulletIndex = 0;
private GameObject currentBullet;
public Transform bulletSource;
public float bulletSpeed = 20f;
public float frequency = .5f;
private float bulletTimer;
private bool bulletIsQueued;
private void Start()
{
character = GetComponent<CharacterController>();
moveDirection = new Vector3();
shotDirection = new Vector3();
}
private void Update()
{
moveDirection.x = (Input.GetKey(KeyCode.A)) ? -1 : (Input.GetKey(KeyCode.D)) ? 1 : 0;
moveDirection.z = (Input.GetKey(KeyCode.S)) ? -1 : (Input.GetKey(KeyCode.W)) ? 1 : 0;
shotDirection.x = (Input.GetKey(KeyCode.LeftArrow)) ? -1 : (Input.GetKey(KeyCode.RightArrow)) ? 1 : 0;
shotDirection.z = (Input.GetKey(KeyCode.DownArrow)) ? -1 : (Input.GetKey(KeyCode.UpArrow)) ? 1 : 0;
// Update move direction
character.SimpleMove(moveDirection * speed);
// Update look direction
timer -= Time.deltaTime;
// Update bullet shots
bulletTimer -= Time.deltaTime;
if (shotDirection.x != 0 || shotDirection.z != 0)
{
if (bulletTimer < 0)
QueueShot(shotDirection);
}
if (UpdateDirection())
{
if (moveDirection.x != 0 || moveDirection.z != 0)
lookDirection = Quaternion.LookRotation(moveDirection);
}
else
{
lookDirection = Quaternion.LookRotation(lastShot);
}
transform.rotation = lookDirection;
if (bulletIsQueued)
Shoot(shotDirection);
}
private bool UpdateDirection()
{
if (timer < 0)
{
return true;
}
return false;
}
private void QueueShot(Vector3 shotDirection)
{
lastShot = shotDirection;
timer = timeToMatchMovementDirection;
bulletIsQueued = true;
}
private void Shoot(Vector3 shotDirection)
{
bulletTimer = frequency;
currentBullet = bullets[bulletIndex];
currentBullet.SetActive(true);
currentBullet.transform.SetPositionAndRotation(bulletSource.position, new Quaternion(0f, 0f, 0f, 0f));
currentBullet.GetComponent<Rigidbody>().velocity = Vector3.zero;
currentBullet.GetComponent<Rigidbody>().AddForce(lastShot * bulletSpeed, ForceMode.Impulse);
bulletIsQueued = false;
bulletIndex = (bulletIndex + 1 >= bullets.Count) ? 0 : bulletIndex + 1;
}
}
|
using System;
using System.Collections.Generic;
namespace GenericProgramming
{
interface IEmployee
{
string GetExperienceLvl();
}
class Employee : IEmployee
{
public string Name;
public int YearOfExp;
public Employee(){}
public Employee(string name, int yearOfExp)
{
Name = name;
YearOfExp = yearOfExp;
}
public string GetExperienceLvl()
{
string experienceLvl;
// C# 7
switch (YearOfExp)
{
case int n when (n <= 1):
experienceLvl = "Fresher";
break;
case int n when (n >= 2 && n <= 5):
experienceLvl = "Intermediate";
break;
default:
experienceLvl = "Expert";
break;
}
return experienceLvl;
}
}
class EmployeeStoreHouse<T> where T : IEmployee, new()
{
private List<Employee> employeeStore = new List<Employee>();
public void AddToStore(Employee employee)
{
employeeStore.Add(employee);
}
public void DisplayStore()
{
Console.WriteLine("The store contains:");
foreach (Employee e in employeeStore)
{
Console.Write($"{e.Name}: ");
Console.WriteLine(e.GetExperienceLvl());
}
}
}
public class Demo5
{
public static void Run()
{
Console.WriteLine("\n=== Generic Constrains ===");
//Employees
Employee e1 = new Employee("Nandi", 1);
Employee e2 = new Employee("Bambang", 5);
Employee e3 = new Employee("Jon", 7);
Employee e4 = new Employee("Somad", 2);
Employee e5 = new Employee("Butet", 3);
//Employee StoreHouse
EmployeeStoreHouse<Employee> myEmployeeStore = new EmployeeStoreHouse<Employee>();
myEmployeeStore.AddToStore(e1);
myEmployeeStore.AddToStore(e2);
myEmployeeStore.AddToStore(e3);
myEmployeeStore.AddToStore(e4);
myEmployeeStore.AddToStore(e5);
//Display the Employee Positions in Store
myEmployeeStore.DisplayStore();
}
}
} |
namespace BettingSystem.Infrastructure.Matches.Persistence.Migrations
{
using Microsoft.EntityFrameworkCore.Migrations;
public partial class TeamImage : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Image_ThumbnailContent",
table: "Stadiums",
newName: "Image_Thumbnail");
migrationBuilder.RenameColumn(
name: "Image_OriginalContent",
table: "Stadiums",
newName: "Image_Original");
migrationBuilder.AddColumn<byte[]>(
name: "Image_Original",
table: "Teams",
type: "varbinary(max)",
nullable: false,
defaultValue: new byte[0]);
migrationBuilder.AddColumn<byte[]>(
name: "Image_Thumbnail",
table: "Teams",
type: "varbinary(max)",
nullable: false,
defaultValue: new byte[0]);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Image_Original",
table: "Teams");
migrationBuilder.DropColumn(
name: "Image_Thumbnail",
table: "Teams");
migrationBuilder.RenameColumn(
name: "Image_Thumbnail",
table: "Stadiums",
newName: "Image_ThumbnailContent");
migrationBuilder.RenameColumn(
name: "Image_Original",
table: "Stadiums",
newName: "Image_OriginalContent");
}
}
}
|
using Sentry.Tests.Helpers.Reflection;
namespace Sentry.Tests.Internals;
public class SparseArrayTests
{
private void Test(SparseScalarArray<int> sut, int setDefault)
{
sut.ContainsKey(0).Should().BeFalse();
sut.ContainsKey(1).Should().BeFalse();
sut[0] = setDefault;
sut.ContainsKey(0).Should().BeFalse();
sut.ContainsKey(1).Should().BeFalse();
sut[0] = setDefault + 1;
sut.ContainsKey(0).Should().BeTrue();
sut.ContainsKey(1).Should().BeFalse();
}
[Theory]
[InlineData(0)]
[InlineData(42)]
public void ContainsKey_WhenInitializedEmpty_Works(int defaultValue)
{
var sut = new SparseScalarArray<int>(defaultValue);
Test(sut, defaultValue);
}
[Theory]
[InlineData(0)]
[InlineData(42)]
public void ContainsKey_WhenGivenCapacity_Works(int defaultValue)
{
var sut = new SparseScalarArray<int>(defaultValue, 10);
Test(sut, defaultValue);
}
}
|
// <copyright file="BaseSerializer.cs" company="Firoozeh Technology LTD">
// Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
/**
* @author Alireza Ghodrati
*/
using System;
using FiroozehGameService.Utils.Serializer.Helpers;
namespace FiroozehGameService.Utils.Serializer.Abstracts
{
/// <summary>
/// Represents BaseSerializer In Game Service Binary Serializer
/// </summary>
public abstract class BaseSerializer
{
internal BaseSerializer()
{
}
internal abstract void SerializeObject(object obj, GsWriteStream writeStream);
internal abstract object DeserializeObject(GsReadStream readStream);
internal abstract bool CanSerializeModel(object obj);
internal abstract bool CanSerializeModel(Type type);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace HelloASPDotNET.Controllers
{
public class HelloController : Controller
{
// GET: /<controller>/
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("/hello")]
public IActionResult Welcome(string name = "World")
{
ViewBag.person = name;
return View();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler3
{
class PrimeFactors
{
public Int64 value;
public void calculate(Int64 number)
{
if (number % 2 == 0)
{
if (value < 2) value = 2;
calculate(number / 2);
}
for (int i = 3; i <= number; i += 2)
{
if (number % i == 0)
{
if (value < i) value = i;
calculate(number / i);
break;
}
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MapClasses;
using EntityClasses;
[ExecuteInEditMode]
public class ShowLevel : MonoBehaviour
{
[SerializeField] GameManager manager;
[SerializeField] int levelToLoad = 0;
LevelManager levelManager;
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(gameObject.transform.position, 0.25f);
if (manager == null)
return;
levelManager = manager.LevelManager;
var levels = levelManager.levels;
if (levelToLoad < 0 || levelToLoad >= levels.Count)
{
Debug.LogWarning("Level To Load is out of range.");
return;
}
Level level = levels[levelToLoad];
if (level != null)
{
DrawCells(level);
DrawEntitySpawns(level);
}
}
void DrawCells(Level level)
{
Texture2D levelMap = level.levelMap;
if (levelMap == null)
{
Debug.Log("Level texture is null.");
return;
}
Color[] levelPixels = levelMap.GetPixels();
int width = levelMap.width;
int depth = levelMap.height;
Vector3 size = new Vector3(0.98f, 0f, 0.98f) * levelManager.CellScale;
for (int p = 0; p < levelPixels.Length; p++)
{
Gizmos.color = levelPixels[p];
Vector3 center = new Vector3(Cell.GetX(p, width) * levelManager.CellScale, 0, Cell.GetZ(p, width) * levelManager.CellScale);
Gizmos.DrawWireCube(center, size);
}
}
void DrawEntitySpawns(Level level)
{
if (level.spawnList.Count > 0 && level.spawnList[0] == null)
{
Debug.LogWarning("WARNING: level has no spawns.");
}
foreach (EnemySpawn spawn in level.spawnList)
{
if (spawn.EnemyObject != null && spawn.EnemyObject.Enemy != null)
{
Gizmos.color = new Color(1, 0, 0, 0.1f);
Vector3 center = new Vector3(spawn.X * levelManager.CellScale, 0f, spawn.Z * levelManager.CellScale);
SkinnedMeshRenderer rend = spawn.EnemyObject.Enemy.Renderer;
Gizmos.DrawWireMesh(rend.sharedMesh, center + (rend.transform.localPosition * levelManager.CellScale), Quaternion.identity, spawn.EnemyObject.Enemy.Instance.transform.localScale * levelManager.CellScale);
// foreach (MeshFilter filter in spawn.EnemyObject.Enemy.Instance.GetComponentsInChildren<MeshFilter>())
// {
// Transform pieceTransform = filter.transform;
// if (pieceTransform != null && filter.sharedMesh != null)
// {
// Gizmos.DrawWireMesh(filter.sharedMesh, center + pieceTransform.localPosition, pieceTransform.localRotation, filter.transform.localScale * levelManager.CellScale);
// }
// }
}
}
}
}
|
using System;
using System.Data.SQLite;
using System.Diagnostics;
using System.Windows.Forms;
namespace electrika
{
public partial class Search : Form
{
//sqlite connection properties
private SQLiteConnection sqliteConnection;
private SQLiteCommand sqliteCommand;
private SQLiteDataReader sqliteReader;
private string sqlQuery;
private AutoCompleteStringCollection equipements_names;
private string shemaTypePdf;
public Search()
{
InitializeComponent();
//hide image and shema btn
technical_img.ImageLocation = "../../../res/logo-ocp.png";
shema_pdf_btn.Visible = false;
// nombre and observation set to 0 at beginning
equipement_nmbr_label.Text = "0";
equipement_observation_label.Text = "0";
//sqlite connection initialization
sqliteConnection = new SQLiteConnection("Data Source=../../../res/database/laverie.db");
//open the connection
sqliteConnection.Open();
sqlQuery = "SELECT e.designation , e.id , d.nom FROM equipement e , departement d where e.departement_id = d.id;";
sqliteCommand = new SQLiteCommand(sqlQuery, sqliteConnection);
equipements_names = new AutoCompleteStringCollection();
try
{
sqliteReader = sqliteCommand.ExecuteReader();
while (sqliteReader.Read())
{
//add data to the autocomplete variable so we can use it in text box
equipements_names.Add(sqliteReader.GetString(0) + " | " + sqliteReader.GetString(2) + " | "
+ sqliteReader.GetInt32(1).ToString() ); //format Equipement_name | departement_name | equpement_id
}
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
}
finally {
if (sqliteReader != null) sqliteReader.Close();
sqliteConnection.Close();
sqlQuery = null;
sqliteCommand = null;
}
}
private void Search_Load(object sender, EventArgs e)
{
search_box.AutoCompleteCustomSource = equipements_names;
search_box.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
search_box.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void Button2_Click(object sender, EventArgs e)
{
//get search box query
string searchQuery = search_box.Text;
//split search query to get id
string[] searchQueryWords = searchQuery.Split('|');
string[] searchedEquipementId = searchQueryWords[2].Split(' '); // equipement real id
//sqlite connection and command
sqliteConnection.Open();
//equpement informations query
sqlQuery = "SELECT e.nombre , e.observation FROM equipement e WHERE e.id = " + searchedEquipementId[1];
//fiche technique query
var technicalImgQuery = "SELECT f.id , f.shema_pdf FROM fiche_technique f ," +
" equipement e WHERE f.equipement_id = e.id and e.id = " + searchedEquipementId[1];
//fiche technique query command
var technicalImgSqliteCommand = new SQLiteCommand(technicalImgQuery, sqliteConnection);
//fiche technique reader
SQLiteDataReader technicalImgReader = technicalImgSqliteCommand.ExecuteReader();
sqliteCommand = new SQLiteCommand(sqlQuery, sqliteConnection);
sqliteReader = sqliteCommand.ExecuteReader();
try
{
while (sqliteReader.Read())
{
if (sqliteReader.GetString(0) != "")
{
equipement_nmbr_label.Text = sqliteReader.GetString(0);
}
else {
equipement_nmbr_label.Text = "non-défini";
}
if (sqliteReader.GetString(1) != "") {
equipement_observation_label.Text = sqliteReader.GetString(1);
}
else {
equipement_observation_label.Text = "non-défini";
}
}
if (technicalImgReader.HasRows)
{
while (technicalImgReader.Read())
{
//set technical image format image{number}.png
technical_img.ImageLocation = "../../../res/fiche_technique_img/image" +
technicalImgReader.GetInt32(0).ToString() + ".png";
shema_pdf_btn.Visible = true;
if (technicalImgReader.GetValue(1).ToString() == "0")
{
shema_pdf_btn.Visible = false;
}
else
{ //set the button click to open pdf shema
shemaTypePdf = technicalImgReader.GetValue(1).ToString();
}
}
}
else {
technical_img.ImageLocation = "../../../res/logo-ocp.png";
shema_pdf_btn.Visible = false;
}
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
}
finally {
sqliteConnection.Close();
}
}
private void Shema_pdf_btn_Click(object sender, EventArgs e)
{
try {
ProcessStartInfo shemaTypePdfFile = new ProcessStartInfo("D:/Projects/Desktop/dotNet/electrika/res/shemaPdf/page-" + shemaTypePdf + ".pdf");
Process.Start(shemaTypePdfFile);
} catch (Exception error){
Console.WriteLine(error.ToString());
}
Console.WriteLine("../../../res/shemaPdf/page-" + shemaTypePdf + ".pdf");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandamMove : MonoBehaviour
{
public GameObject[] Block = new GameObject[8];
public GameObject[] MoveBranch = new GameObject[9];
// ソードの当たり判定のオブジェクトの宣言※親
GameObject Sword_L;
GameObject Sword_R;
// 子オブジェクト用に変数を宣言s
Transform Sword_L_Child;
Transform Sword_R_Child;
public int[] MoveNum = new int[8];
public int[] BlockNum = new int[8];
public bool Rank;
int Block_Num;
public int temp;
// 自分自身がどの空オブジェクトにいるか判断する
public static bool MoveTopL;
public static bool MoveTopR;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < MoveBranch.Length - 1; i++)
{
Block_Num = Random.Range(0, Block.Length);
Instantiate(MoveBranch[i], MoveBranch[i].transform.position, MoveBranch[i].transform.rotation);
Instantiate(Block[Block_Num], MoveBranch[i].transform.position, Block[Block_Num].transform.rotation);
}
//Instantiate(MoveBranch[8], MoveBranch[8].transform.position, MoveBranch[8].transform.rotation);
this.Sword_L = GameObject.Find("Sword_L");
this.Sword_R = GameObject.Find("Sword_R");
this.Sword_L_Child = this.Sword_L.transform.Find("effect");
this.Sword_R_Child = this.Sword_R.transform.Find("effect2");
}
// Update is called once per frame
void Update()
{
// Tagで指定したブロックに衝突した場合、真偽値を返す。※ソードについてるscriptで判定
// 真の場合、一番後ろに生成される。
//MoveTopL = this.Sword_L_Child.GetComponent<Collision_L_Sword>().Collision_rank_L;
//MoveTopR = this.Sword_R_Child.GetComponent<Collision_R_Sword>().Collision_rank_R;
//if (MoveTopL)
//{
// Block_Num = Random.Range(0, Block.Length - 1);
// Instantiate(Block[Block_Num], MoveBranch[8].transform.position, Block[Block_Num].transform.rotation);
//if (MoveTopR)
//{
// Block_Num = Random.Range(0, Block.Length - 1);
// Instantiate(Block[Block_Num], MoveBranch[8].transform.position, Block[Block_Num].transform.rotation);
//}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Fields;
using FakeItEasy;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentFields.Settings;
using Xunit;
namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Fields.NumericFieldGraphSyncerTests
{
public class NumericFieldGraphSyncerValidateSyncComponentTestsBase : FieldGraphSyncer_ValidateSyncComponentTestsBase
{
public Dictionary<string, object> SourceNodeProperties { get; set; }
public NumericFieldSettings NumericFieldSettings { get; set; }
public NumericFieldGraphSyncerValidateSyncComponentTestsBase()
{
SourceNodeProperties = new Dictionary<string, object>();
A.CallTo(() => SourceNode.Properties).Returns(SourceNodeProperties);
NumericFieldSettings = new NumericFieldSettings();
A.CallTo(() => ContentPartFieldDefinition.GetSettings<NumericFieldSettings>()).Returns(NumericFieldSettings);
ContentFieldGraphSyncer = new NumericFieldGraphSyncer();
}
//todo: should we be strict when types mismatch, i.e. scale has changed? probably yes
[Fact]
public async Task ValidateSyncComponent_Scale0PropertyCorrect_ReturnsTrue()
{
const string valueContent = "123.0";
const long valueProperty = 123;
ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
NumericFieldSettings.Scale = 0;
(bool validated, _) = await CallValidateSyncComponent();
Assert.True(validated);
}
[Fact]
public async Task ValidateSyncComponent_ScaleMoreThan0PropertyCorrect_ReturnsTrue()
{
const string valueContent = "123.0";
const double valueProperty = 123d;
ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
NumericFieldSettings.Scale = 1;
(bool validated, _) = await CallValidateSyncComponent();
Assert.True(validated);
}
[Fact]
public async Task ValidateSyncComponent_ContentNull_ReturnsFalse()
{
const long valueProperty = 123;
ContentItemField = JObject.Parse($"{{\"Value\": null}}");
SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
(bool validated, _) = await CallValidateSyncComponent();
Assert.False(validated);
}
[Fact]
public async Task ValidateSyncComponent_PropertyMissing_ReturnsFalse()
{
const string valueContent = "123.0";
ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
NumericFieldSettings.Scale = 0;
(bool validated, _) = await CallValidateSyncComponent();
Assert.False(validated);
}
[Fact]
public async Task ValidateSyncComponent_PropertySameScaleButValueDifferent_ReturnsFalse()
{
const string valueContent = "123.0";
const long valueProperty = 321;
ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
NumericFieldSettings.Scale = 0;
(bool validated, _) = await CallValidateSyncComponent();
Assert.False(validated);
}
// even though values are equivalent, types are different, so we fail validation
//[Fact]
//public async Task ValidateSyncComponent_PropertyDecimalValueScale0ValueEquivalent_ReturnsFalse()
//{
// const string valueContent = "123.0";
// const double valueProperty = 123d;
// ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
// SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
// NumericFieldSettings.Scale = 0;
// (bool validated, _) = await CallValidateSyncComponent();
// Assert.False(validated);
//}
[Fact]
public async Task ValidateSyncComponent_PropertyDecimalValueScale0PropertyValueMorePrecise_ReturnsFalse()
{
const string valueContent = "123.0";
const double valueProperty = 123.4d;
ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
NumericFieldSettings.Scale = 0;
(bool validated, _) = await CallValidateSyncComponent();
Assert.False(validated);
}
//[Fact]
//public async Task ValidateSyncComponent_PropertyLongValueScaleMoreThan0ValueEquivalent_ReturnsFalse()
//{
// const string valueContent = "123.0";
// const long valueProperty = 123;
// ContentItemField = JObject.Parse($"{{\"Value\": {valueContent}}}");
// SourceNodeProperties.Add(FieldNameTransformed, valueProperty);
// NumericFieldSettings.Scale = 1;
// (bool validated, _) = await CallValidateSyncComponent();
// Assert.False(validated);
//}
//todo: test that verifies that failure reason is returned
}
}
|
using System;
namespace DoodleReplacement
{
internal class EnvironmentUtil
{
public static string GetEnvironmentVariable(string name)
{
return Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
}
|
using System;
namespace Calculator
{
public class Calculator: ICalculator
{
public int Result { get; private set; }
public Calculator()
{
Result = 0;
}
public void Reset()
{
throw new System.NotImplementedException();
}
public void Add(int x)
{
if (x >= 0 && (Result + x) < Result)
{
throw new InvalidOperationException("Overflow while adding.");
}
if (x < 0 && (Result + x) > Result)
{
throw new InvalidOperationException("Underflow while adding.");
}
Result += x;
}
public void Subtract(int x)
{
if (x >= 0)
{
Result -= x;
}
if (x < 0)
{
Result -= (x / -1);
}
}
public void Multiply(int x)
{
int a = Result;
if (a > int.MaxValue / x)
{
throw new InvalidOperationException("Overflow occurred while multiplying.");
} /* `a * x` would overflow */;
if ((a < int.MinValue / x))
{
throw new InvalidOperationException("Underflow occurred while multiplying.");
}/* `a * x` would underflow */;
Result *= x;
}
public void Divide(int x)
{
if (x == 0)
{
throw new InvalidOperationException("Can not be divided by zero.");
}
Result /= x;
}
public void Modulus(int x)
{
Result %= x;
}
}
} |
using System;
using System.Collections.Generic;
namespace WebStore.Domain.ViewModels
{
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public decimal Price { get; set; }
}
public class CatalogViewModel
{
public IEnumerable<ProductViewModel> Products { get; set; }
public int? SectionId { get; set; }
public int? BrandId { get; set; }
public PageViewModel PageViewModel { get; set; }
}
public class PageViewModel
{
public int Page { get; set; }
public int PageSize { get; set; }
public int TotalItems { get; set; }
public int TotalPages => PageSize == 0 ? 0 : (int)Math.Ceiling((double)TotalItems / PageSize);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProCodeGuide.Sample.SolidPrinciples.SolidPrinciples.DI
{
public interface IOrderRespository
{
bool AddOrder(object orderDetails);
bool ModifyOrder(object orderDetails);
object GetOrderDetails(string orderId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Web.admin {
public partial class CrearOT : System.Web.UI.Page {
SRV_Planes.SRV_PlanesClient objPlanes = new SRV_Planes.SRV_PlanesClient();
SRV_Proovedor.SRV_ProovedorClient objProovedor = new SRV_Proovedor.SRV_ProovedorClient();
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
listPlanes();
}
}
protected void listPlanes()
{
//Conpañia o Proovedor
ddlConpania.DataSource = objProovedor.ListarProvedor();
ddlConpania.DataTextField = "nombre_proveedor";
ddlConpania.DataValueField = "id_tipoProveedor";
ddlConpania.DataBind();
if (ddlConpania.Items.Count != 0)
{
int id_tipoProveedor = Convert.ToInt32(ddlConpania.SelectedValue);
listTipoPlan(id_tipoProveedor);
}
else
{
ddlConpania.Items.Clear();
ddlConpania.Items.Clear();
ddlConpania.DataSource = null;
ddlConpania.DataBind();
}
}
protected void ddlConpania_SelectedIndexChanged(Object sender, EventArgs e)
{
listTipoPlan(Int32.Parse(ddlConpania.SelectedValue));
}
protected void listTipoPlan(int id_tipoProveedor)
{
//Plan
ddlPlan.DataSource = objPlanes.ListarPlanesProovedor(id_tipoProveedor);
ddlPlan.DataTextField = "cod_plan";
ddlPlan.DataValueField = "id_plan";
ddlPlan.DataBind();
if (ddlPlan.Items.Count != 0)
{
int id_plan = Convert.ToInt32(ddlPlan.SelectedValue);
listRestoPlan(id_plan);
}
else
{
ddlPlan.Items.Clear();
ddlPlan.Items.Clear();
ddlPlan.DataSource = null;
ddlPlan.DataBind();
}
}
protected void ddlPlan_SelectedIndexChanged1(Object sender, EventArgs e)
{
listRestoPlan(Int32.Parse(ddlPlan.SelectedValue));
}
protected void listRestoPlan(int id_plan)
{
//Internet
ddlMB.DataSource = objPlanes.ListarPlanesFiltro(id_plan);
ddlMB.DataTextField = "nav";
ddlMB.DataValueField = "id_plan";
ddlMB.DataBind();
//Precio
ddlPrecio.DataSource = objPlanes.ListarPlanesFiltro(id_plan);
ddlPrecio.DataTextField = "COSTO";
ddlPrecio.DataValueField = "id_plan";
ddlPrecio.DataBind();
}
/*protected void btnGuardar_Click(Object sender, EventArgs e) {
//accede a las funciones
SRV_OrdenTrabajo.SRV_OrdenTrabajoClient ordenTrabajoClient = new SRV_OrdenTrabajo.SRV_OrdenTrabajoClient();
SRV_DetOT.SRV_DetOTClient detOTClient = new SRV_DetOT.SRV_DetOTClient();
if (validador()) {
//OT -> fechaCreacion, idmaquina, idcreador, idencargado, idstatusot, fechacierre (idOT)
//DOT -> idOT, idTecnico, idRepuesto, idFalla, fecha (idDOT)
objUsuarioConectado = (SRV_Login.UsuarioSRV)Session["sesionUsuario"];
var resNvaOT = ordenTrabajoClient.CrearOT(
Int32.Parse(ddlMaquina.SelectedValue),
objUsuarioConectado.idPersona,
Int32.Parse(ddlEncargado.SelectedValue),
statusOTClient.BuscarIDStatusOT("Creada"));
if ((resNvaOT != null) && (resNvaOT.id > 0)) {
//creo el detalle ot
var resDetOT = detOTClient.CrearDetalleOT(
(int)resNvaOT.id,
Int32.Parse(ddlEncargado.SelectedValue),
Int32.Parse(ddlRepuesto.SelectedValue),
Int32.Parse(ddlFalla.SelectedValue));
if (!resDetOT.error) {
refrescador();
Response.Redirect("~/admin/index.aspx");
}
} else {
//error, no pude guardar
}
}
}*/
protected Boolean validador() {
if (ddlConpania.Text.Equals("")) return false;
if (ddlConpania.Text.Equals("")) return false;
if (ddlConpania.Text.Equals("")) return false;
if (ddlConpania.Text.Equals("")) {
return false;
} else {
return true;
}
}
}
} |
using Prism.Navigation;
namespace Soccer.Prism.ViewModels
{
public class MyPositionsPageViewModel : ViewModelBase
{
public MyPositionsPageViewModel(INavigationService navigationService) : base(navigationService)
{
Title = "My Positions";
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using Microsoft.Data.Entity.Storage.Commands;
using Microsoft.Data.Entity.Utilities;
namespace Microsoft.Data.Entity.Infrastructure
{
public class SqlBatchBuilder
{
private readonly List<RelationalCommand> _commands = new List<RelationalCommand>();
private readonly RelationalCommandBuilder _commandBuilder = new RelationalCommandBuilder();
public virtual IReadOnlyList<RelationalCommand> RelationalCommands => _commands;
public virtual SqlBatchBuilder EndBatch()
{
if (_commandBuilder.Length != 0)
{
_commands.Add(_commandBuilder.RelationalCommand);
_commandBuilder.Clear();
}
return this;
}
public virtual SqlBatchBuilder Append([NotNull] object o)
{
Check.NotNull(o, nameof(o));
_commandBuilder.Append(o);
return this;
}
public virtual SqlBatchBuilder AppendLine()
{
_commandBuilder.AppendLine();
return this;
}
public virtual SqlBatchBuilder AppendLine([NotNull] object o)
{
Check.NotNull(o, nameof(o));
_commandBuilder.AppendLine(o);
return this;
}
public virtual SqlBatchBuilder AppendLines([NotNull] object o)
{
Check.NotNull(o, nameof(o));
_commandBuilder.AppendLines(o);
return this;
}
public virtual IDisposable Indent() => _commandBuilder.Indent();
public virtual SqlBatchBuilder IncrementIndent()
{
_commandBuilder.IncrementIndent();
return this;
}
public virtual SqlBatchBuilder DecrementIndent()
{
_commandBuilder.DecrementIndent();
return this;
}
}
}
|
using UnityEngine;
namespace UnityAtoms
{
public class AtomListAttribute : PropertyAttribute
{
public string Label { get; set; }
public string ChildPropName { get; set; }
public bool IncludeChildrenForItems { get; set; }
public AtomListAttribute(string label = null, string childPropName = "_list", bool includeChildrenForItems = true)
{
Label = label;
ChildPropName = childPropName;
IncludeChildrenForItems = includeChildrenForItems;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CSharpFinalProject.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Data.SqlClient;
namespace CSharpFinalProject.Pages
{
public class loginModel : PageModel
{
[BindProperty]
public UserModels user { get; set; }
[BindProperty(SupportsGet = true)]
public string outMessage { get; set; }
[BindProperty(SupportsGet = true)]
public string loginError { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (ModelState.IsValid == false)
{
return Page();
}
SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=finalproject;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
string sql = "SELECT * FROM [finalproject].[dbo].[users] WHERE email = '"
+ user.email + "'AND password = '" + user.password + "'";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
user.userName = string.Format("{0}", reader[1]);
user.email = string.Format("{0}", reader[2]);
user.phone = string.Format("{0}", reader[4]);
return RedirectToPage("/Profile", new { user.userName, user.email, user.phone});
}
else
{
loginError = "Email or password not correct";
return RedirectToPage("/login", new { loginError });
}
}
}
} |
namespace GeoAPI.Geometries
{
public interface IMultiLineString : IMultiCurve
{
IMultiLineString Reverse();
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class DialoguePanel : MonoBehaviour
{
[SerializeField]
string _thingName;
[SerializeField]
string _currentDialoguePlaceholderText;
[SerializeField]
string _currentDialogueText;
[SerializeField]
Image _currentPortrait;
[SerializeField]
Text _textField;
[SerializeField]
Text _nameField;
[SerializeField]
Button _continueDialogueButton;
[SerializeField]
Button _takeItemButton;
[SerializeField]
Button _leaveItemButton;
[SerializeField]
Text _itemDialogueField;
Dictionary<string, List<Transform>> UIElements = new Dictionary<string, List<Transform>>();
List<Transform> _characterUIElements = new List<Transform>();
List<Transform> _itemUIElements = new List<Transform>();
int _currentDialogueIndex;
int _currentDialogueLineIndex = 0;
BaseCharacter _currentThing;
BaseEnemy _currentCharacter;
bool _dialogueFinishedScrolling = false;
bool _isCurrentTargetAnItem = false;
public bool _dialogueComplete = false;
private UnityAction _onContinueDialogueAction;
private UnityAction _onTakeItemAction;
private UnityAction _onLeaveItemAction;
List<string> _dialogueLines;
string _currentDialogueLine;
public BaseEnemy CurrentCharacter
{
set
{
_currentCharacter = value;
}
}
private void Awake()
{
_characterUIElements.Add( _currentPortrait.transform);
_characterUIElements.Add(_nameField.transform);
_characterUIElements.Add( _continueDialogueButton.transform);
_characterUIElements.Add(_textField.transform);
_itemUIElements.Add(_takeItemButton.transform);
_itemUIElements.Add( _leaveItemButton.transform);
_itemUIElements.Add( _itemDialogueField.transform);
UIElements.Add("Character", _characterUIElements);
UIElements.Add("Item", _itemUIElements);
SetUIVisibility(false);
Cursor.visible = true;
_onContinueDialogueAction += OnContinueDialogue;
_continueDialogueButton.onClick.AddListener(_onContinueDialogueAction);
_onTakeItemAction += OnTakeItem;
_takeItemButton.onClick.AddListener(_onTakeItemAction);
_onLeaveItemAction += OnLeaveItem;
_leaveItemButton.onClick.AddListener(_onLeaveItemAction);
_dialogueLines = new List<string>();
}
public void InitDialoguePanel(BaseCharacter thing)
{
_currentThing = thing;
switch (thing.ThingType)
{
case ThingType.Character:
SetUIVisibility(true, "Character");
_dialogueLines = thing.ThingInfo.GeneralDialogueLines;
Debug.Log(_dialogueLines.Count);
_thingName = thing.CharacterName;
_currentPortrait.sprite = thing.CharacterImages[0];
_nameField.text = _thingName;
_currentDialoguePlaceholderText = _dialogueLines[_currentDialogueLineIndex];
_isCurrentTargetAnItem = false;
break;
case ThingType.Item:
SetUIVisibility(true, "Item");
_currentDialoguePlaceholderText = "You find a " + thing.Name + ". Will you take it?";
_isCurrentTargetAnItem = true;
break;
}
_textField.text = _currentDialogueText;
StartCoroutine("ScrollText");
}
public void OnTakeItem()
{
Debug.Log("taking item");
Root.GetComponentFromRoot<UIHandler>().HideAllActiveUIPanels();
Root.GetComponentFromRoot<EncounterHandler>().EndEncounter();
}
public void OnLeaveItem()
{
Debug.Log("leaving item");
Root.GetComponentFromRoot<UIHandler>().HideAllActiveUIPanels();
Root.GetComponentFromRoot<EncounterHandler>().EndEncounter();
}
public void OnContinueDialogue()
{
if (_dialogueComplete)
{
// tell ui handler to make selection panel if needed
// will probs phase this out for card UI
switch (_currentThing.ThingType)
{
case ThingType.Character:
Root.GetComponentFromRoot<UIHandler>().ShowSelectionPanel(UISelectionPanelType.Character);
break;
}
}
if (_dialogueFinishedScrolling)
{
if(_currentDialogueLineIndex >= _dialogueLines.Count-1)
{
_dialogueComplete = true;
}
else
{
_currentDialogueLineIndex++;
UpdateDialogue(GetNextDialogueLine(_currentDialogueLineIndex));
StartCoroutine("ScrollText");
}
}
}
string GetNextDialogueLine(int index)
{
string t = "";
if(_dialogueLines[index] != null)
{
t = _dialogueLines[index];
}
return t;
}
IEnumerator ScrollText()
{
while (_currentDialogueIndex < _currentDialoguePlaceholderText.Length)
{
_currentDialogueText += _currentDialoguePlaceholderText[_currentDialogueIndex];
_currentDialogueIndex++;
if (_isCurrentTargetAnItem)
{
_itemDialogueField.text = _currentDialogueText;
}
else
{
_textField.text = _currentDialogueText;
}
yield return new WaitForSeconds(0.05f);
}
_dialogueFinishedScrolling = true;
}
private void UpdateDialogue(string text)
{
_currentDialogueIndex = 0;
_currentDialoguePlaceholderText = "";
_currentDialogueText = "";
_currentDialoguePlaceholderText = text;
}
private void SetUIVisibility(bool value, string tag = null)
{
if(tag == null)
{
foreach(var x in UIElements["Character"])
{
x.gameObject.SetActive(value);
}
foreach (var x in UIElements["Item"])
{
x.gameObject.SetActive(value);
}
}
else
{
var tempList = UIElements[tag];
for (int i = 0; i < tempList.Count(); i++)
{
tempList[i].gameObject.SetActive(value);
}
}
}
}
|
using System.ComponentModel.DataAnnotations;
using Alabo.Web.Mvc.Attributes;
namespace Alabo.Industry.Shop.Products.Domain.Enums
{
/// <summary>
/// 商品状态
/// </summary>
[ClassProperty(Name = "商品状态")]
public enum ProductStatus
{
/// <summary>
/// 审核中
/// </summary>
[Display(Name = "审核中")] [LabelCssClass(BadgeColorCalss.Metal)]
Auditing = 1,
/// <summary>
/// 已上架
/// </summary>
[Display(Name = "已上架")] [LabelCssClass(BadgeColorCalss.Success)]
Online = 2,
/// <summary>
/// 审核未通过
/// </summary>
[Display(Name = "平台审核失败")] [LabelCssClass(BadgeColorCalss.Danger)]
FailAudited = 3,
/// <summary>
/// 已下架
/// </summary>
[Display(Name = "已下架")] [LabelCssClass(BadgeColorCalss.Danger)]
SoldOut = 4,
/// <summary>
/// 供应商删除
/// </summary>
[Display(Name = "供应商删除")] [LabelCssClass(BadgeColorCalss.Danger)]
SupplerDelete = 5,
/// <summary>
/// 审核删除
/// </summary>
[Display(Name = "平台删除")] [LabelCssClass(BadgeColorCalss.Danger)]
Deleted = 6
}
} |
using damdrempe_zadaca_2.Citaci;
using damdrempe_zadaca_2.Podaci.Modeli;
using damdrempe_zadaca_2.Sustav;
using System;
using System.Collections.Generic;
using System.Linq;
using static damdrempe_zadaca_2.Podaci.Enumeracije;
using static damdrempe_zadaca_2.Pomagaci.Entiteti.PodrucjaComposite;
namespace damdrempe_zadaca_2.Pomagaci.Entiteti
{
class PripremateljPodrucja
{
public static List<Podrucje> PripremiPodrucja(List<PodrucjeRedak> podrucjaPopisRetci)
{
List<Podrucje> podrucja = new List<Podrucje>();
foreach (PodrucjeRedak podrucjeRedak in podrucjaPopisRetci)
{
Podrucje novoPodrucje = new Podrucje(podrucjeRedak.ID, podrucjeRedak.Naziv);
podrucja.Add(novoPodrucje);
}
foreach (Podrucje podrucje in podrucja)
{
PodrucjeRedak podrucjeRedak = podrucjaPopisRetci.FirstOrDefault(p => p.ID == podrucje.PodrucjeID);
foreach (string dioID in podrucjeRedak.Dijelovi)
{
if (Pomocno.DioPodrucjaJeUlica(dioID))
{
Ulica ulica = Program.Ulice.FirstOrDefault(u => u.ID == dioID);
if(ulica != null)
{
UlicaPodrucja ulicaPodrucja = new UlicaPodrucja(dioID, ulica.Naziv, ulica);
podrucje.Dodijeli(ulicaPodrucja);
}
}
else
{
Podrucje podPodrucje = podrucja.FirstOrDefault(p => p.PodrucjeID == dioID);
if(podPodrucje != null)
{
podrucje.Dodijeli(podPodrucje);
}
}
}
}
return podrucja;
}
public static Dictionary<VrstaOtpada, float> IzracunajUkupanOtpadPodrucjaSIspisom(List<PodrucjeComponent> podpodrucja, bool ispis)
{
Dictionary<VrstaOtpada, float> otpad = new Dictionary<VrstaOtpada, float>();
foreach (VrstaOtpada vrsta in Enum.GetValues(typeof(VrstaOtpada)))
{
otpad[vrsta] = 0;
}
foreach (PodrucjeComponent podrucje in podpodrucja)
{
if (podrucje.GetType() == typeof(UlicaPodrucja))
{
UlicaPodrucja ulica = (UlicaPodrucja)podrucje;
if (ispis) Program.Ispisivac.PromijeniBojuTeksta(ConsoleColor.Cyan);
if (ispis) Program.Ispisivac.ObavljeniPosao($"ULICA [{ulica.ReferencaUlice.ID}] {ulica.ReferencaUlice.Naziv}");
foreach (VrstaOtpada vrsta in Enum.GetValues(typeof(VrstaOtpada)))
{
if (ulica.ReferencaUlice.Otpad.ContainsKey(vrsta))
{
if (ispis) Program.Ispisivac.ObavljeniPosao($"{vrsta}: {ulica.ReferencaUlice.Otpad[vrsta]}kg");
otpad[vrsta] += ulica.ReferencaUlice.Otpad[vrsta];
}
}
if (ispis) Program.Ispisivac.ObavljeniPosao("");
}
else if (podrucje.GetType() == typeof(Podrucje))
{
Podrucje podPodrucje = (Podrucje)podrucje;
Dictionary<VrstaOtpada, float> otpadPodpodrucja = IzracunajUkupanOtpadPodrucjaSIspisom(podPodrucje.podrucja, ispis);
foreach (VrstaOtpada vrsta in Enum.GetValues(typeof(VrstaOtpada)))
{
if (otpadPodpodrucja.ContainsKey(vrsta))
{
otpad[vrsta] += otpadPodpodrucja[vrsta];
}
}
}
}
return otpad;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Runtime.InteropServices;
using System.Collections.Specialized;
using System;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Drawing;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int refreshTime = 200;
slike.readData();
//slike.printData();
slike.invert();
String URL = "http://localhost:8080/crest/v1/api";
String avto = "";
String currTime = "";
String mSpeed = "";
int fuelPercentage = 0;
LogitechGSDK.LogiLcdInit("Project cars testing", LogitechGSDK.LOGI_LCD_TYPE_MONO);
LogitechGSDK.LogiLcdUpdate();
while (true)
{
dynamic js = null;
using (var webClient = new System.Net.WebClient())
{
try {
var json = webClient.DownloadString(URL);
js = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
avto = js.vehicleInformation.mCarName;
currTime = js.timings.mCurrentTime;
mSpeed = js.carState.mSpeed;
fuelPercentage = js.carState.mFuelLevel * 100;
}
catch (Exception e)
{
LogitechGSDK.LogiLcdMonoSetText(0, "Error!");
LogitechGSDK.LogiLcdMonoSetBackground(mergeArrays(slike.bmpFileData,fuelGauge(100)));
LogitechGSDK.LogiLcdUpdate();
Thread.Sleep(200);
continue;
}
}
//LogitechGSDK.LogiLcdMonoSetText(0, avto);
//LogitechGSDK.LogiLcdMonoSetText(1, currTime);
//LogitechGSDK.LogiLcdMonoSetText(2, mSpeed);
//
//LogitechGSDK.LogiLcdMonoSetBackground(slike.bmpFileData);
LogitechGSDK.LogiLcdMonoSetBackground(mergeArrays(slike.bmpFileData, fuelGauge(fuelPercentage)));
LogitechGSDK.LogiLcdUpdate();
Thread.Sleep(refreshTime);
}
}
// Merge two arrays into one, needs improvement
static byte[] mergeArrays(byte[] array1, byte[] array2){
byte[] returnArray = new byte[array1.Length];
Array.Copy(array1, returnArray,array1.Length);
for (int i = 0; i < array1.Length; i++){
if (array2[i] == 255){
returnArray[i] = 255;
}
}
return returnArray;
}
// Draw the fuel gauge
static byte[] fuelGauge(int percentage){
byte[] screenArray = new byte[6880];
int startX = 16;
int startY = 34;
int width = 5;
for(int i = 0; i < percentage; i++){
for(int j = 0; j < width; j++) {
screenArray[startY * LogitechGSDK.LOGI_LCD_MONO_WIDTH + startX+i + j* LogitechGSDK.LOGI_LCD_MONO_WIDTH] = 255;
}
}
return screenArray;
}
}
public class slike
{
static Bitmap main = (Bitmap)Bitmap.FromFile("main.bmp");
public static byte[] bmpFileData = null;
public static byte[] bitVaues = null;
public static void readData()
{
Rectangle rect = new Rectangle(0, 0, main.Width, main.Height);
System.Drawing.Imaging.BitmapData bmpData = null;
int stride = 0;
try
{
bmpData = main.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, main.PixelFormat);
IntPtr ptr = bmpData.Scan0;
stride = bmpData.Stride;
int bytes = bmpData.Stride * main.Height;
bmpFileData = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, bmpFileData, 0, bytes);
}
finally
{
if (bmpData != null)
main.UnlockBits(bmpData);
}
//using (var ms = new System.IO.MemoryStream())
//{
// main.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
// bmpFileData = ms.ToArray();
//}
}
public static void printData()
{
for (int i = 0; i <bmpFileData.Length; i++)
{
Console.Write(bmpFileData[i]);
Console.Write(" ");
}
Console.Write(bmpFileData.Length);
}
public static void invert()
{
for(int i=0; i< bmpFileData.Length; i++)
{
if (bmpFileData[i] == 255)
{
bmpFileData[i] = 0;
}
else
{
bmpFileData[i] = 255;
}
}
}
}
public class LogitechGSDK
{
//LCD SDK
public const int LOGI_LCD_COLOR_BUTTON_LEFT = (0x00000100);
public const int LOGI_LCD_COLOR_BUTTON_RIGHT = (0x00000200);
public const int LOGI_LCD_COLOR_BUTTON_OK = (0x00000400);
public const int LOGI_LCD_COLOR_BUTTON_CANCEL = (0x00000800);
public const int LOGI_LCD_COLOR_BUTTON_UP = (0x00001000);
public const int LOGI_LCD_COLOR_BUTTON_DOWN = (0x00002000);
public const int LOGI_LCD_COLOR_BUTTON_MENU = (0x00004000);
public const int LOGI_LCD_MONO_BUTTON_0 = (0x00000001);
public const int LOGI_LCD_MONO_BUTTON_1 = (0x00000002);
public const int LOGI_LCD_MONO_BUTTON_2 = (0x00000004);
public const int LOGI_LCD_MONO_BUTTON_3 = (0x00000008);
public const int LOGI_LCD_MONO_WIDTH = 160;
public const int LOGI_LCD_MONO_HEIGHT = 43;
public const int LOGI_LCD_COLOR_WIDTH = 320;
public const int LOGI_LCD_COLOR_HEIGHT = 240;
public const int LOGI_LCD_TYPE_MONO = (0x00000001);
public const int LOGI_LCD_TYPE_COLOR = (0x00000002);
[DllImport("LogitechLcdEnginesWrapper", CharSet=CharSet.Unicode, CallingConvention= CallingConvention.Cdecl)]
public static extern bool LogiLcdInit(String friendlyName, int lcdType);
[DllImport("LogitechLcdEnginesWrapper", CharSet=CharSet.Unicode,CallingConvention=CallingConvention.Cdecl)]
public static extern bool LogiLcdIsConnected(int lcdType);
[DllImport("LogitechLcdEnginesWrapper", CharSet= CharSet.Unicode,CallingConvention=CallingConvention.Cdecl)]
public static extern bool LogiLcdIsButtonPressed(int button);
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern void LogiLcdUpdate();
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern void LogiLcdShutdown();
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLcdMonoSetBackground(byte [] monoBitmap);
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLcdMonoSetText(int lineNumber, String text);
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLcdColorSetBackground(byte [] colorBitmap);
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLcdColorSetTitle(String text, int red , int green,int blue);
[DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern bool LogiLcdColorSetText(int lineNumber, String text, int red, int green, int blue);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SilverByteProject.BL.Interfaces
{
public interface ICrawlAgent
{
/// <summary>
/// Crawl using a given url and max depth
/// </summary>
/// <param name="url"></param>
/// <param name="maxDebt"></param>
/// <returns></returns>
Task<Dictionary<string, int>> StartCrawling(string url, int maxDepth);
}
}
|
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Events
{
public class EventRelationshipType : Entity
{
public virtual string EventRelationshipTypeName { get; set; }
public virtual bool Archive { get; set; }
public virtual string Notes { get; set; }
public override string ToString()
{
return this.EventRelationshipTypeName;
}
}
}
|
using Gruzer.Data.Infrastructure;
using Gruzer.Models.Users;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Gruzer.Tests.Data
{
public class EfContextTests
{
private IEfContext context;
public EfContextTests()
{
var builder = new DbContextOptionsBuilder<EfContext>();
builder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=gruzerBase;Trusted_Connection=True;MultipleActiveResultSets=true");
context = new EfContext(builder.Options);
}
[Fact]
public void Can_Create_Context()
{
var dbset = context.Set<User>();
Assert.Equal(dbset.Count() > 0, true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Shipwreck.TypeScriptModels.Expressions;
namespace Shipwreck.TypeScriptModels
{
internal static class StringHelper
{
public static string GetToken(this BinaryOperator @operator)
{
switch (@operator )
{
case BinaryOperator.Add:
return "+";
case BinaryOperator.Subtract:
return "-";
case BinaryOperator.Multiply:
return "*";
case BinaryOperator.Divide:
return "/";
case BinaryOperator.Modulo:
return "\\";
case BinaryOperator.IntegerDivide:
return "%";
case BinaryOperator.LeftShift:
return "<<";
case BinaryOperator.SignedRightShift:
return ">>";
case BinaryOperator.UnsignedRightShift:
return ">>>";
case BinaryOperator.BitwiseAnd:
return "&";
case BinaryOperator.BitwiseOr:
return "|";
case BinaryOperator.BitwiseXor:
return "^";
case BinaryOperator.Exponent:
return "**";
case BinaryOperator.Equal:
return "==";
case BinaryOperator.NotEqual:
return "!=";
case BinaryOperator.StrictEqual:
return "===";
case BinaryOperator.StrictNotEqual:
return "!==";
case BinaryOperator.LessThan:
return "<";
case BinaryOperator.LessThanOrEqual:
return "<=";
case BinaryOperator.GreaterThan:
return ">";
case BinaryOperator.GreaterThanOrEqual:
return ">=";
case BinaryOperator.InstanceOf:
return "instanceof";
case BinaryOperator.In:
return "in";
case BinaryOperator.LogicalAnd:
return "&&";
case BinaryOperator.LogicalOr:
return "||";
default:
throw new NotImplementedException($"{nameof(BinaryOperator)}.{@operator}");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp13.Exceptions
{
internal class Email : Exception
{
public Email()
: base("Enter correct email") { }
}
}
|
using Uintra.Infrastructure.TypeProviders;
namespace Uintra.Features.Permissions.TypeProviders
{
public interface IPermissionActionTypeProvider : IEnumTypeProvider
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Calendar;
namespace MyHotel.Business.Entity.Booking
{
public class RoomBookingEntity
{
public int RoomBookingID { get; set; }
public int RoomID { get; set; }
public string GuestName { get; set; }
public string GuestPhone { get; set; }
public int NumberOfAdult { get; set; }
public int NumberOfChild { get; set; }
public int PricePerRoom { get; set; }
public int PriceOfAdditionalBed { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int BookingStatus { get; set; }
public string AdditionalInfo { get; set; }
public int AlreadyPaid { get; set; }
public int AmountOfDays
{
get
{
return (int)(EndDate - StartDate).TotalDays;
}
}
public int TotalSum
{
get
{
return (PricePerRoom + PriceOfAdditionalBed) * AmountOfDays;
}
}
public int RemainsSum
{
get
{
return TotalSum - AlreadyPaid;
}
}
}
} |
using CommandLine;
using CommandLine.Text;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XESmartTarget.Core.Utils;
namespace XelToCsv
{
class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
var result = Parser.Default.ParseArguments<Options>(args)
.WithParsed(options => ProcessTarget(options));
}
private static void ProcessTarget(Options options)
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileMajorPart.ToString() + "." + fvi.FileMinorPart.ToString() + "." + fvi.FileBuildPart.ToString();
string name = assembly.FullName;
logger.Info(name + " " + version);
logger.Info("Converting {0} to {1}", options.SourceFile, options.DestinationFile);
Convert(options.SourceFile, options.DestinationFile);
}
public static void Convert(String sourceFile, String destinationFile)
{
if (File.Exists(destinationFile))
{
File.Delete(destinationFile);
}
XELFileCSVAdapter Adapter = new XELFileCSVAdapter();
Adapter.InputFile = sourceFile;
Adapter.OutputFile = destinationFile;
DateTime startTime = DateTime.Now;
try
{
Adapter.Convert();
}
catch(Exception e)
{
logger.Error("Conversion Error");
logger.Error(e);
}
TimeSpan duration = DateTime.Now - startTime;
logger.Info("Conversion finished at {0}", DateTime.Now);
logger.Info("{0} seconds taken", duration.TotalSeconds);
}
class Options
{
[Option('s', "SourceFile", Required = true, HelpText = "Source file")]
public string SourceFile { get; set; }
[Option('d', "DestinationFile", Required = true, HelpText = "Destination file")]
public string DestinationFile { get; set; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UI_OK_script : MonoBehaviour
{
void Update()
{
this.gameObject.GetComponent<SpriteRenderer>().color = this.gameObject.transform.parent.gameObject.GetComponent<selecter_script>().colorJugador;
}
}
|
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.AccountEntity;
using Anywhere2Go.DataAccess.Object;
using log4net;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.AccountingLogic.Master
{
public class CustomerLogic
{
private static readonly ILog logger = LogManager.GetLogger(typeof(CustomerLogic));
private MyContext _context = null;
public CustomerLogic()
{
_context = new MyContext(Configurator.CrmAccountingConnection);
}
public List<Customer> GetCustomer(bool? isActive = null)
{
var req = new Repository<Customer>(_context);
List<Customer> result = new List<Customer>();
var query = req.GetQuery();
if (isActive != null)
{
query = query.Where(t => t.isActive == isActive);
}
query = query.OrderBy(t => t.cusName);
return query.ToList();
}
public Customer GetCustomerById(string CusId)
{
var req = new Repository<Customer>(_context);
return req.GetQuery().Where(t => t.cusId == CusId).SingleOrDefault();
}
public BaseResult<bool> SaveCustomer(Customer obj, AccountingAuthentication authen)
{
BaseResult<bool> res = new BaseResult<bool>();
string acc_id = authen != null ? authen.acc_id : "";
string user = authen != null ? authen.first_name + " " + authen.last_name : "";
try
{
var req = new Repository<Customer>(_context);
if (obj.cusId == "") // insert
{
obj.createBy = user;
obj.createDate = DateTime.Now;
obj.updateBy = user;
obj.updateDate = DateTime.Now;
req.Add(obj);
req.SaveChanges();
}
else // update
{
var customer = req.Find(t => t.cusId == obj.cusId).FirstOrDefault();
if (customer != null)
{
customer.cusName = obj.cusName;
customer.cusTaxNumber = obj.cusTaxNumber;
customer.cusAddress = obj.cusAddress;
customer.cusTel = obj.cusTel;
customer.cusFax = obj.cusFax;
customer.cusEmail = obj.cusEmail;
customer.comId = obj.comId;
customer.inspectionComId = obj.inspectionComId;
customer.priceGroupId = obj.priceGroupId;
customer.billingRefId = obj.billingRefId;
customer.isActive = obj.isActive;
customer.updateBy = user;
customer.updateDate = DateTime.Now;
req.SaveChanges();
}
}
res.Result = true;
}
catch (DbEntityValidationException ex)
{
foreach (var eve in ex.EntityValidationErrors)
{
logger.Error(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
}
}
res.Result = false;
res.Message = ex.Message;
logger.Error(string.Format("Method = {0},User = {1}", "transferTaskToCompany", user), ex);
}
catch (Exception ex)
{
res.Result = false;
res.Message = ex.Message;
logger.Error(string.Format("Method = {0},User = {1}", "saveCompany", user), ex);
}
return res;
}
}
} |
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace BeetleBot.Modules
{
public class Hi : ModuleBase<SocketCommandContext>
{
[Command("hi")]
public async Task MelonAsync()
{
await ReplyAsync("Hello " + Context.User.Username);
}
}
}
|
using DemoMVCApplication.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DemoMVCApplication.Controllers
{
public class HomeController : Controller
{
MVCApplicationEntities mvcEntity = new MVCApplicationEntities();
WrapperModel wrapperModel = DataHandler.WrapperMethod();
Movie movie = new Movie();
[NonAction]
public ActionResult Index()
{
return View();
}
public ActionResult ShowMovies()
{
ViewBag.Update = null;
wrapperModel.movie = movie;
return View("Index", wrapperModel);
}
public ActionResult DisplayUpdateBox(int id)
{
ViewBag.Update = 2;
wrapperModel.movie = mvcEntity.Movies.Find(id);
return View("Index", wrapperModel);
}
[HttpPost]
public ActionResult UpdateDetails(Movie movie)
{
if(ModelState.IsValid)
{
mvcEntity.Entry(movie).State = EntityState.Modified;
mvcEntity.SaveChanges();
}
return View("Index", DataHandler.WrapperMethod());
}
public ActionResult AddMovie()
{
return View();
}
[HttpPost]
public ActionResult AddMovie(Movie movie)
{
if(ModelState.IsValid)
{
mvcEntity.Movies.Add(movie);
mvcEntity.SaveChanges();
return RedirectToAction("ShowMovies");
}
return View(movie);
}
public ActionResult Delete(int id)
{
ViewBag.Update = 3;
wrapperModel.movie = mvcEntity.Movies.Find(id);
return View("Index", wrapperModel);
}
public ActionResult DeleteMovie(int id)
{
using (var mvc = new MVCApplicationEntities())
{
mvc.Movies.Remove(mvc.Movies.Find(id));
mvc.SaveChanges();
}
return RedirectToAction("ShowMovies");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameMenu : MonoBehaviour
{
private SaveGameManager saveManager;
public static Text scoreTxt;
public static Text timeTxt;
public bool saved = false;
private static GameObject instance;
// Start is called before the first frame update
void Start()
{
saveManager = gameObject.GetComponent<SaveGameManager>();
scoreTxt = GameObject.Find("HighScoreText").GetComponent<Text>();
timeTxt = GameObject.Find("BestTimeText").GetComponent<Text>();
}
void Awake()
{
DontDestroyOnLoad(gameObject);
if (instance == null)
{
instance = gameObject;
}
else DestroyImmediate(gameObject, true);
if (saved)
{
saveManager.LoadScore();
saveManager.LoadTime();
}
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ScriptableObjectFramework.Sets
{
public abstract class SetRegisterer<T, Y> : MonoBehaviour
where Y : IRuntimeSet<T>
{
[SerializeField]
protected List<Y> Sets;
protected abstract void OnEnable();
protected abstract void OnDisable();
}
}
|
using LocusNew.Core;
using LocusNew.Core.Models;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
namespace LocusNew.Areas.Admin.Controllers.ApiControllers
{
[Authorize]
public class CityPartsController : ApiController
{
private readonly IUnitOfWork _unitOfWork;
public CityPartsController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IQueryable<CityPart> GetCityParts()
{
return _unitOfWork.CityParts.GetCityParts();
}
[ResponseType(typeof(CityPart))]
public IHttpActionResult GetCityPart(int id)
{
CityPart cityPart = _unitOfWork.CityParts.GetCityPart(id);
if (cityPart == null)
{
return NotFound();
}
return Ok(cityPart);
}
[ResponseType(typeof(CityPart))]
public IHttpActionResult AddNewCityPart(CityPart cityPart)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_unitOfWork.CityParts.AddCityPart(cityPart);
_unitOfWork.Complete();
return CreatedAtRoute("DefaultApi", new { id = cityPart.Id }, cityPart);
}
[HttpPost]
public IHttpActionResult DeleteCityPart(int id)
{
if (!_unitOfWork.CityParts.RemoveCityPart(id))
{
return BadRequest();
}
_unitOfWork.Complete();
return Ok();
}
}
} |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace VoxelSpace {
public class VoxelType {
public string Identifier { get; private set; }
public bool IsSolid { get; private set; }
public bool IsOpaque { get; private set; } // temporary. will change when we add transparency
public VoxelFaceMode FaceMode { get; private set; }
public VoxelInitialDataMode InitialDataMode { get; private set; }
public byte? PointLightLevel { get; private set; }
public IVoxelSkin Skin { get; private set; }
public UI.VoxelIconMesh VoxelIconMesh { get; private set; }
public VoxelType(string id, bool isSolid, bool isOpaque, IVoxelSkin skin, VoxelFaceMode faceMode, VoxelInitialDataMode initialDataMode, byte? pointLightLevel = null) {
Identifier = id;
Skin = skin;
IsSolid = isSolid;
IsOpaque = isOpaque;
FaceMode = faceMode;
InitialDataMode = initialDataMode;
PointLightLevel = pointLightLevel;
}
public void CreateVoxelIconMesh(UI.VoxelIconMaterial material) {
var voxel = new Voxel(this);
switch (InitialDataMode) {
case VoxelInitialDataMode.None:
voxel.Data = 0;
break;
case VoxelInitialDataMode.NormalOrientation:
voxel.Data = (ushort) Orientation.Yp;
break;
}
VoxelIconMesh = new UI.VoxelIconMesh(voxel, material);
}
public bool CanCreateFace(VoxelType neighbor) {
if (neighbor == null) {
return true;
}
else {
switch (FaceMode) {
case VoxelFaceMode.Transparent:
return neighbor.FaceMode != VoxelFaceMode.Opaque && neighbor != this;
case VoxelFaceMode.Opaque:
case VoxelFaceMode.TransparentInner:
return neighbor.FaceMode != VoxelFaceMode.Opaque;
default:
return false;
}
}
}
public Voxel CreateVoxel(VoxelRaycastResult result) {
ushort data = 0;
switch (InitialDataMode) {
case VoxelInitialDataMode.None:
break;
case VoxelInitialDataMode.NormalOrientation:
data = (ushort) result.Normal.ToOrientation();
break;
}
return new Voxel(this, data);
}
}
public enum VoxelFaceMode {
Opaque,
Transparent,
TransparentInner
}
public enum VoxelInitialDataMode {
None,
NormalOrientation
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArizaTakipYazılımSistemi.Model
{
class Bolum
{
public int bolum_id { get; set; }
public string bolum { get; set; }
}
}
|
namespace Selenio.HtmlReporter
{
public class TestExecutionOutcome
{
public string Message { get; set; }
public bool Passed { get; set; }
}
}
|
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class Program
{
public static int Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Usage: ActivateStoreApp <AppUserModelId>");
return 1;
}
ApplicationActivationManager appActiveManager = new ApplicationActivationManager();
uint pid;
appActiveManager.ActivateApplication(args[0], null, ActivateOptions.None, out pid);
Console.WriteLine("Process ID: {0}", pid);
return 0;
}
}
public enum ActivateOptions
{
None = 0x00000000,
DesignMode = 0x00000001,
NoErrorUI = 0x00000002,
NoSplashScreen = 0x00000004,
}
[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IApplicationActivationManager
{
IntPtr ActivateApplication([In] String appUserModelId,
[In] String arguments,
[In] ActivateOptions options,
[Out] out UInt32 processId);
IntPtr ActivateForFile([In] String appUserModelId,
[In] IntPtr /*IShellItemArray* */ itemArray,
[In] String verb,
[Out] out UInt32 processId);
IntPtr ActivateForProtocol([In] String appUserModelId,
[In] IntPtr /* IShellItemArray* */itemArray,
[Out] out UInt32 processId);
}
[ComImport, Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")]
//Application Activation Manager
internal class ApplicationActivationManager : IApplicationActivationManager
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType =
MethodCodeType.Runtime)/*, PreserveSig*/]
public extern IntPtr ActivateApplication(
[In] String appUserModelId,
[In] String arguments,
[In] ActivateOptions options,
[Out] out UInt32 processId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType =
MethodCodeType.Runtime)]
public extern IntPtr ActivateForFile(
[In] String appUserModelId,
[In] IntPtr /*IShellItemArray* */itemArray,
[In] String verb,
[Out] out UInt32 processId);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType =
MethodCodeType.Runtime)]
public extern IntPtr ActivateForProtocol(
[In] String appUserModelId,
[In] IntPtr /* IShellItemArray* */itemArray,
[Out] out UInt32 processId);
} |
/* 作者: 盛世海
* 创建时间: 2012/7/25 10:32:21
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MODEL.ActionModel
{
/// <summary>
/// 控制器
/// </summary>
public class MVCController
{
/// <summary>
/// 控制器
/// </summary>
public string ControllerName { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 链接地址
/// </summary>
public string LinkUrl { get; set; }
}
}
|
//-----------------------------------------------------------------------
// <copyright file="DomainPrincipal.cs" company="<%= company %>">
// <%= copyrigthDate %>. All rights reserved.
// </copyright>
// <author>Adventiel</author>
//-----------------------------------------------------------------------
namespace <%= domainProjectName %>.Security
{
using System;
using System.Collections.Generic;
using System.Security.Principal;
/// <summary>
/// classe représentant un objet
/// </summary>
[Serializable]
public class DomainPrincipal : IPrincipal
{
/// <summary>
/// initialise une nouvelle intance de la classe
/// </summary>
public DomainPrincipal()
{
Identity = new DomainIdentity();
Profiles = new List<string>();
}
/// <summary>
/// identité
/// </summary>
public IIdentity Identity
{
get;
set;
}
/// <summary>
/// retourne vrai si il est dans le rôle
/// </summary>
/// <param name="role"></param>
/// <returns></returns>
public bool IsInRole(string role)
{
if (Profiles!=null && !string.IsNullOrWhiteSpace(role))
{
return Profiles.Contains(role);
}
return false;
}
/// <summary>
/// liste des profils
/// </summary>
public List<string> Profiles
{
get;
set;
}
/// <summary>
/// date d'expiration
/// </summary>
public DateTime ExpirationDate
{
get;
set;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_recibeAtaques : MonoBehaviour
{
private Player_Ataques scriptAtaques;
public bool siendoChidoriado;
private string nombreAnimacionActual;
private bool PlayerLockeado;
public GameObject PlayerMeTaPegando;
public float clock;
public float tiempoEspera = 0.1f;
public float TiempoRigidDinamic, contadorChidoriPostPiña, tamañoParticulasPostPiña;
private ParticleSystem ps;
void Start()
{
scriptAtaques = this.gameObject.GetComponent<Player_Ataques>(); //referencia al script de ataques.
PlayerLockeado = false;
siendoChidoriado = false;
clock = tiempoEspera;
}
void Update()
{
if (siendoChidoriado)
{
this.gameObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
Invoke("CancelarChidori", contadorChidoriPostPiña);
Invoke("PonerRigidbodyEnDynamic", TiempoRigidDinamic);
PlayerMeTaPegando.GetComponent<Animator>().SetTrigger("chidori_HIT");
this.gameObject.GetComponent<Animator>().SetTrigger("chidori_HITED");
siendoChidoriado = false;
}
if (this.gameObject.GetComponent<Player_Ataques>().nombreAnimacionActual == "Player_chidori_HITED")
this.gameObject.GetComponent<Animator>().ResetTrigger("chidori_HITED");
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.transform.root != null)
{
if (col.transform.root.tag == "Player")
{
//esto es si recive el ataque del chidori de otro Player.
if (col.transform.root.GetComponent<Player_Ataques>().doingChidori == true && col.transform.root.GetComponent<Player_Ataques>().contadorChidori <= 5 && scriptAtaques.doingChidori == false && scriptAtaques.doingEscudo == false && siendoChidoriado == false)
{
PlayerMeTaPegando = col.transform.root.gameObject;
siendoChidoriado = true;
//agrando el tamaño del efecto del chidori.
ps = GameObject.Find(PlayerMeTaPegando.name + "_ParticulasChidori").GetComponent<ParticleSystem>();
var main = ps.main;
main.startSize = tamañoParticulasPostPiña;
//le hago dropear el arma al que le pegan.
if (this.gameObject.transform.Find("ManejadorArmas").GetComponent<ManejadorArmas_controller>().ArmaActual != null)
this.gameObject.transform.Find("ManejadorArmas").GetComponent<ManejadorArmas_controller>().SueltaArma();
}
}
}
}
void OnCollisionExit2D(Collision2D col)
{
if (col.transform.root != null)
{
if (col.transform.root.tag == "Player" && siendoChidoriado)
{
if (col.transform.root.name == PlayerMeTaPegando.name)
{
siendoChidoriado = false;
PlayerMeTaPegando = null;
}
}
}
}
private void PonerRigidbodyEnDynamic() // ESTO METODO SOLO DEBE SER INVOCADO PARA TERMINAR LA ANIMACION DEL GOLPE DEL CHIDORI. PARA NADA MAS.
{
//pongo el rigidbody en Dynamic.
this.gameObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
}
private void CancelarChidori()
{
//le cancelo el chidori
PlayerMeTaPegando.GetComponent<Player_Ataques>().contadorChidori = contadorChidoriPostPiña;
PlayerMeTaPegando.GetComponent<Player_Ataques>().doingChidori = false;
if (GameObject.Find(PlayerMeTaPegando.name + "_Chidori") != null)
Destroy(GameObject.Find(PlayerMeTaPegando.name + "_Chidori"));
//reseteo los triggers.
PlayerMeTaPegando.GetComponent<Animator>().ResetTrigger("chidori_HIT");
this.gameObject.GetComponent<Animator>().ResetTrigger("chidori_HITED");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Console_Interactiable : MonoBehaviour {
float stopWatch, timeLimit;
[HideInInspector]public bool bIsBeingSabatoged = false;
public GameObject radialProgressBar, interactiableIndicator;
ObjectiveSystem _objectiveSystem;
Toggle myGoaldisplay;
// Use this for initialization
void Start() {
HelloAngel();
stopWatch = 0f;
//find the objective manager
_objectiveSystem = FindObjectOfType<ObjectiveSystem>();
foreach (Toggle goal in _objectiveSystem.objectiveDisplay) {
if (goal.GetComponentInChildren<Text>().text == "Stop Disir for Regenerating.") {
myGoaldisplay = goal;
}
}
gameObject.SetActive(false);//turn this object off
}
// Update is called once per frame
void Update() {
if (stopWatch >= timeLimit && bIsBeingSabatoged) {
ForcePlayerSwitch();
interactiableIndicator.SetActive(false);
gameObject.SetActive(false);
}
//tick up the timer while its being worked on.
else if (bIsBeingSabatoged && stopWatch < timeLimit) {
stopWatch += Time.deltaTime;
//math to convert to a precentage
float percentamount = stopWatch / timeLimit;
// print("precent Done: " + percentamount);
//Grab any of the images children
Image[] childImages = radialProgressBar.GetComponentsInChildren<Image>();
//run through and find the ones with a image type of filled
for (int x = 0; x < childImages.Length; x++) {
if(childImages[x].type == Image.Type.Filled)
//print("found:" + childImages[x].name);
//Assign the amount to their fill amount
childImages[x].GetComponent<Image>().fillAmount = percentamount; }
}
}
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player")) {
// print("YO playa");
//if your playing as wolf
if (FindObjectOfType<SwitchCharacters>().charNum == 0) {
interactiableIndicator.SetActive(true);
// print("Push the button");
if (Input.GetKeyDown(KeyCode.F)) {
workTime();
interactiableIndicator.SetActive(false);
}
}
//otherwise if your playing as sondra
else if (FindObjectOfType<SwitchCharacters>().charNum == 1) { print("Not wolf"); }
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player")) interactiableIndicator.SetActive(false);
}
void HelloAngel() {
//If the angel Ai is not found in the scene send out an error and puase the editor.
if (FindObjectOfType<Angel_AI>() == null) { Debug.LogError("Angel_AI not found " + name); Debug.Break(); }
Angel_AI my_Boss = FindObjectOfType<Angel_AI>();
my_Boss._consoles.Add(this.GetComponent<Console_Interactiable>());//Regester with the boss
timeLimit = my_Boss.regenTimeAmount; //Get the amount of time needed to disable the console and store it.
}
void ForcePlayerSwitch() {
//switch the player to wolf and the players ability to switch.
SwitchCharacters _charChanger = FindObjectOfType<SwitchCharacters>();
_charChanger.CharacterLock = !_charChanger.CharacterLock; //Toggle the lock.
// print("Boot");
_charChanger.ChangeCharacters(); //Switch the characters.
}
private void OnDisable()
{
radialProgressBar.SetActive(false); //Turn off the display
bIsBeingSabatoged = false;
interactiableIndicator.SetActive(false);
//If you know what your objective display text/Toggle is
if (myGoaldisplay != null) myGoaldisplay.gameObject.SetActive(false); //Turn off the displayed text objective
//clean the progress bar fill
Image[] childImages = radialProgressBar.GetComponentsInChildren<Image>();
//run through and find the ones with a image type of filled
for (int x = 0; x < childImages.Length; x++)
{
if (childImages[x].type == Image.Type.Filled)
//print("found:" + childImages[x].name);
//Assign the amount to their fill amount
childImages[x].GetComponent<Image>().fillAmount = 0f;
}
}
private void OnEnable()
{
//If you know what your objective display text/Toggle is
if(myGoaldisplay != null)
myGoaldisplay.gameObject.SetActive(true); //Turn on the objective text display
stopWatch = 0f;
}
void workTime() {
ForcePlayerSwitch();
//Disable wolf's AI
if (FindObjectOfType<WolfAI>() != null) FindObjectOfType<WolfAI>().enabled = false;
if (FindObjectOfType<WolfAI2>() != null) FindObjectOfType<WolfAI2>().enabled = false;
if (FindObjectOfType<WolfAI3>() != null) FindObjectOfType<WolfAI3>().enabled = false;
bIsBeingSabatoged = true;
radialProgressBar.SetActive(true); //Turn on the display
interactiableIndicator.SetActive(false);
}
}
|
using System.Collections.Generic;
namespace Quark.Utilities
{
class KeyBindings
{
static List<IBinding> bindings = new List<IBinding>();
public static void AddBinding(IBinding binding)
{
bindings.Add(binding);
}
public static void Register()
{
Messenger.AddListener("Update", Update);
}
static void Update()
{
foreach (IBinding binding in bindings)
binding.Check();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;
namespace Engine.SkinnedModel
{
[Serializable]
[DataContract]
public class AnimationClipKeyFrameInterpolator
{
// Map between timing data and bone indexes for interpolation
[DataMember] private static TimeSpanComparer TimeSpanComp = new TimeSpanComparer();
[DataMember] private Dictionary<int, List<Keyframe>> KeyFrameTimes = new Dictionary<int, List<Keyframe>>();
public AnimationClipKeyFrameInterpolator(AnimationClip clip)
{
KeyFrameTimes.Clear();
//Map bones to times
foreach (Keyframe kf in clip.Keyframes)
{
if (!KeyFrameTimes.ContainsKey(kf.Bone))
KeyFrameTimes[kf.Bone] = new List<Keyframe>();
KeyFrameTimes[kf.Bone].Add(kf);
}
//Sort them
foreach (var kvp in KeyFrameTimes)
kvp.Value.Sort(TimeSpanComp);
}
public Keyframe InterpolateKeyFrame(Keyframe frame, TimeSpan timeValue)
{
Keyframe next = GetPreviousForBone(frame);
if (next == frame)
return frame;
var startMs = (float) frame.Time.TotalMilliseconds;
var currentMs = (float) timeValue.TotalMilliseconds;
var endMs = (float) next.Time.TotalMilliseconds;
float amount = (currentMs - startMs)/(endMs - startMs);
//Don't bother if the amount is too low
if (amount < 0.0001f) return frame;
Matrix interpolatedMatrix = Matrix.Lerp(frame.Transform, next.Transform, amount);
var kf = new Keyframe(frame.Bone, timeValue, interpolatedMatrix);
return kf;
}
private Keyframe GetPreviousForBone(Keyframe frame)
{
for (int i = 0, j = KeyFrameTimes[frame.Bone].Count; i < j; i++)
{
Keyframe kf = KeyFrameTimes[frame.Bone][i];
if (kf == frame)
{
if (i > 0)
{
return KeyFrameTimes[frame.Bone][i - 1]; //previous
}
return KeyFrameTimes[frame.Bone][j - 1]; //last
}
}
//Couldn't find it...strange
return frame;
}
internal List<Keyframe> GetInterpolatedKeyFrames(TimeSpan currentTimeValue)
{
var kframes = new List<Keyframe>();
foreach (var kvp in KeyFrameTimes)
{
foreach (Keyframe kf in kvp.Value)
{
//bool foundFrame = false;
if (kf.Time >= currentTimeValue)
{
kframes.Add(InterpolateKeyFrame(kf, currentTimeValue));
//foundFrame = true;
break;
}
}
}
return kframes;
}
}
internal class TimeSpanComparer : IComparer<Keyframe>
{
#region IComparer<Keyframe> Members
public int Compare(Keyframe x, Keyframe y)
{
return (int) (x.Time.TotalMilliseconds - y.Time.TotalMilliseconds);
}
#endregion
}
} |
using Client.Bussness;
using MahApps.Metro.Controls.Dialogs;
using Meeting.NewClient.UI;
using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
namespace WPF.NewClientl.UI.Dialogs
{
public partial class MultiMediaDialog : UserControl
{
public MultiMediaDialog()
{
InitializeComponent();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
this.Player.SourceProvider.CreatePlayer(libDirectory/* pass your player parameters here */);
this.Player.SourceProvider.MediaPlayer.Play(new Uri(AppClientContext.Context.Meeting.FlashPath));
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
FullScreen.Visibility = Visibility.Visible;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ReturnButton : MonoBehaviour
{
[SerializeField] GameObject parentPanel;
void Awake()
{
var btn = GetComponent<Button>();
btn.onClick.AddListener(ReturnAndClose);
}
private void ReturnAndClose()
{
parentPanel.SetActive(false);
}
}
|
using UnityEngine;
using System.Collections;
public class BigShot : Shot {
public float damage;
public float maxDamage = 60f;
void Start()
{
damage = 0f;
}
public override void Damage()
{
base.Damage();
currentTarget.TakeDamage(damage);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class PlayerNameHandler : NetworkBehaviour
{
public GameObject nameController;
public GameObject nameText;
public string storedName;
[SyncVar]
public string playerName;
[Command]
public void CmdChangeName(string newName)
{
playerName = newName;
}
void Start()
{
if (isLocalPlayer)
{
nameController = GameObject.Find("NameManager");
storedName = nameController.GetComponent<StartGame>().passedName;
CmdChangeName(storedName);
}
}
void Update()
{
if (nameText.GetComponent<TextMesh>().text != playerName)
{
nameText.GetComponent<TextMesh>().text = playerName;
}
}
} |
using System;
using System.Reflection;
using Autofac;
using Framework.Core;
using NUnit.Framework;
namespace Tests
{
public abstract class BaseTest : AssertionHelper
{
private readonly IContainer _container;
protected ILifetimeScope Scope { get; private set; }
protected BaseTest()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterModule<CoreModule>();
containerBuilder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(BaseTest)));
_container = containerBuilder.Build();
}
protected virtual void Setup() { }
protected virtual void TearDown() { }
[SetUp]
public void SetupBase()
{
Scope = _container.BeginLifetimeScope();
Setup();
}
[TearDown]
public void TearDownBase()
{
TearDown();
Scope.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Week4.ZoekertjesApp.DataAccess;
using Week4.ZoekertjesApp.Models;
using ZoekertjesModels;
namespace Week4.ZoekertjesApp.Controllers
{
public class ZoekertjesAPIController : ApiController
{
public List<Zoekertje> Get()
{
List<Zoekertje> zoekertjes = Data.GetZoekertjes();
return zoekertjes;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WPF_ListView_INPC_Command
{
public class MainWindowModel
{
public string Title { get { return "ListView - App"; } }
int iPages = 1;
public ObservableCollection<Book> Books { get; private set; }
public MainWindowModel()
{
Books = new ObservableCollection<Book>
{
new Book{Title = "Qwerty", Pages = 100 },
new Book{Title = "Asdf", Pages = 200 }
};
}
private ICommand changeCommand;
public ICommand ChangeCommand
{
get
{
return changeCommand ?? (changeCommand = new RelayCommand( obj =>
{
Books.Add(new Book { Title = "Zzz", Pages = iPages });
++iPages;
++Books.First().Pages;
}
));
}
}
}
}
|
using System;
namespace Hangman
{
//simple Hangman game. you lose a point for every character in the user input that is incorrect.
// you lose when you reach 6 mistakes
class Program
{
static void SkipLines(int lines) // a function to jump however many lines i need.
{
for (int i = 0; i < lines; i++)
{
Console.WriteLine();
}
}
static void Game()
{
Console.Clear();
int tries = 0; // 6 tries is the limit
string[] samples = { "archeologist", "mathematics", "science", "video games", "computer", "central processing unit" }; // pre-made words
string word = ""; // the word that has to be guessed
string guessedLetters = ""; // keep guessed letters in a string so we can separate them later
Random random = new Random(); // instantiate random
string ReturnCommonCharacters(string target, string guess) // returns how many characters in string "guess" are in common with characters in string "target"
{
string lettersFound = ""; // string of correct characters
foreach (char x in guess)
{
if (target.Contains(x))
{
lettersFound += x; // if the character is correct then add it to "lettersFound"
}
else
{
tries++; // if the character is not found add to "tries"
if (tries >= 6)
{
break; // break the loop once 6 mistakes are reached. Restarts the game
}
}
}
return lettersFound;
}
Console.WriteLine("HANGMAN.");
SkipLines(5);
Console.WriteLine("Please input a word you would like to guess.");
Console.WriteLine("(enter 'S' to pick a random sample word)");
word = Console.ReadLine().ToLower(); // makes the input lowercase
if (word == "s")
{
int rand = random.Next(0, samples.Length);
word = samples[rand]; // get random word from the pre-made words list
}
string foundLetters = ""; // string of correctly guessed characters
bool completed = true; // ugly hack (check line 94)
while (tries < 6) // game loop
{
char[] wordTable = word.ToCharArray(); // where we keep the underscores(_) and actual characters together.
Console.WriteLine("Guess the word!");
guessedLetters = Console.ReadLine();
foundLetters += ReturnCommonCharacters(word, guessedLetters); // add correctly guessed characters to the 'foundLetters' string
completed = true; // ugly hack part 2
for (int i = 0; i < word.Length; i++)
{
if (foundLetters.Contains(word[i]))
{
wordTable[i] = word[i];
}
if (!foundLetters.Contains(word[i]))
{
if (word[i] == ' ') // if the word has a space, then use a space instead of an underscore
{
wordTable[i] = ' ';
}
else
{
completed = false; //ugly hack part 3
wordTable[i] = '_';
}
}
}
Console.WriteLine("Fails: " + tries.ToString());
SkipLines(2);
Console.WriteLine(wordTable);
if (completed == true) // wordTable.ToString()==word didn't work so that's why i did this.
{
Console.WriteLine("You guessed the word!");
break;
}
}
Console.ReadLine();
}
static void Main(string[] args)
{
while (true) // game loop
{
Game();
}
}
}
}
|
using System.Collections.Generic;
using Assets.Scripts.Models.ResourceObjects.CraftingResources;
using Assets.Scripts.Models.Weapons;
namespace Assets.Scripts.Models.Ammo
{
public class MachinegunAmmo : Ammo
{
public MachinegunAmmo()
{
WeaponType = typeof(Machinegun);
LocalizationName = "thompson_ammo";
Description = "thompson_ammo_descr";
IconName = "machinegun_bullet";
CraftAmount = 10;
Damage = 80;
CraftRecipe = new List<HolderObject>();
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Gunpowder), 2));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Metal), 3));
}
}
}
|
namespace TripDestination.Services.Data.Contracts
{
using System.Linq;
using TripDestination.Data.Models;
public interface IRatingServices
{
Rating GetById(int id);
IQueryable<Rating> GetAll();
Rating Edit(int id, int value);
void Delete(int id);
void RateUser(string userToRateId, string fromUserId, int rating, TripNotification tripNotification);
}
}
|
using System;
using System.Collections.Generic;
using Fingo.Auth.DbAccess.Models;
using Fingo.Auth.DbAccess.Models.CustomData;
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.CustomData.Tests.Factories.Actions.Implementation
{
public class GetAllCustomDataFromProjectTest
{
[Fact]
public void Cannot_Get_All_Custom_Data_From_Non_Existing_Project()
{
//Arrange
var projectRepositoryMock = new Mock<IProjectRepository>();
projectRepositoryMock.Setup(m => m.GetByIdWithCustomDatas(It.IsAny<int>())).Returns(() => null);
//Act
var target = new GetAllCustomDataFromProject(projectRepositoryMock.Object);
//Assert
var result = Assert.Throws<Exception>(() => target.Invoke(1));
Assert.True(result.Message.Contains("Could not find project with ID:"));
}
[Fact]
public void Cannot_Get_All_Custom_Data_From_Project()
{
//Arrange
var projectRepositoryMock = new Mock<IProjectRepository>();
projectRepositoryMock.Setup(m => m.GetByIdWithCustomDatas(It.IsAny<int>()))
.Returns(new Project
{
ProjectCustomData = new List<ProjectCustomData>
{
new ProjectCustomData() ,
new ProjectCustomData()
}
});
//Act
var target = new GetAllCustomDataFromProject(projectRepositoryMock.Object);
var result = target.Invoke(1);
//Assert
Assert.True(result.Count == 2);
}
}
} |
using BLL.Dto;
using BLL.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MoneyTracker.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ExpenseController : ControllerBase
{
private readonly IUserService _userService;
private readonly IExpenseService _expenseService;
public ExpenseController(IUserService userService, IExpenseService expenseService)
{
_userService = userService;
_expenseService = expenseService;
}
[HttpGet("/api/Expense/notChecked")]
[Authorize]
public async Task<IEnumerable<ExpenseDto>> GetNotCheckedExpenses()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var notCheckedExpenses = await _expenseService.GetNotChackedExpensesAsync(userId);
return notCheckedExpenses;
}
[HttpPost]
[Authorize]
public async Task<IActionResult> AddExpense(ExpenseDto expense)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _expenseService.AddExpense(userId, expense);
return Ok();
}
[HttpGet("/api/Expense/History")]
[Authorize]
public IEnumerable<ExpenseDto> GetChechedExpenseHistory()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var expenseHistory = _expenseService.GetExpenseHistory(userId);
return expenseHistory;
}
[HttpGet("/api/Expense/Statistics")]
[Authorize]
public IEnumerable<Statistic> GetStatistics()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var statistics = _expenseService.GetStatistics(userId);
return statistics;
}
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Metadata;
using gView.Framework.Geometry;
using gView.Framework.IO;
using gView.Framework.XML;
using gView.MapServer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
namespace gView.Interoperability.ArcXML.Dataset
{
[gView.Framework.system.RegisterPlugIn("3B26682C-BF6E-4fe8-BE80-762260ABA581")]
public class ArcIMSDataset : DatasetMetadata, IFeatureDataset, IRequestDependentDataset
{
internal string _connection = "";
internal string _name = "";
internal List<IWebServiceTheme> _themes = new List<IWebServiceTheme>();
private IClass _class = null;
private IEnvelope _envelope;
private string _errMsg = "";
internal ArcXMLProperties _properties = new ArcXMLProperties();
//internal dotNETConnector _connector = null;
private DatasetState _state = DatasetState.unknown;
private ISpatialReference _sRef = null;
public ArcIMSDataset() { }
public ArcIMSDataset(string connection, string name)
{
_connection = connection;
_name = name;
_class = new ArcIMSClass(this);
}
internal ArcIMSClass WebServiceClass
{
get { return _class as ArcIMSClass; }
}
public XmlDocument Properties
{
get { return _properties.Properties; }
}
#region IFeatureDataset Member
public Task<IEnvelope> Envelope()
{
return Task.FromResult<IEnvelope>(_envelope);
}
public Task<ISpatialReference> GetSpatialReference()
{
return Task.FromResult(_sRef);
}
public void SetSpatialReference(ISpatialReference sRef)
{
_sRef = sRef;
}
#endregion
#region IDataset Member
public void Dispose()
{
_state = DatasetState.unknown;
}
public string ConnectionString
{
get
{
return _connection + ";service=" + _name;
}
}
public Task<bool> SetConnectionString(string value)
{
_connection = "server=" + ConfigTextStream.ExtractValue(value, "server") +
";user=" + ConfigTextStream.ExtractValue(value, "user") +
";pwd=" + ConfigTextStream.ExtractValue(value, "pwd");
_name = ConfigTextStream.ExtractValue(value, "service");
return Task.FromResult(true);
}
public string DatasetGroupName
{
get { return "ESRI ArcIMS"; }
}
public string DatasetName
{
get { return "ESRI ArcIMS Service"; }
}
public string ProviderName
{
get { return "ESRI"; }
}
public DatasetState State
{
get { return _state; }
}
async public Task<bool> Open()
{
return await Open(null);
}
public string LastErrorMessage
{
get { return _errMsg; }
set { _errMsg = value; }
}
public int order
{
get
{
return 0;
}
set
{
}
}
public IDatasetEnum DatasetEnum
{
get { return null; }
}
public Task<List<IDatasetElement>> Elements()
{
List<IDatasetElement> elements = new List<IDatasetElement>();
if (_class != null)
{
elements.Add(new DatasetElement(_class));
}
return Task.FromResult<List<IDatasetElement>>(elements);
}
public string Query_FieldPrefix
{
get { return ""; }
}
public string Query_FieldPostfix
{
get { return ""; }
}
public gView.Framework.FDB.IDatabase Database
{
get { return null; }
}
public Task<IDatasetElement> Element(string title)
{
if (_class != null && title == _class.Name)
{
return Task.FromResult<IDatasetElement>(new DatasetElement(_class));
}
return Task.FromResult<IDatasetElement>(null);
}
public Task RefreshClasses()
{
return Task.CompletedTask;
}
#endregion
#region IRequestDependentDataset Member
async public Task<bool> Open(IServiceRequestContext context)
{
if (_class == null)
{
_class = new ArcIMSClass(this);
}
string server = ConfigTextStream.ExtractValue(ConnectionString, "server");
string service = ConfigTextStream.ExtractValue(ConnectionString, "service");
string user = ConfigTextStream.ExtractValue(ConnectionString, "user");
string pwd = ConfigTextStream.ExtractValue(ConnectionString, "pwd");
//if ((user == "#" || user == "$") &&
// context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null)
//{
// string roles = String.Empty;
// if (user == "#" && context.ServiceRequest.Identity.UserRoles != null)
// {
// foreach (string role in context.ServiceRequest.Identity.UserRoles)
// {
// if (String.IsNullOrEmpty(role)) continue;
// roles += "|" + role;
// }
// }
// user = context.ServiceRequest.Identity.UserName + roles;
// pwd = context.ServiceRequest.Identity.HashedPassword;
//}
dotNETConnector connector = new dotNETConnector();
if (!String.IsNullOrEmpty(user) || !String.IsNullOrEmpty(pwd))
{
connector.setAuthentification(user, pwd);
}
try
{
_themes.Clear();
string axl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO fields=\"true\" envelope=\"true\" renderer=\"true\" extensions=\"true\" /></REQUEST></ARCXML>";
//string axl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO dpi=\"96\" toc=\"true\" /></REQUEST></ARCXML>";
await ArcIMSClass.LogAsync(context, "GetServiceInfo Response", server, service, axl);
axl = connector.SendRequest(axl, server, service);
await ArcIMSClass.LogAsync(context, "GetServiceInfo Response", server, service, axl);
XmlDocument doc = new XmlDocument();
doc.LoadXml(axl);
double dpi = 96.0;
XmlNode screen = doc.SelectSingleNode("//ENVIRONMENT/SCREEN");
if (screen != null)
{
if (screen.Attributes["dpi"] != null)
{
dpi = Convert.ToDouble(screen.Attributes["dpi"].Value.Replace(".", ","));
}
}
double dpm = (dpi / 0.0254);
XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
_sRef = ArcXMLGeometry.AXL2SpatialReference(FeatureCoordSysNode);
foreach (XmlNode envelopeNode in doc.SelectNodes("//ENVELOPE"))
{
if (_envelope == null)
{
_envelope = new Envelope(envelopeNode);
}
else
{
_envelope.Union(new Envelope(envelopeNode));
}
}
foreach (XmlNode layerNode in doc.SelectNodes("//LAYERINFO[@id]"))
{
bool visible = true;
if (layerNode.Attributes["visible"] != null)
{
bool.TryParse(layerNode.Attributes["visible"].Value, out visible);
}
XmlNode tocNode = layerNode.SelectSingleNode("TOC");
if (tocNode != null)
{
ReadTocNode(tocNode);
}
IClass themeClass = null;
IWebServiceTheme theme;
if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "featureclass")
{
themeClass = await ArcIMSThemeFeatureClass.CreateAsync(this, layerNode.Attributes["id"].Value);
((ArcIMSThemeFeatureClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
((ArcIMSThemeFeatureClass)themeClass).fieldsFromAXL = layerNode.InnerXml;
((ArcIMSThemeFeatureClass)themeClass).SpatialReference = _sRef;
XmlNode FCLASS = layerNode.SelectSingleNode("FCLASS[@type]");
if (FCLASS != null)
{
((ArcIMSThemeFeatureClass)themeClass).fClassTypeString = FCLASS.Attributes["type"].Value;
}
foreach (XmlNode child in layerNode.ChildNodes)
{
switch (child.Name)
{
case "SIMPLERENDERER":
case "SIMPLELABELRENDERER":
case "VALUEMAPRENDERER":
case "SCALEDEPENDENTRENDERER":
case "VALUEMAPLABELRENDERER":
case "GROUPRENDERER":
((ArcIMSThemeFeatureClass)themeClass).OriginalRendererNode = child;
break;
}
}
theme = LayerFactory.Create(themeClass, _class as IWebServiceClass) as IWebServiceTheme;
if (theme == null)
{
continue;
}
theme.Visible = visible;
}
else if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "image")
{
//themeClass = new ArcIMSThemeRasterClass(this,
// layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value);
themeClass = new ArcIMSThemeRasterClass(this, layerNode.Attributes["id"].Value);
((ArcIMSThemeRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
theme = new WebServiceTheme(
themeClass,
themeClass.Name,
layerNode.Attributes["id"].Value,
visible,
_class as IWebServiceClass);
}
else
{
continue;
}
try
{
if (layerNode.Attributes["minscale"] != null)
{
theme.MinimumScale = Convert.ToDouble(layerNode.Attributes["minscale"].Value.Replace(".", ",")) * dpm;
}
if (layerNode.Attributes["maxscale"] != null)
{
theme.MaximumScale = Convert.ToDouble(layerNode.Attributes["maxscale"].Value.Replace(".", ",")) * dpm;
}
}
catch { }
_themes.Add(theme);
}
_state = DatasetState.opened;
((ArcIMSClass)_class).SpatialReference = await this.GetSpatialReference();
return true;
}
catch (Exception ex)
{
_state = DatasetState.unknown;
_errMsg = ex.Message;
await ArcIMSClass.ErrorLog(context, "Open Dataset", server, service, ex);
return false;
}
}
#endregion
#region IPersistableAsync Member
async public Task<bool> LoadAsync(IPersistStream stream)
{
await this.SetConnectionString((string)stream.Load("ConnectionString", ""));
_properties = stream.Load("Properties", new ArcXMLProperties(), new ArcXMLProperties()) as ArcXMLProperties;
_class = new ArcIMSClass(this);
return await Open();
}
public void Save(IPersistStream stream)
{
stream.Save("ConnectionString", this.ConnectionString);
stream.Save("Properties", _properties);
}
#endregion
#region Helper
private void ReadTocNode(XmlNode tocNode)
{
foreach (XmlNode tocclass in tocNode.SelectNodes("TOCGROUP/TOCCLASS"))
{
try
{
MemoryStream ms = new MemoryStream();
byte[] imgBytes = Convert.FromBase64String(tocclass.InnerText);
ms.Write(imgBytes, 0, imgBytes.Length);
ms.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
image.Dispose();
}
catch { }
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.App.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Welic.App.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginExternoPage : ContentPage
{
public LoginExternoPage ()
{
InitializeComponent ();
BindingContext = new LoginExternoViewModel();
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace Genesys.WebServicesClient.Components.Test
{
[TestClass]
public class SamplesTest
{
[TestMethod]
public async Task get_contacts()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var connection = new GenesysConnection()
{
ServerUri = Configuration.ServerUri,
UserName = Configuration.UserName,
Password = Configuration.Password,
WebSocketsEnabled = false,
};
await connection.StartAsync();
var response = await connection.InternalClient.CreateRequest("GET", "/api/v2/contacts").SendAsync();
Debug.WriteLine(response.AsString);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using CompiledValidators.Tests.Infrastructure;
using NUnit.Framework;
namespace CompiledValidators.Tests
{
[TestFixture]
public class SimpleValidationTests
{
private Validator _sut;
[TestFixtureSetUp]
public void SetUp()
{
_sut = new Validator(true, new UserAssemblyRecursionPolicy(), new AttributeValidatorProvider(), new ValidationExpressionConverter());
}
[Test]
public void NullIsInvalid()
{
Assert.IsFalse(_sut.IsValid<object>(null));
}
[Test]
public void NullReturnsRootInvalidError()
{
Assert.AreEqual(Validator.RootNullValidationError, _sut.ValidateToFirstError<object>(null).Single());
}
[Test]
public void EmptyTypesAreValid()
{
Assert.IsTrue(_sut.IsValid(new EmptyClass()));
}
[Test]
public void TypeWithNoValidatorsAreValid()
{
Assert.IsTrue(_sut.IsValid(new NoValidatorsClass()));
}
[Test]
public void TypesWithOneInvalidFieldAreInvalid()
{
Assert.IsFalse(_sut.IsValid(new PartialValidClass()));
}
[Test]
public void TypesWithValidFieldsAreValid()
{
Assert.IsTrue(_sut.IsValid(new ValidClass()));
}
[Test]
public void TypeWithInvalidMmebersAreInvalid()
{
Assert.IsFalse(_sut.IsValid(new ValidClassWithInvalidMember()));
}
[Test]
public void TypeWithValidMembersAreValid()
{
Assert.IsTrue(_sut.IsValid(new ValidClassWithValidMember()));
}
[Test]
public void TypesWithEmptyMembersAreValid()
{
Assert.IsTrue(_sut.IsValid(new ValidClassWithEmptyMember()));
}
[Test]
public void TypesWithNullMembersAreValid()
{
Assert.IsTrue(_sut.IsValid(new ValidClassWithNullMember()));
}
[Test]
public void TypesWithValidMemberListsAreValid()
{
Assert.IsTrue(_sut.IsValid(new ValidClassWithValidMemberList()));
}
[Test]
public void TypeWithAnyInvalidMembersInMemberListAreInvalid()
{
Assert.IsFalse(_sut.IsValid(new ValidClassWithOneInvalidInMemberList()));
}
[Test]
public void SelfInvalidatingTypesAreInvalid()
{
Assert.IsFalse(_sut.IsValid(new InvalidEmptyType()));
}
[Test]
public void InvalidClassesWithPropertiesAreInvalid()
{
Assert.IsFalse(_sut.IsValid(new InvalidClassWithProperties()));
}
[Test]
public void FirstInvalidObjectIsReturned()
{
var obj = new ValidClassWithOneInvalidInMemberList();
Assert.AreSame(obj.Value2[0], _sut.ValidateToFirstError(obj).Single().Object);
}
[Test]
public void CorrectlyIdentifiesInvalidMember()
{
Assert.AreEqual("root.Value1", _sut.ValidateToFirstError(new PartialValidClass()).Single().MemberName);
}
[Test]
public void CorrectlyIdentifiesAllInvalidMembers()
{
var obj = new MultiInvalidClass();
var invalidMembers = new object[] { obj, obj.Value3[0], obj.Value4 };
var result = _sut.Validate(obj, false).Select(v => v.Object).ToArray();
Assert.AreEqual(invalidMembers.Length, result.Length);
for (int i = 0; i < result.Length; i++)
Assert.AreSame(result[i], invalidMembers[i]);
}
[Test]
public void IgnoresStaticFields()
{
Assert.IsTrue(_sut.IsValid(new ValidClassWithInvalidStaticMember()));
}
[Test]
public void ValidatesMultipleNullDepths()
{
Assert.IsFalse(_sut.Validate(new DeepNullClass(), false).Any());
}
public class EmptyClass
{
}
public class ValidClassWithInvalidStaticMember : ValidClass
{
[Invalid]
public static int Value2;
}
public class NoValidatorsClass
{
public int Value1;
}
public class PartialValidClass
{
[Invalid]
public int Value1;
[Valid]
public int Value2;
}
public class ValidClass
{
[Valid]
public int Value1;
}
public class ValidClassWithInvalidMember : ValidClass
{
public PartialValidClass Value2 = new PartialValidClass();
}
public class ValidClassWithValidMember : ValidClass
{
public ValidClass Value2 = new ValidClass();
}
public class ValidClassWithEmptyMember : ValidClass
{
public EmptyClass Value2 = new EmptyClass();
}
public class ValidClassWithNullMember : ValidClass
{
public PartialValidClass Value2;
}
public class ValidClassWithValidMemberList : ValidClass
{
public List<ValidClass> Value2 = new List<ValidClass>
{
new ValidClass(),
new ValidClass()
};
}
public class ValidClassWithOneInvalidInMemberList : ValidClass
{
public List<PartialValidClass> Value2 = new List<PartialValidClass>
{
new PartialValidClass()
};
}
public class MultiInvalidClass : PartialValidClass
{
public List<PartialValidClass> Value3 = new List<PartialValidClass>
{
new PartialValidClass()
};
public PartialValidClass Value4 = new PartialValidClass();
}
public class DeepNullClass
{
public Child1 Value1;
public Child1 Value2;
public class Child1
{
public Child2 Value1;
public class Child2
{
[Valid]
public int Value1;
}
}
}
[Invalid]
public class InvalidEmptyType
{
}
public class InvalidClassWithProperties
{
[Invalid]
public int Value1 { get; set; }
}
}
}
|
using System;
using System.Text.RegularExpressions;
class chapter8
{
static void Main()
{
string[] words = new string[] {"bad", "boy", "baaad", "bear", "bend"};
foreach (string word in words)
if (Regex.IsMatch(word, "ba+"))
Console.WriteLine(word);
Console.ReadKey();
}
}
|
using System;
//TODO: Add other using statements here
namespace com.Sconit.Entity.ISI
{
public partial class Checkup
{
#region Non O/R Mapping Properties
public string Desc
{
get
{
return this.CheckupUserNm
+ (!string.IsNullOrEmpty(this.JobNo) ? " " + this.JobNo : string.Empty)
+ (!string.IsNullOrEmpty(this.Dept2) ? " " + this.Dept2 : string.Empty)
+ (!string.IsNullOrEmpty(this.Department) ? " " + this.Department : string.Empty);
}
}
#endregion
}
} |
using UnityEngine;
using UnityEngine.UI;
public class canvasData : MonoBehaviour
{
public int level = 1;
public int randInd = 0;
public int levelTextColor = 0;
public Text getLevel;
public Text getScore;
public Slider progressBar;
public Material[] groundMaterials = new Material[4];
void Start()
{
getLevel.text = "Level " + PlayerPrefs.GetInt("Scenelevel", 1).ToString();
level = PlayerPrefs.GetInt("Scenelevel", 1);
levelTextColor = PlayerPrefs.GetInt("levelColor", 0);
progressBar.maxValue = PlayerPrefs.GetFloat("sliderMax", 25f);
progressBar.value = PlayerPrefs.GetFloat("Score", 0);
getScore.text = PlayerPrefs.GetString("ScoreText", "0%");
if(levelTextColor == 0)
{
getLevel.color = Color.black;
}
else
{
getLevel.color = Color.white;
}
randInd = PlayerPrefs.GetInt("materialInd", 0);
}
void Update()
{
if (progressBar.value >= progressBar.maxValue)
{
gettingnewMaterials();
changingProgressBar();
}
}
private void changingProgressBar()
{
getLevel.text = "Level " + ++level;
getScore.text = "0%";
progressBar.value = 0f;
progressBar.maxValue += level * 10;
progressBar.value = 0;
if (randInd % 2 == 0)
{
getLevel.color = Color.black;
levelTextColor = 0;
}
else
{
getLevel.color = Color.white;
levelTextColor = 1;
}
}
void gettingnewMaterials()
{
getInd(randInd);
changeInitialSpawnObj();
}
void getInd(int i)
{
while(randInd == i) randInd = Random.Range(0, 4);
}
void changeInitialSpawnObj()
{
GameObject[] allGround = GameObject.FindGameObjectsWithTag("Ground");
foreach(GameObject g in allGround)
{
g.GetComponent<MeshRenderer>().material = groundMaterials[randInd];
}
GameObject[] allHoles = GameObject.FindGameObjectsWithTag("Hole");
foreach(GameObject hole in allHoles)
{
if(randInd % 2 == 0) hole.GetComponent<MeshRenderer>().material = groundMaterials[1];
else hole.GetComponent<MeshRenderer>().material = groundMaterials[0];
}
}
}
|
namespace XH.Commands.Tenants
{
public class CreateTenantCommand : CreateOrUpdateTenantCommand
{
}
} |
using System.Collections.Generic;
using Tomelt.MediaLibrary.Models;
namespace Tomelt.MediaLibrary.ViewModels {
public class MediaManagerChildFoldersViewModel {
public IEnumerable<IMediaFolder> Children { get; set; }
}
}
|
using Profiling2.Domain.Prf.Sources;
using System.Collections.Generic;
using System;
namespace Profiling2.Domain.Contracts.Queries
{
public interface ISourceDataTablesQuery
{
int GetSearchTotal(bool canAccessRestricted, string searchName, string searchExt, string searchText, DateTime? start, DateTime? end, string authorSearchText);
IList<SourceSearchResultDTO> GetPaginatedResults(bool canAccessRestricted, int iDisplayStart, int iDisplayLength,
string searchName, string searchExt, string searchText, DateTime? start, DateTime? end, IList<int> adminSourceSearchIds,
int iSortingCols, List<int> iSortCol, List<string> sSortDir,
int userId, int? personId, int? eventId, string authorSearchText);
}
}
|
using System.Threading.Tasks;
using LoanAPound.Db.Model;
using System.Collections.Generic;
namespace LoanAPound.Db
{
public interface ILoanApplicationRepository
{
Task<LoanApplication> GetAsync(int id);
Task CreateAsync(LoanApplication loanApplication);
Task UpdateAsync(LoanApplication loan);
Task<IEnumerable<LoanApplication>> ListOutstandingAsync();
Task<IEnumerable<LoanApplication>> ListApplicationsAsync(int applicantId);
Task<IEnumerable<LoanApplication>> ListReadyForReviewAsync();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace BlackJack1
{
class Game
{
double rate = 0, cash = 1000;
Cards cards;
public Game(int money)
{
cash = money;
cards = new Cards();
}
bool AskForExit()
{
Console.Write("Stop game (Yes/No): ");
string ans = Console.ReadLine();
while (true)
{
if (ans.Equals("Yes"))
{
return true;
}
else if (ans.Equals("No"))
{
return false;
}
else
{
Console.WriteLine("Incorrect answer, try again");
}
}
}
public void Play()
{
while(true)
{
Console.Write("Your cash: {0} Enter your rate: ", cash);
rate = double.Parse(Console.ReadLine());
Cards c = new Cards();
Player player = new Player();
Diller diller = new Diller();
player.playerCount += c.getCard(ref player.myCard1);
player.playerCount += c.getCard(ref player.myCard2);
diller.dillerCount += c.getCard(ref diller.dillerCard);
diller.dillerCount += c.getCard(ref diller.dillerCard2);
diller.CheckScoreWithTUZ();
player.CheckScoreWithTUZ();
Console.WriteLine("Your cards is {0}, {1}; Diller's card is {2}", player.myCard1, player.myCard2, diller.dillerCard);
string answer = "";
if (player.playerCount == 21)
{
Console.WriteLine("BlackJack!");
if (diller.dillerCard == Cards.Card.TUZ)
{
Console.WriteLine("1 to 1? (Yes/No): ");
answer = Console.ReadLine();
if (answer.Equals("Yes"))
{
cash += rate;
Console.WriteLine("You won {0}, your cash {1}", rate, cash);
if (AskForExit()) break;
}
else if (!answer.Equals("No"))
{
Console.WriteLine("Incorrect answer, try again");
}
}
else
{
cash += rate * 1.5;
Console.WriteLine("You won {0}, your cash: {1}", rate * 1.5, cash);
if (AskForExit()) break;
}
}
else if (diller.dillerCount == 21)
{
cash -= rate;
Console.WriteLine("Diller got BlackJack! You lose {0}, your cash: {1}", rate, cash);
if (AskForExit()) break;
}
while (!answer.Equals("No"))
{
Console.Write("Hit me (Yes/No): ");
answer = Console.ReadLine();
if (answer.Equals("Yes"))
{
player.playerCount += c.getCard(ref player.myCard1);
player.CheckScoreWithTUZ();
Console.WriteLine("Card is {0}, current score: {1}", player.myCard1, player.playerCount);
}
else if (!answer.Equals("No"))
{
Console.WriteLine("Incorrect answer, try again");
}
}
if (diller.dillerCount >= 17) Console.WriteLine("Diller's count: {0}", diller.dillerCount);
while (diller.dillerCount < 17)
{
diller.dillerCount += c.getCard(ref diller.dillerCard);
diller.CheckScoreWithTUZ();
Console.WriteLine("Diller got {0}, diller's count: {1}", diller.dillerCard, diller.dillerCount);
}
if ((player.playerCount > diller.dillerCount && player.playerCount <= 21) || (player.playerCount <= 21 && diller.dillerCount > 21))
{
cash += rate * 1.5;
Console.WriteLine("You won {0}, your cash: {1}", rate * 1.5, cash);
}
else if (player.playerCount == diller.dillerCount)
{
Console.WriteLine("Push, your cash: {0}", cash);
}
else
{
cash -= rate;
Console.WriteLine("You lose {0}, your cash: {1}", rate, cash);
}
if (AskForExit()) break;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.Repository
{
public class LeakDbHelper
{
protected LeakDBContext dbcontext { get; set; }
public LeakDbHelper()
{
dbcontext = new LeakDBContext();
}
public IQueryable<T> GetDetails<T>() where T : class
{
return dbcontext.Set<T>().AsQueryable<T>();
}
public int Save<T>(T entity) where T : class
{
dbcontext.Set<T>().Add(entity);
return dbcontext.SaveChanges();
}
public int Update<T>(T entity) where T : class
{
dbcontext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
return dbcontext.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomGenerator
{
public class StyleInfo : ICloneable
{
public String Name { get; set; }
public String Feature { get; set; }
public StyleType Type { get; set; }
public String Value { get; set; }
public String MinValue { get; set; }
public String MaxValue { get; set; }
public IEnumerable<String> PossibleValues { get; set; }
public object Clone()
{
StyleInfo clonedObj = new StyleInfo();
clonedObj.Name = this.Name;
clonedObj.Feature = this.Feature;
clonedObj.Value = this.Value;
clonedObj.MinValue = this.MinValue;
clonedObj.MaxValue = this.MaxValue;
clonedObj.Type = this.Type;
clonedObj.PossibleValues = this.PossibleValues;
return clonedObj;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using DChild.Gameplay.Combat;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Objects.Characters.Enemies
{
public class GoblinBrain : MinionAIBrain<Goblin>, IAITargetingBrain
{
[SerializeField]
[TabGroup("Attack")]
[MinValue(0f)]
private float m_attackDistance;
[SerializeField]
[TabGroup("Attack")]
[MinValue(0f)]
private float m_attackCriticalDistance;
[SerializeField]
private float m_retreatDistance;
private PatrolHandler m_fullRetreatDistance;
private void Retreat()
{
var destination = m_fullRetreatDistance.GetInfo(transform.position).destination;
m_minion.Retreat(destination);
m_minion.LookAt(destination);
}
private void MoveTo(Vector2 currentPos)
{
var destination = new Vector2(currentPos.x + m_retreatDistance, currentPos.y);
m_minion.Retreat(destination);
m_minion.LookAt(destination);
}
private bool isTargetWithinAttackRange(float distance)
{
var attackDirection = (m_minion.facing == Direction.Left ? Vector2.left : Vector2.right);
var hit = Physics2D.Raycast(transform.position, attackDirection, distance, 1 << LayerMask.NameToLayer("Player"));
Debug.DrawRay(transform.position, attackDirection * distance);
return hit.collider != null;
}
private bool isNearDestination()
{
return true;
}
private bool CanBeSeenBy(Character character)
{
if (m_minion.position.x < character.position.x)
{
return character.facing == Direction.Left;
}
else
{
return character.facing == Direction.Right;
}
}
protected override bool IsLookingAt(Vector2 target)
{
return base.IsLookingAt(target);
}
public override void Enable(bool value)
{
if (!value)
{
m_target = null;
}
else
{
m_minion.Stay();
}
enabled = value;
}
public override void ResetBrain()
{
m_target = null;
}
public override void SetTarget(IDamageable target)
{
m_target = target;
if (m_minion.position.x < target.position.x)
{
m_minion.SetFacing(Direction.Right);
}
else
{
m_minion.SetFacing(Direction.Left);
}
}
private void Update()
{
if (m_minion.waitForBehaviourEnd)
return;
if (m_target != null)
{
}
}
protected override void Awake()
{
base.Awake();
m_fullRetreatDistance = GetComponent<PatrolHandler>();
}
#if UNITY_EDITOR
public float retreatDistance => m_retreatDistance;
public float attackDistance => m_attackDistance;
public float attackCriticalDistance => m_attackCriticalDistance;
#endif
}
}
|
using _01_Alabo.Cloud.Core.Extends.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace _01_Alabo.Cloud.Core.Extends.Domain.Repositories
{
public interface IExtendRepository : IRepository<Extend, ObjectId>
{
}
} |
namespace ostranauts_modding
{
public class AudioEmitter
{
public double fLoPassFreq { get; set; }
public double fLoPassFreqOccluded { get; set; }
public double fMaxDistance { get; set; }
public double fMinDistance { get; set; }
public double fSpatialBlend { get; set; }
public double fSteadyDelay { get; set; }
public double fTransDuration { get; set; }
public double fVolumeSteady { get; set; }
public double fVolumeTrans { get; set; }
public string strClipSteady { get; set; }
public string strClipTrans { get; set; }
public string strFalloffCurve { get; set; }
public string strLowPassCurve { get; set; }
public string strMixerName { get; set; }
public string strName { get; set; }
}
} |
using DealOrNoDeal.Data.Rounds;
using DealOrNoDeal.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DealOrNoDeal.Tests.GameSettings
{
[TestClass]
public class TestConstructor
{
[TestMethod]
public void ShouldSetGameSettingsForTenRoundNotSyndicatedGame()
{
var settings = new GameSettingsManager();
Assert.AreEqual(CasesToOpenForEachRound.TenRoundCases.ToString(), settings.CasesToOpen.ToString());
Assert.AreEqual(DollarValuesForEachRound.Regular.ToString(), settings.DollarValues.ToString());
}
[TestMethod]
public void ShouldSetGameSettingsForTenRoundSyndicatedGame()
{
var settings = new GameSettingsManager();
Assert.AreEqual(CasesToOpenForEachRound.TenRoundCases.ToString(), settings.CasesToOpen.ToString());
Assert.AreEqual(DollarValuesForEachRound.Syndicated.ToString(), settings.DollarValues.ToString());
}
[TestMethod]
public void ShouldSetGameSettingsForSevenRoundNotSyndicatedGame()
{
var settings = new GameSettingsManager();
Assert.AreEqual(CasesToOpenForEachRound.SevenRoundGame.ToString(), settings.CasesToOpen.ToString());
Assert.AreEqual(DollarValuesForEachRound.Regular.ToString(), settings.DollarValues.ToString());
}
[TestMethod]
public void ShouldSetGameSettingsForSevenRoundSyndicatedGame()
{
var settings = new GameSettingsManager();
Assert.AreEqual(CasesToOpenForEachRound.SevenRoundGame.ToString(), settings.CasesToOpen.ToString());
Assert.AreEqual(DollarValuesForEachRound.Syndicated.ToString(), settings.DollarValues.ToString());
}
[TestMethod]
public void ShouldSetGameSettingsForQuickPlay()
{
var settings = new GameSettingsManager();
Assert.AreEqual(CasesToOpenForEachRound.FiveRoundGame.ToString(), settings.CasesToOpen.ToString());
Assert.AreEqual(DollarValuesForEachRound.QuickPlay.ToString(), settings.DollarValues.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEMAPI.Models
{
public class HeadWiseClearedAmountsDTO
{
public HeadWiseClearedAmountsDTO()
{
LandCost = 0;
ConstructionCost = 0;
MaintainanceCost = 0;
OtherCost = 0;
ReimbursementCost = 0;
CustomisationCost = 0;
Interest = 0;
HomeImprovementCost = 0;
ReimbursementServiceTax = 0;
ReimbursementVAT = 0;
ReimbursementSBC = 0;
ReimbursementKKC = 0;
ServiceTax = 0;
VAT = 0;
SBC = 0;
KKC = 0;
RefundableServiceTax = 0;
RefundableVAT = 0;
RefundableSBC = 0;
RefundableKKC = 0;
}
public decimal? LandCost { get; set; }
public decimal? ConstructionCost { get; set; }
public decimal? MaintainanceCost { get; set; }
public decimal? OtherCost { get; set; }
public decimal? ReimbursementCost { get; set; }
public decimal? CustomisationCost { get; set; }
public decimal? Interest { get; set; }
public decimal? HomeImprovementCost { get; set; }
public decimal? ReimbursementServiceTax { get; set; }
public decimal? ReimbursementVAT { get; set; }
public decimal? ReimbursementSBC { get; set; }
public decimal? ReimbursementKKC { get; set; }
public decimal? ServiceTax { get; set; }
public decimal? VAT { get; set; }
public decimal? SBC { get; set; }
public decimal? KKC { get; set; }
public decimal? RefundableServiceTax { get; set; }
public decimal? RefundableVAT { get; set; }
public decimal? RefundableSBC { get; set; }
public decimal? RefundableKKC { get; set; }
}
} |
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using WebsiteManagerPanel.Data.Entities;
namespace WebsiteManagerPanel.Query
{
public class UserRoleQuery : BaseQuery<UserRole>
{
public UserRoleQuery(DbContext dbContext) : base(dbContext)
{
}
public async Task<UserRole> GetByUserIdAndRoleGroupId(int userId, int roleGroupId)
{
var userRole = await Query.Include(p => p.RoleGroup).FirstOrDefaultAsync(ur => ur.User.Id == userId && ur.RoleGroup.Id == roleGroupId);
return userRole;
}
public async Task<UserRole> GetUserRole(int userId, int roleGroupID)
{
var userRole = await Query
.Include(r => r.RoleGroup)
.ThenInclude(p => p.Roles)
.Include(p => p.User)
.FirstOrDefaultAsync(ur => ur.User.Id == userId && ur.RoleGroup.Id == roleGroupID);
return userRole;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Alps.Domain.ProductMgr;
using Alps.Web.Models;
using Alps.Web.Models.ProductMgr;
using Alps.Domain;
using Alps.Web.Infrastructure;
namespace Alps.Web.Controllers
{
public class ProductStockApiController : ApiController
{
private AlpsContext db = new AlpsContext();
// GET: api/ProductStockApi
public IHttpActionResult GetProductStocks(int pageIndex = 1,int pageSize=10)
{
var q = from p in db.ProductSkus
from ps in db.ProductStocks
from po in db.Positions
from t in db.Departments
where p.ID==ps.SkuID && ps.DepartmentID==t.ID && ps.PositionID==po.ID
orderby p.Name
select new ProductStockListModel { ProductName = p.Name, ID = ps.ID, OwnerName = t.Name, PositionName = po.Name, ProductNumber = ps.ProductNumber, Quantity = ps.Quantity, Weight = ps.Weight };
var totalCount = q.Count();
var result = q.Skip((pageIndex - 1) * pageSize).Take(pageSize);
return Ok(new {data=result,totalcount=totalCount});
}
// GET: api/ProductStockApi/5
[ResponseType(typeof(ProductStock))]
public IHttpActionResult GetProductStock(Guid id)
{
ProductStock productStock = db.ProductStocks.Find(id);
if (productStock == null)
{
return NotFound();
}
return Ok(productStock);
}
// PUT: api/ProductStockApi/5
[ResponseType(typeof(void))]
public IHttpActionResult PutProductStock(Guid id, ProductStock productStock)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != productStock.ID)
{
return BadRequest();
}
db.Entry(productStock).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductStockExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/ProductStockApi
[ResponseType(typeof(ProductStock))]
public IHttpActionResult PostProductStock(ProductStock productStock)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.ProductStocks.Add(productStock);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (ProductStockExists(productStock.ID))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = productStock.ID }, productStock);
}
// DELETE: api/ProductStockApi/5
[ResponseType(typeof(ProductStock))]
public IHttpActionResult DeleteProductStock(Guid id)
{
ProductStock productStock = db.ProductStocks.Find(id);
if (productStock == null)
{
return NotFound();
}
db.ProductStocks.Remove(productStock);
db.SaveChanges();
return Ok(productStock);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProductStockExists(Guid id)
{
return db.ProductStocks.Count(e => e.ID == id) > 0;
}
}
} |
using System;
class ExtractBitFromInteger
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
uint luiNumber;
int luiMask, lsbBit;
Console.Write("Enter positive integer : ");
luiNumber = uint.Parse(Console.ReadLine());
Console.Write("Enter a number of bit : ");
lsbBit = int.Parse(Console.ReadLine());
luiMask = 1 << lsbBit; // Move the 1st bit left by p positions
Console.WriteLine("Value of the {0} Bit on number {1} -> {2}", lsbBit, luiNumber, (luiNumber & luiMask) != 0 ? 1 : 0);
}
}
} |
using Core.DataAccess.EntityFramework;
using DataAccess.Abstract;
using Entities.Concrete;
using Entities.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace DataAccess.Concrete.EntityFramework
{
public class EfCarDal : EfEntityRepositoryBase<Car, CarDBContext>, ICarDal
{
public List<CarDetailDto> GetCarDetails(Expression<Func<CarDetailDto, bool>> filter = null)
{
using (CarDBContext context=new CarDBContext())
{
var result = from c in context.Cars
join b in context.Brands on c.BrandId equals b.Id
join col in context.Colors on c.ColorId equals col.Id
select new CarDetailDto
{
CarName = c.Name,
ColorName = col.Name,
BrandName = b.Name,
DailyPrice = c.DailyPrice,
ColorId=c.ColorId,
BrandId=b.Id,
Id=c.Id
};
return filter == null ? result.ToList(): result.Where(filter).ToList();
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace POSServices.Models
{
public partial class CashierShift
{
public int Id { get; set; }
public string EmployeeCode { get; set; }
public string EmployeeName { get; set; }
public decimal? OpeningBalance { get; set; }
public decimal? ClosingBalance { get; set; }
public DateTime? OpeningTime { get; set; }
public DateTime? ClosingTime { get; set; }
public string DeviceName { get; set; }
public string ShiftName { get; set; }
public string ShiftCode { get; set; }
public string StoreCode { get; set; }
public string StoreName { get; set; }
public string CashierShiftId { get; set; }
}
}
|
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Welic.Dominio.Models.Estacionamento.Map;
using Welic.Dominio.Models.Estacionamento.Services;
using Welic.Dominio.Patterns.Repository.Pattern.UnitOfWork;
namespace WebApi.API.Controllers
{
[Authorize]
[RoutePrefix("api/estacionamento")]
public class EstacionamentoController : BaseController
{
private readonly IServiceEstacionamento _serviceEstacionamento;
private readonly IServiceEstacionamentoVagas _serviceEstacionamentoVagas;
private readonly IUnitOfWorkAsync _unitOfWorkAsync;
public EstacionamentoController(IServiceEstacionamento serviceEstacionamento, IUnitOfWorkAsync unitOfWorkAsync, IServiceEstacionamentoVagas serviceEstacionamentoVagas)
{
_serviceEstacionamento = serviceEstacionamento;
_serviceEstacionamentoVagas = serviceEstacionamentoVagas;
_unitOfWorkAsync = unitOfWorkAsync;
}
[HttpGet]
[Route("Get/")]
public Task<HttpResponseMessage> Get()
{
return CriaResposta(HttpStatusCode.OK, _serviceEstacionamento.Query().Select(x => x).ToList());
}
[HttpGet]
[Route("GetById/{id:int}")]
public async Task<HttpResponseMessage> Get(int id)
{
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamento.Find(id));
}
[HttpGet]
[Route("GetVagasByEstacionamento/{id:int}")]
public async Task<HttpResponseMessage> GetVagas(int id)
{
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamentoVagas.Query().Select(x=> x).Where(x=> x.IdEstacionamento == id).ToList());
}
[HttpGet]
[Route("GetListVagas/{id:int}")]
public async Task<HttpResponseMessage> GetListVagas(int id)
{
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamentoVagas.Query().Select(x => x).Where(x => x.IdEstacionamento == id).ToList());
}
[HttpPost]
[Route("save")]
public async Task<HttpResponseMessage> Post([FromBody]EstacionamentoMap estacionamento)
{
_serviceEstacionamento.Insert(estacionamento);
await _unitOfWorkAsync.SaveChangesAsync();
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamento
.Query()
.Select(x => x)
.LastOrDefault(x => x.Descricao == estacionamento.Descricao &&
x.ValidaVencimento == estacionamento.ValidaVencimento &&
x.Relacao == estacionamento.Relacao &&
x.TipoIdentificacao == estacionamento.TipoIdentificacao ));
}
[HttpPost]
[Route("saveVagas")]
public async Task<HttpResponseMessage> Post([FromBody]EstacionamentoVagasMap estacionamento)
{
_serviceEstacionamentoVagas.Insert(estacionamento);
await _unitOfWorkAsync.SaveChangesAsync();
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamentoVagas
.Query()
.Select(x => x)
.LastOrDefault(x => x.IdEstacionamento == estacionamento.IdEstacionamento &&
x.Quantidade == estacionamento.Quantidade &&
x.TipoVaga == estacionamento.TipoVaga &&
x.TipoVeiculo == estacionamento.TipoVeiculo));
}
[HttpPost]
[Route("Update")]
public async Task<HttpResponseMessage> Update([FromBody]EstacionamentoMap estacionamento)
{
_serviceEstacionamento.Update(estacionamento);
await _unitOfWorkAsync.SaveChangesAsync();
return await CriaResposta(HttpStatusCode.OK, _serviceEstacionamento.Find(estacionamento.IdEstacionamento));
}
[HttpPost]
[Route("Delete/{id}")]
public Task<HttpResponseMessage> Delete(int id)
{
var cursoMap = _serviceEstacionamento.Find(id);
_serviceEstacionamento.Delete(cursoMap);
_unitOfWorkAsync.SaveChangesAsync();
return CriaResposta(HttpStatusCode.OK);
}
[HttpPost]
[Route("DeleteVagas/{id}/{tipoVaga}/{tipoVeiculo}")]
public Task<HttpResponseMessage> DeleteVagas(int id, int tipoVaga, int tipoVeiculo)
{
var cursoMap = _serviceEstacionamentoVagas.Query().Select(x=> x).FirstOrDefault(x=> x.IdEstacionamento == id && x.TipoVaga == tipoVaga && x.TipoVeiculo == tipoVeiculo);
_serviceEstacionamentoVagas.Delete(cursoMap);
_unitOfWorkAsync.SaveChangesAsync();
return CriaResposta(HttpStatusCode.OK);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SonicSpawner : MonoBehaviour
{
public GameObject Sonic;
public float SpawnRate; // = 3 seconds
float timer = 0;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer >= SpawnRate)
{
Instantiate(Sonic,null);
timer = 0;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.