text stringlengths 13 6.01M |
|---|
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// NOTE: This file is a modified version of SymbolResolver.cs from OleViewDotNet
// https://github.com/tyranid/oleviewdotnet. It's been relicensed from GPLv3 by
// the original author James Forshaw to be used under the Apache License for this
// project.
using System;
namespace NtApiDotNet.Win32.Debugger
{
[Flags]
enum EnumProcessModulesFilter
{
LIST_MODULES_DEFAULT = 0x00,
LIST_MODULES_32BIT = 0x01,
LIST_MODULES_64BIT = 0x02,
LIST_MODULES_ALL = LIST_MODULES_32BIT | LIST_MODULES_64BIT,
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FuzzyLogic.Model
{
class Cutout : AbstractFuzzyfication<ChartItems.ChartItem3Degree>
{
public Cutout(int dokladnosc)
{
CreateData(dokladnosc);
}
public void CreateData(int dokladnosc)
{
int XClosed = 0;
int XMedium = dokladnosc / 2;
int XOpen = dokladnosc;
int range = dokladnosc / 2;
for (int i = 0; i <= dokladnosc; i++)
{
ChartItems.ChartItem3Degree result3Degree = new ChartItems.ChartItem3Degree();
result3Degree.X = i;
result3Degree.Min = RozmywanieTrapez(i, 0, XClosed, range);
result3Degree.Mid = RozmywanieTriangle(i, XMedium, range);
result3Degree.Max = RozmywanieTrapez(i, XOpen, dokladnosc, range);
result3Degree.Text = "X=" + i + Environment.NewLine + "Min=" + result3Degree.Min + Environment.NewLine + "Mid=" + result3Degree.Mid + Environment.NewLine + "Max=" + result3Degree.Max;
base.Add(result3Degree);
}
}
}
}
|
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ToolBox;
namespace DataIngress.Tests
{
[TestClass]
public class CsvTests
{
//public const string Basepath = @"H:\KMPGData\";
public const string Datafile = "KMPGDatasample3.csv";
public const string ZipCodesfile = "ZipCodes.csv";
[TestMethod]
public void ReadsCsvDataFile()
{
var result = ToolBox.IO.ReadDataFile(Datafile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
public void Reads10LinesFromDataFile()
{
var result = ToolBox.IO.ReadLinesFromDataFile(Datafile, 10);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 10);
}
[TestMethod]
public void Reads10LinesFromZipCodeFile()
{
var result = ToolBox.IO.ReadLinesFromZipCodeFile(ZipCodesfile, 10);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 10);
}
[TestMethod]
public void DeserializesDataFile()
{
AppRecordReader reader = new AppRecordReader();
var result = reader.DeserializeAppRecords(Datafile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
public void DeserializesOneRecordFromTheDataFile()
{
AppRecordReader reader = new AppRecordReader();
var result = reader.DeserializeOneAppRecord(Datafile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 1);
}
[TestMethod]
public void DeserializesOneRecordFromTheZipCodeFile()
{
ZipCodeReader reader = new ZipCodeReader();
var result = reader.DeserializeOneZipCodeRecord(ZipCodesfile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 1);
}
[TestMethod]
public void GetsTheDataFileHeaderRecord()
{
AppRecordReader reader = new AppRecordReader();
var result = reader.GetHeaderLine(Datafile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 1);
var firstOrDefault = result.FirstOrDefault();
Assert.IsTrue(firstOrDefault != null && firstOrDefault.StartsWith("leadID"));
}
[TestMethod]
public void DeserializesZipCodesFile()
{
ZipCodeReader reader = new ZipCodeReader();
var result = reader.DeserializeZipCodes(ZipCodesfile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
public void GetsTheZipCodeFileHeaderRecord()
{
AppRecordReader reader = new AppRecordReader();
var result = reader.GetHeaderLine(ZipCodesfile);
Assert.IsNotNull(result);
Assert.IsTrue(result.Count == 1);
var firstOrDefault = result.FirstOrDefault();
Assert.IsTrue(firstOrDefault != null && firstOrDefault.StartsWith("StateCode"));
}
}
}
|
using System;
using System.Net;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace sendHTML
{
internal class Program
{
private static void Main(string[] args)
{
// Changez le Path pour correspondre à la destination de votre fichier de configuration
var doc = new XmlDocument();
doc.Load("config.xml");
var xKey = doc.DocumentElement.SelectSingleNode("/config/xKey").InnerText;
var baseUrl = doc.DocumentElement.SelectSingleNode("/config/url").InnerText;
//Ici, renseignez l'email de la cible, la xKey, l'id du message
const string unicity = "test@test.com";
const string idMessage = "000000";
const string htmlMessage = "html message for Csharp"; //Si vous ne voulez pas de cette option, commentez la ligne de creation du Json
const string textMessage = "text message for Csharp"; //Si vous ne voulez pas de cette option, commentez la ligne de creation du Json
const string subject = "subject for Csharp";
const string mailFrom = "mail@address.com";
const string replyTo = "mail@return.com";
//Appel de la fonction Connect
var url = baseUrl + "targets?unicity=" + unicity;
var reponse = Utils.allConnection(url, xKey, null, "GET");
//Verification des reponses
if ((int)reponse[0] == 200)
{
Console.Write("{0}", (string)reponse[3]);
}
else
{
//Affichage de l'erreur
Console.Write("Error : {0} {1}", (int)reponse[0], ((HttpWebResponse)reponse[2]).StatusCode.ToString());
((HttpWebResponse)reponse[2]).Close();
return;
}
((HttpWebResponse)reponse[2]).Close();
//On affiche la cible
Console.Write((string)reponse[3] + "\n");
//On prend le idTarget
dynamic responseJson = JsonConvert.DeserializeObject((string)reponse[3]);
string idTarget = responseJson.id;
//Nouvelle url en fonction de l'id du message et de la cible
url = baseUrl + "actions/" + idMessage + "/targets/" + idTarget;
//Creation du message en Json
var content = new JObject();
content.Add("html", htmlMessage); //Si vous ne voulez pas de l'option : htmlMessage, commentez cette ligne
content.Add("text", textMessage); //Si vous ne voulez pas de l'option : textMessage, commentez cette ligne
var header = new JObject();
header.Add("subject", subject);
header.Add("mailFrom", mailFrom);
header.Add("replyTo", replyTo);
var jsonMessage = new JObject();
jsonMessage.Add("content", content);
jsonMessage.Add("header", header);
Console.WriteLine("Sending :\n" + jsonMessage + '\n');
//Lancement de la connexion pour remplir la requete
reponse = Utils.allConnection(url, xKey, null, "POST");
//Verification des reponses
if ((int)reponse[0] == 200)
{
Console.Write("\nMessage sent to " + unicity);
}
else
{
//Affichage de l'erreur
Console.Write("Error : {0} {1}", (int)reponse[0], ((HttpWebResponse)reponse[2]).StatusCode.ToString());
}
//Attente de lecture (optionnel)
Console.ReadLine();
((HttpWebResponse)reponse[2]).Close();
}
}
}
|
namespace LiskovSubstitutionSquareAfter
{
public class Square : Shape
{
public decimal Side { get; set; }
public override decimal Area
{
get
{
return this.Side * this.Side;
}
}
}
} |
namespace WebApi.Models
{
using System.Collections.Generic;
public class Company
{
public Company()
{
}
public int CompanyId { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; } = new List<User>();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace C1ILDGen
{
public partial class frmSplash : Form
{
#region FIELDS
Timer timer = new Timer();
bool fadeIn = true;
bool fadeOut = true;
#endregion
public frmSplash()
{
InitializeComponent();
ExtraFormSettings();
SetAndStartTimer();
}
private void SetAndStartTimer()
{
timer.Interval = 10;
timer.Tick += new EventHandler(t_Tick);
timer.Start();
}
private void ExtraFormSettings()
{
this.FormBorderStyle = FormBorderStyle.None;
this.Opacity = 0.7;
//this.BackgroundImage = Properties.;
}
#region EVENTS
void t_Tick(object sender, EventArgs e)
{
if (fadeIn)
{
if (this.Opacity < 1.0)
{
this.Opacity += 0.01;
}
else
{
fadeIn = false;
fadeOut = true;
}
}
else if (fadeOut)
{
if (this.Opacity > 0.7)
{
this.Opacity -= 0.01;
}
else
{
fadeOut = false;
}
}
if (!(fadeIn || fadeOut))
{
timer.Stop();
this.Close();
}
}
#endregion
}
}
|
namespace Services.Descriptors
{
public class AdminDescriptor
{
public string Email { get; set; }
public string Password { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Stage6Talk : StageBase
{
public GameObject yukariObject;
GameObject yukari, yukariMask;
GameObject yukariChara;
Yukari yukariScript;
GraphDiffer yukariBody;
protected CharaPicture yukariPicture;
int firstObentouBulletCount;
int firstMaxHp;
int firstZundaBombBulletCount;
bool isPlayingBattle2;
// Start is called before the first frame update
void Start()
{
ResetSceneParameters();
StaticValues.havingShooter = 4;
step = StaticValues.stage6Step;
firstObentouBulletCount = StaticValues.obentouBulletMax;
firstMaxHp = StaticValues.maxHp;
firstZundaBombBulletCount = StaticValues.zundaBombBulletMax;
yukariChara = GameObject.Find("Yukari");
if (yukariChara != null)
yukariScript = yukariChara.GetComponent<Yukari>();
if (StaticValues.isEXMode)
{
step = 9999;
GameObject.Find("door").SetActive(false);
}
AkariInstantiate();
YukariInstantiate();
AudioManager.Instance.ChangeDSPSnapshot("AddReverb");
LoadACB("Stage6", "Stage6.acb");
PlayBGM("stage");
StaticValues.Save();
}
// Update is called once per frame
void Update()
{
StaticValues.stage3Step = 7;
bool forceNext = false;
time += Time.deltaTime;
if (step == 0 && time >= 2.0f)
forceNext = true;
// ボス撃破後に連打でページ送りしてしまうのを防止するため1秒入力を受け付けない
if (StaticValues.isTalkPause)
{
if (time >= 1.0f)
{
StaticValues.isTalkPause = false;
} else
{
return;
}
}
if (step <= 5)
StaticValues.isPause = true;
if (firstObentouBulletCount != StaticValues.obentouBulletMax)
{
firstObentouBulletCount = StaticValues.obentouBulletMax;
step = 101;
forceNext = true;
}
if (firstMaxHp != StaticValues.maxHp)
{
firstMaxHp = StaticValues.maxHp;
step = 201;
forceNext = true;
}
if (firstZundaBombBulletCount != StaticValues.zundaBombBulletMax)
{
firstZundaBombBulletCount = StaticValues.zundaBombBulletMax;
step = 301;
forceNext = true;
}
if (bossStageEntrance != null && bossStageEntrance.GetTrigger() && !isBossEnter)
{
if (StaticValues.isEXMode)
{
isBossEnter = true;
enemyGaugeScript.PlayGaugeAppear();
PlayBGM("boss");
}
else
{
StaticValues.isPause = true;
if (!cameraScript.IsFixPosMoving())
{
isBossEnter = true;
tmpStep = step;
step = 501;
forceNext = true;
}
}
}
if (isPlayingBattle2 == false)
{
//ボス第一段階
if (yukariScript != null && yukariScript.IsDead() && !isBossDead)
{
isBossDead = true;
tmpStep = step;
step = 601;
forceNext = true;
}
}
else
{
//ボス第二段階
if (yukariScript.IsDead())
{
if (StaticValues.isEXMode)
{
ChangeScene("TitleScene");
}
else
{
step = 701;
forceNext = true;
isPlayingBattle2 = false;
}
}
}
if (Input.GetButtonDown("Shot") || Input.GetButtonDown("Jump") || forceNext)
{
UpdateStep();
}
StaticValues.stage6Step = step;
}
void UpdateStep()
{
switch (step)
{
case 0:
akari.GetComponent<Animator>().SetBool("isOut", false);
akariPicture.SetSprite("normal", "white", "laugh", "nothing");
AddTextWindow(speechWindowLeft, "ごめんくださーい");
PlayVoice("Stage4Akari-0");
break;
case 1:
akariPicture.SetSprite("sad", "normal", "omega");
AddTextWindow(speechWindowLeft, "開け放たれてたから\n入っちゃったけど、\n誰も住んでないよね...?");
PlayVoice("Stage4Akari-1");
break;
case 2:
akariPicture.SetSprite("anger", "shiitake", "triangle");
AddTextWindow(speechWindowLeft, "しかし立派な造りだなぁ\n山の上にこんなお城が\nあったなんて");
PlayVoice("Stage4Akari-2");
break;
case 3:
akariPicture.SetSprite("", "normal", "omega");
AddTextWindow(speechWindowLeft, "とりあえず\n上の階を目指せば良いのかな");
PlayVoice("Stage4Akari-3");
break;
case 4:
akariPicture.SetSprite("normal", "white", "", "question");
AddTextWindow(speechWindowLeft, "それにしても、最後の一人って一体誰なんだろう?");
PlayVoice("Stage4Akari-3");
break;
case 5:
akariPicture.SetSprite("anger", "normal", "laugh", "nothing");
AddTextWindow(speechWindowLeft, "まぁいいか、\nここまで来たからには\n優勝するぞ!");
PlayVoice("Stage4Akari-3");
break;
case 6:
step++;
break;
case 7:
akari.GetComponent<Animator>().SetBool("isOut", true);
step++;
StaticValues.isPause = false;
break;
case 8:
break;
case 101:
StaticValues.isPause = true;
if (akari == null)
{
AkariInstantiate();
}
akariPicture.SetSprite("normal", "shiitake", "laugh");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "携帯食だ!");
PlayVoice("Stage4Akari-4");
break;
case 102:
akariPicture.SetSprite("", "smile", "omega");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "お弁当の量が\n増えました!");
PlayVoice("Stage4Akari-5");
break;
case 103:
step++;
break;
case 104:
StaticValues.isPause = false;
akari.GetComponent<Animator>().SetBool("isOut", true);
break;
case 105:
break;
case 201:
StaticValues.isPause = true;
if (akari == null)
{
AkariInstantiate();
}
akariPicture.SetSprite("anger", "star", "laugh");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "パワーアップアイテムだ!");
PlayVoice("Stage4Akari-6");
break;
case 202:
StaticValues.isPause = true;
akariPicture.SetSprite("", "smile");
AddTextWindow(speechWindowLeft, "体力が少し増えました!");
PlayVoice("Stage4Akari-7");
break;
case 203:
step++;
break;
case 204:
StaticValues.isPause = false;
akari.GetComponent<Animator>().SetBool("isOut", true);
break;
case 205:
break;
case 301:
StaticValues.isPause = true;
if (akari == null)
{
AkariInstantiate();
}
akariPicture.SetSprite("anger", "star", "laugh");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "パワーアップアイテムだ!");
PlayVoice("Stage4Akari-8");
break;
case 302:
akariPicture.SetSprite("", "smile", "omega");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "ずんだボムの\n残弾数が一つ増えました!");
PlayVoice("Stage4Akari-9");
break;
case 303:
step++;
break;
case 304:
StaticValues.isPause = false;
akari.GetComponent<Animator>().SetBool("isOut", true);
break;
case 305:
case 501:
akari.GetComponent<Animator>().SetBool("isOut", false);
akariPicture.SetSprite("sad", "white", "omega", "nothing");
AddTextWindow(speechWindowLeft, "屋上まで来ちゃったけど、\nこっちじゃなかったかな?");
break;
case 502:
akariPicture.SetSprite("", "half_open");
AddTextWindow(speechWindowLeft, "でも他にそれっぽい道も\n無かったしなあ...");
break;
case 503:
AddTextWindow(speechWindowRight, "よくぞここまで\nたどり着きましたね、\nあかりちゃん");
break;
case 504:
akariPicture.SetSprite("anger", "white", "o", "flash");
AddTextWindow(speechWindowLeft, "え?\nこの声は、まさか");
break;
case 505:
yukari.GetComponent<Animator>().SetBool("isOut", false);
yukariPicture.SetSprite("anger", "close", "laugh");
AddTextWindow(speechWindowRight, "そう、私です");
yukariScript.Appear();
break;
case 506:
akariPicture.SetSprite("normal", "normal", "o", "nothing");
// TODO 呼び方を ゆかりさん -> ゆかり先輩に統一する。 ボイス作る時にPrologueの方の呼び方を変えるのを忘れないように
AddTextWindow(speechWindowLeft, "どうしてゆかり先輩が\nこんなところに?");
break;
case 507:
akariPicture.SetSprite("", "", "mu");
AddTextWindow(speechWindowLeft, "先代チャンプは\n非出場だったはずじゃあ...");
break;
case 508:
yukariPicture.SetSprite("normal", "", "omega");
AddTextWindow(speechWindowRight, "知らなかったようなので\nあえて言っていませんでしたが");
break;
case 509:
yukariPicture.SetSprite("", "normal", "cat");
AddTextWindow(speechWindowRight, "前年度優勝者はこうして\n最後の関門として立つことに\nなっているのですよ");
break;
case 510:
yukariPicture.SetSprite("anger", "half_open", "nisisi");
AddTextWindow(speechWindowRight, "チャレンジャーから\nメダルを防衛する\nチャンピオンのようなものです");
break;
case 511:
yukariPicture.SetSprite("normal", "smile", "laugh", "laugh");
AddTextWindow(speechWindowRight, "それっぽいでしょう?");
break;
case 512:
akariPicture.SetSprite("sad", "white_tears", "laugh", "sweat4");
AddTextWindow(speechWindowLeft, "そ、そんな...ということは、\n私はこれからゆかり先輩と...");
break;
case 513:
yukariPicture.SetSprite("", "close", "laugh", "nothing");
AddTextWindow(speechWindowRight, "そう。ここまでたどり着いた\n貴方にはその資格があります");
break;
case 514:
yukariPicture.SetSprite("", "", "omega");
AddTextWindow(speechWindowRight, "初めて武器を手にして、\nバルーンを狙って練習していた時とはまるで別人のようですね");
break;
case 515:
yukariPicture.SetSprite("anger", "normal", "laugh");
AddTextWindow(speechWindowRight, "実践を経て身につけたその力を\n是非見せてください");
break;
case 516:
akariPicture.SetSprite("anger", "normal", "mu", "nothing");
AddTextWindow(speechWindowLeft, "わ、わかりました...!");
break;
case 517:
yukariPicture.SetSprite("", "close");
AddTextWindow(speechWindowRight, "よし、それでは...");
break;
case 518:
yukariPicture.SetSprite("", "normal");
AddTextWindow(speechWindowRight, "初めましょうか!");
PlayVoice("Stage4yukari-5");
//yukariBody.SetSprite("yukari7");
//yukariPicture.SetSprite("nothing", "nothing", "nothing");
PlayBGM("boss");
yukariScript.WeaponSetUp();
break;
case 519:
step++;
break;
case 520:
yukari.GetComponent<Animator>().SetBool("isOut", true);
akari.GetComponent<Animator>().SetBool("isOut", true);
enemyGaugeScript.PlayGaugeAppear();
yukariScript.PositionSetUp();
step++;
break;
case 521:
break;
case 601:
StaticValues.isPause = true;
StaticValues.isTalkPause = true;
time = 0;
AudioManager.Instance.FadeInBGM("stage");
yukari.GetComponent<Animator>().SetBool("isOut", false);
akari.GetComponent<Animator>().SetBool("isOut", false);
yukariPicture.SetSprite("sad", "white_tears", "omega", "sweat", "sweat2", "blusher");
AddTextWindow(speechWindowRight, "っ...!\nお見事です");
break;
case 602:
akariPicture.SetSprite("anger", "normal", "laugh", "nothing");
AddTextWindow(speechWindowLeft, "ど、どうですか...!");
break;
case 603:
yukariPicture.SetSprite("normal", "normal", "smile");
AddTextWindow(speechWindowRight, "スターシューターだけでなく、\n他の武器も手に入れて\nいたんですね");
yukariScript.TalkingJumpCenter();
break;
case 604:
akariPicture.SetSprite("normal", "smile");
AddTextWindow(speechWindowLeft, "みなさんがくれました!");
break;
case 605:
yukariPicture.SetSprite("", "close", "laugh", "sweat", "blusher2", "blusher");
AddTextWindow(speechWindowRight, "きりたんマキさんずん子さんに\n正面から打ち勝った、\n他ならぬ証拠ですね");
break;
case 606:
yukariPicture.SetSprite("", "", "o");
AddTextWindow(speechWindowRight, "そんなあかりちゃんに、\n餞別として一つ有益なことを\n教えてあげましょう");
break;
case 607:
yukariPicture.SetSprite("", "", "omega", "nothing");
AddTextWindow(speechWindowRight, "ラスボスにはね...");
break;
case 608:
PlayBGM("boss");
yukariPicture.SetSprite("anger", "light_off", "cat", "dark", "star", "nothing");
AddTextWindow(speechWindowRight, "第二形態が付き物なんですよ!");
yukariScript.TalkingTripleShot();
break;
case 609:
akariPicture.SetSprite("anger", "white", "cat", "flash");
AddTextWindow(speechWindowLeft, "なっ!\nそ、その技は!");
break;
case 610:
yukariPicture.SetSprite("", "close", "cat", "", "blusher2", "blusher");
AddTextWindow(speechWindowRight, "先代も同じ道を\n通った後と言うことです。");
break;
case 611:
yukariPicture.SetSprite("", "normal", "cat");
AddTextWindow(speechWindowRight, "さあ行きますよ!");
break;
case 612:
yukariPicture.SetSprite("", "smile");
AddTextWindow(speechWindowRight, "次で全てを叩き込みます\n新米の後輩ちゃんには着いて\nこれないかもしれませんね!");
break;
case 613:
akariPicture.SetSprite("anger", "star", "laugh", "nothing");
AddTextWindow(speechWindowLeft, "やってやりますよお!!");
break;
case 614:
yukariPicture.SetSprite("", "normal", "laugh");
AddTextWindow(speechWindowLeft, "うおおおおおお!");
AddTextWindow(speechWindowRight, "うおおおおおお!");
step = 650;
break;
case 650:
step++;
break;
case 651:
yukari.GetComponent<Animator>().SetBool("isOut", true);
akari.GetComponent<Animator>().SetBool("isOut", true);
yukariScript.SetHp(100.0f);
enemyGaugeScript.PlayGaugeReAppear(100);
isPlayingBattle2 = true;
step++;
break;
case 652:
break;
case 701:
StaticValues.isPause = true;
StaticValues.isTalkPause = true;
time = 0;
AudioManager.Instance.FadeInBGM("stage");
yukari.GetComponent<Animator>().SetBool("isOut", false);
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowRight, "2戦目も終わった後");
break;
case 702:
break;
}
}
void PlayVoice(string seName)
{
AudioManager.Instance.PlayExVoice(seName);
}
void YukariInstantiate()
{
if (yukari == null)
{
yukari = Instantiate(yukariObject);
yukari.transform.SetParent(transform.parent);
yukari.transform.localScale = new Vector2(1, 1);
yukariBody = yukari.GetComponent<GraphDiffer>();
yukariMask = yukari.transform.Find("BlackMask").gameObject;
yukariMask.SetActive(false);
yukariPicture = new CharaPicture(yukari);
//yukari.transform.SetAsFirstSibling();
DontDestroyOnLoad(yukari);
}
}
}
|
/** 版本信息模板在安装目录下,可自行修改。
* TEMPLATE_INFO.cs
*
* 功 能: N/A
* 类 名: TEMPLATE_INFO
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014-6-26 9:19:18 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using PDTech.OA.Model;
namespace PDTech.OA.BLL
{
/// <summary>
/// 模板信息表
/// </summary>
public partial class TEMPLATE_INFO
{
private readonly PDTech.OA.DAL.TEMPLATE_INFO dal = new PDTech.OA.DAL.TEMPLATE_INFO();
public TEMPLATE_INFO()
{ }
#region BasicMethod
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(PDTech.OA.Model.TEMPLATE_INFO model)
{
return dal.Add(model);
}
/// <summary>
/// 更新一条数据
/// </summary>
public int Update(PDTech.OA.Model.TEMPLATE_INFO model)
{
return dal.Update(model);
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(decimal TEMPLATE_ID)
{
return dal.Delete(TEMPLATE_ID);
}
/// <summary>
/// 获取信息
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public Model.TEMPLATE_INFO GetmTempInfo(decimal tId)
{
return dal.GetmTempInfo(tId);
}
/// <summary>
/// 获取模板信息-分页
/// </summary>
/// <param name="where"></param>
/// <param name="currentpage"></param>
/// <param name="pagesize"></param>
/// <param name="totalrecord"></param>
/// <returns></returns>
public IList<Model.TEMPLATE_INFO> get_Paging_tempList(Model.TEMPLATE_INFO where, int currentpage, int pagesize, out int totalrecord)
{
return dal.get_Paging_tempList(where,currentpage,pagesize,out totalrecord);
}
/// <summary>
///
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public IList<Model.TEMPLATE_INFO> get_Paging_tempList(Model.TEMPLATE_INFO where)
{
return dal.get_Paging_tempList(where);
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
using System.Threading.Tasks;
using Dapper;
using DDDSouthWest.Domain.Features.Account.Admin.ManageNews.ViewNewsDetail;
using Npgsql;
namespace DDDSouthWest.Domain.Features.Public.News.NewsDetail
{
public class QueryLiveNewsById
{
private readonly ClientConfigurationOptions _options;
public QueryLiveNewsById(ClientConfigurationOptions options)
{
_options = options;
}
public async Task<NewsModel> Invoke(int id)
{
using (var connection = new NpgsqlConnection(_options.Database.ConnectionString))
{
return await connection.QuerySingleOrDefaultAsync<NewsModel>("SELECT Id, Title, Filename, BodyHtml AS Body, IsLive, DatePosted FROM news WHERE Id = @id AND IsLive = TRUE LIMIT 1", new {id});
}
}
}
} |
using System;
namespace Siemens.Simatic.RfReader
{
/// <summary>
/// Used to qualify information conveyed for later filtering
/// </summary>
public enum InformationType
{
/// <summary>Unspecified information</summary>
Unspecified = 0,
/// <summary>Information needed for debugging only.</summary>
Debug,
/// <summary>General information.</summary>
Info,
/// <summary>Just to notify users.</summary>
Notice,
/// <summary>A warning.</summary>
Warning,
/// <summary>An error.</summary>
Error,
/// <summary>A critical error.</summary>
Critical,
/// <summary>A very critical error.</summary>
Alert,
/// <summary>Better leave the building - now!</summary>
Emergency
}
/// <summary>
/// The argument class for information provision
/// </summary>
public class InformationArgs : EventArgs
{
private InformationType type = InformationType.Unspecified;
/// <summary>
/// The category this information belongs to, e.g. Debug, Notice, Error,...
/// </summary>
public InformationType Type
{
get { return type; }
set { type = value; }
}
private string message = "";
/// <summary>
/// Access the stored message
/// </summary>
public string Message
{
get { return message; }
set { message = value; }
}
/// <summary>
/// Initialize an information structure
/// </summary>
/// <param name="type">The severity level of this information.</param>
/// <param name="message">The message to be used</param>
public InformationArgs(InformationType type, string message)
{
this.type = type;
this.message = message;
NewLine();
}
/// <summary>
/// Initialize an information structure
/// </summary>
/// <param name="message">The message to be used</param>
public InformationArgs(string message)
{
this.message = message;
this.type = InformationType.Info;
NewLine();
}
/// <summary>
/// Initialize an information structure
/// </summary>
/// <param name="message">The message to be used</param>
/// <param name="fSingleLine">Allow suppression of newline at the end of the message.</param>
public InformationArgs(string message, bool fSingleLine)
{
this.message = message;
if (!fSingleLine)
{
NewLine();
}
}
/// <summary>
/// Initialize an information structure
/// </summary>
/// <param name="type">The severity level of this information.</param>
/// <param name="message">The message to be used</param>
/// <param name="fSingleLine">Allow suppression of newline at the end of the message.</param>
public InformationArgs(InformationType type, string message, bool fSingleLine)
{
this.type = type;
this.message = message;
if (!fSingleLine)
{
NewLine();
}
}
/// <summary>
/// Add a new line
/// </summary>
public void NewLine()
{
this.message += "\r\n";
}
/// <summary>
/// Initialize an information structure with an exception
/// </summary>
/// <param name="ex">The exception whose information is to be passed on.</param>
public InformationArgs(System.Exception ex)
{
this.message = "Exception: " + ex.ToString();
this.type = InformationType.Error;
NewLine();
}
}
/// <summary>
/// The delegate to provide information.
/// </summary>
/// <param name="sender">The object sending the information.</param>
/// <param name="args">Additional arguments to be delivered.</param>
public delegate void InformationHandler(object sender, InformationArgs args);
} |
///01.Implement an extension method Substring(int index, int length) for the class StringBuilder
///that returns new StringBuilder and has the same functionality as Substring in the class String.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubstringExtensionMethod
{
public static class ExtensionString
{
//Extension method substring
public static StringBuilder Substring(this StringBuilder list, int index, int length)
{
StringBuilder newList = new StringBuilder();
if (index + length <= list.Length)
{
for (int i = index; i < length + index; i++)
{
newList.Append(list[i]);
}
}
else
{
throw new IndexOutOfRangeException();
}
return newList;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace RemoteTech
{
public class RelayNetwork
{
public List<RelayNode>
all,
comSats,
commandStations;
public RelayNetwork()
{
all = new List<RelayNode>();
comSats = new List<RelayNode>();
commandStations = new List<RelayNode>();
foreach (Vessel v in FlightGlobals.Vessels)
{
if (RTUtils.IsComsat(v)) all.Add(new RelayNode(v));
}
foreach (RelayNode node in all)
{
if (node.HasCommand) commandStations.Add(node);
else comSats.Add(node);
}
all.Add(new RelayNode());
commandStations.Add(new RelayNode());
foreach (KeyValuePair<Vessel, RemoteCore> pair in RTGlobals.coreList)
{
try
{
pair.Value.Rnode = new RelayNode(pair.Key);
}
catch { }
}
}
public void Reload()
{
foreach (RelayNode node in all) node.Reload();
foreach (RelayNode node in comSats) node.Reload();
foreach (RelayNode node in commandStations) node.Reload();
}
public void Reload(RelayNode reloadNode)
{
foreach (RelayNode node in all) if (node.Equals(reloadNode)) node.Reload();
foreach (RelayNode node in comSats) if (node.Equals(reloadNode)) node.Reload();
foreach (RelayNode node in commandStations) if (node.Equals(reloadNode)) node.Reload();
}
public RelayPath GetCommandPath(RelayNode start)
{
double compare = double.MaxValue;
RelayPath output = null;
foreach (RelayNode node in commandStations)
{
if (!start.Equals(node) && node.HasCommand)
{
RelayPath tmp = findShortestRelayPath(start, node);
if (tmp != null && tmp.Length < compare)
{
output = tmp;
compare = tmp.Length;
}
}
}
return output;
}
public bool inContactWith(RelayNode node, RelayNode other)
{
return (findShortestRelayPath(node, other) != null);
}
RelayPath findShortestRelayPath(RelayNode start, RelayNode goal)
{
HashSet<RelayNode> closedSet = new HashSet<RelayNode>();
HashSet<RelayNode> openSet = new HashSet<RelayNode>();
Dictionary<RelayNode, RelayNode> cameFrom = new Dictionary<RelayNode, RelayNode>();
Dictionary<RelayNode, double> gScore = new Dictionary<RelayNode, double>();
Dictionary<RelayNode, double> hScore = new Dictionary<RelayNode, double>();
Dictionary<RelayNode, double> fScore = new Dictionary<RelayNode, double>();
openSet.Add(start);
double startBaseHeuristic = (start.Position - goal.Position).magnitude;
gScore[start] = 0.0;
hScore[start] = startBaseHeuristic;
fScore[start] = startBaseHeuristic;
HashSet<RelayNode> neighbors = new HashSet<RelayNode>(all);
neighbors.Add(start);
neighbors.Add(goal);
RelayPath path = null;
while (openSet.Count > 0)
{
RelayNode current = null;
double currentBestScore = double.MaxValue;
foreach (KeyValuePair<RelayNode, double> pair in fScore)
{
if (openSet.Contains(pair.Key) && pair.Value < currentBestScore)
{
current = pair.Key;
currentBestScore = pair.Value;
}
}
if (current == goal)
{
path = new RelayPath(reconstructPath(cameFrom, goal));
break;
}
openSet.Remove(current);
closedSet.Add(current);
foreach (RelayNode neighbor in neighbors)
{
if (!closedSet.Contains(neighbor) && inRange(neighbor, current) && lineOfSight(neighbor, current))
{
//double tentGScore = gScore[current] - (neighbor.Position - current.Position).magnitude;
double tentGScore = gScore[current] + (neighbor.Position - current.Position).magnitude;
bool tentIsBetter = false;
if (!openSet.Contains(neighbor))
{
openSet.Add(neighbor);
hScore[neighbor] = (neighbor.Position - goal.Position).magnitude;
tentIsBetter = true;
}
else if (tentGScore < gScore[neighbor])
{
tentIsBetter = true;
}
if (tentIsBetter)
{
cameFrom[neighbor] = current;
gScore[neighbor] = tentGScore;
fScore[neighbor] = tentGScore + hScore[neighbor];
}
}
}
}
return path;
}
List<RelayNode> reconstructPath(Dictionary<RelayNode, RelayNode> cameFrom, RelayNode curNode)
{
List<RelayNode> tmp = null;
if (cameFrom.ContainsKey(curNode))
{
tmp = reconstructPath(cameFrom, cameFrom[curNode]);
tmp.Add(curNode);
}
else
{
tmp = new List<RelayNode>() { curNode };
}
return tmp;
}
// NK pull out distance return
// NK new distance calcs
// = weaker + sqrt(weaker * stronger), with these maximums:
// antenna to either: Max of 100x weaker.
// dish to dish: Max of 1000x weaker.
static float distFunc(float minRange, float maxRange, float clamp)
{
if (RTGlobals.useNewRange)
{
float temp = minRange + (float)Math.Sqrt(minRange * maxRange);
if (temp > clamp)
return clamp;
return temp;
}
else
return minRange;
}
public static float nodeDistance(RelayNode na, RelayNode nb)
{
return (float)(na.Position - nb.Position).magnitude;
}
public static float maxDistance(RelayNode na, RelayNode nb)
{
float aRange = 0, bRange = 0, aSumRange = 0, bSumRange = 0;
float clamp = 1000f;
bool aDish = false, bDish = false;
// get max-range dish pointed at other node
if (na.HasDish)
{
foreach (DishData naData in na.DishData)
{
if (((naData.pointedAt.Equals(nb.Orbits) && !na.Orbits.Equals(nb.Orbits)) || naData.pointedAt.Equals(nb.ID)))
{
aDish = true;
if (naData.dishRange >= aRange)
aRange = naData.dishRange;
aSumRange += naData.dishRange;
}
}
}
if(RTGlobals.useMultiple)
aRange = (float)Math.Round(aRange + (aSumRange - aRange) * 0.25f);
if(nb.HasDish)
{
foreach (DishData nbData in nb.DishData)
{
if (((nbData.pointedAt.Equals(na.Orbits) && !nb.Orbits.Equals(na.Orbits)) || nbData.pointedAt.Equals(na.ID)))
{
bDish = true;
if (nbData.dishRange >= bRange)
aRange = nbData.dishRange;
bSumRange += nbData.dishRange;
}
}
}
if (RTGlobals.useMultiple)
bRange = (float)Math.Round(bRange + (bSumRange - bRange) * 0.25f);
// if no dish, get antenna. If neither, fail.
if (!aDish)
{
clamp = 100f;
if (na.HasAntenna)
aRange = na.AntennaRange;
else
return 0f;
}
if (!bDish)
{
clamp = 100f;
if (nb.HasAntenna)
bRange = nb.AntennaRange;
else
return 0f;
}
// return distance using distance function; clamp to 1000x min range if both dishes or 100x if one or both isn't
if (aRange < bRange)
{
return distFunc(aRange, bRange, clamp * aRange);
}
else
{
return distFunc(bRange, aRange, clamp * bRange);
}
}
bool inRange(RelayNode na, RelayNode nb)
{
if (CheatOptions.InfiniteEVAFuel)
return true;
// NK refactor distance functions
float distance = nodeDistance(na, nb) * 0.001f; // convert to km
return maxDistance(na, nb) >= distance;
}
bool lineOfSight(RelayNode na, RelayNode nb)
{
if (CheatOptions.InfiniteEVAFuel)
return true;
Vector3d a = na.Position;
Vector3d b = nb.Position;
foreach (CelestialBody referenceBody in FlightGlobals.Bodies)
{
Vector3d bodyFromA = referenceBody.position - a;
Vector3d bFromA = b - a;
if (Vector3d.Dot(bodyFromA, bFromA) > 0)
{
Vector3d bFromAnorm = bFromA.normalized;
if (Vector3d.Dot(bodyFromA, bFromAnorm) < bFromA.magnitude)
{ // check lateral offset from line between b and a
Vector3d lateralOffset = bodyFromA - Vector3d.Dot(bodyFromA, bFromAnorm) * bFromAnorm;
if (lateralOffset.magnitude < (referenceBody.Radius - 5))
{
return false;
}
}
}
}
return true;
}
void print(String s)
{
MonoBehaviour.print(s);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SafeSpace.core.Data;
using SafeSpace.core.Models;
namespace SafeSpace.api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReportItemDefinitionsController : ControllerBase
{
private readonly SafeSpaceContext _context;
public ReportItemDefinitionsController(SafeSpaceContext context)
{
_context = context;
}
// GET: api/ReportItemDefinitions
[HttpGet]
public async Task<ActionResult<IEnumerable<ReportItemDefinition>>> GetReportItemDefinitions()
{
return await _context.ReportItemDefinitions.ToListAsync();
}
// GET: api/ReportItemDefinitions/5
[HttpGet("{id}")]
public async Task<ActionResult<ReportItemDefinition>> GetReportItemDefinition(long id)
{
var reportItemDefinition = await _context.ReportItemDefinitions.FindAsync(id);
if (reportItemDefinition == null)
{
return NotFound();
}
return reportItemDefinition;
}
// PUT: api/ReportItemDefinitions/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutReportItemDefinition(long id, ReportItemDefinition reportItemDefinition)
{
if (id != reportItemDefinition.Id)
{
return BadRequest();
}
_context.Entry(reportItemDefinition).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ReportItemDefinitionExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/ReportItemDefinitions
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<ReportItemDefinition>> PostReportItemDefinition(ReportItemDefinition reportItemDefinition)
{
_context.ReportItemDefinitions.Add(reportItemDefinition);
await _context.SaveChangesAsync();
return CreatedAtAction("GetReportItemDefinition", new { id = reportItemDefinition.Id }, reportItemDefinition);
}
// POST: api/ReportItemDefinitions
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost("uploaddefinitionlist")]
public async Task<ActionResult<List<ReportItemDefinition>>> UploadDefinitionList(List<ReportItemDefinition> reportItemDefinitions)
{
foreach (var def in reportItemDefinitions)
{
_context.ReportItemDefinitions.Add(def);
}
await _context.SaveChangesAsync();
return reportItemDefinitions;
}
// DELETE: api/ReportItemDefinitions/5
[HttpDelete("{id}")]
public async Task<ActionResult<ReportItemDefinition>> DeleteReportItemDefinition(long id)
{
var reportItemDefinition = await _context.ReportItemDefinitions.FindAsync(id);
if (reportItemDefinition == null)
{
return NotFound();
}
_context.ReportItemDefinitions.Remove(reportItemDefinition);
await _context.SaveChangesAsync();
return reportItemDefinition;
}
private bool ReportItemDefinitionExists(long id)
{
return _context.ReportItemDefinitions.Any(e => e.Id == id);
}
}
}
|
using MadScientistLab.Laboratory.Cli;
namespace MadScientistLab.Laboratory.LabInventory.Animals.Interfaces
{
public interface IPurrable
{
void Purr(ICommandInterface cli);
}
}
|
using System;
namespace SharpDL.Graphics
{
public struct Rectangle
{
/// <summary>Top left corner X coordinate.
/// </summary>
public int X { get; private set; }
/// <summary>
/// Top left corner Y coordinate.
/// </summary>
public int Y { get; private set; }
/// <summary>
/// Width of the Rectangle in pixels.
/// </summary>
public int Width { get; private set; }
/// <summary>
/// Height of the Rectangle in pixels.
/// </summary>
public int Height { get; private set; }
/// <summary>
/// Equal to Y coordinate plus the Height.
/// </summary>
public int Bottom => Y + Height;
/// <summary>Equal to Y.
/// </summary>
public int Top => Y;
/// <summary>Equal to X.
/// </summary>
public int Left => X;
/// <summary>Equal to X plus the Width.
/// </summary>
public int Right => X + Width;
/// <summary>Returns a Rectangle at (0,0) with 0 width and 0 height.
/// </summary>
/// <returns></returns>
public static Rectangle Empty => new Rectangle(0, 0, 0, 0);
/// <summary>
/// Returns true if width = 0 and height = 0.
/// </summary>
public bool IsEmpty => Width == 0 && Height == 0;
/// <summary>Returns a Point in 2D space at the top left corner of the Rectangle.
/// </summary>
public Point Location => new Point(X, Y);
/// <summary>Returns a 2D point closest to the center of the Rectangle.
/// </summary>
public Point Center => new Point(this.X + (this.Width / 2), this.Y + (this.Height / 2));
/// <summary>
/// Constructs a new rectangle.
/// </summary>
/// <param name="x">X coordinate of top left corner</param>
/// <param name="y">Y coordinate of top left corner.</param>
/// <param name="width">Width in pixels</param>
/// <param name="height">Height in pixels</param>
public Rectangle(int x, int y, int width, int height)
: this()
{
if (width < 0)
{
throw new ArgumentOutOfRangeException(nameof(width), "Width must be greater than or equal to 0.");
}
if (height < 0)
{
throw new ArgumentOutOfRangeException(nameof(height), "Height must be greater than or equal to 0.");
}
X = x;
Y = y;
Width = width;
Height = height;
}
/// <summary>
/// Indicates if a Point falls within the bounds of the Rectangle.
/// </summary>
/// <param name="point">Point to check within a Rectangle.</param>
/// <returns>True if the Point is contained within the Rectangle. Otherwise false.</returns>
public bool Contains(Point point)
{
return (Left <= point.X) && (Right >= point.X) && (Top <= point.Y) && (Bottom >= point.Y);
}
/// <summary>
/// Indicates if a Rectangle is fully contained within this Rectangle.
/// </summary>
/// <param name="rectangle">Rectangle to check if fully contained within this instanced Rectangle.</param>
/// <returns>True if the Rectangle is contained within this instanced Rectangle. Otherwise false.</returns>
public bool Contains(Rectangle rectangle)
{
return (Left <= rectangle.Left) && (Right >= rectangle.Right) && (Top <= rectangle.Top) && (Bottom >= rectangle.Bottom);
}
/// <summary>
/// Indicates if a Vector is fully contained within this Rectangle.
/// </summary>
/// <param name="vector">Vector to check if fully contained within this instanced Rectangle.</param>
/// <returns>True if the Vector is contained within this instanced Rectangle. Otherwise false.</returns>
public bool Contains(Vector vector)
{
return (Left <= vector.X) && (Right >= vector.X) && (Top <= vector.Y) && (Bottom >= vector.Y);
}
/// <summary>Determines if two Rectangles intersect.
/// </summary>
/// <param name="rectangle">Rectangle to check if intersects with this instanced Rectangle.</param>
/// <returns>True if the Rectangles intersect. Otherwise false.
public bool Intersects(Rectangle rectangle)
{
return (rectangle.Left <= Right) && (Left <= rectangle.Right) && (rectangle.Top <= Bottom) && (Top <= rectangle.Bottom);
}
/// <summary>
/// Calculates the depth at which two Rectangles are intersecting.
/// </summary>
/// <param name="rectangle">Rectangle aginst which to check the intersection depth.</param>
/// <returns>Vector containing the depth at which the Rectangles intersect.</returns>
public Vector GetIntersectionDepth(Rectangle rectangle)
{
// Calculate half sizes.
float halfWidthA = this.Width / 2.0f;
float halfHeightA = this.Height / 2.0f;
float halfWidthB = rectangle.Width / 2.0f;
float halfHeightB = rectangle.Height / 2.0f;
// Calculate centers.
Vector centerA = new Vector(this.Left + halfWidthA, this.Top + halfHeightA);
Vector centerB = new Vector(rectangle.Left + halfWidthB, rectangle.Top + halfHeightB);
// Calculate current and minimum-non-intersecting distances between centers.
float distanceX = centerA.X - centerB.X;
float distanceY = centerA.Y - centerB.Y;
float minDistanceX = halfWidthA + halfWidthB;
float minDistanceY = halfHeightA + halfHeightB;
// If we are not intersecting at all, return (0, 0).
if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
return Vector.Zero;
// Calculate and return intersection depths.
float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector(depthX, depthY);
}
}
} |
using CrossWeather.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CrossWeather.Core.Models;
using CrossWeather.Core.Repository;
namespace CrossWeather.Test
{
class Program
{
static void Main(string[] args)
{
WeatherRepositoryGetWeatherTest().Wait();
Console.ReadLine();
}
public static async Task<WeatherRoot> WeatherRepositoryGetWeatherTest()
{
Console.WriteLine("Doing Request to Weather API...");
var WeatherRepository = new WeatherRepository("Medellin");
var Weather = await WeatherRepository.GetWeather();
Console.WriteLine(Weather.Sys.Country);
Console.WriteLine(Weather.Name);
Console.WriteLine(Weather.Main.Temp);
Console.WriteLine("Request completed");
return Weather;
}
}
}
|
namespace SGDE.Domain.Repositories
{
#region Using
using SGDE.Domain.Entities;
using System.Collections.Generic;
#endregion
public interface ITypeDocumentRepository
{
List<TypeDocument> GetAll();
TypeDocument GetById(int id);
TypeDocument Add(TypeDocument newTypeDocument);
bool Update(TypeDocument typeDocument);
bool Delete(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Project_NotesDeFrais.Models
{
[Table("ExpanseTypes")]
public class ExpanseTypesModel
{
public ExpanseTypesModel()
{
this.Expanses = new HashSet<ExpansesModel>();
}
public System.Guid ExpenseType_ID { get; set; }
[Display(Name = "Nom")]
[RegularExpression(@"^[a-zA-Z]*$", ErrorMessage = "le nom ne doit contenir que des caracteres.")]
[StringLength(20)]
[Required(ErrorMessage = "nom obligatoire")]
public string Name { get; set; }
public Nullable<double> Ceiling { get; set; }
[Display(Name = "Valeur fixée ?")]
public bool Fixed { get; set; }
[Display(Name = "Manager seulement ?")]
public bool OnlyManagers { get; set; }
public System.Guid Tva_ID { get; set; }
public virtual ICollection<ExpansesModel> Expanses { get; set; }
public virtual TvasModel Tvas { get; set; }
public virtual List<Tvas> tvaList { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using Google.Protobuf;
using UnityEngine;
using UnityEngine.UI;
public interface IScrollRectExCallBack1
{
void ScrollCellIndex(int idx);
int GetCellIndex();
void OnPoolDispose();
Transform transform { get;}
GameObject prefab { get; set; }
void ReceiveMsg(IMessage message);
}
public class LayoutDesc
{
public GameObject Prefab;
public List<uint> Ids;
public int ConstraintCount;
public Vector2 CellSize;
public Vector2 Spacing;
}
public class CellsDesc
{
public List<uint> Ids;
public List<Vector2> ArchoredPoss;
public List<IScrollRectExCallBack1> CallBack1s;
public LayoutDesc LayoutDesc;
}
[RequireComponent(typeof(ScrollRect))]
public class ScrollRectEx1 : MonoBehaviour
{
[SerializeField] public ScrollRect scrollRect;
[SerializeField] public Transform CellParent;
public Deque<int> Cells = new Deque<int>(8);
private Dictionary<GameObject, List<IScrollRectExCallBack1>> pools = new Dictionary<GameObject, List<IScrollRectExCallBack1>>();
private Dictionary<int, CellsDesc> CellsDescDic = new Dictionary<int, CellsDesc>();
private float scrollRectHeight;
// Start is called before the first frame update
public void FillCells(List<LayoutDesc> layoutDescList)
{
scrollRect = GetComponent<ScrollRect>();
scrollRectHeight = scrollRect.viewport.rect.height;
float totalY = 0f;
int initCount = -1;
int totalCount = 0;
CellsDesc cellsDesc = new CellsDesc();
// layout
for (int i = 0; i < layoutDescList.Count; i++)
{
var layoutDesc = layoutDescList[i];
if(!pools.ContainsKey(layoutDesc.Prefab))
pools.Add(layoutDesc.Prefab, new List<IScrollRectExCallBack1>(4));
float y = 0f;
for (int j = 0; j < layoutDesc.Ids.Count; j++)
{
var id = layoutDesc.Ids[j];
int hIndex = j % layoutDesc.ConstraintCount;
if (hIndex == 0)
{
cellsDesc = new CellsDesc();
cellsDesc.ArchoredPoss = new List<Vector2>();
cellsDesc.Ids = new List<uint>();
cellsDesc.CallBack1s = new List<IScrollRectExCallBack1>();
CellsDescDic.Add(totalCount, cellsDesc);
totalCount++;
cellsDesc.LayoutDesc = layoutDesc;
y = totalY + (layoutDesc.Spacing.y + layoutDesc.CellSize.y) * 0.5f;
totalY += (layoutDesc.Spacing.y + layoutDesc.CellSize.y);
if (initCount == -1 && scrollRectHeight < totalY)
{
initCount = totalCount;
}
}
float x = hIndex * (layoutDesc.CellSize.x + layoutDesc.Spacing.x) +
(layoutDesc.CellSize.x + layoutDesc.Spacing.x) * 0.5f;
cellsDesc.ArchoredPoss.Add( new Vector2(-x, y));
cellsDesc.Ids.Add(id);
}
}
scrollRect.content.sizeDelta = new Vector2(scrollRect.content.sizeDelta.x, totalY);
endIndex = initCount - 1;
startIndex = 0;
for (int i = 0; i < initCount; i++)
{
var d = CellsDescDic[startIndex + i];
d.CallBack1s.Clear();
for (int j = 0; j < d.Ids.Count; j++)
{
var cell = GetCellFromPool(d.LayoutDesc.Prefab);
d.CallBack1s.Add(cell);
cell.ScrollCellIndex((int)d.Ids[j]);
cell.transform.name = d.Ids[j].ToString();
cell.prefab = d.LayoutDesc.Prefab;
(cell.transform as RectTransform).anchoredPosition = new Vector2(999999f, 0f);
}
Cells.AddTail(startIndex + i);
}
foreach (int cellIndex in Cells)
{
var index = cellIndex;
var cellDesc = CellsDescDic[index];
for (int j = 0; j < cellDesc.Ids.Count; j++)
{
var cell = cellDesc.CallBack1s[j];
(cell.transform as RectTransform).anchoredPosition = scrollRect.content.anchoredPosition - cellDesc.ArchoredPoss[j];
}
}
}
[SerializeField] public int startIndex = 0;
[SerializeField] public int endIndex = 0;
// Update is called once per frame
void Update()
{
if (Cells.Count == 0) return;
foreach (int cellIndex in Cells)
{
var index = cellIndex;
var cellsDesc = CellsDescDic[index];
for (int j = 0; j < cellsDesc.Ids.Count; j++)
{
var cell = cellsDesc.CallBack1s[j];
(cell.transform as RectTransform).anchoredPosition = scrollRect.content.anchoredPosition - cellsDesc.ArchoredPoss[j];
}
}
if (startIndex != 0)
{
var preIndex = startIndex - 1;
var cellsDesc = CellsDescDic[preIndex];
var pos = cellsDesc.ArchoredPoss[0].y;
var cellSizeY = cellsDesc.LayoutDesc.CellSize.y + cellsDesc.LayoutDesc.Spacing.y;
var bottomY = (scrollRect.content.anchoredPosition.y - pos) - cellSizeY / 2f;
if (bottomY < 0f)
{
startIndex = preIndex;
cellsDesc.CallBack1s.Clear();
for (int i = 0; i < cellsDesc.Ids.Count; i++)
{
var cell = GetCellFromPool(cellsDesc.LayoutDesc.Prefab);
cell.ScrollCellIndex((int)cellsDesc.Ids[i]);
cellsDesc.CallBack1s.Add(cell);
cell.transform.name = cellsDesc.Ids[i].ToString();
cell.prefab = cellsDesc.LayoutDesc.Prefab;
(cell.transform as RectTransform).anchoredPosition = scrollRect.content.anchoredPosition - cellsDesc.ArchoredPoss[0];
}
Cells.AddHead(startIndex);
}
}
if (endIndex != CellsDescDic.Count - 1)
{
var nextIndex = endIndex + 1;
var cellsDesc = CellsDescDic[nextIndex];
var pos = cellsDesc.ArchoredPoss[0].y;
var cellSizeY = cellsDesc.LayoutDesc.CellSize.y + cellsDesc.LayoutDesc.Spacing.y;
var topY = (scrollRect.content.anchoredPosition.y - pos) + cellSizeY / 2f;
if (topY > -scrollRectHeight)
{
endIndex = nextIndex;
cellsDesc.CallBack1s.Clear();
for (int i = 0; i < cellsDesc.Ids.Count; i++)
{
var cell = GetCellFromPool(cellsDesc.LayoutDesc.Prefab);
cellsDesc.CallBack1s.Add(cell);
cell.ScrollCellIndex((int)cellsDesc.Ids[i]);
cell.transform.name = cellsDesc.Ids[i].ToString();
cell.prefab = cellsDesc.LayoutDesc.Prefab;
(cell.transform as RectTransform).anchoredPosition = scrollRect.content.anchoredPosition - cellsDesc.ArchoredPoss[0];
}
Cells.AddTail(endIndex);
}
}
////
{
var cellsDesc = CellsDescDic[startIndex];
var startPos = cellsDesc.ArchoredPoss[0].y;
var cellSizeY = cellsDesc.LayoutDesc.CellSize.y + cellsDesc.LayoutDesc.Spacing.y;
var cellBottomY = (scrollRect.content.anchoredPosition.y - startPos) - cellSizeY / 2f;
if (cellBottomY > 0f)
{
Cells.RemoveHead();
for (int i = 0; i < cellsDesc.CallBack1s.Count; i++)
{
ReleaseCell(cellsDesc.CallBack1s[i]);
(cellsDesc.CallBack1s[i].transform as RectTransform).anchoredPosition = new Vector2(999999f, 0f);
}
cellsDesc.CallBack1s.Clear();
startIndex = startIndex + 1;
}
}
{
var cellsDesc = CellsDescDic[endIndex];
var endPos = cellsDesc.ArchoredPoss[0].y;
var cellSizeY = cellsDesc.LayoutDesc.CellSize.y + cellsDesc.LayoutDesc.Spacing.y;
var itemTopY = (scrollRect.content.anchoredPosition.y - endPos) + cellSizeY / 2f;
if (itemTopY < -scrollRectHeight)
{
Cells.RemoveTail();
for (int i = 0; i < cellsDesc.CallBack1s.Count; i++)
{
ReleaseCell(cellsDesc.CallBack1s[i]);
(cellsDesc.CallBack1s[i].transform as RectTransform).anchoredPosition = new Vector2(999999f, 0f);
}
endIndex = endIndex - 1;
}
}
}
float GetCellY(int index)
{
return CellsDescDic[index].ArchoredPoss[0].y;
}
IScrollRectExCallBack1 GetCellFromPool(GameObject prefab)
{
var pool = pools[prefab];
if (pool.Count == 0)
{
var cell = GameObject.Instantiate(prefab, CellParent, false);
return cell.GetComponent<IScrollRectExCallBack1>();
}
var go = pool[pool.Count-1];
pool.RemoveAt(pool.Count - 1);
return go;
}
void ReleaseCell(IScrollRectExCallBack1 cell)
{
cell.OnPoolDispose();
var pool = pools[cell.prefab];
pool.Add(cell);
}
public IScrollRectExCallBack1 GetCell(int Id)
{
foreach (int cellIndex in Cells)
{
var index = cellIndex;
var cellsDesc = CellsDescDic[index];
for (int j = 0; j < cellsDesc.Ids.Count; j++)
{
if (Id == cellsDesc.Ids[j])
{
return cellsDesc.CallBack1s[j];
}
}
}
return null;
}
public void RefreshCells()
{
foreach (int cellIndex in Cells)
{
var index = cellIndex;
var cellsDesc = CellsDescDic[index];
for (int j = 0; j < cellsDesc.Ids.Count; j++)
{
var cell = cellsDesc.CallBack1s[j];
cell.ScrollCellIndex((int)cellsDesc.Ids[j]);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace PaderbornUniversity.SILab.Hip.EventSourcing
{
/// <summary>
/// A hash set that preserves insertion order while still allowing basic set operations in O(1).
/// Adapted from https://www.codeproject.com/Articles/627085/HashSet-that-Preserves-Insertion-Order-or-NET.
/// </summary>
public class OrderedSet<T> : ICollection<T>
{
private readonly IDictionary<T, LinkedListNode<T>> _dictionary;
private readonly LinkedList<T> _linkedList;
public OrderedSet() : this(EqualityComparer<T>.Default)
{
}
public OrderedSet(IEnumerable<T> items) : this(items, EqualityComparer<T>.Default)
{
}
public OrderedSet(IEqualityComparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)
{
}
public OrderedSet(IEnumerable<T> items, IEqualityComparer<T> comparer)
{
_dictionary = new Dictionary<T, LinkedListNode<T>>(comparer);
_linkedList = new LinkedList<T>();
foreach (var item in items)
Add(item);
}
public int Count => _dictionary.Count;
public virtual bool IsReadOnly => false;
void ICollection<T>.Add(T item) => Add(item);
public bool Add(T item)
{
if (_dictionary.ContainsKey(item))
return false;
var node = _linkedList.AddLast(item);
_dictionary.Add(item, node);
return true;
}
public void Clear()
{
_linkedList.Clear();
_dictionary.Clear();
}
public bool Remove(T item)
{
if (item == null)
return false;
if (!_dictionary.TryGetValue(item, out var node))
return false;
_dictionary.Remove(item);
_linkedList.Remove(node);
return true;
}
public IEnumerator<T> GetEnumerator() => _linkedList.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool Contains(T item) {
if (item == null)
return false;
return _dictionary.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex) => _linkedList.CopyTo(array, arrayIndex);
}
}
|
using Modelos.Cadastros.Visitantes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modelos.Relatorios.Parametros
{
public class RelAcessosParametros
{
[Display(Name = "Data de Entrada De")]
public virtual DateTime? DataEntradaDe { get; set; }
[Display(Name = "Data de Entrada Ate")]
public virtual DateTime? DataEntradaAte { get; set; }
[Display(Name = "Data de Saída De")]
public virtual DateTime? DataSaidaDe { get; set; }
[Display(Name = "Data de Saída Ate")]
public virtual DateTime? DataSaidaAte { get; set; }
[Display(Name = "Visitante")]
public virtual string Visitante { get; set; }
[Display(Name ="Visitado")]
public virtual string Visitado { get; set; }
[Display(Name ="Gerar PDF?")]
public virtual bool GerarPdf { get; set; }
[Display(Name = "Informe a Empresa, ou parte do nome")]
public virtual string Empresa { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SoundMenu : MonoBehaviour
{
public AudioSource audio;
public AudioClip idle;
public AudioClip fight;
public string curr = "Settings";
//public AudioClip fight_down;
// Start is called before the first frame update
void Start()
{
audio.clip = idle;
audio.volume = 0.5f;
audio.loop = true;
audio.Play();
}
// Update is called once per frame
void Update()
{
if(SceneManager.GetActiveScene().name!=curr){
if(SceneManager.GetActiveScene().name.Contains("Firrhing")){
audio.clip = fight;
audio.loop = true;
}
if(!SceneManager.GetActiveScene().name.Contains("Firrhing") &&
curr.Contains("Firrhing")){
audio.clip = idle;
audio.loop = true;
}
curr = SceneManager.GetActiveScene().name;
}
}
}
|
using BLL;
using Entidades;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProyectoFinal.UI
{
public partial class rPesador : Form
{
private int IdUsuario;
public rPesador(int IdUsuario)
{
InitializeComponent();
this.IdUsuario = IdUsuario;
}
private void Nuevobutton_Click(object sender, EventArgs e)
{
Limpiar();
}
private void Limpiar()
{
IdnumericUpDown.Value = 0;
NombretextBox.Text = string.Empty;
CedulatextBox.Text = string.Empty;
DirecciontextBox.Text = string.Empty;
TelefonotextBox.Text = string.Empty;
CelulartextBox.Text = string.Empty;
FechaRegistrodateTimePicker.Value = DateTime.Now;
FechaNacimientodateTimePicker.Value = DateTime.Now;
}
private void Guardarbutton_Click(object sender, EventArgs e)
{
if (!Validar())
return;
Pesadores pesador = LlenarClase();
RepositorioBase<Pesadores> db = new RepositorioBase<Pesadores>();
try
{
if (IdnumericUpDown.Value == 0)
{
if (db.Guardar(pesador))
{
MessageBox.Show("Guardado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
if (db.Modificar(pesador))
{
MessageBox.Show("Modificado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo Modificar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
catch (Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private Pesadores LlenarClase()
{
Pesadores pesador = new Pesadores();
pesador.IdPesador = (int)IdnumericUpDown.Value;
pesador.Nombre = NombretextBox.Text;
pesador.Cedula = CedulatextBox.Text;
pesador.Direccion = DirecciontextBox.Text;
pesador.Telefono = TelefonotextBox.Text;
pesador.Celular = CelulartextBox.Text;
pesador.FechaCreacion = FechaRegistrodateTimePicker.Value;
pesador.FechaNacimiento = FechaNacimientodateTimePicker.Value;
pesador.IdUsuario = IdUsuario;
return pesador;
}
private bool Validar()
{
bool paso = true;
errorProvider.Clear();
if (string.IsNullOrWhiteSpace(NombretextBox.Text))
{
paso = false;
errorProvider.SetError(NombretextBox, "Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(CedulatextBox.Text))
{
paso = false;
errorProvider.SetError(CedulatextBox, "Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(DirecciontextBox.Text))
{
paso = false;
errorProvider.SetError(DirecciontextBox, "Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(TelefonotextBox.Text))
{
paso = false;
errorProvider.SetError(TelefonotextBox, "Este campo no puede estar vacio");
}
if (FechaRegistrodateTimePicker.Value > DateTime.Now)
{
paso = false;
errorProvider.SetError(FechaRegistrodateTimePicker, "La fecha no puede ser mayor que la de hoy");
}
if (FechaNacimientodateTimePicker.Value > DateTime.Now)
{
paso = false;
errorProvider.SetError(FechaNacimientodateTimePicker, "La fecha no puede ser mayor que la de hoy");
}
if (!Personas.ValidarCedula(CedulatextBox.Text.Trim()))
{
paso = false;
errorProvider.SetError(CedulatextBox, "Esta cedula no es valida");
}
return paso;
}
private void Eliminarbutton_Click(object sender, EventArgs e)
{
RepositorioBase<Pesadores> db = new RepositorioBase<Pesadores>();
errorProvider.Clear();
try
{
if (IdnumericUpDown.Value == 0)
{
errorProvider.SetError(IdnumericUpDown, "Este campo no puede ser cero al eliminar");
}
else
{
if (db.Elimimar((int)IdnumericUpDown.Value))
{
MessageBox.Show("Eliminado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
catch (Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Buscarbutton_Click(object sender, EventArgs e)
{
RepositorioBase<Pesadores> db = new RepositorioBase<Pesadores>();
Pesadores pesador;
try
{
if ((pesador = db.Buscar((int)IdnumericUpDown.Value)) is null)
{
MessageBox.Show("No se pudo encontrar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
LlenarCampos(pesador);
}
}
catch (Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LlenarCampos(Pesadores pesador)
{
Limpiar();
IdnumericUpDown.Value = pesador.IdPesador;
NombretextBox.Text = pesador.Nombre;
CedulatextBox.Text = pesador.Cedula;
DirecciontextBox.Text = pesador.Direccion;
TelefonotextBox.Text = pesador.Telefono;
CelulartextBox.Text = pesador.Celular;
FechaRegistrodateTimePicker.Value = pesador.FechaCreacion;
FechaNacimientodateTimePicker.Value = pesador.FechaNacimiento;
}
}
}
|
namespace Components.Value.Automapper.Profiles
{
using AutoMapper;
using Components.Value.Business.Models;
using Components.Value.Persistence.Poco;
public class ValueProfile : Profile
{
public ValueProfile()
{
CreateMap<Value, ValueDomainModel>()
.ForMember(destinationMember => destinationMember.Name, memberOptions => memberOptions.MapFrom(sourceMember => sourceMember.Name))
//.ForMember(destinationMember => destinationMember.DateTime, memberOptions => memberOptions.MapFrom(sourceMember => sourceMember.DateTime))
.ReverseMap();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using VideoServiceBL.Exceptions;
using VideoServiceBL.Extensions;
using VideoServiceBL.Services.Interfaces;
using VideoServiceDAL.Interfaces;
using VideoServiceDAL.Persistence;
namespace VideoServiceBL.Services
{
public abstract class BaseService<T, TDto> : IBaseService<TDto>
where T : class, IIdentifier
where TDto : class
{
protected readonly DbSet<T> Entities;
protected readonly VideoServiceDbContext Context;
private readonly ILogger<BaseService<T, TDto>> _logger;
private readonly IMapper _mapper;
protected BaseService(VideoServiceDbContext context, ILogger<BaseService<T,TDto>> logger, IMapper mapper)
{
Context = context;
_logger = logger;
_mapper = mapper;
Entities = context.Set<T>();
}
public async Task<TDto> AddAsync(TDto dtoObj)
{
try
{
var item = _mapper.Map<TDto, T>(dtoObj);
await Entities.AddAsync(item);
await Context.SaveChangesAsync();
return _mapper.Map<T, TDto> (item);
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t add data", ex);
throw new BusinessLogicException("Could not add data!", ex);
}
}
public async Task AddRangeAsync(IList<TDto> dtoObjs)
{
try
{
var items = _mapper.Map<IList<TDto>, IList<T>>(dtoObjs);
await Entities.AddRangeAsync(items);
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t add data", ex);
throw new BusinessLogicException("Could not add data!", ex);
}
}
public async Task<TDto> GetAsync(long id)
{
try
{
var item = await Entities.FindAsync(id);
return _mapper.Map<T,TDto>(item ?? throw new BusinessLogicException("Item not found!"));
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t get data by id", ex);
throw new BusinessLogicException(ex.Message ?? "Could not get data!", ex);
}
}
public async Task<IList<TDto>> GetAllAsync()
{
try
{
var list = await Entities.ToListAsync();
return list.Select(_mapper.Map<T, TDto>).ToList();
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t get data", ex);
throw new BusinessLogicException("Could not get data!", ex);
}
}
public async Task RemoveAsync(long id)
{
try
{
if (id <= 0)
{
throw new BusinessLogicException(@"Invalid remove id - {id}!");
}
var item = await Entities.FindAsync(id);
if (item != null)
{
Entities.Remove(item);
await Context.SaveChangesAsync();
}
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t remove data", ex);
throw new BusinessLogicException("Could not remove data!", ex);
}
}
public async Task RemoveRangeAsync(IList<TDto> dtoObjs)
{
try
{
var items = _mapper.Map<IList<TDto>, IList<T>>(dtoObjs);
Entities.RemoveRange(items);
await Context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t remove data", ex);
throw new BusinessLogicException("Could not remove data!", ex);
}
}
public async Task UpdateAsync(TDto dtoObj, long? id = null)
{
try
{
var item = _mapper.Map<TDto, T>(dtoObj);
Context.DetachLocal(item, id);
await Context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError("DataBase error, could`t update data", ex);
throw new BusinessLogicException("Could not update data!", ex);
}
}
}
}
|
namespace SimpleTerrain
{
class Constants
{
public const float Speed = 0.9f;
public const long RenderChangeCooldown = 1000;
}
}
|
using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections.Generic;
using Karkas.Core.TypeLibrary;
using Karkas.Core.Onaylama;
using Karkas.Core.Onaylama.ForPonos;
using System.ComponentModel.DataAnnotations;
namespace Karkas.Ornek.TypeLibrary.Dbo
{
[Serializable]
[DebuggerDisplay("DiagramId = {DiagramId}")]
public partial class Sysdiagrams: BaseTypeLibrary
{
private string name;
private int principalId;
private int diagramId;
private Nullable<int> version;
private byte[] definition;
[StringLength(128)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string Name
{
[DebuggerStepThrough]
get
{
return name;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (name!= value))
{
this.RowState = DataRowState.Modified;
}
name = value;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int PrincipalId
{
[DebuggerStepThrough]
get
{
return principalId;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (principalId!= value))
{
this.RowState = DataRowState.Modified;
}
principalId = value;
}
}
[Key]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int DiagramId
{
[DebuggerStepThrough]
get
{
return diagramId;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (diagramId!= value))
{
this.RowState = DataRowState.Modified;
}
diagramId = value;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Nullable<int> Version
{
[DebuggerStepThrough]
get
{
return version;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (version!= value))
{
this.RowState = DataRowState.Modified;
}
version = value;
}
}
[Required]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public byte[] Definition
{
[DebuggerStepThrough]
get
{
return definition;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (definition!= value))
{
this.RowState = DataRowState.Modified;
}
definition = value;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlIgnore, SoapIgnore]
[ScaffoldColumn(false)]
public string PrincipalIdAsString
{
[DebuggerStepThrough]
get
{
return principalId.ToString();
}
[DebuggerStepThrough]
set
{
try
{
int _a = Convert.ToInt32(value);
PrincipalId = _a;
}
catch(Exception)
{
this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"PrincipalId",string.Format(CEVIRI_YAZISI,"PrincipalId","int")));
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlIgnore, SoapIgnore]
[ScaffoldColumn(false)]
public string DiagramIdAsString
{
[DebuggerStepThrough]
get
{
return diagramId.ToString();
}
[DebuggerStepThrough]
set
{
try
{
int _a = Convert.ToInt32(value);
DiagramId = _a;
}
catch(Exception)
{
this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"DiagramId",string.Format(CEVIRI_YAZISI,"DiagramId","int")));
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlIgnore, SoapIgnore]
[ScaffoldColumn(false)]
public string VersionAsString
{
[DebuggerStepThrough]
get
{
return version != null ? version.ToString() : "";
}
[DebuggerStepThrough]
set
{
try
{
int _a = Convert.ToInt32(value);
Version = _a;
}
catch(Exception)
{
this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"Version",string.Format(CEVIRI_YAZISI,"Version","int")));
}
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlIgnore, SoapIgnore]
[ScaffoldColumn(false)]
public string DefinitionAsString
{
[DebuggerStepThrough]
get
{
return definition != null ? definition.ToString() : "";
}
[DebuggerStepThrough]
set
{
throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir");
}
}
public Sysdiagrams ShallowCopy()
{
Sysdiagrams obj = new Sysdiagrams();
obj.name = name;
obj.principalId = principalId;
obj.diagramId = diagramId;
obj.version = version;
obj.definition = definition;
return obj;
}
protected override void OnaylamaListesiniOlusturCodeGeneration()
{
this.Onaylayici.OnaylayiciListesi.Add(new GerekliAlanOnaylayici(this, "Name"));
this.Onaylayici.OnaylayiciListesi.Add(new GerekliAlanOnaylayici(this, "PrincipalId")); }
public class PropertyIsimleri
{
public const string Name = "name";
public const string PrincipalId = "principal_id";
public const string DiagramId = "diagram_id";
public const string Version = "version";
public const string Definition = "definition";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UCMAService
{
/// <summary>
/// 端点状态
/// </summary>
public enum EndpointState
{
/// <summary>
/// 启用
/// </summary>
Enabled = 1,
/// <summary>
/// 禁用
/// </summary>
Disabled = 0
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlayTennis.Dal;
using PlayTennis.Model;
using System.Linq.Expressions;
namespace PlayTennis.Bll
{
public class BaseService<T, TKey> where T : class
{
protected GenericRepository<T> MyEntitiesRepository { get; set; }
public BaseService()
{
MyEntitiesRepository = new GenericRepository<T>();
}
public T GetEntityByid(TKey id)
{
return MyEntitiesRepository.GetById(id);
}
public IQueryable<T> Entitys()
{
return MyEntitiesRepository.Entities;
}
public T GetEntityFirstOrDefault(Expression<Func<T, bool>> where)
{
return MyEntitiesRepository.Get(where);
}
public int EditEntity(T t)
{
var result = 0;
if (t == null)
{
return result;
}
return MyEntitiesRepository.Update(t);
}
}
}
|
using System.Collections.Generic;
using RestSharp.Deserializers;
namespace Jira.NET.Models
{
public class JiraExpandedObject<T>
{
[DeserializeAs(Name = "size")]
public int Size { get; set; }
[DeserializeAs(Name = "items")]
public List<T> Items { get; set; }
[DeserializeAs(Name = "max-results")]
public int MaxResults { get; set; }
[DeserializeAs(Name = "start-index")]
public int StartIndex { get; set; }
[DeserializeAs(Name = "end-index")]
public int EndIndex { get; set; }
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("CollectionDeckBoxVisual")]
public class CollectionDeckBoxVisual : PegUIElement
{
public CollectionDeckBoxVisual(IntPtr address) : this(address, "CollectionDeckBoxVisual")
{
}
public CollectionDeckBoxVisual(IntPtr address, string className) : base(address, className)
{
}
public void AssignFromCollectionDeck(CollectionDeck deck)
{
object[] objArray1 = new object[] { deck };
base.method_8("AssignFromCollectionDeck", objArray1);
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void DisableButtonAnimation()
{
base.method_8("DisableButtonAnimation", Array.Empty<object>());
}
public void EnableButtonAnimation()
{
base.method_8("EnableButtonAnimation", Array.Empty<object>());
}
public CardDef GetCardDef()
{
return base.method_14<CardDef>("GetCardDef", Array.Empty<object>());
}
public TAG_CLASS GetClass()
{
return base.method_11<TAG_CLASS>("GetClass", Array.Empty<object>());
}
public long GetDeckID()
{
return base.method_11<long>("GetDeckID", Array.Empty<object>());
}
public UberText GetDeckNameText()
{
return base.method_14<UberText>("GetDeckNameText", Array.Empty<object>());
}
public FullDef GetFullDef()
{
return base.method_14<FullDef>("GetFullDef", Array.Empty<object>());
}
public string GetHeroCardID()
{
return base.method_13("GetHeroCardID", Array.Empty<object>());
}
public Texture GetHeroPortraitTexture()
{
return base.method_14<Texture>("GetHeroPortraitTexture", Array.Empty<object>());
}
public int GetPositionIndex()
{
return base.method_11<int>("GetPositionIndex", Array.Empty<object>());
}
public void Hide()
{
base.method_8("Hide", Array.Empty<object>());
}
public void HideBanner()
{
base.method_8("HideBanner", Array.Empty<object>());
}
public void HideDeckName()
{
base.method_8("HideDeckName", Array.Empty<object>());
}
public bool IsLocked()
{
return base.method_11<bool>("IsLocked", Array.Empty<object>());
}
public bool IsShown()
{
return base.method_11<bool>("IsShown", Array.Empty<object>());
}
public bool IsValid()
{
return base.method_11<bool>("IsValid", Array.Empty<object>());
}
public void OnDeleteButtonConfirmationResponse(AlertPopup.Response response, object userData)
{
object[] objArray1 = new object[] { response, userData };
base.method_8("OnDeleteButtonConfirmationResponse", objArray1);
}
public void OnDeleteButtonOver(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnDeleteButtonOver", objArray1);
}
public void OnDeleteButtonPressed(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnDeleteButtonPressed", objArray1);
}
public void OnDeleteButtonRollout(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnDeleteButtonRollout", objArray1);
}
public void OnHeroFullDefLoaded(string cardID, FullDef def, object userData)
{
object[] objArray1 = new object[] { cardID, def, userData };
base.method_8("OnHeroFullDefLoaded", objArray1);
}
public void OnOut(PegUIElement.InteractionState oldState)
{
object[] objArray1 = new object[] { oldState };
base.method_8("OnOut", objArray1);
}
public void OnOutEvent()
{
base.method_8("OnOutEvent", Array.Empty<object>());
}
public void OnOver(PegUIElement.InteractionState oldState)
{
object[] objArray1 = new object[] { oldState };
base.method_8("OnOver", objArray1);
}
public void OnOverEvent()
{
base.method_8("OnOverEvent", Array.Empty<object>());
}
public void OnPress()
{
base.method_8("OnPress", Array.Empty<object>());
}
public void OnPressEvent()
{
base.method_8("OnPressEvent", Array.Empty<object>());
}
public void OnRelease()
{
base.method_8("OnRelease", Array.Empty<object>());
}
public void OnReleaseEvent()
{
base.method_8("OnReleaseEvent", Array.Empty<object>());
}
public void OnScaleComplete(OnScaleFinishedCallbackData callbackData)
{
object[] objArray1 = new object[] { callbackData };
base.method_8("OnScaleComplete", objArray1);
}
public void OnScaledDown(object callbackData)
{
object[] objArray1 = new object[] { callbackData };
base.method_8("OnScaledDown", objArray1);
}
public void PlayPopAnimation(string animationName)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String };
object[] objArray1 = new object[] { animationName };
base.method_9("PlayPopAnimation", enumArray1, objArray1);
}
public void PlayPopDownAnimation()
{
base.method_9("PlayPopDownAnimation", new Class272.Enum20[0], Array.Empty<object>());
}
public void PlayPopDownAnimationImmediately()
{
base.method_9("PlayPopDownAnimationImmediately", new Class272.Enum20[0], Array.Empty<object>());
}
public void PlayPopUpAnimation()
{
base.method_9("PlayPopUpAnimation", new Class272.Enum20[0], Array.Empty<object>());
}
public void PlayScaleDownAnimation()
{
base.method_9("PlayScaleDownAnimation", new Class272.Enum20[0], Array.Empty<object>());
}
public void PlayScaleUpAnimation()
{
base.method_9("PlayScaleUpAnimation", new Class272.Enum20[0], Array.Empty<object>());
}
public void ScaleDownComplete(OnScaleFinishedCallbackData onScaledDownData)
{
object[] objArray1 = new object[] { onScaledDownData };
base.method_8("ScaleDownComplete", objArray1);
}
public void ScaleUpNow(OnScaleFinishedCallbackData readyToScaleUpData)
{
object[] objArray1 = new object[] { readyToScaleUpData };
base.method_8("ScaleUpNow", objArray1);
}
public void SetBasicSetProgress(TAG_CLASS classTag)
{
object[] objArray1 = new object[] { classTag };
base.method_8("SetBasicSetProgress", objArray1);
}
public void SetClassDisplay(TAG_CLASS classTag)
{
object[] objArray1 = new object[] { classTag };
base.method_8("SetClassDisplay", objArray1);
}
public void SetDeckID(long id)
{
object[] objArray1 = new object[] { id };
base.method_8("SetDeckID", objArray1);
}
public void SetDeckName(string deckName)
{
object[] objArray1 = new object[] { deckName };
base.method_8("SetDeckName", objArray1);
}
public void SetHeroCardID(string heroCardID)
{
object[] objArray1 = new object[] { heroCardID };
base.method_8("SetHeroCardID", objArray1);
}
public void SetHighlightState(ActorStateType stateType)
{
object[] objArray1 = new object[] { stateType };
base.method_8("SetHighlightState", objArray1);
}
public void SetIsLocked(bool isLocked)
{
object[] objArray1 = new object[] { isLocked };
base.method_8("SetIsLocked", objArray1);
}
public void SetIsValid(bool isValid)
{
object[] objArray1 = new object[] { isValid };
base.method_8("SetIsValid", objArray1);
}
public void SetOriginalButtonPosition()
{
base.method_8("SetOriginalButtonPosition", Array.Empty<object>());
}
public void SetPortrait(Material portraitMaterial)
{
object[] objArray1 = new object[] { portraitMaterial };
base.method_8("SetPortrait", objArray1);
}
public void SetPositionIndex(int idx)
{
object[] objArray1 = new object[] { idx };
base.method_8("SetPositionIndex", objArray1);
}
public void SetShowGlow(bool showGlow)
{
object[] objArray1 = new object[] { showGlow };
base.method_8("SetShowGlow", objArray1);
}
public void Show()
{
base.method_8("Show", Array.Empty<object>());
}
public void ShowBanner()
{
base.method_8("ShowBanner", Array.Empty<object>());
}
public void ShowDeckName()
{
base.method_8("ShowDeckName", Array.Empty<object>());
}
public void ShowDeleteButton(bool show)
{
object[] objArray1 = new object[] { show };
base.method_8("ShowDeleteButton", objArray1);
}
public void ShowEditDecal(bool show)
{
object[] objArray1 = new object[] { show };
base.method_8("ShowEditDecal", objArray1);
}
public void Update()
{
base.method_8("Update", Array.Empty<object>());
}
public static float ADJUST_Y_OFFSET_ANIM_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "ADJUST_Y_OFFSET_ANIM_TIME");
}
}
public static Color BASIC_SET_COLOR_IN_PROGRESS
{
get
{
return MonoClass.smethod_6<Color>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "BASIC_SET_COLOR_IN_PROGRESS");
}
}
public static float BUTTON_POP_SPEED
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "BUTTON_POP_SPEED");
}
}
public static string DECKBOX_POPDOWN_ANIM_NAME
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "DECKBOX_POPDOWN_ANIM_NAME");
}
}
public static string DECKBOX_POPUP_ANIM_NAME
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "DECKBOX_POPUP_ANIM_NAME");
}
}
public static float DECKBOX_SCALE
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "DECKBOX_SCALE");
}
}
public bool m_animateButtonPress
{
get
{
return base.method_2<bool>("m_animateButtonPress");
}
}
public Material m_bannerMaterial
{
get
{
return base.method_3<Material>("m_bannerMaterial");
}
}
public CustomDeckBones m_bones
{
get
{
return base.method_3<CustomDeckBones>("m_bones");
}
}
public CardDef m_cardDef
{
get
{
return base.method_3<CardDef>("m_cardDef");
}
}
public int m_classBannerMaterialIndex
{
get
{
return base.method_2<int>("m_classBannerMaterialIndex");
}
}
public Material m_classIconMaterial
{
get
{
return base.method_3<Material>("m_classIconMaterial");
}
}
public int m_classIconMaterialIndex
{
get
{
return base.method_2<int>("m_classIconMaterialIndex");
}
}
public GameObject m_classObject
{
get
{
return base.method_3<GameObject>("m_classObject");
}
}
public Transform m_customDeckTransform
{
get
{
return base.method_3<Transform>("m_customDeckTransform");
}
}
public long m_deckID
{
get
{
return base.method_2<long>("m_deckID");
}
}
public UberText m_deckName
{
get
{
return base.method_3<UberText>("m_deckName");
}
}
public PegUIElement m_deleteButton
{
get
{
return base.method_3<PegUIElement>("m_deleteButton");
}
}
public GameObject m_editDecal
{
get
{
return base.method_3<GameObject>("m_editDecal");
}
}
public EntityDef m_entityDef
{
get
{
return base.method_3<EntityDef>("m_entityDef");
}
}
public FullDef m_fullDef
{
get
{
return base.method_3<FullDef>("m_fullDef");
}
}
public string m_heroCardID
{
get
{
return base.method_4("m_heroCardID");
}
}
public GameObject m_highlight
{
get
{
return base.method_3<GameObject>("m_highlight");
}
}
public HighlightState m_highlightState
{
get
{
return base.method_3<HighlightState>("m_highlightState");
}
}
public GameObject m_invalidDeckX
{
get
{
return base.method_3<GameObject>("m_invalidDeckX");
}
}
public bool m_isLocked
{
get
{
return base.method_2<bool>("m_isLocked");
}
}
public bool m_isPoppedUp
{
get
{
return base.method_2<bool>("m_isPoppedUp");
}
}
public bool m_isShown
{
get
{
return base.method_2<bool>("m_isShown");
}
}
public bool m_isValid
{
get
{
return base.method_2<bool>("m_isValid");
}
}
public GameObject m_labelGradient
{
get
{
return base.method_3<GameObject>("m_labelGradient");
}
}
public GameObject m_lockedDeckVisuals
{
get
{
return base.method_3<GameObject>("m_lockedDeckVisuals");
}
}
public GameObject m_normalDeckVisuals
{
get
{
return base.method_3<GameObject>("m_normalDeckVisuals");
}
}
public Vector3 m_originalButtonPosition
{
get
{
return base.method_2<Vector3>("m_originalButtonPosition");
}
}
public int m_portraitMaterialIndex
{
get
{
return base.method_2<int>("m_portraitMaterialIndex");
}
}
public GameObject m_portraitObject
{
get
{
return base.method_3<GameObject>("m_portraitObject");
}
}
public int m_positionIndex
{
get
{
return base.method_2<int>("m_positionIndex");
}
}
public GameObject m_pressedBone
{
get
{
return base.method_3<GameObject>("m_pressedBone");
}
}
public UberText m_setProgressLabel
{
get
{
return base.method_3<UberText>("m_setProgressLabel");
}
}
public bool m_showGlow
{
get
{
return base.method_2<bool>("m_showGlow");
}
}
public TooltipZone m_tooltipZone
{
get
{
return base.method_3<TooltipZone>("m_tooltipZone");
}
}
public bool m_wasTouchModeEnabled
{
get
{
return base.method_2<bool>("m_wasTouchModeEnabled");
}
}
public static Vector3 POPPED_DOWN_LOCAL_POS
{
get
{
return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "POPPED_DOWN_LOCAL_POS");
}
}
public static float POPPED_UP_LOCAL_Z
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "POPPED_UP_LOCAL_Z");
}
}
public static float SCALE_TIME
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "SCALE_TIME");
}
}
public static Vector3 SCALED_DOWN_LOCAL_SCALE
{
get
{
return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "SCALED_DOWN_LOCAL_SCALE");
}
}
public static float SCALED_DOWN_LOCAL_Y_OFFSET
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "SCALED_DOWN_LOCAL_Y_OFFSET");
}
}
public Vector3 SCALED_UP_DECK_OFFSET
{
get
{
return base.method_2<Vector3>("SCALED_UP_DECK_OFFSET");
}
}
public Vector3 SCALED_UP_LOCAL_SCALE
{
get
{
return base.method_2<Vector3>("SCALED_UP_LOCAL_SCALE");
}
}
public static float SCALED_UP_LOCAL_Y_OFFSET
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "CollectionDeckBoxVisual", "SCALED_UP_LOCAL_Y_OFFSET");
}
}
[Attribute38("CollectionDeckBoxVisual.OnPopAnimationFinishedCallbackData")]
public class OnPopAnimationFinishedCallbackData : MonoClass
{
public OnPopAnimationFinishedCallbackData(IntPtr address) : this(address, "OnPopAnimationFinishedCallbackData")
{
}
public OnPopAnimationFinishedCallbackData(IntPtr address, string className) : base(address, className)
{
}
public string m_animationName
{
get
{
return base.method_4("m_animationName");
}
}
public object m_callbackData
{
get
{
return base.method_3<object>("m_callbackData");
}
}
}
[Attribute38("CollectionDeckBoxVisual.OnScaleFinishedCallbackData")]
public class OnScaleFinishedCallbackData : MonoClass
{
public OnScaleFinishedCallbackData(IntPtr address) : this(address, "OnScaleFinishedCallbackData")
{
}
public OnScaleFinishedCallbackData(IntPtr address, string className) : base(address, className)
{
}
public object m_callbackData
{
get
{
return base.method_3<object>("m_callbackData");
}
}
}
}
}
|
namespace JobCommon
{
public enum ScheduleType : byte
{
Interval = 0,
Daily = 1,
Weekly = 2,
Monthly = 3,
}
}
|
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using MDS.Communication.Messages;
using MDS.Serialization;
namespace MDS.Client.WebServices
{
/// <summary>
/// This class is used by MDS Web Services to serialize/deserialize/create messages.
/// </summary>
public static class WebServiceHelper
{
#region Public methods
/// <summary>
/// Deserializes an incoming message for Web Service from MDS server.
/// </summary>
/// <param name="bytesOfMessage">Message as byte array</param>
/// <returns>Deserialized message</returns>
public static IWebServiceIncomingMessage DeserializeMessage(byte[] bytesOfMessage)
{
var dataMessage = MDSSerializationHelper.DeserializeFromByteArray(() => new MDSDataTransferMessage(), bytesOfMessage);
return new IncomingDataMessage(dataMessage);
}
/// <summary>
/// Serializes a message to send to MDS server from Web Service.
/// </summary>
/// <param name="responseMessage">Message to serialize</param>
/// <returns>Serialized message</returns>
public static byte[] SerializeMessage(IWebServiceResponseMessage responseMessage)
{
CheckResponseMessage(responseMessage);
var response = ((ResponseMessage) responseMessage).CreateDataTransferResponseMessage();
return MDSSerializationHelper.SerializeToByteArray(response);
}
#endregion
#region Private methods
/// <summary>
/// Checks a response message whether it is a valid response message
/// </summary>
/// <param name="responseMessage">Message to check</param>
private static void CheckResponseMessage(IWebServiceResponseMessage responseMessage)
{
if (responseMessage == null)
{
throw new ArgumentNullException("responseMessage", "responseMessage can not be null.");
}
if (!(responseMessage is ResponseMessage))
{
throw new Exception("responseMessage parameter is not known type.");
}
if (responseMessage.Result == null)
{
throw new ArgumentNullException("responseMessage", "responseMessage.Result can not be null.");
}
if( !(responseMessage.Result is ResultMessage))
{
throw new Exception("responseMessage.Result is not known type.");
}
if(responseMessage.Message != null && !(responseMessage.Message is OutgoingDataMessage))
{
throw new Exception("responseMessage.Message is not known type.");
}
}
#endregion
#region Sub classes
/// <summary>
/// Implements IWebServiceIncomingMessage to be used by MDS web service.
/// </summary>
private class IncomingDataMessage : MDSDataTransferMessage, IWebServiceIncomingMessage
{
/// <summary>
/// Creates a new IncomingDataMessage object from a MDSDataTransferMessage object.
/// </summary>
/// <param name="message">MDSDataTransferMessage object to create IncomingDataMessage</param>
public IncomingDataMessage(MDSDataTransferMessage message)
{
DestinationApplicationName = message.DestinationApplicationName;
DestinationCommunicatorId = message.DestinationCommunicatorId;
DestinationServerName = message.DestinationServerName;
MessageData = message.MessageData;
MessageId = message.MessageId;
PassedServers = message.PassedServers;
RepliedMessageId = message.RepliedMessageId;
SourceApplicationName = message.SourceApplicationName;
SourceCommunicatorId = message.SourceCommunicatorId;
SourceServerName = message.SourceServerName;
TransmitRule = message.TransmitRule;
}
/// <summary>
/// Creates IWebServiceResponseMessage using this incoming message, to return from web service to MDS server.
/// </summary>
/// <returns>Response message to this message</returns>
public IWebServiceResponseMessage CreateResponseMessage()
{
return new ResponseMessage { Result = new ResultMessage { RepliedMessageId = MessageId } };
}
/// <summary>
/// Creates IWebServiceOutgoingMessage using this incoming message, to return from web service to MDS server.
/// </summary>
/// <returns>Response message to this message</returns>
public IWebServiceOutgoingMessage CreateResponseDataMessage()
{
return new OutgoingDataMessage
{
DestinationApplicationName = SourceApplicationName,
DestinationCommunicatorId = SourceCommunicatorId,
DestinationServerName = SourceServerName,
RepliedMessageId = MessageId,
TransmitRule = TransmitRule
};
}
}
/// <summary>
/// Implements IWebServiceOutgoingMessage to be used by MDS web service.
/// </summary>
private class OutgoingDataMessage : MDSDataTransferMessage, IWebServiceOutgoingMessage
{
//No data or method
}
/// <summary>
/// Implements IWebServiceResponseMessage to be used by MDS web service.
/// </summary>
private class ResponseMessage : IWebServiceResponseMessage
{
public IWebServiceOperationResultMessage Result { get; set; }
public IWebServiceOutgoingMessage Message { get; set; }
public MDSDataTransferResponseMessage CreateDataTransferResponseMessage()
{
return new MDSDataTransferResponseMessage
{
Message = (MDSDataTransferMessage) Message,
Result = (MDSOperationResultMessage) Result
};
}
}
/// <summary>
/// Implements IWebServiceOperationResultMessage to be used by MDS web service.
/// </summary>
private class ResultMessage : MDSOperationResultMessage, IWebServiceOperationResultMessage
{
//No data or method
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Caminho;
namespace CommonTimeGames.Caminho
{
public class CaminhoDialogueRunner : MonoBehaviour
{
private CaminhoEngine _engine;
// Use this for initialization
void Start()
{
_engine = new CaminhoEngine();
_engine.Initialize();
}
// Update is called once per frame
void Update()
{
}
public void Start(string dialogue,
string package = default(string),
string startNode = default(string))
{
_engine.Start(dialogue, package, startNode);
}
public void Continue(int value = 1)
{
_engine.Continue(value);
}
public void End()
{
_engine.End();
}
}
}
|
using Agent.Installer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AgentService agentService = new AgentService();
agentService.Assemblypath = Path.Combine(@"I:\VMM\Agent\Agent.Install\bin\Release\2222", "../");
agentService.Install();
}
}
}
|
using LDMApp.Core.Models;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Text;
namespace LDMApp.Core.Events
{
public class SampleSelectedEvent : PubSubEvent<IDictionary<string,object>>
{
}
}
|
// GIMP# - A C# wrapper around the GIMP Library
// Copyright (C) 2004-2009 Maurits Rijk
//
// GimpBaseEnums.cs
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
namespace Gimp
{
public enum AddMaskType
{
White,
Black,
Alpha,
AlphaTransfer,
Selection,
Copy
}
public enum BlendMode
{
FgBgRgb,
FgBgHsv,
FgTransparent,
Custom
}
public enum BucketFillMode
{
Foreground,
Background,
Pattern,
}
public enum ChannelOps
{
Add,
Subtract,
Replace,
Intersect
}
public enum ChannelType
{
Red,
Green,
Blue,
Gray,
Indexed,
Alpha
}
public enum CheckSize
{
Small,
Medium,
Large
}
public enum CheckType
{
Light,
Gray,
Dark,
WhiteOnly,
GrayOnly,
BlackOnly
}
public enum DesaturateMode
{
Lightness,
Luminosity,
Average
}
public enum DodgeBurnType
{
Dodge,
Burn
}
public enum ForegroundExtractMode
{
ExtractSiox
}
public enum GradientType
{
Linear,
Bilinear,
Radial,
Square,
ConicalSymmetric,
ConicalAsymmetric,
ShapeburstAngular,
ShapeburstSpherical,
ShapeburstDimpled,
SpiralClockwise,
SpiralAnticlockwise
}
public enum GridStyle
{
Dots,
Intersections,
OnOffDash,
DoubleDash,
Solid
}
public enum IconType
{
StockId,
InlinePixbuf,
ImageFile
}
public enum ImageBaseType
{
Rgb,
Gray,
Indexed
}
public enum ImageType
{
Rgb,
Rgba,
Gray,
Graya,
Indexed,
Indexeda
}
public enum InterpolationType
{
None,
Linear,
Cubic,
Lanczos
}
public enum MessageHandlerType
{
MessageBox,
Console,
ErrorConsole
}
public enum PaintApplicationMode
{
Constant,
Incremental
}
public enum PDBArgType
{
Int32,
Int16,
Int8,
Float,
String,
Int32array,
Int16array,
Int8array,
Floatarray,
Stringarray,
Color,
Region,
Display,
Image,
Layer,
Channel,
Drawable,
Selection,
ColorArray,
Vectors,
Parasite,
Status,
End,
Path = Vectors, // deprecated
Boundary = ColorArray // deprecated
}
public enum PDBProcType
{
Internal,
Plugin,
Extension,
Temporary
}
public enum PDBStatusType
{
ExecutionError,
CallingError,
PassThrough,
Success,
Cancel
}
public enum ProgressCommand
{
Start,
End,
SetText,
SetValue,
Pulse
}
public enum RepeatMode
{
None,
Sawtooth,
Triangular
}
public enum SizeType
{
Pixels,
Points
}
public enum StackTraceMode
{
Never,
Query,
Always
}
public enum TextDirection
{
Ltr,
Rtl
}
public enum TextJustification
{
Left,
Right,
Center,
Fill
}
public enum TransferMode
{
Shadows,
Midtones,
Highlights
}
public enum TransformDirection
{
Forward,
Backward
}
public enum TransformResize
{
Adjust = 0,
Clip = 1,
Crop,
CropWithAspect
}
public enum UserDirectory
{
Desktop,
Documents,
Download,
Music,
Pictures,
PublicShare,
Templates,
Videos
}
public enum VectorsStrokeType
{
Bezier
}
}
|
using LM.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LM.Data
{
public interface ILMDataReps: IDbSession
{
}
}
|
using MyCashFlow.Web.ViewModels.Shared;
using Rsx = MyCashFlow.Resources.Localization.Views;
using System.Collections.Generic;
namespace MyCashFlow.Web.ViewModels.PaymentMethod
{
public class PaymentMethodIndexViewModel : BaseViewModel
{
public PaymentMethodIndexViewModel()
: base(title: Rsx.PaymentMethod._Shared.Title,
header: string.Format(Rsx.Shared.Index.Header, Rsx.PaymentMethod._Shared.Title.ToLower() + "s"))
{ }
public IList<PaymentMethodIndexItemViewModel> Items { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class DecimalToBinary
{
static void Main()
{
/*Write a program to convert decimal numbers to their binary representation.*/
Console.Write("Enter a decimal number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("The decimal number {0} is: ", number);
List<int> bin = new List<int>();
for (int i = 0; i < 32; i++)
{
bin.Add(number % 2);
number /= 2;
}
bin.Reverse();
Console.WriteLine();
for (int i = 0; i < bin.Count; i++)
{
Console.Write(bin[i]);
}
Console.WriteLine(" in binary system.");
Console.WriteLine();
}
}
|
using System.Collections.Generic;
using Akka.Actor;
using akka_microservices_proj.Domain;
namespace akka_microservices_proj.Actors.Provider
{
/// <summary>
/// Provider created to prevent already existent actor after page refresh
/// </summary>
public class ActorProvider
{
private IActorRef BasketActor { get; }
private IActorRef ProductActor { get; }
public ActorProvider(ActorSystem actorSystem)
{
ProductActor = actorSystem.ActorOf(Props.Create(() => new ProductActor(GetMockProducts())), "product");
BasketActor = actorSystem.ActorOf(Props.Create(() => new BasketActor(ProductActor)), "basket");
}
/// <summary>
/// Mock Products found on my desk
/// ¯\_(ツ)_/¯
/// </summary>
/// <returns></returns>
private List<Product> GetMockProducts()
{
return new List<Product>
{
new Product
{
Id = 1,
Name = "Lamp",
Price = 2499,
Stock = new Stock
{
StockAmount = 15,
}
},
new Product
{
Id = 2,
Name = "Controller",
Price = 5999,
Stock = new Stock
{
StockAmount = 1,
}
},
new Product
{
Id = 3,
Name = "Mug",
Price = 1499,
Stock = new Stock
{
StockAmount = 20,
}
},
new Product
{
Id = 4,
Name = "Rubik's Cube",
Price = 1299,
Stock = new Stock
{
StockAmount = 12,
}
},
new Product
{
Id = 5,
Name = "MousePad",
Price = 2499,
Stock = new Stock
{
StockAmount = 8,
}
},
};
}
public IActorRef GetBasketActor()
{
return BasketActor;
}
public IActorRef GetProductActor()
{
return ProductActor;
}
}
}
|
using PickUp.Dal.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace PickUp.Dal.Interfaces
{
public interface IUserServices<TEntity>
{
IEnumerable<TEntity> GetAll();
TEntity GetById(int key);
IEnumerable<TEntity> GetByCategoryId(int key);
IEnumerable<TEntity> GetAllProNow();
void Register(TEntity entity);
TEntity Login(string email, string password);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Text;
[System.Serializable]
public class BaseItem {
public string itemName { get; set; }
public string tooltip { get; set; }
public string icon { get; set; }
public int itemID { get; set; }
public enum ItemTypes{
WEAPON,
SCROLL,
POTION,
CHEST,
OFFHAND,
HELM,
GLOVE,
BOOTS,
RING,
EARRING,
PANTS,
NECK,
MATERIAL,
DEFAULT,
ALL
}
public enum Rarity{
COMMON,
MAGIC,
RARE,
UNIQUE
}
public ItemTypes itemType { get; set; }
[JsonIgnore]
public Sprite sprite { get; set; }
public string spriteLocation { get; set; }
protected virtual void Awake()
{
Debug.Log("DOING THE LOAD");
sprite = Resources.Load<Sprite>(spriteLocation);
}
public BaseItem()
{
this.itemID = -1;
this.itemType = ItemTypes.DEFAULT;
}
public virtual string GetDescription(string s)
{
return s.ToString();
}
}
|
using UnityEngine;
using System.Collections;
using System;
namespace MoLiFrameWork.UI
{
public delegate void StateChangedEvent(object sender, EnumObjectState newState, EnumObjectState oldState);
//全局枚举对象
public enum EnumObjectState
{
None,
Initial,
Loading,
Ready,
Disabled,
Closing
}
public enum EnumUIType:int
{
None = -1,
TestOne = 0,
TestTwo = 1
}
public class UIPathDefines
{
/// <summary>
/// UI预设
/// </summary>
public const string UI_PREFAB = "Prefabs/";
/// <summary>
/// UI小控件预设
/// </summary>
public const string UI_CONTROLS_PREFAB = "UIPrefab/Control";
/// <summary>
/// UI子页面预设
/// </summary>
public const string UI_SUBUI_PREFAB = "UIPrefab/SubUI/";
/// <summary>
/// icon路径
/// </summary>
public const string UI_ICON_PATH = "UI/Icon";
public static string GetPrefabsPathByType(EnumUIType _uiType)
{
string _path = string.Empty;
switch(_uiType)
{
case EnumUIType.TestOne:
_path = UI_PREFAB + "TestOne";
break;
case EnumUIType.TestTwo:
_path = UI_PREFAB + "TestTwo";
break;
default:
Debug.Log("Not Find EnumUIType type: " + _uiType.ToString());
break;
}
return _path;
}
public static System.Type GetUIScriptByType(EnumUIType _uiType)
{
System.Type _scriptType = null;
switch(_uiType)
{
case EnumUIType.TestOne:
_scriptType = typeof(TestOne);
break;
case EnumUIType.TestTwo:
_scriptType = typeof(TestTwo);
break;
default:
Debug.Log("Not Find EnumUIType! type:" + _uiType.ToString());
break;
}
return _scriptType;
}
}
public class Defines :MonoBehaviour
{
}
} |
using Mojio.Events;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Mojio.Client
{
public partial class MojioClient
{
static Dictionary<SubscriptionType, string> PushTypeMap = new Dictionary<SubscriptionType, string>()
{
{ SubscriptionType.Mojio , "Mojios" },
{ SubscriptionType.User, "Users" },
{ SubscriptionType.Trip, "Trips" }
};
const string PushController = "notify";
public string PushRegistrationId { get; set; }
public ChannelType PushRegistrationType { get; set; }
public void SubscribePush<T>(object id, EventType events )
{
var request = GetRequest(Request(Map[typeof(T)], id, "notify"), Method.POST);
request.AddBody(events);
var response = RestClient.Execute(request);
return;
}
public void GetSubscriptions()
{
}
}
}
|
using System;
using System.Text;
using MDS.Client;
namespace Application1
{
class Program
{
static void Main()
{
//Create MDSClient object to connect to DotNetMQ
//Name of this application: Application1
var mdsClient = new MDSClient("Application1");
//Connect to DotNetMQ server
mdsClient.Connect();
Console.WriteLine("Write a text and press enter to send to Application2. Write 'exit' to stop application.");
while (true)
{
//Get a message from user
var messageText = Console.ReadLine();
if (string.IsNullOrEmpty(messageText) || messageText == "exit")
{
break;
}
//Create a DotNetMQ Message to send to Application2
var message = mdsClient.CreateMessage();
//Set destination application name
message.DestinationApplicationName = "Application2";
//message.DestinationServerName = "this_server2";
//Set message data
message.MessageData = Encoding.UTF8.GetBytes(messageText);
//Send message
message.Send();
}
//Disconnect from DotNetMQ server
mdsClient.Disconnect();
}
}
}
|
using Zhouli.BLL.Interface;
using Zhouli.DAL.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.SqlClient;
namespace Zhouli.BLL.Implements
{
public class BaseBLL<T> : IBaseBLL<T> where T : class, new()
{
protected IBaseDAL<T> Dal { get; set; }
public BaseBLL(IBaseDAL<T> Dal)
{
this.Dal = Dal;
}
public bool Add(T t)
{
Dal.Add(t);
return Dal.SaveChanges();
}
public bool AddRange(IEnumerable<T> t)
{
Dal.AddRange(t);
return Dal.SaveChanges();
}
public bool Delete(T t)
{
Dal.Delete(t);
return Dal.SaveChanges();
}
public bool Delete(IEnumerable<T> t)
{
Dal.Delete(t);
return Dal.SaveChanges();
}
public bool Delete(Expression<Func<T, bool>> whereLambda)
{
Dal.Delete(whereLambda);
return Dal.SaveChanges();
}
public bool Update(T t)
{
Dal.Update(t);
return Dal.SaveChanges();
}
// BLL层此方法屏蔽掉,避免BLL层写sql
//public int ExecuteSql(string sql, SqlParameter parameter = null)
//{
// return Dal.ExecuteSql(sql, parameter);
//}
public int GetCount(Expression<Func<T, bool>> whereLambda)
{
return Dal.GetCount(whereLambda);
}
public List<T> GetModels(Expression<Func<T, bool>> whereLambda)
{
return Dal.GetModels(whereLambda).ToList();
}
public List<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc,
Expression<Func<T, type>> orderByLambda, Expression<Func<T, bool>> whereLambda)
{
return Dal.GetModelsByPage(pageSize, pageIndex, isAsc, orderByLambda, whereLambda).ToList();
}
//BLL层此方法屏蔽掉,避免BLL层写sql
//public IEnumerable<T> SqlQuery(string sql)
//{
// return Dal.SqlQuery<T>(sql);
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ScoringSystem
{
public class SynchronousScoreSIMDDeterminant : ScoreDeterminant
{
public SynchronousScoreSIMDDeterminant(ScoreConfiguration configuration) : base(configuration) { }
public override void GetScoring(List<ScoreItem> items)
{
GetMinMaxVector(items);
var minMaxDif = SubstractVectors(_vmax, _vmin);
var proportions = DivideVectors(_vbase, minMaxDif);
foreach(var item in items)
{
var unifiedFactors = Array.ConvertAll(MultiplyVectors(item.Factories, proportions), x => (short)x);
var scoringVector = MultiplyVectors(unifiedFactors, _scoringWeights);
item.Score = SumVector(scoringVector);
}
}
protected void GetMinMaxVector(List<ScoreItem> items)
{
var simdLenght = Vector<float>.Count;
foreach (var item in items)
{
int i;
for (i = 0; i <= _factorsCount - simdLenght; i += simdLenght)
{
var vtmax = new Vector<float>(_vmax, i);
var vtmin = new Vector<float>(_vmin, i);
var vnext = new Vector<float>(item.Factories, i);
Vector.Max(vtmax, vnext).CopyTo(_vmax, i);
Vector.Min(vtmin, vnext).CopyTo(_vmin, i);
}
for (; i < _factorsCount; ++i)
{
_vmax[i] = Math.Max(_vmax[i], item.Factories[i]);
_vmin[i] = Math.Min(_vmin[i], item.Factories[i]);
}
}
}
protected float[] AddVectors(float[] aleft, float[] aright)
{
var simdLenght = Vector<float>.Count;
var result = new float[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<float>(aleft, i);
var vb = new Vector<float>(aright, i);
(va + vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (float)(aleft[i] + aright[i]);
}
return result;
}
protected float[] SubstractVectors(float[] aleft, float[] aright)
{
var simdLenght = Vector<float>.Count;
var result = new float[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<float>(aleft, i);
var vb = new Vector<float>(aright, i);
(va - vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (float)(aleft[i] - aright[i]);
}
return result;
}
protected float[] MultiplyVectors(float[] aleft, float[] aright)
{
var simdLenght = Vector<float>.Count;
var result = new float[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<float>(aleft, i);
var vb = new Vector<float>(aright, i);
(va * vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (float)(aleft[i] * aright[i]);
}
return result;
}
protected float[] DivideVectors(float[] aleft, float[] aright)
{
var simdLenght = Vector<float>.Count;
var result = new float[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<float>(aleft, i);
var vb = new Vector<float>(aright, i);
(va / vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (float)(aleft[i] / aright[i]);
}
return result;
}
protected short[] AddVectors(short[] aleft, short[] aright)
{
var simdLenght = Vector<short>.Count;
var result = new short[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<short>(aleft, i);
var vb = new Vector<short>(aright, i);
(va + vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (short)(aleft[i] + aright[i]);
}
return result;
}
protected short[] SubstractVectors(short[] aleft, short[] aright)
{
var simdLenght = Vector<short>.Count;
var result = new short[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<short>(aleft, i);
var vb = new Vector<short>(aright, i);
(va - vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (short)(aleft[i] - aright[i]);
}
return result;
}
protected short[] MultiplyVectors(short[] aleft, short[] aright)
{
var simdLenght = Vector<short>.Count;
var result = new short[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<short>(aleft, i);
var vb = new Vector<short>(aright, i);
(va * vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (short)(aleft[i] * aright[i]);
}
return result;
}
protected short[] DivideVectors(short[] aleft, short[] aright)
{
var simdLenght = Vector<short>.Count;
var result = new short[aleft.Length];
var i = 0;
for (i = 0; i <= result.Length - simdLenght; i += simdLenght)
{
var va = new Vector<short>(aleft, i);
var vb = new Vector<short>(aright, i);
(va / vb).CopyTo(result, i);
}
for (; i < aleft.Length; ++i)
{
result[i] = (short)(aleft[i] / aright[i]);
}
return result;
}
}
}
|
using System;
using System.Reflection;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
/// <summary>
/// This interface is to be used by all objects that need to be able to create a full, deep
/// copy of themselves. The method itself comes from http://www.thomashapp.com/node/106. I
/// have put it as an interface rather than a class, as most of the objects that need to use it
/// will derive from other base classes.
/// </summary>
public interface IDeepCopy
{
IDeepCopy DeepCopy();
} |
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="TcpConnection.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the TcpConnection class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
namespace IndiePortable.Communication.UniversalWindows
{
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using AdvancedTasks;
using Devices;
using Devices.ConnectionMessages;
using EncryptedConnection;
using Formatter;
using Messages;
using Tcp;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using RTBuffer = Windows.Storage.Streams.Buffer;
/// <summary>
/// Represents a connection between two TCP end points.
/// </summary>
/// <seealso cref="Devices.IConnection{TAddress}" />
/// <seealso cref="IDisposable" />
public sealed partial class TcpConnection
: ICryptableConnection<IPPortAddressInfo>, IDisposable
{
/// <summary>
/// Contains the default keep alive frequency of the <see cref="TcpConnection" /> of 5 seconds.
/// </summary>
public static readonly TimeSpan DefaultKeepAliveFrequency = TimeSpan.FromSeconds(5d);
/// <summary>
/// Contains the default maximum keep alive timeout of the <see cref="TcpConnection" /> of 10 seconds.
/// </summary>
public static readonly TimeSpan DefaultMaxKeepAliveTimeout = TimeSpan.FromSeconds(10d);
/// <summary>
/// The backing field for the <see cref="Cache" /> property.
/// </summary>
private readonly MessageDispatcher cacheBacking;
/// <summary>
/// The backing field for the <see cref="RemoteAddress" /> property.
/// </summary>
private readonly IPPortAddressInfo remoteAddressBacking;
/// <summary>
/// The <see cref="BinaryFormatter" /> used to serialize and deserialize messages.
/// </summary>
private readonly BinaryFormatter formatter = BinaryFormatter.CreateWithCoreSurrogates();
private readonly ConnectionMessageDispatcher<IPPortAddressInfo> connectionCache;
private readonly SemaphoreSlim writeSemaphore = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim keepAliveSemaphore = new SemaphoreSlim(1, 1);
private readonly CryptoManagerBase<PublicKeyInfo> cryptoManager;
private readonly StreamSocket socket;
private readonly IInputStream inputStream;
/// <summary>
/// The <see cref="Stream" /> serving as output.
/// </summary>
private readonly Stream outputStream;
private readonly SemaphoreSlim activationStateSemaphore = new SemaphoreSlim(1, 1);
/// <summary>
/// The backing field for the <see cref="KeepAliveFrequency" /> property.
/// </summary>
private readonly TimeSpan keepAliveFrequencyBacking;
/// <summary>
/// The backing field fort he <see cref="MaxKeepAliveTimeout" /> property.
/// </summary>
private readonly TimeSpan maxKeepAliveTimeoutBacking;
/// <summary>
/// The backing field for the <see cref="IsActivated" /> property.
/// </summary>
private bool isActivatedBacking;
/// <summary>
/// The backing field for the <see cref="IsConnected" /> property.
/// </summary>
private bool isConnectedBacking;
/// <summary>
/// Indicates whether the <see cref="TcpConnection" /> is disposed.
/// </summary>
private bool isDisposed;
/// <summary>
/// The backing filed for the <see cref="IsSessionEncrypted" /> property.
/// </summary>
private bool isSessionEncryptedBacking;
private StateTask messageReaderTask;
private StateTask keepAliveCheckerTask;
private StateTask keepAliveSenderTask;
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnection"/> class.
/// </summary>
/// <param name="socket">
/// The <see cref="StreamSocket" /> providing I/O operations for the <see cref="TcpConnection" />.
/// Must not be <c>null</c>.
/// </param>
/// <param name="remoteAddress">
/// The address of the remote host.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if:</para>
/// <list type="bullet">
/// <item>
/// <description><paramref name="socket" /> is <c>null</c>.</description>
/// </item>
/// <item>
/// <description><paramref name="remoteAddress" /> is <c>null</c>.</description>
/// </item>
/// </list>
/// </exception>
public TcpConnection(StreamSocket socket, IPPortAddressInfo remoteAddress)
: this(socket, remoteAddress, new RsaCryptoManager())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnection" /> class.
/// </summary>
/// <param name="socket">The client.</param>
/// <param name="remoteAddress">The remote address.</param>
/// <param name="keepAliveFrequency">The keep alive frequency.</param>
/// <param name="maxKeepAliveTimeout">The maximum keep alive timeout.</param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if at least one of the following conditions applies:</para>
/// <list type="bullet">
/// <item><paramref name="socket" /> is <c>null</c>.</item>
/// <item><paramref name="remoteAddress" /> is <c>null</c>.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>Thrown if at least one of the following conditions applies:</para>
/// <list type="bullet">
/// <item><paramref name="keepAliveFrequency" /> is <c>null</c>.</item>
/// <item><paramref name="maxKeepAliveTimeout" /> is <c>null</c>.</item>
/// </list>
/// </exception>
public TcpConnection(StreamSocket socket, IPPortAddressInfo remoteAddress, TimeSpan keepAliveFrequency, TimeSpan maxKeepAliveTimeout)
: this(socket, remoteAddress, new RsaCryptoManager(), keepAliveFrequency, maxKeepAliveTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnection"/> class.
/// </summary>
/// <param name="socket">
/// The <see cref="StreamSocket" /> providing I/O operations for the <see cref="TcpConnection" />.
/// Must not be <c>null</c>.
/// </param>
/// <param name="remoteAddress">
/// The address of the remote host.
/// Must not be <c>null</c>.
/// </param>
/// <param name="cryptoManager">
/// The <see cref="CryptoManagerBase{T}" /> managing the encryption and decryption of messages.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if at least one of the following conditions applies:</para>
/// <list type="bullet">
/// <item><paramref name="socket" /> is <c>null</c>.</item>
/// <item><paramref name="remoteAddress" /> is <c>null</c>.</item>
/// <item><paramref name="cryptoManager" /> is <c>null</c>.</item>
/// </list>
/// </exception>
public TcpConnection(StreamSocket socket, IPPortAddressInfo remoteAddress, CryptoManagerBase<PublicKeyInfo> cryptoManager)
: this(socket, remoteAddress, cryptoManager, DefaultKeepAliveFrequency, DefaultMaxKeepAliveTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TcpConnection"/> class.
/// </summary>
/// <param name="socket">
/// The <see cref="StreamSocket" /> providing I/O operations for the <see cref="TcpConnection" />.
/// Must not be <c>null</c>.
/// </param>
/// <param name="remoteAddress">
/// The address of the remote host.
/// Must not be <c>null</c>.
/// </param>
/// <param name="cryptoManager">
/// The <see cref="CryptoManagerBase{T}" /> managing the encryption and decryption of messages.
/// Must not be <c>null</c>.
/// </param>
/// <param name="keepAliveFrequency">
/// The interval of sending keep-alive messages.
/// Must be greater than <see cref="TimeSpan.Zero" />.
/// </param>
/// <param name="maxKeepAliveTimeout">
/// The maximum acceptable interval between sending two keep-alive messages.
/// Must be greater than <paramref name="keepAliveFrequency" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if at least one of the following conditions applies:</para>
/// <list type="bullet">
/// <item><paramref name="socket" /> is <c>null</c>.</item>
/// <item><paramref name="remoteAddress" /> is <c>null</c>.</item>
/// <item><paramref name="cryptoManager" /> is <c>null</c>.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>Thrown if at least one of the following conditions applies:</para>
/// <list type="bullet">
/// <item><paramref name="keepAliveFrequency" /> is <c>null</c>.</item>
/// <item><paramref name="maxKeepAliveTimeout" /> is <c>null</c>.</item>
/// </list>
/// </exception>
public TcpConnection(
StreamSocket socket,
IPPortAddressInfo remoteAddress,
CryptoManagerBase<PublicKeyInfo> cryptoManager,
TimeSpan keepAliveFrequency,
TimeSpan maxKeepAliveTimeout)
{
if (object.ReferenceEquals(socket, null))
{
throw new ArgumentNullException(nameof(socket));
}
if (object.ReferenceEquals(remoteAddress, null))
{
throw new ArgumentNullException(nameof(remoteAddress));
}
if (object.ReferenceEquals(cryptoManager, null))
{
throw new ArgumentNullException(nameof(cryptoManager));
}
if (keepAliveFrequency <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(keepAliveFrequency));
}
if (maxKeepAliveTimeout <= keepAliveFrequency ||
maxKeepAliveTimeout >= TimeSpan.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(maxKeepAliveTimeout));
}
this.socket = socket;
this.isConnectedBacking = true;
this.remoteAddressBacking = remoteAddress;
this.inputStream = this.socket.InputStream;
this.outputStream = this.socket.OutputStream.AsStreamForWrite();
this.cacheBacking = new MessageDispatcher(this);
this.cryptoManager = cryptoManager;
this.keepAliveFrequencyBacking = keepAliveFrequency;
this.maxKeepAliveTimeoutBacking = maxKeepAliveTimeout;
this.connectionCache = new ConnectionMessageDispatcher<IPPortAddressInfo>(this);
this.handlerDisconnect = new ConnectionMessageHandler<ConnectionDisconnectRequest>(this.HandleDisconnect);
this.handlerKeepAlive = new ConnectionMessageHandler<ConnectionMessageKeepAlive>(this.HandleKeepAlive);
this.handlerContent = new ConnectionMessageHandler<ConnectionContentMessage>(this.HandleContent);
this.handlerEncryptionRequest = new ConnectionMessageHandler<ConnectionEncryptRequest>(this.HandleEncryptionRequest);
this.connectionCache.AddMessageHandler(this.handlerDisconnect);
this.connectionCache.AddMessageHandler(this.handlerKeepAlive);
this.connectionCache.AddMessageHandler(this.handlerContent);
this.connectionCache.AddMessageHandler(this.handlerEncryptionRequest);
}
/// <summary>
/// Finalizes an instance of the <see cref="TcpConnection" /> class.
/// </summary>
~TcpConnection()
{
this.Dispose(false);
}
/// <summary>
/// Raised when a <see cref="ConnectionMessageBase" /> has been received.
/// </summary>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.ConnectionMessageReceived" /> implicitly.</para>
/// </remarks>
public event EventHandler<ConnectionMessageReceivedEventArgs> ConnectionMessageReceived;
/// <summary>
/// Raised when a <see cref="MessageBase" /> object has been received.
/// </summary>
/// <remarks>
/// <para>Implements <see cref="IMessageReceiver.MessageReceived" /> implicitly.</para>
/// </remarks>
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
/// <summary>
/// Raised when the <see cref="TcpConnection" /> has been disconnected.
/// </summary>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.Disconnected" /> implicitly.</para>
/// </remarks>
public event EventHandler Disconnected;
/// <summary>
/// Gets the <see cref="MessageDispatcher" /> acting as a message cache for the <see cref="TcpConnection" />.
/// </summary>
/// <value>
/// Contains the <see cref="MessageDispatcher" /> acting as a message cache for the <see cref="TcpConnection" />.
/// </value>
/// <remarks>
/// <para>Implements <see cref="IMessageReceiver.Cache" /> implicitly.</para>
/// </remarks>
public MessageDispatcher Cache => this.cacheBacking;
/// <summary>
/// Gets a value indicating whether the <see cref="TcpConnection" /> is activated.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="TcpConnection" /> is activated; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// Messages can only be sent or received if <see cref="IsActivated" /> is <c>true</c>.
/// Otherwise, an <see cref="InvalidOperationException" /> will be thrown.
/// </para>
/// <para>Implements <see cref="IConnection{TAddress}.IsActivated" /> implicitly.</para>
/// </remarks>
public bool IsActivated => this.isActivatedBacking;
/// <summary>
/// Gets a value indicating whether the <see cref="TcpConnection" /> is connected to the other end.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="TcpConnection" /> is connected; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.IsConnected" /> implicitly.</para>
/// </remarks>
public bool IsConnected => this.isConnectedBacking;
/// <summary>
/// Gets a value indicating whether the current connection session is session encrypted.
/// </summary>
/// <value>
/// <c>true</c> if the current connection session is encrypted; otherwise, <c>false</c>.
/// </value>
public bool IsSessionEncrypted => this.isSessionEncryptedBacking;
/// <summary>
/// Gets the interval of sending keep-alive messages.
/// </summary>
/// <value>
/// Contains the interval of sending keep-alive messages.
/// </value>
public TimeSpan KeepAliveFrequency => this.keepAliveFrequencyBacking;
/// <summary>
/// Gets the maximum acceptable interval between sending two keep-alive messages.
/// </summary>
/// <value>
/// Contains the maximum acceptable interval between sending two keep-alive messages.
/// </value>
public TimeSpan MaxKeepAliveTimeout => this.maxKeepAliveTimeoutBacking;
/// <summary>
/// Gets the remote address of the other connection end.
/// </summary>
/// <value>
/// Contains the remote address of the other connection end.
/// </value>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.RemoteAddress" /> implicitly.</para>
/// </remarks>
public IPPortAddressInfo RemoteAddress => this.remoteAddressBacking;
/// <summary>
/// Activates the <see cref="TcpConnection" />.
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the <see cref="TcpConnection" /> has already been activated.</para>
/// </exception>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.Activate()" /> implicitly.</para>
/// <para>Call this method to allow incoming and outgoing messages to be sent or received.</para>
/// </remarks>
public void Activate()
{
this.activationStateSemaphore.Wait();
try
{
if (this.IsActivated)
{
throw new InvalidOperationException();
}
this.messageReaderTask = new StateTask(this.MessageReader);
this.keepAliveCheckerTask = new StateTask(this.KeepAliveChecker);
this.keepAliveSenderTask = new StateTask(this.KeepAliveSender);
this.isActivatedBacking = true;
}
finally
{
this.activationStateSemaphore.Release();
}
}
/// <summary>
/// Disconnects the two end points.
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if one of the following conditions is true:</para>
/// <list type="bullet">
/// <item>
/// <description>The <see cref="IsActivated" /> property is <c>false</c>.</description>
/// </item>
/// <item>
/// <description>The <see cref="TcpConnection" /> is disposed.</description>
/// </item>
/// <item>
/// <description>The <see cref="IsConnected" /> property is <c>false</c>.</description>
/// </item>
/// </list>
/// </exception>
/// <remarks>
/// <para>Implements <see cref="IConnection{TAddress}.Disconnect()" /> implicitly.</para>
/// </remarks>
public void Disconnect() => this.Disconnect(TimeSpan.FromSeconds(5d));
/// <summary>
/// Disconnects the two end points.
/// </summary>
/// <param name="timeout">
/// The duration that shall be waited until a disconnect response has been received.
/// Must be greater than <see cref="TimeSpan.Zero" />.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>Thrown if <paramref name="timeout" /> is smaller or equals <see cref="TimeSpan.Zero" />.</para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if one of the following conditions is true:</para>
/// <list type="bullet">
/// <item>
/// <description>The <see cref="IsActivated" /> property is <c>false</c>.</description>
/// </item>
/// <item>
/// <description>The <see cref="TcpConnection" /> is disposed.</description>
/// </item>
/// <item>
/// <description>The <see cref="IsConnected" /> property is <c>false</c>.</description>
/// </item>
/// </list>
/// </exception>
public void Disconnect(TimeSpan timeout)
{
if (timeout <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(timeout));
}
if (!this.IsActivated || this.isDisposed || !this.IsConnected)
{
throw new InvalidOperationException();
}
try
{
this.keepAliveCheckerTask.Stop();
var rq = new ConnectionDisconnectRequest();
this.SendConnectionMessage(rq);
this.connectionCache.Wait<ConnectionDisconnectRequest, ConnectionDisconnectResponse>(rq, timeout);
}
catch (IOException)
{
}
finally
{
this.messageReaderTask.Stop();
this.isConnectedBacking = false;
this.RaiseDisconnected();
this.Dispose();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>
/// <para>Implements <see cref="IDisposable.Dispose()" /> implicitly.</para>
/// </remarks>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Starts the encryption session for the <see cref="TcpConnection" />.
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the encryption session has already been started. Check the <see cref="IsSessionEncrypted" /> property.</para>
/// </exception>
public void StartEncryptionSession()
{
if (this.IsSessionEncrypted)
{
throw new InvalidOperationException();
}
var rq = new ConnectionEncryptRequest(this.cryptoManager.LocalPublicKey);
this.SendConnectionMessage(rq);
var rsp = this.connectionCache.Wait<ConnectionEncryptRequest, ConnectionEncryptResponse>(rq, TimeSpan.FromSeconds(5));
if (object.ReferenceEquals(rsp, null))
{
throw new InvalidOperationException();
}
this.cryptoManager.StartSession(rsp.PublicKey);
this.isSessionEncryptedBacking = true;
}
/// <summary>
/// Asynchronously starts the encryption session for the <see cref="TcpConnection" />.
/// </summary>
/// <returns>
/// The task executing the method.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the encryption session has already been started. Check the <see cref="IsSessionEncrypted" /> property.</para>
/// </exception>
public async Task StartEncryptionSessionAsync()
{
if (this.IsSessionEncrypted)
{
throw new InvalidOperationException();
}
var rq = new ConnectionEncryptRequest(this.cryptoManager.LocalPublicKey);
await this.SendConnectionMessageAsync(rq);
var rsp = await this.connectionCache.WaitAsync<ConnectionEncryptRequest, ConnectionEncryptResponse>(rq, TimeSpan.FromSeconds(5));
if (object.ReferenceEquals(rsp, null))
{
throw new InvalidOperationException();
}
this.cryptoManager.StartSession(rsp.PublicKey);
this.isSessionEncryptedBacking = true;
}
/// <summary>
/// Sends a <see cref="MessageBase" /> object to the other connection end.
/// </summary>
/// <param name="message">
/// The <see cref="MessageBase" /> that shall be sent.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="message" /> is <c>null</c>.</para>
/// </exception>
public void SendMessage(MessageBase message)
{
if (object.ReferenceEquals(message, null))
{
throw new ArgumentNullException(nameof(message));
}
this.SendConnectionMessage(new ConnectionContentMessage(message));
}
/// <summary>
/// Sends a <see cref="MessageBase" /> object asynchronously to the other connection end.
/// </summary>
/// <param name="message">
/// The <see cref="MessageBase" /> that shall be sent.
/// Must not be <c>null</c>.
/// </param>
/// <returns>
/// The task processing the method.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="message" /> is <c>null</c>.</para>
/// </exception>
public async Task SendMessageAsync(MessageBase message)
{
if (object.ReferenceEquals(message, null))
{
throw new ArgumentNullException(nameof(message));
}
await this.SendConnectionMessageAsync(new ConnectionContentMessage(message));
}
/// <summary>
/// Sends a connection message.
/// </summary>
/// <param name="message">
/// The <see cref="ConnectionMessageBase" /> that shall be sent.
/// Must not be <c>null</c>.
/// </param>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the <see cref="TcpConnection" /> is not activated. Check the <see cref="IsActivated" /> property.</para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="message" /> is <c>null</c>.</para>
/// </exception>
private void SendConnectionMessage(ConnectionMessageBase message)
{
if (!this.IsActivated)
{
throw new InvalidOperationException($"The {nameof(TcpConnection)} must be activated in order to send a message.");
}
if (object.ReferenceEquals(message, null))
{
throw new ArgumentNullException(nameof(message));
}
using (var str = new MemoryStream())
{
using (var tempstr = new MemoryStream())
{
// serialize message into stream
this.formatter.Serialize(tempstr, message);
byte[] toWrite;
if (this.IsSessionEncrypted)
{
var toEncrypt = tempstr.ToArray();
toWrite = this.cryptoManager.Encrypt(toEncrypt);
}
else
{
toWrite = tempstr.ToArray();
}
var lengthBytes = BitConverter.GetBytes(toWrite.Length);
str.Write(lengthBytes, 0, sizeof(int));
str.Write(toWrite, 0, toWrite.Length);
}
str.Seek(0, SeekOrigin.Begin);
this.writeSemaphore.Wait();
try
{
str.CopyTo(this.outputStream);
this.outputStream.Flush();
}
finally
{
this.writeSemaphore.Release();
}
}
}
/// <summary>
/// Sends a connection message asynchonously.
/// </summary>
/// <param name="message">
/// The <see cref="ConnectionMessageBase" /> that shall be sent.
/// Must not be <c>null</c>.
/// </param>
/// <returns>
/// The running task.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the <see cref="TcpConnection" /> is not activated. Check the <see cref="IsActivated" /> property.</para>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="message" /> is <c>null</c>.</para>
/// </exception>
private async Task SendConnectionMessageAsync(ConnectionMessageBase message)
{
if (!this.IsActivated)
{
throw new InvalidOperationException($"The {nameof(TcpConnection)} must be activated in order to send a message.");
}
if (object.ReferenceEquals(message, null))
{
throw new ArgumentNullException(nameof(message));
}
using (var str = new MemoryStream())
{
using (var tempstr = new MemoryStream())
{
// serialize message into stream
await Task.Factory.StartNew(() => this.formatter.Serialize(tempstr, message));
byte[] toWrite;
if (this.IsSessionEncrypted)
{
var toEncrypt = tempstr.ToArray();
toWrite = this.cryptoManager.Encrypt(toEncrypt);
}
else
{
toWrite = tempstr.ToArray();
}
var lengthBytes = BitConverter.GetBytes(toWrite.Length);
await str.WriteAsync(lengthBytes, 0, sizeof(int));
await str.WriteAsync(toWrite, 0, toWrite.Length);
}
str.Seek(0, SeekOrigin.Begin);
await this.writeSemaphore.WaitAsync();
try
{
await str.CopyToAsync(this.outputStream);
await this.outputStream.FlushAsync();
}
finally
{
this.writeSemaphore.Release();
}
}
}
/// <summary>
/// Raises the <see cref="MessageReceived" /> event.
/// </summary>
/// <param name="message">
/// The <see cref="MessageBase" /> that has been received.
/// </param>
private void RaiseMessageReceived(MessageBase message) => this.MessageReceived?.Invoke(this, new MessageReceivedEventArgs(message));
/// <summary>
/// Raises the <see cref="ConnectionMessageReceived" /> event.
/// </summary>
/// <param name="message">
/// The <see cref="ConnectionMessageBase" /> that has been received.
/// </param>
private void RaiseConnectionMessageReceived(ConnectionMessageBase message)
=> this.ConnectionMessageReceived?.Invoke(this, new ConnectionMessageReceivedEventArgs(message));
/// <summary>
/// Raises the <see cref="Disconnected" /> event.
/// </summary>
private void RaiseDisconnected() => this.Disconnected?.Invoke(this, EventArgs.Empty);
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
/// </param>
private void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
}
this.keepAliveCheckerTask?.Stop();
this.keepAliveSenderTask?.Stop();
this.messageReaderTask?.Stop();
this.keepAliveSemaphore.Wait();
this.keepAliveSemaphore.Dispose();
this.activationStateSemaphore.Wait();
this.activationStateSemaphore.Dispose();
this.writeSemaphore.Wait();
this.writeSemaphore.Dispose();
this.socket.Dispose();
this.outputStream.Dispose();
this.Cache.Dispose();
this.connectionCache.Dispose();
this.isDisposed = true;
}
}
private async void MessageReader(ITaskConnection taskConnection)
{
if (object.ReferenceEquals(taskConnection, null))
{
throw new ArgumentNullException(nameof(taskConnection));
}
try
{
while (!taskConnection.MustFinish)
{
var lengthBuffer = new RTBuffer(sizeof(int));
await this.inputStream.ReadAsync(lengthBuffer, sizeof(int), InputStreamOptions.Partial);
if (lengthBuffer.Length == sizeof(int))
{
// get the length of the message
var lengthBytes = lengthBuffer.ToArray();
var length = BitConverter.ToInt32(lengthBytes, 0);
// fill the buffer with actual message
var messageBuffer = new byte[length];
var currentLength = 0U;
while (currentLength < length)
{
var leftLength = (uint)(length - currentLength);
var tempBuffer = new RTBuffer(leftLength);
await this.inputStream.ReadAsync(tempBuffer, leftLength, InputStreamOptions.Partial);
tempBuffer.CopyTo(0, messageBuffer, (int)currentLength, (int)tempBuffer.Length);
currentLength += tempBuffer.Length;
}
using (var bufferStream = new MemoryStream(messageBuffer, false))
{
if (this.formatter.TryDeserialize(bufferStream, out ConnectionMessageBase message))
{
new Task(() => this.RaiseConnectionMessageReceived(message)).Start();
}
else
{
// if deserialization fails, "reset" connection by consuming all bytes in the socket buffer
RTBuffer clearBuffer;
do
{
clearBuffer = new RTBuffer(sizeof(long));
await this.inputStream.ReadAsync(lengthBuffer, sizeof(long), InputStreamOptions.Partial);
}
while (clearBuffer.Length == sizeof(long));
}
}
}
await Task.Delay(5);
}
}
catch (TaskCanceledException)
{
}
catch (ObjectDisposedException)
{
}
catch (Exception exc)
{
taskConnection.ThrowException(exc);
return;
}
taskConnection.Return();
}
private void KeepAliveChecker(ITaskConnection connection)
{
if (object.ReferenceEquals(connection, null))
{
throw new ArgumentNullException(nameof(connection));
}
try
{
while (!connection.MustFinish)
{
if (!this.keepAliveSemaphore.Wait(TimeSpan.FromSeconds(10d)))
{
this.Disconnect();
connection.Stop();
}
}
}
catch (ObjectDisposedException)
{
}
catch (TaskCanceledException)
{
}
catch (Exception exc)
{
connection.ThrowException(exc);
return;
}
connection.Return();
}
private async void KeepAliveSender(ITaskConnection connection)
{
if (object.ReferenceEquals(connection, null))
{
throw new ArgumentNullException(nameof(connection));
}
try
{
while (!connection.MustFinish)
{
await this.SendConnectionMessageAsync(new ConnectionMessageKeepAlive());
await Task.Delay(this.KeepAliveFrequency);
}
}
catch (TaskCanceledException)
{
}
catch (Exception exc)
{
connection.ThrowException(exc);
return;
}
connection.Return();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsQuery.StringScanner.Implementation;
namespace CsQuery.StringScanner.Patterns
{
/// <summary>
/// ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters,
/// digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
/// </summary>
public class HtmlID: EscapedString
{
/// <summary>
/// Default constructor.
/// </summary>
public HtmlID():
base(IsValidID)
{
}
/// <summary>
/// Match a pattern for a valid HTML ID.
/// </summary>
///
/// <param name="index">
/// .
/// </param>
/// <param name="character">
/// .
/// </param>
///
/// <returns>
/// true if valid identifier, false if not.
/// </returns>
protected static bool IsValidID(int index, char character)
{
if (index == 0)
{
return CharacterData.IsType(character, CharacterType.AlphaISO10646);
}
else
{
return CharacterData.IsType(character, CharacterType.AlphaISO10646 | CharacterType.Number);
}
}
}
}
|
using AppBase.Core.ViewModel;
using AppBase.Services;
using OrganizationTwo.Services.Model;
using Prism.Commands;
using Prism.Navigation;
using System.Threading.Tasks;
namespace OrganizationTwo.Core.ViewModel
{
public class LoginPageViewModel : BaseViewModel
{
private readonly ILoginServiceBase loginService;
#region Properties
private string username;
public string Username
{
get { return username; }
set { SetProperty(ref username, value); }
}
private string password;
public string Password
{
get { return password; }
set { SetProperty(ref password, value); }
}
private string message;
public string Message
{
get { return message; }
set { SetProperty(ref message, value); }
}
#endregion
#region Commands
private DelegateCommand _login;
public DelegateCommand LoginCommand =>
_login ?? (_login = new DelegateCommand(async () => { await ExecuteLoginCommand(); }, CanExecuteLoginCommand));
async Task ExecuteLoginCommand()
{
var response = await loginService.ExecuteLogin(Username, Password);
var access = response.Data as User;
if (!response.Success)
Message = "Erro no login!!";
else
await navigationService.NavigateAsync("MainPage");
}
bool CanExecuteLoginCommand()
{
return true;
}
#endregion
public LoginPageViewModel(ILoginServiceBase loginService, INavigationService navigationService) : base(navigationService)
{
this.loginService = loginService;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditorInternal;
using UnityEngine;
public class Help : Task
{
public Help(Blackboard bb) : base(bb){}
public override bool execute()
{
GameObject aObj = this.bb.GetGameObject("Agent");
// If no marked target, fail
if (aObj == null)
{
return false;
}
Boid agent = aObj.GetComponent<Boid>();
Collider[] allies = Physics.OverlapSphere(agent.transform.position, agent.allyRange, agent.allyLayer);
// Check each ally for a mark
foreach (Collider ally in allies)
{
var target = ally.gameObject.GetComponent<Blackboard>().GetGameObject("Marked");
if (target != null && (target.transform.position - agent.transform.position).magnitude < agent.enemyRange * 1.4f)
{
this.bb.PutGameObject("Marked", target);
return true;
}
}
this.bb.PutGameObject("Marked", null);
return false;
}
}
|
using System;
namespace PracticaPokemon
{
public enum Gender {
MALE,
FEMALE
}
class PokemonInParty : Pokemon
{
Gender gender;
public PokemonInParty(string name, int id, Gender gender) : base( name, id) {
System.Console.WriteLine("A new pokemon was added to the party");
this.gender = gender;
}
public PokemonInParty(Pokemon pokemon, Gender gender) : base(pokemon.name, pokemon.id) {
this.gender = gender;
}
//Sobreescribir el método ToString, para que los PokemonInParty se impriman correctamente
public override string ToString() {
//Pikachu - MALE
return $"{this.name} - {this.gender}";
}
}
} |
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Business.Abstract;
using Entities.Concrete;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerCreditCardController : ControllerBase
{
private ICustomerCreditCardService _customerCreditCardService;
public CustomerCreditCardController(ICustomerCreditCardService customerCreditCardService)
{
_customerCreditCardService = customerCreditCardService;
}
[HttpGet("getall")]
public async Task<IActionResult> GetAll()
{
var result = await _customerCreditCardService.GetAll();
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpGet("getbycustomerid")]
public async Task<IActionResult> GetByCustomerId(int customerId)
{
var result = await _customerCreditCardService.GetByCustomerId(customerId);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpGet("getdetailsbycustomerid")]
public async Task<IActionResult> GetDetailsByCustomerId(int customerId)
{
var result = await _customerCreditCardService.GetDetailsByCustomerId(customerId);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpPost("add")]
public async Task<IActionResult> Add(CustomerCreditCard customerCreditCard)
{
var result = await _customerCreditCardService.Add(customerCreditCard);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpPost("delete")]
public async Task<IActionResult> Delete(CustomerCreditCard customerCreditCard)
{
var result = await _customerCreditCardService.Delete(customerCreditCard);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
[HttpPost("update")]
public async Task<IActionResult> Update(CustomerCreditCard customerCreditCard)
{
var result = await _customerCreditCardService.Update(customerCreditCard);
if (result.Success)
{
return Ok(result);
}
return BadRequest(result);
}
}
}
|
using System;
using A2.Lib;
using Xunit;
using System.Linq;
namespace A2.Test
{
public class CartManagementTest
{
[Theory(DisplayName = "Input order-product correct(no promotion), system calcualte correct")]
[InlineData("iPhone XS", 40000.00)]
[InlineData("Stone", 0.09)]
public void CartManagementCalculate_NoPromotion_Correct(string name, double price)
{
var cartManagement = new CartManagement();
var orderUnit = 3;
cartManagement.OrderProduct(new OrderProduct
{
Name = name,
PricePerUnit = price,
Unit = orderUnit
});
Assert.Single(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = price * orderUnit;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.Products.FirstOrDefault().TotalPrice);
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = 0;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = price * orderUnit;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Theory(DisplayName = "Input order-product correct(promotion 1 time), system calcualte correct")]
[InlineData("iPhone XS", 40000.00)]
[InlineData("Stone", 0.09)]
public void CartManagementCalculate_Promotion1Time_Correct(string name, double price)
{
var cartManagement = new CartManagement();
var orderUnit = 4;
cartManagement.OrderProduct(new OrderProduct
{
Name = name,
PricePerUnit = price,
Unit = orderUnit
});
Assert.Single(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = price * orderUnit;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.Products.FirstOrDefault().TotalPrice);
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = price;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = price * (orderUnit - 1);
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Theory(DisplayName = "Input order-product correct(promotion 2 times), system calcualte correct")]
[InlineData("iPhone XS", 40000.00)]
[InlineData("Stone", 0.09)]
public void CartManagementCalculate_Promotion2Times_Correct(string name, double price)
{
var cartManagement = new CartManagement();
var orderUnit = 8;
cartManagement.OrderProduct(new OrderProduct
{
Name = name,
PricePerUnit = price,
Unit = orderUnit
});
Assert.Single(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = price * orderUnit;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.Products.FirstOrDefault().TotalPrice);
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = price * (orderUnit / 4);
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = expectedTotalPriceBeforeDiscount - expectedDiscount;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Fact(DisplayName = "Input mutiple order-product correct(no promotion), system calcualte correct")]
public void CartManagementCalculate_MutipleTimes_NoPromotion_Correct()
{
var cartManagement = new CartManagement();
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 3
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "Stone",
PricePerUnit = 0.09,
Unit = 3
});
Assert.NotEmpty(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = 120000.27;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = 0;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = 120000.27;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Fact(DisplayName = "Input mutiple order-product correct(promotion 1 time), system calcualte correct")]
public void CartManagementCalculate_MutipleTimes_Promotion1Time_Correct()
{
var cartManagement = new CartManagement();
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 4
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "Stone",
PricePerUnit = 1,
Unit = 3
});
Assert.NotEmpty(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = 160003;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = 40000;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = 120003;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Fact(DisplayName = "Input mutiple order-product correct(promotion 2 times), system calcualte correct")]
public void CartManagementCalculate_MutipleTimes_Promotion2Time_Correct()
{
var cartManagement = new CartManagement();
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 4
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "Stone",
PricePerUnit = 1,
Unit = 3
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 4
});
Assert.NotEmpty(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = 320003;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = 80000;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = 240003;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Fact(DisplayName = "Input mutiple order-product correct(promotion 1 time by 4 orders), system calcualte correct")]
public void CartManagementCalculate_MutipleTimes_Promotion1TimeBy4Order_Correct()
{
var cartManagement = new CartManagement();
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 1
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 1
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 1
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "Stone",
PricePerUnit = 1,
Unit = 3
});
cartManagement.OrderProduct(new OrderProduct
{
Name = "iPhone XS",
PricePerUnit = 40000.00,
Unit = 1
});
Assert.NotEmpty(cartManagement.CartInfo.Products);
var expectedTotalPriceBeforeDiscount = 160003;
Assert.Equal(expectedTotalPriceBeforeDiscount, cartManagement.CartInfo.TotalPriceBeforeDiscount);
var expectedDiscount = 40000;
Assert.Equal(expectedDiscount, cartManagement.CartInfo.Discount);
var expectedTotalPrice = 120003;
Assert.Equal(expectedTotalPrice, cartManagement.CartInfo.TotalPrice);
}
[Theory(DisplayName = "Input order-product incorrect, system calcualte correct")]
[InlineData("", 40000.00)]
[InlineData(null, 40000.00)]
[InlineData("iPhone XS", 0)]
[InlineData("iPhone XS", -1)]
public void CartManagementCalculate_Incorrect(string name, double price)
{
var cartManagement = new CartManagement();
var orderUnit = 3;
cartManagement.OrderProduct(new OrderProduct
{
Name = name,
PricePerUnit = price,
Unit = orderUnit
});
var expectedZeroValue = 0;
Assert.Empty(cartManagement.CartInfo.Products);
Assert.Equal(expectedZeroValue, cartManagement.CartInfo.TotalPriceBeforeDiscount);
Assert.Equal(expectedZeroValue, cartManagement.CartInfo.Discount);
Assert.Equal(expectedZeroValue, cartManagement.CartInfo.TotalPrice);
}
}
}
|
using SIGA.Models.ViewModels;
using SIGA_Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SIGA.Controllers.Api
{
public class CursoSearchController : ApiController
{
// GET: api/CursoInfo
public List<CursoDTO> Get(string search)
{
List<CursoDTO> cursoList = new List<CursoDTO>();
if (search == null) search = "";
try
{
using(SIGAEntities db = new SIGAEntities())
{
cursoList = db.Curso.Where(c => c.CurName.Contains(search) || c.CurName == "")
.Select(c => new CursoDTO
{
CurId = c.CurId,
CurName = c.CurName,
CurNumHoras = (int)c.CurNumHoras,
CurPrecio = c.CurPrecio
}).ToList();
}
if (cursoList.Count() == 0)
{
List<CursoDTO> notFound = new List<CursoDTO>();
var cl = new CursoDTO { CurId = 0, CurName = "", CurNumHoras = 0, CurPrecio = (decimal)0.00 };
notFound.Add(cl);
return notFound;
}
return cursoList;
}
catch (Exception ex)
{
string message = "An error ocurred while getting employee list: " + ex;
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, message));
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
public float m_firerate;
public float m_health;
public TowerProjectile m_projectile;
protected bool m_isShooting = false;
protected float m_nextFire = 0;
protected GameObject m_latestTarget;
// Use this for initialization
void Start () {
}
void OnTriggerEnter(Collider other)
{
Collider collider = other.GetComponent<Collider>();
if (collider && collider.tag == "Minion" && other.GetComponent<Team>().m_Team != GetComponent<Team>().m_Team && m_isShooting == false)
{
Shoot(other.gameObject);
}
}
void OnTriggerStay(Collider other)
{
Collider collider = other.GetComponent<Collider>();
Team my_team = GetComponent<Team>();
if (collider == null)
{
return;
}
// Making it separated, so towers may shoot anything
if (m_latestTarget != null)
{
Minion targetMinion = m_latestTarget.GetComponent<Minion>();
if (targetMinion && !targetMinion.IsDead())
Shoot(m_latestTarget.gameObject);
}
if (collider.tag == "Minion" && collider.GetComponent<Team>().m_Team != my_team.m_Team && m_isShooting == false)
{
Shoot(other.gameObject);
}
}
void OnTriggerExit(Collider other)
{
Collider collider = other.GetComponent<Collider>();
if (collider == null)
{
return;
}
if (collider.gameObject == m_latestTarget)
{
m_latestTarget = null;
}
}
// Update is called once per frame
void Update ()
{
if (Time.time >= m_nextFire)
{
m_isShooting = false;
}
}
void Shoot(GameObject target)
{
if (target == null || target.GetComponent<Minion>().IsDead())
return;
if (m_isShooting == false)
{
m_isShooting = true;
m_nextFire = Time.time + m_firerate;
Vector3 projectile_position = transform.FindChild("SRUAP_OrderTurret1_Idle1").FindChild("Buffbone_Glb_Channel_Loc").position;
TowerProjectile projectile = (TowerProjectile)Instantiate(m_projectile, projectile_position, Quaternion.identity);
projectile.transform.forward = target.transform.position - projectile.transform.position;
projectile.SetTarget(target);
m_latestTarget = target;
FindObjectOfType<Camera>().GetComponent<SoundManager>().PlaySound("tower_shot_1");
//Debug.Log("Spawning a projectile, target: '" + target.name + "'");
}
}
public void UpdateHealth(float variation)
{
m_health += variation;
if (m_health <= 0)
{
Destroy(gameObject);
}
}
public bool IsDead()
{
return (m_health <= 0.0f);
}
}
|
using D_API.Lib;
using DiegoG.Utilities.Settings;
using System;
using System.Threading.Tasks;
using static System.Console;
using static D_API.Test.Helper;
using D_API.Lib.Exceptions;
using DiegoG.Utilities;
using Serilog;
namespace D_API.Test
{
class Program
{
public static D_APIClient Client { get; private set; }
public static async Task Main()
{
Settings<TestSettings>.Initialize(".config", "settings");
Client = new(Settings<TestSettings>.Current.ClientCredentials ?? throw new NullReferenceException("Client Credentials cannot be null"),
Settings<TestSettings>.Current.BaseAddress ?? "https://localhost:44379/", true);
Log.Logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Console().CreateLogger();
WriteLine("Press enter to start the tests");
ReadLine();
await TestUserData();
WriteLine("Finished tests, press any key to continue...");
ReadKey();
}
public static async Task TestUserData()
{
Start:;
WriteLine("Press enter to start TestUserData");
ReadLine();
try
{
WriteLine("Entering TestUserData");
WriteLine($"First Check: {await Client.UserData.CheckAccess("asd")}");
WriteLine($"Upload: {await Client.UserData.Upload("asd", new byte[] { 0, 1, 2, 3, 4, 5 }, true)}");
WriteLine($"Second Check: {await Client.UserData.CheckAccess("asd")}");
WriteLine($"Download: {string.Join(',', await Client.UserData.Download("asd"))}");
WriteLine($"Transfer Report: {await Client.UserData.GetTransferReport()}");
WriteLine("TestUserData succesful");
}
catch(Exception e)
{
WriteLine($"Failed Test with {e}");
goto Start;
}
}
}
} |
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using Document = System.Xml.XmlDocument;
using Element = System.Xml.XmlElement;
using Node = System.Xml.XmlNode;
using OperationFailureException = System.Exception;
namespace DataAccessLayer.basis
{
/// <summary>
/// OracleModalUtility 的摘要描述。
/// </summary>
public class OracleModalUtility
{
private static OracleModalUtility modalUtil = new OracleModalUtility();
private OracleModalUtility()
{
//
// TODO: 在此加入建構函式的程式碼
//
}
public static string GetFieldStringValue(object obj)
{
return (obj!=DBNull.Value)?(string)obj:null;
}
public static string GetFieldDateValue(object obj)
{
return (obj!=DBNull.Value)?((System.DateTime)obj).ToShortDateString():null;
}
public static string GetFieldNumericStringValue(object obj)
{
return (obj!=DBNull.Value)?System.Convert.ToString(obj):null;
}
public static OracleCommand InvokeStoredProcedure(string spName,OracleConnection conn)
{
OracleCommand sqlCmd = new OracleCommand(spName,conn);
sqlCmd.CommandType = CommandType.StoredProcedure;
OracleCommandBuilder.DeriveParameters(sqlCmd);
sqlCmd.CommandTimeout = 86400;
return sqlCmd;
}
public static OracleCommand InvokeStoredProcedure(string spName,OracleConnection conn,object uid)
{
OracleCommand sqlCmd = InvokeStoredProcedure(spName,conn);
if (sqlCmd.Parameters.Contains("UID"))
{
sqlCmd.Parameters["UID"].Value = uid;
}
return sqlCmd;
}
public static OracleCommand InvokeStoredProcedure(string spName,OracleConnection conn,string orderBy)
{
OracleCommand sqlCmd = InvokeStoredProcedure(spName,conn);
if(sqlCmd.Parameters.Contains("OrderBy") && orderBy!=null)
sqlCmd.Parameters["OrderBy"].Value = orderBy;
return sqlCmd;
}
public static void AssignCommandParameter(OracleCommand sqlCmd,DataRow row)
{
OracleParameterCollection cmdParams = sqlCmd.Parameters;
DataColumnCollection columns = row.Table.Columns;
string paramName;
for(int i=0;i<columns.Count;i++)
{
paramName = columns[i].ColumnName;
if(cmdParams.Contains(paramName))
{
cmdParams[paramName].Value = row[i];
}
}
}
public static void AssignCommandParameter(OracleCommand sqlCmd,object[] param)
{
OracleParameterCollection cmdParams = sqlCmd.Parameters;
for(int i=0;i<cmdParams.Count && i<param.Length;i++)
{
cmdParams[i].Value = param[i];
}
}
public static void AssignCommandParameter(OracleCommand sqlCmd,IDataReader dr)
{
OracleParameterCollection cmdParams = sqlCmd.Parameters;
int fieldCount = dr.FieldCount;
string paramName;
for(int i=0;i<fieldCount;i++)
{
paramName = dr.GetName(i);
if(cmdParams.Contains(paramName))
{
cmdParams[paramName].Value = dr[i];
}
}
}
public static DataRow ConvertToDataRow(DataTable table,System.Collections.Specialized.NameValueCollection item)
{
DataRow row = null;
if(table!=null)
{
DataColumnCollection columns = table.Columns;
row = table.NewRow();
for(int i=0;i<item.Count;i++)
{
string name = item.GetKey(i);
if(columns.Contains(name) && item[i].Length>0)
{
row[name] = Convert.ChangeType(item[i],columns[name].DataType);
}
}
}
return row;
}
public static DataRow ConvertToDataRow(DataTable table,ControlCollection controls)
{
DataRow row = null;
if(table!=null)
{
DataColumnCollection columns = table.Columns;
row = table.NewRow();
string assignValue;
foreach(Control control in controls)
{
if(control.ID!=null && columns.Contains(control.ID))
{
if(control is TextBox)
{
assignValue = ((TextBox)control).Text;
row[control.ID] = Convert.ChangeType(assignValue,columns[control.ID].DataType);
}
else if(control is HtmlInputText)
{
assignValue = ((HtmlInputText)control).Value;
row[control.ID] = Convert.ChangeType(assignValue,columns[control.ID].DataType);
}
}
}
}
return row;
}
public static XmlNode CreateResultSet(XmlDocument document,string rootName)
{
if (document == null)
{
document = new XmlDocument();
document.AppendChild(document.CreateElement("Root"));
}
if (rootName == null || rootName.Length == 0)
rootName = "ResultSet";
Element root = document.DocumentElement;
Element table = document.CreateElement("Table");
table.SetAttribute("name", rootName);
root.AppendChild(table);
return table;
}
public static XmlDocument AppendResultSet(XmlNode table,IDataReader dr)
{
XmlDocument document = table.OwnerDocument;
if(dr.Read())
{
int i;
String[] columnName = new string[dr.FieldCount];
for(i=0;i<dr.FieldCount;i++)
columnName[i] = dr.GetName(i);
do
{
Element elmt = document.CreateElement("item");
for (i = 0; i <dr.FieldCount; i++)
{
Element field = document.CreateElement(columnName[i]);
if (!dr.IsDBNull(i))
{
if(dr[i] is System.DateTime)
{
field.AppendChild(document.CreateTextNode(String.Format("{0:yyyy/M/d}",dr[i])));
}
else
{
field.AppendChild(document.CreateTextNode(dr[i].ToString().Replace('\0',' ')));
}
}
else
{
field.AppendChild(document.CreateTextNode(""));
}
elmt.AppendChild(field);
}
table.AppendChild(elmt);
} while(dr.Read());
}
return document;
}
public static XmlDocument AppendResultSet(XmlDocument document,IDataReader dr,string rootName)
{
XmlNode table = CreateResultSet(document,rootName);
AppendResultSet(table,dr);
return table.OwnerDocument;
}
public static void AssignCommandParameter(OracleCommand sqlCmd,IDictionary param)
{
OracleParameterCollection cmdParams = sqlCmd.Parameters;
string paramName;
foreach(object key in param.Keys)
{
paramName = key.ToString();
if(cmdParams.Contains(paramName))
{
cmdParams[paramName].Value = param[key];
}
}
}
public static XmlNode BuildXmlParam(string paramName,IList paramList)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("ROOT");
doc.AppendChild(root);
foreach(object param in paramList)
{
XmlElement elmt = doc.CreateElement(paramName);
elmt.AppendChild(doc.CreateTextNode(param.ToString()));
root.AppendChild(elmt);
}
return doc;
}
public static XmlNode BuildXmlParam(string paramName,DataRow[] rows,params string[] columnName)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("ROOT");
doc.AppendChild(root);
foreach(DataRow row in rows)
{
XmlElement elmt = doc.CreateElement(paramName);
foreach(string name in columnName)
{
XmlElement param = doc.CreateElement(name);
param.AppendChild(doc.CreateTextNode(row[name].ToString()));
elmt.AppendChild(param);
}
root.AppendChild(elmt);
}
return doc;
}
#region HasAtLeastOneRow
public static bool HasAtLeastOneRow(DataSet ds)
{
return (ds.Tables.Count>0 && ds.Tables[0].Rows.Count>0);
}
#endregion
}
}
|
namespace MiddleWare.Host
{
using System;
using System.Threading.Tasks;
public class TransferCommand
{
public virtual Task Execute(Transfer transfer)
{
//do some logic here.
Console.WriteLine($"Transfering {transfer.Amount}, "+
$"from: {transfer.SourceAccount} "+
$"to {transfer.DestinationAccount}");
return Task.CompletedTask;
}
}
} |
using System;
namespace Eprov_del_2
{
public class CleanCar : Car
{
public CleanCar() //konstruktor som definerar variabler för objektet
{
passengers = generator.Next(1,3);
contrabandAmount = 0;
}
}
}
|
using Newtonsoft.Json;
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Models
{
[JsonConverter(typeof(BooleanNumberStringConverter))]
public struct BooleanNumberString
{
private int? _int;
private string? _string;
private bool? _bool;
public BooleanNumberString(int value)
{
_int = value;
_string = null;
_bool = null;
}
public BooleanNumberString(string value)
{
_int = null;
_string = value;
_bool = null;
}
public BooleanNumberString(bool value)
{
_int = null;
_string = null;
_bool = value;
}
public bool IsInteger => _int.HasValue;
public int Integer
{
get => _int ?? 0;
set {
_string = null;
_int = value;
_bool = null;
}
}
public bool IsString => _string != null;
public string String
{
get => _string ?? string.Empty;
set {
_string = value;
_int = null;
_bool = null;
}
}
public bool IsBool => _bool.HasValue;
public bool Bool
{
get => _bool.HasValue && _bool.Value;
set {
_string = null;
_int = null;
_bool = value;
}
}
public static implicit operator BooleanNumberString(int value) => new BooleanNumberString(value);
public static implicit operator BooleanNumberString(string value) => new BooleanNumberString(value);
public static implicit operator BooleanNumberString(bool value) => new BooleanNumberString(value);
}
}
|
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Framework.Utils;
namespace Framework.Metadata
{
/// <summary>
/// Class to read and hold information about row sources.
/// </summary>
public class CxRowSourcesMetadata : CxMetadataCollection
{
//----------------------------------------------------------------------------
// Predefined row source IDs
public const string ID_WORKSPACE_AVAILABLE_FOR_USER = "RS_WorkspaceAvailableForUser_Lookup";
//----------------------------------------------------------------------------
protected Hashtable m_RowSources = new Hashtable(); // Row sources dictionary
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">metadata holder</param>
/// <param name="doc">XML doc to read metadata from</param>
public CxRowSourcesMetadata(CxMetadataHolder holder, XmlDocument doc):
base(holder, doc)
{
}
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">metadata holder</param>
/// <param name="docs">name of file to read assemblies metadata</param>
public CxRowSourcesMetadata(CxMetadataHolder holder, IEnumerable<XmlDocument> docs)
: base(holder, docs)
{
}
//----------------------------------------------------------------------------
/// <summary>
/// Loads metadata collection from the XML document.
/// </summary>
/// <param name="doc">document to load data from</param>
override protected void Load(XmlDocument doc)
{
base.Load(doc);
foreach (XmlElement element in doc.DocumentElement.SelectNodes("row_source"))
{
CxRowSourceMetadata rowSource = new CxRowSourceMetadata(Holder, element);
Add(rowSource);
}
LoadOverrides(doc, "row_source_override", m_RowSources);
}
//-------------------------------------------------------------------------
/// <summary>
/// Adds row source to the collection.
/// </summary>
protected void Add(CxRowSourceMetadata rowSource)
{
m_RowSources.Add(rowSource.Id, rowSource);
}
//----------------------------------------------------------------------------
/// <summary>
/// Loads the custom metadata from the given dictionary of XML documents sorted by
/// attribute usage IDs.
/// </summary>
/// <param name="documents">documents containing the custom metadata</param>
public void LoadCustomMetadata(IDictionary<string, XmlDocument> documents)
{
foreach (KeyValuePair<string, XmlDocument> pair in documents)
{
CxRowSourceMetadata rowSourceMetadata = Find(pair.Key);
if (rowSourceMetadata != null)
{
foreach (XmlElement element in pair.Value.DocumentElement.SelectNodes("row_source_custom"))
{
rowSourceMetadata.LoadCustomMetadata(element);
}
}
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Seeks for the row source with the given id.
/// </summary>
/// <returns>the row source if found, null otherwise</returns>
public CxRowSourceMetadata Find(string id)
{
id = CxText.ToUpper(id);
CxRowSourceMetadata rowSource = (CxRowSourceMetadata) m_RowSources[id];
if (rowSource == null)
{
// Try to create predefined row source.
if (id == ID_WORKSPACE_AVAILABLE_FOR_USER.ToUpper())
{
rowSource = new CxWorkspaceAvailableForUserRowSourceMetadata(Holder);
m_RowSources[id] = rowSource;
}
}
return rowSource;
}
//-------------------------------------------------------------------------
/// <summary>
/// Row source with the given ID.
/// </summary>
public CxRowSourceMetadata this[string id]
{
get
{
CxRowSourceMetadata rowSource = Find(id);
if (rowSource == null)
{
// Row source is not found.
throw new ExMetadataException(string.Format("Row source with ID=\"{0}\" not defined", id));
}
// Row source is found.
return rowSource;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Row source dictionary.
/// </summary>
public Hashtable RowSources
{
get { return m_RowSources; }
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns default name for the metadata XML file.
/// </summary>
override protected string XmlFileName
{ get { return "RowSources.xml"; } }
//-------------------------------------------------------------------------
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class UbicationFeatureUbication
{
[Key]
public int UbicationFeatureUbicationId { get; set; }
public int UbicationFeatureId { get; set; }
public int UbicationId { get; set; }
public virtual UbicationFeature UbicationFeature { get; set; }
public virtual Ubication Ubication { get; set; }
}
} |
using System;
namespace Enrollment.XPlatform.Directives
{
public interface IValidateIfManager : IDisposable
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ContosoUniversity.Models
{
public class Student
{
public int ID { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Last Name")] // changing the way the column is displayed in the app
public string LastName { get; set; }
[Required] // making the field required in the form
[StringLength(50, ErrorMessage = "First Name cannot be longer than 50 characters")]
[Column("FirstName")] // changing the column name in the class && the db
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public DateTime EnrollmentDate { get; set; }
[Display(Name = "Full Name")]
public string FullName // adding a whole new computed column (note) only a get
{
get // only a get
{
return LastName + ", " + FirstMidName;
}
} // there is no setter because this column is not being added to the database
public ICollection<Enrollment> Enrollments { get; set; }
}
}
|
using System;
using Entity;
namespace Business
{
public class BangGiaBO
{
public static ListBangGiaEntity SelectAll()
{
return DataAccess.BangGiaDA.SelectAll();
}
public static Int32 CheckExist(Int32 idgia, Int32 mahang, Int32 makieugiat)
{
return DataAccess.BangGiaDA.CheckExist(idgia, mahang, makieugiat);
}
public static Int32 Insert(BangGiaEntity banggia)
{
return DataAccess.BangGiaDA.Insert(banggia);
}
public static Int32 Update(BangGiaEntity banggia)
{
return DataAccess.BangGiaDA.Update(banggia);
}
public static Int32 Delete(Int32 idgia)
{
return DataAccess.BangGiaDA.Delete(idgia);
}
}
}
|
namespace EventStoreWinServiceWrapper
{
using System.Collections.Generic;
using System.Diagnostics;
internal class ServiceWrapper
{
private readonly EventStoreServiceConfiguration configuration;
private readonly List<Process> processes;
public ServiceWrapper(EventStoreServiceConfiguration configuration)
{
this.configuration = configuration;
this.processes = new List<Process>();
}
public void Start()
{
var processMapper = new ProcessMapper();
foreach (ServiceInstance instance in this.configuration.Instances)
{
var info = processMapper.GetProcessStartInfo(this.configuration.Executable, instance);
var process = Process.Start(info);
process.Exited += (sender, args) => this.Stop();
this.processes.Add(process);
}
}
public void Stop()
{
this.processes.ForEach(p =>
{
p.Refresh();
if (p.HasExited)
{
return;
}
p.Kill();
p.WaitForExit();
p.Dispose();
});
}
}
} |
internal class NevMeshAgent
{
} |
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(SaveGameManager))]
public class SaveGameManagerInspector : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
SaveGameManager saveGameManager = (SaveGameManager)target;
GUILayout.Space(10);
Color origColor = GUI.backgroundColor;
if (Application.isPlaying)
{
GUI.backgroundColor = new Color(0.64f, 0.90f, 0.52f);
if (GUILayout.Button("Serialize", GUILayout.Height(35.0f)))
{
saveGameManager.Serialize();
}
}
else
{
GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f);
if (GUILayout.Button("Serialize (Runtime Only)", GUILayout.Height(35.0f)))
{
Debug.LogWarning("Saving a game only works at runtime!");
}
}
GUI.backgroundColor = origColor;
//GUILayout.Space(5);
//if (world.Progress > 0.0f)
//{
// Rect rect = EditorGUILayout.BeginVertical();
// EditorGUI.ProgressBar(rect, world.Progress, world.ProgressText);
// GUILayout.Space(16);
// EditorGUILayout.EndVertical();
//}
}
//public override bool RequiresConstantRepaint()
//{
// return true;
//}
} |
using Mono.Cecil;
using System;
using System.Collections.Generic;
namespace AlienEngine.ASL
{
public abstract partial class ASLShader
{
internal static class GLSL
{
internal static string ToGLSL(TypeReference t)
{
var typeDef = t.Resolve();
Type type = null;
if (TypeMap.TryGetValue(typeDef.Name, out type))
return ToGLSL(type);
return typeDef.Name;
}
internal static string ToGLSL(Type t)
{
string glslName;
if (!Type.TryGetValue(t, out glslName))
throw new ASLException("ASL Error: " + t + " is currently not supported by GLSL module.");
return glslName;
}
internal static readonly Dictionary<Type, string> Type = new Dictionary<Type, string>() {
// ----------
// Primitives
// -----
{ typeof(int), "int" },
{ typeof(int[]), "int" },
{ typeof(float), "float" },
{ typeof(float[]), "float" },
{ typeof(uint), "uint" },
{ typeof(uint[]), "uint" },
{ typeof(bool), "bool" },
{ typeof(bool[]), "bool" },
{ typeof(double), "double" },
{ typeof(double[]), "double" },
{ typeof(void), "void" },
// ----------
// ----------
// Vectors
// -----
// floats
// -----
{ typeof(vec2), "vec2" },
{ typeof(vec2[]), "vec2" },
{ typeof(vec3), "vec3" },
{ typeof(vec3[]), "vec3" },
{ typeof(vec4), "vec4" },
{ typeof(vec4[]), "vec4" },
// -----
// ints
// -----
{ typeof(ivec2), "ivec2" },
{ typeof(ivec2[]), "ivec2" },
{ typeof(ivec3), "ivec3" },
{ typeof(ivec3[]), "ivec3" },
{ typeof(ivec4), "ivec4" },
{ typeof(ivec4[]), "ivec4" },
// -----
// uints
// -----
{ typeof(uvec2), "uvec2" },
{ typeof(uvec2[]), "uvec2" },
{ typeof(uvec3), "uvec3" },
{ typeof(uvec3[]), "uvec3" },
{ typeof(uvec4), "uvec4" },
{ typeof(uvec4[]), "uvec4" },
// -----
// booleans
// -----
{ typeof(bvec2), "bvec2" },
{ typeof(bvec2[]), "bvec2" },
{ typeof(bvec3), "bvec3" },
{ typeof(bvec3[]), "bvec3" },
{ typeof(bvec4), "bvec4" },
{ typeof(bvec4[]), "bvec4" },
// ----------
// ----------
// Matrices
// -----
// floats
// -----
{ typeof(mat2), "mat2" },
{ typeof(mat2[]), "mat2" },
{ typeof(mat3), "mat3" },
{ typeof(mat3[]), "mat3" },
{ typeof(mat4), "mat4" },
{ typeof(mat4[]), "mat4" },
{ typeof(mat2x3), "mat2x3" },
{ typeof(mat2x3[]), "mat2x3" },
{ typeof(mat2x4), "mat2x4" },
{ typeof(mat2x4[]), "mat2x4" },
{ typeof(mat3x2), "mat3x2" },
{ typeof(mat3x2[]), "mat3x2" },
{ typeof(mat3x4), "mat3x4" },
{ typeof(mat3x4[]), "mat3x4" },
{ typeof(mat4x2), "mat4x2" },
{ typeof(mat4x2[]), "mat4x2" },
{ typeof(mat4x3), "mat4x3" },
{ typeof(mat4x3[]), "mat4x3" }
};
internal static readonly Dictionary<Type, string> Qualifiers = new Dictionary<Type, string>() {
{ typeof(InAttribute), "in" },
{ typeof(OutAttribute), "out" },
{ typeof(UniformAttribute), "uniform" }
};
internal static readonly Dictionary<string, Type> TypeMap = new Dictionary<string, Type> {
// ----------
// Primitives
// -----
{ typeof(int).Name, typeof(int) },
{ typeof(int[]).Name, typeof(int) },
{ typeof(float).Name, typeof(float) },
{ typeof(float[]).Name, typeof(float) },
{ typeof(uint).Name, typeof(uint) },
{ typeof(uint[]).Name, typeof(uint) },
{ typeof(bool).Name, typeof(bool) },
{ typeof(bool[]).Name, typeof(bool) },
{ typeof(double).Name, typeof(double) },
{ typeof(double[]).Name, typeof(double) },
{ typeof(void).Name, typeof(void) },
// ----------
// ----------
// Vectors
// -----
// floats
// -----
{ typeof(vec2).Name, typeof(vec2) },
{ typeof(vec2[]).Name, typeof(vec2) },
{ typeof(vec3).Name, typeof(vec3) },
{ typeof(vec3[]).Name, typeof(vec3) },
{ typeof(vec4).Name, typeof(vec4) },
{ typeof(vec4[]).Name, typeof(vec4) },
// -----
// ints
// -----
{ typeof(ivec2).Name, typeof(ivec2) },
{ typeof(ivec2[]).Name, typeof(ivec2) },
{ typeof(ivec3).Name, typeof(ivec3) },
{ typeof(ivec3[]).Name, typeof(ivec3) },
{ typeof(ivec4).Name, typeof(ivec4) },
{ typeof(ivec4[]).Name, typeof(ivec4) },
// -----
// uints
// -----
{ typeof(uvec2).Name, typeof(uvec2) },
{ typeof(uvec2[]).Name, typeof(uvec2) },
{ typeof(uvec3).Name, typeof(uvec3) },
{ typeof(uvec3[]).Name, typeof(uvec3) },
{ typeof(uvec4).Name, typeof(uvec4) },
{ typeof(uvec4[]).Name, typeof(uvec4) },
// -----
// booleans
// -----
{ typeof(bvec2).Name, typeof(bvec2) },
{ typeof(bvec2[]).Name, typeof(bvec2) },
{ typeof(bvec3).Name, typeof(bvec3) },
{ typeof(bvec3[]).Name, typeof(bvec3) },
{ typeof(bvec4).Name, typeof(bvec4) },
{ typeof(bvec4[]).Name, typeof(bvec4) },
// ----------
// ----------
// Matrices
// -----
// floats
// -----
{ typeof(mat2).Name, typeof(mat2) },
{ typeof(mat2[]).Name, typeof(mat2) },
{ typeof(mat3).Name, typeof(mat3) },
{ typeof(mat3[]).Name, typeof(mat3) },
{ typeof(mat4).Name, typeof(mat4) },
{ typeof(mat4[]).Name, typeof(mat4) },
{ typeof(mat2x3).Name, typeof(mat2x3) },
{ typeof(mat2x3[]).Name, typeof(mat2x3) },
{ typeof(mat2x4).Name, typeof(mat2x4) },
{ typeof(mat2x4[]).Name, typeof(mat2x4) },
{ typeof(mat3x2).Name, typeof(mat3x2) },
{ typeof(mat3x2[]).Name, typeof(mat3x2) },
{ typeof(mat3x4).Name, typeof(mat3x4) },
{ typeof(mat3x4[]).Name, typeof(mat3x4) },
{ typeof(mat4x2).Name, typeof(mat4x2) },
{ typeof(mat4x2[]).Name, typeof(mat4x2) },
{ typeof(mat4x3).Name, typeof(mat4x3) },
{ typeof(mat4x3[]).Name, typeof(mat4x3) }
};
internal static readonly Dictionary<Type, Type> ArrayMap = new Dictionary<Type, Type> {
// ----------
// Primitives
// -----
{ typeof(int), typeof(int[]) },
{ typeof(float), typeof(float[]) },
{ typeof(uint), typeof(uint[]) },
{ typeof(bool), typeof(bool[]) },
{ typeof(double), typeof(double[]) },
// ----------
// ----------
// Vectors
// -----
// floats
// -----
{ typeof(vec2), typeof(vec2[]) },
{ typeof(vec3), typeof(vec3[]) },
{ typeof(vec4), typeof(vec4[]) },
// -----
// ints
// -----
{ typeof(ivec2), typeof(ivec2[]) },
{ typeof(ivec3), typeof(ivec3[]) },
{ typeof(ivec4), typeof(ivec4[]) },
// -----
// uints
// -----
{ typeof(uvec2), typeof(uvec2[]) },
{ typeof(uvec3), typeof(uvec3[]) },
{ typeof(uvec4), typeof(uvec4[]) },
// -----
// booleans
// -----
{ typeof(bvec2), typeof(bvec2[]) },
{ typeof(bvec3), typeof(bvec3[]) },
{ typeof(bvec4), typeof(bvec4[]) },
// ----------
// ----------
// Matrices
// -----
// floats
// -----
{ typeof(mat2), typeof(mat2[]) },
{ typeof(mat3), typeof(mat3[]) },
{ typeof(mat4), typeof(mat4[]) },
{ typeof(mat2x3), typeof(mat2x3[]) },
{ typeof(mat2x4), typeof(mat2x4[]) },
{ typeof(mat3x2), typeof(mat3x2[]) },
{ typeof(mat3x4), typeof(mat3x4[]) },
{ typeof(mat4x2), typeof(mat4x2[]) },
{ typeof(mat4x3), typeof(mat4x3[]) }
};
}
}
} |
using System.Linq;
namespace _4._Matrix_Shuffling
{
using System;
class MatrixShuffling
{
static void Main(string[] args)
{
int[] dimensions = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int rows = dimensions[0];
int cols = dimensions[1];
string[,] matrix = new string[rows, cols];
for (int row = 0; row < matrix.GetLength(0); row++)
{
string[] elements = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries);
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = elements[col];
}
}
while (true)
{
string input = Console.ReadLine();
if (input == "END")
{
break;
}
if (IsInputValid(input, matrix))
{
string[] inputLine = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
int row1 = int.Parse(inputLine[1]);
int col1 = int.Parse(inputLine[2]);
int row2 = int.Parse(inputLine[3]);
int col2 = int.Parse(inputLine[4]);
Swap(row1, col1, row2, col2, matrix);
Print(matrix);
}
else
{
Console.WriteLine("Invalid input!");
}
}
}
private static void Swap(int row1, int col1, int row2, int col2, string[,] matrix)
{
string temp = matrix[row1, col1];
matrix[row1, col1] = matrix[row2, col2];
matrix[row2, col2] = temp;
}
private static void Print(string[,] matrix)
{
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
if (col > 0)
{
Console.Write(" ");
}
Console.Write(matrix[row, col]);
}
Console.WriteLine();
}
}
private static bool IsInputValid(string input, string[,] matrix)
{
string[] inputLine = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
if (inputLine.Length != 5)
{
return false;
}
if (inputLine[0] != "swap")
{
return false;
}
bool isRow1Correct = int.TryParse(inputLine[1], out int row1);
bool isCol1Correct = int.TryParse(inputLine[2], out int col1);
bool isRow2Correct = int.TryParse(inputLine[3], out int row2);
bool isCol2Correct = int.TryParse(inputLine[4], out int col2);
if (isRow1Correct && isCol1Correct && isRow2Correct && isCol2Correct)
{
if (row1 < 0 || row1 > matrix.GetLength(0) - 1)
{
return false;
}
if (col1 < 0 || col1 > matrix.GetLength(1) - 1)
{
return false;
}
if (row2 < 0 || row2 > matrix.GetLength(0) - 1)
{
return false;
}
if (col2 < 0 || col2 > matrix.GetLength(1) - 1)
{
return false;
}
}
return true;
}
}
}
|
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_CullingGroupEvent : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent = default(CullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_index(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_index());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isVisible(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_isVisible());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_wasVisible(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_wasVisible());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_hasBecomeVisible(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_hasBecomeVisible());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_hasBecomeInvisible(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_hasBecomeInvisible());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_currentDistance(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_currentDistance());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_previousDistance(IntPtr l)
{
int result;
try
{
CullingGroupEvent cullingGroupEvent;
LuaObject.checkValueType<CullingGroupEvent>(l, 1, out cullingGroupEvent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, cullingGroupEvent.get_previousDistance());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.CullingGroupEvent");
LuaObject.addMember(l, "index", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_index), null, true);
LuaObject.addMember(l, "isVisible", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_isVisible), null, true);
LuaObject.addMember(l, "wasVisible", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_wasVisible), null, true);
LuaObject.addMember(l, "hasBecomeVisible", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_hasBecomeVisible), null, true);
LuaObject.addMember(l, "hasBecomeInvisible", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_hasBecomeInvisible), null, true);
LuaObject.addMember(l, "currentDistance", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_currentDistance), null, true);
LuaObject.addMember(l, "previousDistance", new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.get_previousDistance), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_CullingGroupEvent.constructor), typeof(CullingGroupEvent), typeof(ValueType));
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotatesky : MonoBehaviour {
public float RotationSpeed;
[ExecuteInEditMode]
void Start () {
}
void FixedUpdate () {
RenderSettings.skybox.SetFloat("_Rotation", Time.time * RotationSpeed);
}
}
|
using Security.Data;
namespace Security.Classes
{
public class ReturnedUser
{
public ApplicationUser User { get; set; }
public string token { get; set; }
}
}
|
using Application.Contract.RepositoryInterfaces;
using Application.CQRS.Handlers.Commands;
using FakeItEasy;
using Xunit;
namespace Application.Test.CQRS.Handlers
{
public class RemoveCryptoCurrencyHandlerTest
{
private readonly RemoveCryptoCurrencyHandler _testee;
private readonly ICryptoCurrencyRepository _cryptoCurrencyRepository;
public RemoveCryptoCurrencyHandlerTest()
{
_cryptoCurrencyRepository = A.Fake<ICryptoCurrencyRepository>();
_testee = new RemoveCryptoCurrencyHandler(_cryptoCurrencyRepository);
}
[Fact]
public async void Handle_ShouldCallAddNewCryptoCurrencyAsync()
{
//arrange
var command = new Application.CQRS.Commands.RemoveCryptoCurrencyCommand(1);
//act
await _testee.Handle(command, default);
//assert
A.CallTo(() => _cryptoCurrencyRepository.RemoveCryptoCurrencyAsync(command.Id, default)).MustHaveHappenedOnceExactly();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace HackerRank_HomeCode
{
public class BeautifulDays
{
public void GetNoOfBD()
{
string[] ijk = Console.ReadLine().Split(' ');
//starting day
int i = Convert.ToInt32(ijk[0]);
//ending day
int j = Convert.ToInt32(ijk[1]);
//divisible number
int k = Convert.ToInt32(ijk[2]);
int bd = 0;
for(int strt = i;strt<=j;strt++)
{
//var reversno = int.Parse(strt.ToString().Reverse().ToArray());
var revserstring = new string(strt.ToString().Reverse().ToArray());
var reversno = int.Parse(revserstring);
var d = Math.Abs(strt - reversno) % k;
if (d == 0)
bd++;
}
Console.WriteLine(bd);
}
}
}
|
using UnityEngine;
using System.Collections;
public class LightColorChange : MonoBehaviour {
private Light lt;
public Color startColor;
public Color endColor;
public float duration;
void Start () {
lt = GetComponent<Light>();
lt.color = startColor;
}
void Update () {
lt.color = Color.Lerp(startColor, endColor, Time.time / duration);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cactus : MonoBehaviour
{
[SerializeField] float damageRate = 1f;
[SerializeField] int damage = 1;
[SerializeField] float lifeTime = 30f;
[SerializeField] RandomAudioPlayer despawnPlayer;
//STATES
//used to limit number of cacti
public static int cactiCount = 0;
//Keeps track of entities touching the cactus
//Applies damage every set interval
Dictionary<CombatTarget, float> targetsInContact = new Dictionary<CombatTarget, float>();
//CACHE REFERENCES
Animator animator;
private void Awake()
{
animator = GetComponent<Animator>();
cactiCount++;
StartCoroutine(Lifetime());
}
//Add new target in contact with cactus
private void OnTriggerEnter(Collider other)
{
CombatTarget target = other.gameObject.GetComponent<CombatTarget>();
if (target == null) return;
if (!targetsInContact.ContainsKey(target))
{
targetsInContact[target] = damageRate; //Damage next update
}
}
//Remove target in contact with cactus
private void OnTriggerExit(Collider other)
{
CombatTarget target = other.gameObject.GetComponent<CombatTarget>();
if (target == null) return;
if (targetsInContact.ContainsKey(target))
{
targetsInContact.Remove(target);
}
}
private void Update()
{
CombatTarget[] targets = new CombatTarget[targetsInContact.Count];
targetsInContact.Keys.CopyTo(targets, 0);
//Prevents animation trigger being called more than once this frame
bool hasAttacked = false;
foreach (var target in targets)
{
if (target.IsDead) //Validate target
{
targetsInContact.Remove(target);
continue;
}
targetsInContact[target] += Time.deltaTime;
if (targetsInContact[target] >= damageRate) //Damage enemy again if contact is sustained for set damage rate
{
target.TakeDamage(damage, transform.position);
targetsInContact[target] = 0f;
hasAttacked = true;
}
}
if (animator == null) return;
if (hasAttacked) animator.SetTrigger("AttackTrigger");
}
//Cacti dies after limited life time is over
IEnumerator Lifetime()
{
yield return new WaitForSeconds(lifeTime);
despawnPlayer.PlayRandomAudio();
animator.SetTrigger("DeathTrigger");
Destroy(gameObject, 1f); //Delay destroy for animation
}
private void OnDestroy()
{
cactiCount--;
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System.Data;
using System.Data.SqlClient;
namespace DIDemo
{
internal class Program
{
static void Main(string[] args)
{
ServiceCollection services= new ServiceCollection();
services.AddScoped<IDbConnection>(sp =>
{
string conStr = "Data Source=.;Initial Catalog=DI_DB;Integrated Security=true";
var con = new SqlConnection(conStr);
con.Open();
return con;
});
services.AddScoped<IUserDao, UserDao>();
services.AddScoped<IUserBiz, UserBiz>();
using(ServiceProvider sp = services.BuildServiceProvider())
{
IUserBiz userBiz= sp.GetRequiredService<IUserBiz>();
bool b = userBiz.CheckLogin("sun", "YUNWEN0305");
Console.WriteLine(b);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TextAnalyse;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string path = Properties.Settings.Default.path;
string writePath = Properties.Settings.Default.writePath;
string result = Analizator.AnaliseText(FileIO.ReadFile(path));
FileIO.WriteFile(writePath, result);
Console.ReadLine();
}
}
}
|
using SharpDL.Shared;
using System;
namespace SharpDL.Graphics
{
public class TrueTypeText : ITrueTypeText
{
public string Text { get; private set; }
public IFont Font { get; private set; }
public Color Color { get; private set; }
public ITexture Texture { get; private set; }
public int OutlineSize { get { return Font.OutlineSize; } }
public bool IsWrapped { get; set; }
public int WrapLength { get; set; }
public TrueTypeText(IRenderer renderer, ISurface surface, string text, Font font, Color color, int wrapLength)
{
if (renderer == null)
{
throw new ArgumentNullException(nameof(renderer));
}
if (surface == null)
{
throw new ArgumentNullException(nameof(surface));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
if (font == null)
{
throw new ArgumentNullException(nameof(font));
}
if (wrapLength < 0)
{
throw new ArgumentOutOfRangeException(nameof(wrapLength), "Wrap length must be greater than or equal to 0.");
}
Texture = new Texture(renderer, surface);
IsWrapped = wrapLength > 0;
Text = text;
Font = font;
Color = color;
WrapLength = wrapLength;
}
public void UpdateText(string text)
{
UpdateText(text, 0);
}
public void UpdateText(string text, int wrapLength)
{
if (Texture == null)
{
throw new InvalidOperationException("Texture is null. Has it been disposed?");
}
ISurface surface = new Surface(Font, text, Color, wrapLength);
Texture.UpdateSurfaceAndTexture(surface);
Text = text;
IsWrapped = wrapLength > 0;
}
public void SetOutlineSize(int outlineSize)
{
if (Font == null)
{
throw new InvalidOperationException("Font is null.");
}
if (outlineSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outlineSize), "Outline size must be greater than or equal to 0.");
}
Font.SetOutlineSize(outlineSize);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (Texture != null)
{
Texture.Dispose();
}
if (Font != null)
{
Font.Dispose();
}
}
}
}
} |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
namespace GENIVisuals.viewClasses
{
public class StatusAnimationInfo
{
public Storyboard storyboard { get; set; }
public List<UIElement> elements { get; set; }
public StatusAnimationInfo()
{
elements = new List<UIElement>();
}
}
}
|
namespace HacktoberfestProject.Web.Models.DTOs
{
public class Contributor
{
public string Name { get; set; }
public string ImageUrl { get; set; }
public string ProfileUrl { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scripts
{
class ShapeComponent
{
Layer Layer;
List<Vector3> Vertices;
public int startIndex;
public int[] HolesIndexes;
int VerticesNum { get; set; }
public (int, int, int, int) BoundingBox { get; private set; }
public (int, int) Center { get; private set; }
List<ShapeComponent> Subcomponents;
List<(int, int)> Border;
List<List<(int, int)>> Holes;
Drawable Drawable;
public readonly double MaxLineError = 5d;
bool Debug = true;
int DebugId;
static System.Random r = new System.Random();
public ShapeComponent(bool[,] bitMap, Layer layer)
{
Layer = layer;
Vertices = layer.Vertices;
Border = new List<(int, int)>();
Holes = new List<List<(int, int)>>();
Subcomponents = new List<ShapeComponent>();
GameObject o = GameObject.Find("DrawingSurface");
Drawable = o.GetComponent<Drawable>();
DebugId = r.Next(0, 100);
GenerateComponent(bitMap);
}
private void GenerateComponent(bool[,] componentMap)
{
//GetBorder(component, layer);
var edges = GetOrderedEdges(componentMap);
if (edges == null)
{
throw new Exception("Ayy lmao");
}
GetBorderAndHoles(edges);
GenerateComponentProperties();
VerticesNum = Border.Count;
foreach (var hole in Holes)
{
VerticesNum += hole.Count;
}
if (Debug)
DebugShowPoints();
}
private List<(int, int)> GetOrderedEdges(bool[,] component)
{
List<(int, int)> pointList = new List<(int, int)>();
bool[,] enlargedBitmap = EnlargeComponent(component);
for (int sy = 0; sy < enlargedBitmap.GetLength(1); sy++)
{
for (int sx = 0; sx < enlargedBitmap.GetLength(0); sx++)
{
if (enlargedBitmap[sx, sy] && IsOnEdge(enlargedBitmap, sx, sy) && !pointList.Contains((sx / 3, sy / 3))) //!!! Later needed to test connectedness (holes are in same list) | On it. | Still on it.
{
int x = sx, y = sy;
int startX = x;
int startY = y;
pointList.Add((x / 3, y / 3));
(x, y) = TakeStepClockwise(enlargedBitmap, x, y);
int loop = 0;
while ((x != startX || y != startY) && loop++ < 100000)
{
if (pointList.Last() != (x / 3, y / 3))
{
pointList.Add((x / 3, y / 3));
}
(x, y) = TakeStepClockwise(enlargedBitmap, x, y);
if (pointList.Count > component.Length)
{
return null;
}
}
}
}
}
pointList.RemoveAt(pointList.Count - 1);
return pointList;
}
(int, int) TakeStepClockwise(bool[,] component, int x, int y)
{
//*
if (x + 1 < component.GetLength(0) && y + 1 < component.GetLength(1) && !component[x + 1, y] && component[x + 1, y + 1])
{
return (x + 1, y + 1);
}
else if (x + 1 < component.GetLength(0) && y + 1 < component.GetLength(1) && !component[x + 1, y + 1] && component[x, y + 1])
{
return (x, y + 1);
}
else if (x - 1 >= 0 && y + 1 < component.GetLength(1) && !component[x, y + 1] && component[x - 1, y + 1])
{
return (x - 1, y + 1);
}
else if (x - 1 >= 0 && y + 1 < component.GetLength(1) && !component[x - 1, y + 1] && component[x - 1, y])
{
return (x - 1, y);
}
else if (x - 1 >= 0 && y - 1 >= 0 && !component[x - 1, y] && component[x - 1, y - 1])
{
return (x - 1, y - 1);
}
else if (x - 1 >= 0 && y - 1 >= 0 && !component[x - 1, y - 1] && component[x, y - 1])
{
return (x, y - 1);
}
else if (x + 1 < component.GetLength(0) && y - 1 >= 0 && !component[x, y - 1] && component[x + 1, y - 1])
{
return (x + 1, y - 1);
}
else if (x + 1 < component.GetLength(0) && y - 1 >= 0 && !component[x + 1, y - 1] && component[x + 1, y])
{
return (x + 1, y);
}
//*/
throw new Exception("Couldn't find next vertex.");
}
private void GetBorderAndHoles(List<(int, int)> edges)
{
var currentEdge = Border;
var pointsArr = edges.ToArray();
int curr = 0;
currentEdge.Add(pointsArr[curr]);
for (int i = 2; i < pointsArr.Length; i++)
{
if (AreNeighbors(pointsArr[i - 1], pointsArr[i]))
{
double lineError = GetAccuracy(pointsArr, curr, i);
if (lineError > MaxLineError)
{
currentEdge.Add(edges[i - 1]);
curr = i - 1;
}
}
else
{
curr = i;
if (currentEdge.Count < 3)
{
Holes.RemoveAt(Holes.Count - 1);
}
var hole = new List<(int, int)>();
Holes.Add(hole);
currentEdge = hole;
}
}
if (currentEdge.Count < 3)
{
if (Holes.Count > 0)
{
Holes.RemoveAt(Holes.Count - 1);
}
}
}
private double GetAccuracy((int, int)[] pointsArr, int curr, int last)
{
if (curr + 1 == last)
{
return 1000d;
}
double sum = 0;
double x1 = pointsArr[curr].Item1;
double x2 = pointsArr[last].Item1;
double y1 = pointsArr[curr].Item2;
double y2 = pointsArr[last].Item2;
for (int i = curr + 1; i < last; i++)
{
sum += Math.Abs((x2 - x1) * ((double)pointsArr[i].Item2 - y2) + (y1 - y2) * ((double)pointsArr[i].Item1 - x2)); ;
}
return sum;
}
bool IsOnEdge(bool[,] component, int x, int y)
{
int falses = 0;
for (int dx = -1; dx <= 1; dx++)
{
for (int dy = -1; dy <= 1; dy++)
{
if (x + dx >= 0 && y + dy >= 0 && x + dx < component.GetLength(0) && y + dy < component.GetLength(1) && !component[x + dx, y + dy])
{
falses++;
if (falses >= 2)
{
return true;
}
}
}
}
return false;
}
bool[,] EnlargeComponent(bool[,] component)
{
bool[,] toReturn = new bool[component.GetLength(0) * 3, component.GetLength(1) * 3];
for (int y = 0; y < toReturn.GetLength(1); y++)
{
for (int x = 0; x < toReturn.GetLength(0); x++)
{
toReturn[x, y] = component[x / 3, y / 3];
}
}
return toReturn;
}
bool AreNeighbors((int, int) first, (int, int) second)
{
if (Math.Abs(first.Item1 - second.Item1) <= 1 && Math.Abs(first.Item2 - second.Item2) <= 1)
{
return true;
}
return false;
}
private void GenerateComponentProperties()
{
int lowestX = int.MaxValue, highestX = 0, lowestY = int.MaxValue, highestY = 0;
foreach (var point in Border)
{
lowestX = point.Item1 < lowestX ? point.Item1 : lowestX;
highestX = point.Item1 > highestX ? point.Item1 : highestX;
lowestY = point.Item2 < lowestY ? point.Item2 : lowestY;
highestY = point.Item2 > highestY ? point.Item2 : highestY;
}
BoundingBox = (lowestX, highestX, lowestY, highestY);
Center = (lowestX + (highestX - lowestX) / 2, lowestY + (highestY - lowestY) / 2);
}
public void DebugShowPoints()
{
Texture2D[] textures = Drawable.GetTextures();
foreach (var point in Border)
{
textures[0].SetPixel(point.Item1, point.Item2, Color.white);
}
foreach (var hole in Holes)
{
foreach (var point in hole)
{
textures[0].SetPixel(point.Item1, point.Item2, new Color(1, 1, 0));
}
}
textures[0].Apply();
}
public void AddSubcomponent(ShapeComponent NewComponent)
{
foreach (var component in Subcomponents)
{
if (NewComponent == component)
{
return;
}
}
foreach (var subcomponent in Subcomponents)
{
if (subcomponent.Contains(NewComponent))
{
subcomponent.AddSubcomponent(NewComponent);
VerticesNum += NewComponent.VerticesNum;
return;
}
if (NewComponent.Contains(subcomponent))
{
Subcomponents.Remove(subcomponent);
NewComponent.AddSubcomponent(subcomponent);
}
}
VerticesNum += NewComponent.VerticesNum;
Subcomponents.Add(NewComponent);
}
public bool Contains(ShapeComponent c2)
{
if (c2 == this)
{
return false;
}
(int c1x1, int c1x2, int c1y1, int c1y2) = BoundingBox;
(int c2x1, int c2x2, int c2y1, int c2y2) = c2.BoundingBox;
if (c1x1 < c2x1 && c2x2 < c1x2 && c1y1 < c2y1 && c2y2 < c1y2)
{
return true;
}
return false;
}
public void AddVertices(List<Vector3> vertices, double zValue)
{
HolesIndexes = new int[Holes.Count];
startIndex = vertices.Count;
foreach (var pixel in Border)
{
vertices.Add(new Vector3(pixel.Item1, pixel.Item2, (float)zValue));
}
if (Holes.Count > 0)
{
HolesIndexes[0] = startIndex + Border.Count;
int currHoleIndex = 1;
foreach (var hole in Holes)
{
foreach (var pixel in hole)
{
vertices.Add(new Vector3(pixel.Item1, pixel.Item2, (float)zValue));
}
if (currHoleIndex < Holes.Count)
{
HolesIndexes[currHoleIndex] = startIndex + Border.Count + Holes[currHoleIndex - 1].Count;
currHoleIndex++;
}
}
}
foreach (var component in Subcomponents)
{
component.AddVertices(vertices, zValue);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Planning
{
class AdvancedProjectionPublicPredicatesAchieverDependenciesSelector : AAdvancedProjectionScoreBasedDependeciesSelector
{
protected override void CalculatePreconditionAmountDictionary(List<Action> possibleActions, Dictionary<Predicate, int> preconditionAmount)
{
List<Predicate> privateEffects = new List<Predicate>(preconditionAmount.Keys);
foreach(Predicate predicate in privateEffects)
{
HashSet<Predicate> publicEffectsThisPredicateCanReveal = new HashSet<Predicate>();
foreach (Action action in possibleActions)
{
if (action.HashPrecondition.Contains(predicate))
{
foreach(Predicate effect in action.HashEffects)
{
if (!effect.Name.Contains(Domain.ARTIFICIAL_PREDICATE)) //public effect
{
if (!publicEffectsThisPredicateCanReveal.Contains(effect))
{
publicEffectsThisPredicateCanReveal.Add(effect);
}
}
}
}
}
preconditionAmount[predicate] = publicEffectsThisPredicateCanReveal.Count;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LogiCon
{
public class Select
{
public short Value { get; set; }
public string Text { get; set; }
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadDataController : MonoBehaviour {
bool loaded;
public int partLoaded;
public Slider slider;
void Start () {
StartCoroutine (loadData());
}
public int numberToLoad;
// Update is called once per frame
IEnumerator loadData () {
if (!loaded) {
for (int x = 0; x < numberToLoad; x++) {
string path = "Audio" + "/First/" + (x + 1);
Debug.Log (path);
ResourceRequest resourceRequest = Resources.LoadAsync<AudioClip> (path);
while (!resourceRequest.isDone) {
Debug.Log ("still loading");
yield return 0;
}
partLoaded++;
slider.value = partLoaded / numberToLoad;
Debug.Log ("part got loaded");
}
Debug.Log ("LOADED!");
loaded = true;
} else {
Debug.Log ("already loaded");
yield return null;
}
}
}
|
using System;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Tool
{
public class Serializer
{
/// <summary>
/// 序列化类到xml文档
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="obj">类的对象</param>
/// <param name="filePath">xml文档路径(包含文件名)</param>
/// <returns>成功:true,失败:false</returns>
public static bool CreateXML<T>(T obj, string filePath)
{
XmlWriter writer = null; //声明一个xml编写器
XmlWriterSettings writerSetting = new XmlWriterSettings //声明编写器设置
{
Indent = true,//定义xml格式,自动创建新的行
Encoding = UTF8Encoding.UTF8,//编码格式
};
try
{
string xmlDirectory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(xmlDirectory))
{
Directory.CreateDirectory(xmlDirectory);
}
//创建一个保存数据到xml文档的流
writer = XmlWriter.Create(filePath, writerSetting);
}
catch (Exception ex)
{
//_logServ.Error(string.Format("创建xml文档失败:{0}", ex.Message));
return false;
}
XmlSerializer xser = new XmlSerializer(typeof(T)); //实例化序列化对象
try
{
xser.Serialize(writer, obj); //序列化对象到xml文档
}
catch (Exception ex)
{
//_logServ.Error(string.Format("创建xml文档失败:{0}", ex.Message));
return false;
}
finally
{
writer.Close();
}
return true;
}
public static bool CreateXML<T>(T obj, ref Stream xmlStream)
{
XmlWriterSettings writerSetting = new XmlWriterSettings //声明编写器设置
{
Indent = true,//定义xml格式,自动创建新的行
Encoding = UTF8Encoding.UTF8,//编码格式
};
XmlSerializer xser = new XmlSerializer(typeof(T)); //实例化序列化对象
try
{
xser.Serialize(xmlStream, obj); //序列化对象到xml文档
using (MemoryStream ms = new MemoryStream())
{
xmlStream.CopyTo(ms);
// return ms.ToArray();
}
}
catch (Exception ex)
{
//_logServ.Error(string.Format("创建xml文档失败:{0}", ex.Message));
return false;
}
finally
{
xmlStream.Close();
}
return true;
}
public static object FromXmlString(Stream xmlStream, Type type)
{
using (XmlReader reader=XmlReader.Create(xmlStream))
{
XmlSerializer serializer = new XmlSerializer(type);
try
{
return serializer.Deserialize(reader);
}
catch
{
return null;
}
}
}
/// <summary>
/// 从 XML 文档中反序列化为对象
/// </summary>
/// <param name="filePath">文档路径(包含文档名)</param>
/// <param name="type">对象的类型</param>
/// <returns>返回object类型</returns>
public static object FromXmlString(string filePath, Type type)
{
if (!File.Exists(filePath))
{
return null;
}
string xmlString = File.ReadAllText(filePath);
if (string.IsNullOrEmpty(xmlString))
{
return null;
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
XmlSerializer serializer = new XmlSerializer(type);
try
{
return serializer.Deserialize(stream);
}
catch
{
return null;
}
}
}
public static string Datatable2Json(DataTable dt)
{
return JsonConvert.SerializeObject(dt);
}
public static DataTable Json2DataTable(string json)
{
return JsonConvert.DeserializeObject<DataTable>(json);
}
public static string Object2Json(object obj)
{
return JsonConvert.SerializeObject(obj);
}
public static T Json2Object<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
public static string SerializeDataTableXml(DataTable pDt)
{
// 序列化DataTable
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
pDt.TableName = "Test";
XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
serializer.Serialize(writer, pDt);
writer.Close();
return sb.ToString();
}
public static DataTable DeserializeDataTable(string pXml)
{
StringReader strReader = new StringReader(pXml);
XmlReader xmlReader = XmlReader.Create(strReader);
XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
return dt;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief ファイル。タスク。
*/
//Async block lacks `await' operator and will run synchronously.
#pragma warning disable 1998
/** NFile
*/
namespace NFile
{
/** ロードローカル。テキストファイル。
*/
public class Task_LoadLocalTextFile
{
/** ResultType
*/
public struct ResultType
{
public string text;
public string errorstring;
}
/** TaskMain
*/
private static async System.Threading.Tasks.Task<ResultType> TaskMain(string a_full_path,System.Threading.CancellationToken a_cancel)
{
ResultType t_ret;
{
t_ret.text = null;
t_ret.errorstring = null;
}
System.IO.StreamReader t_filestream = null;
try{
//ファイルパス。
System.IO.FileInfo t_fileinfo = new System.IO.FileInfo(a_full_path);
//開く。
t_filestream = t_fileinfo.OpenText();
//読み込み。
if(t_filestream != null){
if(Config.USE_ASYNC == true){
t_ret.text = await t_filestream.ReadToEndAsync();
}else{
t_ret.text = t_filestream.ReadToEnd();
}
}
}catch(System.Exception t_exception){
t_ret.text = null;
t_ret.errorstring = "Task_LoadLocalTextFile : " + t_exception.Message;
}
//閉じる。
if(t_filestream != null){
t_filestream.Close();
}
if(a_cancel.IsCancellationRequested == true){
t_ret.text = null;
t_ret.errorstring = "Task_LoadLocalTextFile : Cancel";
a_cancel.ThrowIfCancellationRequested();
}
if(t_ret.text == null){
if(t_ret.errorstring == null){
t_ret.errorstring = "Task_LoadLocalTextFile : null";
}
}
return t_ret;
}
/** 実行。
*/
public static NTaskW.Task<ResultType> Run(string a_full_path,NTaskW.CancelToken a_cancel)
{
System.Threading.CancellationToken t_cancel_token = a_cancel.GetToken();
return new NTaskW.Task<ResultType>(() => {
return Task_LoadLocalTextFile.TaskMain(a_full_path,t_cancel_token);
});
}
}
}
|
using System;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace PmSoft.Utilities
{
/// <summary>
/// 字符串工具类
/// </summary>
public static class StringUtility
{
/// <summary>
/// 取中文文本的拼音
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static string GetPinyin(string ch, bool removeSpace = false)
{
string pinyin = Pinyin.Pinyin.GetPinyin(ch);
if (!string.IsNullOrEmpty(pinyin))
pinyin = Regex.Replace(pinyin, @"\s", string.Empty);
return pinyin;
}
/// <summary>
/// 获取拼音首字母
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
public static string GetPinyinInitials(string ch)
{
return Pinyin.Pinyin.GetInitials(ch);
}
/// <summary>
/// 清除XML无效字符
/// </summary>
/// <param name="rawXml"></param>
/// <returns></returns>
public static string CleanInvalidCharsForXML(string rawXml)
{
if (string.IsNullOrEmpty(rawXml))
{
return rawXml;
}
StringBuilder builder = new StringBuilder();
char[] chArray = rawXml.ToCharArray();
for (int i = 0; i < chArray.Length; i++)
{
int num2 = Convert.ToInt32(chArray[i]);
if ((((num2 < 0) || (num2 > 8)) && ((num2 < 11) || (num2 > 12))) && ((num2 < 14) || (num2 > 0x1f)))
{
builder.Append(chArray[i]);
}
}
return builder.ToString();
}
/// <summary>
/// 移除SQL注入代码
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static string StripSQLInjection(string sql)
{
if (!string.IsNullOrEmpty(sql))
{
string pattern = @"((\%27)|(\'))\s*((\%6F)|o|(\%4F))((\%72)|r|(\%52))";
string str2 = @"(\%27)|(\')|(\-\-)";
string str3 = @"\s+exec(\s|\+)+(s|x)p\w+";
sql = Regex.Replace(sql, pattern, string.Empty, RegexOptions.IgnoreCase);
sql = Regex.Replace(sql, str2, string.Empty, RegexOptions.IgnoreCase);
sql = Regex.Replace(sql, str3, string.Empty, RegexOptions.IgnoreCase);
sql = sql.Replace("%", "[%]");
}
return sql;
}
public static string Trim(string rawString, int charLimit)
{
return Trim(rawString, charLimit, "...");
}
public static string Trim(string rawString, int charLimit, string appendString)
{
if (string.IsNullOrEmpty(rawString) || (rawString.Length <= charLimit))
{
return rawString;
}
if (Encoding.UTF8.GetBytes(rawString).Length <= (charLimit * 2))
{
return rawString;
}
charLimit = (charLimit * 2) - Encoding.UTF8.GetBytes(appendString).Length;
StringBuilder builder = new StringBuilder();
int num2 = 0;
for (int i = 0; i < rawString.Length; i++)
{
char ch = rawString[i];
builder.Append(ch);
num2 += (ch > '\x0080') ? 2 : 1;
if (num2 >= charLimit)
{
break;
}
}
return builder.Append(appendString).ToString();
}
/// <summary>
/// Unicode编码
/// </summary>
/// <param name="rawString"></param>
/// <returns></returns>
public static string UnicodeEncode(string rawString)
{
if ((rawString == null) || (rawString == string.Empty))
{
return rawString;
}
StringBuilder builder = new StringBuilder();
string str2 = rawString;
for (int i = 0; i < str2.Length; i++)
{
int num = str2[i];
string str = "";
if (num > 0x7e)
{
builder.Append(@"\u");
str = num.ToString("x");
for (int j = 0; j < (4 - str.Length); j++)
{
builder.Append("0");
}
}
else
{
str = ((char)num).ToString();
}
builder.Append(str);
}
return builder.ToString();
}
/// <summary>
/// Unicode解码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string UnicodeDecode(this string str)
{
//最直接的方法Regex.Unescape(str);
StringBuilder strResult = new StringBuilder();
if (!string.IsNullOrEmpty(str))
{
string[] strlist = str.Replace("\\", "").Split('u');
try
{
for (int i = 1; i < strlist.Length; i++)
{
int charCode = Convert.ToInt32(strlist[i], 16);
strResult.Append((char)charCode);
}
}
catch (FormatException)
{
return Regex.Unescape(str);
}
}
return strResult.ToString();
}
/// <summary>
/// 获取枚举属性DisplayAttribute的NAME值
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi == null) return value.ToString();
var attribute = fi.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false)
.Cast<System.ComponentModel.DataAnnotations.DisplayAttribute>()
.FirstOrDefault();
if (attribute != null)
return attribute.Name;
return value.ToString();
}
}
}
|
using System;
using System.Threading.Tasks;
namespace JimBobBennett.JimLib.Commands
{
public abstract class AsyncCommandBase<T> : IAsyncCommand<T>
{
public abstract bool CanExecute(object parameter);
public abstract Task ExecuteAsync(T parameter);
public async void Execute(object parameter)
{
if (CanExecute(parameter))
await ExecuteAsync((T)parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class DisplayHealth : MonoBehaviour
{
public PlayerHealth Character;
public Button btn;
Image slider;
private void Start()
{
GameTriggers.OnCharSelect += UpdateDisplay;
slider = GetComponent<Image>();
}
private void OnEnable()
{
GameTriggers.OnCharSelect += UpdateDisplay;
}
private void OnDisable()
{
GameTriggers.OnCharSelect -= UpdateDisplay;
}
void UpdateDisplay()
{
if (slider != null)
{
slider.fillAmount = Character.CurrentHealth / Character.MaxHealth;
if (Character.CurrentHealth <= 0)
{
btn.interactable = false;
}
}
}
}
|
using ScribblersSharp;
using System.Collections.Generic;
/// <summary>
/// Scribble.rs Pad namespace
/// </summary>
namespace ScribblersPad
{
/// <summary>
/// Used to signal when listing lobbies has been finished
/// </summary>
/// <param name="lobbyViews">Lobby views</param>
public delegate void ListLobbyRequestFinishedDelegate(IEnumerable<ILobbyView> lobbyViews);
}
|
using Plus.HabboHotel.GameClients;
using Plus.HabboHotel.Rooms;
using Plus.HabboHotel.Users;
namespace Plus.Communication.Packets.Outgoing.Navigator
{
internal class GetGuestRoomResultComposer : MessageComposer
{
public Habbo Habbo { get; }
public RoomData Data { get; }
public bool IsLoading { get; }
public bool CheckEntry { get; }
public GetGuestRoomResultComposer(GameClient session, RoomData data, bool isLoading, bool checkEntry)
: base(ServerPacketHeader.GetGuestRoomResultMessageComposer)
{
Habbo = session.GetHabbo();
Data = data;
IsLoading = isLoading;
CheckEntry = checkEntry;
}
public override void Compose(ServerPacket packet)
{
packet.WriteBoolean(IsLoading);
packet.WriteInteger(Data.Id);
packet.WriteString(Data.Name);
packet.WriteInteger(Data.OwnerId);
packet.WriteString(Data.OwnerName);
packet.WriteInteger(RoomAccessUtility.GetRoomAccessPacketNum(Data.Access));
packet.WriteInteger(Data.UsersNow);
packet.WriteInteger(Data.UsersMax);
packet.WriteString(Data.Description);
packet.WriteInteger(Data.TradeSettings);
packet.WriteInteger(Data.Score);
packet.WriteInteger(0); //Top rated room rank.
packet.WriteInteger(Data.Category);
packet.WriteInteger(Data.Tags.Count);
foreach (string tag in Data.Tags)
{
packet.WriteString(tag);
}
if (Data.Group != null && Data.Promotion != null)
{
packet.WriteInteger(62);
packet.WriteInteger(Data.Group == null ? 0 : Data.Group.Id);
packet.WriteString(Data.Group == null ? "" : Data.Group.Name);
packet.WriteString(Data.Group == null ? "" : Data.Group.Badge);
packet.WriteString(Data.Promotion != null ? Data.Promotion.Name : "");
packet.WriteString(Data.Promotion != null ? Data.Promotion.Description : "");
packet.WriteInteger(Data.Promotion != null ? Data.Promotion.MinutesLeft : 0);
}
else if (Data.Group != null && Data.Promotion == null)
{
packet.WriteInteger(58);
packet.WriteInteger(Data.Group == null ? 0 : Data.Group.Id);
packet.WriteString(Data.Group == null ? "" : Data.Group.Name);
packet.WriteString(Data.Group == null ? "" : Data.Group.Badge);
}
else if (Data.Group == null && Data.Promotion != null)
{
packet.WriteInteger(60);
packet.WriteString(Data.Promotion != null ? Data.Promotion.Name : "");
packet.WriteString(Data.Promotion != null ? Data.Promotion.Description : "");
packet.WriteInteger(Data.Promotion != null ? Data.Promotion.MinutesLeft : 0);
}
else
{
packet.WriteInteger(56);
}
packet.WriteBoolean(CheckEntry);
packet.WriteBoolean(false);
packet.WriteBoolean(false);
packet.WriteBoolean(false);
packet.WriteInteger(Data.WhoCanMute);
packet.WriteInteger(Data.WhoCanKick);
packet.WriteInteger(Data.WhoCanBan);
packet.WriteBoolean(Habbo.GetPermissions().HasRight("mod_tool") || Data.OwnerName == Habbo.Username);
packet.WriteInteger(Data.ChatMode);
packet.WriteInteger(Data.ChatSize);
packet.WriteInteger(Data.ChatSpeed);
packet.WriteInteger(Data.ExtraFlood);
packet.WriteInteger(Data.ChatDistance);
}
}
} |
namespace Factory.Library.Ingredients.Veggies
{
public class EggPlant :IVeggie
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EffectsManager : MonoBehaviour
{
public Gradient TrailDefaultColorGradient;
public Gradient TrailHitColorGradient;
public Light StrikerEffectPrefab;
private static EffectsManager _instance;
public static EffectsManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<EffectsManager>();
}
return _instance;
}
}
public void InitStrikerEffect(Vector3 position)
{
Light light = Instantiate(StrikerEffectPrefab, position, Quaternion.identity);
Destroy(light, 0.3f);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.