text stringlengths 13 6.01M |
|---|
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 learn_180326_web
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Uri address =new Uri(textBox1.Text);
webBrowser1.Url = address;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
if (textBox1.Text != "")
{
button1_Click(sender,e);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _4._List_Operations
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToList();
string command = Console.ReadLine();
while (command != "End")
{
string[] commandSeparated = command.Split();
if (commandSeparated[0] == "Add")
{
numbers.Add(int.Parse(commandSeparated[1]));
}
else if (commandSeparated[0] == "Insert")
{
if (IsIndexValid(numbers, int.Parse(commandSeparated[2])))
{
numbers.Insert(int.Parse(commandSeparated[2]), int.Parse(commandSeparated[1]));
}
else
{
Console.WriteLine("Invalid index");
}
}
else if (commandSeparated[0] == "Remove")
{
if (IsIndexValid(numbers, int.Parse(commandSeparated[1])))
{
numbers.RemoveAt(int.Parse(commandSeparated[1]));
}
else
{
Console.WriteLine("Invalid index");
}
}
else if (commandSeparated[0] == "Shift")
{
if (commandSeparated[1] == "left")
{
numbers = ShiftLeft(numbers, int.Parse(commandSeparated[2]));
}
else
{
numbers = ShiftRight(numbers, int.Parse(commandSeparated[2]));
}
}
command = Console.ReadLine();
}
Console.WriteLine(String.Join(" ", numbers));
}
static bool IsIndexValid(List<int> numbers, int index)
{
if (index >= 0 && index < numbers.Count)
{
return true;
}
else
{
return false;
}
}
static List<int> ShiftLeft(List<int> numbers, int count)
{
for (int i = 0; i < count; i++)
{
numbers.Add(numbers[0]);
numbers.RemoveAt(0);
}
return numbers
;
}
static List<int> ShiftRight(List<int> numbers, int count)
{
for (int i = 0; i < count; i++)
{
numbers.Insert(0, numbers[numbers.Count - 1]);
numbers.RemoveAt(numbers.Count - 1);
}
return numbers
;
}
}
}
|
using System.Collections.Generic;
using SwordAndFather.Models;
namespace SwordAndFather.Data
{
public class AssaassinRepository
{
static readonly List<Assassin> Assassins = new List<Assassin>();
public Assassin AddAssassin(string codeName, string catchPhrase, string preferredWeapon)
{
var newAssassin = new Assassin(codeName, catchPhrase, preferredWeapon);
newAssassin.Id = Assassins.Count + 1;
Assassins.Add(newAssassin);
return newAssassin;
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Calendar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int iDisplayYear = 0;
int iDisplayMonth = 1;
string campSessionStartMonth = ConfigurationManager.AppSettings["CampSessionStartMonth"];
string campSessionEndMonth = ConfigurationManager.AppSettings["CampSessionEndMonth"];
string campSessionStartYear = Application["CampYear"].ToString();
string campSessionEndYear = Application["CampYear"].ToString();
int startYear, endYear, startMonth, endMonth = 0;
int.TryParse(campSessionStartYear, out startYear);
int.TryParse(campSessionEndYear, out endYear);
int.TryParse(campSessionStartMonth, out startMonth);
int.TryParse(campSessionEndMonth, out endMonth);
if (campSessionStartYear == "*" || campSessionEndYear == "*" || campSessionStartMonth == "*" || campSessionEndMonth == "*" || startYear > endYear)
{ iDisplayMonth = DateTime.Now.Month; iDisplayYear = DateTime.Now.Year; }
else
{
iDisplayMonth = Int32.Parse(ConfigurationManager.AppSettings["CampSessionStartMonth"]);
iDisplayYear = startYear;
}
//new CIPMSBC.CamperApplication().
calStartDt.VisibleDate = new DateTime(iDisplayYear, iDisplayMonth, 1);
calStartDt.PrevMonthText = string.Empty;
}
}
protected void calStartDt_SelectionChanged(object sender, EventArgs e)
{
string strScript;
string strDateValue = calStartDt.SelectedDate.ToString("MM/dd/yyyy");
string strTxtObj = Request.QueryString["txtBox"].ToString();
ltlJavascript.Text = "<script language=\"javascript\" > \n";
ltlJavascript.Text = ltlJavascript.Text + "window.opener.document.getElementById('" + strTxtObj + "').value='" + strDateValue + "'; \n";
ltlJavascript.Text = ltlJavascript.Text + "self.close();\n ";
ltlJavascript.Text = ltlJavascript.Text + "</script>";
}
protected void OnCalendar_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
string campSessionStartMonth = ConfigurationManager.AppSettings["CampSessionStartMonth"];
string campSessionEndMonth = ConfigurationManager.AppSettings["CampSessionEndMonth"];
string campSessionStartYear = Application["CampYear"].ToString();
string campSessionEndYear = Application["CampYear"].ToString();
int startYear, endYear, startMonth, endMonth = 0;
int.TryParse(campSessionStartYear, out startYear);
int.TryParse(campSessionEndYear, out endYear);
int.TryParse(campSessionStartMonth, out startMonth);
int.TryParse(campSessionEndMonth, out endMonth);
//if any of these values are marked as * or start year is greater than end year in both the case the calendar allows camper to navigate to any month
if (campSessionStartYear == "*" || campSessionEndYear == "*" || campSessionStartMonth == "*" || campSessionEndMonth == "*" || startYear > endYear)
{ }
else if (startYear == endYear)
{
if (startMonth <= endMonth)
{
if (e.NewDate.Month <= startMonth) calStartDt.PrevMonthText = ""; else { if (calStartDt.PrevMonthText.Equals(string.Empty)) calStartDt.PrevMonthText = "<"; }
if (e.NewDate.Month >= endMonth) calStartDt.NextMonthText = ""; else { if (calStartDt.NextMonthText.Equals(string.Empty)) calStartDt.NextMonthText = ">"; }
}
}
else if (startYear < endYear)
{
if (startYear == e.NewDate.Year)
{
if (e.NewDate.Month <= startMonth) calStartDt.PrevMonthText = "";
else { if (calStartDt.PrevMonthText.Equals(string.Empty)) calStartDt.PrevMonthText = "<"; }
}
if (endYear == e.NewDate.Year)
{
if (e.NewDate.Month >= endMonth) calStartDt.NextMonthText = "";
else { if (calStartDt.NextMonthText.Equals(string.Empty)) calStartDt.NextMonthText = ">"; }
}
}
else { if (calStartDt.PrevMonthText.Equals(string.Empty)) calStartDt.PrevMonthText = "<"; if (calStartDt.NextMonthText.Equals(string.Empty)) calStartDt.NextMonthText = ">"; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OrbisEngine.ItemSystem;
public class StatMessage : IMessage
{
// Clean: This system, implemented issue could be resolved by changing the IMessage interface
public string Message {
get {
throw new System.NotImplementedException();
}
set {
throw new System.NotImplementedException();
}
}
public string TargetStat;
public StatModifier Modifier;
public StatMessage(string targetStat, StatModifier modifier)
{
TargetStat = targetStat;
Modifier = modifier;
}
public StatMessage(string targetStat)
{
TargetStat = targetStat;
}
public const string UpdateStat = "UPDATE_STAT";
public const string GetStat = "GET_STAT";
}
|
using Microsoft.EntityFrameworkCore;
using OnboardingSIGDB1.Domain.Empresas;
using OnboardingSIGDB1.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnboardingSIGDB1.Data.Empresas.Repositorios
{
public class EmpresaRepository : Repository<Empresa>, IEmpresaRepository
{
private readonly IUnitOfWork _unitOfWork;
public EmpresaRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
_unitOfWork = unitOfWork;
}
public async Task<IEnumerable<Empresa>> GetWithFuncionarios(Predicate<Empresa> predicate)
{
return await _unitOfWork
.Context
.Empresas
.Include(f => f.Funcionarios)
.Where(f => predicate(f)).ToListAsync();
}
}
}
|
using Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Drawing;
using Microsoft.Xna.Framework.Content;
namespace Mario__.Modules
{
public class Resource : Drawable
{
static Texture2D[] Textures;
public int type, amount;
public Resource(int type, int amount)
{
this.type = type;
this.amount = amount;
}
public void draw(SpriteBatch spriteBatch, int x, int y, float tileSizeX, float tileSizeY)
{
hexDraw(spriteBatch, getTexture(), x, y, tileSizeX, tileSizeY, Microsoft.Xna.Framework.Color.White);
}
public override void update(GameTime gameTime, InputListener input)
{
throw new NotImplementedException();
}
//getters and other shit
public string getName()
{
switch (type)
{
case 0: return "Trump";
case 1: return "Gold";
case 2: return "Trump";
case 3: return "Trump";
case 4: return "Trump";
case 5: return "Trump";
case 6: return "Trump";
case 7: return "Trump";
case 8: return "Trump";
case 9: return "Trump";
case 10: return "Trump";
}
return "";
}
public Texture2D getTexture()
{
return Textures[type];
}
public static void loadTextures(ContentManager Content)
{
Textures = new Texture2D[11];
Textures[0] = Content.Load<Texture2D>("trumpWall");
Textures[1] = Content.Load<Texture2D>("ResGold");
Textures[2] = Content.Load<Texture2D>("trumpWall");
Textures[3] = Content.Load<Texture2D>("trumpWall");
Textures[4] = Content.Load<Texture2D>("trumpWall");
Textures[5] = Content.Load<Texture2D>("trumpWall");
Textures[6] = Content.Load<Texture2D>("trumpWall");
Textures[7] = Content.Load<Texture2D>("trumpWall");
Textures[8] = Content.Load<Texture2D>("trumpWall");
Textures[9] = Content.Load<Texture2D>("trumpWall");
Textures[10] = Content.Load<Texture2D>("trumpWall");
}
public static void destroyTextures()
{
foreach (Texture2D tex in Textures)
{
tex.Dispose();
}
}
int mod(int x, int m)
{
return (x % m + m) % m;
}
public override void destroy(){}
public override void draw(SpriteBatch spriteBatch) { }
public override void load(){}
}
} |
using System;
namespace Building
{
class Program
{
static void Main(string[] args)
{
int floors = int.Parse(Console.ReadLine());
int roomsOnFloor = int.Parse(Console.ReadLine());
for (int floorNumber = floors; floorNumber >= 1; floorNumber--)
{
for (int roomNumber = 0; roomNumber < roomsOnFloor; roomNumber++)
{
if (floorNumber == floors)
{
Console.Write($"L{floorNumber}{roomNumber} ");
}
else if (floorNumber % 2 == 0)
{
Console.Write($"O{floorNumber}{roomNumber} ");
}
else if (floorNumber % 2 != 0)
{
Console.Write($"A{floorNumber}{roomNumber} ");
}
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Windows.Threading;
namespace LiveCharts.Wpf.Components
{
public class ChartUpdater : LiveCharts.ChartUpdater
{
public ChartUpdater()
{
Timer = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(50)};
FrecuencyUpdate += () =>
{
Timer.Interval = Frequency;
};
Timer.Tick += (sender, args) =>
{
Update();
IsUpdating = false;
Timer.Stop();
};
}
public DispatcherTimer Timer { get; set; }
public override void Run(bool restartView = false)
{
if (IsUpdating) return;
IsUpdating = true;
Timer.Start();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Door : MonoBehaviour {
[SerializeField]
private Transform rotationDest;
public void Open()
{
StartCoroutine(Opening(rotationDest));
}
IEnumerator Opening( Transform destination)
{
Debug.Log("defg");
while (transform.rotation != destination.rotation)
{
transform.rotation = Quaternion.Lerp(transform.rotation,destination.rotation, Time.deltaTime * 1f);
yield return new WaitForFixedUpdate();
}
}
}
|
using System;
using BikeDistributor.Models.Common;
namespace BikeDistributor.Models
{
public class DiscountCodeModel: BaseModel<int>
{
public string CampainCode { get; set; }
public int QuantityRange1 { get; set; }
public int QuantityRange2 { get; set; }
public string Flag { get; set; }
public double DiscountRate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}
|
using System.Linq;
using UnityEngine;
using UnityEditor;
using UnityEngine.Timeline;
using UnityEngine.Playables;
public class AutoGenerate : MonoBehaviour
{
public float Min = 0.0f;
public float Max = 1.0f;
public double interval = 3.0d;
private LabelTrack AiueoTrack = null;
private LabelTrack BlinkTrack = null;
private BlendShapeTrack AiueoShapeTrack = null;
private BlendShapeTrack BlinkShapeTrack = null;
private BlendShapeTrack UpperTeethShapeTracK = null;
private BlendShapeTrack ButtomTeethShapeTracK = null;
private PlayableDirector Director = null;
private TimelineAsset MyTimelineAsset = null;
private void Awake()
{
Initial();
}
public void OnClick()
{
if (Director == null)
Initial();
GenerateBlendShape();
}
private void GenerateBlendShape()
{
var clips = AiueoTrack.GetClips();
foreach (var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
char[] labels = clipAsset.Label.ToCharArray();
AnimationCurve[] curves = new AnimationCurve[0];
for (int i = 0; i < 5; i++)
ArrayExtensions.Add(ref curves, AnimationCurveExtensions.ZeroCurve());
int begin = 0;
int size = 1;
for (int end = 0; end < labels.Length; end++)
{
if (end < labels.Length - 1 && labels[end] == labels[end + 1])
size++;
else
{
switch (labels[end])
{
case 'a':
case 'A':
AddKey(curves[0], clipAsset, begin, end, size);
break;
case 'i':
case 'I':
AddKey(curves[1], clipAsset, begin, end, size);
break;
case 'u':
case 'U':
AddKey(curves[2], clipAsset, begin, end, size);
break;
case 'e':
case 'E':
AddKey(curves[3], clipAsset, begin, end, size);
break;
case 'o':
case 'O':
AddKey(curves[4], clipAsset, begin, end, size);
break;
}
begin = end + 1;
size = 1;
}
}
float min = clipAsset.Min;
for (int i = 0; i < curves.Length; i++)
PostProcess(ref curves[i], min);
AddBlendShapeClip(clip.start, clip.duration, AiueoShapeTrack, curves);
AddBlendShapeClip(clip.start, clip.duration, UpperTeethShapeTracK, curves);
AddBlendShapeClip(clip.start, clip.duration, ButtomTeethShapeTracK, curves);
}
clips = BlinkTrack.GetClips();
foreach (var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
AnimationCurve[] curves = new AnimationCurve[1] { AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max) };
AddBlendShapeClip(clip.start, clip.duration, BlinkShapeTrack, curves);
}
}
//private GenerateActivation()
//{
//}
private void Initial()
{
Director = gameObject.GetComponent<PlayableDirector>();
MyTimelineAsset = Director.playableAsset as TimelineAsset;
AiueoTrack = GetTrack("AIUEO Label") as LabelTrack;
BlinkTrack = GetTrack("Blink Label") as LabelTrack;
AiueoShapeTrack = GetTrack("AIUEO") as BlendShapeTrack;
BlinkShapeTrack = GetTrack("Blink") as BlendShapeTrack;
UpperTeethShapeTracK = GetTrack("UpperTeeth") as BlendShapeTrack;
ButtomTeethShapeTracK = GetTrack("ButtomTeeth") as BlendShapeTrack;
}
private void AddKey(AnimationCurve curve, LabelClip clip, int begin, int end, int size)
{
char[] labels = clip.Label.ToCharArray();
float duration = 1.0f / labels.Length;
if (curve.length == 2)
curve.AddKey(new Keyframe(duration * begin, 0, 0, 0));
else
curve.AddKey(new Keyframe(duration * begin, clip.Min, 0, 0));
curve.AddKey(new Keyframe(duration * begin + duration * 0.5f, clip.Max, 0, 0));
if (size > 1)
curve.AddKey(new Keyframe(duration * (begin + size) - duration * 0.5f, clip.Max, 0, 0));
if (end < labels.Length - 1)
curve.AddKey(new Keyframe(duration * (begin + size), clip.Min, 0, 0));
}
private TrackAsset GetTrack(string name)
{
return MyTimelineAsset.GetOutputTracks().ToList().Find(x => x.name == name);
}
private void PostProcess(ref AnimationCurve curve, float min)
{
if(curve.keys[curve.length - 2].value == min)
{
float time = curve.keys[curve.length - 2].time;
curve.RemoveKey(curve.length - 2);
curve.AddKey(new Keyframe(time, 0, 0, 0));
}
}
private void AddBlendShapeClip(double start, double duration, BlendShapeTrack track, AnimationCurve[] curves)
{
TimelineClip timelineClip = track.CreateDefaultClip();
timelineClip.start = start;
timelineClip.duration = duration;
BlendShapeClip clipAsset = timelineClip.asset as BlendShapeClip;
PlayableGraph graph = Director.playableGraph;
string[] name = new string[5] { "A", "I", "U", "E", "O" };
if (track.name == "AIUEO")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Face"));
if (track.name == "UpperTeeth")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Teeth_upper"));
if (track.name == "ButtomTeeth")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Teeth_buttom"));
if (track.name == "Blink")
clipAsset.AddShape(new BlendShapeClip.Shape(8, "BlinkBoth", timelineClip, curves[0]));
else if (track.name == "AIUEO")
{
int startIndex = 11;
for(int i = 0; i < 5; i++)
clipAsset.AddShape(new BlendShapeClip.Shape(startIndex + i, name[i], timelineClip, curves[i]));
}
else
{
int startIndex = 8;
for (int i = 0; i < 5; i++)
clipAsset.AddShape(new BlendShapeClip.Shape(startIndex + i, name[i], timelineClip, curves[i]));
}
}
[CustomEditor(typeof(AutoGenerate))]
public class AutoGenerateEditor : Editor
{
public AutoGenerate Target;
private void Awake()
{
Target = target as AutoGenerate;
}
public override void OnInspectorGUI()
{
if (GUILayout.Button("Generate"))
{
Target.OnClick();
}
}
}
}
/* old function
*
public void OnClick()
{
Director = GetComponent<PlayableDirector>();
MyTimelineAsset = Director.playableAsset as TimelineAsset;
LabelTrack aiueoTrack = GetTrack("AIUEO Label") as LabelTrack;
LabelTrack blinkTrack = GetTrack("Blink Label") as LabelTrack;
BlendShapeTrack aiueoShapeTrack = GetTrack("AIUEO") as BlendShapeTrack;
BlendShapeTrack blinkShapeTrack = GetTrack("Blink") as BlendShapeTrack;
BlendShapeTrack upperTeethShapeTracK = GetTrack("UpperTeeth") as BlendShapeTrack;
BlendShapeTrack buttomTeethShapeTracK = GetTrack("ButtomTeeth") as BlendShapeTrack;
var clips = aiueoTrack.GetClips();
foreach(var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
char[] labels = clipAsset.Label.ToCharArray();
double clipDuration = clip.duration / labels.Length;
float duration = 1.0f / labels.Length;
AnimationCurve curve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0));
int size = 1;
int index = 0;
for(int i = 0; i < labels.Length; i++)
{
if (i < labels.Length - 1 && labels[i] == labels[i + 1])
size++;
else
{
int type = -1;
switch (labels[i])
{
case 'a':
case 'A':
type = 1; break;
case 'i':
case 'I':
type = 2; break;
case 'u':
case 'U':
type = 3; break;
case 'e':
case 'E':
type = 4; break;
case 'o':
case 'O':
type = 5; break;
}
AddBlendShapeClip(type, clip.start + clipDuration * index, clipDuration * size,
aiueoShapeTrack, AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max));
AddBlendShapeClip(type, clip.start + clipDuration * index, clipDuration * size,
upperTeethShapeTracK, AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max));
AddBlendShapeClip(type, clip.start + clipDuration * index, clipDuration * size,
buttomTeethShapeTracK, AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max));
size = 1;
index = i + 1;
}
}
}
clips = blinkTrack.GetClips();
foreach (var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
AddBlendShapeClip(0, clip.start, clip.duration, blinkShapeTrack,
AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max));
}
}
private void ProcessBlendShape(LabelTrack track)
{
var clips = track.GetClips();
foreach (var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
char[] labels = clipAsset.Label.ToCharArray();
float duration = 1.0f / labels.Length;
AnimationCurve curveA = AnimationCurveExtensions.ZeroCurve();
AnimationCurve curveI = AnimationCurveExtensions.ZeroCurve();
AnimationCurve curveU = AnimationCurveExtensions.ZeroCurve();
AnimationCurve curveE = AnimationCurveExtensions.ZeroCurve();
AnimationCurve curveO = AnimationCurveExtensions.ZeroCurve();
int size = 1;
int index = 0;
for (int i = 0; i < labels.Length; i++)
{
if (i < labels.Length - 1 && labels[i] == labels[i + 1])
size++;
else
{
int type = -1;
switch (labels[i])
{
case 'a':
case 'A':
curveA.AddKey(duration * index + duration * 0.5f, clipAsset.Max);
if (size > 1)
curveA.AddKey(duration * (index + size) - duration * 0.5f, clipAsset.Max);
if (i < labels.Length - 1)
curveA.AddKey(duration * (index + size), clipAsset.Min);
break;
case 'i':
case 'I':
curveI.AddKey(duration * index + duration * 0.5f, clipAsset.Max);
if (size > 1)
curveI.AddKey(duration * (index + size) - duration * 0.5f, clipAsset.Max);
if (i < labels.Length - 1)
curveI.AddKey(duration * (index + size), clipAsset.Min);
break;
case 'u':
case 'U':
curveU.AddKey(duration * index + duration * 0.5f, clipAsset.Max);
if (size > 1)
curveU.AddKey(duration * (index + size) - duration * 0.5f, clipAsset.Max);
if (i < labels.Length - 1)
curveU.AddKey(duration * (index + size), clipAsset.Min);
break;
case 'e':
case 'E':
curveE.AddKey(duration * index + duration * 0.5f, clipAsset.Max);
if (size > 1)
curveE.AddKey(duration * (index + size) - duration * 0.5f, clipAsset.Max);
if (i < labels.Length - 1)
curveE.AddKey(duration * (index + size), clipAsset.Min);
break;
case 'o':
case 'O':
curveO.AddKey(duration * index + duration * 0.5f, clipAsset.Max);
if (size > 1)
curveO.AddKey(duration * (index + size) - duration * 0.5f, clipAsset.Max);
if (i < labels.Length - 1)
curveO.AddKey(duration * (index + size), clipAsset.Min);
break;
}
}
size = 1;
index = i + 1;
}
AnimationCurve[] curves = new AnimationCurve[5] { curveA, curveI, curveU, curveE, curveO };
AddBlendShapeClip(clip.start, clip.duration, track, curves);
}
clips = track.GetClips();
foreach (var clip in clips)
{
LabelClip clipAsset = clip.asset as LabelClip;
AnimationCurve[] curves = new AnimationCurve[1] { AnimationCurveExtensions.UCurve(0.5f, 0.0f, clipAsset.Min, clipAsset.Max) };
AddBlendShapeClip(clip.start, clip.duration, track, curves);
}
private void AddBlendShapeClip(int type, double start, double duration, BlendShapeTrack track, AnimationCurve curve)
{
TimelineClip timelineClip = track.CreateDefaultClip();
timelineClip.start = start;
timelineClip.duration = duration;
BlendShapeClip clipAsset = timelineClip.asset as BlendShapeClip;
PlayableGraph graph = Director.playableGraph;
if (track.name == "AIUEO")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Face"));
if (track.name == "UpperTeeth")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Teeth_upper"));
if (track.name == "ButtomTeeth")
graph.GetResolver().SetReferenceValue(clipAsset.Mesh.exposedName, GameObject.Find("TKVR01_001_CH_Mesh_Teeth_buttom"));
if (type == 0)
clipAsset.AddShape(new BlendShapeClip.Shape(8, "BlinkBoth", timelineClip, curve));
else if (track.name == "AIUEO")
{
clipAsset.AddShape(new BlendShapeClip.Shape(11, "A", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(12, "I", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(13, "U", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(14, "E", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(15, "O", timelineClip, AnimationCurveExtensions.ZeroCurve()));
}
else
{
clipAsset.AddShape(new BlendShapeClip.Shape(8, "A", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(9, "I", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(10, "U", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(11, "E", timelineClip, AnimationCurveExtensions.ZeroCurve()));
clipAsset.AddShape(new BlendShapeClip.Shape(12, "O", timelineClip, AnimationCurveExtensions.ZeroCurve()));
}
switch (type)
{
case 0:
break;
case 1:
clipAsset.Shapes[0].SetAnimationCurve(curve);
break;
case 2:
clipAsset.Shapes[1].SetAnimationCurve(curve);
break;
case 3:
clipAsset.Shapes[2].SetAnimationCurve(curve);
break;
case 4:
clipAsset.Shapes[3].SetAnimationCurve(curve);
break;
case 5:
clipAsset.Shapes[4].SetAnimationCurve(curve);
break;
}
}
}
*
*/ |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneChange : MonoBehaviour {
public Scene_manager scenemanager_;
void Start () {
scenemanager_ = GameObject.FindGameObjectWithTag("Scenemanager").GetComponent<Scene_manager>();
}
void Update () {
}
public void onNextscene()
{
scenemanager_.NextScene();
}
}
|
using System;
namespace aairvid.Model
{
[Serializable]
public class HistoryItem
{
public long LastPosition { get; set; }
public DateTime LastPlayDate { get; set; }
public string Server { get; set; }
public string FolderPath { get; set; }
public string FolderId { get; set; }
public string ServerId { get; set; }
public string VideoId { get; set; }
public string VideoName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace rita.Helpers
{
public static class Translit
{
private static readonly char[] cyrArr = {'А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П',
'Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я',
'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п',
'р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я'};
private static readonly string[] latArr = {"A","B","V","G","D","E","YO","ZH","Z","I","Y","K","L","M","N","O","P",
"R","S","T","U","F","H","C","CH","SH","SCH","~","Y","'","E","YU","YA",
"a","b","v","g","d","e","yo","zh","z","i","y","k","l","m","n","o","p",
"r","s","t","u","f","h","c","ch","sh","sch","","y","","e","yu","ya"};
private static Int32[] displacementArr;
private static Int32 minValue = Int32.MaxValue;
private static Int32 maxValue = Int32.MinValue;
static Translit()
{
Int32 val;
for (Int32 i = 0; i < cyrArr.Length; i++)
{
val = (Int32)cyrArr[i];
if (val < minValue) minValue = val;
if (maxValue < val) maxValue = val;
}
Int32 delta = maxValue - minValue;
displacementArr = new Int32[delta + 1];
for (Int32 i = 0; i < displacementArr.Length; i++)
displacementArr[i] = -1;
for (int i = 0; i < cyrArr.Length; i++)
{
val = (Int32)cyrArr[i];
delta = val - minValue;
displacementArr[delta] = i;
}
cyrArr = null;
}
public static string Translate(string sourseStr)
{
char[] sourseCArr = sourseStr.Replace("_", "").Replace("-", "").Replace(" ", "-").Replace(@"""", "").Replace(",", "").Replace(".", "").Replace(":", "").Replace(";", "").Replace("?", "").Replace("&", "").ToCharArray();
StringBuilder sb = new StringBuilder(sourseStr.Length * 2);
Int32 val;
Int32 displacement;
for (Int32 i = 0; i < sourseCArr.Length; i++)
{
val = (Int32)sourseCArr[i];
if (val < minValue || maxValue < val)
{
sb.Append(sourseCArr[i]);
}
else
{
displacement = displacementArr[val - minValue];
if (displacement < 0)
{
sb.Append(sourseCArr[i]);
}
else
{
sb.Append(latArr[displacement]);
}
}
}
return sb.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace WindowsFormsApp1
{
public partial class Form7 : Form
{
private Form1 Frm1;
string conString = "Server=167.86.73.27; Database=lcdatabase; User Id=sa; Password=locked123$";
string app_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath.ToString());
string app_dir_temp = System.IO.Path.GetDirectoryName(Application.ExecutablePath.ToString()) + "\\Temp\\";
public Form7(Form1 f1)
{
InitializeComponent();
Frm1 = f1;
InitGrids();
FindCompany("");
}
private void Form7_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
public void InitGrids()
{
// Company List
dataGridView4.RowCount = 0;
dataGridView4.ColumnCount = 3;
dataGridView4.Columns[0].HeaderText = "#";
dataGridView4.Columns[1].HeaderText = "Название компании";
dataGridView4.Columns[2].HeaderText = "db_id";
dataGridView4.Columns[0].Width = 40;
dataGridView4.Columns[1].Width = 260;
dataGridView4.Columns[2].Width = 130;
dataGridView4.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView4.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
//
// Adres list
dataGridView10.RowCount = 0;
dataGridView10.ColumnCount = 3;
dataGridView10.Columns[0].HeaderText = "#";
dataGridView10.Columns[1].HeaderText = "Адрес";
dataGridView10.Columns[2].HeaderText = "db_id";
dataGridView10.Columns[0].Width = 40;
dataGridView10.Columns[1].Width = 255;
dataGridView10.Columns[2].Width = 130;
dataGridView10.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView10.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
///
// Contacts list
dataGridView1.RowCount = 0;
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].HeaderText = "#";
dataGridView1.Columns[1].HeaderText = "Номер телефона";
dataGridView1.Columns[2].HeaderText = "db_id";
dataGridView1.Columns[0].Width = 40;
dataGridView1.Columns[1].Width = 150;
dataGridView1.Columns[2].Width = 130;
dataGridView1.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
///
// Port list
dataGridView5.RowCount = 0;
dataGridView5.ColumnCount = 4;
dataGridView5.Columns[0].HeaderText = "#";
dataGridView5.Columns[1].HeaderText = "Тип";
dataGridView5.Columns[2].HeaderText = "Пункт назначения";
dataGridView5.Columns[3].HeaderText = "db_id";
dataGridView5.Columns[0].Width = 40;
dataGridView5.Columns[1].Width = 50;
dataGridView5.Columns[2].Width = 200;
dataGridView5.Columns[3].Width = 150;
dataGridView5.Columns[3].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView5.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
///
// Notify Company List
dataGridView3.RowCount = 0;
dataGridView3.ColumnCount = 3;
dataGridView3.Columns[0].HeaderText = "#";
dataGridView3.Columns[1].HeaderText = "Название компании";
dataGridView3.Columns[2].HeaderText = "db_id";
dataGridView3.Columns[0].Width = 40;
dataGridView3.Columns[1].Width = 260;
dataGridView3.Columns[2].Width = 130;
dataGridView3.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView3.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
//
// Notify Adres list
dataGridView2.RowCount = 0;
dataGridView2.ColumnCount = 3;
dataGridView2.Columns[0].HeaderText = "#";
dataGridView2.Columns[1].HeaderText = "Адрес";
dataGridView2.Columns[2].HeaderText = "db_id";
dataGridView2.Columns[0].Width = 40;
dataGridView2.Columns[1].Width = 255;
dataGridView2.Columns[2].Width = 130;
dataGridView2.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
///
// Notify Contacts list
dataGridView6.RowCount = 0;
dataGridView6.ColumnCount = 3;
dataGridView6.Columns[0].HeaderText = "#";
dataGridView6.Columns[1].HeaderText = "Номер телефона";
dataGridView6.Columns[2].HeaderText = "db_id";
dataGridView6.Columns[0].Width = 40;
dataGridView6.Columns[1].Width = 150;
dataGridView6.Columns[2].Width = 130;
dataGridView6.Columns[2].Visible = false;
//
foreach (DataGridViewColumn col in dataGridView6.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.SortMode = DataGridViewColumnSortMode.NotSortable;
//col.HeaderCell.Style.Font = new Font("Arial", 12F, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
}
///
}
public void AddCompany(string company_nm)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = connection;
command1.CommandType = CommandType.Text;
command1.CommandText = "INSERT INTO crm_company (company) VALUES(@company_nm)";
command1.Parameters.AddWithValue("@company_nm", company_nm);
command1.ExecuteNonQuery();
connection.Close();
}
public void UpdateCompany(string company_nm, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE crm_company SET company='" + company_nm + "' WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
connection.Close();
}
public void DeleteCompany(string company_nm, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM crm_company WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
}
class CP_list
{
public int id { get; set; }
public string company { get; set; }
}
public void FindCompany(string company_nm)
{
List<CP_list> c_list = new List<CP_list>();
CP_list item = new CP_list();
//
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
//
if (company_nm == "")
{
using (connection = new SqlConnection(conString))
{
connection.Open();
using (command = new SqlCommand("SELECT * FROM crm_company ORDER BY id", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
item = new CP_list();
item.id = Convert.ToInt32(reader.GetValue(0).ToString());
item.company = reader.GetValue(1).ToString();
c_list.Add(item);
}
}
}
connection.Close();
}
}else{
using (connection = new SqlConnection(conString))
{
connection.Open();
using (command = new SqlCommand("SELECT * FROM crm_company WHERE company='" + company_nm + "' ORDER BY id", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
item = new CP_list();
item.id = Convert.ToInt32(reader.GetValue(0).ToString());
item.company = reader.GetValue(1).ToString();
c_list.Add(item);
}
}
}
connection.Close();
}
}
// Display
dataGridView4.RowCount = c_list.Count;
dataGridView4.RowHeadersWidth = 35;
for (int i = 0; i < c_list.Count; i++)
{
dataGridView4.Rows[i].Cells[0].Value = i + 1;
dataGridView4.Rows[i].Cells[1].Value = c_list[i].company;
dataGridView4.Rows[i].Cells[2].Value = c_list[i].id;
if (i % 2 == 0)
{
dataGridView4.Rows[i].Cells[0].Style.BackColor = Color.WhiteSmoke;
dataGridView4.Rows[i].Cells[1].Style.BackColor = Color.WhiteSmoke;
dataGridView4.Rows[i].Cells[2].Style.BackColor = Color.WhiteSmoke;
}
else
{
dataGridView4.Rows[i].Cells[0].Style.BackColor = Color.White;
dataGridView4.Rows[i].Cells[1].Style.BackColor = Color.White;
dataGridView4.Rows[i].Cells[2].Style.BackColor = Color.White;
}
}
}
private void button31_Click(object sender, EventArgs e)
{
if (textBox32.Text != "") {
AddCompany(textBox32.Text);
textBox32.Clear();
FindCompany("");
Frm1.FindCompanies();
}
}
private void button8_Click(object sender, EventArgs e)
{
FindCompany(textBox32.Text);
}
private void label56_Click(object sender, EventArgs e)
{
textBox32.Clear();
}
private void button22_Click(object sender, EventArgs e)
{
int selected = dataGridView4.CurrentCell.RowIndex;
dataGridView4.ReadOnly = false;
dataGridView4.CurrentCell = dataGridView4[1, selected];
dataGridView4.BeginEdit(true);
}
private void dataGridView4_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int column = e.ColumnIndex;
//
string company_nm = dataGridView4.Rows[row].Cells[column].Value.ToString();
int db_id = Convert.ToInt32(dataGridView4.Rows[row].Cells[column + 1].Value);
UpdateCompany(company_nm, db_id);
//
dataGridView4.ReadOnly = true;
}
private void button23_Click(object sender, EventArgs e)
{
try {
int selected = dataGridView4.CurrentCell.RowIndex;
int id_db = Convert.ToInt32(dataGridView4.Rows[selected].Cells[2].Value.ToString());
DeleteCompany("", id_db);
FindCompany(textBox32.Text);
Frm1.FindCompanies();
}
catch { }
}
////////// Adres
public void AddCompanyAdres(string adres, int c_id)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = connection;
command1.CommandType = CommandType.Text;
command1.CommandText = "INSERT INTO crm_adres (adres, company_id) VALUES(@adres, @c_id)";
command1.Parameters.AddWithValue("@adres", adres);
command1.Parameters.AddWithValue("@c_id", c_id);
command1.ExecuteNonQuery();
connection.Close();
}
public void UpdateCompanyAdres(string adres, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE crm_adres SET adres='" + adres + "' WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
connection.Close();
}
public void DeleteCompanyAdres(string company_nm, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM crm_adres WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
}
class CP_Adres_list
{
public int id { get; set; }
public string adres { get; set; }
}
public void FindCompanyAdres(int company_id)
{
List<CP_Adres_list> adres_list = new List<CP_Adres_list>();
CP_Adres_list item = new CP_Adres_list();
//
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
//
using (connection = new SqlConnection(conString))
{
connection.Open();
using (command = new SqlCommand("SELECT * FROM crm_adres WHERE company_id='" + company_id + "' ORDER BY id", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
item = new CP_Adres_list();
item.id = Convert.ToInt32(reader.GetValue(0).ToString());
item.adres = reader.GetValue(1).ToString();
adres_list.Add(item);
}
}
}
connection.Close();
}
// Display
dataGridView10.RowCount = adres_list.Count;
dataGridView10.RowHeadersWidth = 35;
for (int i = 0; i < adres_list.Count; i++)
{
dataGridView10.Rows[i].Cells[0].Value = i + 1;
dataGridView10.Rows[i].Cells[1].Value = adres_list[i].adres;
dataGridView10.Rows[i].Cells[2].Value = adres_list[i].id;
if (i % 2 == 0)
{
dataGridView10.Rows[i].Cells[0].Style.BackColor = Color.WhiteSmoke;
dataGridView10.Rows[i].Cells[1].Style.BackColor = Color.WhiteSmoke;
dataGridView10.Rows[i].Cells[2].Style.BackColor = Color.WhiteSmoke;
}
else
{
dataGridView10.Rows[i].Cells[0].Style.BackColor = Color.White;
dataGridView10.Rows[i].Cells[1].Style.BackColor = Color.White;
dataGridView10.Rows[i].Cells[2].Style.BackColor = Color.White;
}
}
}
private void button9_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
int selected = dataGridView4.CurrentCell.RowIndex;
int c_id = Convert.ToInt32(dataGridView4.Rows[selected].Cells[2].Value.ToString());
//
AddCompanyAdres(textBox1.Text, c_id);
textBox1.Clear();
//
FindCompanyAdres(c_id);
}
}
private void dataGridView4_SelectionChanged(object sender, EventArgs e)
{
try {
dataGridView10.RowCount = 0;
dataGridView1.RowCount = 0;
dataGridView5.RowCount = 0;
dataGridView3.RowCount = 0;
dataGridView2.RowCount = 0;
dataGridView6.RowCount = 0;
//
int selected = dataGridView4.CurrentCell.RowIndex;
int c_id = Convert.ToInt32(dataGridView4.Rows[selected].Cells[2].Value.ToString());
//
FindCompanyAdres(c_id);
FindCompanyDest(c_id);
}
catch{ }
}
private void button1_Click(object sender, EventArgs e)
{
int selected = dataGridView10.CurrentCell.RowIndex;
dataGridView10.ReadOnly = false;
dataGridView10.CurrentCell = dataGridView10[1, selected];
dataGridView10.BeginEdit(true);
}
private void dataGridView10_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int column = e.ColumnIndex;
//
string adres = dataGridView10.Rows[row].Cells[column].Value.ToString();
int db_id = Convert.ToInt32(dataGridView4.Rows[row].Cells[column + 1].Value);
UpdateCompanyAdres(adres, db_id);
//
dataGridView10.ReadOnly = true;
}
private void button5_Click(object sender, EventArgs e)
{
try
{
int selected = dataGridView10.CurrentCell.RowIndex;
int id_db = Convert.ToInt32(dataGridView10.Rows[selected].Cells[2].Value.ToString());
//
DeleteCompanyAdres("", id_db);
//
selected = dataGridView4.CurrentCell.RowIndex;
int c_id = Convert.ToInt32(dataGridView4.Rows[selected].Cells[2].Value.ToString());
//
FindCompanyAdres(c_id);
}
catch { }
}
private void label6_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
////////// Phones
public void AddCompanyPhones(string phone, int adres_id)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = connection;
command1.CommandType = CommandType.Text;
command1.CommandText = "INSERT INTO crm_phones (phone, adres_id) VALUES(@phone, @adr_id)";
command1.Parameters.AddWithValue("@phone", phone);
command1.Parameters.AddWithValue("@adr_id", adres_id);
command1.ExecuteNonQuery();
connection.Close();
}
public void UpdateCompanyPhones(string phone, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE crm_phones SET phone='" + phone + "' WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
connection.Close();
}
public void DeleteCompanyPhones(string company_nm, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM crm_phones WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
}
class CP_Phone_list
{
public int id { get; set; }
public string number { get; set; }
}
public void FindCompanyPhones(int adres_id)
{
List<CP_Phone_list> phone_list = new List<CP_Phone_list>();
CP_Phone_list item = new CP_Phone_list();
//
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
//
using (connection = new SqlConnection(conString))
{
connection.Open();
using (command = new SqlCommand("SELECT * FROM crm_phones WHERE adres_id='" + adres_id + "' ORDER BY id", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
item = new CP_Phone_list();
item.id = Convert.ToInt32(reader.GetValue(0).ToString());
item.number = reader.GetValue(1).ToString();
phone_list.Add(item);
}
}
}
connection.Close();
}
// Display
dataGridView1.RowCount = phone_list.Count;
dataGridView1.RowHeadersWidth = 35;
for (int i = 0; i < phone_list.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = i + 1;
dataGridView1.Rows[i].Cells[1].Value = phone_list[i].number;
dataGridView1.Rows[i].Cells[2].Value = phone_list[i].id;
if (i % 2 == 0)
{
dataGridView1.Rows[i].Cells[0].Style.BackColor = Color.WhiteSmoke;
dataGridView1.Rows[i].Cells[1].Style.BackColor = Color.WhiteSmoke;
dataGridView1.Rows[i].Cells[2].Style.BackColor = Color.WhiteSmoke;
}
else
{
dataGridView1.Rows[i].Cells[0].Style.BackColor = Color.White;
dataGridView1.Rows[i].Cells[1].Style.BackColor = Color.White;
dataGridView1.Rows[i].Cells[2].Style.BackColor = Color.White;
}
}
}
private void dataGridView10_SelectionChanged(object sender, EventArgs e)
{
try
{
int selected = dataGridView10.CurrentCell.RowIndex;
int adr_id = Convert.ToInt32(dataGridView10.Rows[selected].Cells[2].Value.ToString());
//
FindCompanyPhones(adr_id);
}
catch { }
}
private void button12_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
int selected = dataGridView10.CurrentCell.RowIndex;
int adr_id = Convert.ToInt32(dataGridView10.Rows[selected].Cells[2].Value.ToString());
//
AddCompanyPhones(textBox2.Text, adr_id);
textBox2.Clear();
//
FindCompanyPhones(adr_id);
}
}
private void button10_Click(object sender, EventArgs e)
{
int selected = dataGridView1.CurrentCell.RowIndex;
dataGridView1.ReadOnly = false;
dataGridView1.CurrentCell = dataGridView1[1, selected];
dataGridView1.BeginEdit(true);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int column = e.ColumnIndex;
//
string phone = dataGridView1.Rows[row].Cells[column].Value.ToString();
int db_id = Convert.ToInt32(dataGridView1.Rows[row].Cells[column + 1].Value);
UpdateCompanyPhones(phone, db_id);
//
dataGridView1.ReadOnly = true;
}
private void label7_Click(object sender, EventArgs e)
{
textBox2.Clear();
}
/////////////// Destination point
private void checkBox1_Click(object sender, EventArgs e)
{
checkBox1.Checked = true;
checkBox2.Checked = false;
}
private void checkBox2_Click(object sender, EventArgs e)
{
checkBox1.Checked = false;
checkBox2.Checked = true;
}
public void AddCompanyDestPoint(string type, string dest, int c_id)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = connection;
command1.CommandType = CommandType.Text;
command1.CommandText = "INSERT INTO crm_destination (type, dest_point, company_id) VALUES(@type, @dest, @c_id)";
command1.Parameters.AddWithValue("@type", type);
command1.Parameters.AddWithValue("@dest", dest);
command1.Parameters.AddWithValue("@c_id", c_id);
command1.ExecuteNonQuery();
connection.Close();
}
public void UpdateCompanyDestPoint(string dest, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE crm_destination SET dest_point='" + dest + "' WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
connection.Close();
}
public void DeleteCompanyDestPoint(string dest, int id_db)
{
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM crm_destination WHERE id='" + id_db + "'";
command.ExecuteNonQuery();
}
class CP_Dest_list
{
public int id { get; set; }
public string type { get; set; }
public string dest { get; set; }
}
public void FindCompanyDest(int company_id)
{
List<CP_Dest_list> dest_list = new List<CP_Dest_list>();
CP_Dest_list item = new CP_Dest_list();
//
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand command = new SqlCommand();
//
using (connection = new SqlConnection(conString))
{
connection.Open();
using (command = new SqlCommand("SELECT * FROM crm_destination WHERE company_id='" + company_id + "' ORDER BY id", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
item = new CP_Dest_list();
item.id = Convert.ToInt32(reader.GetValue(0).ToString());
item.type = reader.GetValue(1).ToString();
item.dest = reader.GetValue(2).ToString();
dest_list.Add(item);
}
}
}
connection.Close();
}
// Display
dataGridView5.RowCount = dest_list.Count;
dataGridView5.RowHeadersWidth = 35;
for (int i = 0; i < dest_list.Count; i++)
{
dataGridView5.Rows[i].Cells[0].Value = i + 1;
dataGridView5.Rows[i].Cells[1].Value = dest_list[i].type;
dataGridView5.Rows[i].Cells[2].Value = dest_list[i].dest;
dataGridView5.Rows[i].Cells[3].Value = dest_list[i].id;
if (i % 2 == 0)
{
dataGridView5.Rows[i].Cells[0].Style.BackColor = Color.WhiteSmoke;
dataGridView5.Rows[i].Cells[1].Style.BackColor = Color.WhiteSmoke;
dataGridView5.Rows[i].Cells[2].Style.BackColor = Color.WhiteSmoke;
dataGridView5.Rows[i].Cells[3].Style.BackColor = Color.WhiteSmoke;
}
else
{
dataGridView5.Rows[i].Cells[0].Style.BackColor = Color.White;
dataGridView5.Rows[i].Cells[1].Style.BackColor = Color.White;
dataGridView5.Rows[i].Cells[2].Style.BackColor = Color.White;
dataGridView5.Rows[i].Cells[3].Style.BackColor = Color.White;
}
}
}
private void button14_Click(object sender, EventArgs e)
{
if (textBox7.Text != "")
{
int selected = dataGridView4.CurrentCell.RowIndex;
int c_id = Convert.ToInt32(dataGridView4.Rows[selected].Cells[2].Value.ToString());
//
string type = "";
if (checkBox1.Checked == true) { type = "RW"; }
if (checkBox2.Checked == true) { type = "AIR"; }
AddCompanyDestPoint(type, textBox7.Text, c_id);
textBox7.Clear();
//
FindCompanyDest(c_id);
}
}
private void button2_Click(object sender, EventArgs e)
{
int selected = dataGridView5.CurrentCell.RowIndex;
dataGridView5.ReadOnly = false;
dataGridView5.CurrentCell = dataGridView5[2, selected];
dataGridView5.BeginEdit(true);
}
private void dataGridView5_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
int column = e.ColumnIndex;
//
string dest = dataGridView5.Rows[row].Cells[column].Value.ToString();
int db_id = Convert.ToInt32(dataGridView5.Rows[row].Cells[column + 1].Value);
UpdateCompanyDestPoint(dest, db_id);
//
dataGridView5.ReadOnly = true;
}
private void label8_Click(object sender, EventArgs e)
{
textBox7.Clear();
}
private void dataGridView5_SelectionChanged(object sender, EventArgs e)
{
}
private void button13_Click(object sender, EventArgs e)
{
try
{
int selected = dataGridView5.CurrentCell.RowIndex;
int id_db = Convert.ToInt32(dataGridView5.Rows[selected].Cells[3].Value.ToString());
//
DeleteCompanyDestPoint("", id_db);
}
catch { }
}
private void button11_Click(object sender, EventArgs e)
{
try
{
int selected = dataGridView1.CurrentCell.RowIndex;
int id_db = Convert.ToInt32(dataGridView1.Rows[selected].Cells[2].Value.ToString());
//
DeleteCompanyPhones("", id_db);
//
selected = dataGridView10.CurrentCell.RowIndex;
int adr_id = Convert.ToInt32(dataGridView10.Rows[selected].Cells[2].Value.ToString());
//
FindCompanyPhones(adr_id);
}
catch { }
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
namespace BO
{
public class Competitor : Personne
{
[Required]
public virtual Race Race { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public abstract class HandlerAspectAttribute : Attribute
{
public virtual void BeforeHandle(object command)
{}
}
}
|
public class Solution {
private void Helper(char[][] board, int i, int j) {
board[i][j] = '$';
if (i-1>=0 && board[i-1][j] == 'O') Helper(board, i-1, j);
if (i+1<board.Length && board[i+1][j] == 'O') Helper(board, i+1, j);
if (j-1>=0 && board[i][j-1] == 'O') Helper(board, i, j-1);
if (j+1<board[0].Length && board[i][j+1] == 'O') Helper(board, i, j+1);
}
public void Solve(char[][] board) {
if (board.Length == 0 || board[0].Length == 0 || board[0].Length == 1) return;
int m = board.Length, n = board[0].Length;
for (int i=0; i<n-1; i++) {
if (board[0][i] == 'O') Helper(board, 0, i);
if (board[m-1][i+1] == 'O') Helper(board, m-1, i+1);
}
for (int j=0; j<m-1; j++) {
if (board[j][n-1] == 'O') Helper(board, j, n-1);
if (board[j+1][0] == 'O') Helper(board, j+1, 0);
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
if (board[i][j] == '$') board[i][j] = 'O';
else board[i][j] = 'X';
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace KartObjects
{
[Serializable]
public class POSParameter:SimpleDbEntity
{
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public override string FriendlyName
{
get { return "Параметр кассового модуля"; }
}
public PosParameterType ParmeterType
{
get;
set;
}
public string stringValue
{
get;
set;
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public decimal? decimalValue
{
get
{
decimal d=0;
if (!decimal.TryParse(stringValue, out d)) return null;
return d;
}
set
{
stringValue = value.ToString();
}
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool? boolValue
{
get
{
bool b = false;
if (!bool.TryParse(stringValue, out b)) return null;
else return b;
}
set
{
stringValue = value.ToString();
}
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public string regexValue
{
get
{
if ((decimalValue != null) || (boolValue != null))
return null;
else
return stringValue;
}
set
{
stringValue = value;
}
}
/// <summary>
/// Идентификатор группы устройств
/// </summary>
public long IdPOSGroup
{
get;
set;
}
/// <summary>
/// Группа устройств
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public POSGroup POSGroup
{
get;
set;
}
}
}
|
namespace sc80wffmex.Models
{
using System.Collections.Generic;
using Sitecore.Data.Items;
using Sitecore.Links;
public class Menu
{
public List<MenuElement> All
{
get
{
var menuElements = new List<MenuElement>();
menuElements.Add(new MenuElement {Title = HomeItem.DisplayName, Url= LinkManager.GetItemUrl(HomeItem)});
foreach (Item element in HomeItem.GetChildren())
{
var myElement = new MenuElement
{
Title = element["Title"],
Url = Sitecore.Links.LinkManager.GetItemUrl(
Sitecore.Context.Database.GetItem(element.ID.ToString()))
};
menuElements.Add(myElement);
}
return menuElements;
}
}
public Item HomeItem
{
get
{
return Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
}
}
}
} |
using System;
namespace iSukces.Code.Interfaces
{
public partial class Auto
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public class ShouldSerializeInfoAttribute : Attribute
{
public ShouldSerializeInfoAttribute(string codeTemplate)
{
CodeTemplate = codeTemplate ?? throw new ArgumentNullException(nameof(codeTemplate));
}
/// <summary>
/// Code template, use {0} for value
/// </summary>
public string CodeTemplate { get; }
}
}
} |
using System;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
namespace RRExpress.Common.Extends {
public abstract class ConfigurationHelper {
/// <summary>
/// 獲取自訂配置,如果配置不存在,產生實體一個新對配置
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetSection<T>(string configFile = null) where T : ConfigurationSection, new() {
if (string.IsNullOrWhiteSpace(configFile))
configFile = typeof(T).Name;
var section = (T)ConfigurationManager.GetSection(typeof(T).Name);
if (section == null) {
section = new T();
var file = string.Format(@"{0}\{1}.config", AppDomain.CurrentDomain.BaseDirectory, configFile);
if (!File.Exists(file)) {
file = string.Format(@"{0}\bin\{1}.config", AppDomain.CurrentDomain.BaseDirectory, configFile);
}
if (File.Exists(file)) {
var raw = File.ReadAllText(file);
section.SectionInformation.ConfigSource = string.Format("{0}.config", configFile);
section.SectionInformation.SetRawXml(raw);
try {
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections.Remove(typeof(T).Name);
config.Sections.Add(typeof(T).Name, section);
} catch { }
try {
var config = WebConfigurationManager.OpenWebConfiguration(null);
config.Sections.Remove(typeof(T).Name);
config.Sections.Add(typeof(T).Name, section);
} catch {
}
}
}
return section;
}
}
}
|
namespace CSharp_Json
{
public enum EnumTipoPessoa
{
Fisica = 2,
Juridica = 1,
Estrangeiro = 3,
Rural = 4
}
}
|
// Copyright 2019 Serilog Contributors
//
// 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.
namespace Serilog.Events;
/// <summary>
/// A property associated with a <see cref="LogEvent"/>.
/// </summary>
/// <remarks>This type is currently internal, while we consider future directions for the logging pipeline, but should end up public
/// in future.</remarks>
readonly struct EventProperty
{
/// <summary>
/// No property.
/// </summary>
public static EventProperty None = default;
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
/// <summary>
/// The value of the property.
/// </summary>
public LogEventPropertyValue Value { get; }
/// <summary>
/// Construct a <see cref="LogEventProperty"/> with the specified name and value.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
/// <exception cref="ArgumentNullException">When <paramref name="name"/> is <code>null</code></exception>
/// <exception cref="ArgumentException">When <paramref name="name"/> is empty or only contains whitespace</exception>
/// <exception cref="ArgumentNullException">When <paramref name="value"/> is <code>null</code></exception>
public EventProperty(string name, LogEventPropertyValue value)
{
Guard.AgainstNull(value);
LogEventProperty.EnsureValidName(name);
Name = name;
Value = value;
}
/// <summary>
/// Permit deconstruction of the property into a name/value pair.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
public void Deconstruct(out string name, out LogEventPropertyValue value)
{
name = Name;
value = Value;
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return obj is EventProperty other && Equals(other);
}
/// <summary>Indicates whether this instance and a specified <see cref="EventProperty"/> are equal.</summary>
/// <param name="other">The <see cref="EventProperty"/> to compare with the current instance. </param>
/// <returns>
/// <see langword="true" /> if <paramref name="other" /> and this instance represent the same value; otherwise, <see langword="false" />. </returns>
public bool Equals(EventProperty other)
{
return string.Equals(Name, other.Name) && Equals(Value, other.Value);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Value != null ? Value.GetHashCode() : 0);
}
}
}
|
public class Solution {
private void helper(int nrow, int n, List<IList<string>> res, char[][] matrix, bool[] col, bool[] diag1, bool[] diag2) {
if (nrow == n) {
List<string> temp = new List<string>();
for (int i=0; i<n; i++) {
temp.Add(new string(matrix[i]));
}
res.Add(temp);
}
for (int ncol=0; ncol<n; ncol++) {
if (col[ncol] || diag1[nrow+n-1-ncol] || diag2[nrow+ncol]) continue;
matrix[nrow][ncol] = 'Q';
col[ncol] = true;
diag1[nrow+n-1-ncol] = true;
diag2[nrow+ncol] = true;
helper(nrow+1, n, res, matrix, col, diag1, diag2);
diag2[nrow+ncol] = false;
diag1[nrow+n-1-ncol] = false;
col[ncol] = false;
matrix[nrow][ncol] = '.';
}
}
public IList<IList<string>> SolveNQueens(int n) {
char [][] matrix = new char[n][];
for (int i=0; i<n; i++) {
matrix[i] = new char[n];
for (int j=0; j<n; j++) {
matrix[i][j] = '.';
}
}
bool[] col = new bool[n];
bool[] diag1 = new bool[2*n-1];
bool[] diag2 = new bool[2*n-1];
var res = new List<IList<string>>();
helper(0, n, res, matrix, col, diag1, diag2);
return res;
}
} |
using Properties.Core.Objects;
// ReSharper disable InconsistentNaming
namespace Properties.Infrastructure.Rightmove.Objects
{
public class RmrtdfRequestSendProperty
{
public RmrtdfNetwork network { get; }
public RmrtdfBranch branch { get; }
public RmrtdfProperty property { get; }
public RmrtdfRequestSendProperty(Property dbProperty)
{
network = new RmrtdfNetwork();
branch = new RmrtdfBranch();
property = new RmrtdfProperty(dbProperty);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SingLife.FacebookShareBonus.Model
{
internal class DescendingOrderOfPoliciesNumber : IPolicySortService
{
public IEnumerable<Policy> Sort(IEnumerable<Policy> policies)
{
IEnumerable<Policy> sortedPolicies = policies.OrderByDescending(s => s.PolicyNumber, StringComparer.CurrentCultureIgnoreCase);
return sortedPolicies;
}
}
} |
using ODL.ApplicationServices.DTOModel;
using ODL.ApplicationServices.DTOModel.Load;
namespace ODL.ApplicationServices.Validation
{
public class ResultatenhetInputValidator : Validator<ResultatenhetInputDTO>
{
// TODO: OBS! Vid persistering måste vi verifiera att vi har uppdateringsinfo ifall detta objekt redan finns i db, eftersom det då är en uppdatering!?
// Alt. låt uppdateringinfo vara NOT NULL (samma som skapandeinfo vid ny) ?
public ResultatenhetInputValidator()
{
RuleFor(resEnhet => resEnhet.Namn).NotNullOrWhiteSpace().WithinMaxLength(255);
RuleFor(resEnhet => resEnhet.KostnadsstalleNr).NotNullOrWhiteSpace();
RuleFor(resEnhet => resEnhet.Typ).NotNullOrWhiteSpace().WithinMaxLength(1);
RequireMetadata();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Gobiner.PageRank
{
public class PageRankGenerator
{
/// <summary>
///
/// </summary>
/// <param name="linkMatrix">
/// linkMatrix[i] contains the indices of vertices j that link to i
/// </param>
/// <param name="alpha">
/// double in (0,1) that serves as a damping factor
/// </param>
public static double[] DoIt(int[][] linkMatrix, double alpha, double epsilon, int stepSize, int timeoutIterations)
{
Debug.Assert(linkMatrix.Length > 0);
var N = linkMatrix.Length; // N is the number of vertices
var numOutgoingLinks = new int[N]; //numLinks[i] contains the number of links going out from vertex i
for (int i = 0; i < N; i++)
{
foreach(var j in linkMatrix[i])
{
numOutgoingLinks[j] += 1; // counting the number of times j appears i.e. the number of outbound links
}
}
var linklessVertices = numOutgoingLinks.Where(x => x==0);
var M = linklessVertices.Count(); // M holds the number of vertices with 0 outbound links
var newPR = new double[N]; // holds the PageRank for each vertex
var oldPR = new double[N];
for (int i = 0; i < N; i++)
{
newPR[i] = 1.0 / N;
oldPR[i] = 1.0 / N;
}
bool done = false;
while (!done && timeoutIterations > 0)
{
for (int step = 0; step < stepSize; step++)
{
var tmp = newPR;
newPR = oldPR;
oldPR = tmp;
var oneIv = (1 - alpha) / N * oldPR.Sum();
var oneAv = 0.0;
if (M > 0) oneAv = alpha / N * oldPR.WhereIndices(linklessVertices).Sum();
for (int i = 0; i < N; i++)
{
var h = 0.0;
if (linkMatrix[i].Any())
{
h = (1.0 - alpha) / N + alpha * linkMatrix[i].Select(x => oldPR[x] / numOutgoingLinks[x]).Sum();
}
newPR[i] = h + oneAv + oneIv;
}
}
var sum = newPR.Sum();
for (int i = 0; i < N; i++) newPR[i] /= sum; // normalize
for (int i = 0; i < N; i++) oldPR[i] /= sum; // normalize
var diff = new double[N];
for (int i = 0; i < N; i++) diff[i] = newPR[i] - oldPR[i];
done = diff.Sum() < epsilon;
timeoutIterations--;
}
return newPR;
}
}
}
|
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* 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.
*/
#endregion
using System;
using Common.Logging;
using Spring.Context;
using Spring.Messaging.Amqp.Core;
using Spring.Messaging.Amqp.Rabbit.Connection;
using Spring.Objects.Factory;
using Spring.Threading.AtomicTypes;
using Spring.Util;
namespace Spring.Messaging.Amqp.Rabbit.Core
{
/// <summary>
/// RabbitMQ implementation of portable AMQP administrative operations for AMQP >= 0.8
/// </summary>
/// <author>Mark Pollack</author>
/// <author>Joe Fitzgerald</author>
public class RabbitAdmin : IAmqpAdmin, IInitializingObject
{
/// <summary>
/// The logger.
/// </summary>
protected readonly ILog logger = LogManager.GetLogger(typeof(RabbitAdmin));
/// <summary>
/// The rabbit template.
/// </summary>
private RabbitTemplate rabbitTemplate;
/// <summary>
/// The running flag.
/// </summary>
private volatile bool running = false;
/// <summary>
/// The auto startup flag.
/// </summary>
private volatile bool autoStartup = true;
/// <summary>
/// The application context.
/// </summary>
private volatile IApplicationContext applicationContext;
/// <summary>
/// The lifecycle monitor.
/// </summary>
private readonly object lifecycleMonitor = new object();
/// <summary>
/// The connection factory.
/// </summary>
private IConnectionFactory connectionFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RabbitAdmin"/> class.
/// </summary>
/// <param name="connectionFactory">The connection factory.</param>
public RabbitAdmin(IConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
AssertUtils.ArgumentNotNull(connectionFactory, "ConnectionFactory is required");
this.rabbitTemplate = new RabbitTemplate(connectionFactory);
}
/// <summary>
/// Sets a value indicating whether AutoStartup.
/// </summary>
public bool AutoStartup
{
get { return this.autoStartup; }
set { this.autoStartup = value; }
}
/// <summary>
/// Sets ApplicationContext.
/// </summary>
public IApplicationContext ApplicationContext
{
set { this.applicationContext = value; }
}
/// <summary>
/// Gets RabbitTemplate.
/// </summary>
public RabbitTemplate RabbitTemplate
{
get { return this.rabbitTemplate; }
}
#region Implementation of IAmqpAdmin
/// <summary>
/// Declares the exchange.
/// </summary>
/// <param name="exchange">The exchange.</param>
public void DeclareExchange(IExchange exchange)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
this.DeclareExchanges(channel, exchange);
return null;
});
}
/// <summary>
/// Deletes the exchange.
/// </summary>
/// <remarks>
/// Look at implementation specific subclass for implementation specific behavior, for example
/// for RabbitMQ this will delete the exchange without regard for whether it is in use or not.
/// </remarks>
/// <param name="exchangeName">
/// Name of the exchange.
/// </param>
/// <returns>
/// The result of deleting the exchange.
/// </returns>
public bool DeleteExchange(string exchangeName)
{
return this.rabbitTemplate.Execute(delegate(RabbitMQ.Client.IModel channel)
{
try
{
channel.ExchangeDelete(exchangeName, false);
}
catch (Exception e)
{
return false;
}
return true;
});
}
/// <summary>
/// Declares the queue.
/// </summary>
/// <param name="queue">The queue.</param>
public void DeclareQueue(Queue queue)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
this.DeclareQueues(channel, queue);
return null;
});
}
/// <summary>
/// Declares a queue whose name is automatically named by the server. It is created with
/// exclusive = true, autoDelete=true, and durable = false.
/// </summary>
/// <returns>The queue.</returns>
public Queue DeclareQueue()
{
var queueName = this.rabbitTemplate.Execute(channel => channel.QueueDeclare());
var q = new Queue(queueName, true, true, false);
return q;
}
/// <summary>
/// Deletes the queue, without regard for whether it is in use or has messages on it
/// </summary>
/// <param name="queueName">
/// Name of the queue.
/// </param>
/// <returns>
/// The result of deleting the queue.
/// </returns>
public bool DeleteQueue(string queueName)
{
return this.rabbitTemplate.Execute(delegate(RabbitMQ.Client.IModel channel)
{
try
{
channel.QueueDelete(queueName);
}
catch (Exception e)
{
return false;
}
return true;
});
}
/// <summary>
/// Deletes the queue.
/// </summary>
/// <param name="queueName">Name of the queue.</param>
/// <param name="unused">if set to <c>true</c> the queue should be deleted only if not in use.</param>
/// <param name="empty">if set to <c>true</c> the queue should be deleted only if empty.</param>
public void DeleteQueue(string queueName, bool unused, bool empty)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
channel.QueueDelete(queueName, unused, empty);
return null;
});
}
/// <summary>
/// Purges the queue.
/// </summary>
/// <param name="queueName">Name of the queue.</param>
/// <param name="noWait">if set to <c>true</c> [no wait].</param>
public void PurgeQueue(string queueName, bool noWait)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
channel.QueuePurge(queueName);
return null;
});
}
/// <summary>
/// Declare the binding.
/// </summary>
/// <param name="binding">
/// The binding.
/// </param>
public void DeclareBinding(Binding binding)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
this.DeclareBindings(channel, binding);
return null;
});
}
/// <summary>
/// Remove a binding of a queue to an exchange.
/// </summary>
/// <param name="binding">Binding to remove.</param>
public void RemoveBinding(Binding binding)
{
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
if (binding.IsDestinationQueue())
{
channel.QueueUnbind(binding.Destination, binding.Exchange, binding.RoutingKey, binding.Arguments);
}
else
{
channel.ExchangeUnbind(binding.Destination, binding.Exchange, binding.RoutingKey, binding.Arguments);
}
return null;
});
}
#endregion
#region Implementation of IInitializingObject
/// <summary>
/// Actions to perform after properties are set.
/// </summary>
/// <exception cref="InvalidOperationException">
/// </exception>
public void AfterPropertiesSet()
{
lock (this.lifecycleMonitor)
{
if (this.running || !this.autoStartup)
{
return;
}
connectionFactory.AddConnectionListener(new AdminConnectionListener(this));
this.running = true;
}
if (this.connectionFactory == null)
{
throw new InvalidOperationException("'ConnectionFactory' is required.");
}
this.rabbitTemplate = new RabbitTemplate(connectionFactory);
}
/// <summary>
/// Declares all the exchanges, queues and bindings in the enclosing application context, if any. It should be safe
/// (but unnecessary) to call this method more than once.
/// </summary>
public void Initialize()
{
if (this.applicationContext == null)
{
if (this.logger.IsDebugEnabled)
{
this.logger.Debug("no ApplicationContext has been set, cannot auto-declare Exchanges, Queues, and Bindings");
}
return;
}
this.logger.Debug("Initializing declarations");
var exchanges = this.applicationContext.GetObjectsOfType(typeof(IExchange)).Values;
var queues = this.applicationContext.GetObjectsOfType(typeof(Queue)).Values;
var bindings = this.applicationContext.GetObjectsOfType(typeof(Binding)).Values;
foreach (IExchange exchange in exchanges)
{
if (!exchange.Durable)
{
this.logger.Warn("Auto-declaring a non-durable Exchange (" + exchange.Name +
"). It will be deleted by the broker if it shuts down, and can be redeclared by closing and reopening the connection.");
}
if (exchange.AutoDelete)
{
this.logger.Warn("Auto-declaring an auto-delete Exchange ("
+ exchange.Name
+
"). It will be deleted by the broker if not in use (if all bindings are deleted), but will only be redeclared if the connection is closed and reopened.");
}
}
foreach (Queue queue in queues)
{
if (!queue.Durable)
{
this.logger.Warn("Auto-declaring a non-durable Queue ("
+ queue.Name
+ "). It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.");
}
if (queue.AutoDelete)
{
this.logger.Warn("Auto-declaring an auto-delete Queue ("
+ queue.Name
+ "). It will be deleted deleted by the broker if not in use, and all messages will be lost. Redeclared when the connection is closed and reopened.");
}
if (queue.Exclusive)
{
this.logger.Warn("Auto-declaring an exclusive Queue ("
+ queue.Name
+ "). It cannot be accessed by consumers on another connection, and will be redeclared if the connection is reopened.");
}
}
this.rabbitTemplate.Execute<object>(delegate(RabbitMQ.Client.IModel channel)
{
var exchangeArray = new IExchange[exchanges.Count];
var queueArray = new Queue[queues.Count];
var bindingArray = new Binding[bindings.Count];
exchanges.CopyTo(exchangeArray, 0);
queues.CopyTo(queueArray, 0);
bindings.CopyTo(bindingArray, 0);
this.DeclareExchanges(channel, exchangeArray);
this.DeclareQueues(channel, queueArray);
this.DeclareBindings(channel, bindingArray);
return null;
});
this.logger.Debug("Declarations finished");
}
#endregion
/// <summary>
/// Declare the exchanges.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="exchanges">
/// The exchanges.
/// </param>
private void DeclareExchanges(RabbitMQ.Client.IModel channel, params IExchange[] exchanges)
{
foreach (var exchange in exchanges)
{
if (this.logger.IsDebugEnabled)
{
this.logger.Debug("declaring Exchange '" + exchange.Name + "'");
}
channel.ExchangeDeclare(exchange.Name, exchange.ExchangeType, exchange.Durable, exchange.AutoDelete, exchange.Arguments);
}
}
/// <summary>
/// Declare the queues.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="queues">
/// The queues.
/// </param>
private void DeclareQueues(RabbitMQ.Client.IModel channel, params Queue[] queues)
{
foreach (var queue in queues)
{
if (!queue.Name.StartsWith("amq."))
{
if (this.logger.IsDebugEnabled)
{
this.logger.Debug("Declaring Queue '" + queue.Name + "'");
}
channel.QueueDeclare(queue.Name, queue.Durable, queue.Exclusive, queue.AutoDelete, queue.Arguments);
}
else if (this.logger.IsDebugEnabled)
{
this.logger.Debug("Queue with name that starts with 'amq.' cannot be declared.");
}
}
}
/// <summary>
/// Declare the bindings.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="bindings">
/// The bindings.
/// </param>
private void DeclareBindings(RabbitMQ.Client.IModel channel, params Binding[] bindings)
{
foreach (var binding in bindings)
{
if (this.logger.IsDebugEnabled)
{
this.logger.Debug("Binding destination [" + binding.Destination + " (" + binding.BindingDestinationType
+ ")] to exchange [" + binding.Exchange + "] with routing key [" + binding.RoutingKey
+ "]");
}
if (binding.IsDestinationQueue())
{
channel.QueueBind(binding.Destination, binding.Exchange, binding.RoutingKey, binding.Arguments);
}
else
{
channel.ExchangeBind(binding.Destination, binding.Exchange, binding.RoutingKey, binding.Arguments);
}
}
}
}
/// <summary>
/// An admin connection listener.
/// </summary>
internal class AdminConnectionListener : IConnectionListener
{
/// <summary>
/// The outer rabbitadmin.
/// </summary>
private readonly RabbitAdmin outer;
/// <summary>
/// Prevent stack overflow...
/// </summary>
private AtomicBoolean initializing = new AtomicBoolean(false);
/// <summary>
/// Initializes a new instance of the <see cref="AdminConnectionListener"/> class.
/// </summary>
/// <param name="outer">
/// The outer.
/// </param>
public AdminConnectionListener(RabbitAdmin outer)
{
this.outer = outer;
}
/// <summary>
/// Actions to perform on create.
/// </summary>
/// <param name="connection">
/// The connection.
/// </param>
public void OnCreate(IConnection connection)
{
if (!this.initializing.CompareAndSet(false, true))
{
// If we are already initializing, we don't need to do it again...
return;
}
try
{
/*
* ...but it is possible for this to happen twice in the same ConnectionFactory (if more than
* one concurrent Connection is allowed). It's idempotent, so no big deal (a bit of network
* chatter). In fact it might even be a good thing: exclusive queues only make sense if they are
* declared for every connection. If anyone has a problem with it: use auto-startup="false".
*/
this.outer.Initialize();
}
finally
{
this.initializing.CompareAndSet(true, false);
}
}
/// <summary>
/// Actions to perform on close.
/// </summary>
/// <param name="connection">
/// The connection.
/// </param>
public void OnClose(IConnection connection)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace UseFul.Uteis
{
public static class ImportaExcel
{
/// <summary>
/// Recebe o caminho do arquivo e o nome da Planilha excel e retorna em um datatable
/// </summary>
/// <param name="Path">Caminho do Arquivo</param>
/// <param name="PlanName">Nome da Planilha</param>
public static DataTable ImportaExel(string Path, string PlanName)
{
string cnnString = string.Empty;
if (Path.Substring(Path.Length - 1, 1).ToUpper() == "X")
cnnString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES';", Path);
else
cnnString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;""", Path);
string sql = "select * from [{0}$]";
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(cnnString);
System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(String.Format(sql, PlanName), cnn);
DataSet ds = new DataSet();
var dt = new DataTable();
try
{
cnn.Open();
da.Fill(ds);
dt = ds.Tables[0];
}
finally
{
cnn.Close();
cnn.Dispose();
da.Dispose();
ds.Dispose();
}
return dt;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Linq;
using UnityEngine.SceneManagement;
using System;
public class NetworkManager : Photon.PunBehaviour
{
#region Public Variables
// pun standard settings
public PhotonLogLevel Loglevel = PhotonLogLevel.Informational;
public byte MaxPlayersPerRoom = 2;
// Menu panels
public GameObject mainMenuPanel;
public GameObject userNameInputPanel;
public GameObject lobbyPanel;
public GameObject roomNameInputPanel;
public GameObject roomPanel;
// stuff to create tables
public GridLayoutGroup roomGridLayout;
public Button joinButton;
public Text gameName;
public Text playerCount;
public Text gameType;
public GridLayoutGroup playerGridLayout;
public Text playerName;
public Dropdown playerRole;
public Dropdown playerTeam;
public Toggle playerReady;
public Dropdown maxPlayerCount;
public Dropdown gameMode;
#endregion
#region Private Variables
const string _gameVersion = "0.0.1";
public Dictionary<RoomInfo, LobbyGui> lobby;
public Dictionary<RoomInfo, List<RoomGui>> rooms;
#endregion
#region MonoBehaviour CallBacks
private void Awake()
{
PhotonNetwork.autoJoinLobby = false;
PhotonNetwork.automaticallySyncScene = true;
PhotonNetwork.logLevel = Loglevel;
lobby = new Dictionary<RoomInfo, LobbyGui>();
rooms = new Dictionary<RoomInfo, List<RoomGui>>();
}
void Start()
{
lobbyPanel.SetActive(false);
mainMenuPanel.SetActive(true);
}
#endregion
#region Photon.PunBehaviour CallBacks
public override void OnConnectedToMaster()
{
Debug.LogWarning("Join Lobby");
PhotonNetwork.JoinLobby();
}
public override void OnDisconnectedFromPhoton()
{
lobbyPanel.SetActive(false);
mainMenuPanel.SetActive(true);
Debug.LogWarning("OnDisconnectedFromPhoton() was called by PUN");
}
public override void OnJoinedRoom()
{
lobbyPanel.SetActive(false);
roomPanel.SetActive(true);
string playerName = PhotonNetwork.player.NickName;
int playerID = PhotonNetwork.player.ID;
photonView.RPC("RPCUpdateRoom", PhotonTargets.AllBufferedViaServer, playerName, playerID);
}
public override void OnLeftRoom()
{
roomPanel.SetActive(false);
lobbyPanel.SetActive(true);
}
public override void OnPhotonMaxCccuReached()
{
base.OnPhotonMaxCccuReached();
}
public override void OnReceivedRoomListUpdate()
{
Debug.LogWarning("OnReceivedRoomListUpdate");
CheckForNewLobbyEntries();
CheckForOldLobbyEntries();
}
#endregion
#region Helper Methods
public void EnterName()
{
userNameInputPanel.SetActive(false);
lobbyPanel.SetActive(true);
PhotonNetwork.player.NickName = userNameInputPanel.transform.GetChild(1).GetChild(2).GetComponent<Text>().text;
}
public void EnterNameCancel()
{
userNameInputPanel.SetActive(false);
mainMenuPanel.SetActive(true);
}
public void Connect()
{
userNameInputPanel.SetActive(true);
mainMenuPanel.SetActive(false);
if (!PhotonNetwork.connected)
PhotonNetwork.ConnectUsingSettings(_gameVersion);
}
public void Disconnect()
{
PhotonNetwork.Disconnect();
}
public void CreateNewRoom()
{
lobbyPanel.SetActive(false);
roomNameInputPanel.SetActive(true);
}
public void CreateNewRoomCancel()
{
roomNameInputPanel.SetActive(false);
lobbyPanel.SetActive(true);
}
public void ApplyRoom()
{
string roomName = roomNameInputPanel.transform.GetChild(1).GetChild(2).GetComponent<Text>().text;
PhotonNetwork.CreateRoom(roomName, new RoomOptions() { MaxPlayers = MaxPlayersPerRoom }, null);
roomNameInputPanel.SetActive(false);
roomPanel.SetActive(true);
}
public static void JoinRoom(string roomName)
{
Debug.LogWarning(roomName);
PhotonNetwork.JoinRoom(roomName);
}
public void LeaveRoom()
{
try
{
if (rooms != null)
{
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
roomGui.destroyComponents();
}
rooms.Clear();
}
photonView.RPC("RPCLeaveRoom", PhotonTargets.Others, PhotonNetwork.player.ID);
PhotonNetwork.LeaveRoom();
}
catch (ArgumentNullException) { }
}
private void CheckForNewLobbyEntries()
{
foreach (RoomInfo element in PhotonNetwork.GetRoomList())
{
LobbyGui lobbyGui;
if (!lobby.Keys.Contains(element))
{
lobbyGui = new LobbyGui(joinButton, gameName, playerCount, gameType);
lobbyGui.joinButtonAddListener(element.Name);
lobby.Add(element, lobbyGui);
}
foreach (RoomInfo roomInfo in lobby.Keys)
{
if (roomInfo.Equals(element))
{
lobby.TryGetValue(roomInfo, out lobbyGui);
lobbyGui.updateValues(element);
lobbyGui.attachToParent(roomGridLayout);
break;
}
}
}
}
private void CheckForOldLobbyEntries()
{
List<RoomInfo> oldRooms = new List<RoomInfo>();
foreach (RoomInfo roomInfo in lobby.Keys)
{
if(!PhotonNetwork.GetRoomList().Contains(roomInfo))
{
oldRooms.Add(roomInfo);
}
}
foreach (RoomInfo roomInfo in oldRooms)
{
lobby[roomInfo].destroyComponents();
lobby.Remove(roomInfo);
}
}
public void CheckForGameStart()
{
byte roleCounter = 0;
List<RoomGui> roomGuis = rooms[PhotonNetwork.room];
foreach (RoomGui roomGui in roomGuis)
{
if (roomGui.playerReady.isOn)
{
if (roomGui.playerRole.value == 1)
roleCounter++;
else if (roomGui.playerRole.value == 2)
roleCounter--;
}
else
{
roleCounter = 1;
break;
}
}
if (roleCounter == 0)
{
string levelName = "Level_01";
photonView.RPC("RPCStartGame", PhotonTargets.AllBufferedViaServer, levelName);
}
}
private void ChangeRoomMaxPlayers(int pMaxPlayerCountValue)
{
if ((pMaxPlayerCountValue + 1) * 2 >= PhotonNetwork.room.PlayerCount)
{
PhotonNetwork.room.MaxPlayers = 2 + pMaxPlayerCountValue * 2;
photonView.RPC("RPCChangeRoomMaxPlayers", PhotonTargets.OthersBuffered, pMaxPlayerCountValue);
}
}
private void ChangePlayerRole(int pPlayerRoleValue, int pPlayerID)
{
photonView.RPC("RPCChangePlayerRole", PhotonTargets.OthersBuffered, pPlayerRoleValue, pPlayerID);
}
private void ChangePlayerTeam(int pPlayerTeamValue, int pPlayerID)
{
photonView.RPC("RPCChangePlayerTeam", PhotonTargets.OthersBuffered, pPlayerTeamValue, pPlayerID);
}
private void ChangePlayerReady(bool pPlayerReadyValue, int pPlayerID)
{
photonView.RPC("RPCChangePlayerReady", PhotonTargets.OthersBuffered, pPlayerReadyValue, pPlayerID);
}
#endregion
#region PunRPC
[PunRPC]
private void RPCUpdateRoom(string pPlayerName, int pPlayerID)
{
if (!rooms.ContainsKey(PhotonNetwork.room))
{
rooms.Add(PhotonNetwork.room, new List<RoomGui>());
}
RoomGui roomGui = new RoomGui(playerName, playerRole, playerTeam, playerReady, pPlayerID);
roomGui.playerName.text = pPlayerName;
roomGui.playerRole.onValueChanged.AddListener(delegate { ChangePlayerRole(roomGui.playerRole.value, pPlayerID); });
roomGui.playerTeam.onValueChanged.AddListener(delegate { ChangePlayerTeam(roomGui.playerTeam.value, pPlayerID); });
roomGui.playerReady.onValueChanged.AddListener(delegate { ChangePlayerReady(roomGui.playerReady.isOn, pPlayerID); });
maxPlayerCount.onValueChanged.AddListener(delegate { ChangeRoomMaxPlayers(maxPlayerCount.value); });
List<RoomGui> roomGuiList = rooms[PhotonNetwork.room];
roomGuiList.Add(roomGui);
roomGui.attachToParent(playerGridLayout);
if (PhotonNetwork.player.ID != pPlayerID)
{
roomGui.playerRole.interactable = false;
roomGui.playerTeam.interactable = false;
roomGui.playerReady.interactable = false;
}
}
[PunRPC]
private void RPCChangeRoomMaxPlayers(int pMaxPlayerCountValue)
{
maxPlayerCount.value = pMaxPlayerCountValue;
}
[PunRPC]
private void RPCChangePlayerRole(int pRoleValue, int pPlayerID)
{
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
if (roomGui.playerID == pPlayerID)
{
roomGui.playerRole.value = pRoleValue;
}
}
}
[PunRPC]
private void RPCChangePlayerTeam(int pTeamValue, int pPlayerID)
{
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
if (roomGui.playerID == pPlayerID)
{
roomGui.playerTeam.value = pTeamValue;
}
}
}
[PunRPC]
private void RPCChangePlayerReady(bool pReadyValue, int pPlayerID)
{
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
if (roomGui.playerID == pPlayerID)
{
roomGui.playerReady.isOn = pReadyValue;
}
}
}
[PunRPC]
private void RPCStartGame(string pLevelName)
{
int playerType = 0;
string playerTypeText = "";
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
if (roomGui.playerID == PhotonNetwork.player.ID)
{
playerType = roomGui.playerRole.value;
break;
}
}
switch (playerType)
{
case 1:
playerTypeText = "God";
break;
case 2:
playerTypeText = "Priest";
break;
default:
playerTypeText = "Noob";
break;
}
ExitGames.Client.Photon.Hashtable role = new ExitGames.Client.Photon.Hashtable();
role.Add("role", playerTypeText);
PhotonNetwork.player.SetCustomProperties(role);
SceneManager.LoadScene("Level_01");
}
[PunRPC]
private void RPCLeaveRoom(int pPlayerID)
{
RoomGui roomGuiTmp = null;
foreach (RoomGui roomGui in rooms[PhotonNetwork.room])
{
if (roomGui.playerID == pPlayerID)
{
roomGuiTmp = roomGui;
roomGui.destroyComponents();
break;
}
}
Debug.LogWarning("Roomgui:" + roomGuiTmp.playerID);
rooms[PhotonNetwork.room].Remove(roomGuiTmp);
}
#endregion
}
|
using System;
namespace RepositoryCommon
{
public class ComparedInfo
{
public string id { get; set; }
public string name { get; set; }
public string nation { get; set; }
public string nationality { get; set; }
public string address { get; set; }
public string idaddress { get; set; }
public string operatingagency { get; set; }
public string issuer { get; set; }
public string gender { get; set; }
public string birthday { get; set; }
public string startdate { get; set; }
public string enddate { get; set; }
public byte[] idphoto { get; set; }
public byte[] capturephoto { get; set; }
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using APISaudacao.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "APISaudacao", Description = "Teste com Minimal APIs", Version = "v1" });
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "APISaudacao v1");
});
app.MapGet("/Mensagem", (string nome) => new Mensagem()
{
Saudacao = $"Olá {nome ?? "Anônimo(a)"}!"
});
app.Run(); |
using Controller.DrugAndTherapy;
using Model.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Clinic_Health
{
/// <summary>
/// Interaction logic for IngredientsOfDrug.xaml
/// </summary>
public partial class IngredientsOfDrug : Window
{
private static DrugController dc = new DrugController();
public IngredientsOfDrug(Drug drug)
{
InitializeComponent();
List<Ingredient> ingredients = drug.ingredient;
List<string> names = new List<string>();
foreach (Ingredient i in ingredients)
{
names.Add(i.Name);
}
listBox2.DataContext = names;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
|
using System;
namespace MalwareScanner.Contracts
{
public class MalwareScanningException : Exception
{
public MalwareScanningException(string message) : base(message)
{
}
public MalwareScanningException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
|
using Object = StardewValley.Object;
namespace StardewValleyMP.States
{
public class ObjectState : State
{
public bool hasSomething;
public int ready;
public ObjectState(Object obj)
{
hasSomething = (obj.heldObject != null);
ready = obj.minutesUntilReady;
}
public override bool isDifferentEnoughFromOldStateToSend(State obj)
{
ObjectState state = obj as ObjectState;
if (state == null) return false;
if (hasSomething != state.hasSomething) return true;
if (ready > state.ready) return true;
return false;
}
public override string ToString()
{
return base.ToString() + " " + hasSomething + " " + ready;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace AngularWebApiAuthExample.WebApis.Controllers
{
//[Authorize]
[RoutePrefix("api/People")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PeopleController : ApiController
{
private List<Person> people;
public PeopleController()
{
people = new List<Person>
{
new Person
{
Id = 1,
FirstName = "John",
LastName = "Doe",
Age = 35
},
new Person
{
Id = 2,
FirstName = "Mary",
LastName = "Jane",
Age = 19
},
new Person
{
Id = 3,
FirstName = "Longs",
LastName = "Peak",
Age = 6425
}
};
}
[HttpGet]
[Route("List")]
[Authorize(Roles = "Admin, User")]
public List<Person> List()
{
return people;
}
/// <summary>
/// You could return IHttpActionResult also
/// When using IHttpActionResult you would: return Ok(person) Or return NotFound();
/// The reason I don't use that is that the documentation auto produced will not know
/// the data type returned.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
[Route("Get/{id:int}")]
[Authorize(Roles = "User")]
public Person Get(int id)
{
var person = people.FirstOrDefault(x => x.Id == id);
if (person == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return person;
}
}
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace QuizMe {
[Serializable]
public class Point {
public int X { get; set; }
public int Y { get; set; }
}
[Serializable]
public class Snake {
List<Point> body = new List<Point>();
public ConsoleColor BodyColor { get; set; }
public Snake() {
body.Add(new Point { X = 47, Y = 4});
body.Add(new Point { X = 48, Y = 4 });
body.Add(new Point { X = 49, Y = 4 });
body.Add(new Point { X = 50, Y = 4 });
body.Add(new Point { X = 51, Y = 4 });
BodyColor = ConsoleColor.Red;
}
public void Draw() {
foreach(var el in body) {
Console.SetCursorPosition(el.X, el.Y);
Console.ForegroundColor = BodyColor;
Console.Write("@");
}
}
}
class Program {
static void Main(string[] args) {
Console.CursorVisible = false;
Snake sn;
XmlSerializer xSer = new XmlSerializer(typeof(Snake));
using(FileStream fs = new FileStream(@"C:\Users\Kirill\Desktop\snake.xml", FileMode.OpenOrCreate)) {
sn = xSer.Deserialize(fs) as Snake;
}
sn.Draw();
Console.ReadKey();
}
}
}
|
using Semicolon.Attributes;
using System.ComponentModel.DataAnnotations;
namespace TradeProcessing.Model
{
public class Trade
{
[CsvColumn("Trader")]
public string TraderId { get; set; }
[CsvColumn("TSO name")]
public string TSO { get; set; }
[CsvColumn("EIC")]
public string EIC { get; set; }
[CsvColumn("B/S")]
public string BuySell { get; set; }
[CsvColumn("Product")]
public string Product { get; set; }
[CsvColumn("Contract type")]
public string Contract { get; set; }
[CsvColumn("Qantity")]
public decimal Quantity { get; set; }
[CsvColumn("Price")]
public decimal Price { get; set; }
[CsvColumn("Curr")]
public string Currency { get; set; }
[CsvColumn("Act")]
public string Act { get; set; }
[CsvColumn("Text")]
public string Text { get; set; }
[CsvColumn("State")]
public string State { get; set; }
[CsvColumn("Order No")]
public string OrderNo { get; set; }
[Key]
[CsvColumn("Trade No")]
public string TradeNo { get; set; }
[CsvColumn("P/O")]
public string P_O { get; set; }
[CsvColumn("Date/Time")]
public string DateTime { get; set; }
[CsvColumn("BG")]
public string BG { get; set; }
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace IotHubSync.Logic
{
using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Shared;
class DeviceInfo
{
public Device Device { get; set; }
public Twin Twin { get; set; }
public bool ExistsInMaster { get; set; }
public DeviceInfo()
{
}
public DeviceInfo(Device device, Twin twin, bool existsInMaster)
{
Device = device;
Twin = twin;
ExistsInMaster = existsInMaster;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ConsoleLibrary;
using System.Linq;
using ClassLibraryDatabase;
using ClassLibraryCommon.DTO;
namespace UnitTestLibrary
{
[TestClass]
public class UnitTestDbAdo
{
// data
private string _conn;
private DbAdo _dbado;
// Constructor
public UnitTestDbAdo()
{
_conn = this.GetConnectionString();
_dbado = new DbAdo(_conn); //
}
// methods
private string GetConnectionString()
{
return "Data Source=LAPTOP-1RTOL5OV;Initial Catalog=LibraryUT;Integrated Security=True";
//return ConfigurationManager.AppSettings["DBCONN"].ToString();
}
[TestMethod]
public void Add_Exception_To_Logging_Table()
{
// arrange
Exception _exception = new Exception("message");
//_exception.StackTrace = "stacktrace"; // only get - will be null
_exception.Source = "Add_Exception_To_Logging_Table()";
// act
int _pk = _dbado.LogException(_exception);
// assert
Assert.IsTrue(_pk > 0);
}
[TestMethod]
public void Add_One_Role()
{
// arrange
// SqlConnection _sqlConnection = new SqlConnection(_conn);
// List<Book> list = new List<Book>();
RoleDTO roleDTO = new RoleDTO
{
RoleName = "TESTROLE",
Comment = "Comment",
ModifiedByUserId = 0, // SYSTEM USER ID
DateModified = DateTime.Now
};
// act
int _pk = _dbado.CreateRole(roleDTO);
// int savePK = _datasource.CreateBook(b);
// list = _datasource.GetBooks();
// Book bookToUpdate = list.Where(bk => bk.BookID == savePK).FirstOrDefault(); // this get the book
// bookToUpdate.Description = "Testing321";
// bookToUpdate.Title = "Testing321";
// _datasource.UpdateBook(bookToUpdate); // PK should already be correct because of LINQ statement
// list = _datasource.GetBooks(); // look fo this update
// Book bookUpdated = list.Where(bk => bk.Title == "Testing321").FirstOrDefault();
// assert
Assert.IsTrue(_pk > 0);
// Assert.IsNotNull(bookUpdated);
// Assert.IsTrue(bookUpdated.Title == "Testing321");
// // cleanup
// b.BookID = savePK;
// _datasource.DeleteBook(b);
//
}
[TestMethod]
public void Read_Roles_Table_Should_Return_Rows_Greater_Than_Zero()
{
// arrange
// act
var _rows = _dbado.GetRoles();
// assert
Assert.IsTrue(_rows.Count > 0);
}
[TestMethod]
public void Delete_The_Max_PK_From_Roles_Table()
{
// arrange
// act
var _rows = _dbado.GetRoles();
int _count = _rows.Count;
int _max = _rows.Max(y => y.RoleID);
_dbado.DeleteRole(new RoleDTO { RoleID = _max });
_rows = _dbado.GetRoles();
int _count_after_delete = _rows.Count;
// assert
Assert.IsTrue(_count == _count_after_delete + 1);
}
}
}
|
using System.Collections.Generic;
namespace SpaceHosting.Index
{
public interface IIndexStoreFactory<TId, TData>
where TId : notnull
{
IIndexStore<TId, TData, TVector> Create<TVector>(
string algorithm,
int vectorDimension,
bool withDataStorage,
IEqualityComparer<TId> idComparer)
where TVector : IVector;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyHomeWorkLab7
{
class Rational
{
private readonly int ZERO = 0, ONE = 1;
public int m { get; }
public int n { get; }
public double res { get; }
public Rational(int m, int n)
{
this.m = m;
this.n = n;
res = ((m == 0) || (n == 0)) ? 0 : m / (double)n;
Nod();
}
public int Nod ()
{
int a = m;
int b = n;
if ((a != 0) && (b != 0))
{
while (a != b)
{
if (a > b)
a = a - b;
else b = b - a;
}
return a;
}
else return 0;
}
public override string ToString()
{
//return m + " / " + n + " = " + res + "; НОД: " + Nod();
return $"{m}/{n}";
}
private int Find_n(int n1, int n2)
{
Rational a = new Rational(n1,n2);
return n1 * n2 / a.Nod();
}
public static Rational operator +(Rational a,Rational b)
{
if (a.n == 0) return b; if (b.n == 0) return a;
if (a.n == b.n) return new Rational(a.m + b.m, a.n);
else return new Rational((a.m * a.Find_n(a.n, b.n) / b.n) + (b.m * a.Find_n(a.n, b.n) / a.n), a.Find_n(a.n, b.n));
}
public static Rational operator +(Rational a, int b)
{
return new Rational(b * a.n + a.m, a.n);
}
public static Rational operator +(int a, Rational b)
{
return new Rational(a * b.n + b.m, b.n);
}
public static Rational operator -(Rational a, Rational b)
{
if (a.n == 0) return new Rational((b.m * -1), b.n); if (b.n == 0) return a;
if (a.n == b.n) return new Rational(a.m - b.m, a.n);
else return new Rational(((a.m * a.Find_n(a.n, b.n) / b.n) - (b.m * a.Find_n(a.n, b.n) / a.n)), a.Find_n(a.n, b.n));
}
public static Rational operator -(Rational a, int b)
{
return new Rational(a.m - b * a.n, a.n);
}
public static Rational operator -(int b, Rational a)
{
return new Rational(a.m - b * a.n, a.n);
}
public static Rational operator /(Rational a, Rational b)
{
if (a.n == 0 || b.n == 0) return new Rational(0, 0);
return new Rational(a.m * b.n, a.n * b.m);
}
public static Rational operator /(Rational a, int b)
{
if (a.n == 0) return new Rational(0, 0);
return new Rational(a.m, a.n * b);
}
public static Rational operator /(int b, Rational a)
{
if (a.n == 0) return new Rational(0, 0);
return new Rational(a.m, a.n * b);
}
public static Rational operator *(Rational a, Rational b)
{
if (a.n == 0 || b.n == 0) return new Rational(0, 0);
return new Rational(a.m * b.m, a.n * b.n);
}
public static Rational operator *(Rational a, int b)
{
if (a.n == 0) return new Rational(0, 0);
return new Rational(a.m * b, a.n);
}
public static Rational operator *(int b, Rational a)
{
if (a.n == 0) return new Rational(0, 0);
return new Rational(a.m * b, a.n);
}
public static bool operator >(Rational a, Rational b)
{
if (a.n == b.n) return a.m > b.m;
return ((double)a.m / (double)a.n) > ((double)b.m / (double)b.n);
}
public static bool operator >(Rational a, int b)
{
return ((double)a.m / (double)a.n) > b;
}
public static bool operator >(int b, Rational a)
{
return ((double)a.m / (double)a.n) > b;
}
public static bool operator <(Rational a, Rational b)
{
if (a.n == b.n) return a.m < b.m;
return ((double)a.m / (double)a.n) < ((double)a.m / (double)a.n);
}
public static bool operator <(Rational a, int b)
{
return ((double)a.m / (double)a.n) < b;
}
public static bool operator <(int b, Rational a)
{
return ((double)a.m / (double)a.n) < b;
}
}
}
|
using System;
using System.Globalization;
using System.Reflection;
namespace AssemblyResolver
{
/// <summary>
/// Class AssemblyInfo.
/// </summary>
public class AssemblyInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="AssemblyInfo"/> class.
/// </summary>
/// <param name="fullyQualifiedAssemblyName">Name of the fully qualified assembly.</param>
public AssemblyInfo(string fullyQualifiedAssemblyName)
{
var assemblyNameParts = fullyQualifiedAssemblyName.Split(',');
foreach (var assemblyNamePart in assemblyNameParts)
{
var nameComponent = assemblyNamePart.Split('=');
if (nameComponent.Length == 2)
{
var componentName = nameComponent[0].Trim();
var componentValue = nameComponent[1].Trim();
switch (componentName)
{
case nameof(Version):
Version = new Version(componentValue);
break;
case nameof(Culture):
if (componentValue.Equals("neutral", StringComparison.InvariantCultureIgnoreCase))
{
Culture = CultureInfo.CreateSpecificCulture(string.Empty);
}
else
{
Culture = CultureInfo.CreateSpecificCulture(componentValue);
}
break;
case nameof(PublicKeyToken):
if (componentValue.Equals("null", StringComparison.InvariantCultureIgnoreCase))
{
PublicKeyToken = null;
}
else
{
PublicKeyToken = componentValue;
}
break;
case nameof(ProcessorArchitecture):
ProcessorArchitecture =
(ProcessorArchitecture) Enum.Parse(typeof(ProcessorArchitecture), componentValue);
break;
}
}
else
{
Name = assemblyNamePart.Trim();
}
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; }
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public Version Version { get; }
/// <summary>
/// Gets the culture.
/// </summary>
/// <value>The culture.</value>
public CultureInfo Culture { get; }
/// <summary>
/// Gets the public key token.
/// </summary>
/// <value>The public key token.</value>
public string PublicKeyToken { get; }
/// <summary>
/// Gets the processor architecture.
/// </summary>
/// <value>The processor architecture.</value>
public ProcessorArchitecture ProcessorArchitecture { get; }
}
} |
namespace Sentry.Extensibility;
/// <summary>
/// A request body extractor.
/// </summary>
public interface IRequestPayloadExtractor
{
/// <summary>
/// Extracts the payload of the provided <see cref="IHttpRequest"/>.
/// </summary>
/// <param name="request">The HTTP Request object.</param>
/// <returns>The extracted payload.</returns>
object? ExtractPayload(IHttpRequest request);
}
|
using DataAccessLayer.Models;
using IModelRepository;
using MySql.Data.MySqlClient;
using MySql.Data.MySqlClient.Memcached;
using Renci.SshNet.Security.Cryptography;
using System;
namespace DataAccessLayer
{
public class DBContext : IDBContext
{
private MySqlConnection connection;
public DBContext(string connectionString)
{
connection = new MySqlConnection(connectionString);
connection.Open();
SetupConnections();
}
public ITestContext TestContext { get; set; }
public IUserContext UserContext { get; set; }
public IQuestionContext QuestionContext { get; set; }
public void Dispose()
{
connection.Close();
}
public void SetupConnections()
{
TestContext = new TestContext(connection);
UserContext = new UserContext(connection);
QuestionContext = new QuestionContext(connection);
}
}
}
|
using Alabo.Domains.Services;
using MongoDB.Bson;
namespace _01_Alabo.Cloud.Core.DataBackup.Domain.Services
{
public interface IDataBackupService : IService<Entities.DataBackup, ObjectId>
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameCameraTopDown : GameCamera {
protected Vector3 cameraOffset;
protected override void Start()
{
base.Start();
cameraOffset = transform.position - targetTransform.position;
}
public override void HandleUpdate()
{
}
public override void HandleFixedUpdate()
{
Move(Time.fixedDeltaTime);
}
protected virtual void Move(float time)
{
var targetPos = targetTransform.position + cameraOffset;
var smoothPos = Vector3.Lerp(transform.position, targetPos, moveSpeed * time);
if(GameManager.Instance.CameraBounds)
transform.position = GameManager.Instance.CameraBounds.GetPosInBounds(smoothPos, cameraOffset);
else
transform.position = smoothPos;
}
}
|
namespace Core
{
/// <summary>
/// права доступа к отчтам
/// </summary>
public enum AccessRightsReport
{
deny = 1,//запрещен
partial = 2,//частичный доступ
allow = 3//разрешен
}
}
|
using Chess.v4.Engine.Factory;
using Chess.v4.Models.Enums;
using System.Collections.Generic;
namespace Chess.v4.Models
{
/// <summary>
/// Definition
///A FEN "record" defines a particular game position, all in one text line and using only the ASCII character set. A text file with only FEN data records should have the file extension ".fen".
///A FEN record contains six fields. The separator between fields is a space. The fields are:
///1. Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending with rank 1; within each rank, the contents of each square are described from file "a" through file "h". Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken from the standard English names (pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q" and king = "K").[1] White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number of blank squares), and "/" separates ranks.
///2. Active color. "w" means white moves next, "b" means black.
///3. Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle kingside), and/or "q" (Black can castle queenside).
///4. En passant target square in algebraic notation. If there's no en passant target square, this is "-". If a pawn has just made a two-square move, this is the position "behind" the pawn. This is recorded regardless of whether there is a pawn in position to make an en passant capture.[2]
///5. Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used to determine if a draw can be claimed under the fifty-move rule.
///6. Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
///Examples
///Here is the FEN for the starting position:
///rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
///Here is the FEN after the move 1. e4:
///rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1
///And then after 1. ... c5:
///rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2
///And then after 2. Nf3:
///rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
/// </summary>
public class Snapshot
{
//Active colour. "w" means White moves next, "b" means Black.
public Color ActiveColor { get; set; }
//Castling availability. If neither side can castle, this is "-".
//Otherwise, this has one or more letters: "K" (White can castle kingside),
//"Q" (White can castle queenside), "k" (Black can castle kingside), and/or "q" (Black can castle queenside).
public string CastlingAvailability { get; set; }
//Mirrors EnPassantTargetSquare, but uses a board index rather than the algebraic notation
public int EnPassantTargetPosition { get; set; }
//En passant target square in algebraic notation.If there's no en passant target square, this is "-".
//If a pawn has just made a two-square move, this is the position "behind" the pawn.
//This is recorded regardless of whether there is a pawn in position to make an en passant capture.[2]
public string EnPassantTargetSquare { get; set; }
//Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
public int FullmoveNumber { get; set; }
//Halfmove clock: This is the number of halfmoves since the last capture or pawn advance.
//This is used to determine if a draw can be claimed under the fifty-move rule.
public int HalfmoveClock { get; set; }
//Piece placement(from white's perspective). Each rank is described,
//starting with rank 8 and ending with rank 1; within each rank, the contents
//of each square are described from file "a" through file "h".
//Following the Standard Algebraic Notation (SAN), each piece is identified by a
//single letter taken from the standard English names
//(pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q" and king = "K").[1]
//White pieces are designated using upper-case letters ("PNBRQK") while black pieces use
//lowercase ("pnbrqk"). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks.
public string PiecePlacement { get; set; }
public string PGN { get; set; }
public List<string> PGNMoves { get; set; } = new List<string>();
public override string ToString()
{
return FenFactory.Create(this);
}
}
} |
using DataAccess;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace TestConsole
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using PopulationWars.HomeGrownNetwork;
using PopulationWars.Mechanics;
namespace PopulationWars.Components.Governments
{
[Serializable]
class HomeGrownNetwork : IGovernment
{
private const int OutputSize = 9;
private const double TestSetPercentage = 20.0;
private const int MaxEpochs = 1000;
private const double GoalError = 0.0002;
private const double PopulationToMove = 0.5;
private const double LearningRate = 0.005;
private static readonly int[] HiddenLayerSizes = { 50 };
private NeuralNetwork m_network;
private int m_inputSize;
public object Clone()
{
var clone = new HomeGrownNetwork
{
m_network = (NeuralNetwork)m_network?.Clone(),
m_inputSize = m_inputSize
};
return clone;
}
public void Train(TrainSet trainSet)
{
var dim = trainSet.Situation.First().Environment.Size * 2 + 1;
var inputSize = dim * dim * 2 + 3;
if (m_network == null)
{
m_inputSize = inputSize;
var layerSizes = new int[HiddenLayerSizes.Length + 2];
layerSizes[0] = m_inputSize;
layerSizes[layerSizes.Length - 1] = OutputSize;
Array.Copy(HiddenLayerSizes, 0, layerSizes, 1, HiddenLayerSizes.Length);
m_network = new NeuralNetwork(layerSizes, LearningRate);
}
if (inputSize != m_inputSize)
{
throw new Exception("Training set input variables doesn't match neural networks input structure.");
}
/*
var directionCount = (
from object direction in Enum.GetValues(typeof(Direction))
select trainSet.Decision.Count(d => d.Direction == (Direction)direction)).ToList();
var minCount = directionCount.Min();
directionCount = directionCount.Select(cnt => cnt - minCount).ToList();
while (directionCount.Sum() != 0)
{
var ran = new Random();
for (var i = 0; i < trainSet.Situation.Count; i++)
{
if (trainSet.Decision[i] != null &&
directionCount[(int)trainSet.Decision[i].Direction] > 0
&& ran.NextDouble() > 0.5)
{
directionCount[(int)trainSet.Decision[i].Direction]--;
trainSet.Decision[i] = null;
trainSet.Situation[i] = null;
}
}
}
*/
var setSize = trainSet.Decision.Count;
while (trainSet.Decision.Count(d => d?.Direction == Direction.None) > setSize / 6)
{
var ran = new Random();
for (var i = 0; i < trainSet.Decision.Count; i++)
{
if (trainSet.Decision[i]?.Direction == Direction.None && ran.NextDouble() > 0.6)
{
trainSet.Decision[i] = null;
trainSet.Situation[i] = null;
setSize--;
}
}
}
trainSet.Decision = trainSet.Decision.Where(d => d != null).ToList();
trainSet.Situation = trainSet.Situation.Where(s => s != null).ToList();
var inputs = new double[trainSet.Situation.Count][];
var outputs = new double[trainSet.Situation.Count][];
for (var i = 0; i < trainSet.Decision.Count; i++)
{
inputs[i] = SituationToInputs(trainSet.Situation[i]);
outputs[i] = DecisionToOutputs(trainSet.Decision[i]);
}
m_network.Train(inputs, outputs, TestSetPercentage, MaxEpochs, GoalError);
}
public Decision MakeDecision(Situation situation)
{
return OutputsToDecision(m_network.Predict(SituationToInputs(situation)));
}
public override string ToString() => "HomeGrownNetwork";
private double[] SituationToInputs(Situation situation)
{
var dim = situation.Environment.Size * 2 + 1;
var inputSize = dim * dim * 2 + 3;
if (inputSize != m_inputSize)
{
throw new Exception("Situation input variables doesn't match neural networks input structure.");
}
var inputs = new double[inputSize];
var nation = situation.Environment.Map[dim / 2][dim / 2].OwnedBy.Nation;
for (var i = 0; i < dim; i++)
{
for (var k = 0; k < dim; k++)
{
var tile = situation.Environment.Map[i][k];
if (tile.IsColonized)
{
inputs[i * dim + k * 2] = tile.OwnedBy.Population;
inputs[i * dim + k * 2 + 1] = tile.OwnedBy.Nation == nation ? 1 : 2;
}
else
{
inputs[i * dim + k * 2] = 0;
inputs[i * dim + k * 2 + 1] = tile.IsWall ? -1 : 0;
}
}
}
return inputs;
}
private Decision OutputsToDecision(double[] outputs)
{
var max = 0.0;
var direction = Direction.None;
for (var i = 0; i < OutputSize; i++)
{
if (!(outputs[i] > max)) continue;
max = outputs[i];
direction = (Direction)i;
}
return direction == Direction.None ? new Decision() : new Decision(true, direction, PopulationToMove);
}
private static double[] DecisionToOutputs(Decision decision)
{
var output = new double[OutputSize];
output[(int)decision.Direction] = 1;
return output;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InventorServices.Persistence
{
public interface IBindableObject
{
IModuleBinder Binder { get; set; }
dynamic ObjectToBind { get; set; }
void RegisterContextData(int moduleId, int objectId);
//TODO: Add IsBinderValid to be checked when calling GetObjectFromTrace or SetObjectForTrace
//and thow exception. Will check that client code has set IContextData and IContextManager.
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DataStructurePrograms
{
class StackArray
{
public void stackusingArray()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.WithDivisionCheck
{
class DivisionCheck
{
static void Main()
{
Console.Write("Insert a number bigger than 1: ");
int userInput = int.Parse(Console.ReadLine());
Console.WriteLine("The numbers from 1 to {0} that are not divisible by 3 and 7 at the same time are:", userInput);
for (int index = 1; index <= userInput; index++)
{
if (index % 3 == 0 && index % 7 == 0)
{
Console.WriteLine(index);
continue;
}
}
}
}
}
|
using SQLite.Net;
using SQLite.Net.Async;
namespace CC.Utilities.SQLite
{
public interface ISQLite
{
SQLiteConnectionWithLock GetConnectionWithLock ();
SQLiteConnectionWithLock GetConnectionWithLock (string path);
SQLiteAsyncConnection GetAsyncConnection ();
SQLiteAsyncConnection GetAsyncConnection (string path);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Test
{
public class DataToCalculate
{
private int _platelets;
private float _albumin;
private string _action;
public int platelets
{
get { return _platelets; }
set { _platelets = value; }
}
public float albumin
{
get { return _albumin; }
set { _albumin = value; }
}
public string action
{
get { return _action; }
set { _action = value; }
}
public override string ToString()
{
return
platelets + " " +
albumin + " " +
action;
}
}
}
|
/* 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.
*
* 2019.12.27-Changed implement
*/
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using System.Collections.Generic;
using AGConnectAdmin.Auth;
namespace AGConnectAdmin.Messaging
{
/// <summary>
/// A client for making authorized HTTP calls to the HCM backend service. Handles request
/// serialization, response parsing, and HTTP error handling.
/// </summary>
internal sealed class AGConnectMessagingClient : IDisposable
{
private const string SUCCESS_CODE = "80000000";
private readonly HttpClient httpClient;
private string TokenUrl;
private readonly string sendUrl;
private AppOptions options;
private TokenResponse tokenResponse;
private Task<string> accessTokenTask;
private object accessTokenTaskLock = new object();
public AGConnectMessagingClient(AppOptions options)
{
this.options = options;
TokenUrl = options.LoginUri;
sendUrl = options.GetApiUri();
#if PROXY
httpClient = new HttpClient(new HttpClientHandler()
{
UseProxy = true,
// Use cntlm proxy setting to accesss internet.
Proxy = new WebProxy("localhost", 3128),
});
#else
httpClient = new HttpClient();
#endif
}
public void Dispose()
{
httpClient.Dispose();
}
/// <summary>
/// Sends a message to the AGC service for delivery. The message gets validated both by
/// the Admin SDK, and the remote AGC service. A successful return value indicates
/// that the message has been successfully sent to AGC, where it has been accepted by the
/// AGC service.
/// </summary>
/// <returns>A task that completes with a message ID string, which represents
/// successful handoff to AGC.</returns>
/// <exception cref="ArgumentNullException">If the message argument is null.</exception>
/// <exception cref="ArgumentException">If the message contains any invalid
/// fields.</exception>
/// <exception cref="AGConnectException">If an error occurs while sending the
/// message.</exception>
/// <param name="message">The message to be sent. Must not be null.</param>
/// <param name="dryRun">A boolean indicating whether to perform a dry run (validation
/// only) of the send. If set to true, the message will be sent to the AGC backend service,
/// but it will not be delivered to any actual recipients.</param>
/// <param name="cancellationToken">A cancellation token to monitor the asynchronous
/// operation.</param>
public async Task<string> SendAsync(
Message message,
bool dryRun = false,
CancellationToken cancellationToken = default)
{
try
{
var sendRequest = new SendRequest()
{
Message = (message.ThrowIfNull(nameof(message)) as MessagePart<Message>).CopyAndValidate(),
ValidateOnly = dryRun,
};
var accessToken = await GetAccessTokenAsync().ConfigureAwait(false);
var payload = NewtonsoftJsonSerializer.Instance.Serialize(sendRequest);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(sendUrl),
Content = content,
};
using (request)
{
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
string json = await ReadContentSafely(response).ConfigureAwait(false);
if (response.StatusCode != HttpStatusCode.OK)
{
var error = $"Response status code does not indicate success: {response.StatusCode}\r\n" +
$"Response body: {json}";
throw new AGConnectException(error);
}
var parsed = JsonConvert.DeserializeObject<SingleMessageResponse>(json);
if (parsed.Code != SUCCESS_CODE)
{
throw new AGConnectException(
$"Send message failed: {parsed.Code}{Environment.NewLine}{parsed.Message}");
}
return parsed.RequestId;
}
}
catch (HttpRequestException e)
{
throw new AGConnectException("Error while calling the AGC messaging service.", e);
}
}
private async Task<string> ReadContentSafely(HttpResponseMessage msg)
{
try
{
return await msg.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception e)
{
return $"failed to read response: {e.Message}";
}
}
/// <summary>
/// Subscribes a list of registration tokens to a topic.
/// </summary>
/// <param name="registrationTokens">A list of registration tokens to subscribe.</param>
/// <param name="topic">The topic name to subscribe to.</param>
/// <returns>A task that completes with a <see cref="TopicManagementResponse"/>, giving details about the topic subscription operations.</returns>
public async Task<TopicManagementResponse> SubscribeToTopicAsync(
IReadOnlyList<string> registrationTokens, string topic)
{
if (string.IsNullOrWhiteSpace(topic))
{
throw new ArgumentException("Topic can not be empty");
}
if (registrationTokens == null)
{
throw new ArgumentException("Registration tokens can not be null");
}
if (registrationTokens.Count == 0)
{
throw new ArgumentException("Registration tokens can not be empty");
}
if (registrationTokens.Count > 1000)
{
throw new ArgumentException("Registration token list must not contain more than 1000 tokens");
}
var accessToken = await GetAccessTokenAsync().ConfigureAwait(false);
var body = new TopicManagementRequest()
{
Topic = topic,
Tokens = new List<string>(registrationTokens)
};
var url = $"{options.ApiBaseUri}/v1/{options.ClientId}/topic:subscribe";
var payload = NewtonsoftJsonSerializer.Instance.Serialize(body);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = content,
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var resp = await httpClient.SendAsync(request).ConfigureAwait(false);
var json = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
return NewtonsoftJsonSerializer.Instance.Deserialize<TopicManagementResponse>(json);
}
/// <summary>
/// Unsubscribes a list of registration tokens from a topic.
/// </summary>
/// <param name="registrationTokens">A list of registration tokens to unsubscribe.</param>
/// <param name="topic">The topic name to unsubscribe from.</param>
/// <returns>A task that completes with a <see cref="TopicManagementResponse"/>, giving details about the topic unsubscription operations.</returns>
public async Task<TopicManagementResponse> UnsubscribeFromTopicAsync(
IReadOnlyList<string> registrationTokens, string topic)
{
if (string.IsNullOrWhiteSpace(topic))
{
throw new ArgumentException("Topic can not be empty");
}
if (registrationTokens == null)
{
throw new ArgumentException("Registration tokens can not be null");
}
if (registrationTokens.Count == 0)
{
throw new ArgumentException("Registration tokens can not be empty");
}
if (registrationTokens.Count > 1000)
{
throw new ArgumentException("Registration token list must not contain more than 1000 tokens");
}
var accessToken = await GetAccessTokenAsync().ConfigureAwait(false);
var body = new TopicManagementRequest()
{
Topic = topic,
Tokens = new List<string>(registrationTokens)
};
var url = $"{options.ApiBaseUri}/v1/{options.ClientId}/topic:unsubscribe";
var payload = NewtonsoftJsonSerializer.Instance.Serialize(body);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = content,
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var resp = await httpClient.SendAsync(request).ConfigureAwait(false);
var json = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
return NewtonsoftJsonSerializer.Instance.Deserialize<TopicManagementResponse>(json);
}
/// <summary>
/// Retrieve a list of topics that the specified registration token subscribe to.
/// </summary>
/// <param name="registrationToken">The topic name to unsubscribe from.</param>
/// <returns>A task that completes with a <see cref="TopicListResponse"/>, giving details about the topic retrieve operations.</returns>
public async Task<TopicListResponse> GetTopicListAsync(string registrationToken)
{
if (string.IsNullOrWhiteSpace(registrationToken))
{
throw new ArgumentException("Registration token can not be empty");
}
var accessToken = await GetAccessTokenAsync().ConfigureAwait(false);
var body = new TopicListRequest()
{
Token = registrationToken
};
var url = $"{options.ApiBaseUri}/v1/{options.ClientId}/topic:list";
var payload = NewtonsoftJsonSerializer.Instance.Serialize(body);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = content,
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var resp = await httpClient.SendAsync(request).ConfigureAwait(false);
var json = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
return NewtonsoftJsonSerializer.Instance.Deserialize<TopicListResponse>(json);
}
private async Task<string> GetAccessTokenAsync()
{
string accessToken = tokenResponse?.GetValidAccessToken();
if (string.IsNullOrEmpty(accessToken))
{
lock (accessTokenTaskLock)
{
if (accessTokenTask == null)
{
// access token task may be shared by multiple messaging task, thus should not pass cancellationToken to it
accessTokenTask = RequestAccessTokenAsync(default);
}
}
accessToken = await accessTokenTask.ConfigureAwait(false);
lock (accessTokenTaskLock)
{
accessTokenTask = null;
}
}
if (string.IsNullOrEmpty(accessToken))
{
var error = "AccessToken is null or empty";
throw new AGConnectException(error);
}
return accessToken;
}
private async Task<string> RequestAccessTokenAsync(CancellationToken cancellationToken)
{
string content =
$"grant_type=client_credentials&client_secret={options.ClientSecret}&client_id={options.ClientId}";
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(TokenUrl),
Content = new StringContent(content),
};
using (request)
{
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
var json = await ReadContentSafely(response).ConfigureAwait(false);
var parsed = JsonConvert.DeserializeObject<TokenResponse>(json);
switch (parsed.Error)
{
case 1101:
throw new AGConnectException("Get access token failed: invalid request");
case 1102:
throw new AGConnectException("Get access token failed: missing required param");
case 1104:
throw new AGConnectException("Get access token failed: unsupported response type");
case 1105:
throw new AGConnectException("Get access token failed: unsupported grant type");
case 1107:
throw new AGConnectException("Get access token failed: access denied");
case 1201:
throw new AGConnectException("Get access token failed: invalid ticket");
case 1202:
throw new AGConnectException("Get access token failed: invalid sso_st");
default:
break;
}
if (response.StatusCode != HttpStatusCode.OK)
{
var error = $"Response status code for token request does not indicate success: {response.StatusCode}.\r\n" +
$"Response body: {json}";
throw new AGConnectException(error);
}
var token = parsed.GetValidAccessToken();
if (string.IsNullOrEmpty(token))
{
var error = "AccessToken return by AGC is null or empty";
throw new AGConnectException(error);
}
tokenResponse = parsed;
return token;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WingtipToys.Checkout
{
public partial class CheckoutStart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NVPAPICaller payPalCaller = new NVPAPICaller();
string retMsg = "";
string token = "";
if ( Session["payment amt"] != null )
{
string amt = Session["payment amt"].ToString();
bool ret = payPalCaller.ShortcutExpressCheckout( amt, ref token, ref retMsg );
if ( ret )
{
Session["token"] = token;
Response.Redirect( retMsg );
}
else
{
Response.Redirect( "CheckoutError.aspx?" + retMsg );
}
}
else
{
Response.Redirect( "CheckoutError.aspx?ErrorCode=AmtMissing" );
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Szab.Scheduling.Representation;
using System.Text.RegularExpressions;
using System.Globalization;
using Szab.EvolutionaryAlgorithm;
using Szab.Scheduling.MSRCPSP;
using Szab.TabuSearch;
using Szab.SimulatedAnnealing;
namespace Szab.Scheduling.Tools
{
public static class FilesManager
{
private const int TASK_DEF_RELEVANT_COLUMNS = 4;
private const int RES_DEF_RELEVANT_COLUMNS = 2;
private static string ReadFile(string path)
{
string fileContents = "";
using (StreamReader stream = new StreamReader(new FileStream(path, FileMode.Open)))
{
fileContents = stream.ReadToEnd();
}
return fileContents;
}
private static void SaveToFile(string path, string data)
{
using (StreamWriter stream = new StreamWriter(new FileStream(path, FileMode.CreateNew)))
{
stream.Write(data);
}
}
private static void AssignAvailableResources(ProjectSpecification project)
{
foreach(Task task in project.Tasks)
{
var matchingResources = project.Resources.Where(r => task.RequiredSkills.All(rs => r.Skills.Any(s => s.Name == rs.Name && s.Level >= rs.Level)));
task.AvailableResources.AddRange(matchingResources.OrderBy(r => r.Cost));
}
}
private static Resource GetResourceFromArray(string[] resourceData)
{
string name = resourceData[0];
float salary = float.Parse(resourceData[1], CultureInfo.InvariantCulture);
Resource resource = new Resource(name, salary);
for(var i = 2; i < resourceData.Length; i = i + 2)
{
string skillName = resourceData[i].Substring(0, resourceData[i].Length - 1);
int skillLevel = int.Parse(resourceData[i + 1]);
Skill skill = new Skill(skillName, skillLevel);
resource.Skills.Add(skill);
}
return resource;
}
private static void ParseResources(string resourcesString, ProjectSpecification specification)
{
string[] resourcesData = resourcesString.Split('\n');
for (var i = 1; i < resourcesData.Length; i++)
{
string[] resourceData = Regex.Split(resourcesData[i].Trim(), @"\s+");
if (resourceData.Length >= RES_DEF_RELEVANT_COLUMNS)
{
Resource resource = FilesManager.GetResourceFromArray(resourceData);
specification.Resources.Add(resource);
}
}
}
private static void FillPredecessors(string[] taskData, ProjectSpecification specification)
{
string taskName = taskData[0];
Task task = specification.Tasks.FirstOrDefault(x => x.Name == taskName);
for(var i = 4; i < taskData.Length; i++)
{
string predecessorId = taskData[i];
if (!String.IsNullOrEmpty(predecessorId))
{
Task predecessor = specification.Tasks.FirstOrDefault(x => x.Name == predecessorId);
task.Predecessors.Add(predecessor);
}
}
}
private static Task GetTaskFromArray(string[] taskData)
{
string name = taskData[0];
int duration = int.Parse(taskData[1]);
string requiredSkillName = taskData[2].Substring(0, taskData[2].Length - 1);
int requiredSkillLevel = int.Parse(taskData[3]);
Task task = new Task(name, duration);
task.RequiredSkills.Add(new Skill(requiredSkillName, requiredSkillLevel));
return task;
}
private static void ParseTasks(string tasksString, ProjectSpecification specification)
{
string[] tasksData = tasksString.Split('\n');
for (var i = 1; i < tasksData.Length; i++)
{
string[] taskData = Regex.Split(tasksData[i].Trim(), @"\s+");
if (taskData.Length >= TASK_DEF_RELEVANT_COLUMNS)
{
Task task = FilesManager.GetTaskFromArray(taskData);
specification.Tasks.Add(task);
}
}
for (var i = 1; i < tasksData.Length; i++)
{
string[] taskData = Regex.Split(tasksData[i].Trim(), @"\s+");
if (taskData.Length >= TASK_DEF_RELEVANT_COLUMNS)
{
FilesManager.FillPredecessors(taskData, specification);
}
}
}
public static ProjectSpecification ParseProjectData(string path)
{
string fileContent = FilesManager.ReadFile(path);
string[] sections = Regex.Split(fileContent, "=+.+\n");
int numSections = sections.Length;
string tasksSection = String.IsNullOrEmpty(sections[numSections - 1]) ? sections[numSections - 2] : sections[numSections - 1];
string resourcesSection = String.IsNullOrEmpty(sections[numSections - 1]) ? sections[numSections - 3] : sections[numSections - 2];
ProjectSpecification projectSpecification = new ProjectSpecification();
FilesManager.ParseResources(resourcesSection, projectSpecification);
FilesManager.ParseTasks(tasksSection, projectSpecification);
FilesManager.AssignAvailableResources(projectSpecification);
return projectSpecification;
}
public static string SerializeSchedule(Schedule schedule)
{
string header = "Hour Resource assignments (resource ID - task ID) ";
StringBuilder builder = new StringBuilder();
builder.AppendLine(header);
IEnumerable<TaskAssignment> assignments = schedule.GetAllAssignments();
IEnumerable<int> offsets = assignments.Select(x => x.StartOffset).Distinct();
foreach(int offset in offsets)
{
IEnumerable<TaskAssignment> assignmentsAtOffset = schedule.GetTaskAt(offset).Where(x => x.StartOffset == offset);
IEnumerable<string> assignmentsAsString = assignmentsAtOffset.Select(x => x.Resource.Name + "-" + x.Task.Name);
string line = offset.ToString() + " " + String.Join(" ", assignmentsAsString);
builder.AppendLine(line);
}
return builder.ToString();
}
private static string SerializeResultQualities(List<double[]> qualities)
{
StringBuilder statisticsBuilder = new StringBuilder();
statisticsBuilder.AppendLine("Generation;Worst;Average;Best");
for (int i = 0; i < qualities.Count; i++)
{
string worstResult = qualities[i][0].ToString(CultureInfo.CurrentUICulture);
string averageResult = qualities[i][1].ToString(CultureInfo.CurrentUICulture);
string bestResult = qualities[i][2].ToString(CultureInfo.CurrentUICulture);
string partialResult = String.Format("{0};{1};{2};{3}", i + 1, worstResult, averageResult, bestResult);
statisticsBuilder.AppendLine(partialResult);
}
return statisticsBuilder.ToString();
}
private static string CreateRunSummary(string filePath, MSRCPSPEvolutionarySolver solver, Schedule result)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("File: " + filePath);
builder.AppendLine("Metaheuristic: Evolutionary algorithm");
builder.AppendLine("Number of generations: " + solver.MaxGenerations);
builder.AppendLine("Population size: " + solver.PopulationSize);
builder.AppendLine("Percent of population in a tournament group: " + solver.PercentInGroup);
builder.AppendLine("Crossover probability: " + solver.CrossoverProbability);
builder.AppendLine("Mutation probability: " + solver.MutationProbability);
builder.AppendLine();
builder.AppendLine("Result duration: " + result.Length);
builder.AppendLine("Result cost: " + result.SummaryCost);
builder.AppendLine("========================================");
builder.Append(FilesManager.SerializeSchedule(result));
return builder.ToString();
}
private static string CreateRunSummary(string filePath, MSRCPSPAnnealedEASolver solver, Schedule result)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("File: " + filePath);
builder.AppendLine("Metaheuristic: Evolutionary algorithm");
builder.AppendLine("Number of generations: " + solver.MaxGenerations);
builder.AppendLine("Population size: " + solver.PopulationSize);
builder.AppendLine("Percent of population in a tournament group: " + solver.PercentInGroup);
builder.AppendLine("Crossover probability: " + solver.CrossoverProbability);
builder.AppendLine("Mutation probability: " + solver.MutationProbability);
builder.AppendLine();
builder.AppendLine("Result duration: " + result.Length);
builder.AppendLine("Result cost: " + result.SummaryCost);
builder.AppendLine("========================================");
builder.Append(FilesManager.SerializeSchedule(result));
return builder.ToString();
}
private static string CreateRunSummary(string filePath, MSRCPSPTabuCorrectedEASolver solver, Schedule result)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("File: " + filePath);
builder.AppendLine("Metaheuristic: Evolutionary algorithm");
builder.AppendLine("Number of generations: " + solver.MaxGenerations);
builder.AppendLine("Population size: " + solver.PopulationSize);
builder.AppendLine("Percent of population in a tournament group: " + solver.PercentInGroup);
builder.AppendLine("Crossover probability: " + solver.CrossoverProbability);
builder.AppendLine("Mutation probability: " + solver.MutationProbability);
builder.AppendLine();
builder.AppendLine("Result duration: " + result.Length);
builder.AppendLine("Result cost: " + result.SummaryCost);
builder.AppendLine("========================================");
builder.Append(FilesManager.SerializeSchedule(result));
return builder.ToString();
}
private static string CreateRunSummary(string filePath, TabuSolver<ScheduleSpecimen> solver, Schedule result)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("File: " + filePath);
builder.AppendLine("Metaheuristic: Tabu Search");
builder.AppendLine("Number of steps: " + solver.NumberOfSteps);
builder.AppendLine("Tabu size: " + solver.TabuSize);
builder.AppendLine();
builder.AppendLine("Result duration: " + result.Length);
builder.AppendLine("Result cost: " + result.SummaryCost);
builder.AppendLine("========================================");
builder.Append(FilesManager.SerializeSchedule(result));
return builder.ToString();
}
private static string CreateRunSummary(string filePath, SimulatedAnnealingSolver<ScheduleSpecimen> solver, Schedule result)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("File: " + filePath);
builder.AppendLine("Metaheuristic: Simulated Annealing");
builder.AppendLine("Initial temperature: " + solver.InitialTemperature);
builder.AppendLine("Max iterations: " + solver.MaxIterations);
builder.AppendLine();
builder.AppendLine("Result duration: " + result.Length);
builder.AppendLine("Result cost: " + result.SummaryCost);
builder.AppendLine("========================================");
builder.Append(FilesManager.SerializeSchedule(result));
return builder.ToString();
}
public static void SaveResults(string path, ProjectSpecification project, MSRCPSPEvolutionarySolver solver, Schedule result, List<double[]> functionChange = null)
{
string folderName = DateTime.Now.ToString("yyyyMMdd hhmmss");
string workingPath = Directory.GetCurrentDirectory() + "/" + folderName;
string baseFileName = Path.GetFileName(path);
Directory.CreateDirectory(workingPath);
string serializedResult = FilesManager.SerializeSchedule(result);
string qualitiesResult = null;
if (functionChange != null)
{
qualitiesResult = FilesManager.SerializeResultQualities(functionChange);
}
string runSummary = FilesManager.CreateRunSummary(path, solver, result);
FilesManager.SaveToFile(workingPath + "/" + baseFileName + ".sol", serializedResult);
if (qualitiesResult != null)
{
FilesManager.SaveToFile(workingPath + "/QualitiesHistory.csv", qualitiesResult);
}
FilesManager.SaveToFile(workingPath + "/RunSummary.txt", runSummary);
}
public static void SaveResults(string path, ProjectSpecification project, MSRCPSPAnnealedEASolver solver, Schedule result, List<double[]> functionChange = null)
{
string folderName = DateTime.Now.ToString("yyyyMMdd hhmmss");
string workingPath = Directory.GetCurrentDirectory() + "/" + folderName;
string baseFileName = Path.GetFileName(path);
Directory.CreateDirectory(workingPath);
string serializedResult = FilesManager.SerializeSchedule(result);
string qualitiesResult = null;
if (functionChange != null)
{
qualitiesResult = FilesManager.SerializeResultQualities(functionChange);
}
string runSummary = FilesManager.CreateRunSummary(path, solver, result);
FilesManager.SaveToFile(workingPath + "/" + baseFileName + ".sol", serializedResult);
if (qualitiesResult != null)
{
FilesManager.SaveToFile(workingPath + "/QualitiesHistory.csv", qualitiesResult);
}
FilesManager.SaveToFile(workingPath + "/RunSummary.txt", runSummary);
}
public static void SaveResults(string path, ProjectSpecification project, MSRCPSPTabuCorrectedEASolver solver, Schedule result, List<double[]> functionChange = null)
{
string folderName = DateTime.Now.ToString("yyyyMMdd hhmmss");
string workingPath = Directory.GetCurrentDirectory() + "/" + folderName;
string baseFileName = Path.GetFileName(path);
Directory.CreateDirectory(workingPath);
string serializedResult = FilesManager.SerializeSchedule(result);
string qualitiesResult = null;
if (functionChange != null)
{
qualitiesResult = FilesManager.SerializeResultQualities(functionChange);
}
string runSummary = FilesManager.CreateRunSummary(path, solver, result);
runSummary += "==========================================";
runSummary += FilesManager.CreateRunSummary(path, solver.TabuSolver, result);
FilesManager.SaveToFile(workingPath + "/" + baseFileName + ".sol", serializedResult);
if (qualitiesResult != null)
{
FilesManager.SaveToFile(workingPath + "/QualitiesHistory.csv", qualitiesResult);
}
FilesManager.SaveToFile(workingPath + "/RunSummary.txt", runSummary);
}
public static void SaveResults(string path, ProjectSpecification project, TabuSolver<ScheduleSpecimen> solver, Schedule result, List<double[]> functionChange = null)
{
string folderName = DateTime.Now.ToString("yyyyMMdd hhmmss");
string workingPath = Directory.GetCurrentDirectory() + "/" + folderName;
string baseFileName = Path.GetFileName(path);
Directory.CreateDirectory(workingPath);
string serializedResult = FilesManager.SerializeSchedule(result);
string qualitiesResult = null;
if (functionChange != null)
{
qualitiesResult = FilesManager.SerializeResultQualities(functionChange);
}
string runSummary = FilesManager.CreateRunSummary(path, solver, result);
FilesManager.SaveToFile(workingPath + "/" + baseFileName + ".sol", serializedResult);
if (qualitiesResult != null)
{
FilesManager.SaveToFile(workingPath + "/QualitiesHistory.csv", qualitiesResult);
}
FilesManager.SaveToFile(workingPath + "/RunSummary.txt", runSummary);
}
public static void SaveResults(string path, ProjectSpecification project, SimulatedAnnealingSolver<ScheduleSpecimen> solver, Schedule result, List<double[]> functionChange = null)
{
string folderName = DateTime.Now.ToString("yyyyMMdd hhmmss");
string workingPath = Directory.GetCurrentDirectory() + "/" + folderName;
string baseFileName = Path.GetFileName(path);
Directory.CreateDirectory(workingPath);
string serializedResult = FilesManager.SerializeSchedule(result);
string qualitiesResult = null;
if (functionChange != null)
{
qualitiesResult = FilesManager.SerializeResultQualities(functionChange);
}
string runSummary = FilesManager.CreateRunSummary(path, solver, result);
FilesManager.SaveToFile(workingPath + "/" + baseFileName + ".sol", serializedResult);
if (qualitiesResult != null)
{
FilesManager.SaveToFile(workingPath + "/QualitiesHistory.csv", qualitiesResult);
}
FilesManager.SaveToFile(workingPath + "/RunSummary.txt", runSummary);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMoveAnimationEvents : MonoBehaviour {
public PlayerController player;
public AudioSource myAudioSource;
public AudioClip leftFootGrassClip;
public AudioClip rightFootGrassClip;
public void PlayLeftFootGrassClip()
{
myAudioSource.PlayOneShot(leftFootGrassClip);
}
public void PlayRightFootGrassClip()
{
myAudioSource.PlayOneShot(rightFootGrassClip);
}
public void ActivateObject()
{
player.grabbedObject.Activate();
}
public void DeactivateObject()
{
player.grabbedObject.Deactivate();
}
public void ActivateBatTrail()
{
player.grabbedObject.transform.GetChild(1).GetComponent<TrailRenderer>().enabled = true;
}
public void DeactivateBatTrail()
{
player.grabbedObject.transform.GetChild(1).GetComponent<TrailRenderer>().enabled = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PasswordCreator22
{
public class NonMarkLetterFactory:ILetterFactory //記号なしのパターン
{
public Letter Create(Random random,int i)
{
int n = i % 3;
if (n == 0)
return new NumLetter(random);
if (n == 1)
return new LowerLetter(random);
if (n == 2)
return new UpperLetter(random);
return null;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace LinqSharp
{
public static partial class XIEnumerable
{
public static int MaxOrDefault(this IEnumerable<int> source, int @default = default(int)) => source.Any() ? source.Max() : @default;
}
}
|
namespace Allyn.Infrastructure.EfRepositories.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class _201799084203 : DbMigration
{
public override void Up()
{
AddColumn("dbo.FShop", "IsNode", c => c.Boolean(nullable: false));
AddColumn("dbo.FShop", "IsBranch", c => c.Boolean(nullable: false));
}
public override void Down()
{
DropColumn("dbo.FShop", "IsBranch");
DropColumn("dbo.FShop", "IsNode");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class TestLife
{
LifeGauge cube;
[SetUp]
public void Setup()
{
cube = new GameObject().AddComponent<LifeGauge>();
cube.life = 100;
cube.damage = 5;
}
[Test]
public void TestLifeSimpleDamage()
{
Assert.AreEqual(100, cube.life);
cube.Damaged();
Assert.AreEqual(95, cube.life);
}
[Test]
public void TestLifeMultiDamage()
{
Assert.AreEqual(100, cube.life);
cube.Damaged();
cube.Damaged();
cube.Damaged();
Assert.AreEqual(85, cube.life);
}
[Test]
public void TestLifeAlwaysGreaterOrEqualToZero()
{
Assert.AreEqual(100, cube.life);
for (int i = 0; i < 30; i++)
{
cube.Damaged();
}
Assert.That(cube.life == 0);
}
[Test]
public void TestLifeAlwaysGreaterOrEqualToZeroForVariableDamage()
{
cube.damage = 7;
Assert.AreEqual(100, cube.life);
for (int i = 0; i < 15; i++)
{
cube.Damaged();
}
Assert.That(cube.life == 0);
}
[Test]
public void TestIsAliveReturnsTrueWhenAlive()
{
cube.life = 100;
Assert.IsTrue(cube.IsAlive());
cube.life = 1;
Assert.IsTrue(cube.IsAlive());
}
[Test]
public void TestIsAliveReturnsFalseWhenDead()
{
cube.life = 0;
Assert.IsFalse(cube.IsAlive());
}
}
}
|
using System;
namespace Crystal.Plot2D
{
public delegate DataRect ViewportConstraintCallback(DataRect proposedDataRect);
public class InjectionDelegateConstraint : ViewportConstraint
{
public InjectionDelegateConstraint(Viewport2D masterViewport, ViewportConstraintCallback callback)
{
Callback = callback ?? throw new ArgumentNullException("callback");
MasterViewport = masterViewport ?? throw new ArgumentNullException("masterViewport");
masterViewport.PropertyChanged += MasterViewport_PropertyChanged;
}
void MasterViewport_PropertyChanged(object sender, ExtendedPropertyChangedEventArgs e)
{
if (e.PropertyName == "Visible")
{
RaiseChanged();
}
}
public ViewportConstraintCallback Callback { get; set; }
public Viewport2D MasterViewport { get; set; }
public override DataRect Apply(DataRect previousDataRect, DataRect proposedDataRect, Viewport2D viewport)
{
return Callback(proposedDataRect);
}
}
}
|
// <copyright file="Computer.cs" company="Softuni">
// Copyright (c) 2014 All Rights Reserved
// <author>Me</author>
// </copyright>
namespace HWDefiningClassesTask03PCCatalog
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
public class Computer : IComparable
{
private string name;
private List<Component> components;
public Computer(string name, List<Component> components)
{
this.Name = name;
this.Components = components;
}
public Computer(string name) : this(name, null)
{
}
public string Name
{
get
{
return this.name;
}
private set
{
this.name = value;
}
}
public List<Component> Components
{
get
{
return this.components;
}
private set
{
if (value == null)
{
this.components = new List<Component>();
}
else
{
this.components = value;
}
}
}
public decimal Price
{
get
{
if (this.Components.Count == 0)
{
return 0M;
}
return this.Components.Sum(x => x.Price);
}
}
public bool AddComponent(Component component)
{
if (this.Components.Exists(x => x.Name == component.Name))
{
return false;
}
this.Components.Add(component);
return true;
}
public bool RemoveComponentByName(string componentName)
{
int index = this.Components.FindIndex(x => x.Name == componentName);
if (index < 0)
{
return false;
}
this.Components.RemoveAt(index);
return true;
}
public void RemoveAllComponents()
{
this.Components.Clear();
}
public string GetDescription()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(new string('=', 50));
sb.AppendLine(string.Format("{1}-== Computer {0} ==-", this.Name, new string(' ', (33 - this.Name.Length) / 2)));
sb.AppendLine(" Components:");
foreach (var component in this.Components)
{
sb.AppendLine(string.Format(" {0}", component));
}
sb.AppendLine(new string('-', 50));
sb.AppendLine(string.Format("Total Computer price is: {0}", this.Price.ToString("C2", CultureInfo.CreateSpecificCulture("bg-BG"))));
sb.AppendLine(new string('=', 50));
return sb.ToString();
}
int IComparable.CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
Computer otherComputer = obj as Computer;
if (otherComputer != null)
{
return this.Price.CompareTo(otherComputer.Price);
}
throw new ArgumentException("Object is not a Computer!");
}
public override string ToString()
{
return string.Format("Computer {0} with price: {1}", this.Name, this.Price.ToString("C2", CultureInfo.CreateSpecificCulture("bg-BG")));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
namespace ICSharpCode.SharpZipLib
{
/// <summary>
/// Utitilities for simplifying VPK related operations.
/// </summary>
public static class VPKOperation
{
/// <summary>
/// Check if the entry is VPK entry.
/// </summary>
/// <param name="ze"></param>
/// <returns></returns>
public static bool IsVPK(ZipEntry ze)
{
return (new ZipExtraData(ze.ExtraData)).Find(VPKTagData.ID);
}
/// <summary>
/// Unpack the information from the ZipEntry.
/// </summary>
/// <param name="ze"></param>
public static void UnpackInfo(ZipEntry ze)
{
ZipExtraData ed = new ZipExtraData(ze.ExtraData);
VPKTagData vtag;
if (ed.Find(VPKTagData.ID))
{
vtag = (VPKTagData)ed.GetData(VPKTagData.ID);
ze.Size = vtag.Size;
ze.CompressedSize = vtag.CompressedSize;
ze.Crc = vtag.CRC;
}
}
/// <summary>
/// Pack the information.
/// </summary>
/// <param name="ze"></param>
public static void PackInfo(ZipEntry ze)
{
ZipExtraData ed = new ZipExtraData(ze.ExtraData);
VPKTagData vtag = new VPKTagData();
vtag.Size = ze.Size;
vtag.CompressedSize = ze.CompressedSize;
vtag.CRC = ze.Crc;
ed.AddEntry(vtag);
ze.ExtraData = ed.GetEntryData();
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using LorikeetMApp.ViewModels;
using Xamarin.Forms;
namespace LorikeetMApp
{
public partial class CreatePINPage : ContentPage
{
public CreatePINPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
var viewModel = new PinAddViewModel();
viewModel.PinViewModel.Success += (object sender, EventArgs e) =>
{
Application.Current.MainPage = new MainMenu();
};
base.BindingContext = viewModel;
}
protected override bool OnBackButtonPressed() => false;
}
}
|
using Com.Colin.IbatisDataAccess;
using Com.Colin.Model;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Com.Colin.BusinessLayer
{
public class AnimalService : BaseBL, IAnimalService
{
public int Add(AnimalModel item)
{
throw new NotImplementedException();
}
public int Delete(int id)
{
throw new NotImplementedException();
}
public AnimalModel Get(int id)
{
throw new NotImplementedException();
}
public IList<AnimalModel> GetAll()
{
Func<Hashtable, IList<AnimalModel>> operation = delegate (Hashtable parameter)
{
return this.dataAccess.QueryForList<AnimalModel>("GetAnimals", null);
};
return base.DBOperation<IList<AnimalModel>>(operation, null);
}
public int Update(AnimalModel item)
{
throw new NotImplementedException();
}
}
}
|
using Anywhere2Go.Business.Master;
using Anywhere2Go.Business.Utility;
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.Library;
using Anywhere2Go.Library.Datatables;
using Claimdi.Web.TH.Filters;
using Claimdi.Web.TH.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Claimdi.Web.TH.Controllers
{
public class AnnouncementController : Controller
{
// GET: Announcement
[AuthorizeUser(AccessLevel = "View", PageAction = "Announcement")]
public ActionResult Index()
{
AnnouncementViewModel model = new AnnouncementViewModel();
model.AnnouncementStartDate = DateTime.Now.AddDays(-29).ToString("dd/MM/yyyy");
model.AnnouncementEndDate = DateTime.Now.ToString("dd/MM/yyyy");
ViewBag.AnnouncementTypeList = this.GetDropDownAnnouncementType();
ViewBag.AnnouncementAppList = this.GetDropDownApplication();
ViewBag.AnnouncementDeviceList = this.GetDropDownDevice();
var isactive = this.GetDropDownIsActive();
isactive[1].Selected = true;
ViewBag.AnnouncementIsActive = isactive;
return View(model);
}
[HttpPost]
public JsonResult AjaxGetAnnouncementHandler(DTParameters param)
{
try
{
var auth = ClaimdiSessionFacade.ClaimdiSession;
AnnouncementLogic anouncement = new AnnouncementLogic();
DTResultAnnouncement<AnnouncementDataTables> result = anouncement.GetAnnouncementByCondition(param, auth);
return Json(result);
}
catch (Exception ex)
{
return Json(new { error = ex.Message });
}
}
[AuthorizeUser(AccessLevel = "View", PageAction = "Announcement")]
public ActionResult AnnouncementDetail(int id = 0)
{
Announcement model = new Announcement();
AnnouncementLogic annLogic = new AnnouncementLogic();
SurveyorController sur = new SurveyorController();
if (id != 0)
{
model = annLogic.GetAnnouncementById(id);
}
CompanyController com = new CompanyController();
DepartmentController dep = new DepartmentController();
ViewBag.AnnouncementTypeList = this.GetDropDownAnnouncementType();
ViewBag.AnnouncementAppList = this.GetDropDownApplication();
ViewBag.AnnouncementDeviceList = this.GetDropDownDevice();
ViewBag.AnnouncementCompanyList = com.GetDropDownCompanyAnouncement();
ViewBag.AnnouncementDepList = dep.GetDropDownDepByComId(new Guid());
return View(model);
}
[HttpPost]
[ValidateInput(false)]
[AuthorizeUser(AccessLevel = "Edit", PageAction = "Announcement")]
public JsonResult CreateEdit(Announcement model)
{
BaseResult<AnnouncementLogic.AnnouncementActionModel> res = new BaseResult<AnnouncementLogic.AnnouncementActionModel>();
var auth = ClaimdiSessionFacade.ClaimdiSession;
AnnouncementLogic announcement = new AnnouncementLogic();
if (!string.IsNullOrEmpty(Request["dateSend"]))
{
if (!string.IsNullOrEmpty(Request["timeSend"]))
{
model.DatetimeSend = DateExtension.ConvertDateAndTimeTh2En(Request["dateSend"] + " " + Request["timeSend"]);
}
else
{
model.DatetimeSend = DateExtension.ConvertDateAndTimeTh2En(Request["dateSend"] + " 00:00");
}
}
if (!string.IsNullOrEmpty(Request["dateExpire"]))
{
if (!string.IsNullOrEmpty(Request["timeExpire"]))
{
model.ExpireDate = DateExtension.ConvertDateAndTimeTh2En(Request["dateExpire"] + " " + Request["timeExpire"]);
}
else
{
model.ExpireDate = DateExtension.ConvertDateAndTimeTh2En(Request["dateExpire"] + " 23:59");
}
}
// model.IsSend = false;
if (!string.IsNullOrEmpty(model.DepId))
{
var depArray = model.DepId.Split(',');
var strTopic = "";// 'dogs' in topics || 'cats' in topics
for (int i = 0; i <= depArray.Length -1; i++)
{
strTopic += " '" + depArray[i] + "'" + " in topics ||";
}
strTopic=strTopic.TrimEnd('|').TrimEnd('|').Trim();
model.Topic = strTopic;
}
else if (model.CompanyId !=null && model.CompanyId != Guid.Empty)
{
model.Topic=model.CompanyId.ToString();
}
else
{
model.Topic = "news";
}
res = announcement.SaveAnnouncement(model, auth);
CompanyController com = new CompanyController();
DepartmentController dep = new DepartmentController();
ViewBag.AnnouncementTypeList = this.GetDropDownAnnouncementType();
ViewBag.AnnouncementAppList = this.GetDropDownApplication();
ViewBag.AnnouncementDeviceList = this.GetDropDownDevice();
ViewBag.AnnouncementCompanyList = com.GetDropDownCompanyAnouncement();
ViewBag.AnnouncementDepList = dep.GetDropDownDepByComId(new Guid());
return Json(res);
}
[HttpPost]
[ValidateInput(false)]
[AuthorizeUser(AccessLevel = "Edit", PageAction = "Announcement")]
public JsonResult SendPushNotify(Announcement model)
{
BaseResult<AnnouncementLogic.AnnouncementActionModel> resSave = new BaseResult<AnnouncementLogic.AnnouncementActionModel>();
var auth = ClaimdiSessionFacade.ClaimdiSession;
AnnouncementLogic announcement = new AnnouncementLogic();
if (!string.IsNullOrEmpty(Request["dateSend"]))
{
if (!string.IsNullOrEmpty(Request["timeSend"]))
{
model.DatetimeSend = DateExtension.ConvertDateAndTimeTh2En(Request["dateSend"] + " " + Request["timeSend"]);
}
else
{
model.DatetimeSend = DateExtension.ConvertDateAndTimeTh2En(Request["dateSend"] + " 00:00");
}
}
if (!string.IsNullOrEmpty(Request["dateExpire"]))
{
if (!string.IsNullOrEmpty(Request["timeExpire"]))
{
model.ExpireDate = DateExtension.ConvertDateAndTimeTh2En(Request["dateExpire"] + " " + Request["timeExpire"]);
}
else
{
model.ExpireDate = DateExtension.ConvertDateAndTimeTh2En(Request["dateExpire"] + " 23:59");
}
}
// model.IsSend = false;
if (!string.IsNullOrEmpty(model.DepId))
{
var depArray = model.DepId.Split(',');
var strTopic = "";// 'dogs' in topics || 'cats' in topics
for (int i = 0; i <= depArray.Length - 1; i++)
{
strTopic += " '" + depArray[i] + "'" + " in topics ||";
}
strTopic = strTopic.TrimEnd('|').TrimEnd('|').Trim();
model.Topic = strTopic;
}
else if (model.CompanyId != null && model.CompanyId != Guid.Empty)
{
model.Topic = model.CompanyId.ToString();
}
else
{
model.Topic = "news";
}
resSave = announcement.SaveAnnouncement(model, auth);
BaseResult<FCMPushNotification> res = new BaseResult<FCMPushNotification>();
AnnouncementLogic an = new AnnouncementLogic();
if (resSave.StatusCode == "200")
{
if (resSave.Result.Announcement.Id != 0)
{
try
{
res = an.PushAnnouncementById(resSave.Result.Announcement.Id, "ios"); //SendNotificationTopic
res = an.PushAnnouncementById(resSave.Result.Announcement.Id, "ad"); //SendNotificationTopic
}
catch (Exception)
{
res.StatusCode = "500";
res.Message = "ส่งข้อความผิดพลาด";
}
}
}
return Json(res);
}
public JsonResult SendPushNotifyProc(int id)
{
BaseResult<FCMPushNotification> res = new BaseResult<FCMPushNotification>();
AnnouncementLogic an = new AnnouncementLogic();
try
{
res = an.PushAnnouncementById(id, "ios",false); //SendNotificationTopic
res = an.PushAnnouncementById(id, "ad",false);
}
catch (Exception)
{
res.StatusCode = "500";
res.Message = "ส่งข้อความผิดพลาด";
}
return Json(res, JsonRequestBehavior.AllowGet);
}
#region dropdown
public List<SelectListItem> GetDropDownAnnouncementType()
{
AnnouncementLogic obj = new AnnouncementLogic();
List<SelectListItem> ls = new List<SelectListItem>();
var annType = obj.GetAnnouncementType(true);
ls.Add(new SelectListItem() { Text = "ประเภทข่าว", Value = "" });
foreach (var temp in annType)
{
ls.Add(new SelectListItem() { Text = temp.AnnouncementTypeName, Value = temp.AnnouncementTypeId });
}
return ls;
}
public List<SelectListItem> GetDropDownApplication()
{
List<SelectListItem> ls = new List<SelectListItem>();
ls.Add(new SelectListItem() { Text = "Application", Value = "" });
ls.Add(new SelectListItem() { Text = "ClaimDi Bike", Value = "claimdibike" });
ls.Add(new SelectListItem() { Text = "ClaimDi Consumer", Value = "claimdiconsumer" });
return ls;
}
public List<SelectListItem> GetDropDownDevice()
{
List<SelectListItem> ls = new List<SelectListItem>();
ls.Add(new SelectListItem() { Text = "Device", Value = "" });
ls.Add(new SelectListItem() { Text = "Ios", Value = "ios" });
ls.Add(new SelectListItem() { Text = "Android", Value = "ad" });
return ls;
}
public List<SelectListItem> GetDropDownIsActive()
{
List<SelectListItem> ls = new List<SelectListItem>();
ls.Add(new SelectListItem() { Text = "ทั้งหมด", Value = "" });
ls.Add(new SelectListItem() { Text = "ใช้งาน", Value = "1" });
ls.Add(new SelectListItem() { Text = "ไม่ใช้งาน", Value = "0" });
return ls;
}
#endregion
public ActionResult AnnouncementNews(int id = 0)
{
Announcement model = new Announcement();
AnnouncementLogic annLogic = new AnnouncementLogic();
if (id != 0)
{
model = annLogic.GetAnnouncementById(id);
}
return View(model);
}
}
} |
using DAL;
using DAL.Contracts;
using ServiceLayer.Contracts;
using System;
using ServiceLayer.DB;
using Unity;
using Unity.Lifetime;
using WebAppMVC.Entities;
using System.Data.Entity;
using DAL.Context;
namespace WebAppMVC
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public static class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Configured Unity Container.
/// </summary>
public static IUnityContainer Container => container.Value;
#endregion
/// <summary>
/// Registers the type mappings with the Unity container.
/// </summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>
/// There is no need to register concrete types such as controllers or
/// API controllers (unless you want to change the defaults), as Unity
/// allows resolving a concrete type even if it was not previously
/// registered.
/// </remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below.
// Make sure to add a Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your type's mappings here.
// container.RegisterType<IProductRepository, ProductRepository>();
container.RegisterType<ICatalogService, DbCatalogService>(new PerThreadLifetimeManager())
//.RegisterType<ICatalogRepository, EfMovieRepository>(new PerThreadLifetimeManager())
.RegisterType<IDalUnitOfWork, EFUnitOfWork>()
.RegisterInstance<DB>(new DB("Vidly"));
// .RegisterType()
}
}
} |
//############################\\
//Copyrights (c) DarkSky Inc. \\
//Copyrights (c) Only Me Game \\
// https://onlymegame.com \\
//############################\\
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class EasyFpsCounter{
public static Object cusPref;
// public static int maxFrameRate;
public static EasyFps EasyFps;
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Org.Common.Web.Logging
{
public class LoggingOptions
{
public string AppZone { get; set; }
public string ElasticSearchUri { get; set; }
public string ErrorLoggingIndex { get; set; }
public string RequestLoggingIndex { get; set; }
public bool RequestLoggingEnabled { get; set; }
public LoggingOptions()
{
RequestLoggingEnabled = true;
}
}
}
|
using AuctionApi.Models;
using System.Collections.Generic;
using TechTalk.SpecFlow;
namespace SpecflowWorkshop
{
[Binding]
class Hooks
{
private readonly RetrieveAuctionContext _context;
public Hooks(RetrieveAuctionContext context)
{
_context = context;
}
[BeforeScenario]
public void InitializeScenario()
{
_context.Storage = new List<Auction>();
}
[AfterScenario()]
public void Cleanup()
{
_context.Storage.Clear();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using VesApp.Domain;
namespace VesApp.API.Controllers
{
public class ProjectsController : ApiController
{
private DataContext db = new DataContext();
// GET: api/Projects
public IQueryable<Project> GetProjects()
{
return db.Projects;
}
// GET: api/Projects/5
[ResponseType(typeof(Project))]
public async Task<IHttpActionResult> GetProject(int id)
{
Project project = await db.Projects.FindAsync(id);
if (project == null)
{
return NotFound();
}
return Ok(project);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProjectExists(int id)
{
return db.Projects.Count(e => e.IdProject == id) > 0;
}
}
} |
using Irony.Interpreter;
using Irony.Parsing;
namespace Bitbrains.AmmyParser
{
public partial class AstAmmyBindSourceElementName
{
public IAstAmmyBindSourceSource GetData(ScriptThread thread)
{
var tmp = base.DoEvaluate(thread);
return new AstAmmyBindSourceElementNameData(Span, (string)tmp);
}
protected override object DoEvaluate(ScriptThread thread) => GetData(thread);
}
public class AstAmmyBindSourceElementNameData : IBaseData, IAstAmmyBindSourceSource
{
public AstAmmyBindSourceElementNameData(SourceSpan span, string elementName)
{
Span = span;
ElementName = elementName;
}
public override string ToString() => "\"" + ElementName + "\"";
public SourceSpan Span { get; }
public string ElementName { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Marketplaces.Entityes;
namespace Infra.Mapeamentos
{
public class MappingMessageParticipant : EntityTypeConfiguration<MessageParticipant>
{
public MappingMessageParticipant()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
this.Property(t => t.UserID)
.IsRequired()
.HasMaxLength(128);
// Table & Column Mappings
this.ToTable("MessageParticipant");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.MessageThreadID).HasColumnName("MessageThreadID");
this.Property(t => t.UserID).HasColumnName("UserID");
// Relationships
this.HasRequired(t => t.AspNetUser)
.WithMany(t => t.MessageParticipants)
.HasForeignKey(d => d.UserID).WillCascadeOnDelete();
this.HasRequired(t => t.MessageThread)
.WithMany(t => t.MessageParticipants)
.HasForeignKey(d => d.MessageThreadID);
}
}
}
|
using System;
namespace Tools
{
public class StringController
{
private readonly string _currentString;
private int _iterator;
public StringController(string currentString)
{
_currentString = currentString;
_iterator = 0;
}
public char GetNext()
{
if (_iterator >= _currentString.Length)
throw new IndexOutOfRangeException("Strting Ended");
return _currentString[_iterator++];
}
public bool TryGetNext(out char result)
{
if (_iterator >= _currentString.Length)
{
result = default(char);
return false;
}
result = _currentString[_iterator++];
return true;
}
public bool IsFinish()
{
return _iterator >= _currentString.Length;
}
public string GetCompleteString()
{
return _currentString;
}
public bool IsRestContains(string s)
{
var t = _currentString.Substring(_iterator);
return t.Contains(s);
}
public int GetNextIndex()
{
return _iterator;
}
}
}
|
using System.Collections.Generic;
namespace Cafe.API.Models.Repository
{
public interface IDataRepository<TEntity>
{
IEnumerable<TEntity> GetAll();
TEntity Get(int id);
void Add(TEntity entity);
void Update(TEntity entityToUpdate, TEntity entity);
void Delete(TEntity entity);
IEnumerable<TEntity> GetSales(int clientId);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ScanINOUTVer2
{
public partial class frmPOLogin : Form
{
public string pwd;
public frmPOLogin()
{
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == pwd)
{
this.Tag = "ok";
this.Close();
}
else
{
MessageBox.Show("Invalid Password!");
}
}
private void frmPOLogin_Load(object sender, EventArgs e)
{
FileInfo fi = new FileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//POPWD.txt");
if (fi.Exists)
{
StreamReader sr = new StreamReader(fi.FullName);
pwd = sr.ReadToEnd().Trim();
sr.Close();
sr.Dispose();
sr = null;
}
else
{
StreamWriter sw = new StreamWriter(fi.FullName, false);
sw.Write("admin");
sw.Close();
sw.Dispose();
sw = null;
StreamReader sr = new StreamReader(fi.FullName);
pwd = sr.ReadToEnd().Trim();
sr.Close();
sr.Dispose();
sr = null;
}
}
}
}
|
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using Alabo.Validations.Aspects;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Alabo.Datas.Stores.Add.Mongo {
public abstract class AddAsyncMongoStore<TEntity, TKey> : AddMongoStore<TEntity, TKey>,
IAddAsyncStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected AddAsyncMongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public async Task AddManyAsync([Valid] IEnumerable<TEntity> entities) {
await Collection.InsertManyAsync(entities);
}
public async Task<bool> AddSingleAsync([Valid] TEntity entity) {
var model = (IMongoEntity)entity;
if (model.IsObjectIdEmpty()) {
model.Id = ObjectId.GenerateNewId();
model.CreateTime = DateTime.Now;
}
await Collection.InsertOneAsync(entity);
return true;
}
}
} |
using System;
using System.IO;
using System.Web;
namespace WeatherForecast.Services
{
public class CombinedLogger : ILogger
{
public void Log(LogLevel level, string message)
{
using (StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("~/Log/log.txt"), true))
{
sw.WriteLine("{0} [{1}] {2}", DateTime.Now, level, message);
System.Diagnostics.Debug.WriteLine("{0} [{1}] {2}", DateTime.Now, level, message);
}
}
}
} |
namespace RosPurcell.Web.Services.Search
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Examine;
using Examine.Providers;
using Examine.SearchCriteria;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using RosPurcell.Web.Constants.Search;
using RosPurcell.Web.Helpers.Extensions;
using RosPurcell.Web.Services.Search.Base;
using UmbracoExamine;
public class SearchService : BaseSearchService, ISearchService
{
private readonly BaseSearchProvider _searcher;
private readonly Dictionary<string, List<FacetValueCache>> _facetsCacheContainer =
new Dictionary<string, List<FacetValueCache>>();
public SearchService()
{
_searcher = GetSearcher();
}
public SearchResultCollection Search(SearchCriteria criteria)
{
var luceneQuery = new StringBuilder("+__IndexType:content ");
var searchCriteria = _searcher.CreateSearchCriteria(IndexTypes.Content, BooleanOperation.And);
if (!string.IsNullOrWhiteSpace(criteria.Query))
{
luceneQuery = AppendFieldsToQuery(luceneQuery, criteria.Query, new[]
{
SearchFields.Title,
SearchFields.Heading,
SearchFields.NodeName,
SearchFields.Ingredients,
SearchFields.Courses,
SearchFields.Cuisines
});
}
var resultCollection = new SearchResultCollection();
foreach (var facet in criteria.Facets)
{
var facetQuery = new StringBuilder(luceneQuery.ToString());
facetQuery = AppendFacetsToQuery(facetQuery, criteria.SelectedFacets.Where(x => !string.Equals(x.Key, facet.Key)).ToDictionary(x => x.Key, x => x.Value));
resultCollection.Facets
.Add(new KeyValuePair<string, IDictionary<int, int>>(facet.Key, GetFacets(facetQuery, facet)));
}
if (criteria.SelectedFacets.IsAndAny())
{
luceneQuery = AppendFacetsToQuery(luceneQuery, criteria.SelectedFacets);
}
searchCriteria.RawQuery(luceneQuery.ToString());
var results = _searcher.Search(searchCriteria);
resultCollection.Results = MapResults(results);
return resultCollection;
}
private static IEnumerable<RecipeSearchResult> MapResults(ISearchResults results)
{
return results.Select(result => new RecipeSearchResult { Id = result.Id }).ToList();
}
protected BaseSearchProvider GetSearcher()
{
var searcher = ExamineManager.Instance.SearchProviderCollection["RecipesSearcher"];
if (searcher == null)
{
throw new NullReferenceException("Searcher has not been configured.");
}
return searcher;
}
/// <summary>
/// Appends the indexed fields to the Lucene search query
/// </summary>
/// <param name="searchString">The Lucene query</param>
/// <param name="q">The search query</param>
/// <param name="fields">The indexed fields</param>
/// <returns>Amended Lucene query</returns>
private static StringBuilder AppendFieldsToQuery(StringBuilder searchString, string q, IEnumerable<string> fields)
{
searchString.Append("+(");
foreach (var field in fields)
{
searchString.AppendFormat("{0}:({1}) ", field, q);
searchString.AppendFormat("{0}:\"{1}\" ", field, q.Replace("\"", string.Empty));
searchString.AppendFormat("{0}:({1}*) ", field, q);
searchString.AppendFormat("{0}:\"{1}*\" ", field, q.Replace("\"", string.Empty));
}
searchString.Append(")");
return searchString;
}
/// <summary>
/// Appends the selected facets to the Lucene search query
/// </summary>
/// <param name="searchString">The Lucene query</param>
/// <param name="facets">Dictionary of selected facets</param>
/// <returns>Amended Lucene query</returns>
private static StringBuilder AppendFacetsToQuery(StringBuilder searchString, IDictionary<string, int> facets)
{
foreach (var facet in facets)
{
searchString.AppendFormat("+{0}:({1})", facet.Key, facet.Value);
}
return searchString;
}
public IDictionary<int, int> GetFacets(StringBuilder luceneQuery, KeyValuePair<string, IEnumerable<int>> facet)
{
var examineSearcher = (UmbracoExamineSearcher)_searcher;
var luceneSearcher = (IndexSearcher)examineSearcher.GetSearcher();
var reader = luceneSearcher.GetIndexReader();
if (!_facetsCacheContainer.ContainsKey(facet.Key))
{
var cache = new List<FacetValueCache>();
foreach (var fieldValue in facet.Value)
{
var facetQuery = new TermQuery(new Term(facet.Key, fieldValue.ToString()));
var facetQueryFilter = new CachingWrapperFilter(new QueryWrapperFilter(facetQuery));
cache.Add(new FacetValueCache(fieldValue, facetQueryFilter));
}
_facetsCacheContainer.Add(facet.Key, cache);
}
var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "content", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
parser.SetAllowLeadingWildcard(true);
var query = parser.Parse(luceneQuery.ToString());
var mainQueryFilter = new CachingWrapperFilter(new QueryWrapperFilter(query));
var facetDefinition = _facetsCacheContainer[facet.Key];
return facetDefinition.ToDictionary(x => x.FacetValue, x => x.GetFacetCount(reader, mainQueryFilter));
}
}
}
|
using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorybrewScripts
{
public class Flower : StoryboardObjectGenerator
{
[Configurable]
public string SpritePath = "SB/dot.png";
[Configurable]
public int StartTime = 0;
[Configurable]
public int EndTime = 1000;
[Configurable]
public int CentreX = 320;
[Configurable]
public int CentreY = 240;
[Configurable]
public Color4 Color = new Color4(255, 255, 255, 100);
public override void Generate()
{
{
int Count = 10;
for (int i = 0; i < Count; i++)
{
var Radius = 60 ;
double x, y, x1, y1;
x = CentreX + Radius;
y = CentreY ;
int BeatTimer = 360;
int time = (EndTime - StartTime ) / BeatTimer;
int time2 = StartTime ;
var angle = i * (Math.PI * 2) / Count+ (40* Math.PI /180);
var ranTime = Random(0,1000);
var cor = Random(0.5,1);
var dot = GetLayer("").CreateSprite(SpritePath, OsbOrigin.BottomCentre);
dot.Scale(OsbEasing.OutQuart,StartTime + ranTime, StartTime + ranTime + 2000, 0,0.8 );
//dot.Fade(EndTime - 500,EndTime ,1,0);
dot.Rotate(StartTime,EndTime,angle,angle + (400* Math.PI /180));
//dot.Fade(StartTime, StartTime + 1000,0, Color.A);
dot.ColorHsb(StartTime,355836,0,1,0.3,0,1,0.2);
dot.ColorHsb(OsbEasing.InQuart,356654 - 1000,356927,0,1,0.2,0,0,0);
dot.Scale(OsbEasing.InQuart,356654 - ranTime,356927,0.8,0);
//dot.Additive(StartTime,EndTime);
for (int deg = 360 /Count*i; deg < 360 /Count*i + 120 ; deg += BeatTimer/120)
{
double rad = deg * Math.PI / 180;
x1 = Radius * Math.Cos(rad) + CentreX;
y1 = Radius * Math.Sin(rad) + CentreY;
dot.Move(time2, time2 + time, x, y, x1, y1);
time2 += time;
x = x1;
y = y1;
}
}
}
{
int Count = 10;
for (int i = 0; i < Count; i++)
{
var Radius = 0 ;
double x, y, x1, y1;
x = CentreX + Radius;
y = CentreY ;
int BeatTimer = 360;
int time = (EndTime - StartTime ) / BeatTimer;
int time2 = StartTime ;
var angle = i * (Math.PI * 2) / Count+ (40* Math.PI /180);
var ranTime = Random(0,1000);
var cor = Random(0.3,0.6);
var dot = GetLayer("").CreateSprite(SpritePath, OsbOrigin.BottomCentre);
dot.Scale(OsbEasing.OutQuart,StartTime + ranTime, StartTime + ranTime + 2000, 0,0.6 );
//dot.Fade(EndTime - 500,EndTime ,1,0);
dot.Rotate(StartTime,EndTime,angle,angle + (360* Math.PI /180));
//dot.Fade(StartTime, StartTime + 1000,0, Color.A);
dot.ColorHsb(StartTime,355836,0,1,cor,0,1,cor-0.2);
dot.ColorHsb(OsbEasing.InQuart,356654 - 1000,356927,0,1,cor-0.2,0,0,0);
dot.Scale(OsbEasing.InQuart,356654 - ranTime,356927,0.6,0);
//dot.Additive(StartTime,EndTime);
for (int deg = 360 /Count*i; deg < 360 /Count*i + 240 ; deg += BeatTimer/240)
{
double rad = deg * Math.PI / 180;
x1 = Radius * Math.Cos(rad) + CentreX;
y1 = Radius * Math.Sin(rad) + CentreY;
//dot.Move(time2, time2 + time, x, y, x1, y1);
time2 += time;
x = x1;
y = y1;
}
}
}
{
int Count = 6;
for (int i = 0; i < Count; i++)
{
var Radius = -2 ;
double x, y, x1, y1;
x = CentreX + Radius;
y = CentreY ;
int BeatTimer = 360;
int time = (EndTime - StartTime ) / BeatTimer;
int time2 = StartTime ;
var angle = i * (Math.PI * 2) / Count+ (40* Math.PI /180);
var ranTime = Random(0,1000);
var cor = Random(0.6,1);
var dot = GetLayer("").CreateSprite(SpritePath, OsbOrigin.BottomCentre);
dot.Scale(OsbEasing.OutQuart,StartTime + ranTime, StartTime + ranTime + 2000, 0,0.4 );
//dot.Fade(EndTime - 500,EndTime ,1,0);
dot.Rotate(StartTime,EndTime,angle,angle + (360* Math.PI /180));
//dot.Fade(StartTime, StartTime + 1000,0, Color.A);
dot.ColorHsb(StartTime,355836,0,1,cor,0,0.8,cor-0.2);
dot.ColorHsb(OsbEasing.InQuart,356654 - 1000,356927,0,0.8,cor-0.2,0,0,0);
dot.Scale(OsbEasing.InQuart,356654 - ranTime,356927,0.4,0);
//dot.Additive(StartTime,EndTime);
for (int deg = 360 /Count*i; deg < 360 /Count*i + 360 ; deg += BeatTimer/360)
{
double rad = deg * Math.PI / 180;
x1 = Radius * Math.Cos(rad) + CentreX;
y1 = Radius * Math.Sin(rad) + CentreY;
dot.Move(time2, time2 + time, x, y, x1, y1);
time2 += time;
x = x1;
y = y1;
}
}
}
}
}
}
|
/// Author: Nate Hales
/// <summary>
/// Boss attack data. This is a class that can be instansianed by other scripts as a bass template to build a bosses attack arround.
/// </summary>
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class BossAttackData {
public string attackName;
public int attackIndex;
public float damageValue;
public float attackRange;
public AudioClip attackSound;
public AnimationClip attackAnim;
public bool bCanInterrupt;
public enum targetType{
AreaOfEffect,
SingleTarget,
Defualt
}
public targetType attackType;
}
|
using BookRentalShop20;
using MetroFramework;
using MetroFramework.Forms;
using System;
using System.Windows.Forms;
namespace _20200620_디비연동하기
{
public partial class MainForm : MetroForm
{
public MainForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoginForm loginForm = new LoginForm();
loginForm.ShowDialog();
}
private void MainForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
if(MetroMessageBox.Show(this,"정말 종료하시겠습니까?", "종료", MessageBoxButtons.YesNo, MessageBoxIcon.Information)==DialogResult.Yes )
{
e.Cancel = false; //이게 값이 없는거니까 ok
}
else
{
e.Cancel = true; // 이게 값이 있는거니까 no
}
}
/// <summary>
/// 코딩의 메소드화
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
private void ChildForm( Form form,string strFormTitle)
{
form.Text = strFormTitle;
form.Dock = DockStyle.Fill;
form.MdiParent = this;
form.Show();
form.WindowState = FormWindowState.Maximized;
}
private void 구분코드관리DToolStripMenuItem_Click(object sender, EventArgs e)
{
DivForm form = new DivForm();
ChildForm(form, "구분코드관리");
}
private void 책대여관리RToolStripMenuItem_Click(object sender, EventArgs e)
{
RentalForm form = new RentalForm();
ChildForm(form, "책대여관리");
}
}
}
|
using System;
using System.Collections.Generic;
namespace EqualityLogic
{
public class StartUp
{
static void Main(string[] args)
{
SortedSet<IPerson> setPersons = new SortedSet<IPerson>();
HashSet<IPerson> hashPersons = new HashSet<IPerson>();
int number = int.Parse(Console.ReadLine());
for (int i = 0; i < number; i++)
{
string[] input = Console.ReadLine().Split();
string name = input[0];
int age = int.Parse(input[1]);
IPerson person = new Person(name, age);
setPersons.Add(person);
hashPersons.Add(person);
}
Console.WriteLine(setPersons.Count);
Console.WriteLine(hashPersons.Count);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommandExample.Draw;
namespace CommandExample
{
public partial class DrawCanvas : UserControl, IDrawable
{
public DrawCanvas()
{
InitializeComponent();
}
private Color _color = Color.Red;
private int _radius = 6;
private MacroCommand _history = null;
public void Draw(int x, int y)
{
using (Graphics g = CreateGraphics())
using (Brush brush = new SolidBrush(_color))
{
g.FillEllipse(brush, x - _radius, y - _radius, _radius * 2, _radius * 2);
}
}
public void SetHistory(MacroCommand history)
{
this._history = history;
}
public void EraseCanvas()
{
using (Graphics g = CreateGraphics())
{
g.Clear(Color.White);
}
}
private void DrawCanvas_Paint(object sender, PaintEventArgs e)
{
if (_history != null)
_history.Execute();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NLog;
using SongLoaderPlugin;
using SongLoaderPlugin.OverrideClasses;
using TMPro;
using TwitchIntegrationPlugin.ICSharpCode.SharpZipLib.Zip;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using VRUI;
using Logger = NLog.Logger;
namespace TwitchIntegrationPlugin.UI
{
public class RequestInfoViewController : VRUIViewController
{
private bool _initialized;
private TwitchIntegrationUi _ui;
private TextMeshProUGUI _songName;
private TextMeshProUGUI _requestorName;
private Button _downloadButton;
private Button _skipButton;
private Logger _logger;
private string _songTitle;
private string _requestorNameString;
private QueuedSong _queuedSong;
public event Action SkipButtonPressed;
public event Action DownloadButtonpressed;
protected override void DidActivate(bool firstActivation, ActivationType activationType)
{
if (_songName == null)
{
_songName = _ui.CreateText(rectTransform, _songTitle, new Vector2(0f, 0f));
_songName.fontSize = 6f;
_songName.rectTransform.anchorMin = new Vector2(0.0f, 0.7f);
_songName.rectTransform.anchorMax = new Vector2(1f, 0.6f);
}
else
_songName.SetText(_songTitle);
if (_requestorName == null)
{
_requestorName = _ui.CreateText(rectTransform, "Requested By:\n" + _requestorNameString, new Vector2(0f, 0f));
_requestorName.fontSize = 4f;
_requestorName.rectTransform.anchorMin = new Vector2(0.2f, 0.4f);
_requestorName.rectTransform.anchorMax = new Vector2(0.8f, 0.5f);
}
else
_requestorName.SetText("Requested By:\n" + _requestorNameString);
if (_skipButton == null)
{
_skipButton = _ui.CreateUiButton(rectTransform, "ApplyButton");
((RectTransform)_skipButton.transform).anchorMin = new Vector2(0.6f, 0.1f);
((RectTransform)_skipButton.transform).anchorMax = new Vector2(1f, 0.2f);
((RectTransform)_skipButton.transform).sizeDelta = new Vector2(0f, 0f);
((RectTransform)_skipButton.transform).anchoredPosition = new Vector2(-5f, 0f);
_ui.SetButtonText(ref _skipButton, "Skip");
_skipButton.onClick.AddListener(OnSkipButtonPressed);
}
if (_downloadButton == null)
{
_downloadButton = _ui.CreateUiButton(rectTransform, "ApplyButton");
((RectTransform)_downloadButton.transform).anchorMin = new Vector2(0f, 0.1f);
((RectTransform)_downloadButton.transform).anchorMax = new Vector2(0.4f, 0.2f);
((RectTransform)_downloadButton.transform).sizeDelta = new Vector2(0f, 0f);
((RectTransform)_downloadButton.transform).anchoredPosition = new Vector2(5f, 0f);
_ui.SetButtonText(ref _downloadButton, "Download");
_downloadButton.GetComponentInChildren<TextMeshProUGUI>().fontSize = _downloadButton.GetComponentInChildren<TextMeshProUGUI>().fontSize - 0.3f;
_downloadButton.onClick.AddListener(OnDownloadButtonPressed);
}
}
public void Init(string songName, string requestorName)
{
_ui = TwitchIntegrationUi.Instance;
_logger = LogManager.GetCurrentClassLogger();
_songTitle = songName;
_requestorNameString = requestorName;
_initialized = true;
}
public void SetQueuedSong(QueuedSong song)
{
if (!_initialized) return;
_songName.SetText(song.BeatName);
_requestorName.SetText("Requested By:\n" + song.RequestedBy);
}
private void OnSkipButtonPressed()
{
SkipButtonPressed?.Invoke();
}
private void OnDownloadButtonPressed()
{
DownloadButtonpressed?.Invoke();
}
public IEnumerator DownloadSongCoroutine(QueuedSong song)
{
_ui.SetButtonText(ref _downloadButton, "Downloading...");
_downloadButton.interactable = false;
_skipButton.interactable = false;
_logger.Debug("Web Request sent to: " + song.DownloadUrl);
var www = UnityWebRequest.Get(song.DownloadUrl);
var timeout = false;
var time = 0f;
var asyncRequest = www.SendWebRequest();
while (!asyncRequest.isDone || asyncRequest.progress < 1f)
{
yield return null;
time += Time.deltaTime;
if (!(time >= 15f) || asyncRequest.progress != 0f) continue;
www.Abort();
timeout = true;
}
if (www.isNetworkError || www.isHttpError || timeout)
{
www.Abort();
_skipButton.interactable = true;
_downloadButton.interactable = true;
_ui.SetButtonText(ref _downloadButton, "Download");
}
else
{
var zipPath = "";
var customSongsPath = "";
try
{
_logger.Debug("Download complete in: " + time);
var data = www.downloadHandler.data;
var docPath = Application.dataPath;
docPath = docPath.Substring(0, docPath.Length - 5);
docPath = docPath.Substring(0, docPath.LastIndexOf("/", StringComparison.Ordinal));
customSongsPath = docPath + "/CustomSongs/" + song.Id + "/";
zipPath = customSongsPath + song.Id + ".zip";
if (!Directory.Exists(customSongsPath))
{
Directory.CreateDirectory(customSongsPath);
}
File.WriteAllBytes(zipPath, data);
}
catch (Exception e)
{
_logger.Error(e);
_skipButton.interactable = true;
_downloadButton.interactable = true;
_ui.SetButtonText(ref _downloadButton, "Download");
}
var zip = new FastZip();
zip.ExtractZip(zipPath, customSongsPath, null);
try
{
SongLoader.Instance.RefreshSongs();
_queuedSong = song;
SongLoader.SongsLoadedEvent += OnSongsLoaded;
}
catch (Exception e)
{
_logger.Error(e);
}
File.Delete(zipPath);
_skipButton.interactable = true;
}
}
private void OnSongsLoaded(SongLoader songLoader, List<CustomLevel> list)
{
SongLoader.SongsLoadedEvent -= OnSongsLoaded;
_downloadButton.interactable = true;
if (DoesSongExist(_queuedSong))
{
_ui.SetButtonText(ref _downloadButton, "Downloaded");
}
else
_ui.SetButtonText(ref _downloadButton, "Download");
_queuedSong = null;
FindObjectOfType<LevelRequestFlowCoordinator>().CheckQueueAndUpdate(); //This kinda goes against the purpose of a flow controller, but I just want it to work.
}
public void SetDownloadButtonText(string text)
{
_ui.SetButtonText(ref _downloadButton, text);
}
public void SetDownloadState(bool state)
{
_downloadButton.interactable = state;
}
public void SetSkipState(bool state)
{
_skipButton.interactable = state;
}
public bool DoesSongExist(QueuedSong song)
{
try
{
return SongLoader.CustomLevels.FirstOrDefault(x => x.levelID.Contains(song.SongHash)) != null;
}
catch (Exception e)
{
_logger.Debug(e); //Not a fatal error.
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
namespace DataAccess.Connection
{
public class CommandExecutor
{
private readonly string command;
private readonly string connectionString;
private readonly bool storedProc;
private readonly List<SqlParameter> paramList = new List<SqlParameter>();
public CommandExecutor(string command, string connectionString, bool storedProc = true)
{
this.command = command;
this.connectionString = connectionString;
this.storedProc = storedProc;
}
public void SetParam(string name, object value, SqlDbType type, string typeName = null)
{
var param = new SqlParameter(name, type)
{
Value = value
};
if (typeName != null)
{
param.TypeName = typeName;
}
paramList.Add(param);
}
public object ExecuteCommand(bool nonQuery = false)
{
object result;
var dataSet = new DataSet();
using (var connection = new SqlConnection())
{
connection.ConnectionString = connectionString;
var sqlCommand = new SqlCommand(command, connection)
{
CommandType = storedProc ? CommandType.StoredProcedure : CommandType.Text
};
paramList.ForEach(param => sqlCommand.Parameters.Add(param));
try
{
connection.Open();
if (nonQuery)
{
sqlCommand.ExecuteNonQuery();
result = null;
}
else
{
var adapter = new SqlDataAdapter {SelectCommand = sqlCommand};
adapter.Fill(dataSet);
result = dataSet;
}
}
catch (Exception ex)
{
result = ex;
}
finally
{
connection.Close();
}
}
return result;
}
}
} |
/// <summary>
/// Summary description
/// </summary>
namespace com.Sconit.Web.Controllers.SP
{
#region reference
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using com.Sconit.Entity.ORD;
using com.Sconit.Entity.SYS;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.ORD;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using System.Text;
using System;
using System.ComponentModel;
#endregion
/// <summary>
/// This controller response to control the Address.
/// </summary>
public class SupplierReceiptController : WebAppBaseController
{
#region Properties
/// <summary>
/// Gets or sets the this.GeneMgr which main consider the ProcurementGoodsReceipt security
/// </summary>
//public IGenericMgr genericMgr { get; set; }
#endregion
/// <summary>
/// hql
/// </summary>
private static string selectCountStatement = "select count(*) from ReceiptMaster as r";
/// <summary>
/// hql
/// </summary>
private static string selectStatement = "select r from ReceiptMaster as r";
//public IGenericMgr genericMgr { get; set; }
#region public actions
/// <summary>
/// Index action for ProcurementGoodsReceipt controller
/// </summary>
/// <returns>Index view</returns>
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
public ActionResult Index()
{
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
public ActionResult _ReceiptDetail(string receiptNo)
{
string hql = "select r from ReceiptDetail as r where r.ReceiptNo = ?";
IList<ReceiptDetail> receiptDetailList = genericMgr.FindAll<ReceiptDetail>(hql, receiptNo);
return PartialView(receiptDetailList);
}
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
public ActionResult Edit(string receiptNo)
{
if (string.IsNullOrEmpty(receiptNo))
{
return HttpNotFound();
}
else
{
ViewBag.ReceiptNo = receiptNo;
ReceiptMaster rm = this.genericMgr.FindById<ReceiptMaster>(receiptNo);
return View(rm);
}
}
[SconitAuthorize(Permissions = "Url_ProcurementReceipt_Cancel")]
public ActionResult CancelIndex()
{
return View();
}
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Detail_Query")]
public ActionResult DetailIndex()
{
return View();
}
/// <summary>
/// List action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel"> ReceiptMaster Search model</param>
/// <returns>return the result view</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
public ActionResult List(GridCommand command, ReceiptMasterSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject))
{
TempData["_AjaxMessage"] = "";
}
else
{
SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions);
}
if (searchCacheModel.isBack == true)
{
ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page;
}
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_ProcurementReceipt_Cancel")]
public ActionResult CancelList(GridCommand command, ReceiptMasterSearchModel searchModel)
{
SearchCacheModel searchCacheModel = ProcessSearchModel(command, searchModel);
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, (ReceiptMasterSearchModel)searchCacheModel.SearchObject);
return View(GetPageData<ReceiptMaster>(searchStatementModel, command));
}
/// <summary>
/// AjaxList action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel"> ReceiptMaster Search Model</param>
/// <returns>return the result action</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
public ActionResult _AjaxList(GridCommand command, ReceiptMasterSearchModel searchModel)
{
this.GetCommand(ref command, searchModel);
if (!this.CheckSearchModelIsNull(searchModel))
{
return PartialView(new GridModel(new List<ReceiptMaster>()));
}
string whereStatement = string.Empty;
ProcedureSearchStatementModel procedureSearchStatementModel = this.PrepareProcedureSearchStatement(command, searchModel, whereStatement);
return PartialView(GetAjaxPageDataProcedure<ReceiptMaster>(procedureSearchStatementModel, command));
}
[GridAction]
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Detail_Query")]
public ActionResult DetailList(GridCommand command, ReceiptMasterSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
if (this.CheckSearchModelIsNull(searchCacheModel.SearchObject))
{
TempData["_AjaxMessage"] = "";
}
else
{
SaveWarningMessage(Resources.SYS.ErrorMessage.Errors_NoConditions);
}
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = true)]
public ActionResult _AjaxRecDetList(GridCommand command, ReceiptMasterSearchModel searchModel)
{
if (!this.CheckSearchModelIsNull(searchModel))
{
return PartialView(new GridModel(new List<ReceiptDetail>()));
}
string whereStatement = string.Empty;
ProcedureSearchStatementModel procedureSearchStatementModel = PrepareSearchDetailStatement(command, searchModel, whereStatement);
return PartialView(GetAjaxPageDataProcedure<ReceiptDetail>(procedureSearchStatementModel, command));
}
#region
[GridAction(EnableCustomBinding = true)]
public void ExportXLS(ReceiptMasterSearchModel searchModel)
{
int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage));
GridCommand command = new GridCommand();
command.Page = 1;
command.PageSize = !this.CheckSearchModelIsNull(searchModel) ? 0 : value;
string whereStatement = null;
ProcedureSearchStatementModel procedureSearchStatementModel = PrepareSearchDetailStatement(command, searchModel, whereStatement);
var ReceiptDetailLists = GetAjaxPageDataProcedure<ReceiptDetail>(procedureSearchStatementModel, command);
List<ReceiptDetail> ReceiptDetailList = ReceiptDetailLists.Data.ToList();
ExportToXLS<ReceiptDetail>("DailsOfSupplierReceiptMaster.xls", ReceiptDetailList);
}
#endregion
#endregion
/// <summary>
/// Search Statement
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">ReceiptMaster Search Model</param>
/// <returns>return ReceiptMaster search model</returns>
private SearchStatementModel PrepareSearchStatement(GridCommand command, ReceiptMasterSearchModel searchModel)
{
string whereStatement = " where r.OrderType in (" + (int)com.Sconit.CodeMaster.OrderType.Procurement + "," + (int)com.Sconit.CodeMaster.OrderType.CustomerGoods + "," + (int)com.Sconit.CodeMaster.OrderType.SubContract + ")"
+ " and r.OrderSubType = " + (int)com.Sconit.CodeMaster.OrderSubType.Normal;
IList<object> param = new List<object>();
HqlStatementHelper.AddLikeStatement("ReceiptNo", searchModel.ReceiptNo, HqlStatementHelper.LikeMatchMode.Start, "r", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("IpNo", searchModel.IpNo, HqlStatementHelper.LikeMatchMode.Start, "r", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("PartyFrom", searchModel.PartyFrom, "r", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("PartyTo", searchModel.PartyTo, "r", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("OrderType", searchModel.GoodsReceiptOrderType, "r", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Flow", searchModel.Flow, "r", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("WMSNo", searchModel.ExternalReceiptNo, HqlStatementHelper.LikeMatchMode.Start, "r", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("Dock", searchModel.Dock, HqlStatementHelper.LikeMatchMode.Start, "r", ref whereStatement, param);
//SecurityHelper.AddPartyFromPermissionStatement(ref whereStatement, "r", "PartyFrom", com.Sconit.CodeMaster.OrderType.Procurement, true);
SecurityHelper.AddPartyFromAndPartyToPermissionStatement(ref whereStatement, "r", "OrderType", "r", "PartyFrom", "r", "PartyTo", com.Sconit.CodeMaster.OrderType.Procurement, true);
if (searchModel.StartDate != null & searchModel.EndDate != null)
{
HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.StartDate, searchModel.EndDate, "r", ref whereStatement, param);
}
else if (searchModel.StartDate != null & searchModel.EndDate == null)
{
HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartDate, "r", ref whereStatement, param);
}
else if (searchModel.StartDate == null & searchModel.EndDate != null)
{
HqlStatementHelper.AddLeStatement("CreateDate", searchModel.EndDate, "r", ref whereStatement, param);
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
if (command.SortDescriptors.Count == 0)
{
sortingStatement = " order by CreateDate desc";
}
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
private ProcedureSearchStatementModel PrepareProcedureSearchStatement(GridCommand command, ReceiptMasterSearchModel searchModel, string whereStatement)
{
List<ProcedureParameter> paraList = new List<ProcedureParameter>();
List<ProcedureParameter> pageParaList = new List<ProcedureParameter>();
paraList.Add(new ProcedureParameter { Parameter = searchModel.ReceiptNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.IpNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Status, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter
{
Parameter = (int)com.Sconit.CodeMaster.OrderType.Procurement + "," + (int)com.Sconit.CodeMaster.OrderType.CustomerGoods + ","
+ (int)com.Sconit.CodeMaster.OrderType.SubContract,
Type = NHibernate.NHibernateUtil.String
});
paraList.Add(new ProcedureParameter { Parameter = (int)com.Sconit.CodeMaster.OrderSubType.Normal, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter { Parameter = searchModel.IpDetailType, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter { Parameter = searchModel.PartyFrom, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.PartyTo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.StartDate, Type = NHibernate.NHibernateUtil.DateTime });
paraList.Add(new ProcedureParameter { Parameter = searchModel.EndDate, Type = NHibernate.NHibernateUtil.DateTime });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Dock, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Item, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.ExternalReceiptNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.ManufactureParty, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Flow, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = true, Type = NHibernate.NHibernateUtil.Boolean });
paraList.Add(new ProcedureParameter { Parameter = CurrentUser.Id, Type = NHibernate.NHibernateUtil.Int32 });
paraList.Add(new ProcedureParameter { Parameter = whereStatement, Type = NHibernate.NHibernateUtil.String });
if (command.SortDescriptors.Count > 0)
{
if (command.SortDescriptors[0].Member == "ReceiptMasterStatusDescription")
{
command.SortDescriptors[0].Member = "Status";
}
}
pageParaList.Add(new ProcedureParameter { Parameter = command.SortDescriptors.Count > 0 ? command.SortDescriptors[0].Member : null, Type = NHibernate.NHibernateUtil.String });
pageParaList.Add(new ProcedureParameter { Parameter = command.SortDescriptors.Count > 0 ? (command.SortDescriptors[0].SortDirection == ListSortDirection.Descending ? "desc" : "asc") : "asc", Type = NHibernate.NHibernateUtil.String });
pageParaList.Add(new ProcedureParameter { Parameter = command.PageSize, Type = NHibernate.NHibernateUtil.Int32 });
pageParaList.Add(new ProcedureParameter { Parameter = command.Page, Type = NHibernate.NHibernateUtil.Int32 });
var procedureSearchStatementModel = new ProcedureSearchStatementModel();
procedureSearchStatementModel.Parameters = paraList;
procedureSearchStatementModel.PageParameters = pageParaList;
procedureSearchStatementModel.CountProcedure = "USP_Search_RecMstrCount";
procedureSearchStatementModel.SelectProcedure = "USP_Search_RecMstr";
return procedureSearchStatementModel;
}
private ProcedureSearchStatementModel PrepareSearchDetailStatement(GridCommand command, ReceiptMasterSearchModel searchModel, string whereStatement)
{
List<ProcedureParameter> paraList = new List<ProcedureParameter>();
List<ProcedureParameter> pageParaList = new List<ProcedureParameter>();
paraList.Add(new ProcedureParameter { Parameter = searchModel.ReceiptNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.IpNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.OrderNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Status, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter
{
Parameter = (int)com.Sconit.CodeMaster.OrderType.CustomerGoods + "," + (int)com.Sconit.CodeMaster.OrderType.Procurement
+ "," + (int)com.Sconit.CodeMaster.OrderType.SubContract,
Type = NHibernate.NHibernateUtil.String
});
paraList.Add(new ProcedureParameter { Parameter = (int)com.Sconit.CodeMaster.OrderSubType.Normal, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter { Parameter = searchModel.IpDetailType, Type = NHibernate.NHibernateUtil.Int16 });
paraList.Add(new ProcedureParameter { Parameter = searchModel.PartyFrom, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.PartyTo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.StartDate, Type = NHibernate.NHibernateUtil.DateTime });
paraList.Add(new ProcedureParameter { Parameter = searchModel.EndDate, Type = NHibernate.NHibernateUtil.DateTime });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Dock, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Item, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.ExternalReceiptNo, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.ManufactureParty, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = searchModel.Flow, Type = NHibernate.NHibernateUtil.String });
paraList.Add(new ProcedureParameter { Parameter = true, Type = NHibernate.NHibernateUtil.Int64 });
paraList.Add(new ProcedureParameter { Parameter = CurrentUser.Id, Type = NHibernate.NHibernateUtil.Int32 });
paraList.Add(new ProcedureParameter { Parameter = whereStatement, Type = NHibernate.NHibernateUtil.String });
if (command.SortDescriptors.Count > 0)
{
if (command.SortDescriptors[0].Member == "StatusDescription")
{
command.SortDescriptors[0].Member = "Status";
}
}
pageParaList.Add(new ProcedureParameter { Parameter = command.SortDescriptors.Count > 0 ? command.SortDescriptors[0].Member : null, Type = NHibernate.NHibernateUtil.String });
pageParaList.Add(new ProcedureParameter { Parameter = command.SortDescriptors.Count > 0 ? (command.SortDescriptors[0].SortDirection == ListSortDirection.Descending ? "desc" : "asc") : "asc", Type = NHibernate.NHibernateUtil.String });
pageParaList.Add(new ProcedureParameter { Parameter = command.PageSize, Type = NHibernate.NHibernateUtil.Int32 });
pageParaList.Add(new ProcedureParameter { Parameter = command.Page, Type = NHibernate.NHibernateUtil.Int32 });
var procedureSearchStatementModel = new ProcedureSearchStatementModel();
procedureSearchStatementModel.Parameters = paraList;
procedureSearchStatementModel.PageParameters = pageParaList;
procedureSearchStatementModel.CountProcedure = "USP_Search_RecDetCount";
procedureSearchStatementModel.SelectProcedure = "USP_Search_RecDet";
return procedureSearchStatementModel;
}
#region Export master search
[SconitAuthorize(Permissions = "Url_Supplier_Invoice_Query")]
[GridAction(EnableCustomBinding = true)]
public void ExportMstr(ReceiptMasterSearchModel searchModel)
{
int value = Convert.ToInt32(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.MaxRowSizeOnPage));
GridCommand command = new GridCommand();
command.Page = 1;
command.PageSize = !this.CheckSearchModelIsNull(searchModel) ? 0 : value;
if (!this.CheckSearchModelIsNull(searchModel))
{
return;
}
string whereStatement = string.Empty;
ProcedureSearchStatementModel procedureSearchStatementModel = this.PrepareProcedureSearchStatement(command, searchModel, whereStatement);
ExportToXLS<ReceiptMaster>("SupplierReceiptOrderMaster.xls", GetAjaxPageDataProcedure<ReceiptMaster>(procedureSearchStatementModel, command).Data.ToList());
}
#endregion
}
}
|
using System.Collections.Generic;
using System.Linq;
using DataAccess.DBContext;
namespace DataAccess.Repositories
{
public interface IProductRepository : IRepository<IProduct>
{
}
public class ProductRepository : IProductRepository
{
private readonly IFactory<IProduct> m_iFactory;
private readonly ProductsContext m_context;
public ProductRepository()
{
m_iFactory = new ProductFactory();
m_context = new ProductsContext();
}
public List<IProduct> GetEntities
{
get
{
return m_context.Products.AsEnumerable()
.Select(p => m_iFactory.Create(p)).ToList();
}
}
public void Save()
{
m_context.SaveChanges();
}
public IProduct GetById(int id)
{
return m_iFactory.Create(m_context.Products.Find(id));
}
public void Insert(IProduct entity)
{
var productToAdd = new Product
{
Category = entity.Category,
Description = entity.Description,
Name = entity.Name,
Price = entity.Price
};
m_context.Products.Add(productToAdd);
Save();
}
public void Delete(IProduct entity)
{
var entityToRemove = m_context.Products.Find(entity.ProductId);
if (entityToRemove == null)
{
return;
}
m_context.Products.Remove(entityToRemove);
Save();
}
}
}
|
using System.Linq;
using SqlServerRunnerNet.Infrastructure;
namespace SqlServerRunnerNet.ViewModel
{
public class FolderViewModel : FileSystemObjectViewModel
{
private TrulyObservableCollection<ScriptViewModel> _scripts;
public FolderViewModel()
{
Scripts = new TrulyObservableCollection<ScriptViewModel>();
Scripts.ItemChanged += (sender, args) =>
{
OnPropertyChanged("HasError");
OnPropertyChanged("SucceededScriptsCount");
OnPropertyChanged("FailedScriptsCount");
};
Scripts.CollectionChanged += (sender, args) =>
{
OnPropertyChanged("HasError");
OnPropertyChanged("SucceededScriptsCount");
OnPropertyChanged("FailedScriptsCount");
};
}
public override bool HasError
{
get { return Scripts.Any(script => script.HasError); }
}
public override string DisplayName
{
get { return Path; }
}
public TrulyObservableCollection<ScriptViewModel> Scripts
{
get { return _scripts; }
set
{
if (Equals(value, _scripts)) return;
_scripts = value;
OnPropertyChanged();
}
}
public int SucceededScriptsCount
{
get
{
return Scripts.Count(script => !script.HasError);
}
}
public int FailedScriptsCount
{
get
{
return Scripts.Count(script => script.HasError);
}
}
#region Commands
#endregion
}
}
|
using System;
using GatewayEDI.Logging.Factories;
namespace GatewayEDI.Logging.Resolver
{
/// <summary> A factory resolver that always returns a given <see cref="ILogFactory" />, which can be set at runtime. </summary>
public class SimpleFactoryResolver : IFactoryResolver
{
private ILogFactory factory = NullLogFactory.Instance;
/// <summary> Gets or sets the logger factory that is used by this resolver. If a null reference is being assigned, this resolver automatically falls back to a <see cref="NullLogFactory" /> instance. </summary>
public ILogFactory Factory
{
get { return factory; }
set { factory = value ?? NullLogFactory.Instance; }
}
/// <summary> Determines a factory which cab create an <see cref="ILog" /> instance based on a request for a named log. </summary>
/// <param name="logName"> The log name. </param>
/// <returns> This implementation always returns the currently assigned <see cref="Factory" />, regardless of the submitted <paramref name="logName" />. </returns>
public ILogFactory GetFactory(string logName)
{
return factory;
}
#region construction
/// <summary> Initializes a new instance of the resolver, which uses an <see cref="NullLogFactory" /> instance until the <see cref="Factory" /> property is set explicitly. </summary>
public SimpleFactoryResolver()
{
}
/// <summary> Initializes a new instance of the resolver with the log to be maintained. </summary>
/// <param name="factory"> The factory to be returned by this resolver's <see cref="GetFactory" /> method. </param>
/// <exception cref="ArgumentNullException"> If <paramref name="factory" /> is a null reference. </exception>
public SimpleFactoryResolver(ILogFactory factory)
{
if (factory == null) throw new ArgumentNullException("factory");
this.Factory = factory;
}
#endregion
}
} |
namespace BikeDistributor.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class initialmigration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.BusinessEntities",
c => new
{
Id = c.Int(nullable: false, identity: true),
FirstName = c.String(maxLength: 4000),
LastName = c.String(maxLength: 4000),
CompanyName = c.String(maxLength: 4000),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Locations",
c => new
{
Id = c.Int(nullable: false, identity: true),
BusinessEntityId = c.Int(nullable: false),
Type = c.String(maxLength: 4000),
AddressLine1 = c.String(maxLength: 4000),
AddressLine2 = c.String(maxLength: 4000),
Zip = c.String(maxLength: 4000),
City = c.String(maxLength: 4000),
State = c.String(maxLength: 4000),
Country = c.String(maxLength: 4000),
TaxRate = c.Double(nullable: false),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.BusinessEntities", t => t.BusinessEntityId, cascadeDelete: true)
.Index(t => t.BusinessEntityId);
CreateTable(
"dbo.DiscountCodes",
c => new
{
Id = c.Int(nullable: false, identity: true),
CampainCode = c.String(maxLength: 4000),
QuantityRange1 = c.Int(nullable: false),
QuantityRange2 = c.Int(nullable: false),
Flag = c.String(maxLength: 4000),
DiscountRate = c.Double(nullable: false),
StartDate = c.DateTime(nullable: false),
EndDate = c.DateTime(nullable: false),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.HtmlTemplates",
c => new
{
Id = c.Int(nullable: false, identity: true),
Type = c.String(maxLength: 4000),
Content = c.String(maxLength: 4000),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.OrderLines",
c => new
{
Id = c.Int(nullable: false, identity: true),
OrderId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
Quantity = c.Int(nullable: false),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Products", t => t.ProductId, cascadeDelete: true)
.ForeignKey("dbo.Orders", t => t.OrderId, cascadeDelete: true)
.Index(t => t.OrderId)
.Index(t => t.ProductId);
CreateTable(
"dbo.Products",
c => new
{
Id = c.Int(nullable: false, identity: true),
Brand = c.String(maxLength: 4000),
Model = c.String(maxLength: 4000),
Make = c.String(maxLength: 4000),
Sku = c.String(maxLength: 4000),
Msrp = c.Double(nullable: false),
TaxedPrice = c.Double(nullable: false),
DiscountedPrice = c.Double(nullable: false),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Orders",
c => new
{
Id = c.Int(nullable: false, identity: true),
OrderDate = c.DateTime(nullable: false),
OrderedById = c.Int(nullable: false),
DiscountCodeId = c.Int(nullable: false),
Name = c.String(maxLength: 4000),
CreatedDate = c.DateTime(),
ModifiedDate = c.DateTime(),
CreatedBy = c.String(maxLength: 4000),
ModifiedBy = c.String(maxLength: 4000),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion"),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.DiscountCodes", t => t.DiscountCodeId, cascadeDelete: true)
.ForeignKey("dbo.BusinessEntities", t => t.OrderedById, cascadeDelete: true)
.Index(t => t.OrderedById)
.Index(t => t.DiscountCodeId);
}
public override void Down()
{
DropForeignKey("dbo.OrderLines", "OrderId", "dbo.Orders");
DropForeignKey("dbo.Orders", "OrderedById", "dbo.BusinessEntities");
DropForeignKey("dbo.Orders", "DiscountCodeId", "dbo.DiscountCodes");
DropForeignKey("dbo.OrderLines", "ProductId", "dbo.Products");
DropForeignKey("dbo.Locations", "BusinessEntityId", "dbo.BusinessEntities");
DropIndex("dbo.Orders", new[] { "DiscountCodeId" });
DropIndex("dbo.Orders", new[] { "OrderedById" });
DropIndex("dbo.OrderLines", new[] { "ProductId" });
DropIndex("dbo.OrderLines", new[] { "OrderId" });
DropIndex("dbo.Locations", new[] { "BusinessEntityId" });
DropTable("dbo.Orders");
DropTable("dbo.Products");
DropTable("dbo.OrderLines");
DropTable("dbo.HtmlTemplates");
DropTable("dbo.DiscountCodes");
DropTable("dbo.Locations");
DropTable("dbo.BusinessEntities");
}
}
}
|
using Tests.Pages.ActionID;
using Framework.Core.Common;
using Framework.Core.Helpers.Data;
using Tests.Pages.Van.LogIn;
using NUnit.Framework;
using Tests.Data.Van;
using Tests.Pages.Van.Main;
using Tests.Pages.Van.Main.Common;
using Tests.Pages.Van.Main.Common.DefaultPage;
namespace Tests.Projects.Van.Login
{
public class ActionIdSwitchContext
{
private Driver _driver;
[SetUp]
public void SetUp()
{
//start browser
_driver = new Driver();
}
/// <summary>
/// Logs in with actionID that is linked to multiple users, select one of the user and verifies to enter PIN and home page displays
/// Clicks on Switch Context to swithc to a different user with access to differenct state and committee
/// </summary>
[Test]
[Category("van"), Category("van_actionid"), Category("van_login"), Category("van_smoketest")]
public void ActionIdSwitchContextTest()
{
var user = new VanTestUser
{
UserName = "saznee+test1723_2@gmail.com",
Password = "actionid123",
ActionIdUserName = "sajActionID",
StateId = "Massachusetts",
CommitteeId = "Sajani Test Committee",
PinCode = "1212"
};
var login = new LoginPage(_driver, "dnc");
login.LoginWithActionId(user);
// Switch Context
var homepage = new VoterDefaultPage(_driver);
homepage.ClickSwitchLink();
user.SwitchUserName = "sajanitester";
user.SwitchState = "Training";
user.SwitchCommittee = "Master Staging Committee";
homepage.SwitchUserAndCommittees(user);
Assert.IsTrue(_driver.IsElementPresent(homepage.TrainingSiteBanner), "TrainingSiteBanner element did not display");
}
[TearDown]
public void Teardown()
{
_driver.BrowserQuit();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Breeze.Helpers;
namespace Breeze.Helpers
{
public sealed class AppDomain
{
public static AppDomain CurrentDomain { get; private set; }
static AppDomain()
{
CurrentDomain = new AppDomain();
}
public Assembly[] GetAssemblies()
{
return GetAssemblyList().ToArray();
}
public List<string> AssembliesToNotLoad = new List<string>
{
"clrcompression.dll","clrjit.dll"
};
private IEnumerable<Assembly> GetAssemblyList()
{
var folder = FileLocation.InstalledLocation;
List<Assembly> assemblies = new List<Assembly>();
foreach (var file in Directory.GetFiles(folder))
{
if (!AssembliesToNotLoad.Contains(file.Split('\\').Last()))
{
if (file.Split('.').Last() == "dll" || file.Split('.').Last() == "exe")
{
AssemblyName name = new AssemblyName()
{Name = Path.GetFileNameWithoutExtension(file.Split('\\').Last())};
try
{
Assembly asm = Assembly.Load(name);
assemblies.Add(asm);
}
catch (Exception e)
{
Debug.WriteLine($"Couldnt load {name} - {e.Message}");
}
}
}
}
return assemblies;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.