text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] Transform playerCamera = null;
[SerializeField] float mouseSensitivity = 3.5f;
[SerializeField] float walkSpeed = 15.0f;
[SerializeField] float sprintSpeed = 30.0f;
[SerializeField] float jumpHeight= 3.0f;
[SerializeField] float gravity = -40.0f;
[SerializeField] [Range(0.0f, 0.5f)] float moveSmoothTime = 0.1f;
[SerializeField] bool lockCursor = true;
float cameraPitch = 0.0f;
float velocityY = 0.0f;
CharacterController controller = null;
Vector2 currentDir = Vector2.zero;
Vector2 currentDirVelocity = Vector2.zero;
AudioSource audioSrc;
bool isMoving;
public InteractionInputData interactionInputData;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
audioSrc = GetComponent<AudioSource>();
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
interactionInputData.Reset();
}
// Update is called once per frame
void Update()
{
UpdateMouseLook();
UpdateMovement();
UpdateInteraction();
}
void UpdateMouseLook()
{
Vector2 MouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
cameraPitch -= MouseDelta.y * mouseSensitivity;
cameraPitch = Mathf.Clamp(cameraPitch, -90.0f, 90.0f);
playerCamera.localEulerAngles = Vector3.right * cameraPitch;
transform.Rotate(Vector3.up * MouseDelta.x * mouseSensitivity);
}
void UpdateMovement()
{
Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
targetDir.Normalize();
currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);
if (controller.isGrounded)
{
velocityY = 0.0f;
if (Input.GetButtonDown("Jump"))
velocityY = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocityY += gravity * Time.deltaTime;
Vector3 velocity = (transform.forward * currentDir.y + transform.right * currentDir.x);
if (controller.velocity.x != 0 || controller.velocity.z != 0){
isMoving = true;
} else{
isMoving = false;
}
if(isMoving){
if(!audioSrc.isPlaying){
audioSrc.Play();
}
}else{
audioSrc.Stop();
}
if (Input.GetKey(KeyCode.LeftShift))
{
velocity = velocity * sprintSpeed + Vector3.up * velocityY;
}
else
{
velocity = velocity * walkSpeed + Vector3.up * velocityY;
}
controller.Move(velocity * Time.deltaTime);
}
void UpdateInteraction()
{
interactionInputData.InteractedClicked = Input.GetKeyDown(KeyCode.E);
interactionInputData.InteractedRelease = Input.GetKeyUp(KeyCode.E);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestNameSpace
{
class StructTest
{
}
struct point1
{
public double x;
public double y;
public point1(int x, int y)
{
this.x = x;
this.y = y;
}
public string show()
{
Console.WriteLine(x + "," + y);
return x + "," + y;
}
}
}
|
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Apprentices.ChangeEmployer
{
public class GetInformRequest : IGetApiRequest
{
public long ProviderId { get; }
public long ApprenticeshipId { get; set; }
public GetInformRequest(long providerId, long apprenticeshipId)
{
ProviderId = providerId;
ApprenticeshipId = apprenticeshipId;
}
public string GetUrl => $"provider/{ProviderId}/apprentices/{ApprenticeshipId}/change-employer/inform";
}
public class GetInformResponse
{
public string LegalEntityName { get; set; }
}
}
|
using Game.World;
using UnityEngine;
public class CharacterShoot : CharacterAbility {
[SerializeField] protected Bullet _bulletPrefab;
[SerializeField] protected float _cooldown = 1;
[SerializeField] protected Transform _spawnPositionLeft;
[SerializeField] protected Transform _spawnPositionRight;
[SerializeField] protected Transform _spawnPositionUp;
[SerializeField] protected AudioClip _shootAudioClip;
private float _lastShootTime { get; set; } = -100;
protected override void PlayAbility(bool keyDown) {
if (!keyDown) return;
if (_lastShootTime + _cooldown > Time.time) return;
if (animator.gripped) Instantiate(_bulletPrefab, _spawnPositionUp.position, Quaternion.identity, null).movementVector = Vector3.up;
else if (animator.faceLeft) Instantiate(_bulletPrefab, _spawnPositionLeft.position, Quaternion.identity, null).movementVector = Vector3.left;
else Instantiate(_bulletPrefab, _spawnPositionRight.position, Quaternion.identity, null).movementVector = Vector3.right;
_lastShootTime = Time.time;
animator.SetShoot();
AudioManager.Sfx.Play(_shootAudioClip);
}
} |
using System;
using Evernote.EDAM.Type;
using EvernoteSDK;
using EvernoteSDK.Advanced;
namespace En
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
ENSessionAdvanced.SetSharedSessionConsumerKey("your key", "your secret");
ENNoteStoreClient PrimaryNoteStore;
ENNoteStoreClient BusinessNoteStore;
//static ENNoteStoreClient NoteStoreForLinkedNotebook(linkedNotebook);
//LinkedNotebook linkedNotebook = (LinkedNotebook)Preferences.ObjectForKey(ENSessionPreferencesLinkedAppNotebook);
// First create the ENML content for the note.
ENMLWriter writer = new ENMLWriter();
writer.WriteStartDocument();
writer.WriteString("Hello again, world.");
writer.WriteEndDocument();
// Create a note locally.
Note myNote = new Note();
myNote.Title = "Sample note from the Advanced world";
myNote.Content = writer.Contents.ToString();
// Create the note in the service, in the user's personal, default notebook.
ENNoteStoreClient store = ENSessionAdvanced.SharedSession.PrimaryNoteStore;
Note resultNote = store.CreateNote(myNote);
//myNoteAdv.EdamAttributes["ReminderOrder"] = DateTime.Now.ToEdamTimestamp();
DateTime noteCreatedOn = myNote.Created.ToDateTime();
}
}
}
|
using System;
using System.Collections;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.HighLevel.GameEngine2D;
using Sce.PlayStation.HighLevel.GameEngine2D.Base;
namespace ShootingApp
{
public enum BulletType
{ Single, Line, Circle, Spiral,
SingleUp, LineUp, CircleUp, SpiralUp,
SingleDown, LineDown, CircleDown, SpiralDown,
SingleAimed, LineAimed, CircleAimed,
Boss
}
/// <summary>
/// 1つの弾丸を管理するクラス
/// </summary>
public class Bullet1
{
public float X,Y; // 発射地点の座標
public float DX,DY; // 飛ばす方向
public SpriteUV Sprite;
public Bullet1(float x,float y, float dx, float dy){
X = x; Y = y; DX = dx; DY = dy;
}
}
/// <summary>
/// 自機から発射された弾丸をまとめて管理するクラス
/// </summary>
public static class MyBullet
{
public static ArrayList BulletList; // 弾丸を登録するArrayList
private static Texture2D Texture;
private static TextureInfo TextureInfo;
public static void InitMyBullet(){
BulletList = new ArrayList();
Texture = new Texture2D("Application/resourses/arrow.gif", false);
TextureInfo = new TextureInfo(Texture);
}
/// <summary>
/// 新たに弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置のx座標
/// </param>
/// <param name='y'>
/// 初期位置のy座標
/// </param>
/// <param name='dx'>
/// x方向の速度
/// </param>
/// <param name='dy'>
/// y方向の速度
/// </param>
public static void MakeNewBullet(float x, float y, float dx, float dy){
var newBullet = new Bullet1(x,y,dx,dy);
newBullet.Sprite = new SpriteUV(){TextureInfo = TextureInfo};
newBullet.Sprite.Quad.S = TextureInfo.TextureSizef;
newBullet.Sprite.CenterSprite();
newBullet.Sprite.Position = new Sce.PlayStation.Core.Vector2(x,y);
BulletList.Add(newBullet);
Scenes.sceneOnGame.AddChild(((Bullet1)BulletList[BulletList.Count-1]).Sprite);
}
/// <summary>
/// 弾丸の位置を更新する
/// </summary>
/// <param name='bl'>
/// Bullet1
/// </param>
public static void Update(Bullet1 bl){
var newblPosition = new Vector2(bl.Sprite.Position.X,bl.Sprite.Position.Y);
newblPosition += new Vector2(bl.DX,bl.DY);
bl.Sprite.RunAction(new MoveTo(newblPosition,0.0f));
}
/// <summary>
/// 弾丸を削除する
/// </summary>
/// <param name='bl'>
/// Bullet1
/// </param>
public static void RemoveBullet(Bullet1 bl){
bl.Sprite.RemoveAllChildren(true);
Scenes.sceneOnGame.RemoveChild(bl.Sprite,true);
BulletList.Remove(bl);
}
public static void TextureDispose(){
Texture.Dispose();
TextureInfo.Dispose();
}
}
/// <summary>
/// 敵の弾丸をまとめて管理するクラス
/// </summary>
public static class EnemyBullet
{
public static ArrayList BulletList; // 弾丸を登録するArrayList
private static Texture2D[] BulletTexture;
private static TextureInfo[] BulletTextureInfo;
public static void InitEnemyBullet(){
BulletList = new ArrayList();
BulletTexture = new Texture2D[4];
BulletTextureInfo = new TextureInfo[4];
var image2 = new Image("/Application/resourses/Bullet01_16x16.png");
var image20 = image2.Crop(new ImageRect(0,0,16,16));
var image21 = image2.Crop(new ImageRect(0,16,16,16));
var image22 = image2.Crop(new ImageRect(0,32,16,16));
var image23 = image2.Crop(new ImageRect(0,48,16,16));
BulletTexture[0] = Convert.CreateTextureFromImage(image20);
BulletTextureInfo[0] = new TextureInfo(BulletTexture[0]);
BulletTexture[1] = Convert.CreateTextureFromImage(image21);
BulletTextureInfo[1] = new TextureInfo(BulletTexture[1]);
BulletTexture[2] = Convert.CreateTextureFromImage(image22);
BulletTextureInfo[2] = new TextureInfo(BulletTexture[2]);
BulletTexture[3] = Convert.CreateTextureFromImage(image23);
BulletTextureInfo[3] = new TextureInfo(BulletTexture[3]);
image2.Dispose();
image20.Dispose();
image21.Dispose();
image22.Dispose();
image23.Dispose();
}
public static void TextureDispose(){
foreach(Texture2D texture in BulletTexture)
texture.Dispose();
foreach(TextureInfo textureInfo in BulletTextureInfo)
textureInfo.Dispose();
}
/// <summary>
/// 単品の弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置
/// </param>
/// <param name='y'>
/// 初期位置
/// </param>
/// <param name='dx'>
/// フレームあたり変化量
/// </param>
/// <param name='dy'>
/// フレームあたり変化量
/// </param>
public static void MakeSingleBullet(float x, float y, float dx, float dy){
NewBullet(BulletType.Single,x,y,dx,dy);
}
/// <summary>
/// 縦に並んだ弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置(中心座標)
/// </param>
/// <param name='y'>
/// 初期位置(中心座標)
/// </param>
/// <param name='n'>
/// 個数
/// </param>
/// <param name='interval'>
/// 弾丸と弾丸の間[pixel]
/// </param>
/// <param name='dx'>
/// フレームあたり変化量
/// </param>
/// <param name='dy'>
/// フレームあたり変化量
/// </param>
public static void MakeLineBullets(float x, float y, int n, int interval, float dx, float dy){
NewBullet(BulletType.Line,x,y,dx,dy);
for(int i = 1; i < n; i++){
NewBullet(BulletType.Line,x,y+i*interval,dx,dy);
NewBullet(BulletType.Line,x,y+i*interval*(-1),dx,dy);
}
}
/// <summary>
/// 放射状に広がる弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置
/// </param>
/// <param name='y'>
/// 初期位置
/// </param>
/// <param name='n'>
/// 円を構成する弾丸の個数
/// </param>
/// <param name='dr'>
/// フレームあたり変化する半径
/// </param>
public static void MakeCircleBullets(float x, float y, int n, float dr){
for(int i = 0;i < n; i++){
NewBullet(BulletType.Circle,x,y,dr*FMath.Cos(FMath.DegToRad * (360/n*i)),dr*FMath.Sin(FMath.DegToRad * (360/n*i)));
}
}
/// <summary>
/// 自機狙い円形の弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置
/// </param>
/// <param name='y'>
/// 初期位置
/// </param>
/// <param name='n'>
/// 個数
/// </param>
/// <param name='r'>
/// 半径
/// </param>
/// <param name='dx'>
/// フレームあたり変化量
/// </param>
/// <param name='dy'>
/// フレームあたり変化量
/// </param>
public static void MakeDirectionCircleBullets(float x, float y, int n, float r, float dx, float dy){
for(int i = 0;i < n; i++){
NewBullet(BulletType.Circle,x+r*FMath.Cos(FMath.DegToRad * (360/n*i)),y+r*FMath.Sin(FMath.DegToRad * (360/n*i)),dx,dy);
}
}
/// <summary>
/// 螺旋状に広がる弾丸を生成
/// </summary>
/// <param name='x'>
/// 初期位置
/// </param>
/// <param name='y'>
/// 初期位置
/// </param>
/// <param name='n'>
/// 1周の個数
/// </param>
/// <param name='times'>
/// 何周するか
/// </param>
public static void MakeSpiralBullets(float x, float y, int n, int times){
for(int i = 0;i < n * times; i++){
NewBullet(BulletType.Spiral,x,y,(float)(i+n/3)/n*FMath.Cos(FMath.DegToRad * (360/n*i)),(float)(i+n/3)/n*FMath.Sin(FMath.DegToRad * (360/n*i)));
}
}
/// <summary>
/// 弾丸1つ生成
/// </summary>
/// <param name='type'>
/// 弾丸タイプ
/// </param>
/// <param name='x'>
/// 初期位置
/// </param>
/// <param name='y'>
/// 初期位置
/// </param>
/// <param name='dx'>
/// フレームあたり変化量
/// </param>
/// <param name='dy'>
/// フレームあたり変化量
/// </param>
private static void NewBullet(BulletType type, float x, float y, float dx, float dy){
var newBullet = new Bullet1(x,y,dx,dy);
newBullet.Sprite = new SpriteUV(){TextureInfo = BulletTextureInfo[(int)type]};
newBullet.Sprite.Quad.S = BulletTextureInfo[(int)type].TextureSizef;
newBullet.Sprite.CenterSprite();
newBullet.Sprite.Position = new Sce.PlayStation.Core.Vector2(x,y);
BulletList.Add(newBullet);
Scenes.sceneOnGame.AddChild(((Bullet1)BulletList[BulletList.Count-1]).Sprite);
}
/// <summary>
/// 弾丸の位置を更新
/// </summary>
/// <param name='bl'>
/// 更新する弾丸
/// </param>
public static void Update(Bullet1 bl){
var newblPosition = new Vector2(bl.Sprite.Position.X,bl.Sprite.Position.Y);
newblPosition += new Vector2(bl.DX,bl.DY);
bl.Sprite.RunAction(new MoveTo(newblPosition,0.0f));
}
/// <summary>
/// 弾丸を削除する
/// </summary>
/// <param name='bl'>
/// 削除する弾丸
/// </param>
public static void RemoveBullet(Bullet1 bl){
bl.Sprite.RemoveAllChildren(true);
Scenes.sceneOnGame.RemoveChild(bl.Sprite,true);
BulletList.Remove(bl);
}
/// <summary>
/// 敵弾丸リストに登録されている弾丸を自機弾丸リストに移動
/// </summary>
/// <param name='myShipSpritePosition'>
/// 自機の位置
/// </param>
public static void moveToMyBulletList(Vector2 myShipSpritePosition){
foreach(Bullet1 bl in BulletList){
var newDirectionVector = Vector2.Normalize(bl.Sprite.Position - myShipSpritePosition) * 2;
bl.DX = newDirectionVector.X;
bl.DY = newDirectionVector.Y;
MyBullet.BulletList.Add(bl);
}
BulletList.Clear();
}
}
}
|
namespace Shouter.Web.Views.Users
{
using System.IO;
using SimpleMVC.Interfaces;
public class Register : IRenderable
{
public string Render()
{
return File.ReadAllText(Constants.ContantPath + "register.html");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Domain.ValueObject;
using EBS.Infrastructure.Extension;
namespace EBS.Query.DTO
{
public class SaleOrderDto
{
public int Id { get; set; }
public string Code { get; set; }
public string StoreName { get; set; }
public int PosId { get; set; }
public OrderType OrderType { get; set; }
public string OrderTypeName { get {
return OrderType.Description();
} }
public SaleOrderStatus Status { get; set; }
public string StatusName {
get {
return Status.Description();
}
}
public string OrderLevelName
{
get
{
return OrderLevel.Description();
}
}
public SaleOrderLevel OrderLevel { get; set; }
public decimal OrderAmount { get; set; }
public decimal PayAmount { get; set; }
public decimal OnlinePayAmount { get; set; }
public PaymentWay PaymentWay { get; set; }
public string PaymentWayName {
get {
return PaymentWay.Description();
}
}
public string UpdatedOn { get; set; }
public string PaidDate { get; set; }
/// <summary>
/// 收银员
/// </summary>
public string NickName { get; set; }
public List<SaleOrderItemDto> Items { get; set; }
}
}
|
using MongoDb.CarPark.Entities.Concrete;
namespace MongoDb.CarPark.DataAccess.Abstract
{
public interface ISerieRepository : IRepository<Serie, string>
{
}
}
|
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace CODE.Framework.Wpf.Mvvm
{
/// <summary>
/// Grid UI element that is automatically made visible and invisible depending on whether the current model implements IModelStatus
/// </summary>
public class ModelStatusGrid : Grid
{
/// <summary>
/// Model used as the data context
/// </summary>
public object Model
{
get { return GetValue(ModelProperty); }
set { SetValue(ModelProperty, value); }
}
/// <summary>
/// Model dependency property
/// </summary>
public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof (object), typeof (ModelStatusGrid), new UIPropertyMetadata(null, ModelChanged));
/// <summary>
/// Change handler for model property
/// </summary>
/// <param name="d">The dependency object that triggered this change.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as ModelStatusGrid;
if (grid != null)
{
grid.Visibility = Visibility.Visible;
var ms = e.NewValue as IModelStatus;
if (ms != null)
{
grid.ModelStatus = ms.ModelStatus;
var ms2 = ms as INotifyPropertyChanged;
if (ms2 != null)
ms2.PropertyChanged += (s2, e2) =>
{
if (string.IsNullOrEmpty(e2.PropertyName) || e2.PropertyName == "ModelStatus")
grid.ModelStatus = ms.ModelStatus;
};
}
else
grid.Visibility = Visibility.Collapsed;
}
}
/// <summary>Indicates the model status of the bound model object</summary>
public ModelStatus ModelStatus
{
get { return (ModelStatus) GetValue(ModelStatusProperty); }
set { SetValue(ModelStatusProperty, value); }
}
/// <summary>Indicates the model status of the bound model object</summary>
public static readonly DependencyProperty ModelStatusProperty = DependencyProperty.Register("ModelStatus", typeof(ModelStatus), typeof(ModelStatusGrid), new UIPropertyMetadata(ModelStatus.Unknown));
}
/// <summary>
/// Converts a model status to visibility
/// </summary>
public class ModelStatusToVisibleConverter : IValueConverter
{
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ModelStatus)
{
var status = (ModelStatus) value;
if (status == ModelStatus.Loading || status == ModelStatus.Saving) return Visibility.Visible;
return Visibility.Collapsed;
}
return Visibility.Collapsed;
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ModelStatus.Unknown; // Not really using this
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace DatingApp.API.Model
{
public partial class DatingAppContext : DbContext
{
public DatingAppContext()
{
}
public DatingAppContext(DbContextOptions<DatingAppContext> options)
: base(options)
{
}
public virtual DbSet<Likes> Likes { get; set; }
public virtual DbSet<Message> Message { get; set; }
public virtual DbSet<Photo> Photo { get; set; }
public virtual DbSet<Users> Users { get; set; }
public virtual DbSet<Value> Value { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=localhost;Database=DatingApp;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.2-servicing-10034");
modelBuilder.Entity<Likes>(entity =>
{
entity.HasOne(d => d.Likee)
.WithMany(p => p.LikesLikee)
.HasForeignKey(d => d.LikeeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_LikeeId");
entity.HasOne(d => d.Liker)
.WithMany(p => p.LikesLiker)
.HasForeignKey(d => d.LikerId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_likerId");
});
modelBuilder.Entity<Message>(entity =>
{
entity.Property(e => e.Content).IsUnicode(false);
entity.Property(e => e.DateRead).HasColumnType("datetime");
entity.Property(e => e.IsRead)
.IsRequired()
.HasDefaultValueSql("('false')");
entity.Property(e => e.MessageSent)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
entity.Property(e => e.RecipientDeleted)
.IsRequired()
.HasDefaultValueSql("('false')");
entity.Property(e => e.SenderDeleted)
.IsRequired()
.HasDefaultValueSql("('false')");
entity.HasOne(d => d.Recipient)
.WithMany(p => p.MessageRecipient)
.HasForeignKey(d => d.RecipientId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_RecipientId");
entity.HasOne(d => d.Sender)
.WithMany(p => p.MessageSender)
.HasForeignKey(d => d.SenderId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_SenderId");
});
modelBuilder.Entity<Photo>(entity =>
{
entity.Property(e => e.DateAdded).HasColumnType("datetime");
entity.Property(e => e.Description).IsUnicode(false);
entity.Property(e => e.PublicId)
.HasColumnName("PublicID")
.IsUnicode(false);
entity.Property(e => e.Url).IsUnicode(false);
entity.HasOne(d => d.User)
.WithMany(p => p.Photo)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_UserId");
});
modelBuilder.Entity<Users>(entity =>
{
entity.Property(e => e.City)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.Country)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.Created).HasColumnType("datetime");
entity.Property(e => e.DateOfBirth).HasColumnType("datetime");
entity.Property(e => e.Gender)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.Interests)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.Introduction).IsUnicode(false);
entity.Property(e => e.KnownAs)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.LastActive).HasColumnType("datetime");
entity.Property(e => e.LookingFor)
.HasMaxLength(128)
.IsUnicode(false);
entity.Property(e => e.Username)
.HasMaxLength(128)
.IsUnicode(false);
});
modelBuilder.Entity<Value>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.Name).IsUnicode(false);
});
}
}
}
|
using DataAccess;
using Microsoft.Extensions.DependencyInjection;
using Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Services.Users
{
public interface IUserService
{
Task<User> Authenticate(string username, string password);
}
public class UserService : IUserService
{
private readonly IServiceProvider _provider;
// Constructor
public UserService(IServiceProvider provider)
{
_provider = provider;
}
/// <summary>
/// Authenticate user
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns>Task<User></returns>
public async Task<User> Authenticate(string username, string password)
{
using (var scope = _provider.CreateScope())
{
var service = scope.ServiceProvider.GetService<DatabaseContext>();
var user = await Task.Run(() => service.Users.SingleOrDefault(x => x.Username == username && x.Password == password));
// return null if user not found
if (user == null)
return null;
// authentication successful, return user details without password
user.Password = null;
return user;
}
}
}
}
|
using Microsoft.AspNet.SignalR;
namespace Uintra.Features.Notification
{
[Authorize]
public class UintraHub : Hub
{
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Products
{
public abstract class Product
{
public int ProductID { get; set; }
public string BrandName { get; set; }
public string ProductName { get; set; }
public string Department { get; set; }
public string Size { get; set; }
public double Price { get; set; }
public void Print()
{
Console.WriteLine($" Product Id: {ProductID} BrandName: {BrandName}, ProductName: {ProductName}, Department: {Department}, Size: {Size} Price: {Price} ");
}
}
}
|
using System;
using HandlingException.HelperClass;
namespace HandlingException
{
public static class Demo3
{
public static void Run()
{
/*
MESSAGE:
Attempted to divide by zero.
STACK TRACE:
at HandlingException.HelperClass.Arithmetic.Division(Int32 numerator, Int32 denominator) in C:\...\Modul01 - Exception Handling\HandlingException\HelperClass\Aritmethic.cs:line 16
RETURN VALUE:
Hasil: 0
*/
// ArithmeticA arithmeticA = new ArithmeticA();
// int resultA = arithmeticA.GetResult(20, 0);
// Console.WriteLine($"Hasil: {resultA}");
/*
MESSAGE:
Attempted to divide by zero.
STACK TRACE:
at HandlingException.HelperClass.ArithmeticB.Division(Int32 numerator, Int32 denominator) in C:\...\Modul01 - Exception Handling\HandlingException\HelperClass\ArithemticB.cs:line 14
at HandlingException.HelperClass.ArithmeticB.GetResult(Int32 x, Int32 y) in C:\...\Modul01 - Exception Handling\HandlingException\HelperClass\ArithemticB.cs:line 9
at HandlingException.Demo3.Run() in C:\...\Modul01 - Exception Handling\HandlingException\Demo3.cs:line 37
*/
try
{
ArithmeticB arithmeticB = new ArithmeticB();
int resultB = arithmeticB.GetResult(20, 0);
Console.WriteLine($"Result: {resultB}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Win32;
using Appnotics.PCBackupLib;
using Appnotics.Library.UI.Helpers;
using Appnotics.PCBackupLib.Helpers;
using Appnotics.Library.UI.UserControls;
namespace Appnotics.PCBackup
{
public enum BackupPages
{
Status = 1,
Setup,
Logs,
Schedule
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class PCBackupUI : Window, INotifyPropertyChanged
{
BackgroundWorker uiUpdateWorker = new BackgroundWorker();
BackupStatus backupStatus = null;
Schedule selectedSchedule = null;
WCFClientHost clientHost;
LogSummaryCollection logSummaries;
Logger logger = new Logger();
Schedules schedules;
public bool HasFolders { get; set; } = false;
public BackupConfig BackupConfig { get; private set; }
public static PCBackupUI UIWindow { get; private set; } = null;
private BackupPages currentPage = BackupPages.Status;
public BackupPages CurrentPage
{
get { return currentPage; }
set
{
if (value == currentPage)
return;
currentPage = value;
OnPropertyChanged("StatusPageActive");
OnPropertyChanged("SetupPageActive");
OnPropertyChanged("SchedulePageActive");
OnPropertyChanged("LogsPageActive");
if (LogsPageActive)
LoadLogView();
else
LogViewActive = false;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public bool StatusPageActive => (CurrentPage == BackupPages.Status);
public bool SetupPageActive => (CurrentPage == BackupPages.Setup);
public bool SchedulePageActive => (CurrentPage == BackupPages.Schedule);
public bool LogsPageActive => (CurrentPage == BackupPages.Logs);
public bool CanSave
{
get { return (IsSourceValid && IsDirty && IsDestinationValid); }
}
public bool CanRun
{
get
{
return (IsSourceValid &&
IsDestinationValid &&
(((backupStatus != null) && (backupStatus.RunState == RunState.Ready)) ||
((backupStatus == null) && (clientHost.IsRegisteredNotification))));
}
}
private bool isSourceValid = false;
public bool IsSourceValid
{
get { return isSourceValid; }
set
{
isSourceValid = value;
OnPropertyChanged("IsSourceValid");
OnPropertyChanged("CanSave");
OnPropertyChanged("CanRun");
}
}
private bool isDestinationValid = false;
public bool IsDestinationValid
{
get { return isDestinationValid; }
set
{
isDestinationValid = value;
OnPropertyChanged("IsDestinationValid");
OnPropertyChanged("CanSave");
OnPropertyChanged("CanRun");
}
}
private bool isDirty = false;
public bool IsDirty
{
get { return isDirty; }
set
{
isDirty = value;
OnPropertyChanged("IsDirty");
OnPropertyChanged("CanSave");
}
}
private bool logViewActive = false;
public bool LogViewActive
{
get { return logViewActive; }
set
{
logViewActive = value;
if (logViewActive == false)
LogInfo.Text = "";
OnPropertyChanged("LogViewActive");
}
}
public PCBackupUI()
{
InitializeComponent();
UIWindow = this;
BackupConfig = new BackupConfig();
clientHost = new WCFClientHost(DisplayMessage);
DataContext = this;
InitSchedules();
InitUI();
InitEventHandlers();
DialogHelper.SetDialogPosition(this, Properties.Settings.Default.PositionMainWindow);
}
private void DisplayMessage(string message)
{
StatusDisplay.Text = message;
}
private void InitSchedules()
{
schedules = SchedulesLoader.Load();
}
private bool Initialising = false;
private readonly object _dummyNode = null;
private void InitUI()
{
Initialising = true;
Title = Properties.Resources.TitleApp;
comboCopyType.Items.Add(BackupType.Copy.ToName());
comboCopyType.Items.Add(BackupType.Mirror.ToName());
comboCopyType.Items.Add(BackupType.Sync.ToName());
comboCopyType.SelectedIndex = 0;
comboCopyType.SelectionChanged += OnCopyTypeSelectionChanged;
comboOverwriteType.Items.Add(OverwriteType.Never.ToName());
comboOverwriteType.Items.Add(OverwriteType.Always.ToName());
comboOverwriteType.Items.Add(OverwriteType.OlderOnly.ToName());
comboOverwriteType.SelectedIndex = 0;
InitTreeView();
// progress tab
CancelButton.IsEnabled = false;
// RunButton.IsEnabled = false;
// SaveButton.IsEnabled = false;
// progressBar.Value = 0;
// logs tab
logSummaries = new LogSummaryCollection();
LogGrid.ItemsSource = logSummaries;
LogGrid.DataContext = this;
ScheduleGrid.ItemsSource = schedules.ScheduleList;
ScheduleGrid.DataContext = this;
DeleteScheduleButton.IsEnabled = false;
EditScheduleButton.IsEnabled = false;
DeleteLogButton.IsEnabled = false;
ViewLogButton.IsEnabled = false;
Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new EventSetter(DataGridRow.MouseDoubleClickEvent,
new MouseButtonEventHandler(LogsRowDoubleClick)));
LogGrid.RowStyle = rowStyle;
Initialising = false;
uiUpdateWorker = new BackgroundWorker()
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = false
};
uiUpdateWorker.ProgressChanged += UiUpdateWorker_ProgressChanged;
uiUpdateWorker.DoWork += UiUpdateWorker_DoWork;
uiUpdateWorker.RunWorkerAsync();
}
int uiUpdateWorkerSleepTime = 3000;
bool uiUpdateWorkerNeedsUpdate = false;
private void UiUpdateWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (1 == 1)
{
Thread.Sleep(uiUpdateWorkerSleepTime);
if (uiUpdateWorkerNeedsUpdate)
{
uiUpdateWorker.ReportProgress(0);
}
}
}
private void UiUpdateWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
UpdateUI();
if (backupStatus.RunState == RunState.Running)
uiUpdateWorkerSleepTime = 100;
else
uiUpdateWorkerSleepTime = 3000;
}
private void InitTreeView()
{
foldersTree.Items.Clear();
for (char d = 'A'; d <= 'Z'; d++)
{
string folder = d + ":\\";
if (Directory.Exists(folder))
{
CheckBox cb = new CheckBox();
TreeViewItem item = new TreeViewItem()
{
Tag = folder,
Header = cb
};
cb.Content = folder;
cb.Tag = item;
cb.Click += OnClickCheckbox;
item.Tag = folder;
item.Items.Add(_dummyNode);
item.Expanded += OnFolderExpanded;
foldersTree.Items.Add(item);
}
}
}
void OnFolderExpanded(object sender, RoutedEventArgs e)
{
TreeViewItem item = (TreeViewItem)sender;
// if the only item is the dummy node
if (item.Items.Count == 1 && item.Items[0] == _dummyNode)
{
// get rid of the dummy
item.Items.Clear();
try
{
// find out if it's checked
CheckBox cbi = item.Header as CheckBox;
bool? cbChecked = cbi.IsChecked;
// then get all the subdiretories
foreach (string dir in Directory.GetDirectories(item.Tag as string))
{
TreeViewItem subitem = new TreeViewItem();
DirectoryInfo di = new DirectoryInfo(dir);
subitem.Tag = di.FullName;
CheckBox cb = new CheckBox();
if (cbChecked == null)
{
if (ContainsFolder(di.FullName))
cb.IsChecked = true;
else if (ContainsFolderPart(di.FullName))
cb.IsChecked = null;
else
cb.IsChecked = false;
}
else
cb.IsChecked = cbChecked;
cb.Tag = subitem;
cb.Click += OnClickCheckbox;
cb.Content = di.Name;
subitem.Header = cb;
subitem.Tag = dir;
subitem.Items.Add(_dummyNode);
subitem.Expanded += OnFolderExpanded;
item.Items.Add(subitem);
}
}
catch (Exception) { }
}
}
private void OnClickCheckbox(object sender, RoutedEventArgs e)
{
CheckBox clickedCb = sender as CheckBox;
TreeViewItem clickedItem = clickedCb.Tag as TreeViewItem;
string di = clickedItem.Tag as string;
Debug.WriteLine(di);
SelectAllChildren(clickedItem, clickedCb.IsChecked);
CheckParent(clickedItem);
UpdateBackup();
GetAllUpdateFolders();
SetButtonStatus();
}
private void SelectAllChildren(TreeViewItem tvi, bool? select)
{
foreach (object o in tvi.Items)
{
if (o is TreeViewItem)
{
TreeViewItem childItem = o as TreeViewItem;
CheckBox cb = childItem.Header as CheckBox;
cb.IsChecked = select;
SelectAllChildren(childItem, select);
}
}
}
private void CheckParent(TreeViewItem tviChild)
{
if (tviChild.Parent is TreeViewItem tvi)
{
CheckBox cbParent = tvi.Header as CheckBox;
bool allChecked = true;
bool someChecked = false;
foreach (object o in tvi.Items)
{
if (o is TreeViewItem)
{
TreeViewItem childItem = o as TreeViewItem;
CheckBox cb = childItem.Header as CheckBox;
if (cb.IsChecked != false)
someChecked = true;
else
allChecked = false;
}
}
if (allChecked)
cbParent.IsChecked = true;
else if (someChecked == false)
cbParent.IsChecked = false;
else
cbParent.IsChecked = null;
CheckParent(tvi);
}
}
void OnCopyTypeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (comboCopyType.SelectedIndex == 2)
CopyToButton.Content = Properties.Resources.ButtonSyncWith;
else
CopyToButton.Content = Properties.Resources.ButtonCopyTo;
}
private bool IsFolderInTree(ItemCollection items, string folder)
{
foreach (object o in items)
{
if (o is TreeViewItem)
{
TreeViewItem tvi = o as TreeViewItem;
string folderName = tvi.Tag as string;
if (folderName.ToLower().Equals(folder.ToLower()))
return true;
if (IsFolderInTree(tvi.Items, folder))
return true;
}
return false;
}
return false;
}
private void CheckTree(ItemCollection items)
{
foreach (object o in items)
{
if (o is TreeViewItem)
{
TreeViewItem tvi = o as TreeViewItem;
if (IsItemChecked(tvi))
{
string folder = tvi.Tag as string;
// remove all source folders that contain this
RemoveAnySourceFoldersContainingThisPath(folder);
DirectoryInfo di = new DirectoryInfo(folder);
// then add it
BackupDirectory backupDirectory = new BackupDirectory()
{
path = di.FullName,
name = di.Name
};
//BackupConfig.SourceFolders.Add(backupDirectory);
BackupConfig.SourceFolders.Add(di.FullName);
}
else
{
// if it's not checked, recurse down
CheckTree(tvi.Items);
}
}
}
}
private void RemoveAnySourceFoldersContainingThisPath(string folder)
{
//List<BackupDirectory> directoriesToRemove = new List<BackupDirectory>();
List<string> directoriesToRemove = new List<string>();
//foreach (BackupDirectory sourceFolder in BackupConfig.SourceFolders)
foreach (string sourceFolder in BackupConfig.SourceFolders)
{
if (sourceFolder.ToLower().Contains(folder.ToLower()))
{
// remove this one
Debug.WriteLine("Remove " + sourceFolder);
directoriesToRemove.Add(sourceFolder);
}
}
//foreach (BackupDirectory sourceFolder in directoriesToRemove)
// BackupConfig.SourceFolders.Remove(sourceFolder);
foreach (string sourceFolder in directoriesToRemove)
BackupConfig.SourceFolders.Remove(sourceFolder);
}
private void UpdateBackup()
{
// find all the folders in the backup config and check they are still checked, if they are in the tree
List<string> directoriesToRemove = new List<string>();
foreach (string sourceFolder in BackupConfig.SourceFolders)
{
if (!IsFolderInTree(foldersTree.Items, sourceFolder))
{
// remove this one
Debug.WriteLine("Remove " + sourceFolder);
directoriesToRemove.Add(sourceFolder);
}
}
foreach (string sourceFolder in directoriesToRemove)
BackupConfig.SourceFolders.Remove(sourceFolder);
// then look through the tree and make sure all the checked items are in the backup config
// finally, remove all the folders in the backup config that don't exist
IsDirty = true;
CheckTree(foldersTree.Items);
IsSourceValid = (BackupConfig.SourceFolders.Count > 0);
// RunButton.IsEnabled = canBackup;
// SaveButton.IsEnabled = canBackup;
}
private bool IsItemChecked(TreeViewItem tvi)
{
CheckBox cb = tvi.Header as CheckBox;
return (cb.IsChecked == true);
}
private void InitEventHandlers()
{
Closing += OnClosing;
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
clientHost.TryRegisterServer();
}
void OnClosing(object sender, CancelEventArgs e)
{
Properties.Settings.Default.PositionMainWindow = Left.ToString() + "," + Top.ToString() + "," + ActualWidth.ToString() + "," + ActualHeight.ToString();
Properties.Settings.Default.Save();
// TryDeRegisterServer();
Application.Current.Shutdown();
}
public void ReceivedShutdown()
{
clientHost.IsRegisteredNotification = false;
backupStatus = null;
DisplayMessage("Disconnected from backup engine");
OnPropertyChanged("CanRun");
}
public void UpdateStatus(BackupStatus engineBackupStatus)
{
backupStatus = engineBackupStatus.GetCopy();
uiUpdateWorkerNeedsUpdate = true; // set this here, allow the background worker to pick it up in its own time
}
private void UpdateUI()
{
uiUpdateWorkerNeedsUpdate = false;
if (backupStatus == null)
return;
progressBar.Value = backupStatus.PercentageComplete;
progressBar.Visibility = (progressBar.Value > 0) ? Visibility.Visible : Visibility.Hidden;
currentStatus.Text = backupStatus.StatusMessage;
completedFiles.Text = (backupStatus.FilesCopied > 0) ? StringHelper.ToNiceNumber(backupStatus.FilesCopied) : string.Empty;
skippedFiles.Text = (backupStatus.FilesSkipped > 0) ? StringHelper.ToNiceNumber(backupStatus.FilesSkipped) : string.Empty;
selectedFiles.Text = (backupStatus.FilesSelected > 0) ? StringHelper.ToNiceNumber(backupStatus.FilesSelected) : string.Empty;
failedFiles.Text = (backupStatus.FilesFailed > 0) ? StringHelper.ToNiceNumber(backupStatus.FilesFailed) : string.Empty;
completedBytes.Text = (backupStatus.BytesCopied > 0) ? StringHelper.ToNiceBytes(backupStatus.BytesCopied) : string.Empty;
selectedBytes.Text = (backupStatus.BytesSelected > 0) ? StringHelper.ToNiceBytes(backupStatus.BytesSelected) : string.Empty;
skippedBytes.Text = (backupStatus.BytesSkipped > 0) ? StringHelper.ToNiceBytes(backupStatus.BytesSkipped) : string.Empty;
failedBytes.Text = (backupStatus.BytesFailed > 0) ? StringHelper.ToNiceBytes(backupStatus.BytesFailed) : string.Empty;
// do times
timeElapsed.Text = backupStatus.ElapsedTime;
timeComplete.Text = backupStatus.EndTime;
timeRemaining.Text = backupStatus.RemainingTime;
currentStatus.Text = backupStatus.RunState.ToString();
if (backupStatus.ShowFile)
{
currentFile.Text = backupStatus.CurrentFile.FullName;
currentSize.Text = (backupStatus.CurrentFile.Length > 0) ? StringHelper.ToNiceBytes(backupStatus.CurrentFile.Length) : string.Empty;
}
OnPropertyChanged("CanRun");
CancelButton.IsEnabled = (backupStatus.RunState == RunState.Running || backupStatus.RunState == RunState.Cancelling);
}
private bool logsLoaded = false;
private void LoadLogView()
{
if (!logsLoaded)
{
logSummaries.Clear();
foreach (LogSummary logSummary in logger.GetSummaries())
{
logSummaries.Add(logSummary);
}
logsLoaded = true;
}
}
// UI event handlers
private void OnClickCancel(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Are you sure you want to cancel the running backup?", "PCBackup", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
clientHost.TryCancelBackup();
}
private void OnRunCopy(object sender, RoutedEventArgs e)
{
GetAllUpdateFolders();
if (!Directory.Exists(TBTargetFolder.Text))
{
MessageBox.Show("Destination folder does not exist", "PCBackup", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
BackupConfig.TargetFolder = TBTargetFolder.Text;
clientHost.TryRunBackup(BackupConfig);
CurrentPage = BackupPages.Status;
}
private void OnClickSave(object sender, RoutedEventArgs e)
{
GetAllUpdateFolders();
if (BackupConfig.SourceFolders.Count == 0)
{
MessageBox.Show(Properties.Resources.MsgNoFolders, "Warning", MessageBoxButton.OK);
return;
}
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string scriptFolder = folderBase + @"\Appnotics\PCBackup\Scripts\";
if (!Directory.Exists(scriptFolder))
Directory.CreateDirectory(scriptFolder);
SaveFileDialog fdlg = new SaveFileDialog()
{
DefaultExt = ".bbx",
Filter = Properties.Resources.ScriptFilter + " (*.bbx) | *.bbx",
InitialDirectory = scriptFolder
};
if (fdlg.ShowDialog() == true)
{
string fileName = fdlg.FileName;
if (Directory.Exists(TBTargetFolder.Text))
BackupConfig.TargetFolder = TBTargetFolder.Text;
BackupConfig.BackupType = (BackupType)comboCopyType.SelectedIndex;
BackupConfig.OverwriteType = (OverwriteType)comboOverwriteType.SelectedIndex;
BackupConfig.VerifyAfterCopy = (CheckVerify.IsChecked == true);
if (File.Exists(fileName))
{
if (MessageBox.Show("Do you want to overwrite this configuration?", Properties.Resources.AppName, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
return;
}
var helper = new XmlSerializerHelper<BackupConfig>();
helper.Save(fileName, BackupConfig);
}
}
private void OnClickOpen(object sender, RoutedEventArgs e)
{
GetAllUpdateFolders();
if (BackupConfig.SourceFolders.Count > 0)
{
if (MessageBox.Show("Do you want to clear the existing selection?", Properties.Resources.AppName, MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No)
return;
ClearTreeView();
BackupConfig.SourceFolders.Clear();
}
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string scriptFolder = folderBase + @"\Appnotics\PCBackup\Scripts\";
OpenFileDialog fdlg = new OpenFileDialog()
{
DefaultExt = ".bbx",
Filter = Properties.Resources.ScriptFilter + " (*.bbx) | *.bbx",
Multiselect = false,
InitialDirectory = scriptFolder
};
if (fdlg.ShowDialog() == true)
{
string fileName = fdlg.FileName;
var helper = new XmlSerializerHelper<BackupConfig>();
BackupConfig = helper.Read(fileName);
FileInfo fi = new FileInfo(fileName);
BackupConfig.FileName = fi.Name.Replace(fi.Extension, "");
CurrentPage = BackupPages.Setup;
// RunButton.IsEnabled = true;
TBTargetFolder.Text = BackupConfig.TargetFolder;
comboCopyType.SelectedIndex = (int)BackupConfig.BackupType;
comboOverwriteType.SelectedIndex = (int)BackupConfig.OverwriteType;
CheckVerify.IsChecked = BackupConfig.VerifyAfterCopy;
foreach (object o in foldersTree.Items)
{
if (o is TreeViewItem)
{
TreeViewItem tvi = o as TreeViewItem;
CheckItemIfInConfig(tvi);
}
}
IsSourceValid = true;
SetButtonStatus();
}
}
private void CheckItemIfInConfig(TreeViewItem tvi)
{
CheckBox cb = tvi.Header as CheckBox;
string folderName = tvi.Tag as string;
if (ContainsFolder(folderName))
{
cb.IsChecked = true;
CheckParent(tvi);
}
else
{
// it's not selected, so recurse down the children
if (tvi.Items.Count == 1 && tvi.Items[0] == _dummyNode)
{
// no children, but dummy is there, so check if this folder is the parent of any
// in the config, and if so, half check it
if (ContainsFolderPart(folderName))
{
cb.IsChecked = null;
CheckParent(tvi);
}
}
else
{
foreach (object o in tvi.Items)
{
if (o is TreeViewItem)
{
TreeViewItem tviChild = o as TreeViewItem;
CheckItemIfInConfig(tviChild);
}
}
}
}
}
// private List<string> testFolders = new List<string>();
public void ClearTreeView()
{
foreach (object o in foldersTree.Items)
{
if (o is TreeViewItem)
{
TreeViewItem tvi = o as TreeViewItem;
ClearTreeViewItem(tvi);
}
}
}
private void ClearTreeViewItem(TreeViewItem tvi)
{
CheckBox cb = tvi.Header as CheckBox;
string folderName = tvi.Tag as string;
cb.IsChecked = false;
if (tvi.Items.Count == 1 && tvi.Items[0] == _dummyNode)
{
}
else
{
foreach (object o in tvi.Items)
{
if (o is TreeViewItem)
{
TreeViewItem tviChild = o as TreeViewItem;
ClearTreeViewItem(tviChild);
}
}
}
}
public void GetAllUpdateFolders()
{
//backupConfig.SourceFolders.Clear();
//foreach (object o in foldersTree.Items)
//{
// if (o is TreeViewItem)
// {
// TreeViewItem tvi = o as TreeViewItem;
// AddItemToConfigIfChecked(tvi);
// }
//}
}
private void SetButtonStatus()
{
}
private void AddItemToConfigIfChecked(TreeViewItem tvi)
{
CheckBox cb = tvi.Header as CheckBox;
string folderName = tvi.Tag as string;
if (cb.IsChecked == true)
{
BackupConfig.SourceFolders.Add(folderName);
}
else
{
if (!(tvi.Items.Count == 1 && tvi.Items[0] == _dummyNode))
{
foreach (object o in tvi.Items)
{
if (o is TreeViewItem)
{
TreeViewItem tviChild = o as TreeViewItem;
AddItemToConfigIfChecked(tviChild); // recurse into this method
}
}
}
}
}
public bool ContainsFolderPart(string folderName)
{
foreach (string sourceFolder in BackupConfig.SourceFolders)
{
if (sourceFolder.ToLower().Contains(folderName.ToLower()))
return true;
}
//foreach (BackupDirectory sourceFolder in backupConfig.SourceFolders)
//{
// if (sourceFolder.path.ToLower().Contains(folderName.ToLower()))
// return true;
//}
return false;
}
public bool ContainsFolder(string folderName)
{
foreach (string sourceFolder in BackupConfig.SourceFolders)
{
if (sourceFolder.ToLower().Equals(folderName.ToLower()))
return true;
}
//foreach (BackupDirectory sourceFolder in backupConfig.SourceFolders)
//{
// if (sourceFolder.path.ToLower().Equals(folderName.ToLower()))
// return true;
//}
return false;
}
private void OnLogSelected(object sender, SelectionChangedEventArgs e)
{
DeleteLogButton.IsEnabled = (LogGrid.SelectedItems.Count > 0);
ViewLogButton.IsEnabled = (LogGrid.SelectedItems.Count == 1);
}
private void OnDeleteLog(object sender, RoutedEventArgs e)
{
List<LogSummary> summariesToRemove = new List<LogSummary>();
foreach (object o in LogGrid.SelectedItems)
{
LogSummary logSummary = o as LogSummary;
logger.DeleteLog(logSummary); // don't actually delete it if in debug
summariesToRemove.Add(logSummary);
}
foreach (LogSummary logSummary in summariesToRemove)
logSummaries.Remove(logSummary);
}
private void OnViewLog(object sender, RoutedEventArgs e)
{
ViewLogSummary(LogGrid.SelectedItem as LogSummary);
}
private void LogsRowDoubleClick(object sender, MouseButtonEventArgs e)
{
DataGridRow row = sender as DataGridRow;
if (LogGrid.SelectedItems.Count != 1)
return;
ViewLogSummary(LogGrid.SelectedItem as LogSummary);
}
private void ViewLogSummary(LogSummary logSummary)
{
if (logSummary == null)
return;
string logFile = logger.LogFolder + logSummary.LogName + ".log";
if (File.Exists(logFile))
{
string readText = File.ReadAllText(logFile);
LogInfo.Text = readText;
LogViewActive = true;
}
}
private void OnBack(object sender, RoutedEventArgs e)
{
LogViewActive = false;
}
private void OnClickAddSchedule(object sender, RoutedEventArgs e)
{
ScheduleOptions dlg = new ScheduleOptions();
dlg.ShowDialog();
if (dlg.DialogResult == true)
{
dlg.schedule.CalculateNextRunTime();
schedules.ScheduleList.Add(dlg.schedule);
schedules.ScheduleList.Sort();
SchedulesLoader.Save(schedules);
ScheduleGrid.ItemsSource = schedules.ScheduleList;
ScheduleGrid.Items.Refresh();
clientHost.TryReloadSchedule();
}
}
private void OnScheduleSelected(object sender, SelectionChangedEventArgs e)
{
selectedSchedule = ScheduleGrid.SelectedItem as Schedule;
DeleteScheduleButton.IsEnabled = (selectedSchedule != null);
EditScheduleButton.IsEnabled = (selectedSchedule != null);
}
private void OnDoubleClickSchedule(object sender, MouseButtonEventArgs e)
{
EditSelectedSchedule();
}
private void OnClickEditSchedule(object sender, RoutedEventArgs e)
{
EditSelectedSchedule();
}
private void OnClickDeleteSchedule(object sender, RoutedEventArgs e)
{
if (selectedSchedule == null)
return;
schedules.ScheduleList.Remove(selectedSchedule);
schedules.ScheduleList.Sort();
SchedulesLoader.Save(schedules);
ScheduleGrid.ItemsSource = schedules.ScheduleList;
ScheduleGrid.Items.Refresh();
}
private void EditSelectedSchedule()
{
if (selectedSchedule == null)
return;
ScheduleOptions dlg = new ScheduleOptions(selectedSchedule);
dlg.ShowDialog();
if (dlg.DialogResult == true)
{
dlg.schedule.CalculateNextRunTime();
schedules.ScheduleList.Sort();
SchedulesLoader.Save(schedules);
ScheduleGrid.ItemsSource = schedules.ScheduleList;
ScheduleGrid.Items.Refresh();
}
clientHost.TryReloadSchedule();
}
private void OnCopyTo(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
dlg.ShowDialog();
if (!string.IsNullOrEmpty(dlg.SelectedPath))
{
TBTargetFolder.Text = dlg.SelectedPath;
}
}
private void OnClickExit(object sender, RoutedEventArgs e)
{
Close();
}
private void OnClickAbout(object sender, RoutedEventArgs e)
{
Splash splash = new Splash();
splash.ShowDialog();
}
private void OnShowPreferences(object sender, RoutedEventArgs e)
{
}
private void OnChangePage(object sender, RoutedEventArgs e)
{
XButton b = sender as XButton;
if (int.TryParse(b.ExtraInt.ToString(), out int i))
CurrentPage = (BackupPages)i;
}
private void OnTargetFolderChanged(object sender, TextChangedEventArgs e)
{
IsDestinationValid = Directory.Exists(TBTargetFolder.Text);
}
private void OnChangedCopyType(object sender, SelectionChangedEventArgs e)
{
if (!Initialising)
IsDirty = true;
}
private void OnChangedOverwriteType(object sender, SelectionChangedEventArgs e)
{
if (!Initialising)
IsDirty = true;
}
private void OnChangedVerifyOption(object sender, RoutedEventArgs e)
{
if (!Initialising)
IsDirty = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UKPR.Hermes.Asp.NetCoreApi.Dtos
{
public class AvailibilityWithWindowsForCreation : AvailibilityDeclarationForCreation
{
public ICollection<NGWindowForCreation> windows { get; set; }
= new List<NGWindowForCreation>();
}
}
|
using System;
namespace RBush
{
public class Envelope
{
public double MinX;
public double MinY;
public double MaxX;
public double MaxY;
public double Area => Math.Max(this.MaxX - this.MinX, 0) * Math.Max(this.MaxY - this.MinY, 0);
public double Margin => Math.Max(this.MaxX - this.MinX, 0) + Math.Max(this.MaxY - this.MinY, 0);
public void Extend(Envelope other)
{
this.MinX = Math.Min(this.MinX, other.MinX);
this.MinY = Math.Min(this.MinY, other.MinY);
this.MaxX = Math.Max(this.MaxX, other.MaxX);
this.MaxY = Math.Max(this.MaxY, other.MaxY);
}
public Envelope Clone()
{
return new Envelope
{
MinX = this.MinX,
MinY = this.MinY,
MaxX = this.MaxX,
MaxY = this.MaxY,
};
}
public Envelope Intersection(Envelope other)
{
return new Envelope
{
MinX = Math.Max(this.MinX, other.MinX),
MinY = Math.Max(this.MinY, other.MinY),
MaxX = Math.Min(this.MaxX, other.MaxX),
MaxY = Math.Min(this.MaxY, other.MaxY),
};
}
public Envelope Enlargement(Envelope other)
{
var clone = this.Clone();
clone.Extend(other);
return clone;
}
public bool Contains(Envelope other)
{
return
this.MinX <= other.MinX &&
this.MinY <= other.MinY &&
this.MaxX >= other.MaxX &&
this.MaxY >= other.MaxY;
}
public bool Intersects(Envelope other)
{
return
this.MinX <= other.MaxX &&
this.MinY <= other.MaxY &&
this.MaxX >= other.MinX &&
this.MaxY >= other.MinY;
}
public static Envelope InfiniteBounds =>
new Envelope
{
MinX = double.NegativeInfinity,
MinY = double.NegativeInfinity,
MaxX = double.PositiveInfinity,
MaxY = double.PositiveInfinity,
};
public static Envelope EmptyBounds =>
new Envelope
{
MinX = double.PositiveInfinity,
MinY = double.PositiveInfinity,
MaxX = double.NegativeInfinity,
MaxY = double.NegativeInfinity,
};
}
} |
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Causes a Popup to open when a Button is clicked or a hotkey is
/// pressed.
/// When attached to GameObjects with a Button, this will add a
/// callback to the Button's onClick listener that opens a Popup.
/// </summary>
[RequireComponent(typeof(Button)), DisallowMultipleComponent]
public class BtnOpenPopup : MonoBehaviour {
[SerializeField]
private PopupWindow popup = null;
[SerializeField, Tooltip("If set, the popup will be opened with this hotkey")]
private KeyCode hotkey = KeyCode.None;
private void Start() {
this.GetComponent<Button>().onClick.AddListener(() => {
this.openPopupIfSet();
});
}
private void Update() {
if(Input.GetKeyDown(this.hotkey)) {
this.openPopupIfSet();
}
}
private void openPopupIfSet() {
if(this.popup != null) {
this.popup.open();
}
}
}
|
using Cottle.Functions;
using Cottle.Values;
using EddiSpeechResponder.Service;
using EddiSpeechService;
using System;
using System.Linq;
namespace EddiSpeechResponder.CustomFunctions
{
[JetBrains.Annotations.UsedImplicitly]
public class VoiceDetails : ICustomFunction
{
public string name => "VoiceDetails";
public FunctionCategory Category => FunctionCategory.Details;
public string description => Properties.CustomFunctions_Untranslated.VoiceDetails;
public Type ReturnType => typeof( VoiceDetails );
public NativeFunction function => new NativeFunction((values) =>
{
if (values.Count == 0)
{
if (SpeechService.Instance?.allVoices != null)
{
return new ReflectionValue(
SpeechService.Instance.allVoices.FirstOrDefault(v =>
v.name == SpeechService.Instance.Configuration.StandardVoice) ?? new object());
}
}
if (values.Count == 1)
{
if (int.TryParse(values[0].AsString, out var seed) && SpeechService.Instance?.allVoices != null)
{
var fromSeed = new System.Random(seed);
return new ReflectionValue(SpeechService.Instance.allVoices
.OrderBy(o => fromSeed.Next()).ToList());
}
if (!string.IsNullOrEmpty(values[0].AsString) && SpeechService.Instance?.allVoices != null)
{
foreach (var vc in SpeechService.Instance.allVoices)
{
if (vc.name.ToLowerInvariant().Contains(values[0].AsString.ToLowerInvariant()))
{
return new ReflectionValue(vc);
}
}
return $"Voice \"{values[0].AsString}\" not found.";
}
}
return "The VoiceDetails function is used improperly. Please review the documentation for correct usage.";
}, 0, 1);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
namespace Org.Common.Web.Configuration
{
public class ServiceDiscoveryConfigurationSource : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new ServiceDiscoveryConfigurationProvider(o => o.ServiceName = Environment.GetEnvironmentVariable(EnvironmentConstants.ServiceName));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0009
{
/*
Determine whether an integer is a palindrome.Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer.However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow.How would you handle such case?
There is a more generic way of solving this problem.
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
int input = 1234321;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
input = -22;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
input = 2;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
input = 23;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
input = int.MaxValue;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
//-2147483648
input = -2147483648;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
/*
Input: -101
Output:true
Expected:false
*/
input = -101;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
/*
Input:1073773701
Output:false
Expected:true
*/
input = 1073773701;
Console.WriteLine($"Check number'{input}' is palindrom = {sol.IsPalindrome(input)}");
}
public class Solution
{
/*
if we have number abcdf
try to build number fdcba
and if (abcdf + fdcba) / 2 = abcdf => is palindrome
if any overflow - not palindrome
*/
public bool IsPalindrome(int x)
{
try
{
int num1 = Math.Abs(x);
int num2 = 0;
while (num1 > 0)
{
num2 = checked(num2 * 10 + (num1 % 10));
num1 = num1 / 10; //rest of division by 10
}//while
//num1 = Math.Abs(x);
//num1 = x;
//return ((num1 + num2) / 2) == num1;
return num2 == x;
}
catch (Exception ex)
{
string sex = ex.ToString();
return false;
}
//return false;
}
}
}//
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Genesys.WebServicesClient
{
public interface IEventSubscription : IDisposable
{
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Instancer of type `int`. Inherits from `AtomEventInstancer<int, IntEvent>`.
/// </summary>
[EditorIcon("atom-icon-sign-blue")]
[AddComponentMenu("Unity Atoms/Event Instancers/Int Event Instancer")]
public class IntEventInstancer : AtomEventInstancer<int, IntEvent> { }
}
|
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Cs_Gerencial.Aplicacao.Interfaces;
using Cs_Gerencial.Dominio.Entities_Fracas;
using Cs_Gerencial.WindowsAguarde;
using System.ComponentModel;
using System.Threading;
using System.Data;
using System.Diagnostics;
namespace Cs_Gerencial.Windows
{
/// <summary>
/// Interaction logic for EstoqueSelos.xaml
/// </summary>
public partial class EstoqueSelos : Window
{
private readonly IAppServicoSelos _AppServicoSelos = BootStrap.Container.GetInstance<IAppServicoSelos>();
private readonly IAppServicoLogSistema _AppServicoLogSistema = BootStrap.Container.GetInstance<IAppServicoLogSistema>();
private readonly IAppServicoSeries _AppServicoSeries = BootStrap.Container.GetInstance<IAppServicoSeries>();
private readonly IAppServicoParametros _AppServicoParametros = BootStrap.Container.GetInstance<IAppServicoParametros>();
private readonly IAppServicoCompraSelo _AppServicoCompraSelo = BootStrap.Container.GetInstance<IAppServicoCompraSelo>();
public LeituraArquivoSeloComprado leituraDoArquivoXml;
public LeituraArquivoSeloComprado leituraDoArquivoXmlImportado;
Usuario _usuario;
Principal _principal;
public string autorizacao;
public FileInfo arquivoSelecionado;
FileInfo arquivoSelecionadoImportados;
public List<Series> _listSeriesDisponiveis = new List<Series>();
public List<Series> _listSeriesIndisponiveis = new List<Series>();
IEnumerable<Selos> listSelosDisponiveis = new List<Selos>();
IEnumerable<Selos> listSelosIndisponiveis = new List<Selos>();
List<Selos> listSelosCheckedsDisponiveis = new List<Selos>();
List<Selos> listSelosCheckedsIndisponiveis = new List<Selos>();
public Series serieDisponiveisSelecionada;
public Series serieIndisponiveisSelecionada;
Selos seloDisponivelSelecionado;
Selos seloIndisponivelSelecionado;
public List<Selos> listSelosDisponiveisSerieSelecionada;
public List<Selos> listSelosIndisponiveisSerieSelecionada;
public Parametros parametros;
List<FileInfo> listArquivosNaoImportados;
List<FileInfo> listArquivosImportados;
List<CompraSelo> listCompraSelos;
public EstoqueSelos(List<Series> listSeriesDisponiveis, List<Series> listSeriesIndisponiveis, Usuario usuario, Principal principal, Selos selecionado)
{
_usuario = usuario;
_listSeriesDisponiveis = listSeriesDisponiveis;
_listSeriesIndisponiveis = listSeriesIndisponiveis;
seloDisponivelSelecionado = selecionado;
_principal = principal;
InitializeComponent();
}
public EstoqueSelos(List<Series> listSeriesDisponiveis, List<Series> listSeriesIndisponiveis, Usuario usuario, Principal principal, Selos seloSelecionado, FileInfo arquivoSelecionado, FileInfo arquivoSelecionadoImportados)
{
// TODO: Complete member initialization
_usuario = usuario;
_listSeriesDisponiveis = listSeriesDisponiveis;
_listSeriesIndisponiveis = listSeriesIndisponiveis;
seloDisponivelSelecionado = seloSelecionado;
_principal = principal;
this.arquivoSelecionado = arquivoSelecionado;
this.arquivoSelecionadoImportados = arquivoSelecionadoImportados;
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
parametros = _AppServicoParametros.GetAll().FirstOrDefault();
CarregarTodosOsMetodosDeCarregamento();
}
public void CarregarTodosOsMetodosDeCarregamento()
{
CarregarHistorio();
CarregarSelosNaoImpotados();
CarregarSelosImportados();
CarregarDataGridSeriesDisponiveis();
CarregaDataGridSeriesIndisponiveis();
}
private void CarregarHistorio()
{
listCompraSelos = new List<CompraSelo>();
listCompraSelos = _AppServicoCompraSelo.GetAll().OrderBy(p => p.DataPedido).ToList();
dataGridHistorico.ItemsSource = listCompraSelos;
if (listCompraSelos.Count > 0)
{
dataGridHistorico.SelectedIndex = 0;
}
}
private void CarregarSelosNaoImpotados()
{
try
{
var diretorio = parametros.PathSelosNaoImportados;
DirectoryInfo diretorioAtual = new DirectoryInfo(diretorio);
if (diretorioAtual.Exists)
{
listView.ItemsSource = null;
listView.Items.Clear();
List<FileInfo> arquivos = diretorioAtual.GetFiles().Where(p => p.Extension == ".xml" || p.Extension == ".XML" && p.Name.Contains("ArquivoSelos")).ToList();
listArquivosNaoImportados = arquivos;
listView.ItemsSource = listArquivosNaoImportados;
if (listArquivosNaoImportados.Count() > 0)
{
if (arquivoSelecionado != null)
{
arquivoSelecionado = listArquivosNaoImportados.Where(p => p.Name == arquivoSelecionado.Name).FirstOrDefault();
tabItemNaoImportarSelos.IsSelected = true;
listView.SelectedItem = arquivoSelecionado;
listView.ScrollIntoView(arquivoSelecionado);
listView.SelectedItem = arquivoSelecionado;
}
else
listView.SelectedIndex = 0;
btnImportar.IsEnabled = true;
MenuMoverImportados.Visibility = Visibility.Visible;
}
else
{
btnImportar.IsEnabled = false;
MenuMoverImportados.Visibility = Visibility.Hidden;
}
}
}
catch (Exception)
{
}
}
private void CarregarSelosImportados()
{
try
{
var diretorio = parametros.PathSelosImportados;
DirectoryInfo diretorioAtual = new DirectoryInfo(diretorio);
if (diretorioAtual.Exists)
{
listViewImportados.ItemsSource = null;
listViewImportados.Items.Clear();
List<FileInfo> arquivos = diretorioAtual.GetFiles().Where(p => p.Extension == ".xml" || p.Extension == ".XML" && p.Name.Contains("ArquivoSelos")).ToList();
listArquivosImportados = arquivos;
listViewImportados.ItemsSource = listArquivosImportados;
MenuMoverNaoImportados.Visibility = Visibility.Hidden;
if (listArquivosImportados.Count() > 0)
{
if (arquivoSelecionadoImportados != null)
{
arquivoSelecionadoImportados = listArquivosImportados.Where(p => p.Name == arquivoSelecionadoImportados.Name).FirstOrDefault();
tabItemImportarSelos.IsSelected = true;
listView.SelectedItem = arquivoSelecionadoImportados;
listView.ScrollIntoView(arquivoSelecionadoImportados);
listViewImportados.SelectedItem = arquivoSelecionadoImportados;
}
else
listViewImportados.SelectedIndex = 0;
MenuMoverNaoImportados.Visibility = Visibility.Visible;
}
}
}
catch (Exception)
{
}
}
private void DigitarSomenteLetras(object sender, KeyEventArgs e)
{
int key = (int)e.Key;
e.Handled = !(key == 2 || key == 3 || key == 23 || key == 25 || key == 32 || key >= 44 && key <= 69);
}
private void DigitarSomenteNumeros(object sender, KeyEventArgs e)
{
int key = (int)e.Key;
e.Handled = !(key >= 34 && key <= 43 || key >= 74 && key <= 83 || key == 2 || key == 3 || key == 23 || key == 25 || key == 32);
}
private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (listView.Items.Count > 0)
{
try
{
{
arquivoSelecionado = (FileInfo)listView.SelectedItem;
CarregaInformacoesDoArquivo();
}
}
catch (Exception)
{
CarregarTodosProcessos();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message);
}
}
private void CarregaInformacoesDoArquivo()
{
leituraDoArquivoXml = _AppServicoSelos.LerArquivoCompraSelo(arquivoSelecionado.FullName);
lblNomeSolicitanteValor.Content = leituraDoArquivoXml.SolicitanteNome;
lblCpfSolicitanteValor.Content = leituraDoArquivoXml.SolicitanteCpf;
lblDataPedidoValor.Content = String.Format("{0:dd/MM/yyyy HH:mm:ss}", leituraDoArquivoXml.DataPedido);
lblDataGeracaoValor.Content = String.Format("{0:dd/MM/yyyy HH:mm:ss}", leituraDoArquivoXml.DataGeracao);
lblCodigoServicoValor.Content = leituraDoArquivoXml.CodigoServico;
lblIdValor.Content = leituraDoArquivoXml.Id;
lblSerieValor.Content = leituraDoArquivoXml.Serie;
lblQuantidadeValor.Content = leituraDoArquivoXml.Quantidade;
lblSeloInicialValor.Content = leituraDoArquivoXml.SequenciaInicio;
lblSeloFinalValor.Content = leituraDoArquivoXml.SequenciaFim;
lblGrerjValor.Content = leituraDoArquivoXml.Grerj;
}
private void CarregaInformacoesDoArquivoImportado()
{
leituraDoArquivoXmlImportado = _AppServicoSelos.LerArquivoCompraSelo(arquivoSelecionadoImportados.FullName);
lblNomeSolicitanteValor1.Content = leituraDoArquivoXmlImportado.SolicitanteNome;
lblCpfSolicitanteValor1.Content = leituraDoArquivoXmlImportado.SolicitanteCpf;
lblDataPedidoValor1.Content = String.Format("{0:dd/MM/yyyy HH:mm:ss}", leituraDoArquivoXmlImportado.DataPedido);
lblDataGeracaoValor1.Content = String.Format("{0:dd/MM/yyyy HH:mm:ss}", leituraDoArquivoXmlImportado.DataGeracao);
lblCodigoServicoValor1.Content = leituraDoArquivoXmlImportado.CodigoServico;
lblIdValor1.Content = leituraDoArquivoXmlImportado.Id;
lblSerieValor1.Content = leituraDoArquivoXmlImportado.Serie;
lblQuantidadeValor1.Content = leituraDoArquivoXmlImportado.Quantidade;
lblSeloInicialValor1.Content = leituraDoArquivoXmlImportado.SequenciaInicio;
lblSeloFinalValor1.Content = leituraDoArquivoXmlImportado.SequenciaFim;
lblGrerjValor1.Content = leituraDoArquivoXmlImportado.Grerj;
}
private void btnImportar_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Deseja realmente importar o arquivo selecionado? " + "\n" + "\n" + "Este processo pode demorar alguns minutos.", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
var aguardeImportarSelos = new AguardeImportarSelos(_usuario, this);
aguardeImportarSelos.Owner = this;
aguardeImportarSelos.ShowDialog();
this.Close();
seloDisponivelSelecionado = _AppServicoSelos.ConsultarPorIdSerie(serieDisponiveisSelecionada.SerieId).FirstOrDefault();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloDisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
}
private void CarregarTodosProcessos()
{
CarregarSelosNaoImpotados();
CarregarSelosImportados();
var aguardeProcessando = new AguardeProcessandoSelosNoEstoqueSelos(this);
aguardeProcessando.Owner = this;
aguardeProcessando.ShowDialog();
CarregarDataGridSeriesDisponiveis();
CarregaDataGridSeriesIndisponiveis();
}
//---------------------------------------- INÍCIO SÉRIES DISPONÍVEIS --------------------------------------------------------------
private void CarregarDataGridSeriesDisponiveis()
{
dataGridSeriesDisponiveis.ItemsSource = _listSeriesDisponiveis;
dataGridSeriesDisponiveis.SelectedValuePath = "SerieId";
dataGridSeriesDisponiveis.Items.Refresh();
if (seloDisponivelSelecionado != null)
serieDisponiveisSelecionada = _listSeriesDisponiveis.Where(p => p.SerieId == seloDisponivelSelecionado.IdSerie).FirstOrDefault();
if (serieDisponiveisSelecionada == null)
{
if (_listSeriesDisponiveis.Count > 0)
{
dataGridSeriesDisponiveis.SelectedIndex = 0;
}
}
else
{
dataGridSeriesDisponiveis.SelectedItem = serieDisponiveisSelecionada;
dataGridSeriesDisponiveis.ScrollIntoView(serieDisponiveisSelecionada);
dataGridSelosDisponiveis.ScrollIntoView(serieDisponiveisSelecionada);
}
}
private void CarregarSerieDisponivelSelecionadaTextBox()
{
txtSerieLetra.Text = serieDisponiveisSelecionada.Letra;
txtSerieInicial.Text = string.Format("{0:00000}", serieDisponiveisSelecionada.Inicial);
txtSerieFinal.Text = string.Format("{0:00000}", serieDisponiveisSelecionada.Final);
txtSerieQtd.Text = serieDisponiveisSelecionada.Quantidade.ToString();
txtSerieUtilizado.Text = listSelosDisponiveisSerieSelecionada.Where(p => p.IdSerie == serieDisponiveisSelecionada.SerieId && p.Status != "LIVRE").Count().ToString();
txtSerieLivre.Text = listSelosDisponiveisSerieSelecionada.Where(p => p.IdSerie == serieDisponiveisSelecionada.SerieId && p.Status == "LIVRE").Count().ToString();
}
private void checkedUmDisponivel_Unchecked(object sender, RoutedEventArgs e)
{
VerificarQtdMarcadosDisponiveis();
}
private void checkedUmDisponivel_Checked(object sender, RoutedEventArgs e)
{
VerificarQtdMarcadosDisponiveis();
}
private void VerificarQtdMarcadosDisponiveis()
{
int qtd = listSelosDisponiveisSerieSelecionada.Where(p => p.Check == true).Count();
lblQtdMarcados.Content = string.Format("Qtd Selos Marcados: {0}", qtd);
}
private void dataGridSeriesDisponiveis_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
serieDisponiveisSelecionada = (Series)dataGridSeriesDisponiveis.SelectedItem;
if (serieDisponiveisSelecionada != null)
{
CarregarDataGridSelosDaSerieDisponivel();
CarregarSerieDisponivelSelecionadaTextBox();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DesmarcarTodosCheckesDisponiveis();
checkTodosDisponiveis.IsChecked = false;
dataGridSelosDisponiveis.ScrollIntoView(seloDisponivelSelecionado);
}
}
public void CarregarDataGridSelosDaSerieDisponivel()
{
listSelosDisponiveisSerieSelecionada = _AppServicoSelos.ConsultarPorIdSerie(serieDisponiveisSelecionada.SerieId).ToList();
dataGridSelosDisponiveis.ItemsSource = listSelosDisponiveisSerieSelecionada;
if (seloDisponivelSelecionado != null)
seloDisponivelSelecionado = listSelosDisponiveisSerieSelecionada.Where(p => p.SeloId == seloDisponivelSelecionado.SeloId).FirstOrDefault();
if (listSelosDisponiveisSerieSelecionada.Count > 0)
{
if (seloDisponivelSelecionado != null)
{
dataGridSelosDisponiveis.SelectedItem = seloDisponivelSelecionado;
}
else
{
dataGridSelosDisponiveis.SelectedIndex = 0;
}
}
}
private void checkTodosDisponiveis_Checked(object sender, RoutedEventArgs e)
{
MarcarTodosCheckesDisponiveis();
}
private void checkTodosDisponiveis_Unchecked(object sender, RoutedEventArgs e)
{
DesmarcarTodosCheckesDisponiveis();
}
private void DesmarcarTodosCheckesDisponiveis()
{
if (listSelosDisponiveisSerieSelecionada == null)
return;
foreach (var item in listSelosDisponiveisSerieSelecionada)
{
item.Check = false;
dataGridSelosDisponiveis.Items.Refresh();
listSelosCheckedsDisponiveis.Remove(item);
}
VerificarQtdMarcadosDisponiveis();
}
private void MarcarTodosCheckesDisponiveis()
{
if (listSelosDisponiveisSerieSelecionada == null)
return;
foreach (var item in listSelosDisponiveisSerieSelecionada)
{
item.Check = true;
dataGridSelosDisponiveis.Items.Refresh();
listSelosCheckedsDisponiveis.Add(item);
}
VerificarQtdMarcadosDisponiveis();
}
private void txtConsultaSerieDisponivel_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtConsultaSerieDisponivel.Text.Length == 4)
{
ConsultarSerieDisponivel();
}
else
{
txtConsultaNumeroDisponivel.Text = "";
txtConsultaNumeroDisponivel.IsEnabled = false;
}
}
private void ConsultarSerieDisponivel()
{
try
{
Series serie = _listSeriesDisponiveis.Where(p => p.Letra.Contains(txtConsultaSerieDisponivel.Text)).FirstOrDefault();
if (serie != null)
{
dataGridSeriesDisponiveis.SelectedItem = serie;
dataGridSeriesDisponiveis.ScrollIntoView(serie);
txtConsultaNumeroDisponivel.IsEnabled = true;
txtConsultaNumeroDisponivel.Focus();
}
else
{
MessageBox.Show("Série não encontrada.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning);
txtConsultaSerieDisponivel.Text = "";
txtConsultaSerieDisponivel.Focus();
txtConsultaNumeroDisponivel.Text = "";
txtConsultaNumeroDisponivel.IsEnabled = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtConsultaNumeroDisponivel_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtConsultaNumeroDisponivel.Text.Length == 5)
ConsultarSerieDisponivel_E_Numero();
}
private void ConsultarSerieDisponivel_E_Numero()
{
Series serie = null;
try
{
Selos selo = _AppServicoSelos.ConsultarPorSerieNumero(txtConsultaSerieDisponivel.Text, Convert.ToInt32(txtConsultaNumeroDisponivel.Text));
if (selo != null)
serie = _listSeriesDisponiveis.Where(p => p.SerieId == selo.IdSerie).FirstOrDefault();
if (serie != null)
{
dataGridSeriesDisponiveis.SelectedItem = serie;
dataGridSeriesDisponiveis.ScrollIntoView(serie);
if (selo != null)
{
dataGridSelosDisponiveis.SelectedItem = selo;
dataGridSelosDisponiveis.ScrollIntoView(selo);
}
}
else
{
MessageBox.Show("Selo informado não foi encontrado.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning);
txtConsultaSerieDisponivel.Text = "";
txtConsultaSerieDisponivel.Focus();
txtConsultaNumeroDisponivel.Text = "";
txtConsultaNumeroDisponivel.IsEnabled = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnAtualizar_Click(object sender, RoutedEventArgs e)
{
this.Close();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloDisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
private void dataGridSelosDisponiveis_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
seloDisponivelSelecionado = (Selos)dataGridSelosDisponiveis.SelectedItem;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnLiberarSeloDisponiveis_Click(object sender, RoutedEventArgs e)
{
if ( listSelosDisponiveisSerieSelecionada == null)
return;
List<Selos> selosLiberar = new List<Selos>();
selosLiberar = listSelosDisponiveisSerieSelecionada.Where(p => p.Check == true && p.Status != "LIVRE").ToList();
if (selosLiberar.Count > 0)
{
if (_usuario.NomeUsuario != "Administrador")
{
autorizacao = string.Empty;
var verificarSenha = new InformarSenhaMaster(this);
verificarSenha.Owner = this;
verificarSenha.ShowDialog();
if (autorizacao != "autorizado")
{
return;
}
}
lblQtdMarcados.Visibility = Visibility.Hidden;
var liberarBaixarSelos = new CarreguandoBaixarLiberarSelo(selosLiberar, _usuario, "liberar", this);
liberarBaixarSelos.Owner = this;
liberarBaixarSelos.ShowDialog();
lblQtdMarcados.Visibility = Visibility.Visible;
this.Close();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloDisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
else
{
MessageBox.Show("Nenhum selo com Status diferente de LIVRE foi selecionado", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
private void btnBaixarManualDisponiveis_Click(object sender, RoutedEventArgs e)
{
if (listSelosDisponiveisSerieSelecionada == null)
return;
List<Selos> selosBaixar = new List<Selos>();
selosBaixar = listSelosDisponiveisSerieSelecionada.Where(p => p.Check == true && p.Status == "LIVRE").ToList();
if (selosBaixar.Count > 0)
{
if (_usuario.NomeUsuario != "Administrador")
{
autorizacao = string.Empty;
var verificarSenha = new InformarSenhaMaster(this);
verificarSenha.Owner = this;
verificarSenha.ShowDialog();
if (autorizacao != "autorizado")
{
return;
}
}
lblQtdMarcados.Visibility = Visibility.Hidden;
var liberarBaixarSelos = new CarreguandoBaixarLiberarSelo(selosBaixar, _usuario, "baixar", this);
liberarBaixarSelos.Owner = this;
liberarBaixarSelos.ShowDialog();
lblQtdMarcados.Visibility = Visibility.Visible;
this.Close();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloDisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
else
{
MessageBox.Show("Nenhum selo LIVRE foi selecionado", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
private void dataGridSelosDisponiveis_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var detalhesSelo = new DetalhesDoSelo(seloDisponivelSelecionado, _usuario);
detalhesSelo.Owner = this;
detalhesSelo.ShowDialog();
listSelosDisponiveisSerieSelecionada[dataGridSelosDisponiveis.SelectedIndex] = _AppServicoSelos.GetById(seloDisponivelSelecionado.SeloId);
dataGridSelosDisponiveis.Items.Refresh();
}
//---------------------------------------- FIM SÉRIES DISPONÍVEIS --------------------------------------------------------------
//---------------------------------------- INÍCIO SÉRIES INDISPONÍVEIS --------------------------------------------------------------
private void CarregaDataGridSeriesIndisponiveis()
{
dataGridSeriesIndisponiveis.ItemsSource = _listSeriesIndisponiveis;
dataGridSeriesIndisponiveis.SelectedValuePath = "SerieId";
dataGridSeriesIndisponiveis.Items.Refresh();
if (serieIndisponiveisSelecionada == null)
{
if (_listSeriesIndisponiveis.Count > 0)
{
dataGridSeriesIndisponiveis.SelectedIndex = 0;
}
}
else
{
dataGridSeriesIndisponiveis.SelectedItem = serieIndisponiveisSelecionada;
}
}
private void CarregarSerieIndisponiveisSelecionadaTextBox()
{
txtSerieLetraIndisponiveis.Text = serieIndisponiveisSelecionada.Letra;
txtSerieInicialIndisponiveis.Text = string.Format("{0:00000}", serieIndisponiveisSelecionada.Inicial);
txtSerieFinalIndisponiveis.Text = string.Format("{0:00000}", serieIndisponiveisSelecionada.Final);
txtSerieQtdIndisponiveis.Text = serieIndisponiveisSelecionada.Quantidade.ToString();
txtSerieUtilizadoIndisponiveis.Text = listSelosIndisponiveisSerieSelecionada.Where(p => p.IdSerie == serieIndisponiveisSelecionada.SerieId && p.Status != "LIVRE").Count().ToString();
txtSerieLivreIndisponiveis.Text = listSelosIndisponiveisSerieSelecionada.Where(p => p.IdSerie == serieIndisponiveisSelecionada.SerieId && p.Status == "LIVRE").Count().ToString();
}
private void checkedUmIndisponiveis_Unchecked(object sender, RoutedEventArgs e)
{
VerificarQtdMarcadosIndisponiveis();
}
private void checkedUmIndisponiveis_Checked(object sender, RoutedEventArgs e)
{
VerificarQtdMarcadosIndisponiveis();
}
private void VerificarQtdMarcadosIndisponiveis()
{
int qtd = listSelosIndisponiveisSerieSelecionada.Where(p => p.Check == true).Count();
lblQtdMarcadosIndisponiveis.Content = string.Format("Qtd Selos Marcados: {0}", qtd);
}
private void dataGridSeriesIndisponiveis_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
serieIndisponiveisSelecionada = (Series)dataGridSeriesIndisponiveis.SelectedItem;
if (serieIndisponiveisSelecionada != null)
{
CarregarDataGridSelosDaSerieIndisponiveis();
CarregarSerieIndisponiveisSelecionadaTextBox();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (serieDisponiveisSelecionada != null)
{
DesmarcarTodosCheckesIndisponiveis();
checkTodosIndisponiveis.IsChecked = false;
if (seloIndisponivelSelecionado != null)
dataGridSelosIndisponiveis.ScrollIntoView(seloIndisponivelSelecionado);
}
}
}
public void CarregarDataGridSelosDaSerieIndisponiveis()
{
dataGridSelosIndisponiveis.ItemsSource = null;
listSelosIndisponiveisSerieSelecionada = _AppServicoSelos.ConsultarPorIdSerie(serieIndisponiveisSelecionada.SerieId).ToList();
dataGridSelosIndisponiveis.ItemsSource = listSelosIndisponiveisSerieSelecionada;
if (seloIndisponivelSelecionado != null)
seloIndisponivelSelecionado = listSelosIndisponiveisSerieSelecionada.Where(p => p.SeloId == seloIndisponivelSelecionado.SeloId).FirstOrDefault();
if (listSelosIndisponiveisSerieSelecionada.Count > 0)
{
if (seloIndisponivelSelecionado != null)
{
dataGridSelosIndisponiveis.SelectedItem = seloIndisponivelSelecionado;
}
else
{
dataGridSelosIndisponiveis.SelectedIndex = 0;
}
}
}
private void checkTodosIndisponiveis_Checked(object sender, RoutedEventArgs e)
{
MarcarTodosCheckesIndisponiveis();
}
private void checkTodosIndisponiveis_Unchecked(object sender, RoutedEventArgs e)
{
DesmarcarTodosCheckesIndisponiveis();
}
private void DesmarcarTodosCheckesIndisponiveis()
{
if (listSelosIndisponiveisSerieSelecionada == null)
return;
foreach (var item in listSelosIndisponiveisSerieSelecionada)
{
item.Check = false;
dataGridSelosIndisponiveis.Items.Refresh();
listSelosCheckedsIndisponiveis.Remove(item);
}
VerificarQtdMarcadosIndisponiveis();
}
private void MarcarTodosCheckesIndisponiveis()
{
if (listSelosIndisponiveisSerieSelecionada == null)
return;
foreach (var item in listSelosIndisponiveisSerieSelecionada)
{
item.Check = true;
dataGridSelosIndisponiveis.Items.Refresh();
listSelosCheckedsIndisponiveis.Add(item);
}
VerificarQtdMarcadosIndisponiveis();
}
private void txtConsultaSerieIndisponiveis_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtConsultaSerieIndisponiveis.Text.Length == 4)
{
ConsultarSerieIndisponiveis();
}
else
{
txtConsultaNumeroIndisponiveis.Text = "";
txtConsultaNumeroIndisponiveis.IsEnabled = false;
}
}
private void ConsultarSerieIndisponiveis()
{
try
{
Series serie = _listSeriesIndisponiveis.Where(p => p.Letra.Contains(txtConsultaSerieIndisponiveis.Text)).FirstOrDefault();
if (serie != null)
{
dataGridSeriesIndisponiveis.SelectedItem = serie;
dataGridSeriesIndisponiveis.ScrollIntoView(serie);
txtConsultaNumeroIndisponiveis.IsEnabled = true;
txtConsultaNumeroIndisponiveis.Focus();
}
else
{
MessageBox.Show("Série não encontrada.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning);
txtConsultaSerieIndisponiveis.Text = "";
txtConsultaSerieIndisponiveis.Focus();
txtConsultaNumeroIndisponiveis.Text = "";
txtConsultaNumeroIndisponiveis.IsEnabled = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtConsultaNumeroIndisponiveis_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtConsultaNumeroIndisponiveis.Text.Length == 5)
ConsultarSerieIndisponiveis_E_Numero();
}
private void ConsultarSerieIndisponiveis_E_Numero()
{
Series serie = null;
try
{
Selos selo = _AppServicoSelos.ConsultarPorSerieNumero(txtConsultaSerieIndisponiveis.Text, Convert.ToInt32(txtConsultaNumeroIndisponiveis.Text));
if (selo != null)
serie = _listSeriesIndisponiveis.Where(p => p.SerieId == selo.IdSerie).FirstOrDefault();
if (serie != null)
{
dataGridSeriesIndisponiveis.SelectedItem = serie;
dataGridSeriesIndisponiveis.ScrollIntoView(serie);
if (selo != null)
{
dataGridSelosIndisponiveis.SelectedItem = selo;
dataGridSelosIndisponiveis.ScrollIntoView(selo);
}
}
else
{
MessageBox.Show("Selo informado não foi encontrado.", "Atenção", MessageBoxButton.OK, MessageBoxImage.Warning);
txtConsultaSerieIndisponiveis.Text = "";
txtConsultaSerieIndisponiveis.Focus();
txtConsultaNumeroIndisponiveis.Text = "";
txtConsultaNumeroIndisponiveis.IsEnabled = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridSelosIndisponiveis_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
seloIndisponivelSelecionado = (Selos)dataGridSelosIndisponiveis.SelectedItem;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnLiberarSeloIndisponiveis_Click(object sender, RoutedEventArgs e)
{
if (listSelosIndisponiveisSerieSelecionada == null)
return;
List<Selos> selosLiberar = new List<Selos>();
selosLiberar = listSelosIndisponiveisSerieSelecionada.Where(p => p.Check == true && p.Status != "LIVRE").ToList();
if (selosLiberar.Count > 0)
{
if (_usuario.NomeUsuario != "Administrador")
{
autorizacao = string.Empty;
var verificarSenha = new InformarSenhaMaster(this);
verificarSenha.Owner = this;
verificarSenha.ShowDialog();
if (autorizacao != "autorizado")
{
return;
}
}
lblQtdMarcadosIndisponiveis.Visibility = Visibility.Hidden;
var liberarBaixarSelos = new CarreguandoBaixarLiberarSelo(selosLiberar, _usuario, "liberar", this);
liberarBaixarSelos.Owner = this;
liberarBaixarSelos.ShowDialog();
lblQtdMarcadosIndisponiveis.Visibility = Visibility.Visible;
this.Close();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloIndisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
else
{
MessageBox.Show("Nenhum selo com Status diferente de LIVRE foi selecionado", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
private void btnBaixarManualIndisponiveis_Click(object sender, RoutedEventArgs e)
{
if (listSelosIndisponiveisSerieSelecionada == null)
return;
List<Selos> selosBaixar = new List<Selos>();
selosBaixar = listSelosIndisponiveisSerieSelecionada.Where(p => p.Check == true && p.Status == "LIVRE").ToList();
if (selosBaixar.Count > 0)
{
if (_usuario.NomeUsuario != "Administrador")
{
autorizacao = string.Empty;
var verificarSenha = new InformarSenhaMaster(this);
verificarSenha.Owner = this;
verificarSenha.ShowDialog();
if (autorizacao != "autorizado")
{
return;
}
}
lblQtdMarcadosIndisponiveis.Visibility = Visibility.Hidden;
var liberarBaixarSelos = new CarreguandoBaixarLiberarSelo(selosBaixar, _usuario, "baixar", this);
liberarBaixarSelos.Owner = this;
liberarBaixarSelos.ShowDialog();
lblQtdMarcadosIndisponiveis.Visibility = Visibility.Visible;
this.Close();
AguardeProcessandoSelos aguarde = new AguardeProcessandoSelos(_principal, _usuario, seloIndisponivelSelecionado);
aguarde.Owner = _principal;
aguarde.ShowDialog();
}
else
{
MessageBox.Show("Nenhum selo LIVRE foi selecionado", "Atenção", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
private void moverNaoImportados_Click(object sender, RoutedEventArgs e)
{
string pathImportados = parametros.PathSelosImportados + @"\" + arquivoSelecionadoImportados.Name;
string pathNaoImportados = parametros.PathSelosNaoImportados + @"\" + arquivoSelecionadoImportados.Name;
try
{
if (File.Exists(pathNaoImportados))
File.Delete(pathNaoImportados);
arquivoSelecionadoImportados = new FileInfo(pathImportados);
if (arquivoSelecionadoImportados.Exists)
arquivoSelecionadoImportados.MoveTo(pathNaoImportados);
string arquivoMovido = arquivoSelecionadoImportados.Name;
CarregarSelosImportados();
CarregarSelosNaoImpotados();
tabItemNaoImportarSelos.IsSelected = true;
arquivoSelecionado = listArquivosNaoImportados.Where(p => p.Name == arquivoMovido).FirstOrDefault();
listView.SelectedItem = arquivoSelecionado;
listView.ScrollIntoView(arquivoSelecionado);
}
catch (Exception)
{
MessageBox.Show("Não foi possível mover o arquivo. Por favor aguarde alguns segundo e tente novamente.", "Aguarde", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void listViewImportados_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (listViewImportados.Items.Count > 0)
{
arquivoSelecionadoImportados = (FileInfo)listViewImportados.SelectedItem;
CarregaInformacoesDoArquivoImportado();
}
}
catch (Exception ex)
{
MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message);
CarregarTodosProcessos();
}
try
{
if (listView.Items.Count > 0)
{
try
{
{
arquivoSelecionado = (FileInfo)listView.SelectedItem;
CarregaInformacoesDoArquivo();
}
}
catch (Exception)
{
CarregarTodosProcessos();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ocorreu um erro inesperado. " + ex.Message);
CarregarTodosProcessos();
}
}
private void moverImportados_Click(object sender, RoutedEventArgs e)
{
string pathImportados = parametros.PathSelosImportados + @"\" + arquivoSelecionado.Name;
string pathNaoImportados = parametros.PathSelosNaoImportados + @"\" + arquivoSelecionado.Name;
try
{
if (File.Exists(pathImportados))
File.Delete(pathImportados);
arquivoSelecionado = new FileInfo(pathNaoImportados);
if (arquivoSelecionado.Exists)
arquivoSelecionado.MoveTo(pathImportados);
string arquivoMovido = arquivoSelecionado.Name;
CarregarSelosImportados();
CarregarSelosNaoImpotados();
tabItemImportarSelos.IsSelected = true;
arquivoSelecionadoImportados = listArquivosImportados.Where(p => p.Name == arquivoMovido).FirstOrDefault();
listViewImportados.SelectedItem = arquivoSelecionadoImportados;
listViewImportados.ScrollIntoView(arquivoSelecionadoImportados);
}
catch (Exception)
{
MessageBox.Show("Não foi possível mover o arquivo. Por favor aguarde alguns segundo e tente novamente.", "Aguarde", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void dataGridHistorico_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
CompraSelo compraSelo = (CompraSelo)dataGridHistorico.SelectedItem;
Series serie = _AppServicoSeries.ConsultarPorIdCompraSelo(compraSelo.CompraSeloId).FirstOrDefault();
List<Series> series = new List<Series>();
series.Add(serie);
listViewSeries.ItemsSource = null;
listViewSeries.Items.Clear();
listViewSeries.ItemsSource = series;
if (listViewSeries.Items.Count > 0)
listViewSeries.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridSelosIndisponiveis_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var detalhesSelo = new DetalhesDoSelo(seloIndisponivelSelecionado, _usuario);
detalhesSelo.Owner = this;
detalhesSelo.ShowDialog();
listSelosIndisponiveisSerieSelecionada[dataGridSelosIndisponiveis.SelectedIndex] = _AppServicoSelos.GetById(seloIndisponivelSelecionado.SeloId);
dataGridSelosIndisponiveis.Items.Refresh();
}
}
}
|
using Microsoft.AspNetCore.Hosting;
namespace IDI.Digiccy.Transaction.Service
{
internal abstract class HostService
{
public HostService(IWebHost host) { }
protected virtual void OnStarting(string[] args) { }
protected virtual void OnStarted() { }
protected virtual void OnStopped() { }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TubeController : MonoBehaviour
{
private float speed = 1;
private GameController gameController;
private void Awake()
{
gameController = FindObjectOfType<GameController>();
speed = gameController.defilementSpeed;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (gameController.GameIsOn)
{
transform.Translate(new Vector2(-1, 0) * Time.deltaTime * speed);
if (transform.position.x < -2.5)
{
Destroy(this.gameObject);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Application;
using Dapper.DBContext;
using EBS.Domain.Service;
using EBS.Domain.Entity;
using EBS.Domain.ValueObject;
using EBS.Application.DTO;
using Newtonsoft.Json;
using EBS.Application.Facade.Mapping;
namespace EBS.Application.Facade
{
public class PurchaseContractFacade : IPurchaseContractFacade
{
IDBContext _db;
PurchaseContractService _service;
ProcessHistoryService _processHistoryService;
SupplierService _supplierService;
public PurchaseContractFacade(IDBContext dbContext)
{
_db = dbContext;
_service = new PurchaseContractService(this._db);
_processHistoryService = new ProcessHistoryService(this._db);
_supplierService = new SupplierService(this._db);
}
public void Create(CreatePurchaseContract model)
{
var entity = new PurchaseContract();
entity = model.MapTo<PurchaseContract>();
entity.AddPurchaseContractItem(model.ConvertJsonToPurchaseContractItem());
entity.UpdatedBy = entity.CreatedBy;
_service.ValidateContractCode(entity.Code);
// _service.ValidateContract(entity);
_db.Insert(entity);
_db.SaveChange();
var reason = "创建合同";
entity = _db.Table.Find<PurchaseContract>(n => n.Code == entity.Code);
_processHistoryService.Track(model.CreatedBy, model.CreatedByName, (int)entity.Status, entity.Id, FormType.PurchaseContract, reason);
_db.SaveChange();
}
public void Edit(EditPurchaseContract model)
{
var entity = _db.Table.Find<PurchaseContract>(model.Id);
if (model.Code != entity.Code)
{
_service.ValidateContractCode(model.Code);
}
entity = model.MapTo<PurchaseContract>(entity);
entity.AddPurchaseContractItem(model.ConvertJsonToPurchaseContractItem());
entity.UpdatedOn = DateTime.Now;
// _service.ValidateContract(entity);
_db.Update(entity);
_db.Delete<PurchaseContractItem>(n => n.PurchaseContractId == model.Id);
_db.Insert<PurchaseContractItem>(entity.Items.ToArray());
var reason = "修改合同";
_processHistoryService.Track(model.UpdatedBy, model.UpdatedByName, (int)entity.Status, entity.Id, FormType.PurchaseContract, reason);
_db.SaveChange();
}
public void Delete(int id, int editBy, string editor, string reason)
{
var entity = _db.Table.Find<PurchaseContract>(id);
entity.Cancel();
entity.EditBy(editBy);
_db.Update(entity);
_processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, FormType.PurchaseContract, reason);
_db.SaveChange();
}
public void Submit(int id, int editBy, string editor)
{
var entity = _db.Table.Find<PurchaseContract>(id);
entity.Submit();
entity.EditBy(editBy);
_db.Update(entity);
var reason = "提交审核";
_processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, FormType.PurchaseContract, reason);
_db.SaveChange();
}
public void Audit(int id, int editBy, string editor)
{
var entity = _db.Table.Find<PurchaseContract>(id);
entity.Audit();
entity.EditBy(editBy);
_db.Update(entity);
//审核通过后,修改商品明细在比价状态中的比价状态
var supplyProducts= _supplierService.EditSupplyStatus(entity.Id, entity.SupplierId, editBy);
if (supplyProducts.Any())
{
_db.Update(supplyProducts.ToArray());
}
// 记录操作流程
var reason = "审核通过";
_processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, FormType.PurchaseContract, reason);
_db.SaveChange();
}
}
}
|
namespace TripDestination.Data.Models
{
public enum TripStatus
{
Open = 1,
Closed = 2,
InProgress = 3,
Finished = 4
}
}
|
namespace Properties.Models
{
public class Photo
{
public string PhotoReference { get; set; }
public string PhotoUrl { get; set; }
public int Index { get; set; }
}
} |
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
namespace CODE.Framework.Wpf.Documents
{
/// <summary>Paragraph object capable of displaying simple HTML fragments as part of Flow Documents</summary>
[ContentProperty("Html")]
public class HtmlParagraph : Paragraph
{
/// <summary>HTML string (fragment with limited HTML support)</summary>
public string Html
{
get { return (string)GetValue(HtmlProperty); }
set { SetValue(HtmlProperty, value); }
}
/// <summary>HTML string (fragment with limited HTML support)</summary>
public static readonly DependencyProperty HtmlProperty = DependencyProperty.Register("Html", typeof(string), typeof(HtmlParagraph), new UIPropertyMetadata("", RepopulateInlines));
/// <summary>Leading HTML string (fragment with limited HTML support)</summary>
public string LeadingHtml
{
get { return (string)GetValue(LeadingHtmlProperty); }
set { SetValue(LeadingHtmlProperty, value); }
}
/// <summary>Leading HTML string (fragment with limited HTML support)</summary>
public static readonly DependencyProperty LeadingHtmlProperty = DependencyProperty.Register("LeadingHtml", typeof(string), typeof(HtmlParagraph), new UIPropertyMetadata("", RepopulateInlines));
/// <summary>Trailing HTML string (fragment with limited HTML support)</summary>
public string TrailingHtml
{
get { return (string)GetValue(TrailingHtmlProperty); }
set { SetValue(TrailingHtmlProperty, value); }
}
/// <summary>Trailing HTML string (fragment with limited HTML support)</summary>
public static readonly DependencyProperty TrailingHtmlProperty = DependencyProperty.Register("TrailingHtml", typeof(string), typeof(HtmlParagraph), new UIPropertyMetadata("", RepopulateInlines));
/// <summary>Defines whether spaces are trimmed off at the start of the paragraph</summary>
public bool TrimLeadingSpaces
{
get { return (bool)GetValue(TrimLeadingSpacesProperty); }
set { SetValue(TrimLeadingSpacesProperty, value); }
}
/// <summary>Defines whether spaces are trimmed off at the start of the paragraph</summary>
public static readonly DependencyProperty TrimLeadingSpacesProperty = DependencyProperty.Register("TrimLeadingSpaces", typeof(bool), typeof(HtmlParagraph), new UIPropertyMetadata(true, RepopulateInlines));
/// <summary>Defines whether spaces are trimmed off at the start of the paragraph</summary>
public bool TrimLeadingTabs
{
get { return (bool)GetValue(TrimLeadingTabsProperty); }
set { SetValue(TrimLeadingTabsProperty, value); }
}
/// <summary>Defines whether spaces are trimmed off at the start of the paragraph</summary>
public static readonly DependencyProperty TrimLeadingTabsProperty = DependencyProperty.Register("TrimLeadingTabs", typeof(bool), typeof(HtmlParagraph), new UIPropertyMetadata(true, RepopulateInlines));
/// <summary>Re-creates the actual paragraph inlines based on the HTML as well as leading and trailing inlines</summary>
/// <param name="source">Special Paragraph object</param>
/// <param name="e">Event arguments</param>
private static void RepopulateInlines(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var paragraph = source as HtmlParagraph;
if (paragraph == null) return;
paragraph.Inlines.Clear();
paragraph.Inlines.AddRange(paragraph.LeadingHtml.ToInlines(paragraph.TrimLeadingSpaces, paragraph.TrimLeadingTabs));
paragraph.Inlines.AddRange(paragraph.Html.ToInlines(paragraph.TrimLeadingSpaces, paragraph.TrimLeadingTabs));
paragraph.Inlines.AddRange(paragraph.TrailingHtml.ToInlines(paragraph.TrimLeadingSpaces, paragraph.TrimLeadingTabs));
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
[SerializeField] private GameObject player_prefab;
[SerializeField] private Vector3 spawn_location;
private GameObject player;
public static GameManager instance = null;
private void Awake()
{
if (instance != this && instance != null)
{
Destroy(this);
}
instance = this;
}
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
// Reloads the entire level to reset the game state
if (player.transform.position.y <= -6)
{
// Respawns with current state intact
// Respawn01();
ReloadLevel();
}
}
public void ReloadLevel()
{
SceneManager.LoadScene("Level 01");
}
public void LevelComplete()
{
// Player successfully completed level
StartCoroutine(player.GetComponent<PlayerController>().Win());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Data;
namespace TestTutorial101
{
public partial class ForgotPasswaord : System.Web.UI.Page
{
BusLogic _bl = new BusLogic();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillNewEvent();
}
}
private void FillNewEvent()
{
DataTable dt = new DataTable();
dt = _bl.GetAllField("NewEvent", "Id", "desc");
rptNews.DataSource = dt;
rptNews.DataBind();
}
private string Decryptdata(string decryptPwd)
{
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(decryptPwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;
}
protected void btnForget_Click(object sender, EventArgs e)
{
if (txtEmail.Text.Trim() == "")
{
lblRegisMsg.Text = "Email ID can not be empty";
}
else
{
DataTable st = new DataTable();
st = _bl.GetEmail(txtEmail.Text.Trim());
if (st.Rows.Count > 0)
{
string decrptpass = Decryptdata(st.Rows[0]["pass"].ToString());
Send_mails sms = new Send_mails();
if (sms.SendMailForgetPassword(txtEmail.Text, st.Rows[0]["Name"].ToString(), decrptpass, Server.MapPath("~/Mail/forget-password.htm")))
{
lblRegisMsg.Text = "your password sucessfully send at " + txtEmail.Text;
lblRegisMsg.ForeColor = System.Drawing.Color.Green;
txtEmail.Text = "";
}
}
else
{
lblRegisMsg.Text = "Invaild EmailID";
return;
}
}
}
}
} |
namespace StackTask
{
/// <summary>
/// Main class of program of realization stack
/// contains creating a stack adding and removing elements and it clearing.
/// </summary>
class EntryPoint
{
static void Main(string[] args)
{
Stack<int> stack = new Stack<int>();
for (int i = 0; i < 5; i++)
{
stack.Push(i);
}
stack.Pop();
stack.Peek();
stack.Clear();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace Westerhoff.Configuration.EnvironmentAliases.Test
{
public class IntegrationTests
{
[Fact]
public void VariablesAreMapped()
{
Environment.SetEnvironmentVariable("APP_TEST_DATABASE", "Data Source=mydatabase.db");
Environment.SetEnvironmentVariable("APP_TEST_NUMBER", "12345");
Environment.SetEnvironmentVariable("APP_TEST_STUFF", "Foo bar baz");
Environment.SetEnvironmentVariable("APP_TEST_NOTMAPPED", "This should not appear anywhere");
var configuration = new ConfigurationBuilder()
.AddEnvironmentAliases(new Dictionary<string, string>()
{
["APP_TEST_DATABASE"] = "ConnectionStrings:Default",
["APP_TEST_NUMBER"] = "Settings:Nested:Number",
["APP_TEST_STUFF"] = "Stuff",
["APP_TEST_NOTSPECIFIED"] = "Settings:Text",
})
.Build();
Assert.Equal(6, configuration.AsEnumerable().Count());
var keys = configuration.AsEnumerable().Select(kv => kv.Key).ToList();
Assert.Contains("ConnectionStrings", keys);
Assert.Contains("ConnectionStrings:Default", keys);
Assert.Contains("Settings", keys);
Assert.Contains("Settings:Nested", keys);
Assert.Contains("Settings:Nested:Number", keys);
Assert.Contains("Stuff", keys);
Assert.Equal("Data Source=mydatabase.db", configuration.GetConnectionString("Default"));
Assert.Equal("12345", configuration["Settings:Nested:Number"]);
Assert.Equal("Foo bar baz", configuration["Stuff"]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MerchantRPG.Data
{
public class ItemTemplate
{
public readonly string Name;
public readonly int Level;
public readonly ItemSlot Slot;
public readonly ItemStereotype Stereotype;
public readonly double Attack;
public readonly double MagicAttack;
public readonly double Accuracy;
public readonly double CriticalRate;
public readonly double Defense;
public readonly double MagicDefense;
public readonly double Strength;
public readonly double Intelligence;
public readonly double Dexterity;
public readonly double HP;
public ItemTemplate(string name, int level, ItemSlot slot, ItemStereotype stereotype, double attack = 0, double magicAttack = 0, double accuracy = 0, double criticalRate = 0, double defense = 0, double magicDefense = 0, double strength = 0, double intelligence = 0, double dexterity = 0, double hp = 0)
{
this.Name = name;
this.Level = level;
this.Slot = slot;
this.Stereotype = stereotype;
this.Attack = attack;
this.MagicAttack = magicAttack;
this.Accuracy = accuracy;
this.CriticalRate = criticalRate;
this.Defense = defense;
this.MagicDefense = magicDefense;
this.Strength = strength;
this.Intelligence = intelligence;
this.Dexterity = dexterity;
this.HP = hp;
}
public Item Make(double roll)
{
return new Item(this,
statFunc(Stereotype.AttackBase, Stereotype.AttackPerLevel, roll) + Attack,
statFunc(Stereotype.MagicAttackBase, Stereotype.MagicAttackPerLevel, roll) + MagicAttack,
statFunc(Stereotype.AccuracyBase, Stereotype.AccuracyPerLevel, roll) + Accuracy,
Stereotype.CriticalRate + CriticalRate,
statFunc(Stereotype.DefenseBase, Stereotype.DefensePerLevel, roll) + Defense,
statFunc(Stereotype.MagicDefenseBase, Stereotype.MagicDefensePerLevel, roll) + MagicDefense,
Strength,
Intelligence,
Dexterity,
HP);
}
private double statFunc(double baseValue, double perLevelValue, double roll)
{
double average = baseValue + Level * perLevelValue;
double min = Math.Floor(average * 0.9);
double max = Math.Ceiling(average * 1.1);
return min + (max - min) * roll;
}
}
}
|
using System;
using Xunit;
namespace NStandard.Test
{
public class EnumOptionTests
{
private enum ETest { Default = 16 }
[Fact]
public void Test1()
{
var a0 = new EnumOption(typeof(ETest), nameof(ETest.Default));
var a1 = new EnumOption(typeof(ETest), nameof(ETest.Default));
Assert.Equal(a0, a1);
}
[Fact]
public void Test2()
{
var a0 = new EnumOption(typeof(ETest), nameof(ETest.Default));
var b0 = new EnumOption<ETest, int>(nameof(ETest.Default));
var b1 = new EnumOption<ETest, int>(16);
Assert.Equal(a0, b0);
Assert.Equal(b0, a0);
Assert.Equal(b0, b1);
Assert.Throws<InvalidOperationException>(() => new EnumOption<ETest, byte>(16));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQJoinFile
{
class Program
{
static void Main(string[] args)
{
string[] names = System.IO.File.ReadAllLines(@"names.csv");
string[] scores = System.IO.File.ReadAllLines(@"scores.csv");
//根据ID匹配成绩表和名称表数据,并输出带名字的成绩单
var scoresQuery1 =
from name in names
let nameField = name.Split(',')
from score in scores
let scoreField = score.Split(',')
where Convert.ToInt32(nameField[2]) == Convert.ToInt32(scoreField[0])
select $"{nameField[0]} {nameField[1]}:{scoreField[1]},{scoreField[2]},{scoreField[3]},{scoreField[4]}";
foreach(var item in scoresQuery1)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
/*
* Omelchenko Svetlana: 97, 92, 81, 60
* O'Donnell Claire: 75, 84, 91, 39
* Mortensen Sven: 88, 94, 65, 91
* Garcia Cesar: 97, 89, 85, 82
* Garcia Debra: 35, 72, 91, 70
* Fakhouri Fadi: 99, 86, 90, 94
* Feng Hanying: 93, 92, 80, 87
* Garcia Hugo: 92, 90, 83, 78
* Tucker Lance: 68, 79, 88, 92
* Adams Terry: 99, 82, 81, 79
* Zabokritski Eugene: 96, 85, 91, 60
* Tucker Michael: 94, 92, 91, 91
*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Conditions;
using Conditions.Guards;
using Properties.Core.Interfaces;
using Properties.Core.Objects;
using Swashbuckle.Swagger.Annotations;
namespace Properties.Controllers
{
[RoutePrefix("api/properties/{propertyReference:length(1,12)}/videos")]
public class VideosController : ApiController
{
private readonly IVideoService _videoService;
public VideosController( IVideoService videoService)
{
Check.If(videoService).IsNotNull();
_videoService = videoService;
}
[HttpGet, Route("")]
public List<Models.Video> GetPropertyVideos(string propertyReference)
{
Check.If(propertyReference).IsNotNullOrEmpty();
return
_videoService.GetVideosForProperty(propertyReference).Select(Mapper.Map<Models.Video>).ToList();
}
[HttpGet, Route("{videoReference:length(1,10)}", Name = "GetPropertyVideo")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof (Models.Video))]
public HttpResponseMessage GetPropertyVideo(string propertyReference, string videoReference)
{
Check.If(propertyReference).IsNotNullOrEmpty();
Check.If(videoReference).IsNotNullOrEmpty();
var result = _videoService.GetVideoForProperty(propertyReference, videoReference);
return result.IsNull()
? Request.CreateResponse(HttpStatusCode.NotFound)
: Request.CreateResponse(Mapper.Map<Models.Video>(result));
}
[HttpPost, Route("")]
public HttpResponseMessage PostVideo(string propertyReference, Models.Video video)
{
Check.If(propertyReference).IsNotNullOrEmpty();
Check.If(video).IsNotNull();
var result = _videoService.CreateVideo(propertyReference, Mapper.Map<Video>(video));
if(result == null)
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError };
}
var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created };
response.Headers.Location = new Uri(Url.Link("GetPropertyVideo", new { propertyReference, videoReference = result }));
return response;
}
[HttpPut, Route("{videoReference:length(1,10)}")]
public HttpResponseMessage PutVideo(string propertyReference, string videoReference, Models.Video video)
{
Check.If(propertyReference).IsNotNullOrEmpty();
Check.If(videoReference).IsNotNullOrEmpty();
Check.If(video).IsNotNull();
var result = _videoService.UpdateVideo(propertyReference, videoReference, Mapper.Map<Video>(video));
return result
? new HttpResponseMessage { StatusCode = HttpStatusCode.OK }
: new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError };
}
[HttpDelete, Route("{videoReference:length(1,10)}")]
public HttpResponseMessage DeleteVideo(string propertyReference, string videoReference)
{
Check.If(propertyReference).IsNotNullOrEmpty();
Check.If(videoReference).IsNotNullOrEmpty();
var result = _videoService.DeleteVideo(propertyReference, videoReference);
return result
? new HttpResponseMessage { StatusCode = HttpStatusCode.NoContent }
: new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError };
}
}
}
|
using System.Collections.Generic;
using System.Threading;
using Framework.Core.Common;
using Framework.Core.Config;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.Event
{
public class EventUpdate : EventBasePage
{
public EventUpdate(Driver driver) : base(driver) { }
#region Methods
/// <summary>
/// navigate directly to event update page by event id
/// </summary>
public void GoToEventUpdate(string eventId)
{
_driver.GoToPage(AppConfig.OberonBaseUrl + "Event/Update?EventId=" + eventId);
_driver.WaitForElementToDisplayBy(UpdateButtonLocator);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// Author: Corwin Belser
/// Allows active states to be stored for wall types in tile prefabs,
/// preventing them from being overriden when the base prefab is updated
[ExecuteInEditMode]
public class PrefabActiveTogglePropertyLock : MonoBehaviour {
/// <summary>
/// string constants for doing string.Contains to find wall components for a given orientation
/// </summary>
public static class Orientation
{
public const string North = "N";
public const string South = "S";
public const string East = "E";
public const string West = "W";
}
/// <summary>
/// string constants for for doing string.Contains to find individual wall components
/// </summary>
/// <TODO> _Door will match both _Doorway & _Door</TODO>
public static class WallType
{
public const string Passable = "_Passable";
public const string Impassable = "_Impassable";
public const string Doorway = "_Doorway";
public const string Door = "_Door";
}
/// <summary>
/// Holds Active states of wall types for an orientation
/// </summary>
[System.Serializable]
public class PrefabProperty
{
public string orientation;
public bool passable;
public bool impassable;
public bool doorway;
public bool door;
public override string ToString()
{
return orientation + "\r\n"
+ "\t" + "passable: " + passable.ToString() + "\r\n"
+ "\t" + "impassable: " + impassable.ToString() + "\r\n"
+ "\t" + "doorway: " + doorway.ToString() + "\r\n"
+ "\t" + "door: " + door.ToString() + "\r\n";
}
}
public PrefabProperty[] prefabProperties; /* Array of orientations present on the prefab */
/// <summary>
/// Creates a PrefabProperty for an orientation, setting the Active state of the wall components
/// </summary>
/// <param name="orientation"> The Orientation string const</param>
/// <returns></returns>
private PrefabProperty ReadActiveState(string orientation)
{
PrefabProperty prefabProperty = new PrefabProperty();
prefabProperty.orientation = orientation;
for (int i = 0; i < transform.childCount; i++)
{
GameObject child = transform.GetChild(i).gameObject;
if (child.name.Contains(orientation + "_"))
{
if (child.name.Contains(WallType.Passable))
prefabProperty.passable = child.activeSelf;
else if (child.name.Contains(WallType.Impassable))
prefabProperty.impassable = child.activeSelf;
else if (child.name.Contains(WallType.Doorway))
prefabProperty.doorway = child.activeSelf;
else if (child.name.Contains(WallType.Door))
prefabProperty.door = child.activeSelf;
}
}
return prefabProperty;
}
/// <summary>
/// Overwrites the active states of wall components for all wall orientations
/// </summary>
private void WriteActiveStates()
{
foreach (PrefabProperty prefabProperty in prefabProperties)
{
for (int i = 0; i < transform.childCount; i++)
{
GameObject child = transform.GetChild(i).gameObject;
if (child.name.Contains(prefabProperty.orientation + "_"))
{
if (child.name.Contains(WallType.Passable))
child.SetActive(prefabProperty.passable);
else if (child.name.Contains(WallType.Impassable))
child.SetActive(prefabProperty.impassable);
else if (child.name.Contains(WallType.Doorway))
child.SetActive(prefabProperty.doorway);
else if (child.name.Contains(WallType.Door))
child.SetActive(prefabProperty.door);
}
}
}
}
/// <summary>
/// Initializes the prefabProperties variable, inserting a PrefabProperty instance for each instance found
/// </summary>
public void SetupPrefabProperties()
{
/* Determine how many orientations are attached to this prefab */
int orientationCount = 0;
if (name.Contains(Orientation.North)) orientationCount++;
if (name.Contains(Orientation.South)) orientationCount++;
if (name.Contains(Orientation.East)) orientationCount++;
if (name.Contains(Orientation.West)) orientationCount++;
if (orientationCount == 0)
return;
/* Initialize each orientation */
prefabProperties = new PrefabProperty[orientationCount];
int index = 0;
if (name.Contains(Orientation.North))
{
prefabProperties[index] = ReadActiveState(Orientation.North);
index++;
}
if (name.Contains(Orientation.South))
{
prefabProperties[index] = ReadActiveState(Orientation.South);
index++;
}
if (name.Contains(Orientation.East))
{
prefabProperties[index] = ReadActiveState(Orientation.East);
index++;
}
if (name.Contains(Orientation.West))
{
prefabProperties[index] = ReadActiveState(Orientation.West);
index++;
}
}
/// <summary>
/// Called when script is started. Initializes if not already
/// </summary>
public void Start()
{
if (prefabProperties == null)
SetupPrefabProperties();
}
/// <summary>
/// Called from PrefabPropertyLockEditor when a change is made
/// </summary>
public void UpdateActiveStates()
{
if (prefabProperties != null && prefabProperties.Length != 0)
{
foreach (PrefabProperty prefabProperty in prefabProperties)
WriteActiveStates();
}
}
}
|
using System;
using LinkedListExample.Lib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListExample.Tests
{
[TestClass]
public class BasicLinkedListTests
{
// Unit test work just make sure you are debugging in the right folder
[TestMethod]
public void TestEmpty()
{
IntegerLinkedList ill = new IntegerLinkedList();
Assert.AreEqual(0, ill.Count);
}
[TestMethod]
public void TestCount()
{
var ill = new IntegerLinkedList(5);
ill.Append(7);
ill.Append(9);
Assert.AreEqual(3, ill.Count);
}
[TestMethod]
public void TestSum()
{
var ill = new IntegerLinkedList(5);
ill.Append(7);
ill.Append(9);
Assert.AreEqual(21, ill.Sum);
}
[TestMethod]
public void TestToStringExplicit()
{
var ill = new IntegerLinkedList(5);
ill.Append(7);
ill.Append(8);
ill.Append(9);
Assert.AreEqual("{5, 7, 8, 9}", ill.ToStr);
}
[TestMethod]
public void TestDelete()
{
var ill = new IntegerLinkedList(5);
ill.Append(7);
ill.Append(8);
ill.Delete(7);
ill.Append(9);
Assert.AreEqual("{5, 8, 9}", ill.ToStr); // I found it easier to use ToStr to test my delete
}
}
} |
using System.IO;
namespace AxiEndPoint.EndPointClient.Crypt
{
public interface ICryptor
{
byte[] EncryptData(byte[] bytes, byte[] cryptKey);
byte[] DecryptData(byte[] bytes, byte[] cryptKey);
Stream EncryptData(Stream data, byte[] cryptKey);
Stream DecryptData(Stream data, byte[] cryptKey);
}
} |
using ClientDependency.Core;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.PropertyEditors;
namespace Our.Umbraco.Tuple.PropertyEditors
{
[PropertyEditor(PropertyEditorAlias, PropertyEditorName, "JSON", PropertyEditorViewPath, Group = "Common", Icon = "icon-sience", IsParameterEditor = false)]
[PropertyEditorAsset(ClientDependencyType.Css, "~/App_Plugins/Tuple/tuple.css")]
[PropertyEditorAsset(ClientDependencyType.Javascript, "~/App_Plugins/Tuple/tuple.js")]
public class TuplePropertyEditor : PropertyEditor
{
public const string PropertyEditorAlias = "Our.Umbraco.Tuple";
public const string PropertyEditorName = "Tuple";
public const string PropertyEditorViewPath = "~/App_Plugins/Tuple/tuple.html";
protected override PreValueEditor CreatePreValueEditor()
{
return new TuplePreValueEditor();
}
protected override PropertyValueEditor CreateValueEditor()
{
return new TuplePropertyValueEditor(base.CreateValueEditor());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Aeropuerto
{
class Validation
{
public static void SoloLetras(KeyPressEventArgs V)
{
if (Char.IsLetter(V.KeyChar))
{
V.Handled = false;
}
else if (Char.IsSeparator(V.KeyChar))
{
V.Handled = false;
}
else if (char.IsControl(V.KeyChar))
{
V.Handled = false;
}
else
{
V.Handled = true;
// DialogResult resultado = new DialogResult();
// MensajeDeError error = new MensajeDeError("Entre solo letras");
//resultado = error.ShowDialog();
}
}
public static void SoloNumeros(KeyPressEventArgs V)
{
if (Char.IsDigit(V.KeyChar))
{
V.Handled = false;
}
else if (Char.IsSeparator(V.KeyChar))
{
V.Handled = false;
}
else if (char.IsControl(V.KeyChar))
{
V.Handled = false;
}
else
{
V.Handled = true;
//DialogResult resultado = new DialogResult();
// MensajeDeError error = new MensajeDeError("Entre solo números");
// resultado = error.ShowDialog();
}
}
public static void SoloDoubles(KeyPressEventArgs V)
{
if (Char.IsDigit(V.KeyChar))
{
V.Handled = false;
}
else if (Char.IsSeparator(V.KeyChar))
{
V.Handled = false;
}
else if (char.IsControl(V.KeyChar))
{
V.Handled = false;
}
else if (V.KeyChar.ToString().Equals("."))
{
V.Handled = false;
}
else
{
V.Handled = true;
// DialogResult resultado = new DialogResult();
// MensajeDeError error = new MensajeDeError("Entre solo números");
//resultado = error.ShowDialog();
}
}
public static void NoEscribir(KeyPressEventArgs V)
{
if (Char.IsDigit(V.KeyChar))
{
V.Handled = true;
}
else if (Char.IsSeparator(V.KeyChar))
{
V.Handled = true;
}
else if (char.IsControl(V.KeyChar))
{
V.Handled = true;
}
else if (V.KeyChar.ToString().Equals("."))
{
V.Handled = true;
}
else
{
V.Handled = true;
// DialogResult resultado = new DialogResult();
// MensajeDeError error = new MensajeDeError("Entre solo números");
//resultado = error.ShowDialog();
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomUtils {
public static T RandomItem<T>(System.Random r, List<T> items) {
int index = (int) Mathf.Floor((float)r.NextDouble() * items.Count);
return items[index];
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma warning disable 0649 // For serialized fields
using UnityEngine;
using Random = UnityEngine.Random;
public class Flock : FingerSurface
{
[System.Serializable]
public struct Boid
{
public Vector2 Position;
public Vector2 Velocity;
public Vector2 Acceleration;
public float Rotation;
}
[System.Serializable]
public struct SurfaceBoid
{
public Vector3 Position;
public Quaternion Rotation;
public Vector3 Normal;
public float Offset;
internal float Agitation;
}
[System.Serializable]
public struct Force
{
public bool Enabled;
public bool Active;
public Vector2 Position;
public float Radius;
}
public override float SurfaceRadius
{
get { return oceanCollider.radius; }
}
public Transform[] Fingers => fingers;
public Force[] Forces => forces;
public Transform SurfaceTransform => surfaceTransform;
[SerializeField]
private MeshSampler sampler;
[SerializeField]
private SphereCollider oceanCollider;
[SerializeField]
private int numBoids = 512;
[SerializeField]
private float coherenceAmount = 0.5f;
[SerializeField]
private float alignmentAmount = 0.5f;
[SerializeField]
private float separationAmount = 0.5f;
[SerializeField]
private float fleeAmount = 1f;
[SerializeField]
private float maxSpeed = 1f;
[SerializeField]
private float maxForce = 0.035f;
[SerializeField]
private float minDistance = 0.05f;
[SerializeField]
private float boidRespawnTime = 1f;
[SerializeField]
private float surfaceBounce = 0.015f;
[SerializeField]
private float surfaceBounceSpeed = 10;
[SerializeField]
private float agitationMultiplier = 0.15f;
[SerializeField]
private Vector2 forceRadius = Vector2.one;
[SerializeField]
private GameObject splashPrefab;
[SerializeField]
private AnimationCurve bounceCurve;
[SerializeField]
private Vector3 flockRotate;
[Header("Audio")]
[SerializeField]
private AudioSource normalAudio;
[SerializeField]
private AudioSource fleeingAudio;
[SerializeField]
private float masterVolume = 0.25f;
[SerializeField]
private float audioChangeSpeed = 0.25f;
[SerializeField]
private int numBoidsFleeingMaxVolume = 100;
[SerializeField]
private Mesh boidMesh;
[SerializeField]
private Material boidMat;
[SerializeField]
private float boidScale;
private float crowdNoisePing;
private int numBoidsFleeing = 0;
[SerializeField]
private Texture2D positionMap;
private Bounds meshBounds;
private Force[] forces;
private Boid[] boids;
private SurfaceBoid[] surfaceBoids;
private Matrix4x4[] boidMatrices;
public void PingCrowdNoises()
{
crowdNoisePing = 1;
}
protected override void Awake()
{
base.Awake();
normalAudio.volume = 0;
fleeingAudio.volume = 0;
}
public override void Initialize(Vector3 surfacePosition)
{
base.Initialize(surfacePosition);
sampler.SampleMesh(false);
meshBounds = sampler.Bounds;
boids = new Boid[numBoids];
surfaceBoids = new SurfaceBoid[numBoids];
boidMatrices = new Matrix4x4[numBoids];
for (int i = 0; i < numBoids; i++)
{
Boid b = new Boid();
MeshSample s = sampler.Samples[Random.Range(0, sampler.Samples.Length)];
b.Position = s.UV;
b.Rotation = Random.Range(0, 360);
boids[i] = b;
SurfaceBoid sb = new SurfaceBoid();
sb.Offset = Random.value;
surfaceBoids[i] = sb;
}
forces = new Force[fingers.Length];
}
private void Update()
{
if (!Initialized)
return;
surfaceTransform.Rotate(flockRotate * Time.deltaTime);
for (int i = 0; i < fingers.Length; i++)
{
Force f = forces[i];
if (!fingers[i].gameObject.activeSelf)
{
f.Enabled = false;
forces[i] = f;
continue;
}
f.Enabled = true;
float distToSphere = Vector3.Distance(fingers[i].position, surfaceTransform.position);
if (distToSphere > SurfaceRadius)
{
float distToSurface = 1f - Mathf.Clamp01(forceRadius.x / (distToSphere - SurfaceRadius));
f.Radius = Mathf.Lerp(forceRadius.x, forceRadius.y, distToSurface);
}
else
{
float distToSurface = Mathf.Clamp01(forceRadius.x / (distToSphere - SurfaceRadius));
f.Radius = Mathf.Lerp(forceRadius.x, forceRadius.y, distToSurface);
}
f.Position = ProjectFingerPosition(fingers[i].position);
forces[i] = f;
}
UpdateBoids(Time.time, Time.deltaTime);
DrawSurfaceBoids();
UpdateAudio();
}
private void UpdateAudio()
{
float normalizedBoidsFleeing = Mathf.Clamp01((float)numBoidsFleeing / numBoidsFleeingMaxVolume);
normalAudio.volume = Mathf.Lerp(normalAudio.volume, (1f - normalizedBoidsFleeing) * masterVolume, 0.5f);
float fleeingAudioVolume = Mathf.Clamp01((normalizedBoidsFleeing + crowdNoisePing) * masterVolume);
crowdNoisePing = Mathf.Clamp01(crowdNoisePing - Time.deltaTime * 5);
if (fleeingAudioVolume > fleeingAudio.volume)
{
fleeingAudio.volume = fleeingAudioVolume;
}
else
{
fleeingAudio.volume = Mathf.Lerp(fleeingAudio.volume, fleeingAudioVolume, Time.deltaTime * audioChangeSpeed);
}
}
private void DrawSurfaceBoids()
{
Vector3 scale = Vector3.one * boidScale;
for (int i = 0; i < numBoids; i++)
{
SurfaceBoid b = surfaceBoids[i];
float bounce = bounceCurve.Evaluate(Mathf.Repeat((b.Offset + Time.time) * (surfaceBounceSpeed * b.Agitation), 1f)) * surfaceBounce;
boidMatrices[i] = Matrix4x4.TRS(b.Position + (b.Normal * bounce), b.Rotation, scale);
}
Graphics.DrawMeshInstanced(boidMesh, 0, boidMat, boidMatrices);
}
private Vector2 ProjectFingerPosition(Vector3 position)
{
MeshSample sample = sampler.ClosestSample(surfaceTransform.InverseTransformPoint(position));
return sample.UV;
}
private void UpdateBoids(float time, float deltaTime)
{
Vector2 sumPositions = Vector2.zero;
Vector2 sumVelocities = Vector2.zero;
Vector2 averagePosition = Vector2.zero;
Vector2 averageVelocity = Vector2.zero;
int newNumBoidFleeing = 0;
for (int i = 0; i < numBoids; i++)
{
Boid b = boids[i];
sumPositions += b.Position;
sumVelocities += b.Velocity;
}
averagePosition = sumPositions / numBoids;
averageVelocity = sumVelocities / numBoids;
for (int b1i = 0; b1i < numBoids; b1i++)
{
Boid b1 = boids[b1i];
Vector2 desiredAverageDirection = (averagePosition - b1.Position).normalized;
Vector2 separationDirection = Vector2.zero;
Vector2 fleeDirection = Vector2.zero;
Vector2 forceAveragePosition = Vector2.zero;
Vector2 difference = Vector2.zero;
int numBoidsInRange = 0;
for (int b2i = 0; b2i < numBoids; b2i++)
{
if (b1i == b2i)
continue;
Boid b2 = boids[b2i];
float dist = DistanceBetween(b1.Position, b2.Position, ref difference);
if (dist < minDistance)
{
separationDirection += (difference.normalized / dist);
numBoidsInRange++;
}
}
int numForcesInRange = 0;
for (int fi = 0; fi < forces.Length; fi++)
{
Force f = forces[fi];
if (!f.Enabled || !f.Active)
continue;
float dist = DistanceBetween(b1.Position, f.Position, ref difference);
if (dist < f.Radius)
{
fleeDirection += (difference.normalized / dist);
forceAveragePosition += f.Position;
numForcesInRange++;
newNumBoidFleeing++;
}
}
// Alignment and coherence happen regardless of proximity
Vector2 alignment = Steer(b1.Velocity, averageVelocity);
Vector2 coherence = Steer(b1.Velocity, desiredAverageDirection);
Vector2 newVelocity = (alignmentAmount * alignment) + (coherenceAmount * coherence);
if (numBoidsInRange > 0)
{
// Separation happens if any boids were in range
separationDirection = (separationDirection / numBoidsInRange).normalized;
Vector2 separation = Steer(b1.Velocity, separationDirection * maxSpeed);
newVelocity += (separationAmount * separation);
}
// Do a smooth lerp for alignment, coherence and separation
b1.Velocity = Vector2.Lerp(b1.Velocity, LimitMagnitude(newVelocity, maxSpeed), deltaTime);
if (numForcesInRange > 0)
{
// Flee is more disruptive
// Use disance to force center to determine flee amount
forceAveragePosition = (forceAveragePosition / numForcesInRange);
fleeDirection = (fleeDirection / numForcesInRange).normalized;
float distToForceCenter = DistanceBetween(b1.Position, forceAveragePosition, ref difference);
float normalizedFleeForce = Mathf.Clamp01(distToForceCenter / forceRadius.y);
Vector2 flee = Steer(b1.Velocity, fleeDirection * fleeAmount * normalizedFleeForce);
// Don't limit flee velocity
b1.Velocity = b1.Velocity + flee;
}
// Make sure boids don't go out of range
Vector2 position = b1.Position + (b1.Velocity * deltaTime);
position.x = Mathf.Repeat(position.x, 1);
position.y = Mathf.Repeat(position.y, 1);
b1.Position = position;
b1.Rotation = Mathf.Lerp(b1.Rotation, Mathf.Atan2(b1.Velocity.y, b1.Velocity.x) * Mathf.Rad2Deg, deltaTime);
boids[b1i] = b1;
}
numBoidsFleeing = newNumBoidFleeing;
Vector3 origin = surfaceTransform.position;
for (int i = 0; i < numBoids; i++)
{
Boid b = boids[i];
SurfaceBoid sb = surfaceBoids[i];
sb.Agitation = 1f + (b.Velocity.magnitude * agitationMultiplier);
sb.Position = SampleSurface(b.Position);
sb.Normal = (sb.Position - origin).normalized;
Vector3 up = Quaternion.AngleAxis(b.Rotation, Vector3.forward) * Vector3.right;
sb.Rotation = Quaternion.LookRotation(sb.Normal, up);
surfaceBoids[i] = sb;
}
}
private Vector3 SampleSurface(Vector2 position)
{
Color c = positionMap.GetPixelBilinear(position.x, position.y);
Vector3 pos = Vector3.zero;
pos.x = c.r * meshBounds.size.x;
pos.y = c.g * meshBounds.size.y;
pos.z = c.b * meshBounds.size.z;
pos = pos - meshBounds.extents - meshBounds.center;
return surfaceTransform.TransformPoint(pos);
}
private Vector2 Steer(Vector2 current, Vector2 desired)
{
return LimitMagnitude(desired - current, maxForce);
}
private float DistanceBetween(Vector2 p1, Vector2 p2, ref Vector2 diff)
{
diff.x = p1.x - p2.x;
diff.y = p1.y - p2.y;
return diff.magnitude;
}
private Vector2 LimitMagnitude(Vector2 v, float max)
{
if (v.sqrMagnitude > max * max)
v = v.normalized * max;
return v;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
foreach (Transform finger in fingers)
Gizmos.DrawWireSphere(finger.position, 0.05f);
if (!Application.isPlaying)
return;
Gizmos.color = Color.Lerp(Color.yellow, Color.clear, 0.75f);
foreach (Force f in forces)
{
if (!f.Enabled)
continue;
Vector3 position = Quaternion.Euler(-90f, 0f, 0f) * f.Position;
Gizmos.DrawSphere(position, f.Radius);
}
foreach (Boid b in boids)
{
Gizmos.color = Color.magenta;
Vector3 forward = Vector3.forward;
Vector3 position = Quaternion.Euler(-90f, 0f, 0f) * b.Position;
Gizmos.DrawCube(position, Vector3.one * minDistance * 0.5f);
if (!Mathf.Approximately(b.Rotation, 0))
{
forward = Quaternion.Euler(0f, b.Rotation, 0f) * Vector3.forward;
}
Gizmos.DrawLine(position, position + (forward * 0.05f));
Gizmos.color = Color.Lerp(Color.magenta, Color.clear, 0.65f);
Gizmos.DrawWireSphere(position, minDistance);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Robotiv2
{
public class Weapon : Items
{
public int combatpower;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ShopMVC.Models
{
public class TovarCategory
{
public IEnumerable<TovarModels> Tovars { get; set; }
public SelectList Categories { get; set; }
}
} |
using Acr.UserDialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIMAYE.businesslayer;
using UIMAYE.classes;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace UIMAYE.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
int saniye = 1500;
bl b = new bl();
int gorevId;
int projeId;
bool k = true;
object syncLock = new object();
public MainPage(string gorev,int gorevId,int projeId, int kaldigi)
{
InitializeComponent();
this.gorevId = gorevId;
this.projeId = projeId;
saniye = kaldigi;
if (gorevId == 0) gizle.IsVisible = false;
gorevCek(gorev);
}
private void gorevCek(string gorev)
{
gorevAdi.Text = gorev;
timer(saniye);
}
public async void dondur(int dur)
{
if (k)
{
uint x = (uint)(saniye * 1000);
await box.RotateTo(360, x, Easing.SinInOut);
}
else
{
uint x = (uint)(dur * 1000);
await box.RotateTo(360, x, Easing.SinInOut);
}
}
private void ToolbarItem_Clicked(object sender, EventArgs e)
{
Navigation.PushModalAsync(new ProjeTab());
}
private void ToolbarItem_Clicked_1(object sender, EventArgs e)
{
Navigation.PushModalAsync(new Singing());
}
private bool _kontrol;
private bool kontrol
{
get
{
lock (this.syncLock)
{
return this._kontrol;
}
}
set
{
lock (this.syncLock)
{
this._kontrol = value;
}
}
}
int kalanZaman;
private void timer(int zaman)
{
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
dondur(zaman);
if (k)
{
zaman -= 1;
kalanZaman = zaman;
int dakika = zaman / 60;
int saniye = zaman % 60;
dakika = dakika % 60;
lblZaman.Text = String.Format("{0} : {1}", dakika, saniye);
if (zaman == 0.00)
{
SureBitir();
return false;
}
return true;
}
else
{
dondur(0);
return false;
}
});
}
private async void SureBitir()
{
k = false;
var id = Application.Current.Properties["id"];
if (gorevId == 0)
{
await b.TaskState(Convert.ToInt32(id), gorevId, 4, 0);
await Navigation.PushModalAsync(new Gorevler(projeId));
}
else
{
LocalTask lt = await b.TaskState(Convert.ToInt32(id), gorevId, 2, 0);
await DisplayAlert("Süre Doldu", "Geri sayım süresi bitti!", "Ok");
LocalSetting ls = await b.GetSetting(Convert.ToInt32(id));
if (ls.kacinciSure % 4 == 0)
{
await Navigation.PushModalAsync(new MainPage("MOLA", 0, 0, (int)ls.uzunMola));
}
else
{
await Navigation.PushModalAsync(new MainPage("MOLA", 0, 0, (int)ls.kisaMola));
}
}
}
private async void GucuKes_Click(object sender, EventArgs e)
{
k = false;
var id = Application.Current.Properties["id"];
LocalTask lt = await b.TaskState(Convert.ToInt32(id), gorevId, 1, kalanZaman);
await DisplayAlert("Bilgi", "Görevi tamamladınız", "Tamam");
await Navigation.PushModalAsync(new Gorevler(projeId));
}
private async void Duraklat_Click(object sender, EventArgs e)
{
k = false;
var id = Application.Current.Properties["id"];
await DisplayAlert("Duraklat", "Görev Duraklatma!", "Tamam");
LocalTask lt = await b.TaskState(Convert.ToInt32(id), gorevId, 2, kalanZaman);
await Navigation.PushModalAsync(new Gorevler(projeId));
}
private void YenidenBaslat_Click(object sender, EventArgs e)
{
DisplayAlert("Görev Yeniden Başlat", "Görev süresi sıfırlama!", "Tamam");
}
private void Hmenu_Click(object sender, EventArgs e)
{
ActionSheetConfig cfg = new ActionSheetConfig();
cfg.Add("a", null, null);
cfg.Add("b", null, null);
cfg.Add("c", null, null);
UserDialogs.Instance.ActionSheet(cfg);
}
}
} |
using SimpleRESTChat.Entities;
using SimpleRESTChat.Services.Enumerations;
namespace SimpleRESTChat.Services.BusinessObjects
{
public class UserBo
{
public UserBo(string id, UserAction userAction)
{
Id = id;
UserAction = userAction;
}
public UserBo(User user, UserAction userAction)
{
User = user;
Id = user.Id;
UserAction = userAction;
}
public string Id { get; set; }
public User User { get; set; }
public UserAction UserAction { get; set; }
}
}
|
using CPClient.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace CPClient.Data.Interfaces
{
public interface IEnderecoTipoRepository : IRepository<EnderecoTipo>
{
}
}
|
using System;
namespace DemoApplication.Pattern2_Prototype
{
public abstract class BasicCar
{
public string Brand { get; set; }
public string Engine { get; set; }
public string Transmission { get; set; }
public int Price { get; set; }
public static int SetPrice()
{
return new Random().Next(200000, 500000);
}
public abstract BasicCar Clone();
}
}
|
//-----------------------------------------------------------------------
// <copyright file="CameraPoseFinder.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Kinect.Fusion
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// CameraPoseFinder encapsulates camera pose finder creation, updating and pose-finding functions.
/// </summary>
public sealed class CameraPoseFinder : IDisposable
{
/// <summary>
/// The default minimum distance threshold for capturing key frame poses for use in ProcessFrame.
/// </summary>
public const float DefaultMinimumDistanceThreshold = 0.3f;
/// <summary>
/// The native CameraPoseFinder interface wrapper.
/// </summary>
private INuiFusionCameraPoseFinder cameraPoseFinder;
/// <summary>
/// Track whether Dispose has been called.
/// </summary>
private bool disposed = false;
/// <summary>
/// Initializes a new instance of the CameraPoseFinder class.
/// Default constructor used to initialize with the native CameraPoseFinder object.
/// </summary>
/// <param name="poseFinder">
/// The native CameraPoseFinder object to be encapsulated.
/// </param>
internal CameraPoseFinder(INuiFusionCameraPoseFinder poseFinder)
{
this.cameraPoseFinder = poseFinder;
}
/// <summary>
/// Finalizes an instance of the CameraPoseFinder class.
/// This destructor will run only if the Dispose method does not get called.
/// </summary>
~CameraPoseFinder()
{
Dispose();
}
/// <summary>
/// Initialize a Kinect Fusion cameraPoseFinder.
/// A Kinect camera is required to be connected.
/// </summary>
/// <param name="cameraPoseFinderParameters">
/// The parameters to define the number of poses and feature sample locations the camera pose finder uses.
/// </param>
/// <returns>The CameraPoseFinder instance.</returns>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="cameraPoseFinderParameters"/> parameter is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="cameraPoseFinderParameters"/> parameter's
/// <c>featureSampleLocationsPerFrameCount</c>, <c>maxPoseHistoryCount</c> member is not a greater than 0,
/// or the <c>featureSampleLocationsPerFrameCount</c> member is greater than 1000.
/// </exception>
/// <exception cref="OutOfMemoryException">
/// Thrown when the memory required for the camera pose finder 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 call failed for an unknown reason.
/// </exception>
public static CameraPoseFinder FusionCreateCameraPoseFinder(
CameraPoseFinderParameters cameraPoseFinderParameters)
{
if (null == cameraPoseFinderParameters)
{
throw new ArgumentNullException("cameraPoseFinderParameters");
}
INuiFusionCameraPoseFinder poseFinder = null;
ExceptionHelper.ThrowIfFailed(NativeMethods.NuiFusionCreateCameraPoseFinder2(
cameraPoseFinderParameters,
IntPtr.Zero,
out poseFinder));
return new CameraPoseFinder(poseFinder);
}
/// <summary>
/// Initialize a Kinect Fusion cameraPoseFinder, with random number generator seed for feature
/// locations and feature thresholds.
/// </summary>
/// <param name="cameraPoseFinderParameters">
/// The parameters to define the number of poses and feature sample locations the camera pose finder uses.
/// </param>
/// <param name="randomFeatureLocationAndThresholdSeed">
/// A seed to initialize the random number generator for feature locations and feature thresholds.
/// </param>
/// <returns>The CameraPoseFinder instance.</returns>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="cameraPoseFinderParameters"/> parameter is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="cameraPoseFinderParameters"/> parameter's
/// <c>featureSampleLocationsPerFrameCount</c>, <c>maxPoseHistoryCount</c> member is not a greater than 0,
/// or a maximum of 10,000,000, the <c>featureSampleLocationsPerFrameCount</c> member is greater than 1000,
/// or the <paramref name="randomFeatureLocationAndThresholdSeed"/> parameter is negative.
/// </exception>
/// <exception cref="OutOfMemoryException">
/// Thrown when the memory required for the camera pose finder 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 call failed for an unknown reason.
/// </exception>
public static CameraPoseFinder FusionCreateCameraPoseFinder(
CameraPoseFinderParameters cameraPoseFinderParameters,
int randomFeatureLocationAndThresholdSeed)
{
if (null == cameraPoseFinderParameters)
{
throw new ArgumentNullException("cameraPoseFinderParameters");
}
uint seed = ExceptionHelper.CastAndThrowIfOutOfUintRange(randomFeatureLocationAndThresholdSeed);
INuiFusionCameraPoseFinder poseFinder = null;
ExceptionHelper.ThrowIfFailed(NativeMethods.NuiFusionCreateCameraPoseFinder(
cameraPoseFinderParameters,
ref seed,
out poseFinder));
return new CameraPoseFinder(poseFinder);
}
/// <summary>
/// Clear the cameraPoseFinder.
/// </summary>
/// <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 ResetCameraPoseFinder()
{
ExceptionHelper.ThrowIfFailed(cameraPoseFinder.ResetCameraPoseFinder());
}
/// <summary>
/// Test input camera frames against the camera pose finder database, adding frames to the
/// database if dis-similar enough to existing frames. Both input depth and color frames
/// must be identical sizes, a minimum size of 80x60, with valid camera parameters, and
/// captured at the same time.
/// Note that once the database reaches its maximum initialized size, it will overwrite old
/// pose information. Check the <pararmref name="pHistoryTrimmed"/> flag or the number of
/// poses in the database to determine whether the old poses are being overwritten.
/// </summary>
/// <param name="depthFloatFrame">The depth float frame to be processed.</param>
/// <param name="colorFrame">The color frame to be processed.</param>
/// <param name="worldToCameraTransform"> The current camera pose (usually the camera pose
/// result from the last AlignPointClouds or AlignDepthFloatToReconstruction).</param>
/// <param name="minimumDistanceThreshold">A float distance threshold between 0 and 1.0f which
/// regulates how close together poses are stored in the database. Input frames
/// which have a minimum distance equal to or above this threshold when compared against the
/// database will be stored, as it indicates the input has become dis-similar to the existing
/// stored poses. Set to 0.0f to ignore and always add a pose when this function is called,
/// however in this case, unless there is an external test of distance, there is a risk this
/// can lead to many duplicated poses.
/// </param>
/// <param name="addedPose">
/// Set true when the input frame was added to the camera pose finder database.
/// </param>
/// <param name="trimmedHistory">
/// Set true if the maxPoseHistoryCount was reached when the input frame is stored, so the
/// oldest pose was overwritten in the camera pose finder database to store the latest pose.
/// </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="depthFloatFrame"/> and <paramref name="colorFrame"/>
/// parameter is an incorrect or different image size, or their <c>CameraParameters</c>
/// member is null or has incorrectly sized focal lengths, or the
/// <paramref name="minimumDistanceThreshold"/> parameter is less than 0 or greater
/// than 1.0f.</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 camera pose finder works by accumulating whether the values at each sample location pixel
/// in a saved pose frame are less than or greater than a threshold which is randomly chosen
/// between minimum and maximum boundaries (e.g. for color this is 0-255). Given enough samples
/// this represents a unique key frame signature that we can match against, as different poses
/// will have different values for surfaces which are closer or further away, or different
/// colors.
/// Note that unlike depth, the robustness of finding a valid camera pose can have issues with
/// ambient illumination levels in the color image. For best matching results, both the Kinect
/// camera and also the environment should have exactly the same configuration as when the
/// database key frame images were captured i.e. if you had a fixed exposure and custom white
/// balance, this should again be set when testing the database later, otherwise the matching
/// accuracy will be reduced.
/// To improve accuracy, it is possible to not just provide a red, green, blue input in the
/// color image, but instead provide a different 3 channels of match data scaled 0-255. For
/// example, to be more illumination independent, you could calculate hue and saturation, or
/// convert RGB to to LAB and use the AB channels. Other measures such as texture response
/// or corner response could additionally be computed and used in one or more of the channels.
/// </remarks>
public void ProcessFrame(
FusionFloatImageFrame depthFloatFrame,
FusionColorImageFrame colorFrame,
Matrix4 worldToCameraTransform,
float minimumDistanceThreshold,
out bool addedPose,
out bool trimmedHistory)
{
if (null == depthFloatFrame)
{
throw new ArgumentNullException("depthFloatFrame");
}
if (null == colorFrame)
{
throw new ArgumentNullException("colorFrame");
}
HRESULT hr = cameraPoseFinder.ProcessFrame(
FusionImageFrame.ToHandleRef(depthFloatFrame),
FusionImageFrame.ToHandleRef(colorFrame),
ref worldToCameraTransform,
minimumDistanceThreshold,
out addedPose,
out trimmedHistory);
ExceptionHelper.ThrowIfFailed(hr);
}
/// <summary>
/// Find the most similar camera poses to the current camera input by comparing against the
/// camera pose finder database, and returning a set of similar camera poses. These poses
/// and similarity measurements are ordered in terms of decreasing similarity (i.e. the most
/// similar is first). Both input depth and color frames must be identical sizes, with valid
/// camera parameters and captured at the same time.
/// </summary>
/// <param name="depthFloatFrame">The depth float frame to be processed.</param>
/// <param name="colorFrame">The color frame to be processed.</param>
/// <returns>Returns the matched frames object created by the camera pose finder.</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"/> and <paramref name="colorFrame"/>
/// parameter is an incorrect or different image size, or their <c>CameraParameters</c>
/// member is null or has incorrectly sized focal lengths.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the Kinect Runtime could not be accessed,
/// or the call failed for an unknown reason.
/// </exception>
/// <returns>Returns a set of matched frames/poses.</returns>
public MatchCandidates FindCameraPose(
FusionFloatImageFrame depthFloatFrame,
FusionColorImageFrame colorFrame)
{
if (null == depthFloatFrame)
{
throw new ArgumentNullException("depthFloatFrame");
}
if (null == colorFrame)
{
throw new ArgumentNullException("colorFrame");
}
INuiFusionMatchCandidates matchCandidates = null;
ExceptionHelper.ThrowIfFailed(cameraPoseFinder.FindCameraPose(
FusionImageFrame.ToHandleRef(depthFloatFrame),
FusionImageFrame.ToHandleRef(colorFrame),
out matchCandidates));
return new MatchCandidates(matchCandidates);
}
/// <summary>
/// Load a previously saved camera pose finder database from disk.
/// Note: All existing data is replaced on a successful load of the database.
/// If the database is saved to disk alongside the reconstruction volume, when both are
/// re-loaded, this potentially enables reconstruction and tracking to be re-started
/// and the reconstruction updated by running the camera pose finder.
/// </summary>
/// <param name="fileName">The filename of the database file to load.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="fileName"/> is incorrect or the file was not found.</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 LoadCameraPoseFinderDatabase(
string fileName)
{
ExceptionHelper.ThrowIfFailed(cameraPoseFinder.LoadCameraPoseFinderDatabase(fileName));
}
/// <summary>
/// Save the camera pose finder database to disk.
/// If the camera pose finder database is saved to disk alongside the reconstruction volume,
/// when both are re-loaded, this potentially enables reconstruction and tracking to be
/// re-started and the reconstruction updated by running the camera pose finder.
/// </summary>
/// <param name="fileName">The filename of the database file to save.</param>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="fileName"/> is incorrect or the path was not found.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the Kinect Runtime could not be accessed, the device is not connected,
/// the device does not have enough space, or the call failed for an unknown reason.
/// </exception>
public void SaveCameraPoseFinderDatabase(
string fileName)
{
ExceptionHelper.ThrowIfFailed(cameraPoseFinder.SaveCameraPoseFinderDatabase(fileName));
}
/// <summary>
/// Get the parameters used in the camera pose finder.
/// </summary>
/// <returns>Returns the parameters used in the camera pose finder.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown when the Kinect Runtime could not be accessed, or
/// the call failed for an unknown reason.
/// </exception>
public CameraPoseFinderParameters GetCameraPoseFinderParameters()
{
CameraPoseFinderParameters parameters = new CameraPoseFinderParameters(
CameraPoseFinderParameters.Defaults.FeatureSampleLocationsPerFrame,
CameraPoseFinderParameters.Defaults.MaxPoseHistory,
CameraPoseFinderParameters.Defaults.MaxDepthThreshold);
HRESULT hr = cameraPoseFinder.GetCameraPoseFinderParameters(parameters);
ExceptionHelper.ThrowIfFailed(hr);
return parameters;
}
/// <summary>
/// Get the count of stored frames in the camera pose finder database.
/// </summary>
/// <returns>Returns the count of stored poses in the database.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown when the Kinect Runtime could not be accessed,
/// or the call failed for an unknown reason.
/// </exception>
public int GetStoredPoseCount()
{
return (int)cameraPoseFinder.GetStoredPoseCount();
}
/// <summary>
/// Disposes the CameraPoseFinder.
/// </summary>
public void Dispose()
{
if (!this.disposed)
{
Marshal.FinalReleaseComObject(cameraPoseFinder);
disposed = true;
}
// This object will be cleaned up by the Dispose method.
GC.SuppressFinalize(this);
}
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TwitterAnalytics.Domain.Models.SentimentAnalysis
{
public class ResponseRootObject
{
[JsonProperty("documents")] public List<ResponseDocument> Documents { get; set; }
[JsonProperty("errors")] public List<Error> Errors { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApartmentApps.Data
{
public interface IBaseEntity
{
int Id { get; }
DateTime? CreateDate { get; set; }
//DateTime? UpdateDate { get; set; }
}
public partial class Unit : PropertyEntity
{
public int BuildingId { get; set; }
[ForeignKey("BuildingId"),Searchable]
public virtual Building Building { get; set; }
public virtual ICollection<MaitenanceRequest> MaitenanceRequests { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
[Searchable]
public string Name { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
/// <summary>
/// This property should not be modified it is calculated on the nightly run
/// </summary>
public string CalculatedTitle { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using wsApiEPayment.Models;
using wsApiEPayment.Models.Openpay;
using wsApiEPayment.Services.Openpay;
namespace wsApiEPayment.Controllers
{
public class OpenpayController : ApiController
{
[Route("api/openpay/PostCargoComercio", Name = "PostCargoComercio")]
public Object PostCargoComercio(int IdEmpresa, [FromBody]VentaOP Venta, string DispositivoId)
{
OpenpayService servicio = new OpenpayService();
return servicio.CargoComercio(IdEmpresa, Venta, DispositivoId);
}
#region Método de cargo a tarjeta registrada en OpenPay
[Route("api/openpay/PostCargoId", Name = "PostCargoId")]
public Object PostCargoId(int aIdEmpresa, [FromBody]VentaIdTarjeta aVenta, string aIdT, string aDispositivoId)
{
OpenpayService servicio = new OpenpayService();
return servicio.CargoId(aIdEmpresa, aVenta, aIdT, aDispositivoId);
}
#endregion
#region Cancelar pago
[Route("api/openpay/PostCancelarPago", Name = "PostCancelarPago")]
public Object PostCancelarPago(int IdEmpresa, string IdCargo, string Description)
{
OpenpayService servicio = new OpenpayService();
return servicio.CancelarPago(IdEmpresa, IdCargo, Description);
}
#endregion
#region Obtener cargo
[Route("api/openpay/GetConsultaCargo", Name = "GetConsultaCargo")]
public Object GetConsultaCargo(int IdEmpresa, string IdCargo)
{
OpenpayService servicio = new OpenpayService();
return servicio.ObtenerCargo(IdEmpresa, IdCargo);
}
#endregion
#region Cargo sepi referencia
[Route("api/openpay/PostSPEI", Name = "PostSPEI")]
public Object PostSPEI(int IdEmpresa, [FromBody]ObSPEI Venta)
{
OpenpayService servicio = new OpenpayService();
return servicio.SPEI(IdEmpresa, Venta);
}
#endregion
#region Cargo spei
[Route("api/openpay/PostCargoSPEI", Name = "PostCargoSPEI")]
public Object PostCargoSPEI(int IdEmpresa, [FromBody]ChargeSPEI Venta)
{
OpenpayService servicio = new OpenpayService();
return servicio.CargoSPEI(IdEmpresa, Venta);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
private Rigidbody rbball;
private Vector3 direction = Vector3.one;
[SerializeField] private float force;
// Start is called before the first frame update
private int points1;
private int points2;
void Start()
{
// rbball = transform.GetComponent<Rigidbody>();
// direction = new Vector3(Random.Range(-1.0f, 1.0f), Random.Range(-10.0f, 10.0f), 0);
// rbball.AddForce(direction * force);
// points1 = 0;
// points2 = 0;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other) {
if (other.GetComponent<Collider>().CompareTag("Limit1"))
{
points1++;
print("Red Scores!");
print("Points: " + points1 + "-" + points2);
transform.position = Vector3.zero;
}
//if (other.collider.CompareTag("Limit2"))
if (other.GetComponent<Collider>().CompareTag("Limit2"))
{
points2++;
print("Blue Scores!");
print("Points: " + points1 + "-" + points2);
transform.position = Vector3.zero;
}
}
// private void OnCollisionEnter(Collision other) {
// if (other.collider.CompareTag("Limit1"))
// {
// points1++;
// print("Red Scores!");
// print("Points: " + points1 + "-" + points2);
// }
// //if (other.collider.CompareTag("Limit2"))
// if (other.collider.CompareTag("Limit2"))
// {
// points2++;
// print("Blue Scores!");
// print("Points: " + points1 + "-" + points2);
// }
// }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VnStyle.Services.Business.Models;
namespace VnStyle.Services.Business
{
public interface IArtistsService
{
IList<ArtistListingModel> GetAllArtists();
IEnumerable<ImagesByArtist> GetAllImageByArtist(int id);
IEnumerable<ImagesByArtist> GetAllImage();
IList<ArtistListingModel> GetImage();
}
}
|
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 JustRipeFarm.ClassEntity;
using MySql.Data.MySqlClient;
namespace JustRipeFarm
{
public partial class FormFertiliser : Form
{
List<Fertiliser> FertiliserList;
public string state = "";
public Fertiliser f11;
public FormFertiliser()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDone_Click(object sender, EventArgs e)
{
if (state == "Edit")
{
updateFertiliser();
}
else
{
if (String.IsNullOrEmpty(textBox1.Text))
{
if (String.IsNullOrEmpty(textBox2.Text))
{
if (String.IsNullOrEmpty(textBox3.Text))
{
MessageBox.Show("Please check last name again");
}
MessageBox.Show("Please check last name again");
}
MessageBox.Show("Please check first name again");
}
else
{
addFertiliser();
}
}
}
private void addFertiliser()
{
Fertiliser f1 = new Fertiliser();
f1.Name = textBox1.Text;
f1.Quantity_kg = Convert.ToInt32(textBox2.Text);
f1.Remark = textBox3.Text;
InsertSQL add = new InsertSQL();
int addrecord = add.addNewFertiliser(f1);
MessageBox.Show("Seccuess!!");
this.Close();
}
private void updateFertiliser()
{
Fertiliser f1 = new Fertiliser();
f1.Id = f11.Id;
f1.Name = textBox1.Text;
f1.Quantity_kg = Convert.ToInt32(textBox2.Text);
f1.Remark = textBox3.Text;
UpdateSQL add = new UpdateSQL();
int editrecord = add.updateFertiliser(f1);
MessageBox.Show("Seccuess!!");
this.Close();
}
private void FormFertiliser_Load(object sender, EventArgs e)
{
InsertSQL crop = new InsertSQL();
if (state == "Edit")
{
textBox1.Text = f11.Name;
textBox2.Text = f11.Quantity_kg.ToString();
textBox3.Text = f11.Remark;
}
}
}
}
|
using System;
namespace ConsoleApplication1
{
class StudentListHandlerEventArgs : EventArgs
{
public string Name { get; set; }
public string Type { get; set; }
public Student Stud { get; set; }
public StudentListHandlerEventArgs()
{
Name = "[empty]";
Type = "[empty]";
Stud = null;
}
public StudentListHandlerEventArgs(string name, string type, Student student)
{
Name = name;
Type = type;
Stud = student;
}
public override string ToString()
{
return $"Name of collection: {Name}\nType: {Type}\nStudent: {Stud}\n";
}
}
} |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using BerdziskoBot.Models;
using BerdziskoBot.Modules;
using BerdziskoBot.Services;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
namespace BerdziskoBot
{
class Program
{
static void Main(string[] args) =>
new Program().MainAsync(args).GetAwaiter().GetResult();
async Task MainAsync(string[] args)
{
var token = Environment.GetEnvironmentVariable("berdziskobot_token");
try
{
TokenUtils.ValidateToken(TokenType.Bot, token);
}
catch (ArgumentException)
{
Console.WriteLine("Provided token is not valid.");
Environment.Exit(1);
}
using (var services = ConfigureServices())
{
var client = services.GetRequiredService<DiscordSocketClient>();
client.Log += LogAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;
await client.LoginAsync(TokenType.Bot, token);
await client.StartAsync();
await services.GetRequiredService<CommandHandlingService>().InitializeAsync();
await services.GetRequiredService<GreetingsService>().InitializeAsync();
await Task.Delay(-1);
}
}
private Task LogAsync(LogMessage arg)
{
Console.WriteLine(arg.ToString());
return Task.CompletedTask;
}
private ServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddSingleton<Random>()
.AddSingleton<HttpClient>()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<LocalStorageService>()
.AddSingleton<CommandService>()
.AddSingleton<CommandHandlingService>()
.AddSingleton<GreetingsService>()
.AddSingleton<RedditMemesService>()
.BuildServiceProvider();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccess.Concrete.EntityFramework.Abstract;
using Entities.Concrete;
namespace DataAccess.Concrete.EntityFramework.Concrete
{
public class EfBrandDal : EfEntityRepository<Brand,ReCapContext>, IBrandDal
{
}
}
|
using CarRental.API.DAL.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CarRental.API.DAL.DataServices.Car
{
public interface ICarDataService
{
Task<CarItem> GetAsync(Guid id);
Task<IEnumerable<CarItem>> GetAllAsync();
Task<CarItem> CreateAsync(CarItem car);
Task<CarItem> DeleteAsync(Guid Id);
Task<IEnumerable<CarItem>> UpsertAsync(CarItem car);
Task<IEnumerable<CarItem>> MarkCarAsAvailable(CarItem car);
}
}
|
using BradescoPGP.Common;
using BradescoPGP.Repositorio;
using BradescoPGP.Web.Areas.Portabilidade.Enums;
using BradescoPGP.Web.Areas.Portabilidade.Interfaces;
using BradescoPGP.Web.Areas.Portabilidade.Models;
using BradescoPGP.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BradescoPGP.Web.Areas.Portabilidade.Controllers
{
public class GerencialIndicadoresRankingController : AbstractController
{
private readonly ISolicitacaoService _solicitacaoService;
private readonly PGPEntities _context;
private readonly IUsuarioService _usuario;
private readonly IUtil _util;
public GerencialIndicadoresRankingController(DbContext context, ISolicitacaoService solicitacaoService, IUtil util, IUsuarioService usuario) : base(context)
{
_solicitacaoService = solicitacaoService;
_context = context as PGPEntities;
_util = util;
_usuario = usuario as IUsuarioService;
}
// GET: Portabilidade/GerencialIndicadoresRanking
public ActionResult Index(FiltrosPortabilidade filtros = null)
{
var produtividade = _util.ObterProdutividade();
var modelRankin = GerarRanking(filtros);
var RetencaoAtual = produtividade
.Where(s => s.De <= DateTime.Now.Date && s.Parametro == OpcoesProdutividade.MinimoRetencao.ToString()).FirstOrDefault()?.ValorPercerntualMinino ?? 0;
var minimoContato = produtividade
.Where(s => s.De <= DateTime.Now.Date && s.Parametro == OpcoesProdutividade.MinimoContato.ToString()).FirstOrDefault()?.ValorPercerntualMinino ?? 0;
ViewBag.PercMinimoContato = minimoContato;
ViewBag.PercMinimoRetencao = RetencaoAtual;
ViewBag.Titulo = "Ranking de Especialistas";
return View(modelRankin.OrderByDescending(s => s.PorcentgemRetida).ToList());
}
private List<RankingViewModel> GerarRanking(FiltrosPortabilidade filtros)
{
var dados = _usuario.ObterTodosUsuarios();
//Traz apenas usuarios de um gestor
if (Cargo == NivelAcesso.Gestor.ToString())
{
dados = dados.Where(s => s.MatriculaSupervisor == MatriculaUsuario).ToList();
}
dados = dados.Where(u => u.PerfilId == 3).ToList();
var dataAtual = DateTime.Now;
var minDate = new DateTime(dataAtual.Year, dataAtual.Month, 1);
var maxDate = new DateTime(dataAtual.Year, dataAtual.Month, dataAtual.Day - 1);
var modelRankin = new List<RankingViewModel>();
dados.ForEach(m =>
{
var viewModel = new RankingViewModel();
var solicitacao = new List<Solicitacao>();
if (filtros.TemFiltro())
{
solicitacao = _solicitacaoService.Obter(filtros.De.Value, filtros.Ate.Value, m.Matricula);
}
else
{
solicitacao = _solicitacaoService.Obter(minDate, maxDate, m.Matricula);
}
//Remove não elegíveis
var idNaoElegivel = _context.Motivo.FirstOrDefault(s => s.Descricao.Contains("Não Elegível"))?.Id;
solicitacao = solicitacao.Where(s => s.MotivoId != idNaoElegivel).ToList();
viewModel.Especialista = m.Nome;
viewModel.QuantidadeSolicitacoes = solicitacao.Count();
viewModel.ValorSolicitacoes = solicitacao.Sum(s => s.ValorPrevistoSaida);
//Remove solicitacoes com motivo especifico para não ser incluido na contagem de valor de solicitações
var idMotivoCliente = _context.Motivo.FirstOrDefault(s => s.Descricao.Contains("Não Conseguiu Falar com o Cliente"))?.Id;
var solicitacoesNaoInclusas = solicitacao.Where(s =>
s.Motivo != null && s.MotivoId == idMotivoCliente)
.Sum(s => s.ValorPrevistoSaida);
//Porcentagem de contatos
var qtdContatado = solicitacao.Count(s => s.MotivoId.HasValue);
viewModel.Contatos = qtdContatado;
var qtdSolicitacaoes = viewModel.QuantidadeSolicitacoes == 0 ? 1 : viewModel.QuantidadeSolicitacoes;
viewModel.PorcentagemContatos = qtdContatado != 0 ? Math.Round(Convert.ToDecimal(qtdContatado) / qtdSolicitacaoes * 100, 2) : 0;
viewModel.QuantidadeRetida = solicitacao.Where(s => s.ValorRetido != null && s.SubStatusId == 1).Count();
viewModel.ValorRetido = solicitacao.Where(s => s.ValorRetido != null && s.SubStatusId == 1).Sum(s => s.ValorRetido ?? 0);
var totalSolicitacoes = viewModel.ValorSolicitacoes == 0 ? 1 : viewModel.ValorSolicitacoes;
var total = (totalSolicitacoes - solicitacoesNaoInclusas);
viewModel.PorcentgemRetida = total != 0 && viewModel.ValorRetido != 0 ? Math.Round(viewModel.ValorRetido / total * 100, 2) : 0;
modelRankin.Add(viewModel);
});
return modelRankin;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sparda.SettingProviderContext.DAL.V6.y2017_m9_d22_h13_m25_s45_ms528;
using System.Data.Services;
using System.Web;
using Sparda.Contracts;
using Sparda.Core.Helpers;
namespace Sparda.Core.Services.Contexts
{
public class MainSettingProviderContext : Sparda.SettingProviderContext.DAL.V6.y2017_m9_d22_h13_m25_s45_ms528.SettingProviderContext
{
public MainSettingProviderContext()
: base("SettingProviderContext")
{
}
}
public class MainSettingProviderService : Telerik.OpenAccess.DataServices.OpenAccessDataService<MainSettingProviderContext>
{
[ChangeInterceptor("Setting")]
public void OnChangeService(Setting setting, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (setting != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(setting, operations);
break;
case UpdateOperations.Change:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, setting.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Not allowed !");
}
EntityTrackingHelper.OnChangeInterceptor(setting, operations);
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, setting.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Setting>(this._service, operations);
NotifierHelper.NotifySettingsChanged(setting.Id);
}
}
}
}
|
using System;
using System.Windows.Forms;
using TY.SPIMS.Client.Helper;
using TY.SPIMS.Controllers;
using TY.SPIMS.Entities;
using TY.SPIMS.POCOs;
using TY.SPIMS.Utilities;
using ComponentFactory.Krypton.Toolkit;
using System.Collections.Generic;
using TY.SPIMS.Controllers.Interfaces;
namespace TY.SPIMS.Client.Payment
{
public partial class AddInvoiceForm : KryptonForm
{
private readonly ISaleController saleController;
private readonly ISalesReturnController salesReturnController;
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public event SelectionCompleteEventHandler SelectionComplete;
protected void OnSelectionComplete(SelectionCompleteEventArgs args)
{
SelectionCompleteEventHandler handler = SelectionComplete;
if (handler != null)
{
handler(this, args);
}
}
public AddInvoiceForm()
{
this.saleController = IOC.Container.GetInstance<SaleController>();
this.salesReturnController = IOC.Container.GetInstance<SalesReturnController>();
InitializeComponent();
}
private void AddInvoiceForm_Load(object sender, EventArgs e)
{
this.Text = string.Format("Select Invoice - {0}", this.CustomerName);
LoadInvoices();
}
private void LoadInvoices()
{
var dateFrom = DateFromPicker.Value;
var dateTo = DateToPicker.Value;
SaleFilterModel filter = new SaleFilterModel()
{
CustomerId = this.CustomerId,
Paid = PaidType.NotPaid,
DateType = dateFrom == dateTo ? DateSearchType.All : DateSearchType.DateRange,
DateFrom = dateFrom,
DateTo = dateTo,
Type = -1
};
var invoices = this.saleController.FetchSaleWithSearch(filter);
saleDisplayModelBindingSource.DataSource = invoices;
}
private void FilterButton_Click(object sender, EventArgs e)
{
LoadInvoices();
}
private void OkButton_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
SortableBindingList<SalesCounterItemModel> selectedItems = GetSelectedItems();
var args = new SelectionCompleteEventArgs(selectedItems);
OnSelectionComplete(args);
this.Close();
}
else
{
ClientHelper.ShowErrorMessage("No invoice selected.");
}
}
private SortableBindingList<SalesCounterItemModel> GetSelectedItems()
{
SortableBindingList<SalesCounterItemModel> result = new SortableBindingList<SalesCounterItemModel>(selectedInvoices);
return result;
}
SalesCounterItemModel selectedItem;
List<SalesCounterItemModel> selectedInvoices = new List<SalesCounterItemModel>();
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if(dataGridView1.SelectedRows.Count > 0)
{
DataGridViewRow row = dataGridView1.SelectedRows[0];
int id = (int)row.Cells[SalesIdColumn.Name].Value;
DateTime date = (DateTime)row.Cells[DateColumn.Name].Value;
string invoiceNumber = row.Cells[InvoiceNumberColumn.Name].Value.ToString();
decimal amount = (decimal)row.Cells[BalanceColumn.Name].Value;
selectedItem = new SalesCounterItemModel() {
SaleId = id,
Date = date,
InvoiceNumber = invoiceNumber,
Amount = amount
};
InvoiceNumberTextbox.Text = invoiceNumber;
InvoiceAmountTextbox.Value = amount;
InvoiceAmountTextbox.Focus();
CheckForInvoiceReturns();
}
}
List<SalesReturnDetailModel> returnsList = new List<SalesReturnDetailModel>();
private void CheckForInvoiceReturns()
{
returnsList.Clear();
if (selectedItem != null)
{
returnsList = this.salesReturnController.GetReturnsPerInvoice(selectedItem.InvoiceNumber);
salesReturnDetailModelBindingSource.DataSource = null;
if (returnsList.Count > 0)
{
salesReturnDetailModelBindingSource.DataSource = returnsList;
MemoNumberDropdown.SelectedIndex = -1;
MemoNumberDropdown.ComboBox.SelectedIndex = -1;
ReturnWarningLink.Visible = true;
}
else
{
ReturnWarningLink.Visible = false;
}
}
}
private void AddButton_Click(object sender, EventArgs e)
{
if (selectedItem != null && !string.IsNullOrWhiteSpace(InvoiceNumberTextbox.Text))
{
if (InvoiceAmountTextbox.Value > selectedItem.Amount)
{
ClientHelper.ShowErrorMessage("Amount cannot be greater than original amount.");
return;
}
selectedInvoices.RemoveAll(a => a.SaleId == selectedItem.SaleId);
string poNumber = this.saleController.GetPONumber(selectedItem.SaleId.Value);
selectedItem.Amount = InvoiceAmountTextbox.Value;
selectedItem.PONumber = !string.IsNullOrWhiteSpace(poNumber) ? poNumber : "-";
selectedInvoices.Insert(0, selectedItem);
BindSelectedInvoices();
ClearInvoiceSection();
}
}
private void ClearInvoiceSection()
{
InvoiceNumberTextbox.Clear();
InvoiceAmountTextbox.Value = 0;
dataGridView1.Focus();
}
private void BindSelectedInvoices()
{
salesCounterItemModelBindingSource.DataSource = null;
salesCounterItemModelBindingSource.DataSource = selectedInvoices;
}
SalesCounterItemModel selectedReturn;
private void MemoNumberDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (MemoNumberDropdown.SelectedIndex != -1)
{
int id = (int)MemoNumberDropdown.SelectedValue;
var item = returnsList.Find(a => a.Id == id);
selectedReturn = new SalesCounterItemModel()
{
ReturnId = id,
Date = item.ReturnDate.HasValue ? item.ReturnDate.Value : DateTime.Today,
MemoNumber = item.MemoNumber,
Amount = item.Balance
};
ReturnAmountTextbox.Value = item.Balance;
}
else
{
selectedReturn = null;
ReturnAmountTextbox.Value = 0;
}
}
private void AddReturnButton_Click(object sender, EventArgs e)
{
if (selectedReturn != null)
{
if (ReturnAmountTextbox.Value > selectedReturn.Amount)
{
ClientHelper.ShowErrorMessage("Amount cannot be greater than original amount.");
return;
}
selectedInvoices.RemoveAll(a => a.ReturnId == selectedReturn.ReturnId);
selectedReturn.Amount = ReturnAmountTextbox.Value;
selectedReturn.PONumber = "return";
selectedInvoices.Insert(0, selectedReturn);
BindSelectedInvoices();
ClearReturnSection();
}
}
private void ClearReturnSection()
{
MemoNumberDropdown.SelectedIndex = -1;
MemoNumberDropdown.ComboBox.SelectedIndex = -1;
}
}
public delegate void SelectionCompleteEventHandler(object sender, SelectionCompleteEventArgs args);
public class SelectionCompleteEventArgs : EventArgs
{
public SortableBindingList<SalesCounterItemModel> SelectedSalesItems { get; set; }
public SortableBindingList<PurchaseCounterItemModel> SelectedPurchaseItems { get; set; }
public SelectionCompleteEventArgs(SortableBindingList<SalesCounterItemModel> items)
{
this.SelectedSalesItems = items;
}
public SelectionCompleteEventArgs(SortableBindingList<PurchaseCounterItemModel> items)
{
this.SelectedPurchaseItems = items;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerControllerAndroid : MonoBehaviour
{
Rigidbody2D rb;
//Some var for run and animation
public float speed;
bool facingRight=true;
public Animator anim;
//public GameObject DustCloud;
//for die
public bool dieIfFalling;
public float diePosition;
public bool dead;
public bool completed;
//var for jump
public float jumpForce;
public int jumpValue;
private bool isJumping=false;// for anim
private bool isGround;
public Transform groundCheck;
public float rCheck;
public LayerMask whatIsGround;
public int extraJumpValue;
private int extraJump;
// Start is called before the first frame update
void Start()
{
//get Rigidbody2D
rb = GetComponent<Rigidbody2D>();
//Jump
extraJump = extraJumpValue;
}
void FixedUpdate()
{
//for run
float getHorizontal = CrossPlatformInputManager.GetAxis("Horizontal");
rb.velocity = new Vector2(getHorizontal*speed, rb.velocity.y);
anim.SetFloat("Run",Mathf.Abs(getHorizontal));
//Character facing
if(facingRight==true && getHorizontal<0){
Flip();
} else if (facingRight==false && getHorizontal>0) {
Flip();
}
//for falling die
if(dieIfFalling==true){
Vector2 tmpPosition = transform.position;
if(tmpPosition.y < diePosition){
dead=true;
}
}
}
void Update(){
//for jump
isGround=Physics2D.OverlapCircle(groundCheck.position,rCheck,whatIsGround);
if(isGround){
isJumping=false;
extraJump = extraJumpValue;
}else {
isJumping=true;
}
anim.SetBool("isJumping",isJumping);
if(CrossPlatformInputManager.GetButtonDown("Jump") && jumpValue>0 && extraJump>0){
rb.velocity = Vector2.up * jumpForce;
jumpValue--;
extraJump--;
} else if (CrossPlatformInputManager.GetButtonDown("Jump") && extraJump==0 && isGround==true && jumpValue>0) {
rb.velocity = Vector2.up * jumpForce;
jumpValue--;
}
}
// complete or die
void OnCollisionEnter2D(Collision2D other){
if(other.gameObject.tag == "Enemy"){
dead=true;
gameObject.SetActive(false);
}
}
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("Door")){
completed=true;
gameObject.SetActive(false);
}
if(other.gameObject.tag == "Enemy"){
dead=true;
gameObject.SetActive(false);
}
}
void Flip(){
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *=-1;
transform.localScale = Scaler;
}
}
|
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace My_News
{
class Excel_Helper
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
public void Create()
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
public void SetValue(int row, int col, string value)
{
xlWorkSheet.Cells[row, col] = value;
}
public void Save(string filename)
{
xlWorkBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
}
public void Open(string filename)
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
public string GetValue(int row, int col)
{
//return xlWorkSheet.get_Range(p1, p1).Value2;
return Convert.ToString(((Excel.Range)(xlWorkSheet.Cells[row, col])).Value2);
}
public void Close()
{
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception)
{
obj = null;
//MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
|
// Utility.cs
//
using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using System.Serialization;
using jQueryApi;
namespace SportsLinkScript.Shared.Facebook
{
public delegate void FBUiHandler(object response);
[IgnoreNamespace]
[Imported]
public static class FB
{
[PreserveCase]
public static Data Data;
[PreserveCase]
public static Event Event;
public static void Init(JsonObject nameValuePairs)
{
}
public static void Ui(JsonObject nameValuePairs, FBUiHandler handler)
{
}
public static void Api(string path, string method, JsonObject nameValuePairs, FBUiHandler handler)
{
}
public static void GetLoginStatus(FBSubscribeHandler handler) { }
}
}
|
using System;
namespace ClassRoom
{
public class Studerende
{
public string Name { get; }
public int BirthMonth { get; }
public int BirthDay { get; }
public Studerende()
{
}
public Studerende(string name, int birthMonth, int birthDay)
{
Name = name;
BirthMonth = birthMonth;
if (birthMonth > 12 || birthMonth < 1)
{
throw new ArgumentException("BirthMonth is invalid.");
}
BirthDay = birthDay;
}
}
} |
using IAPharmacySystemService.Settings;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace IntegrationAdaptersPharmacySystemService.MicroserviceComunicator
{
public class ActionBenefitService : IActionBenefitService
{
private HttpClient _httpClient;
public ActionBenefitService(IHttpClientFactory httpClientFactory, IOptions<ServiceSettings> serviceSettings)
{
_httpClient = httpClientFactory.CreateClient();
_httpClient.BaseAddress = new System.Uri(serviceSettings.Value.ActionBenefitServiceUrl);
}
public async Task<bool> Subscribe(string exchangeName)
{
var request = new HttpRequestMessage(HttpMethod.Patch, "actionbenefitservice/subscribe");
request.Content = new StringContent("\"" + exchangeName + "\"", Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
return false;
return true;
}
public async Task<bool> SubscriptionEdit(string exOld, bool subOld, string exNew, bool subNew)
{
var request = new HttpRequestMessage(HttpMethod.Patch, "actionbenefitservice/subscriptionedit");
request.Content = new StringContent(
JsonConvert.SerializeObject(new SubEditRequest(exOld, subOld, exNew, subNew)),
Encoding.UTF8,
"application/json");
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
return false;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace DATN_Hoa_Yambi.Controllers
{
public class PVLController : Controller
{
// GET: PVL
public ActionResult Index()
{
if (Session["User"] != null )
{
return View();
}
else
{
return RedirectToAction("Index", "User");
}
}
[HttpPost]
public string getPVL()
{
if (Session["User"] != null) // nếu có User thì mới bắt đầu tính toán
{
string macoc = Request["id_dm"];
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext(); // kết nối
if (macoc != null)
{
Session["MaCoc"] = macoc;
var qr = (from p in db.tbl_Users where p.MaNguoiDung == Session["User"].ToString() select p).FirstOrDefault(); // lấy ra người Dùng // lấy ra cọc
qr.MaCoc = macoc; // gán mã cọc của người dùng bằng mã cọc mới.
db.SubmitChanges(); // lưu lại
}
var qr_macoc = db.tbl_Users.Where(o => o.MaNguoiDung == Session["User"].ToString()).SingleOrDefault();
var query = from coc in db.tbl_cocs
join bt in db.tbl_betongs
on coc.id_betong equals bt.id_betong
where coc.MaCoc == qr_macoc.MaCoc
select new { Coc = coc, Bt = bt };
CalulatorSPT();
CalulatorCPT();
return JsonConvert.SerializeObject(query.SingleOrDefault());
}
else
{
return "500";
}
}
public void CalulatorSPT()
{
List<tbl_lop_dat> dsld = new List<tbl_lop_dat>();
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext();
// đầu cọc cách mắt đất lấy tạm 1m;
double Qa = 0;
double Qs = 0;
var qr = db.tbl_lop_dats;
if (qr.Any())
{
foreach (tbl_lop_dat item in qr)
{
dsld.Add(item); // thêm vào danh sách lớp đất;
}
}
// Tính cao độ cho các lớp đất
// cao độ 0 là đầu lớp đất 1
// Cao độ 1 là cuối lớp đất 1 và đầu lớp đất 2
// Cao độ 2 tính từ 0 cho đến cuối lớp đất 2 nền bằng lớp đất 1 cộng lớp đất 2, tương tự
List<double> Caodo = new List<double>();
Caodo.Add(0);
for (int i = 0; i <= dsld.Count - 1; i++)
{
double tong = 0;
for (int j = 0; j <= i; j++)
{
tong = (tong + (double)dsld[j].chieuday);
}
Caodo.Add(tong);
}
// Lấy ra người dùng.
var qr_us = db.tbl_Users.Where(NA => NA.MaNguoiDung == Session["User"].ToString()).SingleOrDefault();
// lấy ra được cọc của người đó đã chọn
var qr_coc = db.tbl_cocs.Where(NA => NA.MaCoc == qr_us.MaCoc).SingleOrDefault();
// xem cọc nằm ở lớp đất nào ?
int lopdat_index = 0;
for (int i = 0; i < Caodo.Count - 1; i++)
{
if (double.Parse(qr_coc.DoDai) > Caodo[i] && double.Parse(qr_coc.DoDai) < Caodo[i + 1])
{
lopdat_index = i + 1;
}
}
// Tính chu vi của cọc:
double u = (double)qr_coc.ChuVi_TD;
// Tính diện tích của cọc :
double F = (double)qr_coc.DienTich_TD;
#region "Tính Qs"
double[] qa = new double[10];
for (int i = 0; i < lopdat_index; i++)
{
if (i == 0)
{
// đoạn ngàm vào đài la 1m ,nên không thể lấy trọn vẹn lớp 1
qa[i] = ((double)dsld[i].chieuday - 1) * (double)dsld[i].n * 2 * u; // 2 là hệ số; u là chu vi
qa[i] = qa[i] / 3; // 3 là hệ số mình lấy
}
else if (i == lopdat_index - 1)
{
// Tính đoạn ngàm vào lớp đất cuối : chiều dài cọc + đoạn ngàm rồi trừ đi cao độ lớp trước
double lngam_end = 1 + double.Parse(qr_coc.DoDai) - Caodo[lopdat_index - 1];
qa[i] = lngam_end * (double)dsld[i].n * 2 * u;
qa[i] = qa[i] / 3;
}
else
{
qa[i] = ((double)dsld[i].chieuday) * (double)dsld[i].n * 2 * u;
qa[i] = qa[i] / 3;
}
Qs = Qs + qa[i];
}
#endregion
#region "Tính Qc"
// Tính Qc
double n = (double)dsld.LastOrDefault().n; // Lấy ra lớp đất cuối cùng trong danh sách
double Qc = (400 * n * F) / 3; // chuyển đôi sức kháng mũi sang sức kháng ma sát.
// Tính Qa
#endregion
#region "Tính Qa"
Qa = Math.Round((Qs + Qc), 3);
#endregion // Qa là Giá trị SPT mình Tính ra
// Cập nhật Qa vào dữ liệu của người dùng
qr_us.Spt = Qa;
db.SubmitChanges();
}
public void CalulatorCPT()
{
VuVanHoa_DatabaseDataContext db = new VuVanHoa_DatabaseDataContext();
List<tbl_lop_dat> dsld = new List<tbl_lop_dat>();
List<double> Caodo = new List<double>();
var pr_last = db.tbl_lop_dats.ToList().LastOrDefault();
var qr = db.tbl_lop_dats;
var qr_user = db.tbl_Users.Where(o => o.MaNguoiDung == Session["User"].ToString()).FirstOrDefault();
var qr_coc = db.tbl_cocs.Where(o => o.MaCoc == qr_user.MaCoc).SingleOrDefault();
double[] Ti = new double[10];
double[] Li = new double[10]; //m
double u; //m
double Qms = 0, Qs = 0;
double Qa = 0;
dsld = qr.ToList();
if (qr.Any())
{
//int i = 0;
//foreach (tbl_lop_dat item in qr)
//{
// // Sức kháng xuyên bằng Qc/ alpha!
// Ti[i] = (double)(item.suckhangxuyen / item.alpha);
// // Tính Chiều dày lớp đất Li :
// Li[i] = (double)item.chieuday;
// // Chuvi :
// u =(double)qr_coc.DuongKinhCoc * 4; // đơn vị là m
// // TÍnh Qms :
// Qms += Ti[i] * Li[i] * u;
// i++;
// }
Caodo.Add(0);
for (int k = 0; k <= dsld.Count - 1; k++)
{
double tong = 0;
for (int j = 0; j <= k; j++)
{
tong = (tong + (double)dsld[j].chieuday);
}
Caodo.Add(tong);
}
int lopdat_index = 0;
for (int i = 0; i < Caodo.Count - 1; i++)
{
if (double.Parse(qr_coc.DoDai) > Caodo[i] && double.Parse(qr_coc.DoDai) < Caodo[i + 1])
{
lopdat_index = i + 1;
}
}
for (int k = 0; k < lopdat_index; k++)
{
if (k == 0)
{
// đoạn ngàm vào đài la 1m ,nên không thể lấy trọn vẹn lớp 1
Ti[k] = (double)(dsld[k].suckhangxuyen / dsld[k].alpha);
// Tính Chiều dày lớp đất Li :
Li[k] = (double)dsld[k].chieuday - 1;
// Chuvi :
u = (double)qr_coc.DuongKinhCoc * 4; // đơn vị là m
Qms += Ti[k] * Li[k] * u;
}
else if (k == lopdat_index - 1)
{
// Tính đoạn ngàm vào lớp đất cuối : chiều dài cọc + đoạn ngàm rồi trừ đi cao độ lớp trước
double lngam_end = 1 + double.Parse(qr_coc.DoDai) - Caodo[lopdat_index - 1];
// đoạn ngàm vào đài la 1m ,nên không thể lấy trọn vẹn lớp 1
Ti[k] = (double)(dsld[k].suckhangxuyen / dsld[k].alpha);
u = (double)qr_coc.DuongKinhCoc * 4; // đơn vị là m
Qms += Ti[k] * lngam_end * u;
}
else
{
Ti[k] = (double)(dsld[k].suckhangxuyen / dsld[k].alpha);
// Tính Chiều dày lớp đất Li :
Li[k] = (double)dsld[k].chieuday;
// Chuvi :
u = (double)qr_coc.DuongKinhCoc * 4; // đơn vị là m
Qms += Ti[k] * Li[k] * u;
}
}
}
Qs = (double)(pr_last.k * pr_last.suckhangxuyen) * (double)qr_coc.DuongKinhCoc * (double)qr_coc.DuongKinhCoc;
Qa = (Qms + Qs) / 2;
// lưu dữ liệu
qr_user.Cpt = Qa;
db.SubmitChanges();
}
}
} |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using RimWorld;
using Verse;
using UnityEngine;
namespace SyrThrumkin
{
public class Frostleaf : Plant
{
public override float GrowthRate
{
get
{
if (Blighted)
{
return 0f;
}
else
{
return GrowthRateFactor_Fertility * GrowthRateFactor_TemperatureFrostleaf * GrowthRateFactor_Light;
}
}
}
public float GrowthRateFactor_TemperatureFrostleaf
{
get
{
if (!GenTemperature.TryGetTemperatureForCell(Position, Map, out float num))
{
return 1f;
}
if (num < -15f)
{
return Mathf.InverseLerp(-35f, -15f, num);
}
if (num > 15f)
{
return Mathf.InverseLerp(25f, 15f, num);
}
return 1f;
}
}
public override string GetInspectString()
{
StringBuilder stringBuilder = new StringBuilder();
if (this.LifeStage == PlantLifeStage.Growing)
{
stringBuilder.AppendLine("PercentGrowth".Translate(this.GrowthPercentString));
stringBuilder.AppendLine("GrowthRate".Translate() + ": " + this.GrowthRate.ToStringPercent());
if (!this.Blighted)
{
if (this.Resting)
{
stringBuilder.AppendLine("PlantResting".Translate());
}
if (!this.HasEnoughLightToGrow)
{
stringBuilder.AppendLine("PlantNeedsLightLevel".Translate() + ": " + this.def.plant.growMinGlow.ToStringPercent());
}
float growthRateFactor_Temperature = this.GrowthRateFactor_TemperatureFrostleaf;
if (growthRateFactor_Temperature < 0.99f)
{
if (growthRateFactor_Temperature < 0.01f)
{
stringBuilder.AppendLine("OutOfIdealTemperatureRangeNotGrowing".Translate());
}
else
{
stringBuilder.AppendLine("OutOfIdealTemperatureRange".Translate(Mathf.RoundToInt(growthRateFactor_Temperature * 100f).ToString()));
}
}
}
}
else if (this.LifeStage == PlantLifeStage.Mature)
{
if (this.HarvestableNow)
{
stringBuilder.AppendLine("ReadyToHarvest".Translate());
}
else
{
stringBuilder.AppendLine("Mature".Translate());
}
}
if (this.DyingBecauseExposedToLight)
{
stringBuilder.AppendLine("DyingBecauseExposedToLight".Translate());
}
if (this.Blighted)
{
stringBuilder.AppendLine("Blighted".Translate() + " (" + this.Blight.Severity.ToStringPercent() + ")");
}
return stringBuilder.ToString().TrimEndNewlines();
}
}
}
|
// Copyright (c) Christopher Clayton. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace praxicloud.core.metrics
{
#region Using Clauses
using System;
#endregion
/// <summary>
/// A metric that indicates an known event occurred
/// </summary>
public interface IPulse : IMetric
{
#region Methods
/// <summary>
/// Records that an event occurred
/// </summary>
void Observe();
#endregion
}
}
|
/*
* Company:
* Motto: Talk more to loved ones!
* Assignment: A book shelf application
* Deadline: 2012-01-02
* Programmer: Baran Topal
* Solution name: .BookShelfWeb
* Folder name: .DataAccess
* Project name: .BookShelfWeb.DAL
* File name: BookShelfUserDAL.cs
* Status: Finished
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using BookShelfWeb.IDAL;
using BookShelfWeb.BookShelfModel;
using BookShelfWeb.DataAccessHelper;
namespace BookShelfWeb.DAL
{
/// <summary>
/// BookShelfUser data access layer manipulations
/// </summary>
public class BookShelfUserDAL : IBookShelfUserDAL
{
#region member variables
public BookShelfUser bsu = new BookShelfUser();
#endregion member variables
#region constructors
/// <summary>
/// Ctor**
/// </summary>
/// <param name="userID"></param>
/// <param name="fullName"></param>
/// <param name="password"></param>
/// <param name="email"></param>
/// <param name="address"></param>
/// <param name="city"></param>
public BookShelfUserDAL(int userID, string fullName, string password, string email, string address, string city)
{
bsu.UserID = userID;
bsu.FullName = fullName;
bsu.Password = password;
bsu.Email = email;
bsu.Address = address;
bsu.City = city;
}
/// <summary>
/// Ctor**
/// </summary>
/// <param name="userID"></param>
public BookShelfUserDAL(int userID)
{
bsu.UserID = userID;
}
/// <summary>
/// Ctor**
/// </summary>
public BookShelfUserDAL()
{
}
#endregion constructors
#region Add
/// <summary>
/// Adding user
/// </summary>
/// <param name="userEntity">user</param>
/// <returns>affected row count</returns>
public int AddUser(BookShelfUser userEntity)
{
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.INSERT,
typeof(BookShelfUser),
"User",
null,
new string[] { "fullName", "password", "email", "address", "city" },
new object[] { userEntity.FullName, userEntity.Password, userEntity.Email, userEntity.Address, userEntity.City });
return SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetInsertSql(),
objCommandHelper.GetParameters());
}
#endregion Add
#region Update
/// <summary>
/// Update user
/// </summary>
/// <param name="userEntity">user</param>
/// <returns>Affected row count</returns>
public int UpdateUser(BookShelfUser userEntity)
{
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.UPDATE,
typeof(BookShelfUser),
"User",
null,
new string[] { "fullName", "password", "email", "address", "city" },
new object[] { userEntity.FullName, userEntity.Password, userEntity.Email, userEntity.Address, userEntity.City });
objCommandHelper.AddAditionalParameters("userID = @userID", new string[] { "userID" }, new object[] { userEntity.UserID });
return SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetUpdateSql(),
objCommandHelper.GetParameters());
}
/// <summary>
/// Update book membership of the user
/// </summary>
/// <param name="userID">user id</param>
/// <param name="bookEntity">book</param>
/// <param name="action">action</param>
/// <returns></returns>
public int UpdateBookMembership(int userID, BookShelfBook bookEntity, string action)
{
string bookName = bookEntity.BookName;
SqlCommandHelper objCommandHelper = null;
if (action == "Loan")
{
objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.UPDATE,
typeof(BookShelfBook),
"Book",
null,
new string[] { "userID", "bookStatus" },
new object[] { userID, 1 });
}
else
{
objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.UPDATE,
typeof(BookShelfBook),
"Book",
null,
new string[] { "userID", "bookStatus" },
new object[] { userID, 2 });
}
objCommandHelper.AddAditionalParameters("bookName = @bookName", new string[] { "bookName" }, new object[] { bookName });
return SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetUpdateSql(),
objCommandHelper.GetParameters());
}
#endregion Update
#region Delete
/// <summary>
/// Delete user by user id
/// </summary>
/// <param name="userID">user id</param>
/// <returns>Affected row count</returns>
public int DeleteUser(int userID)
{
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.DELETE,
typeof(BookShelfUser),
"User",
null,
new string[] { "userID" },
new object[] { userID });
return SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetDeleteSql(),
objCommandHelper.GetParameters());
}
#endregion Delete
#region Get
/// <summary>
/// Get user by user id
/// </summary>
/// <param name="userID">user id</param>
/// <returns>null if not found</returns>
public BookShelfUser GetUserbyID(int userID)
{
//build sql script
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.SELECT,
typeof(BookShelfUser),
"User",
null,
new string[] { "userID" },
new object[] { userID });
SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetSelectSql(),
objCommandHelper.GetParameters());
BookShelfUser bsu = new BookShelfUser();
dr.Read();
bsu.UserID = dr.GetInt32(0);
bsu.FullName = dr.GetString(1);
bsu.Password = dr.GetString(2);
bsu.Email = dr.GetString(3);
bsu.Address = dr.GetString(4);
bsu.City = dr.GetString(5);
return bsu;
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name="fullName">full name</param>
/// <returns>BookShelfUser, null if not found</returns>
public BookShelfUser GetUserbyName(string fullName)
{
//build sql script
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.SELECT,
typeof(BookShelfUser),
"User",
null,
new string[] { "fullName" },
new object[] { fullName });
SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringBookShelfTransaction,
CommandType.Text,
objCommandHelper.GetSelectSql(),
objCommandHelper.GetParameters());
BookShelfUser bsu = new BookShelfUser();
dr.Read();
bsu.UserID = dr.GetInt32(0);
bsu.FullName = dr.GetString(1);
bsu.Password = dr.GetString(2);
bsu.Email = dr.GetString(3);
bsu.Address = dr.GetString(4);
bsu.City = dr.GetString(5);
return bsu;
}
/// <summary>
/// get all user list
/// </summary>
/// <returns>empty list if not found</returns>
public IList<BookShelfUser> GetUsers()
{
List<BookShelfUser> userEntityList = new List<BookShelfUser>();
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.SELECT,
typeof(BookShelfUser), "User", null, null, null);
using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringBookShelfTransaction, CommandType.Text, objCommandHelper.GetSelectSql(), objCommandHelper.GetParameters()))
{
while (dr.Read())
{
BookShelfUser tmpUser = new BookShelfUser();
tmpUser.UserID = dr.GetInt32(0);
tmpUser.FullName = dr.GetString(1);
tmpUser.Password = dr.GetString(2);
tmpUser.Email = dr.GetString(3);
tmpUser.Address = dr.GetString(4);
tmpUser.City = dr.GetString(5);
userEntityList.Add(tmpUser);
}
}
return userEntityList;
}
/// <summary>
/// get all user table content list, POSSIBLE Debugging Use
/// </summary>
/// <returns>empty list if not found</returns>
public IList<BookShelfUser> GetUserTableContent()
{
List<BookShelfUser> userTableEntityList = new List<BookShelfUser>();
SqlCommandHelper objCommandHelper = new SqlCommandHelper(SqlCommandHelper.SqlCommandType.SELECT,
typeof(BookShelfUser), "User", null, null, null);
using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringBookShelfTransaction, CommandType.Text, objCommandHelper.GetSelectSql(), objCommandHelper.GetParameters()))
{
while (dr.Read())
{
BookShelfUser tmpUser = new BookShelfUser();
tmpUser.UserID = dr.GetInt32(0);
tmpUser.FullName = dr.GetString(1);
tmpUser.Password = dr.GetString(2);
tmpUser.Email = dr.GetString(3);
tmpUser.Address = dr.GetString(4);
tmpUser.City = dr.GetString(5);
}
}
return userTableEntityList;
}
/// <summary>
/// POSSIBLE Debugging Use
/// </summary>
/// <param name="userID"></param>
/// <param name="bookEntity"></param>
/// <returns></returns>
public int GetBookMembership(int userID, BookShelfBook bookEntity)
{
//TODO for POSSIBLE Debugging Use
return 1;
}
#endregion Get
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RiskEngine
{
public class CommonFunctions
{
/// This is a library of common functions not necessarily tied to any individual object,
/// such as the board, a player, etc.
public static int RESERVE_COUNT = 35; // Number of reserves. TODO: change based on num. players
public static int MIN_ARMIES_TO_ATTACK = 2; // Min number of armies needed on a given territory in order to launch attack
public static int[] CARD_BONUSES = { 4, 6, 8, 10, 12, 15 }; // Card bonuses for each set traded in. After 15, increases by 5 each time
public enum FactionState
{
Attacker,
Defender
}
public enum Continent
{
NorthAmerica,
SouthAmerica,
Europe,
Africa,
Asia,
Australia
}
public enum CardType
{
Infantry,
Cavalry,
Artillery,
Wild
}
/// <summary>
/// Returns a mapping of territory names to their adjacent territories based on a text file. The text
/// file should adhere to the following format:
///
/// TerritoryA:AdjacentTerritoryA1,AdjacentTerritoryA2,...,AdjacentTerritoryAK\n
/// TerritoryB:AdjacentTerritoryB1,AdjacentTerritoryB2,...,AdjacentTerritoryBL\n
/// ...
/// TerritoryN:AdjacentTerritoryN1,AdjacentTerritoryN2,...,AdjacentTerritoryNM
///
/// This also assumes there is a file that maps territories to continents.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static Dictionary<string, string[]> ParseMapFile(string filePath)
{
Dictionary<string, string[]> territoryMap = new Dictionary<string, string[]>();
using (var sr = new StreamReader(filePath + "Risk_Map.txt"))
{
string node;
while ((node = sr.ReadLine()) != null)
{
var nodeInfo = node.Split(':');
var nodeName = nodeInfo[0];
var adjacentNodes = nodeInfo[1].Split(',');
territoryMap.Add(nodeName, adjacentNodes);
}
}
return territoryMap;
}
public static void ParseContinentFile(string filePath, ref Dictionary<string, string[]> continentToTerritories, ref Dictionary<string, int> continentToScore)
{
using (var sr = new StreamReader(filePath + "Risk_Continents.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var lineSplit = line.Split(':');
var continentAndScore = lineSplit[0].Split('_');
var continentTerritories = lineSplit[1].Split(',');
string continent = continentAndScore[0];
int score = Int32.Parse(continentAndScore[1]);
continentToTerritories.Add(continent, continentTerritories);
continentToScore.Add(continent, score);
}
}
}
/// <summary>
/// Compares roll of the dice, depleting armies from attacker and defender nodes accordingly (Command Line Only)
/// </summary>
/// <param name="attackerDice"></param>
/// <param name="defenderDice"></param>
/// <returns></returns>
public static void CompareDiceRoll(List<Dice> attackerDice, List<Dice> defenderDice,
TerritoryNode attackerNode, TerritoryNode defenderNode)
{
if (attackerNode.GetArmyCount() < MIN_ARMIES_TO_ATTACK)
{
Console.WriteLine(String.Format("You need at least {0} armies on this territory to launch an attack.", MIN_ARMIES_TO_ATTACK));
}
if (attackerNode.GetArmyCount() >= MIN_ARMIES_TO_ATTACK && defenderNode.GetArmyCount() > 0)
{
// Compare first pair of die
int[] attackerVals = GetMaxDiceValues(attackerDice);
int[] defenderVals = GetMaxDiceValues(defenderDice);
if (attackerVals[0] > defenderVals[0])
{
defenderNode.RemoveArmies(1);
}
else
{
attackerNode.RemoveArmies(1);
}
// Compare second pair of die, if both players had rolled at least 2 dice each
if (attackerNode.GetArmyCount() >= MIN_ARMIES_TO_ATTACK && defenderNode.GetArmyCount() > 0 && attackerVals[1] > 0 && defenderVals[1] > 0)
{
if (attackerVals[1] > defenderVals[1])
{
defenderNode.RemoveArmies(1);
}
else
{
attackerNode.RemoveArmies(1);
}
if (defenderNode.GetArmyCount() == 0)
{
TransferArmies(attackerNode, defenderNode);
}
}
else if (defenderNode.GetArmyCount() == 0)
{
TransferArmies(attackerNode, defenderNode);
}
}
}
/// <summary>
/// Gets the maximum dice values in the list. Second element is -1 if only 1 dice is rolled.
/// </summary>
/// <param name="dice"></param>
/// <returns></returns>
public static int[] GetMaxDiceValues(List<Dice> dice)
{
int[] max2 = new int[] { -1, -1 };
foreach (var die in dice)
{
if (die.PeekDice() > max2[0])
{
max2[0] = die.PeekDice();
}
}
// Get second-highest dice if applicable
if (dice.Count > 1)
{
foreach (var die in dice)
{
if (die.PeekDice() > max2[1] && die.PeekDice() <= max2[0])
{
max2[1] = die.PeekDice();
}
}
}
return max2;
}
/// <summary>
/// Rolls all dice for both players.
/// </summary>
/// <param name="redDice"></param>
/// <param name="whiteDice"></param>
/// <param name="numRed"></param>
/// <param name="numWhite"></param>
public static void RollAllDie(ref List<Dice> redDice, ref List<Dice> whiteDice, int numRed, int numWhite)
{
for (int i = 0; i < numRed; i++)
{
redDice.Add(new Dice());
}
for (int i = 0; i < numWhite; i++)
{
whiteDice.Add(new Dice());
}
foreach (var d in redDice)
{
d.Roll();
}
foreach (var d in whiteDice)
{
d.Roll();
}
}
/// <summary>
/// Returns the maximum number of dice that can be rolled
/// </summary>
/// <param name="armies"></param>
/// <param name="state"></param>
/// <returns></returns>
public static int GetMaxDiceToRoll(int armies, FactionState state)
{
if (state == FactionState.Attacker)
{
if (armies > 3) return 3;
else if (armies == 3) return 2;
else return 1;
}
else
{
if (armies >= 2) return 2;
else return 1;
}
}
/// <summary>
/// Transfers a user-input number of armies from the attacker node to the defender node (Console Only)
/// </summary>
/// <param name="attackerNode"></param>
/// <param name="defenderNode"></param>
private static void TransferArmies(TerritoryNode attackerNode, TerritoryNode defenderNode)
{
//Console.Write("Attacker won new territory! Choose number of armies to move: ");
int movingArmies = Int32.Parse(Console.ReadLine());
while (movingArmies < 1 || movingArmies >= attackerNode.GetArmyCount())
{
Console.WriteLine(String.Format("Number of armies to move must be at least 1 and no more than {0}.", attackerNode.GetArmyCount() - 1));
Console.Write("Please choose a different value: ");
movingArmies = Int32.Parse(Console.ReadLine());
}
attackerNode.RemoveArmies(movingArmies);
defenderNode.AddArmies(movingArmies);
attackerNode.OccupyingFaction.OccupyTerritory(defenderNode);
attackerNode.OccupyingFaction.NumConqueredTerritoriesCurrentTurn += 1;
}
/// <summary>
/// Assign offensive and defensive nodes
/// </summary>
/// <param name="board"></param>
/// <param name="player"></param>
/// <param name="offensiveNode"></param>
/// <param name="defensiveNode"></param>
public static void DeclareAttack(RiskBoard board, Faction player, ref TerritoryNode offensiveNode, ref TerritoryNode defensiveNode)
{
Console.Write(String.Format("Player {0}, choose attacking territory: ", player.FactionName));
offensiveNode = board.GetTerritoryNodeByName(Console.ReadLine());
Console.Write(String.Format("Player {0}, choose territory to attack: ", player.FactionName));
defensiveNode = board.GetTerritoryNodeByName(Console.ReadLine());
}
/// <summary>
/// Shuffles a list using the Fisher-Yates algorithm (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<T> Shuffle<T>(List<T> list)
{
Random r = new Random();
for (int i = list.Count - 1; i > 0; i--)
{
int j = r.Next(i + 1);
var temp = list[i];
list[i] = list[j];
list[j] = temp;
}
return list;
}
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace SimpleRESTChat.DAL.Migrations
{
public partial class ExtendChatTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "017d86f4-a117-44b8-82ab-95c1e5576805");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "1798dda8-2c07-479c-bc9b-60fe1557d35e");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "17b155d1-897d-4186-9308-5790c53e55ca");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "972fa836-46a6-4148-a1b1-bf4b1a81a21c");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "be9fc336-085b-4f49-a359-a051e8018be4");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "d20f2b50-4009-4156-84f6-2972d516662d");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "d560427e-cfb7-4da7-9506-f24e2ab942e7");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "eb43d418-70f6-4d84-b0cb-94b31f2d32c8");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "f1aa18e2-cdfc-4afd-89d7-e32cf2e83247");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "f815afeb-8e72-4834-827a-168ce5bcc2f7");
migrationBuilder.AddColumn<bool>(
name: "Active",
table: "Chat",
nullable: false,
defaultValue: false);
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Active", "AvailabilityStatus", "Email", "Firstname", "Lastname", "Password", "Username" },
values: new object[,]
{
{ "bb05fa59-2ad1-449e-860c-86a2f37ca980", true, 1, "user10@gmail.com", "User00Firstname", "User00Lastname", "1234", "User10Test" },
{ "3b4576a2-3a3c-4047-8bbe-952fa6dfecc8", true, 1, "user236@gmail.com", "User136Firstname", "User136Lastname", "1234", "User236Test" },
{ "d8ddef16-4c2d-4bf1-956c-be8cda7fc034", true, 1, "user390@gmail.com", "User290Firstname", "User290Lastname", "1234", "User390Test" },
{ "756da0ed-7a86-4b3b-ad1b-5fe1401e9c99", true, 1, "user431@gmail.com", "User331Firstname", "User331Lastname", "1234", "User431Test" },
{ "14ee355d-2d53-4685-b5a1-17cd9e1711df", true, 1, "user521@gmail.com", "User421Firstname", "User421Lastname", "1234", "User521Test" },
{ "59d6588e-ae6a-4536-b1cf-099ed76a3bb8", true, 1, "user692@gmail.com", "User592Firstname", "User592Lastname", "1234", "User692Test" },
{ "4b17e492-5e20-4ac8-b42b-1271ae7aa78e", true, 1, "user721@gmail.com", "User621Firstname", "User621Lastname", "1234", "User721Test" },
{ "9123e1bc-6d6c-4b85-be39-e5f4704a8501", true, 1, "user844@gmail.com", "User744Firstname", "User744Lastname", "1234", "User844Test" },
{ "da272b23-dd75-47fa-ac8a-191858206476", true, 1, "user939@gmail.com", "User839Firstname", "User839Lastname", "1234", "User939Test" },
{ "7ba96b4f-e48b-4b70-90b0-932fb8d5d1e2", true, 1, "user1042@gmail.com", "User942Firstname", "User942Lastname", "1234", "User1042Test" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "14ee355d-2d53-4685-b5a1-17cd9e1711df");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "3b4576a2-3a3c-4047-8bbe-952fa6dfecc8");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "4b17e492-5e20-4ac8-b42b-1271ae7aa78e");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "59d6588e-ae6a-4536-b1cf-099ed76a3bb8");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "756da0ed-7a86-4b3b-ad1b-5fe1401e9c99");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "7ba96b4f-e48b-4b70-90b0-932fb8d5d1e2");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "9123e1bc-6d6c-4b85-be39-e5f4704a8501");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "bb05fa59-2ad1-449e-860c-86a2f37ca980");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "d8ddef16-4c2d-4bf1-956c-be8cda7fc034");
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: "da272b23-dd75-47fa-ac8a-191858206476");
migrationBuilder.DropColumn(
name: "Active",
table: "Chat");
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Active", "AvailabilityStatus", "Email", "Firstname", "Lastname", "Password", "Username" },
values: new object[,]
{
{ "1798dda8-2c07-479c-bc9b-60fe1557d35e", true, 1, "user162@gmail.com", "User062Firstname", "User062Lastname", "1234", "User162Test" },
{ "be9fc336-085b-4f49-a359-a051e8018be4", true, 1, "user215@gmail.com", "User115Firstname", "User115Lastname", "1234", "User215Test" },
{ "d20f2b50-4009-4156-84f6-2972d516662d", true, 1, "user363@gmail.com", "User263Firstname", "User263Lastname", "1234", "User363Test" },
{ "972fa836-46a6-4148-a1b1-bf4b1a81a21c", true, 1, "user48@gmail.com", "User38Firstname", "User38Lastname", "1234", "User48Test" },
{ "f815afeb-8e72-4834-827a-168ce5bcc2f7", true, 1, "user543@gmail.com", "User443Firstname", "User443Lastname", "1234", "User543Test" },
{ "f1aa18e2-cdfc-4afd-89d7-e32cf2e83247", true, 1, "user644@gmail.com", "User544Firstname", "User544Lastname", "1234", "User644Test" },
{ "eb43d418-70f6-4d84-b0cb-94b31f2d32c8", true, 1, "user782@gmail.com", "User682Firstname", "User682Lastname", "1234", "User782Test" },
{ "d560427e-cfb7-4da7-9506-f24e2ab942e7", true, 1, "user852@gmail.com", "User752Firstname", "User752Lastname", "1234", "User852Test" },
{ "017d86f4-a117-44b8-82ab-95c1e5576805", true, 1, "user936@gmail.com", "User836Firstname", "User836Lastname", "1234", "User936Test" },
{ "17b155d1-897d-4186-9308-5790c53e55ca", true, 1, "user1023@gmail.com", "User923Firstname", "User923Lastname", "1234", "User1023Test" }
});
}
}
}
|
using Alabo.Domains.Query.Dto;
using Alabo.Domains.Repositories.Mongo.Extension;
using Alabo.Industry.Shop.Orders.Domain.Enums;
using MongoDB.Bson;
using Newtonsoft.Json;
namespace Alabo.Industry.Shop.Orders.Dtos
{
/// <summary>
/// 订单
/// </summary>
public class OrderListInput : ApiInputDto
{
/// <summary>
/// 订单状态
/// </summary>
public OrderStatus OrderStatus { get; set; }
/// <summary>
/// 获取订单类型
/// UserOrderList = 1, // 会员订单
/// StoreOrderList = 2, // 店铺订单
/// AdminOrderList = 3 // 平台订单
/// </summary>
public OrderType? OrderType { get; set; } = Domain.Enums.OrderType.Normal;
/// <summary>
/// 获取会员Id
/// </summary>
public long UserId { get; set; }
/// <summary>
/// 店铺Id
/// </summary>
[JsonConverter(typeof(ObjectIdConverter))] public ObjectId StoreId { get; set; }
/// <summary>
/// 发货用户Id
/// </summary>
public long DeliverUserId { get; set; }
/// <summary>
/// 当前页 private
/// </summary>
public long PageIndex { get; set; }
/// <summary>
/// 每页记录数 private
/// </summary>
public long PageSize { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Models;
using WitsmlExplorer.Api.Query;
namespace WitsmlExplorer.Api.Services
{
public interface IMessageObjectService
{
Task<MessageObject> GetMessageObject(string wellUid, string wellboreUid, string msgUid);
Task<IEnumerable<MessageObject>> GetMessageObjects(string wellUid, string wellboreUid);
}
public class MessageObjectService : WitsmlService, IMessageObjectService
{
public MessageObjectService(IWitsmlClientProvider witsmlClientProvider) : base(witsmlClientProvider)
{
}
public async Task<MessageObject> GetMessageObject(string wellUid, string wellboreUid, string msgUid)
{
var witsmlMessage = MessageQueries.GetMessageById(wellUid, wellboreUid, msgUid);
var result = await WitsmlClient.GetFromStoreAsync(witsmlMessage, new OptionsIn(ReturnElements.All));
var messageObject = result.Messages.FirstOrDefault();
if (messageObject == null) return null;
return new MessageObject
{
WellboreUid = messageObject.UidWellbore,
WellboreName = messageObject.NameWellbore,
WellUid = messageObject.UidWell,
WellName = messageObject.NameWell,
Uid = messageObject.Uid,
Name = messageObject.Name,
MessageText = messageObject.MessageText,
DateTimeCreation = StringHelpers.ToDateTime(messageObject.CommonData.DTimCreation),
DateTimeLastChange = StringHelpers.ToDateTime(messageObject.CommonData.DTimLastChange)
};
}
public async Task<IEnumerable<MessageObject>> GetMessageObjects(string wellUid, string wellboreUid)
{
var start = DateTime.Now;
var witsmlMessage = MessageQueries.GetMessageByWellbore(wellUid, wellboreUid);
var result = await WitsmlClient.GetFromStoreAsync(witsmlMessage, new OptionsIn(ReturnElements.Requested));
var messageObjects = result.Messages
.Select(message =>
new MessageObject
{
Uid = message.Uid,
Name = message.Name,
WellboreUid = message.UidWellbore,
WellboreName = message.NameWellbore,
WellUid = message.UidWell,
WellName = message.NameWell,
MessageText = message.MessageText,
DateTimeLastChange = StringHelpers.ToDateTime(message.CommonData.DTimLastChange),
DateTimeCreation = StringHelpers.ToDateTime(message.CommonData.DTimCreation)
})
.OrderBy(message => message.WellboreName).ToList();
var elapsed = DateTime.Now.Subtract(start).Milliseconds / 1000.0;
Log.Debug("Fetched {Count} messageobjects from {WellboreName} in {Elapsed} seconds", messageObjects.Count, messageObjects.FirstOrDefault()?.WellboreName, elapsed);
return messageObjects;
}
}
}
|
using Tomelt.Localization;
using Tomelt.UI.Navigation;
namespace Tomelt.MediaLibrary {
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public AdminMenu() {
T = NullLocalizer.Instance;
}
public string MenuName { get { return "admin"; } }
//public void GetNavigation(NavigationBuilder builder) {
// builder.AddImageSet("media-library")
// .Add(T("Media"), "6",
// menu => menu.Add(T("Media"), "0", item => item.Action("Index", "Admin", new { area = "Tomelt.MediaLibrary" })
// .Permission(Permissions.ManageOwnMedia)));
//}
public void GetNavigation(NavigationBuilder builder)
{
builder.AddImageSet("ok")
.Add(T("系统功能"), "88", menu =>
{
menu.LinkToFirstChild(false);
menu.Add(T("媒体库"), "0",
item => item.Action("Index", "Admin", new { area = "Tomelt.MediaLibrary" })
.Permission(Permissions.ManageOwnMedia).LocalNav());
});
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using OPCAutomation;
namespace OPCClient.UserContols
{
public partial class ucOPCServer : OPCClient.UserContols.ucCustomBase
{
/// <summary>
/// OPCServer 的 IP 地址
/// </summary>
private string remoteOPCServerIP = "";
public ucOPCServer()
{
InitializeComponent();
}
public ucOPCServer(string title) : base(title)
{
InitializeComponent();
}
public string OPCServerIP
{
get { return remoteOPCServerIP; }
set
{
remoteOPCServerIP = value;
// 连接 OPCSever
Thread threadConnectOPCServer = new Thread(ConnectRemoteServerInThread);
threadConnectOPCServer.IsBackground = true;
threadConnectOPCServer.Start();
}
}
private void ConnectRemoteServerInThread()
{
}
}
}
|
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Models.OveralppingTrainingDate;
using System.Threading.Tasks;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.OverlappingTrainingDateRequestControllerTests
{
[TestFixture]
public class WhenIGetEmployerNotified
{
private OverlappingTrainingDateRequestControllerTestFixture _fixture;
[SetUp]
public void Arrange()
{
_fixture = new OverlappingTrainingDateRequestControllerTestFixture();
}
[Test]
public void AndWhenGetEmployerNotifiedEndPointIsCalled_CorrectViewModelIsReturned()
{
_fixture.GetEmployerNotified();
_fixture.VerifyEmployerNotifiedViewReturned();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Dynamic_Programming
{
/// <summary>
/// Given a path of Size 4*width.
/// And an infinite supply of brick of size 1x4.
/// The brick can be layed horizontally or vertically.
/// Find the total number of ways in which the bricks can be layed
/// </summary>
class BrickLaying
{
/// <summary>
/// We do this using the dynamic programming approach.
/// We consider the case in which we lay the brick vertically and horizontally.
/// And we do this in a bottoms up manner.
/// The space required is O(width)
/// The running time is also O(width)
/// </summary>
/// <param name="width"></param>
/// <returns></returns>
public static int DifferentWaysOfLayingBricks(int width)
{
int[] arr = new int[width+1];
arr[0] = 1;
for(int i=1;i<= width; i++)
{
// Lay a brick vertically
arr[i] += arr[i - 1];
// Lay 4 bricks horizontally
if(i-4>=0)
{
arr[i] += arr[i - 4];
}
}
return arr[width];
}
public static void TestBrickLaying()
{
int width = 7;
Console.WriteLine("The different ways in which bricks can be laid for width {0} is {1} ways", width, DifferentWaysOfLayingBricks(width));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Battle_city
{
public class Boom : Object_of_map
{
}
}
|
using System.Xml;
using NUnit;
namespace Ghpr.NUnit.Extensions
{
public static class XmlNodeExtensions
{
public static string Val(this XmlNode node) => node.GetAttribute("value");
}
} |
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
using Sentry.Reflection;
namespace Sentry.Internal;
internal class MainSentryEventProcessor : ISentryEventProcessor
{
internal const string CultureInfoKey = "Current Culture";
internal const string CurrentUiCultureKey = "Current UI Culture";
internal const string MemoryInfoKey = "Memory Info";
internal const string ThreadPoolInfoKey = "ThreadPool Info";
internal const string IsDynamicCodeKey = "Dynamic Code";
internal const string IsDynamicCodeCompiledKey = "Compiled";
internal const string IsDynamicCodeSupportedKey = "Supported";
private readonly Enricher _enricher;
private readonly SentryOptions _options;
internal Func<ISentryStackTraceFactory> SentryStackTraceFactoryAccessor { get; }
internal string? Release => _options.SettingLocator.GetRelease();
internal string? Distribution => _options.Distribution;
public MainSentryEventProcessor(
SentryOptions options,
Func<ISentryStackTraceFactory> sentryStackTraceFactoryAccessor)
{
_options = options;
SentryStackTraceFactoryAccessor = sentryStackTraceFactoryAccessor;
_enricher = new Enricher(options);
}
public SentryEvent Process(SentryEvent @event)
{
_options.LogDebug("Running main event processor on: Event {0}", @event.EventId);
if (TimeZoneInfo.Local is { } timeZoneInfo)
{
@event.Contexts.Device.Timezone = timeZoneInfo;
}
IDictionary<string, string>? cultureInfoMapped = null;
if (!@event.Contexts.ContainsKey(CultureInfoKey)
&& CultureInfoToDictionary(CultureInfo.CurrentCulture) is { } currentCultureMap)
{
cultureInfoMapped = currentCultureMap;
@event.Contexts[CultureInfoKey] = currentCultureMap;
}
if (!@event.Contexts.ContainsKey(CurrentUiCultureKey)
&& CultureInfoToDictionary(CultureInfo.CurrentUICulture) is { } currentUiCultureMap
&& (cultureInfoMapped is null || currentUiCultureMap.Any(p => !cultureInfoMapped.Contains(p))))
{
@event.Contexts[CurrentUiCultureKey] = currentUiCultureMap;
}
#if NETCOREAPP3_0_OR_GREATER
@event.Contexts[IsDynamicCodeKey] = new Dictionary<string, bool>
{
{ IsDynamicCodeCompiledKey, RuntimeFeature.IsDynamicCodeCompiled },
{ IsDynamicCodeSupportedKey, RuntimeFeature.IsDynamicCodeSupported }
};
#endif
AddMemoryInfo(@event.Contexts);
AddThreadPoolInfo(@event.Contexts);
if (@event.ServerName == null)
{
// Value set on the options take precedence over device name.
if (!string.IsNullOrEmpty(_options.ServerName))
{
@event.ServerName = _options.ServerName;
}
else if (_options.SendDefaultPii)
{
@event.ServerName = Environment.MachineName;
}
}
@event.Level ??= SentryLevel.Error;
@event.Release ??= Release;
@event.Distribution ??= Distribution;
// if there's no exception with a stack trace, then get the current stack trace
if (@event.Exception?.StackTrace is null)
{
var stackTrace = SentryStackTraceFactoryAccessor().Create();
if (stackTrace != null)
{
var currentThread = Thread.CurrentThread;
var thread = new SentryThread
{
Crashed = false,
Current = true,
Name = currentThread.Name,
Id = currentThread.ManagedThreadId,
Stacktrace = stackTrace
};
@event.SentryThreads = @event.SentryThreads?.Any() == true
? new List<SentryThread>(@event.SentryThreads) { thread }
: new[] { thread }.AsEnumerable();
if (stackTrace is DebugStackTrace debugStackTrace)
{
debugStackTrace.MergeDebugImagesInto(@event);
}
}
}
// Add all the Debug Images that were referenced from stack traces to the Event.
if (@event.SentryExceptions is { } sentryExceptions)
{
foreach (var sentryException in sentryExceptions)
{
if (sentryException.Stacktrace is DebugStackTrace debugStackTrace)
{
debugStackTrace.MergeDebugImagesInto(@event);
}
}
}
if (_options.ReportAssembliesMode != ReportAssembliesMode.None)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.IsDynamic)
{
continue;
}
var asmName = assembly.GetName();
if (asmName.Name is null)
{
continue;
}
var asmVersion = _options.ReportAssembliesMode switch
{
ReportAssembliesMode.Version => asmName.Version?.ToString() ?? string.Empty,
ReportAssembliesMode.InformationalVersion => assembly.GetVersion() ?? string.Empty,
_ => throw new ArgumentOutOfRangeException(
$"Report assemblies mode '{_options.ReportAssembliesMode}' is not yet supported")
};
if (!string.IsNullOrWhiteSpace(asmVersion))
{
@event.Modules[asmName.Name] = asmVersion;
}
}
}
// Run enricher to fill in the gaps
_enricher.Apply(@event);
return @event;
}
private static void AddMemoryInfo(Contexts contexts)
{
#if NETCOREAPP3_0_OR_GREATER
var memory = GC.GetGCMemoryInfo();
var allocatedBytes = GC.GetTotalAllocatedBytes();
#if NET5_0_OR_GREATER
contexts[MemoryInfoKey] = new MemoryInfo(
allocatedBytes,
memory.FragmentedBytes,
memory.HeapSizeBytes,
memory.HighMemoryLoadThresholdBytes,
memory.TotalAvailableMemoryBytes,
memory.MemoryLoadBytes,
memory.TotalCommittedBytes,
memory.PromotedBytes,
memory.PinnedObjectsCount,
memory.PauseTimePercentage,
memory.Index,
memory.FinalizationPendingCount,
memory.Compacted,
memory.Concurrent,
memory.PauseDurations.ToArray());
#else
contexts[MemoryInfoKey] = new MemoryInfo(
allocatedBytes,
memory.FragmentedBytes,
memory.HeapSizeBytes,
memory.HighMemoryLoadThresholdBytes,
memory.TotalAvailableMemoryBytes,
memory.MemoryLoadBytes);
#endif
#endif
}
private static void AddThreadPoolInfo(Contexts contexts)
{
ThreadPool.GetMinThreads(out var minWorkerThreads, out var minCompletionPortThreads);
ThreadPool.GetMaxThreads(out var maxWorkerThreads, out var maxCompletionPortThreads);
ThreadPool.GetAvailableThreads(out var availableWorkerThreads, out var availableCompletionPortThreads);
contexts[ThreadPoolInfoKey] = new ThreadPoolInfo(
minWorkerThreads,
minCompletionPortThreads,
maxWorkerThreads,
maxCompletionPortThreads,
availableWorkerThreads,
availableCompletionPortThreads);
}
private static IDictionary<string, string>? CultureInfoToDictionary(CultureInfo cultureInfo)
{
var dic = new Dictionary<string, string>();
if (!string.IsNullOrWhiteSpace(cultureInfo.Name))
{
dic.Add("name", cultureInfo.Name);
}
if (!string.IsNullOrWhiteSpace(cultureInfo.DisplayName))
{
dic.Add("display_name", cultureInfo.DisplayName);
}
if (cultureInfo.Calendar is { } cal)
{
dic.Add("calendar", cal.GetType().Name);
}
return dic.Count > 0 ? dic : null;
}
}
|
#if NETCOREAPP3_1_OR_GREATER
using Sentry.Testing;
namespace Sentry.Tests.Internals;
[UsesVerify]
public class MemoryInfoTests
{
private readonly IDiagnosticLogger _testOutputLogger;
public MemoryInfoTests(ITestOutputHelper output)
{
_testOutputLogger = new TestOutputDiagnosticLogger(output);
}
[Fact]
public Task WriteTo()
{
#if NET5_0_OR_GREATER
var info = new MemoryInfo(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, true, false, new[] {TimeSpan.FromSeconds(1)});
#else
var info = new MemoryInfo(1, 2, 3, 4, 5, 6);
#endif
var json = info.ToJsonString(_testOutputLogger);
return VerifyJson(json).UniqueForTargetFrameworkAndVersion();
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Entities;
using MongoDB.Entities.Core;
namespace ProductService.Persistance.Entities
{
[Name("Products")]
public class Product : Entity
{
public string Name { get; set; }
public double Price { get; set; }
public bool Active { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Euler_Logic.Problems.AdventOfCode.Y2018 {
public class Problem05 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2018: 5"; }
}
public override string GetAnswer() {
BuildHash();
return Answer1();
}
public override string GetAnswer2() {
BuildHash();
return Answer2();
}
private string Answer1() {
var poly = GetPoly(Input().First());
poly = Collapse(poly);
return Count(poly).ToString();
}
private string Answer2() {
var start = (int)'A';
int lowest = int.MaxValue;
for (int count = 1; count <= 26; count++) {
var poly = GetPoly(Input().First());
poly = Remove(poly, (char)start);
poly = Collapse(poly);
int sum = Count(poly);
if (sum < lowest) {
lowest = sum;
}
start++;
}
return lowest.ToString();
}
private string PrintPoly(Poly poly) {
StringBuilder text = new StringBuilder();
while (poly != null) {
text.Append(poly.Name);
poly = poly.Next;
}
return text.ToString();
}
private Poly GetPoly(string text) {
Poly poly = null;
for (int index = text.Length - 1; index >= 0; index--) {
poly = new Poly() { Name = text[index], Next = poly };
}
return poly;
}
private Dictionary<char, char> _hash = new Dictionary<char, char>();
private void BuildHash() {
var start = (int)'a';
var end = (int)'A';
for (int count = 1; count <= 26; count++) {
_hash.Add((char)start, (char)end);
_hash.Add((char)end, (char)start);
start++;
end++;
}
}
private Poly Collapse(Poly poly) {
bool keepGoing = false;
var top = poly;
var current = top;
Poly prior = null;
do {
keepGoing = false;
current = top;
do {
if (_hash[current.Name] == current.Next.Name) {
if (current == top) {
prior = null;
top = current.Next.Next;
current = top;
} else {
prior.Next = current.Next.Next;
current = prior.Next;
}
keepGoing = true;
} else {
prior = current;
current = current.Next;
}
} while (current != null && current.Next != null);
} while (keepGoing);
return top;
}
private Poly Remove(Poly poly, char subToRemove) {
var top = poly;
while (poly.Name == subToRemove || poly.Name == _hash[subToRemove]) {
top = poly.Next;
poly = top;
}
var current = top;
Poly prior = null;
while (current != null) {
if (current.Name == subToRemove || current.Name == _hash[subToRemove]) {
prior.Next = current.Next;
current = prior.Next;
} else {
prior = current;
current = current.Next;
}
}
return top;
}
private int Count(Poly poly) {
int count = 0;
while (poly != null) {
count++;
poly = poly.Next;
}
return count;
}
private class Poly {
public char Name { get; set; }
public Poly Next { get; set; }
}
}
}
|
using System;
using System.Drawing;
using UIKit;
using Welic.App.Services.ResizePcture;
using Xamarin.Forms;
[assembly: Dependency(typeof(Welic.App.iOS.Implements.ResizePicture))]
namespace Welic.App.iOS.Implements
{
class ResizePicture : IResizePicture
{
public byte[] ResizeImage(byte[] imageData, float width, float heigth)
{
UIImage originalImage = ImageFromByteArray(imageData);
var originalHeight = originalImage.Size.Height;
var originalWidth = originalImage.Size.Width;
nfloat newHeight;
nfloat newWidth;
if (originalHeight > originalWidth)
{
newHeight = heigth;
nfloat ratio = originalHeight / heigth;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
nfloat ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
width = (float)newWidth;
heigth = (float)newHeight;
UIGraphics.BeginImageContext(new SizeF(width, heigth));
originalImage.Draw(new RectangleF(0, 0, width, heigth));
var resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
var bytesImagen = resizedImage.AsJPEG().ToArray();
resizedImage.Dispose();
return bytesImagen;
}
public UIImage ImageFromByteArray(byte[] data)
{
if (data == null)
return null;
return new UIImage(Foundation.NSData.FromArray(data));
}
}
} |
namespace Sentry;
/// <summary>
/// Models members common between types that represent event-like data.
/// </summary>
public interface IEventLike : IHasBreadcrumbs, IHasTags, IHasExtra
{
/// <summary>
/// Sentry level.
/// </summary>
SentryLevel? Level { get; set; }
/// <summary>
/// Gets or sets the HTTP.
/// </summary>
/// <value>
/// The HTTP.
/// </value>
Request Request { get; set; }
/// <summary>
/// Gets the structured Sentry context.
/// </summary>
/// <value>
/// The contexts.
/// </value>
Contexts Contexts { get; set; }
/// <summary>
/// Gets the user information.
/// </summary>
/// <value>
/// The user.
/// </value>
User User { get; set; }
/// <summary>
/// The name of the platform.
/// </summary>
/// <remarks>
/// In most cases, the platform will be "csharp". However, it may differ if the event
/// was generated from another embeded SDK. For example, when targeting net6.0-android,
/// events generated by the Sentry Android SDK will have the platform "java".
/// </remarks>
public string? Platform { get; set; }
/// <summary>
/// The release version of the application.
/// </summary>
string? Release { get; set; }
/// <summary>
/// The environment name, such as 'production' or 'staging'.
/// </summary>
/// <remarks>Requires Sentry 8.0 or higher.</remarks>
string? Environment { get; set; }
/// <summary>
/// The name of the transaction in which there was an event.
/// </summary>
/// <remarks>
/// A transaction should only be defined when it can be well defined.
/// On a Web framework, for example, a transaction is the route template
/// rather than the actual request path. That is so GET /user/10 and /user/20
/// (which have route template /user/{id}) are identified as the same transaction.
/// </remarks>
string? TransactionName { get; set; }
/// <summary>
/// SDK information.
/// </summary>
/// <remarks>New in Sentry version: 8.4</remarks>
SdkVersion Sdk { get; }
/// <summary>
/// A list of strings used to dictate the deduplication of this event.
/// </summary>
/// <seealso href="https://docs.sentry.io/platforms/dotnet/data-management/event-grouping/grouping-enhancements/"/>
/// <remarks>
/// A value of {{ default }} will be replaced with the built-in behavior, thus allowing you to extend it, or completely replace it.
/// New in version Protocol: version '7'
/// </remarks>
/// <example> { "fingerprint": ["myrpc", "POST", "/foo.bar"] } </example>
/// <example> { "fingerprint": ["{{ default }}", "http://example.com/my.url"] } </example>
IReadOnlyList<string> Fingerprint { get; set; }
}
/// <summary>
/// Extensions for <see cref="IEventLike"/>.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class EventLikeExtensions
{
/// <summary>
/// Whether a <see cref="User"/> has been set to the object with any of its fields non null.
/// </summary>
public static bool HasUser(this IEventLike eventLike) => eventLike.User.HasAnyData();
/// <summary>
/// Sets the fingerprint to the object.
/// </summary>
public static void SetFingerprint(this IEventLike eventLike, IEnumerable<string> fingerprint)
=> eventLike.Fingerprint = fingerprint as IReadOnlyList<string> ?? fingerprint.ToArray();
/// <summary>
/// Sets the fingerprint to the object.
/// </summary>
public static void SetFingerprint(this IEventLike eventLike, params string[] fingerprint)
=> eventLike.Fingerprint = fingerprint;
}
|
using System;
using System.Collections.Generic;
using Jypeli;
using Jypeli.Assets;
using Jypeli.Controls;
using Jypeli.Widgets;
namespace Tasohyppelypeli;
/// @author Omanimi
/// @version Päivämäärä
/// <summary>
///
/// </summary>
public class Tasohyppelypeli : PhysicsGame
{
private const double NOPEUS = 200;
private const double HYPPYNOPEUS = 750;
private const int RUUDUN_KOKO = 40;
private PlatformCharacter pelaaja1;
private Image pelaajanKuva = LoadImage("norsu.png");
private Image tahtiKuva = LoadImage("tahti.png");
private SoundEffect maaliAani = LoadSoundEffect("maali.wav");
public override void Begin()
{
Gravity = new Vector(0, -1000);
LuoKentta();
LisaaNappaimet();
Camera.Follow(pelaaja1);
Camera.ZoomFactor = 1.2;
Camera.StayInLevel = true;
MasterVolume = 0.5;
}
private void LuoKentta()
{
TileMap kentta = TileMap.FromLevelAsset("kentta1.txt");
kentta.SetTileMethod('#', LisaaTaso);
kentta.SetTileMethod('*', LisaaTahti);
kentta.SetTileMethod('N', LisaaPelaaja);
kentta.Execute(RUUDUN_KOKO, RUUDUN_KOKO);
Level.CreateBorders();
Level.Background.CreateGradient(Color.White, Color.SkyBlue);
}
private void LisaaTaso(Vector paikka, double leveys, double korkeus)
{
PhysicsObject taso = PhysicsObject.CreateStaticObject(leveys, korkeus);
taso.Position = paikka;
taso.Color = Color.Green;
Add(taso);
}
private void LisaaTahti(Vector paikka, double leveys, double korkeus)
{
PhysicsObject tahti = PhysicsObject.CreateStaticObject(leveys, korkeus);
tahti.IgnoresCollisionResponse = true;
tahti.Position = paikka;
tahti.Image = tahtiKuva;
tahti.Tag = "tahti";
Add(tahti);
}
private void LisaaPelaaja(Vector paikka, double leveys, double korkeus)
{
pelaaja1 = new PlatformCharacter(leveys, korkeus);
pelaaja1.Position = paikka;
pelaaja1.Mass = 4.0;
pelaaja1.Image = pelaajanKuva;
AddCollisionHandler(pelaaja1, "tahti", TormaaTahteen);
Add(pelaaja1);
}
private void LisaaNappaimet()
{
Keyboard.Listen(Key.F1, ButtonState.Pressed, ShowControlHelp, "Näytä ohjeet");
Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmExit, "Lopeta peli");
Keyboard.Listen(Key.Left, ButtonState.Down, Liikuta, "Liikkuu vasemmalle", pelaaja1, -NOPEUS);
Keyboard.Listen(Key.Right, ButtonState.Down, Liikuta, "Liikkuu vasemmalle", pelaaja1, NOPEUS);
Keyboard.Listen(Key.Up, ButtonState.Pressed, Hyppaa, "Pelaaja hyppää", pelaaja1, HYPPYNOPEUS);
ControllerOne.Listen(Button.Back, ButtonState.Pressed, Exit, "Poistu pelistä");
ControllerOne.Listen(Button.DPadLeft, ButtonState.Down, Liikuta, "Pelaaja liikkuu vasemmalle", pelaaja1, -NOPEUS);
ControllerOne.Listen(Button.DPadRight, ButtonState.Down, Liikuta, "Pelaaja liikkuu oikealle", pelaaja1, NOPEUS);
ControllerOne.Listen(Button.A, ButtonState.Pressed, Hyppaa, "Pelaaja hyppää", pelaaja1, HYPPYNOPEUS);
PhoneBackButton.Listen(ConfirmExit, "Lopeta peli");
}
private void Liikuta(PlatformCharacter hahmo, double nopeus)
{
hahmo.Walk(nopeus);
}
private void Hyppaa(PlatformCharacter hahmo, double nopeus)
{
hahmo.Jump(nopeus);
}
private void TormaaTahteen(PhysicsObject hahmo, PhysicsObject tahti)
{
maaliAani.Play();
MessageDisplay.Add("Keräsit tähden!");
tahti.Destroy();
}
}
|
using EAN.GPD.Domain.Entities;
namespace EAN.GPD.Domain.Repositories
{
public interface IUnidadeMedidaRepository : IBaseRepository<UnidadeMedidaEntity>
{
}
internal class UnidadeMedidaRepository : BaseRepository<UnidadeMedidaEntity>, IUnidadeMedidaRepository
{
}
}
|
using Tools;
namespace _072
{
class Program
{
private static long TotientFunc(int num)
{
var primeFactors = NumUtils.ComputePrimeFactorization_Cached(num);
long res = num;
foreach (var primeFactor in primeFactors)
{
res *= primeFactor.Key - 1;
res /= primeFactor.Key;
}
return res;
}
public static long CountFractions(int maxDenom)
{
long res = 0;
for (int i = 2; i <= maxDenom; i++)
{
res += TotientFunc(i);
}
return res;
}
public static long Solve(int maxDenom)
{
NumUtils.ResetPrimesCache();
return CountFractions(maxDenom);
}
static void Main(string[] args)
{
Decorators.Benchmark(Solve, 1000000);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
#region 변수 목록
private GameManager gameManager = null;
private Animator animator = null;
private AudioSource audioSource = null;
private bool isDamaged = false;
private SpriteRenderer spriteRenderer = null;
public bool Thunder = false;
public bool Stone = false;
public bool Flame = false;
#endregion
#region 발사
private Vector2 targetPosition = Vector2.zero;
[Header("이동속도")] [SerializeField] private float speed = 5f;
[Header("총알 발사 위치")] [SerializeField] private Transform bulletPosition = null;
[Header("총알 프리팹")] [SerializeField] private GameObject bulletPrefab = null;
[Header("총알 발사간격")] [SerializeField] private float bulletDelay = 0.5f;
[Header("총알 스프라이트")] [SerializeField] private Sprite OriginalBulletSprite;
#endregion
void Start()
{
bulletPrefab.GetComponent<SpriteRenderer>().sprite = OriginalBulletSprite;
animator = GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
spriteRenderer = GetComponent<SpriteRenderer>();
gameManager = FindObjectOfType<GameManager>();
StartCoroutine(Fire());
}
void Update()
{
if (Input.GetMouseButton(0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.x = Mathf.Clamp(targetPosition.x, gameManager.MinPosition.x, gameManager.MaxPosition.x);
targetPosition.y = Mathf.Clamp(targetPosition.y, gameManager.MinPosition.y, gameManager.MaxPosition.y);
transform.localPosition = Vector2.MoveTowards(transform.localPosition, targetPosition, speed * Time.deltaTime);
}
}
#region 총알 발사
private IEnumerator Fire()
{
while (true)
{
InstantiateOrPool();
yield return new WaitForSeconds(bulletDelay);
}
}
private GameObject InstantiateOrPool()
{
GameObject result = null;
if (gameManager.poolManager.transform.childCount > 0)
{
audioSource.Play();
result = gameManager.poolManager.transform.GetChild(0).gameObject;
result.transform.position = bulletPosition.position;
result.transform.SetParent(null);
result.SetActive(true);
}
else
{
audioSource.Play();
GameObject Bullet = Instantiate(bulletPrefab, bulletPosition);
Bullet.transform.position = bulletPosition.position;
Bullet.transform.SetParent(null);
result = Bullet;
}
result.transform.localScale = bulletPosition.lossyScale;
return result;
}
#endregion
#region 플레이어가 먹거나 맞을 때
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Item"))
{
if (isDamaged) return;
ItemMove item = collision.gameObject.GetComponent<ItemMove>();
Destroy(collision.gameObject);
switch(item.Name)
{
case "Thunder":
Stone = false;
Flame = false;
StartCoroutine(Blip(2));
animator.Play("Thunder");
gameManager.getLife(3);
bulletDelay = 0.5f;
Thunder = true;
break;
case "Stone":
Thunder = false;
Flame = false;
StartCoroutine(Blip(2));
gameManager.getLife(6);
animator.Play("Stone");
Stone = true;
break;
case "Flame":
Thunder = false;
Stone = false;
StartCoroutine(Blip(2));
gameManager.getLife(4);
animator.Play("Fire");
bulletDelay = 0.3f;
Flame = true;
break;
}
}
else{
if (isDamaged) return;
Dead();
}
}
private void Dead()
{
gameManager.Dead();
isDamaged = true;
StartCoroutine(Blip(5));
isDamaged = false;
}
public void SetDelay(float delay)
{
bulletDelay = delay;
}
private IEnumerator Blip(int num)
{for (int i = 0; i < num; i++)
{
spriteRenderer.enabled = false;
yield return new WaitForSeconds(0.1f);
spriteRenderer.enabled = true;
yield return new WaitForSeconds(0.1f);
}
}
#endregion
}
|
using System.Windows;
using System.Windows.Controls;
namespace Watch
{
public partial class Analog : UserControl
{
public Analog()
{
// Required to initialize variables
InitializeComponent();
//Loaded += AnalogLoaded;
}
//void AnalogLoaded(object sender, RoutedEventArgs e)
//{
// //We begin the rotation animation of each hour, minute and second element
// //all the transformation info is in XAML
// //clockStoryboard.Begin();
//}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Person
{
public class IPerson : Person
{
}
/// <summary>
/// 会员/人
/// </summary>
[Attribute.Table(TableName = "Person")]
public class Person : IModelBase,CoreHelper.FormAuthentication.IUser
{
/// <summary>
/// 用户组仅在验证时用
/// </summary>
public string RuleName;
/// <summary>
/// 存入自定义数据
/// </summary>
public string TagData;
public override string CheckData()
{
return "";
}
#region FORM验证存取
/// <summary>
/// 转为登录用的IUSER
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public CoreHelper.FormAuthentication.IUser ConverFromArry(string content)
{
string[] arry = content.Split('|');
IPerson p = new IPerson();
p.Id = Convert.ToInt32(arry[0]);
p.Name = arry[1];
p.RuleName = arry[2];
if (arry.Length > 3)
{
p.TagData = arry[3];
}
return p;
}
/// <summary>
/// 转为可存储的STRING
/// </summary>
/// <returns></returns>
public string ToArry()
{
return string.Format("{0}|{1}|{2}|{3}", Id, Name, RuleName, TagData);
}
#endregion
/// <summary>
/// 名称
/// </summary>
[CRL.Attribute.Field(Length = 50)]
public string Name
{
get;
set;
}
/// <summary>
/// 帐号
/// </summary>
[Attribute.Field(FieldIndexType=Attribute.FieldIndexType.非聚集唯一,Length=50)]
public string AccountNo
{
get;
set;
}
[Attribute.Field( Length=100)]
public string PassWord
{
get;
set;
}
/// <summary>
/// 邮箱
/// </summary>
public string Email
{
get;
set;
}
/// <summary>
/// 手机
/// </summary>
public string Mobile
{
get;
set;
}
/// <summary>
/// 是否锁定
/// </summary>
public bool Locked
{
get;
set;
}
/// <summary>
/// 注册IP
/// </summary>
public string RegisterIp
{
get;
set;
}
}
}
|
using System.Data.Entity;
namespace VesApp.Domain
{
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public System.Data.Entity.DbSet<VesApp.Domain.Reflexion> Reflexions { get; set; }
public System.Data.Entity.DbSet<VesApp.Domain.Predication> Predications { get; set; }
public System.Data.Entity.DbSet<VesApp.Domain.Project> Projects { get; set; }
public System.Data.Entity.DbSet<VesApp.Domain.Event> Events { get; set; }
public System.Data.Entity.DbSet<VesApp.Domain.Donation> Donations { get; set; }
}
}
|
using System;
namespace Coding
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
string numberInString = number.ToString();
for (int rows = 0; rows < numberInString.Length; rows++)
{
if (number % 10 == 0)
{
Console.WriteLine("ZERO");
}
else
{
for (int i = 0; i < number % 10; i++)
{
int element = (number % 10) + 33;
Console.Write($"{(char)(element)}");
}
Console.WriteLine();
}
number = number / 10;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.