text
stringlengths
13
6.01M
using gView.Framework.Geometry; namespace gView.DataSources.VectorTileCache.Extensions { static class GeoJsonExtensions { static public IGeometry ToGeometry(this GeoJSON.Net.Geometry.IGeometryObject geoJsonGeometry) { IGeometry geometry = null; switch (geoJsonGeometry.Type) { case GeoJSON.Net.GeoJSONObjectType.Point: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.Point).ToPoint(); break; case GeoJSON.Net.GeoJSONObjectType.MultiPoint: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.MultiPoint).ToMultiPoint(); break; case GeoJSON.Net.GeoJSONObjectType.LineString: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.LineString).ToPolyline(); break; case GeoJSON.Net.GeoJSONObjectType.MultiLineString: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.MultiLineString).ToPolyline(); break; case GeoJSON.Net.GeoJSONObjectType.Polygon: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.Polygon).ToPolygon(); break; case GeoJSON.Net.GeoJSONObjectType.MultiPolygon: geometry = (geoJsonGeometry as GeoJSON.Net.Geometry.MultiPolygon).ToPolygon(); break; } return geometry; } static public Point ToPoint(this GeoJSON.Net.Geometry.Point geoJsonPoint) { if (geoJsonPoint?.Coordinates != null) { return new Point(geoJsonPoint.Coordinates.Longitude, geoJsonPoint.Coordinates.Latitude); } return null; } static public MultiPoint ToMultiPoint(this GeoJSON.Net.Geometry.MultiPoint geoJsonMultiPoint) { var multiPoint = new MultiPoint(); if (geoJsonMultiPoint?.Coordinates != null) { foreach (var geoJsonPoint in geoJsonMultiPoint.Coordinates) { var point = geoJsonPoint.ToPoint(); if (point != null) { multiPoint.AddPoint(point); } } } return multiPoint; } static public Polyline ToPolyline(this GeoJSON.Net.Geometry.LineString geoJsonLineString) { var polyline = new Polyline(); var path = new Path(); polyline.AddPath(path); if (geoJsonLineString?.Coordinates != null) { foreach (var position in geoJsonLineString.Coordinates) { path.AddPoint(new Point(position.Longitude, position.Latitude)); } } return polyline; } static public Polyline ToPolyline(this GeoJSON.Net.Geometry.MultiLineString geoJsonMultiLineString) { var polyline = new Polyline(); if (geoJsonMultiLineString?.Coordinates != null) { foreach (var geoJsonLineString in geoJsonMultiLineString.Coordinates) { if (geoJsonLineString.Coordinates != null) { var path = new Path(); polyline.AddPath(path); foreach (var position in geoJsonLineString.Coordinates) { path.AddPoint(new Point(position.Longitude, position.Latitude)); } } } } return polyline; } static public Polygon ToPolygon(this GeoJSON.Net.Geometry.Polygon geoJsonPolygon) { var polygon = new Polygon(); if (geoJsonPolygon?.Coordinates != null) { foreach (var geoJsonLineString in geoJsonPolygon.Coordinates) { if (geoJsonLineString?.Coordinates != null) { var ring = new Ring(); polygon.AddRing(ring); foreach (var position in geoJsonLineString.Coordinates) { ring.AddPoint(new Point(position.Longitude, position.Latitude)); } } } } return polygon; } static public Polygon ToPolygon(this GeoJSON.Net.Geometry.MultiPolygon geoJsonMultiPolygon) { var polygon = new Polygon(); if (geoJsonMultiPolygon?.Coordinates != null) { foreach (var geoJsonPolygon in geoJsonMultiPolygon.Coordinates) { if (geoJsonPolygon?.Coordinates != null) { foreach (var geoJsonLineString in geoJsonPolygon.Coordinates) { if (geoJsonLineString?.Coordinates != null) { var ring = new Ring(); polygon.AddRing(ring); foreach (var position in geoJsonLineString.Coordinates) { ring.AddPoint(new Point(position.Longitude, position.Latitude)); } } } } } } return polygon; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EasyDev.Util { public enum TimeUnit { Hour, Minute, Second } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ShabakahRedir; using Honeywell.SimulationFramework.LoggerComponent; using System.IO; using System.Configuration; using System.Threading; using ShabakahRedir; using ShabakahEntityManager; namespace ShabakahSimulator { public partial class ShabakahSimulatorMainForm : Form { private ShabakahRedir.MockRedir MockRedir; private string ConfigFileName; private int NumberofDevicesToBeSimulated; private List<PanelServices> PanelMAC; private Logger m_logger; private Thread thDetReportUpdate; private bool blnUpdateDet = false; private int PanelsPerMin = 0; private int Arm_DisArm_Min = 0; Thread thArmDisArm; delegate void TempDelegate(); public ShabakahSimulatorMainForm() { InitializeComponent(); //Logger bool valid = false; string level = ConfigurationSettings.AppSettings["LoggerLevel"]; Level loggerLevel = GetLoggerLevel(level); string logFileSizeInMB = ConfigurationSettings.AppSettings["LogFileSizeInMB"]; float logFileSize; valid = float.TryParse(logFileSizeInMB, out logFileSize); if (!valid) { logFileSize = 5; } m_logger = new Logger("SimulatorLog.txt", true, loggerLevel); m_logger.RollOverFileSizeInMB = logFileSize; //MockRedir = new ShabakahRedir.MockRedir(m_logger); } private Level GetLoggerLevel(string level) { int levelValue; bool valid = Int32.TryParse(level, out levelValue); if (!valid) return Level.MEDIUM; if (levelValue == (int)Level.TRACE) { return Level.TRACE; } if (levelValue >= (int)Level.MEDIUM) { return Level.MEDIUM; } if (levelValue >= (int)Level.LOW) { return Level.LOW; } if (levelValue >= (int)Level.HIGH) { return Level.HIGH; } return Level.CRITICAL; } private void configureToolStripMenuItem_Click(object sender, EventArgs e) { try { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - configureToolStripMenuItem_Click - Start"); //if (btnStopRedir.Enabled && btnStartRedir.Enabled) //{ // MessageBox.Show("Stop Redir Server", "ShabakahSimulator"); //} ConfigurePanels configDevicesForm = new ConfigurePanels(); if (configDevicesForm.ShowDialog() == DialogResult.OK) { if (thDetReportUpdate != null) { thDetReportUpdate.Abort(); thDetReportUpdate = null; blnUpdateDet = false; } ConfigFileName = configDevicesForm.m_ConfigFileName; NumberofDevicesToBeSimulated = configDevicesForm.m_NumberofDevices; if (ConfigureDevicesCSV()) { TabControl.Enabled = true; //In DetailedReport tab dgv_DetailedReport.Enabled = true; //In Config tab btnStartRedir.Enabled = true; btnStopRedir.Enabled = true; btnStartReq.Enabled = false; btnStopRedir.Enabled = false; txtPanelsPerMin.Enabled = true; txtArmDisArm.Enabled = true; grpBoxReport.Enabled = true; //InitializeDeviceCounters(); PopulateDetailedReportsTable(); blnUpdateDet = true; thDetReportUpdate = new Thread(new ThreadStart(UpdateDetailReportTable)); thDetReportUpdate.Start(); } } m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - configureToolStripMenuItem_Click - End"); } catch (Exception ex) { m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - configureToolStripMenuItem_Click - Exception - " + ex.Message); } } private void UpdateDetailReportTable() { try { int RowNum = 0; while (blnUpdateDet) { //Update Total Report details TempDelegate td1 = delegate() { lblRedirStatus.Text = MockRedir.RedirStatus.ToString(); lblRecArm.Text = MockPanel.RecArm.ToString(); lblRespArm.Text = MockPanel.RespArm.ToString(); lblRecDisarm.Text = MockPanel.RecDisarm.ToString(); lblRespDisarm.Text = MockPanel.RespDisarm.ToString(); lblOSSent.Text = PanelServices.totSessionSent.ToString(); lblOSSuccess.Text = PanelServices.totSessionSuccess.ToString(); lblOSFail.Text = PanelServices.totSessionFailed.ToString(); lblArmSent.Text = PanelServices.totArmSent.ToString(); lblArmSuccess.Text = PanelServices.totArmSuccess.ToString(); lblArmFail.Text = PanelServices.totArmFailed.ToString(); lblDSSent.Text = PanelServices.totDisArmSent.ToString(); lblDSSuccess.Text = PanelServices.totDisArmSuccess.ToString(); lblDSFail.Text = PanelServices.totDisArmFailed.ToString(); }; this.BeginInvoke(td1); RowNum = 0; foreach (var panel in PanelMAC) { TempDelegate td = delegate() { if (RowNum < dgv_DetailedReport.Rows.Count) { dgv_DetailedReport.Rows[RowNum].Cells[1].Value = "Session Sent: " + panel.SessionSent + Environment.NewLine + " Session Success: " + panel.SessionSuccess + Environment.NewLine + " Session Failed: " + panel.SessionFailed; dgv_DetailedReport.Rows[RowNum].Cells[2].Value = "Arm Sent: " + panel.ArmSent + Environment.NewLine + " Arm Success: " + panel.ArmSuccess + Environment.NewLine + " Arm Fail : " + panel.ArmFailed; dgv_DetailedReport.Rows[RowNum].Cells[3].Value = "DisArm Send: " + panel.DisArmSent + Environment.NewLine + " DisArm Success: " + panel.DisArmSuccess + Environment.NewLine + " DisArm Fail: " + panel.DisArmFailed; } RowNum++; }; this.BeginInvoke(td); } Thread.Sleep(5000); } } catch (Exception ex) { m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - UpdateDetailReportTable - Exception - " + ex.Message); } } /// <summary> /// Used to fill the table with device ids and default row data for all devices read from DB. --shaiju /// </summary> private void PopulateDetailedReportsTable() { try { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - PopulateDetailedReportsTable - Start"); dgv_DetailedReport.Rows.Clear(); int rowIndex = 0; foreach (var ShabPanel in PanelMAC) { dgv_DetailedReport.Rows.Add(); dgv_DetailedReport.Rows[rowIndex].Height = 70; dgv_DetailedReport.Rows[rowIndex++].Cells[0].Value = ShabPanel.MAC; } m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - PopulateDetailedReportsTable - End"); } catch (Exception ex) { m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - PopulateDetailedReportsTable - Exception - " + ex.Message); } } private bool ConfigureDevicesCSV() { bool blnRes = false; try { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - ConfigureDevicesCSV - Start"); PanelMAC = new List<PanelServices>(); using (var streamReader = new StreamReader(ConfigFileName)) { int lineNumber = 0; string lineRead = string.Empty; while (!string.IsNullOrEmpty(lineRead = streamReader.ReadLine())) { if (lineNumber == 0) { lineNumber++; continue; } string[] data = lineRead.Split(','); string MAC = data[0]; PanelServices PanelServ = new PanelServices(MAC,m_logger); PanelMAC.Add(PanelServ); lineNumber++; if (lineNumber > NumberofDevicesToBeSimulated) { blnRes = true; break; } } //MockRedir.ConfigPanelMAC(PanelMAC); } m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - ConfigureDevicesCSV - End"); } catch (Exception ex) { blnRes = false; m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - ConfigureDevicesCSV - Exception - " + ex.Message); } return blnRes; } private void sTARTToolStripMenuItem_Click(object sender, EventArgs e) { startRedir(); } private void startRedir() { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - startRedir - Start"); MockRedir.StartServer(); btnStopRedir.Enabled = true; btnStartReq.Enabled = true; btnStopReq.Enabled = true; txtArmDisArm.Enabled = true; txtPanelsPerMin.Enabled = true; btnStartRedir.Enabled = false; m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - startRedir - End"); } private void stopRedir() { try { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - stopRedir - Start"); btnStopRedir.Enabled = false; StopRequest(); MockRedir.StopServer(); MockRedir = null; btnStartRedir.Enabled = true; btnStartReq.Enabled = false; m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - stopRedir - End"); } catch (Exception ex) { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - stopRedir - Exception - " + ex.Message); } } private void stopServerToolStripMenuItem_Click(object sender, EventArgs e) { stopRedir(); } private void btnStopRedir_Click(object sender, EventArgs e) { stopRedir(); } private void btnStartRedir_Click(object sender, EventArgs e) { //Initialize MockRedir MockRedir = new ShabakahRedir.MockRedir(m_logger); MockRedir.ConfigPanelMAC(PanelMAC); //InitializeRedirCounters(); startRedir(); } protected override void OnClosing(CancelEventArgs e) { CloseSimulator(); } private void groupBox1_Enter(object sender, EventArgs e) { } private void lblRedirSent_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void btnStartReq_Click(object sender, EventArgs e) { Int32.TryParse(txtPanelsPerMin.Text, out PanelsPerMin); Int32.TryParse(txtArmDisArm.Text, out Arm_DisArm_Min); if (PanelsPerMin > NumberofDevicesToBeSimulated) { MessageBox.Show("Entered Panel is more than configured Panel."); } else { btnStartReq.Enabled = false; btnStopReq.Enabled = true; MockRedir.InitializeCounter(); StartArmDisArmRequest(); } } private void StartArmDisArmRequest() { try { //ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(() => MockRedir.SendRequest(PanelsPerMin,Arm_DisArm_Min))); thArmDisArm = new Thread(() => MockRedir.SendRequest(PanelsPerMin, Arm_DisArm_Min)); thArmDisArm.Start(); } catch (Exception ex) { m_logger.LogMessage(Level.TRACE, "ShabakahSimulatorMainForm - StartArmDisArmRequest - Exception - " + ex.Message); } } private void btnStopReq_Click(object sender, EventArgs e) { StopRequest(); } private void StopRequest() { try { btnStopReq.Enabled = false; MockRedir.StopRequest(); if (thArmDisArm != null) { thArmDisArm.Abort(); } btnStartReq.Enabled = true; } catch (Exception ex) { m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - StopRequest - Exception - " + ex.Message); } } private void txtNoOfIDoXs_KeyPress(object sender, KeyPressEventArgs e) { int KeyCode = (int)e.KeyChar; if (!IsNumberInRange(KeyCode, 48, 57) && KeyCode != 8) { e.Handled = true; Console.Beep(); } } private bool IsNumberInRange(int Val, int Min, int Max) { try { return (Val >= Min && Val <= Max); } catch (Exception ex) { // m_Logger.LogMessage(Level.CRITICAL, "frmReadersConfiguration:IsNumberInRange:Exception:" + ex.Message); return false; } } private void CloseSimulator() { try { stopRedir(); Application.Exit(); } catch (Exception ex) { m_logger.LogMessage(Level.CRITICAL, "ShabakahSimulatorMainForm - CloseSimulator"); } } private void ShabakahSimulatorMainForm_Load(object sender, EventArgs e) { /* TabControl.Enabled = false; //In DetailedReport tab dgv_DetailedReport.Enabled = false; //In Config tab btnStartRedir.Enabled = false; btnStopRedir.Enabled = false; btnStartReq.Enabled = false; btnStopReq.Enabled = false; txtPanelsPerMin.Enabled = false; txtArmDisArm.Enabled = false; grpBoxReport.Enabled = false;*/ } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { CloseSimulator(); } private void groupBox1_Enter_1(object sender, EventArgs e) { } private void grpBoxConfig_Enter(object sender, EventArgs e) { } private void lblRedirStatus_Click(object sender, EventArgs e) { } private void grpRedirReport_Enter(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace _12_Little_John { public class _12_Little_John { public static void Main() { var arrows = new List<string>(); var bigArrow = ">>>----->>"; var middleArrow = ">>----->"; var smallArrow = ">----->"; var pattern = new Regex(@"\>+\-{5}\>+"); for (int i = 0; i < 4; i++) { var input = Console.ReadLine(); var matches = pattern.Matches(input); foreach (Match match in matches) { arrows.Add(match.Value); } } var bigArrowCount = 0; var middleArrowCount = 0; var smallArrowCount = 0; foreach (var item in arrows) { if (item.Contains(bigArrow)) { bigArrowCount++; } else if (item.Contains(middleArrow)) { middleArrowCount++; } else if (item.Contains(smallArrow)) { smallArrowCount++; } } var finalString = smallArrowCount.ToString() + middleArrowCount.ToString() + bigArrowCount.ToString(); var binary = Convert.ToString(int.Parse(finalString), 2); var reversed = binary.ToString().ToArray(); Array.Reverse(reversed); foreach (var symbol in reversed) { binary += symbol; } var dec = Convert.ToInt64(binary, 2); Console.WriteLine(dec); } } }
using UnrealBuildTool; using System.IO; public class RemoteController : ModuleRules { public RemoteController(TargetInfo Target) { PrivateIncludePaths.AddRange(new string[] { "RemoteController/Private", "RemoteController/Private/Server", "RemoteController/Private/Shared", }); PublicIncludePaths.AddRange(new string[] { "RemoteController/Public" }); PublicDependencyModuleNames.AddRange(new string[] { "Engine", "Core", "CoreUObject", "Sockets", "Networking", "InputCore" }); } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.UI; [CustomEditor(typeof(RailBuilder))] public class RailEditor : Editor { private List<bool> foldouts; private List<bool> edits; private void DestroyRail() { RailBuilder self = (RailBuilder)target; if (self.railPieces != null) { foreach (RailPiece r in self.railPieces) { if (r.self != null) { DestroyImmediate(r.self.gameObject); } } self.railPieces.Clear(); } } private void CreateRail() { RailBuilder self = (RailBuilder)target; Quaternion srot = self.transform.rotation; self.transform.rotation = Quaternion.identity; DestroyRail(); self.railPieces = new List<RailPiece>(); for (int i = 0; i < self.segmentCount; i++) { GameObject piece = Instantiate(self.prefab, self.transform.position - Vector3.forward * i * 5, Quaternion.identity, self.transform); self.railPieces.Add(new RailPiece(piece.transform)); } self.transform.rotation = srot; self.Refresh(); } public override void OnInspectorGUI() { RailBuilder self = (RailBuilder)target; self.editors = edits; if (self.railPieces == null) { self.railPieces = new List<RailPiece>(); } if (foldouts == null) { foldouts = new List<bool>(); foreach (RailPiece r in self.railPieces) foldouts.Add(false); } self.prefab = (GameObject)EditorGUILayout.ObjectField("Rail Prefab", self.prefab, typeof(GameObject), false); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("-")) { foldouts = new List<bool>(); edits = new List<bool>(); RailPiece[] backup = new RailPiece[self.railPieces.Count]; self.railPieces.CopyTo(backup); self.segmentCount--; CreateRail(); int index = 0; foreach (RailPiece r in self.railPieces) { foldouts.Add(false); edits.Add(false); if (backup != null && index < backup.Length) { r.bend = backup[index].bend; } index++; } } GUILayout.Label(self.segmentCount.ToString()); if (GUILayout.Button("+")) { foldouts = new List<bool>(); edits = new List<bool>(); RailPiece[] backup = new RailPiece[self.railPieces.Count]; self.railPieces.CopyTo(backup); self.segmentCount++; CreateRail(); int index = 0; foreach (RailPiece r in self.railPieces) { foldouts.Add(false); edits.Add(false); if (backup != null && index < backup.Length) { r.bend = backup[index].bend; } index++; } } EditorGUILayout.EndHorizontal(); //base.OnInspectorGUI(); if (GUILayout.Button("Destroy rail")) { DestroyRail(); self.segmentCount = 0; } if (GUILayout.Button("Generate waypoints for animation")) { int w = 0; foreach (RailPiece r in self.railPieces) { GameObject g = new GameObject("Rail waypoint " + w); g.transform.position = r.bones[r.bones.Count - 1].position; g.transform.rotation = r.bones[r.bones.Count - 1].rotation; w++; } } ((RailBuilder)this.target).Refresh(); if (self.railPieces != null) { int j = 0; foreach (RailPiece r in self.railPieces) { foldouts[j] = EditorGUILayout.Foldout(foldouts[j], "Rail Piece " + j); if (foldouts[j]) { r.bend = EditorGUILayout.Vector3Field("Rail Bend", r.bend); /*if (GUILayout.Button(edits[j] ? "Finish" : "Edit")) { if (!edits[j]) { for (int i = 0; i < edits.Count; i++) { edits[i] = false; } edits[j] = true; } else { edits[j] = false; } }*/ /*if(GUILayout.Button("Create Junction")) { GameObject n = new GameObject("Junction"); n.transform.parent = r.bones[r.bones.Count-1]; n.transform.localPosition = Vector3.zero; n.transform.rotation = r.bones[r.bones.Count - 1].rotation * Quaternion.Euler(90,0,0); n.AddComponent<RailBuilder>(); n.GetComponent<RailBuilder>().prefab = self.prefab; Selection.activeGameObject = n; }*/ } j++; } } ((RailBuilder)this.target).Refresh(); if(GUILayout.Button("Apply All")) { if (EditorUtility.DisplayDialog("Are you sure?", "This action is irreversible", "Si", "No")) { foreach (RailBuilder r in self.GetComponentsInChildren<RailBuilder>()) { DestroyImmediate(r); } DestroyImmediate(self); } } } private void OnSceneGUI() { RailBuilder self = (RailBuilder)target; if (self.railPieces == null) { return; } int j = 0; foreach (RailPiece r in self.railPieces) { if (r.bones[0] != null) { GUIStyle style = new GUIStyle(); style.fontSize = 25; Handles.Label(r.bones[0].position, j.ToString(), style); } j++; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TimeKeeping_System_v1._0._0._2.Model; namespace WindowsFormsApp1 { public partial class FileManager : Form { public static string command; int shiftId; List<EmployeeScheduleDetails> employees = new List<EmployeeScheduleDetails>(); public FileManager() { InitializeComponent(); FirstName.Text = GlobalLogin.FirstName + " " + GlobalLogin.LastName; Department.Text = GlobalLogin.Department; IDno.Text = Convert.ToString(GlobalLogin.EmpiID); //tabPage3.Text = "Daily work schedule"; } private void employeeData_Click(object sender, EventArgs e) { Form1 fm = new Form1(); fm.Show(); this.Hide(); } private void FileManager_Load(object sender, EventArgs e) { InitializeComponent(); FirstName.Text = GlobalLogin.FirstName + " " + GlobalLogin.LastName; Department.Text = GlobalLogin.Department; IDno.Text = Convert.ToString(GlobalLogin.EmpiID); } private void tabPage3_Click(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button3_Click(object sender, EventArgs e) { } private void cbShifts_SelectedIndexChanged(object sender, EventArgs e) { } private void button3_Click_1(object sender, EventArgs e) { DailyWorkShedule dw = new DailyWorkShedule(); dw.Show(); this.Hide(); } private void button2_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } } }
using GesCMS.Application.Common.Interfaces; using GesCMS.Infrastructure.Persistence; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; namespace GesCMS.Infrastructure { public static class DependencyInjection { public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName))); services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>()); return services; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class EnemyView : MonoBehaviour { public float field_of_view; private bool player_in_view; private SphereCollider col; bool playerHit = false; float test = 0; bool gate = true; void Awake () { field_of_view = 45.0f; player_in_view = false; col = transform.GetComponent<SphereCollider>(); } void OnTriggerStay(Collider other) { if(other.transform.tag == "PlayerParent") { //player_in_view = false; Vector3 dir = other.transform.position - transform.position; float view_angle = Vector3.Angle(dir, transform.forward); if (view_angle < field_of_view) { RaycastHit hit; bool bDidHit = Physics.Raycast(transform.position, dir.normalized, out hit, col.radius); if (Physics.Raycast(transform.position, dir.normalized, out hit, col.radius)) { if(hit.collider.gameObject.GetComponent<Transform>().tag == "PlayerParent") { // run towards player or some other action transform.GetComponentInParent<NavMeshAgent>().speed = 6; playerHit = true; transform.GetComponentInParent<Ai>().goal = other.transform.position; } } } } } private void OnTriggerExit(Collider other) { if(other.transform.CompareTag("PlayerParent") && playerHit) { playerHit = false; StartCoroutine(transform.GetComponentInParent<Ai>().CoolDown()); } } }
namespace BettingSystem.Infrastructure.Games.Configurations { using Domain.Common.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; internal class ImageConfiguration : IEntityTypeConfiguration<Image> { public void Configure(EntityTypeBuilder<Image> builder) { builder .HasKey(i => i.Id); builder .Property(i => i.OriginalContent) .IsRequired(); builder .Property(i => i.ThumbnailContent) .IsRequired(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using UseFul.ClientApi.Entidades; using UseFul.Uteis; namespace UseFul.ClientApi { public class ConfiguracaoApi { public string Usuario { get; private set; } private string _senha; private HttpClient _clienteApi; public HttpClient ObterClientApiPadraoNaoAutenticado() { return _clienteApi; } private string ObterUrlApi() { return @"http://localhost:40157/api/"; //string urlEncript = ConfigurationManager.AppSettings["Api"]; //return CryptographyUtil.DecryptSecureString(urlEncript); } public void Configurar() { string url = ObterUrlApi(); //Testes com https _clienteApi = new HttpClient { BaseAddress = new Uri(url) }; _clienteApi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); } public void Autenticar(string usuario, string senha) { try { Usuario = usuario; _senha = senha; var _args = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", Usuario), new KeyValuePair<string, string>("password", _senha), }; MediaTypeFormatterCollection formatters = ConfigurarHttpFormatter(); HttpResponseMessage tokenResponse = _clienteApi.PostAsync("token", new FormUrlEncodedContent(_args)).Result; Token apiToken = tokenResponse.Content.ReadAsAsync<Token>(formatters).Result; _clienteApi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken.AccessToken); if (tokenResponse.StatusCode != HttpStatusCode.OK) { throw CustomErro.Erro("Não possível autenticar o usuário e senha"); } } catch (Exception e) { Console.WriteLine(e); throw CustomErro.Erro(e.Message); } } private static MediaTypeFormatterCollection ConfigurarHttpFormatter() { HttpConfiguration config = new HttpConfiguration(); MediaTypeFormatterCollection formatters = config.Formatters; formatters.Remove(formatters.XmlFormatter); JsonSerializerSettings jsonSettings = formatters.JsonFormatter.SerializerSettings; jsonSettings.Formatting = Formatting.Indented; jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; return formatters; } } }
using System; using System.Linq; using FluentAssertions; using NUnit.Framework; using SpaceHosting.Index.Faiss; namespace SpaceHosting.Index.Tests.Faiss { [Category("RequiresNativeFaissLibrary")] public class FaissIndexTests { // from https://en.wikipedia.org/wiki/Machine_epsilon private const double HalfPrecisionEpsilon = 1e-03; private const double SinglePrecisionEpsilon = 1e-06; private readonly Random random = new Random(); [Test] [Repeat(1000)] public void FindNearest_AddRandomDataPointsAndSearch_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var firstIndexDataPoint = (Id: 1, Vector: RandomVector(2)); var secondIndexDataPoint = (Id: 2, Vector: RandomVector(2)); var indexDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPoint, secondIndexDataPoint, }; index.AddBatch(indexDataPoints); var queryDataPoints = indexDataPoints.Select(x => x.Vector).ToArray(); var foundDataPoints = index.FindNearest(queryDataPoints, 2); var firstQueryFoundDataPoints = foundDataPoints[0]; Assert.AreEqual(firstIndexDataPoint.Id, firstQueryFoundDataPoints[0].Id); Assert.AreEqual(0.0, firstQueryFoundDataPoints[0].Distance, SinglePrecisionEpsilon); Assert.AreEqual(secondIndexDataPoint.Id, firstQueryFoundDataPoints[1].Id); Assert.IsTrue(!0.0.Equals(firstQueryFoundDataPoints[1].Distance)); var secondQueryFoundDataPoints = foundDataPoints[1]; Assert.AreEqual(secondIndexDataPoint.Id, secondQueryFoundDataPoints[0].Id); Assert.AreEqual(0.0, secondQueryFoundDataPoints[0].Distance, SinglePrecisionEpsilon); Assert.AreEqual(firstIndexDataPoint.Id, secondQueryFoundDataPoints[1].Id); Assert.IsTrue(!0.0.Equals(secondQueryFoundDataPoints[1].Distance)); } [Test] public void FindNearest_AddStaticDataPoints_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var firstIndexDataPoint = (Id: 1, Vector: Vector(1.0, 2.0)); var secondIndexDataPoint = (Id: 2, Vector: Vector(10.0, 20.0)); var indexDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPoint, secondIndexDataPoint, }; index.AddBatch(indexDataPoints); var queryDataPoint = Vector(2.0, 3.0); var queryDataPoints = new[] {queryDataPoint}; var foundDataPoints = index.FindNearest(queryDataPoints, 2); var firstQueryFoundDataPoints = foundDataPoints[0]; Assert.AreEqual(firstIndexDataPoint.Id, firstQueryFoundDataPoints[0].Id); Assert.AreEqual(2.0, firstQueryFoundDataPoints[0].Distance, SinglePrecisionEpsilon); Assert.AreEqual(secondIndexDataPoint.Id, firstQueryFoundDataPoints[1].Id); Assert.AreEqual(353.0, firstQueryFoundDataPoints[1].Distance, SinglePrecisionEpsilon); } [Test] public void FindNearest_AddAndDeleteStaticDataPointsAndSearch_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var firstIndexDataPoint = (Id: 1, Vector: Vector(1.0, 2.0)); var secondIndexDataPoint = (Id: 2, Vector: Vector(10.0, 20.0)); var thirdIndexDataPoint = (Id: 2, Vector: Vector(11.0, 21.0)); var indexDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPoint, secondIndexDataPoint, thirdIndexDataPoint }; index.AddBatch(indexDataPoints); index.DeleteBatch(new long[] {firstIndexDataPoint.Id}); var queryDataPoint = Vector(2.0, 3.0); var queryDataPoints = new[] {queryDataPoint}; var foundDataPoints = index.FindNearest(queryDataPoints, 2); var firstQueryFoundDataPoints = foundDataPoints[0]; Assert.AreEqual(secondIndexDataPoint.Id, firstQueryFoundDataPoints[0].Id); Assert.AreEqual(353.0, firstQueryFoundDataPoints[0].Distance, SinglePrecisionEpsilon); Assert.AreEqual(thirdIndexDataPoint.Id, firstQueryFoundDataPoints[1].Id); Assert.AreEqual(405.0, firstQueryFoundDataPoints[1].Distance, SinglePrecisionEpsilon); } [Test] public void FindNearest_AddAndUpdateStaticDataPointsAndSearch_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var firstIndexDataPoint = (Id: 1, Vector: Vector(1.0, 2.0)); var secondIndexDataPoint = (Id: 2, Vector: Vector(10.0, 20.0)); var thirdIndexDataPoint = (Id: 3, Vector: Vector(11.0, 21.0)); var indexDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPoint, secondIndexDataPoint, thirdIndexDataPoint }; var firstIndexDataPointUpdate = (Id: 1, Vector: Vector(5.0, 6.0)); var updateDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPointUpdate }; index.AddBatch(indexDataPoints); index.DeleteBatch(new long[] {firstIndexDataPoint.Id}); index.AddBatch(updateDataPoints); var queryDataPoint = Vector(2.0, 3.0); var queryDataPoints = new[] {queryDataPoint}; var foundDataPoints = index.FindNearest(queryDataPoints, 2); var firstFoundDataPoint = foundDataPoints[0][0]; firstFoundDataPoint.Id.Should().Be(firstIndexDataPointUpdate.Id); firstFoundDataPoint.Vector.Should().BeEquivalentTo(firstIndexDataPointUpdate.Vector); firstFoundDataPoint.Distance.Should().BeApproximately(18.0, SinglePrecisionEpsilon); var secondFoundDataPoint = foundDataPoints[0][1]; secondFoundDataPoint.Id.Should().Be(secondIndexDataPoint.Id); secondFoundDataPoint.Vector.Should().BeEquivalentTo(secondIndexDataPoint.Vector); secondFoundDataPoint.Distance.Should().BeApproximately(353.0, SinglePrecisionEpsilon); } [Test] public void FindNearest_InitEmptyDataPointsAndSearch_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var foundDataPoints = index.FindNearest(new[] {Vector(5.0, 6.0)}, 2); foundDataPoints[0].Should().BeEmpty(); } [Test] public void FindNearest_AddAndClearStaticDataPointsAndSearch_FlatL2() { using var index = new FaissIndex(Algorithms.FaissIndexTypeFlat, FaissMetricType.METRIC_L2, 2); var firstIndexDataPoint = (Id: 1, Vector: Vector(1.0, 2.0)); var secondIndexDataPoint = (Id: 2, Vector: Vector(10.0, 20.0)); var indexDataPoints = new (long Id, DenseVector Vector)[] { firstIndexDataPoint, secondIndexDataPoint, }; index.AddBatch(indexDataPoints); index.DeleteBatch(indexDataPoints.Select(x => x.Id).ToArray()); var foundDataPoints = index.FindNearest(new[] {Vector(5.0, 6.0)}, 2); foundDataPoints[0].Should().BeEmpty(); } private DenseVector RandomVector(int dimensionCount) { var coordinates = Enumerable.Range(0, dimensionCount).Select(_ => random.NextDouble()).ToArray(); return Vector(coordinates); } private static DenseVector Vector(params double[] coordinates) { return new DenseVector(coordinates); } } }
using GeneralStore.MVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace GeneralStore.MVC.Controllers { public class TransactionController : Controller { private ApplicationDbContext _db = new ApplicationDbContext(); // GET: Transaction public ActionResult Index() { List<Transaction> transactionList = _db.Transactions.ToList(); List<Transaction> orderedList = transactionList.OrderByDescending(t => t.DateOfTransaction).ToList(); return View(orderedList); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Transaction transaction) { Product product = _db.Products.Find(transaction.ProductId); if (product.InventoryCount < transaction.Quantity) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (ModelState.IsValid) { _db.Transactions.Add(transaction); } _db.SaveChanges(); return RedirectToAction("Index"); } } }
using System.Collections.Generic; using System.Linq; namespace EPI.Sorting { /// <summary> /// For arrays where the number of distinct elements is very low compared to the size, an efficient /// approach to sorting is the count the occurences of each distinct element and write them in sorted order. /// You are given an array of objects.Each object has a field that is to be treated as a key. Rearrange the /// elements of the array so that objects with equal keys appear together. the order in which distinct keys /// appear is not imporant /// </summary> public static class CountingSort { public class Element { public int key; public string name; public override int GetHashCode() { return key.GetHashCode(); } public override bool Equals(object obj) { Element element = obj as Element; if (null != element) { return key.Equals(element.key) && name.Equals(element.name); } return false; } }; public static void ReOrderArrayByElementKeys(Element[] array) { // first count the occurences of each key Dictionary<int, int> elementKeyCount = new Dictionary<int, int>(); foreach (Element element in array) { if (!elementKeyCount.ContainsKey(element.key)) { elementKeyCount.Add(element.key, 0); } elementKeyCount[element.key]++; } // We can optimize by reordering the array in-place // based on the occurence count, determine offset for each key subarray Dictionary<int, int> keyOffset = new Dictionary<int, int>(); int offset = 0; foreach (int key in elementKeyCount.Keys) { keyOffset.Add(key, offset); offset += elementKeyCount[key]; } // now perform in-place swap for each subarray based on it's offset while (keyOffset.Count > 0) { var fromKeyOffsetPair = keyOffset.First(); var toOffsetKey = array[fromKeyOffsetPair.Value].key; // swap from and to Swap(array, fromKeyOffsetPair.Value, keyOffset[toOffsetKey]); // decrement key count --elementKeyCount[toOffsetKey]; if (elementKeyCount[toOffsetKey] > 0) { // we still have more occurences of this key, increment offset ++keyOffset[toOffsetKey]; } else { // no more occurences of this key left to swapped, clean up keyOffset.Remove(toOffsetKey); } } // when all key offset subarray have been swapped } private static void Swap(Element[] array, int from, int to) { if (from != to) { var temp = array[from]; array[from] = array[to]; array[to] = temp; } } } }
namespace DaDo.Command.Common { public class GlobalOptions { public bool Simulate { get; set; } public string OutputFolder { get; set; } } }
namespace MeeToo.Api.Models { public class OptionCreationModel { public string Text { get; set; } public bool IsCorrect { get; set; } } }
using System; namespace AW.Data.Domain { public class Request : Entity<long> { public int ClientPlatformId { get; set; } public decimal Amount { get; set; } public string Description { get; set; } public string AccountNo { get; set; } public string AccountHolder { get; set; } public string AccountNumber { get; set; } public string BankName { get; set; } public DateTime RequestDate { get; set; } public string BranchName { get; set; } public string ProvinceBank { get; set; } public string CityBank { get; set; } public string SwiftCode { get; set; } public int Status { get; set; } public bool IsDeleted { get; set; } public DateTime? DeletedDate { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace TestShop.Application.ServiceInterfaces { public interface IEmailSender { Task SendEmailAsync(string email, string subject, string htmlMessage); } }
using System.Collections.Generic; namespace useSOLIDin { interface IFileReader { void GetAllData(string fileName, List<Level> levels); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="APredefinedBenchmark.cs"> // Copyright (c) 2020 Johannes Deml. All rights reserved. // </copyright> // <author> // Johannes Deml // public@deml.io // </author> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Threading; using BenchmarkDotNet.Attributes; namespace NetworkBenchmark { public abstract class APredefinedBenchmark { public abstract int Clients { get; set; } public abstract int MessageTarget { get; set; } protected abstract BenchmarkMode Mode { get; } protected abstract NetworkLibrary LibraryTarget { get; } private INetworkBenchmark libraryImpl; [GlobalSetup] public void PrepareBenchmark() { var config = BenchmarkCoordinator.Config; config.Benchmark = Mode; config.Clients = Clients; config.Library = LibraryTarget; Console.Write(config.ToFormattedString()); libraryImpl = INetworkBenchmark.CreateNetworkBenchmark(LibraryTarget); BenchmarkCoordinator.PrepareBenchmark(libraryImpl); } protected long RunBenchmark() { var statistics = BenchmarkCoordinator.BenchmarkStatistics; BenchmarkCoordinator.StartBenchmark(libraryImpl); var receivedMessages = Interlocked.Read(ref statistics.MessagesClientReceived); while (receivedMessages < MessageTarget) { Thread.Sleep(1); receivedMessages = Interlocked.Read(ref statistics.MessagesClientReceived); } BenchmarkCoordinator.StopBenchmark(libraryImpl); return receivedMessages; } [IterationCleanup] public void CleanupIteration() { // Wait for messages from previous benchmark to be all sent // TODO this can be done in a cleaner way Thread.Sleep(100); } [GlobalCleanup] public void CleanupBenchmark() { BenchmarkCoordinator.CleanupBenchmark(libraryImpl); } } }
using DigitalFormsSteamLeak.Entity.Models; using DigitalFormsSteamLeak.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DigitalFormsSteamLeak.Business { public class PortalInsulationRemoveSessionFactory : ILeakFactory<PortalInsulationRemoveSession> { protected LeakDbHelper leakDB { get; set; } public PortalInsulationRemoveSessionFactory() { leakDB = new LeakDbHelper(); } public int Create(PortalInsulationRemoveSession entity) { return leakDB.Save<PortalInsulationRemoveSession>(entity); } public int Update(PortalInsulationRemoveSession entity) { return leakDB.Update<PortalInsulationRemoveSession>(entity); } public IQueryable<PortalInsulationRemoveSession> GetAll() { return leakDB.GetDetails<PortalInsulationRemoveSession>(); } public IQueryable<PortalInsulationRemoveSession> GetById(Guid? id) { return GetAll().Where(i => i.RemoveInsulationId == id); } } }
using Alps.Domain.ProductMgr; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using Alps.Web.Infrastructure; namespace Alps.Web.Models.ProductMgr { public class ProductEditModel { [Display(Name = "物料名")] public string Name { get; set; } //public Guid CatagoryID { get; set; } //[Display(Name = "类别")]; //public virtual Catagory Catagory { get; set; } [Display(Name = "全名")] public string FullName { get; set; } [Display(Name = "简介")] public string ShortDiscription { get; set; } [Display(Name = "详细介绍")] public string FullDiscription { get; set; } [Display(Name = "包装数")] public int PackingQuantity { get; set; } [Display(Name = "理论重量")] public decimal Weight { get; set; } //public ProductGrade ProductGrade { get; set; } [Display(Name = "删除否")] public bool Deleted { get; set; } [Display(Name = "计价方式")] public PricingMethod PricingMethod { get; set; } [Display(Name = "定价")] public decimal ListPrice { get; set; } public IList<AlpsSelectListItem<int>> PricingMethodSelectList { get; set; } //public } }
using CESI_Afficheur.BDD; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace CESI_Afficheur.Model { public class Actualite { public static MyDatabase MyDatabase { get; set; } public int Actualite_Id { get; set; } public string Libelle { get; set; } public string Img { get; set; } public DateTime Date { get; set; } public static void AddActualite(string texte, DateTime date,string path) { if (checkIfActuExist(texte,date)) { string query = "INSERT INTO actualite (libelle,date,img) VALUES ('" + texte.Replace("'", "''") + "', '" + date.Date.ToString().Substring(0, 10) + "','"+ path + "');"; MyDatabase = new MyDatabase(); if (MyDatabase.OpenConnection() == true) { MySqlConnection connection = MyDatabase.getCon(); connection.Open(); //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command cmd.ExecuteNonQuery(); MyDatabase.CloseConnection(); App.Server.NeddUpdate = true; MessageBox.Show("Succès", "Information", MessageBoxButton.OK, MessageBoxImage.Information); } } else { MessageBox.Show("Cette actualité existe déjà !", "Avertissement", MessageBoxButton.OK, MessageBoxImage.Information); } } public static void EditActu(int Id, string texte, DateTime date) { if (checkIfActuExist(texte,date)) { string query = "UPDATE actualite SET libelle = '" + texte.Replace("'", "''") + "', date = ' " + date.Date +" ' WHERE actualite_id= " + Id + ";"; MyDatabase = new MyDatabase(); if (MyDatabase.OpenConnection() == true) { MySqlConnection connection = MyDatabase.getCon(); connection.Open(); //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command cmd.ExecuteNonQuery(); MyDatabase.CloseConnection(); App.Server.NeddUpdate = true; } } else { MessageBox.Show("Cette actualité existe déjà !", "Avertissement", MessageBoxButton.OK, MessageBoxImage.Information); } } public static void DeleteActu(int Id) { string query = "DELETE FROM actualite WHERE actualite_id = " + Id + ";"; MyDatabase = new MyDatabase(); if (MyDatabase.OpenConnection() == true) { MySqlConnection connection = MyDatabase.getCon(); connection.Open(); //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Execute command cmd.ExecuteNonQuery(); MyDatabase.CloseConnection(); App.Server.NeddUpdate = true; } } public static List<Actualite> GetActu() { string query = "SELECT * FROM actualite"; MyDatabase = new MyDatabase(); //Create a list to store the result List<Actualite> list = new List<Actualite>(); //Open connection if (MyDatabase.OpenConnection() == true) { MySqlConnection connection = MyDatabase.getCon(); connection.Open(); //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list while (dataReader.Read()) { Actualite actualite = new Actualite(); actualite.Actualite_Id = (int)dataReader["actualite_Id"]; actualite.Libelle = (string)dataReader["libelle"]; actualite.Date = DateTime.Parse((string)dataReader["date"]); actualite.Img = (string)dataReader["img"]; list.Add(actualite); } //close Data Reader dataReader.Close(); //close Connection MyDatabase.CloseConnection(); //return list to be displayed return list; } else { return list; } } public static bool checkIfActuExist(string texte, DateTime date) { string query = "SELECT * FROM actualite WHERE libelle = '" + texte.Replace("'","''") +"' AND date = '" + date.Date + "'"; MyDatabase = new MyDatabase(); if (MyDatabase.OpenConnection() == true) { MySqlConnection connection = MyDatabase.getCon(); connection.Open(); //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list while (dataReader.Read()) { return false; } //close Data Reader dataReader.Close(); //close Connection MyDatabase.CloseConnection(); return true; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestWebApp.Database.Models { public enum Test { A, B, C } public class Blog { public int Id { get; set; } public bool Bool { get; set; } //public bool[] Bools { get; set; } public byte Byte { get; set; } public byte[] Bytes { get; set; } public sbyte Sbyte { get; set; } //public sbyte[] Sbytes { get; set; } public char Char { get; set; } //public char[] Chars { get; set; } public decimal Decimal { get; set; } //public decimal[] Decimals { get; set; } public double Double { get; set; } //public double[] Doubles { get; set; } public float Float { get; set; } //public float[] Floats { get; set; } public int Int { get; set; } //public int[] Ints { get; set; } public uint UInt { get; set; } //public uint[] UInts { get; set; } public long Long { get; set; } //public long[] Longs { get; set; } public ulong ULong { get; set; } //public ulong[] ULongs { get; set; } //public object Object { get; set; } //public object[] Objects { get; set; } public short Short { get; set; } //public short[] Shorts { get; set; } public ushort UShort { get; set; } //public ushort[] UShorts { get; set; } public string String { get; set; } public string[] Strings { get; set; } public Test TestEnum { get; set; } } public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } } public class TestView { public int Id { get; set; } public string Name { get; set; } public bool Enabled { get; set; } } }
using UnityEngine; public class BaseClueTextHoler : MonoBehaviour { public virtual string GetDefaultClueText(KeyCode ActionKey) { return "Press " + ActionKey; } public virtual string GetExecutedClueText(KeyCode ActionKey) { return "Press " + ActionKey; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AxisPosCore; using AxisPosCore.Common; using KartObjects; using System.Threading; using System.Globalization; namespace AxisPosCore { public class ChangePriceActionAxecutor:POSActionExecutor { public ChangePriceActionAxecutor(POSActionMnemonic action) : base(action) { ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification); } public ChangePriceActionAxecutor() { ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification); } protected override void InnerExecute(PosCore model, params object[] args) { string str = args[0].ToString(); str = str.Replace(".", decimalSeparator).Replace(",", decimalSeparator); decimal Price = 0; if (!Decimal.TryParse(str, out Price)) throw new POSException("Неправильный формат вводимых данных!"); if (Price < 0) throw new POSException("Неправильный формат вводимых данных!"); if (!DataDictionary.GetParamBoolValue(PosParameterType.EnableZeroPriceSale)) if (Price == 0) throw new POSException("Нельзя продать по нулевой цене!"); POSEnvironment.CurrReceipt.ChangePrice(model.RegistrationState.CurrPos,Price,DataDictionary.SPosParameters[PosParameterType.MaxReceiptSum].decimalValue); model.PosEnvironment.SaveCurrReceipt(); POSEnvironment.SendEvent(TypeExtEvent.eeChangePrice,POSEnvironment.CurrReceipt, model.RegistrationState.CurrPos); POSEnvironment.Log.WriteToLog("Изменение цены. Позиция " + model.RegistrationState.CurrPos +" новое количество " + str); model.RegistrationState.ChangeState(); } } }
using System; using System.Collections.Generic; namespace Crystal.Plot2D.Common { public sealed class CollectionRemoveAction<T> : UndoAction { public CollectionRemoveAction(IList<T> collection, T item, int index) { if (item == null) { throw new ArgumentNullException("addedItem"); } Collection = collection ?? throw new ArgumentNullException("collection"); Item = item; Index = index; } public IList<T> Collection { get; } public T Item { get; } public int Index { get; } public override void Do() => Collection.Remove(Item); public override void Undo() => Collection.Insert(Index, Item); } }
using CleanArchitecture.Aplicacao.Interfaces; using CleanArchitecture.Aplicacao.Servicos; using CleanArchitecture.Dominio.Interfaces; using CleanArchitecture.Infra.Dados.Contextos; using CleanArchitecture.Infra.Dados.Repositorios; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CleanArchitecture.IoC.Extensoes { public static class ServiceCollectionExtensao { public static IServiceCollection ConfigurarPersistencia(this IServiceCollection colecaoServicos, IConfiguration configuracao) { colecaoServicos.AddDbContext<AplicacaoBDContexto>(opcoes => { opcoes.UseMySql(configuracao.GetConnectionString("CleanArchitecture")); }); colecaoServicos.AddScoped<IProdutoServico, ProdutoServico>(); colecaoServicos.AddScoped<IProdutoRepositorio, ProdutoRepositorio>(); return colecaoServicos; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Hits : MissionComponent { private DialogueScript dialogue; private TMPro.TextMeshProUGUI timeText; private TMPro.TextMeshProUGUI hitsCount; public override void OnSucceed() { Debug.Log("suceed"); finish = true; timeText.text = "0"; countdownText.GetComponent<TMPro.TextMeshProUGUI>().text = "Finish"; countdownText.GetComponent<TMPro.TextMeshProUGUI>().enabled = true; timeFinished = time; time = maxFinish; Time.timeScale = 0; } // Start is called before the first frame update void Start() { Debug.Log( "StartHits" ); dialogue = this.GetComponent<DialogueScript>(); dialogue.ChangeLine("hits"); dialogue.StartWriting(); time = maxTime; type = MissionType.Hits; ball = GameObject.Find("ball"); timeText = GameObject.Find("Time").GetComponent<TMPro.TextMeshProUGUI>(); countdownText = GameObject.Find("Countdown"); countdownText.GetComponent<TMPro.TextMeshProUGUI>().text = ""; hitsCount = GameObject.Find("HitsCount").GetComponent<TMPro.TextMeshProUGUI>(); hitsCount.enabled = true; missionLabel = GameObject.Find("MissionLabel").GetComponent<TMPro.TextMeshProUGUI>(); missionLabel.text = "HITS"; ball.GetComponent<BallController>().ChangeToHits(); maxTime = 30f; } public override void ChangeToNext() { this.GetComponent<MissionController>().FinishMission(true, timeFinished); } // Update is called once per frame void Update() { if (started) { time -= Time.deltaTime; hitsCount.text = ball.GetComponent<BallController>().hits + ""; timeText.text = "Time: " + Math.Round(time, 2); if (time <= maxTime - 1) { var text = countdownText.GetComponent<TMPro.TextMeshProUGUI>(); text.enabled = false; text.text = ""; } if (time <= 0) { time = 0; started = false; OnSucceed(); } } else if (finish) { if (time <= 0) { Debug.Log("Finish Change Line"); if (!finishDialog) { dialogue.ChangeLine("hits_finish"); dialogue.StartWriting(); } finishDialog = true; } else { time -= Time.unscaledDeltaTime; } } else { if (countdown) { time -= Time.unscaledDeltaTime; var text = countdownText.GetComponent<TMPro.TextMeshProUGUI>(); if (Math.Round(time) < 1) { text.text = "GO"; Time.timeScale = 1; countdown = false; started = true; time = maxTime; return; } else { text.text = (Math.Round(time)) + ""; } return; } Time.timeScale = 0; } } public override void OnTarget() { time = 0; started = false; OnSucceed(); } }
#r "Newtonsoft.Json" #load "..\shared\csomHelper.csx" using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Utilities; using System.Net; using System.Text; using Newtonsoft.Json; public class CreateSpoSubWeb { public string scUrl {get; set;} public string title {get; set;} public string description {get; set;} public string language { get; set;} public string url {get; set;} public string useSamePermissionsAsParentSite { get; set;} public string template {get; set;} } public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string jsonContent = await req.Content.ReadAsStringAsync(); var pl = JsonConvert.DeserializeObject<CreateSpoSubWeb>(jsonContent); log.Info($"Sub Web Title requested is: {pl.title} and the description is: {pl.description}"); //ClientResult<string> result; try { // Get the SharePoint Context using (var ctx = await csomHelper.GetClientContext(pl.scUrl)) { WebCollection collWeb = ctx.Web.Webs; WebCreationInformation webCreationInfo = new WebCreationInformation(); webCreationInfo.Title = pl.title; webCreationInfo.Description = pl.description; webCreationInfo.Language = 1033; webCreationInfo.Url = pl.url; webCreationInfo.UseSamePermissionsAsParentSite = true; webCreationInfo.WebTemplate = pl.template; Web oNewWebsite = collWeb.Add(webCreationInfo); //result = oNewWebsite; ctx.ExecuteQuery(); } // Return item URL or error return pl.title == null ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a path on the query string or in the request body" + req.RequestUri) : req.CreateResponse(HttpStatusCode.OK); } catch (Exception ex) { string message = ex.Message + "\n" + ex.StackTrace; return req.CreateResponse(HttpStatusCode.BadRequest, "ERROR FOUND: " + message); } }
namespace AbstractFactoryPattern.Abstractions { public interface IGredient { string Name { get; } } }
namespace RosPurcell.Web.Helpers.Extensions { using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; public static class StringExtensions { public static IHtmlString ConvertLineBreaksToHtml(this string input) { if (string.IsNullOrEmpty(input)) { return null; } input = Regex.Replace(input, @"\r\n?|\n", "<br/>"); return new MvcHtmlString(input); } } }
namespace _06.TruckTour { using System; using System.Collections.Generic; using System.Linq; public class TruckTour { public static void Main() { int numberGasStation = int.Parse(Console.ReadLine()); Queue<Station> stationsQueue = new Queue<Station>(); for (int i = 0; i < numberGasStation; i++) { int[] inpInts = Console.ReadLine().Split(new char[] { ' ' }).Select(int.Parse).ToArray(); Station station = new Station { Gas = inpInts[0], Distance = inpInts[1] }; stationsQueue.Enqueue(station); } int gasTank = 0; Boolean isFound = false; int index; while (true) { Station currStation = stationsQueue.Dequeue(); gasTank += currStation.Gas; stationsQueue.Enqueue(currStation); Station firstStation = currStation; while (gasTank >= currStation.Distance) { gasTank -= currStation.Distance; currStation = stationsQueue.Dequeue(); stationsQueue.Enqueue(currStation); gasTank += currStation.Gas; if (firstStation == currStation) { isFound = true; break; } } if (isFound) { index = currStation.Id; break; } gasTank = 0; } Console.WriteLine(index); } } public class Station { private static int counter = -1; public Station() { this.Id = System.Threading.Interlocked.Increment(ref counter); } public int Id { get; } public int Distance { get; set; } public int Gas { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DummyCamera : MonoBehaviour { [Tooltip("Camera speed is lower when the value goes down.")] public float speedLimiter = 5f; public float rotationSpeed = 1f; private float rotationSpeedMultiplier = 50; void Update() { transform.Translate(new Vector3(Input.GetAxis("Horizontal") * (speedLimiter / 100), 0, Input.GetAxis("Vertical") * (speedLimiter / 100))); Vector3 rotation = transform.eulerAngles; if (Input.GetKey(KeyCode.Q)) { rotation.y -= rotationSpeed * rotationSpeedMultiplier * Time.deltaTime; } if (Input.GetKey(KeyCode.E)) { rotation.y += rotationSpeed * rotationSpeedMultiplier * Time.deltaTime; } if (Input.GetKey(KeyCode.R)) { rotation.x -= rotationSpeed * rotationSpeedMultiplier * Time.deltaTime; } if (Input.GetKey(KeyCode.F)) { rotation.x += rotationSpeed * rotationSpeedMultiplier * Time.deltaTime; } transform.eulerAngles = rotation; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using MediatR; using ProductService.Application.Commands; using ProductService.Application.Dtos; using ProductService.Application.Queries; namespace ProductsService.Api.Controllers { [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly IMediator _mediator; public ProductController(IMediator mediator) { _mediator = mediator; } [HttpPost] public async Task<ActionResult> Post([FromBody] CreateProductCommand command) { var result = await _mediator.Send(command); if (!string.IsNullOrEmpty(result)) { return Ok(result); } else { return BadRequest(); } } [HttpGet] [Route("{id}")] public async Task<ActionResult<ProductDTO>> Get(string id) { if (string.IsNullOrEmpty(id)) { return BadRequest("invalid Id provided"); } var query = new GetProductQuery() { ProductId = id }; try { var result = await _mediator.Send(query); if (result != null) { return Ok(result); } else { return BadRequest("Product could not be found"); } } catch { return BadRequest("Error Retrieving Product"); } } } }
using NumSharp; using System; using System.Collections.Generic; using System.Text; using Tensorflow; using static Tensorflow.Binding; namespace TensorFlowNET.Examples.ImageProcessing.YOLO { public class YOLOv3 { Config cfg; Tensor trainable; Tensor input_data; Dictionary<int, string> classes; int num_class; NDArray strides; NDArray anchors; int anchor_per_scale; float iou_loss_thresh; string upsample_method; Tensor conv_lbbox; Tensor conv_mbbox; Tensor conv_sbbox; Tensor pred_sbbox; Tensor pred_mbbox; Tensor pred_lbbox; public YOLOv3(Config cfg_, Tensor input_data_, Tensor trainable_) { cfg = cfg_; input_data = input_data_; trainable = trainable_; classes = Utils.read_class_names(cfg.YOLO.CLASSES); num_class = len(classes); strides = np.array(cfg.YOLO.STRIDES); anchors = Utils.get_anchors(cfg.YOLO.ANCHORS); anchor_per_scale = cfg.YOLO.ANCHOR_PER_SCALE; iou_loss_thresh = cfg.YOLO.IOU_LOSS_THRESH; upsample_method = cfg.YOLO.UPSAMPLE_METHOD; (conv_lbbox, conv_mbbox, conv_sbbox) = __build_nework(input_data); tf_with(tf.variable_scope("pred_sbbox"), scope => { pred_sbbox = decode(conv_sbbox, anchors[0], strides[0]); }); tf_with(tf.variable_scope("pred_mbbox"), scope => { pred_mbbox = decode(conv_mbbox, anchors[1], strides[1]); }); tf_with(tf.variable_scope("pred_lbbox"), scope => { pred_lbbox = decode(conv_lbbox, anchors[2], strides[2]); }); } private (Tensor, Tensor, Tensor) __build_nework(Tensor input_data) { Tensor route_1, route_2; (route_1, route_2, input_data) = backbone.darknet53(input_data, trainable); input_data = common.convolutional(input_data, new[] { 1, 1, 1024, 512 }, trainable, "conv52"); input_data = common.convolutional(input_data, new[] { 3, 3, 512, 1024 }, trainable, "conv53"); input_data = common.convolutional(input_data, new[] { 1, 1, 1024, 512 }, trainable, "conv54"); input_data = common.convolutional(input_data, new[] { 3, 3, 512, 1024 }, trainable, "conv55"); input_data = common.convolutional(input_data, new[] { 1, 1, 1024, 512 }, trainable, "conv56"); var conv_lobj_branch = common.convolutional(input_data, new[] { 3, 3, 512, 1024 }, trainable, name: "conv_lobj_branch"); var conv_lbbox = common.convolutional(conv_lobj_branch, new[] { 1, 1, 1024, 3 * (num_class + 5) }, trainable: trainable, name: "conv_lbbox", activate: false, bn: false); input_data = common.convolutional(input_data, new[] { 1, 1, 512, 256 }, trainable, "conv57"); input_data = common.upsample(input_data, name: "upsample0", method: upsample_method); tf_with(tf.variable_scope("route_1"), delegate { input_data = tf.concat(new[] { input_data, route_2 }, axis: -1); }); input_data = common.convolutional(input_data, new[] { 1, 1, 768, 256 }, trainable, "conv58"); input_data = common.convolutional(input_data, new[] { 3, 3, 256, 512 }, trainable, "conv59"); input_data = common.convolutional(input_data, new[] { 1, 1, 512, 256 }, trainable, "conv60"); input_data = common.convolutional(input_data, new[] { 3, 3, 256, 512 }, trainable, "conv61"); input_data = common.convolutional(input_data, new[] { 1, 1, 512, 256 }, trainable, "conv62"); var conv_mobj_branch = common.convolutional(input_data, new[] { 3, 3, 256, 512 }, trainable, name: "conv_mobj_branch"); conv_mbbox = common.convolutional(conv_mobj_branch, new[] { 1, 1, 512, 3 * (num_class + 5) }, trainable: trainable, name: "conv_mbbox", activate: false, bn: false); input_data = common.convolutional(input_data, new[] { 1, 1, 256, 128 }, trainable, "conv63"); input_data = common.upsample(input_data, name: "upsample1", method: upsample_method); tf_with(tf.variable_scope("route_2"), delegate { input_data = tf.concat(new[] { input_data, route_1 }, axis: -1); }); input_data = common.convolutional(input_data, new[] { 1, 1, 384, 128 }, trainable, "conv64"); input_data = common.convolutional(input_data, new[] { 3, 3, 128, 256 }, trainable, "conv65"); input_data = common.convolutional(input_data, new[] { 1, 1, 256, 128 }, trainable, "conv66"); input_data = common.convolutional(input_data, new[] { 3, 3, 128, 256 }, trainable, "conv67"); input_data = common.convolutional(input_data, new[] { 1, 1, 256, 128 }, trainable, "conv68"); var conv_sobj_branch = common.convolutional(input_data, new[] { 3, 3, 128, 256 }, trainable, name: "conv_sobj_branch"); conv_sbbox = common.convolutional(conv_sobj_branch, new[] { 1, 1, 256, 3 * (num_class + 5) }, trainable: trainable, name: "conv_sbbox", activate: false, bn: false); return (conv_lbbox, conv_mbbox, conv_sbbox); } private Tensor decode(Tensor conv_output, NDArray anchors, int stride) { var conv_shape = tf.shape(conv_output); var batch_size = conv_shape[0]; var output_size = conv_shape[1]; anchor_per_scale = len(anchors); conv_output = tf.reshape(conv_output, (1, 1)/*new object[] { batch_size, output_size, output_size, anchor_per_scale, 5 + num_class }*/); var conv_raw_dxdy = conv_output[":", ":", ":", ":", "0:2"]; var conv_raw_dwdh = conv_output[":", ":", ":", ":", "2:4"]; var conv_raw_conf = conv_output[":", ":", ":", ":", "4:5"]; var conv_raw_prob = conv_output[":", ":", ":", ":", "5:"]; var y = tf.tile(tf.range(output_size, dtype: tf.int32)[Slice.All, tf.newaxis], new object[] { 1, output_size }); var x = tf.tile(tf.range(output_size, dtype: tf.int32)[tf.newaxis, Slice.All], new object[] { output_size, 1 }); var xy_grid = tf.concat(new[] { x[Slice.All, Slice.All, tf.newaxis], y[Slice.All, Slice.All, tf.newaxis] }, axis: -1); xy_grid = tf.tile(xy_grid[tf.newaxis, Slice.All, Slice.All, tf.newaxis, Slice.All], new object[] { batch_size, 1, 1, anchor_per_scale, 1 }); xy_grid = tf.cast(xy_grid, tf.float32); var pred_xy = (tf.sigmoid(conv_raw_dxdy) + xy_grid) * stride; var pred_wh = (tf.exp(conv_raw_dwdh) * anchors) * stride; var pred_xywh = tf.concat(new[] { pred_xy, pred_wh }, axis: -1); var pred_conf = tf.sigmoid(conv_raw_conf); var pred_prob = tf.sigmoid(conv_raw_prob); return tf.concat(new[] { pred_xywh, pred_conf, pred_prob }, axis: -1); } public (Tensor, Tensor, Tensor) compute_loss(Tensor label_sbbox, Tensor label_mbbox, Tensor label_lbbox, Tensor true_sbbox, Tensor true_mbbox, Tensor true_lbbox) { Tensor giou_loss = null, conf_loss = null, prob_loss = null; (Tensor, Tensor, Tensor) loss_sbbox = (null, null, null); (Tensor, Tensor, Tensor) loss_mbbox = (null, null, null); (Tensor, Tensor, Tensor) loss_lbbox = (null, null, null); tf_with(tf.name_scope("smaller_box_loss"), delegate { loss_sbbox = loss_layer(conv_sbbox, pred_sbbox, label_sbbox, true_sbbox, anchors: anchors[0], stride: strides[0]); }); tf_with(tf.name_scope("medium_box_loss"), delegate { loss_mbbox = loss_layer(conv_mbbox, pred_mbbox, label_mbbox, true_mbbox, anchors: anchors[1], stride: strides[1]); }); tf_with(tf.name_scope("bigger_box_loss"), delegate { loss_lbbox = loss_layer(conv_lbbox, pred_lbbox, label_lbbox, true_lbbox, anchors: anchors[2], stride: strides[2]); }); tf_with(tf.name_scope("giou_loss"), delegate { giou_loss = loss_sbbox.Item1 + loss_mbbox.Item1 + loss_lbbox.Item1; }); tf_with(tf.name_scope("conf_loss"), delegate { conf_loss = loss_sbbox.Item2 + loss_mbbox.Item2 + loss_lbbox.Item2; }); tf_with(tf.name_scope("prob_loss"), delegate { prob_loss = loss_sbbox.Item3 + loss_mbbox.Item3 + loss_lbbox.Item3; }); return (giou_loss, conf_loss, prob_loss); } public (Tensor, Tensor, Tensor) loss_layer(Tensor conv, Tensor pred, Tensor label, Tensor bboxes, NDArray anchors, int stride) { var conv_shape = tf.shape(conv); var batch_size = conv_shape[0]; var output_size = conv_shape[1]; var input_size = stride * output_size; conv = tf.reshape(conv, (1, 1)/*new object[] {batch_size, output_size, output_size, anchor_per_scale, 5 + num_class }*/); var conv_raw_conf = conv[":", ":", ":", ":", "4:5"]; var conv_raw_prob = conv[":", ":", ":", ":", "5:"]; var pred_xywh = pred[":", ":", ":", ":", "0:4"]; var pred_conf = pred[":", ":", ":", ":", "4:5"]; var label_xywh = label[":", ":", ":", ":", "0:4"]; var respond_bbox = label[":", ":", ":", ":", "4:5"]; var label_prob = label[":", ":", ":", ":", "5:"]; var giou = tf.expand_dims(bbox_giou(pred_xywh, label_xywh), axis: -1); input_size = tf.cast(input_size, tf.float32); var bbox_loss_scale = 2.0f - 1.0f * label_xywh[":", ":", ":", ":", "2:3"] * label_xywh[":", ":", ":", ":", "3:4"] / tf.pow(input_size, 2); var giou_loss = respond_bbox * bbox_loss_scale * (1.0f - giou); var iou = bbox_iou(pred_xywh[Slice.All, Slice.All, Slice.All, Slice.All, tf.newaxis, Slice.All], bboxes[Slice.All, tf.newaxis, tf.newaxis, tf.newaxis, Slice.All, Slice.All]); var max_iou = tf.expand_dims(tf.reduce_max(iou, axis: -1), axis: -1); var respond_bgd = (1.0f - respond_bbox) * tf.cast(max_iou < iou_loss_thresh, tf.float32); var conf_focal = focal(respond_bbox, pred_conf); var conf_loss = conf_focal * ( respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels: respond_bbox, logits: conv_raw_conf) + respond_bgd * tf.nn.sigmoid_cross_entropy_with_logits(labels: respond_bbox, logits: conv_raw_conf)); var prob_loss = respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels: label_prob, logits: conv_raw_prob); ; giou_loss = tf.reduce_mean(tf.reduce_sum(giou_loss, axis: (1, 2, 3, 4))); conf_loss = tf.reduce_mean(tf.reduce_sum(conf_loss, axis: (1, 2, 3, 4))); prob_loss = tf.reduce_mean(tf.reduce_sum(prob_loss, axis: (1, 2, 3, 4))); return (giou_loss, conf_loss, prob_loss); } public Tensor focal(Tensor target, Tensor actual, int alpha = 1, int gamma = 2) { var focal_loss = alpha * tf.pow(tf.abs(target - actual), gamma, name: "Pow"); return focal_loss; } public Tensor bbox_giou(Tensor boxes1, Tensor boxes2) { boxes1 = tf.concat(new[] { boxes1["...", ":2"] - boxes1["...", "2:"] * 0.5f, boxes1["...", ":2"] + boxes1["...", "2:"] * 0.5f}, axis: -1); boxes2 = tf.concat(new[] { boxes2["...", ":2"] - boxes2["...", "2:"] * 0.5f, boxes2["...", ":2"] + boxes2["...", "2:"] * 0.5f}, axis: -1); boxes1 = tf.concat(new[] { tf.minimum(boxes1["...", ":2"], boxes1["...", "2:"]), tf.maximum(boxes1["...", ":2"], boxes1["...", "2:"])}, axis: -1); boxes2 = tf.concat(new[] { tf.minimum(boxes2["...", ":2"], boxes2["...", "2:"]), tf.maximum(boxes2["...", ":2"], boxes2["...", "2:"])}, axis: -1); var boxes1_area = (boxes1["...", "2"] - boxes1["...", "0"]) * (boxes1["...", "3"] - boxes1["...", "1"]); var boxes2_area = (boxes2["...", "2"] - boxes2["...", "0"]) * (boxes2["...", "3"] - boxes2["...", "1"]); var left_up = tf.maximum(boxes1["...", ":2"], boxes2["...", ":2"]); var right_down = tf.minimum(boxes1["...", "2:"], boxes2["...", "2:"]); var inter_section = tf.maximum(right_down - left_up, 0.0f); var inter_area = inter_section["...", "0"] * inter_section["...", "1"]; var union_area = boxes1_area + boxes2_area - inter_area; var iou = inter_area / union_area; var enclose_left_up = tf.minimum(boxes1["...", ":2"], boxes2["...", ":2"]); var enclose_right_down = tf.maximum(boxes1["...", "2:"], boxes2["...", "2:"]); var enclose = tf.maximum(enclose_right_down - enclose_left_up, 0.0f); var enclose_area = enclose["...", "0"] * enclose["...", "1"]; var giou = iou - 1.0f * (enclose_area - union_area) / enclose_area; return giou; } public Tensor bbox_iou(Tensor boxes1, Tensor boxes2) { var boxes1_area = boxes1["...", "2"] * boxes1["...", "3"]; var boxes2_area = boxes2["...", "2"] * boxes2["...", "3"]; boxes1 = tf.concat(new[] { boxes1["...", ":2"] - boxes1["...", "2:"] * 0.5, boxes1["...", ":2"] + boxes1["...", "2:"] * 0.5}, axis: -1); boxes2 = tf.concat(new[] { boxes2["...", ":2"] - boxes2["...", "2:"] * 0.5, boxes2["...", ":2"] + boxes2["...", "2:"] * 0.5}, axis: -1); var left_up = tf.maximum(boxes1["...", ":2"], boxes2["...", ":2"]); var right_down = tf.minimum(boxes1["...", "2:"], boxes2["...", "2:"]); var inter_section = tf.maximum(right_down - left_up, 0.0); var inter_area = inter_section["...", "0"] * inter_section["...", "1"]; var union_area = boxes1_area + boxes2_area - inter_area; var iou = 1.0f * inter_area / union_area; return iou; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TellMeMoreBlazor.Models { public class DnsRecord { public string dns { get; set; } } public class MxRecord { public string mx { get; set; } } public class HostRecord { public string host { get; set; } } public class TechFound { public string tech { get; set; } } public class TxtRecord { public string txt { get; set; } } public class DnsDumpsterModel { public IList<DnsRecord> dnsRecords { get; set; } public IList<MxRecord> mxRecords { get; set; } public IList<HostRecord> hostRecords { get; set; } public IList<TechFound> techFound { get; set; } public IList<TxtRecord> txtRecords { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace Cr1p.Cryptography { public abstract class Hash { /// <summary> /// Hashes a byte array using SHA256. /// </summary> /// <param name="buffer">Bytes to hash</param> /// <param name="loops">How many times to hash buffer</param> /// <returns></returns> public static byte[] SHA256(byte[] buffer, UInt64 loops = 1) { using (SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider()) for (UInt64 x = 0; loops > x; x++) buffer = sha.ComputeHash(buffer); return buffer; } /// <summary> /// Hashes a byte array using SHA512 /// </summary> /// <param name="buffer">Bytes to hash</param> /// <param name="loops">How many times to hash the buffer</param> /// <returns></returns> public static byte[] SHA512(byte[] buffer, UInt64 loops = 1) { using (SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider()) for (UInt64 x = 0; loops > x; x++) buffer = sha.ComputeHash(buffer); return buffer; } /// <summary> /// Hashses a byte array using MD5 /// </summary> /// <param name="buffer">Bytes to hash</param> /// <param name="loops">How many times to hash the buffer</param> /// <returns></returns> public static byte[] MD5(byte[] buffer, UInt64 loops = 1) { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) for (UInt64 x = 0; loops > x; x++) buffer = md5.ComputeHash(buffer); return buffer; } /// <summary> /// Hashes a string using SHA256 /// </summary> /// <param name="buffer">String to hash</param> /// <param name="loops">How many times to hash the string</param> /// <returns></returns> public static CryptedString SHA256(string buffer, string encoding = "utf-8", UInt64 loops = 1) { return new CryptedString(SHA256(Encoding.GetEncoding(encoding).GetBytes(buffer), loops)); } /// <summary> /// Hashes a string using SHA512 /// </summary> /// <param name="buffer">String to hash</param> /// <param name="loops">How many times to hash the string</param> /// <returns></returns> public static CryptedString SHA512(string buffer, string encoding = "utf-8", UInt64 loops = 1) { return new CryptedString(Hash.SHA256(Encoding.GetEncoding(encoding).GetBytes(buffer),loops)); } /// <summary> /// Hashes a string using MD5 /// </summary> /// <param name="buffer">String to hash</param> /// <param name="loops">How many times to hash the string</param> /// <returns></returns> public static CryptedString MD5(string buffer, string encoding = "utf-8", UInt64 loops = 1) { return new CryptedString(MD5(Encoding.GetEncoding(encoding).GetBytes(buffer), loops)); } /// <summary> /// Hashes a file using SHA256 /// </summary> /// <param name="file">FileInfo of file you wish to hash.</param> /// <param name="loops">How many times to hash the file</param> /// <returns></returns> public static byte[] SHA256(System.IO.FileInfo file, UInt64 loops = 1) { return SHA256(System.IO.File.ReadAllBytes(file.FullName), loops); } /// <summary> /// Hashes a file using SHA512 /// </summary> /// <param name="file">FileInfo of file you wish to hash.</param> /// <param name="loops">How many times to hash the file</param> /// <returns></returns> public static byte[] SHA512(System.IO.FileInfo file, UInt64 loops = 1) { return SHA512(System.IO.File.ReadAllBytes(file.FullName), loops); } /// <summary> /// Hashes a file using MD5 /// </summary> /// <param name="file">FileInfo of file you wish to hash.</param> /// <param name="loops">How many times to hash the file</param> /// <returns></returns> public static byte[] MD5(System.IO.FileInfo file, UInt64 loops = 1) { return MD5(System.IO.File.ReadAllBytes(file.FullName), loops); } } }
using System; namespace AnalogDisplay { /// <summary> /// Summary description for PercentageAdapter. /// </summary> public class PercentageAdapter : Adapter { private double max; private double min; private bool reverse; public PercentageAdapter() { max = 100; min = 0; } public PercentageAdapter(string aname):this() { name = aname; } public bool Reverse { get { return reverse; } set { reverse = value; } } public double Max { get { return max; } set { max = value; } } public double Min { get { return min; } set { min = value; } } public override int TranslateValue (double input) { // simply translate value into a value for the device input = input > max ? max : input; input = input < min ? min : input; if (reverse) { input = max - input; } return (int)(((input - min) / max) * (device.Max - device.Min) + device.Min); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BudgetApp.Domain.DAL; namespace BudgetApp.Domain.Entities { public class CreditEntryWrapper { private CreditEntry mEntry; private UnitofWork mUnitOfWork; private IEnumerable<CardEntry> mCards; private IEnumerable<PartyEntry> mParties; // Constant strings for CreditEntry field names private const string PURCHASEDATE = "entry-date"; private const string SCHEDULEDDATE = "scheduledate"; private const string DESCRIPTION = "entry-description"; private const string PURCHASEAMOUNT = "entry-amount"; private const string PAYAMOUNT = "amount-paid"; private const string CARD = "card-spinner"; private const string PARTY = "party-spinner"; public CreditEntryWrapper(CreditEntry entry, UnitofWork unitOfWork, IEnumerable<CardEntry> cards, IEnumerable<PartyEntry> parties) { this.mEntry = entry; this.mUnitOfWork = unitOfWork; if (cards != null) mCards = cards; if (parties != null) mParties = parties; } public void Add() { } public void Edit() { } public void UpdateField(string fieldName, string value) { bool dateChange = false; switch (fieldName) { case PURCHASEDATE: mEntry.Date = DateTime.Parse(value); break; case SCHEDULEDDATE: mEntry.PayDate = DateTime.Parse(value); dateChange = true; break; case DESCRIPTION: mEntry.Description = value; break; case PURCHASEAMOUNT: mEntry.PurchaseTotal = Decimal.Parse(value); break; case PAYAMOUNT: mEntry.AmountPaid = Decimal.Parse(value); mEntry.AmountRemaining = mEntry.PurchaseTotal - Decimal.Parse(value); break; case CARD: //mEntry.Card = value; var newCard = mUnitOfWork.CardRepo .CreditCards .Where(c => c.Card == value) .FirstOrDefault(); mEntry.Card = newCard; break; case PARTY: var newParty = mUnitOfWork.PartyRepo .Parties .Where(p => p.PartyName == value) .FirstOrDefault(); mEntry.ResponsibleParty = newParty; break; default: break; } if (dateChange) { if (mEntry.PayDate.HasValue) UpdatePaymentPlans(mEntry); else DeleteCharges(mEntry); } mUnitOfWork.CreditRepo.Edit(mEntry); mUnitOfWork.Save(); } private void UpdatePaymentPlans(CreditEntry entry) { // Is this a new payment plan charge we're adding? bool newAdd = true; PaymentPlanCharge charge; PaymentPlanEntry oldPlan = null; // Pull the charge for the DB. // If charge exists, pull the attached PaymentPlan // If charge does not exist, create a new charge charge = mUnitOfWork.PaymentPlanChargeRepo.PaymentPlanCharges .Where(c => c.CreditEntry.CreditEntryId == entry.CreditEntryId) .SingleOrDefault(); if (charge != null) { oldPlan = charge.PaymentPlanEntry; newAdd = false; } else { charge = new PaymentPlanCharge { PurchaseAmount = entry.PurchaseTotal, Description = entry.Description, Comment = "Added" + DateTime.Now.ToShortDateString(), CreditEntry = entry }; } // Does a paymentplan with the modified date already exist PaymentPlanEntry plan = mUnitOfWork.PaymentPlanRepo.PaymentPlanEntries .Where(p => p.PaymentDate == entry.PayDate.Value) .SingleOrDefault(); if (plan != null) { plan.Charges.Add(charge); mUnitOfWork.PaymentPlanRepo.Modify(plan); } else { PaymentPlanEntry newEntry = new PaymentPlanEntry { Card = entry.Card, Charges = new List<PaymentPlanCharge> { charge }, PaymentDate = entry.PayDate.Value, PaymentTotal = entry.AmountPaid, ResponsibleParty = entry.ResponsibleParty }; mUnitOfWork.PaymentPlanRepo.Add(newEntry); } // If this is an existing charge, remove from old PaymentPlan if (!newAdd) { oldPlan.Charges.Remove(charge); mUnitOfWork.PaymentPlanRepo.Modify(oldPlan); } } private void DeleteCharges(CreditEntry entry) { // Find existing charge and the PaymentPlan it's attached to PaymentPlanCharge charge = mUnitOfWork.PaymentPlanChargeRepo.PaymentPlanCharges .Where(c => c.CreditEntry == entry) .First(); PaymentPlanEntry oldPlan = charge.PaymentPlanEntry; // Remove charge from payment plan. Then remove charge. oldPlan.Charges.Remove(charge); mUnitOfWork.PaymentPlanChargeRepo.Delete(charge); } } }
using System.Collections; using Assets.Scripts.Controllers.Fauna; using Assets.Scripts.Models; using Assets.Scripts.Models.Ammo; using UnityEngine; namespace Assets.Scripts.Controllers { public enum CrossbowState { Ready, Reload, Shoot } public class CrossbowController : MonoBehaviour { public GameObject Arrow; public Animation Animation; public CrossbowState CurrentState = CrossbowState.Ready; private GameManager _gameManager; public void Init(GameManager gameManager) { _gameManager = gameManager; } public void Shoot() { if (CurrentState == CrossbowState.Ready) { var amountArrow = _gameManager.PlayerModel.Inventory.GetAmount(typeof(CrossbowArrow)); if (amountArrow > 0) { CurrentState = CrossbowState.Shoot; if (!Arrow.activeSelf) Arrow.SetActive(true); _gameManager.PlayerModel.Inventory.UseItem(_gameManager, typeof(CrossbowArrow)); Animation.Play("Shoot"); SoundManager.PlaySFX(WorldConsts.AudioConsts.BowRelease); StartCoroutine(CheckShoot()); } else { _gameManager.Player.MainHud.ShowHudText(Localization.Get("no_arrows"), HudTextColor.Red); } } } private IEnumerator CheckShoot() { yield return new WaitForSeconds(0.3f); var ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f)); RaycastHit hit; int waterLayerMask = 1 << 4;//берем слой воды waterLayerMask = ~waterLayerMask;//инвентируем, теперь в переменной все слои крое воды if (Physics.Raycast(ray, out hit, 150f, waterLayerMask)) { var distance = Vector3.Distance(transform.position, hit.collider.transform.position); var precent = 100; if (distance > 100) precent = 60; else if (distance > 70) precent = 70; else if (distance > 50) precent = 80; var rand = Random.Range(0, 100); if (rand < precent) { var enemy = hit.collider.gameObject.GetComponent<AnimalColliderLink>(); if (enemy != null) { var item = BaseObjectFactory.GetItem(typeof(CrossbowArrow)); enemy.SetDamage(item.Damage); } } } var amountArrow = _gameManager.PlayerModel.Inventory.GetAmount(typeof(CrossbowArrow)); if (amountArrow > 0) Reload(); else { CurrentState = CrossbowState.Ready; } } private void Reload() { CurrentState = CrossbowState.Reload; Animation.Play("Reload"); SoundManager.PlaySFX(WorldConsts.AudioConsts.BowString, false, 0.3f); } public void Reloaded() { CurrentState = CrossbowState.Ready; } } }
using FluentAssertions; using Simple.Expressions; using Xunit; namespace Simple.Tests { public class ExpressionInspectTests { [Fact] public void GivenANumber_WhenInspectIsCalled_ThenTheValueIsReturnedInQuotes() { var number = new Number(7); number.Inspect().Should().Be("«7»"); } [Fact] public void GivenAnAddExpression_WhenInspectIsCalled_ThenTheOperandsAreReturnedInQuotes() { var add = new Add(new Number(13), new Number(8)); add.Inspect().Should().Be("«13 + 8»"); } [Fact] public void GivenAMultiplyExpression_WhenInspectIsCalled_ThenTheOperandsAreReturnedInQuotes() { var multiply = new Multiply(new Number(2), new Number(14)); multiply.Inspect().Should().Be("«2 * 14»"); } [Fact] public void GivenAComplexExpression_WhenInspectIsCalled_ThenTheRepresentationIsReturnedInQuotes() { var expression = new Add( new Multiply(new Number(1), new Number(2)), new Multiply(new Number(3), new Number(4))); expression.Inspect().Should().Be("«1 * 2 + 3 * 4»"); } } }
using System; using System.IO; using System.Net; namespace PowerPad.RouteHandlers { internal class SlideImageHandler : IRouteHandler { public void HandleRequest(HttpListenerContext context, StreamWriter sw) { var cache = PowerPad.ActiveSlideShowCache; // Validate parameters if (context.Request.QueryString["Number"] == null) { new ErrorHandler(500, "Missing parameter: 'Number'").HandleRequest(context, sw); return; } // Try to read slide number int slideNumber; try { slideNumber = Convert.ToInt32(context.Request.QueryString["Number"]); } catch (FormatException) { new ErrorHandler(500, "Invalid parameter value: 'Number'").HandleRequest(context, sw); return; } // Ensure slide image exists in cache if (!cache.SlideIsCached(slideNumber)) { new ErrorHandler(404, "Slide does not exist").HandleRequest(context, sw); return; } // Serve slide image to user var handler = new StaticFileHandler(cache.GetImagePath(slideNumber)); handler.HandleRequest(context, sw); } } }
using System.Reflection; namespace ReactMusicStore.Core.IoC { public static class ReferencedAssemblies { public static Assembly WebApi => Assembly.Load("React-MusicStore.WebApi"); public static Assembly Framework => Assembly.Load("React-MusicStore.WebApi.Framework"); public static Assembly Services => Assembly.Load("React-MusicStore.Services"); public static Assembly Domain => Assembly.Load("React-MusicStore.Core.Domain"); public static Assembly DataContext => Assembly.Load("React-MusicStore.Core.Data.Context"); public static Assembly Repositories => Assembly.Load("React-MusicStore.Core.Data.Repository"); } }
using myBOOK.data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace myBOOK.UI { /// <summary> /// Логика взаимодействия для AddOwnBook.xaml /// </summary> public partial class AddOwnBook : Window { public Action<Books> AddBook { get; set; } public AddOwnBook() { InitializeComponent(); Genre.ItemsSource = Enum.GetNames(typeof(Books.Genres)); Genre.SelectedIndex = 0; } private void Add_Click(object sender, RoutedEventArgs e) { var author = AuthorName.Text; var bookname = BookName.Text; var genre = (Books.Genres)Genre.SelectedIndex; var desc = Description.Text; var link = LoadingLink.Text; if (author=="") { MessageBox.Show("Укажите автора"); return; } if (bookname=="") { MessageBox.Show("Укажите название книги"); return; } var b = new Books { Author = author, BookName = bookname, Description = desc, Genre = genre, LoadingLink = link }; AddBook?.Invoke(b); Close(); } private void MenuHelp_Click(object sender, RoutedEventArgs e) { Help help = new Help(); help.ShowDialog(); } private void MenuClose_Click(object sender, RoutedEventArgs e) { Close(); } private void MenuAbout_Click(object sender, RoutedEventArgs e) { About about = new About(); about.ShowDialog(); } private void MenuAuthors_Click(object sender, RoutedEventArgs e) { Authors authors = new Authors(); authors.ShowDialog(); } } }
using UnityEngine; using System.Collections; public class EnemyBig : Enemy { // Use this for initialization public override void Start() { base.Start(); Health = 200f; MaxHealth = 200f; Damage = 15f; Score = 100; } // Update is called once per frame public override void Update() { base.Update(); } }
using System.Linq; using System.Collections.Generic; using UIKit; using Foundation; using CoreGraphics; namespace AVMetadataRecordPlay { public static class UICollectionViewExtensions { public static IEnumerable<NSIndexPath> GetIndexPaths (this UICollectionView collectionView, CGRect rect) { return collectionView.CollectionViewLayout .LayoutAttributesForElementsInRect (rect) .Select (attr => attr.IndexPath); } } }
using AsNum.XFControls; using Caliburn.Micro; using Caliburn.Micro.Xamarin.Forms; using RRExpress.AppCommon; using RRExpress.AppCommon.Attributes; using System.Collections.Generic; using System.Windows.Input; using Xamarin.Forms; namespace RRExpress.Store.ViewModels { [Regist(InstanceMode.PreRequest)] public class GoodsInfoViewModel : BaseVM, ISelectable { public override string Title { get { return "详情"; } } public long ID { get; set; } public Dictionary<string, string> Imgs { get; } = new Dictionary<string, string>() { {"http://img1.ph.126.net/hZ35wHe4KwqgPbh-hkONGQ==/723390690246397027.jpg","散养家鸡" }, {"http://image.99114.com/2009/12/25/5ea77b1a2c8e40eab8ea938c69e77ba9.jpg","绿色安全" }, {"http://www.tjyj.org/uploads/allimg/130125/1_0011083762.jpg","自由生态" }, {"http://htdz.7015.cn/uploadfile/2016/0201/20160201030414712.jpg","描述" } }; #region ISelectable public bool IsSelected { get; set; } public ICommand SelectedCommand { get; set; } public ICommand UnSelectedCommand { get; set; } #endregion public ICommand ShowFullImgCmd { get; } public GoodsInfoViewModel() { this.ShowFullImgCmd = new Command(() => { IoC.Get<INavigationService>() .For<ImageViewModel>() .WithParam(vm => vm.Datas, this.Imgs.Keys) .Navigate(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Client.Map; using Welic.Dominio.Models.Client.Service; using Welic.Dominio.Patterns.Repository.Pattern.Repositories; using Welic.Dominio.Patterns.Service.Pattern; namespace Services.Pessoa { public class ServicePessoa: Service<PessoaMap>, IServicePessoa { public ServicePessoa(IRepositoryAsync<PessoaMap> repository) : base(repository) { } } }
using System.Runtime.Serialization; namespace Quasar.Client.IpGeoLocation { [DataContract] public class GeoResponse { [DataMember(Name = "ip")] public string Ip { get; set; } [DataMember(Name = "continent_code")] public string ContinentCode { get; set; } [DataMember(Name = "country")] public string Country { get; set; } [DataMember(Name = "country_code")] public string CountryCode { get; set; } [DataMember(Name = "timezone")] public Time Timezone { get; set; } [DataMember(Name = "connection")] public Conn Connection { get; set; } } [DataContract] public class Time { [DataMember(Name = "utc")] public string UTC { get; set; } } [DataContract] public class Conn { [DataMember(Name = "asn")] public string ASN { get; set; } [DataMember(Name = "isp")] public string ISP { get; set; } } }
using VehiclesInfoModels.MorotVihicle; namespace VehiclesInfoModels.NonMotorVihicle { public class Carriage : NonMotorVehicle { public int PassengersCapacity { get; set; } public virtual Train Train { get; set; } } }
namespace Draft_FF.Frontend.Helpers { using AutoMapper; using Draft_FF.Frontend.Entities; using Draft_FF.Frontend.DTOs; public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<Owner, OwnerDto>(); CreateMap<OwnerDto, Owner>(); CreateMap<DraftPickSlot, DraftSlotDto>().ForMember(dest => dest.OwnerName, opt => opt.MapFrom(src => src.Owner.Name)) .ForMember(dest => dest.PickedPlayerName, opt => opt.MapFrom(src => src.SelectedPlayer.Name)).ReverseMap(); CreateMap<Player, PlayerDto>().ForMember(dest => dest.TeamShortName, opt => opt.MapFrom(src => src.Team.ShortName)) .ForMember(dest => dest.TeamByeWeek, opt => opt.MapFrom(src => src.Team.ByeWeek)).ReverseMap(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputerraBIN { /// <summary> /// Class for generate items ant theirs parameters /// </summary> public class EmploeeGenerator { private readonly Random random = new Random(); /// <summary> /// Create List of emplooes /// </summary> public List<Emploee> GenerateEmploees(int workersCount, int bossesCount, int bigBossesCount, int minCoordinate, int maxCoordinate) { List<Emploee> emploees = CreateEmploees(workersCount, bossesCount, bigBossesCount); emploees = GiveSalary(emploees, 1000, 3000, 5000, 10000, 20000, 50000); emploees = GiveName(emploees); emploees = GiveMood(emploees); emploees = GivePost(emploees); emploees = GivePhrase(emploees); foreach(var emploee in emploees) { emploee.Position = GivePosition(emploee.Position, minCoordinate, maxCoordinate, minCoordinate, maxCoordinate); } return emploees; } /// <summary> /// Create List of works /// </summary> public List<Work> GenereteWork(int worksCount, int minCoordinate, int maxCoordinate) { List<Work> works = new List<Work>(); while (worksCount != 0) { Work work = new Work(); works.Add(work); worksCount--; } foreach (var work in works) { work.Position = GivePosition(work.Position, minCoordinate, maxCoordinate, minCoordinate, maxCoordinate); } return works; } /// <summary> /// Create List of Customers /// </summary> public List<Customer> GenereteCustomer(int customersCount, int minCoordinate, int maxCoordinate) { List<Customer> customers = new List<Customer>(); for (int count = customersCount; count!=0; count--) { Customer customer = new Customer(); customer.Position = GivePosition(customer.Position, minCoordinate, maxCoordinate, minCoordinate, maxCoordinate); customers.Add(customer); } return customers; } /// <summary> /// Create emploee /// </summary> public List<Emploee> CreateEmploees(int workersCount, int bossesCount, int bigBossesCount) { List<Emploee> workersList = new List<Emploee>(); while (workersCount != 0) { Worker worker = new Worker(); workersList.Add(worker); workersCount--; } while (bossesCount != 0) { Boss boss = new Boss(); workersList.Add(boss); bossesCount--; } while (bigBossesCount != 0) { BigBoss bigBoss = new BigBoss(); workersList.Add(bigBoss); bigBossesCount--; } return workersList; } /// <summary> /// Give name for each emploees in list /// </summary> /// <param name="emploees"></param> public List<Emploee> GiveName(List<Emploee> emploees) { List<string> firstNames = new List<string>() { "John", "William", "James", "Charles", "George", "Frank", "Joseph", "Mary", "Anna", "Emma", "Elizabeth", "Minnie" }; List<string> secondNames = new List<string>() { "Smith", "Johnson", "Williams", "Brown", "Jones", "Miller", "Davis", "Garcia", "Rodriguez", "Wilson", "Martinez", "Anderson" }; foreach (var emploee in emploees) { string firstName = firstNames[random.Next(0, firstNames.Count - 1)]; string secondName = secondNames[random.Next(0, secondNames.Count - 1)]; emploee.Name = firstName + " " + secondName; } return emploees; } /// <summary> /// Give position for each emploees in list /// </summary> public Point GivePosition(Point point, int minXCoordinate, int maxXCoordinate, int minYCoordinate, int maxYCoordinate) { List<Point> usedPoints = new List<Point>(); bool isUnic = false; while (isUnic == false) { point = new Point { CoordinateX = Utilities.GetRandomCoordinate(minXCoordinate, maxXCoordinate), CoordinateY = Utilities.GetRandomCoordinate(minYCoordinate, maxYCoordinate) }; if (usedPoints.Contains(point)) { continue; } else { isUnic = true; usedPoints.Add(point); } } return point; } /// <summary> /// Give Mood for each emploees in list /// </summary> public List<Emploee> GiveMood(List<Emploee> emploees) { foreach (var emploee in emploees) { emploee.Mood = random.Next(100) <= 30 ? true : false; } return emploees; } /// <summary> /// Give salary for each emploees in list /// </summary> public List<Emploee> GiveSalary(List<Emploee> emploees, int workerMin, int workerMax, int bossMin, int bossMax, int bigBossMin, int bigBossMax) { foreach (var emploee in emploees) { if (emploee is Worker) { emploee.Salary = random.Next(workerMin, workerMax); } if (emploee is Boss) { emploee.Salary = random.Next(bossMin, bossMax); } if (emploee is BigBoss) { emploee.Salary = random.Next(bigBossMin, bigBossMax); } } return emploees; } /// <summary> /// Give post for each emploees in list /// </summary> public List<Emploee> GivePost(List<Emploee> emploees) { foreach (var emploee in emploees) { if (emploee is Worker) { emploee.Post = "Worker"; } if (emploee is Boss) { emploee.Post = "Boss"; } if (emploee is BigBoss) { emploee.Post = "BigBoss"; } } return emploees; } /// <summary> /// Give phrase for each emploees in list /// </summary> public List<Emploee> GivePhrase(List<Emploee> emploees) { foreach (var emploee in emploees) { if (emploee is Worker) { emploee.Phrase = "All too easy."; } if (emploee is Boss) { emploee.Phrase = "Taz'dingo"; } if (emploee is BigBoss) { emploee.Phrase = "Lok-narash!"; } } return emploees; } } }
using System; using System.Collections.Generic; using System.Text; namespace TreeSolver { public class FirstRoomRelaxation { // This relaxation searches for the minimum number of rooms used if only the first jab has to be scheduled. This is equal // or better than the full problem, and gives us a bound to determine whether we should continue in a branch in the // main problem. int firstDoseTime; int currentBound; Schedule schedule; public FirstRoomRelaxation(int firstDoseTime, Schedule schedule, int currentBound) { this.firstDoseTime = firstDoseTime; this.schedule = schedule; this.currentBound = currentBound; } public int SolveRelaxation() { // Given schedule is the best we can do in this instance. Schedule bestSchedule = schedule.CopySchedule(); // Worst solution is when every patient has their own hospital room. int bound = currentBound; // Using a stack for depth-first. Stack<Schedule> schedules = new Stack<Schedule>(); // Put the empty schedule to start with on the stack schedules.Push(schedule.CopySchedule()); while (schedules.Count > 0) { Schedule currentSchedule = schedules.Pop(); // if rooms used > bound, do nothing if (currentSchedule.rooms < bound) { // Take first patient from list Patient curPatient = currentSchedule.availablePatients[0]; // Try to fit first jab on every position in every room + every position in a new room for (int k = 0; k <= currentSchedule.rooms; k++) { for (int i = 0; i < curPatient.firstIntervalEnd - curPatient.firstIntervalStart - firstDoseTime + 2; i++) { bool blockedFirst = false; // start + shift until start + shift + jabtime, this doesn't exceed interval due to previous loop. for (int j = curPatient.firstIntervalStart + i; j <= curPatient.firstIntervalStart + i + firstDoseTime - 1; j++) { if (currentSchedule.schedule[k, j] != 0) { blockedFirst = true; } } //First jab fits, now try every second jab if (!blockedFirst) { //Both first and second jab fit: create a new schedule and add to the stack { Schedule newSchedule = currentSchedule.CopySchedule(); for (int j = curPatient.firstIntervalStart + i; j <= curPatient.firstIntervalStart + i + firstDoseTime - 1; j++) { newSchedule.schedule[k, j] = curPatient.id; } if (k == currentSchedule.rooms) { newSchedule.rooms++; } List<Patient> remainingPatients = new List<Patient>(); if (currentSchedule.availablePatients.Count > 1) { for (int p = 1; p < currentSchedule.availablePatients.Count; p++) { remainingPatients.Add(currentSchedule.availablePatients[p]); } newSchedule.availablePatients = remainingPatients; schedules.Push(newSchedule); } else { if (currentSchedule.rooms <= bound) { bound = newSchedule.rooms; bestSchedule = newSchedule; } } } } } } } } return bestSchedule.rooms; } } }
using Tomelt.Localization; using Tomelt.UI.Navigation; namespace Tomelt.Widgets { public class AdminMenu : INavigationProvider { public Localizer T { get; set; } public string MenuName { get { return "admin"; } } //public void GetNavigation(NavigationBuilder builder) { // builder.AddImageSet("widgets") // .Add(T("Widgets"), "5", // menu => menu.Add(T("Configure"), "0", item => item.Action("Index", "Admin", new { area = "Tomelt.Widgets" }) // .Permission(Permissions.ManageWidgets))); //} public void GetNavigation(NavigationBuilder builder) { builder.AddImageSet("ok") .Add(T("系统功能"), "88", menu => { menu.LinkToFirstChild(false); menu.Add(T("部件功能"), "95", item => item .Action("Index", "Admin", new {area = "Tomelt.Widgets"}) .Permission(Permissions.ManageWidgets)); }); } } }
using _7DRL_2021.Behaviors; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Results { class ActionGripDash : IActionHasOrigin, ITickable { static Random Random = new Random(); public ICurio Origin { get; set; } public Vector2 Direction; public Slider Frame; public bool Done => Frame.Done; static SoundReference SoundSwish = SoundLoader.AddSound("content/sound/swish.wav"); static SoundReference SoundKick = SoundLoader.AddSound("content/sound/clack.wav"); public ActionGripDash(ICurio origin, Vector2 direction, float time) { Origin = origin; Direction = direction; Frame = new Slider(time); } public void Run() { var player = Origin.GetBehavior<BehaviorPlayer>(); var grapple = Origin.GetBehavior<BehaviorGrapplingHook>(); var orientable = Origin.GetBehavior<BehaviorOrientable>(); grapple.GripDirection = null; orientable.OrientTo(Util.VectorToAngle(Direction)); if (player != null) { player.Momentum.Direction = Direction; player.Momentum.Amount = Math.Min(player.Momentum.Amount, 32); } SoundKick.Play(1, Random.NextFloat(-0.5f, +0.5f), 0); SoundSwish.Play(1, Random.NextFloat(-1.0f, -0.5f), 0); } public void Tick(SceneGame scene) { Frame += scene.TimeModCurrent; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace SomeTechie.RoundRobinScheduler.WebServer { class MimeTypeHelper { protected static Dictionary<string, string> _mimeTypes; protected static void InitializeMimeTypes() { _mimeTypes = new Dictionary<string, string>(); try { string dataPath = Path.Combine(Directory.GetCurrentDirectory(), "mime.dat"); if (File.Exists(dataPath)) { StreamReader reader = new StreamReader(dataPath); string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.Length < 1) continue; if (line.StartsWith("#")) continue; string[] lineParts = line.Split(new char[] { ';' }); if (lineParts.Length < 2) continue; string mime = lineParts[1].Trim(); if (mime.Length < 1) continue; string[] extensions = lineParts[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (extensions.Length < 1) continue; foreach (string rawExtension in extensions) { string extension = rawExtension.Trim().TrimStart(new char[] { '.' }); if (extension.Length < 1) continue; if (_mimeTypes.ContainsKey(extension)) _mimeTypes[extension] = mime; else _mimeTypes.Add(extension, mime); } } } } catch { } } public static string GetMimeTypeByExtension(string fileExtension) { if (_mimeTypes == null) InitializeMimeTypes(); string extension = fileExtension.TrimStart(new char[] { '.' }); if (_mimeTypes.ContainsKey(extension)) return _mimeTypes[extension]; else return null; } public static string GetMimeTypeByFilePath(FileInfo fileInfo) { return GetMimeTypeByExtension(fileInfo.Extension); } public static string GetMimeTypeByFilePath(string filePath) { return GetMimeTypeByFilePath(new FileInfo(filePath)); } public static string[] GetExtensions(string mimetype) { string mime = mimetype.ToLower(); if (_mimeTypes == null) InitializeMimeTypes(); List<string> ret = new List<string>(); foreach (KeyValuePair<string, string> pair in _mimeTypes) { if (pair.Value == mime) ret.Add(pair.Key); } return ret.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DataAccessLayer.dbContext; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace SovaWebService.Controllers { [Route("api/graph")] public class TermNetworkController : Controller { private readonly IDataService _dataService; public TermNetworkController(IDataService dataService) { _dataService = dataService; } // GET: api/graph/{searchText} [HttpGet("{searchText}", Name = nameof(GetTermNetworkResult))] public IActionResult GetTermNetworkResult(string searchText) { return Ok(JsonConvert.SerializeObject(_dataService.TermNetworkList(searchText))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GitHubExplorer.Entities { public class GitHubUser { /* *{ "login": "grantw1991", "id": 15818013, "avatar_url": "https://avatars2.githubusercontent.com/u/15818013?v=4", "gravatar_id": "", "url": "https://api.github.com/users/grantw1991", "html_url": "https://github.com/grantw1991", "followers_url": "https://api.github.com/users/grantw1991/followers", "following_url": "https://api.github.com/users/grantw1991/following{/other_user}", "gists_url": "https://api.github.com/users/grantw1991/gists{/gist_id}", "starred_url": "https://api.github.com/users/grantw1991/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/grantw1991/subscriptions", "organizations_url": "https://api.github.com/users/grantw1991/orgs", "repos_url": "https://api.github.com/users/grantw1991/repos", "events_url": "https://api.github.com/users/grantw1991/events{/privacy}", "received_events_url": "https://api.github.com/users/grantw1991/received_events", "type": "User", "site_admin": false, "name": "Grant Wright", "company": "Beagle Street", "blog": "", "location": "Peterborough", "email": null, "hireable": null, "bio": "Software Engineer", "public_repos": 4, "public_gists": 0, "followers": 0, "following": 0, "created_at": "2015-11-12T14:20:36Z", "updated_at": "2017-10-10T11:00:20Z" } * */ public string AvatarUrl { get; set; } public string Name { get; set; } public string Location { get; set; } public string Bio { get; set; } } }
using Spine.Unity; using UnityEngine; namespace DChild.Gameplay.Player { public class SpinesheetAnimation : CharacterAnimation { #region Basic Animations public const string ANIMATION_IDLE = "Idle"; public const string ANIMATION_RUN = "Run"; public const string ANIMATION_WALK = "Walk"; public const string ANIMATION_JUMP = "jump"; public const string ANIMATION_IDLE_TO_RUN = "Idle_To_Run"; public const string ANIMATION_RUN_TO_STOP = "Run_To_Stop"; public const string ANIMATION_IDLE_TO_WALK = "Idle_To_Walk"; public const string ANIMATION_WALK_TO_STOP = "Walk_To_Stop"; #endregion [SerializeField] private float m_transition; private bool m_moving; private bool m_transitionPlayed; //public bool TransitionPlayed => m_transitionPlayed; public override void DoDeath() { throw new System.NotImplementedException(); } public override void DoIdle() { SetAnimation(0, ANIMATION_IDLE, true); m_moving = false; } public void DoJump() { SetAnimation(0, ANIMATION_JUMP, true); } public void DoWalk() { SetAnimation(0, ANIMATION_WALK, true); m_moving = true; } public void DoIdleToWalk() { SetAnimation(0, ANIMATION_IDLE_TO_WALK, false); } public void DoWalkToStop() { SetAnimation(0, ANIMATION_WALK_TO_STOP, false); } public void DoRun() { SetAnimation(0, ANIMATION_RUN, true); m_moving = true; } public void DoIdleToRun() { SetAnimation(0, ANIMATION_IDLE_TO_RUN, false); } public void DoRunToStop() { SetAnimation(0, ANIMATION_RUN_TO_STOP, false); } //private void Update() //{ // var HorizontalInput = Input.GetAxisRaw("Horizontal"); // if (HorizontalInput != 0) // { // if (!m_moving) // { // m_moving = true; // m_transitionPlayed = true; // } // if (m_moving) // { // //DoRun(); // DoWalk(); // } // } // else if (HorizontalInput == 0) // { // if (m_moving) // { // //DoRunToStop(); // DoWalkToStop(); // if (skeletonAnimation.state.GetCurrent(0).AnimationTime > m_transition) // { // m_moving = false; // m_transitionPlayed = false; // } // } // else if (!m_moving) // { // DoIdle(); // } // } //} } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace WebAppCa.Models { public class Channel { [Key] public int ChannelId { get; set; } public string Name { get; set; } public string Description { get; set; } public string Image { get; set; } public virtual ICollection<Schedule> Schedules { get; set; } } }
namespace SpaceHosting.Index.Sparnn.Distances { internal enum MatrixMetricSearchSpaceAlgorithm { Cosine, JaccardBinary } }
using Hangfire; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace ConsoleApp1 { public class Program { public static void Main(string[] args) { //Console.WriteLine("Hello World!"); var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); GlobalConfiguration .Configuration //.UseSqlServerStorage(@"Server=.\sqlexpress;Database=Hangfire;Trusted_Connection=True;"); .UseSqlServerStorage(configuration.GetConnectionString("HangfireDb")) .UseColouredConsoleLogProvider(); //Queue Job //BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!")); //Process Job using (var server = new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press any key to exit..."); Console.ReadKey(); } } } }
namespace Reacher.Storage.File.Json.Configuration { public class StorageFileJsonConfiguration { public string Path { get; set; } } }
using System; using NUnit.Framework; using SharpMap.Geometries; namespace UnitTests.Geometries { [TestFixture] public class MultiLinestringsTests { [Test] public void MultiLinestring() { MultiLineString mls = new MultiLineString(); Assert.IsTrue(mls.IsEmpty()); mls.LineStrings.Add(new LineString()); Assert.IsTrue(mls.IsEmpty()); mls.LineStrings[0].Vertices.Add(new Point(45, 68)); mls.LineStrings[0].Vertices.Add(new Point(82, 44)); mls.LineStrings.Add(CreateLineString()); foreach (LineString ls in mls) Assert.IsFalse(ls.IsEmpty()); Assert.IsFalse(mls.IsEmpty()); foreach (LineString ls in mls) Assert.IsFalse(ls.IsClosed); Assert.IsFalse(mls.IsClosed); //Close linestrings foreach (LineString ls in mls) ls.Vertices.Add(ls.StartPoint.Clone()); foreach (LineString ls in mls) Assert.IsTrue(ls.IsClosed); Assert.IsTrue(mls.IsClosed); Assert.AreEqual(new BoundingBox(1,2,930,123), mls.GetBoundingBox()); } private LineString CreateLineString() { LineString ls = new LineString(); ls.Vertices.Add(new Point(1, 2)); ls.Vertices.Add(new Point(10, 22)); ls.Vertices.Add(new Point(930, 123)); return ls; } } }
using Sentry.Http; using Sentry.Internal.Http; using Sentry.Tests.Helpers; namespace Sentry.Tests.Internals.Http; public partial class HttpTransportTests { private readonly IDiagnosticLogger _testOutputLogger; private readonly ISystemClock _fakeClock; public HttpTransportTests(ITestOutputHelper output) { _testOutputLogger = new TestOutputDiagnosticLogger(output); _fakeClock = new MockClock(DateTimeOffset.UtcNow); } [Fact] public async Task SendEnvelopeAsync_CancellationToken_PassedToClient() { // Arrange using var source = new CancellationTokenSource(); source.Cancel(); var token = source.Token; var httpHandler = Substitute.For<MockableHttpMessageHandler>(); httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetOkResponse()); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient(httpHandler)); var envelope = Envelope.FromEvent( new SentryEvent(eventId: SentryResponses.ResponseId)); #if NET5_0_OR_GREATER await Assert.ThrowsAsync<TaskCanceledException>(() => httpTransport.SendEnvelopeAsync(envelope, token)); #else // Act await httpTransport.SendEnvelopeAsync(envelope, token); // Assert await httpHandler .Received(1) .VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Is<CancellationToken>(c => c.IsCancellationRequested)); #endif } [Fact] public async Task SendEnvelopeAsync_ResponseNotOkWithJsonMessage_LogsError() { // Arrange const HttpStatusCode expectedCode = HttpStatusCode.BadGateway; const string expectedMessage = "Bad Gateway!"; var expectedCauses = new[] { "invalid file", "wrong arguments" }; var expectedCausesFormatted = string.Join(", ", expectedCauses); var httpHandler = Substitute.For<MockableHttpMessageHandler>(); httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetJsonErrorResponse(expectedCode, expectedMessage, expectedCauses)); var logger = new InMemoryDiagnosticLogger(); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, Debug = true, DiagnosticLogger = logger }, new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); // Act await httpTransport.SendEnvelopeAsync(envelope); // Assert logger.Entries.Any(e => e.Level == SentryLevel.Error && e.Message == "Sentry rejected the envelope {0}. Status code: {1}. Error detail: {2}. Error causes: {3}." && e.Exception == null && e.Args[0].ToString() == envelope.TryGetEventId().ToString() && e.Args[1].ToString() == expectedCode.ToString() && e.Args[2].ToString() == expectedMessage && e.Args[3].ToString() == expectedCausesFormatted ).Should().BeTrue(); } [Fact] public async Task SendEnvelopeAsync_ResponseRequestEntityTooLargeWithPathDefined_StoresFile() { // Arrange var httpHandler = Substitute.For<MockableHttpMessageHandler>(); httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetJsonErrorResponse(HttpStatusCode.RequestEntityTooLarge, "")); var logger = new InMemoryDiagnosticLogger(); var options = new SentryOptions { Dsn = ValidDsn, Debug = true, DiagnosticLogger = logger }; var path = Path.GetTempPath(); const string expectedEnvVar = "SENTRY_KEEP_LARGE_ENVELOPE_PATH"; options.FakeSettings().EnvironmentVariables[expectedEnvVar] = path; var httpTransport = new HttpTransport( options, new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); // Act await httpTransport.SendEnvelopeAsync(envelope); // Assert logger.Entries.Any(e => e.Level == SentryLevel.Debug && e.Message == "Environment variable '{0}' set. Writing envelope to {1}" && e.Exception == null && e.Args[0].ToString() == expectedEnvVar && e.Args[1].ToString() == path) .Should() .BeTrue(); var fileStoredLogEntry = logger.Entries.FirstOrDefault(e => e.Level == SentryLevel.Info && e.Message == "Envelope's {0} bytes written to: {1}"); Assert.NotNull(fileStoredLogEntry); var expectedFile = new FileInfo(fileStoredLogEntry.Args[1].ToString()!); Assert.True(expectedFile.Exists); try { Assert.Null(fileStoredLogEntry.Exception); // // Path is based on the provided path: Assert.Contains(path, fileStoredLogEntry.Args[1] as string); // // Path contains the envelope id in its name: Assert.Contains(envelope.TryGetEventId().ToString(), fileStoredLogEntry.Args[1] as string); Assert.Equal(expectedFile.Length, (long)fileStoredLogEntry.Args[0]); } finally { // It's in the temp folder but just to keep things tidy: expectedFile.Delete(); } } [Fact] public async Task SendEnvelopeAsync_ResponseRequestEntityTooLargeWithoutPathDefined_DoesNotStoreFile() { // Arrange var httpHandler = Substitute.For<MockableHttpMessageHandler>(); httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetJsonErrorResponse(HttpStatusCode.RequestEntityTooLarge, "")); var logger = new InMemoryDiagnosticLogger(); var options = new SentryOptions { Dsn = ValidDsn, Debug = true, DiagnosticLogger = logger }; const string expectedEnvVar = "SENTRY_KEEP_LARGE_ENVELOPE_PATH"; options.FakeSettings().EnvironmentVariables[expectedEnvVar] = null; // explicitly for this test var httpTransport = new HttpTransport( options, new HttpClient(httpHandler)); // Act await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); // Assert logger.Entries.Any(e => e.Message == "Environment variable '{0}' set. Writing envelope to {1}") .Should() .BeFalse(); logger.Entries.Any(e => e.Message == "Envelope's {0} bytes written to: {1}") .Should() .BeFalse(); } [Fact] public async Task SendEnvelopeAsync_ResponseNotOkWithStringMessage_LogsError() { // Arrange const HttpStatusCode expectedCode = HttpStatusCode.RequestEntityTooLarge; const string expectedMessage = "413 Request Entity Too Large"; var httpHandler = Substitute.For<MockableHttpMessageHandler>(); _ = httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetTextErrorResponse(expectedCode, expectedMessage)); var logger = new InMemoryDiagnosticLogger(); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, Debug = true, DiagnosticLogger = logger }, new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); // Act await httpTransport.SendEnvelopeAsync(envelope); // Assert _ = logger.Entries.Any(e => e.Level == SentryLevel.Error && e.Message == "Sentry rejected the envelope {0}. Status code: {1}. Error detail: {2}." && e.Exception == null && e.Args[0].ToString() == envelope.TryGetEventId().ToString() && e.Args[1].ToString() == expectedCode.ToString() && e.Args[2].ToString() == expectedMessage ).Should().BeTrue(); } [Fact] public async Task SendEnvelopeAsync_ResponseNotOkNoMessage_LogsError() { // Arrange const HttpStatusCode expectedCode = HttpStatusCode.BadGateway; var httpHandler = Substitute.For<MockableHttpMessageHandler>(); httpHandler.VerifiableSendAsync(Arg.Any<HttpRequestMessage>(), Arg.Any<CancellationToken>()) .Returns(_ => SentryResponses.GetJsonErrorResponse(expectedCode, null)); var logger = new InMemoryDiagnosticLogger(); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, Debug = true, DiagnosticLogger = logger }, new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); // Act await httpTransport.SendEnvelopeAsync(envelope); // Assert logger.Entries.Any(e => e.Level == SentryLevel.Error && e.Message == "Sentry rejected the envelope {0}. Status code: {1}. Error detail: {2}. Error causes: {3}." && e.Exception == null && e.Args[0].ToString() == envelope.TryGetEventId().ToString() && e.Args[1].ToString() == expectedCode.ToString() && e.Args[2].ToString() == HttpTransportBase.DefaultErrorMessage && e.Args[3].ToString() == string.Empty ).Should().BeTrue(); } [Fact] public async Task SendEnvelopeAsync_ItemRateLimit_DropsItem() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1234:event, 897:transaction") )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, DiagnosticLogger = _testOutputLogger, SendClientReports = false, Debug = true }, new HttpClient(httpHandler), clock: _fakeClock); // First request always goes through await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); var envelope = new Envelope( new Dictionary<string, object>(), new[] { // Should be dropped new EnvelopeItem( new Dictionary<string, object> {["type"] = "event"}, new EmptySerializable()), new EnvelopeItem( new Dictionary<string, object> {["type"] = "event"}, new EmptySerializable()), new EnvelopeItem( new Dictionary<string, object> {["type"] = "transaction"}, new EmptySerializable()), // Should stay new EnvelopeItem( new Dictionary<string, object> {["type"] = "other"}, new EmptySerializable()) }); var expectedEnvelope = new Envelope( new Dictionary<string, object>(), new[] { new EnvelopeItem( new Dictionary<string, object> {["type"] = "other"}, new EmptySerializable()) }); var expectedEnvelopeSerialized = await expectedEnvelope.SerializeToStringAsync(_testOutputLogger, _fakeClock); // Act await httpTransport.SendEnvelopeAsync(envelope); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert actualEnvelopeSerialized.Should().BeEquivalentTo(expectedEnvelopeSerialized); } [Fact] public async Task SendEnvelopeAsync_RateLimited_CountsDiscardedEventsCorrectly() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1234:event, 897:transaction") )); var options = new SentryOptions { Dsn = ValidDsn, DiagnosticLogger = _testOutputLogger, SendClientReports = true, Debug = true }; var recorder = new ClientReportRecorder(options, _fakeClock); options.ClientReportRecorder = recorder; var httpTransport = new HttpTransport( options, new HttpClient(httpHandler), clock: _fakeClock ); // First request always goes through await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); var envelope = new Envelope( new Dictionary<string, object>(), new[] { // Should be dropped new EnvelopeItem( new Dictionary<string, object> {["type"] = "event"}, new EmptySerializable()), new EnvelopeItem( new Dictionary<string, object> {["type"] = "event"}, new EmptySerializable()), new EnvelopeItem( new Dictionary<string, object> {["type"] = "transaction"}, new EmptySerializable()), // Should stay new EnvelopeItem( new Dictionary<string, object> {["type"] = "other"}, new EmptySerializable()) }); // The client report should contain rate limit discards only. var expectedClientReport = new ClientReport(_fakeClock.GetUtcNow(), new Dictionary<DiscardReasonWithCategory, int> { {DiscardReason.RateLimitBackoff.WithCategory(DataCategory.Error), 2}, {DiscardReason.RateLimitBackoff.WithCategory(DataCategory.Transaction), 1} }); var expectedEnvelope = new Envelope( new Dictionary<string, object>(), new[] { new EnvelopeItem( new Dictionary<string, object> {["type"] = "other"}, new EmptySerializable()), EnvelopeItem.FromClientReport(expectedClientReport) }); var expectedEnvelopeSerialized = await expectedEnvelope.SerializeToStringAsync(_testOutputLogger, _fakeClock); // Act await httpTransport.SendEnvelopeAsync(envelope); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert actualEnvelopeSerialized.Should().BeEquivalentTo(expectedEnvelopeSerialized); } [Fact] public async Task SendEnvelopeAsync_Fails_RestoresDiscardedEventCounts() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => new HttpResponseMessage(HttpStatusCode.InternalServerError))); var options = new SentryOptions { Dsn = ValidDsn, DiagnosticLogger = _testOutputLogger, SendClientReports = true, Debug = true }; var httpTransport = new HttpTransport(options, new HttpClient(httpHandler)); // some arbitrary discarded events ahead of time var recorder = (ClientReportRecorder) options.ClientReportRecorder; recorder.RecordDiscardedEvent(DiscardReason.BeforeSend, DataCategory.Attachment); recorder.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error); recorder.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); // Act await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); // Assert recorder.DiscardedEvents.Should().BeEquivalentTo(new Dictionary<DiscardReasonWithCategory, int> { // These are the original items recorded. They should still be there. {DiscardReason.BeforeSend.WithCategory(DataCategory.Attachment), 1}, {DiscardReason.EventProcessor.WithCategory(DataCategory.Error), 2}, {DiscardReason.QueueOverflow.WithCategory(DataCategory.Security), 3}, // We also expect two new items recorded, due to the forced network failure. {DiscardReason.NetworkError.WithCategory(DataCategory.Error), 1}, // from the event {DiscardReason.NetworkError.WithCategory(DataCategory.Default), 1} // from the client report }); } [Fact] public async Task SendEnvelopeAsync_RateLimited_DoesNotRestoreDiscardedEventCounts() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => new HttpResponseMessage((HttpStatusCode)429))); var options = new SentryOptions { Dsn = ValidDsn, DiagnosticLogger = _testOutputLogger, SendClientReports = true, Debug = true }; var httpTransport = new HttpTransport(options, new HttpClient(httpHandler)); // some arbitrary discarded events ahead of time var recorder = (ClientReportRecorder) options.ClientReportRecorder; recorder.RecordDiscardedEvent(DiscardReason.BeforeSend, DataCategory.Attachment); recorder.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error); recorder.RecordDiscardedEvent(DiscardReason.EventProcessor, DataCategory.Error); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Security); // Act await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); // Assert var totalCounts = recorder.DiscardedEvents.Values.Sum(); Assert.Equal(0, totalCounts); } [Fact] public async Task SendEnvelopeAsync_AttachmentFail_DropsItem() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler()); var logger = new InMemoryDiagnosticLogger(); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, MaxAttachmentSize = 1, DiagnosticLogger = logger, Debug = true }, new HttpClient(httpHandler)); var attachment = new Attachment( AttachmentType.Default, new FileAttachmentContent("test1.txt"), "test1.txt", null); using var envelope = Envelope.FromEvent( new SentryEvent(), logger, new[] { attachment }); // Act await httpTransport.SendEnvelopeAsync(envelope); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert // (the envelope should have only one item) logger.Entries.Should().Contain(e => e.Message == "Failed to add attachment: {0}." && (string)e.Args[0] == "test1.txt"); actualEnvelopeSerialized.Should().NotContain("test1.txt"); } [Fact] public async Task SendEnvelopeAsync_AttachmentTooLarge_DropsItem() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler()); var logger = new InMemoryDiagnosticLogger(); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn, MaxAttachmentSize = 1, DiagnosticLogger = logger, Debug = true }, new HttpClient(httpHandler)); var attachmentNormal = new Attachment( AttachmentType.Default, new StreamAttachmentContent(new MemoryStream(new byte[] { 1 })), "test1.txt", null); var attachmentTooBig = new Attachment( AttachmentType.Default, new StreamAttachmentContent(new MemoryStream(new byte[] { 1, 2, 3, 4, 5 })), "test2.txt", null); using var envelope = Envelope.FromEvent( new SentryEvent(), null, new[] { attachmentNormal, attachmentTooBig }); // Act await httpTransport.SendEnvelopeAsync(envelope); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert // (the envelope should have only one item) logger.Entries.Should().Contain(e => string.Format(e.Message, e.Args) == "Attachment 'test2.txt' dropped because it's too large (5 bytes)."); actualEnvelopeSerialized.Should().NotContain("test2.txt"); } [Fact] public async Task SendEnvelopeAsync_ItemRateLimit_PromotesNextSessionWithSameId() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1:session") )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient(httpHandler)); var session = new Session("foo", "bar", "baz"); // First request always goes through await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); // Send session update with init=true await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent(), null, null, session.CreateUpdate(true, DateTimeOffset.Now))); // Pretend the rate limit has already passed foreach (var (category, _) in httpTransport.CategoryLimitResets) { httpTransport.CategoryLimitResets[category] = DateTimeOffset.Now - TimeSpan.FromDays(1); } // Act // Send another update with init=false (should get promoted) await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent(), null, null, session.CreateUpdate(false, DateTimeOffset.Now))); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert actualEnvelopeSerialized.Should().Contain("\"init\":true"); } [Fact] public async Task SendEnvelopeAsync_ItemRateLimit_DoesNotAffectNextSessionWithDifferentId() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1:session") )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient(httpHandler)); var session = new Session("foo", "bar", "baz"); // First request always goes through await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); // Send session update with init=true await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent(), null, null, session.CreateUpdate(true, DateTimeOffset.Now))); // Pretend the rate limit has already passed foreach (var (category, _) in httpTransport.CategoryLimitResets) { httpTransport.CategoryLimitResets[category] = DateTimeOffset.Now - TimeSpan.FromDays(1); } // Act // Send an update for different session with init=false (should NOT get promoted) var nextSession = new Session("foo2", "bar2", "baz2"); await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent(), null, null, nextSession.CreateUpdate(false, DateTimeOffset.Now))); var lastRequest = httpHandler.GetRequests().Last(); var actualEnvelopeSerialized = await lastRequest.Content!.ReadAsStringAsync(); // Assert actualEnvelopeSerialized.Should().NotContain("\"init\":true"); } [Fact] public void CreateRequest_AuthHeader_IsSet() { // Arrange var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); // Act using var request = httpTransport.CreateRequest(envelope); var authHeader = request.Headers.GetValues("X-Sentry-Auth").FirstOrDefault(); // Assert authHeader.Should().NotBeNullOrWhiteSpace(); } [Fact] public void CreateRequest_AuthHeader_IncludesVersion() { // Arrange var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); // Act using var request = httpTransport.CreateRequest(envelope); var authHeader = request.Headers.GetValues("X-Sentry-Auth").First(); // Assert var versionString = Regex.Match(authHeader, @"sentry_client=(\S+),sentry_key").Groups[1].Value; Assert.Contains(versionString, $"{SdkVersion.Instance.Name}/{SdkVersion.Instance.Version}"); } [Fact] public void CreateRequest_RequestMethod_Post() { // Arrange var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); // Act var request = httpTransport.CreateRequest(envelope); // Assert request.Method.Should().Be(HttpMethod.Post); } [Fact] public void CreateRequest_SentryUrl_FromOptions() { // Arrange var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); var uri = Dsn.Parse(ValidDsn).GetEnvelopeEndpointUri(); // Act var request = httpTransport.CreateRequest(envelope); // Assert request.RequestUri.Should().Be(uri); } [Fact] public async Task CreateRequest_Content_IncludesEvent() { // Arrange var httpTransport = new HttpTransport( new SentryOptions { Dsn = ValidDsn }, new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); // Act var request = httpTransport.CreateRequest(envelope); var requestContent = await request.Content!.ReadAsStringAsync(); // Assert requestContent.Should().Contain(envelope.TryGetEventId().ToString()); } [Fact] public void ProcessEnvelope_ShouldNotAttachClientReportWhenOptionDisabled() { var options = new SentryOptions { // Disable sending of client reports SendClientReports = false }; var httpTransport = Substitute.For<HttpTransportBase>(options, null, null); var recorder = options.ClientReportRecorder; recorder.RecordDiscardedEvent(DiscardReason.QueueOverflow, DataCategory.Error); var envelope = Envelope.FromEvent(new SentryEvent()); var processedEnvelope = httpTransport.ProcessEnvelope(envelope); // There should only be the one event in the envelope Assert.Equal(1, processedEnvelope.Items.Count); Assert.Equal("event", processedEnvelope.Items[0].TryGetType()); } }
using System; using JetBrains.Annotations; using UnityEngine; public class Character : MonoBehaviour { public GameObject gfxSide; public GameObject gfxForward; public GameObject gfxBack; public FacingDirection defaultDirection; public Vector2 desiredVelocity; private Rigidbody2D body; private Animator animator; private FacingDirection direction; public FacingDirection Direction { private set { if (this.direction != value) { this.direction = value; this.gfxForward.SetActive(value == FacingDirection.Down); this.gfxBack.SetActive(value == FacingDirection.Up); this.gfxSide.SetActive(value == FacingDirection.Left || value == FacingDirection.Right); this.gfxSide.transform.localScale = new Vector3(value == FacingDirection.Left ? -1 : 1, 1, 1); } } get => this.direction; } private void Start() { this.body = this.GetComponent<Rigidbody2D>(); this.animator = this.GetComponent<Animator>(); this.Direction = this.defaultDirection; } [UsedImplicitly] public void FaceCharacter(Character character) { this.Direction = DirectionUtil.Opposite(character.Direction); } private void FixedUpdate() { this.body.velocity = this.desiredVelocity; var moving = this.desiredVelocity.x != 0 || this.desiredVelocity.y != 0; if (moving) { var dir = DirectionUtil.FromVelocity(this.desiredVelocity); this.Direction = dir; } this.animator.SetBool("Walking", moving); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace ManageDomain { public class PermissionProvider { static PermissionProvider() { InitKeyTree(); } private static ManageDomain.BLL.PermissionBll permissionbll = new BLL.PermissionBll(); private static Dictionary<string, List<string>> PermissionCache = new Dictionary<string, List<string>>(); private static object locker = new object(); private static readonly List<PermissionItem> PermissionTree = new List<PermissionItem>(); public static bool Exist(int managerid, SystemPermissionKey key) { var v = EnumHelper.GetEnumAttr<PermissionKeyAttribute>(key); if (v == null) return true; return Exist(managerid, v.Key); } public static void ClearCache() { lock (locker) { PermissionCache.Clear(); } } public static bool Exist(SystemPermissionKey key) { int id = Pub.CurrUserId(); if (id <= 0) return false; var v = EnumHelper.GetEnumAttr<PermissionKeyAttribute>(key); if (v == null) return true; return Exist(id, v.Key); } public static bool Exist(int managerid, string key) { return permissionbll.ManagerExistKey(managerid, key); } public static bool ExistWidthCache(int managerid, string key) { if (managerid <= 0) return false; if (!PermissionCache.ContainsKey(managerid.ToString())) { InitManagerKeys(managerid); } var keys = PermissionCache[managerid.ToString()]; if (keys.Contains(key.ToLower())) return true; return false; } public static bool ExistWidthCache(SystemPermissionKey key) { int managerid = Pub.CurrUserId(); if (managerid <= 0) return false; var v = EnumHelper.GetEnumAttr<PermissionKeyAttribute>(key); if (v == null) return false; return ExistWidthCache(managerid, v.Key); } public static void CheckExist(SystemPermissionKey key) { int id = Pub.CurrUserId(); if (id <= 0) { throw new MException(MExceptionCode.NoPermission, "不允许未登录用户!"); } var v = EnumHelper.GetEnumAttr<PermissionKeyAttribute>(key); if (v == null) return; bool exist = Exist(id, v.Key); if (exist == false) { throw new MPermissionException(key, "你没有操作权限!"); } } public static int GetManagerId() { if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated) return 0; var token = Pub.GetTokenModel(System.Web.HttpContext.Current.User.Identity.Name); if (token == null) return 0; return CCF.DB.LibConvert.ObjToInt(token.Id); } public static void InitManagerKeys(int managerid) { var keys = permissionbll.GetManagerKeys(managerid); if (keys == null) keys = new List<string>(); for (int i = 0; i < keys.Count; i++) { keys[i] = keys[i].ToLower(); } lock (locker) { PermissionCache[managerid.ToString()] = keys; } } public static void RemoveManagerKeys(int mangerid) { lock (locker) { PermissionCache.Remove(mangerid.ToString()); } } public static string GetPermissionKey(SystemPermissionKey key) { var keys = EnumHelper.GetEnumAttr<PermissionKeyAttribute>(key); if (keys == null) return ""; return keys.Key; } private static void InitKeyTree() { List<PermissionItem> items = new List<PermissionItem>(); var types = typeof(SystemPermissionKey); var ens = types.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (var a in ens) { ManageDomain.PermissionKeyAttribute currattr = null; var attr = a.GetCustomAttributes(typeof(ManageDomain.PermissionKeyAttribute), false); if (attr != null && attr.Length > 0) currattr = attr[0] as ManageDomain.PermissionKeyAttribute; if (currattr == null) continue; if (!string.IsNullOrEmpty(currattr.Key)) { if (items.Exists(x => x.Key == currattr.Key.ToLower())) continue; } items.Add(new PermissionItem() { GroupName = currattr.Group ?? "", HasPermission = 0, Key = currattr.Key.ToLower(), Name = currattr.Name, SubPermissions = new List<PermissionItem>() }); } for (int i = items.Count - 1; i >= 0; i--) { var curr = items[i]; if (!string.IsNullOrEmpty(curr.GroupName)) { for (int k = 0; k < items.Count; k++) { if (k == i) continue; if (SetSub(items[k], items[i])) { items.Remove(curr); break; } } } } PermissionTree.AddRange(items); } private static bool SetSub(PermissionItem parent, PermissionItem sub) { if (!string.IsNullOrEmpty(parent.Name) && !string.IsNullOrEmpty(sub.GroupName)) { if (parent.Name == sub.GroupName) { parent.SubPermissions.Add(sub); return true; } } foreach (var a in parent.SubPermissions) { bool isok = SetSub(a, sub); if (isok) return true; } return false; } public static List<PermissionItem> GetPermissionTree() { List<PermissionItem> items = new List<PermissionItem>(); foreach (var a in PermissionTree) { items.Add(a.Clone()); } return items; } } public class PermissionItem { public string Key { get; set; } public string Name { get; set; } public string GroupName { get; set; } public int HasPermission { get; set; } public PermissionItem Clone() { var newmodel = new PermissionItem() { SubPermissions = new List<PermissionItem>(), GroupName = this.GroupName, Name = this.Name, Key = this.Key, HasPermission = this.HasPermission, }; foreach (var a in this.SubPermissions) newmodel.SubPermissions.Add(a.Clone()); return newmodel; } public List<PermissionItem> SubPermissions { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DinucleotidesFrq.Models; using DinucleotidesFrq.Helpers; namespace DinucleotidesFrq.Controllers { public class SeqInputController : Controller { public ActionResult SeqIn(SequenceModels sequenceModels, string choose) { switch(choose) { //case "add-test": //sequenceModels.TestSeq.TSeq = sequenceModels.TestSeq.TSeq; //break; case "make-random": RandomSeq randomSeq = new RandomSeq(); sequenceModels.Seq.Seq = randomSeq.RandSeq(); break; case "add-random": sequenceModels.Seq.Seq = sequenceModels.RandomSeq.Seq; break; //case "add-from-list": //SequenceFile sequenceFile = new SequenceFile(); //sequenceFile.SeqFile(sequenceModels); //break; } return View ("~/Views/Home/Index.cshtml", sequenceModels); } } }
using System; namespace Domain.Entities { public class MeuJogo { public Guid MeusJogosId { get; set; } public JogoPlataforma JogoPlataforma { get; set; } public bool Desejo { get; set; } public DateTime DataDesejo { get; set; } public bool Troco { get; set; } public bool Vendo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using KPIDemo.Service; using KPIDemo.DTO; using KPIDemo.Models; using KPIDemo.DataAccess; using KPIDemo.Entity; namespace KPIDemo.Controllers { public class HomeController : Controller { private ICourseService courseService; public HomeController(ICourseService courseService) { this.courseService = courseService; } public IActionResult Index() { var courses = courseService.List(); return View(courses); } public IActionResult Edit(Guid id) { if(id != null && id != Guid.Empty) { var course = courseService.Get(id); return View(course); } else { return View(); } } public IActionResult AddStudent (Guid id) { return View(); } // POST: /Account/Register [HttpPost] public IActionResult Edit(CourseDto model) { if (ModelState.IsValid) { if(model.Id != Guid.Empty && model.Id != null) { this.courseService.Update(model); } else { model.CourseResults = new List<CourseResult>(); this.courseService.Insert(model); } } return View(model); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View("~/Views/Shared/Error.cshtml"); } [HttpPost] public ActionResult DeleteCourse(Guid courseId) { var response = new JsonResponse(); if (courseId == null || courseId == Guid.Empty) { response.IsSuccess = false; response.Message = "We cannot find the course"; response.CssClass = "red"; return Json(response); } else { try { this.courseService.Delete(courseId); response.ObjectId = courseId; response.IsSuccess = true; response.Message = "Course delete successfully!"; response.CssClass = "green"; return Json(response); } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; response.CssClass = "red"; return Json(response); } } } [HttpPost] public JsonResult IsCourseExists(string name) { return Json(!this.courseService.IsCourseExists(name)); } } }
using System.Data.Entity.ModelConfiguration; using Properties.Core.Objects; namespace Properties.Infrastructure.Data.Mapping { public class PhotoMap : EntityTypeConfiguration<Photo> { public PhotoMap() { Property(p => p.PhotoReference) .HasMaxLength(25); Property(p => p.PhotoUrl) .HasColumnType("nvarchar") .HasMaxLength(255); Ignore(p => p.IsDirty); } } }
using MemberRegistrationMicroservice.DataAccess.Abstract; using MemberRegistrationMicroservice.Entities.Concrete; using OK.Core.DataAccess.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MemberRegistrationMicroservice.DataAccess.Concrete.EntityFramework { public class EfMemberDal:EFEntityRepositoryBase<Member, MembershipContext>, IMemberDal { } }
using System; using Phenix.Core.Data; namespace Phenix.Test.使用指南._03._5 { /// <summary> /// /// </summary> [Serializable] [System.ComponentModel.DisplayName("")] [Phenix.Core.Mapping.Class("PH_USER", FriendlyName = "")] public class UserEasy : EntityBase<UserEasy> { private UserEasy() { //禁止添加代码 } /// <summary> /// 构建实体 /// </summary> protected override object CreateInstance() { return new UserEasy(); } /// <summary> /// 标签 /// 缺省为唯一键值 /// 用于提示信息等 /// </summary> [System.ComponentModel.Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] public override string Caption { get { return base.Caption; } } /// <summary> /// 主键值 /// </summary> [System.ComponentModel.Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] public override string PrimaryKey { get { return US_ID.ToString(); } } /// <summary> /// US_ID /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<long?> US_IDProperty = RegisterProperty<long?>(c => c.US_ID, "US_ID"); /// <summary> /// US_ID /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_ID", TableName = "PH_USER", ColumnName = "US_ID", IsPrimaryKey = true, NeedUpdate = true)] private long? _US_ID; /// <summary> /// US_ID /// </summary> [System.ComponentModel.DisplayName("US_ID")] public long? US_ID { get { return _US_ID; } set { SetProperty(US_IDProperty, ref _US_ID, value); } } /// <summary> /// US_USERNUMBER /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<string> UsernumberProperty = RegisterProperty<string>(c => c.Usernumber, "US_USERNUMBER"); /// <summary> /// US_USERNUMBER /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_USERNUMBER", Alias = "US_USERNUMBER", TableName = "PH_USER", ColumnName = "US_USERNUMBER", NeedUpdate = true)] private string _usernumber; /// <summary> /// US_USERNUMBER /// </summary> [System.ComponentModel.DisplayName("US_USERNUMBER")] public string Usernumber { get { return _usernumber; } set { SetProperty(UsernumberProperty, ref _usernumber, value); } } /// <summary> /// US_PASSWORD /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<string> PasswordProperty = RegisterProperty<string>(c => c.Password, "US_PASSWORD"); /// <summary> /// US_PASSWORD /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_PASSWORD", Alias = "US_PASSWORD", TableName = "PH_USER", ColumnName = "US_PASSWORD", NeedUpdate = true)] private string _password; /// <summary> /// US_PASSWORD /// </summary> [System.ComponentModel.DisplayName("US_PASSWORD")] public string Password { get { return _password; } set { SetProperty(PasswordProperty, ref _password, value); } } /// <summary> /// US_NAME /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name, "US_NAME"); /// <summary> /// US_NAME /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_NAME", Alias = "US_NAME", TableName = "PH_USER", ColumnName = "US_NAME", NeedUpdate = true, IsNameColumn = true, InLookUpColumn = true, InLookUpColumnDisplay = true)] private string _name; /// <summary> /// US_NAME /// </summary> [System.ComponentModel.DisplayName("US_NAME")] public string Name { get { return _name; } set { SetProperty(NameProperty, ref _name, value); } } /// <summary> /// US_DP_ID /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<long?> US_DP_IDProperty = RegisterProperty<long?>(c => c.US_DP_ID, "US_DP_ID"); /// <summary> /// US_DP_ID /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_DP_ID", TableName = "PH_USER", ColumnName = "US_DP_ID", NeedUpdate = true)] private long? _US_DP_ID; /// <summary> /// US_DP_ID /// </summary> [System.ComponentModel.DisplayName("US_DP_ID")] public long? US_DP_ID { get { return _US_DP_ID; } set { SetProperty(US_DP_IDProperty, ref _US_DP_ID, value); } } /// <summary> /// US_PT_ID /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<long?> US_PT_IDProperty = RegisterProperty<long?>(c => c.US_PT_ID, "US_PT_ID"); /// <summary> /// US_PT_ID /// </summary> [Phenix.Core.Mapping.Field(FriendlyName = "US_PT_ID", TableName = "PH_USER", ColumnName = "US_PT_ID", NeedUpdate = true)] private long? _US_PT_ID; /// <summary> /// US_PT_ID /// </summary> [System.ComponentModel.DisplayName("US_PT_ID")] public long? US_PT_ID { get { return _US_PT_ID; } set { SetProperty(US_PT_IDProperty, ref _US_PT_ID, value); } } /// <summary> /// US_Locked /// </summary> public static readonly Phenix.Core.Mapping.PropertyInfo<bool?> LockedProperty = RegisterProperty<bool?>(c => c.Locked); [Phenix.Core.Mapping.Field(FriendlyName = "US_Locked", Alias = "US_Locked", TableName = "PH_User", ColumnName = "US_Locked")] private int? _locked; /// <summary> /// US_Locked /// </summary> [System.ComponentModel.DataAnnotations.Display(Name = "US_Locked")] [System.ComponentModel.DisplayName("US_Locked")] public bool? Locked { get { return GetPropertyConvert(LockedProperty, _locked); } set { SetPropertyConvert(LockedProperty, ref _locked, value); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace GerenciamentoFuncionarios.Models { [Table("Funcionarios")] public class Funcionario { [Key] public int Id { get; set; } [DisplayName("Nome completo")] [Column(TypeName = "nvarchar(250)")] [Required(ErrorMessage = "Este campo é obrigatório.")] public string NomeCompleto { get; set; } [DisplayName("Código")] [Column(TypeName = "nvarchar(10)")] public string Codigo { get; set; } [DisplayName("Posição")] [Column(TypeName = "nvarchar(100)")] public string Posicao { get; set; } [DisplayName("Localização do escritório")] [Column(TypeName = "nvarchar(100)")] public string LocalizacaoEscritorio { get; set; } } }
using System; using System.ComponentModel.DataAnnotations.Schema; namespace Inventory.Data { public class MenuFolderModifier : BaseEntity { public Guid RowGuid { get; set; } public Guid MenuFolderGuid { get; set; } [ForeignKey(nameof(MenuFolderGuid))] public virtual MenuFolder MenuFolder { get; set; } public Guid ModifierGuid { get; set; } [ForeignKey(nameof(ModifierGuid))] public virtual Modifier Modifier { get; set; } } }
using _01_Alabo.Cloud.Core.SendSms.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using MongoDB.Bson; namespace _01_Alabo.Cloud.Core.SendSms.Domain.Services { /// <summary> /// 短信服务 /// </summary> public class SmsService : ServiceBase<SmsSend, ObjectId>, ISmsService { public SmsService(IUnitOfWork unitOfWork, IRepository<SmsSend, ObjectId> repository) : base(unitOfWork, repository) { } } }
using System; using System.Collections.Generic; using System.Text; namespace Course.Generics { /* * Essa class resolveria o problema de "reuso" das classes "PrintServiceInt" e "PrintServiceString". Pois ela permite trabalhar com a qualquer tipo de dados. * Enquanto que a class "PrintServiceInt" foi codificado para trabalhar com o tipo "int" e a "PrintServiceString" com o tipo "string" * * Mas o problema da class "PrintServiceObject" é o "type safety" e a "performance" * Exemplo: Se a gente quisesse atribuir o valor de retorno do método "First()" para uma variável "int", * a gente precisaria fazer uma conversão manual (casting) deste jeito: int x = (int)First(). Para além de não ser bom, ele não oferece a garantia de tipificação, * ou seja, o "compilador" não irá acionar "Error" se o método "First()" retornasse uma "string", O que fará com que o "Error" vá para o tempo de "execução". * * A melhor solução seria usar uma classe do tipo <T> como mostra a class "PrintServiceGeneric<T>", que é chamado de classe genérico: */ class PrintServiceObject { private object[] _values = new object[10]; private int count = 0; public void AddValue(object value) { if (count == 10) { throw new InvalidOperationException("PrintService is full"); } _values[count] = value; count++; } public object First() { if (count == 0) { throw new InvalidOperationException("PrintService is empty"); } return _values[0]; } public void Print() { Console.Write("["); for (int i = 0; i < count - 1; i++) { Console.Write(_values[i] + ", "); } if (count > 0) { Console.Write(_values[count - 1]); } Console.Write("]"); } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class MainInGame : MonoBehaviour { public GameObject[] Levels; private static bool touch = false; private Camera Cam; private bool fix = false; public Sprite[] SpritesCount; [HideInInspector] public int fixCount; private GameObject CurrentLevel; private bool GameOver = false; IEnumerator Start () { CurrentLevel = Levels [PlayerPrefs.GetInt ("iLevel") - 1]; CurrentLevel.SetActive (true); fixCount = Levels [PlayerPrefs.GetInt ("iLevel") - 1].GetComponent<PlatformRotation> ().CountOfFix; GameObject.Find ("FixCount").GetComponent<SpriteRenderer>().sprite = SpritesCount[fixCount]; touch = false; Cam = GameObject.Find ("Camera").GetComponent<Camera>(); if (GameObject.Find ("Player").GetComponent<Rigidbody2D> ().isKinematic) FIX (); yield return new WaitForSeconds (0.5f); touch = true; } public void Menu(){ if (touch) { touch = false; StartCoroutine (AwaitMenu ()); } } IEnumerator AwaitMenu(){ Time.timeScale = 1; GameObject.Find ("iFon").GetComponent<Animation> ().Play ("from iFon"); GameObject.Find ("ButtonMenu").GetComponent<AudioSource> ().Play (); float camCount = 1f; while (camCount > 0) { Cam.transform.position += new Vector3 (0.02f, 0, 0); camCount -= 0.02f; yield return new WaitForFixedUpdate (); } SceneManager.LoadScene ("Menu"); } public void Pause(){ if (touch && Time.timeScale != 0) { touch = false; StartCoroutine (AwaitPause ()); } } IEnumerator AwaitPause(){ GameObject.Find ("Pause").GetComponent<AudioSource> ().Play (); GameObject.Find ("Pause Panel").GetComponent<Animation> ().Play ("To Pause"); GameObject.Find ("Music").GetComponent<AudioSource> ().pitch = 0; yield return new WaitForSeconds (0.4f); Time.timeScale = 0; AudioListener.pause = true; touch = true; } public void Continue(){ if (touch && Time.timeScale == 0) { touch = false; StartCoroutine (AwaitContinue ()); } } IEnumerator AwaitContinue(){ if (PlayerPrefs.GetInt ("Sounds") == 1) AudioListener.pause = false; GameObject.Find ("Continue").GetComponent<AudioSource> ().Play (); GameObject.Find ("Pause Panel").GetComponent<Animation> ().Play ("From Pause"); Time.timeScale = 1; GameObject.Find ("Music").GetComponent<AudioSource> ().pitch = 1; yield return new WaitForSeconds (0.4f); touch = true; } public void FIX(){ if (fix == false) { if (fixCount > 0) { fixCount--; fix = !fix; GameObject.Find ("Fix").GetComponent<Animation> ().Play ("To Fix"); StartCoroutine (AwaitFIX()); CurrentLevel.GetComponent<PlatformRotation> ().Player.velocity = new Vector2 (0, 0); CurrentLevel.GetComponent<PlatformRotation> ().Player.angularVelocity = 0; CurrentLevel.GetComponent<PlatformRotation> ().Player.isKinematic = true; CurrentLevel.GetComponent<PlatformRotation> ().FixOn.SetActive(true); GameObject.Find ("Pause").GetComponent<AudioSource> ().Play (); } } else { fix = !fix; GameObject.Find ("Fix").GetComponent<Animation> ().Play ("From Fix"); CurrentLevel.GetComponent<PlatformRotation> ().Player.isKinematic = false; CurrentLevel.GetComponent<PlatformRotation> ().FixOn.SetActive(false); GameObject.Find ("Continue").GetComponent<AudioSource> ().Play (); } } IEnumerator AwaitFIX(){ yield return new WaitForSeconds (0.165f); GameObject.Find ("FixCount").GetComponent<SpriteRenderer>().sprite = SpritesCount[fixCount]; } public void Next(){ if (touch) { touch = false; StartCoroutine (AwaitNext ()); } } IEnumerator AwaitNext(){ Time.timeScale = 1; GameObject.Find ("iFon").GetComponent<Animation> ().Play ("from iFon"); GameObject.Find ("ButtonMenu").GetComponent<AudioSource> ().Play (); float camCount = 1f; while (camCount > 0) { Cam.transform.position += new Vector3 (0.02f, 0, 0); camCount -= 0.02f; yield return new WaitForFixedUpdate (); } if (!PlayerPrefs.HasKey ("endLevels") || GameOver) { SceneManager.LoadScene ("Levels"); } else { SceneManager.LoadScene ("Menu"); } } IEnumerator AwaitGameOver(){ yield return new WaitForSeconds (2); GameOver = true; Next (); } }
using System.Data.Common; namespace Kaax { public class DbConnectionFactoryOptions { public string ConnectionString { get; set; } public DbProviderFactory ProviderFactory { get; set; } } }
namespace Sentry.Internal; internal interface IAppDomain { event UnhandledExceptionEventHandler UnhandledException; event EventHandler ProcessExit; event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException; } internal sealed class AppDomainAdapter : IAppDomain { public static AppDomainAdapter Instance { get; } = new(); private AppDomainAdapter() { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; TaskScheduler.UnobservedTaskException += OnUnobservedTaskException; } public event UnhandledExceptionEventHandler? UnhandledException; public event EventHandler? ProcessExit; public event EventHandler<UnobservedTaskExceptionEventArgs>? UnobservedTaskException; private void OnProcessExit(object? sender, EventArgs e) => ProcessExit?.Invoke(sender, e); #if !NET6_0_OR_GREATER [HandleProcessCorruptedStateExceptions] #endif [SecurityCritical] private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) => UnhandledException?.Invoke(this, e); #if !NET6_0_OR_GREATER [HandleProcessCorruptedStateExceptions] #endif [SecurityCritical] private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) => UnobservedTaskException?.Invoke(this, e); }
using UnityEngine; using System.Collections; using UnityEngine.UI; /// <summary> /// Add this script to your tooltip gameObject to setup the GameObject containing the text for it. /// </summary> public class simpleTooltipWithText : MonoBehaviour { public Text text; public float maxWidth = 200f; public static float MaxWidth = 200f; public float padding = 5f; public static float Padding = 5f; void Awake() { MaxWidth = maxWidth; Padding = padding; text.rectTransform.anchoredPosition = new Vector2 (padding, -padding); } }
using SFA.DAS.CommitmentsV2.Api.Types.Responses; using System.Collections.Generic; using System.Linq; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using System; namespace SFA.DAS.ProviderCommitments.Web.Extensions { public static class DataLockMapExtensions { public static IEnumerable<CourseDataLockViewModel> MapCourseDataLock(this GetApprenticeshipResponse apprenticeship, IList<DataLockViewModel> dataLockWithCourseMismatch, IReadOnlyCollection<GetPriceEpisodesResponse.PriceEpisode> priceEpisodes) { if (apprenticeship.HasHadDataLockSuccess) return new CourseDataLockViewModel[0]; var result = new List<CourseDataLockViewModel>(); return dataLockWithCourseMismatch .Select(dataLock => { var previousPriceEpisode = priceEpisodes .OrderByDescending(m => m.FromDate) .FirstOrDefault(m => m.FromDate <= dataLock.IlrEffectiveFromDate); return new CourseDataLockViewModel { CurrentStartDate = previousPriceEpisode?.FromDate ?? DateTime.MinValue, CurrentEndDate = previousPriceEpisode?.ToDate, CurrentTrainingName = apprenticeship.CourseName, IlrTrainingName = dataLock.IlrTrainingCourseName, IlrEffectiveFromDate = dataLock.IlrEffectiveFromDate ?? DateTime.MinValue, IlrEffectiveToDate = dataLock.IlrPriceEffectiveToDate }; }).ToList(); } public static IEnumerable<PriceDataLockViewModel> MapPriceDataLock(this IReadOnlyCollection<GetPriceEpisodesResponse.PriceEpisode> priceEpisodes, IEnumerable<DataLock> dataLockWithOnlyPriceMismatch) { var dataLocks = dataLockWithOnlyPriceMismatch .OrderBy(x => x.IlrEffectiveFromDate); return dataLocks .Select(dataLock => { var previousPriceEpisode = priceEpisodes .OrderByDescending(m => m.FromDate) .FirstOrDefault(m => m.FromDate <= dataLock.IlrEffectiveFromDate); if (previousPriceEpisode == null) { previousPriceEpisode = priceEpisodes .OrderByDescending(m => m.FromDate) .FirstOrDefault(); } return new PriceDataLockViewModel { ApprenticeshipId = previousPriceEpisode.ApprenticeshipId, CurrentStartDate = previousPriceEpisode?.FromDate ?? DateTime.MinValue, CurrentEndDate = previousPriceEpisode?.ToDate, CurrentCost = previousPriceEpisode?.Cost ?? default(decimal), IlrEffectiveFromDate = dataLock.IlrEffectiveFromDate ?? DateTime.MinValue, IlrEffectiveToDate = dataLock.IlrPriceEffectiveToDate, IlrTotalCost = dataLock.IlrTotalCost ?? default(decimal) }; }).ToList(); } public static UpdateDateLockSummaryViewModel MapDataLockSummary(this GetDataLockSummariesResponse dataLockSummaries, GetAllTrainingProgrammesResponse trainingProgrammes) { var result = new UpdateDateLockSummaryViewModel { DataLockWithCourseMismatch = new List<DataLockViewModel>(), }; foreach (var dataLock in dataLockSummaries.DataLocksWithCourseMismatch) { var training = trainingProgrammes.TrainingProgrammes.SingleOrDefault(x => x.CourseCode == dataLock.IlrTrainingCourseCode); if (training == null) { throw new InvalidOperationException( $"Datalock {dataLock.Id} IlrTrainingCourseCode {dataLock.IlrTrainingCourseCode} not found; possible expiry"); } result.DataLockWithCourseMismatch.Add(MapDataLockStatus(dataLock, training)); } return result; } private static DataLockViewModel MapDataLockStatus(DataLock dataLock, TrainingProgramme training) { return new DataLockViewModel { DataLockEventDatetime = dataLock.DataLockEventDatetime, PriceEpisodeIdentifier = dataLock.PriceEpisodeIdentifier, ApprenticeshipId = dataLock.ApprenticeshipId, IlrTrainingCourseCode = dataLock.IlrTrainingCourseCode, IlrTrainingCourseName = training.Name, IlrActualStartDate = dataLock.IlrActualStartDate, IlrEffectiveFromDate = dataLock.IlrEffectiveFromDate, IlrPriceEffectiveToDate = dataLock.IlrPriceEffectiveToDate, IlrTotalCost = dataLock.IlrTotalCost, DataLockErrorCode = dataLock.ErrorCode }; } } }
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace SSDAssignmentBOX.Migrations { public partial class Rating : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Rating", columns: table => new { RatingId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), BookComments = table.Column<string>(maxLength: 100000, nullable: false), BookRating = table.Column<int>(nullable: false), BookTitle = table.Column<string>(maxLength: 100000, nullable: false), RatingTime = table.Column<DateTime>(nullable: false), User = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Rating", x => x.RatingId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Rating"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInRoom : MonoBehaviour { public string roomType; private GameObject player; private MusicManager mm; public bool pir; // Start is called before the first frame update void Start() { player = FindObjectOfType<PlayerMovement>().gameObject; mm = FindObjectOfType<MusicManager>(); } // Update is called once per frame void Update() { if (player != null && Mathf.Abs(player.transform.position.x - transform.position.x) < 9 && Mathf.Abs(player.transform.position.y - transform.position.y) < 5) { mm.currentSong = roomType; pir = true; } else pir = false; } }
#region MIT License /* * Copyright (c) 2009 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Original Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen. * Modified for Farseer engine by Mikko Röyskö */ using System; using FarseerPhysics.Common; using FarseerPhysics.Dynamics; using FarseerPhysics.Factories; using FarseerPhysics.Collision.Shapes; using Jypeli.Farseer; using Jypeli.Physics; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace Jypeli { /// <summary> /// Peliolio, joka noudattaa fysiikkamoottorin määräämiä fysiikan lakeja. /// Voidaan kuitenkin myös laittaa noudattamaan lakeja valikoidusti. /// </summary> public partial class PhysicsBody : IPhysicsBody { /// <summary> /// Kappaleen omistajaolio. /// </summary> public IPhysicsObject Owner { get; internal set; } /// <summary> /// Luotavien fysiikkakappaleiden oletustiheys. /// Oletuksena 0.001. /// </summary> public static float DefaultDensity { get; set; } = 0.001f; /// <summary> /// Jättääkö olio painovoiman huomioimatta. /// </summary> public bool IgnoresGravity { get { return FSBody.IgnoreGravity; } set { FSBody.IgnoreGravity = value; } } /// <summary> /// Jättääkö olio kaikki fysiikkalogiikat (ks. <c>AddPhysicsLogic</c>) /// huomiotta. Vaikuttaa esim. painovoimaan, mutta ei törmäyksiin. /// </summary> public bool IgnoresPhysicsLogics { get { return FSBody.IgnoreGravity; } // TODO: Mitä tän käytännössä pitäisi tehdä? set { FSBody.IgnoreGravity = value; } } /// <summary> /// Fysiikkamuodon muodostavat verteksit. /// </summary> public List<List<Vector2>> Vertices { get { List<List<Vector2>> vert = new List<List<Vector2>>(); for (int i = 0; i < FSBody.FixtureList.Count; i++) { vert.Add(new List<Vector2>()); Fixture f = FSBody.FixtureList[i]; if (f.Shape is PolygonShape shape) vert[i].AddRange(shape.Vertices); } return vert; } } #region Constructors /// <summary> /// Luo uuden fysiikkaolion. /// </summary> /// <param name="width">Leveys.</param> /// <param name="height">Korkeus.</param> /// <param name="world">Fysiikkamoottorin maailma johon kappale luodaan.</param> public PhysicsBody(double width, double height, World world) : this(width, height, Shape.Rectangle, world) { } /// <summary> /// Luo uuden fysiikkaolion. /// </summary> /// <param name="width">Leveys.</param> /// <param name="height">Korkeus.</param> /// <param name="shape">Muoto.</param> /// <param name="world">Fysiikkamoottorin maailma johon kappale luodaan.</param> public PhysicsBody(double width, double height, Shape shape, World world) { this._size = new Vector(width, height) * FSConvert.DisplayToSim; this._shape = shape; FSBody = world.CreateBody(bodyType: BodyType.Dynamic);// BodyFactory.CreateBody(world, bodyType: BodyType.Dynamic); FSBody.owner = this; FSBody.Enabled = false; if (shape is Ellipse && width == height) { Fixture f = FixtureFactory.AttachCircle((float)height * FSConvert.DisplayToSim / 2, DefaultDensity, FSBody); f.Tag = FSBody; } else { List<Vertices> vertices = CreatePhysicsShape(shape, this._size); List<Fixture> fixtures = FixtureFactory.AttachCompoundPolygon(vertices, DefaultDensity, FSBody); fixtures.ForEach((f) => f.Tag = FSBody); } } /// <summary> /// Luo fysiikkaolion, jonka muotona on säde. /// </summary> /// <param name="raySegment">Säde.</param> /// <param name="world">Fysiikkamoottorin maailma johon kappale luodaan</param> public PhysicsBody(RaySegment raySegment, World world) : this(1, 1, raySegment, world) { this._size = Vector.One; this._shape = raySegment; } #endregion public void Update(Time time) { } public void SetCollisionIgnorer(Ignorer ignorer) { if (ignorer is null) { FSBody.JypeliGroupIgnorer = null; FSBody.ObjectIgnorer = null; return; } if (ignorer is JypeliGroupIgnorer) { JypeliGroupIgnorer ign = ignorer as JypeliGroupIgnorer; FSBody.JypeliGroupIgnorer = ign; } else if (ignorer is ObjectIgnorer || ignorer is null) { ObjectIgnorer ign = ignorer as ObjectIgnorer; FSBody.ObjectIgnorer = ign; } else throw new NotImplementedException("Annettu Ignore ei ole toteutettu."); } /// <summary> /// Muodostaa uudelleen yhdistettyjen fysiikkakappaleiden fysiikkamuodot. /// Kutsuttava jos esim. lapsiolion paikkaa tai kokoa muutetaan. /// </summary> /// <param name="physObj">Kappale jonka ominaisuuksia muutettiin.</param> public void RegenerateConnectedFixtures() { /** * "Post-order" puuhakualgoritmi. * Jos muokataan obj3, tälle voidaan antaa parametrina obj3, obj2 tai obj1 ilman ongelmia. * obj1 * obj2 * obj3 * obj4 * obj5 * obj6 */ PhysicsObject physObj = this.Owner as PhysicsObject; SynchronousList<GameObject> childs = physObj.Objects; foreach (var child in childs) { if (child is PhysicsObject) { if (!child.IsAddedToGame) continue; PhysicsObject physChild = child as PhysicsObject; physChild.Parent.Size *= 1; physChild.Body.RegenerateConnectedFixtures(); } } PhysicsBody physMainParent = (PhysicsBody)((PhysicsObject)physObj.GetMainParent()).Body; List<Fixture> fs = physMainParent.FSBody.FixtureList._list; for (int i = 0; i < fs.Count; i++) { if ((Body)fs[i].Tag == ((PhysicsBody)physObj.Body).FSBody) physMainParent.FSBody.Remove(fs[i]); } if (physObj.Parent != null) PhysicsGame.Instance.Engine.ConnectBodies((PhysicsObject)physObj.Parent, physObj); } } /* class CollisionIgnorerAdapter : Physics2DDotNet.Ignorers.Ignorer { private Jypeli.Ignorer innerIgnorer; public override bool BothNeeded { get { return innerIgnorer.BothNeeded; } } protected override bool CanCollide( Body thisBody, Body otherBody, Physics2DDotNet.Ignorers.Ignorer other ) { var body1 = (Jypeli.PhysicsBody)( thisBody.Tag ); var body2 = (Jypeli.PhysicsBody)( otherBody.Tag ); var otherIgnorer = other == null ? null : ( (CollisionIgnorerAdapter)other ).innerIgnorer; return innerIgnorer.CanCollide( body1, body2, otherIgnorer ); } public CollisionIgnorerAdapter( Jypeli.Ignorer adaptee ) { this.innerIgnorer = adaptee; } }*/ }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DocumentSystem { public abstract class EncyptableDocument : BinaryDocument, IEncryptable { public bool isEncrypted = false; public bool IsEncrypted { get { return isEncrypted; } } public void Encrypt() { this.isEncrypted = true; } public void Decrypt() { this.isEncrypted = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Responses { public class CloudServerUsageDetailResponse { public List<UsageDetailItemResponse> Xlarge { get; set; } public List<UsageDetailItemResponse> Small { get; set; } public List<UsageDetailItemResponse> Large { get; set; } public List<UsageDetailItemResponse> Tiny { get; set; } public List<UsageDetailItemResponse> Medium { get; set; } } }
using System; using System.Collections.Generic; namespace GameAPI.Models { public class LoginRequest { /// <summary> /// Správné je "admin" /// </summary> public string UserName { get; set; } /// <summary> /// Správné je "admin" /// </summary> public string Password { get; set; } } public class LoginResponse { public bool LoggedIn { get; set; } public string AccessToken { get; set; } } public class LeaderboardScoreDTO { public string PlayerName { get; set; } public int Score { get; set; } } public class GetLeaderBoardRequest { /// <summary> /// Akční, RPG, MMO, Sportovní, Strategické nebo Závodní /// </summary> public string GameType { get; set; } } public class GetLeaderBoardResponse { public List<LeaderboardScoreDTO> Results { get; set; } } public class MatchDTO { public int Id { get; set; } public string Name { get; set; } public string AccessToken { get; set; } public MatchState State { get; set; } } public class GetActiveMatchesResponse { public List<MatchDTO> Matches { get; set; } } public class JoinMatchResponse { public string WebSocketToken { get; set; } } public enum MatchState { neaktivni, aktivni } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InstructionsDisplay : MonoBehaviour { // Start is called before the first frame update [SerializeField] private GameObject textSpace; [SerializeField] private PulsationConvertor pc; private float calibratedSince; void Start() { calibratedSince = -1; } // Update is called once per frame void Update() { if(!pc.getCalibrated()){ textSpace.SetActive(true); textSpace.GetComponent<Text>().text = "Calibration running..."; } else if(calibratedSince==-1){ textSpace.GetComponent<Text>().text = "Calibration done ! Normal beat rate around " + pc.getCalibrationValue()+" BPM"; calibratedSince = Time.time; } else if(Time.time - calibratedSince > 8){ textSpace.SetActive(false); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using DevExpress.XtraBars; using KartLib; using KartLib.Entities; using KartLib.Views; using KartObjects; using System.Text; using System.Drawing; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Grid.ViewInfo; using System.Xml.Serialization; using KartExchangeEngine; using KartObjects.Entities.Documents; using KartSystem.Common; using KartSystem.Views.Document; namespace KartSystem { public partial class DocumentsView : KartUserControl, IDocumentsView { public DocumentsView() { DocTypeFilter = new List<DocType>(); InitializeComponent(); UseSubmenu = false; ViewObjectType = ObjectType.Document; Preseneter = new DocumentsPresenter(this); dateEditBegin.DateTime = DateTime.Now; dateEditEnd.DateTime = DateTime.Now; foreach (DocType d in KartDataDictionary.sDocTypes) _ListDocTypeDocument.Add(d.Id, null); this.ContextMenu1 = new System.Windows.Forms.ContextMenu(); this.MenuItem1 = new System.Windows.Forms.MenuItem(); this.MenuItem2 = new System.Windows.Forms.MenuItem(); this.MenuItem3 = new System.Windows.Forms.MenuItem(); // // ContextMenu1 // this.ContextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.MenuItem1, this.MenuItem2, this.MenuItem3 }); // // MenuItem1 // this.MenuItem1.Index = 0; this.MenuItem1.Text = "Печать цеников"; this.MenuItem1.Click += this._PrintPrice; // // MenuItem2 // this.MenuItem2.Index = 1; this.MenuItem2.Text = "Печать ШК"; this.MenuItem2.Click += this._PrintLabel; // // MenuItem3 // this.MenuItem3.Index = 2; this.MenuItem3.Text = "Экспорт"; this.MenuItem3.Click += this._GenerateDocument; } internal System.Windows.Forms.ContextMenu ContextMenu1; internal System.Windows.Forms.MenuItem MenuItem1; internal System.Windows.Forms.MenuItem MenuItem2; internal System.Windows.Forms.MenuItem MenuItem3; public void ShowGridMenu(object sender, DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs e) { GridView view = (GridView)sender; GridHitInfo hitInfo = view.CalcHitInfo(e.Point); if (hitInfo.InRow) { view.FocusedRowHandle = hitInfo.RowHandle; ContextMenu1.Show(view.GridControl, e.Point); } } #region IDocumentsView Members public IList<Document> Documents { get; set; } public IList<DocType> DocTypeFilter { get; set; } #endregion #region IView Members public void RefreshView() { (Preseneter as DocumentsPresenter).LoadDocuments(); Document d = ActiveDocument; gridControlDocuments.DataSource = Documents; if (d != null) ActiveDocument = d; //gvDocuments.RefreshData(); //gvDocuments.Focus(); if (ActiveDocument != null) cbDocStatus.Checked = (ActiveDocument.Status == 1); } public void InitDocumentsView() { lueWarehouses.Properties.DataSource = KartDataDictionary.sWarehouses; rilueWarehouse.DataSource = KartDataDictionary.sWarehouses; rileDocType.DataSource = Loader.DbLoad<DocType>("");//KartDataDictionary.sDocTypes; if (KartDataDictionary.CurrWh != null) { lueWarehouses.EditValue = KartDataDictionary.CurrWh; lueWarehouses.Enabled = false; } gvleStatus.DataSource = KartDataDictionary.sDocStatuses; gridControlDocuments.DataSource = Documents; dateEditBegin.Focus(); tlDocKind.DataSource = KartDataDictionary.sDocKinds; tlDocKind.ExpandAll(); tlDocKind.SetFocusedNode(tlDocKind.FindNodeByKeyID(InitIdDocKind)); tlDocKind.FocusedNodeChanged += new DevExpress.XtraTreeList.FocusedNodeChangedEventHandler(tlDocKind_FocusedNodeChanged); tlDocKind_FocusedNodeChanged(this, new DevExpress.XtraTreeList.FocusedNodeChangedEventArgs(null, tlDocKind.FocusedNode)); if (InitIdDocument != null) for (int i = 0; i < gvDocuments.RowCount; i++) { if ((gvDocuments.GetRow(i) as Document).Id == InitIdDocument) { gvDocuments.ClearSelection(); gvDocuments.FocusedRowHandle = i; gvDocuments.SelectRow(i); break; } } dateEditBegin.EditValueChanged += new EventHandler(dateEditBegin_EditValueChanged); dateEditEnd.EditValueChanged += new EventHandler(dateEditEnd_EditValueChanged); } #endregion public Document ActiveDocument { get { return gvDocuments.GetFocusedRow() as Document; } set { if (value == null) { gvDocuments.ClearSelection(); gvDocuments.FocusedRowHandle = 0; gvDocuments.SelectRow(0); return; } gvDocuments.ClearSelection(); for (int i = 0; i < gvDocuments.RowCount; i++) { if ((gvDocuments.GetRow(i) as Document).Id == value.Id) { gvDocuments.ClearSelection(); gvDocuments.FocusedRowHandle = i; gvDocuments.SelectRow(i); break; } } } } public List<Document> ActiveDocuments { get { List<Document> resultList = new List<Document>(); ; int[] selectedRows = gvDocuments.GetSelectedRows(); if (selectedRows.Count() > 0) { foreach (int i in selectedRows) { resultList.Add((Document)gvDocuments.GetRow(i)); } } return resultList; } } private void DocumentsView_Load(object sender, EventArgs e) { MainView form = FindForm() as MainView; if (form != null) { form.bbiNewInvoice.ItemClick += new ItemClickEventHandler(barButtonNewInvoice_ItemClick); form.bbiNewReturn.ItemClick += new ItemClickEventHandler(barButtonNewReturn_ItemClick); form.bbiNewRevaluation.ItemClick += new ItemClickEventHandler(barButtonNewRevaluationAct_ItemClick); form.bbiNewInventory.ItemClick += new ItemClickEventHandler(barNewInventoryDoc_ItemClick); form.bbiNewExpDocument.ItemClick += new ItemClickEventHandler(bbiNewExpDocument_ItemClick); form.bbiNewAct.ItemClick += new ItemClickEventHandler(bbiNewAct_ItemClick); } Preseneter.ViewLoad(); InitDocumentsView(); } /// <summary> /// Новый акт для печати ценников /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void bbiNewAct_ItemClick(object sender, ItemClickEventArgs e) { InventoryDocument doc = new InventoryDocument(); doc.IsNew = true; DocType d = KartDataDictionary.sDocTypes.FirstOrDefault(dt => { return !dt.IsReversal && !dt.IsTradeOper && (dt.Multiplicator == 0); }); if (d != null) { doc.IdDocType = d.Id; doc.Number = (Loader.DataContext.ExecuteScalar("select DOCNUMBER from GET_LAST_DOCNUM(" + d.Id + ")")).ToString();//"select cast(DOCNUMBER as varchar(40)) from GET_LAST_DOCNUM(" + d.Id+")" } doc.ExtDate = DateTime.Now; doc.DateDoc = DateTime.Now; InventoryDocEditor form = new InventoryDocEditor(doc); form.SetActiveSpecifiactionPage(); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } } public void bbiNewExpDocument_ItemClick(object sender, ItemClickEventArgs e) { Document doc = new Document(); doc.IsNew = true; DocType d = KartDataDictionary.sDocTypes.FirstOrDefault(dt => { return !dt.IsReversal && dt.IsTradeOper && (dt.Multiplicator == -1); }); if (d != null) { doc.IdDocType = d.Id; doc.Number = (Loader.DataContext.ExecuteScalar("select DOCNUMBER from GET_LAST_DOCNUM(" + d.Id + ")")).ToString();//"select cast(DOCNUMBER as varchar(40)) from GET_LAST_DOCNUM(" + d.Id+")" } doc.ExtDate = DateTime.Now; doc.DateDoc = DateTime.Now; XExpDocEditor form = new XExpDocEditor(doc); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } } private void buttonOpen_Click(object sender, EventArgs e) { UpdateDocList(); } private void UpdateDocList() { ShowStatus("Загрузка документов..."); try { //(_preseneter as DocumentsPresenter).LoadDocuments(); RefreshView(); } finally { ShowStatus(string.Empty); } } public override bool RecordSelected { get { return gvDocuments.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle; } } public override void EditorAction(bool addMode) { bool NeedDockKind = false; if (addMode && tlDocKind.FocusedNode.ParentNode == null) NeedDockKind=true; else if (addMode && tlDocKind.FocusedNode.HasChildren) NeedDockKind = true; if (NeedDockKind) { MessageBox.Show(this, "Выберите тип документа.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Document document = addMode ? new Document() : ActiveDocument; if (document == null) return; if (addMode) { if (ActiveDocument != null) if (KartDataDictionary.getAxiTradeParamValueAsBool(AxiParamNames.UseActiveDocSupplier)) { document.IdSupplier = ActiveDocument.IdSupplier; document.ExtDate = DateTime.Now; } document.IdDocType = DocTypeFilter[0].Id; if (lueWarehouses.EditValue != null) document.IdWarehouse = (lueWarehouses.EditValue as Warehouse).Id; document.IsNew = true; ActiveDocument = document; } else //Обновляем документ перед редактированием, защита от смены статуса (Preseneter as DocumentsPresenter).refreshDoc(ref document); // Создаем вьюху для редактирования IDocumentEditView editView = null; try { editView = getDocEditor(document); editView.ColumnAutoWidth = ceAutoColumnWidth.Checked; // Если сохранение прошло успешно, нужно обновить представление if ((editView as Form).ShowDialog() == DialogResult.OK) { if (addMode) { Documents.Add(editView.Document as Document); } else { Documents[Documents.IndexOf(ActiveDocument)] = editView.Document as Document; } // (_preseneter as DocumentsPresenter).refreshDoc(ref editView.Document); RefreshView(); gridControlDocuments.RefreshDataSource(); ActiveDocument = editView.Document as Document; gvDocuments.RefreshData(); gvDocuments.Focus(); } else { /*if (addMode) { User ActiveUser = KartDataDictionary.user; (editView.Document as Document).IdUser = ActiveUser.Id; //Saver.DeleteFromDb<Document>((editView.Document as Document).GetDocumentInstance()); }*/ RefreshView(); ActiveDocument = editView.Document as Document; } } finally { if (editView != null) { ((IDisposable)editView).Dispose(); } GC.Collect(); } } /// <summary> /// Получение редактора документа по его типу /// </summary> /// <param name="document"></param> /// <returns></returns> public static IDocumentEditView getDocEditor(Document document) { DocType doctype = (from d in KartDataDictionary.sDocTypes where d.Id == document.IdDocType select d).First(); if ((doctype.DocKind == DocKindEnum.MovingDoc) && (doctype.Multiplicator == 1)) { InvoiceDocument invDoc = Loader.DbLoadSingle<InvoiceDocument>("Id=" + document.Id); return new XIncDocEditor(invDoc); } if ((doctype.DocKind == DocKindEnum.MovingDoc) && (doctype.Multiplicator == -1)) { return new MoveExpDocEditor(document); } if ((doctype.DocKind == DocKindEnum.IncomeDoc) && (!doctype.IsReversal)) { InvoiceDocument invoiceDoc = null; if (document.IsNew) invoiceDoc = new InvoiceDocument(document); else invoiceDoc = Loader.DbLoadSingle<InvoiceDocument>("Id=" + document.Id); return new InvoiceDocsEditor(invoiceDoc); } if ((doctype.DocKind == DocKindEnum.ExpenseDoc) && (doctype.IsReversal)) { ReturnDocument invoiceDoc = null; if (document.IsNew) { invoiceDoc = new ReturnDocument(document); } else invoiceDoc = Loader.DbLoadSingle<ReturnDocument>("Id=" + document.Id); return new ReturnDocEditor(invoiceDoc); } if ((doctype.DocKind == DocKindEnum.Inventory)) { InventoryDocument invoiceDoc = null; if (document.IsNew) invoiceDoc = new InventoryDocument(document) { InventoryType = InventoryType.ExactInventory }; else invoiceDoc = Loader.DbLoadSingle<InventoryDocument>("Id=" + document.Id); return new InventoryDocEditor(invoiceDoc); } if ((doctype.DocKind == DocKindEnum.Revaluation)) { RevaluationDocument invoiceDoc = null; if (document.IsNew) invoiceDoc = new RevaluationDocument(document); else invoiceDoc = Loader.DbLoadSingle<RevaluationDocument>("Id=" + document.Id); return new RevaluationActEditor(invoiceDoc); } if ((doctype.DocKind == DocKindEnum.Contract)) //Контракт { Contract invoiceDoc = null; if (document.IsNew) invoiceDoc = new Contract(document); else invoiceDoc = Loader.DbLoadSingle<Contract>("Id=" + document.Id); return new ContractDocEditor(invoiceDoc); } if ((doctype.DocKind == DocKindEnum.Production)) //Производство { if (doctype.Multiplicator == -1 || doctype.Multiplicator == 0) { ProductionDocument invoiceDoc = null; if (document.IsNew) invoiceDoc = new ProductionDocument(document); else invoiceDoc = Loader.DbLoadSingle<ProductionDocument>("Id=" + document.Id); return new ProductionDocEditor(invoiceDoc); } else { InvoiceDocument invoiceDoc = null; if (document.IsNew) invoiceDoc = new InvoiceDocument(document); else invoiceDoc = Loader.DbLoadSingle<InvoiceDocument>("Id=" + document.Id); return new InvoiceDocsEditor(invoiceDoc); } } else return new XExpDocEditor(document); } public override void DeleteItem(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (ActiveDocument.Status != 1) { if (MessageBox.Show(this, "Вы уверены что хотите удалить документ?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { int Handle = gvDocuments.FocusedRowHandle; (Preseneter as DocumentsPresenter).deleteDoc(); RefreshView(); gvDocuments.ClearSelection(); gvDocuments.FocusedRowHandle = Handle - 1; gvDocuments.SelectRow(Handle - 1); } } } /// <summary> /// Выбраный склад /// </summary> public Warehouse Warehouse { get { return (Warehouse)lueWarehouses.EditValue; } set { lueWarehouses.EditValue = value; } } private void lueWarehouses_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close) { lueWarehouses.EditValue = null; } } private void gridControlDocuments_DoubleClick(object sender, EventArgs e) { EditAction(this, null); } private void gvleStatus_EditValueChanged(object sender, EventArgs e) { if (ActiveDocument != null) if (ActiveDocument.Status != Convert.ToInt32((sender as DevExpress.XtraEditors.LookUpEdit).Properties.KeyValue)) ChangeDocStatus(Convert.ToInt32((sender as DevExpress.XtraEditors.LookUpEdit).Properties.KeyValue)); } FormWait frmWait; bool periodIsLocked = true; private void ChangeDocStatus(int newStatus) { if (periodIsLocked) { if (ActiveDocument == null) return; (Preseneter as DocumentsPresenter).docLocker.IdDocument = ActiveDocument.Id; if ((Preseneter as DocumentsPresenter).docLocker.IsBlocked) //Проверка блокированного документа { MessageBox.Show(this, "Документ заблокирован.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Document d = new Document(); if (MessageBox.Show(this, "Вы уверены что хотите изменить статус документа?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { if (ActiveDocument == null) return; ActiveDocument.Status = newStatus; if ((ActiveDocument.Status == 1 && IsActionBanned(AxiTradeAction.Posting)) || (ActiveDocument.Status == 0 && IsActionBanned(AxiTradeAction.Retirement))) { ExtMessageBox.ShowError("Не хватает прав"); } else { if (ActiveDocument.Status == 1) { List<DocGoodSpecRecord> negativeRestRecords = (Preseneter as DocumentsPresenter).getNegativeRestRecords(ActiveDocument); if (negativeRestRecords.Count > 0) { Warehouse wh = KartDataDictionary.sWarehouses.First(q => q.Id == ActiveDocument.IdWarehouse); NegativeRestWarningForm frmNegativeRestWarning = new NegativeRestWarningForm(negativeRestRecords, wh); if (frmNegativeRestWarning.ShowDialog() == DialogResult.Cancel) return; else { if (!wh.EnableNegativeRest) { DocType _doctype = KartDataDictionary.sDocTypes.Where(q => q.DocKind == DocKindEnum.IncomeDoc && q.IsReversal == false && q.IsTradeOper == true).FirstOrDefault(); Document newdocument = new Document() { DateDoc = DateTime.Now, docType = _doctype, ExtNumber = ActiveDocument.Number, IdOrganization = ActiveDocument.IdOrganization, IdSupplier = ActiveDocument.IdSupplier, IdWarehouse = ActiveDocument.IdWarehouse, IdUser = ActiveDocument.IdUser, IsNew = true, Status = 0, Comment = "Документ создан для избежания появления отрицательных остатков на складе, номер документа " + ActiveDocument.Number }; Saver.SaveToDb<Document>(newdocument); Saver.DataContext.ExecuteNonQuery("insert into docrelations (idparentdoc, IDCHILDDOC) values (" + ActiveDocument.Id + "," + newdocument.Id + ");"); List<DocGoodSpecRecord> newdocgood = negativeRestRecords; double DocSum = 0; foreach (DocGoodSpecRecord dg in newdocgood) { dg.IdDocument = newdocument.Id; dg.Quantity = dg.Quantity - dg.RestWhSale; dg.MarginPrice = KartDataDictionary.GetPriceFromWarehouse(Convert.ToInt64(newdocument.IdWarehouse), dg.IdGood); DocSum += dg.SumPos; } Saver.SaveToDb<DocGoodSpecRecord>(newdocgood); newdocument.Status = 1; newdocument.SumDoc = Convert.ToDecimal(DocSum); Saver.SaveToDb<Document>(newdocument); } } } if (ActiveDocument.docType.DocKind == DocKindEnum.Contract) { List<ContractSpecRecord> _ContractSpecRecord = Loader.DbLoad<ContractSpecRecord>("MarginPrice != CurrPrice", 0, ActiveDocument.Id) ?? new List<ContractSpecRecord>(); //_ContractSpecRecord = from s in _ContractSpecRecord where s.MarginPrice != s.CurrPrice select s; if (_ContractSpecRecord.Count > 0) { PriceWarningForm frmPriceWarningForm = new PriceWarningForm(_ContractSpecRecord); if (frmPriceWarningForm.ShowDialog() == DialogResult.Cancel) return; } } } frmWait = new FormWait("Изменение статуса документа ..."); KartDataDictionary.ReportRunningFlag = true; Exception exc = null; // Процесс формирования запускаем отдельным потоком Thread thread = new Thread(new ThreadStart( delegate { try { (Preseneter as DocumentsPresenter).ChangeDocState(); } catch (Exception e) { exc = e; } Thread.Sleep(100); frmWait.CloseWaitForm(); })); thread.Start(); frmWait.ShowDialog(); KartDataDictionary.ReportRunningFlag = false; frmWait.Dispose(); frmWait = null; if (exc != null) { string Error = exc.Message.ToString(); if (Error.IndexOf("Действие запрещено") > 1) MessageBox.Show(@"При выполнении этого действия произошла ошибка: Действие запрещено.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); else throw exc; } if (exc == null) { List<Document> DependedDocs = (Loader.DbLoad<ChildDocument>("IdParentDocument = " + ActiveDocument.Id) ?? new List<ChildDocument>()).ConvertAll(q => q as Document); StringBuilder msg = new StringBuilder(); if (DependedDocs.Count > 0) { foreach (var item in DependedDocs) { msg.Append(item.Number + ";"); } MessageBox.Show("В процессе изменения статуса были созданы документы: " + msg, "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } /*if (ActiveDocuments.Count == 1) { if (MessageBox.Show(this, "Вы уверены что хотите изменить статус документа?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { d = ActiveDocument; ChangeDocStatus(newStatus, ActiveDocument); } } else { if (MessageBox.Show(this, "Вы уверены что хотите изменить статус документов?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { foreach (Document doc in ActiveDocuments) { d = doc; ChangeDocStatus(newStatus, doc); } } }*/ Document d = ActiveDocument; RefreshView(); ActiveDocument = d; } } /* private void ChangeDocStatus(int newStatus, Document _SelectedDocument) { if (_SelectedDocument == null) return; _SelectedDocument.Status = newStatus; if ((_SelectedDocument.Status == 1 && IsActionBanned(AxiTradeAction.Posting)) || (_SelectedDocument.Status == 0 && IsActionBanned(AxiTradeAction.Retirement))) { ExtMessageBox.ShowError("Не хватает прав"); } else { if (_SelectedDocument.Status == 1) { List<DocGoodSpecRecord> negativeRestRecords = (_preseneter as DocumentsPresenter).getNegativeRestRecords(_SelectedDocument); if (negativeRestRecords.Count > 0) { Warehouse wh = KartDataDictionary.sWarehouses.First(q => q.Id == _SelectedDocument.IdWarehouse); NegativeRestWarningForm frmNegativeRestWarning = new NegativeRestWarningForm(negativeRestRecords, wh); if (frmNegativeRestWarning.ShowDialog() == DialogResult.Cancel) return; else { if (!wh.EnableNegativeRest) { DocType _doctype = KartDataDictionary.sDocTypes.Where(q => q.DocKind == DocKindEnum.IncomeDoc && q.IsReversal == false && q.IsTradeOper == true).FirstOrDefault(); Document newdocument = new Document() { DateDoc = DateTime.Now, docType = _doctype, ExtNumber = _SelectedDocument.Number, IdOrganization = _SelectedDocument.IdOrganization, IdSupplier = _SelectedDocument.IdSupplier, IdWarehouse = _SelectedDocument.IdWarehouse, IdUser = _SelectedDocument.IdUser, IsNew = true, Status = 0, Comment = "Документ создан для избежания появления отрицательных остатков на складе, номер документа " + _SelectedDocument.Number }; Saver.SaveToDb<Document>(newdocument); Saver.DataContext.ExecuteNonQuery("insert into docrelations (idparentdoc, IDCHILDDOC) values (" + _SelectedDocument.Id + "," + newdocument.Id + ");"); List<DocGoodSpecRecord> newdocgood = negativeRestRecords; double DocSum = 0; foreach (DocGoodSpecRecord dg in newdocgood) { dg.IdDocument = newdocument.Id; dg.Quantity = dg.Quantity - dg.RestWhSale; DocSum += dg.SumPos; } Saver.SaveToDb<DocGoodSpecRecord>(newdocgood); newdocument.Status = 1; newdocument.SumDoc = Convert.ToDecimal(DocSum); Saver.SaveToDb<Document>(newdocument); } } } if (_SelectedDocument.docType.DocKind == DocKindEnum.Contract) { List<ContractSpecRecord> _ContractSpecRecord = Loader.DbLoad<ContractSpecRecord>("MarginPrice != CurrPrice", 0, _SelectedDocument.Id) ?? new List<ContractSpecRecord>(); //_ContractSpecRecord = from s in _ContractSpecRecord where s.MarginPrice != s.CurrPrice select s; if (_ContractSpecRecord.Count > 0) { PriceWarningForm frmPriceWarningForm = new PriceWarningForm(_ContractSpecRecord); if (frmPriceWarningForm.ShowDialog() == DialogResult.Cancel) return; } } } frmWait = new FormWait("Изменение статуса документа ..."); KartDataDictionary.ReportRunningFlag = true; Exception exc = null; // Процесс формирования запускаем отдельным потоком Thread thread = new Thread(new ThreadStart( delegate { try { (_preseneter as DocumentsPresenter).ChangeDocState(_SelectedDocument); } catch (Exception e) { exc = e; } Thread.Sleep(100); frmWait.CloseWaitForm(); })); thread.Start(); frmWait.ShowDialog(); KartDataDictionary.ReportRunningFlag = false; frmWait.Dispose(); frmWait = null; if (exc != null) { string Error = exc.Message.ToString(); if (Error.IndexOf("Действие запрещено") > 1) MessageBox.Show("При выполнении этого действия произошла ошибка: Действие запрещено.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); else throw exc; } if (exc == null) { List<Document> DependedDocs = (Loader.DbLoad<ChildDocument>("IdParentDocument = " + _SelectedDocument.Id) ?? new List<ChildDocument>()).ConvertAll(q => q as Document); StringBuilder msg = new StringBuilder(); if (DependedDocs.Count > 0) { foreach (var title in DependedDocs) { msg.Append(title.Number + ";"); } MessageBox.Show("В процессе изменения статуса были созданы документы: " + msg, "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } */ #region Обработчики событий подменю "Новая запись" (создания документов) public void barButtonNewInvoice_ItemClick(object sender, ItemClickEventArgs e) { InvoiceDocument doc = new InvoiceDocument(); doc.IsNew = true; DocType d = KartDataDictionary.sDocTypes.FirstOrDefault(dt => { return !dt.IsReversal && dt.IsTradeOper && (dt.Multiplicator == 1); }); if (d != null) { doc.IdDocType = d.Id; doc.Number = (Loader.DataContext.ExecuteScalar("select DOCNUMBER from GET_LAST_DOCNUM(" + d.Id + ")")).ToString();//"select cast(DOCNUMBER as varchar(40)) from GET_LAST_DOCNUM(" + d.Id+")" } doc.ExtDate = DateTime.Now; doc.DateDoc = DateTime.Now; InvoiceDocsEditor form = new InvoiceDocsEditor(doc); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } else if (doc.Id != 0) Saver.DeleteFromDb<Document>(doc); } public void barButtonNewReturn_ItemClick(object sender, ItemClickEventArgs e) { ReturnDocument doc = new ReturnDocument(); // doc.IdDocType = 49; ReturnDocEditor form = new ReturnDocEditor(doc); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } else if (doc.Id != 0) Saver.DeleteFromDb<Document>(doc); } public void barButtonNewRevaluationAct_ItemClick(object sender, ItemClickEventArgs e)//InventoryDocEditor { RevaluationDocument doc = new RevaluationDocument(); // doc.IdDocType = 47; RevaluationActEditor form = new RevaluationActEditor(doc); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } else if (doc.Id != 0) Saver.DeleteFromDb<Document>(doc); } public void barNewInventoryDoc_ItemClick(object sender, ItemClickEventArgs e) { InventoryDocument doc = new InventoryDocument(); // doc.IdDocType = 48; InventoryDocEditor form = new InventoryDocEditor(doc); if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UpdateDocList(); ActiveDocument = doc; } else if (doc.Id != 0) Saver.DeleteFromDb<Document>(doc); } #endregion public DateTime DateFrom { get { return dateEditBegin.DateTime.Date; } } public DateTime DateTo { get { return dateEditEnd.DateTime.Date; } } public override bool IsEditable { get { return true; } } public override bool IsInsertable { get { return true; } } public override bool UseSubmenu { get; set; } public override bool IsDeletable { get { return true; } } public override bool IsPrintable { get { return true; } } public override void PrintItems(object sender, EventArgs e) { Document d = gvDocuments.GetFocusedRow() as Document; GoodWaybillReportViewer gvbRv; if (d != null) if ((d as Document).Status == 0) { User ActiveUser = KartDataDictionary.User; UserRoleRight _UserRoleRight = Loader.DbLoadSingle<UserRoleRight>("IdRole = " + ActiveUser.IdRole + "and OBJTYPE = 67"); if (_UserRoleRight != null) { if (!_UserRoleRight.AllowView) { MessageBox.Show(@"У вас нет прав на печать документа", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } else { MessageBox.Show(@"У вас нет прав на печать документа", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } if (d == null) return; if (d.IdDocType == 54) //тип документа: заказ поставщику gvbRv = new GoodWaybillReportViewer(this.ParentForm, KartLib.Settings.GetExecPath() + @"\Reports", @"\simpleWayBillShort.frx"); else gvbRv = new GoodWaybillReportViewer(this.ParentForm, KartLib.Settings.GetExecPath() + @"\Reports"); gvbRv.ShowReport(d, cbShow.Checked); if (Loader.DbLoadSingle<Warehouse>("Id = " + d.IdWarehouse).AutoAcceptMovement) if (Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id) != null) if (Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id).IdChildDoc != 0) { InvoiceDocument ChildDocument = Loader.DbLoadSingle<InvoiceDocument>("Id = " + Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id).IdChildDoc); if (ChildDocument != null) gvbRv.ShowReport(ChildDocument, cbShow.Checked); } } public void PrintItems(List<string> ListPrint, bool Show) { Document d = gvDocuments.GetFocusedRow() as Document; GoodWaybillReportViewer gvbRv; if (d != null) if ((d as Document).Status == 0) { User ActiveUser = KartDataDictionary.User; UserRoleRight _UserRoleRight = Loader.DbLoadSingle<UserRoleRight>("IdRole = " + ActiveUser.IdRole + "and OBJTYPE = 67"); if (_UserRoleRight != null) { if (!_UserRoleRight.AllowView) { MessageBox.Show(@"У вас нет прав на печать документа", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } else { MessageBox.Show(@"У вас нет прав на печать документа", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } if (d == null) return; if (d.IdDocType == 54) //тип документа: заказ поставщику gvbRv = new GoodWaybillReportViewer(this.ParentForm, KartLib.Settings.GetExecPath() + @"\Reports", @"\simpleWayBillShort.frx"); else gvbRv = new GoodWaybillReportViewer(this.ParentForm, KartLib.Settings.GetExecPath() + @"\Reports"); gvbRv.ShowReport(d, ListPrint, Show); //if (Loader.DbLoadSingle<Warehouse>("Id = " + d.IdWarehouse).AutoAcceptMovement) if (Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id) != null) if (Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id).IdChildDoc != 0) { InvoiceDocument ChildDocument = Loader.DbLoadSingle<InvoiceDocument>("Id = " + Loader.DbLoadSingle<LinkDocument>("IdBaseDoc = " + d.Id).IdChildDoc); if (ChildDocument != null) gvbRv.ShowReport(ChildDocument, ListPrint, Show); } } private void PrintButton_Click(object sender, EventArgs e) { if (cbShow.Checked) { SelectDocumentPrintForm Form = new SelectDocumentPrintForm((long)ActiveDocument.IdDocType); if (Form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { List<string> ListPrintFile = new List<string>(); if (!string.IsNullOrEmpty(Form.beFileName1.Text)) ListPrintFile.Add(Form.beFileName1.Text); if (!string.IsNullOrEmpty(Form.beFileName2.Text)) ListPrintFile.Add(Form.beFileName2.Text); if (!string.IsNullOrEmpty(Form.beFileName3.Text)) ListPrintFile.Add(Form.beFileName3.Text); if (!string.IsNullOrEmpty(Form.beFileName4.Text)) ListPrintFile.Add(Form.beFileName4.Text); if (!string.IsNullOrEmpty(Form.beFileName5.Text)) ListPrintFile.Add(Form.beFileName5.Text); if (ListPrintFile.Count > 0) { PrintItems(ListPrintFile, cbShow.Checked); } else PrintItems(sender, e); } else PrintItems(sender, e); } else { List<string> ListPrintFile = GetParameterDocumentPrintForm(); if (ListPrintFile.Count > 0) { PrintItems(ListPrintFile, cbShow.Checked); } else PrintItems(sender, e); } } private List<string> GetParameterDocumentPrintForm() { List<string> ListPrintFile = new List<string>(); ParameterDocumentPrintForm s = (ParameterDocumentPrintForm)LoadParameter<ParameterDocumentPrintForm>(); if (s != null) { if (!string.IsNullOrEmpty(s.File1)) ListPrintFile.Add(s.File1); if (!string.IsNullOrEmpty(s.File2)) ListPrintFile.Add(s.File2); if (!string.IsNullOrEmpty(s.File3)) ListPrintFile.Add(s.File3); if (!string.IsNullOrEmpty(s.File4)) ListPrintFile.Add(s.File4); if (!string.IsNullOrEmpty(s.File5)) ListPrintFile.Add(s.File5); } return ListPrintFile; } private Entity LoadParameter<T>() { Entity e = null; string FileName = KartLib.Settings.GetExecPath() + @"\settings\docprint\" + typeof(T).Name + ActiveDocument.IdDocType + "_" + KartDataDictionary.User.Id.ToString() + ".xml"; if (File.Exists(FileName)) using (StreamReader reader = new StreamReader(FileName)) { XmlSerializer SettingsSerializer = new XmlSerializer(typeof(T)); e = SettingsSerializer.Deserialize(reader) as Entity; } return e; } private void sbExport_Click(object sender, EventArgs e) { _GenerateDocument(sender, e); } private void gridViewDocuments_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { if (ActiveDocument != null) { //проверка закрытого периода KartDataDictionary.sLockedPeriods = Loader.DbLoad<LockedPeriod>(""); if (KartDataDictionary.sLockedPeriods != null) { LockedPeriod lockedPeriod = KartDataDictionary.sLockedPeriods.FirstOrDefault(q => q.IdUser == KartDataDictionary.User.Id); if (lockedPeriod == null)//Если записи нет, ей присваивается значение запили с полем null (Все пользователи) lockedPeriod = KartDataDictionary.sLockedPeriods.FirstOrDefault(q => q.IdUser == null); if (lockedPeriod != null)//Если запись есть происходит проверка даты документа { //Проверка условия по дате if (ActiveDocument.DateDoc > lockedPeriod.LockedDate) { periodIsLocked = true; cbDocStatus.Enabled = true; } else { periodIsLocked = false; cbDocStatus.Enabled = false; } } } } if (ActiveDocument != null) cbDocStatus.Checked = (ActiveDocument.Status == 1); } //public int ButtonStatus = 0; public bool ButtonStatus = true; private void cbDocStatus_Click(object sender, EventArgs e) { if (!ButtonStatus) { ButtonStatus = true; } else { ButtonStatus = false; } ChangeDocStatus(Convert.ToInt32(!cbDocStatus.Checked)); } private void ceAutoFilter_CheckedChanged(object sender, EventArgs e) { gvDocuments.OptionsView.ShowAutoFilterRow = ceAutoFilter.Checked; } public override void SaveSettings() { DocumentViewSettings s = new DocumentViewSettings(); s.BeginDate = dateEditBegin.DateTime; s.EndDate = dateEditEnd.DateTime; s.AutoFilter = ceAutoFilter.Checked; s.SplitterPosition = splitContainer1.SplitterDistance; if (tlDocKind.FocusedNode != null) s.DocTreePosition = (tlDocKind.GetDataRecordByNode(tlDocKind.FocusedNode) as DocKindRecord).Id; if (lueWarehouses.EditValue == null) s.IdWarehouse = null; else s.IdWarehouse = (lueWarehouses.EditValue as Warehouse).Id; if (ActiveDocument != null) s.IdDocument = ActiveDocument.Id; s.ShowReport = cbShow.Checked; SaveSettings<DocumentViewSettings>(s); gvDocuments.SaveLayoutToXml(gvSettingsFileName()); } private long? InitIdDocument; private long InitIdDocKind; public override void LoadSettings() { DocumentViewSettings s = (DocumentViewSettings)LoadSettings<DocumentViewSettings>(); if (s != null) { dateEditBegin.DateTime = s.BeginDate; dateEditEnd.DateTime = s.EndDate; ceAutoFilter.Checked = s.AutoFilter; splitContainer1.SplitterDistance = s.SplitterPosition; InitIdDocKind = s.DocTreePosition; InitIdDocument = s.IdDocument; cbShow.Checked = s.ShowReport; if (s.IdWarehouse != null) if (KartDataDictionary.sWarehouses.Where(q => q.Id == s.IdWarehouse).Count() > 0) lueWarehouses.EditValue = KartDataDictionary.sWarehouses.First(q => q.Id == s.IdWarehouse); } if (File.Exists(gvSettingsFileName())) gvDocuments.RestoreLayoutFromXml(gvSettingsFileName()); } /// <summary> /// Список связи: тип документа - последний выбранный документ /// </summary> public Dictionary<long, Document> _ListDocTypeDocument = new Dictionary<long, Document>(); private void tlDocKind_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e) { if (e.OldNode != null) if ((tlDocKind.GetDataRecordByNode(e.OldNode) as DocKindRecord).IdDocType != null) if (_ListDocTypeDocument.ContainsKey((long)(tlDocKind.GetDataRecordByNode(e.OldNode) as DocKindRecord).IdDocType)) _ListDocTypeDocument[(long)(tlDocKind.GetDataRecordByNode(e.OldNode) as DocKindRecord).IdDocType] = ActiveDocument; DocKindRecord dk = tlDocKind.GetDataRecordByNode(e.Node) as DocKindRecord; if (dk != null) { DocTypeFilter.Clear(); var v = (from d in KartDataDictionary.sDocTypes where (d.DocKind == dk.docKind && (d.Id == dk.IdDocType) && (dk.IdDocType != null)) || ((d.DocKind == dk.docKind) && (dk.IdDocType == null)) select d); if (v != null) DocTypeFilter = v.ToList(); UpdateDocList(); if (dk.IdDocType!=null) if (_ListDocTypeDocument.ContainsKey((long)dk.IdDocType)) ActiveDocument = _ListDocTypeDocument[(long)dk.IdDocType]; } if (ActiveDocument != null) cbDocStatus.Checked = (ActiveDocument.Status == 1); UseSubmenu = e.Node.ParentNode == null; } private void ceAutoColumnWidth_CheckedChanged(object sender, EventArgs e) { gvDocuments.OptionsView.ColumnAutoWidth = ceAutoColumnWidth.Checked; } private void dateEditBegin_EditValueChanged(object sender, EventArgs e) { if (dateEditBegin.DateTime > dateEditEnd.DateTime) { /*DevExpress.Utils.ToolTipControllerShowEventArgs i = new DevExpress.Utils.ToolTipControllerShowEventArgs() { Title = "Неверная дата", ToolTipLocation = DevExpress.Utils.ToolTipLocation.BottomCenter, IconType = DevExpress.Utils.ToolTipIconType.Hand, //IconSize = DevExpress.Utils.ToolTipIconSize.Large, ShowBeak = true, Rounded = true }; toolTipController1.ShowHint(i, dateEditBegin); */ dateEditEnd.DateTime = dateEditBegin.DateTime; } } private void dateEditEnd_EditValueChanged(object sender, EventArgs e) { if (dateEditEnd.DateTime < dateEditBegin.DateTime) { /*DevExpress.Utils.ToolTipControllerShowEventArgs i = new DevExpress.Utils.ToolTipControllerShowEventArgs() { Title = "Неверная дата", ToolTipLocation = DevExpress.Utils.ToolTipLocation.BottomCenter, IconType = DevExpress.Utils.ToolTipIconType.Hand, //IconSize = DevExpress.Utils.ToolTipIconSize.Large, ShowBeak = true, Rounded = true }; toolTipController1.ShowHint(i, dateEditEnd);*/ dateEditBegin.DateTime = dateEditEnd.DateTime; } } public SelectForPrintForm _SelectForPrintForm = null; private void _PrintPrice(object sender, System.EventArgs e) { long iddocument = ActiveDocument.Id; List<TORG12SpecRecord> _TORG12SpecRecord = Loader.DbLoad<TORG12SpecRecord>("", 0, iddocument) ?? new List<TORG12SpecRecord>(); if (_TORG12SpecRecord.Count == 0) { MessageBox.Show(@"Невозможно напечатать ценики, нет спецификации.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } _SelectForPrintForm = new SelectForPrintForm(); if (_SelectForPrintForm.IsDisposed != true) { _SelectForPrintForm.Activate(); } else { _SelectForPrintForm = new SelectForPrintForm(); } //_SelectForPrintForm.Owner = this; _SelectForPrintForm.Rows = new List<TORG12SpecRecord>(); for (int i = 0; i < _TORG12SpecRecord.Count; i++) { if (_TORG12SpecRecord[i].Barcode == null) { string querybarcode = "select first 1 barcode from barcodes where idgood = " + _TORG12SpecRecord[i].IdGood + " and ISDELETED = 0"; if (Loader.DataContext.ExecuteScalar(querybarcode) != null) { string barcode = (string)Loader.DataContext.ExecuteScalar(querybarcode); _TORG12SpecRecord[i].Barcode = barcode; } } if (_TORG12SpecRecord[i].PLU == "") { _TORG12SpecRecord[i].PLU = Loader.DataContext.ExecuteScalar("select PLU from SP_GET_PLU(" + KartDataDictionary.sPriceListHeads.Min(q => q.Id).ToString() + ", " + _TORG12SpecRecord[i].IdGood + ")").ToString(); } _TORG12SpecRecord[i].Quantity = 1; _SelectForPrintForm.Rows.Add(TORG12SpecRecord.AddItem(_TORG12SpecRecord[i])); } _SelectForPrintForm.simpleButton2.Visible = false; if (_SelectForPrintForm.IsDisposed != true) _SelectForPrintForm.Activate(); else _SelectForPrintForm = new SelectForPrintForm(); _SelectForPrintForm.Show(); } private void _PrintLabel(object sender, System.EventArgs e) { long iddocument = ActiveDocument.Id; List<TORG12SpecRecord> _TORG12SpecRecord = Loader.DbLoad<TORG12SpecRecord>("", 0, iddocument) ?? new List<TORG12SpecRecord>(); if (_TORG12SpecRecord.Count == 0) { MessageBox.Show(@"Невозможно напечатать ценики, нет спецификации.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } _SelectForPrintForm = new SelectForPrintForm(); if (_SelectForPrintForm.IsDisposed != true) { _SelectForPrintForm.Activate(); } else { _SelectForPrintForm = new SelectForPrintForm(); } //_SelectForPrintForm.Owner = this; _SelectForPrintForm.Rows = new List<TORG12SpecRecord>(); for (int i = 0; i < _TORG12SpecRecord.Count; i++) { if (_TORG12SpecRecord[i].Barcode == null) { string querybarcode = "select first 1 barcode from barcodes where idgood = " + _TORG12SpecRecord[i].IdGood + " and ISDELETED = 0"; if (Loader.DataContext.ExecuteScalar(querybarcode) != null) { string barcode = (string)Loader.DataContext.ExecuteScalar(querybarcode); _TORG12SpecRecord[i].Barcode = barcode; } } if (_TORG12SpecRecord[i].Quantity != (int)_TORG12SpecRecord[i].Quantity) _TORG12SpecRecord[i].Quantity = 1; _SelectForPrintForm.Rows.Add(TORG12SpecRecord.AddItem(_TORG12SpecRecord[i])); } _SelectForPrintForm.simpleButton1.Visible = false; _SelectForPrintForm.rgPriceType.Visible = false; _SelectForPrintForm.tePriceReportFile.Visible = false; if (_SelectForPrintForm.IsDisposed != true) _SelectForPrintForm.Activate(); else _SelectForPrintForm = new SelectForPrintForm(); _SelectForPrintForm.Show(); } private void gvDocuments_RowCellStyle(object sender, RowCellStyleEventArgs e) { GridView View = sender as GridView; if (e.Column.FieldName == "Status") { string category = View.GetRowCellDisplayText(e.RowHandle, View.Columns["Status"]); if (category == "Разоприходован") { e.Appearance.ForeColor = Color.Red; } } } private void _GenerateDocument(object sender, System.EventArgs e) { if (gvDocuments.SelectedRowsCount == 0) return; GenDocForm frmGenDoc = new GenDocForm(); foreach (int selectedItemIndex in gvDocuments.GetSelectedRows()) { Document _selectedItem = gvDocuments.GetRow(selectedItemIndex) as Document; if (_selectedItem != null) { if (frmGenDoc.Documents.Count == 0) { frmGenDoc.lueDocTypes.EditValue = _selectedItem.IdDocType; frmGenDoc.lueSuppliers.EditValue = _selectedItem.IdSupplier; frmGenDoc.lueWarehouses.EditValue = _selectedItem.IdWarehouse; } frmGenDoc.Documents.Add(_selectedItem); } } frmGenDoc.ShowDialog(); } private void simpleButton1_Click(object sender, EventArgs e) { long? idwh = null; if (lueWarehouses.EditValue == null) idwh = null; else idwh = (lueWarehouses.EditValue as Warehouse).Id; ImportDocumentFromExl edfe = new ImportDocumentFromExl(); edfe.ShowDialog(); } } }
using System.Text; namespace NStandard { public static partial class ArrayExtensions { /// <summary> /// Decodes all the bytes in the specified byte(Default: UTF-8) array into a string. /// </summary> /// <param name="this"></param> /// <returns></returns> public static string String(this byte[] @this) => String(@this, Encoding.Unicode); /// <summary> /// Decodes all the bytes in the specified byte array into a string. /// </summary> /// <param name="this"></param> /// <param name="encoding"></param> /// <returns></returns> public static string String(this byte[] @this, string encoding) => Encoding.GetEncoding(encoding).GetString(@this); /// <summary> /// Decodes all the bytes in the specified byte array into a string. /// </summary> /// <param name="this"></param> /// <param name="encoding"></param> /// <returns></returns> public static string String(this byte[] @this, Encoding encoding) => encoding.GetString(@this); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TY.SPIMS.Utilities; namespace TY.SPIMS.Client.Helper.CodeGenerator { public class ReceivableCodeGenerator : IGenerator { #region IGenerator Members public string GenerateCode() { try { string number = "1"; var db = ConnectionManager.Instance.Connection; var p = db.PaymentDetail .Where(a => a.SalesPayments.Any()) .OrderByDescending(a => a.Id) .FirstOrDefault(); if (p != null) //If there are previous items { string[] vCode = p.VoucherNumber.Split('-'); if (vCode.Length == 3) { int thisYear = DateTime.Now.Year; int voucherYear = 0; if (int.TryParse(vCode[1], out voucherYear)) { } int oldNumber = 0; if (voucherYear == thisYear) { if (int.TryParse(vCode[2], out oldNumber)) { number = (oldNumber + 1).ToString(); } } } } //For building the code: RCV-YYYY-00001 StringBuilder codeBuilder = new StringBuilder(); codeBuilder.AppendFormat("RCV-{0}-{1}", DateTime.Now.Year.ToString(), number.PadLeft(5, '0')); return codeBuilder.ToString(); } catch (Exception ex) { throw ex; } } #endregion } }
using System; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Threading; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; using ApartmentApps.Portal.Controllers; using DBDiff.Schema.SQLServer.Generates.Generates; using DBDiff.Schema.SQLServer.Generates.Model; using DBDiff.Schema.SQLServer.Generates.Options; using Korzh.EasyQuery; using Korzh.EasyQuery.Db; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using WatiN.Core; namespace ApartmentApps.Tests { //[TestClass] //public class WebTest //{ // [TestInitialize] // public void Init() // { // wd = new FirefoxDriver(); // } // public FirefoxDriver wd { get; set; } // [TestMethod] // public void Web() // { // Login(); // var wait = new WebDriverWait(wd,new TimeSpan(0,0,0,5)); // wait.Until(p=>p.) // wd.Navigate().GoToUrl("http://dev.apartmentapps.com/MaitenanceRequests/NewRequest"); // if (!wd.FindElement(By.XPath("//select[@id='UnitId']//option[4]")).Selected) // { // wd.FindElement(By.XPath("//select[@id='UnitId']//option[4]")).Click(); // } // if (!wd.FindElement(By.XPath("//select[@id='MaitenanceRequestTypeId']//option[10]")).Selected) // { // wd.FindElement(By.XPath("//select[@id='MaitenanceRequestTypeId']//option[10]")).Click(); // } // if (!wd.FindElement(By.Id("PermissionToEnter")).Selected) // { // wd.FindElement(By.Id("PermissionToEnter")).Click(); // } // wd.FindElement(By.XPath("//div[@class='btn-group']/label[2]"),20).Click(); // wd.FindElement(By.Id("Comments")).Click(); // wd.FindElement(By.Id("Comments")).Clear(); // wd.FindElement(By.Id("Comments")).SendKeys("Selenium Test Request"); // wd.FindElement(By.CssSelector("input.btn.btn-primary")).Click(); // wd.FindElement(By.LinkText("Edit"),20).Click(); // wd.FindElement(By.Id("Comments"),20).Click(); // wd.FindElement(By.Id("Comments")).Clear(); // wd.FindElement(By.Id("Comments")).SendKeys("Selenium Test Requests"); // wd.FindElement(By.XPath("//div[@class='modal-footer']/input")).Click(); // } // public void Login() // { // wd.Navigate().GoToUrl("http://dev.apartmentapps.com/Account/Login"); // wd.FindElement(By.Id("Email"),20).Click(); // wd.FindElement(By.Id("Email")).Clear(); // wd.FindElement(By.Id("Email")).SendKeys("micahosborne@gmail.com"); // wd.FindElement(By.Id("Password")).Click(); // wd.FindElement(By.Id("Password")).Clear(); // wd.FindElement(By.Id("Password")).SendKeys("micah123"); // wd.FindElement(By.XPath("//form[@id='form0']/div[5]/input")).Click(); // } //} //public static class WebDriverExtensions //{ // public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds) // { // if (timeoutInSeconds > 0) // { // var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); // return wait.Until(drv => drv.FindElement(by)); // } // return driver.FindElement(by); // } //} [TestClass] public class DbTasks { public static string ConnectionStringTest = "Server=aptapps.database.windows.net,1433;Database=ApartmentApps_Test;User ID=aptapps;Password=Asdf1234!@#$;"; public static string ConnectionStringDevelopment = "Server=aptapps.database.windows.net,1433;Database=ApartmentApps_Development;User ID=aptapps;Password=Asdf1234!@#$;"; public static string ConnectionStringProduction = "Server=aptapps.database.windows.net,1433;Database=ApartmentApps;User ID=aptapps;Password=Asdf1234!@#$;"; public static SqlOption SqlFilter = new SqlOption(); static void SaveFile(string filenmame, string sql) { if (!String.IsNullOrEmpty(filenmame)) { StreamWriter writer = new StreamWriter(filenmame, false); writer.Write(sql); writer.Close(); } } static Boolean TestConnection(string connectionString1, string connectionString2) { try { SqlConnection connection = new SqlConnection(); connection.ConnectionString = connectionString1; connection.Open(); connection.Close(); connection.ConnectionString = connectionString2; connection.Open(); connection.Close(); return true; } catch (Exception ex) { throw ex; } } //#if !DEBUG [TestMethod] public void MigrateProdDb() { #if DEBUG return; #endif string backupDbName = $"ApartmentApps_Backup{DateTime.Now.Month}_{DateTime.Now.Day}_{DateTime.Now.Year}_{DateTime.Now.Ticks}"; // Make Backup MackProdBackup(backupDbName); Thread.Sleep(new TimeSpan(0, 0, 1, 0)); #if RELEASE // Migrate production database using (var productionDb = new SqlConnection(ConnectionStringProduction)) { MigrateDbInternal(productionDb); } #endif #if TEST // Migrate Test database using (var testDb = new SqlConnection($"Server=aptapps.database.windows.net,1433;Database={backupDbName};User ID=aptapps;Password=Asdf1234!@#$")) { MigrateDbInternal(testDb); } // Rename backup database to test database using (var masterDb = new SqlConnection($"Server=aptapps.database.windows.net,1433;Database=master;User ID=aptapps;Password=Asdf1234!@#$")) { masterDb.Open(); var cmd = new SqlCommand($"IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'ApartmentApps_Test') ALTER DATABASE ApartmentApps_Test Modify Name = ApartmentApps_Test_{DateTime.Now.Ticks}; ", masterDb); cmd.CommandTimeout = Int32.MaxValue; cmd.ExecuteNonQuery(); cmd = new SqlCommand($"ALTER DATABASE {backupDbName} Modify Name = ApartmentApps_Test; ", masterDb); cmd.CommandTimeout = Int32.MaxValue; cmd.ExecuteNonQuery(); Console.WriteLine("Moved database into place"); } #endif } private static void MackProdBackup(string backupDbName) { Console.WriteLine("Creating Backup"); using (var prodDb = new SqlConnection(ConnectionStringProduction)) { prodDb.Open(); var cmd = new SqlCommand($"CREATE DATABASE {backupDbName} AS COPY OF ApartmentApps;", prodDb); cmd.CommandTimeout = Int32.MaxValue; cmd.ExecuteNonQuery(); Console.WriteLine("Copied Production Database"); } } private void MigrateDbInternal(SqlConnection connection) { var diffScript = GenerateDiffScript(); var cmds = diffScript.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries).ToList(); Console.WriteLine("Migrating Database With OpenDBDiff"); connection.Open(); SqlCommand cmd = new SqlCommand("DROP TABLE IF EXISTS [dbo].[__MigrationHistory]", connection); cmd.CommandTimeout = Int32.MaxValue; cmd.ExecuteNonQuery(); foreach (var c in cmds) { try { cmd = new SqlCommand(c, connection); cmd.CommandTimeout = Int32.MaxValue; cmd.ExecuteNonQuery(); } catch (Exception ex) { Assert.IsTrue(false, $"Sql command {c} didn't execute successfully" + Environment.NewLine + ex.Message); } Console.WriteLine($"Success: {c}"); } Console.WriteLine("Database migration complete"); } //#endif public string GenerateDiffScript() { Database origin; Database destination; if (TestConnection(ConnectionStringProduction, ConnectionStringDevelopment)) { Generate sql = new Generate(); sql.ConnectionString = ConnectionStringProduction; Console.WriteLine("Reading first database..."); sql.Options = SqlFilter; origin = sql.Process(); sql.ConnectionString = ConnectionStringDevelopment; Console.WriteLine("Reading second database..."); destination = sql.Process(); Console.WriteLine("Comparing databases schemas..."); origin = Generate.Compare(origin, destination); //if (!arguments.OutputAll) //{ // // temporary work-around: run twice just like GUI // origin.ToSqlDiff(); //} origin.ToSqlDiff(); Console.WriteLine("Generating SQL file..."); Console.WriteLine(); return origin.ToSqlDiff().ToSQL(); } return null; } [TestMethod] public void GenerateScripts() { try { } catch (Exception ex) { Console.WriteLine(String.Format("{0}\r\n{1}\r\n\r\nPlease report this issue at http://opendbiff.codeplex.com/workitem/list/basic\r\n\r\n", ex.Message, ex.StackTrace)); } } } [TestClass] public class DbQueryTest : PropertyTest { [TestInitialize] public override void Init() { base.Init(); } [TestCleanup] public override void DeInit() { base.DeInit(); } [TestMethod] public void Test() { DbQuery query = new DbQuery(); query.Model = new DbModel(); query.Model.LoadFromType(typeof(ApplicationUser)); query.Root.Conditions.Add(query.CreateSimpleCondition("ApplicationUser.Archived", "NotTrue")); var service = Context.Kernel.Get<UserService>(); int count; var result = service.GetAll<UserBindingModel>(query, out count, null, false); Console.WriteLine(query.GetConditionsText(QueryTextFormats.Default)); Console.WriteLine(count); //SqlQueryBuilder builder = new SqlQueryBuilder(query); //builder.BuildSQL(); //string sql = builder.Result.SQL; //Console.WriteLine(sql); } } }
using EasyConsoleNG.Menus; using System; namespace EasyConsoleNG.Demo.Pages { public class SelectDemoPage : Page { public SelectDemoPage(Menu menu) : base(menu) { } public override void Display() { var value = Console.Input.ReadOption("Value", new[] { "A", "B", "C" }, defaultValue: "C"); Console.Output.WriteLine(ConsoleColor.Green, "You entered: '{0}'", value); Input.ReadString("Press [Enter] to navigate back"); Menu.Pop(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SumArrays { class Program { static void Main(string[] args) { Console.Write("Enter array size:"); int size = int.Parse(Console.ReadLine()); int[] arr = new int[size]; int sum = 0; Console.WriteLine($"Enter {size} elements in the array:"); for (int i = 0; i < size; i++) { arr[i] = int.Parse(Console.ReadLine()); } for (int i = 0; i < size; i++) { sum += arr[i]; } Console.Write($"Sum of all elements of array = {sum}"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using ResonateXamarin.Models; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace ResonateXamarin.Views.Swipe { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ProfileSwipePage : ContentPage { public ProfileSwipePage(string userId) { InitializeComponent(); LoadProfile(userId); } async private void LoadProfile(string userId) { SpotifyUser spotifyUser = await ResonateManager.GetUser(userId); lblName.Text = spotifyUser.nameAndAge; imgProfilePic.Source = spotifyUser.urlPf; lblDescription.Text = spotifyUser.beschrijving; int i = 0; foreach(Artist artist in spotifyUser.Artists) { gArtists.Children.Add(new Image { Source = artist.UrlPf, Aspect = Aspect.AspectFill }, i, 0); gArtists.Children.Add(new BoxView { BackgroundColor = Color.FromHex("#1e9b6c") }, i, 1); gArtists.Children.Add(new Label { Text = artist.ArtistName, VerticalTextAlignment = TextAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.FromHex("#3f4648"), TextColor = Color.FromHex("#FFFFFF"), FontSize = 18 }, i, 2); i++; } } } }
using ISE.Framework.Common.Aspects; using ISE.Framework.Common.Service.Message; using ISE.Framework.Common.Service.ServiceBase; using ISE.SM.Common.DTO; using ISE.SM.Common.DTOContainer; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace ISE.SM.Common.Contract { [ServiceContract(Namespace = "http://www.iseikco.com/Sec")] public interface IGroupService : IServiceBase { [OperationContract] [Process] ResponseDto AssignUsers(List<UserDto> users,int groupId); [OperationContract] [Process] ResponseDto AssignRoles(List<RoleDto> roles, int groupId); [OperationContract] [Process] ResponseDto DeAssignUsers(List<UserDto> users, int groupId); [OperationContract] [Process] ResponseDto DeAssignRoles(List<RoleDto> roles, int groupId); [OperationContract] [Process] UserDtoContainer AssignedUsers(int groupId); [OperationContract] [Process] RoleDtoContainer AssignedRoles(int groupId); } }
using Pelican.Friendship; using StardewValley; namespace Pelican.Items { public class ItemHandler { public Object Item { get; private set; } public ItemHandler() { Item = Game1.player.ActiveObject; } public int GiftTasteRating(NpcHandler npcHandler) { if (Item == null) { return 0; } GiftTaste giftTaste = new GiftTaste(Item, npcHandler); return giftTaste.Rating; } public void RemoveFromInventory(int amount) { if (amount > 1) { // Removes first matching item in inventory, ignoring quality Game1.player.removeItemsFromInventory(Item.ParentSheetIndex, amount); } else { Game1.player.reduceActiveItemByOne(); } } private class GiftTaste { public int Rating { get; private set; } public GiftTaste(Object item, NpcHandler npcHandler) { string who = npcHandler.Target.Name; Rating = (int) (RateByRecipient(npcHandler.Target, item) * RateByCurrentDate(NpcHandler.IsBirthday(who)) * RateByQuality(item.Quality)); } private int RateByCurrentDate(bool isBirthday) { if (Game1.currentSeason.Equals("winter") && Game1.dayOfMonth == 25) { return 5; } else if (isBirthday) { return 8; } return 1; } private float RateByQuality(int quality) { // Normal: 0, Silver: 1, Gold: 2, Iridium: 4 switch (quality) { case 1: return 1.1f; case 2: return 1.25f; case 4: return 1.5f; default: return 1f; } } private int RateByRecipient(NPC who, Object item) { int flag = who.getGiftTasteForThisItem(item); switch (flag) { case 0: return 80; case 2: return 45; case 4: return -20; case 6: return -40; case 8: return 20; default: return 0; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using KartLib; using System.ComponentModel; using System.Xml.Serialization; namespace KartExchangeEngine { public class SImportGood : SimpleDbEntity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Импорт Смаркет: товары"; } } [DisplayName("Крепость")] [XmlIgnore] public decimal AlcoStrength { get; set; } [DisplayName("Объем")] [XmlIgnore] public decimal AlcoVolume { get; set; } [DisplayName("Артикул")] public string Articul { get; set; } [DisplayName("Алко тип")] [XmlIgnore] public long IdAlcoType { get; set; } [DisplayName("Страна")] [XmlIgnore] public long? IdCountry { get; set; } [DisplayName("Товарная группа")] public long IdGoodGroup { get; set; } [DisplayName("Вид товара")] public long IdGoodKind { get; set; } [DisplayName("Единица измерения")] public long IdMeasure { get; set; } [DisplayName("Наименование товара")] public string Name { get; set; } [DisplayName("Цена")] public decimal Price { get; set; } [DisplayName("Участвует в промоакциях")] public bool PromoActionEnabled { get; set; } } }