text stringlengths 13 6.01M |
|---|
using AsNum.XFControls.iOS.Services;
using AsNum.XFControls.Services;
using Foundation;
using UIKit;
using Xamarin.Forms;
[assembly: Dependency(typeof(ToasImpl))]
namespace AsNum.XFControls.iOS.Services {
public class ToasImpl : IToast {
public void Show(string msg, bool longShow = false) {
Device.BeginInvokeOnMainThread(() => {
var font = UIFont.SystemFontOfSize(12F);
var lbl = new UILabel()
{
Text = msg,
Font = font,
TextColor = UIColor.White,
};
Toast.Instance.SetContent(lbl);
Toast.Instance.Show(duration: longShow ? Toast.Durations.Long : Toast.Durations.Short);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PROJECT
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MainWindow : Window
{
List<MovieInfo> movieInfos = new List<MovieInfo>();
List<MovieInfo> rand10mov = new List<MovieInfo>();
List<MovieInfo> AlreadyShowlst = new List<MovieInfo>();
List<MovieInfo> SelectedMovlst = new List<MovieInfo>();
List<MovieInfo> RecommandMovieInfos = new List<MovieInfo>();
List<Button> btnlist = new List<Button>();
private int cnt = 0;
public MainWindow()
{
InitializeComponent();
btnlist.Add(poster1);
btnlist.Add(poster2);
btnlist.Add(poster3);
btnlist.Add(poster4);
btnlist.Add(Poster5);
btnlist.Add(Poster6);
btnlist.Add(Poster7);
btnlist.Add(Poster8);
btnlist.Add(Poster9);
btnlist.Add(Poster10);
movieInfos = (List<MovieInfo>)Application.Current.Properties["mvInfoList"];
RecommandMovieInfos = (List<MovieInfo>)Application.Current.Properties["mvInfoList2"];
ClickedChange();
this.MouseLeftButtonDown += new MouseButtonEventHandler(Window_MouseLeftButtonDown);
}
void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
private void posterOption_Click(object sender, RoutedEventArgs e)
{
var posterOption = sender as Button;
if (posterOption.Name == "Move")
{
for (int i = 0; i < 10; i++)
{
if (btnlist[i].Tag.ToString() == "checked")
{
SelectedMovlst.Add(rand10mov[i]);
cnt++;
}
}
if (cnt >= 30)
{
List<string> Genre = RcmMovlst(SelectedMovlst);
List<string> Actor = ActorsCounts(SelectedMovlst);
List<string> Country = CountryCounts(SelectedMovlst);
// 취향분석 알고리즘을 통해 얻은 추천영화 리스트
List<string> Rcmlst = RecommandMovies(Genre, Actor, Country);
foreach (var item in Rcmlst)
{
Console.WriteLine(item);
}
List<string> list = new List<string>();
Page1 p1 = new Page1(Rcmlst);
this.Content = p1;
}
}
ClickedChange();
}
private void PosterClick(object sender, RoutedEventArgs e)
{
var posterOption = sender as Button;
if (posterOption.Tag.ToString() == "unchecked")
{
posterOption.Tag = "checked";
posterOption.BorderThickness = new Thickness(10);
posterOption.BorderBrush = Brushes.Red;
}
else
{
posterOption.Tag = "unchecked";
posterOption.BorderThickness = new Thickness(1);
posterOption.BorderBrush = Brushes.Black;
}
}
private void ClickedChange()
{
initPoster();
var random = new Random();
foreach (var Mov in rand10mov)
{
AlreadyShowlst.Add(Mov);
}
rand10mov.Clear();
List<ImageBrush> brushes = new List<ImageBrush>();
for (int k = 0; k < 10; k++)
{
var tempmov = movieInfos[random.Next(movieInfos.Count)];
while (tempmov.MoviePoster == "None" && AlreadyShowlst.Contains(tempmov) == false)
{
tempmov = movieInfos[random.Next(movieInfos.Count)];
}
BitmapImage i = new BitmapImage(new Uri(tempmov.MoviePoster, UriKind.RelativeOrAbsolute));
rand10mov.Add(tempmov);
ImageBrush brush = new ImageBrush();
brush.ImageSource = i;
brushes.Add(brush);
}
for (int i = 0; i < 10; i++)
{
btnlist[i].Background = brushes[i];
}
}
private void initPoster()
{
foreach (var item in btnlist)
{
item.Tag = "unchecked";
item.BorderBrush = Brushes.Black;
item.BorderThickness = new Thickness(1);
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.Close();
}
private List<string> RcmMovlst(List<MovieInfo> selectedlst)
{
List<string> Genrelst = new List<string>();
Dictionary<string, double> movieDic = new Dictionary<string, double>();
for (int i = 0; i < selectedlst.Count; i++)
{
int t = selectedlst[i].Genre.Count();
for (int k = 0; k < t; k++)
{
double grScore = 1 / (double)t;
if (t == 1 && selectedlst[i].Genre[k] == "드라마")
{
if (Genrelst.Contains(selectedlst[i].Genre[k]) == false)
{
Genrelst.Add(selectedlst[i].Genre[k]);
movieDic.Add(selectedlst[i].Genre[k], 0);
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
else
{
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
}
else if (selectedlst[i].Genre.Contains("드라마") == true)
{
grScore = 1 / (double)(t - 1);
if (selectedlst[i].Genre[k] == "드라마")
continue;
if (Genrelst.Contains(selectedlst[i].Genre[k]) == false)
{
Genrelst.Add(selectedlst[i].Genre[k]);
movieDic.Add(selectedlst[i].Genre[k], 0);
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
else
{
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
}
else
{
if (Genrelst.Contains(selectedlst[i].Genre[k]) == false)
{
Genrelst.Add(selectedlst[i].Genre[k]);
movieDic.Add(selectedlst[i].Genre[k], 0);
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
else
{
movieDic[selectedlst[i].Genre[k]] += Math.Round(grScore, 3);
}
}
}
}
//선택영화당 장르별 가중치 계산하여 구하고 dictionary에 저장
var sortedmovieDic = movieDic.OrderByDescending(num => num.Value);
double averageGenreSC = 0;
List<double> gsArr = new List<double>();
foreach (KeyValuePair<string, double> tt in sortedmovieDic)
{
Console.WriteLine("key:{0}, Value:{1}", tt.Key, tt.Value);
averageGenreSC += tt.Value;
gsArr.Add(tt.Value);
}
Console.WriteLine("AVG "+averageGenreSC / sortedmovieDic.Count());
Console.WriteLine("STD " + StdDev(gsArr));
//장르별로 표준편차 계산
int casenum = 0;
List<string> Fgenrelst = new List<string>();
if (StdDev(gsArr) + averageGenreSC / sortedmovieDic.Count() < sortedmovieDic.ElementAt(0).Value)
casenum = 1;
else
casenum = 2;
switch (casenum)
{
case 1:
foreach (KeyValuePair<string, double> tt in sortedmovieDic)
{
if (tt.Value > StdDev(gsArr) + averageGenreSC / sortedmovieDic.Count())
Fgenrelst.Add(tt.Key);
}
break;
case 2:
//foreach (KeyValuePair<string, double> tt in sortedmovieDic)
//{
// if (tt.Value > averageGenreSC / sortedmovieDic.Count() - StdDev(gsArr))
// Fgenrelst.Add(tt.Key);
//}
Fgenrelst.Add(sortedmovieDic.ElementAt(0).Key);
break;
default:
Console.WriteLine("Wrong Genre Search");
break;
}
//표준편차구간의 최상의 장르의 유무에 따라 추천 장르 저장
foreach (var item in Fgenrelst)
{
Console.WriteLine(item);
}
return Fgenrelst;
}
private List<string> ActorsCounts(List<MovieInfo> selectedlst)
{
List<string> Actorlst = new List<string>();
Dictionary<string, int> movieDic = new Dictionary<string, int>();
for (int i = 0; i < selectedlst.Count; i++)
{
int t = selectedlst[i].Actor.Count();
for (int k = 0; k < t; k++)
{
if (Actorlst.Contains(selectedlst[i].Actor[k]) == false)
{
Actorlst.Add(selectedlst[i].Actor[k]);
movieDic.Add(selectedlst[i].Actor[k], 0);
movieDic[selectedlst[i].Actor[k]] += 1;
}
else
{
movieDic[selectedlst[i].Actor[k]] += 1;
}
}
}
var sortedmovieDic = movieDic.OrderByDescending(num => num.Value);
List<string> RActorlst = new List<string>();
foreach (KeyValuePair<string, int> tt in sortedmovieDic)
{
Console.WriteLine("key:{0}, Value:{1}", tt.Key, tt.Value);
if (tt.Value > 8)
RActorlst.Add(tt.Key);
}
if (RActorlst.Count() < 1)
RActorlst.Add("None");
return RActorlst;
}
private List<string> CountryCounts(List<MovieInfo> selectedlst)
{
List<string> Countrylst = new List<string>();
Dictionary<string, int> movieDic = new Dictionary<string, int>();
for (int i = 0; i < selectedlst.Count; i++)
{
int t = selectedlst[i].Country.Count();
for (int k = 0; k < t; k++)
{
if (Countrylst.Contains(selectedlst[i].Country[k]) == false)
{
Countrylst.Add(selectedlst[i].Country[k]);
movieDic.Add(selectedlst[i].Country[k], 0);
movieDic[selectedlst[i].Country[k]] += 1;
}
else
{
movieDic[selectedlst[i].Country[k]] += 1;
}
}
}
var sortedmovieDic = movieDic.OrderByDescending(num => num.Value);
List<string> RCountrylst = new List<string>();
foreach (KeyValuePair<string, int> tt in sortedmovieDic)
{
Console.WriteLine("key:{0}, Value:{1}", tt.Key, tt.Value);
if (tt.Value > 20)
RCountrylst.Add(tt.Key);
}
if (RCountrylst.Count() < 1)
RCountrylst.Add("None");
return RCountrylst;
}
private List<string> RecommandMovies(List<string> Genrelst, List<string> Actorlst, List<string> Countrylst)
{
List<string> Recommandlst = new List<string>();
List<string> UrlNum = new List<string>();
int GenreCounts = Genrelst.Count();
var tempmov = new MovieInfo();
var random = new Random();
int movCount = 0;
if (Actorlst[0] != "None")
{
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Actor.Contains(Actorlst[0]) == true && Recommandlst.Contains(tempmov.MovieName) == false && UrlNum.Contains(tempmov.Url.Split('=')[1]) == false)
{
Console.WriteLine(tempmov.Url.Split('=')[1]);
Recommandlst.Add(tempmov.MovieName);
UrlNum.Add(tempmov.Url.Split('=')[1]);
}
movCount++;
if (movCount > 30000)
{
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
}
}
}
//Actor Selected
else
{
Console.WriteLine(Countrylst[0]);
if (Countrylst[0] != "None")
{
switch (GenreCounts)
{
case 1:
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && tempmov.Country[0]==Countrylst[0] && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
case 2:
while (Recommandlst.Count() != 5)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Contains(Genrelst[1]) && tempmov.Genre.Count() == 2 && tempmov.Country[0] == Countrylst[0] && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && tempmov.Country[0] == Countrylst[0] && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[1]) == true && tempmov.Genre.Count() == 1 && tempmov.Country[0] == Countrylst[0] && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
default:
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && tempmov.Country[0] == Countrylst[0] && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
}
}
//country selected
else
{
switch (GenreCounts)
{
case 1:
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
case 2:
while (Recommandlst.Count() != 4)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Contains(Genrelst[1]) && tempmov.Genre.Count() == 2 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
while (Recommandlst.Count() != 7)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[1]) == true && tempmov.Genre.Count() == 1 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
default:
while (Recommandlst.Count() != 10)
{
tempmov = RecommandMovieInfos[random.Next(RecommandMovieInfos.Count())];
if (tempmov.Genre != null && tempmov.Genre.Contains(Genrelst[0]) == true && tempmov.Genre.Count() == 1 && Recommandlst.Contains(tempmov.MovieName) == false)
{
Recommandlst.Add(tempmov.MovieName);
}
}
break;
}
}
}
return Recommandlst;
}
private double StdDev(IEnumerable<double> values)
{
double result = 0;
try
{
if (values.Count() > 0)
{
double mean = values.Average();
double sum = values.Sum(d => Math.Pow(d - mean, 2));
result = Math.Sqrt((sum) / (values.Count() - 1));
}
}
catch { }
return result;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RushEnemy : Enemy
{
[SerializeField] private AnimationCurve curve;
protected override void AttackFrame(float t)
{
rBody.velocity = Vector3.zero;
rBody.AddForce(transform.forward * curve.Evaluate(t / attackTime) * speed, ForceMode.VelocityChange);
}
}
|
#if UNITY_2019_1_OR_NEWER
using UnityEditor;
using UnityAtoms.Editor;
namespace UnityAtoms.MonoHooks.Editor
{
/// <summary>
/// Event property drawer of type `ColliderGameObject`. Inherits from `AtomDrawer<ColliderGameObjectEvent>`. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
[CustomPropertyDrawer(typeof(ColliderGameObjectEvent))]
public class ColliderGameObjectEventDrawer : AtomDrawer<ColliderGameObjectEvent> { }
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// 以下を追加
using System.Windows.Interop;
using System.Runtime.InteropServices;
namespace WinMes
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
private static readonly int WM_USER = 0x0400;
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint RegisterWindowMessage(string lpString);
private uint _myMessage = RegisterWindowMessage("MyMsg");
public MainWindow()
{
InitializeComponent();
Loaded += (o, e) =>
{
var source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
};
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_USER)
{
string timstr = DateTime.Now.ToLongTimeString();
Console.WriteLine("Mouse Wheel : " + timstr);
}
else if (msg == _myMessage)
{
string timstr = DateTime.Now.ToLongTimeString();
Console.WriteLine("Mouse Wheel : " + timstr);
}
return IntPtr.Zero;
}
private void B_send_Click(object sender, RoutedEventArgs e)
{
IntPtr win = FindWindow(null, "MainWindow");
SendMessage(win, (int)WM_USER, IntPtr.Zero, IntPtr.Zero);
}
}
}
|
using Assets.Scripts.UI;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Controllers
{
public class GroundPlacementItemController : MonoBehaviour
{
public float ObjectHeight;
public bool CheckCanPlace = false;
public Color CanPlaceColor;
public Color CantPlaceColor;
public List<Material> Materials;
public string CantPlaceLocalizationKey;
public bool CanPlace { get; protected set; }
public float AdditionalHeigth { get; set; }
public UiSlot Slot { get; private set; }
protected GameManager GameManager;
private Transform _cachedTransform;
private bool _isInitialized;
private float _raycastTimer = 0.0f;
public void Init(GameManager gameManager, UiSlot slot)
{
CanPlace = true;
_cachedTransform = transform;
Slot = slot;
AdditionalHeigth = 0.0f;
GameManager = gameManager;
if (CheckCanPlace)
{
foreach (var material in Materials)
material.SetColor("_Color", CanPlaceColor);
}
_isInitialized = true;
}
public void Up()
{
AdditionalHeigth += 0.5f;
}
public void Down()
{
AdditionalHeigth -= 0.5f;
}
void LateUpdate()
{
UpdatePosition();
}
protected virtual void UpdatePosition()
{
Vector3 pos = transform.position;
RaycastHit hit;
Physics.Raycast(transform.position, -Vector3.up, out hit, 10);
if (hit.collider != null && hit.collider.gameObject.tag != "Terrain")
{
pos.y = hit.collider.transform.position.y + ObjectHeight;
}
else
{
//pos.y = Terrain.activeTerrain.SampleHeight(transform.position) + ObjectHeight;
pos.y = GameManager.CurrentTerain.SampleHeight(transform.position) + ObjectHeight;
}
transform.position = pos;
}
}
}
|
using GisSharpBlog.NetTopologySuite.Geometries;
using NUnit.Framework;
namespace NetTopologySuite.Tests.Geometry
{
[TestFixture]
public class PointTest
{
[Test]
public void GetHashCodeMustBeComputed()
{
var first = new Point(1.0, 2.0);
Assert.AreEqual(712319917, first.GetHashCode());
}
}
} |
using System;
using System.Text.RegularExpressions;
class SeriesofLetters
{
static void Main()
{
string input = "aaaaabbbbbcdddeeeedssaa";
Regex myRegex = new Regex(@"([a-z])\1*");
MatchCollection matches = myRegex.Matches(input);
foreach (Match match in matches)
{
Console.Write(match.Value[0]);
}
Console.WriteLine();
}
}
|
using System;
using System.Threading.Tasks;
namespace Author
{
class Program
{
static async Task Main(string[] args)
{
await ArticleRequest.GotoPage(1);
var usernames = ArticleRequest.GetUsernames(32);
var usernamesSortedByRecordDate = ArticleRequest.GetUsernamesSortedByRecordDate(32);
Console.WriteLine("The author with the highest comment count. .................................................");
Console.WriteLine(ArticleRequest.GetUsernameWithHighestCommentCount());
Console.WriteLine();
Console.WriteLine("The list of most active authors according to a set threshold .........................................................");
foreach (var username in usernames)
Console.WriteLine(username);
Console.WriteLine();
Console.WriteLine("The list of the authors sorted by when their record was created according to a set threshold ..........................");
foreach (var username in usernamesSortedByRecordDate)
Console.WriteLine(username);
}
}
}
|
using Bolster.Base;
using Bolster.Base.Interface;
using NUnit.Framework;
namespace Bolster.Test
{
[TestFixture]
public class TestEitherExplicit
{
private Either<string, int> numAsStringOrNumber(int number, bool asString)
=> asString ? number.ToString().ToLeft<string, int>() : number.ToRight<string, int>();
[Test]
public void TestEitherTypes() {
var left = Either<bool, int>.Choose(5);
Assert.IsTrue(left.ValueAs<int>().Return().GetType() == 5.GetType());
Assert.IsTrue(left.ValueAs<bool>().HasError);
}
[Test]
public void TestDisparateReturnValues() {
var returnOfRunOne = numAsStringOrNumber(4, true).ValueAs<string>().Return();
var returnOfRunTwo = numAsStringOrNumber(5, false).ValueAs<int>().Return();
Assert.IsTrue(returnOfRunOne.Equals("4"));
Assert.IsTrue(returnOfRunTwo == 5);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace HBPonto.Kernel.Helpers.Jiras
{
public class JiraIssueEpic
{
public string key { get; set; }
public string name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using ThirdPartyTools;
using FileManager;
using System.Configuration;
namespace FileData
{
public static class Program
{
public static void Main(string[] args)
{
string action;
string filePath;
IOperation operation = (IOperation)new Operation();
try
{
if (args.Length == operation.GetCommands)
{
action = args[0];
filePath = args[1];
var result = operation.Invoker(action, filePath);
Console.WriteLine("Output: {0}", result);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
}
}
|
using System;
using System.Linq.Expressions;
using Seterlund.CodeGuard.Internals;
namespace Seterlund.CodeGuard
{
public static class Guard
{
/// <summary>
/// Check the argument
/// </summary>
/// <param name="argument">
/// The argument.
/// </param>
/// <typeparam name="T">
/// Type of the argument
/// </typeparam>
/// <returns>
/// An ArgumentValidator
/// </returns>
public static ValidatorBase<T> Check<T>(Expression<Func<T>> argument)
{
return new ThrowValidator<T>(argument);
}
/// <summary>
/// Check the argument
/// </summary>
/// <typeparam name="T">
/// Type of the argument
/// </typeparam>
/// <param name="argument"></param>
/// <returns>
/// An ArgumentValidator
/// </returns>
public static ValidatorBase<T> Check<T>(T argument)
{
return new ThrowValidator<T>(argument);
}
public static ValidatorBase<T> Validate<T>(Expression<Func<T>> argument)
{
return new Validator<T>(argument);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data.Filtering;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Registrator;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
namespace CustomControlz.XtraGrids
{
public partial class ccGridControl : GridControl
{
public ccGridControl()
{
InitializeComponent();
}
protected override BaseView CreateDefaultView()
{
return CreateView("MyGridView");
}
protected override void RegisterAvailableViewsCore(InfoCollection collection)
{
base.RegisterAvailableViewsCore(collection);
collection.Add(new MyGridViewInfoRegistrator());
}
}
public class MyGridViewInfoRegistrator : GridInfoRegistrator
{
public override string ViewName { get { return "MyGridView"; } }
public override BaseView CreateView(GridControl grid) { return new MyGridView(grid as GridControl); }
}
public class MyGridView : GridView
{
public MyGridView() : this(null) { }
public MyGridView(GridControl grid) : base(grid) { }
protected override string ViewName { get { return "MyGridView"; } }
protected override CriteriaOperator CreateAutoFilterCriterion(DevExpress.XtraGrid.Columns.GridColumn column, DevExpress.XtraGrid.Columns.AutoFilterCondition condition, object _value, string strVal)
{
if (column.ColumnType == typeof(DateTime) && strVal.Length > 0)
{
BinaryOperatorType type = BinaryOperatorType.Equal;
string operand = string.Empty;
if (strVal.Length > 1)
{
operand = strVal.Substring(0, 2);
if (operand.Equals(">="))
type = BinaryOperatorType.GreaterOrEqual;
else if (operand.Equals("<="))
type = BinaryOperatorType.LessOrEqual;
}
if (type == BinaryOperatorType.Equal)
{
operand = strVal.Substring(0, 1);
if (operand.Equals(">"))
type = BinaryOperatorType.Greater;
else if (operand.Equals("<"))
type = BinaryOperatorType.Less;
}
if (type != BinaryOperatorType.Equal)
{
string val = strVal.Replace(operand, string.Empty);
try
{
DateTime dt = DateTime.ParseExact(val, "d", column.RealColumnEdit.EditFormat.Format);
return new BinaryOperator(column.FieldName, dt, type);
}
catch
{
return null;
}
}
}
return base.CreateAutoFilterCriterion(column, condition, _value, strVal);
}
}
}
|
using System.Collections.Generic;
using SelectionCommittee.DAL.Entities;
namespace SelectionCommittee.DAL.Interfaces
{
public interface ISubjectRepository
{
IEnumerable<Subject> GetCertificates();
//EIE - extern independent evalution
IEnumerable<Subject> GetSubjectsEIE();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Win32
{
public enum KeyInformationClass : int
{
KeyBasicInformation = 0,
KeyNodeInformation = 1,
KeyFullInformation = 2,
KeyNameInformation = 3,
KeyCachedInformation = 4,
KeyFlagsInformation = 5,
KeyVirtualizationInformation = 6,
KeyHandleTagsInformation = 7,
MaxKeyInfoClass = 8
}
public static class Nt
{
[DllImport("ntdll.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern uint NtQueryKey(
IntPtr KeyHandle,
KeyInformationClass keyInformationClass,
byte[] KeyInformation,
int Length,
ref int ResultLength);
public static byte[] QueryKey(HKey keyHandle, KeyInformationClass keyInformationClass)
{
int length = 0;
var ret = NtQueryKey(keyHandle.IntPtr, KeyInformationClass.KeyNameInformation, null, 0, ref length);
if (ret != SetupDi.STATUS_BUFFER_TOO_SMALL)
{
throw new Win32Exception();
}
var keyInformation = new byte[length];
ret = Nt.NtQueryKey(keyHandle.IntPtr, KeyInformationClass.KeyNameInformation, keyInformation, length, ref length);
if (ret != SetupDi.STATUS_SUCCESS)
{
throw new Win32Exception();
}
return keyInformation;
}
public static string QueryKeyNameInformation(HKey keyHandle)
{
var info = QueryKey(keyHandle, KeyInformationClass.KeyNameInformation);
// first four bytes is length, followed by utf-16 string
return Encoding.Unicode.GetString(info, 4, info.Length - 4);
}
}
}
|
using Content.Server.Disease.Components;
using JetBrains.Annotations;
using Content.Shared.Disease;
namespace Content.Server.Disease.Effects
{
/// <summary>
/// Handles a disease which incubates over a period of time
/// before adding another component to the infected entity
/// currently used for zombie virus
/// </summary>
[UsedImplicitly]
public sealed class DiseaseProgression : DiseaseEffect
{
/// <summary>
/// The rate that's increased over time. Defaults to 1% so the probability can be varied in yaml
/// </summary>
[DataField("rate")]
[ViewVariables(VVAccess.ReadWrite)]
public float Rate = 0.01f;
/// <summary>
/// The component that is added at the end of build up
/// </summary>
[DataField("comp")]
public string? Comp = null;
public override void Effect(DiseaseEffectArgs args)
{
args.EntityManager.EnsureComponent<DiseaseBuildupComponent>(args.DiseasedEntity, out var buildup);
if (buildup.Progression < 1) //increases steadily until 100%
{
buildup.Progression += Rate;
}
else if (Comp != null)//adds the component for the later stage of the disease.
{
EntityUid uid = args.DiseasedEntity;
var newComponent = (Component) IoCManager.Resolve<IComponentFactory>().GetComponent(Comp);
newComponent.Owner = uid;
if (!args.EntityManager.HasComponent(uid, newComponent.GetType()))
args.EntityManager.AddComponent(uid, newComponent);
}
}
}
}
|
using Domain.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain.Entities
{
public class WidgetsInPage : AuditableEntity
{
public virtual Widget Widget { get; set; }
public virtual WidgetValue WidgetValue { get; set; }
public virtual Page Page { get; set; }
public virtual WidgetInPagePriority WidgetInPagePriority { get; set; }
}
}
|
using Cw3.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace Cw3.DAL
{
public class DbService : IDbService
{
public bool CheckIndex(string index)
{
try
{
using (var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s18445; Integrated Security=True"))
using (var com = new SqlCommand())
{
com.Connection = con;
con.Open();
com.CommandText = "SELECT * FROM Student where Student.IndexNumber = " + index;
var dataReader = com.ExecuteReader();
if (dataReader.Read())
{
dataReader.Close();
return true;
}
else if (!dataReader.Read())
{
dataReader.Close();
return false;
}
}
}
catch (SqlException ex)
{
return false;
}
//default, zawsze musi się kończyć returnem metoda, nawet jak nie wejdzie do ifa
return false;
}
public IEnumerable<Student> GetStudents()
{
throw new NotImplementedException();
}
}
//public IEnumerable<Student> GetStudents()
//{
// throw new NotImplementedException();
//}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraBehaviour : MonoBehaviour
{
public Vector3Data aimPoint, offsetCam;
[Range(0.01f, 1.0f)]
public float smoothFactor = 0.5f;
// Start is called before the first frame update
void Start()
{
offsetCam.value = gameObject.transform.position - aimPoint.value;
Vector3 newPos = aimPoint.value + offsetCam.value;
}
// Update is called once per frame
void LateUpdate()
{
Vector3 newPos = aimPoint.value + offsetCam.value;
gameObject.transform.position = Vector3.Slerp(gameObject.transform.position, newPos, smoothFactor);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CellScript : MonoBehaviour {
public int iResult = -1;
public static int x = 1;
public static int y = 1;
public Sprite X;
public Sprite O;
public static int win = 0;
public Text text;
public static int player = 1;
public Controller controller;
public static int[] bigSize = new int[4];
public void getEventButtonClick()
{
if (win == 0)
{
if (iResult == -1)
{
x = (int)(gameObject.transform.localPosition.x - (-486)) / 108;
y = (int)(600 - gameObject.transform.localPosition.y) / 108;
Debug.Log(x + " " + y + " " + player);
loadMap.Border = updateSize(x, y, loadMap.Border);
Debug.Log("minwidth : " + loadMap.Border[0] + " max width " + loadMap.Border[1] + " min height" + loadMap.Border[2] + " max height " + loadMap.Border[3]);
//Debug.Log(gameObject.transform.localPosition.x+" "+gameObject.transform.localPosition.y);
loadMap.BigMap[y, x] = player;
if (loadMap.win(loadMap.BigMap, y, x) == true)
{
Debug.Log("Win");
win = 1;
}
if (player == 1)
{
gameObject.GetComponent<Image>().sprite = X;
player = 2;
if (SceneManager.GetActiveScene().name.ToString() == "AI")
{
Controller.MiniMax();
}
//Debug.Log(player);
}
else
{
gameObject.GetComponent<Image>().sprite = O;
player = 1;
}
iResult = player;
loadMap.instance.checkTurn();
}
}
}
public static int[] updateSize(int x,int y,int[] arr){
int[] border = new int[4];
int newMaxWidth = (x + 1 <= loadMap.width - 1 ? (x + 1) : loadMap.width - 1);
int newMaxHeight = y + 1 <= loadMap.height - 1 ? (y + 1) : loadMap.height - 1;
int newMinWidth = x - 1 >= 0 ? (x - 1) : 0;
int newMinHeight = y - 1 >= 0 ? y - 1 : 0;
arr[1] = newMaxWidth > arr[1] ? newMaxWidth : arr[1];
arr[3] = newMaxHeight > arr[3] ? newMaxHeight : arr[3];
arr[0] = newMinWidth < arr[0] ? newMinWidth : arr[0];
arr[2] = newMinHeight < arr[2] ? newMinHeight : arr[2];
return arr;
}
}
|
namespace Sentry;
public readonly partial struct MeasurementUnit
{
/// <summary>
/// A time duration unit
/// </summary>
/// <seealso href="https://getsentry.github.io/relay/relay_metrics/enum.DurationUnit.html"/>
public enum Duration
{
/// <summary>
/// Nanosecond unit (10^-9 seconds)
/// </summary>
Nanosecond,
/// <summary>
/// Microsecond unit (10^-6 seconds)
/// </summary>
Microsecond,
/// <summary>
/// Millisecond unit (10^-3 seconds)
/// </summary>
Millisecond,
/// <summary>
/// Second unit
/// </summary>
Second,
/// <summary>
/// Minute unit (60 seconds)
/// </summary>
Minute,
/// <summary>
/// Hour unit (3,600 seconds)
/// </summary>
Hour,
/// <summary>
/// Day unit (86,400 seconds)
/// </summary>
Day,
/// <summary>
/// Week unit (604,800 seconds)
/// </summary>
Week
}
/// <summary>
/// Implicitly casts a <see cref="MeasurementUnit.Duration"/> to a <see cref="MeasurementUnit"/>.
/// </summary>
public static implicit operator MeasurementUnit(Duration unit) => new(unit);
} |
using System.Collections.Generic;
using System.Linq;
namespace Oop.Loops
{
class Program3
{
private static IPainter FindCheapestPainter(double sqMeters, IEnumerable<IPainter> painters)
{
return painters
.Where(painter => painter.IsAvailable)
.Aggregate((best, curent) =>
best.EstimateCompensation(sqMeters) < curent.EstimateCompensation(sqMeters) ?
best : curent);
}
static void Main3(string[] args)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TruckPad.Services.Models
{
public partial class Veiculo
{
public Veiculo()
{
Viagem = new HashSet<Viagem>();
}
[Key]
public int IdVeiculo { get; set; }
public int IdTipoVeiculo { get; set; }
[Required]
[StringLength(11)]
public string CodRenavam { get; set; }
[Required]
[StringLength(17)]
public string Chassi { get; set; }
[Required]
[StringLength(100)]
public string Nome { get; set; }
[Required]
[Column("CPF_CNPJ")]
[StringLength(15)]
public string CpfCnpj { get; set; }
[Required]
[StringLength(7)]
public string Placa { get; set; }
[Required]
[Column("Marca_Modelo")]
[StringLength(100)]
public string MarcaModelo { get; set; }
[Required]
[Column("Ano_Mod")]
[StringLength(4)]
public string AnoMod { get; set; }
[Required]
[StringLength(20)]
public string Cor { get; set; }
public bool Ativo { get; set; }
[Column(TypeName = "datetime")]
public DateTime DataRegistro { get; set; }
[ForeignKey("IdTipoVeiculo")]
[InverseProperty("Veiculo")]
public TipoVeiculo IdTipoVeiculoNavigation { get; set; }
[InverseProperty("IdVeiculoNavigation")]
public ICollection<Viagem> Viagem { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FoodMachine
{
public partial class Form1 : Form, IFoodMachineView
{
List<String> goods {get; set;}
List<String> additions {get; set;}
FoodMachinePresenter presenter;
public event EventHandler<FoodMachineEventArgs> FoodMachineEvent;
public Form1()
{
InitializeComponent();
presenter = new FoodMachinePresenter(this);
}
private void GoodListCombo_SelectedIndexChanged(object sender, EventArgs e)
{
foodGroup.Enabled = false;
drinkGroup.Enabled = false;
FoodMachineEventArgs args=new FoodMachineEventArgs();
args.code=EventCode.GoodSelected;
args.Message=(String)GoodListCombo.SelectedItem;
FoodMachineEvent(this,args);
}
public void UpdateGoodList(List<String> goodList)
{
this.goods = goodList;
GoodListCombo.Items.AddRange(goods.ToArray());
}
public void ShowOrderDescription(String description)
{
orderText.Text = description;
}
public void ShowAvailableAdditions(List<String> additionsList, SingleGoodType type)
{
if (type==SingleGoodType.Food)
{
foodAdditionsCombo.Items.Clear();
foodGroup.Enabled = true;
foodAdditionsCombo.Items.AddRange(additionsList.ToArray());
foodAdditionsCombo.Text = "Select addition";
}
else if (type == SingleGoodType.Drink)
{
drinkAdditionsCombo.Items.Clear();
drinkGroup.Enabled = true;
drinkAdditionsCombo.Items.AddRange(additionsList.ToArray());
drinkAdditionsCombo.Text = "Select addition";
additionUpDown.Enabled = false;
}
this.additions = additionsList;
}
public void ShowAvailiableAdditionLevel(int max)
{
if (max == 1)
additionUpDown.Enabled = false;
else
{
additionUpDown.Enabled = true;
additionUpDown.Maximum = max;
}
}
private void getButton_Click(object sender, EventArgs e)
{
FoodMachineEventArgs args = new FoodMachineEventArgs();
args.code = EventCode.GetOrderRequested;
FoodMachineEvent(this, args);
}
public void TakeOrder(String text)
{
MessageBox.Show(text);
}
private void addToFoodButton_Click(object sender, EventArgs e)
{
FoodMachineEventArgs args = new FoodMachineEventArgs();
args.code = EventCode.AdditionAdded;
args.Message = (String)foodAdditionsCombo.SelectedItem;
FoodMachineEvent(this, args);
}
private void addToDrinkButton_Click(object sender, EventArgs e)
{
FoodMachineEventArgs args = new FoodMachineEventArgs();
args.code = EventCode.AdditionAdded;
args.Message = (String)drinkAdditionsCombo.SelectedItem;
if (additionUpDown.Enabled == true)
args.MessageAdditionalData = (int) additionUpDown.Value;
FoodMachineEvent(this, args);
}
private void drinkAdditionsCombo_SelectedIndexChanged(object sender, EventArgs e)
{
additionUpDown.Enabled = false;
FoodMachineEventArgs args = new FoodMachineEventArgs();
args.code = EventCode.AdditionSelected;
args.Message = (String)drinkAdditionsCombo.SelectedItem;
FoodMachineEvent(this, args);
}
}
}
|
namespace Fukasawa {
public enum BlogPostTypes {
Image = 1,
Gallery = 2,
Content = 4
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Problem_4_Roli___The_Coder
{
public class Problem_4_Roli___The_Coder
{
public static void Main()
{
var input = Console.ReadLine();
var result = new Dictionary<int, Event>();
while (input != "Time for Code")
{
var pattren = new Regex(@"(\d+)\s+#([\w\d]+)(\s+(?:@\w+\s*)+)?");
var validData = pattren.Match(input);
if (validData.Success)
{
var line = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
var id = int.Parse(line[0]);
var nameEvent = line[1].TrimStart('#');
var participant = line.Skip(2).ToList();
var currentEvent = new Event() { EventName = nameEvent, Participants = participant };
if (!result.ContainsKey(id))
{
result[id] = currentEvent;
}
if (result[id].EventName == nameEvent)
{
result[id].Participants.AddRange(participant);
result[id].Participants = result[id].Participants.Distinct().ToList();
}
}
input = Console.ReadLine();
}
foreach (var item in result.OrderByDescending(x => x.Value.Participants.Count).ThenBy(a => a.Value.EventName))
{
var details = item.Value;
Console.WriteLine($"{details.EventName} - {details.Participants.Count}");
foreach (var people in details.Participants.OrderBy(y => y))
{
Console.WriteLine(people);
}
}
}
}
public class Event
{
public string EventName { get; set; }
public List<string> Participants { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ODL.InfrastructureServices
{
public class Anvandare : IAnvandare
{
public Anvandare(ClaimsPrincipal user)
{
Namn = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
AnvandarNamn = user.Claims.FirstOrDefault(c => c.Type == "AnvandarNamn")?.Value;
Email = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var minaRolerString = user.Claims.FirstOrDefault(c => c.Type == "Roler")?.Value;
if (minaRolerString != null) Roler = new List<string>(minaRolerString.Split(','));
var minaRbacString = user.Claims.FirstOrDefault(c => c.Type == "Rbac")?.Value;
if (minaRbacString != null) Rbac = new List<string>(minaRbacString.Split(','));
Personnummer = user.Claims.FirstOrDefault(c => c.Type == "Personnummer")?.Value;
Applikation = user.Claims.FirstOrDefault(c => c.Type == "Applikation")?.Value;
}
public string Personnummer { get; }
public string AnvandarNamn { get; }
public string Namn { get; }
public string Email { get; }
public IEnumerable<string> Roler { get; }
public IEnumerable<string> Rbac { get; }
public string Applikation { get; }
public bool IsBehorig()
{
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OptimisationCat
{
public class TestExport
{
public string Name { get; set; }
public string Func { get; set; }
public string Answer { get; set; }
public string Iterations { get; set; }
public string Time{ get; set; }
public string Eps { get; set; }
public TestExport(string name, string func, string answer, string iterations, string time, string eps)
{
Name = name;
Func = func;
Answer = answer;
Iterations = iterations;
Time = time;
Eps = eps;
}
}
}
|
using Task1_Euclidian_Algorithm;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Task1_Euclidian_Algorithm_Unit_Tests
{
[TestClass]
public class CalculatorTests
{
/// <summary>
/// Initialization for work with Calculator
/// </summary>
private Calculator _calculator = new Calculator();
/// <summary>
/// Calculate GCD by Stain algoritm input: positive numbers
/// </summary>
[TestMethod]
public void GetGCDbySteinAlgorithmTest()
{
//act
var result1 = _calculator.GetGCDbySteinAlgorithm(125, 25);
//assert
Assert.AreEqual(25, result1);
}
/// <summary>
/// Calculate GCD by Stain algoritm input: positive and negative numbers
/// </summary>
[TestMethod]
public void GetGCDbySteinAlgorithmTestWithNegativeInput()
{
//arrenge
int firstValue = 125;
int secondValue = -25;
//act
var result1 = _calculator.GetGCDbySteinAlgorithm(firstValue, secondValue);
//assert
Assert.AreEqual(25, result1);
}
/// <summary>
/// Calculate GCD by Stain algoritm input: negative numbers
/// </summary>
[TestMethod]
public void GetGCDbySteinAlgorithmTestWithNegativeInput2()
{
//arrenge
int firstValue = -125;
int secondValue = -25;
//act
var result1 = _calculator.GetGCDbySteinAlgorithm(firstValue, secondValue);
//assert
Assert.AreEqual(25, result1);
}
/// <summary>
/// Calculate GCD by Newton algoritm input: positive numbers
/// </summary>
[TestMethod]
public void GetGreatestCommonDivisorTest()
{
//arrenge
int firstValue = 125;
int secondValue = 25;
//act
var result1 = _calculator.GetGreatestCommonDivisor(firstValue, secondValue);
//assert
Assert.AreEqual(25, result1);
}
/// <summary>
/// Calculate GCD by Newton algoritm input: positive and negative numbers
/// </summary>
[TestMethod]
public void GetGreatestCommonDivisorTestWithNegative()
{
//arrenge
int firstValue = 125;
int secondValue = -25;
//act
var result1 = _calculator.GetGreatestCommonDivisor(firstValue, secondValue);
//assert
Assert.AreEqual(25, result1);
}
/// <summary>
/// Calculate GCD by Newton algoritm input: negative numbers
/// </summary>
[TestMethod]
public void GetGreatestCommonDivisorTestWithNegative2()
{
//arrenge
int firstValue = -125;
int secondValue = -25;
//act
var result1 = _calculator.GetGreatestCommonDivisor(firstValue, secondValue);
//assert
Assert.AreEqual(25, result1);
}
}
}
|
namespace Ach.Fulfillment.Scheduler.Jobs
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ach.Fulfillment.Data;
using Business;
using Fulfillment.Common;
using Microsoft.Practices.Unity;
using Quartz;
using Renci.SshNet;
[DisallowConcurrentExecution]
public class GenerateAchFilesJob : IJob
{
#region Public Properties
[Dependency]
public IAchFileManager Manager { get; set; }
#endregion
#region Public Methods and Operators
public void Execute(IJobExecutionContext context)
{
try
{
using (new UnitOfWork())
{
var dataMap = context.JobDetail.JobDataMap;
var achfilesStore = dataMap.GetString("AchFilesStore");
this.Manager.Generate();
var achFiles = this.Manager.GetAchFilesDataForUploading();
foreach (var newPath in achFiles.Select(achFile => Path.Combine(achfilesStore, achFile.Key.Name + ".ach")))
{
using (var file = new StreamWriter(newPath))
{
file.Write(newPath);
file.Flush();
file.Close();
}
}
var ftphost = dataMap.GetString("FtpHost");
var userId = dataMap.GetString("UserId");
var password = dataMap.GetString("Password");
if (!(string.IsNullOrEmpty(ftphost)
&& string.IsNullOrEmpty(userId) && string.IsNullOrEmpty(password)))
{
var connectionInfo = new PasswordConnectionInfo(ftphost, userId, password);
// {
// Timeout = TimeSpan.FromSeconds(60)
// };
this.Uploadfiles(connectionInfo, achFiles);
}
}
}
catch (Exception ex)
{
throw new JobExecutionException(ex);
}
}
#endregion
#region Private Methods
private void Uploadfiles(PasswordConnectionInfo connectionInfo, Dictionary<AchFileEntity, string> achFilesToUpload)
{
using (var sftp = new SftpClient(connectionInfo))
{
try
{
sftp.Connect();
foreach (var achfile in achFilesToUpload)
{
try
{
using (var stream = new MemoryStream())
{
var fileName = achfile.Key.Name + ".ach";
this.Manager.Lock(achfile.Key);
var writer = new StreamWriter(stream);
writer.Write(achfile.Value);
writer.Flush();
stream.Position = 0;
sftp.UploadFile(stream, fileName);
this.Manager.ChangeAchFilesStatus(achfile.Key, AchFileStatus.Uploaded);
}
}
finally
{
this.Manager.UnLock(achfile.Key);
}
}
}
finally
{
sftp.Disconnect();
}
}
}
#endregion
}
} |
namespace ApiSoftPlan.Controllers
{
using ApiSoftPlan.Models;
using Microsoft.AspNetCore.Mvc;
/// <summary>The calcula juros controller.</summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ShowMeTheCodeController : Controller
{
/// <summary>The show me the code get.</summary>
/// <returns>The <see cref="IActionResult"/>.</returns>
[HttpGet(Name = nameof(ShowMeTheCodeGet))]
[Produces("application/json")]
public string ShowMeTheCodeGet()
{
return "https://github.com/BrunoMR/SofPlan";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class HandleTurn
{
public string Attacker; //name of attacker
public Types attackerType;
public Types targetType;
public GameObject AttackersGameObject; //GameObject of attacker
public GameObject AttackersTarget; //Who will be attacked
public BaseAttack chosenAttack; //which attack is performed
public Item chosenItem; //which attack is performed
public ActionType actionType; //to determine how turn should be processed when applying damage/effect
List<BaseStatusEffect> statusEffects = new List<BaseStatusEffect>(); //any status effects to be stored in the turn
}
|
using System;
namespace Emanate.Service
{
static class Program
{
static void Main()
{
if (Environment.UserInteractive)
{
var serviceRunner = new ServiceRunner();
serviceRunner.RunAsConsole();
}
else
{
var serviceRunner = new ServiceRunner();
serviceRunner.RunAsService();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Facturation.Shared
{
public class DashboardResearch
{
public DateTime DateMin { get; set; }
public DateTime DateMax { get; set; }
public DashboardResearch()
{
int year = DateTime.Now.Year;
DateMin = new DateTime(year, 1, 1);
DateMax = new DateTime(year, 12, 31);
}
}
}
|
namespace Ricky.Infrastructure.Core.Generic
{
public interface IHit<TKey, TDoc>
{
TKey Id { get; set; }
TDoc Document { get; set; }
}
}
|
using System;
namespace ServiceQuotes.Application.DTOs.Quote
{
public class GetQuoteResponse
{
public Guid Id { get; set; }
public int ReferenceNumber { get; set; }
public decimal Total { get; set; }
public string Status { get; set; }
public Guid ServiceRequestId { get; set; }
public DateTime Created { get; set; }
}
}
|
namespace AbstractFactory
{
public class BluetoothPlayer : Som
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Globalization;
public class Ball_Controller : MonoBehaviour
{
public GameObject G_MaxScale;
private GameObject G_LevelCircle; //Circle
private int I_Random; //To find random circle
public GameObject[] G_Circle; //Circle for all level
public static int level; //Level
public static string S_Happened; //What happened(Win, Die or Middle)
public GameObject G_Ball; //This object(for static void)
public static Transform T_BallTransform; //To change scale in static void
private float F_Speed = 0; //Speed do ball bigger when touch
private float F_SpeedValue; //Speed whaw ball do bigger;
public static bool B_Second; //False when ball bigger than target(circle) => player lose
public static bool B_First; //Trrue when ball smoller than target(circle) => player can win
public void Start()
{
T_BallTransform = gameObject.GetComponent<Transform>();
level = 1; //First level must be first :)
V_NewLevel();
S_Happened = "nope"; //This is the start value of this variable
//T_BallTransform = G_Ball.GetComponent<Transform>();
F_SpeedValue = 0.00005f;//U need to change this(If level big this beed be bigger)
}
void Update()
{
transform.position = new Vector3(GameController.F_X, GameController.F_Y, transform.position.z); //Ball will be do bigger into the circle, near the Touch
if (Touch.S_Touch == "true" && !B_Second)
{
//Do ball bigger
F_Speed += F_SpeedValue;
transform.localScale = new Vector3(transform.localScale.y + F_Speed, transform.localScale.y + F_Speed);
}
//What happened (haw big ball when pleyer stop do it bigger)
if (Touch.S_Touch == "false" && !B_First && !B_Second)
{
Touch.S_Touch = "nope";
S_Happened = "middle";
print("midle");
}
if (Touch.S_Touch == "false" && B_First && !B_Second)
{
level++;
if (level <= 100)
{
F_SpeedValue += 0.000003f;
}
Touch.S_Touch = "nope";
S_Happened = "win";
print("win");
V_NewLevel();
}
if ((Touch.S_Touch == "false" && B_Second) || B_Second)
{
Touch.S_Touch = "nope";
S_Happened = "lose";
print("lose");
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
//To know haw big ball(to know when player die or won)
if (collision.gameObject.CompareTag("CircleDiePlase"))
{
B_Second = true;
print(collision + " DiePlase");
}
if (collision.gameObject.CompareTag("CircleWinPlase"))
{
B_First = true;
print(collision + " WinPlase");
}
}
public void V_NewLevel()
{
//find random circle(level affect)
if (Mathf.CeilToInt(level / 10f) - 3f >= 0) //If "level" (level / 10) >= 3
{
I_Random = Random.Range(Mathf.CeilToInt((level / 10f) - 3f) * (G_Circle.Length / 10), Mathf.CeilToInt(level / 10f) * (G_Circle.Length / 10));
}
else if (Mathf.CeilToInt(level / 10f) - 3f < 0) //If "level" (level / 10) < 3
{
I_Random = Random.Range(0, Mathf.CeilToInt(level / 10f) * (G_Circle.Length / 10));
print(Mathf.CeilToInt(level / 10f) + " " + level + " " + (level / 10f));
}
//print("test " + G_CloneCircle.transform.position.z + " random" + I_Random); //
if (level > 1)
{
Destroy(G_LevelCircle);
}
G_LevelCircle = Instantiate(G_Circle[I_Random]);
G_LevelCircle.transform.localScale = new Vector3(G_MaxScale.transform.localScale.x, G_MaxScale.transform.localScale.y, G_MaxScale.transform.localScale.z);
//If u will not change this speed for do ball bigger will be more bigger every level (level doesnt affect)
F_Speed = 0f;
//Spawn random circle
G_LevelCircle.transform.position = new Vector3
(GameController.F_X, GameController.F_Y, 5f);
//For new level u need do value of collider like this
T_BallTransform.localScale = new Vector2(0f, 0f);
B_Second = false;
B_First = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FoodMachine
{
public enum EventCode { GoodSelected, AdditionSelected, AdditionAdded, SugarLevelSet, GetOrderRequested}
public class FoodMachineEventArgs:EventArgs
{
public EventCode code;
public String Message;
public int MessageAdditionalData;
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class MissionSelect : MonoBehaviour {
struct Mission{
private string missionType, missionDescription, missionTarget, missionTheme, difficulty;
private int daysLeft;
private Texture missionTargetLogo;
public Mission(string type, string des, string target, string theme, string diff, int days, Texture logo){
missionType = type;
missionDescription = des;
missionTarget = target;
missionTheme = theme;
difficulty = diff;
daysLeft = days;
missionTargetLogo = logo;
}
public string mission_type{
get {return missionType;}
set {missionType = value;}
}
public string mission_description{
get {return missionDescription;}
set {missionDescription = value;}
}
public string mission_target{
get {return missionTarget;}
set {missionTarget = value;}
}
public string mission_theme{
get {return missionTheme;}
set {missionTheme = value;}
}
public Texture mission_logo{
get {return missionTargetLogo;}
set {missionTargetLogo = value;}
}
public string mission_difficulty{
get {return difficulty;}
set {difficulty = value;}
}
public int days_left{
get {return daysLeft;}
set {daysLeft = value;}
}
}
List<Mission> missionList = new List<Mission>();
RectTransform rTransform;
Text txt;
GameObject missionListObject;
// Use this for initialization
void Start () {
//missionList.Add(new Mission(());
for(int i = 0; i < 20; i++){
GenerateMission();
}
// foreach (Mission m in missionList) // Loop through List with foreach.
// {
// print("FOREACH: " +m.mission_difficulty);
// }
missionListObject = GameObject.Find("Canvas").transform.Find("ScrollableWindow").Find("MissionList").gameObject;
missionListObject.GetComponent<RectTransform>().sizeDelta = new Vector2(900, missionList.Count * 80 );
for(int i =0; i < missionList.Count; i++){
//print("FOR: " +missionList[i].mission_difficulty);
GameObject missionObject = Instantiate(Resources.Load("Mission"), transform.position, Quaternion.identity) as GameObject;
missionObject.transform.parent = missionListObject.transform;
missionObject.GetComponent<RectTransform>().localPosition = new Vector3(0,(-i*80) + (((missionList.Count/2) * 80) - 40),0);
missionObject.transform.Find("Days").GetComponent<Text>().text = missionList[i].days_left.ToString();
missionObject.transform.Find("Difficulty").GetComponent<Text>().text = missionList[i].mission_difficulty;
missionObject.transform.Find("Title").GetComponent<Text>().text = missionList[i].mission_description;
if(i == 0)missionObject.GetComponent<MissionListing>().isSelected = true;
}
GameObject scrollbarObject = Instantiate(Resources.Load("Scrollbar")) as GameObject;
scrollbarObject.transform.parent = missionListObject.transform.parent.parent;
scrollbarObject.GetComponent<RectTransform>().localPosition = new Vector3(470,0,0);
scrollbarObject.GetComponent<Scrollbar>().value = 1;
missionListObject.transform.parent.GetComponent<ScrollRect>().verticalScrollbar = scrollbarObject.GetComponent<Scrollbar>();
}
void GenerateMission(){
string m_type = "Heist",
m_description = "Description goes here",
m_target = "Target",
m_difficulty = "Easy",
m_theme = "Office";
int m_days = 5;
Texture m_logo = new Texture();
missionList.Add(new Mission(m_type, m_description, m_target, m_theme, m_difficulty, m_days, m_logo));
}
string CalculateDifficulty(){
string difficulty = "Easy";
return difficulty;
}
// Update is called once per frame
void Update () {
}
}
|
using Model.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PagedList;
namespace Model.DAO
{
public class TeacherDao
{
PinwhellDbContext db = null;
public TeacherDao()
{
db = new PinwhellDbContext();
}
public long Insert(Teacher entity)
{
db.Teacher.Add(entity);
db.SaveChanges();
return entity.MaGV;
}
public IEnumerable<Teacher> ListAllTeacherPaging(int page, int pageSize)
{
return db.Teacher.OrderBy(x => x.MaGV).ToPagedList(page, pageSize);
}
public IEnumerable<TaiLieuHocTap> ListAllTaiLieupaging(int page, int pageSize)
{
return db.TaiLieuHocTap.OrderByDescending(x => x.MaTL).ToPagedList(page, pageSize);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scripts
{
public class Sphere : MonoBehaviour
{
public bool IsTied { get; set; }
public GameObject TiedWith { get; set; }
public GameObject Line { get; set; }
private AudioSource audioSource;
private GameInit gameInit;
void Start()
{
gameInit = GameObject.Find("Initialization").GetComponent<GameInit>();
audioSource = GetComponent<AudioSource>();
IsTied = false;
StartCoroutine(Move());
}
IEnumerator Move()
{
while (true)
{
yield return new WaitForSeconds(0.001f);
if (IsTied && gameObject != null && TiedWith != null)
{
transform.position = Vector3.MoveTowards(transform.position, TiedWith.transform.position, Time.deltaTime * 2);
}
}
}
private void GameOver()
{
StopAllCoroutines();
gameInit.GameOver();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Cut")
{
transform.GetComponent<CircleCollider2D>().enabled = false;
audioSource.Play();
GameObject waterSplash = Instantiate(gameInit.waterSplashPrefab, collision.transform.position, new Quaternion());
Destroy(waterSplash, 1f);
if (gameObject != null)
{
GameObject.Find("Canvas").transform.GetChild(3).GetChild(0).GetComponent<Image>().fillAmount -= .3f;
if (GameObject.Find("Canvas").transform.GetChild(3).GetChild(0).GetComponent<Image>().fillAmount <= 0)
{
GameOver();
StopCoroutine(Move());
gameInit.gameOverUI.SetActive(true);
}
gameInit.spheres.Remove(gameInit.spheres.Find(_ => _ == gameObject));
gameInit.NumberOfSpheres -= 1;
if (IsTied)
{
StopCoroutine(Move());
Destroy(Line);
gameInit.lines.Remove(gameInit.lines.Find(_ => _ == gameObject));
TiedWith.GetComponent<Sphere>().IsTied = false;
}
gameObject.GetComponent<Animator>().SetBool("IsTouched", true);
}
}
if (collision.tag == "Sphere")
{
if (gameObject != null)
{
audioSource.Play();
GameObject sphereTouchEffect = Instantiate(gameInit.sphereDeathEffectPrefab, collision.transform.position, new Quaternion());
Destroy(sphereTouchEffect, 1f);
GameObject.Find("Canvas").transform.GetChild(3).GetChild(0).GetComponent<Image>().fillAmount -= .2f;
if (GameObject.Find("Canvas").transform.GetChild(3).GetChild(0).GetComponent<Image>().fillAmount == 0)
{
GameOver();
StopCoroutine(Move());
gameInit.gameOverUI.SetActive(true);
}
gameInit.spheres.Remove(gameInit.spheres.Find(_ => _ == gameObject));
gameInit.NumberOfSpheres -= 1;
gameInit.lines.Remove(gameInit.lines.Find(_ => _ == gameObject));
DoubleSphereDestroy();
Destroy(Line);
}
}
}
public void DoubleSphereDestroy()
{
TiedWith.GetComponent<CircleCollider2D>().enabled = false;
this.Line.GetComponent<EdgeCollider2D>().enabled = false;
transform.GetComponent<CircleCollider2D>().enabled = false;
StartCoroutine(DoubleSphereDeath());
}
public void DestroySphere()
{
StartCoroutine(SphereDeath());
}
private IEnumerator DoubleSphereDeath()
{
yield return new WaitForSeconds(.3f);
if (gameObject != null)
{
Destroy(gameObject);
}
if (TiedWith != null)
{
Destroy(TiedWith);
}
yield return null;
}
private IEnumerator SphereDeath()
{
//yield return new WaitWhile(() => audioSource.isPlaying);
//gameObject.GetComponent<Animator>().cli
//yield return new WaitForSeconds(.3f);
if (gameObject != null)
{
Destroy(gameObject);
}
yield return null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour {
#region main variables
public List<Sprite> availableSymbols = new List<Sprite>(); // List of available symbol sprites.
public Image player1Sprite; // Chosen sprite of player 1.
public Image player2Sprite; // Chosen sprite of player 2.
private int chosenGridSize = 3; // Current grid size.
public Button gridSizeButton; // Button showing the grid size.
#endregion
#region monobehavior methods
// Use this for initialization
void Start () {
Overseer.ChangeGameState(Overseer.GameState.Main_Menu);
if (player1Sprite != null)
player1Sprite.sprite = availableSymbols[(int)Random.Range(0, availableSymbols.Count)];
if (player2Sprite != null)
player2Sprite.sprite = availableSymbols[(int)Random.Range(0, availableSymbols.Count)];
ChangePlayer1Image();
}
// Update is called once per frame
void Update () {
}
#endregion
#region methods
/// <summary>
/// Switch the selected sprite of Player 1.
/// </summary>
public void ChangePlayer1Image()
{
int index = 0;
if(player1Sprite != null)
{
index = availableSymbols.IndexOf(player1Sprite.sprite); // Current position in list of player 1.
player1Sprite.sprite = availableSymbols[(index + 1) % availableSymbols.Count]; // Increment index.
if (player1Sprite.sprite == player2Sprite.sprite) // If we have the same symbol as player 2, we should skip the next symbol.
player1Sprite.sprite = availableSymbols[(index + 2) % availableSymbols.Count];
}
}
/// <summary>
/// Switch the selected sprite of Player 2.
/// </summary>
public void ChangePlayer2Image()
{
int index = 0;
if (player1Sprite != null)
{
index = availableSymbols.IndexOf(player2Sprite.sprite);
player2Sprite.sprite = availableSymbols[(index + 1) % availableSymbols.Capacity];
if (player2Sprite.sprite == player1Sprite.sprite)
player2Sprite.sprite = availableSymbols[(index + 2) % availableSymbols.Capacity];
}
}
/// <summary>
/// Change grid size of main menu button and game.
/// </summary>
public void ChangeGridSize()
{
if (chosenGridSize == 3)
chosenGridSize = 4;
else
chosenGridSize = 3;
if(gridSizeButton != null)
gridSizeButton.GetComponentInChildren<Text>().text = chosenGridSize + "X" + chosenGridSize; // Change display text of grid size button.
}
/// <summary>
/// Start game from main menu. Load game scene.
/// </summary>
public void StartGame()
{
Overseer.ChangeGridSize(chosenGridSize); // Set the grid size of the grid in the game scene.
Overseer.SetPlayerSymbols(new Sprite[2] { player1Sprite.sprite, player2Sprite.sprite }); // Based on the symbols chosen by the player in the menu, save and send to the Overseer for use in the game scene.
UnityEngine.SceneManagement.SceneManager.LoadScene("TicTacToe-Game"); // Load the game scene.
}
#endregion
}
|
using System;
namespace Spool.Harlowe
{
abstract class Changer : Data
{
public static DataType Type { get; } = new DataType(typeof(Changer));
public override bool Serializable => true;
protected override object GetObject() => this;
protected override string GetString() => $"a ({GetType().Name}:) changer";
public virtual void Apply(ref bool? hidden, ref string name) {}
public abstract void Render(Context context, Action source);
public virtual void RememberHidden(Context context, IDisposable cursorPosition) {}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Docller.Core.Common;
using Docller.Core.Models;
namespace Docller.UI.Models
{
public class FileAttachmentViewModel
{
public FileAttachmentViewModel()
{
}
public FileAttachmentViewModel(long fileId)
{
this.FileId = fileId;
}
public FileAttachmentViewModel(FileAttachment fileAttachment)
{
if (fileAttachment != null)
{
this.FileId = fileAttachment.FileId;
this.FileName = fileAttachment.FileName;
this.Extension = fileAttachment.FileExtension;
this.CreatedBy = fileAttachment.CreatedBy.DisplayName;
this.FormattedCreatedDate = fileAttachment.CreatedDate.ToShortDateString().Replace("/", ".");
this.Icon = string.Format("/Images/filetype-icons/32X32/{0}",
FileTypeIconsFactory.Current.Medium[fileAttachment.FileExtension]);
this.RevisionNumber = fileAttachment.RevisionNumber;
Initversions(fileAttachment.Versions);
}
}
public int TotalChunks { get; set; }
public int CurrentChunk { get; set; }
public Stream FileStream { get; set; }
public long FileId { get; set; }
public int RevisionNumber { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
public string CreatedBy { get; set; }
public string Icon { get; set; }
public string FormattedCreatedDate { get; set; }
public List<FileAttachmentViewModel> Versions { get; set; }
public decimal FileSize { get; set; }
public long ProjectId { get; set; }
public long FolderId { get; set; }
private void Initversions(IEnumerable<FileAttachmentVersion> versions)
{
if (versions != null)
{
Versions = new List<FileAttachmentViewModel>();
foreach (var version in versions)
{
Versions.Add(new FileAttachmentViewModel(version));
}
}
}
public FileAttachment GetFileAttachment()
{
return new FileAttachment()
{
FileSize = this.FileSize,
FileName = this.FileName,
FileId = this.FileId,
Project = new Project() {ProjectId = this.ProjectId},
Folder = new Folder() {FolderId = this.FolderId}
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Deployment.Application;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
namespace WinAirvid
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
DispatcherUnhandledException += App_DispatcherUnhandledException;
base.OnStartup(e);
CheckForShortcut();
}
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
ShowExceptionMsg(e.Exception);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
ShowExceptionMsg(ex);
}
void ShowExceptionMsg(Exception ex)
{
MessageBox.Show(ex.ToString(), "Uncaught Exception",
MessageBoxButton.OK, MessageBoxImage.Error);
}
/// <summary>
/// This will create a Application Reference file on the users desktop
/// if they do not already have one when the program is loaded.
/// Check for them running the deployed version before doing this,
/// so it doesn't kick it when you're running it from Visual Studio.
/// </summary>
static void CheckForShortcut()
{
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.IsFirstRun) //first time user has run the app since installation or update
{
Assembly code = Assembly.GetExecutingAssembly();
string company = string.Empty;
string description = string.Empty;
if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
{
AssemblyCompanyAttribute ascompany =
(AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyCompanyAttribute));
company = ascompany.Company;
}
if (Attribute.IsDefined(code, typeof(AssemblyDescriptionAttribute)))
{
AssemblyDescriptionAttribute asdescription =
(AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code,
typeof(AssemblyDescriptionAttribute));
description = asdescription.Description;
}
if (company != string.Empty && description != string.Empty)
{
string desktopPath = string.Empty;
desktopPath = string.Concat(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"\\", description, ".appref-ms");
string shortcutName = string.Empty;
shortcutName = string.Concat(
Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"\\", company, "\\", description, ".appref-ms");
System.IO.File.Copy(shortcutName, desktopPath, true);
}
}
}
}
}
}
|
namespace GeneralResources.CursoAlgoritmoEstruturaDeDados.Sorting
{
/// <summary>
/// https://www.techopedia.com/definition/21578/quicksort
/// </summary>
public class QuickSort
{
/* Description
*
The quicksort algorithm is performed as follows:
A pivot point is chosen from the array.
The array is reordered so that all values smaller than the pivot are moved before it and all values larger than the pivot are moved after it, with values equaling the pivot going either way. When this is done, the pivot is in its final position.
The above step is repeated for each subarray of smaller values as well as done separately for the subarray with greater values.
This is repeated until the entire array is sorted.
*/
/// <summary>
/// The pivot choice is the most important step in this algorithm
/// </summary>
/// <param name="m"></param>
public static void Sort(int[] m)
{
Sort(m, 0, m.Length - 1);
}
static void Sort(int[] m, int startPos, int endPos)
{
//pivot choice
int pivot = m[startPos];
int l = startPos;
int r = endPos;
while (l <= r)
{
//stop if any point break the rule
while (m[l] < pivot) l++;
while (m[r] > pivot) r--;
if (l <= r)
{
SortUtils.Swap(m, l, r);
l++;
r--;
}
}
if(startPos < r) Sort(m, startPos, r);
if(endPos > l) Sort(m, l, endPos);
}
[Theory]
[InlineData(new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 2, 3, 4, 5 })]
[InlineData(new int[] { 3, 1, 6, 4, 2 }, new int[] { 1, 2, 3, 4, 6 })]
public void Validate(int[] input, int[] expected)
{
//Arrange
//Act
QuickSort.Sort(input);
//Assert
Assert.Equal(expected, input);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Serilog;
using TestTask.CustomAuth.Models;
using TestTask.CustomAuth.Repositories;
namespace TestTask.CustomAuth.Controllers
{
[Authorize(Roles = "admin")]
public class AdminController : Controller
{
private IProductRepository productRepository;
public AdminController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public ViewResult Index() => View(productRepository.Products);
public ViewResult Edit(int productId) =>
View(productRepository.Products
.FirstOrDefault(p => p.ProductId == productId));
[HttpPost]
public IActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
bool isNew = product.ProductId == 0 ? true : false;
productRepository.SaveProduct(product);
TempData["message"] = $"{product.Name} успешно сохранен";
if (isNew)
{
Log.Information("{@User}: Товар был добавлен {@product}", User.Identity.Name, product);
}
else
{
Log.Information("{@User}: Товар был изменен {@ProductId}", User.Identity.Name, product.ProductId);
}
return RedirectToAction("Index");
}
else
{
//ошибка в веденных данных
return View(product);
}
}
public ViewResult Create() => View("Edit", new Product());
[HttpPost]
public IActionResult Delete(int productId)
{
Product deletedProduct = productRepository.DeleteProduct(productId);
if (deletedProduct != null)
{
TempData["message"] = $"{deletedProduct.Name} успешно удален";
Log.Information("{@User}: Товар был удален {@product}", User.Identity.Name, deletedProduct);
}
return RedirectToAction("Index");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Rexxar.Identity.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Identity;
using IdentityServer4.Services;
using System.Threading.Tasks;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
namespace Rexxar.Identity
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
#region DbContext
//配置AspNetCore DbContext 服务
services.AddDbContext<RexxarDbContext>(o =>
{
o.UseNpgsql(Configuration.GetConnectionString("RexxarIdentity"),options=>
{
//配置迁移时程序集
options.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
});
});
#endregion
#region Identity
//配置AspNetCore Identity服务用户密码的验证规则
services.AddIdentity<RexxarUser, RexxarRole>(o =>
{
o.Password.RequireDigit = false;
o.Password.RequiredLength = 6;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
})
// 告诉AspNetCore Identity 使用RexxarDbContext为数据库上下文
.AddEntityFrameworkStores<RexxarDbContext>()
.AddDefaultTokenProviders();
#endregion
#region IdentityServer4
//配置IdentityServer4服务
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddAspNetIdentity<RexxarUser>()
.AddConfigurationStore(o =>
{
o.ConfigureDbContext = builder =>
{
builder.UseNpgsql(Configuration.GetConnectionString("RexxarIdentity"), options =>
{
//配置迁移时程序集
options.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
});
};
})
// 使用数据库存储授权操作相关操作,数据库表PersistedGrants
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
{
builder.UseNpgsql(Configuration.GetConnectionString("RexxarIdentity"), sql =>
{
sql.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
});
};
})
// ids4使用自定义的用户档案服务
.Services.AddScoped<IProfileService, ProfileService>(); ;
#endregion
#region CORS
// 配置跨域,允许所有
services.AddCors(o =>
{
o.AddPolicy("all", policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
;
});
});
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("all");
app.UseIdentityServer();
MigrateDatabase(app).Wait();
}
public static async Task MigrateDatabase(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.CreateScope())
{
// 迁移DemoDbContext上下文
scope.ServiceProvider.GetRequiredService<RexxarDbContext>().Database.Migrate();
// 迁移PersistedGrantDbContext上下文
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var configurationDbContext = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
// 迁移ConfigurationDbContext上下文
configurationDbContext.Database.Migrate();
// 注入用户管理 增加用户
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<RexxarUser>>();
foreach (var user in SeedData.Users())
{
if (userManager.FindByNameAsync(user.UserName).Result == null)
{
await userManager.CreateAsync(user, "123456");
}
}
// 增加ApiResources IdentityResources Clients
if (!configurationDbContext.ApiResources.Any())
configurationDbContext.ApiResources.AddRange(Config.GetApiResouces().Select(r => r.ToEntity()));
if (!configurationDbContext.IdentityResources.Any())
configurationDbContext.IdentityResources.AddRange(Config.GetIdentityResources().Select(r => r.ToEntity()));
if (!configurationDbContext.Clients.Any())
configurationDbContext.Clients.AddRange(Config.GetClients().Select(r => r.ToEntity()));
await configurationDbContext.SaveChangesAsync();
}
}
}
}
|
/***********************************************************************
* Module: Equipment.cs
* Author: Jelena Budisa
* Purpose: Definition of the Class Equipment
***********************************************************************/
using System;
namespace Model.Manager
{
public class Equipment
{
public int Id { get; set; }
}
} |
using System;
namespace TestTdd
{
internal class SimpleService
{
public void Add(int a, int b, Action<bool, int> handler)
{
handler(true, a + b);
}
public void WhatTimeIsIt(Action<bool, long> handler)
{
handler(true, 123);
}
}
} |
using UnityEngine;
using System.Collections.Generic;
public class AbsoluteMove : BasicMove
{
private Vector3 endPoint;
public AbsoluteMove(Vector3 end) {
endPoint = end;
}
#region implemented abstract members of BasicMove
public override Move Clone ()
{
return new AbsoluteMove (endPoint).AddConstraint(manualAddedConstraints.ToArray());
}
#endregion
protected override List<Vector3> CalcEndPoints (Vector3 start, Board[] boards)
{
return new List<Vector3> (){ endPoint };
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using ac6_example_chop_configure_model;
namespace WebApplication.Models
{
public class Coordinate
{
public double Xcoordinate { get; set; }
public double Ycoordinate { get; set; }
public Coordinate(double x, double y)
{
Xcoordinate = x;
Ycoordinate = y;
}
}
public class GenerateCoordinate
{
//array parameters can be passed by [] into pointer, but result pointer cannot by passed back as []. Need to Marshal.
//entrypoint function can also be: public static extern IntPtr simulation(IntPtr sizes, IntPtr type_id, IntPtr begin, IntPtr end, IntPtr a, IntPtr b, IntPtr c, IntPtr d);
//[DllImport(@"ac6_example_chop_dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "simulation")]
//private static extern IntPtr simulation(int[] sizes, int[] type_id, double[] begin, double[] end, double[] a, double[] b, double[] c, double[] d);
private static AC6Simulation AC6Instance = new AC6Simulation();
private int howManySignals, howManySpeed, howManyTorque, paras_size;
private int[] paras_id, sizes, type_id;
private double[] paras_value, begin, end, a, b, c, d;
unsafe private void testfunc()
{
int[] abc = { 1, 2 };
fixed (int* cba = abc) { };
}
private void processInputData(string[] value)
{
int howManyModelParameters = 6;
paras_size = howManyModelParameters;
paras_id = new int[howManyModelParameters];
paras_value = new double[howManyModelParameters];
int[] defaul_ids = { 40, 48, 142, 141, 144, 143 };
for(int i=0;i<howManyModelParameters;i++)
{
paras_id[i] = defaul_ids[i];
paras_value[i] = double.Parse(value[i]);
}
string[] inputParameters = new string[value.Length - howManyModelParameters];
Array.Copy(value, howManyModelParameters, inputParameters, 0, inputParameters.Length);
int howManyInputParameters = 8;
howManySignals = inputParameters.Length / howManyInputParameters;
howManySpeed = 0;
howManyTorque = 0;
sizes = new int[2];
type_id = new int[howManySignals];
begin = new double[howManySignals];
end = new double[howManySignals];
a = new double[howManySignals];
b = new double[howManySignals];
c = new double[howManySignals];
d = new double[howManySignals];
for (int i = 0; i < howManySignals; i++)
{
if (inputParameters[i * howManyInputParameters] == "Speed")
howManySpeed++;
else
howManyTorque++;
if (inputParameters[i * howManyInputParameters + 1] == "Ramp")
type_id[i] = 1;
else if (inputParameters[i * howManyInputParameters + 1] == "Step")
type_id[i] = 2;
else
type_id[i] = 3;
begin[i] = double.TryParse(inputParameters[i * howManyInputParameters + 2], out begin[i]) ? begin[i] : 0.0;
end[i] = double.TryParse(inputParameters[i * howManyInputParameters + 3], out end[i]) ? end[i] : 0.0;
a[i] = double.TryParse(inputParameters[i * howManyInputParameters + 4], out a[i]) ? a[i] : 0.0;
b[i] = double.TryParse(inputParameters[i * howManyInputParameters + 5], out b[i]) ? b[i] : 0.0;
c[i] = double.TryParse(inputParameters[i * howManyInputParameters + 6], out c[i]) ? c[i] : 0.0;
d[i] = double.TryParse(inputParameters[i * howManyInputParameters + 7], out d[i]) ? d[i] : 0.0;
}
sizes[0] = howManySpeed;
sizes[1] = howManyTorque;
}
public List<List<Coordinate>> GeneratePoints(string[] value)
{
processInputData(value);
unsafe
{
fixed (int* parasID = paras_id)
fixed (double* parasValue = paras_value)
fixed (int* Sizes = sizes)
fixed (int* typeID = type_id)
fixed (double* Begin = begin)
fixed (double* End = end)
fixed (double* A = a)
fixed (double* B = b)
fixed (double* C = c)
fixed (double* D = d)
AC6Instance.configure_model(paras_size, parasID, parasValue, Sizes, typeID, Begin, End, A, B, C, D);
}
//Defining list of coordinate
List<List<Coordinate>> lst = new List<List<Coordinate>>();
List<Coordinate> lstCoordiante_Speed = new List<Coordinate>();
List<Coordinate> lstCoordiante_Torque = new List<Coordinate>();
for (int i = 0; i < howManySignals; i++)
{
if (type_id[i] == 1)
{
Console.WriteLine("Ramp");
Coordinate temp1 = new Coordinate(begin[i], c[i]);
Coordinate temp2 = new Coordinate(b[i], c[i]);
Coordinate temp3 = new Coordinate(end[i], c[i] + a[i] * (end[i] - b[i]));
if (i < howManySpeed)
{
lstCoordiante_Speed.Add(temp1);
lstCoordiante_Speed.Add(temp2);
lstCoordiante_Speed.Add(temp3);
}
else
{
lstCoordiante_Torque.Add(temp1);
lstCoordiante_Torque.Add(temp2);
lstCoordiante_Torque.Add(temp3);
}
}
else if (type_id[i] == 2)
{
Console.WriteLine("Step");
Coordinate temp1 = new Coordinate(begin[i], b[i]);
Coordinate temp2 = new Coordinate(a[i], b[i]);
Coordinate temp3 = new Coordinate(a[i], c[i]);
Coordinate temp4 = new Coordinate(end[i], c[i]);
if (i < howManySpeed)
{
lstCoordiante_Speed.Add(temp1);
lstCoordiante_Speed.Add(temp2);
lstCoordiante_Speed.Add(temp3);
lstCoordiante_Speed.Add(temp4);
}
else
{
lstCoordiante_Torque.Add(temp1);
lstCoordiante_Torque.Add(temp2);
lstCoordiante_Torque.Add(temp3);
lstCoordiante_Torque.Add(temp4);
}
}
else if (type_id[i] == 3)
{
Console.WriteLine("Step");
double sample_time = 0.01;
for (int j = 0; j < (end[i] - begin[i]) / sample_time; j++)
{
double x = begin[i] + j * sample_time;
double y = b[i] + a[i] * Math.Sin(c[i] * j * sample_time + Math.PI * d[i] / 180.0);
Coordinate temp = new Coordinate(x, y);
if (i < howManySpeed)
lstCoordiante_Speed.Add(temp);
else
lstCoordiante_Torque.Add(temp);
}
}
}
if (lstCoordiante_Speed.Count == 0)
lstCoordiante_Speed.Add(new Coordinate(0, 0));
if (lstCoordiante_Torque.Count == 0)
lstCoordiante_Torque.Add(new Coordinate(0, 0));
lst.Add(lstCoordiante_Speed);
lst.Add(lstCoordiante_Torque);
return lst;
}
public List<List<Coordinate>> FinalGraphFunction(string[] value)
{
processInputData(value);
double min_begin = (begin[0] <= begin[sizes[0]]) ? begin[0] : begin[sizes[0]];
double max_end = (end[sizes[0] - 1] >= end[sizes[0] + sizes[1] - 1]) ? end[sizes[0] - 1] : end[sizes[0] + sizes[1] - 1];
double simulation_duration = max_end - min_begin;
int total_steps = (int)Math.Ceiling(simulation_duration / 1.0E-5);
int allResults = total_steps * 6;
int show_steps = Math.Min((int)(2000 * simulation_duration), 5000);
int scale = total_steps / show_steps;
double[] xValue = new double[show_steps];
double[] yValue = new double[allResults];
//Defining list of coordinate
List<List<Coordinate>> lstCoordiante = new List<List<Coordinate>>();
List<Coordinate> StatorCurrent = new List<Coordinate>();
List<Coordinate> Speed = new List<Coordinate>();
List<Coordinate> Torque = new List<Coordinate>();
List<Coordinate> DCBusVoltage = new List<Coordinate>();
try
{
//IntPtr buffer = simulation(sizes, type_id, begin, end, a, b, c, d);
//Marshal.Copy(buffer, yValue, 0, allResults);
//Marshal.FreeCoTaskMem(buffer);
//unsafe method, copy result to yValue
unsafe
{
double* result = AC6Instance.simulation();
for (int i = 0; i < allResults; i++)
yValue[i] = result[i];
}
//define result list<Coordinate>
for (int i = 0; i < show_steps; i++)
{
int j = i * scale, k = 1 * total_steps + i * scale, l = 3 * total_steps + i * scale, m = 5 * total_steps + i * scale;
xValue[i] = 0.00001 * j;
StatorCurrent.Add(new Coordinate(xValue[i], yValue[j]));
Speed.Add(new Coordinate(xValue[i], yValue[k]));
Torque.Add(new Coordinate(xValue[i], yValue[l]));
DCBusVoltage.Add(new Coordinate(xValue[i], yValue[m]));
}
}
catch (Exception)
{
Console.WriteLine();
}
lstCoordiante.Add(StatorCurrent);
lstCoordiante.Add(Speed);
lstCoordiante.Add(Torque);
lstCoordiante.Add(DCBusVoltage);
return lstCoordiante;
}
}
} |
using UnityEngine;
public class DogMoving : MonoBehaviour
{
[Tooltip("狗子的水平移动速度")]
public float dog_speed_x;
[Tooltip("狗子的竖直移动速度")]
public float dog_speed_y;
//此时狗子是不是在空中
private bool is_inAir=false;
private bool is_lookingRight = false;
private bool is_moving = false;
private Vector3 target_pos;
private bool lookRight;
private void LateUpdate()
{
is_inAir = GetComponent<BottomCheck>().IsInAir();
if (is_moving&&!is_inAir)
{
Vector3 offset = target_pos - transform.position;
#region 水平位移
if (offset.x < 0.1f&&offset.x>-0.1f)
{
StopMoving();
GetComponent<Rigidbody2D>().velocity = new Vector2(0f,0f);
return;
}
if (offset.x > 0)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(dog_speed_x, 0f);
}else if (offset.x < 0)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-dog_speed_x, 0f);
}
#endregion
}
}
private void MoveTo(Vector3 target_position)
{
StartMoving();
this.target_pos = target_position;
if (target_position.x > transform.position.x)
{
LookRight();
}
else if (target_position.x < transform.position.x)
{
LookLeft();
}
}
private void JumpTo(Vector3 target_position)
{
if (!is_inAir)
{
StopMoving();
if (target_position.x > transform.position.x)
{
LookRight();
GetComponent<Rigidbody2D>().velocity = new Vector2(dog_speed_x, dog_speed_y);
}
else if (target_position.x < transform.position.x)
{
LookLeft();
GetComponent<Rigidbody2D>().velocity = new Vector2(-dog_speed_x, dog_speed_y);
}
else
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0f, dog_speed_y);
}
}
}
private void LookLeft()
{
is_lookingRight = false;
Transform spriteTransform = transform.GetChild(0);
if (is_lookingRight)
{
Quaternion look = new Quaternion(spriteTransform.rotation.x, 0.0f, spriteTransform.rotation.z, spriteTransform.rotation.w);
spriteTransform.rotation = look;
}
else
{
Quaternion look = new Quaternion(spriteTransform.rotation.x, 180.0f, spriteTransform.rotation.z, spriteTransform.rotation.w);
spriteTransform.rotation = look;
}
}
private void LookRight()
{
is_lookingRight = true;
Transform spriteTransform = transform.GetChild(0);
if (is_lookingRight)
{
Quaternion look = new Quaternion(spriteTransform.rotation.x, 0.0f, spriteTransform.rotation.z, spriteTransform.rotation.w);
spriteTransform.rotation = look;
}
else
{
Quaternion look = new Quaternion(spriteTransform.rotation.x, 180.0f, spriteTransform.rotation.z, spriteTransform.rotation.w);
spriteTransform.rotation = look;
}
}
public void StopMoving()
{
is_moving = false;
GetComponentInChildren<Animator>().SetBool("IsMoving", false);
}
public void StartMoving()
{
is_moving = true;
GetComponentInChildren<Animator>().SetBool("IsMoving", true);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.contacts[0].normal.x>=-1&&collision.contacts[0].normal.x<=1)
{
StopMoving();
}
}
}
|
using MediaBrowser.Common.IO;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Common.ScheduledTasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.ScheduledTasks
{
/// <summary>
/// Class AudioImagesTask
/// </summary>
public class AudioImagesTask : IScheduledTask
{
/// <summary>
/// Gets or sets the image cache.
/// </summary>
/// <value>The image cache.</value>
public FileSystemRepository ImageCache { get; set; }
/// <summary>
/// The _library manager
/// </summary>
private readonly ILibraryManager _libraryManager;
/// <summary>
/// The _media encoder
/// </summary>
private readonly IMediaEncoder _mediaEncoder;
/// <summary>
/// The _locks
/// </summary>
private readonly ConcurrentDictionary<string, SemaphoreSlim> _locks = new ConcurrentDictionary<string, SemaphoreSlim>();
/// <summary>
/// Initializes a new instance of the <see cref="AudioImagesTask" /> class.
/// </summary>
/// <param name="libraryManager">The library manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
public AudioImagesTask(ILibraryManager libraryManager, IMediaEncoder mediaEncoder)
{
_libraryManager = libraryManager;
_mediaEncoder = mediaEncoder;
ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
}
/// <summary>
/// Gets the name of the task
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return "Audio image extraction"; }
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public string Description
{
get { return "Extracts images from audio files that do not have external images."; }
}
/// <summary>
/// Gets the category.
/// </summary>
/// <value>The category.</value>
public string Category
{
get { return "Library"; }
}
/// <summary>
/// Executes the task
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="progress">The progress.</param>
/// <returns>Task.</returns>
public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{
var items = _libraryManager.RootFolder.RecursiveChildren
.OfType<Audio>()
.Where(i => i.LocationType == LocationType.FileSystem && string.IsNullOrEmpty(i.PrimaryImagePath) && i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Video))
.ToList();
progress.Report(0);
var numComplete = 0;
foreach (var item in items)
{
cancellationToken.ThrowIfCancellationRequested();
var album = item.Parent as MusicAlbum;
var filename = item.Album ?? string.Empty;
filename += album == null ? item.Id.ToString() + item.DateModified.Ticks : album.Id.ToString() + album.DateModified.Ticks;
var path = ImageCache.GetResourcePath(filename + "_primary", ".jpg");
var success = true;
if (!ImageCache.ContainsFilePath(path))
{
var semaphore = GetLock(path);
// Acquire a lock
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
// Check again
if (!ImageCache.ContainsFilePath(path))
{
try
{
await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, path, cancellationToken).ConfigureAwait(false);
}
catch
{
success = false;
}
finally
{
semaphore.Release();
}
}
else
{
semaphore.Release();
}
}
numComplete++;
double percent = numComplete;
percent /= items.Count;
progress.Report(100 * percent);
if (success)
{
// Image is already in the cache
item.PrimaryImagePath = path;
await _libraryManager.SaveItem(item, cancellationToken).ConfigureAwait(false);
}
}
progress.Report(100);
}
/// <summary>
/// Gets the default triggers.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<ITaskTrigger> GetDefaultTriggers()
{
return new ITaskTrigger[]
{
new DailyTrigger { TimeOfDay = TimeSpan.FromHours(1) }
};
}
/// <summary>
/// Gets the lock.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>System.Object.</returns>
private SemaphoreSlim GetLock(string filename)
{
return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
}
}
}
|
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TweetApp.DAL.Interfaces;
using TweetApp.Entities;
namespace TweetApp.Services
{
public class UserService
{
private readonly IMongoCollection<AppUser> _users;
public UserService(IMongoCollection<AppUser> users)
{
_users = users;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess;
using System.Collections;
using Anywhere2Go.Business.Utility;
using System.Globalization;
namespace Anywhere2Go.Business.Master
{
public class RegionLogic
{
MyContext _context = null;
public RegionLogic()
{
_context = new MyContext();
}
public RegionLogic(MyContext context)
{
_context = context;
}
public List<Geography> getGeography()
{
var req = new Repository<Geography>(_context);
List<Geography> result = req.GetQuery().Where(t => t.isActive == true).ToList();
return result;
}
public List<Province> getAllProvice()
{
List<Province> result = ApplicationCache.GetMaster<Province>();
return result;
}
public List<Province> getProvice(int geoID = 0)
{
List<Province> result = getAllProvice();
if (geoID != 0)
result = result.Where(t => t.geoID == geoID).ToList() ?? null;
result = result.Where(t => t.isActive == true && t.isAddress.Value).OrderByDescending(s => s.sort).ThenBy(s => s.provinceName, StringComparer.Create(new System.Globalization.CultureInfo("th-TH"), false)).ToList() ?? null;
return result;
}
public List<Province> GetProviceCarRegis()
{
List<Province> result = getAllProvice();
result = result.Where(t => t.isActive == true && t.isCarRegis.Value).OrderByDescending(s => s.sort).ThenBy(s => s.provinceName, StringComparer.Create(new System.Globalization.CultureInfo("th-TH"), false)).ToList() ?? null;
return result;
}
public Province GetProvinceByCode(string ProvinceCode)
{
MyContext _context = new MyContext();
var req = new Repository<Province>(_context);
return req.GetQuery().Where(t => t.provinceCode == ProvinceCode).SingleOrDefault();
}
public Province GetProvinceByName(string ProvinceName)
{
MyContext _context = new MyContext();
var req = new Repository<Province>(_context);
return req.GetQuery().Where(t => t.provinceName == ProvinceName).SingleOrDefault();
}
public List<Province> provinceID(int provinceID = 0)
{
MyContext _context = new MyContext();
var req = new Repository<Province>(_context);
List<Province> result = new List<Province>();
if (provinceID != 0)
{
result = req.GetQuery().Where(t => t.provinceCode == provinceID.ToString()).ToList();
}
else
{
result = req.GetQuery().ToList();
}
return result;
}
public Aumphur GetAumphurByName(string name)
{
var req = new Repository<Aumphur>(_context);
Aumphur result = new Aumphur();
result = req.GetQuery().Where(t => t.aumphurName.ToLower() == name.ToLower()).FirstOrDefault();
return result;
}
public List<Aumphur> getAumphur(string proviceID, bool isActive)
{
List<Aumphur> result = ApplicationCache.GetMaster<Aumphur>();
result = result.Where(t => t.provinceCode == proviceID && t.isActive == isActive)
.OrderByDescending(o => o.sort).ThenBy(o => o.aumphurName, StringComparer.Create(new CultureInfo("th-TH"), false))
.ToList() ?? result;
return result;
}
public List<Aumphur> getAumphur(string proviceID = null)
{
List<Aumphur> result = ApplicationCache.GetMaster<Aumphur>();
if (proviceID != null)
{
result = result.Where(t => t.provinceCode == proviceID).OrderByDescending(s => s.sort).ThenBy(s => s.aumphurName, StringComparer.Create(new System.Globalization.CultureInfo("th-TH"), false)).ToList() ?? null;
}
else if (proviceID == "")
{
result = result.ToList() ?? null;
}
return result;
}
public List<District> getDistrict(string aumphurID, bool isActive)
{
List<District> result = new List<District>();
try
{
result = ApplicationCache.GetMaster<District>();
result = result.Where(t => t.ampurID == aumphurID && t.isActive == isActive)
.OrderByDescending(o => o.sort).ThenBy(o => o.districtName, StringComparer.Create(new CultureInfo("th-TH"), false))
.ToList() ?? null;
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public List<District> getDistrict(string aumphurID = null)
{
List<District> result = null;
try
{
result = ApplicationCache.GetMaster<District>();
if (aumphurID != null)
{
result = result.Where(t => t.ampurID == aumphurID).OrderByDescending(s => s.sort).ThenBy(s => s.districtName, StringComparer.Create(new System.Globalization.CultureInfo("th-TH"), false)).ToList() ?? null;
}
else if (aumphurID == "")
{
result = result.ToList() ?? null;
}
else
{
return result;
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public District GetDistrictByName(string name)
{
var req = new Repository<District>(_context);
District result = new District();
result = req.GetQuery().Where(t => t.districtName == name).FirstOrDefault();
return result;
}
}
}
|
/**********************************************************************
* Утилита по сборке архивов игры Crash Bandicoot N. Same Trilogy *
* Особая благодарность за помощь в разборе структуры архивов: *
* Neo_Kesha и SileNTViP *
**********************************************************************/
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
namespace CBNSTT
{
public partial class Packer_Tool_Form : Form
{
public Packer_Tool_Form()
{
InitializeComponent();
}
public struct table
{
public int offset;
public short order1;
public short order2;
public int size;
public int c_size; //Добавил для, возможно, более удобной сборки сжатых архивов.
public short block_offset; //Смещение в таблице 1 или 2
public short compression_flag; //Сжат или не сжат архив (Если значение равно 0x2000, то это LZMA сжатие)
public string file_name; //Имя файла
public int index; //Индексы (на всякий случай сохраню)
public byte[] big_chunks_data; //Для хранения информации о количестве блоков
};
public class HeaderStruct : IDisposable
{
public byte[] header; //IGA\x1A заголовок
public int count; //Количество элементов в заголовке (должно быть 11)
public int table_size; //Длина таблицы с файлами и таблицами о сжатых блоках
public int file_count; //Количество файлов
public int chunks_sz; //Размер одного выравненного сжатого куска (если их несколько, то они делятся на эту длину и считаются кусками)
public int unknown1; //Неизвестное значение (за что оно отвечает, я так и не понял)
public int unknown2; //Тоже неизвестно, за что отвечает.
public int zero1; //Тут постоянно 0. Возможно, всё-таки unknown2 должен быть типа long
public int big_chunks_count; //Количество элементов больших сжатых файлов
public int small_chunks_count; //Количество элементов маленьких сжатых файлов
public int name_offset; //Смещение к таблице имени файлов
public int zero2; //Странное значение. Возможно, оно тоже относится к name_offset и оно должно быть типа long
public int name_table_sz; //Длина таблицы имени файлов
public int one; //Это значение постоянно равно единице
public int[] IDs; //Какие-то отсортированные идентификаторы для файлов
public table[] file_table; //Структура таблицы файлов
public byte[] big_chunks_table; //Массив из типа Int16 с данными о таблице сжатых блоков больших файлов
public byte[] small_chunks_table; //Массив байтов для таблицы сжатых блоков маленьких файлов
//Предполагаю, после таблицы small_shunks_table идёт выравнивание таблицы до размера, кратного 4...
public byte[] unknown_data; //Не понимаю, за что отвечает последний кусок, но он постоянно равен 0x18
public HeaderStruct() { }
public void Dispose()
{
header = null;
IDs = null;
file_table = null;
big_chunks_table = null;
small_chunks_table = null;
unknown_data = null;
}
}
private void button1_Click(object sender, EventArgs e) //Обзор для папок к PAK файлам или выбор одного PAK файла
{
if (onlyOneRB.Checked)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PAK файлы (*.pak) | *.pak";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
else
{
FileFolderDialog ffd = new FileFolderDialog();
ffd.Dialog.Title = "Выберите папку с pak архивами";
if(ffd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ffd.SelectedPath;
}
}
}
int pad_size(int size, int chunks)
{
if(size % chunks != 0)
{
while(size % chunks != 0)
{
if (size % chunks == 0) break;
size++;
}
}
return size;
}
//Пересортировка таблицы с файлами (для более удобного пересчитывания смещения файлов)
public static void ResortTable(ref table[] table_resort)
{
for (int k = 0; k < table_resort.Length; k++)
{
for (int m = k - 1; m >= 0; m--)
{
if (table_resort[m].offset > table_resort[m + 1].offset)
{
int tmp_offset = table_resort[m].offset;
int tmp_size = table_resort[m].size;
int tmp_c_size = table_resort[m].c_size;
short tmp_order1 = table_resort[m].order1;
short tmp_order2 = table_resort[m].order2;
short tmp_blk_off = table_resort[m].block_offset;
short tmp_com_fl = table_resort[m].compression_flag;
string tmp_file_name = table_resort[m].file_name;
int tmp_index = table_resort[m].index;
byte[] tmp_bcd = table_resort[m].big_chunks_data;
table_resort[m].offset = table_resort[m + 1].offset;
table_resort[m].size = table_resort[m + 1].size;
table_resort[m].c_size = table_resort[m + 1].c_size;
table_resort[m].order1 = table_resort[m + 1].order1;
table_resort[m].order2 = table_resort[m + 1].order2;
table_resort[m].block_offset = table_resort[m + 1].block_offset;
table_resort[m].compression_flag = table_resort[m + 1].compression_flag;
table_resort[m].file_name = table_resort[m + 1].file_name;
table_resort[m].index = table_resort[m + 1].index;
table_resort[m].big_chunks_data = table_resort[m + 1].big_chunks_data;
table_resort[m + 1].offset = tmp_offset;
table_resort[m + 1].order1 = tmp_order1;
table_resort[m + 1].order2 = tmp_order2;
table_resort[m + 1].block_offset = tmp_blk_off;
table_resort[m + 1].compression_flag = tmp_com_fl;
table_resort[m + 1].size = tmp_size;
table_resort[m + 1].c_size = tmp_c_size;
table_resort[m + 1].file_name = tmp_file_name;
table_resort[m + 1].index = tmp_index;
table_resort[m + 1].big_chunks_data = tmp_bcd;
}
}
}
}
//Попытка вытащить архив (тестировал на Nintendo Switch)
public string UnpackArchive(string input_path, string dir_path)
{
int num = -1;
if (!Directory.Exists(dir_path)) return "Папка не найдена. Укажите другую папку для распаковки";
if (!File.Exists(input_path)) return "Файл не найден. Укажите правильный путь к файлу для распаковки";
FileStream fr = new FileStream(input_path, FileMode.Open);
BinaryReader br = new BinaryReader(fr);
try
{
HeaderStruct head = new HeaderStruct();
long header_offset = 0;
int new_head_offset = 0;
head.header = br.ReadBytes(4);
header_offset += 4;
new_head_offset += 4;
head.count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.table_size = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.file_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.chunks_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown2 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.zero1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.big_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.small_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.name_offset = br.ReadInt32();
head.zero2 = br.ReadInt32();
header_offset += 8;
new_head_offset += 8;
head.name_table_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.one = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.IDs = new int[head.file_count];
int file_size = 0;
for (int i = 0; i < head.file_count; i++)
{
head.IDs[i] = br.ReadInt32();
file_size += 4;
}
header_offset += (4 * head.file_count);
new_head_offset += (4 * head.file_count);
head.file_table = new table[head.file_count];
for (int i = 0; i < head.file_count; i++)
{
head.file_table[i].offset = br.ReadInt32();
head.file_table[i].order1 = br.ReadInt16();
head.file_table[i].order2 = br.ReadInt16();
head.file_table[i].size = br.ReadInt32();
head.file_table[i].c_size = -1; //Пригодится, если окажется, что флаг не равен -1
head.file_table[i].block_offset = br.ReadInt16();
head.file_table[i].compression_flag = br.ReadInt16();
head.file_table[i].index = i;
}
header_offset += (16 * head.file_count);
new_head_offset += (16 * head.file_count);
file_size += (16 * head.file_count);
head.big_chunks_table = new byte[1];
if (head.big_chunks_count > 0)
{
head.big_chunks_table = br.ReadBytes(head.big_chunks_count * 2);
header_offset += head.big_chunks_count * 2;
}
head.small_chunks_table = new byte[1];
if (head.small_chunks_count > 0)
{
head.small_chunks_table = br.ReadBytes(head.small_chunks_count);
header_offset += head.small_chunks_count;
}
head.small_chunks_count = 0;
head.big_chunks_count = 0;
head.table_size = file_size;
int padded_off = pad_size((int)header_offset, 4);
br.BaseStream.Seek(padded_off, SeekOrigin.Begin);
int new_size = (int)header_offset - head.small_chunks_count - (head.big_chunks_count * 2);
//Какой-то изврат. Надо будет подумать над этим...
int padded_sz = pad_size(new_size, 4) - new_size;
byte[] tmp;
if (padded_sz > 0)
{
tmp = new byte[padded_sz];
header_offset += padded_sz;
}
head.unknown_data = br.ReadBytes(24);
new_size += 24;
new_head_offset += 24;
padded_sz = pad_size(new_head_offset, 0x800) - new_head_offset;
header_offset = pad_size(new_head_offset, 0x800);
br.BaseStream.Seek(head.name_offset, SeekOrigin.Begin);
byte[] name_block = br.ReadBytes(head.name_table_sz);
int off = 0;
int offf = 0;
int counter = 0;
int index = 0;
for (int j = 0; j < head.file_count; j++)
{
tmp = new byte[4];
counter = 0;
Array.Copy(name_block, off, tmp, 0, 4);
off += 4;
offf = BitConverter.ToInt32(tmp, 0);
tmp = new byte[1];
char ch = '1';
tmp = new byte[name_block.Length - offf];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
index = 0;
while (index < tmp.Length)
{
ch = (char)tmp[index];
if (ch == '\0')
{
break;
}
index++;
counter++;
}
tmp = new byte[counter];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
head.file_table[j].file_name = Encoding.ASCII.GetString(tmp);
if (head.file_table[j].file_name.Contains("/")) head.file_table[j].file_name = head.file_table[j].file_name.Replace('/', '\\');
}
table[] new_table = new table[head.file_count];
for (int i = 0; i < head.file_table.Length; i++)
{
new_table[i].offset = head.file_table[i].offset;
new_table[i].size = head.file_table[i].size;
new_table[i].c_size = head.file_table[i].c_size;
new_table[i].order1 = head.file_table[i].order1;
new_table[i].order2 = head.file_table[i].order2;
new_table[i].block_offset = head.file_table[i].block_offset;
new_table[i].compression_flag = head.file_table[i].compression_flag;
new_table[i].file_name = head.file_table[i].file_name;
new_table[i].index = head.file_table[i].index;
if (head.file_table[i].size >= 0x40000 && head.big_chunks_count > 0)
{
int tmp_off = head.file_table[i].block_offset * 2;
int tmp_sz = (pad_size(head.file_table[i].size, 0x8000) / 0x8000) + 2;
head.file_table[i].big_chunks_data = new byte[tmp_sz];
Array.Copy(head.big_chunks_table, tmp_off, head.file_table[i].big_chunks_data, 0, head.file_table[i].big_chunks_data.Length);
}
else head.file_table[i].big_chunks_data = null;
new_table[i].big_chunks_data = head.file_table[i].big_chunks_data;
}
byte[] content;
int ch_size;
byte[] properties;
byte[] c_content;
for (int j = 0; j < new_table.Length; j++)
{
string pak_name = get_file_name(input_path);
pak_name = pak_name.Remove(pak_name.IndexOf('.'), pak_name.Length - pak_name.IndexOf('.'));
string dir = get_dir_path(new_table[j].file_name);
if (!Directory.Exists(dir_path + "\\" + pak_name + "\\" + dir)) Directory.CreateDirectory(dir_path + "\\" + pak_name + "\\" + dir);
if (File.Exists(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name)) File.Delete(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name);
if (new_table[j].compression_flag != -1)
{
int size = 0;
int offset = new_table[j].offset;
int def_block = 0x8000;
FileStream fw = new FileStream(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name, FileMode.CreateNew);
while (size != new_table[j].size)
{
try
{
br.BaseStream.Seek(offset, SeekOrigin.Begin);
if (head.count == 11) ch_size = br.ReadInt16();
else ch_size = br.ReadInt32();
if (def_block > new_table[j].size - size) def_block = new_table[j].size - size;
properties = br.ReadBytes(5);
c_content = br.ReadBytes(ch_size);
SevenZip.Compression.LZMA.Decoder decode = new SevenZip.Compression.LZMA.Decoder();
decode.SetDecoderProperties(properties);
MemoryStream ms = new MemoryStream(c_content);
MemoryStream ms2 = new MemoryStream();
decode.Code(ms, ms2, ch_size, def_block, null);
content = ms2.ToArray();
ms.Close();
ms2.Close();
fw.Write(content, 0, content.Length);
if (head.count == 11) offset += pad_size(ch_size + 7, 0x800);
else offset += pad_size(ch_size + 9, 0x800);
size += def_block;
content = null;
c_content = null;
}
catch
{
if(size >= new_table[j].size)
{
if (fw != null) fw.Close();
if (br != null) br.Close();
if (fr != null) fr.Close();
if (File.Exists(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name)) File.Delete(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name);
return "Wrong archive format: " + get_file_name(pak_name);
}
else
{
br.BaseStream.Seek(offset, SeekOrigin.Begin);
def_block = 0x8000;
if (def_block > new_table[j].size - size) def_block = new_table[j].size - size;
content = br.ReadBytes(def_block);
fw.Write(content, 0, content.Length);
offset += pad_size(def_block, 0x800);
size += def_block;
content = null;
}
}
}
fw.Close();
}
else
{
br.BaseStream.Seek(new_table[j].offset, SeekOrigin.Begin);
content = br.ReadBytes(new_table[j].size);
FileStream fw = new FileStream(dir_path + "\\" + pak_name + "\\" + new_table[j].file_name, FileMode.CreateNew);
fw.Write(content, 0, content.Length);
fw.Close();
content = null;
}
}
new_table = null;
head.Dispose();
br.Close();
fr.Close();
return "File " + input_path + " successfully extracted!";
}
catch
{
if (br != null) br.Close();
if (fr != null) fr.Close();
return "Something wrong. The last file was number " + num + 1;
}
}
//Экспериментальная версия с полной пересборкой архивов
public string RepackNew(string input_path, string output_path, string dir_path)
{
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
DirectoryInfo di = new DirectoryInfo(dir_path);
FileInfo[] fi = di.GetFiles("*.*", SearchOption.AllDirectories);
FileStream fr = new FileStream(input_path, FileMode.Open);
FileStream fs = new FileStream(output_path + ".tmp", FileMode.CreateNew);
BinaryReader br = new BinaryReader(fr);
BinaryWriter bw = new BinaryWriter(fs);
byte[] c_header = { 0x5D, 0x00, 0x80, 0x00, 0x00 }; //Заголовок сжатого блока
HeaderStruct head = new HeaderStruct();
long header_offset = 0;
int new_head_offset = 0;
head.header = br.ReadBytes(4);
header_offset += 4;
new_head_offset += 4;
head.count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.table_size = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.file_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
if (fi.Length != head.file_count)
{
br.Close();
bw.Close();
fs.Close();
fr.Close();
File.Delete(output_path + ".tmp");
return "Количество файлов в папке не соответствует количеству файлов в архиве! Найдено " + fi.Length + ", а должно быть " + head.file_count;
}
head.chunks_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown2 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.zero1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.big_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.small_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.name_offset = br.ReadInt32();
head.zero2 = br.ReadInt32();
header_offset += 8;
new_head_offset += 8;
head.name_table_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.one = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.IDs = new int[head.file_count];
int file_size = 0;
for (int i = 0; i < head.file_count; i++)
{
head.IDs[i] = br.ReadInt32();
file_size += 4;
}
header_offset += (4 * head.file_count);
new_head_offset += (4 * head.file_count);
head.file_table = new table[head.file_count];
for (int i = 0; i < head.file_count; i++)
{
head.file_table[i].offset = br.ReadInt32();
head.file_table[i].order1 = br.ReadInt16();
head.file_table[i].order2 = br.ReadInt16();
head.file_table[i].size = br.ReadInt32();
head.file_table[i].c_size = -1; //Пригодится, если окажется, что флаг не равен -1
head.file_table[i].block_offset = br.ReadInt16();
head.file_table[i].compression_flag = br.ReadInt16();
//head.file_table[i].block_offset = -1;
//head.file_table[i].compression_flag = -1;
head.file_table[i].index = i;
}
header_offset += (16 * head.file_count);
new_head_offset += (16 * head.file_count);
file_size += (16 * head.file_count);
head.big_chunks_table = new byte[1];
if (head.big_chunks_count > 0)
{
head.big_chunks_table = br.ReadBytes(head.big_chunks_count * 2);
header_offset += head.big_chunks_count * 2;
}
head.small_chunks_table = new byte[1];
if (head.small_chunks_count > 0)
{
head.small_chunks_table = br.ReadBytes(head.small_chunks_count);
header_offset += head.small_chunks_count;
}
head.small_chunks_count = 0;
head.big_chunks_count = 0;
head.table_size = file_size;
int padded_off = pad_size((int)header_offset, 4);
br.BaseStream.Seek(padded_off, SeekOrigin.Begin);
int new_size = (int)header_offset - head.small_chunks_count - (head.big_chunks_count * 2);
//Какой-то изврат. Надо будет подумать над этим...
int padded_sz = pad_size(new_size, 4) - new_size;
byte[] tmp;
if (padded_sz > 0)
{
tmp = new byte[padded_sz];
header_offset += padded_sz;
}
head.unknown_data = br.ReadBytes(24);
new_size += 24;
new_head_offset += 24;
padded_sz = pad_size(new_head_offset, 0x800) - new_head_offset;
header_offset = pad_size(new_head_offset, 0x800);
br.BaseStream.Seek(head.name_offset, SeekOrigin.Begin);
byte[] name_block = br.ReadBytes(head.name_table_sz);
int off = 0;
int offf = 0;
int counter = 0;
int index = 0;
for (int j = 0; j < head.file_count; j++)
{
tmp = new byte[4];
counter = 0;
Array.Copy(name_block, off, tmp, 0, 4);
off += 4;
offf = BitConverter.ToInt32(tmp, 0);
tmp = new byte[1];
char ch = '1';
tmp = new byte[name_block.Length - offf];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
index = 0;
while (index < tmp.Length)
{
ch = (char)tmp[index];
if (ch == '\0')
{
break;
}
index++;
counter++;
}
tmp = new byte[counter];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
head.file_table[j].file_name = Encoding.ASCII.GetString(tmp);
if (head.file_table[j].file_name.Contains("/")) head.file_table[j].file_name = head.file_table[j].file_name.Replace('/', '\\');
}
table[] new_table = new table[head.file_count];
for (int i = 0; i < head.file_table.Length; i++)
{
new_table[i].offset = head.file_table[i].offset;
new_table[i].size = head.file_table[i].size;
new_table[i].c_size = head.file_table[i].c_size;
new_table[i].order1 = head.file_table[i].order1;
new_table[i].order2 = head.file_table[i].order2;
new_table[i].block_offset = head.file_table[i].block_offset;
new_table[i].compression_flag = head.file_table[i].compression_flag;
new_table[i].file_name = head.file_table[i].file_name;
new_table[i].index = head.file_table[i].index;
if (head.file_table[i].size >= 0x40000 && head.big_chunks_count > 0)
{
int tmp_off = head.file_table[i].block_offset * 2;
int tmp_sz = (pad_size(head.file_table[i].size, 0x8000) / 0x8000) + 2;
head.file_table[i].big_chunks_data = new byte[tmp_sz];
Array.Copy(head.big_chunks_table, tmp_off, head.file_table[i].big_chunks_data, 0, head.file_table[i].big_chunks_data.Length);
}
else head.file_table[i].big_chunks_data = null;
new_table[i].big_chunks_data = head.file_table[i].big_chunks_data;
}
ResortTable(ref new_table);
int offset = 0;
int size = 0;
int count = 0;
byte[] tmp2;
List<byte[]> tmp3 = new List<byte[]>();
List<byte[]> tmp4 = new List<byte[]>();
int c_offset = 0; //Это для таблицы
for (int i = 0; i < new_table.Length; i++)
{
index = 0;
bool res = false;
while (!res)
{
if (fi[index].FullName.Length < 255)
{
if (fi[index].FullName.ToUpper().IndexOf(new_table[i].file_name.ToUpper()) > 0)
{
new_table[i].offset = offset;
new_table[i].size = (int)fi[index].Length;
if (new_table[i].size >= 0x40000 && new_table[i].compression_flag != -1)
{
count = (pad_size(new_table[i].size, 0x8000) / 0x8000) + 1;
head.big_chunks_count += count;
int c_off = 0;
int f_off = 0; //Для смещения при считывании файла
int f_size = (int)fi[index].Length;
new_table[i].size = (int)fi[index].Length;
int bl_size = 0x8000;
short len = 0;
short tmps = 0;
if (tmp3.Count > 0) tmp3.Clear();
new_table[i].c_size = 0;
FileStream fcr = new FileStream(fi[index].FullName, FileMode.Open);
while(f_off != f_size)
{
bl_size = 0x8000;
if (bl_size > f_size - f_off) bl_size = f_size - f_off;
tmp = new byte[bl_size];
fcr.Read(tmp, 0, tmp.Length);
f_off += tmp.Length;
SevenZip.Compression.LZMA.Encoder encode = new SevenZip.Compression.LZMA.Encoder();
MemoryStream ms = new MemoryStream(tmp);
MemoryStream ms2 = new MemoryStream();
encode.Code(ms, ms2, -1, -1, null);
ms2.Close();
ms.Close();
tmp = ms2.ToArray();
len = (short)tmp.Length;
tmp2 = new byte[pad_size(tmp.Length + 7, 0x800)];
Array.Copy(c_header, 0, tmp2, 2, c_header.Length);
Array.Copy(tmp, 0, tmp2, 7, tmp.Length);
tmp = new byte[2];
tmp = BitConverter.GetBytes(len);
Array.Copy(tmp, 0, tmp2, 0, tmp.Length);
new_table[i].c_size += tmp2.Length;
tmp = new byte[2];
tmps = (short)((c_off / 0x800) | 0x8000); //Делим смещение и логически прибавляем 0x8000 (Надо так делать!)
tmp = BitConverter.GetBytes(tmps);
tmp3.Add(tmp);
c_off += tmp2.Length;
bw.Write(tmp2, 0, tmp2.Length);
}
tmps = (short)(new_table[i].c_size / 0x800);
tmp = new byte[2];
tmp = BitConverter.GetBytes(tmps);
tmp3.Add(tmp);
tmp = new byte[count * 2];
new_table[i].big_chunks_data = null;
new_table[i].block_offset = (short)c_offset;
c_offset += (tmp.Length / 2);
for (int c = 0; c < tmp3.Count; c++)
{
Array.Copy(tmp3[c], 0, tmp, c * 2, tmp3[c].Length);
}
fcr.Close();
tmp4.Add(tmp);
offset += new_table[i].c_size;
}
else
{
offset += pad_size((int)fi[index].Length, 0x800);
new_table[i].block_offset = -1;
new_table[i].compression_flag = -1;
FileStream frf = new FileStream(fi[index].FullName, FileMode.Open);
tmp = new byte[frf.Length];
frf.Read(tmp, 0, tmp.Length);
frf.Close();
tmp2 = new byte[pad_size(tmp.Length, 0x800)];
Array.Copy(tmp, 0, tmp2, 0, tmp.Length);
bw.Write(tmp2, 0, tmp2.Length);
}
res = true;
break;
}
index++;
if (index >= fi.Length)
{
br.Close();
bw.Close();
fs.Close();
fr.Close();
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
GC.Collect();
return "Файл архива " + output_path + " не найден в папке!";
}
}
else
{
//Какой же убогий костыль благодаря сраному ограничению Windows 7!
br.Close();
bw.Close();
fs.Close();
fr.Close();
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
GC.Collect();
return "Длина пути к файлу больше 255 символов. Сократите, пожалуйста, путь к ресурсам для правильной работы утилиты.";
}
}
}
head.name_offset = offset;
bw.Close();
br.Close();
fs.Close();
fr.Close();
offset = pad_size(pad_size(56 + (4 * head.file_count) + (16 * head.file_count) + (head.big_chunks_count * 2) + head.small_chunks_count, 4) + 24, 0x800);
for(int i = 0; i < new_table.Length; i++)
{
new_table[i].offset += offset;
}
head.name_offset += offset;
if (File.Exists(output_path)) File.Delete(output_path);
fr = new FileStream(output_path + ".tmp", FileMode.Open);
fs = new FileStream(output_path, FileMode.CreateNew);
bw = new BinaryWriter(fs);
bw.Write(head.header);
bw.Write(head.count);
head.table_size = (4 * head.file_count) + (16 * head.file_count) + (head.big_chunks_count * 2) + head.small_chunks_count;
bw.Write(head.table_size);
bw.Write(head.file_count);
bw.Write(head.chunks_sz);
bw.Write(head.unknown1);
bw.Write(head.unknown2);
bw.Write(head.zero1);
bw.Write(head.big_chunks_count);
bw.Write(head.small_chunks_count);
bw.Write(head.name_offset);
bw.Write(head.zero2);
bw.Write(head.name_table_sz);
bw.Write(head.one);
for(int i = 0; i < head.file_count; i++)
{
bw.Write(head.IDs[i]);
}
for (int i = 0; i < head.file_count; i++)
for(int j = 0; j < new_table.Length; j++)
{
if(head.file_table[i].index == new_table[j].index)
{
bw.Write(new_table[j].offset);
bw.Write(new_table[j].order1);
bw.Write(new_table[j].order2);
bw.Write(new_table[j].size);
bw.Write(new_table[j].block_offset);
bw.Write(new_table[j].compression_flag);
}
}
for(int i = 0; i < tmp4.Count; i++)
{
bw.Write(tmp4[i]);
}
if(head.small_chunks_table.Length > 0 && head.small_chunks_count > 0)
{
bw.Write(head.small_chunks_table);
}
int tmp_sz2 = 56 + (4 * head.file_count) + (16 * head.file_count) + (head.big_chunks_count * 2) + head.small_chunks_count;
tmp = new byte[pad_size(tmp_sz2, 4) - tmp_sz2];
bw.Write(tmp);
tmp = new byte[offset - (pad_size(tmp_sz2, 4) + 24)];
bw.Write(head.unknown_data);
bw.Write(tmp);
offset = 0;
while (offset != fr.Length)
{
tmp = new byte[0x10000]; //Сделаю буфер считывания 64КБ
if (tmp.Length > fr.Length - offset) tmp = new byte[fr.Length - offset];
fr.Read(tmp, 0, tmp.Length);
bw.Write(tmp);
offset += tmp.Length;
}
bw.Write(name_block);
fr.Close();
bw.Close();
fs.Close();
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
new_table = null;
head.Dispose();
return "Файл " + output_path + " пересобран успешно!";
}
public string RepackArchive(string input_path, string output_path, string dir_path, bool compress)
{
#region
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
DirectoryInfo di = new DirectoryInfo(dir_path);
FileInfo[] fi = di.GetFiles("*.*", SearchOption.AllDirectories);
FileStream fr = new FileStream(input_path, FileMode.Open);
FileStream fs = new FileStream(output_path + ".tmp", FileMode.CreateNew);
BinaryReader br = new BinaryReader(fr);
BinaryWriter bw = new BinaryWriter(fs);
HeaderStruct head = new HeaderStruct();
long header_offset = 0;
int new_head_offset = 0;
head.header = br.ReadBytes(4);
header_offset += 4;
new_head_offset += 4;
head.count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.table_size = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.file_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
if (fi.Length != head.file_count)
{
br.Close();
bw.Close();
fs.Close();
fr.Close();
File.Delete(output_path + ".tmp");
return "Количество файлов в папке не соответствует количеству файлов в архиве! Найдено " + fi.Length + ", а должно быть " + head.file_count;
}
head.chunks_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.unknown2 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.zero1 = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.big_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.small_chunks_count = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.name_offset = br.ReadInt32();
head.zero2 = br.ReadInt32();
header_offset += 8;
new_head_offset += 8;
head.name_table_sz = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.one = br.ReadInt32();
header_offset += 4;
new_head_offset += 4;
head.IDs = new int[head.file_count];
int file_size = 0;
for(int i = 0; i < head.file_count; i++)
{
head.IDs[i] = br.ReadInt32();
file_size += 4;
}
header_offset += (4 * head.file_count);
new_head_offset += (4 * head.file_count);
head.file_table = new table[head.file_count];
for (int i = 0; i < head.file_count; i++)
{
head.file_table[i].offset = br.ReadInt32();
head.file_table[i].order1 = br.ReadInt16();
head.file_table[i].order2 = br.ReadInt16();
head.file_table[i].size = br.ReadInt32();
head.file_table[i].c_size = -1; //Пригодится, если окажется, что флаг не равен -1
head.file_table[i].block_offset = br.ReadInt16();
head.file_table[i].compression_flag = br.ReadInt16();
head.file_table[i].block_offset = -1;
head.file_table[i].compression_flag = -1;
head.file_table[i].index = i;
}
header_offset += (16 * head.file_count);
new_head_offset += (16 * head.file_count);
file_size += (16 * head.file_count);
head.big_chunks_table = new byte[1];
if (head.big_chunks_count > 0)
{
head.big_chunks_table = br.ReadBytes(head.big_chunks_count * 2);
header_offset += head.big_chunks_count * 2;
}
head.small_chunks_table = new byte[1];
if(head.small_chunks_count > 0)
{
head.small_chunks_table = br.ReadBytes(head.small_chunks_count);
header_offset += head.small_chunks_count;
}
head.small_chunks_count = 0;
head.big_chunks_count = 0;
head.table_size = file_size;
int padded_off = pad_size((int)header_offset, 4);
br.BaseStream.Seek(padded_off, SeekOrigin.Begin);
int new_size = (int)header_offset - head.small_chunks_count - (head.big_chunks_count * 2);
//Какой-то изврат. Надо будет подумать над этим...
int padded_sz = pad_size(new_size, 4) - new_size;
byte[] tmp;
if (padded_sz > 0)
{
tmp = new byte[padded_sz];
header_offset += padded_sz;
}
head.unknown_data = br.ReadBytes(24);
new_size += 24;
new_head_offset += 24;
padded_sz = pad_size(new_head_offset, 0x800) - new_head_offset;
header_offset = pad_size(new_head_offset, 0x800);
br.BaseStream.Seek(head.name_offset, SeekOrigin.Begin);
byte[] name_block = br.ReadBytes(head.name_table_sz);
int off = 0;
int offf = 0;
int counter = 0;
int index = 0;
for (int j = 0; j < head.file_count; j++)
{
tmp = new byte[4];
counter = 0;
Array.Copy(name_block, off, tmp, 0, 4);
off += 4;
offf = BitConverter.ToInt32(tmp, 0);
tmp = new byte[1];
char ch = '1';
tmp = new byte[name_block.Length - offf];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
index = 0;
while (index<tmp.Length)
{
ch = (char) tmp[index];
if (ch == '\0')
{
break;
}
index++;
counter++;
}
tmp = new byte[counter];
Array.Copy(name_block, offf, tmp, 0, tmp.Length);
head.file_table[j].file_name = Encoding.ASCII.GetString(tmp);
if (head.file_table[j].file_name.Contains("/")) head.file_table[j].file_name = head.file_table[j].file_name.Replace('/', '\\');
}
table[] new_table = new table[head.file_count];
for(int i = 0; i < head.file_table.Length; i++)
{
new_table[i].offset = head.file_table[i].offset;
new_table[i].size = head.file_table[i].size;
new_table[i].c_size = head.file_table[i].c_size;
new_table[i].order1 = head.file_table[i].order1;
new_table[i].order2 = head.file_table[i].order2;
new_table[i].block_offset = head.file_table[i].block_offset;
new_table[i].compression_flag = head.file_table[i].compression_flag;
new_table[i].file_name = head.file_table[i].file_name;
new_table[i].index = head.file_table[i].index;
}
ResortTable(ref new_table);
int files_off = (int)header_offset;
for (int i = 0; i < new_table.Length; i++)
{
index = 0;
bool res = false;
while (!res)
{
if (fi[index].FullName.Length < 255)
{
if (fi[index].FullName.ToUpper().IndexOf(new_table[i].file_name.ToUpper()) > 0)
{
new_table[i].offset = files_off;
new_table[i].size = (int)fi[index].Length;
files_off += pad_size((int)fi[index].Length, 0x800);
res = true;
break;
}
index++;
if (index >= fi.Length)
{
br.Close();
bw.Close();
fs.Close();
fr.Close();
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
GC.Collect();
return "Файл архива " + output_path + " не найден в папке!";
}
}
else
{
//Какой же убогий костыль благодаря сраному ограничению Windows 7!
br.Close();
bw.Close();
fs.Close();
fr.Close();
if (File.Exists(output_path + ".tmp")) File.Delete(output_path + ".tmp");
GC.Collect();
return "Длина пути к файлу больше 255 символов. Сократите, пожалуйста, путь к ресурсам для правильной работы утилиты.";
}
}
}
head.name_offset = files_off;
for (int f = 0; f < head.file_table.Length; f++)
{
for (int j = 0; j < new_table.Length; j++)
{
if ((new_table[j].index == head.file_table[f].index))
{
head.file_table[f].offset = new_table[j].offset;
head.file_table[f].size = new_table[j].size;
break;
}
}
}
//Запись данных в файл
bw.Write(head.header);
bw.Write(head.count);
bw.Write(head.table_size);
bw.Write(head.file_count);
bw.Write(head.chunks_sz);
bw.Write(head.unknown1);
bw.Write(head.unknown2);
bw.Write(head.zero1);
bw.Write(head.big_chunks_count);
bw.Write(head.small_chunks_count);
bw.Write(head.name_offset);
bw.Write(head.zero2);
bw.Write(head.name_table_sz);
bw.Write(head.one);
for(int i = 0; i < head.IDs.Length; i++)
{
bw.Write(head.IDs[i]);
}
for (int i = 0; i < head.file_table.Length; i++)
{
bw.Write(head.file_table[i].offset);
bw.Write(head.file_table[i].order1);
bw.Write(head.file_table[i].order2);
bw.Write(head.file_table[i].size);
bw.Write(head.file_table[i].block_offset);
bw.Write(head.file_table[i].compression_flag);
}
bw.Write(head.unknown_data);
if (padded_sz > 0)
{
tmp = new byte[padded_sz];
bw.Write(tmp);
}
byte[] tmp_f;
int idx = 0;
bool res2;
for (int i = 0; i < new_table.Length; i++)
{
idx = 0;
res2 = false;
while (!res2)
{
if (fi[idx].FullName.ToUpper().IndexOf(new_table[i].file_name.ToUpper()) > 0)
{
tmp = File.ReadAllBytes(fi[idx].FullName);
tmp_f = new byte[pad_size(tmp.Length, 0x800)];
Array.Copy(tmp, 0, tmp_f, 0, tmp.Length);
bw.Write(tmp_f);
tmp = null;
tmp_f = null;
res2 = true;
}
idx++;
}
}
bw.Write(name_block);
name_block = null;
string info = "\r\n";
new_table = null;
br.Close();
bw.Close();
fs.Close();
fr.Close();
if (File.Exists(output_path)) File.Delete(output_path);
File.Move(output_path + ".tmp", output_path);
head.Dispose();
GC.Collect();
return "Файл " + output_path + " пересобран успешно!" + info;
#endregion
}
public static string get_file_name(string path)
{
int len = path.Length - 1;
while(path[len] != '\\')
{
len--;
if (len < 0) return null;
}
path = path.Remove(0, len + 1);
return path;
}
public static string get_dir_path(string path)
{
int len = path.Length - 1;
while (path[len] != '\\')
{
len--;
if (len < 0) return null;
}
path = path.Remove(len, path.Length - len);
return path;
}
private void button2_Click(object sender, EventArgs e) //Выбор папки с с ресурсами
{
FileFolderDialog fbd = new FileFolderDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
textBox2.Text = fbd.SelectedPath;
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
bool save_modal = checkBox1.Checked;
string output_path = textBox1.Text;
string pak_path = textBox1.Text;
string dir_path = textBox2.Text; //Папка с ресурсами
if (onlyOneRB.Checked)
{
if (File.Exists(pak_path) && Directory.Exists(dir_path))
{
if (save_modal)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PAK File | *.pak";
if (sfd.ShowDialog() == DialogResult.OK)
{
output_path = sfd.FileName;
}
}
//string result = RepackArchive(pak_path, output_path, textBox2.Text, compress, get_list);
string result = RepackArchive(pak_path, output_path, dir_path, false);
MessageBox.Show(result);
}
}
else
{
if(Directory.Exists(pak_path) && Directory.Exists(dir_path))
{
if(save_modal)
{
FileFolderDialog ffd = new FileFolderDialog();
ffd.Dialog.Title = "Укажите папку для пересобранных архивов";
if(ffd.ShowDialog() == DialogResult.OK)
{
output_path = ffd.SelectedPath;
}
}
DirectoryInfo di = new DirectoryInfo(pak_path);
FileInfo[] fi = di.GetFiles("*.pak");
string[] dirs = Directory.GetDirectories(dir_path);
if (fi.Length > 0 && dirs.Length > 0)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = fi.Length - 1;
string result = "";
for (int i = 0; i < fi.Length; i++)
{
for (int j = 0; j < dirs.Length; j++)
{
string check = get_file_name(dirs[j]);
if (fi[i].Name.Contains(check) && check.Length == fi[i].Name.Length - 4)
{
var Thread = new System.Threading.Thread(
() =>
{
result = RepackArchive(fi[i].FullName, output_path + "\\" + fi[i].Name, dirs[j], false);
}
);
Thread.Start();
Thread.Join();
listBox1.Items.Add(result);
}
}
progressBar1.Value = i;
}
}
else listBox1.Items.Add("Проверьте на наличие файлов pak или папок для пересборки архивов");
}
}
}
private void Packer_Tool_Form_Load(object sender, EventArgs e)
{
onlyOneRB.Checked = true;
}
private void button3_Click(object sender, EventArgs e)
{
bool save_modal = checkBox1.Checked;
string output_path = textBox1.Text;
string pak_path = textBox1.Text;
string dir_path = textBox2.Text; //Папка с ресурсами
if (onlyOneRB.Checked)
{
if (File.Exists(pak_path) && Directory.Exists(dir_path))
{
if (save_modal)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PAK File | *.pak";
if (sfd.ShowDialog() == DialogResult.OK)
{
output_path = sfd.FileName;
}
}
//string result = RepackArchive(pak_path, output_path, textBox2.Text, compress, get_list);
string result = RepackNew(pak_path, output_path, dir_path);
MessageBox.Show(result);
}
}
else
{
if (Directory.Exists(pak_path) && Directory.Exists(dir_path))
{
if (save_modal)
{
FileFolderDialog ffd = new FileFolderDialog();
ffd.Dialog.Title = "Укажите папку для пересобранных архивов";
if (ffd.ShowDialog() == DialogResult.OK)
{
output_path = ffd.SelectedPath;
}
}
DirectoryInfo di = new DirectoryInfo(pak_path);
FileInfo[] fi = di.GetFiles("*.pak");
string[] dirs = Directory.GetDirectories(dir_path);
if (fi.Length > 0 && dirs.Length > 0)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = fi.Length - 1;
string result = "";
for (int i = 0; i < fi.Length; i++)
{
for (int j = 0; j < dirs.Length; j++)
{
string check = get_file_name(dirs[j]);
if (fi[i].Name.Contains(check) && check.Length == fi[i].Name.Length - 4)
{
var Thread = new System.Threading.Thread(
() =>
{
result = RepackNew(fi[i].FullName, output_path + "\\" + fi[i].Name, dirs[j]);
}
);
Thread.Start();
Thread.Join();
listBox1.Items.Add(result);
}
}
progressBar1.Value = i;
}
}
else listBox1.Items.Add("Проверьте на наличие файлов pak или папок для пересборки архивов");
}
}
}
private void button4_Click(object sender, EventArgs e)
{
bool save_modal = checkBox1.Checked;
string output_path = textBox1.Text;
string pak_path = textBox1.Text;
string dir_path = textBox2.Text; //Папка с ресурсами
if (onlyOneRB.Checked)
{
if (File.Exists(pak_path) && Directory.Exists(dir_path))
{
if (save_modal)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PAK File | *.pak";
if (sfd.ShowDialog() == DialogResult.OK)
{
output_path = sfd.FileName;
}
}
//string result = RepackArchive(pak_path, output_path, textBox2.Text, compress, get_list);
string result = UnpackArchive(pak_path, dir_path);
MessageBox.Show(result);
}
}
else
{
//MessageBox.Show("Пока не работает");
if (Directory.Exists(pak_path) && Directory.Exists(dir_path))
{
DirectoryInfo di = new DirectoryInfo(pak_path);
FileInfo[] fi = di.GetFiles("*.pak");
if (fi.Length > 0)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = fi.Length - 1;
string result = "";
for (int i = 0; i < fi.Length; i++)
{
var Thread = new System.Threading.Thread(
() =>
{
result = UnpackArchive(fi[i].FullName, dir_path);
}
);
Thread.Start();
Thread.Join();
listBox1.Items.Add(result);
progressBar1.Value = i;
}
}
else listBox1.Items.Add("Проверьте на наличие файлов pak или папок для пересборки архивов");
}
}
}
}
}
|
namespace gView.Interoperability.GeoServices.Rest.Json.Features
{
class JsonAttributes
{
}
}
|
using System;
namespace _13_Lesson
{
class Program
{
static void Main(string[] args)
{
int a = 2;
int b = 5;
bool argsEqual = a == b;
Console.WriteLine(argsEqual);
}
static void MathOperations()
{
//Взятие остатка от числа
int x;
x = 4 % 2;
Console.WriteLine(x);
x = 5 % 2;
Console.WriteLine(x);
// Умножение
int a;
a = 2 * 2;
Console.WriteLine(a);
a *= 2;
Console.WriteLine(a);
}
static void IncrementDecrement()
{
// Самое простое и доходчивое объяснение инкремента в постфиксном и префискном представлении
int x = 0;
int y = x++;
Console.WriteLine($"Значение Y: {y}");
Console.WriteLine($"Значение X: {x}\n");
y = ++x;
Console.WriteLine($"Значение Y: {y}");
Console.WriteLine($"Значение X: {x}\n");
x += 2;
// x = x + 2;
Console.WriteLine($"x + 2 = {x}");
x -= 3;
// x = x - 3;
Console.WriteLine($"x - 3 = {x}");
x = 2;
y = x--;
Console.WriteLine($"Значение Y: {y}");
Console.WriteLine($"Значение X: {x}\n");
y = --x;
Console.WriteLine($"Значение Y: {y}");
Console.WriteLine($"Значение X: {x}\n");
}
}
}
|
using myFinPort.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace myFinPort.ViewModels
{
public class TransactionsVM
{
public TransactionType TransactionType { get; set; }
public int BankAccountId { get; set; }
public int BudgetItemId { get; set; }
public decimal Amount { get; set; }
public string Memo { get; set; }
}
} |
using System;
namespace TestGr4d3.UI.ViewModels.EstudianteVM
{
public class EstudianteFormularioVM
{
public int Id { get; set; }
public string Nombre { get; set; }
public string Apellido { get; set; }
public int Edad { get; set; }
public string Curso { get; set; }
public string ImagenURL { get; set; }
}
}
|
using System.Windows.Controls;
namespace Crystal.Plot2D.Charts
{
/// <summary>
/// Interaction logic for SimpleNavigationBar.xaml
/// </summary>
public partial class SimpleNavigationBar : UserControl
{
public SimpleNavigationBar()
{
InitializeComponent();
}
}
}
|
using System;
using System.IO;
using System.Linq;
using BudgetHelper;
using BudgetHelper.Api;
using BudgetHelper.Common;
namespace BudgetHelperCli
{
public class BudgetHelperCli
{
private static void Main(string[] args)
{
try
{
// TODO: use fluent command line parser
// TODO: do validation
var config = new ConfigParameters(
args[0],
args[1],
args[2]);
var transactions = BudgetHelperWrapper.GetTransactions(config);
var transactionCsvLines = transactions.
Select(t =>
CsvUtil.Serialize(new object[]
{
t.Date.ToShortDateString(),
t.Month,
t.Establishment,
t.Amount,
t.Category,
t.PaymentMethod
})).
ToList();
File.WriteAllLines(args[3], transactionCsvLines);
}
catch (Exception ex)
{
Console.WriteLine("Unhandled exception.");
Console.WriteLine(ex);
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
|
using UnityEngine;
public class Player : MonoBehaviour, IDamageable {
public Animator animator;
public Rigidbody2D rb;
// Health
public int health = 5;
private float _damageColorEndTime;
private float _damageColorDuration = 0.1f;
private Health _healthUI;
// Movement
public float baseSpeed = 5f;
private Vector3 _moveDir;
private float _speed;
// Dodging
public float dodgeMultiplier = 2.5f;
public float dodgeCooldown = 1.5f;
public float dodgeDuration = 0.3f;
public AnimationCurve dodgeSpeedCurve;
private float _dodgeRefreshTime;
private float _dodgeEndTime;
private Vector3 _dodgeDir;
private bool _dodging;
// Weapons
public GameObject primaryWeaponGO;
public GameObject secondaryWeaponGO;
private bool _primaryActive = true;
private Weapon _activeWeapon;
private Weapon _inactiveWeapon;
private bool _attackEnabled = true;
// SFX
public AudioSource playerAudio;
public AudioClip playerDamagedSFX;
// Debug
private LineRenderer _lineRenderer;
private SpriteRenderer _spriteRenderer;
private bool _useRawInput = false;
public void TakeDamage(int damage) {
if (_dodging)
return;
health -= damage;
playerAudio.PlayOneShot(playerDamagedSFX, 0.5f);
_damageColorEndTime = Time.time + _damageColorDuration;
Debug.Log("Player Took Damage");
}
void Start() {
_lineRenderer = GetComponent<LineRenderer>();
_spriteRenderer = GetComponent<SpriteRenderer>();
_healthUI = GetComponent<Health>();
_activeWeapon = primaryWeaponGO.GetComponent<Weapon>();
_inactiveWeapon = secondaryWeaponGO.GetComponent<Weapon>();
secondaryWeaponGO.SetActive(false);
}
public void SwitchWeapons() {
_primaryActive = !_primaryActive;
Weapon tmp = _activeWeapon;
_activeWeapon = _inactiveWeapon;
_inactiveWeapon = tmp;
if (_primaryActive) {
primaryWeaponGO.SetActive(true);
secondaryWeaponGO.SetActive(false);
} else {
primaryWeaponGO.SetActive(false);
secondaryWeaponGO.SetActive(true);
}
}
public void replenishWeapon(string name, float valToReplenish) {
if (_activeWeapon.name == name) {
_activeWeapon.Replenish(valToReplenish);
} else if (_inactiveWeapon.name == name) {
_inactiveWeapon.Replenish(valToReplenish);
}
}
public void replenishAmmo(string name) {
if (_activeWeapon.name == name) {
_activeWeapon.Replenish(_activeWeapon.baseDegrade);
} else if (_inactiveWeapon.name == name) {
_inactiveWeapon.Replenish(_activeWeapon.baseDegrade);
}
}
public void Move(Vector2 moveInput, bool dodge = false) {
_moveDir = new Vector3(moveInput.x, moveInput.y, 0f);
_moveDir = Vector3.ClampMagnitude(_moveDir, 1f);
if (dodge && Time.time > _dodgeRefreshTime && _moveDir.sqrMagnitude > 0f) {
_dodging = true;
_dodgeDir = _moveDir.normalized;
_dodgeRefreshTime = Time.time + dodgeCooldown;
_dodgeEndTime = Time.time + dodgeDuration;
}
_speed = baseSpeed;
if (_dodging) {
_moveDir = _dodgeDir;
float t = 1f - (_dodgeEndTime - Time.time) / dodgeDuration;
if (t > 1f)
_dodging = false;
else
_speed *= dodgeMultiplier * dodgeSpeedCurve.Evaluate(t);
}
animator.SetFloat("Horizontal", moveInput.x);
animator.SetFloat("Vertical", moveInput.y);
animator.SetFloat("Magnitude", Vector3.ClampMagnitude(moveInput, 1f).magnitude);
}
void FixedUpdate() {
// Move player and set animator parameters
Vector3 movement = _moveDir * _speed * Time.fixedDeltaTime;
rb.MovePosition(transform.position + movement);
//transform.position += moveDir * speed * Time.deltaTime;
}
void Update() {
if (Time.timeScale == 0f) {
return;
}
// Handle damage
if (Time.time < _damageColorEndTime)
_spriteRenderer.color = Color.red;
else
_spriteRenderer.color = Color.white;
if (health <= 0f) {
transform.position = Vector3.zero;
_spriteRenderer.color = Color.red;
}
// Dodge and movement
Vector2 moveInput;
if (_useRawInput)
moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
else
moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
Move(moveInput, Input.GetKeyDown(KeyCode.LeftShift));
// Aiming and orientation
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPos.z = 0f;
Vector3 playerToMouseDir = (mouseWorldPos - transform.position).normalized;
float orient = -Mathf.Sign(playerToMouseDir.x);
transform.localScale = new Vector3(orient*Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
_lineRenderer.SetPosition(0, transform.position + 0.1f * playerToMouseDir);
_lineRenderer.SetPosition(1, transform.position + 0.3f * playerToMouseDir);
// Attacking
if (_attackEnabled && Input.GetMouseButtonDown(0) && _activeWeapon.durability > 0) {
_activeWeapon.Attack(playerToMouseDir);
playerAudio.PlayOneShot(_activeWeapon.weaponSFX, 0.2f);
}
// Switch weapons
if (Input.GetMouseButtonDown(1)) {
SwitchWeapons();
}
_healthUI.health = health;
}
public void OnCraftingEnter() {
_attackEnabled = false;
}
public void OnCraftingExit() {
_attackEnabled = true;
}
/* void OnGUI() {
GUI.Box(new Rect(10, 10, 240, 200), "Dev Menu");
_useRawInput = GUI.Toggle(new Rect(20, 40, 80, 20), _useRawInput, "Raw Input");
GUI.Label(new Rect(20, 100, 200, 20), "Weapon Durability: " + _activeWeapon.durability.ToString("n2"));
if (GUI.Button(new Rect(20, 120, 120, 20), "Restore Durability"))
_activeWeapon.durability = 1.0f;
GUI.Label(new Rect(20, 140, 120, 20), "Health: " + health.ToString("n1"));
if (GUI.Button(new Rect(20, 160, 120, 20), "Restore Health")) {
health = 8f;
_spriteRenderer.color = Color.white;
}
}
*/
public void healPlayer(int plusHP) {
//Heals the player for plusHP hearts, up to the max
health = Mathf.Min(health + plusHP, _healthUI.numberOfHearts);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
//by julia duda
public class DialogMenager : MonoBehaviour
{
public GameObject DialogPanel;
public TMP_Text npcNameText;
public TMP_Text dialogText;
public Button NextButton;
public GameObject StopTheDialog;
/*
Skrypt odpwoedzialny za dialogi w grze
*/
private List<string> conversation;
private int convoIndex;
private void Start()
{
DialogPanel.SetActive(false);
}
public void Start_Dialog(string _npcName, List<string> _convo)
{
Cursor.visible = true;
Cursor.lockState = CursorLockMode.Confined;
npcNameText.text = _npcName;
conversation = new List<string>(_convo);
DialogPanel.SetActive(true);
convoIndex = 0;
ShowText();
Time.timeScale = 0;
}
public void StopDialog()
{
Cursor.visible = false;
DialogPanel.SetActive(false);
Time.timeScale = 1;
StopTheDialog.GetComponent<BoxCollider>().enabled = false;
}
private void ShowText()
{
dialogText.text = conversation[convoIndex];
}
public void Next()
{
if (convoIndex < conversation.Count - 1)
{
convoIndex += 1;
ShowText();
Debug.Log("Next Button pressed");
}
}
}
|
using FluentValidation.TestHelper;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using SFA.DAS.ProviderCommitments.Web.Validators.Cohort;
using System;
using System.Linq.Expressions;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Validators.Cohort
{
public class FileDiscardViewModelValidatorTests
{
[TestCase(0, false)]
[TestCase(1, true)]
public void Validate_ProviderId_ShouldBeValidated(int providerId, bool expectedValid)
{
var model = new FileDiscardViewModel { ProviderId = providerId };
AssertValidationResult(request => request.ProviderId, model, expectedValid);
}
[TestCase(null, false)]
[TestCase(true, true)]
[TestCase(false, true)]
public void Validate_Confirm_ShouldBeValidated(bool? confirm, bool expectedValid)
{
var model = new FileDiscardViewModel { FileDiscardConfirmed = confirm };
AssertValidationResult(request => request.FileDiscardConfirmed, model, expectedValid);
}
private void AssertValidationResult<T>(Expression<Func<FileDiscardViewModel, T>> property, FileDiscardViewModel instance, bool expectedValid)
{
var validator = new FileDiscardViewModelValidator();
if (expectedValid)
{
validator.ShouldNotHaveValidationErrorFor(property, instance);
}
else
{
validator.ShouldHaveValidationErrorFor(property, instance);
}
}
}
}
|
using RimWorld;
using UnityEngine;
using Verse;
using RimlightArchive.Defs;
namespace RimlightArchive.Verbs
{
/// <summary>
/// Handles shardblade cuts to single and adjacent targets.
/// </summary>
[StaticConstructorOnStartup]
public class Verb_MeleeShardCut : Verb_MeleeAttack
{
private static readonly Color color = new Color(160f, 160f, 160f);
private static readonly Material mat = MaterialPool.MatFrom("Spells/cleave_straight", ShaderDatabase.Transparent, Verb_MeleeShardCut.color);
protected override DamageWorker.DamageResult ApplyMeleeDamageToTarget(LocalTargetInfo target)
{
var damageResult = new DamageWorker.DamageResult();
var armorPen = Utils.IsWearingShardplate(target.Thing as Pawn) ? 0f : 999f;
var dinfo = new DamageInfo(RadiantDefOf.RA_Shardburn, this.tool.power, armorPen, -1f, this.CasterPawn, null, null, DamageInfo.SourceCategory.ThingOrUnknown);
damageResult.totalDamageDealt = Mathf.Min((float)target.Thing.HitPoints, dinfo.Amount);
Log.Message($"ApplyMeleeDamageToTarget|target {target}|armorPen {armorPen}|dinfo {dinfo}|damageResult {damageResult}|");
foreach (var adjacent in GenAdj.AdjacentCells)
{
var intVec = target.Cell + adjacent;
var cleaveVictim = intVec.GetFirstPawn(target.Thing.Map);
// add chance to hit friendly if in mental state?
if (cleaveVictim == null || cleaveVictim.Faction == caster.Faction)
continue;
cleaveVictim.TakeDamage(dinfo);
MoteMaker.ThrowMicroSparks(cleaveVictim.Position.ToVector3(), target.Thing.Map);
this.DrawCleaving(cleaveVictim, base.CasterPawn, 10);
}
target.Thing.TakeDamage(dinfo);
return damageResult;
}
private void DrawCleaving(Pawn cleavedPawn, Pawn caster, int magnitude)
{
if (caster.Dead || caster.Downed)
{
return;
}
var vector = cleavedPawn.Position.ToVector3();
vector.y = Altitudes.AltitudeFor(AltitudeLayer.MoteOverhead);
var hyp = Mathf.Sqrt((Mathf.Pow(caster.Position.x - cleavedPawn.Position.x, 2)) + (Mathf.Pow(caster.Position.z - cleavedPawn.Position.z, 2)));
var angleRad = Mathf.Asin(Mathf.Abs(caster.Position.x - cleavedPawn.Position.x) / hyp);
var angle = Mathf.Rad2Deg * angleRad;
var s = new Vector3(3f, 3f, 5f);
var matrix = default(Matrix4x4);
matrix.SetTRS(vector, Quaternion.AngleAxis(angle, Vector3.up), s);
Graphics.DrawMesh(MeshPool.plane10, matrix, Verb_MeleeShardCut.mat, 0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Josephus
{
class Program
{
static void Main(string[] args)
{
Josephus josephus = new Josephus();
josephus.imprimirTitulo();
String input = "";
while (!Int32.TryParse(input, out int num))
{
Console.Write("Ingrese cantidad de personas: ");
input = Console.ReadLine();
}
// Asigno cantidad de personas en el circulo
int personas = Convert.ToInt32(input);
input = "";
while (!Int32.TryParse(input, out int num))
{
Console.Write("Ingrese salto: ");
input = Console.ReadLine();
}
// Asigno tamaño del salto
int k = Convert.ToInt32(input);
int[] circulo = josephus.josephusItera(personas, k);
josephus.DibujarArreglo(circulo);
Console.WriteLine("Press a key to exit...");
Console.ReadKey();
}
}
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Leprechaun.InputProviders.Rainbow")]
[assembly: AssemblyDescription("")]
[assembly: InternalsVisibleTo("Leprechaun.InputProviders.Rainbow.Tests")] |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EFDebug : MonoBehaviour {
//
public void _Log (string st) {
Debug.Log (st);
}
public void _Log (GameObject st) {
Debug.Log (st);
}
public void _Break () {
Debug.Break ();
}
} |
using System.IO;
namespace SolarSystemWeb.Models.Application
{
/// <summary>
/// Синглтон, позволяющий получать дефолтное изображение для планеты на схеме,
/// загружая это изображение из файла только один раз
/// </summary>
public sealed class DefaultOrbitImage
{
private static volatile DefaultOrbitImage _instance;
private static readonly object SyncRoot = new object();
public static string DefaultImagePath { get; set; }
private DefaultOrbitImage()
{
var file = new FileStream(DefaultImagePath, FileMode.Open);
ImageData = new byte[file.Length];
file.Read(ImageData, 0, (int)file.Length);
}
public byte[] ImageData { get; }
public static DefaultOrbitImage Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new DefaultOrbitImage();
}
}
return _instance;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*******************************
* Created By franco
* Description: ProcessPlanningModule
*******************************/
namespace Kingdee.CAPP.Model
{
public class ProcessPlanningModule
{
/// <summary>
/// 工艺规程模板ID
/// </summary>
public Guid ProcessPlanningModuleId { get; set; }
/// <summary>
/// 业务ID
/// </summary>
public Guid BusinessId { get; set; }
/// <summary>
/// 模板的名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 业务类型
/// </summary>
public BusinessType BType { get; set; }
/// <summary>
/// 父节点的级别
/// </summary>
public int ParentNode { get; set; }
/// <summary>
/// 当前节点的级别
/// </summary>
public int CurrentNode { get; set; }
/// <summary>
/// 排序字段
/// </summary>
public int Sort { get; set; }
}
}
|
/* JurrasicJava.cs
* Author: Agustin Rodriguez
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace DinoDiner.Menu
{
/// <summary>
/// This class implements the coffee at dinodiner that inherits from Drink base class
/// </summary>
public class JurrasicJava : Drink
{
/// <summary>
/// whether or not you need room for cream
/// </summary>
private bool roomForCream;
/// <summary>
/// property that will set room for cream in cofffee
/// </summary>
public bool RoomForCream
{
get
{
return roomForCream;
}
set
{
roomForCream = value;
}
}
/// <summary>
/// if you want coffee decaf
/// </summary>
private bool decaf;
/// <summary>
/// property that keeps coffee decaf
/// </summary>
public bool Decaf
{
get
{
return decaf;
}
set
{
decaf = value;
}
}
/// <summary>
/// size for the drink
/// </summary>
protected Size size;
/// <summary>
/// initializes the drink as a small and no room for cream or decaf
/// </summary>
public JurrasicJava()
{
this.Price = 0.59;
this.Calories = 2;
this.Ice = false;
this.roomForCream = false;
this.decaf = false;
}
/// <summary>
/// this method will leave room for cream in coffee
/// </summary>
public void LeaveRoomForCream()
{
RoomForCream = true;
NotifyOfPropertyChanged("Special");
}
/// <summary>
/// this method adds ice to the coffee
/// </summary>
public void AddIce()
{
this.Ice = true;
NotifyOfPropertyChanged("Special");
}
/// <summary>
/// this method makes coffee decaf
/// </summary>
public void DecafCoffee()
{
Decaf = true;
NotifyOfPropertyChanged("Description");
}
/// <summary>
/// Sets size, price, and calories for the coffee. If sweetener is added the calories are doubled
/// </summary>
public override Size Size
{
set
{
size = value;
switch (size)
{
case Size.Small:
Price = 0.59;
Calories = 2;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
case Size.Medium:
Price = 0.99;
Calories = 4;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
case Size.Large:
Price = 1.49;
Calories = 8;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
}
}
get
{ return size; }
}
/// <summary>
/// ingredients in the coffee
/// </summary>
public override List<string> Ingredients
{
get
{
List<string> ingredients = new List<string>() { "Water", "Coffee" };
return ingredients;
}
}
/// <summary>
/// overrides the ToString method and returns menu item as a string with size
/// </summary>
/// <returns></returns>string menu item with size
public override string ToString()
{
if (Decaf)
{
switch (size)
{
case Size.Small:
return $"Small Decaf Jurassic Java";
case Size.Medium:
return $"Medium Decaf Jurassic Java";
case Size.Large:
return $"Large Decaf Jurassic Java";
}
}
else
{
switch (size)
{
case Size.Small:
return $"Small Jurassic Java";
case Size.Medium:
return $"Medium Jurassic Java";
case Size.Large:
return $"Large Jurassic Java";
}
}
return base.ToString();
}
/// <summary>
/// gets a description of the order item
/// </summary>
public override string Description
{
get { return this.ToString(); }
}
/// <summary>
/// gets special instructions for food prep
/// </summary>
public override string[] Special
{
get
{
List<string> special = new List<string>();
if (Ice) special.Add("Add Ice");
if (roomForCream) special.Add("Leave Room For Cream");
return special.ToArray();
}
}
}
}
|
#region MIT License
/*
* Copyright (c) 2013 University of Jyväskylä, Department of Mathematical
* Information Technology.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
/*
* Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen.
*/
using System.Collections.Generic;
using Jypeli.Controls;
using Silk.NET.Input;
namespace Jypeli
{
public partial class Game : ControlContexted
{
private ListenContext context;
private List<IController> controllers;
/// <summary>
/// Näppäimistö.
/// </summary>
public Keyboard Keyboard { get; private set; }
/// <summary>
/// Hiiri.
/// </summary>
public Mouse Mouse { get; private set; }
/// <summary>
/// Kiihtyvyysanturi.
/// </summary>
public Accelerometer Accelerometer
{
get { return Device.Accelerometer; }
}
/// <summary>
/// Kosketusnäyttö
/// </summary>
public TouchPanel TouchPanel { get; private set; }
/// <summary>
/// Puhelimen takaisin-näppäin.
/// </summary>
public BackButton PhoneBackButton { get; private set; }
/// <summary>
/// Lista kaikista peliohjaimista järjestyksessä.
/// </summary>
public List<GamePad> GameControllers { get; private set; }
/// <summary>
/// Ensimmäinen peliohjain.
/// </summary>
public GamePad ControllerOne { get { return GameControllers[0]; } }
/// <summary>
/// Toinen peliohjain.
/// </summary>
public GamePad ControllerTwo { get { return GameControllers[1]; } }
/// <summary>
/// Kolmas peliohjain.
/// </summary>
public GamePad ControllerThree { get { return GameControllers[2]; } }
/// <summary>
/// Neljäs peliohjain.
/// </summary>
public GamePad ControllerFour { get { return GameControllers[3]; } }
private IInputContext inputContext;
/// <summary>
/// Pelin pääohjainkonteksti.
/// </summary>
public ListenContext ControlContext
{
get { return Instance.context; }
}
/// <summary>
/// Onko ohjauskonteksti modaalinen (ei)
/// </summary>
public bool IsModal
{
get { return false; }
}
private void InitControls()
{
inputContext = Window.CreateInput();
context = new ListenContext() { Active = true };
Keyboard = new Keyboard(inputContext);
Mouse = new Mouse(Screen, inputContext);
PhoneBackButton = new BackButton();
TouchPanel = new TouchPanel();
controllers = new List<IController>();
GameControllers = new List<GamePad>(4);
GameControllers.Add(new GamePad(inputContext, 0));
GameControllers.Add(new GamePad(inputContext, 1));
GameControllers.Add(new GamePad(inputContext, 2));
GameControllers.Add(new GamePad(inputContext, 3));
controllers.AddRange(GameControllers);
controllers.Add(Mouse);
controllers.Add(Keyboard);
controllers.Add(Accelerometer);
controllers.Add(TouchPanel);
controllers.Add(PhoneBackButton);
}
private void UpdateControls(Time gameTime)
{
controllers.ForEach(c => c.Update());
GameControllers.ForEach(g => g.UpdateVibrations(gameTime));
}
/// <summary>
/// Poistaa kaikki ohjainkuuntelijat.
/// </summary>
public void ClearControls()
{
controllers.ForEach(c => c.Clear());
}
/// <summary>
/// Näyttää kontrollien ohjetekstit.
/// </summary>
public void ShowControlHelp()
{
controllers.ForEach(c => MessageDisplay.Add(c.GetHelpTexts()));
}
/// <summary>
/// Näyttää kontrollien ohjetekstit tietylle ohjaimelle.
/// </summary>
public void ShowControlHelp(IController controller)
{
MessageDisplay.Add(controller.GetHelpTexts());
}
private void ActivateObject(ControlContexted obj)
{
obj.ControlContext.Active = true;
if (obj.IsModal)
{
Game.Instance.ControlContext.SaveFocus();
Game.Instance.ControlContext.Active = false;
foreach (Layer l in Layers)
{
foreach (IGameObject lo in l.Objects)
{
ControlContexted co = lo as ControlContexted;
if (lo == obj || co == null)
continue;
co.ControlContext.SaveFocus();
co.ControlContext.Active = false;
}
}
}
}
private void DeactivateObject(ControlContexted obj)
{
obj.ControlContext.Active = false;
if (obj.IsModal)
{
Game.Instance.ControlContext.RestoreFocus();
foreach (Layer l in Layers)
{
foreach (IGameObject lo in l.Objects)
{
ControlContexted co = lo as ControlContexted;
if (lo == obj || co == null)
continue;
co.ControlContext.RestoreFocus();
}
}
}
}
}
}
|
namespace Titan.Meta
{
public class LiveGameInfo : TitanPayloadInfo
{
// Uhh, yea - we're useless now I guess? :(
}
}
|
using RabbitMQ.Client.Service.Enums;
namespace RabbitMQ.Client.Service.Options
{
public class ExchangeOptions
{
public string Name { get; set; }
public ExchangeTypeEnum Type { get; set; }
public bool Durable { get; set; }
public bool AutoDelete { get; set; }
public string RoutingKey { get; set; }
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReliablePerformanceBenchmark.cs">
// Copyright (c) 2021 Johannes Deml. All rights reserved.
// </copyright>
// <author>
// Johannes Deml
// public@deml.io
// </author>
// --------------------------------------------------------------------------------------------------------------------
using BenchmarkDotNet.Attributes;
namespace NetworkBenchmark
{
[Config(typeof(PerformanceBenchmarkConfig))]
public class ReliablePerformanceBenchmark : APredefinedBenchmark
{
[Params(NetworkLibrary.ENet, NetworkLibrary.LiteNetLib)]
public NetworkLibrary Library { get; set; }
[Params(TransmissionType.Reliable)]
public TransmissionType Transmission { get; set; }
[Params(500, Priority = 100)]
public override int Clients { get; set; }
public override int MessageTarget { get; set; } = 500_000;
protected override BenchmarkMode Mode => BenchmarkMode.Performance;
protected override NetworkLibrary LibraryTarget => Library;
[GlobalSetup(Target = nameof(PingPongReliable))]
public void PreparePingPongReliable()
{
BenchmarkCoordinator.ApplyPredefinedConfiguration();
var config = BenchmarkCoordinator.Config;
config.ParallelMessages = 1;
config.MessageByteSize = 32;
config.Transmission = Transmission;
PrepareBenchmark();
}
[Benchmark]
public long PingPongReliable()
{
return RunBenchmark();
}
public override string ToString()
{
return "ReliablePerformanceBenchmark";
}
}
}
|
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 RPG
{
public partial class frm_ork : Form
{
InventarKlasse invObjekt = InventarKlasse.globalesInventar();
public frm_ork()
{
InitializeComponent();
tm3.Interval = 500;
tm3.Tick += new EventHandler(Timer_tickAgain);
tm3.Start();
prg_Lebens();
}
Timer tm3 = new Timer();
int ork_leben = 100;
void Timer_tickAgain(object sender, EventArgs e)
{
prg_Leben.Value = prg_Leben.Value - 3;
if (prg_Leben.Value <= 7)
{
tm3.Stop();
MessageBox.Show("Du bist Gestorben!");
Form formes = new Form3();
formes.Visible = true;
this.Hide();
}
}
private void prg_Lebens()
{
prg_Leben.Style = ProgressBarStyle.Continuous;
prg_Leben.Minimum = 0;
prg_Leben.Maximum = 50;
prg_Leben.Value = frm1.lebenzahl();
prg_Leben.ForeColor = Color.Green;
}
private void button1_Click(object sender, EventArgs e)
{
ork_leben = ork_leben - Stats.Schadenausteilen();
if(ork_leben <= 0)
{
tm3.Stop();
MessageBox.Show("Gewonnen!");
Gebiet_3.Zurück();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wobble : MonoBehaviour {
public float offset;
public float speed;
public float size;
public Vector3 axis = Vector3.one;
float curSize;
Vector3 origSize;
// Use this for initialization
void Start () {
origSize = transform.localScale;
}
// Update is called once per frame
void Update () {
curSize = (Mathf.Sin(Time.time * speed + offset) * size);
transform.localScale = new Vector3(origSize.x + (axis.x * curSize), origSize.y + (axis.y * curSize), (axis.z * curSize));
}
}
|
using Microsoft.AspNet.Http;
using Microsoft.Data.Entity;
using Stolons.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Stolons.ViewModels.ProductsManagement
{
public class ProductViewModel
{
public Product Product { get; set; }
public string OrderedQuantityString;
public ProductViewModel()
{
}
public ProductViewModel(Product product, int orderedQty)
{
Product = product;
OrderedQuantityString = product.GetQuantityString(orderedQty);
}
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class MasterDetailwPhoto : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
}
protected void gvStudent_RowCommand(object sender, GridViewCommandEventArgs e) {
displayImage(Convert.ToInt32(e.CommandArgument));
}
private void displayImage(int index) {
try {
string filename = gvStudent.DataKeys[index].Values[1].ToString();
string imagePath = AppDomain.CurrentDomain.BaseDirectory + "images/" + filename;
imgStudent.ImageUrl = "../Images/" + filename;
if (System.IO.File.Exists(imagePath)) {
imgStudent.Visible = true;
lblMsg.Visible = false;
} else {
imgStudent.Visible = false;
lblMsg.Visible = true;
}
} catch {
imgStudent.Visible = false;
lblMsg.Visible = true;
}
}
protected void ddlAdvisor_SelectedIndexChanged(object sender, EventArgs e) {
imgStudent.Visible = false;
lblMsg.Visible = false;
gvStudent.EditIndex = -1;
}
}
|
/* Size.cs
* Author: Agustin Rodriguez
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace DinoDiner.Menu
{
/// <summary>
/// enum for different sizes of sides and drinks
/// </summary>
public enum Size
{
Small,
Medium,
Large
}
}
|
using System;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using StarlightRiver.NPCs;
using Microsoft.Xna.Framework.Graphics;
namespace StarlightRiver.Projectiles.WeaponProjectiles
{
public class VitricIcicleProjectile : ModProjectile
{
public override void SetDefaults()
{
projectile.width = 24;
projectile.height = 24;
projectile.friendly = true;
projectile.penetrate = 2;
projectile.extraUpdates = 1;
projectile.timeLeft = 800;
projectile.magic = true;
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault("VortexPenisStaff moment 2");
}
public override void AI()
{
}
public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
{
}
public override void Kill(int timeLeft)
{
}
}
} |
using Sfa.Poc.ResultsAndCertification.CsvHelper.Models.Configuration;
using Sfa.Poc.ResultsAndCertification.CsvHelper.Web.WebConfigurationHelper;
namespace Sfa.Tl.ResultsAndCertification.Web.WebConfigurationHelper
{
public class WebConfigurationService : IWebConfigurationService
{
public readonly ResultsAndCertificationConfiguration _configuration;
public WebConfigurationService(ResultsAndCertificationConfiguration configuration)
{
_configuration = configuration;
}
public string GetFeedbackEmailAddress()
{
return string.Empty; //_configuration.FeedbackEmailAddress;
}
public string GetSignOutPath()
{
return string.Empty;
//return _configuration.DfeSignInSettings.SignOutEnabled ? RouteConstants.SignOutDsi : RouteConstants.SignOut;
}
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;
namespace BookboonSDK.Tests
{
public class BookboonClientTests
{
[Test]
public async void SimpleGet()
{
var client = new BookboonClient();
var data = await client.Get("/categories");
Assert.NotNull(data[0].id);
}
[Test]
public async void AuthenticatedGet()
{
var client = new BookboonClient();
var handle = GetAuthenticationHandle();
var data = await client.Get("/recommendations", handle);
Assert.NotNull(data[0].id);
}
[Test]
public async void AuthenticatedPost()
{
var client = new BookboonClient();
var handle = GetAuthenticationHandle();
var data = await client.Post("/profile", handle, new { email = "test@example.com", newsletter = false });
Assert.AreEqual("test@example.com", (string) data.email);
}
[Test]
public async void NotFoundException()
{
var client = new BookboonClient();
var task = client.Get("/nosuchthing");
AssertThrowsApiException("NotFound", task);
}
[Test]
public async void HttpsRequiredException()
{
var client = new BookboonClient();
var task = client.Get("/recommendations");
AssertThrowsApiException("HttpsRequired", task);
}
[Test]
public async void ApiKeyInvalidException()
{
var client = new BookboonClient();
var handle = new AuthenticationHandle("badapikey", "dummyhandle");
var task = client.Get("/recommendations", handle);
AssertThrowsApiException("ApiKeyInvalid", task);
}
[Test]
public async void BadDataException()
{
var client = new BookboonClient();
var handle = GetAuthenticationHandle();
var task = client.Post("/profile", handle, new { email = "invalid", newsletter = false });
AssertThrowsApiException("UnacceptableParameterValue", task);
}
public static async void AssertThrowsApiException(string expectedErrorCode, Task task)
{
try
{
await task;
Assert.Fail("Action did not throw ApiException.");
}
catch (ApiException exception)
{
Assert.AreEqual(expectedErrorCode, exception.ErrorCode);
}
}
private static AuthenticationHandle GetAuthenticationHandle()
{
var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "apikey.txt");
var apiKey = File.ReadAllText(configFilePath).Trim();
return new AuthenticationHandle(apiKey, "test");
}
}
}
|
using System.Text.Json;
using Microsoft.AspNetCore.Http;
namespace Robot.Backend
{
// Convenience methods for reading/writing the Robot state from the session.
public static class SessionExtensions
{
const string RobotKey = "Robot";
readonly static JsonSerializerOptions Options = new JsonSerializerOptions
{
Converters = { new RobotJsonConverter() },
WriteIndented = false
};
public static void Set(this ISession session, Robot robot)
{
session.SetString(RobotKey, JsonSerializer.Serialize(robot, Options));
}
public static Robot? Get(this ISession session)
{
var json = session.GetString(RobotKey);
if (string.IsNullOrEmpty(json)) {
return null;
}
return JsonSerializer.Deserialize<Robot>(json, Options);
}
}
} |
using MChooser.Constants;
using MChooser.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace MChooser.XMLControl
{
public class MChooserXMLWriter
{
public static AddMechResult AddMechToFile(MechModel mech)
{
AddMechResult result = AddMechResult.CHASSIS_AND_VARIANT_EXIST;
FileInfo fileInfo = new FileInfo(Constants.StaticValues.OwnedMechsFile);
XDocument doc = XDocument.Load(fileInfo.FullName);
XElement model = (from el in doc.Root.Elements(mech.MechClass.ToString().ToLower())
.Elements(StaticValues.XMLMechTag)
where (string)el.Attribute(StaticValues.XMLModelNameTag) == mech.MechModelName
select el)
.FirstOrDefault();
if (CheckEntryExists(model, mech) == false)
{
if (model == null)
{
XElement weightClass = doc.Root.Element(mech.MechClass.ToString().ToLower());
weightClass.Add(
new XElement(StaticValues.XMLMechTag, new object[] {
new XAttribute(StaticValues.XMLMechfactionTag, mech.MechFaction),
new XAttribute(StaticValues.XMLWeightIncrementTag, mech.GetMechWeight()),
new XAttribute(StaticValues.XMLModelNameTag, mech.MechModelName),
new XElement(StaticValues.XMLModelVariantTag, mech.ModelVariantName)
}));
result = AddMechResult.SUCCESSFULLY_ADDED_NEW_CHASSIS_AND_VARIANT;
}
else
{
model.Add(
new XElement(StaticValues.XMLModelVariantTag, mech.ModelVariantName));
result = AddMechResult.SUCCESSFULLY_ADDED_NEW_VARIANT;
}
doc.Save(fileInfo.FullName);
}
else
{
result = AddMechResult.CHASSIS_AND_VARIANT_EXIST;
}
return result;
}
private static bool CheckEntryExists(XElement model, MechModel mech)
{
if (model == null)
{
return false;
}
else
{
XElement variant = (from el in model.Elements(StaticValues.XMLModelVariantTag)
where (string)el.Value == mech.ModelVariantName
select el)
.FirstOrDefault();
if (variant == null)
{
return false;
}
else
{
return true;
}
}
}
}
}
|
using gView.Framework.Data;
using gView.Framework.FDB;
using gView.Framework.Network;
using gView.Framework.UI.Controls.Wizard;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Framework.UI.Dialogs.Network
{
public partial class NetworkSwitchesControl : UserControl, IWizardPageNotification, IWizardPageNecessity
{
private IFeatureDatabase3 _database = null;
private SelectFeatureclassesControl _selected;
public NetworkSwitchesControl(IFeatureDataset dataset, SelectFeatureclassesControl selected)
{
InitializeComponent();
if (dataset != null)
{
_database = dataset.Database as IFeatureDatabase3;
}
if (_database == null)
{
throw new ArgumentException();
}
_selected = selected;
if (_selected == null)
{
throw new ArgumentException();
}
}
async private Task FillGrid()
{
if (_selected.NodeFeatureclasses == null)
{
return;
}
#region Delete Rows
List<DataGridViewRow> delete = new List<DataGridViewRow>();
foreach (DataGridViewRow r in gridFcs.Rows)
{
int fcId = (int)r.Cells[0].Value;
bool found = false;
foreach (IFeatureClass fc in _selected.NodeFeatureclasses)
{
if (await _database.GetFeatureClassID(fc.Name) == fcId)
{
found = true;
break;
}
}
if (!found)
{
delete.Add(r);
}
}
foreach (DataGridViewRow r in delete)
{
gridFcs.Rows.Remove(r);
}
#endregion
foreach (IFeatureClass fc in _selected.NodeFeatureclasses)
{
await AddGridRow(fc);
}
}
async private Task AddGridRow(IFeatureClass fc)
{
int fcId = await _database.GetFeatureClassID(fc.Name);
foreach (DataGridViewRow r in gridFcs.Rows)
{
if (r.Cells[0].Value.Equals(fcId))
{
return;
}
}
DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell idCell = new DataGridViewTextBoxCell();
idCell.Value = fcId;
row.Cells.Add(idCell);
DataGridViewCheckBoxCell chkCell = new DataGridViewCheckBoxCell();
chkCell.Value = true;
row.Cells.Add(chkCell);
DataGridViewTextBoxCell nameCell = new DataGridViewTextBoxCell();
nameCell.Value = fc.Name;
row.Cells.Add(nameCell);
DataGridViewComboBoxCell fieldCell = new DataGridViewComboBoxCell();
fieldCell.Items.Add("<none>");
foreach (IField field in fc.Fields.ToEnumerable())
{
switch (field.type)
{
case FieldType.integer:
case FieldType.smallinteger:
case FieldType.biginteger:
case FieldType.boolean:
fieldCell.Items.Add(field.name);
break;
}
}
fieldCell.Value = "<none>";
row.Cells.Add(fieldCell);
DataGridViewComboBoxCell typeCell = new DataGridViewComboBoxCell();
foreach (object nodeType in Enum.GetValues(typeof(NetworkNodeType)))
{
typeCell.Items.Add(nodeType.ToString());
}
typeCell.Value = gView.Framework.Network.NetworkNodeType.Unknown.ToString();
row.Cells.Add(typeCell);
gridFcs.Rows.Add(row);
}
#region Properties
public Dictionary<int, string> SwitchNodeFcIds
{
get
{
Dictionary<int, string> ret = new Dictionary<int, string>();
foreach (DataGridViewRow row in gridFcs.Rows)
{
if ((bool)row.Cells[1].Value == true)
{
string fieldname = (string)row.Cells[3].Value;
if (fieldname == "<none>")
{
fieldname = String.Empty;
}
ret.Add((int)row.Cells[0].Value, fieldname);
}
}
return ret.Keys.Count > 0 ? ret : null;
}
}
public Dictionary<int, gView.Framework.Network.NetworkNodeType> NetworkNodeTypeFcIds
{
get
{
Dictionary<int, gView.Framework.Network.NetworkNodeType> ret = new Dictionary<int, gView.Framework.Network.NetworkNodeType>();
foreach (DataGridViewRow row in gridFcs.Rows)
{
foreach (NetworkNodeType nodeType in Enum.GetValues(typeof(NetworkNodeType)))
{
if ((string)row.Cells[4].Value == nodeType.ToString())
{
ret.Add((int)row.Cells[0].Value, nodeType);
break;
}
}
}
return ret;
}
}
public Serialized Serialize
{
get
{
List<Serialized.Row> rows = new List<Serialized.Row>();
foreach (DataGridViewRow gridRow in gridFcs.Rows)
{
rows.Add(new Serialized.Row()
{
IsSwitch = (bool)gridRow.Cells[1].Value,
FeatureclassName = (string)gridRow.Cells[2].Value,
FieldName = (string)gridRow.Cells[3].Value,
NodeType = gridRow.Cells[4].Value?.ToString()
});
}
return new Serialized
{
Rows = rows.ToArray()
};
}
set
{
if (value == null || value.Rows == null)
{
return;
}
foreach (DataGridViewRow gridRow in gridFcs.Rows)
{
var row = value.Rows.Where(m => m.FeatureclassName == (string)gridRow.Cells[2].Value).FirstOrDefault();
if (row != null)
{
gridRow.Cells[1].Value = row.IsSwitch;
gridRow.Cells[3].Value = row.FieldName;
gridRow.Cells[4].Value = row.NodeType;
}
}
}
}
#endregion
#region Serialization Class
public class Serialized
{
[JsonProperty(PropertyName = "rows")]
public Row[] Rows { get; set; }
public class Row
{
[JsonProperty(PropertyName = "switch")]
public bool IsSwitch { get; set; }
[JsonProperty(PropertyName = "fcname")]
public string FeatureclassName { get; set; }
[JsonProperty(PropertyName = "fieldname")]
public string FieldName { get; set; }
[JsonProperty(PropertyName = "nodetype")]
public string NodeType { get; set; }
}
}
#endregion
#region IWizardPageNotification Member
async public Task OnShowWizardPage()
{
await FillGrid();
}
#endregion
#region IWizardPageNecessity Member
public bool CheckNecessity()
{
if (_selected == null || _selected.NodeFeatureclasses == null || _selected.NodeFeatureclasses.Count == 0)
{
return false;
}
return true;
}
#endregion
}
}
|
using MattyControls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace TabularTool
{
public class NewlineParser : Parser
{
private Tb _tbColumnRegex;
private Db _dbColumnPresets;
private (string name, string regex)[] ColumnPresets {
get => new[] {
("Whitespace", @"\ \ +|\ *\t+\ *"),
("Commas", @",\s*"),
("Semicolons", @";"),
("Vertical bars", @"|")
};
}
public override void InitControls(MattyUserControl userControl) {
_tbColumnRegex = new Tb(userControl);
_dbColumnPresets = new Db(userControl);
_dbColumnPresets.Items.AddRange(ColumnPresets.Select(p => p.name).ToArray());
_dbColumnPresets.SelectedIndexChanged += (o, e) => {
_tbColumnRegex.Text = ColumnPresets[_dbColumnPresets.SelectedIndex].regex;
};
// TODO: add these to options and read from there
if (_dbColumnPresets.SelectedIndex < 0) {
_dbColumnPresets.SelectedIndex = 0;
}
Controls = new Control[] { _tbColumnRegex, _dbColumnPresets };
base.InitControls(userControl);
}
public override TabularData Parse(string input) {
var lines = SplitLines(input);
var regex = new Regex(_tbColumnRegex.Text);
var rows = lines.Select(l => regex.Replace(l, "\n").Split('\n'));
rows = FilterWhitespace(rows);
return TabularData.FromRows(rows);
}
private string[] SplitLines(string input) {
return input
.Replace("\r\n", "\n")
.Split('\n');
}
private IEnumerable<T> FilterWhitespace<T>(IEnumerable<T> rows) where T : IEnumerable<string> {
return rows.Where(l => l.Any(s => !string.IsNullOrWhiteSpace(s)));
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SuperMario.Collision;
namespace SuperMario.Entities.BackgroundElements
{
public class BigHill : StaticEntity
{
public BigHill(Vector2 screenLocation) : base(screenLocation)
{
Texture2D hillTexture = WinterBackgroundTextureStorage.BigHillTextureWinter;
CurrentSprite = new Sprite(hillTexture, new Rectangle(0, 0, hillTexture.Width, hillTexture.Height));
}
public override void Collide(Entity entity, RectangleCollisions collisions)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.IO;
using AlmenaraGames;
#if UNITY_EDITOR
namespace AlmenaraGames.Tools
{
public class CreateAudioObjectFromFile : Editor
{
[MenuItem("Assets/Multi Listener Pooling Audio System Tools/Create Audio Object From Selection")]
private static void DoSomethingWithVariable()
{
foreach (Object o in Selection.objects)
{
if (o.GetType() == typeof(AudioClip))
{
string path = AssetDatabase.GetAssetPath(o);
if (path == "")
{
path = "Assets/";
}
else if (Path.GetExtension(path) != "")
{
path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(o)), "");
}
AudioObject asset = ScriptableObject.CreateInstance<AudioObject>();
AssetDatabase.CreateAsset(asset, path + o.name + "_AO.asset");
asset.clips = new AudioClip[] { AssetDatabase.LoadAssetAtPath<AudioClip>(AssetDatabase.GetAssetPath(o)) };
EditorUtility.SetDirty(asset);
Selection.activeObject = asset;
}
}
}
[MenuItem("Assets/Multi Listener Pooling Audio System Tools/Create Audio Object From Selection", true)]
private static bool NewMenuOptionValidation()
{
bool testAllAudioClips = true;
foreach (Object obj in Selection.objects)
{
if (obj.GetType() != typeof(AudioClip))
{
testAllAudioClips = false;
}
}
return testAllAudioClips;
}
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PROnline.Models.ShortMessages
{
//短信模块
public class ShortMessageTemplate
{
//短信模块ID
public Guid ShortMessageTemplateID { get; set; }
[Display(Name = "类型")]
[MaxLength(50)]
[Required]
public String Title { get; set; }
[Display(Name = "短信内容")]
[MaxLength(300)]
[Required]
public String Content { get; set; }
//创建者
public Guid Creator { get; set; }
//创建日期
public DateTime CreateDate { get; set; }
//修改者
public Guid Modifier { get; set; }
//修改日期
public DateTime? ModifyDate { get; set; }
//是否删除
public Boolean isDelete { get; set; }
}
} |
using System;
namespace ProgrammingCourseWork.Display
{
public static class MainDisplay
{
public static void Display()
{
Console.Clear();
Console.WriteLine("Изберете опция:");
Console.WriteLine("1. Меню");
Console.WriteLine("2. Купи");
Console.WriteLine("3. Продажби");
Console.WriteLine("4. Изход");
string input = Console.ReadLine();
if (input == "1")
{
MenuDisplay.Display();
}
else if (input == "2")
{
BuyDisplay.Display();
}
else if (input == "3")
{
SellsDisplay.Display();
}
else if (input == "4")
{
SellsDisplay.Display();
Environment.Exit(0);
}
Display();
}
}
}
|
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace RegionTree
{
public class RegionDbContext : AbpDbContext
{
public RegionDbContext(DbContextOptions<RegionDbContext> options) : base(options)
{
}
public DbSet<Region> Region { get; set; }
}
/// <summary>
/// dotnet ef ....
/// </summary>
public class RegionDbContextFactory : IDesignTimeDbContextFactory<RegionDbContext>
{
public RegionDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<RegionDbContext>();
optionsBuilder.UseSqlServer("Server=.;Database=Region;Trusted_Connection=True;");
return new RegionDbContext(optionsBuilder.Options);
}
}
} |
using UnityEngine;
using System.Collections;
public class Trap : BaseEntity
{
private SkillImpactInfo m_impactInfo;
void Start()
{
Initialize();
}
public override void Initialize()
{
base.Initialize();
m_impactInfo = thisObject.GetComponent<SkillImpactInfo>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == LayerMask.NameToLayer("Character"))
{
Character tempChar = other.gameObject.GetComponent<Character>();
//체력 닳게
if (tempChar != null)
tempChar.onDamage(this, m_impactInfo);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace test_cs
{
class Program
{
static void Main(string[] args)
{
ISample[] samples =
{
new Window.Empty(),
new Window.EmptyExternal(),
new LogSample(),
new Input.KeyboardSample(),
new Input.MouseSample1(),
new Input.MouseSample2(),
new Input.JoystickSample(),
new Sound.SoundSample(),
new Graphics.PostEffect.CustomPostEffect(),
};
var cui = new SampleGuide( samples );
cui.Show();
}
}
}
|
namespace _04._PascalTriangle
{
using System;
using System.Collections.Generic;
public class Startup
{
public static void Main()
{
int number = int.Parse(Console.ReadLine());
List<List<long>> matrix = new List<List<long>>();
matrix.Add(new List<long>() { 1 });
for (int i = 1; i < number; i++)
{
matrix.Add(new List<long>() { 1 });
for (int j = 0; j < i - 1; j++)
{
matrix[i].Add(matrix[i - 1][j] + matrix[i - 1][j + 1]);
}
matrix[i].Add(1);
}
foreach (List<long> list in matrix)
{
Console.WriteLine(string.Join(" ", list));
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class rotater : MonoBehaviour
{
public bool x, y, z;
public float rotationSpeed;
private float sX = 0f, sY = 0f, sZ = 0f;
private Vector3 rotation;
void Start()
{
if (x)
sX = rotationSpeed;
if (y)
sY = rotationSpeed;
if (y)
sY = rotationSpeed;
rotation = new Vector3(sX, sY, sZ);
}
void Update()
{
transform.Rotate(rotation * Time.deltaTime);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.