text
stringlengths
13
6.01M
using System; using System.Collections.Generic; namespace Indexer { public class Demo2 { public static void Run() { List<Person> myPeople = new List<Person>(); myPeople.Add(new Person("Lisa", "Simpson", 9)); myPeople.Add(new Person("Bart", "Simpson", 7)); // Change first person with indexer. myPeople[0] = new Person("Maggie", "Simpson", 2); // Now obtain and display each item using indexer. for (int i = 0; i < myPeople.Count; i++) { Console.WriteLine("Person number: {0}", i); Console.WriteLine("Name: {0} {1}", myPeople[i].FirstName, myPeople[i].LastName); Console.WriteLine("Age: {0}", myPeople[i].Age); Console.WriteLine(); } } } }
/// <summary> /// The <c>gView.Framework</c> provides all interfaces to develope /// with and for gView /// </summary> namespace gView.Framework.system { public interface ICancelTracker { void Cancel(); void Pause(); bool Continue { get; } bool Paused { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mojang.Minecraft.Protocol.Providers; namespace Mojang.Minecraft { public class Player : IPackageField { public Uuid UUID { get; private set; } void IPackageField.FromField(FieldMatcher fieldMatcher) { throw new NotImplementedException(); } void IPackageField.AppendIntoField(FieldMaker fieldMaker) { throw new NotImplementedException(); } } }
namespace Demo.Interfaces { public interface ICtcImporter { List<string> ReadLines(string sourceDirectory); } }
using Backend.Model.Manager; using GraphicalEditorServer.DTO; namespace GraphicalEditorServer.Mappers { public class EquipmentTypesMapper { public static EquipmentType EquipmentTypeDTO_To_EquipmentType(EquipmentTypeDTO equipmentTypeDTO) { return new EquipmentType(equipmentTypeDTO.Name, equipmentTypeDTO.IsConsumable); } public static EquipmentTypeDTO EquipmentType_To_EquipmentTypeDTO(EquipmentType equipmentType) { return new EquipmentTypeDTO(equipmentType.Id, equipmentType.Name, equipmentType.IsConsumable); } } }
//----------------------------------------------------------------------- // <copyright file="ColorReconstruction.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.Kinect.Fusion { using System; using System.Runtime.InteropServices; /// <summary> /// Reconstruction encapsulates reconstruction volume creation updating and meshing functions with color. /// </summary> public class ColorReconstruction : IDisposable { /// <summary> /// The native reconstruction interface wrapper. /// </summary> private INuiFusionColorReconstruction volume; private Matrix4 defaultWorldToVolumeTransform; /// <summary> /// Track whether Dispose has been called. /// </summary> private bool disposed = false; /// <summary> /// Initializes a new instance of the ColorReconstruction class. /// Default constructor used to initialize with the native color Reconstruction volume object. /// </summary> /// <param name="volume"> /// The native Reconstruction volume object to be encapsulated. /// </param> internal ColorReconstruction(INuiFusionColorReconstruction volume) { this.volume = volume; this.defaultWorldToVolumeTransform = this.GetCurrentWorldToVolumeTransform(); } /// <summary> /// Finalizes an instance of the ColorReconstruction class. /// This destructor will run only if the Dispose method does not get called. /// </summary> ~ColorReconstruction() { Dispose(false); } /// <summary> /// Initialize a Kinect Fusion 3D Reconstruction Volume enabling use with color. /// Voxel volume axis sizes must be greater than 0 and a multiple of 32. A Kinect camera /// is also required to be connected. /// </summary> /// <param name="reconstructionParameters"> /// The Reconstruction parameters to define the size and shape of the reconstruction volume. /// </param> /// <param name="reconstructionProcessorType"> /// the processor type to be used for all calls to the reconstruction volume object returned /// from this function. /// </param> /// <param name="deviceIndex">Set this variable to an explicit zero-based device index to use /// a specific GPU as enumerated by FusionDepthProcessor.GetDeviceInfo, or set to -1 to /// automatically select the default device for a given processor type. /// </param> /// <param name="initialWorldToCameraTransform"> /// The initial camera pose of the reconstruction volume with respect to the world origin. /// Pass identity as the default camera pose. /// </param> /// <returns>The Reconstruction instance.</returns> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="reconstructionParameters"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="reconstructionParameters"/> parameter's <c>VoxelX</c>, /// <c>VoxelY</c>, or <c>VoxelZ</c> member is not a greater than 0 and multiple of 32. /// Thrown when the <paramref name="deviceIndex"/> parameter is less than -1 or greater /// than the number of available devices for the respective processor type. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown when the memory required for the Reconstruction volume processing could not be /// allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the Kinect device is not /// connected or the Reconstruction volume is too big so a GPU memory allocation failed, /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// Users can select which device the processing is performed on with /// the <paramref name="reconstructionProcessorType"/> parameter. For those with multiple GPUs /// the <paramref name="deviceIndex"/> parameter also enables users to explicitly configure /// on which device the reconstruction volume is created. /// Note that this function creates a default world-volume transform. To set a non-default /// transform call ResetReconstruction with an appropriate Matrix4. This default transformation /// is a combination of translation in X,Y to locate the world origin at the center of the front /// face of the reconstruction volume cube, and scaling by the voxelsPerMeter reconstruction /// parameter to convert from the world coordinate system to volume voxel indices. /// </remarks> public static ColorReconstruction FusionCreateReconstruction( ReconstructionParameters reconstructionParameters, ReconstructionProcessor reconstructionProcessorType, int deviceIndex, Matrix4 initialWorldToCameraTransform) { if (null == reconstructionParameters) { throw new ArgumentNullException("reconstructionParameters"); } INuiFusionColorReconstruction reconstruction = null; ExceptionHelper.ThrowIfFailed(NativeMethods.NuiFusionCreateColorReconstruction( reconstructionParameters, reconstructionProcessorType, deviceIndex, ref initialWorldToCameraTransform, out reconstruction)); return new ColorReconstruction(reconstruction); } /// <summary> /// Clear the volume, and set a new world-to-camera transform (camera view pose) or identity. /// This internally sets the default world-to-volume transform. where the Kinect camera is /// translated in X,Y to the center of the front face of the volume cube, looking into the cube, /// and the world coordinates are scaled to volume indices according to the voxels per meter /// setting. /// </summary> /// <param name="initialWorldToCameraTransform"> /// The initial camera pose with respect to the world origin. /// Pass identity as the default camera pose. /// </param> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// or the call failed for an unknown reason. /// </exception> public void ResetReconstruction(Matrix4 initialWorldToCameraTransform) { ExceptionHelper.ThrowIfFailed(volume.ResetReconstruction( ref initialWorldToCameraTransform, ref defaultWorldToVolumeTransform)); } /// <summary> /// Clear the reconstruction volume, and set a world-to-camera transform (camera view pose) /// and a world-to-volume transform. /// The world-volume transform expresses the location and orientation of the world coordinate /// system origin in volume coordinates and the scaling of the world coordinates to /// volume indices. In practice, this controls where the reconstruction volume appears in the /// real world with respect to the world origin position, or with respect to the camera if /// identity is passed for the initial world-to-camera transform (as the camera and world /// origins then coincide). /// To create your own world-volume transformation first get the current transform by calling /// GetCurrentWorldToVolumeTransform then either modify the matrix directly or multiply /// with your own similarity matrix to alter the volume translation or rotation with respect /// to the world coordinate system. Note that other transforms such as skew are not supported. /// To reset the volume while keeping the same world-volume transform, first get the current /// transform by calling GetCurrentWorldToVolumeTransform and pass this Matrix4 as the /// <paramref name="worldToVolumeTransform"/> parameter when calling this reset /// function. /// </summary> /// <param name="initialWorldToCameraTransform"> /// The initial camera pose with respect to the world origin. /// Pass identity as the default camera pose. /// </param> /// <param name="worldToVolumeTransform">A Matrix4 instance, containing the world to volume /// transform. /// </param> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// or the call failed for an unknown reason. /// </exception> public void ResetReconstruction( Matrix4 initialWorldToCameraTransform, Matrix4 worldToVolumeTransform) { ExceptionHelper.ThrowIfFailed(volume.ResetReconstruction( ref initialWorldToCameraTransform, ref worldToVolumeTransform)); } /// <summary> /// Aligns a depth float image to the Reconstruction volume to calculate the new camera pose. /// This camera tracking method requires a Reconstruction volume, and updates the internal /// camera pose if successful. The maximum image resolution supported in this function is 640x480. /// </summary> /// <param name="depthFloatFrame">The depth float frame to be processed.</param> /// <param name="maxAlignIterationCount"> /// The maximum number of iterations of the algorithm to run. /// The minimum value is 1. Using only a small number of iterations will have a faster runtime, /// however, the algorithm may not converge to the correct transformation. /// </param> /// <param name="deltaFromReferenceFrame"> /// Optionally, a pre-allocated float image frame, to be filled with information about how /// well each observed pixel aligns with the passed in reference frame. This may be processed /// to create a color rendering, or may be used as input to additional vision algorithms such /// as object segmentation. These residual values are normalized -1 to 1 and represent the /// alignment cost/energy for each pixel. Larger magnitude values (either positive or negative) /// represent more discrepancy, and lower values represent less discrepancy or less information /// at that pixel. /// Note that if valid depth exists, but no reconstruction model exists behind the depth /// pixels, 0 values indicating perfect alignment will be returned for that area. In contrast, /// where no valid depth occurs 1 values will always be returned. Pass null if not required. /// </param> /// <param name="alignmentEnergy"> /// A float to receive a value describing how well the observed frame aligns to the model with /// the calculated pose. A larger magnitude value represent more discrepancy, and a lower value /// represent less discrepancy. Note that it is unlikely an exact 0 (perfect alignment) value /// will ever be returned as every frame from the sensor will contain some sensor noise. /// </param> /// <param name="worldToCameraTransform"> /// The best guess of the camera pose (usually the camera pose result from the last /// AlignPointClouds or AlignDepthFloatToReconstruction). /// </param> /// <returns> /// Returns true if successful; return false if the algorithm encountered a problem aligning /// the input depth image and could not calculate a valid transformation. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="depthFloatFrame"/> parameter is an incorrect image size. /// Thrown when the <paramref name="maxAlignIterationCount"/> parameter is less than 1 or /// an incorrect value. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// Note that this function is designed primarily for tracking either with static scenes when /// performing environment reconstruction, or objects which move rigidly when performing object /// reconstruction from a static camera. Consider using the function AlignPointClouds instead /// if tracking failures occur due to parts of a scene which move non-rigidly or should be /// considered as outliers, although in practice, such issues are best avoided by carefully /// designing or constraining usage scenarios wherever possible. /// </remarks> public bool AlignDepthFloatToReconstruction( FusionFloatImageFrame depthFloatFrame, int maxAlignIterationCount, FusionFloatImageFrame deltaFromReferenceFrame, out float alignmentEnergy, Matrix4 worldToCameraTransform) { if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } ushort maxIterations = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxAlignIterationCount); HRESULT hr = volume.AlignDepthFloatToReconstruction( FusionImageFrame.ToHandleRef(depthFloatFrame), maxIterations, FusionImageFrame.ToHandleRef(deltaFromReferenceFrame), out alignmentEnergy, ref worldToCameraTransform); if (hr == HRESULT.E_NUI_FUSION_TRACKING_ERROR) { return false; } else { ExceptionHelper.ThrowIfFailed(hr); } return true; } /// <summary> /// Get current internal world-to-camera transform (camera view pose). /// </summary> /// <returns>The current world to camera pose.</returns> /// <exception cref="InvalidOperationException"> /// Thrown when the call failed for an unknown reason. /// </exception> public Matrix4 GetCurrentWorldToCameraTransform() { Matrix4 cameraPose; ExceptionHelper.ThrowIfFailed(volume.GetCurrentWorldToCameraTransform(out cameraPose)); return cameraPose; } /// <summary> /// Get current internal world-to-volume transform. /// Note: A right handed coordinate system is used, with the origin of the volume (i.e. voxel 0,0,0) /// at the top left of the front plane of the cube. Similar to bitmap images with top left origin, /// +X is to the right, +Y down, and +Z is now forward from origin into the reconstruction volume. /// The default transform is a combination of translation in X,Y to locate the world origin at the /// center of the front face of the reconstruction volume cube (with the camera looking onto the /// volume along +Z), and scaling by the voxelsPerMeter reconstruction parameter to convert from /// world coordinate system to volume voxel indices. /// </summary> /// <returns>The current world to volume transform. This is a similarity transformation /// that converts world coordinates to volume coordinates.</returns> /// <exception cref="InvalidOperationException"> /// Thrown when the call failed for an unknown reason. /// </exception> public Matrix4 GetCurrentWorldToVolumeTransform() { Matrix4 transform; ExceptionHelper.ThrowIfFailed(volume.GetCurrentWorldToVolumeTransform(out transform)); return transform; } /// <summary> /// Integrates depth float data into the reconstruction volume from the passed /// camera pose. /// Note: this function will also set the internal camera pose. /// </summary> /// <param name="depthFloatFrame">The depth float frame to be integrated.</param> /// <param name="maxIntegrationWeight"> /// A parameter to control the temporal smoothing of depth integration. Minimum value is 1. /// Lower values have more noisy representations, but objects that move integrate and /// disintegrate faster, so are suitable for more dynamic environments. Higher values /// integrate objects more slowly, but provides finer detail with less noise.</param> /// <param name="worldToCameraTransform"> /// The camera pose (usually the camera pose result from the last /// FusionDepthProcessor.AlignPointClouds or AlignDepthFloatToReconstruction). /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="maxIntegrationWeight"/> parameter is less than 1 or /// greater than the maximum unsigned short value. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> public void IntegrateFrame( FusionFloatImageFrame depthFloatFrame, int maxIntegrationWeight, Matrix4 worldToCameraTransform) { if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } ushort integrationWeight = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxIntegrationWeight); ExceptionHelper.ThrowIfFailed(volume.IntegrateFrame( FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(null), integrationWeight, FusionDepthProcessor.DefaultColorIntegrationOfAllAngles, ref worldToCameraTransform)); } /// <summary> /// Integrates depth float data and color data into the reconstruction volume from the /// passed camera pose. Here the angle parameter constrains the integration to /// integrate color over a given angle relative to the surface normal (recommended use /// is for thin structure scanning). /// </summary> /// <param name="depthFloatFrame">The depth float frame to be integrated.</param> /// <param name="colorFrame">The color frame to be integrated.</param> /// <param name="maxIntegrationWeight"> /// A parameter to control the temporal smoothing of depth integration. Minimum value is 1. /// Lower values have more noisy representations, but objects that move integrate and /// disintegrate faster, so are suitable for more dynamic environments. Higher values /// integrate objects more slowly, but provides finer detail with less noise.</param> /// <param name="maxColorIntegrationAngle">An angle parameter in degrees to specify the angle /// with respect to the surface normal over which color will be integrated. This can be used so /// only when the camera sensor is near parallel with the surface (i.e. the camera direction of /// view is perpendicular to the surface), or +/- an angle from the surface normal direction that /// color is integrated. /// Pass FusionDepthProcessor.DefaultColorIntegrationOfAllAngles to ignore and accept color from /// all angles (default, fastest processing). /// This angle relative to this normal direction vector describe the acceptance half angle, for /// example, a +/- 90 degree acceptance angle in all directions (i.e. a 180 degree hemisphere) /// relative to the normal would integrate color in any orientation of the sensor towards the /// front of the surface, even when parallel to the surface, whereas a 0 acceptance angle would /// only integrate color directly along a single ray exactly perpendicular to the surface. /// In reality, the useful range of values is actually between 0 and 90 exclusively /// (e.g. setting +/- 60 degrees = 120 degrees total acceptance angle). /// Note that there is a trade-off here, as setting this has a runtime cost, however, conversely, /// ignoring this will integrate color from any angle over all voxels along camera rays around the /// zero crossing surface region in the volume, which can cause thin structures to have the same /// color on both sides</param> /// <param name="worldToCameraTransform"> /// The camera pose (usually the camera pose result from the last AlignPointClouds or /// AlignDepthFloatToReconstruction). /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthFloatFrame"/> or <paramref name="colorFrame"/> /// parameter is null.</exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="maxIntegrationWeight"/> parameter is less than 1 or /// greater than the maximum unsigned short value, or the /// Thrown when the <paramref name="maxColorIntegrationAngle"/> parameter value is not /// FusionDepthProcessor.DefaultColorIntegrationOfAllAngles or between 0 and 90 degrees, /// exclusively. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> public void IntegrateFrame( FusionFloatImageFrame depthFloatFrame, FusionColorImageFrame colorFrame, int maxIntegrationWeight, float maxColorIntegrationAngle, Matrix4 worldToCameraTransform) { if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } if (null == colorFrame) { throw new ArgumentNullException("colorFrame"); } ushort integrationWeight = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxIntegrationWeight); ExceptionHelper.ThrowIfFailed(volume.IntegrateFrame( FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(colorFrame), integrationWeight, maxColorIntegrationAngle, ref worldToCameraTransform)); } /// <summary> /// A high-level function to process a depth frame through the Kinect Fusion pipeline. /// Specifically, this performs processing equivalent to the following functions for each frame: /// <para> /// 1) AlignDepthFloatToReconstruction /// 2) IntegrateFrame /// </para> /// If there is a tracking error in the AlignDepthFloatToReconstruction stage, no depth data /// integration will be performed, and the camera pose will remain unchanged. /// The maximum image resolution supported in this function is 640x480. /// </summary> /// <param name="depthFloatFrame">The depth float frame to be processed.</param> /// <param name="maxAlignIterationCount"> /// The maximum number of iterations of the align camera tracking algorithm to run. /// The minimum value is 1. Using only a small number of iterations will have a faster /// runtime, however, the algorithm may not converge to the correct transformation. /// </param> /// <param name="maxIntegrationWeight"> /// A parameter to control the temporal smoothing of depth integration. Lower values have /// more noisy representations, but objects that move appear and disappear faster, so are /// suitable for more dynamic environments. Higher values integrate objects more slowly, /// but provides finer detail with less noise. /// </param> /// <param name="alignmentEnergy"> /// A float to receive a value describing how well the observed frame aligns to the model with /// the calculated pose. A larger magnitude value represent more discrepancy, and a lower value /// represent less discrepancy. Note that it is unlikely an exact 0 (perfect alignment) value /// will ever be returned as every frame from the sensor will contain some sensor noise. /// </param> /// <param name="worldToCameraTransform"> /// The best guess of the latest camera pose (usually the camera pose result from the last /// process call). /// </param> /// <returns> /// Returns true if successful; return false if the algorithm encountered a problem aligning /// the input depth image and could not calculate a valid transformation. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="depthFloatFrame"/> parameter is an incorrect image size. /// Thrown when the <paramref name="maxAlignIterationCount"/> parameter is less than 1 or /// greater than the maximum unsigned short value. /// Thrown when the <paramref name="maxIntegrationWeight"/> parameter is less than 1 or /// greater than the maximum unsigned short value. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// Users may also optionally call the low-level functions individually, instead of calling this /// function, for more control. However, this function call will be faster due to the integrated /// nature of the calls. After this call completes, if a visible output image of the reconstruction /// is required, the user can call CalculatePointCloud and then FusionDepthProcessor.ShadePointCloud. /// </remarks> public bool ProcessFrame( FusionFloatImageFrame depthFloatFrame, int maxAlignIterationCount, int maxIntegrationWeight, out float alignmentEnergy, Matrix4 worldToCameraTransform) { if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } ushort maxIterations = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxAlignIterationCount); ushort maxWeight = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxIntegrationWeight); HRESULT hr = volume.ProcessFrame( FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(null), maxIterations, maxWeight, FusionDepthProcessor.DefaultColorIntegrationOfAllAngles, out alignmentEnergy, ref worldToCameraTransform); if (hr == HRESULT.E_NUI_FUSION_TRACKING_ERROR) { return false; } else { ExceptionHelper.ThrowIfFailed(hr); } return true; } /// <summary> /// A high-level function to process a depth frame through the Kinect Fusion pipeline. /// Also integrates color, further using a parameter to constrain the integration to /// integrate color over a given angle relative to the surface normal (recommended use /// is for thin structure scanning). /// Specifically, this performs processing equivalent to the following functions for each frame: /// <para> /// 1) AlignDepthFloatToReconstruction /// 2) IntegrateFrame /// </para> /// If there is a tracking error in the AlignDepthFloatToReconstruction stage, no depth data /// integration will be performed, and the camera pose will remain unchanged. /// The maximum image resolution supported in this function is 640x480. /// </summary> /// <param name="depthFloatFrame">The depth float frame to be processed.</param> /// <param name="colorFrame">The color frame to be processed.</param> /// <param name="maxAlignIterationCount"> /// The maximum number of iterations of the align camera tracking algorithm to run. /// The minimum value is 1. Using only a small number of iterations will have a faster /// runtime, however, the algorithm may not converge to the correct transformation. /// </param> /// <param name="maxIntegrationWeight"> /// A parameter to control the temporal smoothing of depth integration. Lower values have /// more noisy representations, but objects that move appear and disappear faster, so are /// suitable for more dynamic environments. Higher values integrate objects more slowly, /// but provides finer detail with less noise. /// </param> /// <param name="maxColorIntegrationAngle">An angle parameter in degrees to specify the angle /// with respect to the surface normal over which color will be integrated.This can be used so /// only when the camera sensor is near parallel with the surface (i.e. the camera direction of /// view is perpendicular to the surface), or +/- an angle from the surface normal direction that /// color is integrated. /// Pass FusionDepthProcessor.DefaultColorIntegrationOfAllAngles to ignore and accept color from /// all angles (default, fastest processing). /// This angle relative to this normal direction vector describe the acceptance half angle, for /// example, a +/- 90 degree acceptance angle in all directions (i.e. a 180 degree hemisphere) /// relative to the normal would integrate color in any orientation of the sensor towards the /// front of the surface, even when parallel to the surface, whereas a 0 acceptance angle would /// only integrate color directly along a single ray exactly perpendicular to the surface. /// In reality, the useful range of values is actually between 0 and 90 exclusively /// (e.g. setting +/- 60 degrees = 120 degrees total acceptance angle). /// Note that there is a trade-off here, as setting this has a runtime cost, however, conversely, /// ignoring this will integrate color from any angle over all voxels along camera rays around the /// zero crossing surface region in the volume, which can cause thin structures to have the same /// color on both sides.</param> /// <param name="alignmentEnergy"> /// A float to receive a value describing how well the observed frame aligns to the model with /// the calculated pose. A larger magnitude value represent more discrepancy, and a lower value /// represent less discrepancy. Note that it is unlikely an exact 0 (perfect alignment) value /// will ever be returned as every frame from the sensor will contain some sensor noise. /// </param> /// <param name="worldToCameraTransform"> /// The best guess of the latest camera pose (usually the camera pose result from the last /// process call). /// </param> /// <returns> /// Returns true if successful; return false if the algorithm encountered a problem aligning /// the input depth image and could not calculate a valid transformation. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthFloatFrame"/> or <paramref name="colorFrame"/> /// parameter is null. </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="depthFloatFrame"/> or <paramref name="colorFrame"/> /// parameter is an incorrect image size. /// Thrown when the <paramref name="maxAlignIterationCount"/> parameter is less than 1 or /// greater than the maximum unsigned short value. /// Thrown when the <paramref name="maxIntegrationWeight"/> parameter is less than 1 or /// greater than the maximum unsigned short value. /// Thrown when the <paramref name="maxColorIntegrationAngle"/> parameter value is not /// FusionDepthProcessor.DefaultColorIntegrationOfAllAngles or between 0 and 90 degrees, /// exclusively. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// Users may also optionally call the low-level functions individually, instead of calling this /// function, for more control. However, this function call will be faster due to the integrated /// nature of the calls. After this call completes, if a visible output image of the reconstruction /// is required, the user can call CalculatePointCloud and then FusionDepthProcessor.ShadePointCloud. /// </remarks> public bool ProcessFrame( FusionFloatImageFrame depthFloatFrame, FusionColorImageFrame colorFrame, int maxAlignIterationCount, int maxIntegrationWeight, float maxColorIntegrationAngle, out float alignmentEnergy, Matrix4 worldToCameraTransform) { if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } if (null == colorFrame) { throw new ArgumentNullException("colorFrame"); } ushort maxIterations = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxAlignIterationCount); ushort maxWeight = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxIntegrationWeight); HRESULT hr = volume.ProcessFrame( FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(colorFrame), maxIterations, maxWeight, maxColorIntegrationAngle, out alignmentEnergy, ref worldToCameraTransform); if (hr == HRESULT.E_NUI_FUSION_TRACKING_ERROR) { return false; } else { ExceptionHelper.ThrowIfFailed(hr); } return true; } /// <summary> /// Calculate a point cloud by raycasting into the reconstruction volume, returning the point /// cloud containing 3D points and normals of the zero-crossing dense surface at every visible /// pixel in the image from the given camera pose. /// This point cloud can be used as a reference frame in the next call to /// FusionDepthProcessor.AlignPointClouds, or passed to FusionDepthProcessor.ShadePointCloud /// to produce a visible image output. /// The <paramref name="pointCloudFrame"/> can be an arbitrary image size, for example, enabling /// you to calculate point clouds at the size of your window and then create a visible image by /// calling FusionDepthProcessor.ShadePointCloud and render this image, however, be aware that /// large images will be expensive to calculate. /// </summary> /// <param name="pointCloudFrame"> /// The pre-allocated point cloud frame, to be filled by raycasting into the reconstruction volume. /// Typically used as the reference frame with the FusionDepthProcessor.AlignPointClouds function /// or for visualization by calling FusionDepthProcessor.ShadePointCloud. /// </param> /// <param name="worldToCameraTransform"> /// The world to camera transform (camera pose) to raycast from. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="pointCloudFrame"/> parameter is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the call failed for an unknown reason. /// </exception> public void CalculatePointCloud( FusionPointCloudImageFrame pointCloudFrame, Matrix4 worldToCameraTransform) { if (null == pointCloudFrame) { throw new ArgumentNullException("pointCloudFrame"); } ExceptionHelper.ThrowIfFailed(volume.CalculatePointCloud( FusionImageFrame.ToHandleRef(pointCloudFrame), FusionImageFrame.ToHandleRef(null), ref worldToCameraTransform)); } /// <summary> /// Calculate a point cloud by raycasting into the reconstruction volume, returning the point /// cloud containing 3D points and normals of the zero-crossing dense surface at every visible /// pixel in the image from the given camera pose, and optionally the color visualization image. /// This point cloud can be used as a reference frame in the next call to /// FusionDepthProcessor.AlignPointClouds, or passed to FusionDepthProcessor.ShadePointCloud /// to produce a visible image output. /// The <paramref name="pointCloudFrame"/> can be an arbitrary image size, for example, enabling /// you to calculate point clouds at the size of your window and then create a visible image by /// calling FusionDepthProcessor.ShadePointCloud and render this image, however, be aware that /// large images will be expensive to calculate. /// </summary> /// <param name="pointCloudFrame"> /// The pre-allocated point cloud frame, to be filled by raycasting into the reconstruction volume. /// Typically used as the reference frame with the FusionDepthProcessor.AlignPointClouds function /// or for visualization by calling FusionDepthProcessor.ShadePointCloud. /// </param> /// <param name="colorFrame">Optionally, the color frame to fill. Pass null to ignore.</param> /// <param name="worldToCameraTransform"> /// The world to camera transform (camera pose) to raycast from. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="pointCloudFrame"/> parameter is null. </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the call failed for an unknown reason. /// </exception> public void CalculatePointCloud( FusionPointCloudImageFrame pointCloudFrame, FusionColorImageFrame colorFrame, Matrix4 worldToCameraTransform) { if (null == pointCloudFrame) { throw new ArgumentNullException("pointCloudFrame"); } if (null == colorFrame) { throw new ArgumentNullException("colorFrame"); } ExceptionHelper.ThrowIfFailed(volume.CalculatePointCloud( FusionImageFrame.ToHandleRef(pointCloudFrame), FusionImageFrame.ToHandleRef(colorFrame), ref worldToCameraTransform)); } /// <summary> /// Export a polygon mesh of the zero-crossing dense surfaces from the reconstruction volume /// with per-vertex color. /// </summary> /// <param name="voxelStep"> /// The step value in voxels for sampling points to use in the volume when exporting a mesh, which /// determines the final resolution of the mesh. Use higher values for lower resolution meshes. /// voxelStep must be greater than 0 and smaller than the smallest volume axis voxel resolution. /// To mesh the volume at its full resolution, use a step value of 1. /// Note: Any value higher than 1 for this parameter runs the risk of missing zero crossings, and /// hence missing surfaces or surface details. /// </param> /// <returns>Returns the mesh object created by Kinect Fusion.</returns> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="voxelStep"/> parameter is less than 1 or /// greater than the maximum unsigned int value or the smallest volume axis resolution. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown if the CPU memory required for mesh calculation could not be allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// a GPU memory allocation failed or the call failed for an unknown reason. /// </exception> public ColorMesh CalculateMesh(int voxelStep) { INuiFusionColorMesh mesh = null; uint step = ExceptionHelper.CastAndThrowIfOutOfUintRange(voxelStep); ExceptionHelper.ThrowIfFailed(volume.CalculateMesh(step, out mesh)); return new ColorMesh(mesh); } /// <summary> /// Export a part or all of the reconstruction volume as a short array. /// The surface boundary occurs where the tri-linearly interpolated voxel values have a zero crossing /// (i.e. when an interpolation crosses from positive to negative or vice versa). A voxel value of /// 0x8000 indicates that a voxel is uninitialized and has no valid data associated with it. /// </summary> /// <param name="sourceOriginX">The reconstruction volume voxel index in the X axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume X axis voxel resolution.</param> /// <param name="sourceOriginY">The reconstruction volume voxel index in the Y axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume Y axis voxel resolution.</param> /// <param name="sourceOriginZ">The reconstruction volume voxel index in the Z axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume Z axis voxel resolution.</param> /// <param name="destinationResolutionX">The X axis resolution/width of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume X /// axis voxel resolution. The final count of (sourceOriginX+(destinationResolutionX*voxelStep) must /// not be greater than the current reconstruction volume X axis voxel resolution.</param> /// <param name="destinationResolutionY">The Y axis resolution/height of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume Y /// axis voxel resolution. The final count of (sourceOriginY+(destinationResolutionY*voxelStep) must /// not be greater than the current reconstruction volume Y axis voxel resolution.</param> /// <param name="destinationResolutionZ">The Z axis resolution/depth of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume Z /// axis voxel resolution. The final count of (sourceOriginZ+(destinationResolutionZ*voxelStep) must /// not be greater than the current reconstruction volume Z axis voxel resolution.</param> /// <param name="voxelStep">The step value in integer voxels for sampling points to use in the /// volume when exporting. The value must be greater than 0 and less than the smallest /// volume axis voxel resolution. To export the volume at its full resolution, use a step value of 1. /// Use higher step values to skip voxels and return the new volume as if there were a lower effective /// resolution volume. For example, when exporting with a destination resolution of 320^3, setting /// voxelStep to 2 would actually cover a 640^3 voxel are a(destinationResolution*voxelStep) in the /// source reconstruction, but the data returned would skip every other voxel in the original volume. /// NOTE: Any value higher than 1 for this value runs the risk of missing zero crossings, and hence /// missing surfaces or surface details.</param> /// <param name="volumeBlock">A pre-allocated short array to be filled with /// volume data. The number of elements in this user array should be allocated as: /// (destinationResolutionX * destinationResolutionY * destinationResolutionZ) /// To access the voxel located at x,y,z use pVolume[z][y][x], or index as 1D array for a particular /// voxel(x,y,z) as follows: with pitch = x resolution, slice = (y resolution * pitch) /// unsigned int index = (z * slice) + (y * pitch) + x; /// Note: A right handed coordinate system is used, with the origin of the volume (i.e. voxel 0,0,0) /// at the top left of the front plane of the cube. Similar to bitmap images with top left origin, /// +X is to the right, +Y down, and +Z is forward from origin into the reconstruction volume. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="volumeBlock"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="volumeBlock"/> parameter length is not equal to /// (<paramref name="destinationResolutionX"/> * <paramref name="destinationResolutionY"/> * /// <paramref name="destinationResolutionZ"/>). /// Thrown when a sourceOrigin or destinationResolution parameter less than 1 or /// greater than the maximum unsigned short value. /// Thrown when the (sourceOrigin+(destinationResolution*voxelStep) calculation was /// greater than the current reconstruction volume voxel resolution along an axis. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown if the CPU memory required for volume export could not be allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// a GPU memory allocation failed or the call failed for an unknown reason. /// </exception> public void ExportVolumeBlock( int sourceOriginX, int sourceOriginY, int sourceOriginZ, int destinationResolutionX, int destinationResolutionY, int destinationResolutionZ, int voxelStep, short[] volumeBlock) { if (null == volumeBlock) { throw new ArgumentNullException("volumeBlock"); } uint srcX = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginX); uint srcY = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginY); uint srcZ = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginZ); uint destX = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionX); uint destY = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionY); uint destZ = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionZ); uint step = ExceptionHelper.CastAndThrowIfOutOfUintRange(voxelStep); if (volumeBlock.Length != (destX * destY * destZ)) { throw new ArgumentException("volumeBlock"); } ExceptionHelper.ThrowIfFailed(volume.ExportVolumeBlock(srcX, srcY, srcZ, destX, destY, destZ, step, (uint)volumeBlock.Length * sizeof(short), 0, volumeBlock, null)); } /// <summary> /// Export a part or all of the reconstruction volume as a short array with color as int array. /// The surface boundary occurs where the tri-linearly interpolated voxel values have a zero crossing /// (i.e. when an interpolation crosses from positive to negative or vice versa). A voxel value of /// 0x8000 indicates that a voxel is uninitialized and has no valid data associated with it. /// </summary> /// <param name="sourceOriginX">The reconstruction volume voxel index in the X axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume X axis voxel resolution.</param> /// <param name="sourceOriginY">The reconstruction volume voxel index in the Y axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume Y axis voxel resolution.</param> /// <param name="sourceOriginZ">The reconstruction volume voxel index in the Z axis from which the /// extraction should begin. This value must be greater than or equal to 0 and less than the /// reconstruction volume Z axis voxel resolution.</param> /// <param name="destinationResolutionX">The X axis resolution/width of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume X /// axis voxel resolution. The final count of (sourceOriginX+(destinationResolutionX*voxelStep) must /// not be greater than the current reconstruction volume X axis voxel resolution.</param> /// <param name="destinationResolutionY">The Y axis resolution/height of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume Y /// axis voxel resolution. The final count of (sourceOriginY+(destinationResolutionY*voxelStep) must /// not be greater than the current reconstruction volume Y axis voxel resolution.</param> /// <param name="destinationResolutionZ">The Z axis resolution/depth of the new voxel volume to return /// in the array. This value must be greater than 0 and less than or equal to the current volume Z /// axis voxel resolution. The final count of (sourceOriginZ+(destinationResolutionZ*voxelStep) must /// not be greater than the current reconstruction volume Z axis voxel resolution.</param> /// <param name="voxelStep">The step value in integer voxels for sampling points to use in the /// volume when exporting. The value must be greater than 0 and less than the smallest /// volume axis voxel resolution. To export the volume at its full resolution, use a step value of 1. /// Use higher step values to skip voxels and return the new volume as if there were a lower effective /// resolution volume. For example, when exporting with a destination resolution of 320^3, setting /// voxelStep to 2 would actually cover a 640^3 voxel are a(destinationResolution*voxelStep) in the /// source reconstruction, but the data returned would skip every other voxel in the original volume. /// NOTE: Any value higher than 1 for this value runs the risk of missing zero crossings, and hence /// missing surfaces or surface details.</param> /// <param name="volumeBlock">A pre-allocated short array to be filled with /// volume data. The number of elements in this user array should be allocated as: /// (destinationResolutionX * destinationResolutionY * destinationResolutionZ) /// To access the voxel located at x,y,z use pVolume[z][y][x], or index as 1D array for a particular /// voxel(x,y,z) as follows: with pitch = x resolution, slice = (y resolution * pitch) /// unsigned int index = (z * slice) + (y * pitch) + x; /// Note: A right handed coordinate system is used, with the origin of the volume (i.e. voxel 0,0,0) /// at the top left of the front plane of the cube. Similar to bitmap images with top left origin, /// +X is to the right, +Y down, and +Z is forward from origin into the reconstruction volume. /// </param> /// <param name="colorVolumeBlock">A pre-allocated int array filled with color volume data. /// The number of elements must be identical to those in <paramref name="volumeBlock"/>. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="volumeBlock"/> or <paramref name="colorVolumeBlock"/> parameter /// is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="volumeBlock"/> or <paramref name="colorVolumeBlock"/> parameter /// length is not equal to: /// (<paramref name="destinationResolutionX"/> * <paramref name="destinationResolutionY"/> * /// <paramref name="destinationResolutionZ"/>). /// Thrown when a sourceOrigin or destinationResolution parameter less than 1 or /// greater than the maximum unsigned short value. /// Thrown when the (sourceOrigin+(destinationResolution*voxelStep) calculation was /// greater than the current reconstruction volume voxel resolution along an axis. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown if the CPU memory required for volume export could not be allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// a GPU memory allocation failed or the call failed for an unknown reason. /// </exception> public void ExportVolumeBlock( int sourceOriginX, int sourceOriginY, int sourceOriginZ, int destinationResolutionX, int destinationResolutionY, int destinationResolutionZ, int voxelStep, short[] volumeBlock, int[] colorVolumeBlock) { if (null == volumeBlock) { throw new ArgumentNullException("volumeBlock"); } if (null == colorVolumeBlock) { throw new ArgumentNullException("colorVolumeBlock"); } uint srcX = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginX); uint srcY = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginY); uint srcZ = ExceptionHelper.CastAndThrowIfOutOfUintRange(sourceOriginZ); uint destX = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionX); uint destY = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionY); uint destZ = ExceptionHelper.CastAndThrowIfOutOfUintRange(destinationResolutionZ); uint step = ExceptionHelper.CastAndThrowIfOutOfUintRange(voxelStep); if (volumeBlock.Length != (destX * destY * destZ)) { throw new ArgumentException("volumeBlock"); } if (colorVolumeBlock.Length != (destX * destY * destZ)) { throw new ArgumentException("colorVolumeBlock"); } ExceptionHelper.ThrowIfFailed(volume.ExportVolumeBlock(srcX, srcY, srcZ, destX, destY, destZ, step, (uint)volumeBlock.Length * sizeof(short), (uint)colorVolumeBlock.Length * sizeof(int), volumeBlock, colorVolumeBlock)); } /// <summary> /// Import a reconstruction volume as a short array. /// This array must equal the size of the current initialized reconstruction volume. /// </summary> /// <param name="volumeBlock">A pre-allocated short array filled with volume data. /// The number of elements in this user array should be allocated as: /// (sourceResolutionX * sourceResolutionY * sourceResolutionZ) /// To access the voxel located at x,y,z use pVolume[z][y][x], or index as 1D array for a particular /// voxel(x,y,z) as follows: with pitch = x resolution, slice = (y resolution * pitch) /// unsigned int index = (z * slice) + (y * pitch) + x; /// Note: A right handed coordinate system is used, with the origin of the volume (i.e. voxel 0,0,0) /// at the top left of the front plane of the cube. Similar to bitmap images with top left origin, /// +X is to the right, +Y down, and +Z is forward from origin into the reconstruction volume. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="volumeBlock"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="volumeBlock"/> parameter length is not equal to /// the existing initialized volume. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown if the CPU memory required for volume export could not be allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// a GPU memory allocation failed or the call failed for an unknown reason. /// </exception> public void ImportVolumeBlock( short[] volumeBlock) { if (null == volumeBlock) { throw new ArgumentNullException("volumeBlock"); } ExceptionHelper.ThrowIfFailed(volume.ImportVolumeBlock((uint)volumeBlock.Length * sizeof(short), 0, volumeBlock, null)); } /// <summary> /// Import a reconstruction volume as a short array with color as int array. /// This arrays must both have the same number of elements and this must be equal to the size of the /// current initialized reconstruction volume. /// </summary> /// <param name="volumeBlock">A pre-allocated short array filled with volume data. /// The number of elements in this user array should be allocated as: /// (sourceResolutionX * sourceResolutionY * sourceResolutionZ) /// To access the voxel located at x,y,z use pVolume[z][y][x], or index as 1D array for a particular /// voxel(x,y,z) as follows: with pitch = x resolution, slice = (y resolution * pitch) /// unsigned int index = (z * slice) + (y * pitch) + x; /// Note: A right handed coordinate system is used, with the origin of the volume (i.e. voxel 0,0,0) /// at the top left of the front plane of the cube. Similar to bitmap images with top left origin, /// +X is to the right, +Y down, and +Z is forward from origin into the reconstruction volume. /// </param> /// <param name="colorVolumeBlock">A pre-allocated int array filled with color volume data. /// The number of elements must be identical to those in <paramref name="volumeBlock"/>. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="volumeBlock"/> or <paramref name="colorVolumeBlock"/> parameter /// is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="volumeBlock"/> or <paramref name="colorVolumeBlock"/> parameter /// length is not equal to the existing initialized volume or the two array lengths are different. /// </exception> /// <exception cref="OutOfMemoryException"> /// Thrown if the CPU memory required for volume export could not be allocated. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected, /// a GPU memory allocation failed or the call failed for an unknown reason. /// </exception> public void ImportVolumeBlock( short[] volumeBlock, int[] colorVolumeBlock) { if (null == volumeBlock) { throw new ArgumentNullException("volumeBlock"); } if (null == colorVolumeBlock) { throw new ArgumentNullException("colorVolumeBlock"); } if (volumeBlock.Length != colorVolumeBlock.Length) { throw new ArgumentException("volumeBlock.Length != colorVolumeBlock.Length"); } ExceptionHelper.ThrowIfFailed(volume.ImportVolumeBlock((uint)volumeBlock.Length * sizeof(short), (uint)colorVolumeBlock.Length * sizeof(int), volumeBlock, colorVolumeBlock)); } /// <summary> /// Converts Kinect depth frames in unsigned short format to depth frames in float format /// representing distance from the camera in meters (parallel to the optical center axis). /// Note: <paramref name="depthImageData"/> and <paramref name="depthFloatFrame"/> must /// be the same pixel resolution. This version of the function runs on the GPU. /// </summary> /// <param name="depthImageData">The source depth data.</param> /// <param name="depthFloatFrame">A depth float frame, to be filled with depth.</param> /// <param name="minDepthClip">The minimum depth threshold. Values below this will be set to 0.</param> /// <param name="maxDepthClip">The maximum depth threshold. Values above this will be set to 1000.</param> /// <param name="mirrorDepth">Set true to mirror depth, false so the image appears correct if viewing /// the Kinect camera from behind.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="depthImageData"/> or /// <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="depthImageData"/> or /// <paramref name="depthFloatFrame"/> parameter is an incorrect image size, or the /// kernelWidth is an incorrect size. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// The min and max depth clip values enable clipping of the input data, for example, to help /// isolate particular objects or surfaces to be reconstructed. Note that the thresholds return /// different values when a depth pixel is outside the threshold - pixels inside minDepthClip will /// will be returned as 0 and ignored in processing, whereas pixels beyond maxDepthClip will be set /// to 1000 to signify a valid depth ray with depth beyond the set threshold. Setting this far- /// distance flag is important for reconstruction integration in situations where the camera is /// static or does not move significantly, as it enables any voxels closer to the camera /// along this ray to be culled instead of persisting (as would happen if the pixels were simply /// set to 0 and ignored in processing). Note that when reconstructing large real-world size volumes, /// be sure to set large maxDepthClip distances, as when the camera moves around, any voxels in view /// which go beyond this threshold distance from the camera will be removed. /// </remarks> #pragma warning disable 3001 public void DepthToDepthFloatFrame( ushort[] depthImageData, FusionFloatImageFrame depthFloatFrame, float minDepthClip, float maxDepthClip, bool mirrorDepth) { if (null == depthImageData) { throw new ArgumentNullException("depthImageData"); } if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } ExceptionHelper.ThrowIfFailed(volume.DepthToDepthFloatFrame( depthImageData, (uint)depthImageData.Length * sizeof(short), FusionImageFrame.ToHandleRef(depthFloatFrame), minDepthClip, maxDepthClip, mirrorDepth)); } #pragma warning restore 3001 /// <summary> /// Spatially smooth a depth float image frame using edge-preserving filtering on GPU. /// </summary> /// <param name="depthFloatFrame">A source depth float frame.</param> /// <param name="smoothDepthFloatFrame">A depth float frame, to be filled with smoothed /// depth.</param> /// <param name="kernelWidth">Smoothing Kernel Width. Valid values are 1,2,3 /// (for 3x3,5x5,7x7 smoothing kernel block size respectively).</param> /// <param name="distanceThreshold">A distance difference range that smoothing occurs in. /// Pixels with neighboring pixels outside this distance range will not be smoothed /// (larger values indicate discontinuity/edge). Must be greater than 0.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="smoothDepthFloatFrame"/> or /// <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="smoothDepthFloatFrame"/> or /// <paramref name="depthFloatFrame"/> parameter is an incorrect image size, or the /// kernelWidth is an incorrect size. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> public void SmoothDepthFloatFrame( FusionFloatImageFrame depthFloatFrame, FusionFloatImageFrame smoothDepthFloatFrame, int kernelWidth, float distanceThreshold) { if (null == smoothDepthFloatFrame) { throw new ArgumentNullException("smoothDepthFloatFrame"); } if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } uint kW = ExceptionHelper.CastAndThrowIfOutOfUintRange(kernelWidth); ExceptionHelper.ThrowIfFailed(volume.SmoothDepthFloatFrame( FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(smoothDepthFloatFrame), kW, distanceThreshold)); } /// <summary> /// The AlignPointClouds function uses an on GPU iterative algorithm to align two sets of /// overlapping oriented point clouds and calculate the camera's relative pose. /// All images must be the same size and have the same camera parameters. /// </summary> /// <param name="referencePointCloudFrame">A reference point cloud frame.</param> /// <param name="observedPointCloudFrame">An observerd point cloud frame.</param> /// <param name="maxAlignIterationCount">The number of iterations to run.</param> /// <param name="deltaFromReferenceFrame"> /// Optionally, a pre-allocated color image frame, to be filled with color-coded data /// from the camera tracking. This may be used as input to additional vision algorithms such as /// object segmentation. Values vary depending on whether the pixel was a valid pixel used in /// tracking (inlier) or failed in different tests (outlier). 0xff000000 indicates an invalid /// input vertex (e.g. from 0 input depth), or one where no correspondences occur between point /// cloud images. Outlier vertices rejected due to too large a distance between vertices are /// coded as 0xff008000. Outlier vertices rejected due to to large a difference in normal angle /// between point clouds are coded as 0xff800000. Inliers are color shaded depending on the /// residual energy at that point, with more saturated colors indicating more discrepancy /// between vertices and less saturated colors (i.e. more white) representing less discrepancy, /// or less information at that pixel. Pass null if this image is not required. /// </param> /// <param name="alignmentEnergy">A value describing /// how well the observed frame aligns to the model with the calculated pose (mean distance between /// matching points in the point clouds). A larger magnitude value represent more discrepancy, and /// a lower value represent less discrepancy. Note that it is unlikely an exact 0 (perfect alignment) /// value will ever/ be returned as every frame from the sensor will contain some sensor noise. /// Pass NULL to ignore this parameter.</param> /// <param name="referenceToObservedTransform">The initial guess at the transform. This is /// updated on tracking success, or returned as identity on failure.</param> /// <returns> /// Returns true if successful; return false if the algorithm encountered a problem aligning /// the input depth image and could not calculate a valid transformation. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="referencePointCloudFrame"/> or /// <paramref name="observedPointCloudFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="referencePointCloudFrame"/> or /// <paramref name="observedPointCloudFrame"/> or <paramref name="deltaFromReferenceFrame"/> /// parameter is an incorrect image size, or the iterations parameter is not greater than 0. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> public bool AlignPointClouds( FusionPointCloudImageFrame referencePointCloudFrame, FusionPointCloudImageFrame observedPointCloudFrame, int maxAlignIterationCount, FusionColorImageFrame deltaFromReferenceFrame, out float alignmentEnergy, ref Matrix4 referenceToObservedTransform) { if (null == referencePointCloudFrame) { throw new ArgumentNullException("referencePointCloudFrame"); } if (null == observedPointCloudFrame) { throw new ArgumentNullException("observedPointCloudFrame"); } ushort iterations = ExceptionHelper.CastAndThrowIfOutOfUshortRange(maxAlignIterationCount); HRESULT hr = volume.AlignPointClouds( FusionImageFrame.ToHandleRef(referencePointCloudFrame), FusionImageFrame.ToHandleRef(observedPointCloudFrame), iterations, FusionImageFrame.ToHandleRef(deltaFromReferenceFrame), out alignmentEnergy, ref referenceToObservedTransform); if (hr == HRESULT.E_NUI_FUSION_TRACKING_ERROR) { return false; } else { ExceptionHelper.ThrowIfFailed(hr); } return true; } /// <summary> /// Set a reference depth frame to be used internally to help with tracking when calling /// AlignDepthFloatToReconstruction to calculate a new camera pose. This function should /// only be called when not using the default tracking behavior of Kinect Fusion. /// </summary> /// <remarks> /// AlignDepthFloatToReconstruction internally saves the last depth frame it was passed and /// uses this image to help it track when called the next time. For example, this can be used /// if you are reconstructing and lose track, then want to re-start tracking from a different /// (known) location without resetting the volume. To enable the tracking to succeed you /// could perform a raycast from the new location to get a depth image (by calling /// CalculatePointCloudAndDepth) then call this set function with the depth image, before /// calling AlignDepthFloatToReconstruction. /// </remarks> /// <param name="referenceDepthFloatFrame">A previous depth float frame where align was /// successful (and hence same functionality as AlignDepthFloatToReconstruction), /// or a ray-casted model depth.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="referenceDepthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="referenceDepthFloatFrame"/> parameter is an incorrect /// image size.</exception> /// <exception cref="InvalidOperationException"> /// Thrown when the call failed for an unknown reason. /// </exception> public void SetAlignDepthFloatToReconstructionReferenceFrame( FusionFloatImageFrame referenceDepthFloatFrame) { if (null == referenceDepthFloatFrame) { throw new ArgumentNullException("referenceDepthFloatFrame"); } ExceptionHelper.ThrowIfFailed(volume.SetAlignDepthFloatToReconstructionReferenceFrame( FusionImageFrame.ToHandleRef(referenceDepthFloatFrame))); } /// <summary> /// Calculate a point cloud, depth and optionally color image by raycasting into the /// reconstruction volume. This returns the point cloud containing 3D points and normals of the /// zero-crossing dense surface at every visible pixel in the image from the given camera pose, /// the depth to the surface, and optionally the color visualization image. /// </summary> /// <param name="pointCloudFrame">A point cloud frame, to be filled by raycasting into the /// reconstruction volume. Typically used as the reference frame with the /// FusionDepthProcessor.AlignPointClouds function or for visualization by calling /// FusionDepthProcessor.ShadePointCloud.</param> /// <param name="depthFloatFrame">A floating point depth frame, to be filled with floating point /// depth in meters to the raycast surface. This image must be identical in size, and camera /// parameters to the <paramref name="pointCloudFrame"/> parameter.</param> /// <param name="colorFrame">Optionally, the color frame to fill. Pass null to ignore.</param> /// <param name="worldToCameraTransform">The world-to-camera transform (camera pose) to /// raycast from.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="pointCloudFrame"/> or /// <paramref name="depthFloatFrame"/> parameter is null. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="pointCloudFrame"/> or <paramref name="depthFloatFrame"/> or /// <paramref name="colorFrame"/> parameter is an incorrect image size. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when the Kinect Runtime could not be accessed, the device is not connected /// or the call failed for an unknown reason. /// </exception> /// <remarks> /// This point cloud can then be used as a reference frame in the next call to /// FusionDepthProcessor.AlignPointClouds, or passed to FusionDepthProcessor.ShadePointCloud /// to produce a visible image output.The depth image can be used as a reference frame for /// AlignDepthFloatToReconstruction by calling SetAlignDepthFloatToReconstructionReferenceFrame /// to enable a greater range of tracking. The <paramref name="pointCloudFrame"/> and /// <paramref name="depthFloatFrame"/> parameters can be an arbitrary image size, for example, /// enabling you to calculate point clouds at the size of your UI window and then create a visible /// image by calling FusionDepthProcessor.ShadePointCloud and render this image, however, be aware /// that the calculation of high resolution images will be expensive in terms of runtime. /// </remarks> public void CalculatePointCloudAndDepth( FusionPointCloudImageFrame pointCloudFrame, FusionFloatImageFrame depthFloatFrame, FusionColorImageFrame colorFrame, Matrix4 worldToCameraTransform) { if (null == pointCloudFrame) { throw new ArgumentNullException("pointCloudFrame"); } if (null == depthFloatFrame) { throw new ArgumentNullException("depthFloatFrame"); } ExceptionHelper.ThrowIfFailed(volume.CalculatePointCloudAndDepth( FusionImageFrame.ToHandleRef(pointCloudFrame), FusionImageFrame.ToHandleRef(depthFloatFrame), FusionImageFrame.ToHandleRef(colorFrame), ref worldToCameraTransform)); } /// <summary> /// Disposes the Reconstruction. /// </summary> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. GC.SuppressFinalize(this); } /// <summary> /// Frees all memory associated with the Reconstruction. /// </summary> /// <param name="disposing">Whether the function was called from Dispose.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { Marshal.FinalReleaseComObject(volume); disposed = true; } } } }
using BusVenta; using DatVentas; using EntVenta; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Management; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VentasD1002 { public partial class frmDashboard : Form { public frmDashboard() { InitializeComponent(); pnlFiltro.Visible = false; ContarDatos(); DibujarGrafica(); } private string Usuario; string loggedUser; string loggedName; string Apertura; string UserLoginNow; string nameUserNow; string userPermision; string BoxPermission; int countMcsxu; int idAdmin; string serialPC; int IdCaja; string caja; List<User> lstLoggedUser; List<OpenCloseBox> lstOpenCloseDetail; DataTable dt; private void frmDashboard_Load(object sender, EventArgs e) { try { ManagementObject mos = new ManagementObject(@"Win32_PhysicalMedia='\\.\PHYSICALDRIVE0'"); serialPC = mos.Properties["SerialNumber"].Value.ToString().Trim(); var auxSerial = EncriptarTexto.Encriptar(serialPC); userPermision = new BusUser().ObtenerUsuario(auxSerial).Rol; } catch (Exception ex) { MessageBox.Show("Error en la consulta de la llave del admin :" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } panel1.Visible = true; Productos_MasVendidos(); ClientesFrecuentes(); } private void btnVentas_Click(object sender, EventArgs e) { Iniciar_Caja_Venta(); } private void Iniciar_Caja_Venta() { try { IdCaja = new BusBox().showBoxBySerial(serialPC).Id; idAdmin = new DatCatGenerico().Obtener_IdAdmin(); caja = new BusBox().showBoxBySerial(serialPC).SerialPC; int contadorDCC = ListOpenCloseDetailBox(); // userPermision = lstLoggedUser.Select(x => x.Rol).First(); if (contadorDCC == 0 & userPermision != "Solo Ventas") { AddOpenCloseDetailBox(); Apertura = "NUEVO"; timer2.Start(); } else { if (userPermision != "Solo Ventas") { GetSerialBoxByUser(); try { ListOpenCloseDetailBox(); UserLoginNow = lstOpenCloseDetail.Select(x => x.UsuarioId.Usuario).FirstOrDefault(); nameUserNow = lstOpenCloseDetail.Select(x => x.UsuarioId.Nombre).FirstOrDefault(); } catch (Exception ex) { MessageBox.Show(ex.Message); } if (countMcsxu == 0) { if (UserLoginNow == "Administrador" || Usuario == "Admininistrador" || userPermision == "ADMINISTRADOR") { MessageBox.Show("Continuaras Turno de *" + nameUserNow + " Todos los Registros seran con ese Usuario", "Caja Iniciada", MessageBoxButtons.OK, MessageBoxIcon.Warning); BoxPermission = "Correcto"; } if (loggedName == "Admin" && Usuario == "Admin") { BoxPermission = "Correcto"; } else if (UserLoginNow != Usuario && userPermision != "ADMINISTRADOR") { MessageBox.Show("Para poder continuar con el Turno de *" + nameUserNow + "* ,Inicia sesion con el Usuario " + UserLoginNow + " -ó-el Usuario *admin*", "Caja Iniciada", MessageBoxButtons.OK, MessageBoxIcon.Information); BoxPermission = "Vacio"; } else if (UserLoginNow == Usuario) { BoxPermission = "Correcto"; } } else { BoxPermission = "Correcto"; } if (BoxPermission == "Correcto") { Apertura = "Aperturado"; timer2.Start(); } } else { timer2.Start(); } } } catch (Exception ex) { MessageBox.Show("Error : "+ ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private int ListOpenCloseDetailBox() { int auxcount = 0; try { lstOpenCloseDetail = new BusOpenCloseBox().showMovBoxBySerial(serialPC); auxcount = lstOpenCloseDetail.Count; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return auxcount; } private void AddOpenCloseDetailBox() { try { // int usuarioID = lstLoggedUser.Select(x => x.Id).First(); User u = new User(); u.Id = idAdmin; Box b = new Box(); b.Id = IdCaja; OpenCloseBox open = new OpenCloseBox(); open.FechaInicio = DateTime.Today; open.FechaFin = DateTime.Today; open.FechaCierre = DateTime.Today; open.Ingresos = 0; open.Egresos = 0; open.Saldo = 0; open.UsuarioId = u; open.TotalCalculado = 0; open.TotalReal = 0; open.Estado = true; open.Diferencia = 0; open.CadaId = b; new BusOpenCloseBox().AddOpenCloseBoxDetail(open); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private int GetSerialBoxByUser() { try { //int idUsuario = lstLoggedUser.Select(x => x.Id).First(); countMcsxu = new BusOpenCloseBox().getMovOpenCloseBox(serialPC, idAdmin); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return countMcsxu; } ProgressBar pb = new ProgressBar(); private void timer2_Tick(object sender, EventArgs e) { timer2.Stop(); if ( Apertura.Equals( "NUEVO" ) ) { frmAperturaCaja aperturaCaja = new frmAperturaCaja(); this.Hide(); aperturaCaja.ShowDialog(); Dispose(); } else { frmMenuPrincipal principal = new frmMenuPrincipal(); this.Hide(); principal.ShowDialog(); Dispose(); } } private void toolStripMenuItem2_Click(object sender, EventArgs e) { //this.Hide(); frmConfiguracion configuracion = new frmConfiguracion(); configuracion.ShowDialog(); // Dispose(); } private void panel10_Paint(object sender, PaintEventArgs e) { } private void panel9_Paint(object sender, PaintEventArgs e) { } private void ContarDatos() { try { lblTotalClientes.Text = DatCliente.TotalClientes().ToString(); lblTotalProducto.Text = DatProducto.TotalProducto().ToString(); lblStockBajos.Text = DatProducto.TotalProducto_StockBajos().ToString(); lblVentasCredito.Text = DatVenta.Total_VentasCredito().ToString(); lblVentaTotal.Text = DatVenta.Total_VentasRealizadas().ToString(); } catch (Exception ex) { MessageBox.Show("Error al mostrar los datos : "+ex.Message, "Error de lectura", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void DibujarGrafica() { try { ArrayList arrFecha = new ArrayList(); ArrayList arrMonto = new ArrayList(); dt = new DataTable(); DatVenta.DatosGrafica(ref dt); foreach (DataRow dr in dt.Rows) { arrFecha.Add(dr["Fecha"]); arrMonto.Add(dr["Total"]); } chart1.Series[0].Points.DataBindXY(arrFecha, arrMonto); } catch (Exception ex) { MessageBox.Show("Ocurrio un error al obtener los datos : "+ex.Message, "Error en la gráfica", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Filtrar_Grafica() { try { ArrayList arrFecha = new ArrayList(); ArrayList arrMonto = new ArrayList(); dt = new DataTable(); DatVenta.Filtrar_DatosGrafica(ref dt, dtpInicio.Value, dtpFin.Value); foreach (DataRow dr in dt.Rows) { arrFecha.Add(dr["Fecha"]); arrMonto.Add(dr["Total"]); } chart1.Series[0].Points.DataBindXY(arrFecha, arrMonto); } catch (Exception ex) { MessageBox.Show("Ocurrio un error al obtener los datos : " + ex.Message, "Error en la gráfica", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dtpInicio_ValueChanged(object sender, EventArgs e) { Filtrar_Grafica(); } private void dtpFin_ValueChanged(object sender, EventArgs e) { Filtrar_Grafica(); } private void chkFiltro_CheckedChanged(object sender, EventArgs e) { if (chkFiltro.Checked == true) { pnlFiltro.Visible = true; } else { pnlFiltro.Visible = false; DibujarGrafica(); } } private void Productos_MasVendidos() { try { ArrayList arrTotal = new ArrayList(); ArrayList arrProducto = new ArrayList(); dt = new DataTable(); DatDetalleVenta.Productos_MasVendidos(ref dt); foreach (DataRow dr in dt.Rows) { arrTotal.Add(dr["Total"]); arrProducto.Add(dr["Descripcion"]); } chartProductosVendidos.Series[0].Points.DataBindXY(arrProducto , arrTotal); } catch (Exception ex) { MessageBox.Show("Ocurrio un error al obtener los datos : " + ex.Message, "Grafica productos", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ClientesFrecuentes() { try { ArrayList arrTotal = new ArrayList(); ArrayList arrNombres = new ArrayList(); dt = new DataTable(); DatVenta.Grafica_ClienteFrecuente(ref dt); foreach (DataRow dr in dt.Rows) { arrTotal.Add(dr["Total"]); arrNombres.Add(dr["Nombre"]); } chartClientesFrecuentes.Series[0].Points.DataBindXY(arrNombres, arrTotal); } catch (Exception ex) { MessageBox.Show("Ocurrio un error al obtener los datos : " + ex.Message, "Grafica clientes", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void toolStripMenuItem1_Click(object sender, EventArgs e) { Iniciar_Caja_Venta(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media; namespace DmxController.Converters { /// <summary> /// Sert à faire la conversion de ColorBrush vers Color /// </summary> public class ColorBrushToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return new SolidColorBrush((Color)value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { SolidColorBrush scb = (SolidColorBrush)value; return Color.FromRgb(scb.Color.R, scb.Color.G, scb.Color.B); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace CountDownGame { public partial class frmMain : MetroFramework.Forms.MetroForm { private WordManager WM; public frmMain() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { WM = new WordManager(); } private void btnGenerateWord_Click(object sender, EventArgs e) { lboxFoundWords.Items.Clear(); lblSelectedLetters.Text = String.Empty; lblSelectedLetters.Text += "Seçilen Harfler: \" "; var selectedLetters = WM.GenerateRandomLetter(); foreach (var item in selectedLetters) { lblSelectedLetters.Text += (item + " "); } foreach (var item in WM.FindWords()) { lboxFoundWords.Items.Add(item); } lblSelectedLetters.Text += "\"\n"; lblSelectedLetters.Text += String.Format("En uzun kelime: \"{0}\"", WM.LongestWord != String.Empty ? WM.LongestWord : ""); lblSelectedLetters.Text += String.Format("\nJoker harf: {0}", WM.JokerLetter); } private void btnGenerateNumbers_Click(object sender, EventArgs e) { OperationManager operationManager = new OperationManager(); Operation operation = operationManager.MakeOperation(); richTextBox1.Text = operation.OperationSteps; lblSelectedNumbers.Text = String.Empty; lblSelectedNumbers.Text += "Seçilen Sayılar: "; for (int i = 0; i < operationManager.FirstNumbers.Count; i++) { if (i == operationManager.FirstNumbers.Count - 1) { lblSelectedNumbers.Text += operationManager.FirstNumbers[i].ToString(); continue; } lblSelectedNumbers.Text += operationManager.FirstNumbers[i].ToString() + ", "; } lblSelectedNumbers.Text += Environment.NewLine + "Bulunacak Sayı: " + operationManager.NumberToBeFound; lblSelectedNumbers.Text += Environment.NewLine + "Bulunan Sayı: " + operation.ResultFound; } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace GradConnect.Migrations { public partial class newmig : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), Discriminator = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "Employers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Employers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Jobs", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Title = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Salary = table.Column<double>(nullable: false), Location = table.Column<string>(nullable: true), ContractType = table.Column<string>(nullable: true), ContractedHours = table.Column<string>(nullable: true), DatePosted = table.Column<DateTime>(nullable: true), EmployerId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Jobs", x => x.Id); table.ForeignKey( name: "FK_Jobs_Employers_EmployerId", column: x => x.EmployerId, principalTable: "Employers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserRole", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<string>(nullable: true), RoleId = table.Column<int>(nullable: false), RoleId1 = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_UserRole", x => x.Id); table.ForeignKey( name: "FK_UserRole_AspNetRoles_RoleId1", column: x => x.RoleId1, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "BookmarkedPosts", columns: table => new { UserId = table.Column<string>(nullable: false), PostId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BookmarkedPosts", x => new { x.UserId, x.PostId }); }); migrationBuilder.CreateTable( name: "Comments", columns: table => new { UserId = table.Column<string>(nullable: false), ArticleId = table.Column<int>(nullable: false), Id = table.Column<int>(nullable: false), Content = table.Column<string>(nullable: true), DatePosted = table.Column<DateTime>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Comments", x => new { x.UserId, x.ArticleId }); }); migrationBuilder.CreateTable( name: "CVs", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CvName = table.Column<string>(nullable: true), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), Street = table.Column<string>(nullable: true), City = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), Postcode = table.Column<string>(nullable: true), DateOfBirth = table.Column<DateTime>(nullable: false), PersonalStatement = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_CVs", x => x.Id); }); migrationBuilder.CreateTable( name: "References", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), CvId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_References", x => x.Id); table.ForeignKey( name: "FK_References_CVs_CvId", column: x => x.CvId, principalTable: "CVs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Skills", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), CvId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Skills", x => x.Id); table.ForeignKey( name: "FK_Skills_CVs_CvId", column: x => x.CvId, principalTable: "CVs", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "JobSkills", columns: table => new { JobId = table.Column<int>(nullable: false), SkillId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_JobSkills", x => new { x.JobId, x.SkillId }); table.ForeignKey( name: "FK_JobSkills_Jobs_JobId", column: x => x.JobId, principalTable: "Jobs", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_JobSkills_Skills_SkillId", column: x => x.SkillId, principalTable: "Skills", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Educations", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Institution = table.Column<string>(nullable: true), CourseName = table.Column<string>(nullable: true), YearStart = table.Column<string>(nullable: true), YearEnd = table.Column<string>(nullable: true), CvId = table.Column<int>(nullable: true), UserId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Educations", x => x.Id); table.ForeignKey( name: "FK_Educations_CVs_CvId", column: x => x.CvId, principalTable: "CVs", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Modules", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Title = table.Column<string>(nullable: true), Grade = table.Column<string>(nullable: true), EducationId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Modules", x => x.Id); table.ForeignKey( name: "FK_Modules_Educations_EducationId", column: x => x.EducationId, principalTable: "Educations", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Experiences", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), CompanyName = table.Column<string>(nullable: true), JobTitle = table.Column<string>(nullable: true), YearStart = table.Column<string>(nullable: true), YearEnd = table.Column<string>(nullable: true), Responsibilities = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: true), CvId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Experiences", x => x.Id); table.ForeignKey( name: "FK_Experiences_CVs_CvId", column: x => x.CvId, principalTable: "CVs", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Portfolios", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), ProjectName = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Link = table.Column<string>(nullable: true), Image = table.Column<string>(nullable: true), PhotoId = table.Column<int>(nullable: true), UserId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Portfolios", x => x.Id); }); migrationBuilder.CreateTable( name: "Posts", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Title = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), DatePosted = table.Column<DateTime>(nullable: true), Thumbnail = table.Column<int>(nullable: false), UserId = table.Column<string>(nullable: true), post_type = table.Column<string>(nullable: false), Link = table.Column<string>(nullable: true), Task = table.Column<string>(nullable: true), EmployerId = table.Column<int>(nullable: true), Sponsored_EmployerId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Posts", x => x.Id); table.ForeignKey( name: "FK_Posts_Employers_EmployerId", column: x => x.EmployerId, principalTable: "Employers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Posts_Employers_Sponsored_EmployerId", column: x => x.Sponsored_EmployerId, principalTable: "Employers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Photos", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Link = table.Column<string>(nullable: true), DateUploaded = table.Column<DateTime>(nullable: true), PostId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Photos", x => x.Id); table.ForeignKey( name: "FK_Photos_Posts_PostId", column: x => x.PostId, principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PostSkills", columns: table => new { PostId = table.Column<int>(nullable: false), SkillId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PostSkills", x => new { x.PostId, x.SkillId }); table.ForeignKey( name: "FK_PostSkills_Posts_PostId", column: x => x.PostId, principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PostSkills_Skills_SkillId", column: x => x.SkillId, principalTable: "Skills", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), Forename = table.Column<string>(nullable: true), Surname = table.Column<string>(nullable: true), StudentEmial = table.Column<string>(nullable: true), StudentEmailConfirmed = table.Column<bool>(nullable: false), DateOfBirth = table.Column<DateTime>(nullable: false), About = table.Column<string>(nullable: true), InstitutionName = table.Column<string>(nullable: true), CourseName = table.Column<string>(nullable: true), ProfileImage = table.Column<string>(nullable: true), PhotoId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); table.ForeignKey( name: "FK_AspNetUsers_Photos_PhotoId", column: x => x.PhotoId, principalTable: "Photos", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Submissions", columns: table => new { UserId = table.Column<string>(nullable: false), ChallengeId = table.Column<int>(nullable: false), Id = table.Column<int>(nullable: false), ContentLink = table.Column<string>(nullable: true), DateSubmitted = table.Column<DateTime>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Submissions", x => new { x.UserId, x.ChallengeId }); table.ForeignKey( name: "FK_Submissions_Posts_ChallengeId", column: x => x.ChallengeId, principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Submissions_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "UserSkills", columns: table => new { UserId = table.Column<string>(nullable: false), SkillId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_UserSkills", x => new { x.UserId, x.SkillId }); table.ForeignKey( name: "FK_UserSkills_Skills_SkillId", column: x => x.SkillId, principalTable: "Skills", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserSkills_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_PhotoId", table: "AspNetUsers", column: "PhotoId"); migrationBuilder.CreateIndex( name: "IX_BookmarkedPosts_PostId", table: "BookmarkedPosts", column: "PostId"); migrationBuilder.CreateIndex( name: "IX_Comments_ArticleId", table: "Comments", column: "ArticleId"); migrationBuilder.CreateIndex( name: "IX_CVs_UserId", table: "CVs", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Educations_CvId", table: "Educations", column: "CvId"); migrationBuilder.CreateIndex( name: "IX_Educations_UserId", table: "Educations", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Experiences_CvId", table: "Experiences", column: "CvId"); migrationBuilder.CreateIndex( name: "IX_Experiences_UserId", table: "Experiences", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Jobs_EmployerId", table: "Jobs", column: "EmployerId"); migrationBuilder.CreateIndex( name: "IX_JobSkills_SkillId", table: "JobSkills", column: "SkillId"); migrationBuilder.CreateIndex( name: "IX_Modules_EducationId", table: "Modules", column: "EducationId"); migrationBuilder.CreateIndex( name: "IX_Photos_PostId", table: "Photos", column: "PostId"); migrationBuilder.CreateIndex( name: "IX_Portfolios_PhotoId", table: "Portfolios", column: "PhotoId"); migrationBuilder.CreateIndex( name: "IX_Portfolios_UserId", table: "Portfolios", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Posts_EmployerId", table: "Posts", column: "EmployerId"); migrationBuilder.CreateIndex( name: "IX_Posts_UserId", table: "Posts", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Posts_Sponsored_EmployerId", table: "Posts", column: "Sponsored_EmployerId"); migrationBuilder.CreateIndex( name: "IX_PostSkills_SkillId", table: "PostSkills", column: "SkillId"); migrationBuilder.CreateIndex( name: "IX_References_CvId", table: "References", column: "CvId"); migrationBuilder.CreateIndex( name: "IX_Skills_CvId", table: "Skills", column: "CvId"); migrationBuilder.CreateIndex( name: "IX_Submissions_ChallengeId", table: "Submissions", column: "ChallengeId"); migrationBuilder.CreateIndex( name: "IX_UserRole_RoleId1", table: "UserRole", column: "RoleId1"); migrationBuilder.CreateIndex( name: "IX_UserRole_UserId", table: "UserRole", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_UserSkills_SkillId", table: "UserSkills", column: "SkillId"); migrationBuilder.AddForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserRole_AspNetUsers_UserId", table: "UserRole", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", table: "AspNetUserTokens", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_BookmarkedPosts_AspNetUsers_UserId", table: "BookmarkedPosts", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_BookmarkedPosts_Posts_PostId", table: "BookmarkedPosts", column: "PostId", principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Comments_AspNetUsers_UserId", table: "Comments", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Comments_Posts_ArticleId", table: "Comments", column: "ArticleId", principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CVs_AspNetUsers_UserId", table: "CVs", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Educations_AspNetUsers_UserId", table: "Educations", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Experiences_AspNetUsers_UserId", table: "Experiences", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Portfolios_AspNetUsers_UserId", table: "Portfolios", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Portfolios_Photos_PhotoId", table: "Portfolios", column: "PhotoId", principalTable: "Photos", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Posts_AspNetUsers_UserId", table: "Posts", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Posts_AspNetUsers_UserId", table: "Posts"); migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "BookmarkedPosts"); migrationBuilder.DropTable( name: "Comments"); migrationBuilder.DropTable( name: "Experiences"); migrationBuilder.DropTable( name: "JobSkills"); migrationBuilder.DropTable( name: "Modules"); migrationBuilder.DropTable( name: "Portfolios"); migrationBuilder.DropTable( name: "PostSkills"); migrationBuilder.DropTable( name: "References"); migrationBuilder.DropTable( name: "Submissions"); migrationBuilder.DropTable( name: "UserRole"); migrationBuilder.DropTable( name: "UserSkills"); migrationBuilder.DropTable( name: "Jobs"); migrationBuilder.DropTable( name: "Educations"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "Skills"); migrationBuilder.DropTable( name: "CVs"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "Photos"); migrationBuilder.DropTable( name: "Posts"); migrationBuilder.DropTable( name: "Employers"); } } }
using Cs_Gerencial.Dominio.Entities; using Cs_Gerencial.Dominio.Interfaces.Repositorios; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Gerencial.Infra.Data.Repositorios { public class RepositorioParticipantes: RepositorioBase<Participantes>, IRepositorioParticipantes { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class xAnimControl : MonoBehaviour { // public Animator animator; public GameObject clip_board; public void play_clipboard() { Animator anim = clip_board.GetComponent<Animator>(); anim.SetBool("play", true); } }
using System; namespace Utilities { // A collection of common functions used in code public class Functions { /// <summary>The direct distance in light years from one point in space to another.</summary> public static decimal? StellarDistanceLy(decimal? x1, decimal? y1, decimal? z1, decimal? x2, decimal? y2, decimal? z2) { var diffX = x1 - x2; var diffY = y1 - y2; var diffZ = z1 - z2; if (diffX != null && diffY != null && diffZ != null) { double square(double x) => x * x; var distance = Math.Sqrt(square((double)diffX) + square((double)diffY) + square((double)diffZ)); return (decimal)Math.Round(distance, 2); } else { return null; } } /// <summary>The constant bearing in degrees required to travel from one point on the surface of a body to another (results in a longer, straight path). /// Follows a ‘rhumb line’ (or loxodrome) path of constant bearing, which crosses all meridians at the same angle.</summary> public static decimal? SurfaceConstantHeadingDegrees(decimal? planetRadiusMeters, decimal? currentLatitude, decimal? currentLongitude, decimal? destinationLatitude, decimal? destinationLongitude) { if (planetRadiusMeters != null && currentLatitude != null && currentLongitude != null && destinationLatitude != null && destinationLongitude != null) { // Convert latitude & longitude to radians double lat1 = (double)currentLatitude * Math.PI / 180; double lat2 = (double)destinationLatitude * Math.PI / 180; double deltaLong = (double)(destinationLongitude - currentLongitude) * Math.PI / 180; // if deltaLong is over 180°, take the shorter rhumb line across the anti-meridian if (Math.Abs(deltaLong) > Math.PI) { deltaLong = deltaLong > 0 ? -((2*Math.PI) - deltaLong) : ((2*Math.PI) + deltaLong); } // Calculate heading using Law of Haversines double projectedDeltaLat = Math.Log(Math.Tan((Math.PI / 4) + (lat2 / 2)) / Math.Tan((Math.PI / 4) + (lat1 / 2))); var headingRadians = Math.Atan2(deltaLong, projectedDeltaLat); var headingDegrees = (decimal)(headingRadians * 180 / Math.PI); while (headingDegrees < 0) { headingDegrees += 360; } while (headingDegrees > 360) { headingDegrees -= 360; } return headingDegrees; } else { return null; } } /// <summary>The distance traveled when following a constant bearing from one point on the surface of a body to another (results in a longer, straight path). /// Follows a ‘rhumb line’ (or loxodrome) path of constant bearing, which crosses all meridians at the same angle.</summary> public static decimal? SurfaceConstantHeadingDistanceKm(decimal? planetRadiusMeters, decimal? currentLatitude, decimal? currentLongitude, decimal? destinationLatitude, decimal? destinationLongitude) { if (planetRadiusMeters != null && currentLatitude != null && currentLongitude != null && destinationLatitude != null && destinationLongitude != null) { double square(double x) => x * x; // Convert latitude & longitude to radians double lat1 = (double)currentLatitude * Math.PI / 180; double lat2 = (double)destinationLatitude * Math.PI / 180; double deltaLat = lat2 - lat1; double deltaLong = (double)(destinationLongitude - currentLongitude) * Math.PI / 180; // if deltaLong is over 180°, take the shorter rhumb line across the anti-meridian if (Math.Abs(deltaLong) > Math.PI) { deltaLong = deltaLong > 0 ? -((2 * Math.PI) - deltaLong) : ((2 * Math.PI) + deltaLong); } // Calculate straight path distance using Law of Haversines double projectedDeltaLat = Math.Log(Math.Tan((Math.PI / 4) + (lat2 / 2)) / Math.Tan((Math.PI / 4) + (lat1 / 2))); double q = Math.Abs(projectedDeltaLat) > 10E-12 ? deltaLat / projectedDeltaLat : Math.Cos(lat1); // // E-W course becomes ill-conditioned with 0/0 var distanceKm = (decimal)Math.Sqrt(square(deltaLat) + (square(q) * square(deltaLong))) * planetRadiusMeters / 1000; return distanceKm; } else { return null; } } /// <summary>The projected latitude and longitude of a point on the surface of a body, when pointing your ship to that location.</summary> public static void SurfaceCoordinates(decimal? altitudeMeters, decimal? planetRadiusMeters, decimal? slopeDegrees, decimal? headingDegrees, decimal? currentLatitude, decimal? currentLongitude, out decimal? outputLatitude, out decimal? outputLongitude) { outputLatitude = null; outputLongitude = null; if (altitudeMeters != null && planetRadiusMeters != null && slopeDegrees != null && headingDegrees != null && currentLatitude != null && currentLongitude != null) { // Normalize slope to between 0 and 360° while (slopeDegrees < 0) { slopeDegrees += 360; } while (slopeDegrees > 360) { slopeDegrees -= 360; } // Convert latitude, longitude & slope to radians double currLat = (double)currentLatitude * Math.PI / 180; double currLong = (double)currentLongitude * Math.PI / 180; double slopeRadians = (double)slopeDegrees * Math.PI / 180; double altitudeKm = (double)altitudeMeters / 1000; // Determine minimum slope double radiusKm = (double)planetRadiusMeters / 1000; double minSlopeRadians = Math.Acos(radiusKm / (altitudeKm + radiusKm)); if (slopeRadians > minSlopeRadians) { // Calculate the orbital cruise 'point to' position using Laws of Sines & Haversines double a = (Math.PI / 2) - slopeRadians; double path = altitudeKm / Math.Cos(a); double c = Math.Asin(path * Math.Sin(a) / radiusKm); double heading = (double)headingDegrees * Math.PI / 180; double Lat = Math.Asin((Math.Sin(currLat) * Math.Cos(c)) + (Math.Cos(currLat) * Math.Sin(c) * Math.Cos(heading))); double Lon = currLong + Math.Atan2(Math.Sin(heading) * Math.Sin(c) * Math.Cos(Lat), Math.Cos(c) - (Math.Sin(currLat) * Math.Sin(Lat))); // Convert position to degrees outputLatitude = (decimal)Math.Round(Lat * 180 / Math.PI, 4); outputLongitude = (decimal)Math.Round(Lon * 180 / Math.PI, 4); } } } /// <summary>The spherical distance from one point on the surface of a body to another. Altitude is not considered in this calculation.</summary> public static decimal? SurfaceDistanceKm(decimal? planetRadiusMeters, decimal? currentLatitude, decimal? currentLongitude, decimal? destinationLatitude, decimal? destinationLongitude) { if (planetRadiusMeters != null && currentLatitude != null && currentLongitude != null && destinationLatitude != null && destinationLongitude != null) { double square(double x) => x * x; double radiusKm = (double)planetRadiusMeters / 1000; // Convert latitude & longitude to radians double lat1 = (double)currentLatitude * Math.PI / 180; double lat2 = (double)destinationLatitude * Math.PI / 180; double deltaLat = lat2 - lat1; double deltaLong = (double)(destinationLongitude - currentLongitude) * Math.PI / 180; // Calculate shortest path distance using Law of Haversines double a = square(Math.Sin(deltaLat / 2)) + ( Math.Cos(lat2) * Math.Cos(lat1) * square(Math.Sin(deltaLong / 2)) ); double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var distanceKm = (decimal)(c * radiusKm); return distanceKm; } else { return null; } } /// <summary>The initial bearing in degrees required to travel from one point on the surface of a body to another.</summary> public static decimal? SurfaceHeadingDegrees(decimal? currentLatitude, decimal? currentLongitude, decimal? destinationLatitude, decimal? destinationLongitude) { if (currentLatitude != null && currentLongitude != null && destinationLatitude != null && destinationLongitude != null) { // Convert latitude & longitude to radians double lat1 = (double)currentLatitude * Math.PI / 180; double lat2 = (double)destinationLatitude * Math.PI / 180; double deltaLong = (double)(destinationLongitude - currentLongitude) * Math.PI / 180; // Calculate heading using Law of Haversines double y = Math.Sin(deltaLong) * Math.Cos(lat2); double x = ( Math.Cos(lat1) * Math.Sin(lat2) ) - ( Math.Sin(lat1) * Math.Cos(lat2) * Math.Cos(deltaLong) ); var headingRadians = Math.Atan2(y, x); var headingDegrees = (decimal)(headingRadians * 180 / Math.PI); while (headingDegrees < 0) { headingDegrees += 360; } while (headingDegrees > 360) { headingDegrees -= 360; } return headingDegrees; } else { return null; } } } }
/************************************** * * Does not allow Character to Move and * Attack for a set duration * **************************************/ using UnityEngine; namespace DChild.Gameplay.Combat.StatusEffects { public class StatusEffectFXHandler { private Transform m_parent; private string m_statusEffect; private ParticleFX m_fx; public StatusEffectFXHandler(Transform parent, string statusEffect) { this.m_parent = parent; this.m_statusEffect = statusEffect; m_fx = null; } public void PlayFX(float duration) { if (m_fx = null) { m_fx = GameplaySystem.GetRoutine<IFXInstantiation>().InstantiateStatusFX(GetType().Name, m_parent.transform.position); m_fx.transform.parent = m_parent; } var main = m_fx.GetParticle(0).main; main.startLifetime = duration; main.duration = duration; m_fx.Play(); } public void Stop() { m_fx.Stop(); m_fx = null; } } }
using Alabo.Data.People.Counties.Domain.Entities; using Alabo.Data.People.Counties.Domain.Services; using Alabo.Framework.Core.WebApis.Controller; using Alabo.Framework.Core.WebApis.Filter; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; namespace Alabo.Data.People.Counties.Controllers { [ApiExceptionFilter] [Route("Api/County/[action]")] public class ApiCountyController : ApiBaseController<County, ObjectId> { public ApiCountyController() { BaseService = Resolve<ICountyService>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Anywhere2Go.Business.Master; using Anywhere2Go.DataAccess.Object; using Anywhere2Go.DataAccess.Entity; using Claimdi.Web.MY.Filters; using System.Web.Security; using Claimdi.Web.MY.Helper; using Claimdi.Web.MY.Models; namespace Claimdi.Web.MY.Controllers { public class HomeController : Controller { public ActionResult Index() { //RoleLogic role = new RoleLogic(); //var obj = role.getRole(); //A00001 var test = ClaimdiSessionFacade.ClaimdiSession; AccountProfileLogic acc = new AccountProfileLogic(); var obj = acc.getAccountProfileById("A00001"); Authentication authen = new Authentication() { acc_id = obj.acc_id.ToString(), facebook_id = obj.facebook_id, first_name = obj.first_name, gender = obj.gender, last_name = obj.last_name, username = obj.username, dev_id = obj.dev_id, Role = obj.Role, RolePermissions = (ICollection<RolePermission>)obj.Role.RolePermissions }; //Session[Configurator.SessionUserAuthen] = authen; ClaimdiSessionFacade.ClaimdiSession = authen; //RegionLogic region = new RegionLogic(); //var result = region.getProvice(); //CompanyLogic comp = new CompanyLogic(); //var te = comp.getCompany(); CarLogic car = new CarLogic(); var resultComp = car.getCar(); return View(resultComp); } [AuthorizeUser(AccessLevel = "Edit", PageAction = "Home")] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(LoginModel model) { if (ModelState.IsValid) { AccountProfileLogic acc = new AccountProfileLogic(); var obj = acc.getAccountProfileByUsernamePassword(model.Username, model.Password); if (obj != null) { Authentication authen = new Authentication() { acc_id = obj.acc_id.ToString(), facebook_id = obj.facebook_id, first_name = obj.first_name, gender = obj.gender, last_name = obj.last_name, username = obj.username, com_id = obj.com_id, Role = obj.Role, picture = obj.picture, RolePermissions = (ICollection<RolePermission>)obj.Role.RolePermissions }; ClaimdiSessionFacade.ClaimdiSession = authen; return RedirectToAction("Index", "Dashboard"); } ViewBag.Message = "invalid login, Please try again ."; } return View(model); } public ActionResult Logout() { ClaimdiSessionFacade.Clear(); return RedirectToAction("Login", "Home"); } } }
using BankAppCore.Data.Converters; using BankAppCore.Data.Repositories; using BankAppCore.DataTranferObjects; using BankAppCore.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using static BankAppCore.Data.EFContext.EFContext; namespace BankAppCore.Services { public class ClientService : IClientService { private ClientRepository clientRepository; private AccountRepository accountRepository; public ClientService(ShopContext context) { accountRepository = new AccountRepository(context); clientRepository = new ClientRepository(context); } public IEnumerable<ClientDTO> getAllClients() { return ClientConverter.toDtos(clientRepository.Get()); } public ClientDTO getClientById(String clientId) { Client client = clientRepository.GetByID(clientId); if (client == null) throw new InvalidOperationException("No client found with that clientId"); return ClientConverter.toDto(client); } public void createClient(ClientDTO clientDto) { var context = new ValidationContext(clientDto, serviceProvider: null, items: null); var isValid = Validator.TryValidateObject(clientDto, context, null); if (!isValid) throw new InvalidOperationException("Invalid client"); Client client = new Client { SocialSecurityNumber = clientDto.SocialSecurityNumber, Address = clientDto.Address, FirstName = clientDto.FirstName, LastName = clientDto.LastName, IdentityCardNumber = clientDto.IdentityCardNumber }; Client possibleAlreadyExistingClient = clientRepository.GetByID(clientDto.SocialSecurityNumber); if (possibleAlreadyExistingClient == null) { clientRepository.Insert(client); } else { throw new InvalidOperationException("Client already exists!"); } } public void changeClient(String clientId, ClientDTO clientDto) { Client client = clientRepository.GetByID(clientId); if (client == null) { throw new InvalidOperationException("No client found with that clientId"); } client.FirstName = clientDto.FirstName; client.LastName = clientDto.LastName; client.Address = clientDto.Address; client.IdentityCardNumber = clientDto.IdentityCardNumber; clientRepository.Update(client); } public void deleteClient(String clientId) { Client client = clientRepository.GetByID(clientId); if (client == null) { throw new InvalidOperationException("No client with that clientId"); } foreach (Account account in client.Accounts) { accountRepository.Delete(account.Id); } clientRepository.Delete(client.IdentityCardNumber); } public IEnumerable<AccountDTO> addAccountToClient(String clientId, int accountId) { Client client = clientRepository.GetByID(clientId); Account account = accountRepository.GetByID(accountId); if (client == null || account == null) throw new InvalidOperationException("Client or account does not exist"); account.Client = client; accountRepository.Update(account); return AccountConverter.toDtos(accountRepository.Get().Where(x => x.Client.SocialSecurityNumber == clientId)); } public IEnumerable<AccountDTO> deleteAccountFromClient(String clientId, int accountId) { Client client = clientRepository.GetByID(clientId); accountRepository.Delete(accountId); return AccountConverter.toDtos(accountRepository.Get().Where(x => x.Client.SocialSecurityNumber == clientId)); } }}
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace StarBastard.Windows.Infrastructure { public class GameInfrastructure { public GameTime GameTime { get; set; } public SpriteBatch SpriteBatch { get; set; } public GraphicsDeviceManager GraphicsDeviceManager { get; set; } public GraphicsDevice GraphicsDevice { get; set; } } }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Industry.Offline.Product.Domain.Entities; using MongoDB.Bson; namespace Alabo.Industry.Offline.Product.Domain.Repositories { public class MerchantProductRepository : RepositoryMongo<MerchantProduct, ObjectId>, IMerchantProductRepository { public MerchantProductRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using ScriptableObjectFramework.Events.UnityEvents; using UnityEngine; namespace ScriptableObjectFramework.Sets { [CreateAssetMenu(fileName = "NewGameObjectSet", menuName = "Scriptable Objects/Sets/Game Object")] public class GameObjectRuntimeSet : RuntimeSet<GameObject, GameObjectUnityEvent> { } }
using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Drawing; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class SceneManager : StoryboardObjectGenerator { private delegate void AdditionalCommands(OsbSprite sprite); private Color4 whiteColor = new Color4(229, 225, 226, 255); private Color4 redColor = new Color4(236, 80, 83, 255); private Color4 blueMarineColor = new Color4(15, 155, 178, 255); private Color4 magentaColor = new Color4(198, 110, 118, 255); private Color4 blueColor = new Color4(1, 104, 195, 255); private Color4 violetColor = new Color4(150, 115, 179, 255); private Color4 yellowColor = new Color4(248, 200, 93, 255); /*============================================= //* Scenes =============================================*/ private void Scene1(FontGenerator font) { generateCinematicBars(); /*============================================= //* Line 1 =============================================*/ //* Background generateBackgroundColor(965, 1888, whiteColor); generateBackgroundColor(1888, 2811, redColor); generateBackgroundColor(2811, 3272, whiteColor); generateBackgroundColor(3272, 4195, blueMarineColor); //* Lyrics // 小さく AdditionalCommands line1word1 = (sprite) => { sprite.Color(965, redColor); sprite.Color(1888, Color4.White); sprite.MoveX(1888, 320 + 107); sprite.MoveX(2811, 320 + 854 / 4); sprite.Color(2811, blueMarineColor); sprite.Color(3272, Color4.White); sprite.MoveX(3272, 320 + 107 + 854 / 4); }; generateVeritcalText("小さく", font, 0.1f, 320, 240, "lyrics", 965, 4195, line1word1); // 遠くで AdditionalCommands line1word2 = (sprite) => { sprite.Color(1888, Color4.White); sprite.MoveX(2811, 320); sprite.Color(2811, blueMarineColor); sprite.Color(3272, Color4.White); sprite.MoveX(3272, 320 + 107); }; generateVeritcalText("遠くで", font, 0.1f, 320 - 107, 240, "lyrics", 1888, 4195, line1word2); // 何かが AdditionalCommands line1word3 = (sprite) => { sprite.Color(2811, blueMarineColor); sprite.Color(3272, Color4.White); sprite.MoveX(3272, 320 - 107); }; generateVeritcalText("何かが", font, 0.1f, 320 - 854 / 4, 240, "lyrics", 2811, 4195, line1word3); // 鳴った generateVeritcalText("鳴った", font, 0.1f, 320 - 107 - 854 / 4, 240, "lyrics", 3272, 4195); /*============================================= //* Line 2 =============================================*/ //* Background generateBackgroundColor(4195, 4657, whiteColor); generateBackgroundColor(4657, 5118, magentaColor); generateBackgroundColor(5118, 6272, whiteColor); generateBackgroundColor(6272, 6965, violetColor); generateBackgroundColor(6965, 8349, whiteColor); //* Lyrics // 君の AdditionalCommands line2word1 = (sprite) => { sprite.Color(4195, magentaColor); sprite.Color(4657, Color4.White); sprite.MoveX(4657, 320 + 107); sprite.MoveX(5118, 320 + 854 / 4); sprite.Color(5118, violetColor); sprite.Color(6272, Color4.White); sprite.MoveX(6272, 320 + 107 + 854 / 4); sprite.Color(6965, blueMarineColor); }; generateVeritcalText("君の", font, 0.1f, 320, 240, "lyrics", 4195, 7426, line2word1); // 横顔を AdditionalCommands line2word2 = (sprite) => { sprite.Color(4657, Color4.White); sprite.MoveX(5118, 320); sprite.Color(5118, violetColor); sprite.Color(6272, Color4.White); sprite.MoveX(6272, 320 + 107); sprite.Color(6965, blueMarineColor); }; generateVeritcalText("横顔を", font, 0.1f, 320 - 107, 240, "lyrics", 4657, 7426, line2word2); // 追った AdditionalCommands line2word3 = (sprite) => { sprite.Color(5118, violetColor); sprite.Color(6272, Color4.White); sprite.MoveX(6272, 320 - 107); sprite.Color(6965, blueMarineColor); }; generateVeritcalText("追った", font, 0.1f, 320 - 854 / 4, 240, "lyrics", 5118, 7426, line2word3); // 一瞬、 AdditionalCommands line2word4 = (sprite) => { sprite.Color(6272, Color4.White); sprite.Color(6965, blueMarineColor); }; generateVeritcalText("一瞬、", font, 0.1f, 320 - 107 - 854 / 4, 240, "lyrics", 6272, 7426, line2word4); // もう一瞬 AdditionalCommands line2word5 = (sprite) => { sprite.Color(7888, blueMarineColor); }; generateHorizontalText("もう一瞬", font, 0.7f, 140, 7888, 8349, line2word5); } private void Scene2() { generateBackgroundColor(8349, 23118, whiteColor); generateVerticalStripeBackground(10195, 11580, 60, blueColor, -60, true); generateVerticalStripeBackground(12041, 13426, 45, magentaColor, 45, false); generateHorizontalStripeBackground(13888, 15272, 60, blueMarineColor, false); generateVerticalStripeBackground(15734, 17118, 45, yellowColor, 30, true); generateVerticalStripeBackground(17580, 18965, 45, redColor, 0, true); generateVerticalStripeBackground(19426, 20811, 60, blueColor, 60, false); generateHorizontalStripeBackground(21272, 23118, 60, blueMarineColor, true, false); generateVerticalStripeTransition(22657, 60, whiteColor, 45, true); // Girl var girl = GetLayer("elements").CreateSprite("sb/elements/s-girl.png", OsbOrigin.Centre); girl.Scale(8349, 0.5); girl.Fade(8349, 1); girl.Fade(23118, 0); girl.Move(8349, 23118, new Vector2(150, 480), new Vector2(415, 320)); } private void Scene3(FontGenerator font) { /*============================================= //* 1st half =============================================*/ generateBackgroundColor(23118, 24503, yellowColor); generateVerticalStripeBackground(24041, 25426, 60, blueColor, -60, true, false); generateVerticalStripeBackground(24965, 27272, 45, magentaColor, 45, false, false); generateHorizontalStripeBackground(26811, 28195, 60, blueMarineColor, false, false); generateVerticalStripeBackground(27734, 29118, 45, yellowColor, 30, true, false); generateVerticalStripeBackground(28657, 29580, 60, redColor, 0, true, false); generateBackgroundColor(29580, 30041, blueMarineColor); generateBackgroundColor(30041, 30272, magentaColor); generateBackgroundColor(30272, 30964, yellowColor); //* Lyrics generateScrollUpTiltedRightAlignedText(23118, 29580, "もうちょっとだけ\n大人でいたくて\n夏際くるぶしに\n少し掠るくらいで\n歩いている", 0.2f, new Vector2(270, 170), 228, -30, font, whiteColor); //* Sleeping girl var girl = GetLayer("elements").CreateSprite("sb/elements/s-girl.png", OsbOrigin.Centre); girl.Scale(23118, 0.5); girl.Fade(23118, 1); girl.Fade(30272, 0); girl.Move(23118, 30964, new Vector2(754, 480), new Vector2(615, 240)); //* Ice cream var icecreamW = GetLayer("elements-w").CreateSprite("sb/elements/ice-cream-w.png", OsbOrigin.Centre); icecreamW.Scale(23118, 0.5); icecreamW.Fade(23118, 0); icecreamW.Fade(29811, 1); icecreamW.Fade(30964, 0); icecreamW.Color(29811, yellowColor); icecreamW.Color(30041, blueMarineColor); icecreamW.Color(30272, magentaColor); icecreamW.Move(23118, 30964, new Vector2(754, 480), new Vector2(615, 240)); //* Girl white 2 var girlW2 = GetLayer("elements-w").CreateSprite("sb/elements/s-girl-w-2.png", OsbOrigin.Centre); girlW2.Scale(23118, 0.5); girlW2.Fade(23118, 0); girlW2.Fade(30041, 1); girlW2.Fade(30964, 0); girlW2.Color(30041, yellowColor); girlW2.Color(30272, redColor); girlW2.Move(23118, 30964, new Vector2(754, 480), new Vector2(615, 240)); //* Bubble var bubbleW = GetLayer("elements-w").CreateSprite("sb/elements/bubble-w.png", OsbOrigin.Centre); bubbleW.Scale(23118, 0.5); bubbleW.Color(30272, blueColor); bubbleW.Fade(23118, 0); bubbleW.Fade(30272, 1); bubbleW.Fade(30964, 0); bubbleW.Move(23118, 30964, new Vector2(754, 480), new Vector2(615, 240)); /*============================================= //* 2nd half =============================================*/ var mask = GetLayer("dropdown-element").CreateSprite("sb/elements/mask.png", OsbOrigin.BottomCentre); mask.Scale(30503, 0.2); generateDropdownTextAndElement(30503, 31426, "小さく", font, blueColor, mask); var fan = GetLayer("dropdown-element").CreateSprite("sb/elements/fan.png", OsbOrigin.BottomCentre); fan.Scale(31426, 0.2); generateDropdownTextAndElement(31426, 32349, "遠くで", font, yellowColor, fan); var bubble = GetLayer("dropdown-element").CreateSprite("sb/elements/bubble.png", OsbOrigin.BottomCentre); bubble.Scale(32349, 0.3); generateDropdownTextAndElement(32349, 33272, "何かが\n鳴った", font, redColor, bubble); var bg = GetLayer("dropdown-bg").CreateSprite("sb/common/pixel.png", OsbOrigin.TopLeft, new Vector2(-107, 0)); bg.ScaleVec(OsbEasing.OutCirc, 33272, 33734, new Vector2(854, 0), new Vector2(854, 480)); bg.Color(33272, blueMarineColor); bg.Fade(33272, 1); bg.Fade(37426, 0); //* Circles + elements var bigCircle = GetLayer("circle").CreateSprite("sb/common/circle.png", OsbOrigin.Centre); bigCircle.Scale(OsbEasing.OutCirc, 33272, 33734, 0.2, 1.05); bigCircle.Color(33272, yellowColor); bigCircle.Fade(33272, 1); bigCircle.Fade(37426, 0); var innerCircle = GetLayer("circle").CreateSprite("sb/common/circle.png", OsbOrigin.Centre); innerCircle.Scale(OsbEasing.OutCirc, 33272, 33734, 0, 0.95); innerCircle.Color(33272, whiteColor); innerCircle.Fade(33272, 1); innerCircle.Fade(37426, 0); var girlShadow = GetLayer("girl-on-circle").CreateSprite("sb/elements/s-girl-w.png", OsbOrigin.Centre, new Vector2(315, 243)); girlShadow.Color(33734, yellowColor); girlShadow.Scale(OsbEasing.OutCirc, 33734, 34195, 0.0, 0.2); girlShadow.Scale(34195, 37426, 0.2, 0.17); girlShadow.Rotate(33734, 37426, 0, MathHelper.DegreesToRadians(-15)); girlShadow.Fade(33734, 1); girl = GetLayer("girl-on-circle").CreateSprite("sb/elements/s-girl.png", OsbOrigin.Centre); girl.Scale(OsbEasing.OutCirc, 33734, 34195, 0.0, 0.2); girl.Scale(34195, 37426, 0.2, 0.17); girl.Rotate(33734, 37426, 0, MathHelper.DegreesToRadians(-15)); girl.Fade(33734, 1); girl.Fade(37426, 0); //* Particle pool using (var pool = new OsbSpritePool(GetLayer("particles-on-circle"), "sb/common/circle.png", OsbOrigin.Centre, (sprite, startTime, endTime) => { var rScale = Random(0.002, 0.006); var rColor = Random(0, 2); sprite.Scale(33272, rScale); sprite.Color(33272, rColor == 0 ? blueMarineColor : yellowColor); })) { var particleAmount = 500; for (int i = 0; i < particleAmount; i++) { var sprite = pool.Get(33734, 37426); var startX = Random(-107, 747); var startY = Random(0, 480); sprite.Move(33272, 37426, new Vector2(startX, startY), new Vector2(startX + Random(-50, 50), startY + Random(-50, 50))); sprite.Fade(33272, 33734, 0, 1); sprite.Fade(37426, 0); } } //* Lyrics generateRotatingSplitText(33734, 37426, 36964, "いつも横顔を", "追っていたんだ", 0.2f, 20, 100, 50, font); // Transition generateCentreRectangleTransition(36964, 37657, blueColor); generateCentreRectangleTransition(37426, 37888, blueMarineColor); } private void Scene4(FontGenerator font) { generateBackgroundColor(37657, 52657, whiteColor); } /*============================================= //* Helper Methods =============================================*/ private void generateCinematicBars() { var upperBar = GetLayer("cinematic-bar").CreateSprite("sb/common/pixel.png", OsbOrigin.TopCentre, new Vector2(320, 0)); upperBar.ScaleVec(965, 8349, new Vector2(854, 60), new Vector2(854, 60)); upperBar.Color(965, Color4.Black); var lowerBar = GetLayer("cinematic-bar").CreateSprite("sb/common/pixel.png", OsbOrigin.BottomCentre, new Vector2(320, 480)); lowerBar.ScaleVec(965, 8349, new Vector2(854, 60), new Vector2(854, 60)); lowerBar.Color(965, Color4.Black); var vig = GetLayer("vig").CreateSprite("sb/common/vig.png", OsbOrigin.Centre); vig.Fade(965, 0.9); vig.Fade(8349, 0); vig.Scale(965, 854.0 / 1920.0); } private void generateVeritcalText(string text, FontGenerator font, float fontScale, float initPositionX, float initPositionY, string layer, double startTime, double endTime, AdditionalCommands callback = null) { var lineHeight = 0f; var letterX = initPositionX; foreach (var letter in text) { var texture = font.GetTexture(letter.ToString()); lineHeight += texture.BaseHeight * fontScale; } var letterY = initPositionY - lineHeight * 0.5f; foreach (var letter in text) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY); var sprite = GetLayer(layer).CreateSprite(texture.Path, OsbOrigin.Centre, position); sprite.MoveX(startTime, position.X); sprite.Scale(startTime, fontScale); sprite.Fade(startTime, 1); sprite.Fade(endTime, 0); if (callback != null) { callback(sprite); } letterY += texture.BaseHeight * fontScale; } } } private void generateHorizontalText(string text, FontGenerator font, float fontScale, float initPositionY, double startTime, double endTime, AdditionalCommands callback = null) { var lineWidth = 0f; var letterY = initPositionY; foreach (var letter in text) { var texture = font.GetTexture(letter.ToString()); lineWidth += texture.BaseWidth * fontScale; } var letterX = 320 - lineWidth * 0.5f; foreach (var letter in text) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY) + texture.OffsetFor(OsbOrigin.Centre) * fontScale; var sprite = GetLayer("lyrics").CreateSprite(texture.Path, OsbOrigin.Centre, position); sprite.MoveY(startTime, position.Y); sprite.Scale(startTime, fontScale); sprite.Fade(startTime, 1); sprite.Fade(endTime, 0); if (callback != null) { callback(sprite); } letterX += texture.BaseWidth * fontScale; } } } private void generateBackgroundColor(double startTime, double endTime, Color4 color) { var sprite = GetLayer("bg").CreateSprite("sb/common/pixel.png", OsbOrigin.Centre); sprite.ScaleVec(startTime, new Vector2(854, 480)); sprite.Color(startTime, color); sprite.Fade(startTime, 1); sprite.Fade(endTime, 0); } private void generateVerticalStripeBackground(double startTime, double endTime, int thickness, Color4 color, int angle, bool rightToLeft = false, bool withClosing = true) { Assert((angle < 90 && angle >= 0) || (angle > -90 && angle <= 0), "Parameter angle of generateVerticalStripeBackground() can only accept value from -90 to 90 degree."); var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var actualLength = 854 + 480 * Math.Tan(MathHelper.DegreesToRadians(Math.Abs(angle))); var spriteLength = (float)(Math.Sqrt(Math.Pow(854, 2) + Math.Pow(480, 2)) + thickness * Math.Tan(MathHelper.DegreesToRadians(Math.Abs(angle)))); if (angle < 90 && angle >= 0) { var openOrigin = rightToLeft ? OsbOrigin.TopRight : OsbOrigin.TopLeft; var closeOrigin = rightToLeft ? OsbOrigin.TopLeft : OsbOrigin.TopRight; var openX = rightToLeft ? (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness * (1 / Math.Sin(MathHelper.DegreesToRadians(angle)) - Math.Cos(MathHelper.DegreesToRadians(angle)))); var openY = rightToLeft ? 0f : (float)(0 - thickness * Math.Sin(MathHelper.DegreesToRadians(angle))); var closeX = rightToLeft ? (float)(openX - thickness * Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); var closeY = rightToLeft ? (float)(0 - thickness * Math.Sin(MathHelper.DegreesToRadians(angle))) : 0f; for (int i = 0; i <= (int)(actualLength / (thickness / Math.Cos(MathHelper.DegreesToRadians(angle)))); i++) { var openSprite = GetLayer("open-stripe").CreateSprite("sb/common/pixel.png", openOrigin, new Vector2(openX, openY)); openSprite.Color(startTime, color); openSprite.Rotate(startTime, MathHelper.DegreesToRadians(angle)); openSprite.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat, new Vector2(0, spriteLength), new Vector2(thickness, spriteLength)); openSprite.Fade(startTime, 1); if (withClosing) { openSprite.Fade(endTime - beat, 0); var closeSprite = GetLayer("close-stripe").CreateSprite("sb/common/pixel.png", closeOrigin, new Vector2(closeX, closeY)); closeSprite.Color(endTime - beat, color); closeSprite.Rotate(endTime - beat, MathHelper.DegreesToRadians(angle)); closeSprite.ScaleVec(OsbEasing.InCirc, endTime - beat, endTime, new Vector2(thickness, spriteLength), new Vector2(0, spriteLength)); closeSprite.Fade(endTime - beat, 1); closeSprite.Fade(endTime, 0); } else { openSprite.Fade(endTime, 0); } openX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); closeX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); } } else if (angle > -90 && angle <= 0) { var openOrigin = rightToLeft ? OsbOrigin.BottomRight : OsbOrigin.BottomLeft; var closeOrigin = rightToLeft ? OsbOrigin.BottomLeft : OsbOrigin.BottomRight; var openX = rightToLeft ? (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness * (1 / Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle))) - Math.Cos(MathHelper.DegreesToRadians(angle)))); var openY = rightToLeft ? 480f : (float)(480 + thickness * Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle)))); var closeX = rightToLeft ? (float)(openX - thickness * Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); var closeY = rightToLeft ? (float)(480 + thickness * Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle)))) : 480f; for (int i = 0; i <= (int)(actualLength / (thickness / Math.Cos(MathHelper.DegreesToRadians(angle)))); i++) { var openSprite = GetLayer("open-stripe").CreateSprite("sb/common/pixel.png", openOrigin, new Vector2(openX, openY)); openSprite.Color(startTime, color); openSprite.Rotate(startTime, MathHelper.DegreesToRadians(angle)); openSprite.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat, new Vector2(0, spriteLength), new Vector2(thickness, spriteLength)); openSprite.Fade(startTime, 1); if (withClosing) { openSprite.Fade(endTime - beat, 0); var closeSprite = GetLayer("close-stripe").CreateSprite("sb/common/pixel.png", closeOrigin, new Vector2(closeX, closeY)); closeSprite.Color(endTime - beat, color); closeSprite.Rotate(endTime - beat, MathHelper.DegreesToRadians(angle)); closeSprite.ScaleVec(OsbEasing.InCirc, endTime - beat, endTime, new Vector2(thickness, spriteLength), new Vector2(0, spriteLength)); closeSprite.Fade(endTime - beat, 1); closeSprite.Fade(endTime, 0); } else { openSprite.Fade(endTime, 0); } openX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); closeX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); } } } private void generateHorizontalStripeBackground(double startTime, double endTime, int thickness, Color4 color, bool bottomToTop = false, bool withClosing = true) { var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var openOrigin = bottomToTop ? OsbOrigin.BottomLeft : OsbOrigin.TopLeft; var closeOrigin = bottomToTop ? OsbOrigin.TopLeft : OsbOrigin.BottomLeft; var openX = -107f; var openY = bottomToTop ? 0 + thickness : 0; var closeX = openX; var closeY = bottomToTop ? 0 : 0 + thickness; for (int i = 0; i <= (int)(480 / thickness); i++) { var openSprite = GetLayer("open-stripe").CreateSprite("sb/common/pixel.png", openOrigin, new Vector2(openX, openY)); openSprite.Color(startTime, color); openSprite.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat, new Vector2(854, 0), new Vector2(854, thickness)); openSprite.Fade(startTime, 1); if (withClosing) { openSprite.Fade(endTime - beat, 0); var closeSprite = GetLayer("close-stripe").CreateSprite("sb/common/pixel.png", closeOrigin, new Vector2(closeX, closeY)); closeSprite.Color(endTime - beat, color); closeSprite.ScaleVec(OsbEasing.InCirc, endTime - beat, endTime, new Vector2(854, thickness), new Vector2(854, 0)); closeSprite.Fade(endTime - beat, 1); closeSprite.Fade(endTime, 0); } else { openSprite.Fade(endTime, 0); } openY += thickness; closeY += thickness; } } private void generateVerticalStripeTransition(double startTime, int thickness, Color4 color, int angle, bool rightToLeft = false) { Assert((angle < 90 && angle >= 0) || (angle > -90 && angle <= 0), "Parameter angle of generateVerticalStripeTransition() can only accept value from -90 to 90 degree."); var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var actualLength = 854 + 480 * Math.Tan(MathHelper.DegreesToRadians(Math.Abs(angle))); var spriteLength = (float)(Math.Sqrt(Math.Pow(854, 2) + Math.Pow(480, 2)) + thickness * Math.Tan(MathHelper.DegreesToRadians(Math.Abs(angle)))); if (angle < 90 && angle >= 0) { var openOrigin = rightToLeft ? OsbOrigin.TopRight : OsbOrigin.TopLeft; var closeOrigin = rightToLeft ? OsbOrigin.TopLeft : OsbOrigin.TopRight; var openX = rightToLeft ? (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness * (1 / Math.Sin(MathHelper.DegreesToRadians(angle)) - Math.Cos(MathHelper.DegreesToRadians(angle)))); var openY = rightToLeft ? 0f : (float)(0 - thickness * Math.Sin(MathHelper.DegreesToRadians(angle))); var closeX = rightToLeft ? (float)(openX - thickness * Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); var closeY = rightToLeft ? (float)(0 - thickness * Math.Sin(MathHelper.DegreesToRadians(angle))) : 0f; for (int i = 0; i <= (int)(actualLength / (thickness / Math.Cos(MathHelper.DegreesToRadians(angle)))); i++) { var openSprite = GetLayer("transition").CreateSprite("sb/common/pixel.png", openOrigin, new Vector2(openX, openY)); openSprite.Color(startTime, color); openSprite.Rotate(startTime, MathHelper.DegreesToRadians(angle)); openSprite.ScaleVec(OsbEasing.OutExpo, startTime, startTime + beat, new Vector2(0, spriteLength), new Vector2(thickness, spriteLength)); openSprite.Fade(startTime, 1); openSprite.Fade(startTime + beat, 0); var closeSprite = GetLayer("transition").CreateSprite("sb/common/pixel.png", closeOrigin, new Vector2(closeX, closeY)); closeSprite.Color(startTime + beat, color); closeSprite.Rotate(startTime + beat, MathHelper.DegreesToRadians(angle)); closeSprite.ScaleVec(OsbEasing.OutCirc, startTime + beat, startTime + beat * 2, new Vector2(thickness, spriteLength), new Vector2(0, spriteLength)); closeSprite.Fade(startTime + beat, 1); closeSprite.Fade(startTime + beat * 2, 0); openX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); closeX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); } } else if (angle > -90 && angle <= 0) { var openOrigin = rightToLeft ? OsbOrigin.BottomRight : OsbOrigin.BottomLeft; var closeOrigin = rightToLeft ? OsbOrigin.BottomLeft : OsbOrigin.BottomRight; var openX = rightToLeft ? (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness * (1 / Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle))) - Math.Cos(MathHelper.DegreesToRadians(angle)))); var openY = rightToLeft ? 480f : (float)(480 + thickness * Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle)))); var closeX = rightToLeft ? (float)(openX - thickness * Math.Cos(MathHelper.DegreesToRadians(angle))) : (float)(-107 + thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); var closeY = rightToLeft ? (float)(480 + thickness * Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle)))) : 480f; for (int i = 0; i <= (int)(actualLength / (thickness / Math.Cos(MathHelper.DegreesToRadians(angle)))); i++) { var openSprite = GetLayer("open-stripe").CreateSprite("sb/common/pixel.png", openOrigin, new Vector2(openX, openY)); openSprite.Color(startTime, color); openSprite.Rotate(startTime, MathHelper.DegreesToRadians(angle)); openSprite.ScaleVec(OsbEasing.OutExpo, startTime, startTime + beat, new Vector2(0, spriteLength), new Vector2(thickness, spriteLength)); openSprite.Fade(startTime, 1); openSprite.Fade(startTime + beat, 0); var closeSprite = GetLayer("close-stripe").CreateSprite("sb/common/pixel.png", closeOrigin, new Vector2(closeX, closeY)); closeSprite.Color(startTime + beat, color); closeSprite.Rotate(startTime + beat, MathHelper.DegreesToRadians(angle)); closeSprite.ScaleVec(OsbEasing.OutCirc, startTime + beat, startTime + beat * 2, new Vector2(thickness, spriteLength), new Vector2(0, spriteLength)); closeSprite.Fade(startTime + beat, 1); closeSprite.Fade(startTime + beat * 2, 0); openX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); closeX += (float)(thickness / Math.Cos(MathHelper.DegreesToRadians(angle))); } } } private void generateDropdownTextAndElement(double startTime, double endTime, string text, FontGenerator font, Color4 color, OsbSprite element) { var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var bg = GetLayer("dropdown-bg").CreateSprite("sb/common/pixel.png", OsbOrigin.TopLeft, new Vector2(-107, 0)); bg.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat, new Vector2(854, 0), new Vector2(854, 480)); bg.Color(startTime, color); bg.Fade(startTime, 1); bg.Fade(endTime + beat, 0); element.MoveY(OsbEasing.OutCirc, startTime, startTime + beat, 0, 200); element.MoveY(OsbEasing.InCirc, endTime - beat, endTime, 200, 560); element.Fade(startTime, 1); element.Fade(endTime, 0); var numberOfLine = (float)text.Split('\n').Length; var posX = 0f; var lineWidth = 0f; var lineHeight = 0f; var textPadding = 20; foreach (var line in text.Split('\n')) { lineHeight = 0f; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); lineWidth = Math.Max(lineWidth, texture.BaseWidth * 0.3f); lineHeight += texture.BaseHeight * 0.3f; posX = (float)(numberOfLine % 2 == 0 ? 320f - ((numberOfLine - 1) / 2) * (lineWidth + textPadding) : 320f - ((numberOfLine - 1) / 2) * (lineWidth + textPadding)); } } foreach (var line in text.Split('\n')) { var letterX = posX; var letterY = 0 - lineHeight; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY); var sprite = GetLayer("dropdown-text").CreateSprite(texture.Path, OsbOrigin.Centre, position); sprite.MoveY(OsbEasing.OutCirc, startTime, startTime + beat, letterY, letterY + 340); sprite.MoveY(OsbEasing.InCirc, endTime - beat, endTime, letterY + 340, letterY + 700); sprite.Scale(startTime, 0.3f); sprite.Fade(startTime, 1); sprite.Fade(endTime, 0); letterY += texture.BaseHeight * 0.3f; } } posX += (lineWidth + textPadding); } } private void generateScrollUpTiltedRightAlignedText(double startTime, double endTime, string text, float fontScale, Vector2 startPosition, float distance, int angle, FontGenerator font, Color4 color) { var beat = Beatmap.GetTimingPointAt(965).BeatDuration; // startPosition is actually the top right coordinate of the last letter of the first line. var currentPosition = startPosition; var time = startTime; var numberOfLetters = text.Replace("\n", "").Length; var textPadding = 10; foreach (var line in text.Split('\n')) { var lineWidth = 0f; var lineHeight = 0f; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); lineWidth += texture.BaseWidth * fontScale + textPadding; lineHeight = Math.Max(texture.BaseHeight * fontScale, lineHeight); } var letterX = currentPosition.X - lineWidth * (float)Math.Cos(MathHelper.DegreesToRadians(Math.Abs(angle))); var letterY = currentPosition.Y + lineWidth * (float)Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle))); foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY) + texture.OffsetFor(OsbOrigin.TopRight) * fontScale; var sprite = GetLayer("lyrics").CreateSprite(texture.Path, OsbOrigin.Centre, position); sprite.Rotate(startTime, MathHelper.DegreesToRadians(angle)); sprite.Scale(startTime, fontScale); sprite.Fade(startTime, 0); sprite.Fade(time, 1); sprite.Fade(endTime, 0); sprite.MoveX(startTime, endTime, letterX, letterX - distance * (float)Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle)))); sprite.MoveY(startTime, endTime, letterY, letterY - distance * (float)Math.Cos(MathHelper.DegreesToRadians(Math.Abs(angle)))); letterX += (texture.BaseWidth * fontScale + textPadding) * (float)Math.Cos(MathHelper.DegreesToRadians(Math.Abs(angle))); letterY -= (texture.BaseWidth * fontScale + textPadding) * (float)Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle))); time += (double)((endTime - startTime - beat / 2) / numberOfLetters); } } currentPosition.X += (lineHeight + textPadding) * (float)Math.Sin(MathHelper.DegreesToRadians(Math.Abs(angle))); currentPosition.Y += (lineHeight + textPadding) * (float)Math.Cos(MathHelper.DegreesToRadians(Math.Abs(angle))); } } private void generateRotatingSplitText(double startTime, double endTime, double textEndTime, string text1, string text2, float fontScale, int angle, int offsetTopY, int offsetBottomY, FontGenerator font) { // preconfigured options var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var timeStep = beat / 8; var radius = 150; var angleStep = angle / ((endTime - startTime) / timeStep); var t = (int)((endTime - startTime) / timeStep); var textPadding = 10; // text1 var text1Postition = new Vector2(320, 240) - new Vector2(radius, offsetTopY); var time = startTime; var numberOfLetters = text1.Replace("\n", "").Length; int lineOrder = 0; foreach (var line in text1.Split('\n')) { var lineWidth = 0f; var lineHeight = 0f; int letterOrder = line.Length; var textureWidth = 0f; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); textureWidth = texture.BaseWidth * fontScale; lineWidth += texture.BaseWidth * fontScale + textPadding; lineHeight = Math.Max(texture.BaseHeight * fontScale, lineHeight); } var letterX = text1Postition.X - lineWidth - textureWidth; var letterY = text1Postition.Y; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY) + texture.OffsetFor(OsbOrigin.CentreRight) * fontScale; var sprite = GetLayer("lyrics-on-circle").CreateSprite(texture.Path, OsbOrigin.CentreRight, position); sprite.Scale(startTime, fontScale); if (time != startTime) { sprite.Fade(startTime, 0); } sprite.Fade(time, 1); sprite.Fade(endTime, 0); sprite.Color(startTime, Random(0, 2) == 0 ? redColor : blueColor); // loop var currentTime = startTime; var currentAngle = 0 + angleStep; var currentPosition = position; for (int i = 0; i < t; i++) { var targetPosition = new Vector2(); targetPosition.X = (float)(320 - (radius + letterOrder * (20 + textPadding)) * Math.Cos(MathHelper.DegreesToRadians(currentAngle)) + (lineOrder * (20 + textPadding)) * Math.Sin(MathHelper.DegreesToRadians(currentAngle))); targetPosition.Y = (float)((240 - offsetTopY) + (radius + letterOrder * (20 + textPadding)) * Math.Sin(MathHelper.DegreesToRadians(currentAngle)) + (lineOrder * (20 + textPadding)) * Math.Cos(MathHelper.DegreesToRadians(currentAngle))); sprite.Move(currentTime, currentTime + timeStep, currentPosition, targetPosition); sprite.Rotate(currentTime, MathHelper.DegreesToRadians(-currentAngle)); currentTime += timeStep; currentAngle += angleStep; currentPosition = targetPosition; } letterX -= (texture.BaseWidth * fontScale + textPadding); time += (double)(((textEndTime - startTime) / 2 - beat / 2) / numberOfLetters); letterOrder--; } } text1Postition.Y += (lineHeight + textPadding); lineOrder++; } // text2 var text2Postition = new Vector2(320, 240) + new Vector2(radius, offsetBottomY); numberOfLetters = text2.Replace("\n", "").Length; lineOrder = 0; foreach (var line in text2.Split('\n')) { var lineWidth = 0f; var lineHeight = 0f; int letterOrder = 0; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); lineWidth += texture.BaseWidth * fontScale + textPadding; lineHeight = Math.Max(texture.BaseHeight * fontScale, lineHeight); } var letterX = text2Postition.X; var letterY = text2Postition.Y; foreach (var letter in line) { var texture = font.GetTexture(letter.ToString()); if (!texture.IsEmpty) { var position = new Vector2(letterX, letterY) + texture.OffsetFor(OsbOrigin.CentreLeft) * fontScale; var sprite = GetLayer("lyrics-on-circle").CreateSprite(texture.Path, OsbOrigin.CentreLeft, position); sprite.Scale(startTime, fontScale); sprite.Fade(startTime, 0); sprite.Fade(time, 1); sprite.Fade(endTime, 0); sprite.Color(startTime, Random(0, 2) == 0 ? redColor : blueColor); // loop var currentTime = startTime; var currentAngle = 0 + angleStep; var currentPosition = position; for (int i = 0; i < t; i++) { var targetPosition = new Vector2(); targetPosition.X = (float)(320 + (radius + letterOrder * (20 + textPadding)) * Math.Cos(MathHelper.DegreesToRadians(currentAngle)) + (lineOrder * (20 + textPadding)) * Math.Sin(MathHelper.DegreesToRadians(currentAngle))); targetPosition.Y = (float)((240 + offsetBottomY) - (radius + letterOrder * (20 + textPadding)) * Math.Sin(MathHelper.DegreesToRadians(currentAngle)) + (lineOrder * (20 + textPadding)) * Math.Cos(MathHelper.DegreesToRadians(currentAngle))); sprite.Move(currentTime, currentTime + timeStep, currentPosition, targetPosition); sprite.Rotate(currentTime, MathHelper.DegreesToRadians(-currentAngle)); currentTime += timeStep; currentAngle += angleStep; currentPosition = targetPosition; } Log(letterY.ToString()); letterX += (texture.BaseWidth * fontScale + textPadding); time += (double)(((textEndTime - startTime) / 2 - beat / 2) / numberOfLetters); letterOrder++; } } text2Postition.Y += (lineHeight + textPadding); lineOrder++; } } private void generateCentreRectangleTransition(double startTime, double endTime, Color4 color) { var beat = Beatmap.GetTimingPointAt(965).BeatDuration; var leftSprite1 = GetLayer("transition").CreateSprite("sb/common/pixel.png", OsbOrigin.CentreRight, new Vector2(320, 240)); leftSprite1.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat / 2, new Vector2(0, 480), new Vector2(427, 480)); leftSprite1.Fade(startTime, 1); leftSprite1.Fade(endTime - beat / 2, 0); leftSprite1.Color(startTime, color); var rightSprite1 = GetLayer("transition").CreateSprite("sb/common/pixel.png", OsbOrigin.CentreLeft, new Vector2(320, 240)); rightSprite1.ScaleVec(OsbEasing.OutCirc, startTime, startTime + beat / 2, new Vector2(0, 480), new Vector2(427, 480)); rightSprite1.Fade(startTime, 1); rightSprite1.Fade(endTime - beat / 2, 0); rightSprite1.Color(startTime, color); var leftSprite2 = GetLayer("transition").CreateSprite("sb/common/pixel.png", OsbOrigin.CentreLeft, new Vector2(-107, 240)); leftSprite2.ScaleVec(OsbEasing.InQuad, endTime - beat / 2, endTime, new Vector2(427, 480), new Vector2(0, 480)); leftSprite2.Fade(endTime - beat / 2, 1); leftSprite2.Fade(endTime, 0); leftSprite2.Color(endTime - beat / 2, color); var rightSprite2 = GetLayer("transition").CreateSprite("sb/common/pixel.png", OsbOrigin.CentreRight, new Vector2(747, 240)); rightSprite2.ScaleVec(OsbEasing.InQuad, endTime - beat / 2, endTime, new Vector2(427, 480), new Vector2(0, 480)); rightSprite2.Fade(endTime - beat / 2, 1); rightSprite2.Fade(endTime, 0); rightSprite2.Color(endTime - beat / 2, color); } /*============================================= //* Main =============================================*/ public override void Generate() { var fontSoukouMincho = LoadFont("sb/lyrics/SoukouMincho", new FontDescription() { FontPath = "SoukouMincho.ttf", FontSize = 200, Color = Color4.White, Padding = Vector2.Zero, FontStyle = FontStyle.Regular, TrimTransparency = true }); var fontYasashisaAntique = LoadFont("sb/lyrics/YasashisaAntique", new FontDescription() { FontPath = "YasashisaAntique.otf", FontSize = 70, Color = Color4.White, Padding = Vector2.Zero, FontStyle = FontStyle.Regular, TrimTransparency = true }); Scene1(fontSoukouMincho); Scene2(); Scene3(fontYasashisaAntique); Scene4(fontYasashisaAntique); } } }
using DependencyViewModel; using KinectSandbox.Capture.ColorMapping; using KinectSandbox.Common; using KinectSandbox.Common.Events; using Microsoft.Kinect; using Microsoft.Practices.Prism.PubSubEvents; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace KinectSandbox.Capture.Preview { public class PreviewViewModel : ViewModelBase, IPreviewViewModel { private IColorMap colorMap; private KinectSensor sensor; /// <summary> /// Gets the frame reader /// </summary> private MultiSourceFrameReader reader; /// <summary> /// Returns the current depth values. /// </summary> private UInt16[] DepthData { get; set; } /// <summary> /// Returns the RGB pixel values. /// </summary> private byte[] Pixels { get; set; } /// <summary> /// Returns the width of the bitmap. /// </summary> private int Width { get; set; } /// <summary> /// Returns the height of the bitmap. /// </summary> private int Height { get; set; } /// <summary> /// The bitmap to display /// </summary> private WriteableBitmap Bitmap { get; set; } public ImageSource ImageSource { get { return Bitmap; } } /// <summary> /// Gets and sets the skew to apply to the image /// </summary> [DefaultValue(0)] public int Skew { get { return Get<int>(); } set { Set(value); } } private readonly IEventAggregator eventAggregator; public PreviewViewModel(IPropertyStore propertyStore, IColorMap colorMap, IEventAggregator eventAggregator) : base(propertyStore) { this.colorMap = colorMap; this.eventAggregator = eventAggregator; InitKinect(); //this.StatusText = this.sensor.IsAvailable ? KinectStatus.StatusText.Available : KinectStatus.StatusText.NotAvailable; this.eventAggregator.GetEvent<AdjustmentChangedEvent>() .Subscribe(UpdateSkew, ThreadOption.BackgroundThread); } private void UpdateSkew(AdjustmentChangedInformation info) { this.Skew = info.Skew; } private void InitKinect() { sensor = KinectSensor.GetDefault(); sensor.IsAvailableChanged += sensor_IsAvailableChanged; reader = sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Depth); reader.MultiSourceFrameArrived += reader_FrameArrived; sensor.Open(); } private void InitBitmap() { Width = 512; //depthFrame.FrameDescription.Width; Height = 424; //depthFrame.FrameDescription.Height; DepthData = new UInt16[Width * Height]; Pixels = new byte[DepthData.Length * Constants.BYTES_PER_PIXEL]; Bitmap = new WriteableBitmap(Width, Height, Constants.DPI, Constants.DPI, Constants.FORMAT, null); } void reader_FrameArrived(Object sender, MultiSourceFrameArrivedEventArgs e) { var multiSourceFrame = e.FrameReference.AcquireFrame(); if (multiSourceFrame == null) { return; } var depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); if (depthFrame == null) { return; } if (Bitmap == null) { InitBitmap(); colorMap.Init(depthFrame.DepthMinReliableDistance, depthFrame.DepthMaxReliableDistance); } depthFrame.CopyFrameDataToArray(DepthData); //This yeilds a black diagonal line where x==y - not sure why, but will look into later. //Parallel.For(0, Width, x => //{ // Parallel.For(0, Height, y => // { // if (y == 423) // { return; } // var depthIndex = (512 * y) + x + y; // var depth = DepthData[depthIndex]; // var color = colorMap.GetColorForDepth(x, y, depth); // var pixelIndexStart = (depthIndex * 4); // Pixels[pixelIndexStart] = color.B; // Pixels[pixelIndexStart + 1] = color.G; // Pixels[pixelIndexStart + 2] = color.R; // Pixels[pixelIndexStart + 3] = 255; // }); //}); var x = 0; var y = 0; for (var i = 0; i < DepthData.Length; i++) { var color = colorMap.GetColorForDepth(x, y, DepthData[i]); Pixels[i * 4] = color.B; Pixels[(i * 4) + 1] = color.G; Pixels[(i * 4) + 2] = color.R; Pixels[(i * 4) + 3] = 255; if (x > Width) { x = 0; y++; } else { x++; } } depthFrame.Dispose(); Bitmap.Lock(); Marshal.Copy(Pixels, 0, Bitmap.BackBuffer, Pixels.Length); Bitmap.AddDirtyRect(new Int32Rect(0, 0, Width, Height)); Bitmap.Unlock(); OnPropertyChanged(()=>ImageSource); } void sensor_IsAvailableChanged(object sender, IsAvailableChangedEventArgs e) { //this.SensorAvailable = e.IsAvailable; //this.StatusText = this.sensor.IsAvailable ? KinectStatus.StatusText.Available : KinectStatus.StatusText.NotAvailable; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Construction_Project { public partial class EmployPayments : System.Web.UI.Page { string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } //SELECT Button Click protected void Button2_Click(object sender, EventArgs e) { getDutySheetByID(); } // user defined function void getDutySheetByID() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("SELECT * from Duty_Sheet_tbl where Duty_Sheet_No='" + TextBox38.Text.Trim() + "';", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count >= 1) { TextBox39.Text = dt.Rows[0][1].ToString(); //Date Setted // ----------- Employee One ----------------- // TextBox8.Text = dt.Rows[0][7].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd1 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox8.Text.Trim() + "'", con); SqlDataAdapter da1 = new SqlDataAdapter(cmd1); DataTable dt1 = new DataTable(); da1.Fill(dt1); if (dt1.Rows.Count >= 1) { TextBox9.Text = dt1.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee One Is Removed From The Project !');</script>"); } TextBox40.Text = dt.Rows[0][12].ToString(); //attendance TextBox1.Text = dt.Rows[0][10].ToString(); //worked no of hrs TextBox3.Text = dt.Rows[0][9].ToString(); //pay for hr TextBox4.Text = dt.Rows[0][11].ToString(); //tot pay TextBox5.Text = dt.Rows[0][13].ToString(); // pd or not //Calculation Part int worked_hr1, payHr1, tot_pay1; worked_hr1 = Convert.ToInt32(dt.Rows[0][9].ToString().Trim()); payHr1 = Convert.ToInt32(dt.Rows[0][10].ToString().Trim()); tot_pay1 = worked_hr1 * payHr1; TextBox4.Text = tot_pay1.ToString(); // ----------- Employee Two ----------------- // TextBox2.Text = dt.Rows[0][14].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd2 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox2.Text.Trim() + "'", con); SqlDataAdapter da2 = new SqlDataAdapter(cmd2); DataTable dt2 = new DataTable(); da2.Fill(dt2); if (dt2.Rows.Count >= 1) { TextBox6.Text = dt2.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee two Is Removed From The Project !');</script>"); } TextBox7.Text = dt.Rows[0][19].ToString(); //attendance TextBox10.Text = dt.Rows[0][17].ToString(); //worked no of hrs TextBox11.Text = dt.Rows[0][16].ToString(); //pay for hr TextBox12.Text = dt.Rows[0][11].ToString(); //tot pay TextBox13.Text = dt.Rows[0][20].ToString(); // pd or not //Calculation Part int worked_hr2, payHr2, tot_pay2; worked_hr2 = Convert.ToInt32(dt.Rows[0][17].ToString().Trim()); payHr2 = Convert.ToInt32(dt.Rows[0][16].ToString().Trim()); tot_pay2 = worked_hr2 * payHr2; TextBox12.Text = tot_pay2.ToString(); // ----------- Employee three ----------------- // TextBox14.Text = dt.Rows[0][21].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd3 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox14.Text.Trim() + "'", con); SqlDataAdapter da3 = new SqlDataAdapter(cmd3); DataTable dt3 = new DataTable(); da3.Fill(dt3); if (dt3.Rows.Count >= 1) { TextBox15.Text = dt3.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee Three Is Removed From The Project !');</script>"); } TextBox16.Text = dt.Rows[0][26].ToString(); //attendance TextBox17.Text = dt.Rows[0][24].ToString(); //worked no of hrs TextBox18.Text = dt.Rows[0][23].ToString(); //pay for hr TextBox19.Text = dt.Rows[0][25].ToString(); //tot pay TextBox20.Text = dt.Rows[0][27].ToString(); // pd or not //Calculation Part int worked_hr3, payHr3, tot_pay3; worked_hr3 = Convert.ToInt32(dt.Rows[0][24].ToString().Trim()); payHr3 = Convert.ToInt32(dt.Rows[0][23].ToString().Trim()); tot_pay3 = worked_hr3 * payHr3; TextBox19.Text = tot_pay3.ToString(); // ----------- Employee Four ----------------- // TextBox21.Text = dt.Rows[0][28].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd4 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox21.Text.Trim() + "'", con); SqlDataAdapter da4 = new SqlDataAdapter(cmd4); DataTable dt4 = new DataTable(); da4.Fill(dt4); if (dt4.Rows.Count >= 1) { TextBox22.Text = dt4.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee four Is Removed From The Project !');</script>"); } TextBox23.Text = dt.Rows[0][33].ToString(); //attendance TextBox24.Text = dt.Rows[0][31].ToString(); //worked no of hrs TextBox25.Text = dt.Rows[0][30].ToString(); //pay for hr TextBox26.Text = dt.Rows[0][32].ToString(); //tot pay TextBox27.Text = dt.Rows[0][34].ToString(); // pd or not //Calculation Part int worked_hr4, payHr4, tot_pay4; worked_hr4 = Convert.ToInt32(dt.Rows[0][31].ToString().Trim()); payHr4 = Convert.ToInt32(dt.Rows[0][30].ToString().Trim()); tot_pay4 = worked_hr4 * payHr4; TextBox26.Text = tot_pay4.ToString(); // ----------- Employee Five ----------------- // TextBox28.Text = dt.Rows[0][35].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd5 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox28.Text.Trim() + "'", con); SqlDataAdapter da5 = new SqlDataAdapter(cmd5); DataTable dt5 = new DataTable(); da5.Fill(dt5); if (dt5.Rows.Count >= 1) { TextBox29.Text = dt5.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee five Is Removed From The Project !');</script>"); } TextBox30.Text = dt.Rows[0][40].ToString(); //attendance TextBox31.Text = dt.Rows[0][38].ToString(); //worked no of hrs TextBox32.Text = dt.Rows[0][37].ToString(); //pay for hr TextBox33.Text = dt.Rows[0][39].ToString(); //tot pay TextBox34.Text = dt.Rows[0][41].ToString(); // pd or not //Calculation Part int worked_hr5, payHr5, tot_pay5; worked_hr5 = Convert.ToInt32(dt.Rows[0][38].ToString().Trim()); payHr5 = Convert.ToInt32(dt.Rows[0][37].ToString().Trim()); tot_pay5 = worked_hr5 * payHr5; TextBox33.Text = tot_pay5.ToString(); // ----------- Employee Six ----------------- // TextBox35.Text = dt.Rows[0][42].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd6 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox35.Text.Trim() + "'", con); SqlDataAdapter da6 = new SqlDataAdapter(cmd6); DataTable dt6 = new DataTable(); da6.Fill(dt6); if (dt6.Rows.Count >= 1) { TextBox36.Text = dt6.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee six Is Removed From The Project !');</script>"); } TextBox37.Text = dt.Rows[0][47].ToString(); //attendance TextBox41.Text = dt.Rows[0][45].ToString(); //worked no of hrs TextBox42.Text = dt.Rows[0][44].ToString(); //pay for hr TextBox43.Text = dt.Rows[0][46].ToString(); //tot pay TextBox44.Text = dt.Rows[0][48].ToString(); // pd or not //Calculation Part int worked_hr6, payHr6, tot_pay6; worked_hr6 = Convert.ToInt32(dt.Rows[0][38].ToString().Trim()); payHr6 = Convert.ToInt32(dt.Rows[0][37].ToString().Trim()); tot_pay6 = worked_hr6 * payHr6; TextBox43.Text = tot_pay6.ToString(); // ----------- Employee Seventh ----------------- // TextBox45.Text = dt.Rows[0][49].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd7 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox45.Text.Trim() + "'", con); SqlDataAdapter da7 = new SqlDataAdapter(cmd7); DataTable dt7 = new DataTable(); da7.Fill(dt7); if (dt7.Rows.Count >= 1) { TextBox46.Text = dt7.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee seven Is Removed From The Project !');</script>"); } TextBox47.Text = dt.Rows[0][54].ToString(); //attendance TextBox48.Text = dt.Rows[0][52].ToString(); //worked no of hrs TextBox49.Text = dt.Rows[0][51].ToString(); //pay for hr TextBox50.Text = dt.Rows[0][53].ToString(); //tot pay TextBox51.Text = dt.Rows[0][55].ToString(); // pd or not //Calculation Part int worked_hr7, payHr7, tot_pay7; worked_hr7 = Convert.ToInt32(dt.Rows[0][52].ToString().Trim()); payHr7 = Convert.ToInt32(dt.Rows[0][51].ToString().Trim()); tot_pay7 = worked_hr7 * payHr7; TextBox50.Text = tot_pay7.ToString(); // ----------- Employee Eighth ----------------- // TextBox52.Text = dt.Rows[0][56].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd8 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox52.Text.Trim() + "'", con); SqlDataAdapter da8 = new SqlDataAdapter(cmd8); DataTable dt8 = new DataTable(); da8.Fill(dt8); if (dt8.Rows.Count >= 1) { TextBox53.Text = dt8.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee eight Is Removed From The Project !');</script>"); } TextBox54.Text = dt.Rows[0][61].ToString(); //attendance TextBox55.Text = dt.Rows[0][59].ToString(); //worked no of hrs TextBox56.Text = dt.Rows[0][58].ToString(); //pay for hr TextBox57.Text = dt.Rows[0][60].ToString(); //tot pay TextBox58.Text = dt.Rows[0][62].ToString(); // pd or not //Calculation Part int worked_hr8, payHr8, tot_pay8; worked_hr8 = Convert.ToInt32(dt.Rows[0][59].ToString().Trim()); payHr8 = Convert.ToInt32(dt.Rows[0][58].ToString().Trim()); tot_pay8 = worked_hr8 * payHr8; TextBox57.Text = tot_pay8.ToString(); // ----------- Employee Nine ----------------- // TextBox59.Text = dt.Rows[0][63].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd9 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox59.Text.Trim() + "'", con); SqlDataAdapter da9 = new SqlDataAdapter(cmd9); DataTable dt9 = new DataTable(); da9.Fill(dt9); if (dt9.Rows.Count >= 1) { TextBox60.Text = dt9.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee nine Is Removed From The Project !');</script>"); } TextBox61.Text = dt.Rows[0][68].ToString(); //attendance TextBox62.Text = dt.Rows[0][66].ToString(); //worked no of hrs TextBox63.Text = dt.Rows[0][65].ToString(); //pay for hr TextBox64.Text = dt.Rows[0][67].ToString(); //tot pay TextBox65.Text = dt.Rows[0][69].ToString(); // pd or not //Calculation Part int worked_hr9, payHr9, tot_pay9; worked_hr9 = Convert.ToInt32(dt.Rows[0][66].ToString().Trim()); payHr9 = Convert.ToInt32(dt.Rows[0][65].ToString().Trim()); tot_pay9 = worked_hr9 * payHr9; TextBox64.Text = tot_pay9.ToString(); // ----------- Employee Ten ----------------- // TextBox66.Text = dt.Rows[0][70].ToString(); //npid // Correct this by calling emp table latter SqlCommand cmd10 = new SqlCommand("select * from Non_Permant_Employee_tbl WHERE NPEID='" + TextBox66.Text.Trim() + "'", con); SqlDataAdapter da10 = new SqlDataAdapter(cmd10); DataTable dt10 = new DataTable(); da10.Fill(dt10); if (dt10.Rows.Count >= 1) { TextBox67.Text = dt10.Rows[0][1].ToString(); //name setting } else { Response.Write("<script>alert('Employee ten Is Removed From The Project !');</script>"); } TextBox68.Text = dt.Rows[0][75].ToString(); //attendance TextBox69.Text = dt.Rows[0][73].ToString(); //worked no of hrs TextBox70.Text = dt.Rows[0][72].ToString(); //pay for hr TextBox71.Text = dt.Rows[0][74].ToString(); //tot pay TextBox72.Text = dt.Rows[0][76].ToString(); // pd or not //Calculation Part int worked_hr10,payHr10,tot_pay10; worked_hr10 = Convert.ToInt32(dt.Rows[0][73].ToString().Trim()); payHr10 = Convert.ToInt32(dt.Rows[0][72].ToString().Trim()); tot_pay10 = worked_hr10*payHr10; TextBox71.Text = tot_pay10.ToString(); } else { Response.Write("<script>alert('Sorry This Duty Sheet Doesn't exist at ICC Data Bases');</script>"); } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } // User Defined Function bool checkIfSheetExists() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("SELECT * from Duty_Sheet_tbl where Duty_Sheet_No='" + TextBox38.Text.Trim() + "';", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count >= 1) { return true; } else { return false; } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); return false; } } //Check Over protected void LinkButton1_Click(object sender, EventArgs e) { TextBox5.Text = "Paid"; // pd or not } protected void LinkButton3_Click(object sender, EventArgs e) { TextBox5.Text = ""; } protected void LinkButton2_Click(object sender, EventArgs e) { TextBox13.Text = "Paid"; // pd or not } protected void LinkButton4_Click(object sender, EventArgs e) { TextBox13.Text = ""; // pd or not } protected void LinkButton5_Click(object sender, EventArgs e) { TextBox20.Text = "Paid"; // pd or not } protected void LinkButton6_Click(object sender, EventArgs e) { TextBox20.Text = ""; // pd or not } protected void LinkButton7_Click(object sender, EventArgs e) { TextBox27.Text = "Paid"; // pd or not } protected void LinkButton8_Click(object sender, EventArgs e) { TextBox27.Text = ""; // pd or not } protected void LinkButton9_Click(object sender, EventArgs e) { TextBox34.Text = "Paid"; // pd or not } protected void LinkButton10_Click(object sender, EventArgs e) { TextBox34.Text = ""; // pd or not } protected void LinkButton11_Click(object sender, EventArgs e) { TextBox44.Text = "Paid"; // pd or not } protected void LinkButton12_Click(object sender, EventArgs e) { TextBox44.Text = ""; // pd or not } protected void LinkButton13_Click(object sender, EventArgs e) { TextBox51.Text = "Paid"; // pd or not } protected void LinkButton14_Click(object sender, EventArgs e) { TextBox51.Text = ""; // pd or not } protected void LinkButton15_Click(object sender, EventArgs e) { TextBox58.Text = "Paid"; // pd or not } protected void LinkButton16_Click(object sender, EventArgs e) { TextBox58.Text = ""; // pd or not } protected void LinkButton17_Click(object sender, EventArgs e) { TextBox65.Text = "Paid"; // pd or not } protected void LinkButton18_Click(object sender, EventArgs e) { TextBox65.Text = ""; // pd or not } protected void LinkButton19_Click(object sender, EventArgs e) { TextBox72.Text = "Paid"; // pd or not } protected void LinkButton20_Click(object sender, EventArgs e) { TextBox72.Text = ""; // pd or not } //Mark Payments (submit the updation) protected void Button4_Click(object sender, EventArgs e) { if (checkIfSheetExists()) { MarkPayments(); } else { Response.Write("<script>alert('Duty Sheet does not exist at the current Duty Sheet List');</script>"); } } // User Defined Function void MarkPayments() { try { SqlConnection con = new SqlConnection(strcon); if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("UPDATE Duty_Sheet_tbl SET Emp_01_Toal_Payment=@Emp_01_Toal_Payment,Emp_01_Salary_Pd=@Emp_01_Salary_Pd,Emp_02_Toal_Payment=@Emp_02_Toal_Payment,Emp_02_Salary_Pd=@Emp_02_Salary_Pd,Emp_03_Toal_Payment=@Emp_03_Toal_Payment,Emp_03_Salary_Pd=@Emp_03_Salary_Pd,Emp_04_Toal_Payment=@Emp_04_Toal_Payment,Emp_04_Salary_Pd=@Emp_04_Salary_Pd,Emp_05_Toal_Payment=@Emp_05_Toal_Payment,Emp_05_Salary_Pd=@Emp_05_Salary_Pd,Emp_07_Toal_Payment=@Emp_07_Toal_Payment,Emp_07_Salary_Pd=@Emp_07_Salary_Pd,Emp_08_Toal_Payment=@Emp_08_Toal_Payment,Emp_08_Salary_Pd=@Emp_08_Salary_Pd,Emp_09_Toal_Payment=@Emp_09_Toal_Payment,Emp_09_Salary_Pd=@Emp_09_Salary_Pd,Emp_10_Toal_Payment=@Emp_10_Toal_Payment,Emp_10_Salary_Pd=@Emp_10_Salary_Pd WHERE Duty_Sheet_No='" + TextBox38.Text.Trim() + "'", con); cmd.Parameters.AddWithValue("@Emp_01_Toal_Payment", TextBox4.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_02_Toal_Payment", TextBox12.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_03_Toal_Payment", TextBox19.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_04_Toal_Payment", TextBox26.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_05_Toal_Payment", TextBox33.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_06_Toal_Payment", TextBox43.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_07_Toal_Payment", TextBox50.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_08_Toal_Payment", TextBox57.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_09_Toal_Payment", TextBox64.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_10_Toal_Payment", TextBox71.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_01_Salary_Pd", TextBox5.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_02_Salary_Pd", TextBox13.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_03_Salary_Pd", TextBox20.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_04_Salary_Pd", TextBox27.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_05_Salary_Pd", TextBox34.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_06_Salary_Pd", TextBox44.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_07_Salary_Pd", TextBox51.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_08_Salary_Pd", TextBox58.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_09_Salary_Pd", TextBox65.Text.Trim()); cmd.Parameters.AddWithValue("@Emp_10_Salary_Pd", TextBox72.Text.Trim()); cmd.ExecuteNonQuery(); con.Close(); Response.Write("<script>alert('Given Payments Recorded Successfully');</script>"); clearForm(); } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } //Attendance Marking Over // User Defined Function void clearForm() { TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; TextBox5.Text = ""; TextBox6.Text = ""; TextBox7.Text = ""; TextBox8.Text = ""; TextBox9.Text = ""; TextBox10.Text = ""; TextBox11.Text = ""; TextBox12.Text = ""; TextBox13.Text = ""; TextBox14.Text = ""; TextBox15.Text = ""; TextBox16.Text = ""; TextBox17.Text = ""; TextBox18.Text = ""; TextBox19.Text = ""; TextBox20.Text = ""; TextBox21.Text = ""; TextBox22.Text = ""; TextBox23.Text = ""; TextBox24.Text = ""; TextBox25.Text = ""; TextBox26.Text = ""; TextBox27.Text = ""; TextBox28.Text = ""; TextBox29.Text = ""; TextBox30.Text = ""; TextBox31.Text = ""; TextBox32.Text = ""; TextBox33.Text = ""; TextBox34.Text = ""; TextBox35.Text = ""; TextBox36.Text = ""; TextBox37.Text = ""; TextBox38.Text = ""; TextBox39.Text = ""; TextBox40.Text = ""; TextBox41.Text = ""; TextBox42.Text = ""; TextBox43.Text = ""; TextBox44.Text = ""; TextBox45.Text = ""; TextBox46.Text = ""; TextBox47.Text = ""; TextBox48.Text = ""; TextBox49.Text = ""; TextBox50.Text = ""; TextBox51.Text = ""; TextBox52.Text = ""; TextBox53.Text = ""; TextBox54.Text = ""; TextBox55.Text = ""; TextBox56.Text = ""; TextBox57.Text = ""; TextBox58.Text = ""; TextBox59.Text = ""; TextBox60.Text = ""; TextBox61.Text = ""; TextBox62.Text = ""; TextBox63.Text = ""; TextBox64.Text = ""; TextBox65.Text = ""; TextBox66.Text = ""; TextBox67.Text = ""; TextBox68.Text = ""; TextBox69.Text = ""; TextBox70.Text = ""; TextBox71.Text = ""; TextBox72.Text = ""; } protected void Button6_Click(object sender, EventArgs e) { clearForm(); } // User Defined Function void clearMarking() { TextBox5.Text = ""; TextBox13.Text = ""; TextBox20.Text = ""; TextBox27.Text = ""; TextBox34.Text = ""; TextBox44.Text = ""; TextBox51.Text = ""; TextBox58.Text = ""; TextBox68.Text = ""; TextBox72.Text = ""; } protected void Button1_Click(object sender, EventArgs e) { clearMarking(); } } }
using System; namespace CC.Mobile.Routing { public interface IScreenlessEnabled{ event EventHandler<CompletionEventArgs> OnCompleted; void Start(); void Stop(); } }
/*************************************** * * This class is use to isolate Time to each object * ***************************************/ using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects { [System.Serializable] public abstract class IsolatedTime : MonoBehaviour, IIsolatedTime, ITimeSpeed { [SerializeField] [MinValue(0f)] protected float m_timeScale = 1f; [SerializeField] [MinValue(0f)] protected float m_slowFactor; [SerializeField] [MinValue(0f)] protected float m_fastFactor; private float m_totalTimeScale; public IsolatedTime() { m_timeScale = 1f; m_slowFactor = 0f; m_fastFactor = 0f; } public float totalTimeScale => m_totalTimeScale; public float timeScale => m_timeScale; public void Faster(float percentValue) { m_fastFactor = percentValue; UpdateTimeScale(); UpdateComponents(); } public void SetTimeScale(float timeScale) { m_timeScale = timeScale; UpdateTimeScale(); UpdateComponents(); } public void Slower(float percentValue) { m_slowFactor = percentValue; UpdateTimeScale(); UpdateComponents(); } protected void UpdateTimeScale() => m_totalTimeScale = m_timeScale * (1f + (m_fastFactor - m_slowFactor)); protected abstract void UpdateComponents(); private void OnEnable() { World.Register(this); } private void OnDisable() { World.Unregister(this); } } }
using BO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TpRace.Controllers { public class RaceController : Controller { private static List<Race> races= new List<Race>(); // GET: Race public ActionResult Index() { if (races.Count == 0) { races.Add(new Race { Id = 1, Title = "GTA", DateStart = DateTime.Now, DateEnd = DateTime.Now.AddDays(5), Description = "first race", Organizer = null, Competitors = null }); } return View(races); } // GET: Race/Details/5 public ActionResult Details(int id) { return View(); } // GET: Race/Create public ActionResult Create() { return View(); } // POST: Race/Create [HttpPost] public ActionResult Create(FormCollection collection) { try { // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Race/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: Race/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } // GET: Race/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Race/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace WcfAukcija { public class ListaKlijenata { public List<Klijent> klijenti; private static ListaKlijenata instance = null; private static object locker = true; public static ListaKlijenata Instance { get { lock (locker) { if (instance == null) instance = new ListaKlijenata(); } return instance; } } protected ListaKlijenata() { klijenti = new List<Klijent>(){ new Klijent() { Id = "1", Ime = "Joca", Prezime = "Jovanovic" }, new Klijent() { Id = "2", Ime = "Mitar", Prezime = "Mitrovic" }, new Klijent() { Id = "3", Ime = "Petar", Prezime = "Petrovic" } }; } } }
using System; namespace BinarySearchTreeVisualizer { class Program { static void Main(string[] args) { int[] testData = new int[10]; testData[0] = 5; testData[1] = 9; testData[2] = 4; testData[3] = 1; testData[4] = 2; testData[5] = 8; testData[6] = 6; testData[7] = 7; testData[8] = 10; testData[9] = 3; /* Tree tree = new Tree(testData); Visual visual = new Visual(tree); tree.AddNode(tree.Root, 15); tree.AddNode(tree.Root, 0); tree.AddNode(tree.Root, 11); tree.InOrder(tree.Root); for (int i = 0; i < tree.Output.Count; i++) { Console.WriteLine(tree.Output[i]); } Console.WriteLine(tree.Search(11, tree.Root)); tree.AddNode(tree.Root, 23); tree.Remove(tree.Search(8, tree.Root)); tree.InOrder(tree.Root); for (int i = 0; i < tree.Output.Count; i++) { Console.WriteLine(tree.Output[i]); }*/ RedBlackTree rbTree = new RedBlackTree(testData); rbTree.AddNode(rbTree.Root, 20); rbTree.AddNode(rbTree.Root, 21); rbTree.AddNode(rbTree.Root, 22); rbTree.AddNode(rbTree.Root, 23); rbTree.AddNode(rbTree.Root, 15); rbTree.AddNode(rbTree.Root, 0); rbTree.InOrder(rbTree.Root); for (int i = 0; i < rbTree.Output.Count; i++) { Console.WriteLine(rbTree.Output[i]); } //visual.DrawTree(); } } }
using System; namespace SOLIDPrinciples.CouplingProblem.Example02.Good { public class DespachadorDeNotasFiscais { private NFDao dao; private CalculadorDeImposto impostos; private EntregadoresDeNFs entregadoresDeNFs; public DespachadorDeNotasFiscais( NFDao dao, CalculadorDeImposto impostos, EntregadoresDeNFs entregadoresDeNFs) => (this.dao, this.impostos, this.entregadoresDeNFs) = (dao, impostos, entregadoresDeNFs); public void Processar(NotaFiscal nf) { double imposto = impostos.Aplicar(nf); nf.SetImposto(imposto); entregadoresDeNFs.DeterminarFormaDeEnvio(nf); dao.Persiste(nf); } } }
using System; using System.Collections.Generic; using DFC.ServiceTaxonomy.GraphSync.Models; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts { public interface IDescribeRelationshipsContext : IGraphSyncContext { IServiceProvider ServiceProvider { get; } List<ContentItemRelationship> AvailableRelationships { get; } string SourceNodeId { get; } IEnumerable<string> SourceNodeLabels { get; } int CurrentDepth { get; } int MaxDepthFromHere { get; } string SourceNodeIdPropertyName { get; } } }
namespace Sentry.Android.AssemblyReader; /// <summary> /// Writes a log message for debugging. /// </summary> /// <param name="message">The message string to write.</param> /// <param name="args">Arguments for the formatted message string.</param> public delegate void DebugLogger(string message, params object?[] args);
namespace AGCompressedAir.Domain.Domains.Base { public interface IEntity<out T> : IDomain { new T Id { get; } } }
using System.ComponentModel; using System.Windows.Forms; namespace Com.Colin.Win.Customized { public class MyControl:Control { private License license = null; public MyControl() { license = LicenseManager.Validate(typeof(MyControl), this); } protected override void Dispose(bool disposing) { if (Disposing) { if (license != null) { license.Dispose(); license = null; } } base.Dispose(Disposing); } ~MyControl() { Dispose(); } } }
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using Pe.Stracon.Politicas.Infraestructura.CommandModel.General; using Pe.Stracon.Politicas.Infraestructura.Core.Context; using Pe.Stracon.Politicas.Infraestructura.QueryModel.General; using System; namespace Pe.Stracon.Politicas.Aplicacion.Adapter.General { /// <summary> /// Adaptador de Parámetro /// </summary> /// <remarks> /// Creación: GMD 20150327 <br /> /// Modificación: <br /> /// </remarks> public sealed class ParametroAdapter { /// <summary> /// Obtiene un response de Parámetro apartir de su logic /// </summary> /// <param name="parametroLogic">Entidad de Parámetro</param> /// <returns>Response de Parámetro</returns> public static ParametroResponse ObtenerParametroResponse(ParametroLogic parametroLogic) { var parametro = new ParametroResponse(); parametro.CodigoIdentificador = parametroLogic.CodigoIdentificador; parametro.TipoParametro = parametroLogic.TipoParametro; switch(parametro.TipoParametro) { case DatosConstantes.TipoParametro.Comun: parametro.DescripcionTipoParametro = "Común"; break; case DatosConstantes.TipoParametro.Sistema: parametro.DescripcionTipoParametro = "Sistema"; break; case DatosConstantes.TipoParametro.Funcional: parametro.DescripcionTipoParametro = "Funcional"; break; default: parametro.DescripcionTipoParametro = string.Empty; break; } parametro.CodigoParametro = parametroLogic.CodigoParametro; parametro.CodigoEmpresa = parametroLogic.CodigoEmpresa.ToString(); parametro.CodigoEmpresaIdentificador = parametroLogic.CodigoEmpresaIdentificador; parametro.NombreEmpresa = parametroLogic.NombreEmpresa; parametro.CodigoSistema = parametroLogic.CodigoSistema.HasValue ? parametroLogic.CodigoSistema.ToString() : null; parametro.CodigoSistemaIdentificador = parametroLogic.CodigoSistemaIdentificador; parametro.NombreSistema = parametroLogic.NombreSistema; parametro.Descripcion = parametroLogic.Descripcion; parametro.EstadoRegistro = parametroLogic.EstadoRegistro; parametro.IndicadorEmpresa = parametroLogic.IndicadorEmpresa; parametro.DescripcionIndicadorEmpresa = parametroLogic.IndicadorEmpresa ? "Si" : "No"; parametro.IndicadorPermiteAgregar = parametroLogic.IndicadorPermiteAgregar; parametro.IndicadorPermiteEliminar = parametroLogic.IndicadorPermiteEliminar; parametro.IndicadorPermiteModificar = parametroLogic.IndicadorPermiteModificar; parametro.Nombre = parametroLogic.Nombre; return parametro; } /// <summary> /// Obtiene un entity de Parámetro apartir de su request /// </summary> /// <param name="parametroRequest">Request de Parámetro</param> /// <returns>Entity del Parámetro</returns> public static ParametroEntity ObtenerParametroEntity(ParametroRequest parametroRequest) { var entity = new ParametroEntity(); entity.CodigoParametro = Convert.ToInt32(parametroRequest.CodigoParametro); entity.CodigoEmpresa = new Guid(parametroRequest.CodigoEmpresa); entity.CodigoSistema = parametroRequest.CodigoSistema != null ? new Guid(parametroRequest.CodigoSistema) : (Guid?) null; entity.CodigoIdentificador = parametroRequest.CodigoIdentificador; entity.Nombre = parametroRequest.Nombre; entity.Descripcion = parametroRequest.Descripcion; entity.IndicadorPermiteAgregar = Convert.ToBoolean(parametroRequest.IndicadorPermiteAgregar); entity.IndicadorPermiteModificar = Convert.ToBoolean(parametroRequest.IndicadorPermiteModificar); entity.IndicadorPermiteEliminar = Convert.ToBoolean(parametroRequest.IndicadorPermiteEliminar); entity.TipoParametro = parametroRequest.TipoParametro; entity.IndicadorEmpresa = parametroRequest.IndicadorEmpresa; return entity; } } }
using System.Data; public class MovementDAL { public static DataTable GetAllMovement() { var db = new SQLDBAccess("CIPConnectionString"); db.AddParameter("@Action", "All"); return db.FillDataTable("usp_Movement_Select"); } public static DataTable GetMovementFedIDsByUserID(int userId) { var db = new SQLDBAccess("CIPConnectionString"); db.AddParameter("@Action", "GetMovementFedIDsByUserID"); db.AddParameter("@UserID", userId); return db.FillDataTable("usp_Movement_Select"); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace Athenaeum.Models { public class NewsArticle { public int NewsArticleId { get; protected set; } public string Title { get; set; } public string AuthorId { get; set; } public DateTime PostedDate { get; set; } public string Body { get; set; } public int NewsCategoryId { get; set; } public string ImageUrl { get; set; } public int NumberOfComments { get; set; } [ForeignKey("NewsCategoryId")] public virtual NewsCategory Category { get; set; } [ForeignKey("AuthorId")] public virtual ApplicationUser Author { get; set; } } }
using DemoF.Core.Repositories; using DemoF.Persistence.Repositories; using Microsoft.EntityFrameworkCore; using System; namespace DemoF.Persistence { public class UnitOfDemof : UnitOfWork<DemofContext>, IUnitOfDemof { private readonly DemofContext context; public IUserRepositoryDapper Users { get; private set; } //public IUserRepository Users { get; private set; } public UnitOfDemof(DemofContext context, IServiceProvider serviceProvider) : base (context) { this.context = context; Users = (IUserRepositoryDapper)serviceProvider.GetService(typeof(IUserRepositoryDapper)); //Users = new UserRepository(this.context); } public int Complete() { return context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Description résumée de ProduitRepository /// </summary> public class ProduitRepository { protected GammeRepository gammeRepository; protected ModeleGammeRepository modeleGammeRepository; public ProduitRepository() { gammeRepository = new GammeRepository(); modeleGammeRepository = new ModeleGammeRepository(); } public void Add(Produit produit, int devisId) { PRODUIT entity = new PRODUIT(); entity.PRODUIT_NOM = produit.Nom; entity.PRODUIT_DESCRIPTION = produit.Description; entity.DEVIS_ID = devisId; entity.GAMME_ID = produit.Gamme.Id; if (produit.ModeleDeGamme.Id != 0) entity.MODELE_DE_GAMME_ID = produit.ModeleDeGamme.Id; else { entity.MODELE_DE_GAMME_ID = modeleGammeRepository.Add(produit.ModeleDeGamme); } using (var db = new maderaEntities()) { db.PRODUIT.Add(entity); db.SaveChanges(); } } public List<Produit> GetByDevis(Devis devis) { List<Produit> dtos = new List<Produit>(); using (var db = new maderaEntities()) { var query = from a in db.PRODUIT where a.DEVIS_ID.Equals(devis.Id) select a; foreach (var item in query) { Produit dto = new Produit(); dto.Id = item.PRODUIT_ID; dto.Nom = item.PRODUIT_NOM; dto.Description = item.PRODUIT_DESCRIPTION; dto.Gamme = gammeRepository.GetOne(item.GAMME_ID); if (item.MODELE_DE_GAMME_ID != null) dto.ModeleDeGamme = modeleGammeRepository.GetOne((int) item.MODELE_DE_GAMME_ID); dtos.Add(dto); } } return dtos; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace calc_pro { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void button15_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "7"; } private void label1_Click_1(object sender, EventArgs e) { } private void Clear_Click(object sender, EventArgs e) { this.main_num_label1.Text = ""; } private void button3_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "8"; } private void button1_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "0"; } private void button18_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "1"; } private void button17_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "2"; } private void button11_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "3"; } private void button16_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "4"; } private void button21_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "5"; } private void button14_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "6"; } private void button2_Click_1(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "9"; } private void Multiply_Click(object sender, EventArgs e) { this.operator_label.Text = "*"; /* if (this.main_num_label1.Text == "0") { }*/ this.first_num_label.Text = this.main_num_label1.Text; this.main_num_label1.Text = ""; } private void Addition_Click(object sender, EventArgs e) { this.operator_label.Text = "+"; //If operator label is + show the operator in the label// // if (this.main_num_label1.Text == "0") // { this.first_num_label.Text = this.main_num_label1.Text; // } //If main num label is equal to nothing then do nothing else// this.main_num_label1.Text = ""; } private void Subtraction_Click(object sender, EventArgs e) { this.operator_label.Text = "-"; //if (this.main_num_label1.Text == "0") // { this.first_num_label.Text = this.main_num_label1.Text; // } this.main_num_label1.Text = ""; } private void Division_Click(object sender, EventArgs e) { this.operator_label.Text = "%"; //if (this.main_num_label1.Text == "0") //{ this.first_num_label.Text = this.main_num_label1.Text; // } this.main_num_label1.Text = ""; } private void operator_label_Click(object sender, EventArgs e) { } private void Equal_Click(object sender, EventArgs e) { double fn; double sn; double r; //---------------------------- double.TryParse(this.first_num_label.Text, out fn); double.TryParse(this.main_num_label1.Text, out sn); r = 0; //---------------------------- if (this.operator_label.Text == "+") { r = fn + sn; } //-------------------------------- if (this.operator_label.Text == "-") { r = fn - sn; } //-------------------------------- if (this.operator_label.Text == "*") { r = fn * sn; } //-------------------------------- if (this.operator_label.Text == "%") { r = fn / sn; } //-------------------------------- this.main_num_label1.Text = r.ToString(); this.operator_label.Text = ""; this.first_num_label.ResetText(); } private void first_num_label_Click(object sender, EventArgs e) { } private void Decimal_Click(object sender, EventArgs e) { this.main_num_label1.Text = this.main_num_label1.Text + "."; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; namespace ExampleBot.Modules { public class ExampleModuleBase<T> : ModuleBase<T> where T : class, ICommandContext { public IDependencyMap DependencyMap { get; set; } public DiscordSocketClient Client { get; set; } public CommandService CommandService { get; set; } // You can override ReplyAsync, do some stuff. protected override Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, Embed embed = null, RequestOptions options = null) { // Try to replace @everyone or @here if present // \x200B is a no-width blank space // By inserting it we basically sabotage the mentions return base.ReplyAsync( message.Replace(Context.Guild.EveryoneRole.Mention, "@every\x200Bone").Replace("@here", "@he\x200Bre"), isTTS, embed, options); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using XH.Infrastructure.Domain.Models; namespace DSM.ImportData.Resolvers { public class LocalFileEntityEnumerator<T> : IEntityDataSourceEnumerator<T>, IDisposable where T : EntityBase { private readonly string _filePath; private readonly IEntityResolver<T> _entityResolver; private StreamReader _reader; private T currentEntity; private string currentLine; public LocalFileEntityEnumerator(IEntityResolver<T> entityResolver, string filePath) { _filePath = $"{filePath}\\{typeof(T).Name}.txt"; _entityResolver = entityResolver; _reader = File.OpenText(_filePath); } public T Current { get { return currentEntity; } } object IEnumerator.Current { get { return currentEntity; } } public void Dispose() { try { _reader.Dispose(); } catch { } } public bool MoveNext() { currentEntity = null; currentLine = _reader.ReadLine(); if (currentLine != null) { currentEntity = _entityResolver.Resovle(currentLine); } return currentLine != null; } public void Reset() { _reader.BaseStream.Seek(0, SeekOrigin.Begin); } } }
using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.FSM.Editor { /// <summary> /// A custom property drawer for FiniteStateMachineReference. Makes it possible to choose between a FSM or a FSM Instancer. /// </summary> [CustomPropertyDrawer(typeof(FiniteStateMachineReference), true)] public class FiniteStateMachineReferenceDrawer : AtomBaseReferenceDrawer { protected class UsageFSM : UsageData { public override int Value { get => FiniteStateMachineReferenceUsage.FSM; } public override string PropertyName { get => "_fsm"; } public override string DisplayName { get => "Use FSM"; } } protected class UsageFSMInstancer : UsageData { public override int Value { get => FiniteStateMachineReferenceUsage.FSM_INSTANCER; } public override string PropertyName { get => "_fsmInstancer"; } public override string DisplayName { get => "Use FSM Instancer"; } } private readonly UsageData[] _usages = new UsageData[2] { new UsageFSM(), new UsageFSMInstancer() }; protected override UsageData[] GetUsages(SerializedProperty prop = null) => _usages; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Application.DTO; namespace EBS.Application { public interface IRoleFacade { void Create(RoleModel model); void Edit(RoleModel model); void Delete(string ids); } }
using System; using System.Collections.Generic; /*Write a program that finds in given array of integers a sequence of given sum S (if present). Example: array S result 4, 3, 1, 4, 2, 5, 8 11 4, 2, 5*/ class Program { static int Sum(List<int> list) { int sum = 0; for (int i = 0; i < list.Count; i++) sum += list[i]; return sum; } static void Main() { Console.WriteLine("Write an array like in the example:"); string s = Console.ReadLine(); string[] arrHelper = s.Split(','); int length = arrHelper.Length + 1; int[] arr = new int[length]; for (int i = 0; i < length - 1; i++) arr[i] = int.Parse(arrHelper[i]); arr[length - 1] = 0; Console.Write("sum = "); int sum = int.Parse(Console.ReadLine()); List<int> result = new List<int>(); result.Add(arr[0]); int counter = 1; while (counter < length) { if (Sum(result) < sum) { result.Add(arr[counter]); counter++; } else if (Sum(result) > sum) result.RemoveAt(0); if (Sum(result) == sum) { for (int i = 0; i < result.Count - 1; i++) Console.Write(result[i] + ", "); Console.WriteLine(result[result.Count - 1]); break; } } } }
using System.Collections.Generic; using System.Xml.Serialization; using Tomelt.ContentManagement.Records; using Tomelt.Data.Conventions; namespace Tomelt.MediaProcessing.Models { public class ImageProfilePartRecord : ContentPartRecord { public ImageProfilePartRecord() { Filters = new List<FilterRecord>(); FileNames = new List<FileNameRecord>(); } public virtual string Name { get; set; } [CascadeAllDeleteOrphan, Aggregate] [XmlArray("FilterRecords")] public virtual IList<FilterRecord> Filters { get; set; } [CascadeAllDeleteOrphan, Aggregate] [XmlArray("FileNameRecords")] public virtual IList<FileNameRecord> FileNames { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace StreamTest { public static class BinaryReaderTest { public class Product { public int Id { get; set; } public string Name { get; set; } public double Price { get; set; } } public static void ReadClassUsingBinaryReader() { string path = @"..\..\..\product.txt"; Product product = new Product() { Id = 1, Name = "CocaCola", Price = 3.5f }; using (var stream = new FileStream(path,FileMode.OpenOrCreate,FileAccess.Write)) { BinaryWriter writer = new BinaryWriter(stream,Encoding.ASCII); writer.Write(product.Id); writer.Write(product.Name); writer.Write(product.Price); } Product product1 = new Product(); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { BinaryReader reader = new BinaryReader(stream); product1.Id = reader.ReadInt32(); product1.Name = reader.ReadString(); product1.Price = reader.ReadDouble(); } Console.WriteLine(product1.Id); Console.WriteLine(product1.Name); Console.WriteLine(product1.Price); } } }
namespace Reacher.Shared.Common { public class ClientProvider : IClientProvider { private readonly string _clientId; public ClientProvider(string clientId) { _clientId = clientId; } public string ClientId() => _clientId.ToLowerInvariant(); } }
using Vintagestory.API.Common; namespace OreCrystals { class RegisterEntities : ModSystem { public override void Start(ICoreAPI api) { base.Start(api); api.RegisterEntity("EntityCrystalLocust", typeof(EntityCrystalLocust)); api.RegisterEntity("EntityCrystalHeart", typeof(EntityCrystalHeart)); api.RegisterEntity("EntityCrystalGrenade", typeof(EntityCrystalGrenade)); } } }
using System.Collections.Generic; namespace libairvidproto.model { public class Folder : AirVidResource { public static readonly int ContentType = (int)EmContentType.Folder; public Folder(AirVidServer server, string name, string id, NodeInfo parent) : base(server, name, id, parent) { } public List<AirVidResource> GetResources(IWebClient webClient) { return Server.GetResources(webClient, Id, this); } } }
using System; using System.Runtime.Serialization; namespace DBAccess.Exceptions { [Serializable] internal class InvalidRepositoryTableException : Exception { public InvalidRepositoryTableException() { } public InvalidRepositoryTableException(string message) : base(message) { } public InvalidRepositoryTableException(string message, Exception innerException) : base(message, innerException) { } protected InvalidRepositoryTableException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RC.Infra { public class RCAlert { public string Message { get; set; } public AlertType Type { get; set; } public string HTMLClass { get; private set; } public string UrlHelp { get; set; } public string UrlName { get; set; } public RCAlert(string message, AlertType type) { this.Message = message; this.Type = type; switch (this.Type) { case AlertType.Warning: this.HTMLClass = ""; break; case AlertType.Error: this.HTMLClass = "alert-danger"; break; case AlertType.Success: this.HTMLClass = "alert-success"; break; case AlertType.Info: this.HTMLClass = "alert-info"; break; } } public RCAlert(string message, AlertType type, string urlHelp, string urlName) { this.Message = message; this.Type = type; this.UrlHelp = urlHelp; this.UrlName = urlName; switch (this.Type) { case AlertType.Warning: this.HTMLClass = ""; break; case AlertType.Error: this.HTMLClass = "alert-error"; break; case AlertType.Success: this.HTMLClass = "alert-success"; break; case AlertType.Info: this.HTMLClass = "alert-info"; break; } } } public enum AlertType { Warning, Error, Success, Info } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.Threading; using StackExchange.Profiling.Storage; using NUnit.Framework; using System.IO; using System.Data.SqlServerCe; using StackExchange.Profiling.Helpers.Dapper; using StackExchange.Profiling.Data; namespace StackExchange.Profiling.Tests.Storage { [TestFixture] public class SqlServerStorageTest : BaseTest { [TestFixtureSetUp] public void TestFixtureSetUp() { var sqlToExecute = SqlServerStorage.TableCreationScript.Replace("nvarchar(max)", "ntext").Split(';').Where(s => !string.IsNullOrWhiteSpace(s)); var connStr = CreateSqlCeDatabase<SqlServerStorageTest>(sqlToExecute: sqlToExecute); MiniProfiler.Settings.Storage = new SqlCeStorage(connStr); _conn = GetOpenSqlCeConnection<SqlServerStorageTest>(); } [TestFixtureTearDown] public void TestFixtureTearDown() { MiniProfiler.Settings.Storage = null; } [Test] public void NoChildTimings() { var mp = GetProfiler(); AssertMiniProfilerExists(mp); AssertTimingsExist(mp, 1); var mp2 = MiniProfiler.Settings.Storage.Load(mp.Id); AssertProfilersAreEqual(mp, mp2); } [Test] public void WithChildTimings() { var mp = GetProfiler(childDepth: 5); AssertMiniProfilerExists(mp); AssertTimingsExist(mp, 6); var mp2 = MiniProfiler.Settings.Storage.Load(mp.Id); AssertProfilersAreEqual(mp, mp2); } [Test] public void WithSqlTimings() { MiniProfiler mp; using (GetRequest()) using (var conn = GetProfiledConnection()) { mp = MiniProfiler.Current; // one sql in the root timing conn.Query("select 1"); using (mp.Step("Child step")) { conn.Query("select 2 where 1 = @one", new { one = 1 }); } } Assert.IsFalse(mp.HasDuplicateSqlTimings); AssertSqlTimingsExist(mp.Root, 1); var t = mp.Root.Children.Single(); AssertSqlTimingsExist(t, 1); AssertSqlParametersExist(t.SqlTimings.Single(), 1); var mp2 = MiniProfiler.Settings.Storage.Load(mp.Id); AssertProfilersAreEqual(mp, mp2); } [Test] public void WithDuplicateSqlTimings() { MiniProfiler mp; using (GetRequest()) using (var conn = GetProfiledConnection()) { mp = MiniProfiler.Current; // one sql in the root timing conn.Query("select 1"); using (mp.Step("Child step")) { conn.Query("select 1"); } } Assert.IsTrue(mp.HasDuplicateSqlTimings); AssertSqlTimingsExist(mp.Root, 1); AssertSqlTimingsExist(mp.Root.Children.Single(), 1); var mp2 = MiniProfiler.Settings.Storage.Load(mp.Id); AssertProfilersAreEqual(mp, mp2); } private SqlCeConnection _conn; private ProfiledDbConnection GetProfiledConnection() { return new ProfiledDbConnection(GetOpenSqlCeConnection<SqlServerStorageTest>(), MiniProfiler.Current); } private void AssertMiniProfilerExists(MiniProfiler mp) { Assert.That(_conn.Query<int>("select count(*) from MiniProfilers where Id = @Id", new { mp.Id }).Single() == 1); } private void AssertTimingsExist(MiniProfiler mp, int count) { Assert.That(_conn.Query<int>("select count(*) from MiniProfilerTimings where MiniProfilerId = @Id", new { mp.Id }).Single() == count); } private void AssertSqlTimingsExist(Timing t, int count) { Assert.That(_conn.Query<int>("select count(*) from MiniProfilerSqlTimings where ParentTimingId = @Id ", new { t.Id }).Single() == count); } private void AssertSqlParametersExist(SqlTiming s, int count) { Assert.That(_conn.Query<int>("select count(*) from MiniProfilerSqlTimingParameters where ParentSqlTimingId = @Id ", new { s.Id }).Single() == count); } } internal class SqlCeStorage : SqlServerStorage { public SqlCeStorage(string connectionString) : base(connectionString) { } protected override System.Data.Common.DbConnection GetConnection() { return new SqlCeConnection(ConnectionString); } /// <summary> /// CE doesn't support multiple result sets in one query. /// </summary> public override bool EnableBatchSelects { get { return false; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using CYJ.DingDing.Dto.Dto.Base; namespace CYJ.DingDing.Dto.Dto { public class ProcessListResponse : DingTalkResponse { /// <summary> /// result /// </summary> public DingOpenResultDomain Result { get; set; } /// <summary> /// DingOpenResultDomain Data Structure. /// </summary> public class DingOpenResultDomain { /// <summary> /// result /// </summary> public PageResultDomain Result { get; set; } } /// <summary> /// FormComponentValueVoDomain Data Structure. /// </summary> public class FormComponentValueVoDomain { /// <summary> /// 表单标签名 /// </summary> public string Name { get; set; } /// <summary> /// 表单标签值 /// </summary> public string Value { get; set; } } /// <summary> /// ProcessInstanceTopVoDomain Data Structure. /// </summary> public class ProcessInstanceTopVoDomain { /// <summary> /// 审批人列表 /// </summary> public List<string> ApproverUseridList { get; set; } /// <summary> /// 流程实例业务编号 /// </summary> public string BusinessId { get; set; } /// <summary> /// 抄送人列表 /// </summary> public List<string> CcUseridList { get; set; } /// <summary> /// 开始时间 /// </summary> public string CreateTime { get; set; } /// <summary> /// 结束时间 /// </summary> public string FinishTime { get; set; } /// <summary> /// 审批表单变量组 /// </summary> public List<FormComponentValueVoDomain> FormComponentValues { get; set; } /// <summary> /// 发起人部门id /// </summary> public string OriginatorDeptId { get; set; } /// <summary> /// 发起人userid /// </summary> public string OriginatorUserid { get; set; } /// <summary> /// 审批实例id /// </summary> public string ProcessInstanceId { get; set; } /// <summary> /// 审批结果,分为agree和refuse /// </summary> public string ProcessInstanceResult { get; set; } /// <summary> /// 审批状态,分为NEW(刚创建)|RUNNING(运行中)|TERMINATED(被终止)|COMPLETED(完成)|CANCELED(取消) /// </summary> public string Status { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } } /// <summary> /// PageResultDomain Data Structure. /// </summary> public class PageResultDomain { /// <summary> /// list /// </summary> public List<ProcessInstanceTopVoDomain> List { get; set; } /// <summary> /// 表示下次查询的游标,当返回结果没有该字段时表示没有更多数据了 /// </summary> public long NextCursor { get; set; } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using Agencia_Datos_Entidades; namespace Agencia_Datos_Repositorio { public class Repositorio<T>:IRepositorio<T>, IDisposable where T: class { private readonly AgenciaContext _db; public Repositorio(AgenciaContext _db) { this._db = _db; } public IQueryable<T> AsQueryable() { return _db.Set<T>().AsQueryable(); } public IEnumerable<T> TraerTodo() { return _db.Set<T>(); } public IEnumerable<T> Buscar(System.Linq.Expressions.Expression<Func<T, bool>> predicado) { return _db.Set<T>().Where(predicado); } public T TraerUno(System.Linq.Expressions.Expression<Func<T, bool>> predicado) { return _db.Set<T>().Where(predicado).FirstOrDefault(); } public T TraerUnoPorId(int id) { return _db.Set<T>().Find(id); } public void Agregar(T modelo) { if (_db.Entry<T>(modelo).State != System.Data.Entity.EntityState.Detached) _db.Entry<T>(modelo).State = System.Data.Entity.EntityState.Added; else _db.Set<T>().Add(modelo); } public void Modificar(T modelo) { if (_db.Entry<T>(modelo).State == System.Data.Entity.EntityState.Detached) _db.Set<T>().Attach(modelo); _db.Entry<T>(modelo).State = System.Data.Entity.EntityState.Modified; } public void Eliminar(T modelo) { if (_db.Entry<T>(modelo).State == System.Data.Entity.EntityState.Detached) _db.Set<T>().Attach(modelo); _db.Entry<T>(modelo).State = System.Data.Entity.EntityState.Deleted; } public void Guardar() { _db.SaveChanges(); } public void Dispose() { return; } public void Commit() { using (var transaction = _db.Database.BeginTransaction()) { transaction.Commit(); } } public void RollBack() { using (var transaction = _db.Database.BeginTransaction()) { transaction.Rollback(); } } } }
using System; using System.Collections.Generic; using System.Text; using TruckPad.Services.Models; namespace TruckPad.Tests { public class DummyDataDBInitializer { public DummyDataDBInitializer() { } public void Seed(TruckPadContext context) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Motorista.AddRange( new Motorista() { Nome="" }, new Motorista() { Nome="" } ); context.Viagem.AddRange( new Viagem() { IdMotorista = 0 }, new Viagem() { IdMotorista = 0 } ); context.SaveChanges(); } } }
using System; namespace Uintra.Features.Subscribe.Models { public class ActivitySubscribeSettingDto { public Guid ActivityId { get; set; } public bool CanSubscribe { get; set; } public string SubscribeNotes { get; set; } } }
using UnityEngine; using System.Collections; public class ToggleOutline : MonoBehaviour { public Shader normalShader = Shader.Find("Diffuse"); public Shader outlinedShader = Shader.Find("Outlined/Silhouetted Diffuse"); public void OriginalShader(Shader original) { normalShader = original; } public void TurnOnOutline(GameObject obj) { obj.gameObject.GetComponent<Renderer> ().material.shader = outlinedShader; } public void TurnOffOutline(GameObject obj) { obj.gameObject.GetComponent<Renderer> ().material.shader = normalShader; } }
// ScoreManagerMono script. This wraps a ScoreManager UI written in gdscript that utilises SilentWolf Leaderboard addon // To use, change the config in score_unit.gd, and instance this node in a scene. // Don't forget to customise the UI elements in this node and in pnl_scoreunit // If you expect the positions / high scores to reach higher numbers, adjust the label min_rect_size.x // Can request to submit a high score - this checks the position of the high score and if it is within the maxScores.. // .. it submits the score (with loading animations that can be customised), and optionally then displays the leaderboard: // StartScoreSaver(highScore:30, maxScores:10); // Can just directly show the leaderboard (up to x max scores): // ShowAndRefreshLeaderboard(maxScores:10); // Or can refresh and show the leaderboard separately: // RefreshLeaderboard(maxScores:10) // ShowLeaderboard() // To wipe the leaderboard: // GetNode("score_manager").CallDeferred("wipe"); // See below for optional arguments // Enable player2 by passing "Player2Name" in the metaData dict as the KEY (the value doesnt matter) // Signals can be connected when this is instanced, for UI transition purposes (e.g. on high_score play victory sound, on score saver finished go to end menu) // NOTE: in html5 as of 3.2.3, this addon FAILS if the game is paused while the leaderboard is active... // ... instead consider "pausing" individual nodes using Godot; using System; using Godot.Collections; public class ScoreManagerMono : Node { public override void _Ready() { // GetNode("score_manager").CallDeferred("wipe", "multi"); // GetNode("score_manager").CallDeferred("wipe", "main"); } public void StartScoreSaver(int highScore, int maxScores, string ldBoardName = "main", Dictionary<string,string> metaData = null) { GetNode("score_manager/score_saver").CallDeferred("start", highScore, maxScores, ldBoardName, metaData); } public void ShowAndRefreshLeaderboard(int maxScores, string ldboardName = "main") { GetNode("score_manager/leaderboard").CallDeferred("show_and_refresh_board", maxScores, ldboardName); } public void ShowLeaderboard() { GetNode("score_manager/leaderboard").CallDeferred("show_board"); } public void RefreshLeaderboard(int maxScores, string ldboardName = "main") { GetNode("score_manager/leaderboard").CallDeferred("refresh_board", maxScores, ldboardName); } } // _scoreManager.ShowAndRefreshLeaderboard(_maxScoresLeaderboard, _leaderBoardMode);
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationMapper : MonoBehaviour { private FinalResult result; private AnimationBiulder biulder; void Start() { //result = GetComponent<FinalResult>(); //biulder = GetComponent<AnimationBiulder>(); biulder = new AnimationBiulder(); Data.LoadChar(); Data.LoadWords(); } public FinalResult mapper(string text, string originalTetx) { /* UnitAnimation[] units = new UnitAnimation[] { }; */ List<UnitAnimation> units = new List<UnitAnimation>(); string[] stringArray = text.Split(' '); foreach (string word in stringArray) { string[,,] foundValue = new string[ 2, 3, 3]; if (Data.words.TryGetValue(word, out foundValue)) { units.Add(mapper(foundValue)); } // finger spell char[] ca = word.ToCharArray(); foreach (var c in ca) { if (Data.characters.TryGetValue(c, out foundValue)) { units.Add(mapper(foundValue)); } } } result = new FinalResult(originalTetx, text, units); return result; } public UnitAnimation mapper(string[,,] symbol) { // split the string string[] temp = new string[18]; int place = 0; for (int i = 0; i < symbol.GetLength(0); i++) { for (int j = 0; j < symbol.GetLength(1); j++) { for (int k = 0; k < symbol.GetLength(2); k++) { temp[place] = symbol[i, j, k]; place++; } } } if (temp[0] != null) { char[] ca = temp[0].ToCharArray(); string str = ""; foreach (var c in ca) { str += GetConf(c); } biulder = biulder.RightHandConfigration(str); } if (temp[1] != null) { biulder = biulder.RightHandOrientation(temp[1]); } if (temp[2] != null) { biulder = biulder.RightArmPosition(GetPos(temp[2])); } if (temp[3] != null) { biulder = biulder.RightHandTransition(temp[3]); } if (temp[6] != null) { char[] ca = temp[6].ToCharArray(); string str = ""; foreach (var c in ca) { str += GetConf(c); } biulder = biulder.RightHandConfigrationFinal(str); } if (temp[7] != null) { biulder = biulder.RightHandOrientationFinal(temp[7]); } if (temp[8] != null) { biulder = biulder.RightArmPositionFinal(GetPos(temp[8])); } if (temp[9] != null) { char[] ca = temp[9].ToCharArray(); string str = ""; foreach (var c in ca) { str += GetConf(c); } biulder = biulder.LeftHandConfigration(str); } if (temp[10] != null) { biulder = biulder.LeftHandOrientation(temp[10]); } if (temp[11] != null) { biulder = biulder.LeftArmPosition(GetPos(temp[11])); } if (temp[12] != null) { biulder = biulder.LeftHandTransition(temp[12]); } if (temp[15] != null) { char[] ca = temp[15].ToCharArray(); string str = ""; foreach (var c in ca) { str += GetConf(c); } biulder = biulder.LeftHandConfigrationFinal(str); } if (temp[16] != null) { biulder = biulder.LeftHandOrientationFinal(temp[16]); } if (temp[17] != null) { biulder = biulder.LeftArmPositionFinal(GetPos(temp[17])); } return biulder.Build(); } private string GetConf(char c) { switch (c) { case 'A': return "XOYO"; case 'B': return "XOY1"; case 'C': return "X1YO"; case 'D': return "X1Y1"; case 'E': return "X2YO"; case 'F': return "X2Y1"; case 'G': return "X3YO"; case 'H': return "X3Y1"; case 'I': return "X4YO"; case 'J': return "X4Y1"; case 'K': return "X5YO"; case 'L': return "X5Y1"; default: return "XOYO"; } } private Vector3 GetPos(string poseString) { switch (poseString) { case "00": return new Vector3( 0.30f, 1.0f, 0.3f); case "01": return new Vector3( 0.30f, 1.2f, 0.3f); case "02": return new Vector3( 0.30f, 1.4f, 0.3f); case "03": return new Vector3( 0.30f, 1.6f, 0.3f); case "04": return new Vector3( 0.15f, 1.0f, 0.3f); case "05": return new Vector3( 0.15f, 1.2f, 0.3f); case "06": return new Vector3( 0.15f, 1.4f, 0.3f); case "07": return new Vector3( 0.15f, 1.6f, 0.3f); case "08": return new Vector3( 0.00f, 1.0f, 0.3f); case "09": return new Vector3( 0.00f, 1.2f, 0.3f); case "10": return new Vector3( 0.00f, 1.4f, 0.3f); case "11": return new Vector3( 0.00f, 1.6f, 0.3f); case "12": return new Vector3(-0.15f, 1.0f, 0.3f); case "13": return new Vector3(-0.15f, 1.2f, 0.3f); case "14": return new Vector3(-0.15f, 1.4f, 0.3f); case "15": return new Vector3(-0.15f, 1.6f, 0.3f); case "16": return new Vector3(-0.30f, 1.0f, 0.3f); case "17": return new Vector3(-0.30f, 1.2f, 0.3f); case "18": return new Vector3(-0.30f, 1.4f, 0.3f); case "19": return new Vector3(-0.30f, 1.6f, 0.3f); case "20": return new Vector3(0.02f, 1.4f, 0.43f); case "21": return new Vector3(0.02f, 1.4f, 0.43f); case "22": return new Vector3(0.02f, 1.4f, 0.43f); case "23": return new Vector3(0.02f, 1.4f, 0.43f); case "24": return new Vector3(0.02f, 1.4f, 0.43f); case "25": return new Vector3(0.02f, 1.4f, 0.43f); case "26": return new Vector3(0.02f, 1.4f, 0.43f); case "27": return new Vector3(0.02f, 1.4f, 0.43f); case "28": return new Vector3(0.02f, 1.4f, 0.43f); case "29": return new Vector3(0.02f, 1.4f, 0.43f); case "30": return new Vector3(0.02f, 1.4f, 0.43f); case "31": return new Vector3(0.02f, 1.4f, 0.43f); case "32": return new Vector3(0.02f, 1.4f, 0.43f); case "33": return new Vector3(0.02f, 1.4f, 0.43f); case "34": return new Vector3(0.02f, 1.4f, 0.43f); case "35": return new Vector3(0.02f, 1.4f, 0.43f); case "36": return new Vector3(0.02f, 1.4f, 0.43f); default: return new Vector3(0.00f, 0.0f, 0.00f); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Operations.Extensions { public static class StringExtensions { /// <summary> /// Perform case insensitive equal on two strings /// </summary> /// <param name="sender"></param> /// <param name="item"></param> /// <returns>true if both strings are a match, false if not a match</returns> public static bool AreEqual(this string sender, string item) => string.Equals(sender, item, StringComparison.OrdinalIgnoreCase); /// <summary> /// Determines if a string is within another string with Comparison options /// </summary> /// <param name="source"></param> /// <param name="compareToken">string to see if it exists in source string</param> /// <param name="comparer">StringComparison</param> /// <returns></returns> public static bool Contains(this string source, string compareToken, StringComparison comparer = StringComparison.OrdinalIgnoreCase) => source?.IndexOf(compareToken, comparer) >= 0; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIweapon2 : MonoBehaviour { public float speed = 3.0f; public float obstacleRange = 5.0f; public float speeed = 100; [SerializeField] private GameObject fireballPrefab; private GameObject _fireball; void Update() { transform.Rotate(0, speeed * Time.deltaTime, 0); Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.SphereCast(ray, 0.75f, out hit)) { GameObject hitObject = hit.transform.gameObject; if (hitObject.GetComponent<PlayerCharacter>()) { _fireball = Instantiate(fireballPrefab) as GameObject; _fireball.transform.position = transform.TransformPoint(Vector3.forward * 1.5f); _fireball.transform.rotation = transform.rotation; speeed = 0; } else { speeed = 100; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shipwreck.TypeScriptModels.Declarations { public enum AccessibilityModifier { None, Public, Private, Protected } }
using EBS.Domain.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Query.DTO; namespace EBS.Query { public interface IProductQuery { IEnumerable<ProductDto> GetPageList(Pager page, string name, string codeOrBarCode, string categoryId, int brandId); IEnumerable<PriceTagDto> QueryProductPriceTagList(string ids); PriceTagDto QueryPriceTag(string productCodeOrBarCode); string GenerateBarCode(); IEnumerable<ProductCheckDto> QueryContractProductNoSalePrice(string productCodeOrBarCode); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ledge_Controller : MonoBehaviour { [Header("Climable Layer")] public LayerMask climbable; [Header("Detection Points")] public Vector3 top; public Vector3 mid; public Vector3 bottom; public float ledgeClimbSpeed; [Header("References")] public RaycastHit objectHit; public Player_Controller controller; private void OnDrawGizmos() { Gizmos.color = Color.magenta; Gizmos.DrawWireSphere(transform.position+ controller.playerModel.TransformDirection(top), 0.1f); Gizmos.DrawWireSphere(transform.position + controller.playerModel.TransformDirection(bottom), 0.1f); Gizmos.DrawWireSphere(transform.position + controller.playerModel.TransformDirection(mid), 0.1f); Gizmos.color = Color.red; Gizmos.DrawWireSphere(detectCase, 0.1f); } private Vector3 detectCase; private RaycastHit surface() { Ray ray = new Ray(transform.position, controller.playerModel.forward); RaycastHit hit; Debug.DrawRay(ray.origin, ray.direction); if (Physics.Raycast(ray, out hit, Mathf.Infinity, climbable)) { controller.playerModel.forward = -objectHit.normal; return hit; } return objectHit; } //Top & Bottom Edge Case or Comes off Side (Don't handle corner and transitions right now). private void DetectEnd() { //Top RayCast (for top case)... Ray bottomRay = new Ray(transform.position + controller.playerModel.TransformDirection(bottom), -controller.playerModel.up); RaycastHit hitH; if (Physics.Raycast(bottomRay, out hitH, 1f)) { Disable(); return; } Ray topRay = new Ray(transform.position+ controller.playerModel.TransformDirection(top), controller.playerModel.forward); RaycastHit hit = new RaycastHit(); if (!Physics.Raycast(topRay, out hit, 0.5f, climbable)) { topRay = new Ray(transform.position + top + controller.playerModel.forward * 0.5f, - objectHit.transform.up); if (Physics.Raycast(topRay, out hit, 20, climbable)) { if (hit.transform == objectHit.transform) { Debug.DrawRay(topRay.origin, topRay.direction, Color.yellow, 0.1f); detectCase = hit.point; transform.position = new Vector3(hit.point.x, hit.point.y + controller.height, hit.point.z); Disable(); return; } } } Ray midRay = new Ray(transform.position, controller.playerModel.forward); RaycastHit midHit; if (!Physics.Raycast(topRay, out hit, 0.3f, climbable) || hit.transform != objectHit.transform) { Disable(); } } private Vector3 InputV() { Vector3 input; input = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * ledgeClimbSpeed; controller.playerModel.forward = -objectHit.normal; input = controller.playerModel.transform.TransformDirection(input); //input.z = 0; return input; } private void CollisionCheck(Vector3 v) { Vector3 added = v; //Check all nearby colliders (except self) Collider[] c = Physics.OverlapSphere(transform.position, 20, controller.discludePlayer); //Custom Collision Implementation foreach (Collider col in c) { Vector3 penDir = new Vector3(); float penDist = 0f; for (int i = 0; i < 2; i++) { bool d = Physics.ComputePenetration(col, col.transform.position, col.transform.rotation, this.GetComponent<CapsuleCollider>(), transform.position + added, transform.rotation, out penDir, out penDist); if (d == false) continue; Vector3 moveSet = -penDir.normalized * penDist; moveSet = controller.playerModel.TransformDirection(moveSet); moveSet.z = 0; moveSet = controller.playerModel.InverseTransformDirection(moveSet); transform.position += moveSet; } } } private void OnEnable() { controller = this.GetComponent<Player_Controller>(); controller.controller.enabled = false; } private void FixedUpdate() { objectHit = surface(); transform.position += InputV()*Time.fixedDeltaTime; DetectEnd(); } private void LateUpdate() { CollisionCheck(InputV() * Time.fixedDeltaTime); } private void Disable() { controller.Enable(); this.enabled = false; } }
using System; using Tweetinvi.Controllers.Messages; using Tweetinvi.Models; using Tweetinvi.Models.DTO; using Tweetinvi.Parameters; namespace Tweetinvi.Json { public static class MessageJson { [ThreadStatic] private static IMessageJsonController _messageJsonController; public static IMessageJsonController MessageJsonController { get { if (_messageJsonController == null) { Initialize(); } return _messageJsonController; } } static MessageJson() { Initialize(); } private static void Initialize() { _messageJsonController = TweetinviContainer.Resolve<IMessageJsonController>(); } // Get Messages public static string GetLatestMessagesReceived(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT) { return MessageJsonController.GetLatestMessagesReceived(maximumMessages); } public static string GetLatestMessagesReceived(IMessagesReceivedParameters queryParameters) { return MessageJsonController.GetLatestMessagesReceived(queryParameters); } public static string GetLatestMessagesSent(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT) { return MessageJsonController.GetLatestMessagesSent(maximumMessages); } public static string GetLatestMessagesSent(IMessagesSentParameters queryParameters) { return MessageJsonController.GetLatestMessagesSent(queryParameters); } // Publish Message public static string PublishMessage(string text, IUserIdentifier targetUserIdentifier) { return MessageJsonController.PublishMessage(text, targetUserIdentifier); } public static string PublishMessage(string text, long targetUserId) { return MessageJsonController.PublishMessage(text, targetUserId); } public static string PublishMessage(string text, string targetUserScreenName) { return MessageJsonController.PublishMessage(text, targetUserScreenName); } // Destroy Message public static string DestroyMessage(IMessage message) { return MessageJsonController.DestroyMessage(message); } public static string DestroyMessage(IMessageDTO messageDTO) { return MessageJsonController.DestroyMessage(messageDTO); } public static string DestroyMessage(long messageId) { return MessageJsonController.DestroyMessage(messageId); } } }
/* Copyright (C) 2020 Federico Peinado http://www.federicopeinado.com Este fichero forma parte del material de la asignatura Inteligencia Artificial para Videojuegos. Esta asignatura se imparte en la Facultad de Informática de la Universidad Complutense de Madrid (España). Autor: Federico Peinado Contacto: email@federicopeinado.com */ namespace UCM.IAV.Navegacion { using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Abstract class for graphs /// </summary> public abstract class Graph : MonoBehaviour { public GameObject vertexPrefab; protected List<Vertex> vertices; protected List<List<Vertex>> neighbors; protected List<List<float>> costs; protected Dictionary<int, int> instIdToId; //// this is for informed search like A* public delegate float Heuristic(Vertex a, Vertex b); // Used for getting path in frames public List<Vertex> path; public bool isFinished; public virtual void Start() { Load(); } public virtual void Load() { } public virtual int GetSize() { if (ReferenceEquals(vertices, null)) return 0; return vertices.Count; } public virtual Vertex GetNearestVertex(Vector3 position) { return null; } public virtual Vertex[] GetNeighbours(Vertex v) { if (ReferenceEquals(neighbors, null) || neighbors.Count == 0) return new Vertex[0]; if (v.id < 0 || v.id >= neighbors.Count) return new Vertex[0]; return neighbors[v.id].ToArray(); } public virtual Edge[] GetEdges(Vertex v) { if (ReferenceEquals(neighbors, null) || neighbors.Count == 0) return new Edge[0]; if (v.id < 0 || v.id >= neighbors.Count) return new Edge[0]; int numEdges = neighbors[v.id].Count; Edge[] edges = new Edge[numEdges]; List<Vertex> vertexList = neighbors[v.id]; List<float> costList = costs[v.id]; for (int i = 0; i < numEdges; i++) { edges[i] = new Edge(); edges[i].cost = costList[i]; edges[i].vertex = vertexList[i]; } return edges; } public List<Vertex> GetPathBFS(GameObject srcObj, GameObject dstObj) { if (srcObj == null || dstObj == null) return new List<Vertex>(); Vertex[] neighbours; Queue<Vertex> q = new Queue<Vertex>(); Vertex src = GetNearestVertex(srcObj.transform.position); Vertex dst = GetNearestVertex(dstObj.transform.position); Vertex v; int[] previous = new int[vertices.Count]; for (int i = 0; i < previous.Length; i++) previous[i] = -1; previous[src.id] = src.id; q.Enqueue(src); while (q.Count != 0) { v = q.Dequeue(); if (ReferenceEquals(v, dst)) { return BuildPath(src.id, v.id, ref previous); } neighbours = GetNeighbours(v); foreach (Vertex n in neighbours) { if (previous[n.id] != -1) continue; previous[n.id] = v.id; q.Enqueue(n); } } return new List<Vertex>(); } public List<Vertex> GetPathDFS(GameObject srcObj, GameObject dstObj) { if (srcObj == null || dstObj == null) return new List<Vertex>(); Vertex src = GetNearestVertex(srcObj.transform.position); Vertex dst = GetNearestVertex(dstObj.transform.position); Vertex[] neighbours; Vertex v; int[] previous = new int[vertices.Count]; for (int i = 0; i < previous.Length; i++) previous[i] = -1; previous[src.id] = src.id; Stack<Vertex> s = new Stack<Vertex>(); s.Push(src); while (s.Count != 0) { v = s.Pop(); if (ReferenceEquals(v, dst)) { return BuildPath(src.id, v.id, ref previous); } neighbours = GetNeighbours(v); foreach (Vertex n in neighbours) { if (previous[n.id] != -1) continue; previous[n.id] = v.id; s.Push(n); } } return new List<Vertex>(); } public List<Vertex> GetPathDijkstra(GameObject srcObj, GameObject dstObj) { // IMPLEMENTACIÓN DEL ALGORITMO DE DIJKSTRA return new List<Vertex>(); } public List<Vertex> GetPathAstar(GameObject srcObj, GameObject dstObj, Heuristic h = null) { // IMPLEMENTACIÓN DEL ALGORITMO A* return new List<Vertex>(); } public List<Vertex> Smooth(List<Vertex> path) { // IMPLEMENTACIÓN DEL ALGORITMO DE SUAVIZADO return null; //newPath } private List<Vertex> BuildPath(int srcId, int dstId, ref int[] prevList) { List<Vertex> path = new List<Vertex>(); int prev = dstId; do { path.Add(vertices[prev]); prev = prevList[prev]; } while (prev != srcId); return path; } // Heurística de distancia euclídea public float EuclidDist(Vertex a, Vertex b) { Vector3 posA = a.transform.position; Vector3 posB = b.transform.position; return Vector3.Distance(posA, posB); } // Heurística de distancia Manhattan public float ManhattanDist(Vertex a, Vertex b) { Vector3 posA = a.transform.position; Vector3 posB = b.transform.position; return Mathf.Abs(posA.x - posB.x) + Mathf.Abs(posA.y - posB.y); } } }
using Ardalis.Specification; using FrontDesk.Core.Aggregates; namespace FrontDesk.Core.Specifications { public class ClientsIncludePatientsSpecification : Specification<Client> { public ClientsIncludePatientsSpecification() { Query .Include(client => client.Patients) .OrderBy(client => client.FullName); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; using System; namespace DSSAHP.Tests { [TestClass] public class MatrixTest { private MatrixAHP Matrix { get; set; } public MatrixTest() { double[,] values = new double[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, }; Matrix = new MatrixAHP(values); } [TestMethod] public void SumTest() { Assert.AreEqual(Matrix.Sum, 45, "Неправильно считается сумма матрицы"); } [TestMethod] public void SumRows() { Assert.IsTrue(Enumerable.SequenceEqual(Matrix.SumRows, new double[] { 6, 15, 24 }), "Неправильно считаются суммы строк"); } [TestMethod] public void SumCols() { Assert.IsTrue(Enumerable.SequenceEqual(Matrix.SumColumns, new double[] { 12, 15, 18 }), "Неправильно считается суммы столбцов"); } public void Normalised() { Assert.AreEqual(Matrix.Normalised, new double[,] { { 1,2,3 }, { 1,2,3 }, { 1,2,3 } }, "Матрица неправильно нормализуется"); } public void Coefficients() { Assert.AreEqual(Matrix.Coeffiients, new double[] { 12, 15, 18 }, "Матрица неверно расчитывает коэффициенты"); } } }
using System; using System.Collections.Specialized; using System.Windows.Forms; using Laan.AddIns.Core; using Laan.AddIns.Forms; namespace Laan.AddIns.Actions { [ResultsMenu] public class SaveResultAs2 : SaveResultsAs { public SaveResultAs2( AddIn addIn ) : base( addIn ) { KeyName = "LannSqlSaveResultsAs2"; DisplayName = "Save Results As"; DescriptivePhrase = "Save Results to log file and optionally copy file to clipboard"; ButtonText = "Save Results to .log"; //ToolTip = "hi there"; SaveResultsAsPatternName = Settings.Constants.SaveResultsAsPattern2; SaveResultsAsPatternDefault = Settings.Defaults.SaveResultsAsPattern2; SaveResultsAsCopyToClipboardName = Settings.Constants.SaveResultsCopyToClipboard2; SaveResultsAsCopyToClipboardDefault = Settings.Defaults.SaveResultsCopyToClipboard2; } } }
using PCLStorage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Plugin.Share.Abstractions; using Xamarin.Forms; namespace TestApp { public partial class CodeEditor : TabbedPage { private string path; public async Task code() { IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder projects = await rootFolder.CreateFolderAsync("Projects", CreationCollisionOption.OpenIfExists); string project = "Projects\\" + path; IFolder projectFolder = await rootFolder.CreateFolderAsync(project, CreationCollisionOption.OpenIfExists); IFile file = await projects.CreateFileAsync(path + "\\index.html", CreationCollisionOption.OpenIfExists); string code = await file.ReadAllTextAsync(); editor.Text = code; await DisplayAlert("PATH", "Project created in: " + file.Path, "OK"); web_view.Source = new HtmlWebViewSource { Html = code }; } public async void OnSave(Object o, EventArgs e) { IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder projects = await rootFolder.CreateFolderAsync("Projects", CreationCollisionOption.OpenIfExists); string project = "Projects\\" + path; IFolder projectFolder = await rootFolder.CreateFolderAsync(project, CreationCollisionOption.OpenIfExists); IFile file = await projects.CreateFileAsync(path + "\\index.html", CreationCollisionOption.OpenIfExists); await file.WriteAllTextAsync(editor.Text); await DisplayAlert("Success", path + "Saved succesfully.", "OK"); } public void refresh(Object o, EventArgs e) { web_view.Source = new HtmlWebViewSource { Html = editor.Text }; } public CodeEditor(string path) { InitializeComponent(); this.path = path; code(); } public void CopyToClipboard(Object o, EventArgs e) { if (Plugin.Share.CrossShare.Current.SupportsClipboard == false) { DisplayAlert("Error", "Error while copying to the clipboard.", "OK"); } Plugin.Share.CrossShare.Current.SetClipboardText(editor.Text); } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Behaviors { interface ISlider { float Slide { get; } } class SliderScene : ISlider { Scene Scene; float Frame; float Time; public float Slide => MathHelper.Clamp((Scene.Frame - Frame) / Time, 0, 1); public SliderScene(Scene scene, float time) { Scene = scene; Frame = scene.Frame; Time = time; } } class SliderTime : ISlider { SceneGame Scene; Slider Frame; public float Slide => Frame.Slide; public SliderTime(SceneGame scene, float time) { Scene = scene; Frame = new Slider(time); Scene.Timers.Add(this); } public void Update() { Frame += Scene.TimeModCurrent; } } }
using NBatch.Main.Core; namespace NBatch.ConsoleDemo { public class ProductUppercaseProcessor : IProcessor<Product, Product> { public Product Process(Product input) { return new Product { ProductId = input.ProductId, Name = input.Name.ToUpper(), Description = input.Description.ToUpper(), Price = input.Price }; } } }
namespace Tutorial.Functional { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; internal static partial class Functions { internal static void MethodWithLocalFunction() { void LocalFunction() // Define local function. { nameof(LocalFunction).WriteLine(); } LocalFunction(); // Call local function. } internal static int PropertyWithLocalFunction { get { LocalFunction(); // Call local function. void LocalFunction() // Define local function. { nameof(LocalFunction).WriteLine(); } LocalFunction(); // Call local function. return 0; } } } internal static partial class Functions { #if DEMO // Cannot be compiled. internal static void LocalFunctionOverload() { void LocalFunction() { } void LocalFunction(int int32) { } // Cannot be compiled. } #endif internal static int BinarySearch<T>(this IList<T> source, T value, IComparer<T> comparer = null) { return BinarySearch(source, value, comparer ?? Comparer<T>.Default, 0, source.Count - 1); } private static int BinarySearch<T>(IList<T> source, T value, IComparer<T> comparer, int startIndex, int endIndex) { if (startIndex > endIndex) { return -1; } int middleIndex = startIndex + (endIndex - startIndex) / 2; int compare = comparer.Compare(source[middleIndex], value); if (compare == 0) { return middleIndex; } return compare > 0 ? BinarySearch(source, value, comparer, startIndex, middleIndex - 1) : BinarySearch(source, value, comparer, middleIndex + 1, endIndex); } internal static int BinarySearchWithLocalFunction<T>(this IList<T> source, T value, IComparer<T> comparer = null) { int BinarySearch( IList<T> localSource, T localValue, IComparer<T> localComparer, int startIndex, int endIndex) { if (startIndex > endIndex) { return -1; } int middleIndex = startIndex + (endIndex - startIndex) / 2; int compare = localComparer.Compare(localSource[middleIndex], localValue); if (compare == 0) { return middleIndex; } return compare > 0 ? BinarySearch(localSource, localValue, localComparer, startIndex, middleIndex - 1) : BinarySearch(localSource, localValue, localComparer, middleIndex + 1, endIndex); } return BinarySearch(source, value, comparer ?? Comparer<T>.Default, 0, source.Count - 1); } internal static int BinarySearchWithClosure<T>(this IList<T> source, T value, IComparer<T> comparer = null) { int BinarySearch(int startIndex, int endIndex) { if (startIndex > endIndex) { return -1; } int middleIndex = startIndex + (endIndex - startIndex) / 2; int compare = comparer.Compare(source[middleIndex], value); if (compare == 0) { return middleIndex; } return compare > 0 ? BinarySearch(startIndex, middleIndex - 1) : BinarySearch(middleIndex + 1, endIndex); } comparer = comparer ?? Comparer<T>.Default; return BinarySearch(0, source.Count - 1); } [CompilerGenerated] [StructLayout(LayoutKind.Auto)] private struct Display1<T> { public IComparer<T> Comparer; public IList<T> Source; public T Value; } [CompilerGenerated] private static int CompiledLocalBinarySearch<T>(int startIndex, int endIndex, ref Display1<T> display) { if (startIndex > endIndex) { return -1; } int middleIndex = startIndex + (endIndex - startIndex) / 2; int compare = display.Comparer.Compare(display.Source[middleIndex], display.Value); if (compare == 0) { return middleIndex; } return compare <= 0 ? CompiledLocalBinarySearch(middleIndex + 1, endIndex, ref display) : CompiledLocalBinarySearch(startIndex, middleIndex - 1, ref display); } internal static int CompiledBinarySearchWithClosure<T>(IList<T> source, T value, IComparer<T> comparer = null) { Display1<T> display = new Display1<T>() { Source = source, Value = value, Comparer = comparer }; return CompiledLocalBinarySearch(0, source.Count - 1, ref display); } internal static void FunctionMember() { void LocalFunction() { void LocalFunctionInLocalFunction() { } } } internal static Action AnonymousFunctionWithLocalFunction() { return () => { void LocalFunction() { } LocalFunction(); }; } internal class Display { int outer = 1; // Outside the scope of method Add. internal void Add() { int local = 2; // Inside the scope of method Add. (local + outer).WriteLine(); // this.outer field. } } internal static void LocalFunctionClosure2() { int outer = 1; // Outside the scope of function Add. void Add() { int local = 2; // Inside the scope of function Add. (local + outer).WriteLine(); } Add(); // 3 } [CompilerGenerated] [StructLayout(LayoutKind.Auto)] private struct Display0 { public int Outer; } private static void Add(ref Display0 display) { int local = 2; (local + display.Outer).WriteLine(); } internal static void CompiledLocalFunctionClosure() { int outer = 1; // Outside the scope of function Add. Display0 display = new Display0() { Outer = outer }; Add(ref display); // 3 } internal static void Outer() { int outer = 1; // Outside the scope of function Add. void Add() { int local = 2; // Inside the scope of function Add. (local + outer).WriteLine(); } Add(); // 3 outer = 3; // Outer variable can change. Add(); // 5 } internal static void CompiledOuter() { int outer = 1; Display0 closure = new Display0 { Outer = outer }; Add(ref closure); closure.Outer = outer = 3; Add(ref closure); } internal static void OuterReference() { List<Action> localFunctions = new List<Action>(); for (int outer = 0; outer < 3; outer++) { void LocalFunction() { outer.WriteLine(); // outer is 0, 1, 2. } localFunctions.Add(LocalFunction); } // outer is 3. foreach (Action localFunction in localFunctions) { localFunction(); // 3 3 3 (instead of 0 1 2) } } internal static void CopyOuterReference() { List<Action> localFunctions = new List<Action>(); for (int outer = 0; outer < 3; outer++) { int copyOfOuter = outer; // outer is 0, 1, 2. // When outer changes, copyOfOuter does not change. void LocalFunction() { copyOfOuter.WriteLine(); } localFunctions.Add(LocalFunction); } // copyOfOuter is 0, 1, 2. foreach (Action localFunction in localFunctions) { localFunction(); // 0 1 2 } } [CompilerGenerated] private sealed class Display2 { public int CopyOfOuter; internal void LocalFunction() { this.CopyOfOuter.WriteLine(); } } internal static void CompiledCopyOuterReference() { List<Action> localFunctions = new List<Action>(); for (int outer = 0; outer < 3; outer++) { Display2 display = new Display2() { CopyOfOuter = outer }; // outer is 0, 1, 2. // When outer changes, display.CopyOfOuter does not change. localFunctions.Add(display.LocalFunction); } // display.CcopyOfOuter is 0, 1, 2. foreach (Action localFunction in localFunctions) { localFunction(); // 0 1 2 } } } internal static partial class Functions { [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] private static Action longLife; internal static void Reference() { // https://msdn.microsoft.com/en-us/library/System.Array.aspx byte[] shortLife = new byte[0X7FFFFFC7]; // Local variable of large array (Array.MaxByteArrayLength). // ... void LocalFunction() { // ... byte @byte = shortLife[0]; // Closure. // ... } // ... LocalFunction(); // ... longLife = LocalFunction; // Reference from longLife to shortLife. } } internal static partial class Functions { [CompilerGenerated] private sealed class Display3 { public byte[] ShortLife; internal void LocalFunction() { // ... byte @byte = this.ShortLife[0]; // ... } } internal static void CompiledReference() { byte[] shortLife = new byte[0X7FFFFFC7]; // Local variable of large array (Array.MaxByteArrayLength). // ... Display3 display = new Display3(); display.ShortLife = shortLife; display.LocalFunction(); // ... longLife = display.LocalFunction; // Now longLife.ShortLife holds the reference to the huge large array. } } }
using System; using UnityEngine; using UnityEngine.AI; /// Author: Corwin Belser /// Used by EnemyController to create patrolling behavior public class PatrolPoint : MonoBehaviour { public int PATROL_GROUP = 0; public PatrolPoint NEXT; }
using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Entities.Core; using System; namespace Alabo.Datas.Stores.Distinct.EfCore { public abstract class DistinctEfCoreStore<TEntity, TKey> : DistinctAsyncEfCoreStore<TEntity, TKey>, IDistinctStore<TEntity, TKey> where TEntity : class, IKey<TKey>, IVersion, IEntity { protected DistinctEfCoreStore(IUnitOfWork unitOfWork) : base(unitOfWork) { } public bool Distinct(string filedName) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Pronto.Common { public abstract class DataAccess { public abstract string LoadConnectionString(); public abstract List<T> LoadData<T>(string sql); public abstract int SaveData<T>(string sql, T data); public abstract void CreateDb( string FilePath); public abstract void CreateTable(string sql); public abstract void RunScript(string sql); protected string ConnectionString; public string DataSource { get { if (!string.IsNullOrEmpty(ConnectionString)) { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString); return builder.DataSource; } else { return null; } } } } }
using System; using System.Collections.Generic; using System.Linq; namespace E1 { class Program { static void Main(string[] args) { List<Persona> personas = new List<Persona>(); Persona p1 = new Persona(35, "Juan", "Perez"); Persona p2 = new Persona(16, "Juan", "Ludenberg"); Persona p3 = new Persona(60, "Carlos", "Perez"); personas.Add(p1); personas.Add(p2); personas.Add(p3); List<Persona> mayoresDeEdad = personas.Where(persona => persona.Edad >= 18).ToList(); Console.WriteLine("Mayores de Edad:\n"); mayoresDeEdad.ForEach(persona => Console.WriteLine("Nombre: " + persona.Nombre + "\nApellido: " + persona.Apellido + "\nEdad: " + persona.Edad)); List<Persona> Juanes = personas.Where(personas => personas.Nombre == "Juan").ToList(); Console.WriteLine("\nLos Juanes:\n"); Juanes.ForEach(persona => Console.WriteLine("Nombre: " + persona.Nombre + "\nApellido: " + persona.Apellido + "\nEdad: " + persona.Edad)); List<Persona> Perez = personas.Where(personas => personas.Apellido == "Perez").ToList(); Console.WriteLine("\nLos Perez:\n"); Perez.ForEach(persona => Console.WriteLine("Nombre: " + persona.Nombre + "\nApellido: " + persona.Apellido + "\nEdad: " + persona.Edad)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sparda.Contracts { public interface IColumn { string Group { get; } string BusinessType { get; } bool HasDefaultValue { get; } bool IsBackendCalculated(); } }
using System; using System.Collections.Generic; using System.Text; namespace NumbersToWords { public interface IHundredConverter { string ConvertValueHundredToWordHundred(); } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Tndm_ArtShop.Data; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Tndm_ArtShop.Models; using Tndm_ArtShop.Services; using Microsoft.Extensions.FileProviders; using System.IO; using Microsoft.AspNetCore.ResponseCompression; using System.IO.Compression; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using HealthChecks.UI.Client; using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Tndm_ArtShop { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions => { sqlOptions.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); })); //enables resilientSQL connections thatareretried if theconnection fails services.AddDbContext<ProdavnicaContext>(opcije => opcije.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions => { sqlOptions.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); })); //enables resilientSQL connections thatareretried if theconnection fails services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores<ApplicationDbContext>(); services.Configure<IdentityOptions>(opcije => { // Podesavanje lozinke opcije.Password.RequireDigit = false; opcije.Password.RequiredLength = 3; opcije.Password.RequireNonAlphanumeric = false; opcije.Password.RequireUppercase = false; opcije.Password.RequireLowercase = false; opcije.Password.RequiredUniqueChars = 1; opcije.User.RequireUniqueEmail = true; }); services.AddSession(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped<KorpaServis>(); services.AddSingleton<IFileProvider>( new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/slike")) ); services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.RequireRole("Administrator")); options.AddPolicy("Developer", policy => policy.RequireRole("Operater")); options.AddPolicy("Racunovodstvo", policy => policy.RequireRole("Racunovodstvo")); }); //If you have larger file sizes or downloads, //you may want to think about using a compression algorithm. //There are several built-in compression libraries such as Gzip and Brotli. services.AddResponseCompression(); services.Configure<GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; }); services.AddHealthChecks() .AddSqlServer(connectionString: Configuration.GetConnectionString("DefaultConnection"), healthQuery: "SELECT 1;", name: "Sql Server", failureStatus: HealthStatus.Degraded) .AddUrlGroup(new Uri("http://www.google.com"), name: "Base URL", failureStatus: HealthStatus.Degraded); services.AddHealthChecksUI(setupSettings: setup => { setup.AddHealthCheckEndpoint("Basic healthcheck", "https://localhost:44354/healthcheck"); }); services.AddResponseCaching(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseHealthChecks("/healthcheck", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }) .UseHealthChecksUI(); // /healthchecks-ui#/healthcheck app.UseHealthChecksUI(); app.UseResponseCaching(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Security.Cryptography; namespace CNWTT.Core.Admin { public class AdminCore { public static void caculatorPrice(string selectPrice,out string startCost,out string endCost) { startCost = ""; endCost = ""; switch (selectPrice) { case "1": startCost = "0"; endCost = "5000000"; break; case "2": startCost = "5000000"; endCost = "10000000"; break; case "3": startCost = "10000000"; endCost = "20000000"; break; case "4": startCost = "20000000"; endCost = "100000000"; break; } } public static string returnProductType(string content) { string productType = ""; switch (content) { case "mobile": productType = "1"; break; case "tablet": productType = "2"; break; case "laptop": productType = "3"; break; case "desktop": productType = "4"; break; case "accessories": productType = "5"; break; } return productType; } public static void saveImage5(HttpPostedFile[] image) { } public static string EncodeMD5(string password) { Byte[] originalBytes; Byte[] encodedBytes; MD5 md5 = new MD5CryptoServiceProvider(); originalBytes = ASCIIEncoding.Default.GetBytes(password); encodedBytes = md5.ComputeHash(originalBytes); return BitConverter.ToString(encodedBytes); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Marketplaces.Entityes; using Welic.Dominio.Models.Marketplaces.Services; using Welic.Dominio.Patterns.Repository.Pattern.Repositories; using Welic.Dominio.Patterns.Service.Pattern; namespace Services.MarketPlace { public class CategoryService : Service<Category>, ICategoryService { public CategoryService(IRepositoryAsync<Category> repository) : base(repository) { } } }
namespace Orc.FileSystem; using System.IO; public interface IDirectoryService { string Create(string path); void Move(string sourcePath, string destinationPath); void Delete(string path, bool recursive = true); bool Exists(string path); string[] GetDirectories(string path, string searchPattern = "", SearchOption searchOption = SearchOption.TopDirectoryOnly); string[] GetFiles(string path, string searchPattern = "", SearchOption searchOption = SearchOption.TopDirectoryOnly); void Copy(string sourcePath, string destinationPath, bool copySubDirs = true, bool overwriteExisting = false); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SeaFight.Infrastructure { public class Player { public Player() { Name = CreateName(); MyShotHistory = new List<PointCoords>(); } public string Name { get; set; } public Field Field { get; set; } public Field EnemyField { get; set; } public List<PointCoords> MyShotHistory { get; set; } public bool Lose { get { return Field.Ships.All(x => x.ShipSunk); } } public void CreateField() { Field = new Field(); Field.CreateShips(); EnemyField = new Field(); EnemyField.CreateEmptyField(); } public ShotResult ShotByMe(PointCoords coords) { return Field.ShotByMe(coords); } public void ShotByEnemy(PointCoords coords, ShotResult result) { MyShotHistory.Add(coords); EnemyField.ShotByEnemy(coords, result); } public PointCoords CreateCoordsForShot() { var coords = new PointCoords(Consts.GetRandom(10), Consts.GetRandom(10)); while (MyShotHistory.Contains(coords, new PointCoordsComparer())) { coords = new PointCoords(Consts.GetRandom(10), Consts.GetRandom(10)); } return coords; } private string CreateName() { return _names[Consts.GetRandom(_names.Length)]; } private string[] _names = new string[] { "Jacob", "Michael", "Joshua", "Matthew", "Ethan", "Andrew", "Daniel", "William", "Joseph", "Christopher", "Anthony", "Ryan", "Nicholas", "David", "Alexander", "Tyler", "James", "John", "Dylan", "Nathan", "Jonathan", "Brandon", "Samuel", "Christian", "Benjamin", "Zachary", "Logan", "Jose", "Noah", "Justin", "Elijah", "Gabriel", "Caleb", "Kevin", "Austin", "Robert", "Thomas", "Connor", "Evan", "Aidan", "Jack", "Luke", "Jordan", "Angel", "Isaiah", "Isaac", "Jason", "Jackson", "Hunter", "Cameron", "Gavin", "Mason", "Aaron", "Juan", "Kyle", "Charles", "Luis", "Adam", "Brian", "Aiden", "Eric", "Jayden", "Alex", "Bryan", "Sean", "Owen", "Lucas", "Nathaniel", "Ian", "Jesus", "Carlos", "Adrian", "Diego", "Julian", "Cole", "Ashton", "Steven", "Jeremiah", "Timothy", "Chase", "Devin", "Seth", "Jaden", "Colin", "Cody", "Landon", "Carter", "Hayden", "Xavier", "Wyatt", "Dominic", "Richard", "Antonio", "Jesse", "Blake", "Sebastian", "Miguel", "Jake", "Alejandro", "Patrick", }; } }
using eMAM.Data.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace eMAM.Service.DbServices.Contracts { public interface IAttachmentService { Task<Attachment> AddAttachmentAsync(Attachment attachment); } }
using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Models; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort { public class SelectDeliveryModelViewModelFromCreateCohortWithDraftApprenticeshipRequestMapper : IMapper<CreateCohortWithDraftApprenticeshipRequest, SelectDeliveryModelViewModel> { private readonly ISelectDeliveryModelMapperHelper _helper; public SelectDeliveryModelViewModelFromCreateCohortWithDraftApprenticeshipRequestMapper(ISelectDeliveryModelMapperHelper helper) { _helper = helper; } public Task<SelectDeliveryModelViewModel> Map(CreateCohortWithDraftApprenticeshipRequest source) { return _helper.Map(source.ProviderId, source.CourseCode, source.AccountLegalEntityId, source.DeliveryModel, source.IsOnFlexiPaymentPilot); } } }
using BaseFacware.API.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BaseFacware.API.Controllers.Api { [Route("api/[controller]")] [ApiController] public class ItemsController : ControllerBase { private List<Items> GetItems() { var list = new List<Items>(); list.Add(new Items() { Id = 1, Name = "value1" }); list.Add(new Items() { Id = 2, Name = "value2" }); return list; } /// <summary> /// Get items /// </summary> /// <returns>list of items</returns> [HttpGet] public async Task<IActionResult> Get() { var list = await Task.Run(() => GetItems()); return Ok(list); } /// <summary> /// Get item by id /// </summary> /// <returns>list of items</returns> [HttpGet("{id}")] public async Task<IActionResult> GetById([FromRoute] int id) { var item = await Task.Run(() => GetItems().Where(x => x.Id.Equals(id)).FirstOrDefault()); return Ok(item); } /// <summary> /// Create item /// </summary> /// <param name="value"></param> /// <returns></returns> [HttpPost] public IActionResult Post([FromBody] Items value) { return RedirectToAction(nameof(GetById), new { id = value.Id }); } /// <summary> /// Update item /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns></returns> [HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Items value) { return RedirectToAction(nameof(GetById), new { Id = id }); } /// <summary> /// Delete item /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id}")] public IActionResult Delete(int id) { return NoContent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using AudioText.DAL; using AudioText.Models; using AudioText.Models.ViewModels; namespace AudioText.Controllers { /// <summary> /// used to view inventory items /// </summary> [AllowAnonymous] public class InventoryItemController : Controller { [HttpGet] public ActionResult itemdetail(int Id) { return View("InventoryDetail",new ItemDetailViewModel(Id)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowMouseBehaviour : MonoBehaviour { private Camera cam; public Vector3Data postionOfMouse; private void Start() { cam = Camera.main; } public void Update() { if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out var hit, 100)) { postionOfMouse.value = hit.point; } } public void OnLook(Vector3Data obj) { Transform transform1; (transform1 = transform).LookAt(obj.value); var transformRotation = transform1.eulerAngles; transformRotation.x = 0; transformRotation.y -= 90; transform.rotation = Quaternion.Euler(transformRotation); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; using Newtonsoft; using Newtonsoft.Json; using Demo_Wpf_TheSimpleGame.Models; namespace Demo_Wpf_TheSimpleGame.Data { public class DataServiceJson : IDataService { private string _dataFilePath; /// <summary> /// read the json file and load a list of Player objects /// </summary> /// <returns>list of players</returns> public List<Player> ReadAll() { List<Player> players; try { using (StreamReader sr = new StreamReader(_dataFilePath)) { string jsonString = sr.ReadToEnd(); players = JsonConvert.DeserializeObject<List<Player>>(jsonString); } } catch (Exception) { throw; } return players; } /// <summary> /// write the current list of players to the json data file /// </summary> /// <param name="players">list of players</param> public void WriteAll(List<Player> players) { string jsonString = JsonConvert.SerializeObject(players, Formatting.Indented); try { StreamWriter writer = new StreamWriter(_dataFilePath); using (writer) { writer.WriteLine(jsonString); writer.Close(); } } catch (Exception) { throw; } } public DataServiceJson() { _dataFilePath = @"Data\Data.json"; } } }
using EPI.Searching; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Searching { [TestClass] public class BinarySearchInTwoSortedArrayUnitTest { [TestMethod] public void SearchKthInTwoSortedArrays() { int[] A = new[] { 2, 4, 6, 8}; int[] B = new[] { 1, 3, 5, 7, 9, 11}; BinarySearchInTwoSortedArrays.SearchKthElement(A, B, 1).Should().Be(1); BinarySearchInTwoSortedArrays.SearchKthElement(A, B, 2).Should().Be(2); BinarySearchInTwoSortedArrays.SearchKthElement(A, B, 7).Should().Be(7); BinarySearchInTwoSortedArrays.SearchKthElement(A, B, 10).Should().Be(11); BinarySearchInTwoSortedArrays.SearchKthElement(A, B, 5).Should().Be(5); } } }
using Autofac; using SSW.RulesSearchCore.Elastic; namespace SSW.RulesSearchCore.Web { public class RulesSearchWebModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new ElasticSearchModule(new ElasticSearchSettings() { Url = ConfigSettings.ElasticSearchUrl })); builder.RegisterType<ElasticTextSearch>() .AsSelf() .AsImplementedInterfaces(); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore.ChangeTracking; using Task.Model; namespace Task.Services { public class CommentService { public CommentService(BaseDbContext context) { _context = context; } private readonly BaseDbContext _context; private DbSet<Comment> Comments => _context.Comments; public List<Comment> GetAll() { return Comments.ToList(); } public Comment GetCommentById(int id) { Comment comment = Comments.SingleOrDefault((Comment comment) => comment.Id == id); if (comment == null) { return null; } return comment; } public Comment AddNewComment(Comment value) { var comment = ToEntity(value); if (comment == null) return null; Comments.Add(comment); try { _context.SaveChanges(); } catch { return null; } return comment; } public (Comment comment, Exception exception) UpdateComment(Comment value) { Comment comment = Comments.SingleOrDefault((Comment comment) => comment.Id == value.Id); if (comment == null) { return (null, new ArgumentNullException($"comment with id: {value.Id} not found")); } if (value.Id != 0) { comment.Text = value.Text; } try { _context.SaveChanges(); } catch (Exception e) { return (null, new DbUpdateException($"Cannot save changes: {e.Message}")); } return (comment, null); } public (bool result, Exception exception) DeleteComment(int id) { Comment comment = Comments.SingleOrDefault((Comment comment) => comment.Id == id); if (comment == null) { return (false, new ArgumentNullException($"Comment with id: {id} not found")); } EntityEntry<Comment> result = Comments.Remove(comment); try { _context.SaveChanges(); } catch (Exception e) { return (false, new DbUpdateException($"Cannot save changes: {e.Message}")); } return (result.State == EntityState.Deleted, null); } public Comment ToEntity(Comment value) { return new Comment { Id = value.Id, Text = value.Text, }; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Business { public class ConsensusComponent { } }
using ArticlesProject.DatabaseEntities; using ArticlesProject.Repository.Interfaces; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArticlesProject.Repository.Implementations { public class Repository<TEntity> : IRepository<TEntity> where TEntity : class { protected DbContext _db; public Repository(DbContext db) { _db = db; } public void Add(TEntity entity) { _db.Set<TEntity>().Add(entity); } public void DeleteById(object Id) { var obj = _db.Set<TEntity>().Find(Id); if (obj != null) _db.Set<TEntity>().Remove(obj); } public TEntity Find(object Id) { var obj = _db.Set<TEntity>().Find(Id); _db.Entry(obj).State = EntityState.Detached; return obj; } public IEnumerable<TEntity> GetAll() { return _db.Set<TEntity>().ToList(); } public void Update(TEntity entity) { _db.Set<TEntity>().Update(entity); } } }
using UnityEngine; using System.Collections; public enum EvalState { PERFECT, GREAT, GOOD, MISS } public class CEvalQuoteCtrl : CFollowCtrl { private UIWidget _widget; private Transform _tr; private bool _isReset; private float _time; private string _perfectText; private string _greatText; private string _goodText; private string _missText; private Color _yellowColor; private Color _whiteColor; private Color _redColor; public float Duration; public UISprite QuoteSprite; public UILabel QuoteLabel; public override void Start() { base.Start(); _time = 0f; _perfectText = Localization.Get("Perfect") + "!"; _greatText = Localization.Get("Great") + "!"; _goodText = Localization.Get("Good") + "!"; _missText = Localization.Get("Miss") + "!"; _yellowColor = new Color(255f / 255f, 255f / 255f, 153f / 255f, 255f / 255f); _whiteColor = new Color(255f / 255f, 255f / 255f, 255f / 255f, 255f / 255f); _redColor = new Color(255f / 255f, 153f / 255f, 153f / 255f, 255f / 255f); _widget = GetComponent<UIWidget>(); _widget.alpha = 0f; _tr = transform; } public override void Update() { //Debug.Log("Target.Pos : " + Target.transform.position); //base.Update(); HandleDuration(); } public override void Follow() { base.Follow(); } void HandleDuration() { _time += Time.smoothDeltaTime; if (_time > Duration) { _widget.alpha = 0f; } } void FollowPivot() { _tr.position = Target.position; } public void ResetQuote(EvalState state) { Debug.Log("State : " + state); switch (state) { case EvalState.PERFECT: Debug.Log("Perfect"); QuoteSprite.color = _yellowColor; QuoteLabel.text = _perfectText; break; case EvalState.GREAT: Debug.Log("Great"); QuoteSprite.color = _whiteColor; QuoteLabel.text = _greatText; break; case EvalState.GOOD: Debug.Log("Good"); QuoteSprite.color = _whiteColor; QuoteLabel.text = _goodText; break; case EvalState.MISS: Debug.Log("Miss"); QuoteSprite.color = _redColor; QuoteLabel.text = _missText; break; default: break; } _widget.alpha = 1f; //Debug.Log("_time : " + _time); _time = 0f; //Debug.Log("_time : " + _time); } }
using UnityAtoms.BaseAtoms; using UnityEngine; using UnityEngine.InputSystem; namespace UnityAtoms.InputSystem { public class CallbackContextInterpreter<T, P, C, V, E1, E2, F, VI> : BaseAtom where T : struct where P : struct, IPair<T> where C : AtomBaseVariable<T> where V : AtomVariable<T, P, E1, E2, F> where E1 : AtomEvent<T> where E2 : AtomEvent<P> where F : AtomFunction<T, T> where VI : AtomVariableInstancer<V, P, T, E1, E2, F> { [SerializeField] private E1 _started; [SerializeField] private E1 _performed; [SerializeField] private E1 _canceled; [SerializeField] private E1 _waiting; [SerializeField] private E1 _disabled; [SerializeField] private V _value; [SerializeField] private BoolVariable _valueAsButton; public void Raise(InputAction.CallbackContext context) { var value = context.ReadValue<T>(); switch (context.phase) { case InputActionPhase.Disabled: if (_disabled) { _disabled.Raise(value); } break; case InputActionPhase.Waiting: if (_waiting) { _waiting.Raise(value); } break; case InputActionPhase.Started: if (_started) { _started.Raise(value); } break; case InputActionPhase.Performed: if (_performed) { _performed.Raise(value); } break; case InputActionPhase.Canceled: if (_canceled) { _canceled.Raise(value); } break; } } public void UpdateValues(InputAction.CallbackContext context) { if (_value) { _value.Value = context.ReadValue<T>(); } if (_valueAsButton) { _valueAsButton.Value = context.ReadValueAsButton(); } } public void Interpret(InputAction.CallbackContext context) { Raise(context); UpdateValues(context); } } }
using UnityEngine; using System.Collections; /*This class allows the player to complete the level * once the apple has been chosen */ public class apple : MonoBehaviour { public int waitTime; public GameObject back; //if the game door is not zoomed in on the camera zooms in void OnMouseDown() { if (!GameDoor1.zoomedIn) { zoomIn(); GameDoor1.zoomedIn = true; Instantiate (back); } //if the GameDoor is zoomed in on the player has an opportunity to open the door else if (GameDoor1.zoomedIn) { GameManager.level_1_complete = true; back = GameObject.FindWithTag("back"); Destroy (back); openDoor (); //When the apple is chosen the GameDoor opens which completes the level } } void zoomIn () { // Zoom Camera in Vector3 pos; pos.x = 0; pos.y = 0; pos.z = -3; GameObject player = GameObject.FindWithTag ("Player"); player.transform.position = pos; } void openDoor () //GameDoor opens { GameObject blackDoor = GameObject.FindWithTag ("openDoor"); blackDoor.GetComponent<SpriteRenderer> ().sortingOrder = 5; StartCoroutine (wait ()); } //The player is taken to a "Level Complete" Screen IEnumerator wait () { yield return new WaitForSeconds (waitTime); Application.LoadLevel ("LevelCompletion"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using XH.Domain.Catalogs.Models; using XH.Infrastructure.Mapper; using XH.Queries.Categories.Dtos; namespace XH.Query.Handlers.Configs { public class CategoriesMapperRegistrar : IAutoMapperRegistrar { public void Register(IMapperConfigurationExpression cfg) { cfg.CreateMap<Category, CategoryDto>(); cfg.CreateMap<Category, CategoryOverviewDto>(); cfg.CreateMap<CategoryOverviewDto, CategoriesTreeNode>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PropositionalFormulaProver.Prover; namespace PropositionalFormulaProver.Prover.Node { public class Supset : INode { INode left; INode right; string symbol = @"\supset "; public Supset(INode right, INode left) { this.left = left; this.right = right; } public string getDebugString() { return "(" + this.left.getDebugString() + this.symbol + this.right.getDebugString() + ")"; } public string getString() => getChildString(left) + this.symbol + getChildString(right); public INode getLeft() => this.left; public INode getRight() => this.right; public INode deepCopy() => new Supset(this.left.deepCopy(), this.right.deepCopy()); private string getChildString(INode node) { string ret = ""; if (isLowerChild(node)) ret = node.getString(); else ret = "(" + node.getString() + ")"; return ret; } private bool isLowerChild(INode node) => node is Atom || node is Negation || node is Conjunction || node is Disjunction; } }