text stringlengths 13 6.01M |
|---|
// <copyright file="CoreEventHandlers.cs" company="Firoozeh Technology LTD">
// Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using FiroozehGameService.Models.GSLive.Command;
using FiroozehGameService.Models.Internal;
/**
* @author Alireza Ghodrati
*/
namespace FiroozehGameService.Handlers
{
/// <summary>
/// Represents CoreEventHandlers In MultiPlayer System
/// </summary>
public class CoreEventHandlers
{
internal static EventHandler<StartPayload> GsLiveSystemStarted;
internal static EventHandler<DisposeData> Dispose;
/// <summary>
/// Calls When Your Game Successfully Connected To GameService
/// </summary>
public static EventHandler SuccessfullyLogined;
/// <summary>
/// Calls When An New Error Received From Server
/// </summary>
public static EventHandler<ErrorEvent> Error;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace EasyDev.Applications.SQMS
{
public interface IPortalPartService
{
DataSet GetPortalPartData();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MonsterLove.StateMachine;
public class GameManager : Singleton<GameManager> {
// 双方初始血量
public int initialHP = 10;
public Player WangWang;
public Player XianYu;
[SerializeField]
private GameObject SoundBarLeft;
[SerializeField]
private GameObject SoundBarRight;
[SerializeField]
private Wind wind;
public float recordTime = 3f;
public float waitTime = 3f;
public void StartGame()
{
fsm.ChangeState(States.Left);
WangWang.HP = initialHP;
XianYu.HP = initialHP;
}
public void ExitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
public void CheckRoundEnd()
{
if (WangWang.HP <= 0 || XianYu.HP <= 0)
{
fsm.ChangeState(States.End);
}
else
{
if (fsm.State == States.Left)
{
fsm.ChangeState(States.Right);
}
else if (fsm.State == States.Right)
{
fsm.ChangeState(States.Left);
}
}
}
private void ChangeWindDirection()
{
float angle = Random.Range(0f, 360f);
wind.SetWindDirection(angle);
}
public enum States
{
Init,
Left,
Right,
End
}
StateMachine<States> fsm;
void Start()
{
fsm = StateMachine<States>.Initialize(this);
fsm.ChangeState(States.Init);
}
void Init_Exit()
{
UIManager.instance.startUI.SetActive(false);
UIManager.instance.playingUI.SetActive(true);
}
void Left_Enter()
{
ChangeWindDirection();
UIManager.instance.recordButtonLeft.SetActive(true);
/*yield return new WaitForSeconds(prepareTime);
SoundBarLeft.SetActive(true);
yield return new WaitForSeconds(speakTime);
float result = 0;
for (int i = 0; i < 5; ++i)
{
result += SoundDetect.instance.currentVolume;
yield return null;
}
result = result / 5;
SoundBarLeft.SetActive(false);
Throw.instance.ThrowStuff(result, Player.Left);
yield return new WaitForSeconds(waitTime);
if (playerLeftHP <= 0 || playerRightHP <= 0)
{
fsm.ChangeState(States.End);
}
else
{
fsm.ChangeState(States.Right);
}*/
}
void Left_Exit()
{
UIManager.instance.recordButtonLeft.SetActive(false);
}
void Right_Enter()
{
ChangeWindDirection();
UIManager.instance.recordButtonRight.SetActive(true);
/*yield return new WaitForSeconds(prepareTime);
SoundBarRight.SetActive(true);
yield return new WaitForSeconds(speakTime);
float result = 0;
for (int i = 0; i < 5; ++i)
{
result += SoundDetect.instance.currentVolume;
yield return null;
}
result = result / 5;
SoundBarRight.SetActive(false);
Throw.instance.ThrowStuff(result, Player.Right);
yield return new WaitForSeconds(waitTime);
if (playerLeftHP <= 0 || playerRightHP <= 0)
{
fsm.ChangeState(States.End);
}
else
{
fsm.ChangeState(States.Left);
}*/
}
void Right_Exit()
{
UIManager.instance.recordButtonRight.SetActive(false);
}
void End_Enter()
{
UIManager.instance.playingUI.SetActive(false);
UIManager.instance.endUI.SetActive(true);
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class InventoryItem : MonoBehaviour {
public Text count;
public string itemName;
public Image image;
public int itemCount;
public GameObject prefab;
public GameManager gameManager;
public PlacementArea placementArea;
public Text txtTitle;
public void Init(int itemCount)
{
this.itemCount = itemCount;
txtTitle.text = this.itemName;
UpdateCount(0);
}
public void UpdateCount(int difference)
{
itemCount += difference;
count.text = itemCount.ToString();
}
public void Select(){
if (gameManager.selectedItem == this) {
gameManager.CancelItemSelection();
}
else if (itemCount < 1)
{
// play sound?
}
else {
gameManager.SelectInventoryItem(this);
}
//{
//UpdateCount(-1);
//};
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using System.Collections.Generic;
using System.Xml.Serialization;
namespace KartLib.Views.AlcoDeclModel
{
public class Справочники12
{
[XmlElement("ПроизводителиИмпортеры")]
public List<ПроизводителиИмпортеры12> ПроизводителиИмпортеры12;
[XmlElement("Поставщики")] public List<Поставщики12> Поставщики12;
}
public class ПроизводителиИмпортеры12
{
[XmlElement("ЮЛ")] public ЮЛ12 ЮЛ12;
[XmlAttribute]
public string ИДПроизвИмп { get; set; }
[XmlAttribute]
public string П000000000004 { get; set; }
}
public class ЮЛ12
{
[XmlAttribute]
public string П000000000005 { get; set; }
[XmlAttribute]
public string П000000000006 { get; set; }
}
public class Поставщики12
{
public ЮЛ ЮЛ;
[XmlAttribute]
public string ИдПостав { get; set; }
[XmlAttribute]
public string П000000000007 { get; set; }
}
public class Документ12
{
[XmlElement("Организация")]
public Организация12 Организация12;
[XmlElement("ОбъемОборота")] public ОбъемОборота12 ОбъемОборота12;
}
public class Организация12
{
[XmlElement("Реквизиты")]
public Реквизиты12 Реквизиты12;
public ОтветЛицо ОтветЛицо;
}
public class Реквизиты12
{
[XmlAttribute]
public string НаимОрг { get; set; }
[XmlAttribute]
public string ТелОрг { get; set; }
[XmlAttribute]
public string EmailОтпр { get; set; }
public АдрОрг АдрОрг;
[XmlElement("ЮЛ")]
public ЮЛОрг ЮЛОрг;
}
public class ЮЛОрг
{
[XmlAttribute]
public string ИННЮЛ { get; set; }
[XmlAttribute]
public string КППЮЛ { get; set; }
}
public class ОбъемОборота12
{
[XmlAttribute]
public string НаимЮЛ { get; set; }
[XmlAttribute]
public string КППЮЛ { get; set; }
[XmlAttribute]
public string НаличиеОборота { get; set; }
public АдрОрг АдрОрг;
[XmlElement("Оборот")]
public List<Оборот12> Оборот12;
}
public class Оборот12
{
[XmlElement("СведПроизвИмпорт")] public List<СведПроизвИмпорт12> СведПроизвИмпорт12;
[XmlAttribute]
public string ПN { get; set; }
[XmlAttribute]
public string П000000000003 { get; set; }
}
public class СведПроизвИмпорт12
{
[XmlAttribute]
public string ПN { get; set; }
[XmlAttribute]
public string ИдПроизвИмп { get; set; }
[XmlElement("Поставщик")]
public List<Поставщик12> Поставщик12;
[XmlElement("Движение")] public List<Движение12> Движение12;
}
public class Поставщик12
{
[XmlAttribute]
public string ПN { get; set; }
[XmlAttribute]
public string ИдПоставщика { get; set; }
[XmlElement("Продукция")] public List<Продукция> Продукция;
}
public class Движение12
{
[XmlAttribute]
public string ПN { get; set; }
[XmlAttribute]
public string П100000000006 { get; set; }
[XmlAttribute]
public string П100000000007 { get; set; }
[XmlAttribute]
public string П100000000008 { get; set; }
[XmlAttribute]
public string П100000000009 { get; set; }
[XmlAttribute]
public string П100000000010 { get; set; }
[XmlAttribute]
public string П100000000011 { get; set; }
[XmlAttribute]
public string П100000000012 { get; set; }
[XmlAttribute]
public string П100000000013 { get; set; }
[XmlAttribute]
public string П100000000014 { get; set; }
[XmlAttribute]
public string П100000000015 { get; set; }
[XmlAttribute]
public string П100000000016 { get; set; }
[XmlAttribute]
public string П100000000017 { get; set; }
[XmlAttribute]
public string П100000000018 { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Parking_Lot_Project
{
class Admin
{
#region singleton Admin
public static volatile Admin instance;
static object key = new object();
public static Admin Instance
{
get
{
if (instance == null)
{
lock (key)
{
instance = new Admin();
}
}
return instance;
}
}
#endregion
public static string userID { get; private set; }
public static string userAccess { get; private set; }
public static string IdWork { get; private set; }
public static void getIdWork(string id)
{
IdWork = id;
}
public static void getuserID (string user, string access)
{
userID = user;
userAccess = access;
}
public DataTable login (string username, string pass)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM ADMIN WHERE USERNAME= @USER AND PASS = @PASS",Database.Instance.getConnection);
cmd.Parameters.Add("@USER", SqlDbType.VarChar).Value = username;
cmd.Parameters.Add("@PASS", SqlDbType.VarChar).Value = pass;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
public bool editAdmin (string pass)
{
SqlCommand cmd = new SqlCommand("UPDATE ADMIN SET PASS = @PASS WHERE ID = @ID", Database.Instance.getConnection);
cmd.Parameters.Add("@PASS", SqlDbType.VarChar).Value = pass;
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = Admin.userID;
Database.Instance.openConnect();
if (cmd.ExecuteNonQuery() == 1)
{
Database.Instance.closeConnection();
return true;
}
Database.Instance.closeConnection();
return false;
}
public bool insertAdmin (string fullName, string userName, string passWord, string access, MemoryStream pic)
{
string id;
SqlCommand cmd = new SqlCommand("SELECT * FROM ADMIN WHERE USERNAME = @USER AND PASS = @PASS", Database.Instance.getConnection);
cmd.Parameters.Add("@USER", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("@PASS", SqlDbType.VarChar).Value = passWord;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable table = new DataTable();
adapter.Fill(table);
if (table.Rows.Count == 1)
{
MessageBox.Show("Tài khoản đã tồn tại", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
SqlCommand cd = new SqlCommand("SELECT * FROM ADMIN", Database.Instance.getConnection);
SqlDataAdapter ap = new SqlDataAdapter();
ap.SelectCommand = cd;
DataTable tb = new DataTable();
ap.Fill(tb);
if (tb.Rows.Count == 0)
id = "1";
else
{
int count = 1;
for (int i = 0; i < tb.Rows.Count; ++i)
{
if (count != int.Parse(tb.Rows[i][0].ToString()))
break;
++count;
}
id = count.ToString();
}
SqlCommand command = new SqlCommand("INSERT INTO ADMIN VALUES (@ID, @NAME, @USERNAME, @PASS, @ACCESS, @IMG)", Database.Instance.getConnection);
command.Parameters.Add("ID", SqlDbType.VarChar).Value = id;
command.Parameters.Add("@NAME", SqlDbType.NVarChar).Value = fullName;
command.Parameters.Add("@USERNAME", SqlDbType.VarChar).Value = userName;
command.Parameters.Add("@PASS", SqlDbType.VarChar).Value = passWord;
command.Parameters.Add("@ACCESS", SqlDbType.VarChar).Value = access;
command.Parameters.Add("@IMG", SqlDbType.Image).Value = pic.ToArray();
Database.Instance.openConnect();
if (command.ExecuteNonQuery() == 1)
{
Database.Instance.closeConnection();
return true;
}
else
{
Database.Instance.closeConnection();
return false;
}
}
public bool deleteAdmin (string id)
{
SqlCommand cmd = new SqlCommand("DELETE ADMIN WHERE ID = @ID", Database.Instance.getConnection);
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = id;
Database.Instance.openConnect();
if (cmd.ExecuteNonQuery() == 1)
{
Database.Instance.closeConnection();
return true;
}
else
{
Database.Instance.closeConnection();
return false;
}
}
public string[] getName (string fullName)
{
string[] name = new string[2];
string fName = "";
string lName = "";
int count = fullName.Length - 1;
while (count >= 0)
{
if (fullName[count] == ' ')
break;
--count;
}
for (int i = 0; i < count; ++i)
fName += fullName[i];
for (int i = count + 1; i < fullName.Length; ++i)
lName += fullName[i];
name[0] = fName;
name[1] = lName;
return name;
}
public DataTable getAdmin()
{
DataTable table = new DataTable();
SqlCommand cmd = new SqlCommand("SELECT * FROM ADMIN WHERE ID = @ID", Database.Instance.getConnection);
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = userID;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(table);
return table;
}
public DataTable getManager()
{
DataTable table = new DataTable();
SqlCommand cmd = new SqlCommand("SELECT * FROM ADMIN WHERE USERNAME LIKE 'A%'", Database.Instance.getConnection);
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = userID;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(table);
return table;
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Linq;
namespace MergeSort
{
public class StringShuffleService
{
public void ConsoleRun()
{
/*************************************************
* Problem
- Write a function that takes a string, shuffles the string, and returns it.
***************************************************/
var line = string.Empty;
while (line.ToLower() != "exit")
{
Console.WriteLine("Enter a word or sentence: ");
line = Console.ReadLine();
if (line == "exit")
break;
else
{
Console.WriteLine($"Answer: {ShuffleString(line)}");
}
}
}
public string ShuffleString(string str)
{
//create blank array of string.Length
var arr = new string[str.Length];
//loop through string
var random = new Random();
var randomIndex = random.Next(0, str.Length - 1);
var goUp = true;
foreach (var letter in str)
{
//add to random index in array if index is empty
if (arr[randomIndex] == null)
arr[randomIndex] = letter.ToString();
//else while index is not empty
else
{
if (goUp)
{
while (arr[randomIndex] != null)
randomIndex = randomIndex == str.Length - 1 ? 0 : randomIndex + 1;
}
else
{
while (arr[randomIndex] != null)
randomIndex = randomIndex == 0 ? str.Length - 1 : randomIndex - 1;
}
arr[randomIndex] = letter.ToString();
goUp = !goUp;
}
}
return string.Join(string.Empty, arr);
}
}
[TestFixture]
public class StringShuffleServiceTests
{
public StringShuffleService service = new StringShuffleService();
[Test]
public void StringShuffleServiceTest1()
{
var given = "Test string";
var result = service.ShuffleString(given);
foreach (var letter in given)
{
Assert.Contains(letter, result.ToCharArray());
}
}
[Test]
public void StringShuffleServiceTest2()
{
var result = "abcdefghijklmnopqrstuvwxyz";
var thresholdMax = 462; //10000 * (1/26) * 1.2
var thresholdMin = 307; //10000 * (1/26) * .8
var count = 0;
for (int i = 0; i < 10000; i++)
{
result = service.ShuffleString(result);
if (result[0] == 'a')
count++;
}
Console.WriteLine(count.ToString());
Assert.Greater(count, thresholdMin);
Assert.Less(count, thresholdMax);
}
[Test]
public void StringShuffleServiceTest3()
{
var result = "abcdefghijklmnopqrstuvwxyz";
var thresholdMax = 462; //10000 * (1/26) * 1.2
var thresholdMin = 307; //10000 * (1/26) * .8
var count = 0;
for (int i = 0; i < 10000; i++)
{
result = service.ShuffleString(result);
if (result[12] == 'm')
count++;
}
Console.WriteLine(count.ToString());
Assert.Greater(count, thresholdMin);
Assert.Less(count, thresholdMax);
}
[Test]
public void StringShuffleServiceTest4()
{
var result = "abcdefghijklmnopqrstuvwxyz";
var thresholdMax = 462; //10000 * (1/26) * 1.2
var thresholdMin = 307; //10000 * (1/26) * .8
var count = 0;
for (int i = 0; i < 10000; i++)
{
result = service.ShuffleString(result);
if (result[25] == 'z')
count++;
}
Console.WriteLine(count.ToString());
Assert.Greater(count, thresholdMin);
Assert.Less(count, thresholdMax);
}
public class Counter
{
public string Letter { get; set; }
public int Index { get; set; }
public int CountAtIndex { get; set; }
}
[Test]
public void StringShuffleServiceTest5()
{
//class counter
//letter
//position
//count
var result = "abcdefghijklmnopqrstuvwxyz";
var thresholdMax = 462; //10000 * (1/26) * 1.2
var thresholdMin = 307; //10000 * (1/26) * .8
var count = new List<Counter>();
for (int i = 0; i < 10000; i++)
{
result = service.ShuffleString(result);
for (int j = 0; j < result.Length; j++)
{
var counter = count.Where(x => x.Letter == result[j].ToString() && x.Index == j).FirstOrDefault();
if (counter == null)
count.Add(new Counter() { Letter = result[j].ToString(), Index = j, CountAtIndex = 1 });
else
counter.CountAtIndex++;
}
}
var json = JsonSerializer.Serialize(count);
Console.WriteLine(json);
foreach (var counter in count)
{
Assert.Greater(counter.CountAtIndex, thresholdMin);
Assert.Less(counter.CountAtIndex, thresholdMax);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrowdEntityController : MonoBehaviour {
[SerializeField]
private List<string> _animations;
private Animator _animator;
void Start ()
{
_animator = GetComponent<Animator>();
StartCoroutine(StartAnimationLoop());
}
IEnumerator StartAnimationLoop()
{
while (true)
{
int i = Random.Range(0, _animations.Count - 1);
_animator.SetTrigger(_animations[i]);
yield return new WaitForSeconds(Random.Range(4, 10));
}
}
void Update ()
{
}
}
|
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using com.Sconit.Service;
using com.Sconit.Service.Impl;
using com.Sconit.Persistence;
namespace com.Sconit.Web.SI.Installer
{
public class ServiceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(AllTypes.FromAssemblyNamed("com.Sconit.Service")
.Pick().If(t => t.Name.EndsWith("MgrImpl")
&& !t.Name.Equals("GenericMgrImpl")
&& !t.Name.Equals("QueryImpl")
&& !t.Name.Equals("EmailMgrImpl")
&& !t.Name.Equals("PubSubMgrImpl"))
.Configure(c => c.LifeStyle.Singleton)
.WithService.DefaultInterface()
);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundManager : SingletonMonoBehaviour<BackgroundManager> {
private GameObject panel;
private Animator animator;
private bool isInAction;
private FadeInFinishedListener fadeInListener;
private FadeOutFinishedListener fadeOutListener;
[SerializeField]
string[] animator_bools;
// Use this for initialization
void Start () {
isInAction = false;
panel = GameObject.FindGameObjectWithTag ("panel");
animator = panel.GetComponent<Animator> ();
}
public void setFadeOutFinishedListener(FadeOutFinishedListener listener){
fadeOutListener = listener;
}
public void setFadeInFinishedListener(FadeInFinishedListener listener){
fadeInListener = listener;
}
// Update is called once per frame
void Update () {
}
public void fadeIn(){
if (!isInAction) {
isInAction = true;
animator.SetBool ("fadeIn", true);
}
}
public void fadeOut(){
if (!isInAction) {
isInAction = true;
animator.SetBool ("fadeOut", true);
}
}
public void setIsInAction(bool _bool){
isInAction = _bool;
}
public void resetBools(){
foreach (string boolname in animator_bools) {
animator.SetBool (boolname, false);
}
}
public void fadeOutFinished(){
fadeOutListener.fadeOutFinished ();
resetBools ();
setIsInAction (false);
animator.SetBool ("stayDark", true);
}
public void fadeInFinished(){
fadeInListener.fadeInFinished ();
resetBools ();
setIsInAction (false);
animator.SetBool ("stayClear", true);
}
public interface FadeInFinishedListener{
void fadeInFinished();
}
public interface FadeOutFinishedListener{
void fadeOutFinished();
}
}
|
using Atc.CodeAnalysis.CSharp.SyntaxFactories;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
namespace Atc.CodeAnalysis.CSharp.Tests.SyntaxFactories
{
public class SyntaxArgumentFactoryTests
{
[Fact]
public void CreateWithOneItem()
{
// Arrange
var expected = SyntaxFactory.Argument(
SyntaxFactory.IdentifierName("hallo"));
// Act
var actual = SyntaxArgumentFactory.Create("hallo");
// Assert
Assert.Equal(expected.ToFullString(), actual.ToFullString());
}
}
} |
namespace WinAppDriver
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
internal class EndPoint
{
private static ILogger logger = Logger.GetLogger("WinAppDriver");
private static Regex paramRegex = new Regex("/:([^/]+)");
private string method;
private string pattern;
private Regex regex;
public EndPoint(string method, string pattern, IHandler handler)
{
this.method = method;
this.pattern = pattern;
this.regex = this.ToRegex(pattern);
this.Handler = handler;
}
public IHandler Handler { get; private set; }
public bool IsMatch(string method, string path, out Dictionary<string, string> urlParams)
{
urlParams = null;
if (method != this.method)
{
return false;
}
var match = this.regex.Match(path);
if (!match.Success)
{
return false;
}
urlParams = new Dictionary<string, string>();
foreach (string name in this.regex.GetGroupNames())
{
urlParams[name] = match.Groups[name].Value;
}
return true;
}
private Regex ToRegex(string pattern)
{ // TODO no /wd/hub/ hard coded
string pattern_converted = string.Format(
"^/wd/hub{0}$",
paramRegex.Replace(pattern, "/(?<${1}>[^/]+)"));
logger.Debug("Pattern conversion; {0} => {1}", pattern, pattern_converted);
return new Regex(pattern_converted);
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class DrawSimbol : MonoBehaviour {
public List<GameObject> objects1 = new List<GameObject>();
public GameObject object1;
public Transform[] target;
public Transform bestTarget;
public float speed;
public int caseSwitch;
int time;
int timeR = 22;
float rotationleft=720;
public float rotationspeed=50;
public bool New_list;
public bool ReadyToMove;
Vector3 LastPos;
Vector3 CurentPos;
float SetDis;
public float TargetDis;
public bool ZaxisUp;
public bool NewObject;
void Start () {
CreateList ();
TargetList ();
ItereteList ();
caseSwitch=1;
}
void Update () {
GetClosestEnemy (target);
ItereteList ();
TargetDis = Vector3.Distance(this.gameObject.transform.position, object1.gameObject.transform.position);
switch (caseSwitch) {
case 1:
NewObject = false;
Move (1);
break;
case 2:
NewObject = true;
Move (2);
break;
case 3:
SetDis = 4F;
if (TargetDis > SetDis){
Move (3);
rotationleft=1440;
NewObject = true;
}else{
NewObject = false;
Circle();
}
break;
case 4:
SetDis = 2F;
if (TargetDis > SetDis){
Move (3);
NewObject = true;
rotationleft=360;
}else{
Circle();
NewObject = false;
}
break;
}
if (objects1.Count == 0) {
NewObject = true;
CreateList ();
TargetList ();
caseSwitch = caseSwitch + 1;
} else {
New_list = false;
// NewObject = false;
}
if (caseSwitch==5) {
New_list = true;
caseSwitch=1;
}
}
void Circle(){
if(ReadyToMove){
Move (1);
}else{Move (4);}
}
void ItereteList(){
for (int i = 0; i < target.Length; ++i) {
if(bestTarget==target[i]){
object1=objects1[i];
float Dist = Vector3.Distance(this.gameObject.transform.position, object1.gameObject.transform.position);
if (Dist<0.1F && time>timeR ){
ReadyToMove=false;
objects1.RemoveAt(i);
TargetList();
time=0;
}else{time ++;}
}
}
}
// void ItereteList(){
// for (int i = 0; i < objects1 .Count; ++i) {
//
// if (bestTarget == target [i]) {
// object1 = objects1 [i];
//
// if (TargetDis<0.2F && time>timeR){
// ReadyToMove=false;
// objects1.RemoveAt(i);
// TargetList();
// }else{time ++;}
//
// }
// }
// }
void Move(int Type){
float step = speed * Time.deltaTime;
// if(gameObject.GetComponent<SendString> ().IM){
switch (Type) {
case 1:
transform.position = Vector3.MoveTowards (this.gameObject.transform.position, object1.transform.position, step * 10);
break;
case 2:
transform.position = Vector3.RotateTowards (this.gameObject.transform.position, object1.transform.position, (speed * Time.deltaTime), 0.1F);
break;
case 3:
transform.position = Vector3.RotateTowards (this.gameObject.transform.position, object1.transform.position, (speed * Time.deltaTime), 0.1F);
float Dist = Vector3.Distance (this.gameObject.transform.position, object1.gameObject.transform.position);
Vector3 TargetPosition = object1.transform.position;
float move = Dist * Time.deltaTime;
this.gameObject.transform.position = Vector3.MoveTowards (this.gameObject.transform.position, TargetPosition, move);
break;
case 4:
float rotation=rotationspeed*Time.deltaTime;
if (rotationleft > rotation)
{
ReadyToMove=false;
rotationleft-=rotation;
}
else
{
rotation=rotationleft;
rotationleft=0;
ReadyToMove=true;
}
transform.RotateAround(object1.transform.position, Vector3.up,rotation);
break;
}
// }
}
void CreateList(){
objects1 = GameObject.FindGameObjectsWithTag ("FD").ToList();
}
void TargetList(){
target =new Transform[objects1.Count];
for (int i = 0; i < objects1.Count; ++i) {
target [i] = objects1[i].transform;
}
}
Transform GetClosestEnemy (Transform[] enemies)
{
bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = transform.position;
foreach(Transform potentialTarget in enemies)
{
Vector3 directionToTarget = potentialTarget.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if(dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
return bestTarget;
}
} |
namespace Demo.Interfaces
{
public interface INotifier
{
void SendNotification(NotificationType notificationType);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Configuration;
using System.Timers;
namespace DMSTaskService
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.UpdataTask();
}
public void UpdataTask()
{
// log.Warn("开始工作" + DateTime.Now.ToString());
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WFTask> items = db.WFTasks.Where(p => p.Status == "审批中" && p.ApproveType == "初步评审" && DateTime.Compare(DateTime.Now, Convert.ToDateTime(p.LastModifirfDate)) > 0).ToList();
foreach (WFTask witem in items)
{
witem.Status = "完成";
witem.ApprverOpion = "同意";
witem.CompletedDate = DateTime.Now.ToString();
db.SubmitChanges();
}
string wfinstid = "";
foreach (WFTask item in items)
{
bool istrue = true;
if (item.WFinstId != wfinstid)
{
wfinstid = item.WFinstId;
int count = GetWFTaskCountByStep(wfinstid, item.Step);
if (count > 0)
{
istrue = false;
}
WriteTextLog("Instid", wfinstid, DateTime.Now);
WriteTextLog("count", count.ToString(), DateTime.Now);
WriteTextLog("istrue", istrue.ToString(), DateTime.Now);
if (istrue)
{
WFInst inst = db.WFInsts.Where(p => p.Id == Convert.ToInt32(item.WFinstId)).FirstOrDefault();
int step = int.Parse(item.Step);
// WorkflowScenario node = GetWFNode(item.WorkflowId, step.ToString());
inst.Name = "编辑人";
inst.Status = "审批中";
inst.Step = step.ToString();
db.SubmitChanges();
WFTask newtask = new WFTask();
newtask.FileId = item.FileId;
newtask.WorkflowId = inst.WorkflowId;
newtask.WorkflowName = inst.WorkflowName;
newtask.Step = step.ToString();
newtask.AssigedDate = DateTime.Now.ToString();
newtask.Name = "编辑人";
newtask.Status = "审批中";
newtask.WFinstId = item.WFinstId;
newtask.ApproveType = "编辑人";
newtask.ApplicantAD = inst.ApplicantAD;
newtask.ApproverAD = inst.ApplicantAD;
newtask.AssTag = item.AssTag;
newtask.VersionNum = item.VersionNum;
newtask.FileName = item.FileName;
newtask.WFType = inst.WFType;
db.WFTasks.InsertOnSubmit(newtask);
db.SubmitChanges();
}
}
}
}
//}
//catch(Exception ex)
//{
// Console.Write(ex.ToString());
//}
}
/// <summary>
///获取流程某步的所有任务
/// </summary>
/// <param name="workflowid"></param>
/// <param name="step"></param>
/// <param name="fileid"></param>
/// <param name="borrowid"></param>
/// <returns></returns>
public static List<WFTask> GetWFTasksByStep(string workflowid, string step)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WFTask> items = db.WFTasks.Where(p => p.WorkflowId == workflowid && p.Step == step).ToList();
return items;
}
}
public static int GetWFTaskCountByStep(string workflowid, string step)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WFTask> items = db.WFTasks.Where(p => p.WFinstId == workflowid && p.Step == step&&p.Status=="审批中").ToList();
return items.Count;
}
}
/// <summary>
///写日志
/// </summary>
/// <param name="action"></param>
/// <param name="strMessage"></param>
/// <param name="time"></param>
public static void WriteTextLog(string action, string strMessage, DateTime time)
{
string path = AppDomain.CurrentDomain.BaseDirectory + @"System\Log\";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".System.txt";
StringBuilder str = new StringBuilder();
str.Append("Time: " + time.ToString() + "\r\n");
str.Append("Action: " + action + "\r\n");
str.Append("Message: " + strMessage + "\r\n");
str.Append("-----------------------------------------------------------\r\n\r\n");
StreamWriter sw;
if (!System.IO.File.Exists(fileFullPath))
{
sw = System.IO.File.CreateText(fileFullPath);
}
else
{
sw = System.IO.File.AppendText(fileFullPath);
}
sw.WriteLine(str.ToString());
sw.Close();
}
/// <summary>
/// 获取流程节点
/// </summary>
/// <param name="workflowid"></param>
/// <param name="step"></param>
/// <returns></returns>
public static WorkflowScenario GetWFNode(string workflowid, string step)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
WorkflowScenario item = db.WorkflowScenarios.Where(p => p.WorkflowId == workflowid && p.Step == step).FirstOrDefault();
return item;
}
}
/// <summary>
/// 根据流程编号获取流程节点数
/// </summary>
/// <param name="workflowid">流程编号</param>
/// <returns></returns>
public static int GetWFNodeCount(string workflowid)
{
using (TaskDataContext db = new TaskDataContext(ConfigurationSettings.AppSettings["DBCon"]))
{
List<WorkflowScenario> items = db.WorkflowScenarios.Where(p => p.WorkflowId == workflowid).ToList();
return items.Count;
}
}
}
}
|
using System.Threading.Tasks;
namespace EncryptionDecryptionConsole
{
public interface IIOService
{
Task SaveAsync(string filename, string text);
Task<string> LoadAsync(string filename);
}
} |
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace MergeSort
{
public class MissingIntegerService
{
public void ConsoleRun()
{
//Array
var array = string.Empty;
while (array.ToLower() != "exit")
{
Console.WriteLine("Enter an array: ");
array = Console.ReadLine();
if (array == "exit")
break;
else
{
int[] arr = Array.ConvertAll(array.Split(" "), int.Parse);
var output = GetMissingInteger(arr);
Console.WriteLine($"Output: {output}");
}
}
}
public int GetMissingInteger(int[] arr)
{
var returnValue = 1;
var badValues = new HashSet<int>();
//iterate array
for (int i = 0; i < arr.Length; i++)
{
badValues.Add(arr[i]);
if (returnValue == arr[i])
{
while (badValues.Contains(returnValue))
{
returnValue++;
}
}
}
return returnValue;
}
}
[TestFixture]
public class MissingIntegerServiceTests
{
public MissingIntegerService service = new MissingIntegerService();
[Test]
public void GetMissingIntegerTest1()
{
var givenArray = new int[] { 1, 3, 6, 4, 1, 2 };
var expectedArray = 5;
Assert.AreEqual(expectedArray, service.GetMissingInteger(givenArray));
}
}
}
|
using Projeto.Api.Tests.Contexts;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Projeto.Api.Tests.TestSteps
{
public class ProdutoTestSteps
{
private readonly TestContext testContext;
public ProdutoTestSteps()
{
testContext = new TestContext();
}
[Fact(Skip = "Não implementado")]
public async Task CadastrarProduto()
{
}
[Fact(Skip = "Não implementado")]
public async Task AtualizarProduto()
{
}
[Fact(Skip = "Não implementado")]
public async Task ExcluirProduto()
{
}
[Fact(Skip = "Não implementado")]
public async Task ConsultarProdutos()
{
}
[Fact(Skip = "Não implementado")]
public async Task ObterProdutoPorId()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.Principal;
using PagedList;
using PagedList.Mvc;
using System.Web.UI.WebControls;
using System.Web.UI;
namespace Moses.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult FAQ()
{
return View();
}
[HttpGet]
public void ExportToExcel()
{
/*var grid = new GridView();
Branch branch = new Branch();
branch.Filters = new BranchSignageFilter();
branch.Filters.FromDate = (Request.QueryString["fd"] == null) ? new DateTime() : Convert.ToDateTime(Request.QueryString["fd"].ToString());
branch.Filters.ToDate = (Request.QueryString["td"] == null) ? new DateTime() : Convert.ToDateTime(Request.QueryString["td"].ToString());
branch.Filters.Branch = (Request.QueryString["b"] == null) ? string.Empty : Request.QueryString["b"].ToString();
branch.Branch_Sinages = branch.Filter().Branch_Sinages;
grid.DataSource = from data in branch.Branch_Sinages
select new
{
Name = data.Name,
Branch = data.Branch,
Date = data.Date,
SectionName = data.SectionName,
Quantity = data.Quantity
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=test.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grid.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();*/
}
[HttpGet]
public ActionResult Report(int? page)
{
/*var pageNumber = page ?? 1;
Branch branch = new Branch();
branch.Branches = branch.GetBranches();
branch.Filters = new BranchSignageFilter();
branch.Filters.FromDate = (Request.QueryString["fd"] == null) ? new DateTime() : Convert.ToDateTime(Request.QueryString["fd"].ToString());
branch.Filters.ToDate = (Request.QueryString["td"] == null) ? new DateTime() : Convert.ToDateTime(Request.QueryString["td"].ToString());
branch.Filters.Branch = (Request.QueryString["b"] == null) ? string.Empty : Request.QueryString["b"].ToString();
branch.Filters.Branch_Sinage = branch.Filter().Branch_Sinages.ToPagedList(pageNumber, 20);*/
return View();
}
[HttpPost]
public ActionResult Report(int? page, string branch, string FromDate, string ToDate)
{
/*var pageNumber = page ?? 1;
Branch brancho = new Branch();
brancho.Branches = brancho.GetBranches();
brancho.Filters = new BranchSignageFilter();
brancho.Filters.FromDate = (String.IsNullOrEmpty(FromDate)) ? new DateTime() : Convert.ToDateTime(FromDate);
brancho.Filters.ToDate = (String.IsNullOrEmpty(ToDate)) ? new DateTime() : Convert.ToDateTime(ToDate);
brancho.Filters.Branch = (String.IsNullOrEmpty(branch)) ? string.Empty : branch;
brancho.Filters.Branch_Sinage = brancho.Filter().Branch_Sinages.ToPagedList(pageNumber, 20);*/
return View();
}
[HttpPost]
public string Save()
{
/*string message = string.Empty;
if (branch.SaveSinage() == true)
message = "Your items have been saved successfully.";
else
message = "Error Saving data.";
return message;*/
return string.Empty;
}
}
}
|
using UnityEngine;
namespace Assets.Gamelogic.Pirates.Cannons
{
// This MonoBehaviour will be enabled on both client and server-side workers
public class CannonFirer : MonoBehaviour
{
private Cannon cannon;
private void Start()
{
// Cache entity's cannon gameobject
cannon = gameObject.GetComponent<Cannon>();
}
public void AttemptToFireCannons(Vector3 direction)
{
if (cannon != null)
{
cannon.Fire(direction);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Graphs;
using UnityEngine;
namespace Needle.Demystify
{
[CreateAssetMenu(menuName = "Needle/Demystify/Syntax Highlighting Theme")]
public class SyntaxHighlightingTheme : ScriptableObject
{
public Theme theme = new Theme("New Theme");
}
[CustomEditor(typeof(SyntaxHighlightingTheme))]
public class SyntaxHighlightingThemeEditor : Editor
{
private Highlighting previewHighlightingStyle;
private bool editColors
{
get => SessionState.GetBool("DemystifyTheme.EditColors", false);
set => SessionState.SetBool("DemystifyTheme.EditColors", value);
}
private void OnEnable()
{
previewHighlightingStyle = DemystifySettings.instance.SyntaxHighlighting;
if (target is SyntaxHighlightingTheme sh && sh.theme != null)
sh.theme.Name = target.name;
}
public override void OnInspectorGUI()
{
var targetTheme = target as SyntaxHighlightingTheme;
if (!targetTheme) return;
var theme = targetTheme.theme;
theme.EnsureEntries();
serializedObject.Update();
// Name inspector
var themeProperty = serializedObject.FindProperty("theme");
var nameProperty = themeProperty.FindPropertyRelative("Name");
EditorGUI.BeginChangeCheck();
using (new EditorGUI.DisabledScope(true))
{
nameProperty.stringValue = target.name;
EditorGUILayout.PropertyField(nameProperty);
}
EditorGUILayout.Space();
editColors = EditorGUILayout.Toggle(new GUIContent("Edit colors in groups", "Enable to edit multiple fields of the same color at once"), editColors);
if (editColors)
{
HandleColorEditing(theme);
EditorGUILayout.Space(10);
}
EditorGUILayout.LabelField("Theme Colors", EditorStyles.boldLabel);
DemystifySettingsProvider.DrawThemeColorOptions(theme, false);
EditorGUILayout.Space();
if (GUILayout.Button("Copy from Active"))
{
var currentTheme = DemystifySettings.instance.CurrentTheme;
targetTheme.theme = currentTheme;
}
if (GUILayout.Button("Activate"))
{
DemystifySettings.instance.CurrentTheme = theme;
}
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(target, "Edited " + name);
if (theme == DemystifySettings.instance.CurrentTheme)
DemystifySettings.instance.UpdateCurrentTheme();
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
}
EditorGUILayout.Space();
DrawPreview(theme, ref previewHighlightingStyle);
}
private static readonly Dictionary<string, string> previewColorDict = new Dictionary<string, string>();
private static GUIStyle previewStyle;
private static bool themePreviewFoldout
{
get => SessionState.GetBool("DemystifySyntaxPreviewFoldout", false);
set => SessionState.SetBool("DemystifySyntaxPreviewFoldout", value);
}
private static void DrawPreview(Theme theme, ref Highlighting style)
{
EditorGUILayout.Space(8);
themePreviewFoldout = EditorGUILayout.Foldout(themePreviewFoldout, "Theme Preview");
if(!themePreviewFoldout) return;
// style = (Highlighting) EditorGUILayout.EnumPopup("Preview Style", style);
EditorGUILayout.Space(5);
if(previewStyle == null)
previewStyle = new GUIStyle(EditorStyles.label) {richText = true, wordWrap = false};
using (new EditorGUI.DisabledScope(true))
{
var settings = DemystifySettings.instance;
// var currentStyle = settings.SyntaxHighlighting;
// settings.SyntaxHighlighting = style;
theme.SetActive(previewColorDict);
var str = DummyData.SyntaxHighlightVisualization;
DemystifySettingsProvider.ApplySyntaxHighlightingMultiline(ref str, previewColorDict);;
// settings.SyntaxHighlighting = currentStyle;
GUILayout.TextArea(str, previewStyle);
}
}
private static readonly List<(Color color, List<int> matches)> groups = new List<(Color, List<int>)>();
private void HandleColorEditing(Theme theme)
{
groups.Clear();
for (var index = 0; index < theme.Entries.Count; index++)
{
var col = theme.Entries[index];
var group = groups.FirstOrDefault(e => e.color == col.Color);
if (group.matches == null)
{
group = (col.Color, new List<int>());
groups.Add(group);
}
group.matches.Add(index);
}
EditorGUI.BeginChangeCheck();
for (var index = 0; index < groups.Count; index++)
{
var group = groups[index];
group.color = EditorGUILayout.ColorField(group.matches.Count.ToString(), group.color);
groups[index] = group;
}
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(target, $"Batch edit {theme.Name} colors");
foreach (var group in groups)
{
foreach (var index in group.matches)
{
theme.Entries[index].Color = group.color;
}
}
}
}
}
} |
#if !NETSTANDARD1_3
using System;
using System.Globalization;
using System.Threading;
using System.Transactions;
namespace MySql.Data.MySqlClient
{
internal sealed class MySqlXaTransaction : IEnlistmentNotification
{
public MySqlXaTransaction(MySqlConnection connection) => m_connection = connection;
public void Start(Transaction transaction)
{
// generate an "xid" with "gtrid" (Global TRansaction ID) from the .NET Transaction and "bqual" (Branch QUALifier)
// unique to this object
var id = Interlocked.Increment(ref s_currentId);
m_xid = "'" + transaction.TransactionInformation.LocalIdentifier + "', '" + id.ToString(CultureInfo.InvariantCulture) + "'";
ExecuteXaCommand("START");
// TODO: Support EnlistDurable and enable recovery via "XA RECOVER"
transaction.EnlistVolatile(this, EnlistmentOptions.None);
}
public void Prepare(PreparingEnlistment enlistment)
{
ExecuteXaCommand("END");
ExecuteXaCommand("PREPARE");
enlistment.Prepared();
}
public void Commit(Enlistment enlistment)
{
ExecuteXaCommand("COMMIT");
enlistment.Done();
m_connection.UnenlistTransaction(this);
}
public void Rollback(Enlistment enlistment)
{
ExecuteXaCommand("END");
ExecuteXaCommand("ROLLBACK");
enlistment.Done();
m_connection.UnenlistTransaction(this);
}
public void InDoubt(Enlistment enlistment) => throw new NotSupportedException();
private void ExecuteXaCommand(string statement)
{
using (var cmd = m_connection.CreateCommand())
{
cmd.CommandText = "XA " + statement + " " + m_xid;
cmd.ExecuteNonQuery();
}
}
static int s_currentId;
readonly MySqlConnection m_connection;
string m_xid;
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace University.UI.Areas.Admin.Models
{
public class ProductVideoViewModel
{
string ProductImagePath = WebConfigurationManager.AppSettings["ProductImagePath"];
public string TransactionId { get; set; }
public string VideoFullPath
{
get
{
if (string.IsNullOrWhiteSpace(VideoURL))
{
return null;
}
else
{
return ProductImagePath.Replace("~", "") + VideoURL;
}
}
}
public string ImageFullPath
{
get
{
if (string.IsNullOrWhiteSpace(VideoURL))
{
return null;
}
else
{
return ProductImagePath.Replace("~", "") + ThumbnailURL;
}
}
}
public int? cateuserid { get; set; }
public Decimal Id { get; set; }
// [StringLength(50, ErrorMessage = "Do not enter more than 50 characters")]
[Required]
public string Title { get; set; }
//[StringLength(100, ErrorMessage = "Do not enter more than 100 characters")]
public string Decription { get; set; }
public string VideoURL { get; set; }
public string ThumbnailURL { get; set; }
public Decimal ProductId { get; set; }
public Nullable<bool> IsDeleted { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<Decimal> CreatedBy { get; set; }
public Nullable<System.DateTime> DeletedDate { get; set; }
public Nullable<Decimal> DeletedBy { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public Nullable<Decimal> UpdatedBy { get; set; }
public HttpPostedFileBase ProductVideoImg { get; set; }
public HttpPostedFileBase ProductVideo { get; set; }
public Decimal AssocitedCustID { get; set; }
public decimal VideoRate { get; set; }
public bool IsPaid { get; set; }
public Decimal SubCatID { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EarStick : MonoBehaviour
{
public bool earCanTouch = false;
public bool rootMotion = false;
public Rigidbody2D otherRb;
private Rigidbody2D earRb;
public float moveY = 0;
public Collider2D[] exclude;
// Use this for initialization
void Start()
{
earRb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
//idleAnim();
}
public void idleAnim()
{
earRb.velocity = new Vector2(earRb.velocity.x, earRb.velocity.y + moveY);
}
private void OnTriggerEnter2D(Collider2D other)
{
// if (other.gameObject.tag == "ground")
// {
// if (other.gameObject.GetComponent<Rigidbody2D>() != null)
// {
// otherRb = other.gameObject.GetComponent<Rigidbody2D>();
// }
// }
if (other != exclude[0]&&other != exclude[1]&&other.gameObject.tag!="joint"){
earCanTouch = true;
otherRb = other.gameObject.GetComponent<Rigidbody2D>();
}
}
private void OnTriggerStay2D(Collider2D other)
{
// if (other.gameObject.tag == "ground")
// {
// if (other.gameObject.GetComponent<Rigidbody2D>() != null)
// {
// otherRb = other.gameObject.GetComponent<Rigidbody2D>();
// }
// }
if (other != exclude[0]&&other != exclude[1]&&other.gameObject.tag!="joint"){
earCanTouch = true;
otherRb = other.gameObject.GetComponent<Rigidbody2D>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Author: Nathan Hales
/// Credit Data struct for the Credit scene's credit object and credit manager.
/// </summary>
[System.Serializable]
public struct CreditData
{
public string name;
public string teamRole;
}
|
using UBaseline.Shared.VideoPanel;
using Uintra.Core.Search.Converters.SearchDocumentPanelConverter;
using Uintra.Core.Search.Entities;
namespace Uintra.Features.Search.Converters.Panel
{
public class VideoPanelSearchConverter : SearchDocumentPanelConverter<VideoPanelViewModel>
{
protected override SearchablePanel OnConvert(VideoPanelViewModel panel)
{
return new SearchablePanel
{
Title = panel.Title,
Content = panel.Description
};
}
}
} |
using Microsoft.Xna.Framework;
using StarlightRiver.Dusts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.Abilities
{
[DataContract]
public class Dash : Ability
{
[DataMember] protected float X = 0;
[DataMember] protected float Y = 0;
public Dash(Player player) : base(1, player)
{
}
public override bool CanUse => Main.LocalPlayer.controlLeft || Main.LocalPlayer.controlRight || Main.LocalPlayer.controlUp || Main.LocalPlayer.controlDown || player.GetModPlayer<Dragons.DragonHandler>().DragonMounted;
public override void OnCast()
{
Main.PlaySound(SoundID.Item45);
Main.PlaySound(SoundID.Item104);
X = ((player.controlLeft) ? -1 : 0) + ((player.controlRight) ? 1 : 0);
Y = ((player.controlUp) ? -1 : 0) + ((player.controlDown) ? 1 : 0);
Timer = 7;
Cooldown = 90;
}
public override void InUse()
{
player.maxFallSpeed = 999;
Timer--;
if (X != 0 || Y != 0) { player.velocity = Vector2.Normalize(new Vector2(X, Y)) * 28; }
if(Vector2.Distance(player.position, player.oldPosition) < 5 && Timer < 4)
{
Timer = 0;
player.velocity *= -0.2f;
}
if (Timer <= 0)
{
Active = false;
OnExit();
}
}
public override void UseEffects()
{
for (int k = 0; k <= 10; k++)
{
Dust.NewDustPerfect(player.Center + player.velocity * Main.rand.NextFloat(0, 2), ModContent.DustType<Air>(),
player.velocity.RotatedBy((Main.rand.Next(2) == 0) ? 2.8f : 3.48f) * Main.rand.NextFloat(0, 0.05f), 0, default, 0.95f);
}
}
public override void OnCastDragon()
{
if (player.velocity.Y == 0) //on the ground, set to zero so the game knows to do the pounce
{
X = player.direction * 2;
Y = 0;
}
else // jumping/in the air, do the barrel roll
{
X = Vector2.Normalize(player.Center - Main.MouseWorld).X;
Y = Vector2.Normalize(player.Center - Main.MouseWorld).Y;
}
Timer = 20;
Cooldown = 90;
}
public override void InUseDragon()
{
Timer--;
if(Math.Abs(X) > 1) //the normalized X should never be greater than 1, so this should be a valid check for the pounce
{
player.velocity.X = X * 6;
if (Timer == 19) player.velocity.Y -= 4;
}
else //otherwise, barrelroll
{
player.velocity = new Vector2(X, Y) * 0.2f * (((10 - Timer) * (10 - Timer)) - 100);
}
if (Timer <= 0)
{
Active = false;
OnExit();
}
}
public override void UseEffectsDragon()
{
Dust.NewDust(player.position, 50, 50, ModContent.DustType<Air>());
if (Math.Abs(X) < 1)
{
for (int k = 0; k <= 10; k++)
{
float rot = ((Timer - k / 10f) / 10f * 6.28f) + new Vector2(X, Y).ToRotation();
Dust.NewDustPerfect(Vector2.Lerp(player.Center, player.Center + player.velocity, k / 10f) + Vector2.One.RotatedBy(rot) * 30, ModContent.DustType<Air>(), Vector2.Zero);
}
}
}
public override void OffCooldownEffects()
{
for(int k = 0; k <= 25; k++)
{
Dust.NewDust(player.Center, 1, 1, ModContent.DustType<Air>());
}
Main.PlaySound(SoundID.MaxMana);
}
public override void OnExit()
{
player.velocity.X *= 0.15f;
player.velocity.Y *= 0.15f;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OpHomeSecurity.Web.Models
{
public class AlbumModel
{
public string AlbumName { get; set; }
public Guid AlbumId { get; set; }
public bool? IsActive { get; set; }
public bool? IsFeatured { get; set; }
}
} |
using ScriptableObjectFramework.Events.UnityEvents;
namespace ScriptableObjectFramework.Events
{
public class BoolEventHandler : BaseEventHandler<bool, BoolEvent, BoolUnityEvent> { }
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class printfunction : MonoBehaviour {
private string DateTime;
// Use this for initialization
void Start () {
print ("hello, My name is Sam McLain. It is" + DateTime + "pm");
}
}
|
using UnityEngine;
using UnityEngine.UI;
namespace Ardunity
{
[AddComponentMenu("ARDUnity/Utility/UI/ArdunityAppUI")]
[HelpURL("https://sites.google.com/site/ardunitydoc/references/utility/ardunityappui")]
public class ArdunityAppUI : MonoBehaviour
{
public ArdunityApp ardunityApp;
public CommSocketUI commSocketUI;
public Button connect;
public Button disconnect;
public Button quit;
public Canvas messageCanvas;
public RectTransform msgConnecting;
public RectTransform msgConnectionFailed;
public RectTransform msgLostConnection;
public Button okConnectionFailed;
public Button okLostConnection;
void Awake()
{
ardunityApp.OnConnected.AddListener(OnArdunityConnected);
ardunityApp.OnDisconnected.AddListener(OnArdunityDisconnected);
ardunityApp.OnConnectionFailed.AddListener(OnArdunityConnectionFailed);
ardunityApp.OnLostConnection.AddListener(OnArdunityLostConnection);
if(commSocketUI != null)
commSocketUI.OnSettingCompleted.AddListener(OnCommSocketSettingCompleted);
connect.onClick.AddListener(OnConnectClick);
disconnect.onClick.AddListener(OnDisconnectClick);
quit.onClick.AddListener(OnQuitClick);
okConnectionFailed.onClick.AddListener(OnMessageOKClick);
okLostConnection.onClick.AddListener(OnMessageOKClick);
}
// Use this for initialization
void Start ()
{
messageCanvas.gameObject.SetActive(false);
disconnect.gameObject.SetActive(false);
connect.gameObject.SetActive(true);
}
// Update is called once per frame
void Update ()
{
}
private void OnConnectClick()
{
if(commSocketUI != null)
commSocketUI.ShowUI();
else
OnCommSocketSettingCompleted();
}
private void OnDisconnectClick()
{
ardunityApp.Disconnect();
}
private void OnCommSocketSettingCompleted()
{
ardunityApp.Connect();
messageCanvas.gameObject.SetActive(true);
msgConnecting.gameObject.SetActive(true);
msgConnectionFailed.gameObject.SetActive(false);
msgLostConnection.gameObject.SetActive(false);
}
private void OnQuitClick()
{
ardunityApp.Disconnect();
Application.Quit();
}
private void OnMessageOKClick()
{
messageCanvas.gameObject.SetActive(false);
}
private void OnArdunityConnected()
{
disconnect.gameObject.SetActive(true);
connect.gameObject.SetActive(false);
messageCanvas.gameObject.SetActive(false);
msgConnecting.gameObject.SetActive(false);
msgConnectionFailed.gameObject.SetActive(false);
msgLostConnection.gameObject.SetActive(false);
}
private void OnArdunityDisconnected()
{
disconnect.gameObject.SetActive(false);
connect.gameObject.SetActive(true);
}
private void OnArdunityConnectionFailed()
{
messageCanvas.gameObject.SetActive(true);
msgConnecting.gameObject.SetActive(false);
msgConnectionFailed.gameObject.SetActive(true);
msgLostConnection.gameObject.SetActive(false);
}
private void OnArdunityLostConnection()
{
messageCanvas.gameObject.SetActive(true);
msgConnecting.gameObject.SetActive(false);
msgConnectionFailed.gameObject.SetActive(false);
msgLostConnection.gameObject.SetActive(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AssetTracking_EF
{
class LaptopComputer : CompanyAsset
{
public LaptopComputer(string modelName, int price, DateTime purchaseDate, string office) : base(modelName, price, purchaseDate, office)
{
ModelName = modelName;
Price = price;
PurchaseDate = purchaseDate;
AssetType = "Laptop";
}
}
class MobilePhone : CompanyAsset
{
public MobilePhone(string modelName, int price, DateTime purchaseDate, string office) : base(modelName, price, purchaseDate, office)
{
ModelName = modelName;
Price = price; // in dollars
PurchaseDate = purchaseDate;
AssetType = "Phone";
}
}
class CompanyAsset
{
public CompanyAsset(string modelName, int price, DateTime purchaseDate, string office)
{
AssetType = "";
ModelName = modelName;
Price = price;
PurchaseDate = purchaseDate;
Office = office;
}
public int ID { get; set; }
public string AssetType { get; set; }
public string ModelName { get; set; }
public int Price { get; set; }
public DateTime PurchaseDate { get; set; }
public string Office { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
#nullable disable
namespace Models.FicheModel
{
public partial class db_fiche_persoContext : DbContext
{
/* public db_fiche_persoContext()
{
}*/
public db_fiche_persoContext(DbContextOptions<db_fiche_persoContext> options)
: base(options)
{
}
public virtual DbSet<Attaque> Attaques { get; set; }
public virtual DbSet<BasicInfo> BasicInfos { get; set; }
public virtual DbSet<CaracteristicManager> CaracteristicManagers { get; set; }
public virtual DbSet<CharacterMastery> CharacterMasteries { get; set; }
public virtual DbSet<CharacterStatus> CharacterStatuses { get; set; }
public virtual DbSet<Competence> Competences { get; set; }
public virtual DbSet<CompetencesFiche> CompetencesFiches { get; set; }
public virtual DbSet<Compte> Comptes { get; set; }
public virtual DbSet<DeathrollManager> DeathrollManagers { get; set; }
public virtual DbSet<Fiche> Fiches { get; set; }
public virtual DbSet<HealthPointManager> HealthPointManagers { get; set; }
public virtual DbSet<MoneyManager> MoneyManagers { get; set; }
public virtual DbSet<PersonalityAndBackground> PersonalityAndBackgrounds { get; set; }
public virtual DbSet<SaveRollsManager> SaveRollsManagers { get; set; }
public virtual DbSet<Sort> Sorts { get; set; }
/* protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Server=db-fiche-perso.database.windows.net,1433;Database=db_fiche_perso;User Id=louispoulet;Password=ProjetGroupe13");
}
}*/
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<Attaque>(entity =>
{
entity.HasKey(e => new { e.IdFiche, e.NomAttaque })
.HasName("attaque_pk")
.IsClustered(false);
entity.ToTable("attaque");
entity.Property(e => e.IdFiche).HasColumnName("id_fiche");
entity.Property(e => e.NomAttaque)
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("nom_attaque");
entity.Property(e => e.BonusAuDegat).HasColumnName("bonus_au_degat");
entity.Property(e => e.BonusAuJet).HasColumnName("bonus_au_jet");
entity.Property(e => e.DeDegat).HasColumnName("de_degat");
entity.Property(e => e.TypeDegat)
.IsRequired()
.HasMaxLength(5)
.IsUnicode(false)
.HasColumnName("type_degat");
entity.HasOne(d => d.IdFicheNavigation)
.WithMany(p => p.Attaques)
.HasForeignKey(d => d.IdFiche)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("attaque_fiche_id_fiche_fk");
});
modelBuilder.Entity<BasicInfo>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("basic_info_pk")
.IsClustered(false);
entity.ToTable("basic_info");
entity.HasIndex(e => e.IdFiche, "basic_info_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.Classe)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("classe")
.HasDefaultValueSql("('')");
entity.Property(e => e.Experience).HasColumnName("experience");
entity.Property(e => e.Niveau).HasColumnName("niveau");
entity.Property(e => e.NomPersonnage)
.HasColumnName("nom_personnage")
.HasDefaultValueSql("('')");
entity.Property(e => e.Race)
.IsRequired()
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("race")
.HasDefaultValueSql("('')");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.BasicInfo)
.HasForeignKey<BasicInfo>(d => d.IdFiche)
.HasConstraintName("basic_info_fiche_id_fiche_fk");
});
modelBuilder.Entity<CaracteristicManager>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("caracteristic_manager_pk")
.IsClustered(false);
entity.ToTable("caracteristic_manager");
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.Charisme)
.HasColumnName("charisme")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Constitution)
.HasColumnName("constitution")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Dexterite)
.HasColumnName("dexterite")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Force)
.HasColumnName("force")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Intelligence)
.HasColumnName("intelligence")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Sagesse)
.HasColumnName("sagesse")
.HasDefaultValueSql("((10))");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.CaracteristicManager)
.HasForeignKey<CaracteristicManager>(d => d.IdFiche)
.HasConstraintName("caracteristic_manager_fiche_id_fiche_fk");
});
modelBuilder.Entity<CharacterMastery>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("character_masteries_pk")
.IsClustered(false);
entity.ToTable("character_masteries");
entity.HasIndex(e => e.IdFiche, "character_masteries_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.Langues)
.IsRequired()
.HasMaxLength(600)
.IsUnicode(false)
.HasColumnName("langues")
.HasDefaultValueSql("('')");
entity.Property(e => e.Maitrises)
.IsRequired()
.HasMaxLength(600)
.IsUnicode(false)
.HasColumnName("maitrises")
.HasDefaultValueSql("('')");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.CharacterMastery)
.HasForeignKey<CharacterMastery>(d => d.IdFiche)
.HasConstraintName("character_masteries_fiche_id_fiche_fk");
});
modelBuilder.Entity<CharacterStatus>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("character_status_pk")
.IsClustered(false);
entity.ToTable("character_status");
entity.HasIndex(e => e.IdFiche, "character_status_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.ClasseArmure)
.HasColumnName("classe_armure")
.HasDefaultValueSql("((10))");
entity.Property(e => e.Initiative).HasColumnName("initiative");
entity.Property(e => e.Vitesse)
.HasColumnName("vitesse")
.HasDefaultValueSql("((9))");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.CharacterStatus)
.HasForeignKey<CharacterStatus>(d => d.IdFiche)
.HasConstraintName("character_status_fiche_id_fiche_fk");
});
modelBuilder.Entity<Competence>(entity =>
{
entity.HasKey(e => e.IdComp)
.HasName("competences_pk")
.IsClustered(false);
entity.ToTable("competences");
entity.Property(e => e.IdComp).HasColumnName("id_comp");
entity.Property(e => e.NomComp)
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnName("nom_comp");
});
modelBuilder.Entity<CompetencesFiche>(entity =>
{
entity.HasKey(e => new { e.IdComp, e.IdFiche })
.HasName("competences_fiche_pk")
.IsClustered(false);
entity.ToTable("competences_fiche");
entity.Property(e => e.IdComp).HasColumnName("id_comp");
entity.Property(e => e.IdFiche).HasColumnName("id_fiche");
entity.HasOne(d => d.IdCompNavigation)
.WithMany(p => p.CompetencesFiches)
.HasForeignKey(d => d.IdComp)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("competences_fiche_competences_id_comp_fk");
entity.HasOne(d => d.IdFicheNavigation)
.WithMany(p => p.CompetencesFiches)
.HasForeignKey(d => d.IdFiche)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("competences_fiche_fiche_id_fiche_fk");
});
modelBuilder.Entity<Compte>(entity =>
{
entity.HasKey(e => e.Pseudo)
.HasName("PK__compte__EA0EEA23F3248C3D");
entity.ToTable("compte");
entity.HasIndex(e => e.Identifiant, "compte_identifiant_uindex")
.IsUnique();
entity.Property(e => e.Pseudo)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("pseudo");
entity.Property(e => e.Identifiant)
.IsRequired()
.HasMaxLength(320)
.IsUnicode(false)
.HasColumnName("identifiant");
entity.Property(e => e.Mdp)
.IsRequired()
.HasMaxLength(32)
.IsUnicode(false)
.HasColumnName("mdp")
.IsFixedLength(true);
});
modelBuilder.Entity<DeathrollManager>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("deathroll_manager_pk")
.IsClustered(false);
entity.ToTable("deathroll_manager");
entity.HasIndex(e => e.IdFiche, "deathroll_manager_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.EchecJdsContreMort).HasColumnName("echec_jds_contre_mort");
entity.Property(e => e.SuccesJdsContreMort).HasColumnName("succes_jds_contre_mort");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.DeathrollManager)
.HasForeignKey<DeathrollManager>(d => d.IdFiche)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("deathroll_manager_fiche_id_fiche_fk");
});
modelBuilder.Entity<Fiche>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("fiche_pk_2")
.IsClustered(false);
entity.ToTable("fiche");
entity.HasIndex(e => e.IdFiche, "fiche_pk")
.IsUnique();
entity.Property(e => e.IdFiche).HasColumnName("id_fiche");
entity.Property(e => e.CapaciteEtTrait)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("capacite_et_trait");
entity.Property(e => e.Equipement)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("equipement");
entity.Property(e => e.IdJoueur)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("id_joueur");
entity.Property(e => e.Inspiration).HasColumnName("inspiration");
entity.Property(e => e.NoteJoueur)
.IsRequired()
.HasMaxLength(3000)
.IsUnicode(false)
.HasColumnName("note_joueur");
entity.HasOne(d => d.IdJoueurNavigation)
.WithMany(p => p.Fiches)
.HasForeignKey(d => d.IdJoueur)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("fiche_compte_pseudo_fk");
});
modelBuilder.Entity<HealthPointManager>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("health_point_manager_pk")
.IsClustered(false);
entity.ToTable("health_point_manager");
entity.HasIndex(e => e.IdFiche, "health_point_manager_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.DesDeVie).HasColumnName("des_de_vie");
entity.Property(e => e.PvActuel).HasColumnName("pv_actuel");
entity.Property(e => e.PvMax).HasColumnName("pv_max");
entity.Property(e => e.PvTemporaire).HasColumnName("pv_temporaire");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.HealthPointManager)
.HasForeignKey<HealthPointManager>(d => d.IdFiche)
.HasConstraintName("health_point_manager_fiche_id_fiche_fk");
});
modelBuilder.Entity<MoneyManager>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("money_manager_pk")
.IsClustered(false);
entity.ToTable("money_manager");
entity.HasIndex(e => e.IdFiche, "money_manager_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.PieceArgent).HasColumnName("piece_argent");
entity.Property(e => e.PieceCuivre).HasColumnName("piece_cuivre");
entity.Property(e => e.PieceElectrum).HasColumnName("piece_electrum");
entity.Property(e => e.PieceOr).HasColumnName("piece_or");
entity.Property(e => e.PiecePlatine).HasColumnName("piece_platine");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.MoneyManager)
.HasForeignKey<MoneyManager>(d => d.IdFiche)
.HasConstraintName("money_manager_fiche_id_fiche_fk");
});
modelBuilder.Entity<PersonalityAndBackground>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("personality_and_background_pk")
.IsClustered(false);
entity.ToTable("personality_and_background");
entity.HasIndex(e => e.IdFiche, "personality_and_background_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.Age).HasColumnName("age");
entity.Property(e => e.Alignement)
.HasColumnName("alignement")
.HasDefaultValueSql("((5))");
entity.Property(e => e.AllieEtOrganisation)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("allie_et_organisation")
.HasDefaultValueSql("('')");
entity.Property(e => e.Apparence)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("apparence")
.HasDefaultValueSql("('')");
entity.Property(e => e.Background)
.IsRequired()
.HasMaxLength(5000)
.IsUnicode(false)
.HasColumnName("background")
.HasDefaultValueSql("('')");
entity.Property(e => e.Defauts)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("defauts")
.HasDefaultValueSql("('')");
entity.Property(e => e.Historique)
.IsRequired()
.HasMaxLength(1000)
.IsUnicode(false)
.HasColumnName("historique")
.HasDefaultValueSql("('')");
entity.Property(e => e.Ideaux)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("ideaux")
.HasDefaultValueSql("('')");
entity.Property(e => e.Liens)
.IsRequired()
.HasMaxLength(500)
.IsUnicode(false)
.HasColumnName("liens")
.HasDefaultValueSql("('')");
entity.Property(e => e.TraitDePersonnalite)
.IsRequired()
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnName("trait_de_personnalite")
.HasDefaultValueSql("('')");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.PersonalityAndBackground)
.HasForeignKey<PersonalityAndBackground>(d => d.IdFiche)
.HasConstraintName("personality_and_background_fiche_id_fiche_fk");
});
modelBuilder.Entity<SaveRollsManager>(entity =>
{
entity.HasKey(e => e.IdFiche)
.HasName("save_rolls_manager_pk")
.IsClustered(false);
entity.ToTable("save_rolls_manager");
entity.HasIndex(e => e.IdFiche, "save_rolls_manager_id_fiche_uindex")
.IsUnique();
entity.Property(e => e.IdFiche)
.ValueGeneratedNever()
.HasColumnName("id_fiche");
entity.Property(e => e.JdsCharisme).HasColumnName("jds_charisme");
entity.Property(e => e.JdsConstitution).HasColumnName("jds_constitution");
entity.Property(e => e.JdsDexterite).HasColumnName("jds_dexterite");
entity.Property(e => e.JdsForce).HasColumnName("jds_force");
entity.Property(e => e.JdsIntelligence).HasColumnName("jds_intelligence");
entity.Property(e => e.JdsSagesse).HasColumnName("jds_sagesse");
entity.HasOne(d => d.IdFicheNavigation)
.WithOne(p => p.SaveRollsManager)
.HasForeignKey<SaveRollsManager>(d => d.IdFiche)
.HasConstraintName("save_rolls_manager_fiche_id_fiche_fk");
});
modelBuilder.Entity<Sort>(entity =>
{
entity.HasKey(e => new {e.NomSort,e.IdFiche})
.HasName("sorts_pk")
.IsClustered(false);
entity.ToTable("sorts");
//entity.Property(e => e.IdSort).HasColumnName("id_sort");
entity.Property(e => e.DescriptionSort)
.IsRequired()
.HasMaxLength(2000)
.IsUnicode(false)
.HasColumnName("description_sort");
entity.Property(e => e.IdFiche).HasColumnName("id_fiche");
entity.Property(e => e.NiveauSort).HasColumnName("niveau_sort");
entity.Property(e => e.NomSort)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("nom_sort");
entity.HasOne(d => d.IdFicheNavigation)
.WithMany(p => p.Sorts)
.HasForeignKey(d => d.IdFiche)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("sorts_fiche_id_fiche_fk");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
|
namespace Uintra.Features.Notification.Models.NotifierTemplates
{
/// <summary>
/// Marker
/// </summary>
public interface INotifierTemplate { }
}
|
using KartObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects.Entities;
namespace KartLib
{
public class SearchGood:Good
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get
{
return "Сущность товара для поиска";
}
}
public decimal Rest
{
get;
set;
}
public decimal CostPrice
{
get;
set;
}
public static SearchGood FromGood(Good g)
{
return new SearchGood() { Articul = g.Articul, Name = g.Name, Id = g.Id };
}
}
}
|
using System;
using System.Text;
using FxNet;
namespace test
{
class WebSocketSession : FxNet.ISession
{
public override void Close()
{
if (m_pSocket == null)
{
return;
}
IoThread.Instance().DelConnectSocket(m_pSocket);
}
public override void Init(string szIp, UInt16 wPort)
{
//m_pSocket = new FxTcpClientSocket();
m_pSocket = new FxWebSocket();
m_szIp = szIp;
m_wPort = wPort;
}
public override bool IsConnected()
{
if (m_pSocket == null)
{
return false;
}
return m_pSocket.IsConnected();
}
public override void OnClose()
{
}
public override void OnConnect()
{
var st = new System.Diagnostics.StackTrace();
var frame = st.GetFrame(0);
string szData = String.Format("{0}, {1}, {2}, {3}, {4}",
frame.GetFileName(), frame.GetFileLineNumber().ToString(),
frame.GetMethod().ToString(),
ToString(), DateTime.Now.ToLocalTime().ToString());
byte[] pData = Encoding.UTF8.GetBytes(szData);
Send(pData, (UInt32)pData.Length);
}
public override bool OnDestroy()
{
return false;
}
public override void OnError(uint dwErrorNo)
{
}
UInt32 dw1 = 0;
public override void OnRecv(byte[] pBuf, uint dwLen)
{
NetStream pNetStream = new NetStream(pBuf, dwLen);
byte[] pData = new byte[dwLen];
pNetStream.ReadData(ref pData, dwLen);
string szData = Encoding.UTF8.GetString(pData);
var st = new System.Diagnostics.StackTrace();
var frame = st.GetFrame(0);
szData = String.Format("{0}, {1}, {2}, {3}, {4}, {5}",
frame.GetFileName(), frame.GetFileLineNumber().ToString(),
frame.GetMethod().ToString(), dw1++,
ToString(), DateTime.Now.ToLocalTime().ToString());
pData = Encoding.UTF8.GetBytes(szData);
Send(pData, (UInt32)pData.Length);
}
public override IFxClientSocket Reconnect()
{
m_pSocket.Init(this);
m_pSocket.Connect(m_szIp, m_wPort);
return m_pSocket;
}
public override void Release()
{
}
public override bool Send(byte[] pBuf, uint dwLen)
{
if (IsConnected())
{
m_pSocket.Send(pBuf, dwLen);
return true;
}
return false;
}
protected IFxClientSocket m_pSocket;
}
}
|
namespace Uintra.Infrastructure.Extensions
{
public static class ByteExtensions
{
public static float ToMegabytes(this byte[] source) =>
source.Length / 1024.0F / 1024.0F;
}
} |
/**************************************
*
* Needs a another class to dictate
* the DPS and Duration of Corrosion
*
* This design was made based on how
* Corrosion damage is uniform to all
* yet still need to be easily editable
*
* Damages player until it is cured or
* when duration is over
*
**************************************/
using DChild.Gameplay.Objects;
using DChild.Gameplay.Combat.StatusEffects.Configurations;
using Sirenix.OdinInspector;
using UnityEngine;
using DChild.Gameplay.Systems.Subroutine;
using BP12.Collections;
using BP12.Events;
namespace DChild.Gameplay.Combat.StatusEffects
{
public class CorrosionStatus : MonoBehaviour, IStatusEffect<CorrosionConfig>
{
[SerializeField]
[AttackType(AttackType.Corrosion)]
private AttackDamage m_damage;
[SerializeField]
private CountdownTimer m_damageIntervalTimer;
[SerializeField]
private CountdownTimer m_durationTimer;
public float percentDuration => m_durationTimer.percentTime;
private IDamageable m_target;
[Button("Inflict")]
public void Inflict()
{
m_durationTimer.Reset();
m_damageIntervalTimer.Reset();
DamageTarget();
enabled = true;
}
public void SetConfig(CorrosionConfig config)
{
m_damage = config.damage;
m_damageIntervalTimer.SetStartTime(config.damageInterval);
m_durationTimer.SetStartTime(config.duration);
}
private void DamageTarget() => GameplaySystem.GetRoutine<ICombatRoutine>().ApplyDamage(m_target, DamageFXType.None, m_damage);
private EventActionArgs OnDurationEnd(object sender, EventActionArgs eventArgs)
{
enabled = false;
return eventArgs;
}
private EventActionArgs OnIntervalEnd(object sender, EventActionArgs eventArgs)
{
DamageTarget();
return eventArgs;
}
private void Awake()
{
m_damageIntervalTimer.CountdownEnd += OnIntervalEnd;
m_durationTimer.CountdownEnd += OnDurationEnd;
enabled = false;
}
private void Start()
{
m_target = GetComponentInParent<IDamageable>();
}
private void Update()
{
var deltaTime = Time.deltaTime;
m_damageIntervalTimer.Tick(deltaTime);
m_durationTimer.Tick(deltaTime);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Movimiento : MonoBehaviour
{
public float Velocidad;
public GameObject Destino;
public GameObject Personaje;
public bool Ejecutando;
void Start ()
{
Ejecutando = false;
}
public IEnumerator Mostrar ()
{
Ejecutando = true;
float tiempoComienzo = Time.time;
Vector3 posicionComienzo = Personaje.transform.position;
while (Personaje.transform.position != Destino.transform.position) {
float distanciaCubierta = (Time.time - tiempoComienzo) * Velocidad;
float distanciaAObjetivo = Vector3.Distance (posicionComienzo, Destino.transform.position);
float fraccionViaje = distanciaCubierta / distanciaAObjetivo;
Personaje.transform.position = Vector3.Lerp (posicionComienzo, Destino.transform.position, fraccionViaje);
yield return new WaitForSeconds (0.01f);
}
Ejecutando = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThirdParty;
using Adv;
namespace UnitTestBadProject
{
public class TestExceptionThirdPartyService : IThirdPartyService
{
public Advertisement NoSqlGetAdv(string id)
{
throw new Exception("Test Exception");
}
public Advertisement SqlGetAdv(string id)
{
var advert = new Advertisement();
advert.Description = "SQL Advert Description";
advert.Name = "SQL Advert";
advert.WebId = id;
return advert;
}
}
}
|
using System.Collections;
using UnityEngine;
namespace QuestSystem
{
public interface IQuestGoal
{
string Title { get; }
string Description { get; set; }
bool IsComplete { get; }
bool IsSecondary { get; }
void UpdateProgress();
void CheckProgress(GameObject item);
}
}
|
using System;
using System.Configuration;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using upSight.CartaoCorp.Identificacao.ACSOIDTS;
namespace UnitTestCartaoCorp
{
[TestClass]
public class TesteIdentificacao
{
[TestMethod]
public void ImportaPlanilha()
{
var log = new upSight.Global.Log.CN.Logging();
log.IdEntidade = 1;
log.IdUsuario = 1;
IdentificacaoProcessamento imp = new IdentificacaoProcessamento();
imp.Log = log;
string arquivo = "TesteImpSimpf.xlsx";
string nomeArquivoCompleto = Path.Combine(ConfigurationManager.AppSettings["DiretotioOrigemACSOIDTS"], arquivo);
imp.LePlanilhaExcelEInsereDados(nomeArquivoCompleto);
}
}
}
|
using BoardGame.Domain_Model;
using BoardGame.DomainModel;
using System;
using System.Windows.Forms;
namespace BoardGame
{
public partial class PropertyCardForRobot : Form
{
public string FieldName { get; set; }
public int FieldValue { get; set; }
public int FieldFinishedValue { get; set; }
public int FieldBuildingTurns { get; set; }
public bool CantBuy { get; set; }
public bool IDontWannaBuy { get; set; }
private BoardGame m_BoardGame;
private Cards m_Cards;
private Player m_Player;
private Robot m_Robot1;
private Robot m_Robot2;
private Robot m_Robot3;
private Level m_Level;
private int m_Turn;
public PropertyCardForRobot(BoardGame boardGame, Player player, Robot robot1, Robot robot2, Robot robot3, Cards card, Level level)
{
InitializeComponent();
this.m_Level = level;
this.m_BoardGame = boardGame;
this.m_Player = player;
this.m_Robot1 = robot1;
this.m_Robot2 = robot2;
this.m_Robot3 = robot3;
this.m_Turn = boardGame.CurrentTurn;
this.m_Cards = card;
IDontWannaBuy = false;
CantBuy = false;
Random randomCard = new Random();
int randomCardNumber = randomCard.Next(0, m_Cards.PropertyCards.Count);
switch (m_Turn)
{
case 1: //robot1 turn
DrawingACardAndChangeTheTexts(randomCardNumber, m_Robot1);
break;
case 2: //robot2 turn
DrawingACardAndChangeTheTexts(randomCardNumber, m_Robot2);
break;
case 3: //robot3 turn
DrawingACardAndChangeTheTexts(randomCardNumber, m_Robot3);
break;
default:
throw new Exception("Turn is not exist");
}
}
private void Ok_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
this.Close();
}
private void DrawingACardAndChangeTheTexts(int randomCardNumber, Robot m_Robot)
{
PlayerOrRobotName.Text = m_Robot.Name;
for (int i = 0; i < m_Cards.PropertyCards.Count; i++)
{
if (i == randomCardNumber)
{
CardText.Text = "Gratulálok! Felfedeztél egy " + m_Cards.PropertyCards[i].PropertyName + "-t.";
TurnText.Text = "A feltárásának idelye: " + m_Cards.PropertyCards[i].BuildingTurns + " kör.";
FinishedValue.Text = "Ammennyiben elvégezted " + m_Cards.PropertyCards[i].PropertyFinishedValue + "$-t kapsz.";
Price.Text = m_Cards.PropertyCards[i].PropertyValue + "$";
if (ImSmartRobot())
{
if (IsItARightDecession(m_Robot, m_Cards.PropertyCards[i].PropertyValue, m_Cards.PropertyCards[i].PropertyFinishedValue))
{
BuyProperty(i, m_Robot);
}
else
{
IDontWannaBuy = true;
}
}
else
{
if (m_Robot.Balance >= m_Cards.PropertyCards[i].PropertyValue)
{
BuyProperty(i, m_Robot);
}
else
{
CantBuy = true;
}
}
}
}
}
private bool ImSmartRobot()
{
if (m_Level.LevelType == Levels.Nehéz)
{
return true;
}
else if (m_Level.LevelType == Levels.Könnyű)
{
return false;
}
else
{
throw new Exception("This level is not exists: " + m_Level.LevelType.ToString());
}
}
public bool IsItARightDecession(Robot currentRobot, int cardPrice, int cardFinishedValue)
{
double playerCanPayMe = PlayerCanPayMe(currentRobot, cardFinishedValue);//avg
double robotsCanPayMe = RobotsCanPayMe(currentRobot, cardFinishedValue);//avg
double iMightWinXCash = playerCanPayMe + robotsCanPayMe; //the robot might win ? cash, the others can pay him (the next 1-12 property)
double iMightLoseXCash = ICanLose(currentRobot); //the robot might lose ? cash in his next turn (the next 1-12 property)
int theMaxValueThatIShouldPay = GetTheMaximumBill(currentRobot);
int theNumberOfNotFreeDestinations = CountNotFreeDestinations(currentRobot);
if (theNumberOfNotFreeDestinations <= 6)
{
if (theMaxValueThatIShouldPay <= (currentRobot.Balance - cardPrice))
{
if (iMightLoseXCash <= iMightWinXCash)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public void BuyProperty(int i, Robot m_Robot)
{
FieldFinishedValue = m_Cards.PropertyCards[i].PropertyFinishedValue;
FieldValue = m_Cards.PropertyCards[i].PropertyValue;
FieldName = m_Cards.PropertyCards[i].PropertyName;
FieldBuildingTurns = m_Cards.PropertyCards[i].BuildingTurns;
m_Robot.MyPropertyCards.Add(m_Cards.PropertyCards[i]);
m_Cards.PropertyCards.RemoveAt(i);
}
public double PlayerCanPayMe(Robot robot, int cardFinishedValue)
{
return GetCalculationFor(m_Player, robot, cardFinishedValue);
}
public double RobotsCanPayMe(Robot robot, int cardFinishedValue)
{
double sum = 0;
if (robot.Name == m_Robot1.Name)
{
sum += GetCalculationFor(m_Robot2, robot, cardFinishedValue);
sum += GetCalculationFor(m_Robot3, robot, cardFinishedValue);
}
else if (robot.Name == m_Robot2.Name)
{
sum += GetCalculationFor(m_Robot1, robot, cardFinishedValue);
sum += GetCalculationFor(m_Robot3, robot, cardFinishedValue);
}
else if (robot.Name == m_Robot3.Name)
{
sum += GetCalculationFor(m_Robot1, robot, cardFinishedValue);
sum += GetCalculationFor(m_Robot2, robot, cardFinishedValue);
}
return sum;
}
public double GetCalculationFor(Player selectedPlayerOrRobot, Robot robot, int cardFinishedValue)
{
int value = 0;
int counter = 0;
for (int i = 0; i < m_BoardGame.OwnedProperties.Count; i++)
{
if (TheOwnedFieldLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(selectedPlayerOrRobot.CurrentPosition, i))
{
if (m_BoardGame.OwnedProperties[i].FieldOwner == robot)
{
value += GetValueInCaseOfPlayers(value, i, robot);
counter++;
}
}
}
if (TheOwnedCurrentPropertyLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(selectedPlayerOrRobot.CurrentPosition,robot.CurrentPosition))
{
value += (int)Math.Round(cardFinishedValue * 0.25);
counter++;
}
if (!selectedPlayerOrRobot.Loser && selectedPlayerOrRobot.CanNotRollForXTurn == 0)
{
if (counter > 0)
{
double get = value / counter;
return get;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
public int GetValueInCaseOfPlayers(int value, int i, Robot robot)
{
if (m_BoardGame.OwnedProperties[i].FinishedField)
{
value += (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.4);
}
else if (m_BoardGame.OwnedProperties[i].StartedField)
{
value += (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.25);
}
else
{
value = 0;
}
return value;
}
public int CountNotFreeDestinations(Robot robot)
{
int notFreeDestinationsCounter = 0;
for (int i = 0; i < m_BoardGame.OwnedProperties.Count; i++)
{
if (TheOwnedFieldLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(robot.CurrentPosition, i))
{
if (m_BoardGame.OwnedProperties[i].FieldOwner != robot)
{
notFreeDestinationsCounter++;
}
}
}
return notFreeDestinationsCounter;
}
public int GetTheMaximumBill(Robot robot)
{
int maxBill = 0;
for (int i = 0; i < m_BoardGame.OwnedProperties.Count; i++)
{
if (TheOwnedFieldLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(robot.CurrentPosition, i))
{
maxBill = GetMax(i, maxBill, robot);
}
}
return maxBill;
}
public int GetMax(int i, int maxBill, Robot robot)
{
if (m_BoardGame.OwnedProperties[i].FieldOwner != robot)
{
if (m_BoardGame.OwnedProperties[i].FinishedField)
{
if (maxBill < (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.4))
{
maxBill = (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.4);
}
}
else if (m_BoardGame.OwnedProperties[i].StartedField)
{
if (maxBill < (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.25))
{
maxBill = (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.25);
}
}
else
{
maxBill = 0;
}
}
return maxBill;
}
public double ICanLose(Robot robot)
{
int value = 0;
int counter = 0;
for (int i = 0; i < m_BoardGame.OwnedProperties.Count; i++)
{
if (TheOwnedFieldLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(robot.CurrentPosition, i))
{
value += GetValueInCaseOfCurrentRobot(value, i, robot);
counter++;
}
}
if (counter>0)
{
return value / counter;
}
else
{
return 0;
}
}
private int GetValueInCaseOfCurrentRobot(int value, int i, Robot robot)
{
if (m_BoardGame.OwnedProperties[i].FieldOwner != robot)
{
if (m_BoardGame.OwnedProperties[i].FinishedField)
{
value += (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.4);
}
else if (m_BoardGame.OwnedProperties[i].StartedField)
{
value += (int)Math.Round(m_BoardGame.OwnedProperties[i].FieldFinishedValue * 0.25);
}
else
{
value = 0;
}
}
return value;
}
private bool TheOwnedFieldLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(int playerCurrentPosition, int i)
{
if (playerCurrentPosition + 12 >= m_BoardGame.OwnedProperties[i].FieldLocation && playerCurrentPosition < m_BoardGame.OwnedProperties[i].FieldLocation)
{
return true;
}
else
{
return false;
}
}
private bool TheOwnedCurrentPropertyLocationIsBetweenThePlayerCurrentPositionAndThePlayerCurrentPositionPlus12(int playerCurrentPosition, int robotCurrentPosition)
{
if (playerCurrentPosition + 12 >= robotCurrentPosition && playerCurrentPosition < robotCurrentPosition)
{
return true;
}
else
{
return false;
}
}
}
}
|
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.PageLocation.Models;
using DFC.ServiceTaxonomy.PageLocation.ViewModels;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.DisplayManagement.Views;
namespace DFC.ServiceTaxonomy.PageLocation.Drivers
{
public class PageLocationPartSettingsDisplayDriver : ContentTypePartDefinitionDisplayDriver
{
public override IDisplayResult Edit(ContentTypePartDefinition contentTypePartDefinition)
{
if (!string.Equals(nameof(PageLocationPart), contentTypePartDefinition.PartDefinition.Name))
{
return default!;
}
return Initialize<PageLocationPartSettingsViewModel>("PageLocationPartSettings_Edit", model =>
{
PageLocationPartSettings settings = contentTypePartDefinition.GetSettings<PageLocationPartSettings>();
model.DisplayRedirectLocationsAndDefaultPageForLocation = settings.DisplayRedirectLocationsAndDefaultPageForLocation;
model.DefaultPageLocationPath = settings.DefaultPageLocationPath;
})
.Location("Content");
}
public override async Task<IDisplayResult?> UpdateAsync(ContentTypePartDefinition contentTypePartDefinition, UpdateTypePartEditorContext context)
{
if (!string.Equals(nameof(PageLocationPart), contentTypePartDefinition.PartDefinition.Name))
{
return null;
}
var model = new PageLocationPartSettingsViewModel();
await context.Updater.TryUpdateModelAsync(model, Prefix,
m => m.DisplayRedirectLocationsAndDefaultPageForLocation,
m => m.DefaultPageLocationPath);
context.Builder.WithSettings(new PageLocationPartSettings
{
DisplayRedirectLocationsAndDefaultPageForLocation = model.DisplayRedirectLocationsAndDefaultPageForLocation,
DefaultPageLocationPath = model.DefaultPageLocationPath
});
return await EditAsync(contentTypePartDefinition, context.Updater);
}
}
}
|
//Weight Sum Of Digits
public void WeightSumOfDigits(List<string> readInList)
{
string[] tempArray = null;
int final = 0;
List<int> list = new List<int>();
foreach (string x in readInList)
{
tempArray = x.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string y in tempArray)
{
int tempVal = 0;
for (int z = 0; z < y.Length; z++)
{
Int32.TryParse(y[z].ToString(), out tempVal);
z++;
final = final + (tempVal * z);
z--;
}
Console.Write(final + " ");
final = 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ELearningPlatform.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace ELearningPlatform.Data
{
public class ELearningPlatformContext : IdentityDbContext
{
public ELearningPlatformContext (DbContextOptions<ELearningPlatformContext> options)
: base(options)
{
}
public DbSet<ELearningPlatform.Models.Course> Course { get; set; }
public DbSet<ELearningPlatform.Models.User> User { get; set; }
public DbSet<ELearningPlatform.Models.Token> Token { get; set; }
public DbSet<ELearningPlatform.Models.Role> Role { get; set; }
public DbSet<ELearningPlatform.Models.Completed> Completed { get; set; }
public DbSet<ELearningPlatform.Models.Content> Content { get; set; }
public DbSet<ELearningPlatform.Models.Inscription> Inscription { get; set; }
public DbSet<ELearningPlatform.Models.Module> Module { get; set; }
public DbSet<ELearningPlatform.Models.Subject> Subject { get; set; }
}
}
|
using StarBastardCore.Website.Code.Game.Gameplay;
namespace StarBastardCore.Website.Code.Game.Gameworld.Geography.Buildings
{
public class ScienceLab : BuildingBase
{
public override Resources PlayerBenefit { get { return new Resources(0, 0, 4); } }
public override Resources ConstructionCost { get { return new Resources(0, 4, 0); } }
}
} |
using System;
using System.Windows.Controls;
using System.Windows.Media;
using VMDiagrammer.Helpers;
namespace VMDiagrammer.Models
{
/// <summary>
/// Class definition for the point force
/// </summary>
public class VM_PointForce : VM_BaseLoad
{
public VM_PointForce(VM_Beam beam, double d1, double d2, double w1, double w2) : base(beam, LoadTypes.LOADTYPE_CONC_FORCE, d1, d2, w1, w2, 3.0)
{
if (D1 != D2)
throw new NotImplementedException("D1 = " + D1 + " and D2 = " + D2 + " -- dimensions muse be the same for a point force");
if (W1 != W2)
throw new NotImplementedException("W1 = " + W1 + " and W2 = " + W2 + " -- intensities muse be the same for a point force");
}
public override void Draw(Canvas c)
{
double len1 = Math.Abs(W1);
if (W1 < 0)
DrawingHelpers.DrawArrow(c, Beam.Start.X + D1, Beam.Start.Y, Brushes.Blue, Brushes.Blue, ArrowDirections.ARROW_DOWN, this.ArrowThickness, len1 );
else
DrawingHelpers.DrawArrow(c, Beam.Start.X + D1, Beam.Start.Y, Brushes.Blue, Brushes.Blue, ArrowDirections.ARROW_UP, this.ArrowThickness, len1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Nailhang.Display.Tools.TextSearch.Base;
namespace Nailhang.Display.Tools.TextSearch.Processing
{
class StatBuilder : IWSBuilder
{
private static void NextWord(string word, Statistics res)
{
foreach (var c in word.ToLower())
{
if (!char.IsLetter(c))
continue;
CharStat stat;
if (!res.CharStats.TryGetValue(c, out stat))
res.CharStats[c] = stat = new CharStat(c);
stat.Count++;
}
}
public Statistics BuildStatistics(IEnumerable<string> lines)
{
var res = new Statistics();
foreach (var name in lines)
foreach (var s in name.Split(new char[] { ' ' }))
NextWord(s, res);
res.Codes = res.CharStats
.OrderByDescending(q => q.Value.Count)
.Select(q => q.Value)
.Take(255).ToArray();
for (int i = 0; i < res.Codes.Length; ++i)
res.ToCode[res.Codes[i].Char] = (byte)i;
foreach (var i in res.Codes.Select(q => q.Char))
res.Coded.Add(i);
return res;
}
IStat IWSBuilder.BuildStat(IEnumerable<string> lines)
{
return BuildStatistics(lines);
}
public ISearch CreateSearch(IIndex index)
{
return new Search((Index)index);
}
public IIndex Index(IEnumerable<Bulk> bulks, IStat stat)
{
var index = new Index((Statistics)stat);
foreach (var b in bulks)
index.Run(b);
long memory = 0;
foreach(var tv in index.triplets)
{
memory += 4; // на ключ
memory += tv.Value.Bulks.Count * 4;
}
Console.WriteLine($"Index builded: memory usage {memory}");
return index;
}
}
}
|
using NerdStore.Catalog.Application.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NerdStore.Catalog.Application.Services
{
public interface IProductAppService
{
Task<IEnumerable<ProductViewModel>> GetByCategoryCode(int codigo);
Task<ProductViewModel> GetById(Guid id);
Task<IEnumerable<ProductViewModel>> GetAll();
Task<IEnumerable<ProductViewModel>> GetCategories();
Task AddProduct(ProductViewModel productViewModel);
Task UpdateProduct(ProductViewModel productViewModel);
Task<ProductViewModel> DebitStock(Guid id, int quantity);
Task<ProductViewModel> CreditStock(Guid id, int quantity);
}
}
|
namespace Nan.Extensions.Information
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
/// <summary>
/// 取得插件的附加資訊
/// </summary>
internal static class ExtensionInfo
{
/// <summary>
/// 取得插件作者
/// </summary>
/// <param name="extension">插件</param>
/// <returns></returns>
public static string GetExtensionAuthor(this IExtension extension)
=> getAttribute<ExtensionAuthorAttribute>(extension).Author;
/// <summary>
/// 取得插件名稱
/// </summary>
/// <param name="extension">插件</param>
/// <returns></returns>
public static string GetExtensionName(this IExtension extension)
=> getAttribute<ExtensionNameAttribute>(extension).Name;
/// <summary>
/// 取得插件描述
/// </summary>
/// <param name="extension">插件</param>
/// <returns></returns>
public static string GetExtensionDescription(this IExtension extension)
=> getAttribute<ExtensionDescriptionAttribute>(extension).Description;
private static A getAttribute<A>(IExtension e) where A : Attribute
=> e.GetType().GetCustomAttributes<A>().SingleOrDefault();
}
} |
using Cti.Platform.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReiEventTest.Events
{
public abstract class ValidationEventBase : ControlFieldEventBase
{
public String Validator { get; set; }
public String Message { get; set; }
}
}
|
namespace TripDestination.Web.MVC.Areas.Admin.Controllers
{
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using TripDestination.Services.Data.Contracts;
using TripDestination.Web.MVC.Areas.Admin.ViewModels;
using TripDestination.Common.Infrastructure.Mapping;
using MVC.Controllers;
public class PageAdminController : BaseController
{
private IPageServices pageServices;
public PageAdminController(IPageServices pageServices)
{
this.pageServices = pageServices;
}
public ActionResult Index()
{
return this.View();
}
public ActionResult Pages_Read([DataSourceRequest]DataSourceRequest request)
{
var result = this.pageServices
.GetAll()
.To<PageAdminViewModel>()
.ToDataSourceResult(request);
return this.Json(result);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Pages_Create([DataSourceRequest]DataSourceRequest request, PageAdminViewModel page)
{
if (this.ModelState.IsValid)
{
var dbPage = this.pageServices.Create(page.Heading, page.SubHeading, page.Layout);
page.Id = dbPage.Id;
}
return this.Json(new[] { page }.ToDataSourceResult(request, this.ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Pages_Update([DataSourceRequest]DataSourceRequest request, PageAdminViewModel page)
{
if (this.ModelState.IsValid)
{
this.pageServices.Edit(page.Id, page.Heading, page.SubHeading, page.Layout);
}
return this.Json(new[] { page }.ToDataSourceResult(request, this.ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Pages_Destroy([DataSourceRequest]DataSourceRequest request, PageAdminViewModel page)
{
if (this.ModelState.IsValid)
{
this.pageServices.Delete(page.Id);
}
return this.Json(new[] { page }.ToDataSourceResult(request, this.ModelState));
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
}
|
using Terraria;
using Terraria.ModLoader;
namespace ReducedGrinding.Items
{
public class Gold_Reflection_Mirror : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Gold Reflection Mirror");
Tooltip.SetDefault("Used to transform some Critters into Golden Critters.");
}
public override void SetDefaults()
{
item.width = 32;
item.height = 32;
item.maxStack = 1;
item.value = Item.buyPrice(0, 12);
item.rare = 0;
}
}
} |
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.Configuration;
namespace serin
{
public partial class NewUser : Form
{
SqlConnection conn = new SqlConnection(@"Data Source = .\SQLEXPRESS; Initial Catalog = serin; Integrated Security = True");
public NewUser()
{
InitializeComponent();
}
private void btn_Record_Click(object sender, EventArgs e)
{
if(txt_Password.Text == txt_PasswordAgain.Text) {
conn.Open();
string query = "INSERT INTO dbo.UserList (UserName, UserPassword, EmailAddress, SystemDate) " +
"VALUES (@UserNames, @Password, @Email, GETDATE()) ";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@UserNames", txt_UserName.Text);
cmd.Parameters.AddWithValue("@Password", txt_Password.Text);
cmd.Parameters.AddWithValue("@Email", txt_EmailAddress.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Kayıt işlemi başarılı.");
this.Close();
}
else
{
MessageBox.Show("Şifreler uyuşmamaktadır.");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/**
* Controls all logic for mechanical hand
* Including user input, sending messages to grappling hook, interaction etc.
*/
public class MechHandController : Controller
{
//if the mech hand is colliding with something
public bool colliding;
//win text
public Text winText;
//current state of the mech hand
public MechHandState state;
//how strong the throw is
public float throwForce;
//material of sphere
public Material sphereMat;
public Color defaultColor;
[Header("Sounds")]
//grappling hook shoot sound
public AudioSource shootSound;
public AudioSource pullSound;
public AudioSource throwSound;
//Reference to grappling hook controller
private GrapplingHookController grapHookController;
//held Interactable
private Interactable heldItem;
//potential held Interactable
private Interactable potentialHeld;
//references to IK targets
private Transform indexTarget;
private Transform middleTarget;
private Transform ringTarget;
private Transform littleTarget;
private Transform thumbTarget;
//original IK positions
private Vector3 indexOrig;
private Vector3 middleOrig;
private Vector3 ringOrig;
private Vector3 littleOrig;
private Vector3 thumbOrig;
//reticle transform
private Transform reticleTransform;
void Start()
{
sphereMat.SetColor("_EmissionColor", defaultColor);
grapHookController = GetComponent<GrapplingHookController>();
state = MechHandState.Empty;
//IK setup stuff
indexTarget = transform.Find("TargetPoles").Find("IndexTarget");
middleTarget = transform.Find("TargetPoles").Find("MiddleTarget");
ringTarget = transform.Find("TargetPoles").Find("RingTarget");
littleTarget = transform.Find("TargetPoles").Find("LittleTarget");
thumbTarget = transform.Find("TargetPoles").Find("ThumbTarget");
//Original positions
indexOrig = indexTarget.localPosition;
middleOrig = middleTarget.localPosition;
ringOrig = ringTarget.localPosition;
littleOrig = littleTarget.localPosition;
thumbOrig = thumbTarget.localPosition;
}
void Update()
{
//For Controller
CalculateDeltas();
//Empty hand interactions (grappling hook)
if (state == MechHandState.Empty)
{
//Extend from inactive
if (Input.GetMouseButtonDown(0) && grapHookController.State == GrapplingHookState.Inactive)
{
StartCoroutine(grapHookController.Extend());
shootSound.Play();
}
//Retract from hooked
if (Input.GetMouseButtonDown(0) && (grapHookController.State == GrapplingHookState.Hooked
|| grapHookController.State == GrapplingHookState.InAir
|| grapHookController.State == GrapplingHookState.Held))
{
grapHookController.dontBring = true;
StartCoroutine(grapHookController.Retract());
pullSound.Play();
}
//Retract and bring object
if (Input.GetMouseButtonDown(2) && grapHookController.State == GrapplingHookState.Held)
{
StartCoroutine(grapHookController.Retract());
pullSound.Play();
}
//Pull towards hooked position
if (Input.GetMouseButtonDown(1) && grapHookController.State == GrapplingHookState.Hooked)
{
StartCoroutine(grapHookController.Pull());
pullSound.Play();
}
}
//Held item interactions
if (state == MechHandState.Holding)
{
if (Input.GetMouseButtonDown(0))
{
throwSound.Play();
LaunchInteractable();
}
if (Input.GetMouseButtonDown(2))
{
DetachInteractable();
}
}
//In reach interactions
if (state == MechHandState.InReach)
{
if (Input.GetMouseButtonDown(0))
{
AttachInteractable();
}
}
}
public override void Detach()
{
heldItem = null;
state = MechHandState.Empty;
IKGrab(false);
}
public void TakeFromActualHook(Interactable i)
{
heldItem = i;
state = MechHandState.Holding;
i.SwitchController(this);
IKGrab(true);
}
private void LaunchInteractable()
{
heldItem.DetachController();
heldItem.gameObject.GetComponent<Rigidbody>().AddForce(transform.forward * throwForce, ForceMode.Impulse);
heldItem = null;
state = MechHandState.Empty;
IKGrab(false);
}
private void AttachInteractable()
{
heldItem = potentialHeld;
heldItem.AttachController(this);
potentialHeld = null;
state = MechHandState.Holding;
IKGrab(true);
}
private void DetachInteractable()
{
heldItem.DetachController();
heldItem = null;
state = MechHandState.Empty;
IKGrab(false);
}
/*
* Takes care of the IK animation for grabbing
* @param grab true if grabbing, false if releasing grab
*/
private void IKGrab(bool grab)
{
//Sets the new IK target to be approximately on the surface of the Interactable
if (grab)
{
var distance = heldItem.gameObject.transform.position - indexTarget.position;
distance.x = 0; distance.z = 0;
distance.y = distance.y + heldItem.gameObject.transform.localScale.y / 2;
indexTarget.position += distance;
middleTarget.position += distance;
ringTarget.position += distance;
littleTarget.position += distance;
}
//letting go
else
{
indexTarget.localPosition = indexOrig;
middleTarget.localPosition = middleOrig;
ringTarget.localPosition = ringOrig;
littleTarget.localPosition = littleOrig;
}
}
void OnTriggerEnter(Collider other)
{
colliding = true;
//Mech hand's collider includes the grappling hook's collider
//and I don't know how to get it to stop so this'll have to do
if (grapHookController.State == GrapplingHookState.Inactive)
{
if (other.gameObject.GetComponent<Interactable>())
{
state = MechHandState.InReach;
potentialHeld = other.gameObject.GetComponent<Interactable>();
}
}
//a winner is you
if (other.gameObject.name == "WinRoom")
{
winText.text = "You reached the last room! \n You Win!";
}
}
void OnTriggerExit(Collider other)
{
//Mech hand's collider includes the grappling hook's collider
//and I don't know how to get it to stop so this'll have to do
if (grapHookController.State == GrapplingHookState.Inactive)
{
if (other.gameObject.GetComponent<Interactable>())
{
state = MechHandState.Empty;
potentialHeld = null;
}
}
}
}
public enum MechHandState
{
Empty, //hand is empty, will shoot grappling hook
Holding, //hand is holding Interactable, will not shoot hook, will throw/drop Interactable
InReach //hand is in reach of Interactable, will not shoot hook, will grab Interactable
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Journey.WebApp.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Journey.WebApp.Controllers
{
public class TripActivitiesController : Controller
{
private readonly JourneyDBContext _context;
public TripActivitiesController(JourneyDBContext context)
{
_context = context;
}
public async Task<IActionResult> Create(long? id)
{
if (id == null)
{
return NotFound();
}
var tripActivities = new TripActivities();
tripActivities.TripDetailsId = (long)id;
var td = await _context.TripDetails.FindAsync(id);
ViewBag.tripCityId = td.TripCitiesId;
return View("Edit", tripActivities);
}
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var tripActivities = await _context.TripActivities.Include(ta => ta.TripDetails)
.FirstOrDefaultAsync(ta => ta.Id == id);
if (tripActivities == null)
{
return NotFound();
}
ViewBag.tripCityId = tripActivities.TripDetails.TripCitiesId;
return View(tripActivities);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(TripActivities tripActivities)
{
if (ModelState.IsValid)
{
if (tripActivities.Id == 0)
{
_context.Add(tripActivities);
}
else
{
_context.Update(tripActivities);
}
await _context.SaveChangesAsync();
var td = await _context.TripDetails.FindAsync(tripActivities.TripDetailsId);
return RedirectToAction("Details", "TripCities", new { id = td.TripCitiesId });
}
return View(tripActivities);
}
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
var tripActivities = await _context.TripActivities.FirstOrDefaultAsync(tc => tc.Id == id);
if (tripActivities == null)
{
return NotFound();
}
//ViewBag.city = tripActivities.TripCities.City.CityName;
return View(tripActivities);
}
// POST: TravelersTrips/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
var tripActivities = await _context.TripActivities.Include(ta => ta.TripDetails)
.FirstOrDefaultAsync(tc => tc.Id == id);
_context.TripActivities.Remove(tripActivities);
await _context.SaveChangesAsync();
return RedirectToAction("Details", "TripCities", new { id = tripActivities.TripDetails.TripCitiesId });
}
}
} |
using Exiled.API.Interfaces;
namespace CustomTeslaDamage
{
public class Config : IConfig
{
public bool IsEnabled { get; set; } = true;
public float TeslaDamage { get; set; } = 2000;
public float TeslaDamageRange { get; set; } = 200;
}
}
|
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using MigrationTools.Core.Configuration;
using MigrationTools.Core.DataContracts;
using MigrationTools.Core.Sinks;
using System;
using System.Collections.Generic;
using System.Text;
namespace MigrationTools.Sinks.AzureDevOps
{
public class AzureDevOpsWorkItemSink : IWorkItemSink
{
public AzureDevOpsWorkItemSink(IHost host, ILogger<MigrationEngine> log, TelemetryClient telemetry, EngineConfiguration config)
{
}
public IEnumerable<WorkItemData> GetWorkItems()
{
throw new NotImplementedException();
}
public WorkItemData PersistWorkItem(WorkItemData workItem)
{
throw new NotImplementedException();
}
}
}
|
#if NET6_0_OR_GREATER
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
namespace Sentry.AspNetCore.Tests;
[UsesVerify]
public class WebIntegrationTests
{
private readonly TestOutputDiagnosticLogger _logger;
public WebIntegrationTests(ITestOutputHelper output)
{
_logger = new(output);
}
[Fact]
public async Task Versioning()
{
// Arrange
var transport = new RecordingTransport();
using var server = new TestServer(
new WebHostBuilder()
.UseSentry(o =>
{
o.Dsn = ValidDsn;
o.TracesSampleRate = 1;
o.Transport = transport;
o.Debug = true;
o.DiagnosticLogger = _logger;
// Disable process exit flush to resolve "There is no currently active test." errors.
o.DisableAppDomainProcessExitFlush();
})
.ConfigureServices(services =>
{
services.AddRouting();
var controllers = services.AddControllers();
controllers.UseSpecificControllers(typeof(VersionController));
services.AddApiVersioning(versioningOptions =>
{
versioningOptions.DefaultApiVersion = new ApiVersion(1, 0);
versioningOptions.AssumeDefaultVersionWhenUnspecified = true;
versioningOptions.ReportApiVersions = true;
});
})
.Configure(app =>
{
app.UseRouting();
app.UseSentryTracing();
app.UseEndpoints(routeBuilder => routeBuilder.MapControllers());
}));
var client = server.CreateClient();
// Act
var result = await client.GetStringAsync("/v1.1/Target");
// dispose will ultimately trigger the background worker to flush
server.Dispose();
await Verify(new {result, transport.Payloads})
.IgnoreStandardSentryMembers()
.ScrubAspMembers();
}
[ApiController]
[Route("v{version:apiVersion}/Target")]
[ApiVersion("1.1")]
public class VersionController : ControllerBase
{
[HttpGet]
public string Method()
{
return "Hello world";
}
}
[Fact]
public async Task PreFlightIgnoresTransaction()
{
// Arrange
var transport = new RecordingTransport();
using var server = new TestServer(
new WebHostBuilder()
.UseSentry(o =>
{
o.Dsn = ValidDsn;
o.TracesSampleRate = 1;
o.Transport = transport;
o.Debug = true;
o.DiagnosticLogger = _logger;
// Disable process exit flush to resolve "There is no currently active test." errors.
o.DisableAppDomainProcessExitFlush();
})
.ConfigureServices(services =>
{
services.AddRouting();
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
var controllers = services.AddControllers();
controllers.UseSpecificControllers(typeof(TransactionController));
})
.Configure(app =>
{
app.UseRouting();
app.UseSentryTracing();
app.UseCors();
app.UseEndpoints(_ => _.MapControllers());
}));
var client = server.CreateClient();
// Act
var request = new HttpRequestMessage(HttpMethod.Options, "/Target");
request.Headers.Add("Access-Control-Request-Headers", "origin");
request.Headers.Add("Access-Control-Request-Method", "GET");
request.Headers.Add("Origin", "https://sentry.io/foo");
var result = await client.SendAsync(request);
// dispose will ultimately trigger the background worker to flush
server.Dispose();
await Verify(new {result, transport.Payloads})
.IgnoreStandardSentryMembers()
.ScrubAspMembers();
}
[ApiController]
[Route("Target")]
public class TransactionController : ControllerBase
{
[HttpGet]
public string Method()
{
SentrySdk.ConfigureScope(scope => scope.TransactionName = "TheTransaction");
return "Hello world";
}
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pjank.BossaAPI
{
public enum BosOrderSide
{
Buy,
Sell,
}
}
|
using System;
using System.Text.RegularExpressions;
namespace Registration
{
class Program
{
static void Main(string[] args)
{
var regex = @"U\$([A-Z][a-z]{2,})U\$P\@\$([A-Za-z]{5,}\d+)P\@\$";
var numberOfLines = int.Parse(Console.ReadLine());
var numberOfRegistrations = 0;
for (int i = 0; i < numberOfLines; i++)
{
var username = Console.ReadLine();
if (Regex.IsMatch(username,regex))
{
Console.WriteLine("Registration was successful");
Console.WriteLine($"Username: {Regex.Match(username,regex).Groups[1]}, Password: {Regex.Match(username, regex).Groups[2]}");
numberOfRegistrations++;
}
else
{
Console.WriteLine("Invalid username or password");
}
}
Console.WriteLine($"Successful registrations: {numberOfRegistrations}");
}
}
}
|
using System;
namespace WEBTeste.Util
{
public class TratarString
{
public string RetirarAcentos(string pString)
{
string LdsRetorno;
LdsRetorno = pString.Replace("Á", "A").Replace("Ã", "A").Replace("Â", "A").Replace("Ê", "E").Replace("É", "E").Replace("Í", "I").Replace("Õ", "O");
LdsRetorno = LdsRetorno.Replace("Ó", "O").Replace("Ô", "O").Replace("Ú", "U").Replace("Ç", "C");
return LdsRetorno;
}
public string RetirarEspecial(string pString)
{
string LdsRetorno = "";
int i, LcodAsc;
for (i = 0;i < pString.Length;i++)
{
LcodAsc = (int) pString[i] + 0;
if ((LcodAsc > 64 && LcodAsc < 91) || LcodAsc == 32)
LdsRetorno += pString.Substring( i, 1);
}
return LdsRetorno;
}
public string RetirarEspLetra(string pNumero)
{
string LdsRetorno = "";
int i, LcodAsc;
for (i = 0; i < pNumero.Length; i++)
{
LcodAsc = (int)pNumero[i] + 0;
if ((LcodAsc >= 48 && LcodAsc < 58))
LdsRetorno += pNumero.Substring(i, 1);
}
return LdsRetorno;
}
public string RetirarEspacos(string pString)
{
string LdsRetorno = "";
string[] LdsAssunto;
int i, LqtPalavra;
try
{
LqtPalavra = 0;
LdsAssunto = pString.Split(' ');
for (i = 0; i < LdsAssunto.Length - 1; i++)
{
if (LdsAssunto.GetValue(i).ToString().Length > 4)
{
LdsRetorno = LdsRetorno + LdsAssunto.GetValue(i).ToString();
LqtPalavra = LqtPalavra + 1;
}
if (LqtPalavra == 2)
break;
}
}
catch (Exception ex)
{
throw ex;
}
return LdsRetorno;
}
public string[] SepararPalavra(string pString)
{
string[] LdsRetorno;
string[] LstPalavra;
int i, LqtPalavra;
try
{
LqtPalavra = 0;
LstPalavra = pString.Split(' ');
LdsRetorno = new string[LstPalavra.Length];
for (i = 0; i < LstPalavra.Length; i++)
{
LdsRetorno.SetValue("", i);
if (LstPalavra.GetValue(i).ToString().Length >= 3)
{
LdsRetorno.SetValue(LstPalavra.GetValue(i).ToString(), LqtPalavra);
LqtPalavra = LqtPalavra + 1;
}
if (LqtPalavra == 3)
break;
}
}
catch (Exception ex)
{
throw ex;
}
return LdsRetorno;
}
}
} |
using System;
using System.Collections.Generic;
namespace Fbtc.Domain.Entities
{
public class Associado : Pessoa
{
public int AssociadoId { get; set; }
public int? ATCId { get; set; }
public int TipoPublicoId { get; set; }
public string NrMatricula { get; set; }
public string Crp { get; set; }
public string Crm { get; set; }
public string NomeInstFormacao { get; set; }
public bool Certificado { get; set; }
public DateTime? DtCertificacao { get; set; }
public bool DivulgarContato { get; set; }
public string TipoFormaContato { get; set; }
public string NrTelDivulgacao { get; set; }
public string ComprovanteAfiliacaoAtc { get; set; }
public string TipoProfissao { get; set; }
public string TipoTitulacao { get; set; }
}
public class AssociadoDao : Associado
{
public bool MembroDiretoria { get; set; }
public bool AnuidadeAtcOk { get; set; }
public bool MembroConfi { get; set; }
}
public class AssociadoAdimplenteDao
{
public int AssociadoId { get; set; }
public string Nome { get; set; }
public string NomeTipoPublico { get; set; }
public string Certificado { get; set; }
public string NomeCidade { get; set; }
public string SiglaEstado { get; set; }
public string EMail { get; set; }
public string NomeFoto { get; set; }
public string NomeProfissao { get; set; }
public string Sexo { get; set; }
}
public class ResultadoConAssociadoAdimplenteDao
{
public int NumPage { get; set; }
public int PageSize { get; set; }
public Decimal QtdTotalPages { get; set; }
public int QuantTotalRegistros { get; set; }
public string MsgRetorno { get; set; }
public IEnumerable<AssociadoAdimplenteDao> AssociadoAdimplenteDaos { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class PopupMainMenu : PopupWindow {
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdventureWorks.Business.POCOGenerator
{
[Flags]
public enum CommentsStyle
{
None,
InSummaryBlock,
AtEndOfField
};
// Settings to allow selective code generation
[Flags]
public enum Elements
{
None = 0,
Poco = 1,
Context = 2,
UnitOfWork = 4,
PocoConfiguration = 8
};
public class EnumDefinition
{
public string Schema;
public string Table;
public string Column;
public string EnumType;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProgrammingCSharpDemos.Models
{
public class Degree
{
public Degree()
{
this.Courses = new List<Course>();
}
public int UProgram { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Authority { get; set; }
//Navigation
public virtual List<Course> Courses { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Week4.ZoekertjesApp.DataAccess;
using ZoekertjesModels;
namespace Week4.ZoekertjesApp.Controllers
{
public class LocatieController : ApiController
{
public List<Locatie> Get()
{
return Data.GetLocaties();
}
}
}
|
using FluentAssertions;
using NUnit.Framework;
namespace Beeffective.Tests.Data.Entities.CellEntityTests
{
class Urgency : TestFixture
{
[SetUp]
public override void SetUp()
{
base.SetUp();
Sut.Urgency = Urgency;
}
[Test]
public void IsSet() =>
Sut.Urgency.Should().Be(Urgency);
}
} |
namespace Nan.Configuration.Notification
{
/// <summary>
/// 表示處理設定檔上欄位變更時所引發的 <seealso cref="INotifyFieldOperated.FieldOperated"/> 事件的方法。
/// </summary>
/// <param name="sender">事件的來源。</param>
/// <param name="e">包含事件資料的 <see cref="FieldOperatedEventArgs"/> 。</param>
public delegate void FieldOperatedEventHandler(object sender, FieldOperatedEventArgs e);
/// <summary>
/// 告知用戶端欄位已進行操作。
/// </summary>
public interface INotifyFieldOperated
{
/// <summary>
/// 當欄位已進行操作
/// </summary>
event FieldOperatedEventHandler FieldOperated;
}
} |
using System.Collections.Concurrent;
using MediaBrowser.Controller.Entities;
using System;
using System.Collections.Generic;
namespace MediaBrowser.Controller.Library
{
/// <summary>
/// Class ChildrenChangedEventArgs
/// </summary>
public class ChildrenChangedEventArgs : EventArgs
{
/// <summary>
/// Gets or sets the folder.
/// </summary>
/// <value>The folder.</value>
public Folder Folder { get; set; }
/// <summary>
/// Gets or sets the items added.
/// </summary>
/// <value>The items added.</value>
public ConcurrentBag<BaseItem> ItemsAdded { get; set; }
/// <summary>
/// Gets or sets the items removed.
/// </summary>
/// <value>The items removed.</value>
public List<BaseItem> ItemsRemoved { get; set; }
/// <summary>
/// Gets or sets the items updated.
/// </summary>
/// <value>The items updated.</value>
public ConcurrentBag<BaseItem> ItemsUpdated { get; set; }
/// <summary>
/// Create the args and set the folder property
/// </summary>
/// <param name="folder">The folder.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public ChildrenChangedEventArgs(Folder folder)
{
if (folder == null)
{
throw new ArgumentNullException();
}
//init the folder property
Folder = folder;
//init the list
ItemsAdded = new ConcurrentBag<BaseItem>();
ItemsRemoved = new List<BaseItem>();
ItemsUpdated = new ConcurrentBag<BaseItem>();
}
/// <summary>
/// Adds the new item.
/// </summary>
/// <param name="item">The item.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public void AddNewItem(BaseItem item)
{
if (item == null)
{
throw new ArgumentNullException();
}
ItemsAdded.Add(item);
}
/// <summary>
/// Adds the updated item.
/// </summary>
/// <param name="item">The item.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public void AddUpdatedItem(BaseItem item)
{
if (item == null)
{
throw new ArgumentNullException();
}
ItemsUpdated.Add(item);
}
/// <summary>
/// Adds the removed item.
/// </summary>
/// <param name="item">The item.</param>
/// <exception cref="System.ArgumentNullException"></exception>
public void AddRemovedItem(BaseItem item)
{
if (item == null)
{
throw new ArgumentNullException();
}
ItemsRemoved.Add(item);
}
/// <summary>
/// Lists the has change.
/// </summary>
/// <param name="list">The list.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private bool ListHasChange(List<BaseItem> list)
{
return list != null && list.Count > 0;
}
/// <summary>
/// Lists the has change.
/// </summary>
/// <param name="list">The list.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private bool ListHasChange(ConcurrentBag<BaseItem> list)
{
return list != null && !list.IsEmpty;
}
/// <summary>
/// Gets a value indicating whether this instance has change.
/// </summary>
/// <value><c>true</c> if this instance has change; otherwise, <c>false</c>.</value>
public bool HasChange
{
get { return HasAddOrRemoveChange || ListHasChange(ItemsUpdated); }
}
/// <summary>
/// Gets a value indicating whether this instance has add or remove change.
/// </summary>
/// <value><c>true</c> if this instance has add or remove change; otherwise, <c>false</c>.</value>
public bool HasAddOrRemoveChange
{
get { return ListHasChange(ItemsAdded) || ListHasChange(ItemsRemoved); }
}
}
}
|
using System;
/*Votre entier est trop petit: il doit être (d'au moins) (strictement supérieur à) min
Votre entier est trop grand: il doit être (d'au plus) (strictement inférieur à) max
Votre entier est trop petit/grand par rapport à l'intervalle demandé: il doit être compris ENTRE min et max (bornes exclues)
Votre entier est trop petit/grand par rapport à l'intervalle demandé: il ne peut valoir que de min à max (bornes incluses)*/
class SaisiesConsoleValides {
private static int saisirEntierConsole(bool ilYAUnMin, bool ilYAUnMax, bool strict, int min, int max, string specContrainte) {
/*Méthode PRIVÉE, donc non accessible à l'extérieur de la classe. La méthode s'assure de demander à l'usager d'inscrire
un entier, et tant que l'usager n'a pas inscrit un entier valide (ex.: "12a" n'est pas un entier valide!), la méthode
redemande à l'usager de recommencer. De plus, SI l'entier doit être inscrit dans un certain intervalle, la méthode se
charge de s'assurer que l'entier est bien compris entre les minimum et maximum passés en paramètre*/
bool toutEstCorrect;
int réponse = 0; //Initiliation par défaut
string saisieConsole;
string messageDErreur;
string spécificationContrainte = specContrainte.Length == 0 ? "" : " CONTRAINTE! l'entier doit " + specContrainte + ".";
Console.WriteLine("Veuillez svp inscrire un entier." + spécificationContrainte);
do {
messageDErreur = ""; //Initiliation (ou réinitiliation) par défaut
saisieConsole = Console.ReadLine();
try {
réponse = Int32.Parse(saisieConsole);
if (ilYAUnMin || ilYAUnMax){
bool tropPetit = strict ? réponse <= min : réponse < min;
bool tropGrand = strict ? réponse >= max : réponse > max;
if (ilYAUnMin && ilYAUnMax) {
if (tropPetit || tropGrand)
messageDErreur = spécificationContrainte;
} else if (ilYAUnMin){
if (tropPetit)
messageDErreur = spécificationContrainte;
} else if (tropGrand)
messageDErreur = spécificationContrainte;
}
}
catch {
messageDErreur = "Votre entier n'est pas valide.";
}
toutEstCorrect = messageDErreur.Length == 0;
if (!toutEstCorrect) {
messageDErreur += " Veuillez recommencez svp: ";
Console.Write(messageDErreur);
}
} while (!toutEstCorrect);
return réponse;
}
public static int saisirEntierConsole() {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en ne spécifiant aucune contrainte au niveau des arguments*/
return saisirEntierConsole(false, false, false, 0, 0, "");
//Les 0 sont des valeurs par défaut, non applicables s'il n'y a pas d'intervalle
}
public static int saisirEntierConsolePlusGrandQue(int valeurMinimale) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte*/
return saisirEntierConsole(true, false, true, valeurMinimale, 0, "être strictement supérieur à " + valeurMinimale);
}
public static int saisirEntierConsoleAuMoins(int valeurMin) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte*/
return saisirEntierConsole(true, false, false, valeurMin, 0, "être d'au moins " + valeurMin);
}
public static int saisirEntierConsolePlusPetitQue(int valeurMaximale) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte*/
return saisirEntierConsole(false, true, true, 0, valeurMaximale, "être strictement inférieur à " + valeurMaximale);
}
public static int saisirEntierConsoleAuPlus(int valeurMax) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte*/
return saisirEntierConsole(false, true, false, 0, valeurMax, "être d'au plus " + valeurMax);
}
public static int saisirEntierConsoleEntre(int borneMinimale, int borneMaximale) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte. Il y a cette fois un intervalle.*/
return saisirEntierConsole(true, true, true, borneMinimale, borneMaximale, "être compris ENTRE " + borneMinimale + " et " + borneMaximale);
}
public static int saisirEntierConsoleDeA(int borneMin, int borneMax) {
/*Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à la méthode privée
saisirEntierConsole ci-haut, en spécifiant les bons arguments pour ce contexte. Il y a un intervalle.*/
return saisirEntierConsole(true, true, false, borneMin, borneMax, "aller de " + borneMin + " à " + borneMax + " inclusivement");
}
public static int saisirEntierConsolePositifOuNul() {
//Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à une AUTRE méthode publique.
return saisirEntierConsoleAuMoins(0);
}
public static int saisirEntierConsoleStrictementPositif() {
//Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à une AUTRE méthode publique.
return saisirEntierConsolePlusGrandQue(0);
}
public static int saisirEntierConsoleNégatifOuNul() {
//Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à une AUTRE méthode publique.
return saisirEntierConsoleAuPlus(0);
}
public static int saisirEntierConsoleStrictementNégatif() {
//Méthode publique, donc accessible de l'extérieur de la classe. Redirige le travail à une AUTRE méthode publique.
return saisirEntierConsolePlusPetitQue(0);
}
public static bool saisirReponseOuiNon(string questionQuiAppelleOuiNon) {
/*Méthode utile pour tout contexte où on veut demander à l'usager une question qui appelle "oui ou "non" comme
réponse. La méthode prend en paramètre la question, LUI AJOUTE UN " o/n:" pour bien spécifier à l'uager que c'est
ainsi qu'il doit répondre, puis capte la réponse de l'usager. Tant que l'usager n'a pas répondu correctement, la
méthode lui signifie qu'il doit répondre par un seul caractère:`'o' ou 'n' (ou 'O' ou 'N': les majuscules sont
acceptées!), et demande à l'usager de "recommencer" sa réponse. La méthode retourne vrai ou faux selon que l'usager
a répondu... oui ou non!*/
bool toutEstCorrect;
bool réponseEstOui = true; //Initiliation par défaut
string messageDErreur, saisieConsole;
char premierCaractère;
Console.Write(questionQuiAppelleOuiNon + " o/n: ");
do {
messageDErreur = ""; //Initiliation (ou réinitiliation) par défaut
saisieConsole = Console.ReadLine();
if (saisieConsole.Length == 1) {
premierCaractère = saisieConsole.ToLower()[0];
réponseEstOui = premierCaractère == 'o';
if (!réponseEstOui && (premierCaractère != 'n')) messageDErreur = "Votre réponse doit absolument être 'o' ou 'n'(la lettre majuscule est permise).";
}
else {
messageDErreur = "Une saisie valide dans ce cas implique un seul caractère, soit le premier de \"oui\" ou \"non\"!";
}
toutEstCorrect = messageDErreur.Length == 0;
if (!toutEstCorrect) {
messageDErreur += " Recommencez svp: ";
Console.WriteLine(messageDErreur);
}
} while (!toutEstCorrect);
return réponseEstOui;
}
} |
using UnityEngine;
using System;
using System.Collections;
namespace BanSupport
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property |
AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)]
public class BoolConditionAttribute : PropertyAttribute
{
public string boolField = "";
public BoolConditionAttribute(string boolField)
{
this.boolField = boolField;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Integer.Domain.Acesso.Exceptions
{
public class UsuarioExistenteException : ApplicationException
{
private Usuario usuario;
public UsuarioExistenteException(Usuario usuario) : base()
{
this.usuario = usuario;
}
public override string Message
{
get
{
return String.Format("Já existe um usuário cadastrado com o e-mail '{0}'.", usuario.Email);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public abstract class Prefix : AutoExpandingScriptableObject {
public virtual float ModifyHeal(WarheadHeal source, float heal) {
return heal;
}
public virtual float ModifyDamage(WarheadDamage source, float damage) {
return damage;
}
public virtual float ModifyStagger(WarheadStagger source, float stagger) {
return stagger;
}
public virtual IEnumerator PostHitRoutine(BattleUnit actor, BattleUnit target) {
yield return null;
}
public virtual IEnumerator PostHealRoutine(BattleUnit actor, BattleUnit target) {
yield return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using IRAP.Global;
using IRAPGeneralGateway.Entities;
namespace IRAPGeneralGateway
{
public class InitService
{
public static string ConfigConnString;
public static string ExCodeDBConnString;
public static int ExCodeDBType = 1;
public static int DefaultSecurityLevel = 1;
public static int IsWriteLog = 1;
public static int MaxConnectPerSecond = 0;
public static string ServiceID = string.Empty;
public static string ServiceName = string.Empty;
public static string IPAddress = string.Empty; // --多个IP用逗号隔开
public static string APIUrl = string.Empty; // ---对外服务的地址
public static int VerifyMode = 1;
public static string DefaultPrefix = string.Empty;
public static int LoadExCode = 1;
public static int CommandTimeout = 60;
public static int ReceiveStream = 1;
private static bool _regToDB = false;
private static string fileName = string.Empty; // appPath + configName;
private static Dictionary<string, TEntityClient> _clientInMemory =
new Dictionary<string, TEntityClient>();
public static Dictionary<string, TEntityClient> ClientList
{
get
{
return _clientInMemory;
}
}
public static void ReadConfig()
{
if (!_regToDB)
{
DefaultSecurityLevel = int.Parse(ConfigurationManager.AppSettings["DefaultSecurityLevel"]);
ConfigConnString = ConfigurationManager.AppSettings["ConnectionString"];
ExCodeDBConnString = ConfigurationManager.AppSettings["ExCodeDBConn"];
ExCodeDBType = int.Parse(ConfigurationManager.AppSettings["ExCodeDBType"]);
ServiceName = ConfigurationManager.AppSettings["ServiceName"];
ServiceID = ConfigurationManager.AppSettings["ServiceID"];
int.TryParse(ConfigurationManager.AppSettings["IsWriteLog"], out IsWriteLog);
int.TryParse(ConfigurationManager.AppSettings["MaxConnectPerSecond"], out MaxConnectPerSecond);
int.TryParse(ConfigurationManager.AppSettings["VerifyMode"], out VerifyMode);
int.TryParse(ConfigurationManager.AppSettings["loadExCode"], out LoadExCode);
DefaultPrefix = ConfigurationManager.AppSettings["prefix"].ToString();
int.TryParse(ConfigurationManager.AppSettings["CommandTimeout"], out CommandTimeout);
int.TryParse(ConfigurationManager.AppSettings["ReceiveStream"], out ReceiveStream);
Computer com = new Computer();
IPAddress = com.IpAddress;
if (ServiceID == string.Empty)
{
ServiceID = com.CPUID;
}
_regToDB = true;
Thread t = new Thread(HeartBeat);
t.IsBackground = true;
t.Start();
}
try
{
//读取可用渠道设置
using (SqlConnection conn = new SqlConnection(ConfigConnString))
{
conn.Open();
SqlCommand command =
new SqlCommand(
"SELECT ClientID, ChannelName, UserID, Password, IsValid, ExpireDate," +
"SecurityLevel, SecurityPassword FROM dbo.stb_Channels ORDER BY ClientID",
conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
TEntityClient f = new TEntityClient();
f.ClientID = reader["ClientID"].ToString();
f.ChannelName = reader["ChannelName"].ToString();
f.UserID = reader["UserID"].ToString();
f.Password = reader["Password"].ToString();
f.IsValid = int.Parse(reader["IsValid"].ToString());
f.ExpireDate = (DateTime)reader["ExpireDate"];
f.SecurityLevel = int.Parse(reader["SecurityLevel"].ToString());
f.SecurityPassword = reader["SecurityPassword"].ToString();
if (!_clientInMemory.ContainsKey(f.ClientID))
{
_clientInMemory.Add(f.ClientID, f);
}
}
reader.Close();
conn.Close();
}
}
catch (Exception err)
{
WriteLog.Instance.WriteLocalMsg(9999, "读取渠道信息失败:" + err.Message);
}
}
public static void RefreshServiceToDB(int status, string baseURL, string msg)
{
string[] ipList = IPAddress.Split(';');
if (APIUrl == string.Empty)
{
if (ipList.Length > 0)
APIUrl = baseURL.Replace("localhost", ipList[0]);
}
try
{
//判断是否存在服务记录
using (SqlConnection conn = new SqlConnection(ConfigConnString))
{
conn.Open();
SqlCommand command =
new SqlCommand(
"SELECT COUNT(*) AS cnt FROM stb_Services WHERE ServiceID=@ServiceID",
conn);
command.Parameters.AddWithValue("@ServiceID", ServiceID);
object reader = command.ExecuteScalar();
bool exists = (int)reader == 0 ? false : true;
if (!exists)
{
string insertSql =
"INSERT INTO stb_Services "+
"VALUES(@ServiceID, @ServiceName, @IPAddress, @APIURL, GetDate(), " +
"GetDate(), 1, 1, @MaxConnect, @WriteLogLevel, @ExCodeDB, @Remark, @DiagMsg)";
SqlCommand insertCommand = new SqlCommand(insertSql, conn);
insertCommand.Parameters.AddWithValue("@ServiceID", ServiceID);
insertCommand.Parameters.AddWithValue("@ServiceName", ServiceName);
insertCommand.Parameters.AddWithValue("@IPAddress", IPAddress);
insertCommand.Parameters.AddWithValue("@APIURL", APIUrl);
insertCommand.Parameters.AddWithValue("@MaxConnect", MaxConnectPerSecond);
insertCommand.Parameters.AddWithValue("@WriteLogLevel", IsWriteLog);
insertCommand.Parameters.AddWithValue(
"@ExCodeDB",
Regex.Replace(ExCodeDBConnString, @"pwd=(\S+)", "pwd=*****"));
insertCommand.Parameters.AddWithValue("@Remark", "服务初始化成功");
insertCommand.Parameters.AddWithValue("@DiagMsg", "等待连接");
insertCommand.ExecuteNonQuery();
}
else
{
string updateSql =
"UPDATE stb_Services SET MaxConnectPerSecond=@MaxConnect, WriteLogLevel=@WriteLogLevel," +
"ExCodeDB=@ExCodeDB, Remark=@Remark, DiagMsg=@DiagMsg, LastCallTime=GetDate(),"+
"Running=@Status WHERE ServiceID=@ServiceID";
SqlCommand updateCommand = new SqlCommand(updateSql, conn);
updateCommand.Parameters.AddWithValue("@ServiceID", ServiceID);
updateCommand.Parameters.AddWithValue("@MaxConnect", MaxConnectPerSecond);
updateCommand.Parameters.AddWithValue("@WriteLogLevel", IsWriteLog);
updateCommand.Parameters.AddWithValue(
"@ExCodeDB",
Regex.Replace(ExCodeDBConnString, @"pwd=(\S+)", "pwd=*****"));
updateCommand.Parameters.AddWithValue("@Remark", "服务正在运行");
updateCommand.Parameters.AddWithValue("@DiagMsg", msg);
updateCommand.Parameters.AddWithValue("@Status", status);
}
}
}
catch (Exception err)
{
WriteLog.Instance.WriteLocalMsg(9999, "刷新服务状态失败:" + err.Message);
}
}
public static void HeartBeat()
{
while (true)
{
try
{
using (SqlConnection conn = new SqlConnection(ConfigConnString))
{
conn.Open();
SqlCommand command =
new SqlCommand(
"UPDATE stb_Services SET HeartTime=GetDate() WHERE ServiceID=@ServiceID",
conn);
command.Parameters.AddWithValue("@ServiceID", ServiceID);
command.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception err)
{
WriteLog.Instance.WriteLocalMsg(9999, "心跳失败:" + err.Message);
}
//30秒钟检测一次心跳
Thread.Sleep(30000);
//检测过期的令牌删除
try
{
lock (TIRAPGeneralWebAPIService.AccessList)
{
foreach (string key in TIRAPGeneralWebAPIService.AccessList.Keys.ToArray())
{
if (DateTime.Now.Subtract(TIRAPGeneralWebAPIService.AccessList[key]).TotalMinutes > 60)
{
TIRAPGeneralWebAPIService.AccessList.Remove(key);
}
}
}
}
catch (Exception err)
{
WriteLog.Instance.WriteLocalMsg(9999, "移除令牌并发控制列表失败:" + err.Message);
}
}
}
public static void WriteLogToDB(string clientID, string exCode, string msg, int level = 2)
{
//level值 ---0 INFO 1--warning 2--error 3--Excption
try
{
using (SqlConnection conn = new SqlConnection(ConfigConnString))
{
conn.Open();
string insertSql =
"INSERT INTO stb_ServicesLog VALUES(@ServiceID, @ClientID, GetDate(), @Level, @ExCode, @Msg)";
SqlCommand command = new SqlCommand(insertSql, conn);
command.Parameters.AddWithValue("@ServiceID", ServiceID);
command.Parameters.AddWithValue("@ClientID", clientID);
command.Parameters.AddWithValue("@Level", level);
command.Parameters.AddWithValue("@ExCode", exCode);
command.Parameters.AddWithValue("@Msg", msg);
command.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception err)
{
WriteLog.Instance.WriteLocalMsg(9999, "日志记录失败:" + err.Message);
}
}
}
}
|
using SGCFT.Dados.Contextos;
using SGCFT.Dominio.Contratos.Repositorios;
using SGCFT.Dominio.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGCFT.Dados.Repositorios
{
public class AcessoRepositorio : IAcessoRepositorio
{
private readonly Contexto _contexto;
public AcessoRepositorio()
{
_contexto = new Contexto();
}
public void Alterar(Acesso acesso)
{
_contexto.Entry<Acesso>(acesso).State = System.Data.Entity.EntityState.Modified;
_contexto.SaveChanges();
}
public void Inserir(Acesso acesso)
{
_contexto.Acesso.Add(acesso);
_contexto.SaveChanges();
}
public void Dispose()
{
if (_contexto != null)
{
_contexto.Dispose();
}
}
}
}
|
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 ConexaoDataBase;
namespace FormularioPrincipal
{
public partial class FrmLogin : Form
{
private bool Logado = false;
public FrmLogin()
{
InitializeComponent();
}
private void painelLogin_Paint(object sender, PaintEventArgs e)
{
}
private void btEntrar_Click(object sender, EventArgs e)
{
clsUsuario login = new clsUsuario();
if(txtTelaLogin_loginUsuario.Text != null && txtTelaLogin_senhaUsuario.Text != null) {
bool result = login.Logar(txtTelaLogin_loginUsuario.Text, txtTelaLogin_senhaUsuario.Text);
Logado = result;
if (result)
{
FrmInicioSistema abrirInicioSistema = new FrmInicioSistema();
MessageBox.Show("Seja bem vindo!");
this.Hide();
abrirInicioSistema.ShowDialog();
}
else
{
MessageBox.Show("Usuário ou senha incorreto!");
}
}
else
{
MessageBox.Show("Digite os dados para login");
}
}
private void FrmLogin_FormClosed(object sender, FormClosedEventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
namespace WebAPI.MoneyXChange.Models
{
public partial class CurrencyRate
{
public DateTime CrrDateRate { get; set; }
public int CrrCurrencyFrom { get; set; }
public int CrrCurrencyTo { get; set; }
public double CrrExchangeRate { get; set; }
public Currency CrrCurrencyFromNavigation { get; set; }
public Currency CrrCurrencyToNavigation { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class CellBehaviorStove : CellBehaviorOccupiable {
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Kingdee.CAPP.Common;
namespace Kingdee.CAPP.Model
{
/// <summary>
/// 类型说明:产品实体类
/// 作 者:jason.tang
/// 完成时间:2013-03-05
/// </summary>
[TypeConverter(typeof(PropertySorter))]
public class ProductModule
{
/// <summary>
/// 文件夹ID
/// </summary>
[Browsable(false)]
public string FolderId { get; set; }
/// <summary>
/// 文件夹代码
/// </summary>
[CategoryAttribute("编辑文件夹"), DescriptionAttribute("文件夹编号"), DisplayName("文件夹编号"), PropertyOrder(10)]
public string FolderCode { get; set; }
/// <summary>
/// 文件夹名字
/// </summary>
[CategoryAttribute("编辑文件夹"), DescriptionAttribute("文件夹名称"), DisplayName("文件夹名称"), PropertyOrder(11)]
public string FolderName { get; set; }
/// <summary>
/// 父文件夹
/// </summary>
[Browsable(false)]
public string ParentFolder { get; set; }
/// <summary>
/// 父文件夹ID
/// </summary>
[Browsable(false)]
public string ParentFolderId { get; set; }
/// <summary>
/// 创建人
/// </summary>
[Browsable(false)]
public string Createtor { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Browsable(false)]
public string CreateDate { get; set; }
/// <summary>
/// 更新人
/// </summary>
[Browsable(false)]
public string Updater { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[Browsable(false)]
public string UpdateDate { get; set; }
/// <summary>
/// 显示顺序
/// </summary>
[Browsable(false)]
public int DisplaySeq { get; set; }
/// <summary>
/// 子文件夹数目
/// </summary>
[Browsable(false)]
public int ChildCount { get; set; }
/// <summary>
/// 备注
/// </summary>
[CategoryAttribute("编辑文件夹"), DescriptionAttribute("备注"), DisplayName("备注"), PropertyOrder(12)]
public string Remark { get; set; }
}
}
|
global using System.Collections;
global using System.ComponentModel;
global using System.Diagnostics.CodeAnalysis;
global using System.Globalization;
global using System.Reflection;
global using System.Runtime.CompilerServices;
global using System.Text;
global using System.Text.RegularExpressions;
global using System.Threading;
global using Serilog.Capturing;
global using Serilog.Configuration;
global using Serilog.Context;
global using Serilog.Core;
global using Serilog.Core.Enrichers;
global using Serilog.Core.Filters;
global using Serilog.Core.Pipeline;
global using Serilog.Core.Sinks;
global using Serilog.Data;
global using Serilog.Debugging;
global using Serilog.Events;
global using Serilog.Formatting.Json;
global using Serilog.Parsing;
global using Serilog.Policies;
global using Serilog.Rendering;
global using Serilog.Settings.KeyValuePairs;
|
using System.Windows.Controls;
namespace MinecraftToolsBoxSDK
{
/// <summary>
/// Location.xaml 的交互逻辑
/// </summary>
public partial class Location : StackPanel
{
public Location()
{
InitializeComponent();
LocX.setNeighbour(LocZ, LocY);
LocY.setNeighbour(LocX, LocZ);
LocZ.setNeighbour(LocY, LocX);
}
/// <summary>
/// 获取坐标:x y z
/// </summary>
/// <returns></returns>
public string GetLocation()
{
if (LocX.Text == "" || LocY.Text == "" || LocZ.Text == "") return "";
else return LocX.Text+" "+LocY.Text+" "+LocZ.Text;
}
/// <summary>
/// 获取坐标:x=X,y=Y,z=Z
/// </summary>
public string GetLoc()
{
if (LocX.Text == "" || LocY.Text == "" || LocZ.Text == "") return "";else
return "x=" + LocX.Text+",y=" + LocY.Text+",z=" + LocZ.Text;
}
/// <summary>
/// 获取坐标:dx=X,dy=Y,dz=Z
/// </summary>
/// <returns></returns>
public string GetDLoc()
{
if (LocX.Text == "" || LocY.Text == "" || LocZ.Text == "") return "";
else return "dx=" + LocX.Text + ",dy=" + LocY.Text + ",dz=" + LocZ.Text;
}
public string GetLoc2()
{
if (LocX.Text == "" || LocY.Text == "" || LocZ.Text == "") return "";
else return "X:" + LocX.Text + ",Y:" + LocY.Text + ",Z:" + LocZ.Text;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace EjercicioCalculadoraDiseñoDinamico
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddButtons();
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
resultTextBlock.Text += ((Button)sender).Tag;
}
private void AddButtons()
{
for (int i = 1; i <= 3; i++)
{
for (int j = 0; j < 3; j++)
{
int currentButtonValue = (i - 1) * 3 + j + 1;
TextBlock textBlock = new TextBlock
{
Text = currentButtonValue.ToString()
};
Viewbox viewbox = new Viewbox
{
Child = textBlock
};
Button button = new Button
{
Tag = currentButtonValue,
Margin = new Thickness(5),
Content = viewbox
};
button.SetValue(Grid.RowProperty, i);
button.SetValue(Grid.ColumnProperty, j);
button.Click += new RoutedEventHandler(ButtonClick);
MainGrid.Children.Add(button);
}
}
}
}
}
|
namespace Meshop.Framework.Module
{
public interface IPluginModel
{
}
} |
using gView.Framework.Data;
using gView.Framework.Network;
using gView.Framework.UI;
using System;
using System.Collections.Generic;
namespace gView.Plugins.Network
{
[gView.Framework.system.RegisterPlugIn("5b2818b1-2a80-4390-9ca7-2e363cdc1027")]
public class NetworkRibbonTab : ICartoRibbonTab
{
private List<RibbonGroupBox> _groups;
public NetworkRibbonTab()
{
_groups = new List<RibbonGroupBox>(
new RibbonGroupBox[]{
new RibbonGroupBox(String.Empty,
new RibbonItem[] {
new RibbonItem(new Guid("002124CB-804E-449e-BA7B-A3F3CBBBD154")),
new RibbonItem(new Guid("44762AEE-4F9C-4039-9577-372DC106B1C8")),
new RibbonItem(new Guid("457B8BC3-1F92-4512-BD09-9E6A870ADA93")),
new RibbonItem(new Guid("84A6A670-4044-43a0-94CE-05A244931D5C"))
}
),
new RibbonGroupBox(String.Empty,
new RibbonItem[]{
new RibbonItem(new Guid("D7640425-DEF2-4c57-A165-464CDAB7C56E"))
}
),
new RibbonGroupBox(String.Empty,
new RibbonItem[]{
new RibbonItem(new Guid("9A975F46-D727-495b-B752-9E079289E296")),
new RibbonItem(new Guid("83A38411-27C7-4241-9F28-AC3005BFAFA8")),
new RibbonItem(new Guid("17475DC9-5A9B-4c90-8DE1-60654389F108")),
new RibbonItem(new Guid("158C5F28-B987-4d16-8C9D-A1FC6E70EB56")),
new RibbonItem(new Guid("216D616B-FA15-4052-BFDE-16B6346C4B7F"))
}
)
}
);
}
#region ICartoRibbonTab Member
public string Header
{
get { return "Network"; }
}
public List<RibbonGroupBox> Groups
{
get { return _groups; }
}
public int SortOrder
{
get { return 310; }
}
public bool IsVisible(IMapDocument mapDocument)
{
if (mapDocument == null || mapDocument.FocusMap == null)
{
return false;
}
foreach (IDatasetElement dsElement in mapDocument.FocusMap.MapElements)
{
if (dsElement.Class is INetworkFeatureClass)
{
return true;
}
}
return false;
}
#endregion
}
}
|
using Microsoft.AspNetCore.Hosting;
using System.IO;
#if NET461
using System.Linq;
using Microsoft.AspNetCore.Hosting.WindowsServices;
#endif
namespace IDI.Digiccy.Transaction.Service
{
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
#if NET461
if (args.Contains("--windows-service"))
//if (Debugger.IsAttached || args.Contains("--debug"))
{
host.RunAsWindowsService();
}
else
{
host.Run();
}
#else
host.Run();
#endif
}
public static IWebHost BuildWebHost(string[] args) => new WebHostBuilder()
.UseKestrel()
.UseUrls("http://*:17528")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
}
|
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.Runtime.InteropServices;
namespace SMS
{
public partial class Form1 : Form
{
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect,
int nTopRect,
int nRightRect,
int nButtonRect,
int nWidthEllipse,
int nHeightEllipse
);
public Form1()
{
InitializeComponent();
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 25, 25));
panel_nav.Height = button_dashboard.Height;
panel_nav.Top = button_dashboard.Top;
panel_nav.Left = button_dashboard.Left;
button_dashboard.BackColor = Color.FromArgb(46, 51, 73);
labelTitle.Text = "Dashboard";
this.panelFormLoader.Controls.Clear();
frmdashboard Frmdashboard_vrb = new frmdashboard() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
Frmdashboard_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(Frmdashboard_vrb);
Frmdashboard_vrb.Show();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// showSubmenu(panel_members);
}
private void customDesign()
{
panel_members.Visible = false;
panel_posts.Visible = false;
}
private void hideSubmenu()
{
if (panel_members.Visible == true)
panel_members.Visible = false;
if (panel_posts.Visible == true)
panel_posts.Visible = false;
}
private void showSubmenu(Panel submenu)
{
if (submenu.Visible == false)
{
hideSubmenu();
submenu.Visible = true;
}
else
submenu.Visible = false;
}
private void button_members_Click(object sender, EventArgs e)
{
showSubmenu(panel_members);
panel_nav.Height = button_members.Height;
panel_nav.Top = button_members.Top;
panel_nav.Left = button_members.Left;
button_members.BackColor = Color.FromArgb(46, 51, 73);
}
private void button_Students_Click(object sender, EventArgs e)
{
//hideSubmenu();
labelTitle.Text = "Students";
this.panelFormLoader.Controls.Clear();
FrmStudent FrmStudent_vrb = new FrmStudent() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
FrmStudent_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(FrmStudent_vrb);
FrmStudent_vrb.Show();
}
private void button_teachers_Click(object sender, EventArgs e)
{
//hideSubmenu();
labelTitle.Text = "Teacher Registration Form";
this.panelFormLoader.Controls.Clear();
FrmTeacher FrmTeacher_vrb = new FrmTeacher() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
FrmTeacher_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(FrmTeacher_vrb);
FrmTeacher_vrb.Show();
}
private void button_posts_Click(object sender, EventArgs e)
{
showSubmenu(panel_posts);
panel_nav.Height = button_posts.Height;
panel_nav.Top = button_posts.Top;
panel_nav.Left = button_posts.Left;
button_posts.BackColor = Color.FromArgb(46, 51, 73);
}
private void button_poll_Click(object sender, EventArgs e)
{
labelTitle.Text = "Student Registration Form";
this.panelFormLoader.Controls.Clear();
Rstudent Rstudent_vrb = new Rstudent() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
Rstudent_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(Rstudent_vrb);
Rstudent_vrb.Show();
}
private void button_notice_Click(object sender, EventArgs e)
{
labelTitle.Text = "Student Details";
this.panelFormLoader.Controls.Clear();
Vstudents Vstudent_vrb = new Vstudents() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
Vstudent_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(Vstudent_vrb);
Vstudent_vrb.Show();
// hideSubmenu();
}
private void button_Dashboard_Click(object sender, EventArgs e)
{
panel_nav.Height = button_dashboard.Height;
panel_nav.Top = button_dashboard.Top;
panel_nav.Left = button_dashboard.Left;
button_dashboard.BackColor = Color.FromArgb(46, 51, 73);
labelTitle.Text = "Dashboard";
this.panelFormLoader.Controls.Clear();
frmdashboard Frmdashboard_vrb = new frmdashboard() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
Frmdashboard_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(Frmdashboard_vrb);
Frmdashboard_vrb.Show();
}
private void button_classes__Click(object sender, EventArgs e)
{
panel_nav.Height = button_class.Height;
panel_nav.Top = button_class.Top;
panel_nav.Left = button_class.Left;
button_class.BackColor = Color.FromArgb(46, 51, 73);
labelTitle.Text = "Classes";
this.panelFormLoader.Controls.Clear();
FrmClasses FrmClasses_vrb = new FrmClasses() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
FrmClasses_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(FrmClasses_vrb);
FrmClasses_vrb.Show();
}
private void button_modules_Click(object sender, EventArgs e)
{
panel_nav.Height = button_module.Height;
panel_nav.Top = button_module.Top;
panel_nav.Left = button_module.Left;
button_module.BackColor = Color.FromArgb(46, 51, 73);
labelTitle.Text = "Modules";
this.panelFormLoader.Controls.Clear();
FrmModules FrmModules_vrb = new FrmModules() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
FrmModules_vrb.FormBorderStyle = FormBorderStyle.None;
this.panelFormLoader.Controls.Add(FrmModules_vrb);
FrmModules_vrb.Show();
}
private void button_dashboard_Leave(object sender, EventArgs e)
{
button_dashboard.BackColor = Color.FromArgb(24, 30, 54);
}
private void button_class_Leave(object sender, EventArgs e)
{
button_class.BackColor = Color.FromArgb(24, 30, 54);
}
private void button_module_Leave(object sender, EventArgs e)
{
button_module.BackColor = Color.FromArgb(24, 30, 54);
}
private void button_members_Leave(object sender, EventArgs e)
{
button_members.BackColor = Color.FromArgb(24, 30, 54);
}
private void button_posts_Leave(object sender, EventArgs e)
{
button_posts.BackColor = Color.FromArgb(24, 30, 54);
//hideSubmenu();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void buttonClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button_poll_Leave(object sender, EventArgs e)
{
button_poll.BackColor = Color.FromArgb(24, 30, 54);
}
private void button4_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void button1_Click_1(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
}
}
}
|
using System.Data.Entity;
using WebApi_LinkManager.Entities;
namespace WebApi_LinkManager.DAL
{
public class LinkContext : DbContext
{
public LinkContext() : base("name=LinkDBConnectionString")
{
Database.SetInitializer<LinkContext>(new LinkManagerDbInitializer());
}
public DbSet<Link> Links { get; set; }
}
}
|
using UnityEngine;
using Thesis.Interface;
namespace Thesis {
public class DrawableObject : ProceduralObject,
IDrawable,
ICombinable
{
/*************** FIELDS ***************/
public string name;
public Material material;
public MeshFilter meshFilter;
public Mesh mesh;
public Vector3 meshOrigin;
public Vector3[] boundaries;
public Vector3[] vertices;
public int[] triangles;
/*************** CONSTRUCTORS ***************/
public DrawableObject (string name = "drawableObject", string materialName = null)
{
this.name = name;
if (materialName != null)
this.material = MaterialManager.Instance.Get(materialName);
}
/*************** METHODS ***************/
/// <summary>
/// Calculates the intersection point of the lines formed by each two points in 3D space.
/// Points a1 and a2 form the first line and points b1 and b2 form the second.
/// Maths found here: http://mathforum.org/library/drmath/view/62814.html
/// </summary>
public virtual void FindMeshOrigin (Vector3 a1, Vector3 a2, Vector3 b1, Vector3 b2)
{
var a_dir = a1 - a2; // the direction vector of the first line
var b_dir = b1 - b2; // the direction vector of the second line
var dir_cross = Vector3.Cross(a_dir, b_dir);
var tmp_cross = Vector3.Cross(b1 - a1, b_dir);
float c1;
if (dir_cross.x != 0f)
c1 = tmp_cross.x / dir_cross.x;
else if (dir_cross.y != 0f)
c1 = tmp_cross.y / dir_cross.y;
else if (dir_cross.z != 0f)
c1 = tmp_cross.z / dir_cross.z;
else
throw new System.DivideByZeroException("Result of cross product is Vector3(0,0,0)!");
meshOrigin = a1 + c1 * a_dir;
}
public virtual void FindVertices ()
{
throw new System.NotImplementedException();
}
public virtual void FindTriangles ()
{
throw new System.NotImplementedException();
}
public virtual void Draw ()
{
gameObject = new GameObject(name);
meshFilter = gameObject.AddComponent<MeshFilter>();
var renderer = gameObject.AddComponent<MeshRenderer>();
gameObject.SetActive(false);
gameObject.isStatic = true;
if (material != null)
renderer.sharedMaterial = material;
mesh = new Mesh();
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = new Vector2[mesh.vertices.Length];
mesh.RecalculateNormals();
mesh.Optimize();
meshFilter.sharedMesh = mesh;
}
public virtual void Destroy ()
{
GameObject.DestroyImmediate(mesh);
GameObject.DestroyImmediate(gameObject);
}
/*************** INTERFACE EXPLICIT IMPLEMENTATION ***************/
Vector3[] IDrawable.vertices
{
get { return vertices; }
}
int[] IDrawable.triangles
{
get { return triangles; }
}
GameObject ICombinable.gameObject
{
get { return gameObject; }
}
MeshFilter ICombinable.meshFilter
{
get { return meshFilter; }
}
Material ICombinable.material
{
get { return material; }
}
Mesh ICombinable.mesh
{
get { return mesh; }
}
}
} // namespace Thesis |
using System;
namespace Login
{
class Program
{
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static void Main(string[] args)
{
string username = Console.ReadLine();
string password = Reverse(username);
string inputPassword = Console.ReadLine();
int invalidTries = 0;
while (inputPassword != password)
{
invalidTries++;
if (invalidTries >= 4)
{
Console.WriteLine($"User {username} blocked!");
return;
}
Console.WriteLine("Incorrect password. Try again.");
inputPassword = Console.ReadLine();
}
if (inputPassword == password)
{
Console.WriteLine($"User {username} logged in.");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _51_HomeWork
{
class Program
{
static void Main(string[] args)
{
int counter = 0;
while (true)
{
Console.WriteLine("Enter your login:");
string login = Console.ReadLine();
Console.WriteLine("Enter your password:");
string password = Console.ReadLine();
if (login == "andrey" && password == "1234")
{
Console.WriteLine("Enter the system!");
break;
}
else
{
counter++;
if (counter < 3)
Console.WriteLine("The username or password is incorrect! Try again.");
else
{
Console.WriteLine("The number of available tries have been exceeded!");
break;
}
}
}
Console.ReadLine();
}
}
}
|
using Assets.Scripts.Fabric;
using Assets.Scripts.Model;
using System;
using System.Collections;
using TapticPlugin;
using UnityEngine;
namespace Assets.Scripts.Controller
{
public class BlockController : MonoBehaviour
{
public delegate void BlockStacked();
public BlockStacked onBlockStacked;
[SerializeField] GameController _gameController;
[SerializeField] BlockFabric _blockFabric;
[SerializeField] public float _speed = 2.0f;
private const int MaxBoundary = 10;
[SerializeField] private GameObject _startBlock;
private GameObject _currentBlock;
private GameObject _lastBlock;
private bool _isForward = true;
private Vector3 _direction;
private bool _isMoving = false;
private void Awake()
{
_gameController.onGameLost += StopMoving;
_gameController.onGameStart += GenerateNewBlock;
}
private void Start()
{
_lastBlock = _startBlock;
}
public void SetNewBlock(GameObject newBlock)
{
if(_currentBlock)
{
_lastBlock = _currentBlock;
}
_currentBlock = newBlock;
if(_lastBlock != _startBlock)
{
_currentBlock.transform.localScale = _lastBlock.transform.localScale;
}
_direction = _currentBlock.GetComponent<Block>().blockData.MoveDirection;
StartCoroutine(MoveBlock(_currentBlock.GetComponent<Block>().blockData.MoveDirection));
}
public void ReleaseBlock()
{
if (_isMoving)
{
StopAllCoroutines();
TapticManager.Impact(ImpactFeedback.Light);
_isMoving = false;
float hangover = GetHangover();
float direction = hangover > 0 ? 1f : -1f;
float max = _direction == Vector3.right ? _lastBlock.transform.localScale.x : _lastBlock.transform.localScale.z;
if (Mathf.Abs(hangover) >= max)
{
_lastBlock = _startBlock;
_currentBlock = null;
_gameController.StartAnimationsOnLose();
return;
}
if (_direction == Vector3.right)
{
SplitBlockOnX(hangover, direction);
}
if (_direction == Vector3.forward)
{
SplitBlockOnZ(hangover, direction);
}
onBlockStacked?.Invoke();
Invoke("GenerateNewBlock", 1f);
}
}
private float GetHangover()
{
float newHangover = 0;
if (_direction == Vector3.right)
{
newHangover = _currentBlock.transform.position.x - _lastBlock.transform.position.x;
}
if (_direction == Vector3.forward)
{
newHangover = _currentBlock.transform.position.z - _lastBlock.transform.position.z;
}
return newHangover;
}
public void GenerateNewBlock()
{
SetNewBlock(_blockFabric.CreateNewBlock());
}
private void SplitBlockOnX(float hangover, float direction)
{
float newXSize = _lastBlock.transform.localScale.x - Mathf.Abs(hangover);
float fallingBlockSize = _currentBlock.transform.localScale.x - newXSize;
float newPos = _lastBlock.transform.position.x + (hangover / 2);
_currentBlock.transform.localScale = new Vector3(newXSize, _currentBlock.transform.localScale.y, _currentBlock.transform.localScale.z);
_currentBlock.transform.position = new Vector3(newPos, _currentBlock.transform.position.y, _currentBlock.transform.position.z);
float cubeEdge = _currentBlock.transform.position.x + (newXSize / 2f * direction);
float fallingBlockPos = cubeEdge + fallingBlockSize / 2f * direction;
Material material = _currentBlock.GetComponent<Renderer>().material;
SpawnFallingCube(fallingBlockPos, fallingBlockSize, material);
}
private void SplitBlockOnZ(float hangover, float direction)
{
float newSize = _lastBlock.transform.localScale.z - Mathf.Abs(hangover);
float fallingBlockSize = _currentBlock.transform.localScale.z - newSize;
float newPos = _lastBlock.transform.position.z + (hangover / 2);
_currentBlock.transform.localScale = new Vector3(_currentBlock.transform.localScale.x, _currentBlock.transform.localScale.y, newSize);
_currentBlock.transform.position = new Vector3(_currentBlock.transform.position.x, _currentBlock.transform.position.y, newPos);
float cubeEdge = _currentBlock.transform.position.z + (newSize / 2f * direction);
float fallingBlockPos = cubeEdge + fallingBlockSize / 2f * direction;
Material material = _currentBlock.GetComponent<Renderer>().material;
SpawnFallingCube(fallingBlockPos, fallingBlockSize, material);
}
private void SpawnFallingCube(float fallingBlockZPos, float fallingBlockSize, Material blockMaterial)
{
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.GetComponent<Renderer>().material = blockMaterial;
cube.AddComponent<Rigidbody>();
float multiplier = 0;
if (_isForward)
{
multiplier = 5;
}
else
{
multiplier = -5;
}
if (_direction == Vector3.right)
{
cube.transform.localScale = new Vector3(fallingBlockSize, _currentBlock.transform.localScale.y, _currentBlock.transform.localScale.z);
cube.transform.position = new Vector3(fallingBlockZPos, _currentBlock.transform.position.y, _currentBlock.transform.position.z);
cube.GetComponent<Rigidbody>().angularVelocity = Vector3.back * multiplier;
}
if (_direction == Vector3.forward)
{
cube.transform.localScale = new Vector3(_currentBlock.transform.localScale.x, _currentBlock.transform.localScale.y, fallingBlockSize);
cube.transform.position = new Vector3(_currentBlock.transform.position.x, _currentBlock.transform.position.y, fallingBlockZPos);
cube.GetComponent<Rigidbody>().angularVelocity = Vector3.right * multiplier;
}
Destroy(cube.gameObject, 4f);
}
private IEnumerator MoveBlock(Vector3 direction)
{
_isMoving = true;
while (true)
{
if (_isForward)
{
_currentBlock.transform.Translate(direction * _speed * Time.deltaTime);
}
else
{
_currentBlock.transform.Translate(-direction * _speed * Time.deltaTime);
}
if (_currentBlock.transform.position.x >= MaxBoundary || _currentBlock.transform.position.z >= MaxBoundary)
{
_isForward = false;
}
if (_currentBlock.transform.position.x <= -MaxBoundary || _currentBlock.transform.position.z <= -MaxBoundary)
{
_isForward = true;
}
yield return new WaitForEndOfFrame();
}
}
private void StopMoving()
{
StopAllCoroutines();
_isMoving = false;
_currentBlock = null;
_lastBlock = _startBlock;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.FileGenerate.Model
{
public enum MessageType
{
Header = 10,
Record = 20,
Trailer = 30
}
public class HeaderFile
{
public MessageType MessageType { get; set; } = MessageType.Header;
/// <summary>
/// 32 carcteres
/// </summary>
public string Code { get; set; }
public DateTime CreatedAt { get; set; }
/// <summary>
/// 1 - enviado, 2 - aprovado, 3 reprovado
/// </summary>
public int Status { get; set; }
public override string ToString()
{
return $"{MessageType}{Code}{CreatedAt:yyyyMMdd}{Status}";
}
}
public class RecordFile
{
}
public class TrailerFile
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestText : MonoBehaviour {
public static TestText instance;
public Text HitStatus;
public float Delay;
float Timer;
private void Awake()
{
instance = this;
}
// Use this for initialization
void Start () {
Timer = 0f;
}
// Update is called once per frame
void Update () {
Timer += Time.deltaTime;
if(Timer > Delay){
HitStatus.text = "";
}
}
public void Write(string s){
HitStatus.text = s;
Timer = 0f;
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
class DistributeObjects : EditorWindow {
Transform startTransform;
Transform endTransform;
// bool rotate = false;
[MenuItem("Window/Distribute Objects")]
public static void ShowWindow() {
EditorWindow.GetWindow(typeof(DistributeObjects));
}
void OnGUI() {
GUILayout.Label("Even distribution tool!");
GUILayout.Label("Select 1+ objects");
// GUILayout.Label("Last 2 objects decide start and end.");
GUILayout.BeginHorizontal();
GUILayout.Label("Start:");
startTransform = (Transform)EditorGUILayout.ObjectField(startTransform, typeof(Transform), true);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("End:");
endTransform = (Transform)EditorGUILayout.ObjectField(endTransform, typeof(Transform), true);
GUILayout.EndHorizontal();
// GUILayout.Space(8);
// rotate = EditorGUILayout.Toggle("Also rotate?", rotate);
GUILayout.Space(16);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Distribute!", GUILayout.Width(165), GUILayout.Height(32))) {
DistributeSelection();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
void DistributeSelection() {
var selection = Selection.GetTransforms(
SelectionMode.TopLevel | SelectionMode.Editable
);
if (selection.Length < 1) {
Debug.LogWarning("Too few objects");
return;
}
// TODO: assign start and end to last 2 selected instead of name order
// Transform startTransform = selection[selection.Length - 2];
// Transform endTransform = selection[selection.Length - 1];
for (
int i = 0;
i < selection.Length;// - 2;
i++) {
Transform currentTransform = selection[i];
Undo.RecordObject(currentTransform, "Moved object using custom tool");
currentTransform.position = Vector3.Lerp(startTransform.position, endTransform.position, (1f / (selection.Length + 1)) * (i + 1));
// TODO: rotate
}
Debug.Log("distributed " + selection.Length + " objects between " + startTransform.name + " and " + endTransform.name);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWorkFlow.DataBase;
namespace IWorkFlow.ORM
{
//Para_BizTypeDictionary
[Serializable]
[DataTableInfo("Para_BizTypeDictionary", "id")]
public class Para_BizTypeDictionary : QueryInfo
{
/// <summary>
/// id
/// </summary>
[DataField("id", "Para_BizTypeDictionary",false)]
public int? id
{
get { return _id; }
set { _id = value; }
}
private int? _id;
/// <summary>
/// 参数类型,key
/// </summary>
[DataField("lx", "Para_BizTypeDictionary")]
public string lx
{
get { return _lx; }
set { _lx = value; }
}
private string _lx;
/// <summary>
/// 参数名称
/// </summary>
[DataField("mc", "Para_BizTypeDictionary")]
public string mc
{
get { return _mc; }
set { _mc = value; }
}
private string _mc;
/// <summary>
/// 创建时间
/// </summary>
[DataField("cjsj", "Para_BizTypeDictionary")]
public DateTime? cjsj
{
get { return _cjsj; }
set { _cjsj = value; }
}
private DateTime? _cjsj;
/// <summary>
/// 是否启用,默认为1,1为启用
/// </summary>
[DataField("sfqy", "Para_BizTypeDictionary")]
public string sfqy
{
get { return _sfqy; }
set { _sfqy = value; }
}
private string _sfqy;
/// <summary>
/// 权限组集名称
/// </summary>
[DataField("qxzj", "Para_BizTypeDictionary")]
public string qxzj
{
get { return _qxzj; }
set { _qxzj = value; }
}
private string _qxzj;
/// <summary>
/// 备注
/// </summary>
[DataField("bz", "Para_BizTypeDictionary")]
public string bz
{
get { return _bz; }
set { _bz = value; }
}
private string _bz;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Core.Common;
using Framework.Helpers.Pages.FastAction;
using NUnit.Framework;
namespace Framework.Tests.Oberon.FastAction
{
public class FastActionSignUpAccount
{
private Driver _driver;
[SetUp]
public void SetUp()
{
_driver = new Driver();
}
[Test]
[Category("oberon"), Category("oberon_fastaction"), Category("oberon_login")]
public void TestCaseFastActionSignUp()
{
FastActionHome.GoTo();
FastActionMyProfile.GoTo();
FastActionHome.SingupAs(FakeData.RandomEmailAddress(),FakeData.RandomLetterString(10),1);
Assert.IsTrue(_driver.ContainsText("Welcome, "));
}
[TearDown]
public void TearDown()
{
//browser quit
_driver.BrowserQuit();
}
}
}
|
using SimpleJSON;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Ball : MonoBehaviour
{
[Header("Ball Properties")]
public int id;
public Renderer renderer;
public TrailRenderer trail;
public float ballSpeed;
List<Vector3> routes;
Vector3 startPosition;
bool oneClick;
float clickTime;
bool isMoving;
void Awake()
{
//Инициализация списка координат
routes = new List<Vector3>();
//Установка имени объекта и загрузка материала из ресурсов
gameObject.name = "Ball_" + id;
renderer.material = trail.material = Resources.Load<Material>(string.Concat("Materials\\Ball", id.ToString()));
}
void Start()
{
//Получение координат из Global в формате JSON
JSONNode coordinates = Global.GetGlobal.GetCoordinates[id];
//Заполнение списка координат из JSON
for (int i = 0; i < coordinates["x"].Count; i++)
{
routes.Add(new Vector3(coordinates["x"][i].AsFloat,
coordinates["y"][i].AsFloat,
coordinates["z"][i].AsFloat));
}
//Установка стартовых значений и стартовой позиции
oneClick = false;
isMoving = false;
startPosition = transform.position = routes[0];
}
//Обработка события при нажатии на шар
public void OnMouseDown()
{
//Проверка, если поверх шара был нажат UI элемент
if (EventSystem.current.IsPointerOverGameObject())
{
return;
}
//Если один клик был произведен, то проверяется интервал между первым и вторым кликом и если он больше заданного интервала, то клик обнуляется
if (oneClick)
{
if ((Time.time - clickTime) > Global.GetGlobal.doubleClickDelay)
{
oneClick = false;
}
}
//Если клика не было или он обнулился, то начинается движение шара, если он находился в покое
if (!oneClick)
{
//Фиксируем, что один клик был
oneClick = true;
//Засекаем время нажатия для дальнейшего подсчета интервала между кликами
clickTime = Time.time;
//Проверка на движение шара. Если шар в движении, преждевременно выходим из метода
if (isMoving)
{
return;
}
//Запускаем движение и устанавливаем маркер
isMoving = true;
StartCoroutine(MoveBall());
}
//Если же двойной клик прошел, то шар возвращается в стартовую позицию, прекращая свое движение, если он в нем был. Так же выключается слайдер, очищается линия пути и убираются все маркеры.
else
{
oneClick = false;
StopAllCoroutines();
UI.GetUI.SliderOff();
trail.Clear();
transform.position = startPosition;
isMoving = false;
}
}
//Корутина движения шара. Замена Update, т.к. нет смысла работать update постоянно, когда шар должен двигаться только по клику
IEnumerator MoveBall()
{
//Очищаем линию с предыдущего пути
trail.Clear();
//Запускаем слайдер скорости
UI.GetUI.SliderOn();
//Задаем стартовую скорость шара
ballSpeed = Global.GetGlobal.startBallSpeed;
//Инициализируем индекс для прохода по списку координат
int index = 0;
//Выполнять процесс движения, пока индекс не выйдет за пределы кол-ва элементов в списке координат. Иными словами, пока не доберется до последней точки.
while (index < routes.Count)
{
//Если координаты шара и текущих координат совпадают, индекс увеличивается, т.е. теперь будут браться следующие координаты
if (transform.position == routes[index])
{
index++;
}
//Иначе шар будет двигаться к текущим координатам
else
{
transform.position = Vector3.MoveTowards(transform.position, routes[index], ballSpeed * Time.deltaTime);
}
yield return null;
}
//Выключается слайдер и снимается маркер движения, т.е. шар остановился.
UI.GetUI.SliderOff();
isMoving = false;
yield return null;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientAdminFastFood.Models
{
class Account
{
public int Ma { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
[Browsable(false)]
public int? MaNguoiDung { get; set; }
[ForeignKey(nameof(MaNguoiDung))]
[Browsable(false)]
public virtual NguoiDung NguoiDung { get; set; }
public string TenNguoiDung { get => NguoiDung.Ten; }
[Browsable(false)]
public int? MaKhachHang { get; set; }
[ForeignKey(nameof(MaKhachHang))]
[Browsable(false)]
public virtual KhachHang KhachHang { get; set; }
public string tenkhachhang { get => KhachHang.Ten; }
[Browsable(false)]
public int? MaNhomNguoiDung { get; set; }
[ForeignKey(nameof(MaNhomNguoiDung))]
[Browsable(false)]
public virtual NhomNguoiDung NhomNguoiDung { get; set; }
public string TenNhomNguoiDung { get => NhomNguoiDung.Ten; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.