text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web.PublishedCache;
namespace Umbraco.Web.PropertyEditors.ValueConverters
{
/// <summary>
/// The media picker property value converter.
/// </summary>
[DefaultPropertyValueConverter]
public class MediaPickerValueConverter : PropertyValueConverterBase
{
private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor;
public MediaPickerValueConverter(IPublishedSnapshotAccessor publishedSnapshotAccessor)
{
_publishedSnapshotAccessor = publishedSnapshotAccessor ?? throw new ArgumentNullException(nameof(publishedSnapshotAccessor));
}
public override bool IsConverter(PublishedPropertyType propertyType)
{
return propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.MediaPicker);
}
public override Type GetPropertyValueType(PublishedPropertyType propertyType)
{
var isMultiple = IsMultipleDataType(propertyType.DataType);
var isOnlyImages = IsOnlyImagesDataType(propertyType.DataType);
// hard-coding "image" here but that's how it works at UI level too
return isMultiple
? (isOnlyImages ? typeof(IEnumerable<>).MakeGenericType(ModelType.For("image")) : typeof(IEnumerable<IPublishedContent>))
: (isOnlyImages ? ModelType.For("image") : typeof(IPublishedContent));
}
public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType)
=> PropertyCacheLevel.Snapshot;
private bool IsMultipleDataType(PublishedDataType dataType)
{
var config = ConfigurationEditor.ConfigurationAs<MediaPickerConfiguration>(dataType.Configuration);
return config.Multiple;
}
private bool IsOnlyImagesDataType(PublishedDataType dataType)
{
var config = ConfigurationEditor.ConfigurationAs<MediaPickerConfiguration>(dataType.Configuration);
return config.OnlyImages;
}
public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return null;
var nodeIds = source.ToString()
.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(Udi.Parse)
.ToArray();
return nodeIds;
}
public override object ConvertIntermediateToObject(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object source, bool preview)
{
if (source == null)
{
return null;
}
var udis = (Udi[])source;
var mediaItems = new List<IPublishedContent>();
if (udis.Any())
{
foreach (var udi in udis)
{
var guidUdi = udi as GuidUdi;
if (guidUdi == null) continue;
var item = _publishedSnapshotAccessor.PublishedSnapshot.Media.GetById(guidUdi.Guid);
if (item != null)
mediaItems.Add(item);
}
if (IsMultipleDataType(propertyType.DataType))
return mediaItems;
return mediaItems.FirstOrDefault();
}
return source;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
namespace DM_Discord_Bot
{
public class CommandHandler
{
private DiscordSocketClient client;
private CommandService service;
public CommandHandler(DiscordSocketClient _client)
{
client = _client;
service = new CommandService(); //Initiate a new command service
service.AddModulesAsync(Assembly.GetEntryAssembly());
client.MessageReceived += HandleCommandAsync; //When a message is recieved run HandleCommandAsync
}
public async Task HandleCommandAsync(SocketMessage s)
{
var msg = s as SocketUserMessage; //The message the user sent
if (msg == null) return; //If the msg is null then don't bother doing anything else
var context = new SocketCommandContext(client, msg);
int argPos = 0;
if(msg.HasCharPrefix('!', ref argPos))
{
var result = await service.ExecuteAsync(context, argPos);
if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
{
await context.Channel.SendMessageAsync(result.ErrorReason);
}
}
}
}
}
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using DevExpress.XtraReports.UI;
using System.Linq;
using DevExpress.Xpo;
using prjQLNK.QLNK;
namespace prjQLNK
{
public partial class BcBKNK : DevExpress.XtraReports.UI.XtraReport
{
public string NguoiLap_ = "...................................................................", DiaChi_ = "........................................";
public DateTime NgayLap_ = DateTime.Today;
public BcBKNK(int IDNK, string NguoiLap, DateTime NgayLap, string DiaChi)
{
InitializeComponent();
if (NguoiLap != "")
NguoiLap_ = NguoiLap;
if (DiaChi != "")
DiaChi_ = DiaChi;
NgayLap_ = NgayLap;
xrLabel38.Text = DiaChi_ + ", ngày " + NgayLap_.Day + " tháng " + NgayLap_.Month + " năm " + NgayLap_.Year;
xrNguoilap.Text = NguoiLap_;
ThongTin(IDNK);
COT19(IDNK);
COT21(IDNK);
}
private void ThongTin(int IDNK)
{
var TTNhanKhau = xpNHANKHAU.Cast<NHANKHAU>().Where(o => o.ID == IDNK).ToList();
xrLabel30.Text = "1. Họ và tên : " + TTNhanKhau.Select(o => o.HOTENKHAISINH).FirstOrDefault();
xrLabel7.Text = "2. Họ và tên gọi khác (nếu có): " + TTNhanKhau.Select(o => o.TENGOIKHAC).FirstOrDefault();
xrLabel8.Text = "3. Ngày, tháng, năm sinh: " + TTNhanKhau.Select(o => o.NGAYSINH).FirstOrDefault().ToString("dd/MM/yyyy");
xrLabel9.Text = TTNhanKhau.Select(o => o.GIOITINH).FirstOrDefault() == 0 ? "4. Giới tính: Nam" : TTNhanKhau.Select(o => o.GIOITINH).FirstOrDefault() == 1 ? "4. Giới tính: Nữ" : "4. Giới tính:";
xrLabel10.Text = "5. Nơi sinh: " + TTNhanKhau.Select(o => o.DC1).FirstOrDefault() + ", phường " + TTNhanKhau.Select(o => o.IDXA1).FirstOrDefault() + ", huyện " + TTNhanKhau.Select(o => o.IDHUYEN1).FirstOrDefault() + ", tỉnh " + TTNhanKhau.Select(o => o.IDTINH1).FirstOrDefault();
xrLabel11.Text = "6. Nguyên quán: " + TTNhanKhau.Select(o => o.DC2).FirstOrDefault() + ", phường " + TTNhanKhau.Select(o => o.IDXA2).FirstOrDefault() + ", huyện " + TTNhanKhau.Select(o => o.IDHUYEN2).FirstOrDefault() + ", tỉnh " + TTNhanKhau.Select(o => o.IDTINH2).FirstOrDefault();
xrLabel12.Text = "7. Dân tộc: " + TTNhanKhau.Select(o => o.DANTOC).FirstOrDefault();
xrLabel13.Text = "8. Tôn giáo: " + TTNhanKhau.Select(o => o.TONGIAO).FirstOrDefault();
xrLabel14.Text = "9. Quốc tịch: " + TTNhanKhau.Select(o => o.QUOCTICH).FirstOrDefault();
xrLabel20.Text = "10. CMND số: " + TTNhanKhau.Select(o => o.SOCMND).FirstOrDefault();
xrLabel19.Text = "11. Hộ chiếu số: " + TTNhanKhau.Select(o => o.SOHOCHIEU).FirstOrDefault();
xrLabel18.Text = "12. Nơi thường trú: " + TTNhanKhau.Select(o => o.DC3).FirstOrDefault() + ", phường " + TTNhanKhau.Select(o => o.IDXA3).FirstOrDefault() + ", huyện " + TTNhanKhau.Select(o => o.IDHUYEN3).FirstOrDefault() + ", tỉnh " + TTNhanKhau.Select(o => o.IDTINH3).FirstOrDefault();
xrLabel16.Text = "13. Chổ ở hiện nay: " + TTNhanKhau.Select(o => o.DC4).FirstOrDefault() + ", phường " + TTNhanKhau.Select(o => o.IDXA4).FirstOrDefault() + ", huyện " + TTNhanKhau.Select(o => o.IDHUYEN4).FirstOrDefault() + ", tỉnh " + TTNhanKhau.Select(o => o.IDTINH4).FirstOrDefault();
xrLabel32.Text = "14. Trình độ học vấn : " + TTNhanKhau.Select(o => o.TRINHDO).FirstOrDefault();
xrLabel33.Text = "15. Trình độ chuyên môn : " + TTNhanKhau.Select(o => o.TDCHUYENMON).FirstOrDefault();
xrLabel15.Text = "16. Biết tiếng dân tộc: " + TTNhanKhau.Select(o => o.BIETTIENGDANTOC).FirstOrDefault();
xrLabel21.Text = "17. Trình độ ngoại ngữ: " + TTNhanKhau.Select(o => o.TDNGOAINGU).FirstOrDefault();
xrLabel17.Text = "18. Nghề nghiệp, nơi làm việc: " + TTNhanKhau.Select(o => o.NGHENGHIEP).FirstOrDefault() + " - Nơi làm việc: " + TTNhanKhau.Select(o => o.NOILAMVIEC).FirstOrDefault();
}
private void COT19(int IDNK)
{
var QuaTrinh = from nk in xpNHANKHAU.Cast<NHANKHAU>().Where(o => o.ID == IDNK)
join qt in xpQUATRINH.Cast<QUATRINH>() on nk.MAKHAISINH equals qt.MAKHAISINH
select new
{
NGAYTU_DEN = qt.TUTHANGNAM.ToString("dd/MM/yyyy") + " - " + qt.DENTHANGNAM.ToString("dd/MM/yyyy"),
CHOO = qt.CHOO,
NGHE_NOILV = qt.NGHENGHIEP + ". Nơi làm việc: " + qt.NOILAMVIEC,
};
DetailReport.DataSource = QuaTrinh.ToList();
}
private void COT21(int IDNK)
{
var QuanHe_ = from nk in xpNHANKHAU.Cast<NHANKHAU>().Where(o => o.ID == IDNK)
join qh in xpQUANHE.Cast<QUANHE>() on nk.MAKHAISINH equals qh.MAKHAISINH
select new
{
HOTEN = qh.HOTEN,
NGAYSINH = qh.NGAYSINH.ToString("dd/MM/yyyy"),
GIOITINH = qh.GIOITINH == 0 ? "Nam" : qh.GIOITINH == 1 ? "Nữ" : "",
QUANHE1 = qh.QUANHE1,
NGHENGHIEP = qh.NGHENGHIEP,
CHOO = qh.CHOO,
};
DetailReport2.DataSource = QuanHe_.ToList();
}
}
}
|
using FluentAssertions;
using Xunit;
namespace LeeConlin.ExtensionMethods.Tests.StringExtensions
{
public class ToSha256Hash_Should
{
[Theory]
[InlineData("test", true, "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08")]
[InlineData("test", false, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")]
public void Create_Correct_Sha256_Hash_For_Input_Text(string input, bool uppercase, string expected)
{
var sut = input.ToSha256Hash(uppercase);
sut.Should().Be(expected);
}
}
} |
using System.Web.Mvc;
namespace ZiZhuJY.Web.UI.Controllers
{
public class PTPProxyServiceController : Controller
{
//
// GET: /PTPProxyService/
//public JsonResult Index(string privateIP, int? privatePort, string privateHostName, string privateHostFullName, string remark)
//{
// // Register
// PTPClientModel clientInfo = new PTPClientModel(privateIP, privatePort ?? -1, privateHostName, Request.UserHostAddress,
// int.Parse(Request.ServerVariables["REMOTE_PORT"]));
// clientInfo.PrivateHostFullName = privateHostFullName;
// clientInfo.Remark = remark;
// clientInfo.PublicHostName = Request.UserHostName;
// // Save registration info to database
// // Return the entire client list
//}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Utilities.NET.Comparers
{
/// <inheritdoc/>
/// <summary> Version comparer. </summary>
public class VersionComparer : IComparer<string>
{
/// <inheritdoc/>
/// <summary> Compares two version string objects to determine their relative ordering. </summary>
/// <param name="x"> String to be compared. e.g. "2.1.1.3" </param>
/// <param name="y"> String to be compared. e.g. "2.2.6.0" </param>
/// <returns> Negative if 'x' is less than 'y', 0 if they are equal, or positive if it is greater. </returns>
public int Compare(string x, string y)
{
if (x.Equals(y)) return 0;
var xparts = x.Split('.');
var yparts = y.Split('.');
var length = new[] { xparts.Length, yparts.Length }.Max();
for (var i = 0; i < length; i++)
{
if (!int.TryParse(xparts.ElementAtOrDefault(i), out var xint)) xint = 0;
if (!int.TryParse(yparts.ElementAtOrDefault(i), out var yint)) yint = 0;
if (xint > yint) return 1;
if (yint > xint) return -1;
}
//they're equal value but not equal strings, eg 1 and 1.0
return 0;
}
}
} |
using GameForOurProject.Buttons;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameForOurProject.GameHandler
{
public class DrawingOptions
{
public static void DrawUpLabel(List<Button> ButtonsUpper,SpriteBatch spriteBatch)
{
foreach (Button btn in ButtonsUpper)
{
btn.DrawBorder(spriteBatch,5);
}
}
public static void MainDataDisplayDraw(SpriteBatch spriteBatch,RetangleWithText RtgLabel, TextCreator Color,List<Button> btnColors,TextCreator Size,List<Button> btnSizes,List<Button> rtgDataChooser, TextCreator Data,GameTime time)
{
RtgLabel.Draw(time);
if (GameLogic.MouseOverCircle)
{
Data.Draw(spriteBatch);
}
else
{
Color.Draw(spriteBatch);
foreach (Button btn in btnColors)
{
btn.Draw(spriteBatch);
}
Size.Draw(spriteBatch);
foreach (Button btn in btnSizes)
{
btn.Draw(spriteBatch);
}
// Data Save Edit Labels
foreach (Button btn in rtgDataChooser)
{
// Border Draw
btn.DrawBorder(spriteBatch,5);
}
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyThrillRideTrackerApp5.Models
{
public class ThrillRideTrackerDbContext : DbContext
{
public ThrillRideTrackerDbContext (DbContextOptions<ThrillRideTrackerDbContext> options)
: base(options) { }
public DbSet<Park> Parks { get; set; }
public DbSet<Ride> Rides { get; set; }
public DbSet<Visit> Visits { get; set; }
public DbSet<VisitRide> VisitRides { get; set; }
public DbSet<ImageFileName> ImageFileNames { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class LH_Stress : MonoBehaviour
{
List<Vector2> mPathThroughDungeon;
private Vector2 mRandomDir;
LH_Movement mPlayerMovment;
System.Random mRandNum = new System.Random();
private float mHorz, mVert;
void Start()
{
mPathThroughDungeon = FindObjectOfType<AP_DungeonGenerator>().GetPathThroughDungeon();
//gets list of Vector2's that guide the Player through level
mPlayerMovment = this.GetComponent<LH_Movement>();
mPlayerMovment.mSpeedCoefficient = 50; //speeds demo up
}
void Update()
{
}
void FixedUpdate()
{
mHorz=mRandNum.Next(-10,10);
mVert=mRandNum.Next(-10,10);
mRandomDir.Set(mHorz,mVert);
mPlayerMovment.movePlayer(mRandomDir);
}
}
|
using PuddingWolfLoader.Framework.Container;
using PuddingWolfLoader.Framework.View;
using PuddingWolfLoader.Framework.ViewModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using static PuddingWolfLoader.SDK.Model.LogModel;
namespace PuddingWolfLoader.Framework.Converter
{
class ListWhereConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Length == 0)
return (values[0] as IEnumerable<PudLog>).Where(x => x.Type == ((PudLogType)values[1]));
else
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEditorInternal;
using VRM;
using Esperecyan.UniVRMExtensions.Utilities;
namespace Esperecyan.UniVRMExtensions.CopyVRMSettingsComponents
{
internal class CopyVRMSpringBones
{
/// <summary>
/// VRMSpringBone、およびVRMSpringBoneColliderGroupをコピーします。
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <param name="sourceSkeletonBones"></param>
internal static void Copy(
GameObject source,
GameObject destination,
Dictionary<HumanBodyBones, Transform> sourceSkeletonBones
)
{
foreach (var component in new[] { typeof(VRMSpringBone), typeof(VRMSpringBoneColliderGroup) }
.SelectMany(type => destination.GetComponentsInChildren(type)))
{
Object.DestroyImmediate(component);
}
IDictionary<Transform, Transform> transformMapping = new Dictionary<Transform, Transform>();
foreach (var sourceSpringBone in source.GetComponentsInChildren<VRMSpringBone>())
{
if (sourceSpringBone.RootBones.Count == 0)
{
continue;
}
transformMapping = CopyVRMSpringBones.CopySpringBone(
source,
sourceSpringBone,
destination,
sourceSkeletonBones,
transformMapping
);
}
CopyVRMSpringBones.CopySpringBoneColliderGroupForVirtualCast(source: source, destination: destination);
}
/// <summary>
/// VRMSpringBone、およびVRMSpringBoneColliderGroupをコピーします。
/// </summary>
/// <param name="source"></param>
/// <param name="sourceSpringBone"></param>
/// <param name="destination"></param>
/// <param name="sourceSkeletonBones"></param>
/// <param name="transformMapping"></param>
/// <returns>更新された <c>transformMapping</c> を返します。</returns>
private static IDictionary<Transform, Transform> CopySpringBone(
GameObject source,
VRMSpringBone sourceSpringBone,
GameObject destination,
Dictionary<HumanBodyBones, Transform> sourceSkeletonBones,
IDictionary<Transform, Transform> transformMapping
)
{
var destinationSecondary = destination.transform.Find("secondary").gameObject;
ComponentUtility.CopyComponent(sourceSpringBone);
ComponentUtility.PasteComponentAsNew(destinationSecondary);
var destinationSpringBone = destinationSecondary.GetComponents<VRMSpringBone>().Last();
if (destinationSpringBone.m_center)
{
destinationSpringBone.m_center = transformMapping.ContainsKey(destinationSpringBone.m_center)
? transformMapping[destinationSpringBone.m_center]
: (transformMapping[destinationSpringBone.m_center] = BoneMapper.FindCorrespondingBone(
sourceBone: destinationSpringBone.m_center,
source: sourceSpringBone.transform.root.gameObject,
destination,
sourceSkeletonBones
));
}
for (var i = 0; i < destinationSpringBone.RootBones.Count; i++)
{
var sourceSpringBoneRoot = destinationSpringBone.RootBones[i];
destinationSpringBone.RootBones[i] = sourceSpringBoneRoot
? (transformMapping.ContainsKey(sourceSpringBoneRoot)
? transformMapping[sourceSpringBoneRoot]
: (transformMapping[sourceSpringBoneRoot] = BoneMapper.FindCorrespondingBone(
sourceBone: sourceSpringBoneRoot,
source: sourceSpringBone.transform.root.gameObject,
destination,
sourceSkeletonBones
)))
: null;
}
for (var i = 0; i < destinationSpringBone.ColliderGroups.Length; i++)
{
var sourceColliderGroup = destinationSpringBone.ColliderGroups[i];
var destinationColliderGroupTransform = sourceColliderGroup
? (transformMapping.ContainsKey(sourceColliderGroup.transform)
? transformMapping[sourceColliderGroup.transform]
: (transformMapping[sourceColliderGroup.transform] = BoneMapper.FindCorrespondingBone(
sourceBone: sourceColliderGroup.transform,
source: sourceSpringBone.transform.root.gameObject,
destination,
sourceSkeletonBones
)))
: null;
VRMSpringBoneColliderGroup destinationColliderGroup = null;
if (destinationColliderGroupTransform)
{
CopyVRMSpringBones.CopySpringBoneColliderGroups(
source,
sourceBone: sourceColliderGroup.transform,
destination,
destinationBone: destinationColliderGroupTransform
);
destinationColliderGroup
= destinationColliderGroupTransform.GetComponent<VRMSpringBoneColliderGroup>();
}
destinationSpringBone.ColliderGroups[i] = destinationColliderGroup;
}
return transformMapping;
}
/// <summary>
/// コピー先にVRMSpringBoneColliderGroupが存在しなければ、コピー元のVRMSpringBoneColliderGroupをすべてコピーします。
/// </summary>
/// <param name="source"
/// <param name="sourceBone"></param>
/// <param name="destination"></param>
/// <param name="destinationBone"></param>
private static void CopySpringBoneColliderGroups(
GameObject source,
Transform sourceBone,
GameObject destination,
Transform destinationBone
)
{
if (destinationBone.GetComponent<VRMSpringBoneColliderGroup>())
{
return;
}
var localAngularDifference
= destinationBone.transform.rotation * Quaternion.Inverse(destination.transform.rotation)
* Quaternion.Inverse(sourceBone.transform.rotation * Quaternion.Inverse(source.transform.rotation));
foreach (var sourceColliderGroup in sourceBone.GetComponents<VRMSpringBoneColliderGroup>())
{
ComponentUtility.CopyComponent(sourceColliderGroup);
ComponentUtility.PasteComponentAsNew(destinationBone.gameObject);
// 正規化されていないモデルに対応するため、オフセットをルートからの相対的な向きに
var colliderGroup = destinationBone.GetComponents<VRMSpringBoneColliderGroup>().Last();
foreach (var collider in colliderGroup.Colliders)
{
collider.Offset = Quaternion.FromToRotation(Vector3.forward, collider.Offset)
* localAngularDifference * collider.Offset;
}
}
}
/// <summary>
/// バーチャルキャスト向けに、どのVRMSpringBoneにも関連付けられていないVRMSpringBoneColliderGroupをコピーします。
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
private static void CopySpringBoneColliderGroupForVirtualCast(GameObject source, GameObject destination)
{
var sourceAnimator = source.GetComponent<Animator>();
var destinationAnimator = destination.GetComponent<Animator>();
foreach (var humanoidBone in new[] { HumanBodyBones.LeftHand, HumanBodyBones.RightHand })
{
CopyVRMSpringBones.CopySpringBoneColliderGroups(
source,
sourceBone: sourceAnimator.GetBoneTransform(humanoidBone),
destination,
destinationBone: destinationAnimator.GetBoneTransform(humanoidBone)
);
}
}
}
}
|
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI.Ingame;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System;
using VRage.Collections;
using VRage.Game.Components;
using VRage.Game.ModAPI.Ingame;
using VRage.Game.ModAPI.Ingame.Utilities;
using VRage.Game.ObjectBuilders.Definitions;
using VRage.Game;
using VRageMath;
namespace IngameScript
{
partial class Program : MyGridProgram
{
public string controllerName { get { return (string)iniSerializer.GetValue("controllerName"); } }
EntityTracking_Module entityTracking;
AutoPilot autoPilot;
IngameTime time;
Scheduler scheduler;
InterGridComms comms;
INISerializer iniSerializer;
IMyShipController controller;
bool loaded = false;
GridTerminalSystemUtils GTS;
public Program()
{
scheduler = new Scheduler();
scheduler.AddTask(Init());
Runtime.UpdateFrequency = UpdateFrequency.Update1 | UpdateFrequency.Update100;
}
public IEnumerator<bool> Init()
{
iniSerializer = new INISerializer("DroneControl");
iniSerializer.AddValue("controllerName", x => x, "Controller");
if (Me.CustomData == "")
{
string temp = Me.CustomData;
iniSerializer.FirstSerialization(ref temp);
Me.CustomData = temp;
}
else
{
iniSerializer.DeSerialize(Me.CustomData);
}
yield return true;
time = new IngameTime();
GTS = new GridTerminalSystemUtils(Me, GridTerminalSystem);
yield return true;
controller = GTS.GetBlockWithNameOnGrid(controllerName) as IMyShipController;
yield return true;
entityTracking = new EntityTracking_Module(GTS, controller, null, EntityTracking_Module.refExpSettings.Turret);
autoPilot = new AutoPilot(GTS, controller, time, entityTracking);
yield return true;
comms = new InterGridComms(IGC, time, Me);
comms.P = this;
yield return true;
RegisterCommands();
loaded = true;
}
public void Save()
{
}
public void Main(string argument, UpdateType updateSource)
{
if ((updateSource & UpdateType.Update1) != 0)
Update1();
if ((updateSource & UpdateType.Update100) != 0)
Update100();
}
public void Update1()
{
if (loaded)
{
time.Tick(Runtime.TimeSinceLastRun);
comms.CheckPendingMessages();
autoPilot.Main();
}
scheduler.Main();
}
public void Update100()
{
if (loaded)
UpdateStatus();
}
public void RegisterCommands()
{
comms.RegisterCommand("FlyToPoint", FlyToPoint);
}
#region commands
private void FlyToPoint(object point)
{
Vector3D vPoint = (Vector3D)point;
autoPilot.TravelToPosition(vPoint, false);
}
#endregion
#region send
int tickcounter;
private void UpdateStatus()
{
if ((tickcounter++ % 10) != 0)
return;
Echo($"status: {autoPilot.currentMode}");
comms.comms.SendUnicastMessage(comms.serverEndPoint, "UpdateStatus", (int)autoPilot.currentMode);
}
#endregion
}
} |
using nmct.ba.cashlessproject.api.Models.DataAccessOrganisation;
using nmct.ba.cashlessproject.model.WPF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Security.Claims;
using System.Web;
using System.Web.Http;
namespace nmct.ba.cashlessproject.api.Controllers.OrganisationApi
{
[Authorize]
public class RegisterEmployeeController : ApiController
{
/*
* Get list of Register_Employee from database.
*/
public HttpResponseMessage Get()
{
ClaimsPrincipal cp = RequestContext.Principal as ClaimsPrincipal;
List<Register_Employee> regEmps = RegisterEmployeeDA.GetRegisterEmployee(cp.Claims);
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent(typeof(List<Register_Employee>), regEmps, new JsonMediaTypeFormatter());
response.StatusCode = HttpStatusCode.OK;
return response;
}
/*
* Post new Register_Employee to database.
*/
public HttpResponseMessage Post(Register_Employee regEmp)
{
ClaimsPrincipal cp = RequestContext.Principal as ClaimsPrincipal;
if (regEmp == null)
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The parameter is empty"));
int id = RegisterEmployeeDA.PostRegisterEmployee(regEmp, cp.Claims);
HttpResponseMessage response = new HttpResponseMessage();
String url = String.Format("{0}{1}", HttpContext.Current.Request.Url.ToString(), id);
response.Headers.Location = new Uri(url);
response.StatusCode = HttpStatusCode.Created;
return response;
}
/*
* Put a Register_Employee to database.
*/
public HttpResponseMessage Put(Register_Employee regEmp)
{
ClaimsPrincipal cp = RequestContext.Principal as ClaimsPrincipal;
if (regEmp == null)
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The parameter is empty"));
int id = RegisterEmployeeDA.PutRegisterEmployee(regEmp, cp.Claims);
if(id < 1)
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The server could not update the object"));
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
return response;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterviewQuestions
{
public class SystemTextEncoding
{
public static void Test()
{
string strTmp = "abcdefg某某某";
byte[] byt = System.Text.Encoding.Default.GetBytes(strTmp);
int i = System.Text.Encoding.UTF8.GetBytes(strTmp).Length;
int j = strTmp.Length;
Console.WriteLine("X={0},Y={1}", i, j);
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dentist.ViewModels
{
public class RegistrationViewModel
{
[Required]
[Display(Name = "Registration Number")]
public string Number { get; set; }
[Required]
[Display(Name = "Registration College")]
public string College { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;
namespace TaxiDriverSystem
{
public partial class Qalification : Form
{
string ConnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
SqlConnection con;
public Qalification()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtQID.Text = "";
cmbQtype.Text = "";
txtName.Text = "";
dateTimePickerExpireDate.Text = "";
GetDriverID();
}
private void txtQID_TextChanged(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
string QType = cmbQtype.Text;
string QName = txtName.Text;
string Date = dateTimePickerExpireDate.Text;
Connection_Query Database = new Connection_Query();
Database.OpenObject();
Database.OpenConnection();
Database.ExecuteQueries("INSERT INTO Qualification(Type, Name, ExpireDate) VALUES('" + QType + "', '" + QName + "','" + Date + "')");
MessageBox.Show("Qualification is Added");
Database.CloseConnection();
PopulateGridview();
GetDriverID();
txtQID.Text = "";
cmbQtype.Text = "";
txtName.Text = "";
dateTimePickerExpireDate.Text = "";
}
void GetDriverID()
{
int QID = 1;
con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select max (Q_ID) from Qualification", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DataRow row1 = dt.Rows[dt.Rows.Count - 1];
QID = Convert.ToInt32(dt.Rows[0]["Column1"].ToString()) + QID;
txtQID.Text = QID.ToString();
}
void PopulateGridview()
{
con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Qualification", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DataRow row1 = dt.Rows[dt.Rows.Count - 1];
dataGridView1.DataSource = dt;
}
private void Qalification_Load(object sender, EventArgs e)
{
GetDriverID();
PopulateGridview();
}
private void btnDelete_Click(object sender, EventArgs e)
{
int QID = Convert.ToInt32(txtQID.Text);
Connection_Query Database = new Connection_Query();
Database.OpenObject();
Database.OpenConnection();
Database.ExecuteQueries("DELETE from Qualification where Q_ID = " + QID + "");
MessageBox.Show("Qualification is Deleted");
Database.CloseConnection();
PopulateGridview();
GetDriverID();
cmbQtype.Text = "";
txtName.Text = "";
dateTimePickerExpireDate.Text = "";
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
txtQID.Text = Convert.ToString(selectedRow.Cells["Q_ID"].Value);
cmbQtype.Text = Convert.ToString(selectedRow.Cells["Type"].Value);
txtName.Text = Convert.ToString(selectedRow.Cells["Name"].Value);
dateTimePickerExpireDate.Text = Convert.ToString(selectedRow.Cells["ExpireDate"].Value);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
int Q_ID = Convert.ToInt32(txtQID.Text);
string QType = cmbQtype.Text;
string QName = txtName.Text;
string Date = dateTimePickerExpireDate.Text;
Connection_Query Database = new Connection_Query();
Database.OpenObject();
Database.OpenConnection();
Database.ExecuteQueries("UPDATE Qualification set Type ='" + QType + "', Name = '" + QName + "', ExpireDate = '" + Date + "' where Q_ID = " + Q_ID + "");
MessageBox.Show("Driver is Updated");
Database.CloseConnection();
PopulateGridview();
GetDriverID();
cmbQtype.Text = "";
txtName.Text = "";
dateTimePickerExpireDate.Text = "";
}
}
}
|
#region 版本说明
/*****************************************************************************
*
* 项 目 :
* 作 者 : 陈锐(开发)
* 创建时间 : 2010-4-27 下午 01:23:35
*
* Copyright (C) 2008 - 鹏业软件公司
*
*****************************************************************************/
#endregion
/*
<!---->
<component id="AttachmentFileServiceSvr" type="PengeSoft.CMS.BaseDatum.AttachmentFileServiceSvr, PengeSoft.CMS.BaseDatum" service="CMS.BaseDatum.IAttachmentFileServiceSvr, CMS.BaseDatum" lifestyle="Singleton">
<parameters>
</parameters>
</component>
*/
using System;
using System.Collections;
using System.Text;
using Castle.Windsor;
using PengeSoft.Data;
using PengeSoft.Enterprise.Appication;
using PengeSoft.WorkZoneData;
using PengeSoft.Common.Exceptions;
using PengeSoft.Auther.RightCheck;
using PengeSoft.Service;
using PengeSoft.db.IBatis;
using IBatisNet.DataAccess;
namespace PengeSoft.CMS.BaseDatum
{
/// <summary>
/// AttachmentFileServiceSvr实现。附件文件服务
/// </summary>
public class AttachmentFileServiceSvr : ApplicationBase, IAttachmentFileServiceSvr
{
#region 服务描述
private IDaoManager _daoManager = null;
private IAttachmentFileDao _AttachmentFileDao = null;
public override void FormActionList(AppActionList Acts)
{
base.FormActionList(Acts);
// 添加需发布的功能信息
}
public override void FormAttribsRec(PengeSoft.WorkZoneData.AppAttribBaseRec attr)
{
base.FormAttribsRec(attr);
attr.Detail = "";
}
public AttachmentFileServiceSvr()
{
_daoManager = ServiceConfig.GetInstance().DaoManager;
_AttachmentFileDao = (IAttachmentFileDao)_daoManager.GetDao(typeof(IAttachmentFileDao));
}
#endregion
#region IAttachmentFileServiceSvr 函数
/// <summary>
/// 添加附件文件
/// </summary>
/// <param name="item">附件文件对象</param>
public void AddAttachmentFile(AttachmentFile item)
{
item.CreateTime = DateTime.Now;
_AttachmentFileDao.Insert(item);
}
/// <summary>
/// 删除附件文件
/// </summary>
/// <param name="fileId">附件文件id</param>
public void DeleteAttachmentFile(string fileId)
{
AttachmentFile attachmentFile = new AttachmentFile();
attachmentFile.FileId = fileId;
_AttachmentFileDao.Delete(attachmentFile);
}
/// <summary>
/// 获取附件文件
/// </summary>
/// <param name="fileId">附件文件ID</param>
public AttachmentFile GetAttachmentFile(string fileId)
{
AttachmentFile attachmentFile = new AttachmentFile();
attachmentFile.FileId = fileId;
return _AttachmentFileDao.GetDetail(attachmentFile) as AttachmentFile;
}
/// <summary>
/// 更新附件(OCR内容)
/// </summary>
/// <param name="item">附件内容对象</param>
[PublishMethod("item")]
public void ChangeOCRContent(AttachmentFile item)
{
item.IsOCRed = (int)EAttachmentFileIsOCR.Yes;
_AttachmentFileDao.Update("UpdateAttachmentFileOCRContent", item);
}
/// <summary>
/// 查询附件列表
/// </summary>
/// <param name="param">查询条件</param>
/// <param name="start">起始记录</param>
/// <param name="pagesize">页大小</param>
public AttachmentFileList QueryAttachmentFileList(AttachmentFileQueryPara param, int start, int pagesize)
{
DataList rec = null;
rec= _AttachmentFileDao.QueryList(param, start, pagesize);
AttachmentFileList list = new AttachmentFileList();
if (rec != null)
list.AddFrom(rec);
return list;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(5000);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Loading Is working!!');</script>");
lbl_msg_advice.Text = "Hello";
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityStandardAssets.ImageEffects;
using Spine.Unity;
using UnityEngine.EventSystems;
public class campamentosOffline : MonoBehaviour {
public GameObject Player;
public GameObject[] camp;
public GameObject uno;
public GameObject dos;
public GameObject tres;
public string BaseBuena;
public GameObject[] Bases;
public GameObject A1;
public GameObject B1;
public GameObject BasePrimaria;
public GameObject alpha;
public Sprite alpha1;
public Sprite alpha2;
public Sprite alpha3;
public Sprite alpha4;
public GameObject alphaEnemy;
public Sprite alphaEnemy1;
public Sprite alphaEnemy2;
public GameObject beta;
public Sprite beta1;
public Sprite beta2;
public Sprite beta3;
public Sprite beta4;
public GameObject betaEnemy;
public Sprite betaEnemy1;
public Sprite betaEnemy2;
public string buena;
public string mala;
public GameObject Camara;
public int nace;
public GameObject Cabeza;
// Use this for initialization
void Start ()
{
Cabeza = Player.GetComponent<Hero>().cabeza;
}
public GameObject selectedObj;
public EventSystem eventsystem;
public bool contar;
public float cuentaatras;
public Text contador;
public string idioma;
// Update is called once per frame
void Update ()
{
idioma = PlayerPrefs.GetString("idioma");
if(contar)
{
Player.GetComponent<Hero>().salud = 0;
nace = 0;
BasePrimaria.SetActive(false);
alpha.SetActive(false);
beta.SetActive(false);
uno.SetActive(false);
dos.SetActive(false);
tres.SetActive(false);
alphaEnemy.SetActive(false);
betaEnemy.SetActive(false);
if(idioma == "ENGLISH")
{
contador.text = "Waiting..."+cuentaatras.ToString("F0");
}
if(idioma == "SPANISH")
{
contador.text = "Esperando..."+cuentaatras.ToString("F0");
}
if(idioma == "CHINESE")
{
contador.text = "等候..."+cuentaatras.ToString("F0");
}
cuentaatras -= Time.deltaTime;
if(cuentaatras <= 0)
{
BasePrimaria.SetActive(true);
eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(BasePrimaria);
contar = false;
}
}else
{
contador.text = "";
//RESELECCIONAR ELEMENTO DE MENU
//eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(m1);
if (eventsystem.GetComponent<EventSystem>().currentSelectedGameObject == null)
{
eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(selectedObj);
//EventSystem.current.SetSelectedGameObject(selectedObj);
}
selectedObj = eventsystem.GetComponent<EventSystem>().currentSelectedGameObject;
//CAMBIE ENTRE CONTROL Y TECLADO
if(Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)
{
eventsystem.GetComponent<StandaloneInputModule>().horizontalAxis = "Horizontal";
eventsystem.GetComponent<StandaloneInputModule>().verticalAxis = "Vertical";
}
if(Input.GetButtonDown("HorizontalUI") || Input.GetButtonDown("VerticalUI"))
{
eventsystem.GetComponent<StandaloneInputModule>().horizontalAxis = "HorizontalUI";
eventsystem.GetComponent<StandaloneInputModule>().verticalAxis = "VerticalUI";
}
if(Player.tag == "Player")
{
buena = "BaseBuena";
mala = "BaseMala";
alpha.GetComponent<Image>().sprite = alpha1;
SpriteState spritestate = new SpriteState();
spritestate.highlightedSprite = alpha2;
alpha.GetComponent<Button>().spriteState = spritestate;
alphaEnemy.GetComponent<Image>().sprite = alphaEnemy2;
}else
{
buena = "BaseMala";
mala = "BaseBuena";
alpha.GetComponent<Image>().sprite = alpha3;
SpriteState spritestate = new SpriteState();
spritestate.highlightedSprite = alpha4;
alpha.GetComponent<Button>().spriteState = spritestate;
alphaEnemy.GetComponent<Image>().sprite = alphaEnemy1;
}
if(Camara == null)
{
Camara = GameObject.FindGameObjectWithTag("MainCamera");
}
if(A1 == null)
{
A1 = GameObject.Find("ALPHA");
}else if(A1.tag == buena)
{
Bases[0] = A1;
alphaEnemy.SetActive(false);
}else if(A1.tag == mala)
{
Bases[0] = null;
alphaEnemy.SetActive(true);
}else
{
alphaEnemy.SetActive(false);
Bases[0] = null;
}
if(B1 == null)
{
B1 = GameObject.Find("BETA");
}else if(B1.tag == buena)
{
Bases[1] = B1;
}else if(B1.tag == mala)
{
betaEnemy.SetActive(true);
}else
{
Bases[1] = null;
}
if(Bases[0] != null)
{
alpha.SetActive(true);
}else
{
alpha.SetActive(false);
}
if(Bases[1] != null)
{
beta.SetActive(true);
}else
{
beta.SetActive(false);
}
if(camp[0] != null)
{
uno.SetActive(true);
}else
{
uno.SetActive(false);
}
if(camp[1] != null)
{
dos.SetActive(true);
}else
{
dos.SetActive(false);
}
if(camp[2] != null)
{
tres.SetActive(true);
}else
{
tres.SetActive(false);
}
}
}
public void Base()
{
nace = 0;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(Player.GetComponent<Animaciones>().inicial.x, Player.transform.position.y+12, Player.GetComponent<Animaciones>().inicial.z-100);
}
public void primero()
{
nace = 1;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(camp[0].transform.position.x, Player.transform.position.y+12, camp[0].transform.position.z-100);//camp[0].transform.position;
}
public void segundo()
{
nace = 2;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(camp[1].transform.position.x, Player.transform.position.y+12, camp[1].transform.position.z-100);//camp[0].transform.position;
}
public void tercero()
{
nace = 3;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(camp[2].transform.position.x, Player.transform.position.y+12, camp[2].transform.position.z-100);//camp[0].transform.position;
}
public void A()
{
nace = 5;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(Bases[0].transform.position.x, Player.transform.position.y+12, Bases[0].transform.position.z-100);//Bases[0].transform.position;
}
public void B()
{
nace = 6;
Camara.GetComponent<Cam>().campamento = true;
Camara.GetComponent<Cam>().campPos = new Vector3(Bases[1].transform.position.x, Player.transform.position.y+12, Bases[1].transform.position.z-100);//Bases[0].transform.position;
}
public void nacer()
{
if(Application.loadedLevelName == "Tutorial")
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
nace = 0;
BasePrimaria.SetActive(false);
alpha.SetActive(false);
beta.SetActive(false);
uno.SetActive(false);
dos.SetActive(false);
tres.SetActive(false);
alphaEnemy.SetActive(false);
betaEnemy.SetActive(false);
Player.GetComponent<Hero>().animacion.SetActive(false);
Player.GetComponent<CustomFinal>().skinsToCombine[0] = Player.GetComponent<CustomFinal>().casco;
Player.GetComponent<CustomFinal>().listo = false;
Cabeza.GetComponent<Cabeza>().tirosCabeza = 0;
Camara.GetComponent<Cam>().shake = false;
Camara.GetComponent<Cam>().shake2 = false;
Camara.GetComponent<Cam>().shakeAvion = false;
Camara.GetComponent<Cam>().shakeAvion2 = false;
Camara.GetComponent<Cam>().campamento = false;
Player.GetComponent<Hero>().eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(Player.GetComponent<Hero>().carta1);
Player.GetComponent<Hero>().SniperCam.GetComponent<Grayscale>().enabled = false;
Player.GetComponent<Hero>().animacion.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "simple", false);
Player.GetComponent<Hero>().esconderBarra.SetActive(true);
}else
{
if(nace == 0)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(Player.GetComponent<Animaciones>().inicial.x, Player.GetComponent<Animaciones>().inicial.y+10, Player.GetComponent<Animaciones>().inicial.z);//Player.GetComponent<Animaciones>().inicial;
}else if(nace == 1)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(camp[0].transform.position.x, Player.GetComponent<Animaciones>().inicial.y+10, camp[0].transform.position.z);
nace = 0;
}else if(nace == 2)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(camp[1].transform.position.x, Player.GetComponent<Animaciones>().inicial.y+10, camp[1].transform.position.z);
nace = 0;
}else if(nace == 3)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(camp[2].transform.position.x, Player.GetComponent<Animaciones>().inicial.y+10, camp[2].transform.position.z);
nace = 0;
}else if(nace == 5)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(Bases[0].transform.position.x, Player.GetComponent<Animaciones>().inicial.y+10, Bases[0].transform.position.z-3);
nace = 0;
}else if(nace == 6)
{
Player.GetComponent<Hero>().salud = Player.GetComponent<Hero>().saludMax;
Player.GetComponent<Hero>().vivo = true;
Player.GetComponent<Animator>().SetBool("muerto", false);
//Player.GetComponent<Hero>().mascara = "Player";
Player.GetComponent<Hero>().Base.layer = LayerMask.NameToLayer("Vista");
Player.transform.position = new Vector3(Bases[1].transform.position.x, Player.GetComponent<Animaciones>().inicial.y+10, Bases[1].transform.position.z-3);
nace = 0;
}
BasePrimaria.SetActive(false);
alpha.SetActive(false);
beta.SetActive(false);
uno.SetActive(false);
dos.SetActive(false);
tres.SetActive(false);
alphaEnemy.SetActive(false);
betaEnemy.SetActive(false);
Player.GetComponent<Hero>().animacion.SetActive(false);
Player.GetComponent<CustomFinal>().skinsToCombine[0] = Player.GetComponent<CustomFinal>().casco;
Player.GetComponent<CustomFinal>().listo = false;
Cabeza.GetComponent<Cabeza>().tirosCabeza = 0;
Camara.GetComponent<Cam>().shake = false;
Camara.GetComponent<Cam>().shake2 = false;
Camara.GetComponent<Cam>().shakeAvion = false;
Camara.GetComponent<Cam>().shakeAvion2 = false;
Camara.GetComponent<Cam>().campamento = false;
Camara.GetComponent<Cam>().dramatica = false;
Player.GetComponent<Hero>().eventsystem.GetComponent<EventSystem>().SetSelectedGameObject(Player.GetComponent<Hero>().carta1);
Player.GetComponent<Hero>().SniperCam.GetComponent<Grayscale>().enabled = false;
Player.GetComponent<Hero>().animacion.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "simple", false);
Player.GetComponent<Hero>().esconderBarra.SetActive(true);
nace = 0;
}
}
}
|
using Lowscope.Saving;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace Lowscope.Saving.Examples
{
public class ExamplePauseMenu : MonoBehaviour
{
[Header("References")]
[SerializeField] private GameObject pauseMenuObjects;
[SerializeField] private ExampleSlotMenu slotMenu;
[SerializeField] private Button buttonLoad;
[SerializeField] private Button buttonSave;
[SerializeField] private Button buttonQuit;
[Header("Configuration")]
[SerializeField] private KeyCode[] openMenuKeys = new KeyCode[1] { KeyCode.Escape };
[SerializeField] private string quitToScene;
[SerializeField] private bool closeWindowOnSave = true;
[SerializeField] private bool closeWindowOnLoad = true;
[SerializeField] private GameObject[] toggleObjectVisibility;
private Dictionary<GameObject, bool> cachedVisibility = new Dictionary<GameObject, bool>();
int openMenuKeyCount;
private void Awake()
{
openMenuKeyCount = openMenuKeys.Length;
buttonLoad.onClick.AddListener(OnOpenSlotMenuLoad);
buttonSave.onClick.AddListener(OnOpenSlotMenuSave);
buttonQuit.onClick.AddListener(OnQuit);
if (closeWindowOnSave)
{
SaveMaster.OnWritingToDiskDone += OnWrittenToDisk;
}
if (closeWindowOnLoad)
{
SaveMaster.OnSlotChangeDone += OnChangedSlot;
}
int toggleVisibilityCount = toggleObjectVisibility.Length;
for (int i = 0; i < toggleVisibilityCount; i++)
{
cachedVisibility.Add(toggleObjectVisibility[i], toggleObjectVisibility[i].activeSelf);
}
}
private void OnDestroy()
{
if (closeWindowOnSave)
{
SaveMaster.OnWritingToDiskDone -= OnWrittenToDisk;
}
if (closeWindowOnLoad)
{
SaveMaster.OnSlotChangeDone -= OnChangedSlot;
}
}
private void OnChangedSlot(int arg1, int arg2)
{
Hide();
}
private void OnWrittenToDisk(int obj)
{
Hide();
}
private void OnEnable()
{
Hide();
}
private void OnQuit()
{
SceneManager.LoadScene(quitToScene);
}
private void OnOpenSlotMenuSave()
{
slotMenu.SetMode(ExampleSlotMenu.Mode.Save);
slotMenu.gameObject.SetActive(true);
}
private void OnOpenSlotMenuLoad()
{
slotMenu.SetMode(ExampleSlotMenu.Mode.Load);
slotMenu.gameObject.SetActive(true);
}
public void Display()
{
slotMenu.gameObject.SetActive(false);
pauseMenuObjects.gameObject.SetActive(true);
int toggleVisibilityCount = toggleObjectVisibility.Length;
for (int i = 0; i < toggleVisibilityCount; i++)
{
toggleObjectVisibility[i].gameObject.SetActive(false);
}
}
public void Hide()
{
slotMenu.gameObject.SetActive(false);
pauseMenuObjects.gameObject.SetActive(false);
int toggleVisibilityCount = toggleObjectVisibility.Length;
for (int i = 0; i < toggleVisibilityCount; i++)
{
bool visible;
if (cachedVisibility.TryGetValue(toggleObjectVisibility[i], out visible))
{
toggleObjectVisibility[i].gameObject.SetActive(visible);
}
}
}
private void Update()
{
for (int i = 0; i < openMenuKeyCount; i++)
{
if (Input.GetKeyDown(openMenuKeys[i]))
{
if (!pauseMenuObjects.activeSelf)
{
Display();
}
else
{
Hide();
}
return;
}
}
}
}
} |
using System;
namespace HT.Framework
{
/// <summary>
/// 【自动化任务】对象路径定义,将根据设置的路径查找子对象用以初始化(仅可用于 EntityLogicBase 及 UILogicBase 及 HTBehaviour 子类中定义的非静态字段)
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class ObjectPathAttribute : Attribute
{
/// <summary>
/// 路径
/// </summary>
public string Path { get; private set; }
public ObjectPathAttribute(string path)
{
Path = path;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomTreasureSpawner : MonoBehaviour
{
public bool looping = false;
public float loopDelay = 60;
public GameObject treasure;
public string treasurePrefabFolder = "Prefabs/RNGTreasure";
// Start is called before the first frame update
void Start()
{
init();
}
// Update is called once per frame
void Update()
{
}
void init()
{
GameObject[] treasureList = Resources.LoadAll<GameObject>(treasurePrefabFolder);
int randomRoll = Random.Range(-(treasureList.Length - 1), treasureList.Length - 1);
if(randomRoll >= 0)
{
treasure = treasureList[randomRoll];
spawnOnce();
}
}
public void spawnOnce()
{
GameObject treasureInstance = Instantiate(treasure, transform.position, transform.rotation);
Destroy(gameObject);
}
}
|
/*
* Copyright 2014 Technische Universitšt Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using EnvDTE;
using JetBrains.Application;
using JetBrains.Application.Threading;
using KaVE.Commons.Utils;
using KaVE.Commons.Utils.Exceptions;
using KaVE.JetBrains.Annotations;
using KaVE.VS.Commons;
using KaVE.VS.Commons.Generators;
namespace KaVE.VS.FeedbackGenerator.Generators.VisualStudio
{
[ShellComponent]
internal class VsWindowButtonInstrumentationComponent
{
private static readonly IDictionary<Window, VsWindowButtonClickEventGenerator> WindowRegistry =
new Dictionary<Window, VsWindowButtonClickEventGenerator>();
private readonly IRSEnv _env;
private readonly IMessageBus _messageBus;
private readonly IDateUtils _dateUtils;
private readonly ILogger _logger;
private readonly IThreading _threading;
[UsedImplicitly]
private WindowEvents _windowEvents;
public VsWindowButtonInstrumentationComponent([NotNull] IRSEnv env,
[NotNull] IMessageBus messageBus,
[NotNull] IDateUtils dateUtils,
[NotNull] ILogger logger,
[NotNull] IThreading threading)
{
_env = env;
_messageBus = messageBus;
_dateUtils = dateUtils;
_logger = logger;
_threading = threading;
Initialize(env);
}
private void Initialize(IRSEnv env)
{
var dte = env.IDESession.DTE;
if (dte.ActiveWindow != null)
{
OnWindowActivated(dte.ActiveWindow, null);
}
_windowEvents = dte.Events.WindowEvents;
_windowEvents.WindowActivated += OnWindowActivated;
}
private void OnWindowActivated(Window focusedWindow, Window lostfocus)
{
try
{
VsWindowButtonClickEventGenerator listener;
if (!WindowRegistry.TryGetValue(focusedWindow, out listener))
{
listener = new VsWindowButtonClickEventGenerator(
focusedWindow,
_env,
_messageBus,
_dateUtils,
_logger,
_threading,
new DoubleCommandEventDetector(_dateUtils));
WindowRegistry[focusedWindow] = listener;
}
listener.WindowChanged();
}
catch (Exception e)
{
_logger.Error(e, "instrumenting buttons in window failed");
}
}
}
} |
using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;
using Discord.Commands;
using WestBot;
namespace Westbot
{
class Program
{
static void Main(string[] call_args)
=> new Program().MainAsync(call_args).GetAwaiter().GetResult();
public async Task MainAsync(string[] call_args)
{
var services = ConfigureServices();
var client = services.GetRequiredService<DiscordSocketClient>();
client.Log += LogAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;
BotConfiguration.Load(call_args);
await client.LoginAsync(TokenType.Bot, BotConfiguration.Token);
await client.StartAsync();
await services.GetRequiredService<Services.CommandHandler>().InstallCommandsAsync();
client.Ready += () =>
{
ulong BotVersionChannel = 0;
try
{
BotVersionChannel = DatabaseHandler.GetChannelID("BotVersion");
}
catch (Exception ex)
{
Console.Write("Exception: " + ex.Message);
}
var Guild = client.GetGuild(BotConfiguration.ServerID);
var channel = Guild.GetTextChannel(BotVersionChannel);
string version = "";
try
{
version = DatabaseHandler.GetVersion();
}
catch (Exception ex)
{
Console.Write("Exception: " + ex.Message);
}
if(version != "0")
channel.SendMessageAsync("Bot version " + version + " is online.");
Console.WriteLine("**Bot online.**");
return Task.CompletedTask;
};
await Task.Delay(-1);
}
private Task LogAsync(LogMessage log)
{
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private IServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<CommandService>()
.AddSingleton<Services.CommandHandler>()
//.AddSingleton<Tournament>()
.AddSingleton<HttpClient>()
.BuildServiceProvider();
}
}
} |
using System.Collections.Generic;
namespace AddressBook.SearchForm
{
class SearchFormModel
{
public List<string> GetCategories()
{
//but this should accessed db
var cat = new List<string> {"Minny", "Miney", "Moo"};
return cat;
}
}
}
|
using Android.Content;
using Android.Graphics;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace Forms.Plugin.CardForm.Platforms.Helpers
{
public class ImageHelper
{
private static IImageSourceHandler GetHandler(ImageSource source)
{
IImageSourceHandler returnValue = null;
if (source is UriImageSource)
{
returnValue = new ImageLoaderSourceHandler();
}
else if (source is FileImageSource)
{
returnValue = new FileImageSourceHandler();
}
else if (source is StreamImageSource)
{
returnValue = new StreamImagesourceHandler();
}
return returnValue;
}
public static async Task<Bitmap> GetBitmapFromImageSourceAsync(ImageSource source, Context context)
{
var handler = GetHandler(source);
var returnValue = (Bitmap)null;
returnValue = await handler.LoadImageAsync(source, context);
return returnValue;
}
}
}
|
using Arch.Data.Common.Enums;
using Arch.Data.Orm.sql;
using System;
using System.Collections.Generic;
using System.Text;
namespace Arch.Data.Orm.Dialect
{
/// <summary>
/// MySql方言
/// </summary>
public class MySqlDialect : DbDialect
{
public override Char OpenQuote
{
get { return '`'; }
}
public override Char CloseQuote
{
get { return '`'; }
}
public override String IdentitySelectString
{
get { return "SELECT LAST_INSERT_ID();\n"; }
}
/// <summary>
/// 拼接操作头部
/// </summary>
/// <returns></returns>
public override String QuoteOpenOpName(String name)
{
return name;
}
/// <summary>
/// 加锁类型值
/// </summary>
/// <returns></returns>
public override String WithLock(String parameterName)
{
return String.Empty;
}
public override String LimitPrefix(Int32 from, Int32 to)
{
return String.Empty;
}
public override String LimitSuffix(Int32 from, Int32 to)
{
if (from > 0 || to > 0)
{
StringBuilder sb = new StringBuilder(" LIMIT ");
sb.Append(from);
if (to > 0)
{
sb.Append(",")
.Append(to);
}
return sb.ToString();
}
return String.Empty;
}
public override String PagingPrefix(Int32 pageNumber, Int32 pageSize, String orderColumnName, Boolean isAscending)
{
return String.Empty;
}
private const String PagingSuffixTemplate = " ORDER BY {0}{1}{2} {3} LIMIT {4},{5}";
public override String PagingSuffix(Int32 pageNumber, Int32 pageSize, String orderColumnName, Boolean isAscending, IList<SqlColumn> sqlColumns)
{
StringBuilder sb = new StringBuilder();
if (pageNumber > 0 && pageSize > 0 && !String.IsNullOrEmpty(orderColumnName))
{
sb.AppendFormat(PagingSuffixTemplate,
OpenQuote,
orderColumnName,
CloseQuote,
isAscending ? String.Empty : OrderDirection.DESC.ToString(),
(pageNumber - 1) * pageSize,
pageSize);
}
return sb.ToString();
}
}
}
|
using System;
class Program
{
static void Main()
{
//Circle variables
int center_X = 1;
int center_Y = 1;
float radius = 1.5f;
//Points coordinates
var coordinates = new float[10, 2];
coordinates[0, 0] = 1;
coordinates[0, 1] = 2;
coordinates[1, 0] = 2.5f;
coordinates[1, 1] = 2;
coordinates[2, 0] = 0;
coordinates[2, 1] = 1;
coordinates[3, 0] = 2.5f;
coordinates[3, 1] = 1;
coordinates[4, 0] = 2;
coordinates[4, 1] = 0;
coordinates[5, 0] = 4;
coordinates[5, 1] = 0;
coordinates[6, 0] = 2.5f;
coordinates[6, 1] = 1.5f;
coordinates[7, 0] = 2;
coordinates[7, 1] = 1.5f;
coordinates[8, 0] = 1;
coordinates[8, 1] = 2.5f;
coordinates[9, 0] = -100;
coordinates[9, 1] = -100;
for (int i = 0; i < 10; i++)
{
float x = coordinates[i, 0];
float y = coordinates[i, 1];
float dx = Math.Abs(x - center_X);
float dy = y - center_Y;
Console.Write(x.ToString().PadRight(6,' '));
Console.Write(y.ToString().PadRight(6, ' '));
if (dy > 0 && dy < radius)
{
if (dx < radius)
{
Console.Write(true);
}
else
{
Console.Write(false);
}
}
else
{
Console.Write(false);
}
Console.WriteLine();
}
}
}
|
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using NtObjectManager.Utils;
using System.Management.Automation;
using System.Text;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Creates a new ALPC message.</para>
/// <para type="description">This cmdlet creates a new ALPC message based on a byte array or an length initializer.
/// You can also specify a text encoding which allows you to use the DataString property.</para>
/// </summary>
/// <example>
/// <code>$msg = New-NtAlpcMessage -Bytes @(0, 1, 2, 3)</code>
/// <para>Create a new message from a byte array.</para>
/// </example>
/// <example>
/// <code>$msg = New-NtAlpcMessage -Bytes @(0, 1, 2, 3) -AllocatedDataLength 1000</code>
/// <para>Create a new message from a byte array with an allocated length of 1000 bytes.</para>
/// </example>
/// <example>
/// <code>$msg = New-NtAlpcMessage -AllocatedDataLength 1000</code>
/// <para>Create a new message with an allocated length of 1000 bytes.</para>
/// </example>
/// <example>
/// <code>$msg = New-NtAlpcMessage -AllocatedDataLength 1000 -Encoding UTF8</code>
/// <para>Create a new message with an allocated length of 1000 bytes and the message encoding is UTF8.</para>
/// </example>
/// <example>
/// <code>$msg = New-NtAlpcMessage -String "Hello World!"</code>
/// <para>Create a new message from a unicode string.</para>
/// </example>
/// <example>
/// <code>$msg = New-NtAlpcMessage -String "Hello World!" -Encoding UTF8</code>
/// <para>Create a new message from a UTF8 string.</para>
/// </example>
/// <para type="link">about_ManagingNtObjectLifetime</para>
[Cmdlet(VerbsCommon.New, "NtAlpcMessage", DefaultParameterSetName = "FromLength")]
[OutputType(typeof(AlpcMessage))]
public class NewNtAlpcMessageCmdlet : PSCmdlet
{
/// <summary>
/// <para type="description">Create the message from a byte array.</para>
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "FromBytes")]
public byte[] Bytes { get; set; }
/// <summary>
/// <para type="description">Create the message from a string.</para>
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "FromString")]
public string String { get; set; }
/// <summary>
/// <para type="description">Get or set the text encoding for this message.</para>
/// </summary>
[Parameter(ParameterSetName = "FromLength")]
[Parameter(ParameterSetName = "FromBytes")]
[Parameter(ParameterSetName = "FromString")]
public TextEncodingType Encoding { get; set; }
/// <summary>
/// <para type="description">Specify the message with allocated length.</para>
/// </summary>
[Parameter(Position = 0, ParameterSetName = "FromLength")]
[Parameter(Position = 1, ParameterSetName = "FromBytes")]
[Parameter(Position = 1, ParameterSetName = "FromString")]
public int AllocatedDataLength { get; set; }
/// <summary>
/// Constructor.
/// </summary>
public NewNtAlpcMessageCmdlet()
{
AllocatedDataLength = AlpcMessage.MaximumDataLength;
Encoding = TextEncodingType.Unicode;
}
/// <summary>
/// Process record.
/// </summary>
protected override void ProcessRecord()
{
Encoding encoding = PSUtils.GetEncoding(Encoding);
if (ParameterSetName == "FromBytes")
{
WriteObject(new AlpcMessageRaw(Bytes, AllocatedDataLength, encoding));
}
else if (ParameterSetName == "FromString")
{
WriteObject(new AlpcMessageRaw(encoding.GetBytes(String), AllocatedDataLength, encoding));
}
else
{
WriteObject(new AlpcMessageRaw(AllocatedDataLength, encoding));
}
}
}
}
|
using Common;
using Facebook;
using Models.DAO;
using Models.EF;
using OnlineShop.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OnlineShop.Controllers
{
public class UserController : Controller
{
private Uri RedirectUri
{
get
{
var uriBuilder = new UriBuilder(Request.Url);
uriBuilder.Query = null;
uriBuilder.Fragment = null;
uriBuilder.Path = Url.Action("FacebookCallback");
return uriBuilder.Uri;
}
}
// View Đăng Ký
// GET: User
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid) // Kiểm tra fomr
{
var dao = new UserDAO();
if (dao.CheckUserName(model.UserName)) // kiểm tra Tên Đăng Nhập
{
ModelState.AddModelError("", "Tên Đăng Nhập Đã Tồn Tại");
}
else if (dao.CheckEmail(model.Email)) // Kiểm tra Email
{
ModelState.AddModelError("", "Email Đã Được Đăng Ký");
}
else
{
var user = new User(); // tạo mới 1 người dùng
user.UserName = model.UserName;
user.Password = Encryptor.MD5Hash(model.Password);
user.Name = model.Name;
user.Address = model.Address;
user.Phone = model.Phone;
user.Email = model.Email;
user.GroupID = "MEMBER";
user.CreateDate = DateTime.Now;
user.Status = true;
var result = dao.Insert(user); // Thêm người dùng
if (result > 0)
{
UserLogin u = new UserLogin();
u.UserID = user.ID;
u.UserName = user.UserName;
u.Name = user.Name;
u.GroupID = user.GroupID;
Session[Common.SessionCommonConstants.USER_SESSION] = u;
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Đăng Ký Thất Bại");
}
}
}
return View(model);
}
// Đăng Nhập
public ActionResult Login()
{
return View();
}
//
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
var dao = new UserDAO();
var result = dao.Login(model.UserName, Encryptor.MD5Hash(model.Password), false);
if (result == 1) // Nếu tài khoản đúng
{
var user = dao.GetByUserName(model.UserName);
var userSession = new UserLogin();
userSession.UserName = user.UserName;
userSession.UserID = user.ID;
userSession.Name = user.Name;
userSession.GroupID = user.GroupID;
var listCredentials = dao.GetListCredentials(user.UserName);
Session.Add(Common.SessionCommonConstants.USER_SESSION, userSession);
Session.Add(Common.SessionCommonConstants.CREDENTIALS_SESSION, listCredentials);
return RedirectToAction("Index", "Home");
}
else if (result == 0)
{
ModelState.AddModelError("", "Tài Khoản Không Tồn Tại");
}
else if (result == -1)
{
ModelState.AddModelError("", "Tài Khoản Đang Bị Khóa");
}
else if (result == -2)
{
ModelState.AddModelError("", "Mật Khẩu Không Đúng");
}
else if (result == -3)
{
ModelState.AddModelError("", "Bạn Không Có Quyền Đăng Nhập");
}
else
{
ModelState.AddModelError("", "Lỗi Đăng Nhập");
}
}
return View(model);
}
// Đăng Nhập Bằng Facebook
public ActionResult LoginFacebook()
{
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(
new
{
client_id = ConfigurationManager.AppSettings["FbAppID"],
client_secret = ConfigurationManager.AppSettings["FbAppSecret"],
redirect_uri = RedirectUri.AbsoluteUri,
response_type = "code",
scope = "email",
}
);
return Redirect(loginUrl.AbsoluteUri);
}
// Kết quả trả về từ Facebook
public ActionResult FacebookCallback(string code)
{
var fb = new FacebookClient();
dynamic result = fb.Post("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["FbAppID"],
client_secret = ConfigurationManager.AppSettings["FbAppSecret"],
redirect_uri = RedirectUri.AbsoluteUri,
code = code
});
var accessToken = result.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
fb.AccessToken = accessToken;
// Lấy Thông Tin
dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,email");
var user = new User();
user.Email = me.email;
user.UserName = me.email;
user.Password = Encryptor.MD5Hash("123456");
user.GroupID = "MEMBER";
user.Status = true;
user.Name = me.first_name + " " + me.middle_name + " " + me.last_name;
user.CreateDate = DateTime.Now;
user.CreateBy = user.UserName;
var resultInsert = new UserDAO().InsertForFacebook(user); // Thêm User
if (resultInsert > 0)
{
var userSession = new UserLogin();
userSession.UserName = user.UserName;
userSession.UserID = resultInsert;
userSession.GroupID = user.GroupID;
userSession.Name = user.Name;
Session.Add(Common.SessionCommonConstants.USER_SESSION, userSession);
}
}
return Redirect("/");
}
// thông tin người dùng
[HttpGet]
public ActionResult UserDetail()
{
var userSession = (UserLogin)Session[Common.SessionCommonConstants.USER_SESSION];
var user = new User();
if (userSession != null)
{
user = new UserDAO().GetByID(userSession.UserID);
}
return View(user);
}
// Cập nhật thông tin cá nhân của người dùng
[HttpPost]
public ActionResult UserDetail(User user)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(user.Password))
{
user.Password = Encryptor.MD5Hash(user.Password);
}
user.GroupID = "MEMBER";
user.Status = true;
user.ModifiedBy = user.UserName;
user.ModifiedDate = DateTime.Now;
var result = new UserDAO().Update(user);
if (result == true)
{
return RedirectToAction("UserDetail", "User");
}
}
return View(user);
}
// Đăng Xuất
public ActionResult Logout()
{
Session[Common.SessionCommonConstants.USER_SESSION] = null;
return Redirect("/");
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Sklep.Cutomers
{
public class Updater : ICommand
{
private Action commandTask;
private Action<Customer> taskParameter;
public Updater(Action workToDo)
{
commandTask = workToDo;
}
public Updater(Action<Customer> workToDo)
{
taskParameter = workToDo;
}
public bool CanExecute(object parameter)
{
if(commandTask != null)
return true;
if (parameter != null)
return true;
return false;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
if (parameter == null)
commandTask();
else
taskParameter(parameter as Customer);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using ShopsRUs.Domain.Entity;
using ShopsRUs.Infrastructure.Configurations;
using ShopsRUs.Infrastructure.SeedData;
namespace ShopsRUs.Infrastructure
{
public class ShopsRUsContext:DbContext
{
public ShopsRUsContext(DbContextOptions<ShopsRUsContext> options):base(options)
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Discount> Discounts { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new UserConfiguration());
modelBuilder.ApplyConfiguration(new CustomerConfiguration());
modelBuilder.ApplyConfiguration(new DiscountConfiguration());
modelBuilder.ApplyConfiguration(new InvoiceConfiguration());
modelBuilder.Seed();
base.OnModelCreating(modelBuilder);
}
}
}
|
using System.Text.Json.Serialization;
namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json.Rooms;
internal sealed class JsonExplodeBlockMessage : JsonMessageOutgoingMessage
{
internal JsonExplodeBlockMessage(string roomName, int tileY, int tileX) : base(roomName, new RoomMessageData("explodeBlock", new ExplodeBlockData(tileY, tileX)))
{
}
private sealed class ExplodeBlockData
{
[JsonPropertyName("tileY")]
public int TileY { get; set; }
[JsonPropertyName("tileX")]
public int TileX { get; set; }
internal ExplodeBlockData(int tileY, int tileX)
{
this.TileY = tileY;
this.TileX = tileX;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ConfigColeccionable : MonoBehaviour
{
public Sprite noDisponible;
public Button coleccionble1;
public Text titulo_1;
public Text contenido_1;
public Sprite colec_1;
public Button coleccionble2;
public Text titulo_2;
public Text contenido_2;
public Sprite colec_2;
public Button coleccionble3;
public Text titulo_3;
public Text contenido_3;
public Sprite colec_3;
public Button coleccionble4;
public Text titulo_4;
public Text contenido_4;
public Sprite colec_4;
public Button coleccionble5;
public Text titulo_5;
public Text contenido_5;
public Sprite colec_5;
public Button coleccionble6;
public Text titulo_6;
public Text contenido_6;
public Sprite colec_6;
public Button coleccionble7;
public Text titulo_7;
public Text contenido_7;
public Sprite colec_7;
public Button coleccionble8;
public Text titulo_8;
public Text contenido_8;
public Sprite colec_8;
public Button coleccionble9;
public Text titulo_9;
public Text contenido_9;
public Sprite colec_9;
public Button coleccionble10;
public Text titulo_10;
public Text contenido_10;
public Sprite colec_10;
public Button coleccionble11;
public Text titulo_11;
public Text contenido_11;
public Sprite colec_11;
public Button coleccionble12;
public Text titulo_12;
public Text contenido_12;
public Sprite colec_12;
void Start()
{
/*
PlayerPrefs.SetInt("Colecionable_1", 1);
PlayerPrefs.SetInt("Colecionable_2", 1);
PlayerPrefs.SetInt("Colecionable_3", 1);
PlayerPrefs.SetInt("Colecionable_4", 1);
PlayerPrefs.SetInt("Colecionable_5", 1);
PlayerPrefs.SetInt("Colecionable_6", 1);
PlayerPrefs.SetInt("Colecionable_7", 1);
PlayerPrefs.SetInt("Colecionable_8", 1);
PlayerPrefs.SetInt("Colecionable_9", 1);
PlayerPrefs.SetInt("Colecionable_10", 1);
PlayerPrefs.SetInt("Colecionable_11", 1);
PlayerPrefs.SetInt("Colecionable_12", 1);
*/
//-----------------------------------------
AuidoScript.instance.Play("Colecionables");
AuidoScript.instance.Set_Volume("Colecionables", 100f);
AuidoScript.instance.Set_Volume("Marcha", 0f);
//----------------------------------------
if ( PlayerPrefs.GetInt("Colecionable_1") == 1)
{
titulo_1.text = "Me canso ganso";
contenido_1.text = "De los dichos más dichos llega: \"me canso ganso\" a formar de nuestro acervo mexicano";
coleccionble1.GetComponent<Image>().sprite = colec_1;
}
if (PlayerPrefs.GetInt("Colecionable_2") == 1)
{
titulo_2.text = "Galón de oro";
contenido_2.text = "El huachicol no es para que lo lleves en botellas de plástico.";
coleccionble2.GetComponent<Image>().sprite = colec_2;
}
if (PlayerPrefs.GetInt("Colecionable_3") == 1)
{
titulo_3.text = "Cuba de oro";
contenido_3.text = "Quien te trata como Tonayan cuando eres una Cuba no te merece.";
coleccionble3.GetComponent<Image>().sprite = colec_3;
}
if (PlayerPrefs.GetInt("Colecionable_4") == 1)
{
titulo_4.text = "500 gramos de oro";
contenido_4.text = "A éste le llamo el suspiro del águila.";
coleccionble4.GetComponent<Image>().sprite = colec_4;
}
if (PlayerPrefs.GetInt("Colecionable_5") == 1)
{
titulo_5.text = "Copete de oro";
contenido_5.text = "Ni el mismísimo penacho de Cuauhtémoc es más valioso que este monumento al estilacho.";
coleccionble5.GetComponent<Image>().sprite = colec_5;
}
if (PlayerPrefs.GetInt("Colecionable_6") == 1)
{
titulo_6.text = "La libreta de la abundancia de oro";
contenido_6.text = "¨Si merezco este coleccionable¨.";
coleccionble6.GetComponent<Image>().sprite = colec_6;
}
if (PlayerPrefs.GetInt("Colecionable_7") == 1)
{
titulo_7.text = "Alambre de púas de oro";
contenido_7.text = "¨Este si me lo paso por los...¨";
coleccionble7.GetComponent<Image>().sprite = colec_7;
}
if (PlayerPrefs.GetInt("Colecionable_8") == 1)
{
titulo_8.text = "";
contenido_8.text = "";
coleccionble6.GetComponent<Image>().sprite = colec_8;
}
if (PlayerPrefs.GetInt("Colecionable_9") == 1)
{
titulo_9.text = "";
contenido_9.text = "";
coleccionble9.GetComponent<Image>().sprite = colec_9;
}
if (PlayerPrefs.GetInt("Colecionable_10") == 1)
{
titulo_10.text = "";
contenido_10.text = "";
coleccionble6.GetComponent<Image>().sprite = colec_10;
}
if (PlayerPrefs.GetInt("Colecionable_11") == 1)
{
titulo_11.text = "";
contenido_11.text = "";
coleccionble6.GetComponent<Image>().sprite = colec_11;
}
if (PlayerPrefs.GetInt("Colecionable_12") == 1)
{
titulo_12.text = "";
contenido_12.text = "";
coleccionble6.GetComponent<Image>().sprite = colec_12;
}
}
}
|
using UnityEngine;
using System.Collections;
namespace Assets.Scripts
{
public class RoundManager : MonoBehaviour
{
public static int SecondsToStart = 10;
public static int Round = 0;
private bool StartRounds = false;
public Player Player;
public EnemyAI EnemyAI;
public EnemyGenerator EnemyGenerator;
public AudioSource newRoundSFX;
public AudioSource introRemark;
// Use this for initialization
void Start()
{
// give the player 60 seconds to explore before starting the rounds
StartCoroutine(Rounds());
}
// Update is called once per frame
IEnumerator Rounds()
{
while (!Player.IsDead)
{
if (!StartRounds)
{
// give the player 60 seconds to explore before starting the rounds
Debug.Log($"Game is starting, wait {SecondsToStart} seconds...");
introRemark.PlayDelayed(5);
yield return new WaitForSeconds(SecondsToStart);
StartRounds = true;
}
else if (StartRounds && Round == 0)
{
newRoundSFX.Play();
Round = 1;
Debug.Log($"It is now round {Round}");
yield return new WaitForSeconds(5);
EnemyGenerator.spawnLimit = 5;
EnemyGenerator.spawnEnemies = true;
}
else if (StartRounds && EnemyAI.deadEnemyCount == EnemyGenerator.enemyCount && !EnemyGenerator.spawnEnemies)
{
newRoundSFX.Play();
Round += 1;
Debug.Log($"It is now round {Round}");
Debug.Log($"Dead enemy count {EnemyAI.deadEnemyCount}, total enemies allowed is {EnemyGenerator.enemyCount} - going to start a new round");
yield return new WaitForSeconds(5);
EnemyAI.deadEnemyCount = 0;
EnemyGenerator.enemyCount = 0;
EnemyAI.health += 10;
if (EnemyAI.speed < 4.5)
{
Debug.Log($"setting speed from {EnemyAI.speed}");
EnemyAI.speed += 0.20f;
Debug.Log($"to {EnemyAI.speed}");
}
EnemyGenerator.spawnLimit += 5;
EnemyGenerator.spawnEnemies = true;
}
else
{
yield return null;
}
}
Debug.Log("PLAYER IS DEAD!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task1
{
public class NOD
{
#region Public methods
public static int FindNodEuclidean(int first, int second)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
if (first == second)
{
throw new System.ArgumentException("Parameters equals");
}
return FindNod(first,second, EuclideanAlgorithm);
}
public static int FindNodEuclidean(out TimeSpan timer, int first, int second)
{
if(first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
if (first == second)
{
throw new System.ArgumentException("Parameters equals");
}
return FindNod(out timer, first, second, EuclideanAlgorithm);
}
public static int FindNodEuclidean(out TimeSpan timer, int first, int second, int third)
{
if(first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
if (first == second)
{
throw new System.ArgumentException("Parameters equals");
}
return FindNod(out timer, first, second, third, EuclideanAlgorithm);
}
public static int FindNodEuclidean(out TimeSpan timer, params int[] values)
{
return FindNod(out timer, EuclideanAlgorithm, values);
}
public static int FindNodStein(int first, int second)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
return FindNod(first, second, BinaryGcd);
}
public static int FindNodStein(out TimeSpan timer, int first, int second)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
return FindNod(out timer, first, second, BinaryGcd);
}
public static int FindNodStein(out TimeSpan timer, int first, int second, int third)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
return FindNod(out timer, first, second, third, BinaryGcd);
}
public static int FindNodStein(out TimeSpan timer, params int[] values)
{
return FindNod(out timer, BinaryGcd, values);
}
#endregion
private static int FindNod(int first, int second , Func<int, int, int> mode)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
return mode(first, second);
}
private static int FindNod(out TimeSpan timer, int first, int second, Func<int, int, int> mode)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
timer = new TimeSpan();
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int result = mode(first, second);
stopWatch.Stop();
timer = stopWatch.Elapsed;
return result;
}
private static int FindNod(out TimeSpan timer, int first, int second, int third, Func<int, int, int> mode)
{
if (first == 0 && second == 0)
{
throw new System.ArgumentException("All parameters are 0");
}
timer = new TimeSpan();
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int result = mode(mode(first, second), third);
stopWatch.Stop();
timer = stopWatch.Elapsed;
return result;
}
private static int FindNod(out TimeSpan timer, Func<int, int, int> mode, params int[] values)
{
timer = new TimeSpan();
int result = 0;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 1; i < values.Length; i++)
{
result = mode(values[i - 1], values[i]);
}
stopWatch.Stop();
timer = stopWatch.Elapsed;
return result;
}
private static int EuclideanAlgorithm(int first, int second)
{
int max, min;
if (first > second)
{
max = Math.Abs(first);
min=Math.Abs(second);
}
else
{
max = Math.Abs(second);
min = Math.Abs(first);
}
if (min == 0)
{
return max;
}
int residual = 0;
residual = max % min;
if (residual == 0)
{
return min;
}
return EuclideanAlgorithm(min, residual);
}
private static int BinaryGcd(int u, int v)
{
if (u == v)
return u;
if (u == 0)
return v;
if (v == 0)
return u;
if (u % 2 == 0)
{
if (v % 2 == 0)
return 2 * BinaryGcd(u / 2, v / 2);
else
return BinaryGcd(u / 2, v);
}
if (v % 2 == 0)
return BinaryGcd(u, v / 2);
if (u > v)
return BinaryGcd((u - v) / 2, v);
return BinaryGcd(u, (v - u) / 2);
}
}
}
|
// Author(s): Aaron Holloway
// Fall 2018
// Last Modified: 12/2/2018
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Collections.Generic;
// Derived from Summer2018CRCSProject/Assets/ASL/RC/Scripts RCBehavior_TCP.cs
// Allows operation of the RC Car without use of orientation sensor or connection
// to ASL library. Useful for troubleshooting or improving mechanical behaviors.
public class DirectRCControl_TCP : MonoBehaviour
{
// Public
///////////////////////////
public int DriveSpeed = 180;
public int HighDriveSpeed = 255;
public int TurnSpeed = 180;
public int HighTurnSpeed = 255;
public bool HighGear = false;
// Private
///////////////////////////
private const string rcAddress = "172.24.1.1";
private const short rcCPort = 1070;
private const short MAX_MESSAGE_LENGTH = 16;
private TcpClient client;
private IPEndPoint ep;
private NetworkStream sock;
private bool connected;
private bool connectionClosed;
// private Byte[] rBuff;
private Byte[] sBuff;
private short currentCommand;
// private float headingOffset;
// private bool headingDirty;
// private float lastHeading;
// private bool distanceDirty;
void Start() {
connected = false;
connectionClosed = true;
// headingDirty = false;
// distanceDirty = false;
// isMoving = false;
sBuff = new Byte[MAX_MESSAGE_LENGTH];
//rBuff = new Byte[MAX_MESSAGE_LENGTH];
connectRemote();
}
void Update() {
if (connected) {
// if (headingDirty) {
// updateHeading();
// }
//
// if (distanceDirty) {
// updateDistance();
// }
} else {
if (!connectionClosed) {
connectionClosed = true;
print("Closing the TCP connection to the remote control car");
sock.Close();
client.Close();
}
}
}
void connectRemote()
{
client = new TcpClient();
ep = new IPEndPoint(IPAddress.Parse(rcAddress), rcCPort);
client.Connect(ep);
sock = client.GetStream();
connected = true;
connectionClosed = false;
print("TcpClient is connected to the end point with address: " +
rcAddress + " and port: " + rcCPort);
}
///////////////////
// Movement Methods
//
// Notes: Commands are received by sungRover_TCP.py on the RCCar's rPi.
// Each command is comma delimited, while certain commands can have space
// delimited parameters. In the case of movement, two numbers following the
// command indicate the desired speed of the left/right motors, respectively.
///////////////////////////////////////////////////////////////////////////
public void forwardAction() {
string cmd = "F";
if (HighGear) {
cmd += " " + HighDriveSpeed + " " + HighDriveSpeed + ",";
} else {
cmd += " " + DriveSpeed + " " + DriveSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 1;
Debug.Log("Sending Forward command: " + cmd);
sendCommand();
}
public void forwardLeftAction() {
string cmd = "F";
if (HighGear) {
cmd += " " + (HighTurnSpeed / 2) + " " + HighDriveSpeed + ",";
} else {
cmd += " " + (TurnSpeed / 2) + " " + DriveSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 2;
Debug.Log("Sending Forward/Left command: " + cmd);
sendCommand();
}
public void forwardRightAction() {
string cmd = "F";
if (HighGear) {
cmd += " " + HighDriveSpeed + " " + (HighTurnSpeed / 2) + ",";
} else {
cmd += " " + DriveSpeed + " " + (TurnSpeed / 2) + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 3;
Debug.Log("Sending Forward/Right command: " + cmd);
sendCommand();
}
public void backAction() {
string cmd = "B";
if (HighGear) {
cmd += " " + HighDriveSpeed + " " + HighDriveSpeed + ",";
} else {
cmd += " " + DriveSpeed + " " + DriveSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 4;
Debug.Log("Sending Back command: " + cmd);
sendCommand();
}
public void backLeftAction() {
string cmd = "B";
if (HighGear) {
cmd += " " + (HighTurnSpeed / 2) + " " + HighDriveSpeed + ",";
} else {
cmd += " " + (TurnSpeed / 2) + " " + DriveSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 5;
Debug.Log("Sending Back/Left command: " + cmd);
sendCommand();
}
public void backRightAction() {
string cmd = "B";
if (HighGear) {
cmd += " " + HighDriveSpeed + " " + (HighTurnSpeed / 2) + ",";
} else {
cmd += " " + DriveSpeed + " " + (TurnSpeed / 2) + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 6;
Debug.Log("Sending Back/Right command: " + cmd);
sendCommand();
}
public void leftAction() {
string cmd = "L";
if (HighGear) {
cmd += " " + HighTurnSpeed + " " + HighTurnSpeed + ",";
} else {
cmd += " " + TurnSpeed + " " + TurnSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 7;
Debug.Log("Sending Left command: " + cmd);
sendCommand();
}
public void rightAction() {
string cmd = "R";
if (HighGear) {
cmd += " " + HighTurnSpeed + " " + HighTurnSpeed + ",";
} else {
cmd += " " + TurnSpeed + " " + TurnSpeed + ",";
}
sBuff = Encoding.Default.GetBytes(cmd);
currentCommand = 8;
Debug.Log("Sending Right command: " + cmd);
sendCommand();
}
public void stopAction() {
if (currentCommand > 0) {
sBuff = Encoding.ASCII.GetBytes("S,");
currentCommand = 0;
Debug.Log("Sending Stop command: S,");
sendCommand();
}
}
public void exitAction() {
sBuff = Encoding.Default.GetBytes("E,");
Debug.Log("Sending Exit command: E,");
sendCommand();
connected = false;
// headingDirty = false;
}
public void setHighGear() {
if(!HighGear) {
HighGear = true;
renewCurrentCommand();
}
}
public void unsetHighGear() {
if(HighGear) {
HighGear = false;
renewCurrentCommand();
}
}
void renewCurrentCommand() {
switch(currentCommand) {
case 1:
forwardAction();
break;
case 2:
forwardLeftAction();
break;
case 3:
forwardRightAction();
break;
case 4:
backAction();
break;
case 5:
backLeftAction();
break;
case 6:
backRightAction();
break;
case 7:
leftAction();
break;
case 8:
rightAction();
break;
default:
break;
}
}
void sendCommand()
{
if (connected)
{
if (sock.CanWrite)
{
sock.Write(sBuff, 0, sBuff.Length);
}
}
else
{
print("The sendCommand() function cannot write to the socket," +
" because the socket is not connected.");
}
}
// Remnant Methods from RCBehavior_TCP.cs that utilize BMO Orientation
///////////////////////////////////////////////////////////////////////////
// bool updateHeading()
// {
// float heading = getData();
// if (heading != -1)
// {
// // setNewHeading(heading);
// headingDirty = false;
// }
// else
// {
// print("A new heading could not be read from the stream");
// return false;
// }
// return true;
// }
// float getData()
// {
// int headLen = 0;
// string tempS = "";
// int temp = 0;
// while (temp != -1 && (char)temp != 'l')
// {
// temp = sock.ReadByte();
// if ((char)temp != 'l')
// tempS += (char)temp;
// }
// headLen = Int32.Parse(tempS);
// int bRead = 0;
// if (sock.CanRead)
// {
// while (bRead < headLen)
// {
// bRead += sock.Read(rBuff, bRead, headLen);
// }
// return Single.Parse(Encoding.UTF8.GetString(rBuff, 0, bRead));
// }
// else
// return -1;
// }
// void setNewHeading(float target)
// {
// // Quaternion rQ = Quaternion.Euler(0, (target + headingOffset), 0);
// // xform.rotation = rQ;
// lastHeading = target;
// }
// bool updateDistance()
// {
// float dist = getData();
// if (dist != -1)
// {
// // setTranslation(dist);
// distanceDirty = false;
// }
// else
// {
// print("A new distance could not be read from the stream");
// return false;
// }
// return true;
// }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoFrame.Domain.Model;
namespace PhotoFrame.Domain.UseCase
{
public class ChangeKeyword
{
private readonly IKeywordRepository _keywordRepository;
private readonly IPhotoRepository _photoRepository;
public ChangeKeyword(IKeywordRepository keywordRepository, IPhotoRepository photoRepository)
{
_keywordRepository = keywordRepository;
_photoRepository = photoRepository;
}
/// <summary>
/// 引数のフォトの所属アルバムを変更する
/// ※参照渡しなので返り値を保存しなくても書き換わる
/// </summary>
/// <param name="photo"></param>
/// <param name="newAlbumName"></param>
/// <returns></returns>
public Photo Execute(Photo photo, string keywordName)
{
if(keywordName == "")
{
photo.IsAssignedTo(null);
_photoRepository.Store(photo);
}
else
{
var result = _keywordRepository.Find(keywords => keywords.SingleOrDefault(keyword => keyword.Name == keywordName));
if (result != null)
{
photo.IsAssignedTo(result);
_photoRepository.Store(photo);
}
}
return photo;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
namespace BLL.SYSTEM
{
public class FilesBLL
{
DAL.SYSTEM.FilesDAL dal = new DAL.SYSTEM.FilesDAL();
#region 插入数据
/// <summary>
/// 插入数据
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public int Insert(MODEL.SYSTEM.FilesModel model)
{
return dal.Insert(model);
}
#endregion
#region 删除数据
/// <summary>
/// 删除数据
/// </summary>
/// <param name="fileID"></param>
/// <returns></returns>
public int Delete(string fileID)
{
return dal.Delete(fileID);
}
#endregion
#region 得到一个实体
/// <summary>
/// 得到一个实体
/// </summary>
/// <param name="fileID"></param>
/// <returns></returns>
public MODEL.SYSTEM.FilesModel GetModel(string fileID)
{
return (MODEL.SYSTEM.FilesModel)dal.GetModel(fileID);
}
#endregion
#region 更新附件的关链
/// <summary>
/// 更新附件的关链
/// </summary>
/// <param name="moduleType">类型</param>
/// <param name="moduleid">业务外键ID</param>
/// <param name="fileIDs">主键</param>
/// <returns></returns>
public int Update(string moduleType, string moduleid, string fileIDs)
{
if (fileIDs.Trim() == "")
return 0;
return dal.Update(moduleType,moduleid,fileIDs);
}
#endregion
#region 更新路径
public int Update(string FilePath, string FileID)
{
return dal.Update(FilePath, FileID);
}
#endregion
#region 获取 Files 数据集
/// <summary>
/// 获取 Files 数据集
/// </summary>
public DataTable GetDataTable(string moduleType,string moduleID)
{
string sWhere = " ModuleType='" + moduleType + "' and ModuleID in ('"+moduleID+"') ";
return dal.GetDataTable(0, sWhere, "");
}
#endregion
#region 返回附件的所有ID值
/// <summary>
/// 返回附件的所有ID值
/// </summary>
/// <param name="moduleType"></param>
/// <param name="moduleID"></param>
/// <returns></returns>
public string Search(string moduleType, string moduleID)
{
string sWhere = " ModuleType='" + moduleType + "' and ModuleID='" + moduleID + "' ";
return dal.Search(sWhere);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace p527___ConvertsIntToString_Delegate
{
class Program
{
static void Main(string[] args)
{
ConvertsIntToString someMethod;
someMethod = new ConvertsIntToString(helloMethod);
Console.WriteLine( someMethod(5) );
someMethod = new ConvertsIntToString(differentHelloMethod);
Console.WriteLine( someMethod(5) );
}
private static string helloMethod(int i)
{
return "Hi there! #" + (i * 100);
}
private static string differentHelloMethod(int i)
{
return "Ello there! #" + (i * 36);
}
}
}
|
using CheckMySymptoms.Forms.View.Common;
using LogicBuilder.RulesDirector;
using System;
using System.Collections.Generic;
namespace CheckMySymptoms.Forms.View.Input
{
//[JsonConverter(typeof(InputViewConverter))]
public abstract class BaseInputView
{
//LogicBuilder.Forms.Parameters
public int Id { get; set; }
public string VariableName { get; set; }
public abstract string TypeString { get; }
public abstract Type Type { get; }
public abstract object Input { get; }
//Data
public string Text { get; set; }
public string ClassAttribute { get; set; }
public string ToolTipText { get; set; }
public string Placeholder { get; set; }
public string HtmlType { get; set; }
public bool? ReadOnly { get; set; }
public TextFieldTemplateView TextTemplate { get; set; }
public DropDownTemplateView DropDownTemplate { get; set; }
public MultiSelectTemplateView MultiSelectTemplate { get; set; }
public List<DirectiveView> Directives { get; set; }
public FormValidationSettingView ValidationSetting { get; set; }
public FormValidationSettingView UnchangedValidationSetting => ValidationSetting;
private IEnumerable<object> _itemsSource;
public IEnumerable<object> ItemsSource
{
get
{
if (_itemsSource == null)
{
if (this.DropDownTemplate == null)
return null;
//ILookUpsRepository repository = (Application.Current as App).ServiceProvider.GetRequiredService<ILookUpsRepository>();
ILookUpsRepository repository = new LookUpsRepository();
_itemsSource = System.Threading.Tasks.Task.Run(async () => await repository.GetByListId(this.DropDownTemplate.ListId)).Result;
}
return _itemsSource;
}
set { _itemsSource = value; }
}
//Validation
//public string ValidatorFullName { get; set; }
public List<string> Errors { get; set; } = new List<string>();
public bool HasErrors => Errors.Count > 0;
public abstract void Validate(Dictionary<string, Dictionary<string, string>> validationMessages);
public abstract InputResponse GetInputResponse();
public string VariableId => VariableName.Replace('.', '_');
public abstract void UpdateValue(object @value);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InfoPole.Core;
using InfoPole.Core.Entities;
using InfoPole.Core.Services;
namespace InfoPole.Services
{
public class MarkupTagsFileParser : IMarkupTagsFileParser
{
public IEnumerable<MarkupTag> GetAndSaveMarkupTagsFromHeader(string headers, IList<MarkupTag> markupTags, IItemsSaver saver)
{
var values = headers.Split(';');
var result = new List<MarkupTag>();
foreach (var value in values)
{
var mTag = markupTags.FirstOrDefault(mt =>
mt.Name.Equals(value, StringComparison.InvariantCultureIgnoreCase));
if (mTag == null)
{
mTag = saver.SaveItem<MarkupTag>(new MarkupTag() { Name = value });
markupTags.Add(mTag);
}
result.Add(mTag);
}
return result;
}
public IEnumerable<Tag> GetAndSaveTagsFromLine(string line, IEnumerable<MarkupTag> markupTags, IList<Tag> tags, IItemsSaver saver)
{
var values = line.Split(';');
var result =new List<Tag>();
markupTags = markupTags.ToArray();
if (values.Length != markupTags.Count())
{
throw new Exception("Number of values does not equal number of makup tags");
}
for (var i = 0; i < values.Length; i++)
{
if(string.IsNullOrWhiteSpace(values[i].Trim())) continue;
var markupTagId = ((MarkupTag[]) markupTags)[i].Id;
var tag = tags.FirstOrDefault(t => t.Word.Equals(values[i])
&& t.MarkupTagId == markupTagId);
if (tag == null)
{
tag = new Tag()
{
MarkupTagId = markupTagId,
Word = values[i]
};
tag = saver.SaveItem<Tag>(tag);
tags.Add(tag);
}
result.Add(tag);
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FantaCalcioManager.Website.Controllers
{
public class LaMiaSquadraController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult InserisciFormazione()
{
return View();
}
}
} |
using System;
using System.IO;
namespace GreedyDwarf
{
class GreedyDwarf
{
static void Main(string[] args)
{
//Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
int[] valley = ReadValley();
int[][] patterns = ReadPatterns();
int currentPatternCoins = int.MinValue;
int maxCoins = int.MinValue;
for (int i = 0; i < patterns.Length; i++)
{
currentPatternCoins = CalculatePatternCoins(valley, patterns[i]);
if (currentPatternCoins > maxCoins)
{
maxCoins = currentPatternCoins;
}
}
Console.WriteLine(maxCoins);
}
private static int CalculatePatternCoins(int[] valley, int[] pattern)
{
int currentIndex = 0;
int patternIndex = 0;
int coins = 0;
bool[] visited = new bool[valley.Length];
while (true)
{
if (currentIndex >= valley.Length || currentIndex < 0)
{
break;
}
if (visited[currentIndex] == true)
{
break;
}
visited[currentIndex] = true;
coins += valley[currentIndex];
currentIndex += pattern[patternIndex];
patternIndex++;
if (patternIndex == pattern.Length)
{
patternIndex = 0;
}
}
return coins;
}
private static int[] ReadValley()
{
string numbersStr = Console.ReadLine();
string[] numbers = numbersStr.Split(new string[] { ", " }, StringSplitOptions.None);
int[] valley = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
valley[i] = int.Parse(numbers[i]);
}
return valley;
}
private static int[][] ReadPatterns()
{
int patternsNumber = int.Parse(Console.ReadLine());
int[][] patterns = new int[patternsNumber][];
for (int i = 0; i < patternsNumber; i++)
{
string numbersStr = Console.ReadLine();
string[] numbers = numbersStr.Split(new string[] { ", " }, StringSplitOptions.None);
patterns[i] = new int[numbers.Length];
for (int j = 0; j < numbers.Length; j++)
{
patterns[i][j] = int.Parse(numbers[j]);
}
}
return patterns;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdleState : AIState
{
public float idleMin;
public float idleMax;
private float idleTime;
public override void OnEnterState()
{
idleTime = Random.Range(idleMin, idleMax);
StartCoroutine(Idle());
}
public override void OnExitState()
{
StopAllCoroutines();
}
private IEnumerator Idle() {
yield return new WaitForSeconds(idleTime);
controller.ChangeState(controller.patrolState);
}
} |
using System;
using System.Collections.Generic;
using DavisVantage.WeatherReader.Extensions;
namespace DavisVantage.WeatherReader.Models
{
public class CurrentWeather
{
public DateTime UtcTime { get; set; }
public ConsoleInfo ConsoleInfo { get; set; }
public int Barometer { get; set; }
public decimal TempInside { get; set; }
public decimal TempOutside { get; set; }
public int HumidityInside { get; set; }
public int HumidityOutside { get; set; }
public int WindGust { get; set; }
public int Wind10MinutesAvg { get; set; }
public int WindDirection { get; set; }
public List<decimal> ExtraTemperatures { get; set; }
public List<decimal> SoilTemperatures { get; set; }
public List<decimal> LeafTemperatures { get; set; }
public List<int> ExtraHumidities { get; set; }
public List<int> SoilMoistures { get; set; } //in cb
public List<int> LeafWetnesses { get; set; } //scale from 0 - 15
public decimal RainRate { get; set; }
public decimal StormRain { get; set; }
public decimal RainToday { get; set; }
public int Uv { get; set; }
public int SolarRadiation { get; set; } // in watt/meter2
public DateTime SunRise { get; set; }
public DateTime SunSet { get; set; }
public override string ToString()
{
return this.PrintAllProperties();
}
}
}
|
using PlatformRacing3.Server.Core;
using PlatformRacing3.Server.Game.Client;
using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json;
using PlatformRacing3.Server.Game.Communication.Messages.Outgoing;
namespace PlatformRacing3.Server.Game.Communication.Messages.Incoming;
internal class LegacyPingIncomingMessage : MessageIncomingJson<JsonLegacyPingIncomingMessage>
{
internal override void Handle(ClientSession session, JsonLegacyPingIncomingMessage message)
{
session.LastPing.Restart();
session.SendPacket(new LegacyPingOutgoingMessage(message.Time, (ulong)PlatformRacing3Server.Uptime.TotalSeconds));
}
} |
using System;
namespace InstaGramSosa2.Models
{
public class Posts
{
public int PostId { get; set; }
public string PostDate { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CarSelector.Tests.Services
{
using CarSelector.Contracts;
using CarSelector.Model;
using CarSelector.Services;
using CarSelector.Tests.Utils;
using System;
[TestClass]
public class CarEvaluatorServiceTestFixture
{
private RaceTrack _raceTrack;
[TestInitialize]
public void Setup()
{
_raceTrack = new RaceTrack
{
LapDistance = 3, // kilometers
NoOfLapsToComplete = 100,
PitstopTimespan = 30 // Seconds
};
}
[TestMethod]
public void CanEvaluateCarForSingleTrack()
{
CarConfiguration carConfiguration = new CarConfiguration();
carConfiguration.FuelCapacity = 80; // Total Litres of fuel that the car can hold
carConfiguration.TimeToCompleteLap = 300; // Seconds to complete lap
carConfiguration.AverageFuelConsumptionPerLap = 2; // Average fuel consumption per lap in Litres
CarEvaluatorService carEvaluatorService = new CarEvaluatorService();
CarRaceTrackEvaluation carRaceTrackEvaluation = carEvaluatorService.Evaluate(_raceTrack, carConfiguration);
Assert.AreEqual(30060, carRaceTrackEvaluation.CompletionTime);
}
[TestMethod]
public void CanEvaluateMultipleCarsForSingleTrack()
{
CarGenerator carGenerator = new CarGenerator();
CarConfiguration[] carConfigurations = carGenerator.GenerateCarConfigurations(10000);
ICarEvaluatorService carEvaluatorService = new CarEvaluatorService();
CarRaceTrackEvaluation[] carRaceTrackEvaluations =
carEvaluatorService.EvaluateAndSort(_raceTrack, carConfigurations);
for (int i = 0; i < carRaceTrackEvaluations.Length ; i++ )
{
if (i > 0)
{
Assert.IsTrue(carRaceTrackEvaluations[i].CompletionTime >= carRaceTrackEvaluations[i - 1].CompletionTime);
}
}
}
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void WillThrowNullReferenceExceptionIfACarConfigurationIsNullInArray()
{
CarGenerator carGenerator = new CarGenerator();
CarConfiguration[] carConfigurations = carGenerator.GenerateCarConfigurations(100);
carConfigurations[50] = null;
ICarEvaluatorService carEvaluatorService = new CarEvaluatorService();
carEvaluatorService.EvaluateAndSort(_raceTrack, carConfigurations);
}
[TestMethod]
public void EnsureZeroCarValuesAreHandledAndNoExceptionIsThrown()
{
CarConfiguration carConfiguration = new CarConfiguration();
carConfiguration.FuelCapacity = 0;
carConfiguration.TimeToCompleteLap = 0;
carConfiguration.AverageFuelConsumptionPerLap = 0;
ICarEvaluatorService carEvaluatorService = new CarEvaluatorService();
carEvaluatorService.Evaluate(_raceTrack, carConfiguration);
}
[TestMethod]
public void EnsureZeroTrackandCarValuesAreHandledAndNoExceptionIsThrown()
{
RaceTrack raceTrack = new RaceTrack{ LapDistance = 0, NoOfLapsToComplete = 0, PitstopTimespan = 0 };
CarConfiguration carConfiguration = new CarConfiguration();
carConfiguration.FuelCapacity = 0;
carConfiguration.TimeToCompleteLap = 0;
carConfiguration.AverageFuelConsumptionPerLap = 0;
ICarEvaluatorService carEvaluatorService = new CarEvaluatorService();
CarRaceTrackEvaluation carRaceTrackEvaluation = carEvaluatorService.Evaluate(raceTrack, carConfiguration);
Assert.IsNotNull(carRaceTrackEvaluation);
}
[TestMethod]
public void EnsureZeroTrackValuesAreHandledAndNoExceptionIsThrown()
{
RaceTrack raceTrack = new RaceTrack { LapDistance = 0, NoOfLapsToComplete = 0, PitstopTimespan = 0 };
CarConfiguration carConfiguration = new CarConfiguration();
carConfiguration.FuelCapacity = 100;
carConfiguration.TimeToCompleteLap = 400;
carConfiguration.AverageFuelConsumptionPerLap = 7.862;
ICarEvaluatorService carEvaluatorService = new CarEvaluatorService();
CarRaceTrackEvaluation carRaceTrackEvaluation = carEvaluatorService.Evaluate(raceTrack, carConfiguration);
Assert.IsNotNull(carRaceTrackEvaluation);
}
}
}
|
namespace Plus.HabboHotel.Users.Messenger
{
public enum MessengerEventTypes
{
EventStarted,
AchievementUnlocked,
QuestCompleted,
PlayingGame,
FinishedGame,
GameInvite
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApp.Models
{
/// <see cref="https://www.frameip.com/plan-numerotation-telephonique/"/>
public class PhoneNumber : IPhoneNumber
{
private const char SHORT_INTERNATIONAL_PREFIX = '+';
private const string INTERNATIONAL_PREFIX = "00";
private const string REGIONAL_NUMBER = "33";
private const char LOCAL_NUMBER = '0';
private string _number;
public string Label { get; set; }
public string Number { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UIManager : MonoBehaviour {
GameObject[] objects;
void Start() {
Time.timeScale = 1;
objects = GameObject.FindGameObjectsWithTag("hasMovement");
}
void Update() {
if (Input.GetKeyDown(KeyCode.P)) {
pauseControl();
}
}
public void pauseControl() {
if(Time.timeScale == 1) {
Time.timeScale = 0;
pauseObjects();
} else if (Time.timeScale == 0) {
Time.timeScale = 1;
playObjects();
}
}
public void playObjects() {
foreach(GameObject g in objects) {
g.SetActive(true);
}
}
public void pauseObjects() {
foreach(GameObject g in objects) {
g.SetActive(false);
}
}
public void Restart() {
SceneManager.LoadScene("GameStart");
}
public void Reload() {
SceneManager.LoadScene("Game");
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Reserva.Domain.Entities;
namespace Reserva.Infra.Mappings
{
public class FilialMap : IEntityTypeConfiguration<Filial>
{
void IEntityTypeConfiguration<Filial>.Configure(EntityTypeBuilder<Filial> builder)
{
builder.HasKey(k => k.FilialId);
builder.Property(p => p.Nome)
.IsRequired()
.HasMaxLength(100);
builder.Property(p => p.QuantidadeSala);
}
}
}
|
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Hosting;
namespace Umbraco.Examine.Config
{
public sealed class IndexSet : ConfigurationElement
{
[ConfigurationProperty("SetName", IsRequired = true, IsKey = true)]
public string SetName => (string)this["SetName"];
/// <summary>
/// When this property is set, the indexing will only index documents that are descendants of this node.
/// </summary>
[ConfigurationProperty("IndexParentId", IsRequired = false, IsKey = false)]
public int? IndexParentId
{
get
{
if (this["IndexParentId"] == null)
return null;
return (int)this["IndexParentId"];
}
}
/// <summary>
/// The collection of node types to index, if not specified, all node types will be indexed (apart from the ones specified in the ExcludeNodeTypes collection).
/// </summary>
[ConfigurationCollection(typeof(IndexFieldCollection))]
[ConfigurationProperty("IncludeNodeTypes", IsDefaultCollection = false, IsRequired = false)]
public IndexFieldCollection IncludeNodeTypes => (IndexFieldCollection)base["IncludeNodeTypes"];
/// <summary>
/// The collection of node types to not index. If specified, these node types will not be indexed.
/// </summary>
[ConfigurationCollection(typeof(IndexFieldCollection))]
[ConfigurationProperty("ExcludeNodeTypes", IsDefaultCollection = false, IsRequired = false)]
public IndexFieldCollection ExcludeNodeTypes => (IndexFieldCollection)base["ExcludeNodeTypes"];
/// <summary>
/// A collection of user defined umbraco fields to index
/// </summary>
/// <remarks>
/// If this property is not specified, or if it's an empty collection, the default user fields will be all user fields defined in Umbraco
/// </remarks>
[ConfigurationCollection(typeof(IndexFieldCollection))]
[ConfigurationProperty("IndexUserFields", IsDefaultCollection = false, IsRequired = false)]
public IndexFieldCollection IndexUserFields => (IndexFieldCollection)base["IndexUserFields"];
/// <summary>
/// The fields umbraco values that will be indexed. i.e. id, nodeTypeAlias, writer, etc...
/// </summary>
/// <remarks>
/// If this is not specified, or if it's an empty collection, the default optins will be specified:
/// - id
/// - version
/// - parentID
/// - level
/// - writerID
/// - creatorID
/// - nodeType
/// - template
/// - sortOrder
/// - createDate
/// - updateDate
/// - nodeName
/// - urlName
/// - writerName
/// - creatorName
/// - nodeTypeAlias
/// - path
/// </remarks>
[ConfigurationCollection(typeof(IndexFieldCollection))]
[ConfigurationProperty("IndexAttributeFields", IsDefaultCollection = false, IsRequired = false)]
public IndexFieldCollection IndexAttributeFields => (IndexFieldCollection)base["IndexAttributeFields"];
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Attaching this to a gameobject preserves it through scenes and it becomes a singleton.
/// </summary>
public class SingletonObject : MonoBehaviour {
private static SingletonObject instance = null;
public static SingletonObject Instance
{
get
{
return instance;
}
}
void Awake() {
if (instance != null && instance != this)
{
Destroy(this.gameObject);
}
instance = this;
DontDestroyOnLoad(transform.gameObject);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
namespace LuyenTriNho.Controls
{
public partial class MapNumbersToImages : UserControl
{
public MapNumbersToImages()
{
InitializeComponent();
}
public MapNumbersToImages(int numbers, string[] listNumberImage, double imgHeight, double imgWidth, bool isTen)
{
InitializeComponent();
string strNumber = numbers.ToString();
if (isTen == true)
{
if (numbers < 10)
strNumber = "0" + numbers.ToString();
}
int countChar = strNumber.Length;
for (int i = 0; i < strNumber.Length; i++)
{
int num = int.Parse(strNumber.Substring(i, 1));
ExportImage(num, listNumberImage, imgHeight, imgWidth);
}
}
private void ExportImage(int number, string[] listNumberImage, double imgHeight, double imgWidth)
{
Image img = new Image();
switch (number)
{
case 0:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[0].ToString(), UriKind.Relative));
break;
case 1:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[1].ToString(), UriKind.Relative));
break;
case 2:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[2].ToString(), UriKind.Relative));
break;
case 3:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[3].ToString(), UriKind.Relative));
break;
case 4:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[4].ToString(), UriKind.Relative));
break;
case 5:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[5].ToString(), UriKind.Relative));
break;
case 6:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[6].ToString(), UriKind.Relative));
break;
case 7:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[7].ToString(), UriKind.Relative));
break;
case 8:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[8].ToString(), UriKind.Relative));
break;
case 9:
img.Source = new BitmapImage(new Uri("../" + listNumberImage[9].ToString(), UriKind.Relative));
break;
}
img.Height = imgHeight;
img.Width = imgWidth;
spMain.Children.Add(img);
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Web.Models
{
public class CourseSco
{
public int Id { get; set; }
[MaxLength(50)]
public string Title { get; set; }
public int CourseTemplateId { get; set; }
public virtual CourseTemplate CourseTemplate { get; set; }
public int ScoId { get; set; }
public virtual Sco Sco { get; set; }
[MaxLength(10)]
public string CatalogueNumber { get; set; }
public int RequiredScoId { get; set; }
public bool IsFinalExam { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.From_026_To_050
{
public class _027_CommonPrefix
{
/*
* Write a function to find the longest common prefix string amongst an array of strings
*/
// method, go through each string's characters from beginning and compare them, keeep the index of all equal
// until find the first one not same and then return the index.
// Note: unless I under stand this question wrong, there is nothing to write in this question. too simple.
}
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Gui.Controls
{
public class Box : Control
{
public override IEnumerable<Control> Children { get; } = Enumerable.Empty<Control>();
public override Size GetContentSize(IGuiContext context)
{
return new Size(Width, Height);
}
public Color FillColor { get; set; } = Color.White;
public override void Draw(IGuiContext context, IGuiRenderer renderer, float deltaSeconds)
{
base.Draw(context, renderer, deltaSeconds);
renderer.FillRectangle(ContentRectangle, FillColor);
}
}
} |
using System.Linq;
using System.Windows;
using Printer_Status.Printers;
namespace Printer_Status.Helpers
{
/// <summary>
/// Helper class for managing windows.
/// </summary>
public static class WindowHelper
{
/// <summary>
/// Find the first Window of type <typeparamref name="TWindow"/> with the title <paramref name="title"/>
/// </summary>
/// <typeparam name="TWindow">The type of window to find.</typeparam>
/// <param name="title">The title of the window to find.</param>
/// <returns>The window object of the first window if found, otherwise null.</returns>
public static Window FirstWindow<TWindow>(string title = null) where TWindow : Window
{
//Get a list of windows of type TWindow.
var windows = Application.Current.Windows.OfType<TWindow>().ToList();
//If a title was specfified, filter the list to those with that title.
if (!string.IsNullOrEmpty(title)) windows = windows.Where(win => win.Title == title).ToList();
//If there are any windows in the list, return the first window (there should only ever be one).
//Otherwise return null.
return windows.Any() ? windows.First() : null;
}
/// <summary>
/// Focuses an already existing or otherwise new DetailWindow for <paramref name="printer"/>.
/// </summary>
/// <param name="printer">The printer to show a DetailWindow for.</param>
public static void ShowOrFocus(Printer printer)
{
//Get the first window with a DetailWindow-style title.
var window = FirstWindow<DetailWindow>($"{printer.IpAddress} - Printer Details");
//If a window was found, focus it.
if (window != null) window.Focus();
//Otherwise:
else
{
//Create a new DetailWindow for the printer.
window = new DetailWindow(printer);
//Show the window.
window.Show();
}
}
/// <summary>
/// Focuses an already existing or otherwise new <typeparamref name="TWindow"/> with the title <paramref name="title"/>
/// </summary>
/// <typeparam name="TWindow">The type of Window to show.</typeparam>
/// <param name="title">The title of the window to show.</param>
public static void ShowOrFocus<TWindow>(string title = null) where TWindow : Window, new()
{
//Get the first window of this type.
var window = FirstWindow<TWindow>(title);
//If a window was found, focus it.
if (window != null) window.Focus();
//Otherwise:
else
{
//Create a new window of type TWindow.
window = new TWindow();
//Show the window.
window.Show();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public GameObject projector;
public float moveSpeed = 2f;
[HideInInspector]
public Vector3 movement;
[HideInInspector]
public Rigidbody rb;
public LayerMask ground;
// Privates
private Camera cam;
//private Vector3 mousePos;
private Animator animator;
private ClassBase classScript;
private float oldDistance = 0.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
cam = Camera.main;
animator = GetComponentInChildren<Animator>();
classScript = GetComponentInChildren<ClassBase>();
}
void Update()
{
if(classScript.isGuarding == false)
{
movement.x = Input.GetAxis("Horizontal");
movement.y = 0;
movement.z = Input.GetAxis("Vertical");
}
var dist = Mathf.Abs(rb.position.z - Camera.main.transform.position.z);
var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
var distanceBetween = Vector3.Distance(v3Pos, transform.position);
if (movement.x == 0 && movement.z == 0)
{
animator.SetFloat("Velocity", 0f);
animator.SetBool("Moving", false);
}
else
{
// Keep the next line if we're going to make the camera move around
// var dist = Vector3.Distance(Camera.main.transform.position, transform.position);
if (oldDistance < distanceBetween)
{
animator.SetFloat("Animation Speed", -1.0f);
animator.SetFloat("Velocity", 1.0f);
animator.SetBool("Moving", true);
}
else if (oldDistance > distanceBetween)
{
animator.SetFloat("Velocity", 1.0f);
animator.SetBool("Moving", true);
animator.SetFloat("Animation Speed", 1.0f);
}
}
oldDistance = distanceBetween;
playerInput ();
showIndicator ();
}
void playerInput ()
{
if (Input.GetAxis("Fire1") > 0f && classScript.isGuarding == false)
{
StartCoroutine (classScript.normalAttack());
}
if (Input.GetAxis("Fire2") > 0f && !animator.GetCurrentAnimatorStateInfo(0).IsName("Attack1"))
{
classScript.isGuarding = true;
animator.SetFloat("Animation Speed", 0f);
}
else if(Input.GetKeyUp(KeyCode.Mouse1) == false)
{
classScript.isGuarding = false;
animator.SetFloat("Animation Speed", 1f);
}
if (Input.GetKeyDown("e"))
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100.0f))
{
if (hit.transform.gameObject.layer == 8) //ground
{
Vector3 mousePos = hit.point;
StartCoroutine (classScript.specialAttack(mousePos));
}
}
}
if (Input.GetKeyDown("f") && classScript.isGuarding == false)
{
StartCoroutine (classScript.heavyAttack());
}
}
void FixedUpdate()
{
if (!classScript.frozen && !classScript.isGuarding)
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
//Handles character always aiming towards mouse
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100.0f)) {
if (hit.transform.gameObject.layer == 8 || hit.transform.gameObject.layer == 12)
{
Vector3 lookHere = hit.point;
lookHere.y = transform.position.y;
transform.LookAt (lookHere);
}
}
}
public void showIndicator ()
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
LayerMask mask = LayerMask.GetMask("Ground");
//LayerMask mask2 = LayerMask.GetMask("Projectile");
// mask = mask | mask2;
// mask = ~mask;
if (Physics.Raycast (ray, out hit, 100.0f, mask))
{
Vector3 mousePos = hit.point;
mousePos.y += 10;
if (projector != null)
{
projector.SetActive (true);
projector.gameObject.transform.position = mousePos;
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
namespace BlobAndAdlsPerfoamance
{
class Program
{
static DateTime _startTime = DateTime.MinValue;
static DateTime _endTime = DateTime.MaxValue;
static string _baseAddressUri = "http://localhost:64372";
static int count = 5;
static void Main(string[] args)
{
WriteToBlobAsync().GetAwaiter().GetResult();
Console.WriteLine("Completed Blob Write ");
Console.ReadLine();
DummyModel blobContentReceived = ReadFromBlobAsync().GetAwaiter().GetResult();
Console.WriteLine("Completed Blob Read content received is \n " + Encoding.ASCII.GetString(blobContentReceived.Data));
Console.ReadLine();
}
public static async Task WriteToBlobAsync()
{
await WriteContentAsync("api/values/Blob");
}
public static async Task<DummyModel> ReadFromBlobAsync()
{
return await ReadContentAsync("api/values/Blob/1");
}
public static async Task WriteContentAsync(string Url)
{
byte[] bytesFromString = Encoding.ASCII.GetBytes("Hello from Nilesh");
//byte[] bytesFromFile = System.IO.File.ReadAllBytes(@"C:\OffShore\Poc\BlobSample\Nilesh_Photo.JPG");
var client = new HttpClient
{
BaseAddress = new Uri(_baseAddressUri)
};
client.DefaultRequestHeaders.Accept.Clear();
var request = new DummyModel
{
FileName = "From String",
Data = bytesFromString
//Data = bytesFromFile
};
string serializedContent = JsonConvert.SerializeObject(request);
HttpContent latestContent = new StringContent(serializedContent, Encoding.UTF8, "application/json");
_startTime = DateTime.Now;
Console.WriteLine("Starting " + Url + " Write " +_startTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
Task result = client.PostAsync(Url, latestContent);
await result;
}
public static async Task<DummyModel> ReadContentAsync(string Url)
{
var client = new HttpClient
{
BaseAddress = new Uri(_baseAddressUri)
};
client.DefaultRequestHeaders.Accept.Clear();
_startTime = DateTime.Now;
Console.WriteLine("Starting "+Url+" Read " + _startTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
var result = await client.GetAsync(Url);
object x = null;
if (result.IsSuccessStatusCode)
{
x = await result.Content.ReadAsAsync(typeof(DummyModel));
}
return (DummyModel)x;
}
public class DummyModel
{
public byte[] Data { get; set; }
public string FileName { get; set; }
}
static byte[] PrepareContentToWrite()
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using ImageProcessor;
using ImageProcessor.Imaging.Formats;
namespace ImageLibTest
{
public class ImageProcessorLibTester : LibTester
{
public override string LibName => "ImageProcessor";
private Size _size = new Size(Width, Height);
private ISupportedImageFormat _format = new JpegFormat() { Quality = (int)Quality };
public ImageProcessorLibTester()
{
}
public override Result DoSingle(string inputImage)
{
var result = new Result();
var fi = new FileInfo(inputImage);
result.FileName = fi.Name;
result.FileSize = (int)fi.Length;
using (var factory = new ImageFactory())
using (var ms = new MemoryStream(File.ReadAllBytes(inputImage)))
{
var swRead = Stopwatch.StartNew();
factory.Load(ms);
swRead.Stop();
result.ReadTime = swRead.ElapsedMilliseconds;
result.Width = factory.Image.Width;
result.Height = factory.Image.Height;
Console.WriteLine($"{LibName}->{fi.Name}({fi.Length})->ReadTime: {result.ReadTime}ms");
var swResize = Stopwatch.StartNew();
factory.Resize(new Size(Width, Height));
swResize.Stop();
result.ResizeTime = swResize.ElapsedMilliseconds;
Console.WriteLine($"{LibName}->{fi.Name}({fi.Length})->ResizeTime: {result.ResizeTime}ms");
var swWrite = Stopwatch.StartNew();
using (var msout = new MemoryStream())
{
factory.Format(_format).Save(msout);
swWrite.Stop();
result.WriteTime = swWrite.ElapsedMilliseconds;
Console.WriteLine($"{LibName}->{fi.Name}({fi.Length})->WriteTime: {result.WriteTime}ms");
}
}
return result;
}
}
}
|
using CheckMySymptoms.Forms.Parameters.Common;
using LogicBuilder.Attributes;
using LogicBuilder.Forms.Parameters;
using System.Collections.Generic;
namespace CheckMySymptoms.Flow
{
public interface ICustomDialogs
{
[AlsoKnownAs("DisplayHtmlContent")]
[FunctionGroup(FunctionGroup.DialogForm)]
void DisplayHtmlForm
(
[Comments("Configuration details for the form.")]
HtmlPageSettingsParameters setting,
[ListEditorControl(ListControlType.Connectors)]
ICollection<ConnectorParameters> buttons
);
[AlsoKnownAs("DisplaySelectForm")]
[FunctionGroup(FunctionGroup.DialogForm)]
void DisplaySelectForm
(
[Comments("Configuration details for the form.")]
MessageTemplateParameters setting,
[ListEditorControl(ListControlType.Connectors)]
ICollection<ConnectorParameters> buttons
);
[AlsoKnownAs("DisplayFlowComplete")]
[FunctionGroup(FunctionGroup.DialogForm)]
void DisplayFlowComplete
(
[Comments("Configuration details for the form.")]
FlowCompleteParameters setting,
[ListEditorControl(ListControlType.Connectors)]
ICollection<ConnectorParameters> buttons
);
}
}
|
using Promobusque.Aplicacao;
using Promobusque.Dominio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Promobusque.Site
{
public class EmpresaController : Controller
{
private EmpresaAplicacao EmpresaAplicacao;
public EmpresaController()
{
EmpresaAplicacao = new EmpresaAplicacao();
}
public ActionResult Index()
{
return View(new EmpresaModelo());
}
public ActionResult Gravar(EmpresaModelo empresaModelo)
{
if (empresaModelo == null)
throw new Exception("Modelo está nulo!");
try
{
EmpresaAplicacao.Gravar(empresaModelo);
return RedirectToAction("Index");
}
catch (Exception ex)
{
Response.StatusCode = 500;
return Json("Ocorreu um erro: " + ex.Message);
}
}
}
} |
using System;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
namespace StructureAssertions
{
public class AssertAssemblyStructure
{
readonly AssemblyDefinition _assembly;
internal AssertAssemblyStructure(Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException("assembly");
_assembly = AssemblyDefinition.ReadAssembly(assembly.Location);
}
public AssertTypesStructure Types(Func<TypeDefinition, bool> predicate)
{
return new AssertTypesStructure(_assembly, _assembly.MainModule.GetTypes().Where(predicate));
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace eRecruiterRestClient.Tests
{
[TestClass]
public class ErecruiterActionTests
{
public ErecruiterActionTests()
{
}
[TestMethod]
public void check_returned_users_is_not_null()
{
}
}
}
|
#region 版本说明
/*****************************************************************************
*
* 项 目 :
* 作 者 : 李金坪
* 创建时间 : 2014/11/18 13:18:19
*
* Copyright (C) 2008 - 鹏业软件公司
*
*****************************************************************************/
#endregion
/*
<!--布局信息-->
<component id="LayoutInfoServerSvr" type="PengeSoft.CMS.BaseDatum.LayoutInfoServerSvr, PengeSoft.CMS.BaseDatum" service="PengeSoft.CMS.BaseDatum.ILayoutInfoServerSvr, PengeSoft.CMS.BaseDatum" lifestyle="Singleton">
<parameters>
</parameters>
</component>
*/
using System;
using System.Collections;
using System.Text;
using Castle.Windsor;
using PengeSoft.Data;
using PengeSoft.Enterprise.Appication;
using PengeSoft.WorkZoneData;
using PengeSoft.Common.Exceptions;
using PengeSoft.Auther.RightCheck;
using PengeSoft.Service;
using PengeSoft.Service.Auther;
using PengeSoft.Client;
using PengeSoft.Auther;
using IBatisNet.DataAccess;
using PengeSoft.db.IBatis;
using PengeSoft.Common;
using System.Web;
namespace PengeSoft.CMS.BaseDatum
{
/// <summary>
/// LayoutInfoServerSvr实现。
/// </summary>
[PublishName("LayoutInfoServer")]
public class LayoutInfoServerSvr : PengeSoft.Service.Auther.UserAutherImp, ILayoutInfoServerSvr
{
PengeSoft.Service.Auther.IUserAuther auther;
IRightCheck _rightcheck;
protected IDaoManager _daoManager = null;
private ILayoutInfoDao _layoutinfodao;
private IWindsorContainer _container;
#region 服务描述
public override void FormActionList(AppActionList Acts)
{
base.FormActionList(Acts);
// 添加需发布的功能信息
}
public LayoutInfoServerSvr(IRightCheck irig)
{
_rightcheck = irig;
_container = ComponentManager.GetInstance();
auther = RometeClientManager.GetClient("http://118.122.92.139:8989/Service/UserAuther.assx", typeof(PengeSoft.Service.Auther.IUserAuther), 60000) as PengeSoft.Service.Auther.IUserAuther;
_daoManager = ServiceConfig.GetInstance().DaoManager;
_layoutinfodao = (ILayoutInfoDao)_daoManager.GetDao(typeof(ILayoutInfoDao));
}
public override void FormAttribsRec(PengeSoft.WorkZoneData.AppAttribBaseRec attr)
{
base.FormAttribsRec(attr);
attr.Detail = "布局信息";
}
#endregion
#region ILayoutInfoServerSvr 函数
/// <summary>
/// 获取用户布局信息 如无相关布局信息则返回默认布局信息
/// </summary>
/// <param name="UserID">用户id</param>
/// <param name="PageName">页面名称</param>
/// <param name="RoleName">权限等级</param>
[PublishMethod]
public LayoutInfo GetUserLayoutinfo(string uTag, string UserID, string PageName, string RoleName)
{
LayoutInfo result = new LayoutInfo();
LayoutInfoQueryPara para=new LayoutInfoQueryPara();
para.SetOwner(UserID);
para.SetBelongPage (PageName);
para.SetTempType("2");
para.SetIsusing(1);
DataList dlist = _layoutinfodao.QueryList(para, 0,1) ;
if (dlist.Count > 0)
{
result.AssignFrom(dlist[0]);
}
else
{
para = new LayoutInfoQueryPara();
para.SetOwner(RoleName);
para.SetBelongPage(PageName);
para.SetTempType("1");
DataList dlist2 = _layoutinfodao.QueryList(para, 0, 1);
if (dlist2.Count > 0)
{
result.AssignFrom(dlist2[0]);
}
}
return result;
}
[PublishMethod]
public LayoutInfo GetUserLayoutinfobyid(string uTag, int lid)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfo result = new LayoutInfo();
result.LID = lid;
result.AssignFrom(_layoutinfodao.GetDetail(result));
return result;
}
return null;
}
/// <summary>
/// 新增用户布局信息
/// </summary>
/// <param name="UserID">用户id</param>
/// <param name="PageName">页面名称</param>
/// <param name="MLayoutInfo">布局信息</param>
[PublishMethod]
public string AddUserLayoutinf(string uTag, string UserID, string PageName, string MLayoutInfo)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfo nlayoutinfo = new LayoutInfo();
nlayoutinfo.JsonText = MLayoutInfo;
nlayoutinfo.Owner = UserID;
nlayoutinfo.BelongPage = PageName;
nlayoutinfo.Isusing = 1;
_layoutinfodao.Update("upoldinfo", nlayoutinfo);//修改以前的isusing=0;
object result = _layoutinfodao.Insert(nlayoutinfo);
return nlayoutinfo.LID.ToString();
}
return null;
}
/// <summary>
/// 更新用户布局信息
/// </summary>
/// <param name="UserID">用户id</param>
/// <param name="PageName">页面名称</param>
/// <param name="MLayoutInfo">布局信息</param>
[PublishMethod]
public string UpdateUserLayoutinf(string uTag, string UserID, string PageName, string MLayoutInfo)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfo nlayoutinfo = new LayoutInfo();
nlayoutinfo.JsonText = MLayoutInfo;
nlayoutinfo.Owner = UserID;
nlayoutinfo.BelongPage = PageName;
if (nlayoutinfo.LID != 0)
{
return _layoutinfodao.Update(nlayoutinfo).ToString();
}
_layoutinfodao.Update("MyUpdate", nlayoutinfo);
return nlayoutinfo.LID.ToString();
}
return null;
}
/// <summary>
/// 获取布局总数
/// </summary>
/// <param name="uTag"></param>
/// <param name="PageName"></param>
/// <param name="LayType"></param>
/// <param name="uID"></param>
/// <returns></returns>
[PublishMethod]
public int GetLayoutInfoListCount(string uTag, string PageName, string LayType, string uID)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfoQueryPara para = new LayoutInfoQueryPara();
//if (!string.IsNullOrEmpty(uID))
//{
// if (LayType == "1")//布局模板
// {
// para.SetOwner(uID);//改为设定权限
// }
// else
// {
// para.SetOwner(uID);
// }
//}
para.SetLayType(LayType);
para.SetIsusing(1);
if (!string.IsNullOrEmpty(PageName))
{
para.SetBelongPage(PageName);
}
return _layoutinfodao.QueryCount(para);
}
return 0;
}
/// <summary>
/// 删除布局信息
/// </summary>
/// <param name="lid"></param>
[PublishMethod]
public void DelLayputinfo(string uTag,int lid)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfo result = new LayoutInfo();
result.LID = lid;
_layoutinfodao.Delete(result);
}
}
/// <summary>
/// 获取布局模板列表
/// </summary>
/// <param name="PageName">页面名</param>
/// <param name="LayType">模板类型(布局模板或详细模板)</param>
/// <param name="uID">用户id</param>
[PublishMethod]
public LayoutInfoList GetLayoutInfoList(string uTag, string PageName, string LayType, string uID, int currentPage, int PageSize)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
LayoutInfoList result = new LayoutInfoList();
LayoutInfoQueryPara para = new LayoutInfoQueryPara();
//if (!string.IsNullOrEmpty(uID))
//{
// if (LayType == "1")//布局模板
// {
// para.SetOwner(uID);//改为设定权限
// }
// else
// {
// para.SetOwner(uID);
// }
//}
para.SetLayType(LayType);
para.SetIsusing(1);
if (!string.IsNullOrEmpty(PageName))
{
para.SetBelongPage(PageName);
}
int start = 0;
start = (currentPage - 1) * PageSize;
DataList dlist = _layoutinfodao.QueryList(para, start, PageSize);
if (dlist.Count > 0)
{
result.AssignFrom(dlist);
}
return result;
}
return null;
}
#endregion
}
} |
using AlienEngine.Core.Physics;
using AlienEngine.Core.Physics.CollisionShapes;
using AlienEngine.Core.Physics.CollisionShapes.ConvexShapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlienEngine
{
public class BoxCollider : Collider
{
public Vector3f HalfExtends;
public float Margin;
public BoxCollider()
{
HalfExtends = Vector3f.Zero;
Margin = 0;
}
public override ColliderShapes ShapeType
{
get { return ColliderShapes.Box; }
}
public override void Start()
{
ConvexShapeDescription desc = new ConvexShapeDescription
{
CollisionMargin = Margin
};
_shape = new BoxShape(HalfExtends.X, HalfExtends.Y, HalfExtends.Z, desc);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class LayouterStripes : Layouter
{
public float minValue = 0;
public float maxValue = 0;
public int count = 0;
public float delta = 0;
public string mainParameter = "";
public Ensemble ensemble = null;
public float cameraXEndPos = 0;
int camOffset = 0;
int itemOffset = 1;
int itemCount = 6;
float itemSizeX = 0;
float itemSizeY = 0;
float xPosStart = 0;
float yPosStart = 0;
public override Vector3 GetRequiredSpatialDimension()
{
return new Vector3 (0.5f, 1.0f, 0);
}
public override void PlacePreview(int numOfElements)
{
if (GameObject.Find ("Composition Preview") != null)
{
GameObject.DestroyImmediate(GameObject.Find ("Composition Preview"));
}
previewEncapsulateGO = new GameObject("Composition Preview");
itemCount = numOfElements;
Camera cam = Camera.main;
float camSize = cam.orthographicSize;
string[] res = UnityStats.screenRes.Split('x');
float aspect = (float.Parse (res [0]) / float.Parse (res [1]));
if(aspect >= 1)
camSize *= (float.Parse (res [0]) / float.Parse (res [1]));
itemSizeX = ((2f * (camSize - camOffset)) - ((float)itemCount - 1) * itemOffset) / (float)itemCount;
itemSizeY = itemSizeX;
xPosStart = cam.gameObject.transform.position.x - camSize + (float)camOffset + itemSizeX / 2f;
yPosStart = cam.gameObject.transform.position.y;
previewInstanceGO = new GameObject("Instance");
PrimitivesGenerator.Box (previewInstanceGO, itemSizeX, itemSizeY, 0);
previewInstanceGO.transform.parent = previewEncapsulateGO.transform;
for (int i = 0; i < itemCount; i++)
{
GameObject elementGO = GameObject.Instantiate(previewInstanceGO) as GameObject;
elementGO.name = "Instance";
elementGO.transform.parent = previewEncapsulateGO.transform;
elementGO.transform.position = new Vector3(xPosStart + i * (itemSizeX + itemOffset), yPosStart, 5f);
}
elementSize = new Vector3 (itemSizeX, itemSizeY, 0);
GameObject.DestroyImmediate (previewInstanceGO);
}
public override void DestroyGameObjects()
{
if (GameObject.Find ("Composition Preview") != null)
{
GameObject.DestroyImmediate(GameObject.Find ("Composition Preview"));
}
}
public override void SetGUIPreview()
{
GameObject uiGO = GameObject.Find ("UI") as GameObject;
GameObject xPanel = uiGO.transform.Find ("X Axis Panel").gameObject;
GameObject yPanel = uiGO.transform.Find ("Y Axis Panel").gameObject;
GameObject zPanel = uiGO.transform.Find ("Z Axis Panel").gameObject;
xPanel.SetActive(false);
yPanel.SetActive(false);
zPanel.SetActive(false);
return;
}
public override List<RepresentationMesh> PlaceRepresentations (Ensemble ensemble, Abstraction abstraction, GameObject compositionGameObject)
{
List<RepresentationMesh> resultMesh = new List<RepresentationMesh> ();
List<Structure> resultStructures = new List<Structure> ();
this.ensemble = ensemble;
List<KeyValuePair<string, float>> paramsValues = new List<KeyValuePair<string, float>> ();
for (int i = 0; i < axisParameters.Count; i++)
{
paramsValues.Add(new KeyValuePair<string, float>(axisParameters[i].name, axisParameters[i].value));
}
ParameterInfo pi = ensemble.parametersInfo [axisParameters [0].name];
float xDelta = (pi.maxValue - pi.minValue) / (float)(pi.count - 1);
List<float> xDeltas = new List<float> ();
for (float i = pi.minValue; i <= pi.maxValue; i += xDelta)
{
xDeltas.Add(i);
}
if (xDeltas.Count > itemCount)
{
int diffCount = xDeltas.Count - itemCount;
for(int i = 0; i < diffCount; i++)
{
xDeltas.RemoveAt(Random.Range(0, xDeltas.Count - 1));
}
}
foreach (float value in xDeltas)
{
paramsValues[0] = new KeyValuePair<string, float>(paramsValues[0].Key, value);
resultStructures.Add(ensemble.GetStructure(paramsValues));
}
Camera cam = Camera.main;
yPosStart = cam.gameObject.transform.position.y - cam.orthographicSize + (float)camOffset;
int val = 0;
foreach (Structure structure in resultStructures)
{
(structure.representation as RepresentationMesh).gameObject.SetActive(true);
RepresentationMesh newRep = abstraction.Process(structure.representation as RepresentationMesh) as RepresentationMesh;
(structure.representation as RepresentationMesh).gameObject.SetActive(false);
newRep.gameObject.transform.parent = compositionGameObject.transform;
newRep.gameObject.transform.position = new Vector3(xPosStart + val * (itemSizeX + itemOffset) + newRep.offset.x, yPosStart, 0);
val++;
}
GameObject uiGO = GameObject.Find ("UI") as GameObject;
GameObject xPanel = uiGO.transform.Find ("X Axis Panel").gameObject;
GameObject sliderGO = xPanel.transform.Find ("Slider").gameObject;
sliderGO.SetActive (true);
Slider slider = sliderGO.GetComponent<Slider> ();
slider.minValue = pi.minValue;
slider.maxValue = pi.maxValue;
slider.value = pi.minValue;
slider.onValueChanged.RemoveAllListeners ();
slider.onValueChanged.AddListener (CameraPositionChanged);
cameraXEndPos = xPosStart + ((float)resultStructures.Count - 0.5f) * itemSizeX + ((float)resultStructures.Count - 1f) * itemOffset - cam.orthographicSize + camOffset;
cam.transform.position = new Vector3 (0, yPosStart/2f, -300f);
return resultMesh;
}
public void CameraPositionChanged(float value)
{
ParameterInfo pi = ensemble.parametersInfo[axisParameters [0].name];
float normalizedValue = (value - pi.minValue) / (pi.maxValue - pi.minValue);
Vector3 cameraPosition = Camera.main.gameObject.transform.position;
cameraPosition.x = normalizedValue * cameraXEndPos;
Camera.main.gameObject.transform.position = cameraPosition;
}
}
|
using UnityEngine;
using System.Collections;
using Leap;
using System;
public class ComplexPinchDistance : ComplexCondition {
private float minDistance, maxDistance;
public ComplexPinchDistance(float minDistance, float maxDistance)
{
this.minDistance = minDistance;
this.maxDistance = maxDistance;
}
public override bool isSatisfied(Hand hand)
{
return minDistance <= hand.PinchDistance && maxDistance >= hand.PinchDistance;
}
}
|
using System.Collections.Generic;
/// <summary>
/// Windows Presentation Foundation translator namespace
/// </summary>
namespace WPFTranslator
{
/// <summary>
/// Translator interface
/// </summary>
public interface ITranslatorInterface
{
/// <summary>
/// Language
/// </summary>
string Language
{
get;
set;
}
/// <summary>
/// Fallback language
/// </summary>
string FallbackLanguage
{
get;
}
/// <summary>
/// Assembly name
/// </summary>
string AssemblyName
{
get;
}
/// <summary>
/// Languages
/// </summary>
IEnumerable<Language> Languages
{
get;
}
/// <summary>
/// Save settings
/// </summary>
void SaveSettings();
}
}
|
using UnityEngine;
using System.Collections;
// http://answers.unity3d.com/questions/11314/audio-or-music-to-continue-playing-between-scene-c.html
public class DontDestroy : MonoBehaviour {
private static DontDestroy instance = null;
public static DontDestroy Instance {
get {
return instance;
}
}
void Awake() {
if (instance != null && instance != this) {
Destroy(this.gameObject);
return;
} else {
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
}
|
using System;
using System.Runtime.Serialization;
namespace SiDualMode.InputAdapter.TestDataAdapter {
/// <summary>
/// This is the configuration type for the GeneratorFactory. Use instances of this class to configure data
/// and frequency of a generator adapter.
/// </summary>
[DataContract()]
public class TestDataInputConfig {
[DataMember]
public DateTimeOffset StartDateTime { get; set; }
[DataMember]
public TimeSpan RefreshInterval { get; set; }
[DataMember]
public TimeSpan TimestampIncrement { get; set; }
[DataMember]
public int NumberOfItems { get; set; }
[DataMember]
public bool AlwaysUseNow { get; set; }
[DataMember]
public bool EnqueueCtis { get; set; }
public TestDataInputConfig() {
RefreshInterval = TimeSpan.FromMilliseconds(500);
NumberOfItems = 10;
TimestampIncrement = TimeSpan.FromMinutes(5);
StartDateTime = DateTimeOffset.Now.AddMonths(-5);
AlwaysUseNow = false;
EnqueueCtis = true;
}
}
}
|
using FastSQL.Core;
using System;
using System.Collections.Generic;
namespace FastSQL.Magento1
{
public class ProviderOptionManager : BaseOptionManager
{
public override IEnumerable<OptionItem> GetOptionsTemplate()
{
return new List<OptionItem>
{
new OptionItem
{
Name = "api_uri",
DisplayName = "URI",
Type = OptionType.Text
},
new OptionItem
{
Name = "api_user",
DisplayName = "Username",
Type = OptionType.Text
},
new OptionItem
{
Name = "api_key",
DisplayName = "Password",
Type = OptionType.Password
}
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ERP_Palmeiras_RH.Models.Facade;
using ERP_Palmeiras_RH.Models;
namespace ERP_Palmeiras_RH.WebServices
{
/// <summary>
/// Summary description for FuncionariosWS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class FuncionariosWS : System.Web.Services.WebService
{
RecursosHumanos facade = RecursosHumanos.GetInstance();
/// <summary>
/// Busca todas as especialidades.
/// </summary>
/// <returns>Lista de especialidades.</returns>
[WebMethod]
public List<EspecialidadeDTO> BuscarEspecialidades()
{
try
{
IEnumerable<Especialidade> result = facade.BuscarEspecialidades();
List<EspecialidadeDTO> dtos = new List<EspecialidadeDTO>();
if (result != null && result.Count<Especialidade>() > 0)
{
foreach (Especialidade e in result)
{
dtos.Add(new EspecialidadeDTO(e.Nome, e.Id));
}
}
return dtos;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca todos os médicos cadastrados.
/// </summary>
/// <returns>Lista de médicos cadastrados.</returns>
[WebMethod]
public List<MedicoDTO> BuscarMedicos()
{
try
{
IEnumerable<Funcionario> result = facade.BuscarFuncionarios();
List<MedicoDTO> dtos = new List<MedicoDTO>();
if (result != null && result.Count<Funcionario>() > 0)
{
foreach (Funcionario f in result)
{
if (f is Medico)
{
Medico m = (Medico)f;
dtos.Add(new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome));
}
}
}
return dtos;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca um médico pelo seu cpf.
/// </summary>
/// <param name="cpf">Cpf</param>
/// <returns>MedicoDTO ou null.</returns>
[WebMethod]
public MedicoDTO BuscarMedicoPorCpf(long cpf)
{
try
{
Funcionario result = facade.BuscarFuncionario(cpf);
if (result != null)
{
if (result is Medico)
{
Medico m = (Medico)result;
return new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome);
}
}
return null;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca um médico pelo seu cpf.
/// </summary>
/// <param name="medicoId">Id do medico</param>
/// <returns>MedicoDTO ou null.</returns>
[WebMethod]
public MedicoDTO BuscarMedicoPorId(int medicoId)
{
try
{
Funcionario result = facade.BuscarFuncionario(medicoId);
if (result != null)
{
if (result is Medico)
{
Medico m = (Medico)result;
return new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome);
}
}
return null;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca um médico pelo seu Nome.
/// </summary>
/// <param name="medicoNome">Nome do medico</param>
/// <returns>List{MedicoDTO} ou null.</returns>
[WebMethod]
public List<MedicoDTO> BuscarMedicosPorNome(String medicoNome)
{
try
{
IEnumerable<Funcionario> result = facade.BuscarFuncionarios(medicoNome);
List<MedicoDTO> medicos = new List<MedicoDTO>();
if (result != null)
{
foreach (Funcionario funcionario in result)
{
if (funcionario is Medico)
{
Medico m = (Medico)funcionario;
medicos.Add(new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome));
}
}
}
return medicos;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca médicos pela Especialidade.
/// </summary>
/// <param name="especid">Id da Especialidade</param>
/// <returns>List{MedicoDTO}</MedicoDTO> ou null.</returns>
[WebMethod]
public List<MedicoDTO> BuscarMedicosPorEspecialidade(int especId)
{
try
{
IEnumerable<Funcionario> result = facade.BuscarMedicosPorEspec(especId);
List<MedicoDTO> medicos = new List<MedicoDTO>();
if (result != null)
{
foreach (Medico m in result)
{
medicos.Add(new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome));
}
}
return medicos;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Busca um funcionário pelo seu login.
/// </summary>
/// <param name="login">login</param>
/// <returns>FuncionarioDTO, MedicoDTO ou null.</returns>
[WebMethod]
public FuncionarioDTO BuscarFuncionario(String login)
{
try
{
Funcionario result = facade.BuscarFuncionario(login);
if (result != null)
{
if (result is Medico)
{
Medico m = (Medico)result;
return new MedicoDTO(m.Id, m.DadosPessoais.Nome,
m.DadosPessoais.Sobrenome,
m.DadosPessoais.CPF,
m.Credencial.Usuario,
m.Cargo.Nome,
m.CRM,
m.Especialidade.Nome);
}
else
{
return new FuncionarioDTO(result.Id, result.DadosPessoais.Nome,
result.DadosPessoais.Sobrenome,
result.DadosPessoais.CPF,
result.Credencial.Usuario,
result.Cargo.Nome,
false);
}
}
return null;
}
catch (Exception)
{
return null;
}
}
[WebMethod]
public EspecialidadeDTO BuscarEspecialidade(int id)
{
Especialidade e = facade.BuscarEspecialidade(id);
if (e != null)
return new EspecialidadeDTO(e.Nome, e.Id);
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HistoricalDataExport.Entities
{
public class News
{
public int Id { get; set; }
public string PublishDate { get; set; }
public string Classification { get; set; }
/// <summary>
/// 区域经济地区
/// </summary>
public string AreaEconomyRegion { get; set; }
/// <summary>
/// 产业经济行业
/// </summary>
public string IndustrialEconomyVocation { get; set; }
public string Url { get; set; }
/// <summary>
/// 区域经济中国
/// </summary>
public string AreaEconomyChina { get; set; }
/// <summary>
/// 区域经济境外
/// </summary>
public string AreaEconomyOversea { get; set; }
public string Source { get; set; }
public string Author { get; set; }
public string Intro { get; set; }
public string SubTitle { get; set; }
public string Body { get; set; }
public string Tag { get; set; }
public string Title { get; set; }
}
}
|
//
// Copyright 2010, 2015, 2020 Carbonfrost Systems, Inc. (https://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Carbonfrost.Commons.Core.Runtime.Expressions;
namespace Carbonfrost.Commons.PropertyTrees {
static class ExpressionUtility {
private static readonly Regex EXPR_FORMAT = new Regex(
@"
(
(?<DD> \$\$|\$$|\$(?=\s))
| \$ \{ (?<Expression> ([^\}])+ ) (?<ExpEnd> \} | $ )
| \$ (?<Expression> [:a-z0-9_\.]+ )
)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
public static bool TryParse(string text, out Expression result) {
result = null;
if (!text.Contains("$")) {
return false;
}
var matches = EXPR_FORMAT.Matches(text);
var exprs = EnumerateExpressions(matches, text).Where(t => t != null).ToList();
if (exprs.OfType<ErrorExp>().Any()) {
return false;
}
if (exprs.Count == 1) {
result = exprs[0];
} else {
result = Expression.NewArray(exprs);
}
return true;
}
public static Expression LiftToCall(Expression expression, IExpressionContext context) {
return Expression.Call(Expression.Lambda(
expression,
context,
null));
}
private static Expression ParseExprHelper(string expText) {
return Expression.Parse(expText);
}
private static IEnumerable<Expression> EnumerateExpressions(MatchCollection matches, string text) {
int previousIndex = 0;
foreach (Match match in matches) {
yield return Constant(text.Substring(previousIndex, match.Index - previousIndex));
if (match.Groups["DD"].Success) {
yield return Constant("$");
} else {
string expText = match.Groups["Expression"].Value;
if (expText.Length == 0 || string.IsNullOrWhiteSpace(expText)) {
yield return new ErrorExp();
yield break;
}
else if (match.Groups["ExpEnd"].Success && match.Groups["ExpEnd"].Value != "}") {
yield return new ErrorExp();
yield break;
}
else {
Expression exp;
bool success = Expression.TryParse(expText, out exp);
if (!success) {
yield return new ErrorExp();
yield break;
}
yield return exp;
}
}
previousIndex = match.Index + match.Length;
}
yield return Constant(text.Substring(previousIndex, text.Length - previousIndex));
}
class ErrorExp : Expression {
public override ExpressionType ExpressionType {
get {
return (ExpressionType) 0;
}
}
protected override void AcceptVisitor(IExpressionVisitor visitor) {}
protected override TResult AcceptVisitor<TArgument, TResult>(IExpressionVisitor<TArgument, TResult> visitor, TArgument argument) {
return default;
}
protected override TResult AcceptVisitor<TResult>(IExpressionVisitor<TResult> visitor) {
return default;
}
}
static ConstantExpression Constant(string text) {
if (text.Length > 0) {
return Expression.Constant(text);
}
return null;
}
}
}
|
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using HandyControl.Data;
using HandyControl.Tools.Extension;
namespace HandyControlDemo.UserControl
{
/// <summary>
/// 左侧主内容
/// </summary>
public partial class LeftMainContent
{
public LeftMainContent()
{
InitializeComponent();
}
private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count == 0) return;
if (e.AddedItems[0] is TabItem tabItem && tabItem.Content is ListBox listBox)
{
if (listBox.SelectedItem != null)
{
var item = listBox.SelectedItem;
listBox.SelectedIndex = -1;
listBox.SelectedItem = item;
}
}
}
private void ButtonStyleAscending_OnClick(object sender, RoutedEventArgs e)
{
if (ButtonStyleAscending.IsChecked == true)
{
listStyle.Items.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Ascending));
}
else
{
listStyle.Items.SortDescriptions.Clear();
}
}
private void ButtonControlAscending_OnClick(object sender, RoutedEventArgs e)
{
if (ButtonControlAscending.IsChecked == true)
{
listControl.Items.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Ascending));
}
else
{
listControl.Items.SortDescriptions.Clear();
}
}
private void SearchBarStyle_OnSearchStarted(object sender, FunctionEventArgs<string> e)
{
if (e.Info == null) return;
foreach (var listBoxItem in listStyle.Items.OfType<ListBoxItem>())
{
listBoxItem.Show(listBoxItem.Content.ToString().ToLower().Contains(e.Info.ToLower()));
}
}
private void SearchBarControl_OnSearchStarted(object sender, FunctionEventArgs<string> e)
{
if (e.Info == null) return;
foreach (var listBoxItem in listControl.Items.OfType<ListBoxItem>())
{
listBoxItem.Show(listBoxItem.Content.ToString().ToLower().Contains(e.Info.ToLower()));
}
}
}
}
|
using System;
using Foundation;
using UIKit;
namespace JKMIOSApp
{
/// <summary>
/// Controller Name : TearmsConditionViewController
/// Author : Hiren Patel
/// Creation Date : 16 JAN 2018
/// Purpose : To display terms and condition page screen as app shell screen
/// Revision :
/// </summary>
public partial class TearmsConditionViewController : UIViewController
{
public TearmsConditionViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
InitilizeIntarface();
LoadPDFFile();
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
}
/// <summary>
/// Method Name : InitilizeIntarface
/// Author : Hiren Patel
/// Creation Date : 29 Dec 2017
/// Purpose : To Initilizes the intarface.
/// Revision :
/// </summary>
public void InitilizeIntarface()
{
// InitilizeIntarface
btnAlert.TouchUpInside += BtnAlert_TouchUpInside;
btnContactUs.TouchUpInside += BtnContactUs_TouchUpInside;
}
/// <summary>
/// Event Name : BtnContactUs_TouchUpInside
/// Author : Hiren Patel
/// Creation Date : 2 Dec 2017
/// Purpose : To redirect contactus page
/// Revision :
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event Argument</param>
private void BtnContactUs_TouchUpInside(object sender, EventArgs e)
{
PerformSegue("termsToContactus", this);
}
/// <summary>
/// Event Name : BtnAlert_TouchUpInside
/// Author : Hiren Patel
/// Creation Date : 2 Dec 2017
/// Purpose : To redirect notification
/// Revision :
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event Argument</param>
private void BtnAlert_TouchUpInside(object sender, EventArgs e)
{
PerformSegue("termsToNotification", this);
}
/// <summary>
/// Method Name : LoadPDFFile
/// Author : Hiren Patel
/// Creation Date : 20 Feb 2018
/// Purpose : Loads the PDFF ile.
/// Revision :
/// </summary>
private void LoadPDFFile()
{
webViewPDF.Layer.MasksToBounds = true;
webViewPDF.Layer.CornerRadius = 8.0f;
webViewPDF.Layer.BorderWidth = 2;
webViewPDF.Layer.BorderColor = new CoreGraphics.CGColor(0.5f, 0.5f);
webViewPDF.LoadRequest(new NSUrlRequest(new NSUrl(AppConstant.PRIVACY_POLICY_TERMS_DOCUMENT_URL, true)));
webViewPDF.ScalesPageToFit = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ljc.Com.CjzfNews.UI.Entity
{
public class DefaultSettingConfig
{
public bool AutoRun
{
get;
set;
}
private int _maxpopwinnums = 10;
public int MaxPopWinNums
{
get
{
return _maxpopwinnums;
}
set
{
_maxpopwinnums = value;
}
}
private int _captureinterval = 500;
public int CaptureInterval
{
get
{
return _captureinterval;
}
set
{
if (value <= 0)
{
return;
}
_captureinterval = value;
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
namespace BlocksAsTabs.Models.Blocks
{
[ContentType(DisplayName = "TabsBlock", GUID = "42A0899A-032E-4A80-9FF6-B884EDD8AD4B", Description = "")]
public class TabsBlock : BlockData
{
[CultureSpecific]
public virtual ContentArea TabBlocks { get; set; }
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.SfDataGrid;
using Android.Views;
namespace SampleBrowser
{
public class AutoRowHeight:SamplePage
{
SfDataGrid sfGrid;
AutoRowHeightViewModel viewModel;
public override Android.Views.View GetSampleContent (Android.Content.Context context)
{
sfGrid = new SfDataGrid (context);
sfGrid.QueryRowHeight += HandleQueryRowHeightEventHandler;
viewModel = new AutoRowHeightViewModel ();
sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns;
sfGrid.ItemsSource = (viewModel.EmployeeInformation);
return sfGrid;
}
void HandleQueryRowHeightEventHandler (object sender, QueryRowHeightEventArgs e)
{
double height = SfDataGridHelpers.GetRowHeight (sfGrid, e.RowIndex);
if (height > 35) {
e.Height = height;
e.Handled = true;
}
}
void GridAutoGenerateColumns (object sender, AutoGeneratingColumnArgs e)
{
e.Column.LoadUIView = true;
if (e.Column.MappingName == "EmployeeID") {
e.Column.HeaderText = "Employee ID";
e.Column.TextAlignment = GravityFlags.CenterHorizontal;
} else if (e.Column.MappingName == "FirstName") {
e.Column.HeaderText = "First Name";
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "LastName") {
e.Column.HeaderText = "Last Name";
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "Designation") {
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "DateOfBirth") {
e.Column.HeaderText = "Date Of Birth";
e.Column.Format = "d";
e.Column.TextAlignment = GravityFlags.CenterHorizontal;
} else if (e.Column.MappingName == "DateOfJoining") {
e.Column.HeaderText = "Date Of Joining";
e.Column.Format = "d";
e.Column.TextAlignment = GravityFlags.CenterHorizontal;
} else if (e.Column.MappingName == "Address") {
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "City") {
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "PostalCode") {
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "Country") {
e.Column.TextAlignment = GravityFlags.CenterHorizontal;
} else if (e.Column.MappingName == "Telephone") {
e.Column.TextAlignment = GravityFlags.Left;
} else if (e.Column.MappingName == "Qualification") {
e.Column.TextAlignment = GravityFlags.Left;
}
}
public override void Destroy ()
{
this.sfGrid.QueryRowHeight -= HandleQueryRowHeightEventHandler;
sfGrid.Dispose ();
sfGrid = null;
viewModel = null;
}
}
}
|
using MediatR;
using Microsoft.AspNetCore.Identity;
using Publicon.Core.Entities.Concrete;
using Publicon.Core.Entities.Enums;
using Publicon.Core.Exceptions;
using Publicon.Core.Repositories.Abstract;
using Publicon.Infrastructure.Commands.Models.User;
using Publicon.Infrastructure.DTOs;
using Publicon.Infrastructure.Managers.Abstract;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Publicon.Infrastructure.Commands.Handlers.User
{
public class LoginUserHandler : IRequestHandler<LoginUserCommand, TokenDTO>
{
private readonly ICridentialsManager _cridentialsManager;
private readonly IPasswordHasher<Core.Entities.Concrete.User> _passwordHasher;
private readonly IUserRepository _userRepository;
public LoginUserHandler(
ICridentialsManager cridentialsManager,
IPasswordHasher<Core.Entities.Concrete.User> passwordHasher,
IUserRepository userRepository)
{
_cridentialsManager = cridentialsManager;
_passwordHasher = passwordHasher;
_userRepository = userRepository;
}
public async Task<TokenDTO> Handle(LoginUserCommand request, CancellationToken cancellationToken)
{
var user = await _userRepository.GetByEmailAsync(request.Email);
if (user == null)
throw new PubliconException(ErrorCode.UserWithGivenEmailNotExist);
if (!user.IsActive)
throw new PubliconException(ErrorCode.UnverifiedEmail);
var verificationResult = _passwordHasher.VerifyHashedPassword(user, user.HashedPassword, request.Password);
if(verificationResult < PasswordVerificationResult.Success)
throw new PubliconException(ErrorCode.InvalidPassword);
var userRole = Enum.GetName(typeof(UserRole), user.Role);
var tokenDTO = _cridentialsManager.GenerateToken(user.Id, user.Email, userRole, user.GivenName, user.FamilyName);
user.SetRefreshToken(tokenDTO.RefreshToken);
await _userRepository.SaveChangesAsync();
return tokenDTO;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task12
{
class Program
{
static void Main(string[] args)
{
//Implement the ADT stack as auto - resizable array.
//Resize the capacity on demand(when no space is available to add / insert a new element).
Console.WriteLine("Create ADT stack with size 2");
var myStack = new AdtStack<int>(2);
Console.WriteLine("Add 1, 2, 3");
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
Console.WriteLine("ADT stack size now is {0}", myStack.Size);
Console.WriteLine("Stack elements: ");
Console.WriteLine(myStack.Pop());
Console.WriteLine(myStack.Pop());
Console.WriteLine(myStack.Pop());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DietFood.Models.Calculator
{
public class DishParam
{
public int Id { get; set; }
public string Name { get; set; }
public int MealType { get; set; }
public int PossibleWeight { get; set; }
public int MinWeight { get; set; }
public int MaxWeight { get; set; }
public int PossibleMinWeight { get; set; }
public int PossibleMaxWeight { get; set; }
public int ConstWeight { get; set; }
public decimal ProteinsPer100 { get; set; }
public decimal FatsPer100 { get; set; }
public decimal CarbohydratesPer100 { get; set; }
public decimal CaloriesPer100 { get; set; }
public bool IsInterval { get; set; }
public int GetInterval
{
get
{
return MaxWeight - MinWeight;
}
}
public int GetPossibleInterval
{
get
{
return PossibleMaxWeight - PossibleMinWeight;
}
}
}
}
|
namespace syscrawl.Game.Models.Levels
{
public enum NodeType
{
Connector,
Filesystem,
Firewall,
Entrance
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Microsoft.Extensions.Logging;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using System.Threading;
using System.Collections.Concurrent;
using Microsoft.PowerShell.EditorServices.Services.TextDocument;
namespace Microsoft.PowerShell.EditorServices.Services
{
/// <summary>
/// Provides a high-level service for performing semantic analysis
/// of PowerShell scripts.
/// </summary>
public class AnalysisService : IDisposable
{
#region Static fields
/// <summary>
/// Defines the list of Script Analyzer rules to include by default if
/// no settings file is specified.
/// </summary>
private static readonly string[] s_includedRules = {
"PSAvoidAssignmentToAutomaticVariable",
"PSUseToExportFieldsInManifest",
"PSMisleadingBacktick",
"PSAvoidUsingCmdletAliases",
"PSUseApprovedVerbs",
"PSAvoidUsingPlainTextForPassword",
"PSReservedCmdletChar",
"PSReservedParams",
"PSShouldProcess",
"PSMissingModuleManifestField",
"PSAvoidDefaultValueSwitchParameter",
"PSUseDeclaredVarsMoreThanAssignments",
"PSPossibleIncorrectComparisonWithNull",
"PSAvoidDefaultValueForMandatoryParameter",
"PSPossibleIncorrectUsageOfRedirectionOperator"
};
/// <summary>
/// An empty diagnostic result to return when a script fails analysis.
/// </summary>
private static readonly PSObject[] s_emptyDiagnosticResult = new PSObject[0];
private static readonly string[] s_emptyGetRuleResult = new string[0];
private static CancellationTokenSource s_existingRequestCancellation;
/// <summary>
/// The indentation to add when the logger lists errors.
/// </summary>
private static readonly string s_indentJoin = Environment.NewLine + " ";
#endregion // Static fields
#region Private Fields
/// <summary>
/// Maximum number of runspaces we allow to be in use for script analysis.
/// </summary>
private const int NumRunspaces = 1;
/// <summary>
/// Name of the PSScriptAnalyzer module, to be used for PowerShell module interactions.
/// </summary>
private const string PSSA_MODULE_NAME = "PSScriptAnalyzer";
/// <summary>
/// Provides logging.
/// </summary>
private ILogger _logger;
/// <summary>
/// Runspace pool to generate runspaces for script analysis and handle
/// ansynchronous analysis requests.
/// </summary>
private RunspacePool _analysisRunspacePool;
/// <summary>
/// Info object describing the PSScriptAnalyzer module that has been loaded in
/// to provide analysis services.
/// </summary>
private PSModuleInfo _pssaModuleInfo;
private readonly ILanguageServer _languageServer;
private readonly ConfigurationService _configurationService;
private readonly ConcurrentDictionary<string, (SemaphoreSlim, Dictionary<string, MarkerCorrection>)> _mostRecentCorrectionsByFile;
#endregion // Private Fields
#region Properties
/// <summary>
/// Set of PSScriptAnalyzer rules used for analysis.
/// </summary>
public string[] ActiveRules { get; set; }
/// <summary>
/// Gets or sets the path to a settings file (.psd1)
/// containing PSScriptAnalyzer settings.
/// </summary>
public string SettingsPath { get; set; }
#endregion
#region Constructors
/// <summary>
/// Construct a new AnalysisService object.
/// </summary>
/// <param name="analysisRunspacePool">
/// The runspace pool with PSScriptAnalyzer module loaded that will handle
/// analysis tasks.
/// </param>
/// <param name="pssaSettingsPath">
/// The path to the PSScriptAnalyzer settings file to handle analysis settings.
/// </param>
/// <param name="activeRules">An array of rules to be used for analysis.</param>
/// <param name="logger">Maintains logs for the analysis service.</param>
/// <param name="pssaModuleInfo">
/// Optional module info of the loaded PSScriptAnalyzer module. If not provided,
/// the analysis service will populate it, but it can be given here to save time.
/// </param>
private AnalysisService(
RunspacePool analysisRunspacePool,
string pssaSettingsPath,
IEnumerable<string> activeRules,
ILanguageServer languageServer,
ConfigurationService configurationService,
ILogger logger,
PSModuleInfo pssaModuleInfo = null)
{
_analysisRunspacePool = analysisRunspacePool;
SettingsPath = pssaSettingsPath;
ActiveRules = activeRules.ToArray();
_languageServer = languageServer;
_configurationService = configurationService;
_logger = logger;
_pssaModuleInfo = pssaModuleInfo;
_mostRecentCorrectionsByFile = new ConcurrentDictionary<string, (SemaphoreSlim, Dictionary<string, MarkerCorrection>)>();
}
#endregion // constructors
#region Public Methods
/// <summary>
/// Factory method for producing AnalysisService instances. Handles loading of the PSScriptAnalyzer module
/// and runspace pool instantiation before creating the service instance.
/// </summary>
/// <param name="settingsPath">Path to the PSSA settings file to be used for this service instance.</param>
/// <param name="logger">EditorServices logger for logging information.</param>
/// <returns>
/// A new analysis service instance with a freshly imported PSScriptAnalyzer module and runspace pool.
/// Returns null if problems occur. This method should never throw.
/// </returns>
public static AnalysisService Create(ConfigurationService configurationService, ILanguageServer languageServer, ILogger logger)
{
string settingsPath = configurationService.CurrentSettings.ScriptAnalysis.SettingsPath;
try
{
RunspacePool analysisRunspacePool;
PSModuleInfo pssaModuleInfo;
try
{
// Try and load a PSScriptAnalyzer module with the required version
// by looking on the script path. Deep down, this internally runs Get-Module -ListAvailable,
// so we'll use this to check whether such a module exists
analysisRunspacePool = CreatePssaRunspacePool(out pssaModuleInfo);
}
catch (Exception e)
{
throw new AnalysisServiceLoadException("PSScriptAnalyzer runspace pool could not be created", e);
}
if (analysisRunspacePool == null)
{
throw new AnalysisServiceLoadException("PSScriptAnalyzer runspace pool failed to be created");
}
// Having more than one runspace doesn't block code formatting if one
// runspace is occupied for diagnostics
analysisRunspacePool.SetMaxRunspaces(NumRunspaces);
analysisRunspacePool.ThreadOptions = PSThreadOptions.ReuseThread;
analysisRunspacePool.Open();
var analysisService = new AnalysisService(
analysisRunspacePool,
settingsPath,
s_includedRules,
languageServer,
configurationService,
logger,
pssaModuleInfo);
// Log what features are available in PSSA here
analysisService.LogAvailablePssaFeatures();
return analysisService;
}
catch (AnalysisServiceLoadException e)
{
logger.LogWarning("PSScriptAnalyzer cannot be imported, AnalysisService will be disabled", e);
return null;
}
catch (Exception e)
{
logger.LogWarning("AnalysisService could not be started due to an unexpected exception", e);
return null;
}
}
/// <summary>
/// Get PSScriptAnalyzer settings hashtable for PSProvideCommentHelp rule.
/// </summary>
/// <param name="enable">Enable the rule.</param>
/// <param name="exportedOnly">Analyze only exported functions/cmdlets.</param>
/// <param name="blockComment">Use block comment or line comment.</param>
/// <param name="vscodeSnippetCorrection">Return a vscode snipped correction should be returned.</param>
/// <param name="placement">Place comment help at the given location relative to the function definition.</param>
/// <returns>A PSScriptAnalyzer settings hashtable.</returns>
public static Hashtable GetCommentHelpRuleSettings(
bool enable,
bool exportedOnly,
bool blockComment,
bool vscodeSnippetCorrection,
string placement)
{
var settings = new Dictionary<string, Hashtable>();
var ruleSettings = new Hashtable();
ruleSettings.Add("Enable", enable);
ruleSettings.Add("ExportedOnly", exportedOnly);
ruleSettings.Add("BlockComment", blockComment);
ruleSettings.Add("VSCodeSnippetCorrection", vscodeSnippetCorrection);
ruleSettings.Add("Placement", placement);
settings.Add("PSProvideCommentHelp", ruleSettings);
return GetPSSASettingsHashtable(settings);
}
/// <summary>
/// Construct a PSScriptAnalyzer settings hashtable
/// </summary>
/// <param name="ruleSettingsMap">A settings hashtable</param>
/// <returns></returns>
public static Hashtable GetPSSASettingsHashtable(IDictionary<string, Hashtable> ruleSettingsMap)
{
var hashtable = new Hashtable();
var ruleSettingsHashtable = new Hashtable();
hashtable["IncludeRules"] = ruleSettingsMap.Keys.ToArray<object>();
hashtable["Rules"] = ruleSettingsHashtable;
foreach (var kvp in ruleSettingsMap)
{
ruleSettingsHashtable.Add(kvp.Key, kvp.Value);
}
return hashtable;
}
/// <summary>
/// Perform semantic analysis on the given ScriptFile and returns
/// an array of ScriptFileMarkers.
/// </summary>
/// <param name="file">The ScriptFile which will be analyzed for semantic markers.</param>
/// <returns>An array of ScriptFileMarkers containing semantic analysis results.</returns>
public async Task<List<ScriptFileMarker>> GetSemanticMarkersAsync(ScriptFile file)
{
return await GetSemanticMarkersAsync<string>(file, ActiveRules, SettingsPath);
}
/// <summary>
/// Perform semantic analysis on the given ScriptFile with the given settings.
/// </summary>
/// <param name="file">The ScriptFile to be analyzed.</param>
/// <param name="settings">ScriptAnalyzer settings</param>
/// <returns></returns>
public async Task<List<ScriptFileMarker>> GetSemanticMarkersAsync(ScriptFile file, Hashtable settings)
{
return await GetSemanticMarkersAsync<Hashtable>(file, null, settings);
}
/// <summary>
/// Perform semantic analysis on the given script with the given settings.
/// </summary>
/// <param name="scriptContent">The script content to be analyzed.</param>
/// <param name="settings">ScriptAnalyzer settings</param>
/// <returns></returns>
public async Task<List<ScriptFileMarker>> GetSemanticMarkersAsync(
string scriptContent,
Hashtable settings)
{
return await GetSemanticMarkersAsync<Hashtable>(scriptContent, null, settings);
}
/// <summary>
/// Returns a list of builtin-in PSScriptAnalyzer rules
/// </summary>
public IEnumerable<string> GetPSScriptAnalyzerRules()
{
PowerShellResult getRuleResult = InvokePowerShell("Get-ScriptAnalyzerRule");
if (getRuleResult == null)
{
_logger.LogWarning("Get-ScriptAnalyzerRule returned null result");
return s_emptyGetRuleResult;
}
var ruleNames = new List<string>();
foreach (var rule in getRuleResult.Output)
{
ruleNames.Add((string)rule.Members["RuleName"].Value);
}
return ruleNames;
}
/// <summary>
/// Format a given script text with default codeformatting settings.
/// </summary>
/// <param name="scriptDefinition">Script text to be formatted</param>
/// <param name="settings">ScriptAnalyzer settings</param>
/// <param name="rangeList">The range within which formatting should be applied.</param>
/// <returns>The formatted script text.</returns>
public async Task<string> FormatAsync(
string scriptDefinition,
Hashtable settings,
int[] rangeList)
{
// We cannot use Range type therefore this workaround of using -1 default value.
// Invoke-Formatter throws a ParameterBinderValidationException if the ScriptDefinition is an empty string.
if (string.IsNullOrEmpty(scriptDefinition))
{
return null;
}
var argsDict = new Dictionary<string, object> {
{"ScriptDefinition", scriptDefinition},
{"Settings", settings}
};
if (rangeList != null)
{
argsDict.Add("Range", rangeList);
}
PowerShellResult result = await InvokePowerShellAsync("Invoke-Formatter", argsDict);
if (result == null)
{
_logger.LogError("Formatter returned null result");
return null;
}
if (result.HasErrors)
{
var errorBuilder = new StringBuilder().Append(s_indentJoin);
foreach (ErrorRecord err in result.Errors)
{
errorBuilder.Append(err).Append(s_indentJoin);
}
_logger.LogWarning($"Errors found while formatting file: {errorBuilder}");
return null;
}
foreach (PSObject resultObj in result.Output)
{
string formatResult = resultObj?.BaseObject as string;
if (formatResult != null)
{
return formatResult;
}
}
return null;
}
#endregion // public methods
#region Private Methods
private async Task<List<ScriptFileMarker>> GetSemanticMarkersAsync<TSettings>(
ScriptFile file,
string[] rules,
TSettings settings) where TSettings : class
{
if (file.IsAnalysisEnabled)
{
return await GetSemanticMarkersAsync<TSettings>(
file.Contents,
rules,
settings);
}
else
{
// Return an empty marker list
return new List<ScriptFileMarker>();
}
}
private async Task<List<ScriptFileMarker>> GetSemanticMarkersAsync<TSettings>(
string scriptContent,
string[] rules,
TSettings settings) where TSettings : class
{
if ((typeof(TSettings) == typeof(string) || typeof(TSettings) == typeof(Hashtable))
&& (rules != null || settings != null))
{
var scriptFileMarkers = await GetDiagnosticRecordsAsync(scriptContent, rules, settings);
return scriptFileMarkers.Select(ScriptFileMarker.FromDiagnosticRecord).ToList();
}
else
{
// Return an empty marker list
return new List<ScriptFileMarker>();
}
}
/// <summary>
/// Log the features available from the PSScriptAnalyzer module that has been imported
/// for use with the AnalysisService.
/// </summary>
private void LogAvailablePssaFeatures()
{
// Save ourselves some work here
if (!_logger.IsEnabled(LogLevel.Debug))
{
return;
}
// If we already know the module that was imported, save some work
if (_pssaModuleInfo == null)
{
PowerShellResult getModuleResult = InvokePowerShell(
"Get-Module",
new Dictionary<string, object>{ {"Name", PSSA_MODULE_NAME} });
if (getModuleResult == null)
{
throw new AnalysisServiceLoadException("Get-Module call to find PSScriptAnalyzer module failed");
}
_pssaModuleInfo = getModuleResult.Output
.Select(m => m.BaseObject)
.OfType<PSModuleInfo>()
.FirstOrDefault();
}
if (_pssaModuleInfo == null)
{
throw new AnalysisServiceLoadException("Unable to find loaded PSScriptAnalyzer module for logging");
}
var sb = new StringBuilder();
sb.AppendLine("PSScriptAnalyzer successfully imported:");
// Log version
sb.Append(" Version: ");
sb.AppendLine(_pssaModuleInfo.Version.ToString());
// Log exported cmdlets
sb.AppendLine(" Exported Cmdlets:");
foreach (string cmdletName in _pssaModuleInfo.ExportedCmdlets.Keys.OrderBy(name => name))
{
sb.Append(" ");
sb.AppendLine(cmdletName);
}
// Log available rules
sb.AppendLine(" Available Rules:");
foreach (string ruleName in GetPSScriptAnalyzerRules())
{
sb.Append(" ");
sb.AppendLine(ruleName);
}
_logger.LogDebug(sb.ToString());
}
private async Task<PSObject[]> GetDiagnosticRecordsAsync<TSettings>(
string scriptContent,
string[] rules,
TSettings settings) where TSettings : class
{
var diagnosticRecords = s_emptyDiagnosticResult;
// When a new, empty file is created there are by definition no issues.
// Furthermore, if you call Invoke-ScriptAnalyzer with an empty ScriptDefinition
// it will generate a ParameterBindingValidationException.
if (string.IsNullOrEmpty(scriptContent))
{
return diagnosticRecords;
}
if (typeof(TSettings) == typeof(string) || typeof(TSettings) == typeof(Hashtable))
{
//Use a settings file if one is provided, otherwise use the default rule list.
string settingParameter;
object settingArgument;
if (settings != null)
{
settingParameter = "Settings";
settingArgument = settings;
}
else
{
settingParameter = "IncludeRule";
settingArgument = rules;
}
PowerShellResult result = await InvokePowerShellAsync(
"Invoke-ScriptAnalyzer",
new Dictionary<string, object>
{
{ "ScriptDefinition", scriptContent },
{ settingParameter, settingArgument },
// We ignore ParseErrors from PSSA because we already send them when we parse the file.
{ "Severity", new [] { ScriptFileMarkerLevel.Error, ScriptFileMarkerLevel.Information, ScriptFileMarkerLevel.Warning }}
});
diagnosticRecords = result?.Output;
}
_logger.LogDebug(String.Format("Found {0} violations", diagnosticRecords.Count()));
return diagnosticRecords;
}
private PowerShellResult InvokePowerShell(string command, IDictionary<string, object> paramArgMap = null)
{
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.RunspacePool = _analysisRunspacePool;
powerShell.AddCommand(command);
if (paramArgMap != null)
{
foreach (KeyValuePair<string, object> kvp in paramArgMap)
{
powerShell.AddParameter(kvp.Key, kvp.Value);
}
}
PowerShellResult result = null;
try
{
PSObject[] output = powerShell.Invoke().ToArray();
ErrorRecord[] errors = powerShell.Streams.Error.ToArray();
result = new PowerShellResult(output, errors, powerShell.HadErrors);
}
catch (CommandNotFoundException ex)
{
// This exception is possible if the module path loaded
// is wrong even though PSScriptAnalyzer is available as a module
_logger.LogError(ex.Message);
}
catch (CmdletInvocationException ex)
{
// We do not want to crash EditorServices for exceptions caused by cmdlet invocation.
// Two main reasons that cause the exception are:
// * PSCmdlet.WriteOutput being called from another thread than Begin/Process
// * CompositionContainer.ComposeParts complaining that "...Only one batch can be composed at a time"
_logger.LogError(ex.Message);
}
return result;
}
}
private async Task<PowerShellResult> InvokePowerShellAsync(string command, IDictionary<string, object> paramArgMap = null)
{
var task = Task.Run(() =>
{
return InvokePowerShell(command, paramArgMap);
});
return await task;
}
/// <summary>
/// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks.
/// This looks for the latest version of PSScriptAnalyzer on the path and loads that.
/// </summary>
/// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns>
private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo)
{
using (var ps = System.Management.Automation.PowerShell.Create())
{
// Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"`
ps.AddCommand("Get-Module")
.AddParameter("ListAvailable")
.AddParameter("Name", PSSA_MODULE_NAME);
try
{
// Get the latest version of PSScriptAnalyzer we can find
pssaModuleInfo = ps.Invoke()?
.Select(psObj => psObj.BaseObject)
.OfType<PSModuleInfo>()
.OrderByDescending(moduleInfo => moduleInfo.Version)
.FirstOrDefault();
}
catch (Exception e)
{
throw new AnalysisServiceLoadException("Unable to find PSScriptAnalyzer module on the module path", e);
}
if (pssaModuleInfo == null)
{
throw new AnalysisServiceLoadException("Unable to find PSScriptAnalyzer module on the module path");
}
// Create a base session state with PSScriptAnalyzer loaded
InitialSessionState sessionState;
if (Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1") {
sessionState = InitialSessionState.CreateDefault();
} else {
sessionState = InitialSessionState.CreateDefault2();
}
sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase });
// RunspacePool takes care of queuing commands for us so we do not
// need to worry about executing concurrent commands
return RunspaceFactory.CreateRunspacePool(sessionState);
}
}
#endregion //private methods
#region IDisposable Support
private bool _disposedValue = false; // To detect redundant calls
/// <summary>
/// Dispose of this object.
/// </summary>
/// <param name="disposing">True if the method is called by the Dispose method, false if called by the finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
_analysisRunspacePool.Dispose();
_analysisRunspacePool = null;
}
_disposedValue = true;
}
}
/// <summary>
/// Clean up all internal resources and dispose of the analysis service.
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
/// <summary>
/// Wraps the result of an execution of PowerShell to send back through
/// asynchronous calls.
/// </summary>
private class PowerShellResult
{
public PowerShellResult(
PSObject[] output,
ErrorRecord[] errors,
bool hasErrors)
{
Output = output;
Errors = errors;
HasErrors = hasErrors;
}
public PSObject[] Output { get; }
public ErrorRecord[] Errors { get; }
public bool HasErrors { get; }
}
internal async Task RunScriptDiagnosticsAsync(
ScriptFile[] filesToAnalyze)
{
// If there's an existing task, attempt to cancel it
try
{
if (s_existingRequestCancellation != null)
{
// Try to cancel the request
s_existingRequestCancellation.Cancel();
// If cancellation didn't throw an exception,
// clean up the existing token
s_existingRequestCancellation.Dispose();
s_existingRequestCancellation = null;
}
}
catch (Exception e)
{
// TODO: Catch a more specific exception!
_logger.LogError(
string.Format(
"Exception while canceling analysis task:\n\n{0}",
e.ToString()));
TaskCompletionSource<bool> cancelTask = new TaskCompletionSource<bool>();
cancelTask.SetCanceled();
return;
}
// If filesToAnalzye is empty, nothing to do so return early.
if (filesToAnalyze.Length == 0)
{
return;
}
// Create a fresh cancellation token and then start the task.
// We create this on a different TaskScheduler so that we
// don't block the main message loop thread.
// TODO: Is there a better way to do this?
s_existingRequestCancellation = new CancellationTokenSource();
await Task.Factory.StartNew(
() =>
DelayThenInvokeDiagnosticsAsync(
750,
filesToAnalyze,
_configurationService.CurrentSettings.ScriptAnalysis.Enable ?? false,
s_existingRequestCancellation.Token),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
}
private async Task DelayThenInvokeDiagnosticsAsync(
int delayMilliseconds,
ScriptFile[] filesToAnalyze,
bool isScriptAnalysisEnabled,
CancellationToken cancellationToken)
{
// First of all, wait for the desired delay period before
// analyzing the provided list of files
try
{
await Task.Delay(delayMilliseconds, cancellationToken);
}
catch (TaskCanceledException)
{
// If the task is cancelled, exit directly
foreach (var script in filesToAnalyze)
{
PublishScriptDiagnostics(
script,
script.DiagnosticMarkers);
}
return;
}
// If we've made it past the delay period then we don't care
// about the cancellation token anymore. This could happen
// when the user stops typing for long enough that the delay
// period ends but then starts typing while analysis is going
// on. It makes sense to send back the results from the first
// delay period while the second one is ticking away.
// Get the requested files
foreach (ScriptFile scriptFile in filesToAnalyze)
{
List<ScriptFileMarker> semanticMarkers = null;
if (isScriptAnalysisEnabled)
{
semanticMarkers = await GetSemanticMarkersAsync(scriptFile);
}
else
{
// Semantic markers aren't available if the AnalysisService
// isn't available
semanticMarkers = new List<ScriptFileMarker>();
}
scriptFile.DiagnosticMarkers.AddRange(semanticMarkers);
PublishScriptDiagnostics(
scriptFile,
// Concat script analysis errors to any existing parse errors
scriptFile.DiagnosticMarkers);
}
}
internal void ClearMarkers(ScriptFile scriptFile)
{
// send empty diagnostic markers to clear any markers associated with the given file
PublishScriptDiagnostics(
scriptFile,
new List<ScriptFileMarker>());
}
private void PublishScriptDiagnostics(
ScriptFile scriptFile,
List<ScriptFileMarker> markers)
{
var diagnostics = new List<Diagnostic>();
// Create the entry for this file if it does not already exist
SemaphoreSlim fileLock;
Dictionary<string, MarkerCorrection> fileCorrections;
bool newEntryNeeded = false;
if (_mostRecentCorrectionsByFile.TryGetValue(scriptFile.DocumentUri, out (SemaphoreSlim, Dictionary<string, MarkerCorrection>) fileCorrectionsEntry))
{
fileLock = fileCorrectionsEntry.Item1;
fileCorrections = fileCorrectionsEntry.Item2;
}
else
{
fileLock = new SemaphoreSlim(initialCount: 1, maxCount: 1);
fileCorrections = new Dictionary<string, MarkerCorrection>();
newEntryNeeded = true;
}
fileLock.Wait();
try
{
if (newEntryNeeded)
{
// If we create a new entry, we should do it after acquiring the lock we just created
// to ensure a competing thread can never acquire it first and read invalid information from it
_mostRecentCorrectionsByFile[scriptFile.DocumentUri] = (fileLock, fileCorrections);
}
else
{
// Otherwise we need to clear the stale corrections
fileCorrections.Clear();
}
foreach (ScriptFileMarker marker in markers)
{
// Does the marker contain a correction?
Diagnostic markerDiagnostic = GetDiagnosticFromMarker(marker);
if (marker.Correction != null)
{
string diagnosticId = GetUniqueIdFromDiagnostic(markerDiagnostic);
fileCorrections[diagnosticId] = marker.Correction;
}
diagnostics.Add(markerDiagnostic);
}
}
finally
{
fileLock.Release();
}
// Always send syntax and semantic errors. We want to
// make sure no out-of-date markers are being displayed.
_languageServer.Document.PublishDiagnostics(new PublishDiagnosticsParams()
{
Uri = new Uri(scriptFile.DocumentUri),
Diagnostics = new Container<Diagnostic>(diagnostics),
});
}
public async Task<IReadOnlyDictionary<string, MarkerCorrection>> GetMostRecentCodeActionsForFileAsync(string documentUri)
{
if (!_mostRecentCorrectionsByFile.TryGetValue(documentUri, out (SemaphoreSlim fileLock, Dictionary<string, MarkerCorrection> corrections) fileCorrectionsEntry))
{
return null;
}
await fileCorrectionsEntry.fileLock.WaitAsync();
// We must copy the dictionary for thread safety
var corrections = new Dictionary<string, MarkerCorrection>(fileCorrectionsEntry.corrections.Count);
try
{
foreach (KeyValuePair<string, MarkerCorrection> correction in fileCorrectionsEntry.corrections)
{
corrections.Add(correction.Key, correction.Value);
}
return corrections;
}
finally
{
fileCorrectionsEntry.fileLock.Release();
}
}
// Generate a unique id that is used as a key to look up the associated code action (code fix) when
// we receive and process the textDocument/codeAction message.
internal static string GetUniqueIdFromDiagnostic(Diagnostic diagnostic)
{
Position start = diagnostic.Range.Start;
Position end = diagnostic.Range.End;
var sb = new StringBuilder(256)
.Append(diagnostic.Source ?? "?")
.Append("_")
.Append(diagnostic.Code.IsString ? diagnostic.Code.String : diagnostic.Code.Long.ToString())
.Append("_")
.Append(diagnostic.Severity?.ToString() ?? "?")
.Append("_")
.Append(start.Line)
.Append(":")
.Append(start.Character)
.Append("-")
.Append(end.Line)
.Append(":")
.Append(end.Character);
var id = sb.ToString();
return id;
}
private static Diagnostic GetDiagnosticFromMarker(ScriptFileMarker scriptFileMarker)
{
return new Diagnostic
{
Severity = MapDiagnosticSeverity(scriptFileMarker.Level),
Message = scriptFileMarker.Message,
Code = scriptFileMarker.RuleName,
Source = scriptFileMarker.Source,
Range = new Range
{
Start = new Position
{
Line = scriptFileMarker.ScriptRegion.StartLineNumber - 1,
Character = scriptFileMarker.ScriptRegion.StartColumnNumber - 1
},
End = new Position
{
Line = scriptFileMarker.ScriptRegion.EndLineNumber - 1,
Character = scriptFileMarker.ScriptRegion.EndColumnNumber - 1
}
}
};
}
private static DiagnosticSeverity MapDiagnosticSeverity(ScriptFileMarkerLevel markerLevel)
{
switch (markerLevel)
{
case ScriptFileMarkerLevel.Error:
return DiagnosticSeverity.Error;
case ScriptFileMarkerLevel.Warning:
return DiagnosticSeverity.Warning;
case ScriptFileMarkerLevel.Information:
return DiagnosticSeverity.Information;
default:
return DiagnosticSeverity.Error;
}
}
}
/// <summary>
/// Class to catch known failure modes for starting the AnalysisService.
/// </summary>
public class AnalysisServiceLoadException : Exception
{
/// <summary>
/// Instantiate an AnalysisService error based on a simple message.
/// </summary>
/// <param name="message">The message to display to the user detailing the error.</param>
public AnalysisServiceLoadException(string message)
: base(message)
{
}
/// <summary>
/// Instantiate an AnalysisService error based on another error that occurred internally.
/// </summary>
/// <param name="message">The message to display to the user detailing the error.</param>
/// <param name="innerException">The inner exception that occurred to trigger this error.</param>
public AnalysisServiceLoadException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CapstoneProject
{
//
// enum
//
public enum Hair
{
CURLS = 15,
UPDO = 50,
HALFUP = 25,
BUZZED = 10
}
class Program
{
//*****************************************
//
// Title: Capstone Project
// Aplication Type: Console framework
// Description: Quote your event hairstyles
// Author: Chloe Kulanda
// Date Created: 11-27-17
// Last Modified:
//
//******************************************
//
// set up global variables
//
static string userResponse;
static int numberOfPeople;
static int quote;
static int costOfStyle;
static void Main(string[] args)
{
DisplayOpeningScreen();
DisplayMenu();
DisplayClosigScreen();
}
/// <summary>
/// get number of poeple
/// </summary>
static void DisplayNumberOfPeople()
{
DisplayHeader("Number of People");
Console.WriteLine();
Console.Write("Enter number of people: ");
userResponse = Console.ReadLine();
while (!int.TryParse(userResponse, out numberOfPeople))
{
Console.WriteLine();
Console.WriteLine("It appears you did not enter a valid number");
Console.WriteLine("Please Try again");
Console.WriteLine();
Console.Write("Enter number of people: ");
userResponse = Console.ReadLine();
}
}
/// <summary>
/// Select hair style
/// </summary>
static void DisplayHairStyleSelection()
{
Hair hairStyles;
DisplayHeader("Hair Style Selection");
Console.Write("Select your choice of hair style (Curls, Updo, HalfUp, Buzzed): ");
userResponse = Console.ReadLine().ToUpper();
Enum.TryParse<Hair>(userResponse, out hairStyles);
switch (hairStyles)
{
case Hair.CURLS:
costOfStyle = (int)Hair.CURLS;
Console.WriteLine($"You chose {userResponse}");
break;
case Hair.UPDO:
costOfStyle = (int)Hair.UPDO;
Console.WriteLine($"You chose {userResponse}");
break;
case Hair.HALFUP:
costOfStyle = (int)Hair.HALFUP;
Console.WriteLine($"You chose {userResponse}");
break;
case Hair.BUZZED:
costOfStyle = (int)Hair.BUZZED;
Console.WriteLine($"You chose {userResponse}");
break;
default:
Console.WriteLine("Sorry, you chose an invalid option");
break;
}
DisplayContinuePrompt();
}
/// <summary>
/// display calculate & display quote
/// </summary>
static void DisplayQuote()
{
DisplayHeader("Your Quote");
quote = numberOfPeople * costOfStyle;
Console.WriteLine($"Your quote is ${quote}.");
DisplayContinuePrompt();
}
/// <summary>
/// display menu
/// </summary>
static void DisplayMenu()
{
string menuChoice;
bool exiting = false;
while (!exiting)
{
DisplayHeader("Main Menu");
Console.WriteLine("\tA) Select Hair Style");
Console.WriteLine("\tB) Get Number Of People");
Console.WriteLine("\tC) Get Quote");
Console.WriteLine("\tD) Exit");
Console.Write("Enter Choice: ");
menuChoice = Console.ReadLine().ToUpper();
switch (menuChoice)
{
case "A":
DisplayHairStyleSelection();
break;
case "B":
DisplayNumberOfPeople();
break;
case "C":
DisplayQuote();
break;
case "D":
exiting = true;
break;
default:
break;
}
}
}
/// <summary>
/// display opening screen
/// </summary>
static void DisplayOpeningScreen()
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("\t\t\t Capstone Project");
Console.WriteLine();
Console.WriteLine("In this project I will be giving you a quote for how much your hairstyle is");
Console.WriteLine("depending on the hairstyle and how many people.");
DisplayContinuePrompt();
}
/// <summary>
/// display continue prompt
/// </summary>
static void DisplayContinuePrompt()
{
Console.WriteLine();
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
/// <summary>
/// display header
/// </summary>
/// <param name="headerTitle"></param>
static void DisplayHeader(string headerTitle)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("\t\t\t" + headerTitle);
}
/// <summary>
/// display closing screen
/// </summary>
static void DisplayClosigScreen()
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("\t\t\tThank You, have a nice day!");
Console.WriteLine();
Console.WriteLine("press any key to exit.");
Console.ReadKey();
}
}
}
|
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Medit1.Validation;
namespace Medit1.Models.ViewModels
{
public class PortViewModel
{
public int PortId { get; set; }
[Required(ErrorMessage = "Le nom du port est obligatoire")]
[DisplayName("Nom")]
[MinLength(3, ErrorMessage = "Le nom doit contenir 3 caractères ou plus")]
public string Name { get; set; }
//-----------------------------------------------------------------------------
[Required(ErrorMessage = "La latitude est obligatoire")]
[DisplayName("Latitude (séparer avec ',' pour les nombres à virgules)")]
[IsFloating(ErrorMessage = "La latitude ne peut pas contenir des lettres")]
public string Latitude { get; set; }
//-----------------------------------------------------------------------------
[DisplayName("Longitude (séparer avec ',' pour les nombres à virgules)")]
[Required(ErrorMessage = "La longitude est obligatoire")]
[IsFloating(ErrorMessage = "La longitute ne peut pas contenir des lettres")]
public string Longitude { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_RollNewsDetail : System.Web.UI.Page
{
public string t_rand = "";
string newsId = string.Empty;
PDTech.OA.BLL.ROLL_NEWS newsBll = new PDTech.OA.BLL.ROLL_NEWS();
PDTech.OA.BLL.USER_INFO userBll = new PDTech.OA.BLL.USER_INFO();
protected void Page_Load(object sender, EventArgs e)
{
t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff");
newsId = Request.QueryString["news_id"];
//newsId = "4";
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(newsId))
{
ViewData(decimal.Parse(newsId));
}
}
}
private void ViewData(decimal newsId)
{
PDTech.OA.Model.ROLL_NEWS model = newsBll.GetModel(newsId);
if (model != null)
{
lbTitle.Text = model.NEWS_TITLE;
lbCreateTime.Text = model.CREATE_TIME.ToString();
lbCreator.Text = "发布人:" + GetUserName(model.CREATOR.Value);
lbContent.Text = model.NEWS_CONTENT;
}
else
{
lbContent.Text = "新闻已被删除!";
}
}
public string GetUserName(decimal uid)
{
PDTech.OA.Model.USER_INFO user = userBll.GetUserInfo(uid);
return user.FULL_NAME;
}
} |
using System.Collections.Generic;
using TableTopCrucible.Core.Models.ValueTypes.IDs;
namespace TableTopCrucible.Core.Models.Sources
{
public interface IEntityChangeset<Tentity, Tid>
where Tentity : struct, IEntity<Tid>
where Tid : ITypedId
{
Tentity? Origin { get; }
Tentity ToEntity();
Tentity Apply();
IEnumerable<string> GetErrors();
}
}
|
using System.Collections.Generic;
namespace Todo.Core.Entities
{
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
//public List<TaskItem> TodoList { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Sbidu.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Icon = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HomePosters",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<int>(type: "int", maxLength: 50, nullable: false),
Subtitle = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
Text = table.Column<int>(type: "int", maxLength: 300, nullable: false),
Photo = table.Column<int>(type: "int", maxLength: 300, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HomePosters", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Email = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Text = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Teams",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Fullname = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Facebook = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Instagram = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Twitter = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
Photo = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teams", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AuctionProducts",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
About = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: false),
CategoryId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AuctionProducts", x => x.Id);
table.ForeignKey(
name: "FK_AuctionProducts_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AuctionProductGalleries",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Photo = table.Column<string>(type: "nvarchar(max)", nullable: true),
AuctionProductId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AuctionProductGalleries", x => x.Id);
table.ForeignKey(
name: "FK_AuctionProductGalleries_AuctionProducts_AuctionProductId",
column: x => x.AuctionProductId,
principalTable: "AuctionProducts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AuctionProductGalleries_AuctionProductId",
table: "AuctionProductGalleries",
column: "AuctionProductId");
migrationBuilder.CreateIndex(
name: "IX_AuctionProducts_CategoryId",
table: "AuctionProducts",
column: "CategoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AuctionProductGalleries");
migrationBuilder.DropTable(
name: "HomePosters");
migrationBuilder.DropTable(
name: "Messages");
migrationBuilder.DropTable(
name: "Teams");
migrationBuilder.DropTable(
name: "AuctionProducts");
migrationBuilder.DropTable(
name: "Categories");
}
}
}
|
using AssetHub.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AssetHub.ViewModels.Account.Partial
{
public class ChangePasswordViewModel
{
public string Id { get; set; }
[Required(ErrorMessage = User.Validator.USERNAME_REQUIRED)]
public string Username { get; set; }
[Display(Name = "Old password")]
[Required(ErrorMessage = User.Validator.PASSWORD_REQUIRED)]
public string OldPassword { get; set; }
[Display(Name = "New password")]
[RegularExpression(User.Validator.PASSWORD_REGEX, ErrorMessage = User.Validator.INVALID_PASSWORD)]
public string NewPassword { get; set; }
[Display(Name = "Confirm passwod")]
[RegularExpression(User.Validator.PASSWORD_REGEX, ErrorMessage = User.Validator.INVALID_PASSWORD)]
public string ConfirmPassword { get; set; }
}
} |
using GamesInfo.API.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GamesInfo.API.Services
{
public class GameInfoFileRepository : IGameInfoRepository
{
public Task Create(Game game)
{
throw new NotImplementedException();
}
public Task<bool> Delete(string Key)
{
throw new NotImplementedException();
}
public Task<bool> DeleteBulk(List<string> keys)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Game>> GetAllGames()
{
throw new NotImplementedException();
}
public Task<Game> GetGame(string Key)
{
throw new NotImplementedException();
}
public Task<bool> Update(Game game)
{
throw new NotImplementedException();
}
}
};
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GUIPlayer : MonoBehaviour {
public GameObject Player;
public Canvas GUIP;
public Text Lvl;
public Text PAtk;
public Text AtkSpeed;
public Text Speed;
public Text Armor;
public Text Gold;
public Text Exp;
public Text HP;
// Use this for initialization
void Start () {
GUIP.enabled = false;
}
// Update is called once per frame
void Update () {
GUIOn ();
Statistic ();
}
void GUIOn()
{
if (Player.transform.Find ("TargetMark").GetComponent<Renderer> ().enabled == true) {
GUIP.enabled = true;
}
else
{
GUIP.enabled = false;
}
}
// Активация, дезактивация GUI игрока.
void Statistic()
{
Lvl.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().Lvl;
PAtk.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().PAttack;
AtkSpeed.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().AtkSpeed;
Speed.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().speed;
Armor.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().Armor;
Gold.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().Gold;
Exp.GetComponent<Text>().text = " " + Player.GetComponent<MovePlayer> ().Exp;
HP.GetComponent<Text>().text = "HP: " + (int)Player.GetComponent<MovePlayer>().Health;
}
// Вывод статистики на экран.
}
|
using Mirror;
using MobileFPS.PlayerHealth;
using MobileFPS.PlayerWeapon;
using UnityEngine;
using UnityEngine.UI;
namespace MobileFPS.PlayerUI
{
public class PlayerUIManager : NetworkBehaviour
{
GameManager _gameManager;
Health _playerHealth;
WeaponController _weaponController;
Image _healthBar;
void Awake()
{
_gameManager = GameObject.Find( "GameManager" ).GetComponent<GameManager>();
_healthBar = _gameManager.HealthBar;
}
void Update()
{
if ( !hasAuthority ) return;
UpdatePlayerAmmo();
UpdatePlayerHealth();
HealthBar();
}
public override void OnStartAuthority()
{
_weaponController = GetComponent<WeaponController>();
_playerHealth = GetComponent<Health>();
OpenUI();
PlayerAliveUI();
}
void HealthBar()
{
_healthBar.fillAmount = (float)_playerHealth.CurrentHealth / (float)_playerHealth.MaxHealth;
}
public void PlayerDead()
{
_gameManager._deadUI.SetActive( true );
_gameManager._aliveUI.SetActive( false );
}
void PlayerAliveUI()
{
_gameManager._deadUI.SetActive( false );
_gameManager._aliveUI.SetActive( true );
}
void UpdatePlayerAmmo()
{
var currentWeapon = _weaponController.CurrentWeapon;
_gameManager.Ammo.text = currentWeapon.CurrentAmmo + "/" + currentWeapon.AllAmmo;
}
void UpdatePlayerHealth()
{
var currentHealth = _playerHealth;
_gameManager.Health.text = currentHealth.CurrentHealth.ToString();
}
void OpenUI()
{
enabled = true;
_gameManager._canvas.gameObject.SetActive( true );
}
}
}
|
using DG.Tweening;
using UniRx;
using UnityEngine;
public class ProgressProp : MonoBehaviour
{
[SerializeField] private SomewhatFancierExample1 _source;
[SerializeField] private float _min;
[SerializeField] private float _max;
private void Start()
{
_source.PumaProgress
.Select(p => p >= _min && p <= _max)
.DistinctUntilChanged()
.Select(i => i ? 1f : 0f)
.Subscribe(s =>
{
DOTween.Complete(this);
transform.DOScale(s, 2f)
.SetEase(Ease.OutElastic)
.SetId(this);
transform.DOShakeRotation(2f, new Vector3(0, 0, 45f), 8, 45)
.SetId(this);
})
.AddTo(this);
}
} |
namespace RankingsTable.EF
{
using Microsoft.Data.Entity;
using RankingsTable.EF.Entities;
public interface IRankingsTableDbContext
{
DbSet<Player> Players { get; }
DbSet<Season> Seasons { get; }
int SaveChanges();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.