text stringlengths 13 6.01M |
|---|
using SciVacancies.ReadModel.Core;
using SciVacancies.Services.Email;
using System;
using Microsoft.Framework.Configuration;
namespace SciVacancies.SmtpNotifications.SmtpNotificators
{
public class SmtpNotificatorSearchSubscriptionService : ISmtpNotificatorSearchSubscriptionService
{
readonly IEmailService EmailService;
readonly string From;
readonly string Domain;
readonly string PortalLink;
public SmtpNotificatorSearchSubscriptionService(IEmailService emailService, IConfiguration configuration)
{
EmailService = emailService;
From = configuration["EmailSettings:Login"];
Domain = configuration["EmailSettings:Domain"];
PortalLink = configuration["EmailSettings:PortalLink"];
if (string.IsNullOrEmpty(From)) throw new ArgumentNullException("From is null");
if (string.IsNullOrEmpty(Domain)) throw new ArgumentNullException("Domain is null");
if (string.IsNullOrEmpty(PortalLink)) throw new ArgumentNullException("PortalLink is null");
}
public void SendCreated(Researcher researcher, Guid searchSubscriptionGuid, string title)
{
var researcherFullName = $"{researcher.secondname} {researcher.firstname} {researcher.patronymic}";
var body = $@"
<div style=''>
Здравствуйте, {researcherFullName},
<br/>
Сообщаем, что Вы добавили Поисковую подписку '{title}'.
<br/>
<a target='_blank' href='http://{Domain}/researchers/subscriptions/'>Здесь доступно управление подписками</a>.
<br/>
<a target='_blank' href='http://{Domain}/subscriptions/details/{searchSubscriptionGuid}'>Обработать</a> подписку (выполнить поиск).
<br/>
</div>
<br/>
<br/>
<br/>
<hr/>
<div style='color: lightgray; font-size: smaller;'>
Это письмо создано автоматически с
<a target='_blank' href='http://{Domain}'>Портала вакансий</a>.
Чтобы не получать такие уведомления отключите их или смените email в
<a target='_blank' href='http://{Domain}/researchers/account/'>личном кабинете</a>.
</div>
";
EmailService.Send(new SciVacMailMessage(From, researcher.email, "Уведомление с портала вакансий", body));
}
}
}
|
using System;
namespace OrgMan.DomainObjects.Common
{
public class AdressDomainModel
{
public Guid UID { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string Additional { get; set; }
public string PostCode { get; set; }
public string City { get; set; }
public Guid CountryUID { get; set; }
}
} |
using RRExpress.AppCommon;
using RRExpress.AppCommon.Attributes;
using RRExpress.AppCommon.Models;
using RRExpress.Common;
using RRExpress.Seller.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace RRExpress.Seller.ViewModels {
[Regist(InstanceMode.Singleton)]
public class MyGoodsFilterViewModel : BaseVM {
public override string Title {
get {
return "过滤条件";
}
}
public IEnumerable<GoodsCategoryTreeNode> Categories {
get;
private set;
}
public GoodsCategoryTreeNode Cat { get; set; }
public IEnumerable<string> SortTypes {
get;
} = new List<string>() { "不限", "时间", "库存" };
public string SortType { get; set; }
public ICommand ResetCmd { get; }
public ICommand OkCmd { get; }
public MyGoodsFilterViewModel() {
this.LoadCats();
this.ResetCmd = new Command(() => {
});
this.OkCmd = new Command(() => { });
}
private async void LoadCats() {
var datas = await ResJsonReader.GetAll<IEnumerable<GoodsCategory>>(this.GetType().GetTypeInfo().Assembly, "RRExpress.Seller.Cats.json");
var nodes = datas.BuildTree<GoodsCategory, GoodsCategoryTreeNode, int>(c => c.PID, c => c.ID, 0);
var cats = nodes.ToList();
cats.Insert(0, new GoodsCategoryTreeNode() {
ID = -1,
PID = -1,
Data = new Entity.GoodsCategory() {
Name = "不限"
}
});
this.Categories = cats;
this.NotifyOfPropertyChange(() => this.Categories);
}
}
}
|
using System;
namespace cyclicRotation
{
class Program
{
static void Main(string[] args)
{
solution(new int[] {3,8,9,6}, 3);
}
public static int[] solution(int[] A, int K)
{
//use mod to rotate only the smallest amount
//make a new array
//to do in place will needs a storage array, which could result in saving up ot half the array an additional time
//if in place, we want to do a left or right shift to minimize sizeof storage array and double visiting elements
if(K == 0 || A.Length==0)
{
return A;
}
int shift = K % A.Length;
if(shift == 0)
{
return A;
}
int[] result = new int[A.Length];
for(int i= A.Length-1; i >= shift; i--)
{
result[i] = A[i-shift];
}
for(int i = 0; i < shift; i++)
{
result[i] = A[A.Length-shift+i];
}
return result;
}
}
}
|
namespace Ach.Fulfillment.Business.Impl.Validation
{
using Ach.Fulfillment.Data;
using FluentValidation;
internal class PasswordValidator : AbstractValidator<string>
{
public PasswordValidator()
{
this.RuleFor(i => i)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Length(1, MetadataInfo.StringNormal)
.WithName("Password");
}
}
} |
using Infrostructure.Exeption;
namespace DomainModel.Entity.ProductParts
{
/// <summary>
/// وات مصرفی
/// </summary>
public class Wattage
{
private const decimal MinValue = 0m;
public decimal Value { get; private set; }
public Wattage(decimal value)
{
ValidateWattageValue(value);
Value = value;
}
private void ValidateWattageValue(decimal value)
{
if (value < MinValue) throw new InvalidWattageMeasureValueException(value.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Market.Data.DataBaseModel
{
public class Seller
{
public int Id { get; set; }
public string Name { get; set; }
public string Mail { get; set; }
public int Phone { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using Jypeli;
using Jypeli.Assets;
using Jypeli.Controls;
using Jypeli.Widgets;
namespace Fysiikkapeli;
/// @author Omanimi
/// @version Päivämäärä
/// <summary>
///
/// </summary>
public class Fysiikkapeli : PhysicsGame
{
public override void Begin()
{
// Kirjoita ohjelmakoodisi tähän
PhoneBackButton.Listen(ConfirmExit, "Lopeta peli");
Keyboard.Listen(Key.Escape, ButtonState.Pressed, ConfirmExit, "Lopeta peli");
}
}
|
using Terraria.ID;
using Terraria.ModLoader;
namespace Intalium.Items.Materials
{
public class AwesomeAlloy : ModItem //Niebieski
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Awesome Alloy");
Tooltip.SetDefault("This exceedingly rare high-quality steel is as precious as gold");
}
public override void SetDefaults()
{
item.value = 25000;
item.rare = 3;
item.maxStack = 999;
item.width = 34;
item.height = 39;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddRecipeGroup("Intalium:Tier8Bar", 1);
recipe.AddRecipeGroup("Intalium:Tier9Bar", 1);
recipe.AddRecipeGroup("Intalium:Tier10Bar", 1);
recipe.AddIngredient(null, "Shine", 1);
recipe.AddTile(TileID.AdamantiteForge);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
using System;
class SumOfFiveNumbers
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
Console.Write("Enters 5 numbers separated by space: ");
string[] aValues = Console.ReadLine().Split(' ');
double[] aNumbers = new double[aValues.Length];
bool bIsNum = true;
double dSum = 0;
for (int i = 0; i < aValues.Length; i++)
{
if (!double.TryParse(aValues[i], out aNumbers[i]))
{
Console.WriteLine("Only numbers !");
bIsNum = false;
break;
}
else
{
dSum += aNumbers[i];
}
}
if (bIsNum)
{
Console.WriteLine("Sum = {0}",dSum);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems.Rosalind {
public class RNA : RosalindBase {
public override string ProblemName => "Rosalind: RNA";
public override string GetAnswer() {
return Solve(Input());
}
private string Solve(List<string> input) {
return input[0].Replace("T", "U");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Database.Sqlite;
using Android.Database;
namespace Goosent
{
/// <summary>
/// Класс работы с локальной базой данных
/// </summary>
class DBHandler : SQLiteOpenHelper
{
string DATABASE_NAME;
string SETS_TABLE_NAME;
string CHANNELS_TABLE_NAME;
const string KEY_CHANNEL_ID = "id";
const string KEY_CHANNEL_NAME = "channel_name";
const string KEY_CHANNEL_PLATFORM = "platform";
const string KEY_CHANNEL_SET_ID = "channel_set_id";
const string KEY_SET_ID = "set_id";
const string KEY_SET_NAME = "set_name";
Context _context;
public DBHandler(Context context) : base(context, context.Resources.GetString(Resource.String.database_name), null, 1)
{
_context = context;
SETS_TABLE_NAME = _context.Resources.GetString(Resource.String.database_sets_table_name);
CHANNELS_TABLE_NAME = _context.Resources.GetString(Resource.String.database_channels_table_name);
}
public override void OnCreate(SQLiteDatabase db)
{
// Если база данных не найдена - создается новая, состаящая из двух таблиц для сетов и каналов
db.ExecSQL("CREATE TABLE " + SETS_TABLE_NAME +
" (" + KEY_SET_ID + " integer primary key autoincrement, "
+ KEY_SET_NAME + " text)");
db.ExecSQL("CREATE TABLE " + CHANNELS_TABLE_NAME +
" (" + KEY_CHANNEL_ID + " integer primary key autoincrement, "
+ KEY_CHANNEL_NAME + " text, "
+ KEY_CHANNEL_PLATFORM + " text, "
+ KEY_CHANNEL_SET_ID + " integer)");
}
/// <summary>
/// Вызывается если поменялась версия БД (например изменилась структура и надо обновить всю БД), удаляя при этом старую версию
/// </summary>
/// <param name="db"></param>
/// <param name="oldVersion"></param>
/// <param name="newVersion"></param>
public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.ExecSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
OnCreate(db);
}
/// <summary>
/// Добавить канал в локальную БД
/// </summary>
/// <param name="channel"></param>
/// <param name="setIndex"></param>
public void AddChannel(Channel channel, int setIndex)
{
SQLiteDatabase db = WritableDatabase;
ContentValues values = new ContentValues();
values.Put(KEY_CHANNEL_NAME, channel.Name);
values.Put(KEY_CHANNEL_PLATFORM, (int)channel.Platform);
values.Put(KEY_CHANNEL_SET_ID, setIndex + 1);
var id = db.Insert(CHANNELS_TABLE_NAME, null, values);
db.Close();
}
/// <summary>
/// Удалить канал из локальной БД
/// </summary>
/// <param name="setIndex"></param>
/// <param name="channelName"></param>
/// <param name="channelPlatform"></param>
public void DeleteChannel(int setIndex, string channelName, DATA.Platforms channelPlatform)
{
SQLiteDatabase db = WritableDatabase;
var strs = new string[3] { channelName, ((int)channelPlatform).ToString(), (setIndex + 1).ToString() };
db.Delete(CHANNELS_TABLE_NAME, KEY_CHANNEL_NAME + "=? and " + KEY_CHANNEL_PLATFORM + "=? and " + KEY_CHANNEL_SET_ID + "=?",strs );
}
/// <summary>
/// Добавить сет в локальную БД
/// </summary>
/// <param name="set"></param>
public void AddSet(ChannelsSet set)
{
SQLiteDatabase db = WritableDatabase;
ContentValues sets_table_values = new ContentValues();
sets_table_values.Put(KEY_SET_NAME, set.Name);
var id = db.Insert(SETS_TABLE_NAME, null, sets_table_values);
foreach (Channel channel in set.Channels)
{
AddChannel(channel, (int)id);
}
db.Close();
}
/// <summary>
/// Удалить сет из локальной БД
/// </summary>
/// <param name="setIndex"></param>
public void DeleteSet(string setName)
{
SQLiteDatabase db = WritableDatabase;
db.Delete(SETS_TABLE_NAME, KEY_SET_NAME + "=?", new string[1] { setName });
}
/// <summary>
/// Удалить канал из локальной БД
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public Channel GetChannel(int id)
{
SQLiteDatabase db = ReadableDatabase;
ICursor cursor = db.Query(CHANNELS_TABLE_NAME, new string[] { KEY_CHANNEL_ID, KEY_CHANNEL_NAME, KEY_CHANNEL_PLATFORM, KEY_CHANNEL_SET_ID }, KEY_CHANNEL_ID + "=?", new string[] { id.ToString() }, null, null, null, null);
if (cursor != null)
{
cursor.MoveToFirst();
}
// Канал найден
if (cursor.Count > 0)
{
Channel channel = new Channel(cursor.GetString(1), (DATA.Platforms)Int32.Parse(cursor.GetString(2)));
return channel;
}
return null;
}
/// <summary>
/// Полностью очистить локальную БД
/// </summary>
public void ClearDatabase()
{
SQLiteDatabase db = WritableDatabase;
try
{
db.Delete(SETS_TABLE_NAME, null, null);
} catch (Exception) {
};
try
{
db.Delete(CHANNELS_TABLE_NAME, null, null);
}
catch (Exception)
{
};
db.ExecSQL("UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='" + CHANNELS_TABLE_NAME + "'");
db.ExecSQL("UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='" + SETS_TABLE_NAME + "'");
}
/// <summary>
/// Отобразить содержимое локальной БД
/// </summary>
/// <returns></returns>
public ChannelsSetsList GetDataFromDB()
{
ChannelsSetsList setsList = new ChannelsSetsList();
SQLiteDatabase db;
try
{
db = ReadableDatabase;
} catch (Exception)
{
ClearDatabase();
return setsList;
}
// Работа с сетами
ICursor allSets = db.RawQuery("SELECT * FROM " + SETS_TABLE_NAME, null);
if (allSets.MoveToFirst())
{
String[] columnNames = allSets.GetColumnNames();
do
{
// Проходимся по каждому сету в таблице сетов и создаем новый объект сета
var a = allSets.GetString(allSets.GetColumnIndex(columnNames[0]));
setsList.AddSet(new ChannelsSet(allSets.GetString(allSets.GetColumnIndex(columnNames[1]))));
} while (allSets.MoveToNext());
}
// Работа с каналами
ICursor allChannels = db.RawQuery("SELECT * FROM " + CHANNELS_TABLE_NAME, null);
if (allChannels.MoveToFirst())
{
String[] columnNames = allChannels.GetColumnNames();
do
{
// Проходимся по каждому каналу в таблице каналов
var channelName = allChannels.GetString(allChannels.GetColumnIndex(columnNames[1]));
var channelPlatform = allChannels.GetString(allChannels.GetColumnIndex(columnNames[2]));
var channelSetIndex = allChannels.GetString(allChannels.GetColumnIndex(columnNames[3]));
Channel channel = new Channel(channelName, (DATA.Platforms)Int32.Parse(channelPlatform));
setsList.AddChannel(channel, Int32.Parse(channelSetIndex) - 1);
} while (allChannels.MoveToNext());
}
return setsList;
}
public String GetTableAsString(String tableName)
{
SQLiteDatabase db = ReadableDatabase;
String tableString = string.Format("Table {0}\n", tableName);
ICursor allRows = db.RawQuery("SELECT * FROM " + tableName, null);
if (allRows.MoveToFirst())
{
String[] columnNames = allRows.GetColumnNames();
do
{
foreach (String name in columnNames)
{
tableString += string.Format("{0}: {1}\n", name,
allRows.GetString(allRows.GetColumnIndex(name)));
}
tableString += "\n";
} while (allRows.MoveToNext());
}
return tableString;
}
//public void DeleteDatabase()
//{
// try
// {
// _context.DeleteDatabase(DATABASE_NAME);
// } catch (Exception)
// {
// Console.WriteLine("Unable to delete database");
// }
//}
}
} |
namespace hw7
{
public class StateBase
{
}
} |
using System;
using Bounce.Converters;
using Bounce.Pages;
using Xamarin.Forms;
namespace Bounce.Controls
{
public class BallItemCell : ViewCell
{
public BallItemCell()
{
Image ballI = new Image {
Aspect = Aspect.AspectFit,
VerticalOptions = LayoutOptions.Center
};
Image checkI = new Image {
VerticalOptions = LayoutOptions.Center
};
Grid mainG = new Grid {
Padding = new Thickness(AppStyle.Balls.LIST_ITEM_PADDING),
ColumnDefinitions = {
new ColumnDefinition { Width = GridLength.Star },
new ColumnDefinition { Width = GridLength.Auto }
}
};
mainG.Children.Add(ballI, 0, 0);
mainG.Children.Add(checkI, 1, 0);
View = mainG;
//Bindings
ballI.SetBinding(Image.SourceProperty, nameof(BallItem.Filename), converter: new FilenameImageValueConverter());
checkI.SetBinding(Image.SourceProperty, nameof(BallItem.IsSelected), converter: new CheckImageValueConverter());
}
}
}
|
#if false //#Ignore IDE状でエラー表示させ無くするために無効にしておく
// 単純なバネシミュレーション用モジュール。
// Burst対応するために、全てStructで定義している
using System;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace IzBone.Common {
static public partial class Math8 {
//# for (int i=1; i<=3; ++i) {
//# var iType0 = "float" + (i==1?"":i.ToString());
//# var iType1 = "double" + (i==1?"":i.ToString());
//# var iTypeUp0 = char.ToUpper(iType0[0]) + iType0.Substring(1);
//# var iTypeUp1 = char.ToUpper(iType1[0]) + iType1.Substring(1);
/** 単純なバネのシミュレーション。速度優先で、軽い処理で近似する */
public struct Spring_【iTypeUp0】 {
public float maxX, maxV; //!< 位置・速度最大値
public 【iType0】 x, v; //!< 位置と速度
public float kpm, vHL; //!< バネ係数/質量と速度半減期
/** 更新処理 */
public void update(float dt) {
// バネ振動による加速度と空気抵抗による半減期から、新しい速度を算出
var a = -x * kpm;
var newV = (v + a*dt) * calcHL(vHL, dt);
// 新しい速度に直線的に遷移したと仮定して、位置を更新
x += (v + newV)/2 * dt;
v = newV;
// 範囲情報でクリッピング
x = clamp(x, -maxX, maxX);
v = clamp(v, -maxV, maxV);
}
}
/** 単純なバネのシミュレーション。単振動部分を解析的に解くため、少し処理が重い */
public struct SpringDat_【iTypeUp1】 {
public double maxX, maxV; //!< 位置・速度最大値
public 【iType1】 x, v; //!< 位置と速度
public double omg, vHL; //!< 単振動角速度と速度半減期
/** 更新処理 */
public void update(double dt) {
// 現在の位置、速度から、単振動のためのパラメータを取得
var omgT0 = atan2( omg*x, v );
var len = x / sin( omgT0 );
// dt後の単振動による位置・速度を解析的に解く
var t = omg*dt + omgT0;
x = len * sin( t );
v = omg*len * cos( t );
// 半減期による減速を行う
v *= calcHL(vHL, dt);
// 範囲情報でクリッピング
x = clamp(x, -maxX, maxX);
v = clamp(v, -maxV, maxV);
}
}
//# }
} }
#endif //#Ignore
|
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;
namespace GUI_XML
{
public class Student:Person
{
public String MatriculationNumber { get; set; }
public int CreditPoints { get; set; }
public Student() { }
public Student(String SurName, String GivenName, double Height, genderType Gender,
eyeColorType eyeColor,String MatriculationNumber, int CreditPoints)
:base(SurName, GivenName, Height, Gender, eyeColor)
{
this.MatriculationNumber = MatriculationNumber;
this.CreditPoints = CreditPoints;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyStationary : Enemy
{
public override void ResetVariables()
{
base.ResetVariables();
m_agent.Warp(m_spawnPoint.transform.position);
m_duringRoutine = false;
}
[Header("Movement")]
public int projectileAmount = 5;
public int projectileAmountVariation = 2;
public float waitTimeBeforeNextShootSeries;
bool m_duringRoutine;
EnemyWeapon m_enemyWeapon;
int m_shooting = Animator.StringToHash("Shooting");
public override void Init()
{
base.Init();
}
public override void GetComponents()
{
base.GetComponents();
m_enemyWeapon = GetComponent<EnemyWeapon>();
}
public void Update()
{
if (RoomManager.instance.PlayerInCorridor || RoomManager.instance.PlayerCurrentRoom != roomIndex)
{
currentState = State.Idle;
return;
}
if (delayWaited == false && delayRoutine == false) // if we haven't waited for some delay when player came into room
StartCoroutine(WaitTimeCoroutine()); // we call routine to delay our enemy for some delay before being activated
if (!m_playerHealth.IsDead() && delayWaited && !m_health.IsDead()) // if player is not dead and we waited some delay
{
FaceTarget();
if (Vector3.Distance(m_playerTransform.position, transform.position) < attackRange && RoomManager.instance.PlayerInRoom) // if player is within range and player is in room
{
if (currentState != State.Attack && !m_duringRoutine) // if we are not in Attack state and nor during routine
StartCoroutine(ShootSeries()); // we start shoot series routine
}
}
}
IEnumerator ShootSeries()
{
currentState = State.Attack; // set state to Attack
m_duringRoutine = true; // set duringROutine bool to true
int amountToShoot = Random.Range(projectileAmount - projectileAmountVariation, projectileAmount + projectileAmountVariation + 1); // calculate how many projectile will be spawn
while (amountToShoot > 0 && m_playerRested && RoomManager.instance.PlayerInRoom) // while projectile amount is > 0
{
if(m_health.IsDead())
yield break;
AudioManager.instance.PlayClipAt("EnemyShoot", transform.position);
m_anim.SetTrigger(m_shooting);
m_enemyWeapon.ShootProjectile(m_playerTransform.position); // shoot projectile
amountToShoot--; // decrement by one
yield return new WaitForSeconds(attackRate); // wait for some delay and repeat while amount is > 0
}
StartCoroutine(WaitIdle()); // after enemy finish shooting we can optinally wait for few seconds for example to make enemy reload
}
IEnumerator WaitIdle()
{
currentState = State.Idle; // change state to idle
yield return new WaitForSeconds(waitTimeBeforeNextShootSeries); // wait for given time
currentState = State.Chase; // change state to Chase si we can attack again
m_duringRoutine = false; // set during routine to false
}
}
|
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Ejercicio
{
public class Peliculas
{
StreamReader fichero;
List<string> peliculas;
public Peliculas(){
peliculas = new List<string>();
}
public List<string> verLasPeliculas(){
//Ver peliculas
peliculas.Clear();
string aux;
fichero = File.OpenText("peliculas.txt");
do{
aux = fichero.ReadLine();
if (aux != null) peliculas.Add(aux);
}while (aux != null);
fichero.Close();
return peliculas;
}
public List<string> verLasPeliculasFiltradas(){
//Ver peliculas
peliculas.Clear();
string aux;
List<string> peliculasFiltradas = new List<string>();
fichero = File.OpenText("peliculas.txt");
do{
aux = fichero.ReadLine();
if (aux != null) peliculas.Add(aux);
}while (aux != null);
peliculasFiltradas = peliculasFiltradas.Union(peliculas).ToList();
fichero.Close();
return peliculasFiltradas;
}
public string buscador(string busqueda){
fichero = File.OpenText("Peliculas.txt");
string aux = "";
switch (busqueda){
case "Salir":
fichero.Close();
return "Cerrado Correctamente";
default:
do{
aux = fichero.ReadLine();
if (busqueda == aux)
return "La pelicula:\n" + busqueda + ". Fue encontrada";
else
return "No se encontro la pelicula";
}while (aux != null);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BottomBar.XamarinForms;
using ParPorApp.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ParPorApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SocialPage : BottomBarPage
{
public SocialPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
// if (Device.OS == TargetPlatform.Android)
// NavigationPage.SetTitleIcon(this, "ic_face.png");
// Setting Color of selected Text and Icon
BarTextColor = Color.FromHex("#43b05c");
FixedMode = true;
//Dark theme for bottom navigation bar
//BarTheme = BottomBarPage.BarThemeTypes.DarkWithAlpha;
//Children.Add(new HomePage() { Title = "Upcoming", Icon = "ic_home.png" });
//Children.Add(new SchedulePage() { Title = "Events", Icon = "ic_event_black.png" });
//Children.Add(new AccountGroupsPage() { Title = "Groups", Icon = "ic_group.png" });
//Children.Add(new JoinTeamPage() { Title = Title = "Join", Icon = "ic_message.png" });
//Children.Add(new UserProfilePage() { Title = "Profile", Icon = "ic_face.png" });
//NavigationPage.SetHasNavigationBar(this, false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace NetFrwk_Lib
{
public class Department
{
public int DeptNo { get; set; }
public string DeptName { get; set; }
public string Location { get; set; }
}
public class DataSource
{
SqlConnection Conn;
SqlCommand Cmd;
DataTable Dt;
public DataSource()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
}
public List<Department> GetDepartments()
{
List<Department> departments = new List<Department>();
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select * from Department";
SqlDataReader reader = Cmd.ExecuteReader();
Dt = new DataTable();
Dt.Load(reader);
reader.Close();
foreach (DataRow dr in Dt.Rows)
{
departments.Add(
new Department()
{
DeptNo =Convert.ToInt32(dr["DeptNo"]),
DeptName = dr["DeptName"].ToString(),
Location = dr["Location"].ToString()
}
);
}
Conn.Close();
Cmd.Dispose();
Conn.Dispose();
return departments;
}
}
}
|
namespace SentenceTheThief
{
using System;
public class StartUp
{
public static void Main()
{
string integerType = Console.ReadLine();
int receiveIDs = int.Parse(Console.ReadLine());
decimal thiefID = decimal.MinValue;
decimal years = 0.00M;
for (int i = 0; i < receiveIDs; i++)
{
decimal numberID = decimal.Parse(Console.ReadLine());
if (integerType == "sbyte")
{
if ((sbyte.MinValue <= numberID) && (numberID <= sbyte.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
if (integerType == "int")
{
if ((int.MinValue <= numberID) && (numberID <= int.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
if (integerType == "long")
{
if ((long.MinValue <= numberID) && (numberID <= long.MaxValue))
{
if (numberID > thiefID)
thiefID = numberID;
}
}
}
if (thiefID < 0)
{
years = (thiefID / -128M);
years = Math.Round(years, 2);
}
else
{
years = thiefID / 127;
}
years = Math.Ceiling(years);
if (years == 1)
Console.WriteLine($"Prisoner with id {thiefID} is sentenced to 1 year");
else
Console.WriteLine($"Prisoner with id {thiefID} is sentenced to {years} years");
}
}
}
|
using BHLD.Data.Infrastructure;
using BHLD.Data.Repositories;
using BHLD.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Services
{
public interface Ihu_shoes_sizeServices
{
hu_shoes_size Add(hu_shoes_size hu_Shoes_Size);
void Update(hu_shoes_size hu_Shoes_Size);
hu_shoes_size Delete(int id);
IEnumerable<hu_shoes_size> GetAll();
IEnumerable<hu_shoes_size> GetAllByPaging(int tag, int page, int pageSize, out int totalRow);
hu_shoes_size GetById(int id);
IEnumerable<hu_shoes_size> GetAllPaging(int page, int pageSize, out int totalRow);
void SaveChanges();
}
public class hu_shoes_sizeServices : Ihu_shoes_sizeServices
{
Ihu_shoes_sizeRepository _Shoes_SizeRepository;
IUnitOfWork _unitOfWork;
public hu_shoes_sizeServices(hu_shoes_sizeRepository hu_Shoes_SizeRepository, IUnitOfWork unitOfWork)
{
this._Shoes_SizeRepository = hu_Shoes_SizeRepository;
this._unitOfWork = unitOfWork;
}
public hu_shoes_size Add(hu_shoes_size hu_Shoes_Size)
{
return _Shoes_SizeRepository.Add(hu_Shoes_Size);
}
public hu_shoes_size Delete(int id)
{
return _Shoes_SizeRepository.Delete(id);
}
public IEnumerable<hu_shoes_size> GetAll()
{
return _Shoes_SizeRepository.GetAll(new string[] { "D" });
}
public IEnumerable<hu_shoes_size> GetAllByPaging(int tag, int page, int pageSize, out int totalRow)
{
return _Shoes_SizeRepository.GetAllByShoesSize(tag, page, pageSize, out totalRow);
}
public IEnumerable<hu_shoes_size> GetAllPaging(int page, int pageSize, out int totalRow)
{
return _Shoes_SizeRepository.GetMultiPaging(x => x.status, out totalRow, page, pageSize);
}
public hu_shoes_size GetById(int id)
{
return _Shoes_SizeRepository.GetSingleById(id);
}
public void SaveChanges()
{
_unitOfWork.Commit();
}
public void Update(hu_shoes_size hu_Shoes_Size)
{
_Shoes_SizeRepository.Update(hu_Shoes_Size);
}
}
}
|
using System;
using System.Collections.Generic;
using DFC.ServiceTaxonomy.GraphSync.Interfaces.Queries;
using DFC.ServiceTaxonomy.GraphSync.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using static DFC.ServiceTaxonomy.GraphSync.Helpers.DocumentHelper;
using static DFC.ServiceTaxonomy.GraphSync.Helpers.UniqueNumberHelper;
namespace DFC.ServiceTaxonomy.GraphSync.JsonConverters
{
public class NodeAndOutRelationshipsAndTheirInRelationshipsConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var data = JObject.Load(reader);
var properties = data
.ToObject<Dictionary<string, object>>()!
.Where(dictionary => !dictionary.Key.StartsWith("_"))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
string itemId = GetAsString(properties["id"]);
int startNodeId = GetNumber(itemId);
var relationships = new List<(IOutgoingRelationship outgoingRelationship, IEnumerable<IOutgoingRelationship> incomingRelationships)>();
var links = SafeCastToDictionary(data["_links"]);
foreach (var link in links.Where(lnk => lnk.Key != "self" && lnk.Key != "curies"))
{
List<Dictionary<string, object>> linkDictionaries = CanCastToList(link.Value) ?
SafeCastToList(link.Value) :
new List<Dictionary<string, object>> { SafeCastToDictionary(link.Value) };
foreach (var linkDictionary in linkDictionaries)
{
(_, Guid id) = GetContentTypeAndId((string)linkDictionary["href"]);
if (id == Guid.Empty)
{
continue;
}
int endNodeId = GetNumber(GetAsString(id));
int relationshipId = GetNumber(
GetAsString(id) + GetAsString(itemId));
var itemContentType = (string)linkDictionary["contentType"];
var outgoing = new OutgoingRelationship(new StandardRelationship
{
Type = link.Key.Replace("cont:", string.Empty), // e.g. hasPageLocation
StartNodeId = startNodeId,
EndNodeId = endNodeId,
Id = relationshipId
},
new StandardNode
{
Id = endNodeId,
Properties = new Dictionary<string, object>
{
{"ContentType", itemContentType},
{"id", id},
{"endNodeId", endNodeId}
},
Labels = new List<string> { itemContentType, "Resource" }
});
relationships.Add((outgoing, new List<OutgoingRelationship>()));
}
}
string contentType = (string)data["ContentType"]!;
var node = new StandardNode
{
Labels = new List<string> { contentType, "Resource" },
Properties = properties,
Id = startNodeId
};
return new NodeAndOutRelationshipsAndTheirInRelationships(node, relationships);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) => throw new NotImplementedException();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Blazor_WASM
{
public class AppStateContainer
{
public int ValueState { get; set; }
public event Action OnStateChanged;
/// <summary>
/// The method will be invoked by components to update the state</summary>
/// <param name="v"></param>
public void UpdateState(int v) {
ValueState = v;
// Raise the Event for Notification
NotifyStateChanged();
}
private void NotifyStateChanged() => OnStateChanged?.Invoke();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreateInteraction : MonoBehaviour
{
public InteractionManager im;
public Button Abut;
public Button Bbut;
public Button Cbut;
public GameObject TsShell;
public GameObject WolfieShell;
public Text prompt;
// Start is called before the first frame update
void Start()
{
im.chooseInteraction();
Abut.gameObject.SetActive(false);
Bbut.gameObject.SetActive(false);
Cbut.gameObject.SetActive(false);
prompt.gameObject.SetActive(false);
}
}
|
using Sentry.PlatformAbstractions;
namespace Sentry.Tests.Internals;
public class AgggregateExceptionTests
{
private static readonly string DefaultAggregateExceptionMessage = new AggregateException().Message;
[Fact]
public void AggregateException_GetRawMessage_Empty()
{
var exception = new AggregateException();
var rawMessage = exception.GetRawMessage();
Assert.Equal(DefaultAggregateExceptionMessage, rawMessage);
}
[Fact]
public void AggregateException_GetRawMessage_WithInnerExceptions()
{
var exception = GetTestAggregateException();
var rawMessage = exception.GetRawMessage();
Assert.Equal(DefaultAggregateExceptionMessage, rawMessage);
}
[SkippableFact]
public void AggregateException_GetRawMessage_DiffersFromMessage()
{
// Sanity check: The message should be different than the raw message, except on full .NET Framework.
// .NET, .NET Core, and Mono all override the Message property to append messages from the inner exceptions.
// .NET Framework does not.
Skip.If(RuntimeInfo.GetRuntime().IsNetFx());
var exception = GetTestAggregateException();
var rawMessage = exception.GetRawMessage();
Assert.NotEqual(exception.Message, rawMessage);
}
private static AggregateException GetTestAggregateException() =>
Assert.Throws<AggregateException>(() =>
{
var t1 = Task.Run(() => throw new Exception("Test 1"));
var t2 = Task.Run(() => throw new Exception("Test 2"));
Task.WaitAll(t1, t2);
});
}
|
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 备份服务器地址,IP 或域名
/// </summary>
public class JT808_0x8103_0x0017 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0017>
{
public override uint ParamId { get; set; } = 0x0017;
/// <summary>
/// 数据 长度
/// </summary>
public override byte ParamLength { get; set; }
/// <summary>
/// 备份服务器地址,IP 或域名
/// </summary>
public string ParamValue { get; set; }
public JT808_0x8103_0x0017 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0017 jT808_0x8103_0x0017 = new JT808_0x8103_0x0017();
jT808_0x8103_0x0017.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0017.ParamLength = reader.ReadByte();
jT808_0x8103_0x0017.ParamValue = reader.ReadString(jT808_0x8103_0x0017.ParamLength);
return jT808_0x8103_0x0017;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0017 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.Skip(1, out int skipPosition);
writer.WriteString(value.ParamValue);
int length = writer.GetCurrentPosition() - skipPosition - 1;
writer.WriteByteReturn((byte)length, skipPosition);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.RoleAuthorize
{
/// <summary>
/// 角色类型
/// </summary>
public enum RoleType
{
角色,
用户
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class splash : MonoBehaviour
{
bool slowed=false;
// Start is called before the first frame update
void Start()
{
slowed=false;
Time.timeScale=1f;
}
// Update is called once per frame
void Update()
{
}
public void SlowDown()
{
if(slowed)
{
Time.timeScale=1f;
slowed=false;
}
else
{
Time.timeScale=0.3f;
slowed=true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FacadePattern.Equipments
{
public class TheaterLights
{
private int _brightness;
public void Dim(int brightness)
{
_brightness = brightness;
Console.WriteLine($"Theater lights dimming on {_brightness}");
}
public void On()
{
_brightness = 10;
Console.WriteLine("Theater lights on");
}
}
}
|
using System.Net;
using System.Security;
using Enyim.Caching.Configuration;
using Microsoft.Extensions.Logging;
namespace Enyim.Caching.Memcached.Protocol.Binary
{
/// <summary>
/// A node which is used by the BinaryPool. It implements the binary protocol's SASL authentication mechanism.
/// </summary>
public class BinaryNode : MemcachedNode
{
readonly ILogger _logger;
readonly ISaslAuthenticationProvider _authenticationProvider;
public BinaryNode(EndPoint endpoint, ISocketPoolConfiguration config, ISaslAuthenticationProvider authenticationProvider) : base(endpoint, config)
{
this._authenticationProvider = authenticationProvider;
this._logger = Logger.CreateLogger<BinaryNode>();
}
/// <summary>
/// Authenticates the new socket before it is put into the pool.
/// </summary>
protected internal override PooledSocket CreateSocket()
{
var socket = base.CreateSocket();
if (this._authenticationProvider != null && !this.Authenticate(socket))
{
this._logger.LogError($"Authentication failed: {this.EndPoint}");
throw new SecurityException($"Authentication failed: {this.EndPoint}");
}
return socket;
}
/// <summary>
/// Implements memcached's SASL authenticate sequence (see the protocol docs for more details.)
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
bool Authenticate(PooledSocket socket)
{
SaslStep step = new SaslStart(this._authenticationProvider);
socket.Send(step.GetBuffer());
while (!step.ReadResponse(socket).Success)
{
// challenge-response authentication
if (step.StatusCode == 0x21)
{
step = new SaslContinue(this._authenticationProvider, step.Data);
socket.Send(step.GetBuffer());
}
// invalid credentials or other error
else
{
this._logger.LogWarning("Authentication failed, return code: 0x{0:x}", step.StatusCode);
return false;
}
}
return true;
}
}
}
#region [ License information ]
/* ************************************************************
*
* © 2010 Attila Kiskó (aka Enyim), © 2016 CNBlogs, © 2022 VIEApps.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace codeEval_longestWord_20160118
{
class Program
{
static void Main(string[] args)
{
string line = "tragic lines buzzwords out dishes difficult";
string[] allWords = line.Split(' ');
//int maxWord = allWords[0].Length;
int longestWord = Int32.MinValue;
int len = allWords.Length; //number of items in allWords array
for (int i = 0; i < len; i ++)
{
if (allWords[i].Length > longestWord)
{
longestWord = allWords[i].Length;
//Console.WriteLine(allWords[i]);
}
}
for (int j = 0; j < allWords.Length; j ++)
{
if (allWords[j].Length == longestWord)
{
Console.WriteLine(allWords[j]);
break;
}
}
Console.WriteLine("End of Program");
Console.ReadKey();
}
}
}
|
using FluentValidation;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
namespace SFA.DAS.ProviderCommitments.Web.Validators.Apprentice
{
public class DatalockConfirmRestartViewModelValidator :AbstractValidator<DatalockConfirmRestartViewModel>
{
public DatalockConfirmRestartViewModelValidator()
{
RuleFor(x => x.ProviderId).GreaterThan(0);
RuleFor(x => x.ApprenticeshipHashedId).NotEmpty();
RuleFor(x => x.SendRequestToEmployer).NotNull().WithMessage("Confirm if you want the employer to make these changes");
}
}
}
|
using DChild.Gameplay.Objects.Characters;
using DChild.Gameplay.Objects.Characters.Attributes;
namespace DChild.Gameplay.Player
{
public interface IPlayer : ICharacter
{
CharacterPhysics2D physics { get; }
PlayerAnimation animation { get; }
Inventory inventory { get; }
PlayerLevel characterLevel { get; }
IAmbrosia ambrosia { get; }
IMagicPoint magicPoint { get; }
IPlayerSkillEnabler skillEnabler { get; }
IPlayerCombat combat { get; }
PlayerSensors sensors { get; }
Attributes attributes { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SnowBLL.Validators.Users
{
public class UserMessages
{
public static string ID_NOTEMPTY = "Id cannot be empty";
public static string NAME_NOTEMPTY = "Name cannot be empty";
public static string PASSWORD_NOTEMPTY = "Password cannot be empty";
public static string PASSWORD_LENGTH = "Password should have at least 6 characters";
public static string EMAIL_NOTEMPTY = "Email cannot be empty";
public static string EMAIL_VALIDFORMAT = "Email invalid format";
public static string CODE_NOTEMPTY = "Code cannot be empty";
public static string CODE_4CHARACTERS = "Code should have 4 charcaters";
public static string CONFIRMATIONPASSWORD_EQUAL = "Passwords should be the same";
}
}
|
using _7DRL_2021.Behaviors;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021.Drawables
{
class DrawableGrunt : Drawable
{
SpriteReference SpriteBody;
SpriteReference SpriteWeapon;
public DrawableGrunt(string id, SpriteReference body, SpriteReference weapon) : base(id)
{
SpriteBody = body;
SpriteWeapon = weapon;
}
public override void Draw(ICurio curio, SceneGame scene, DrawPass pass)
{
var body = SpriteBody;
var alive = curio.GetBehavior<BehaviorAlive>();
if(alive.Armor > 0)
{
body = SpriteLoader.Instance.AddSprite($"{SpriteBody.FileName}_armor");
}
var center = curio.GetVisualPosition() + new Vector2(8, 8);
var offset = curio.GetOffset();
var color = curio.GetColor();
var angleBody = curio.GetVisualAngle();
scene.PushSpriteBatch(shader: scene.Shader, shaderSetup: (transform, projection) =>
{
scene.SetupColorMatrix(color);
});
scene.DrawSpriteExt(body, 0, center + offset - SpriteBody.Middle, SpriteBody.Middle, angleBody, new Vector2(1), SpriteEffects.None, Color.White, 0);
DrawDagger(curio, scene, pass);
DrawMace(curio, scene, pass);
scene.PopSpriteBatch();
}
private void DrawDagger(ICurio curio, SceneGame scene, DrawPass pass)
{
var center = curio.GetVisualPosition() + new Vector2(8, 8);
var offset = curio.GetOffset();
var angleBody = curio.GetVisualAngle();
var dagger = curio.GetBehavior<BehaviorDagger>();
if (dagger != null && !dagger.Upswing.Done)
{
var weaponAngle = (float)LerpHelper.QuadraticOut(0, 1, dagger.Upswing.Slide);
var weaponScale = (float)LerpHelper.QuadraticOut(0.5, 1.0, dagger.Upswing.Slide);
var weaponStartPos = Util.AngleToVector(angleBody + MathHelper.PiOver4 * 2) * 8;
var weaponEndPos = Util.AngleToVector(angleBody + MathHelper.PiOver4 * 3) * 10;
var weaponPos = center + offset + Vector2.Lerp(weaponStartPos, weaponEndPos, (float)LerpHelper.QuadraticOut(0, 1, dagger.Upswing.Slide));
scene.DrawSpriteExt(SpriteWeapon, 0, weaponPos - SpriteWeapon.Middle, SpriteWeapon.Middle, angleBody + weaponAngle, new Vector2(weaponScale), SpriteEffects.None, Color.White, 0);
}
}
private void DrawMace(ICurio curio, SceneGame scene, DrawPass pass)
{
var center = curio.GetVisualPosition() + new Vector2(8, 8);
var offset = curio.GetOffset();
var angleBody = curio.GetVisualAngle();
var mace = curio.GetBehavior<BehaviorMace>();
if (mace != null && (!mace.Upswing.Done || !mace.MaceReturn.Done))
{
var weaponAngle = (float)LerpHelper.QuadraticOut(0, 1, mace.Upswing.Slide);
var weaponScale = (float)LerpHelper.QuadraticOut(0.5, 1.0, mace.Upswing.Slide);
var weaponStartPos = Util.AngleToVector(angleBody + MathHelper.PiOver4 * 2) * 8;
var weaponEndPos = Util.AngleToVector(angleBody + MathHelper.PiOver4 * 3) * 10;
var weaponPos = center + offset + Vector2.Lerp(weaponStartPos, weaponEndPos, (float)LerpHelper.QuadraticOut(0, 1, mace.Upswing.Slide));
scene.DrawSpriteExt(SpriteWeapon, 0, weaponPos - SpriteWeapon.Middle, SpriteWeapon.Middle, angleBody + weaponAngle, new Vector2(weaponScale), SpriteEffects.None, Color.White, 0);
if(!mace.Upswing.Done)
{
mace.DrawMace(scene, weaponPos, Util.AngleToVector(mace.UpswingAngle) * (float)LerpHelper.QuadraticOut(0, 12, mace.MaceReturn.Slide), 2);
}
if(!mace.MaceReturn.Done)
{
var maceOffset = mace.MacePosition - weaponPos;
mace.DrawMace(scene, weaponPos, Vector2.Lerp(maceOffset, Vector2.Zero, (float)LerpHelper.QuadraticOut(0,1,mace.MaceReturn.Slide)), 8);
}
}
}
public override void DrawIcon(ICurio curio, SceneGame scene, Vector2 pos)
{
throw new NotImplementedException();
}
public override IEnumerable<DrawPass> GetDrawPasses()
{
yield return DrawPass.Creature;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using OrchardCore.Security.Permissions;
namespace DFC.ServiceTaxonomy.GraphSync
{
public class Permissions : IPermissionProvider
{
public static readonly Permission AdministerGraphs = new Permission("AdministerGraphs", "Administer graphs");
public Task<IEnumerable<Permission>> GetPermissionsAsync()
{
return Task.FromResult(GetPermissions());
}
public IEnumerable<PermissionStereotype> GetDefaultStereotypes()
{
return new[]
{
new PermissionStereotype
{
Name = "Administrator",
Permissions = GetPermissions()
}
};
}
private IEnumerable<Permission> GetPermissions()
{
return new[]
{
AdministerGraphs
};
}
}
}
|
using System;
using System.Collections.Generic;
using FluentAssertions;
using ILogging;
using Moq;
using NUnit.Framework;
using ServiceDeskSVC.Controllers.API;
using ServiceDeskSVC.DataAccess;
using ServiceDeskSVC.DataAccess.Models;
using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tasks;
using ServiceDeskSVC.Managers;
using ServiceDeskSVC.Managers.Managers;
namespace ServiceDeskSVC.Tests.Controllers
{
[TestFixture]
public class TaskControllerTest
{
// private TasksController _TaskController;
// private Mock<IHelpDeskTasksRepository> _helpDeskTaskRepository;
// private IHelpDeskTaskManager _helpDeskTaskManager;
// private Mock<ILogger> _logger;
// [SetUp]
// public void BeforeEach()
// {
// _helpDeskTaskRepository = new Mock<IHelpDeskTasksRepository>();
// _logger = new Mock<ILogger>();
// _helpDeskTaskManager = new HelpDeskTaskManager(_helpDeskTaskRepository.Object, _logger.Object);
// _TaskController = new TasksController(_helpDeskTaskManager, _logger.Object);
// }
// [Test]
// public void TestAddingNewTask_DoesntReturnNull_ReturnsNewTaskID()
// {
// // Arrange
// _helpDeskTaskRepository.Setup(x => x.CreateTask(It.IsAny<HelpDesk_Tasks>()))
// .Returns(PostTask_ResultFromPostReturnInt());
// // Act
// var postTaskTypeID = _TaskController.Post(PostTask());
// // Assert
// Assert.IsNotNull(postTaskTypeID, "Result is null");
// postTaskTypeID.ShouldBeEquivalentTo(1);
// }
// [Test]
// public void TestEditingTask_DoesntReturnNull_ReturnsSameTaskTypeID()
// {
// //Arrange
// _helpDeskTaskRepository.Setup(
// x => x.EditTask(It.IsAny<int>(), It.IsAny<HelpDesk_Tasks>()))
// .Returns(PutTask_ResultFromPutReturnInt());
// //Act
// var putTaskID = _TaskController.Put(1, PutTask());
// //Assert
// Assert.IsNotNull(putTaskID, "Result is null");
// putTaskID.ShouldBeEquivalentTo(1);
// }
// [Test]
// public void TestDeleteTaskType_ReturnedTrue()
// {
// //Arrange
// _helpDeskTaskRepository.Setup(x => x.DeleteTask(It.IsAny<int>())).Returns(true);
// //Act
// var isDeleted = _TaskController.Delete(1);
// //Assert
// Assert.IsTrue(isDeleted);
// }
// private List<HelpDesk_Tasks> GetTaskList()
// {
// var TaskValues = new List<HelpDesk_Tasks>
// {
// new HelpDesk_Tasks
// {
// Id = 1,
// Title = "Sample Task 1",
// Description = "Sample Description 1",
// AssignedTo = 1,
// CreatedDateTime = new DateTime(2014, 9, 3),
// TicketID = 1,
// HelpDesk_TaskStatus = new HelpDesk_TaskStatus(){Status = "Open"},
// StatusID = 1,
// HelpDesk_Tickets = new HelpDesk_Tickets()
// {
// Id = 1,
// Title = "Ticket 1",
// RequestDateTime = DateTime.Now
// }
// },
// new HelpDesk_Tasks()
// {
// Id = 2,
// Title = "Sample Ticket 1",
// Description = "Sample Description 1",
// AssignedTo = 1,
// CreatedDateTime = new DateTime(2014, 12, 3),
// TicketID = 1,
// HelpDesk_TaskStatus = new HelpDesk_TaskStatus(){Status = "Closed"},
// StatusID = 2,
// HelpDesk_Tickets = new HelpDesk_Tickets()
// {
// Id = 1,
// Title = "Ticket 1",
// RequestDateTime = DateTime.Now
// }
//}
// };
// return TaskValues;
// }
// private List<HelpDesk_Tasks_View_vm> GetTaskList_ResultForMappingToVM()
// {
// var TaskValues_Result = new List<HelpDesk_Tasks_View_vm>
// {
// new HelpDesk_Tasks_View_vm
// {
// Id = 1,
// Title = "Sample Task 1",
// Description = "Sample Description 1",
// AssignedTo = 1,
// CreatedDateTime = new DateTime(2014, 9, 3),
// TicketID = 1,
// Status= "Open"
// },
// new HelpDesk_Tasks_View_vm
// {
// Id = 2,
// Title = "Sample Ticket 1",
// Description = "Sample Description 1",
// AssignedTo = 1,
// CreatedDateTime = new DateTime(2014, 12, 3),
// TicketID = 1,
// Status = "Closed"
// }
// };
// return TaskValues_Result;
// }
// private HelpDesk_Tasks_vm PostTask()
// {
// return new HelpDesk_Tasks_vm
// {
// Id = 2,
// Title = "Sample Ticket 1",
// Description = "Sample Description 1",
// AssignedTo = 1,
// CreatedDateTime = DateTime.Now,
// TicketID = 1,
// StatusID = 2
// };
// }
// private int PostTask_ResultFromPostReturnInt()
// {
// return 1;
// }
// private HelpDesk_Tasks_vm PutTask()
// {
// return new HelpDesk_Tasks_vm
// {
// Id = 1,
// };
// }
// private int PutTask_ResultFromPutReturnInt()
// {
// return 1;
// }
}
}
|
using UnityEngine;
using System.Collections;
public class Parallaxing : MonoBehaviour {
public Transform[] backgrounds; // array list of all the backgrounds and foregrounds to be parallaxed
public float[] parallaxScales; //the porportion of the camaras to move the backgrounds by
public float smoothing= 1f; //how smooth the paralax is going to be. Must be set above 0
private Transform cam;
private Vector3 previousCamPos; //will store the previous position of the camara being parallaxed
//called before start
void Awake()
{
cam = Camera.main.transform;
}
// Use this for initialization
void Start () {
//the previous cam position has the current cam position
previousCamPos = cam.position;
parallaxScales = new float[backgrounds.Length];
//assigning corresponding index to parallaxed position
for(int i =0; i <backgrounds.Length; i++){
parallaxScales[i] = backgrounds[i].position.z * -1;
}
}
// Update is called once per frame
void Update () {
for (int i = 0; i < backgrounds.Length; i++)
{
float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i];
float backgroundTargetPosX = backgrounds[i].position.x + parallax;
Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);
backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);
}
previousCamPos = cam.position;
}
}
|
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using GooglePlayGames.BasicApi;
using UnityEngine.SceneManagement;
public class Botoes : MonoBehaviour
{
// Use this for initialization
void Start(){
//PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate ();
// authenticate user:
Social.localUser.Authenticate((bool success) => {
// handle success or failure
if(success){
print("yay");
}
else{
print("oh no");
}
});
}
public void OpenLeaderBoard(){
PlayGamesPlatform.Instance.ShowLeaderboardUI("CgkIxLn4os8TEAIQCQ");
}
public void OpenAchievements(){
Social.ShowAchievementsUI();
//PlayGamesPlatform.Instance.ShowAchievementsUI;
}
// Update is called once per frame
public void Play ()
{
SceneManager.LoadScene ("Main");
}
public void Update ()
{
if (Input.GetKeyUp (KeyCode.Escape)) {
Application.Quit ();
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UsbBackupper
{
public partial class FormRemove : Form
{
private UsbInfoList usbInfoList;
public FormRemove()
{
InitializeComponent();
}
private void FormRemove_Load(object sender, EventArgs e)
{
usbInfoList = UsbInfoList.Deserialize() ?? new UsbInfoList();
foreach (var usb in usbInfoList)
{
comboBoxRemove.Items.Add(usb.VolumeLabel);
}
if (comboBoxRemove.Items.Count < 1) return;
comboBoxRemove.SelectedIndex = 0;
}
private void buttonRemove_Click(object sender, EventArgs e)
{
try
{
var deletedDrive = usbInfoList[comboBoxRemove.SelectedIndex];
usbInfoList.RemoveAt(comboBoxRemove.SelectedIndex);
if (checkBoxRemoveDelete.Checked)
{
Task.Factory.StartNew(() => { Directory.Delete(deletedDrive.BackupPath, true); });
}
var drives = DriveInfo.GetDrives();
drives = drives.Where(d => d.DriveType != DriveType.CDRom).ToArray();
try
{
File.Delete(drives.First(drive => drive.VolumeLabel == deletedDrive.VolumeLabel).RootDirectory + "UsbBackupper.bck");
}
catch
{
// ignored
}
finally
{
Close();
}
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("Impossibile cancellare i backup\nprobabilmente sono gia stati eliminati");
Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace PayRoll
{
public class LoginClass
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
public bool authentication(LoginClass login)
{
bool issuccess;
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,Password from Login where UserName='"+login.UserName+"' and Password='"+login.Password+"'",con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
issuccess = true;
}
else
{
issuccess = false;
}
return issuccess;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Spool.Harlowe
{
abstract class Collection : RenderableData, IEnumerable<Data>
{
public abstract int Count { get; }
public IEnumerator<Data> GetEnumerator() {
for (int i = 0; i < Count; i++) {
yield return GetIndex(i);
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
protected abstract bool SupportsIndexing { get; }
protected abstract Data GetIndex(int index);
private Data CheckIndexing(Data obj) => SupportsIndexing ? obj : throw new NotSupportedException();
protected abstract Data Create(IEnumerable<Data> values);
private int NormalizeIndex(Number num)
{
var i = (int)num.Value;
if (i == 0) {
throw new NotSupportedException("You can't access elements at position 0");
}
if (i < 0) {
return Count + i;
} else {
return i - 1;
}
}
public override Data Member(Data member)
{
return member switch {
Number idx => CheckIndexing(GetIndex(NormalizeIndex(idx))),
String str => str.Value switch {
"length" => new Number(Count),
"last" => CheckIndexing(GetIndex(Count - 1)),
"all" => new Checker(this, x => !x.Contains(false)),
"any" => new Checker(this, x => x.Contains(true)),
_ => base.Member(member)
},
Array selector => SupportsIndexing ? Create(
selector.Select(x => GetIndex(NormalizeIndex(x as Number ??
throw new NotSupportedException("Selector must only contain numbers")
)))
) : throw new NotSupportedException(),
_ => base.Member(member)
};
}
}
class Checker : Data
{
private readonly Collection testValues;
private readonly Func<IEnumerable<bool>, bool> aggregator;
public override bool Serializable => throw new NotImplementedException();
public Checker(Collection testValues, Func<IEnumerable<bool>, bool> aggregator)
{
this.testValues = testValues;
this.aggregator = aggregator;
}
public bool TestSwapped(TestOperator op, Data lhs) =>
aggregator(testValues.Select(x => lhs.Test(op, x)));
public override bool Test(TestOperator op, Data rhs) =>
aggregator(testValues.Select(x => x.Test(op, rhs)));
protected override string GetString() => "an 'any' or 'all' expression";
protected override object GetObject() => this;
public override bool Equals(Data other) => false;
}
abstract class DataCollection : Collection, ICollection<Data>
{
public override bool Serializable => true;
public DataCollection(IEnumerable<Data> value) => this.value = value.ToArray();
protected override object GetObject() => this;
protected override string GetString() => string.Join(",", this);
private readonly Data[] value;
public override int Count => value.Length;
protected override Data GetIndex(int index) => value[index];
protected int IndexOf(Data item) => ((IList<Data>)value).IndexOf(item);
bool ICollection<Data>.IsReadOnly => true;
public override int GetHashCode() => this.Aggregate(
GetType().GetHashCode(),
(x, data) => (x * 51) + data.GetHashCode()
);
public override bool Equals(Data other) => other is DataCollection a && value.SequenceEqual(a.value);
public override Data Operate(Operator op, Data rhs)
{
return rhs switch {
DataCollection a => op switch {
Operator.Add => Create(value.Concat(a.value)),
Operator.Subtract => Create(value.Where(x => !a.Contains(x))),
_ => base.Operate(op, rhs)
},
_ => base.Operate(op, rhs)
};
}
public override IEnumerable<Data> Spread() => value;
public override bool Test(TestOperator op, Data rhs)
{
if (rhs is Checker) {
return base.Test(op, rhs);
}
return op switch {
TestOperator.Contains => Contains(rhs),
TestOperator.Matches => rhs is DataCollection other
&& other.Count == Count
&& this.Zip(other, (a,b) => a.Test(op, b)).All(x => x),
_ => base.Test(op, rhs)
};
}
void ICollection<Data>.Add(Data item) => throw new NotSupportedException();
void ICollection<Data>.Clear() => throw new NotSupportedException();
public bool Contains(Data item) => ((IList<Data>)value).Contains(item);
public void CopyTo(Data[] array, int arrayIndex) => value.CopyTo(array, arrayIndex);
bool ICollection<Data>.Remove(Data item) => throw new NotSupportedException();
}
} |
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Overlay.NET.Common;
namespace Overlay.NET.Directx {
public class DirectXOverlayWindow {
/// <summary>
/// Gets a value indicating whether this instance is disposing.
/// </summary>
/// <value>
/// <c>true</c> if this instance is disposing; otherwise, <c>false</c>.
/// </value>
public bool IsDisposing { get; private set; }
/// <summary>
/// Gets a value indicating whether [parent window exists].
/// </summary>
/// <value>
/// <c>true</c> if [parent window exists]; otherwise, <c>false</c>.
/// </value>
public bool ParentWindowExists { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is top most.
/// </summary>
/// <value>
/// <c>true</c> if this instance is top most; otherwise, <c>false</c>.
/// </value>
public bool IsTopMost { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is visible.
/// </summary>
/// <value>
/// <c>true</c> if this instance is visible; otherwise, <c>false</c>.
/// </value>
public bool IsVisible { get; private set; }
/// <summary>
/// Gets the x.
/// </summary>
/// <value>
/// The x.
/// </value>
public int X { get; private set; }
/// <summary>
/// Gets the y.
/// </summary>
/// <value>
/// The y.
/// </value>
public int Y { get; private set; }
/// <summary>
/// Gets the width.
/// </summary>
/// <value>
/// The width.
/// </value>
public int Width { get; private set; }
/// <summary>
/// Gets the height.
/// </summary>
/// <value>
/// The height.
/// </value>
public int Height { get; private set; }
/// <summary>
/// Gets the handle.
/// </summary>
/// <value>
/// The handle.
/// </value>
public IntPtr Handle { get; private set; }
/// <summary>
/// Gets the parent window.
/// </summary>
/// <value>
/// The parent window.
/// </value>
public IntPtr ParentWindow { get; }
/// <summary>
/// The margin
/// </summary>
private Native.RawMargin _margin;
/// <summary>
/// The graphics
/// </summary>
public Direct2DRenderer Graphics;
/// <summary>
/// Makes a transparent Fullscreen window
/// </summary>
/// <param name="limitFps">VSync</param>
/// <exception cref="Exception">Could not create OverlayWindow</exception>
public DirectXOverlayWindow(bool limitFps = true) {
IsDisposing = false;
IsVisible = true;
IsTopMost = true;
ParentWindowExists = false;
X = 0;
Y = 0;
Width = Native.GetSystemMetrics(WindowConstants.SmCxScreen);
Height = Native.GetSystemMetrics(WindowConstants.SmCyScreen);
ParentWindow = IntPtr.Zero;
if (!CreateWindow()) {
throw new Exception("Could not create OverlayWindow");
}
Graphics = new Direct2DRenderer(Handle, limitFps);
SetBounds(X, Y, Width, Height);
}
/// <summary>
/// Makes a transparent window which adjust it's size and position to fit the parent window
/// </summary>
/// <param name="parent">HWND/Handle of a window</param>
/// <param name="limitFps">VSync</param>
/// <exception cref="Exception">
/// The handle of the parent window isn't valid
/// or
/// Could not create OverlayWindow
/// </exception>
public DirectXOverlayWindow(IntPtr parent, bool limitFps = true) {
if (parent == IntPtr.Zero) {
throw new Exception("The handle of the parent window isn't valid");
}
Native.Rect bounds;
Native.GetWindowRect(parent, out bounds);
IsDisposing = false;
IsVisible = true;
IsTopMost = true;
ParentWindowExists = true;
X = bounds.Left;
Y = bounds.Top;
Width = bounds.Right - bounds.Left;
Height = bounds.Bottom - bounds.Top;
ParentWindow = parent;
if (!CreateWindow()) {
throw new Exception("Could not create OverlayWindow");
}
Graphics = new Direct2DRenderer(Handle, limitFps);
SetBounds(X, Y, Width, Height);
Task.Run(() => ParentServiceThread());
}
/// <summary>
/// Finalizes an instance of the <see cref="DirectXOverlayWindow" /> class.
/// </summary>
~DirectXOverlayWindow() {
Dispose();
}
/// <summary>
/// Clean up used ressources and destroy window
/// </summary>
public void Dispose() {
IsDisposing = true;
Graphics.Dispose();
Native.DestroyWindow(Handle);
}
/// <summary>
/// Creates a window with the information's stored in this class
/// </summary>
/// <returns>
/// true on success
/// </returns>
private bool CreateWindow() {
Handle = Native.CreateWindowEx(
WindowConstants.WindowExStyleDx,
WindowConstants.DesktopClass,
"",
WindowConstants.WindowStyleDx,
X,
Y,
Width,
Height,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
ExtendFrameIntoClient();
return true;
}
/// <summary>
/// resize and set new position if the parent window's bounds change
/// </summary>
private void ParentServiceThread() {
while (!IsDisposing) {
Thread.Sleep(10);
Native.Rect bounds;
Native.GetWindowRect(ParentWindow, out bounds);
if (X != bounds.Left || Y != bounds.Top || Width != bounds.Right - bounds.Left ||
Height != bounds.Bottom - bounds.Top) {
SetBounds(bounds.Left, bounds.Top, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
}
}
}
/// <summary>
/// Extends the frame into client.
/// </summary>
private void ExtendFrameIntoClient() {
_margin.cxLeftWidth = X;
_margin.cxRightWidth = Width;
_margin.cyBottomHeight = Height;
_margin.cyTopHeight = Y;
Native.DwmExtendFrameIntoClientArea(Handle, ref _margin);
}
/// <summary>
/// Sets the position.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public void SetPos(int x, int y) {
X = x;
Y = y;
Native.Point pos;
pos.X = x;
pos.Y = y;
Native.Point size;
size.X = Width;
size.Y = Height;
Native.UpdateLayeredWindow(Handle, IntPtr.Zero, ref pos, ref size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero,
0);
ExtendFrameIntoClient();
}
/// <summary>
/// Sets the size.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public void SetSize(int width, int height) {
Width = width;
Height = height;
Native.Point pos;
pos.X = X;
pos.Y = Y;
Native.Point size;
size.X = Width;
size.Y = Height;
Native.UpdateLayeredWindow(Handle, IntPtr.Zero, ref pos, ref size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero,
0);
Graphics.AutoResize(Width, Height);
ExtendFrameIntoClient();
}
/// <summary>
/// Sets the bounds.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public void SetBounds(int x, int y, int width, int height) {
X = x;
Y = y;
Width = width;
Height = height;
Native.Point pos;
pos.X = x;
pos.Y = y;
Native.Point size;
size.X = Width;
size.Y = Height;
Native.UpdateLayeredWindow(Handle, IntPtr.Zero, ref pos, ref size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero,
0);
Graphics?.AutoResize(Width, Height);
ExtendFrameIntoClient();
}
/// <summary>
/// Shows this instance.
/// </summary>
public void Show() {
if (IsVisible) {
return;
}
Native.ShowWindow(Handle, WindowConstants.SwShow);
IsVisible = true;
ExtendFrameIntoClient();
}
/// <summary>
/// Hides this instance.
/// </summary>
public void Hide() {
if (!IsVisible) {
return;
}
Native.ShowWindow(Handle, WindowConstants.SwHide);
IsVisible = false;
}
private class OverlayForm : Form
{
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("dwmapi.dll")]
public static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref int[] pMargins);
//Styles
public const UInt32 SWP_NOSIZE = 0x0001;
public const UInt32 SWP_NOMOVE = 0x0002;
public const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
public static IntPtr HWND_TOPMOST = new IntPtr(-1);
public OverlayForm()
{
int initialStyle = GetWindowLong(this.Handle, -20);
SetWindowLong(this.Handle, -20, initialStyle | 0x80000 | 0x20);
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
OnResize(null);
InitializeComponent();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(284, 262);
this.DoubleBuffered = true;
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Form1";
this.Text = "Form1";
this.TopMost = true;
this.TransparencyKey = System.Drawing.Color.Black;
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
private void Form1_Load(object sender, EventArgs e)
{
this.DoubleBuffered = true;
this.Width = 1920;// set your own size
this.Height = 1080;
this.Location = new System.Drawing.Point(0, 0);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer |// this reduce the flicker
ControlStyles.AllPaintingInWmPaint |
ControlStyles.DoubleBuffer |
ControlStyles.UserPaint |
ControlStyles.Opaque |
ControlStyles.ResizeRedraw |
ControlStyles.SupportsTransparentBackColor, true);
this.TopMost = true;
this.Visible = true;
}
protected override void OnPaint(PaintEventArgs e)// create the whole form
{
int[] marg = new int[] { 0, 0, Width, Height };
DwmExtendFrameIntoClientArea(this.Handle, ref marg);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
[SerializeField]
float rotationSpeed;
[SerializeField]
float moveSpeed;
[SerializeField]
float zoomSpeed;
// Update is called once per frame
void Update()
{
//rotation
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(Vector3.up * rotationSpeed);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(Vector3.down * rotationSpeed);
}
//movement
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * moveSpeed);
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * moveSpeed);
//zoom
transform.Translate((Vector3.forward + transform.up * -1) * Input.mouseScrollDelta.y * zoomSpeed);
}
} |
using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Player
{
public class SlipperyGroundConfiguration: MonoBehaviour
{
public static MoveConfiguration m_walkConfig;
public static MoveConfiguration m_crouchConfig;
public static bool isIcePlatform;
void Start()
{
//m_walkConfig.m_acceleration = 100f;
//m_walkConfig.m_decceleration = 5f;
//m_walkConfig.m_maxSpeed = 15f;
//m_crouchConfig.m_acceleration = 100f;
//m_crouchConfig.m_decceleration = 5f;
//m_crouchConfig.m_maxSpeed = 10f;
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.transform.parent.parent.tag == "Player")
{
isIcePlatform = true;
}else
{
isIcePlatform = false;
}
}
void OnTriggerExit2D(Collider2D col)
{
if(col.transform.parent.parent.tag == "Player")
{
isIcePlatform = false;
}
}
}
}
|
namespace SubC.Attachments {
public enum AttachmentPhase {
Detached,
Attaching,
Attached,
Detaching,
Any = -1
}
public enum AttachObjectPhase {
Initial,
Joining,
Connecting,
Connected,
Disconnecting,
Leaving,
Left,
Any = -1
}
} |
using FamilyAccounting.Web.Interfaces;
using Microsoft.AspNetCore.Mvc;
using X.PagedList;
namespace FamilyAccounting.Web.Controllers
{
public class AuditController : Controller
{
private readonly IAuditWebService auditWebService;
public AuditController(IAuditWebService auditWebService)
{
this.auditWebService = auditWebService;
}
public IActionResult Index()
{
return View();
}
public IActionResult IndexActions(/*int Id, */int? page)
{
var pageNumber = page ?? 1;
var auditActions = auditWebService.GetActions();
var onePageOfAuditActions = auditActions.ToPagedList(pageNumber, 20);
ViewBag.onePageOfAuditActions = onePageOfAuditActions;
return View(auditActions);
}
public IActionResult IndexWallets(/*int Id, */int? page)
{
var pageNumber = page ?? 1;
var auditWallets = auditWebService.GetWallets();
var onePageOfAuditWallets = auditWallets.ToPagedList(pageNumber, 20);
ViewBag.onePageOfAuditWallets = onePageOfAuditWallets;
return View(auditWallets);
}
public IActionResult IndexPersons(/*int Id, */int? page)
{
var pageNumber = page ?? 1;
var auditPersons = auditWebService.GetPersons();
var onePageOfAuditPersons = auditPersons.ToPagedList(pageNumber, 20);
ViewBag.onePageOfAuditPersons = onePageOfAuditPersons;
return View(auditPersons);
}
}
}
|
using System;
using System.Collections.Generic;
namespace EPI.DynamicProgramming
{
/// <summary>
/// Every resident hates his next-door neighbors on both sides in a given town that has been arranged in a big circle around a well.
/// Unfortunately, the town's well is in disrepair and needs to be restored. Each of the town's residents is willing to donate a certain amount
/// which is listed in clockwise order around the well. However, nobody is willing to contribute to a fund to which his neighbor
/// has also contributed.
/// Next-door neighbors are always listed consecutively in donations, except that the first and last entries in donations are also for next-door neighbors.
/// Find the maximum amount of donations that can be collected.
/// </summary>
public static class BadNeighbors
{
public static int FindMaxDonations(int[] donations)
{
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();
int n = donations.Length;
for (int i = 0; i < n; i++)
{
if (i == 0)
{
l1.Add(donations[i]);
}
else if (i == n - 1)
{
l2.Add(donations[i]);
}
else
{
l1.Add(donations[i]);
l2.Add(donations[i]);
}
}
return Math.Max(findMax(l1), findMax(l2));
}
private static int findMax(List<int> list)
{
if (list.Count == 1)
return list[0];
if (list.Count == 2)
return Math.Max(list[0], list[1]);
if (list.Count == 3)
return Math.Max(list[0] + list[2], list[1]);
int[] dp = new int[list.Count];
dp[0] = list[0];
dp[1] = Math.Max(list[0], list[1]);
dp[2] = Math.Max(list[0] + list[2], list[1]);
int i;
for (i = 3; i < list.Count; i++)
{
dp[i] = Math.Max(list[i] + dp[i - 2], list[i - 1] + dp[i - 3]);
}
return dp[list.Count - 1];
}
}
}
|
using System.Collections.Generic;
using Podemski.Musicorum.BusinessLogic.Exceptions;
using Podemski.Musicorum.Core.Enums;
using Podemski.Musicorum.Interfaces.Entities;
using Podemski.Musicorum.Interfaces.Repositories;
using Podemski.Musicorum.Interfaces.SearchCriterias;
using Podemski.Musicorum.Interfaces.Services;
namespace Podemski.Musicorum.BusinessLogic.Services
{
internal sealed class TrackService : ITrackService
{
private readonly IRepository<ITrack> _trackRepository;
internal TrackService(IRepository<ITrack> trackRepository)
{
_trackRepository = trackRepository;
}
public void Save(ITrack track)
{
_trackRepository.Save(track);
}
public void Delete(ITrack track)
{
if (!_trackRepository.Exists(track.Id))
{
throw new NotFoundException(track.Id, "track");
}
_trackRepository.Delete(track.Id);
}
public ITrack Get(int trackId)
{
if (!_trackRepository.Exists(trackId))
{
throw new NotFoundException(trackId, "track");
}
return _trackRepository.Get(trackId);
}
public IEnumerable<ITrack> Find(SearchCriteria searchCriteria)
{
return _trackRepository.Find(IsMatch);
bool IsMatch(ITrack track)
{
return track.Title.Contains(searchCriteria.Name)
&& (searchCriteria.Genre == track.Album.Genre || searchCriteria.Genre == Genre.All)
&& (searchCriteria.AlbumVersion == AlbumVersion.None || (track.Album.IsDigital && searchCriteria.AlbumVersion == AlbumVersion.Digital) || (!track.Album.IsDigital && searchCriteria.AlbumVersion == AlbumVersion.Physical));
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Text scoreText;
public Text timeText;
public float startTime;
public int currentScore;
private void Start()
{
startTime = Time.time;
currentScore = 0;
}
public void AddPoints(int points) {
currentScore += points;
}
public void SetTime() {
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = ((int) (t % 60)).ToString();
timeText.text = minutes + ":" + seconds;
}
// Update is called once per frame
void Update()
{
SetTime();
scoreText.text = "Score: " + currentScore;
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Ardalis.ApiEndpoints;
using AutoMapper;
using BlazorShared.Models.Doctor;
using ClinicManagement.Core.Aggregates;
using Microsoft.AspNetCore.Mvc;
using PluralsightDdd.SharedKernel.Interfaces;
using Swashbuckle.AspNetCore.Annotations;
namespace ClinicManagement.Api.DoctorEndpoints
{
public class Update : BaseAsyncEndpoint
.WithRequest<UpdateDoctorRequest>
.WithResponse<UpdateDoctorResponse>
{
private readonly IRepository _repository;
private readonly IMapper _mapper;
public Update(IRepository repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
[HttpPut("api/doctors")]
[SwaggerOperation(
Summary = "Updates a Doctor",
Description = "Updates a Doctor",
OperationId = "doctors.update",
Tags = new[] { "DoctorEndpoints" })
]
public override async Task<ActionResult<UpdateDoctorResponse>> HandleAsync(UpdateDoctorRequest request, CancellationToken cancellationToken)
{
var response = new UpdateDoctorResponse(request.CorrelationId());
var toUpdate = _mapper.Map<Doctor>(request);
await _repository.UpdateAsync<Doctor, int>(toUpdate);
var dto = _mapper.Map<DoctorDto>(toUpdate);
response.Doctor = dto;
return Ok(response);
}
}
}
|
using DChild.Gameplay.Combat;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChild.Gameplay.Objects.Characters.Enemies
{
public class DeformedCultistBrain : MinionAIBrain<DeformedCultist>
{
[SerializeField]
[MinValue(0f)]
private float m_spellRange;
private bool m_isSpellActive;
private PatrolHandler m_patrol;
public override void Enable(bool value)
{
throw new System.NotImplementedException();
}
public override void ResetBrain()
{
m_isSpellActive = false;
}
public override void SetTarget(IDamageable target)
{
throw new System.NotImplementedException();
}
private void Patrol()
{
var destination = m_patrol.GetInfo(m_minion.position).destination;
if (IsLookingAt(destination))
{
m_minion.MoveTo(destination);
}
else
{
m_minion.Turn();
}
}
protected override void Awake()
{
base.Awake();
m_patrol = GetComponent<PatrolHandler>();
}
private void Update()
{
if (m_minion.waitForBehaviourEnd)
return;
if(m_target == null)
{
Patrol();
}
else
{
if (m_isSpellActive)
{
m_minion.Taunt();
}
else if(Vector2.Distance(m_minion.position,m_target.position) <= m_spellRange)
{
if (IsLookingAt(m_target.position))
{
m_minion.CastSpellAt(m_target);
}
else
{
m_minion.Turn();
}
}
else
{
Patrol();
}
}
}
}
} |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace STUFV
{
public partial class MainPage : MasterDetailPage
{
public MainPage ()
{
InitializeComponent ();
Detail = new NavigationPage (new ContentPage ());
this.IsPresented = true;
}
public void onClick1(object sender,EventArgs e)
{
Detail = new NavigationPage (new EventOverviewView ());
this.IsPresented = false;
}
public void onClick2(object sender,EventArgs e)
{
Detail = new NavigationPage (new LifeSaversView ());
this.IsPresented = false;
}
public void onClick3(object sender,EventArgs e)
{
Detail = new NavigationPage (new TransportView ());
this.IsPresented = false;
}
public void onClick4(object sender,EventArgs e)
{
Detail = new NavigationPage (new InfoView ());
this.IsPresented = false;
}
public void onClick5(object sender,EventArgs e)
{
Detail = new NavigationPage (new AlcoholView ());
this.IsPresented = false;
}
public void onClick6(object sender,EventArgs e)
{
Detail = new NavigationPage (new NewsOverviewView ());
this.IsPresented = false;
}
public void onClick7(object sender,EventArgs e)
{
Detail = new NavigationPage (new SettingsView ());
this.IsPresented = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Inventory.Data;
using Inventory.Models;
namespace Inventory.Services
{
public class OrderDishModifierService : IOrderDishModifierService
{
private IDataServiceFactory DataServiceFactory { get; }
public OrderDishModifierService(IDataServiceFactory dataServiceFactory)
{
DataServiceFactory = dataServiceFactory;
}
public async Task<IList<ModifierModel>> GetRelatedDishModifiersAsync(Guid dishGuid)
{
IList<ModifierModel> models = new List<ModifierModel>();
using (var dataService = DataServiceFactory.CreateDataService())
{
var entities = await dataService.GetRelatedDishModifiersAsync(dishGuid);
foreach (var entity in entities)
{
var model = CreateModifierModelFromEntity(entity);
models.Add(model);
}
}
return models;
}
private ModifierModel CreateModifierModelFromEntity(Modifier entity)
{
if (entity == null)
{
return null;
}
return new ModifierModel
{
Id = entity.Id,
RowGuid = entity.RowGuid,
Name = entity.Name,
IsRequired = entity.IsRequired
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestingJsonDt
{
public class GroupMasterMoqs
{
public IEnumerable<GroupMaster> GetAll()
{
yield return new GroupMaster
{
Id = 1,
Name = "Voltage and Temperature",
JsonDtAsString = "[{\"Environemt\":\"Nominal\", \"Voltage\":3.5, \"Temperature\":25}," +
"{\"Environemt\":\"Extreme\", \"Voltage\":4.2, \"Temperature\":80}]"
};
}
}
}
|
using ISE.Framework.Common.Aspects;
using ISE.Framework.Common.Service.Wcf;
using ISE.SM.Common.DTO;
using ISE.SM.Common.DTOContainer;
using ISE.SM.Common.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace ISE.SM.Common.Contract
{
[ServiceContract(Namespace = "http://www.iseikco.com/Sec")]
public interface IAuthorizationService : IServiceContract
{
[OperationContract]
[Process]
AuthorizationResult CheckAccess(AuthorizationRequest request);
[OperationContract]
[Process]
SecurityResourceDtoContainer AccessList(Common.Message.AuthorizationRequest request);
[OperationContract]
[Process]
SecurityResourceDtoContainer MenuList(Common.Message.AuthorizationRequest request);
}
}
|
// This file is part of LAdotNET.
//
// LAdotNET is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LAdotNET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY, without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with LAdotNET. If not, see <https://www.gnu.org/licenses/>.
using LAdotNET.Network;
using LAdotNET.Network.Packets;
using System;
using System.Threading.Tasks;
namespace LAdotNET.GameServer.Network.Packets.Server
{
class SMPaidShopSettingNotify : Packet
{
public static byte[] ShopData = new byte[]
{
0x00, 0x01, 0x8B, 0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00,
0x45, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0xAC, 0xC2,
0x6F, 0xB8, 0x20, 0x00, 0x55, 0xD6, 0xA5, 0xC7, 0x8C, 0xAD, 0x9A, 0x00, 0x2D, 0x00, 0x20, 0x00,
0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4, 0x40, 0xC7, 0x20, 0x00, 0xD0, 0xC6,
0x15, 0xC8, 0x00, 0xB3, 0x20, 0x00, 0xC0, 0xAD, 0x8D, 0xC1, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4,
0x85, 0xC7, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00,
0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0xAC, 0xC2, 0x6F, 0xB8, 0x40, 0xC7, 0x20, 0x00,
0xD0, 0xC6, 0x15, 0xC8, 0x00, 0xB3, 0xF9, 0xB2, 0x20, 0x00, 0x5C, 0xCD, 0x00, 0xB3, 0x20, 0x00,
0x36, 0x00, 0x8C, 0xD6, 0x4C, 0xAE, 0xC0, 0xC9, 0x20, 0x00, 0x55, 0xD6, 0xA5, 0xC7, 0x20, 0x00,
0x00, 0xAC, 0xA5, 0xB2, 0x58, 0xD5, 0x70, 0xBA, 0x2C, 0x00, 0x20, 0x00, 0x74, 0xC7, 0xD0, 0xC5,
0x20, 0x00, 0x30, 0xB5, 0x7C, 0xB7, 0x20, 0x00, 0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0xC1, 0xC0,
0x88, 0xD4, 0x40, 0xC7, 0x20, 0x00, 0xD0, 0xC6, 0x15, 0xC8, 0x00, 0xB3, 0x20, 0x00, 0xF9, 0xB2,
0x20, 0x00, 0x5C, 0xCD, 0x00, 0xB3, 0x20, 0x00, 0x36, 0x00, 0x1C, 0xAC, 0x4C, 0xAE, 0xC0, 0xC9,
0xCC, 0xB9, 0x20, 0x00, 0x6C, 0xAD, 0xE4, 0xB9, 0x20, 0x00, 0x00, 0xAC, 0xA5, 0xB2, 0x69, 0xD5,
0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00, 0xC1, 0xC0,
0x88, 0xD4, 0x20, 0x00, 0x18, 0xC2, 0x39, 0xB8, 0x20, 0x00, 0xC4, 0xD6, 0x20, 0x00, 0x90, 0xCE,
0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0x20, 0xC1, 0xDD, 0xD0, 0x20, 0x00, 0x54, 0xD6, 0x74, 0xBA,
0xD0, 0xC5, 0x1C, 0xC1, 0x20, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0xAC, 0xC2,
0x6F, 0xB8, 0x44, 0xC7, 0x20, 0x00, 0x94, 0xCD, 0x00, 0xAC, 0xDC, 0xC2, 0xAC, 0xD0, 0x20, 0x00,
0x18, 0xC2, 0x20, 0x00, 0x88, 0xC7, 0x3C, 0xC7, 0x70, 0xBA, 0x2C, 0x00, 0x20, 0x00, 0x44, 0xC5,
0x74, 0xC7, 0x5C, 0xD1, 0x3C, 0xC7, 0x5C, 0xB8, 0x94, 0xB2, 0x20, 0x00, 0x8D, 0xD6, 0xDD, 0xB4,
0x18, 0xB4, 0xC0, 0xC9, 0x20, 0x00, 0x4A, 0xC5, 0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00,
0x09, 0x00, 0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x70, 0x00, 0x5F, 0x00, 0x69, 0x00, 0x63, 0x00,
0x6F, 0x00, 0x6E, 0x00, 0x6D, 0x01, 0x00, 0x00, 0x02, 0x45, 0x00, 0x00, 0x00, 0x0D, 0x01, 0x6C,
0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1F, 0x18, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x56, 0xC3, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0xC3, 0x40, 0x00, 0x0A, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01,
0x00, 0x8C, 0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE3, 0x57, 0x0F, 0x09, 0x3B, 0x00, 0x00,
0x00, 0x57, 0x03, 0x00, 0x00, 0x01, 0x8C, 0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x01, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x07, 0x00, 0xB8, 0xD2, 0xAC, 0xB9, 0xDC, 0xC2, 0x28, 0xC6, 0x20, 0x00, 0x28, 0xD3, 0xA4, 0xC2,
0xBC, 0x00, 0x2D, 0x00, 0x20, 0x00, 0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4,
0x40, 0xC7, 0x20, 0x00, 0xC4, 0xAC, 0x15, 0xC8, 0x20, 0x00, 0xC0, 0xAD, 0x8D, 0xC1, 0x20, 0x00,
0xC1, 0xC0, 0x88, 0xD4, 0x85, 0xC7, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00,
0x2D, 0x00, 0x20, 0x00, 0xB8, 0xD2, 0xAC, 0xB9, 0xDC, 0xC2, 0x28, 0xC6, 0x20, 0x00, 0x28, 0xD3,
0xA4, 0xC2, 0x94, 0xB2, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4, 0x20, 0x00, 0x18, 0xC2, 0x39, 0xB8,
0x20, 0x00, 0xDC, 0xC2, 0x20, 0x00, 0x74, 0xC7, 0xA9, 0xC6, 0x20, 0x00, 0x9F, 0xD6, 0x18, 0xC2,
0x00, 0xAC, 0x20, 0x00, 0x89, 0xC9, 0xDC, 0xC2, 0x20, 0x00, 0x9D, 0xC9, 0x00, 0xAC, 0x58, 0xD5,
0x70, 0xBA, 0x2C, 0x00, 0x20, 0x00, 0x44, 0xC5, 0x74, 0xC7, 0x5C, 0xD1, 0x3C, 0xC7, 0x5C, 0xB8,
0x94, 0xB2, 0x20, 0x00, 0x8D, 0xD6, 0xDD, 0xB4, 0x18, 0xB4, 0xC0, 0xC9, 0x20, 0x00, 0x4A, 0xC5,
0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00,
0xC4, 0xAC, 0x15, 0xC8, 0x20, 0x00, 0xB4, 0xB0, 0x20, 0x00, 0x04, 0xC8, 0x2C, 0xD2, 0x20, 0x00,
0x08, 0xB8, 0xA8, 0xBC, 0x20, 0x00, 0x35, 0x00, 0x30, 0x00, 0x44, 0xC7, 0x20, 0x00, 0xEC, 0xB2,
0x31, 0xC1, 0x5C, 0xD5, 0x20, 0x00, 0x01, 0xC8, 0x74, 0xC7, 0x20, 0x00, 0x88, 0xC7, 0xE0, 0xAC,
0x2C, 0x00, 0x20, 0x00, 0x04, 0xC8, 0xC1, 0xC9, 0x58, 0xD5, 0xC0, 0xC9, 0x20, 0x00, 0x4A, 0xC5,
0x40, 0xC7, 0x20, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0xD0, 0xC5, 0x20, 0x00, 0x5C, 0xD5,
0x74, 0xD5, 0x20, 0x00, 0xAC, 0xC0, 0xA9, 0xC6, 0x60, 0xD5, 0x20, 0x00, 0x18, 0xC2, 0x20, 0x00,
0x88, 0xC7, 0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00,
0x20, 0x00, 0x04, 0xC8, 0x2C, 0xD2, 0x20, 0x00, 0x08, 0xB8, 0xA8, 0xBC, 0x20, 0x00, 0x35, 0x00,
0x30, 0x00, 0x20, 0x00, 0xEC, 0xB2, 0x31, 0xC1, 0x20, 0x00, 0xC4, 0xD6, 0x2C, 0x00, 0x20, 0x00,
0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x7C, 0xB9, 0x20, 0x00,
0xAD, 0xC0, 0x1C, 0xC8, 0x5C, 0xD5, 0x20, 0x00, 0xBD, 0xAC, 0xB0, 0xC6, 0xD0, 0xC5, 0xC4, 0xB3,
0x20, 0x00, 0xB8, 0xD2, 0xAC, 0xB9, 0xDC, 0xC2, 0x28, 0xC6, 0x20, 0x00, 0x28, 0xD3, 0xA4, 0xC2,
0x7C, 0xB9, 0x20, 0x00, 0xAC, 0xC0, 0xA9, 0xC6, 0x60, 0xD5, 0x20, 0x00, 0x18, 0xC2, 0x20, 0x00,
0x88, 0xC7, 0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x09, 0x00, 0x53, 0x00, 0x68, 0x00,
0x6F, 0x00, 0x70, 0x00, 0x5F, 0x00, 0x69, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x70, 0x01,
0x00, 0x00, 0x03, 0x43, 0x00, 0x00, 0x00, 0x4F, 0x01, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x1F, 0x18, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0xE8, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x51, 0xE8, 0x40, 0x00, 0x0A, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x8B,
0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE3, 0x57, 0x0F, 0x09, 0x3B, 0x00, 0x00, 0x00, 0x3E,
0x10, 0x00, 0x00, 0x01, 0x5E, 0x42, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3F, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00,
0x78, 0xC6, 0x15, 0xD6, 0x20, 0x00, 0xC0, 0xBC, 0xBD, 0xAC, 0x8C, 0xAD, 0x72, 0x00, 0x2D, 0x00,
0x20, 0x00, 0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4, 0x40, 0xC7, 0x20, 0x00,
0xC4, 0xAC, 0x15, 0xC8, 0x20, 0x00, 0xC0, 0xAD, 0x8D, 0xC1, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4,
0x85, 0xC7, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00,
0xC1, 0xC0, 0x88, 0xD4, 0x20, 0x00, 0x18, 0xC2, 0x39, 0xB8, 0x20, 0x00, 0xDC, 0xC2, 0x20, 0x00,
0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0x78, 0xC6, 0x15, 0xD6, 0x20, 0x00, 0xC0, 0xBC,
0xBD, 0xAC, 0x20, 0x00, 0x00, 0xAC, 0xA5, 0xB2, 0x20, 0x00, 0x9F, 0xD6, 0x18, 0xC2, 0x00, 0xAC,
0x20, 0x00, 0x89, 0xC9, 0xDC, 0xC2, 0x20, 0x00, 0x9D, 0xC9, 0x00, 0xAC, 0x58, 0xD5, 0x70, 0xBA,
0x2C, 0x00, 0x20, 0x00, 0x44, 0xC5, 0x74, 0xC7, 0x5C, 0xD1, 0x3C, 0xC7, 0x5C, 0xB8, 0x94, 0xB2,
0x20, 0x00, 0x8D, 0xD6, 0xDD, 0xB4, 0x18, 0xB4, 0xC0, 0xC9, 0x20, 0x00, 0x4A, 0xC5, 0xB5, 0xC2,
0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00, 0x90, 0xCE,
0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0x78, 0xC6, 0x15, 0xD6, 0x20, 0x00, 0xC0, 0xBC, 0xBD, 0xAC,
0x40, 0xC7, 0x20, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0x20, 0xC1, 0xDD, 0xD0,
0x20, 0x00, 0x54, 0xD6, 0x74, 0xBA, 0xD0, 0xC5, 0x1C, 0xC1, 0x20, 0x00, 0x74, 0xC7, 0xA9, 0xC6,
0x60, 0xD5, 0x20, 0x00, 0x18, 0xC2, 0x20, 0x00, 0x88, 0xC7, 0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2,
0x2E, 0x00, 0x09, 0x00, 0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x70, 0x00, 0x5F, 0x00, 0x69, 0x00,
0x63, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x58, 0x00, 0x00, 0x00, 0x0F,
0x01, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1F, 0x18, 0x06, 0x00, 0x00, 0x00,
0x00, 0x00, 0x56, 0xC3, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0xC3, 0x40, 0x00, 0x0A, 0x00,
0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x5D, 0x42, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8B,
0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8C, 0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE2,
0xB7, 0x26, 0xD9, 0x11, 0x00, 0x00, 0x00, 0xE7, 0x07, 0x00, 0x00, 0x01, 0x5D, 0x42, 0x0F, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x08, 0x00,
0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x85, 0xBA, 0x20, 0x00, 0xC0, 0xBC, 0xBD, 0xAC, 0x8C, 0xAD,
0x6E, 0x00, 0x2D, 0x00, 0x20, 0x00, 0x74, 0xD5, 0xF9, 0xB2, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4,
0x40, 0xC7, 0x20, 0x00, 0xC4, 0xAC, 0x15, 0xC8, 0x20, 0x00, 0xC0, 0xAD, 0x8D, 0xC1, 0x20, 0x00,
0xC1, 0xC0, 0x88, 0xD4, 0x85, 0xC7, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00,
0x2D, 0x00, 0x20, 0x00, 0xC1, 0xC0, 0x88, 0xD4, 0x20, 0x00, 0x18, 0xC2, 0x39, 0xB8, 0x20, 0x00,
0xDC, 0xC2, 0x20, 0x00, 0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x85, 0xBA, 0x20, 0x00, 0xC0, 0xBC,
0xBD, 0xAC, 0x20, 0x00, 0x00, 0xAC, 0xA5, 0xB2, 0x20, 0x00, 0x9F, 0xD6, 0x18, 0xC2, 0x00, 0xAC,
0x20, 0x00, 0x89, 0xC9, 0xDC, 0xC2, 0x20, 0x00, 0x9D, 0xC9, 0x00, 0xAC, 0x58, 0xD5, 0x70, 0xBA,
0x2C, 0x00, 0x20, 0x00, 0x44, 0xC5, 0x74, 0xC7, 0x5C, 0xD1, 0x3C, 0xC7, 0x5C, 0xB8, 0x94, 0xB2,
0x20, 0x00, 0x8D, 0xD6, 0xDD, 0xB4, 0x18, 0xB4, 0xC0, 0xC9, 0x20, 0x00, 0x4A, 0xC5, 0xB5, 0xC2,
0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x0D, 0x00, 0x0A, 0x00, 0x2D, 0x00, 0x20, 0x00, 0x90, 0xCE,
0xAD, 0xB9, 0x30, 0xD1, 0x85, 0xBA, 0x20, 0x00, 0xC0, 0xBC, 0xBD, 0xAC, 0x40, 0xC7, 0x20, 0x00,
0x90, 0xCE, 0xAD, 0xB9, 0x30, 0xD1, 0x20, 0x00, 0x20, 0xC1, 0xDD, 0xD0, 0x20, 0x00, 0x54, 0xD6,
0x74, 0xBA, 0xD0, 0xC5, 0x1C, 0xC1, 0x20, 0x00, 0x74, 0xC7, 0xA9, 0xC6, 0x60, 0xD5, 0x20, 0x00,
0x18, 0xC2, 0x20, 0x00, 0x88, 0xC7, 0xB5, 0xC2, 0xC8, 0xB2, 0xE4, 0xB2, 0x2E, 0x00, 0x09, 0x00,
0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x70, 0x00, 0x5F, 0x00, 0x69, 0x00, 0x63, 0x00, 0x6F, 0x00,
0x6E, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x59, 0x00, 0x00, 0x00, 0x0F, 0x01, 0x6C, 0x17, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1F, 0x18, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0xD3,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0xD3, 0x40, 0x00, 0x0A, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x03, 0x00, 0x5E, 0x42, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x43, 0x0F, 0x00, 0x00,
0x00, 0x00, 0x00, 0x8C, 0x43, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE2, 0xB7, 0x26, 0xD9, 0x11,
0x00, 0x00, 0x00, 0xB9, 0x03, 0x00, 0x00
};
public SMPaidShopSettingNotify(Connection connection) : base(connection)
{
CompressionType = CompressionType.SNAPPY;
OpCode = PacketFactory.ReverseLookup[GetType()];
}
public override void Deserialize()
{
// Shop Data - .bt in progress
Data.WriteBytes(ShopData);
}
public override Task HandleAsync()
{
throw new NotImplementedException();
}
public override void Serialize()
{
throw new NotImplementedException();
}
}
}
|
using OnboardingSIGDB1.Domain._Base;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
namespace OnboardingSIGDB1.Data
{
public class ConsultaBase<TEntity, TDto>: IConsultaBase<TEntity, TDto>
where TEntity : class
{
private readonly DataContext _context;
private readonly ResultadoDaConsultaBase _resultado;
private readonly IMapper _mapper;
protected IQueryable<TEntity> Query { get; set; }
public ConsultaBase(DataContext context,
IMapper mapper)
{
_context = context;
_resultado = new ResultadoDaConsultaBase();
_mapper = mapper;
}
public virtual void PrepararQuery(Specification<TEntity> specification)
{
Query = _context.Set<TEntity>().Where(specification.Predicate);
}
public ResultadoDaConsultaBase Consultar(Specification<TEntity> specification)
{
PrepararQuery(specification);
if (specification.Order != null)
{
Query = ConfigurarOrdenacao(specification);
}
if (!specification.Page.HasValue)
{
var entities = Query.ToList();
_resultado.Lista = (IEnumerable<object>)_mapper.Map<IEnumerable<TDto>>(entities);
_resultado.Total = Query.Count();
}
else
{
var page = (specification.Page.Value - 1) >= 0 ? (specification.Page.Value - 1) : 0;
var total = page * specification.Size;
List<TEntity> entities;
_resultado.Total = Query.Count();
entities = Query.Skip(total).Take(specification.Size).ToList();
_resultado.Lista = (IEnumerable<object>)_mapper.Map<IEnumerable<TDto>>(entities);
}
return _resultado;
}
private IQueryable<TEntity> ConfigurarOrdenacao(Specification<TEntity> specification)
{
return Query.OrderByDescending(specification.Order);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
public enum PriceListType
{
[EnumDescription("Нет значения")]
None = 0,
[EnumDescription("Розничный")]
Retail = 1,
[EnumDescription("Цена последнего прихода")]
LastIncome = 2,
[EnumDescription("Промо прайс")]
PromoPrice = 3,
[EnumDescription("Запрет скидки")]
DenyDiscount = 4,
[EnumDescription("Список загрузки весов")]
ScaleLoadList =5
}
}
|
using Microsoft.EntityFrameworkCore;
using Projeto.Domain.Interfaces.Repositories;
using Projeto.Infra.Data.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Projeto.Infra.Data.Repositories
{
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
where TEntity : class
{
//Inversao de Dependencia - DIP
protected readonly SqlContext _context;
protected readonly DbSet<TEntity> dbSet; //CRUD
public BaseRepository(SqlContext context) //IoC - Injeção de Dependência
{
_context = context;
dbSet = context.Set<TEntity>();
}
public virtual void Add(TEntity obj)
{
dbSet.Add(obj);
_context.SaveChanges();
}
public virtual void Update(TEntity obj)
{
dbSet.Update(obj);
_context.SaveChanges();
}
public virtual void Remove(TEntity obj)
{
dbSet.Remove(obj);
_context.SaveChanges();
}
public virtual IQueryable<TEntity> GetAll()
{
return dbSet;
}
public virtual TEntity GetById(Guid id)
{
return dbSet.Find(id);
}
public virtual void Dispose()
{
//fechando o contexto
_context.Dispose();
}
}
}
|
using UnityEngine;
public class Particle : MonoBehaviour {
[Tooltip("How long, in seconds, the Particle Effect should be alive. -1 will make it live forever.")]
public float lifespan = 1f;
public World world { get; private set; }
public int depth { get; private set; }
/// <summary>
/// A reference to the ParticleSystem component. This could be
/// null if the Particle does not have this type of component.
/// </summary>
public ParticleSystem ps { get; private set; }
private float timeAlive;
public virtual void initialize(World world, int depth) {
this.world = world;
this.depth = depth;
this.ps = this.GetComponentInChildren<ParticleSystem>();
if(ps != null && this.lifespan != -1) {
this.lifespan = ps.main.duration;
}
}
public virtual void onUpdate() {
if(this.lifespan != -1) {
this.timeAlive += Time.deltaTime;
if(this.timeAlive > this.lifespan) {
this.world.particles.remove(this);
}
}
}
private void OnDrawGizmos() {
Gizmos.DrawWireSphere(this.transform.position, 0.1f);
}
/// <summary>
/// Called when the Particle is removed from the world when it's life runs out.
/// It is NOT called when the application shuts down.
/// </summary>
public virtual void onEnd() {
}
}
|
using System.Collections.Generic;
namespace ParrisConnection.ServiceLayer.Data
{
public class StatusData
{
public int Id { get; set; }
public string UserId { get; set; }
public string Post { get; set; }
public IEnumerable<CommentData> Comments { get; set; }
public string NewComment { get; set; }
public string UserName { get; set; }
}
}
|
namespace Tutorial.ParallelLinq
{
#if NETFX
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.ConcurrencyVisualizer.Instrumentation;
#else
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
#endif
using static Functions;
using Parallel = System.Threading.Tasks.Parallel;
internal static partial class Partitioning
{
internal static void Range()
{
int[] array = Enumerable.Range(0, Environment.ProcessorCount * 4).ToArray();
array.AsParallel().Visualize(value => ComputingWorkload(value), nameof(Range));
}
}
internal static partial class Partitioning
{
internal static void Strip()
{
IEnumerable<int> source = Enumerable.Range(0, Environment.ProcessorCount * 4);
source.AsParallel().Visualize(ParallelEnumerable.Select, value => ComputingWorkload(value)).ForAll();
}
internal static void StripLoadBalance()
{
IEnumerable<int> source = Enumerable.Range(0, Environment.ProcessorCount * 4);
source.AsParallel().Visualize(ParallelEnumerable.Select, value => ComputingWorkload(value % 2)).ForAll();
}
internal static void StripForArray()
{
int[] array = Enumerable.Range(0, Environment.ProcessorCount * 4).ToArray();
Partitioner.Create(array, loadBalance: true).AsParallel().Visualize(value => ComputingWorkload(value), nameof(Strip));
}
}
internal readonly struct Data
{
internal Data(int value) => this.Value = value;
internal int Value { get; }
public override int GetHashCode() => this.Value % Environment.ProcessorCount;
public override bool Equals(object obj) => obj is Data && this.GetHashCode() == ((Data)obj).GetHashCode();
public override string ToString() => this.Value.ToString();
}
internal static partial class Partitioning
{
internal static void HashInGroupBy()
{
IEnumerable<Data> source = new int[] { 0, 1, 2, 2, 2, 2, 3, 4, 5, 6, 10 }.Select(value => new Data(value));
source.AsParallel()
.Visualize(
(parallelQuery, elementSelector) => parallelQuery.GroupBy(
keySelector: data => data, // Key instance's GetHashCode will be called.
elementSelector: elementSelector),
data => ComputingWorkload(data.Value)) // elementSelector.
.ForAll();
// Equivalent to:
// MarkerSeries markerSeries = Markers.CreateMarkerSeries("Parallel");
// source.AsParallel()
// .GroupBy(
// keySelector: data => data,
// elementSelector: data =>
// {
// using (markerSeries.EnterSpan(Thread.CurrentThread.ManagedThreadId, data.ToString()))
// {
// return Compute(data.Value);
// }
// })
// .ForAll();
}
internal static void HashInJoin()
{
IEnumerable<Data> outerSource = new int[] { 0, 1, 2, 2, 2, 2, 3, 6 }.Select(value => new Data(value));
IEnumerable<Data> innerSource = new int[] { 4, 5, 6, 7 }.Select(value => new Data(value));
outerSource.AsParallel()
.Visualize(
(parallelQuery, resultSelector) => parallelQuery
.Join(
inner: innerSource.AsParallel(),
outerKeySelector: data => data, // Key instance's GetHashCode will be called.
innerKeySelector: data => data, // Key instance's GetHashCode will be called.
resultSelector: (outerData, innerData) => resultSelector(outerData)),
data => ComputingWorkload(data.Value)) // resultSelector.
.ForAll();
}
internal static void Chunk()
{
IEnumerable<int> source = Enumerable.Range(0, (1 + 2) * 3 * Environment.ProcessorCount + 3);
Partitioner.Create(source, EnumerablePartitionerOptions.None).AsParallel()
.Visualize(ParallelEnumerable.Select, _ => ComputingWorkload())
.ForAll();
}
}
public class StaticPartitioner<TSource> : Partitioner<TSource>
{
protected readonly IBuffer<TSource> buffer;
public StaticPartitioner(IEnumerable<TSource> source) => this.buffer = source.Share();
public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
{
if (partitionCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(partitionCount));
}
return Enumerable
.Range(0, partitionCount)
.Select(_ => this.buffer.GetEnumerator())
.ToArray();
}
}
public class DynamicPartitioner<TSource> : StaticPartitioner<TSource>
{
public DynamicPartitioner(IEnumerable<TSource> source) : base(source) { }
public override bool SupportsDynamicPartitions => true;
public override IEnumerable<TSource> GetDynamicPartitions() => this.buffer;
}
internal static partial class Partitioning
{
internal static void StaticPartitioner()
{
IEnumerable<int> source = Enumerable.Range(0, Environment.ProcessorCount * 4);
new StaticPartitioner<int>(source).AsParallel()
.Visualize(ParallelEnumerable.Select, value => ComputingWorkload(value))
.ForAll();
}
internal static void DynamicPartitioner()
{
IEnumerable<int> source = Enumerable.Range(0, Environment.ProcessorCount * 4);
Parallel.ForEach(new DynamicPartitioner<int>(source), value => ComputingWorkload(value));
}
internal static void VisualizeDynamicPartitioner()
{
IEnumerable<int> source = Enumerable.Range(0, Environment.ProcessorCount * 4);
MarkerSeries markerSeries = Markers.CreateMarkerSeries(nameof(Parallel));
Parallel.ForEach(
new DynamicPartitioner<int>(source),
value =>
{
using (markerSeries.EnterSpan(Thread.CurrentThread.ManagedThreadId, value.ToString()))
{
ComputingWorkload(value);
}
});
}
internal static IList<IList<TSource>> GetPartitions<TSource>(IEnumerable<TSource> partitionsSource, int partitionCount)
{
List<IList<TSource>> partitions = Enumerable
.Range(0, partitionCount)
.Select<int, IList<TSource>>(_ => new List<TSource>())
.ToList();
Thread[] partitioningThreads = Enumerable
.Range(0, partitionCount)
.Select(_ => partitionsSource.GetEnumerator())
.Select((partitionIterator, partitionIndex) => new Thread(() =>
{
IList<TSource> partition = partitions[partitionIndex];
using (partitionIterator)
{
while (partitionIterator.MoveNext())
{
partition.Add(partitionIterator.Current);
}
}
}))
.ToArray();
partitioningThreads.ForEach(thread => thread.Start());
partitioningThreads.ForEach(thread => thread.Join());
return partitions;
}
}
}
#if DEMO
namespace System.Collections.Concurrent
{
using System.Collections.Generic;
public abstract class Partitioner<TSource>
{
protected Partitioner() { }
public virtual bool SupportsDynamicPartitions => false;
public abstract IList<IEnumerator<TSource>> GetPartitions(int partitionCount);
public virtual IEnumerable<TSource> GetDynamicPartitions() =>
throw new NotSupportedException("Dynamic partitions are not supported by this partitioner.");
}
}
namespace System.Threading.Tasks
{
using System.Collections.Concurrent;
public static class Parallel
{
public static ParallelLoopResult ForEach<TSource>(Partitioner<TSource> source, Action<TSource> body);
}
}
#endif |
namespace Phenix.Security.Business
{
/// <summary>
/// 用户日志查询
/// </summary>
[System.SerializableAttribute(), System.ComponentModel.DisplayNameAttribute("用户日志查询")]
public class UserLogCriteria : Phenix.Business.CriteriaBase
{
[Phenix.Core.Mapping.CriteriaField(FriendlyName = "工号", Logical = Phenix.Core.Mapping.CriteriaLogical.And, Operate = Phenix.Core.Mapping.CriteriaOperate.Equal, TableName = "PH_USERLOG", ColumnName = "US_USERNUMBER")]
private string _userNumber; //private string _userNumber = Phenix.Business.Security.UserPrincipal.User != null ? Phenix.Business.Security.UserPrincipal.User.Identity.UserNumber : null;
/// <summary>
/// 工号
/// </summary>
[System.ComponentModel.DisplayName("工号")]
public string UserNumber
{
get { return _userNumber; }
set { _userNumber = value; PropertyHasChanged(); }
}
}
}
|
using School.Business.Models;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace School.Business
{
public interface ISchoolService
{
ClassMasterModel[] Classes { get; }
ClassMasterModel ClassMaster(int classId);
SelectList PopulateClassesDropDownList();
List<StudentClassModel> GetClassesForStudent(int userId);
void AddClassForUser(int userId, int classId);
}
}
|
using System.Collections.Generic;
namespace FamilyAccounting.Web.Models
{
public class IndexPersonViewModel
{
public IEnumerable<PersonViewModel> Persons { get; set; }
}
}
|
using NfePlusAlpha.Application.ViewModels.ViewModel;
using NfePlusAlpha.Infra.Data.Retorno;
using NfePlusAlpha.UI.Wpf.Apoio.Controles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace NfePlusAlpha.UI.Wpf.Views.Cadastros
{
/// <summary>
/// Interaction logic for winCliente.xaml
/// </summary>
public partial class winCliente : NfePlusAlphaWindow
{
public ClienteViewModel objClienteViewModel { get; set; }
public winCliente()
{
InitializeComponent();
ucComando.Salvar += Salvar;
ucComando.Novo += Novo;
ucComando.Cancelar += Cancelar;
ucComando.Buscar += Buscar;
ucComando.Excluir += Excluir;
ucComando.Sair += Sair;
ucComando.RegistroAnterior += Anterior;
ucComando.RegistroPosterior += Proximo;
}
private void Salvar(object sender, EventArgs e)
{
string strMensagem = string.Empty;
this.objClienteViewModel.Salvar(out strMensagem);
if (!string.IsNullOrEmpty(strMensagem))
MessageBox.Show(strMensagem, "Aviso", MessageBoxButton.OK, MessageBoxImage.Error);
else
if(!this.objClienteViewModel.HasErrors)
this.ucComando.StatusBotao(enStatusNfePlusAlphaComando.Inicial);
}
private void Excluir(object sender, EventArgs e)
{
string strMensagem = string.Empty;
this.objClienteViewModel.Excluir(out strMensagem);
if (!string.IsNullOrEmpty(strMensagem))
MessageBox.Show(strMensagem, "Aviso", MessageBoxButton.OK, MessageBoxImage.Error);
else
{
Cancelar(null, null);
}
}
private void Buscar(object sender, EventArgs e)
{
NFePlusAlphaPesquisa winBuscar = new NFePlusAlphaPesquisa("Cliente");
winBuscar.enTipoBusca = enTipoPesquisa.Cliente;
winBuscar.Owner = this;
winBuscar.ShowDialog();
if (winBuscar.objRetorno != null)
MostrarDados(winBuscar.objRetorno.ToString());
}
private void Cancelar(object sender, EventArgs e)
{
this.objClienteViewModel.blnCodigoEnabled = true;
this.objClienteViewModel = new ClienteViewModel();
this.LayoutRoot.DataContext = this.objClienteViewModel;
ucComando.StatusBotao(enStatusNfePlusAlphaComando.Inicial);
}
private void Novo(object sender, EventArgs e)
{
this.objClienteViewModel = new ClienteViewModel();
this.objClienteViewModel.blnCodigoEnabled = false;
this.LayoutRoot.DataContext = this.objClienteViewModel;
txtCnpj.Focus();
}
private void Anterior(object sender, EventArgs e)
{
MostrarDados(txtCodigo.Text, enDirecao.Anterior);
}
private void Proximo(object sender, EventArgs e)
{
MostrarDados(txtCodigo.Text, enDirecao.Proximo);
}
private void Sair(object sender, EventArgs e)
{
this.Close();
}
private void txtCodigo_LostFocus(object sender, RoutedEventArgs e)
{
}
private void txtCodigo_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
MostrarDados(txtCodigo.Text);
}
private void MostrarDados(string strCodigo, enDirecao? enDirecao = null)
{
int intCodigo = 0;
int.TryParse(strCodigo, out intCodigo);
if (intCodigo >= 0)
{
NfePlusAlphaRetorno objRetorno = this.objClienteViewModel.ObterCliente(intCodigo, enDirecao);
if (!objRetorno.blnTemErro && objRetorno.objRetorno != null)
{
this.objClienteViewModel = new ClienteViewModel();
this.objClienteViewModel.objCliente = (NfePlusAlpha.Domain.Entities.tbCliente)objRetorno.objRetorno;
this.LayoutRoot.DataContext = this.objClienteViewModel;
this.objClienteViewModel.intEstadoCodigo = this.objClienteViewModel.objCliente.tbCidade.est_codigo;
this.objClienteViewModel.objCliente.tbCidade.tbEstado = null;
ucComando.StatusBotao(enStatusNfePlusAlphaComando.Alteracao);
this.objClienteViewModel.blnCodigoEnabled = false;
}
}
}
private void NfePlusAlphaWindow_Loaded(object sender, RoutedEventArgs e)
{
this.objClienteViewModel = new ClienteViewModel();
}
private void NfePlusAlphaWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
this.ucComando.btnSair_Click(null, null);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health : MonoBehaviour
{
public GameObject lives, lives1, lives2,liveD, liveD1, liveD2, gameOver;
public static int health = 3;
void Update()
{
if (health > 3)
health = 3;
switch (health)
{
case 3:
Debug.Log("Case3");
lives.gameObject.SetActive(true);
lives1.gameObject.SetActive(true);
lives2.gameObject.SetActive(true);
liveD.gameObject.SetActive(false);
liveD1.gameObject.SetActive(false);
liveD2.gameObject.SetActive(false);
break;
case 2:
Debug.Log("Case2");
lives.gameObject.SetActive(true);
lives1.gameObject.SetActive(true);
lives2.gameObject.SetActive(false);
liveD.gameObject.SetActive(true);
liveD1.gameObject.SetActive(false);
liveD2.gameObject.SetActive(false);
break;
case 1:
Debug.Log("Case1");
lives.gameObject.SetActive(true);
lives1.gameObject.SetActive(false);
lives2.gameObject.SetActive(false);
liveD.gameObject.SetActive(true);
liveD1.gameObject.SetActive(true);
liveD2.gameObject.SetActive(false);
break;
case 0:
Debug.Log("Case0");
lives.gameObject.SetActive(false);
lives1.gameObject.SetActive(false);
lives2.gameObject.SetActive(false);
liveD.gameObject.SetActive(true);
liveD1.gameObject.SetActive(true);
liveD2.gameObject.SetActive(true);
gameOver.gameObject.SetActive(true);
gameObject.SetActive(false);
MenuManager.instance.GameOver();
// Time.timeScale = 0f;
break;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SoundVisualize : MonoBehaviour {
private Slider slider;
public bool isReactive
{
get
{
return _isReactive;
}
set
{
_isReactive = value;
}
}
private bool _isReactive = false;
private void Awake()
{
slider = GetComponent<Slider>();
}
/// <summary>
/// display the volume of current microphone as a bar
/// </summary>
/// <param name="Volume">a float number in [0,1]</param>
private void DisplayVolume(float volume)
{
slider.value = volume;
}
/// <summary>
/// Update the height of the bar every frame based on the sound from microphone
/// </summary>
void Update()
{
if (isReactive)
{
DisplayVolume(SoundDetect.instance.currentVolume);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Net;
using System.Net.Mail;
using System.ServiceModel.Activation;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
//using System.Net.Http;
using LibraryORI;
using System.Globalization;
namespace WcfOri.Class
{
public class KuotaInvestor
{
Class.LogDb log = new Class.LogDb();
Class.Email email = new Class.Email();
Class.SMS sms = new Class.SMS();
GlobalFunction myobject = new GlobalFunction();
public string setAPIHeader(string url, string body, string methodset)
{
string apiID;
string apiKey;
string requestURL;
string requestHTTPmethod;
string requestBody;
string requestBodyBase64;
string requestTimeStamp;
string nonce;
string signatureBase64;
string authString;
apiID = "76a6b93a5de848f68e5e5b82a2666add";
apiKey = "mVV96drmBDGpZP8TsfgsIl8cTnbtq9qwYlTm3xNnqTM=";
requestURL = System.Web.HttpUtility.UrlEncode(url).ToLower();
requestHTTPmethod = methodset.ToUpper();
requestBody = body;
// -------
try
{
var obj = JObject.Parse(body);
requestBody = Regex.Replace(obj.ToString(Formatting.None), @"\s+", "");
}
catch
{
requestBody = @"""""";
}
// -------
byte[] encodedRequestBody = Encoding.UTF8.GetBytes(requestBody);
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] requestContentHash = md5.ComputeHash(encodedRequestBody);
requestBodyBase64 = Convert.ToBase64String(requestContentHash);
nonce = Guid.NewGuid().ToString("N");
DateTime timestart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime UTCnow = DateTime.UtcNow;
TimeSpan span = UTCnow - timestart;
requestTimeStamp = Convert.ToInt64(span.TotalSeconds).ToString();
var signatureRawData = string.Format("{0}{1}{2}{3}{4}{5}", apiID, requestHTTPmethod, requestURL, requestTimeStamp, nonce, requestBodyBase64);
byte[] encodedApiKey = Encoding.UTF8.GetBytes(apiKey);
byte[] encodedSignatureRaw = Encoding.UTF8.GetBytes(signatureRawData);
System.Security.Cryptography.HMACSHA256 myHMACSHA256 = new System.Security.Cryptography.HMACSHA256(encodedApiKey);
byte[] HashCode = myHMACSHA256.ComputeHash(encodedSignatureRaw);
signatureBase64 = Convert.ToBase64String(HashCode);
byte[] encodedString = Encoding.UTF8.GetBytes(string.Format("{0}:{1}:{2}:{3}", apiID, signatureBase64, nonce, requestTimeStamp));
authString = Convert.ToBase64String(encodedString);
return authString;
}
#region cek kuota
//public Tuple<Response, List<KuotaInvestorData>> CekKuotaInvestor(string norek, string IdSeri)
//{
// List<KuotaInvestorData> li = new List<KuotaInvestorData>();
// KuotaInvestorData data = new KuotaInvestorData();
// data.sid = myobject.getSid(norek).sid.ToString();
// var sid = data.sid.ToString();
// DataTable dt = new DataTable();
// Response responseori = new Response();
// HttpWebResponse response1 = null/* TODO Change to default(_) if this is not a reference type */;
// StreamReader reader;
// if (sid == "0")
// {
// responseori.code = "90";
// responseori.message = "Failed";
// responseori.desc = "No rekening tidak ditemukan";
// }
// string webpage = string.Format("https://test-apisbn.kemenkeu.go.id/v1/Kuota/{0}/{1}", IdSeri, sid);
// string requestBody = @"""""";
// HttpWebRequest request1;
// request1 = (HttpWebRequest)WebRequest.Create(webpage);
// request1.Method = "GET";
// request1.Headers.Add("Authorization", "amx " + setAPIHeader(webpage, requestBody, request1.Method));
// request1.ContentType = "application/json";
// request1.Accept = "application/json";
// WebProxy proxySetting = new WebProxy("http://proxyretad.dnroot.net:8080/", true);
// System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("RS20234MR", "Maybank3");
// CredentialCache cc = new CredentialCache();
// request1.Proxy = proxySetting;
// request1.Proxy.Credentials = credentials;
// try
// {
// if (sid != "0")
// {
// response1 = (HttpWebResponse)request1.GetResponse();
// reader = new StreamReader(response1.GetResponseStream());
// JObject JsonResponse = JObject.Parse(reader.ReadToEnd());
// data.KuotaInvestor = (string)JsonResponse.SelectToken("KuotaInvestor").ToString();
// data.IdSeri = (string)JsonResponse.SelectToken("IdSeri").ToString();
// data.TglSetelmen = (string)JsonResponse.SelectToken("TglSetelmen").ToString();
// data.Seri = (string)JsonResponse.SelectToken("Seri").ToString();
// data.KuotaSeri = (string)JsonResponse.SelectToken("KuotaSeri").ToString();
// data.norek = myobject.getSid(norek).norek.ToString();
// data.noksei = myobject.getSid(norek).noksei.ToString();
// li.Add(data);
// responseori.desc = response1.StatusCode.ToString();
// responseori.code = Convert.ToInt64(response1.StatusCode).ToString();
// responseori.message = "Success";
// }
// }
// catch (WebException ex)
// {
// WebResponse respon = ex.Response;
// using ((respon))
// {
// HttpWebResponse httpRespon = (HttpWebResponse)respon;
// var reader2 = new StreamReader(httpRespon.GetResponseStream());
// JObject jsonResponseError = JObject.Parse(reader2.ReadToEnd());
// responseori.code = Convert.ToInt64(httpRespon.StatusCode).ToString();
// responseori.desc = (string)jsonResponseError.SelectToken("Message").ToString();
// responseori.message = "Failed";
// log.writeLog("CekKuotaInvestor", responseori.desc.ToString(), responseori.message.ToString(), responseori.code.ToString());
// }
// //throw ex;
// }
// return Tuple.Create(responseori, li);
//}
//public JObject GetKuota(string url, string method)
//{
// Response responseori = new Response();
// HttpWebResponse response1 = null/* TODO Change to default(_) if this is not a reference type */;
// StreamReader reader;
// string requestBody = @"""""";
// HttpWebRequest request1;
// request1 = (HttpWebRequest)WebRequest.Create(url);
// request1.Method = method;
// request1.Headers.Add("Authorization", "amx " + setAPIHeader(url, requestBody, request1.Method));
// request1.ContentType = "application/json";
// request1.Accept = "application/json";
// WebProxy proxySetting = new WebProxy("http://proxyretad.dnroot.net:8080/", true);
// System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("RS20234MR", "Maybank3");
// CredentialCache cc = new CredentialCache();
// request1.Proxy = proxySetting;
// request1.Proxy.Credentials = credentials;
// JObject jobject = new JObject();
// try
// {
// response1 = (HttpWebResponse)request1.GetResponse();
// reader = new StreamReader(response1.GetResponseStream());
// JObject JsonResponse = JObject.Parse(reader.ReadToEnd());
// jobject = JsonResponse;
// //responseori.desc = JsonResponse.ToString();
// //responseori.code = Convert.ToInt64(response1.StatusCode).ToString();
// //responseori.message = "Success";
// }
// catch (WebException ex)
// {
// WebResponse respon = ex.Response;
// using ((respon))
// {
// HttpWebResponse httpRespon = (HttpWebResponse)respon;
// var reader2 = new StreamReader(httpRespon.GetResponseStream());
// JObject jsonResponseError = JObject.Parse(reader2.ReadToEnd());
// responseori.code = Convert.ToInt64(httpRespon.StatusCode).ToString();
// responseori.desc = (string)jsonResponseError.SelectToken("Message").ToString();
// responseori.message = "Failed";
// log.writeLog("GetSubRekSid", responseori.desc.ToString(), responseori.message.ToString(), responseori.code.ToString());
// }
// //throw ex;
// }
// return jobject;
//}
#endregion
}
} |
using System;
using System.Linq;
using Godot;
using Dictionary = Godot.Collections.Dictionary;
using Array = Godot.Collections.Array;
public class Player : KinematicBody2D
{
public const int MAX_SPEED = 600;
[Export] public bool jumping = false;
[Export] public int move_speed = 250;
[Export] public int jump_force = 700;
[Export] public int gravity = 1800;
public Vector2 speed = new Vector2();
public Vector2 velocity = new Vector2();
public Vector2 snap_vector = new Vector2(0, 32);
public ulong prev_vert_wall = 0;
public void ProcessJump()
{
speed.y = -jump_force;
jumping = true;
}
public override void _PhysicsProcess(float delta)
{
var direction_x = Input.GetActionStrength("move_right") - Input.GetActionStrength("move_left");
speed.x = direction_x * move_speed ;
speed.y += gravity * delta;
// Limit maximum speed
speed.x = Mathf.Clamp(speed.x, -MAX_SPEED, MAX_SPEED);
speed.y = Mathf.Clamp(speed.y, -MAX_SPEED, MAX_SPEED);
velocity = MoveAndSlideWithSnap( speed, jumping ? speed : snap_vector, Vector2.Up, false, 4, Mathf.Deg2Rad(46), true );
if(IsOnFloor())
{
velocity.y = 0;
jumping = false;
prev_vert_wall = 0 ;
}
if(Input.IsActionJustPressed("jump"))
{
// Is on floor, allow jumping
if(IsOnFloor())
{
ProcessJump();
// Allow wall jumps only when in air already
}
else if(IsOnWall() && jumping)
{
// Do !allow wall jumps from the same wall
foreach(var i in Enumerable.Range(0, GetSlideCount()))
{
var collision = GetSlideCollision(i);
if(collision.ColliderId != prev_vert_wall && collision.Collider.IsClass("StaticBody2D"))
{
ProcessJump();
prev_vert_wall = collision.ColliderId;
break;
}
}
}
}
}
public void collide()
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Menu;
using UnityEngine;
using Rainbow.Enum;
using RWCustom;
namespace Rainbow.SandboxOverhaul
{
public static class SandboxSettingsInterfacePatch
{
public static void SubPatch()
{
On.Menu.SandboxSettingsInterface.ctor += new On.Menu.SandboxSettingsInterface.hook_ctor(CtorPatch);
On.Menu.SandboxSettingsInterface.AddScoreButton_1 += new On.Menu.SandboxSettingsInterface.hook_AddScoreButton_1(AddScoreButtonPatch);
On.Menu.SandboxSettingsInterface.DefaultKillScores += new On.Menu.SandboxSettingsInterface.hook_DefaultKillScores(DefaultKillScoresPatch);
}
public static void CtorPatch(On.Menu.SandboxSettingsInterface.orig_ctor orig, SandboxSettingsInterface self, Menu.Menu menu, MenuObject owner)
{
self.menu = menu;
self.owner = owner;
self.subObjects = new List<MenuObject>();
self.nextSelectable = new MenuObject[4];
self.pos = new Vector2(440f, 385f);
self.lastPos = new Vector2(440f, 385f);
self.scoreControllers = new List<SandboxSettingsInterface.ScoreController>();
IntVector2 intVector = new IntVector2(0, 0);
for (int i = 0; i < MultiplayerUnlocks.CreaturesUnlocks + 9; i++)
{
MultiplayerUnlocks.SandboxUnlockID c = (MultiplayerUnlocks.SandboxUnlockID)i;
if (c != MultiplayerUnlocks.SandboxUnlockID.Fly &&
c != MultiplayerUnlocks.SandboxUnlockID.Leech &&
c != MultiplayerUnlocks.SandboxUnlockID.SeaLeech &&
c != MultiplayerUnlocks.SandboxUnlockID.SmallNeedleWorm &&
c != MultiplayerUnlocks.SandboxUnlockID.Spider &&
c != MultiplayerUnlocks.SandboxUnlockID.VultureGrub &&
c != MultiplayerUnlocks.SandboxUnlockID.BigEel &&
c != MultiplayerUnlocks.SandboxUnlockID.Deer &&
c != MultiplayerUnlocks.SandboxUnlockID.SmallCentipede &&
c != MultiplayerUnlocks.SandboxUnlockID.TubeWorm &&
c != MultiplayerUnlocks.SandboxUnlockID.Hazer &&
c != MultiplayerUnlocks.SandboxUnlockID.BlackLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.BlueLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.CyanLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.GreenLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.PinkLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.RedLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.WhiteLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.YellowLizard &&
c != MultiplayerUnlocks.SandboxUnlockID.Salamander)
{
self.AddScoreButton(c, ref intVector);
}
}
for (int j = 0; j < 1; j++)
{
self.AddScoreButton(null, ref intVector);
}
self.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, self, menu.Translate("Food"), "FOODSCORE"), ref intVector);
self.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, self, menu.Translate("Survive"), "SURVIVESCORE"), ref intVector);
self.AddScoreButton(new SandboxSettingsInterface.MiscScore(menu, self, menu.Translate("Spear hit"), "SPEARHITSCORE"), ref intVector);
if (menu.CurrLang != InGameTranslator.LanguageID.English)
{
for (int k = 1; k < 4; k++)
{
SandboxSettingsInterface.ScoreController scoreController = self.scoreControllers[self.scoreControllers.Count - k];
scoreController.pos.x += 24f;
}
}
self.subObjects.Add(new SymbolButton(menu, self, "Menu_Symbol_Clear_All", "CLEARSCORES", new Vector2(0f, -280f)));
for (int l = 0; l < self.subObjects.Count; l++)
{
if (self.subObjects[l] is SandboxSettingsInterface.ScoreController)
{
(self.subObjects[l] as SandboxSettingsInterface.ScoreController).scoreDragger.UpdateScoreText();
}
}
}
public static void AddScoreButtonPatch(On.Menu.SandboxSettingsInterface.orig_AddScoreButton_1 orig, SandboxSettingsInterface self, SandboxSettingsInterface.ScoreController button, ref IntVector2 ps)
{
//orig_AddScoreButton(button, ref ps);
if (button != null)
{
self.scoreControllers.Add(button);
self.subObjects.Add(button);
button.pos = new Vector2((float)ps.x * 88.666f + 0.01f, (float)ps.y * -30f + 60f);
}
ps.y++;
if (ps.y > 10)
{
ps.y = 0;
ps.x++;
}
}
public static void DefaultKillScoresPatch(On.Menu.SandboxSettingsInterface.orig_DefaultKillScores orig, ref int[] killScores)
{
orig.Invoke(ref killScores);
killScores[(int)EnumExt_Sandbox.Hornest] = 12;
killScores[(int)EnumExt_Sandbox.SmallCentiwing] = 2;
killScores[(int)EnumExt_Sandbox.Wolf] = 4;
killScores[(int)EnumExt_Sandbox.FormulatedGroundLizard] = 10;
killScores[(int)EnumExt_Sandbox.FormulatedClimbLizard] = 7;
killScores[(int)EnumExt_Sandbox.FormulatedWallLizard] = 7;
killScores[(int)EnumExt_Sandbox.FormulatedWaterLizard] = 7;
killScores[(int)EnumExt_Sandbox.FormulatedSkyLizard] = 9;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleController2D : MonoBehaviour
{
[Header("Layer")]
public LayerMask obstacleLayer;
[Header("Movement")]
public float moveSpeed = 6;
float accelerationTimeAirborne = .2f;
float accelerationTimeGrounded = .1f;
public float maxSlopeAngle = 55;
[Header("Jumps")]
public float maxJumpHeight = 4;
public float minJumpHeight = 1;
//Jump Velocity
float maxJumpVelocity;
float minJumpVelocity;
float velocityXSmoothing;
float velocityYSmoothing;
[Header("Airborne jumps")]
public int airborneJumpNumber = 1;
private int jumpsLeft;
public float maxAirborneJumpHeight = 4;
public float minAirborneJumpHeight = 1;
//Jump Velocity
float maxAirborneJumpVelocity;
float minAirborneJumpVelocity;
[Header("Jump Qualitiy")]
//Jump Buffer
public float jumpBufferTime;
float lastJumpBuffer;
bool isJumpBuffer;
// Coyote Time
[Tooltip("Time after leaving ground you can still Jump")]
public float coyoteTime = 0.2f;
float lastGroundedTime;
//JumpCorner Correction
[Tooltip("Minimum speed at which the player is moved to the side if he bumps his head, when jumping")]
public float minJumpCornerCorrectionSpeed = 2;
[Header("Wall Jumps")]
public Vector2 wallJumpClimb = new Vector2(7.5f, 16);
public Vector2 wallJumpOff = new Vector2(8.5f, 7);
public Vector2 wallLeap = new Vector2(18,17);
[Header("Wall Slide")]
public float wallSlideSpeedMax = 3;
public float wallStickTime = .25f;
float timeToWallUnstick;
public bool isWallSliding
{
get;
private set;
}
public bool isSlopeSliding
{
get;
private set;
}
public int wallDirX
{
get;
private set;
}
//Other
Vector2 directionalInput;
Rigidbody2D rigid;
public CollisionInfo _collisionInfo = new CollisionInfo();
#region SETUP
private void Start()
{
rigid = GetComponent<Rigidbody2D>();
//Jump Velocities
maxJumpVelocity = GetJumpSpeed(maxJumpHeight);
minJumpVelocity = GetJumpSpeed(minJumpHeight);
maxAirborneJumpVelocity = GetJumpSpeed(maxAirborneJumpHeight);
minAirborneJumpVelocity = GetJumpSpeed(minAirborneJumpHeight);
// Collisions
_collisionInfo = new CollisionInfo();
_collisionInfo.activeCollisions = new List<Collision2D>();
}
public static float GetJumpSpeed(float jumpHeight)
{
float gravity = -Physics2D.gravity.y;
return Mathf.Sqrt(2 * Mathf.Abs(gravity) * jumpHeight);
}
#endregion
#region COLLISIONS
private void OnCollisionEnter2D(Collision2D other)
{
_collisionInfo.activeCollisions.Add(other);
UpdateCollisions();
}
private void OnCollisionStay2D(Collision2D other)
{
for (int i = 0; i < _collisionInfo.activeCollisions.Count; i++)
{
if (_collisionInfo.activeCollisions[i].collider == other.collider)
{
_collisionInfo.activeCollisions[i] = other;
}
}
UpdateCollisions();
}
public void OnCollisionExit2D(Collision2D other)
{
_collisionInfo.activeCollisions.Remove(other);
UpdateCollisions();
}
#endregion
#region UPDATE
private void Update()
{
HandleCoyoteTime();
HandleWallSliding();
HandleMovement();
HandleJumpBuffer();
HandleAirborneJumps();
_collisionInfo.DrawDebug(transform.position);
_collisionInfo.DrawRay(transform.position,_collisionInfo.slopeNormal*2,_collisionInfo.slopeAngle<maxSlopeAngle);
}
public void SetDirectionalInput(Vector2 input)
{
directionalInput = input;
}
public void UpdateCollisions()
{
Vector2 position = transform.position;
// Reset Collisions
_collisionInfo.Reset();
// Angles
float horizontalAngle = 20f;
// Check collisions
foreach (var collision in _collisionInfo.activeCollisions)
{
for (int i = 0; i < collision.contactCount; i++)
{
ContactPoint2D contactPoint2D = collision.GetContact(i);
Vector2 dif = -contactPoint2D.normal;
//Debug.DrawRay(transform.position, dif, Color.black, 0.3f);
float signedAngle = Vector2.SignedAngle(Vector2.up, dif.normalized);
if (Mathf.Abs(signedAngle) < 45f)
_collisionInfo.above = true;
if (Mathf.Abs(signedAngle) > 90 + horizontalAngle*0.5f)
_collisionInfo.below = true;
if (signedAngle > 90f - horizontalAngle*0.5f && signedAngle < 90f + horizontalAngle*0.5f)
_collisionInfo.left = true;
if (signedAngle < -90f + horizontalAngle*0.5f && signedAngle > -90f - horizontalAngle*0.5f)
_collisionInfo.right = true;
if (Mathf.Abs(signedAngle) > 90f)
{
float slopeAngle = Vector2.Angle(contactPoint2D.normal, Vector2.up);
_collisionInfo.slopeAngle = slopeAngle;
_collisionInfo.slopeNormal = contactPoint2D.normal;
}
}
}
}
public void HandleCoyoteTime()
{
if (_collisionInfo.below)
{
lastGroundedTime = Time.time;
}
_collisionInfo.coyoteBelow = Time.time - lastGroundedTime < coyoteTime || _collisionInfo.below;
}
void HandleWallSliding()
{
Vector2 velocity = rigid.velocity;
wallDirX = _collisionInfo.left ? -1 : 1;
bool onWall = _collisionInfo.left || _collisionInfo.right;
isWallSliding = false;
if (onWall && ! _collisionInfo.below)
{
isWallSliding = true;
if (velocity.y < -wallSlideSpeedMax)
{
velocity.y = -wallSlideSpeedMax;
}
if (timeToWallUnstick > 0)
{
velocityXSmoothing = 0;
//velocity.x = 0;
if (Mathf.Sign(directionalInput.x) != Mathf.Sign(wallDirX) && directionalInput.x != 0)
{
timeToWallUnstick -= Time.deltaTime;
}
else
{
timeToWallUnstick = wallStickTime;
}
}
else
{
timeToWallUnstick = wallStickTime;
}
}
rigid.velocity = velocity;
}
public void HandleMovement()
{
if(rigid.gravityScale < 0.1f)
return;
Debug.DrawRay(Vector2.one, _collisionInfo.slopeNormal, Color.green);
Vector2 velocity = rigid.velocity;
float xDir = Mathf.Sign(velocity.x);
float xDirTarget = Mathf.Sign(directionalInput.x);
float targetSpeed = moveSpeed;
isSlopeSliding = false;
if (!_collisionInfo.below || isWallSliding)
{
velocity.x = Mathf.SmoothDamp(velocity.x, targetSpeed * directionalInput.x, ref velocityXSmoothing, accelerationTimeAirborne);
}
else
{
Vector2 groundNormal = _collisionInfo.slopeNormal;
Vector2 groundRight = -Vector2.Perpendicular(groundNormal);
//Sliding
if (_collisionInfo.slopeAngle > maxSlopeAngle)
{
isSlopeSliding = true;
return;
}
Vector2 targetVelocity = groundRight.normalized * directionalInput.x * targetSpeed;
velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocity.x, ref velocityXSmoothing, accelerationTimeGrounded);
velocity.y = Mathf.SmoothDamp(velocity.y, targetVelocity.y, ref velocityYSmoothing, accelerationTimeGrounded);
}
rigid.velocity = velocity;
}
public void HandleJumpBuffer()
{
if (!isJumpBuffer)
return;
if (Time.unscaledTime - lastJumpBuffer > jumpBufferTime)
return;
if(isWallSliding || _collisionInfo.below)
{
isJumpBuffer = false;
OnJumpStart();
}
}
public void HandleAirborneJumps()
{
if(isWallSliding || _collisionInfo.below )
{
jumpsLeft = airborneJumpNumber;
}
}
public void ResetJumpBuffer()
{
isJumpBuffer = true;
jumpsLeft = airborneJumpNumber;
}
#endregion
#region JUMPS
public void OnJumpStart()
{
Vector2 velocity = rigid.velocity;
// Wall jump
if (isWallSliding)
{
if (Mathf.Sign(wallDirX) == Mathf.Sign(directionalInput.x))
{
velocity.x = -wallDirX * wallJumpClimb.x;
velocity.y = wallJumpClimb.y;
//print("WallJumpClimb");
}
else if (directionalInput.x <= 0.1f)
{
velocity.x = -wallDirX * wallJumpOff.x;
velocity.y = wallJumpOff.y;
//print("wallJumpOff");
}
else
{
velocity.x = -wallDirX * wallLeap.x;
velocity.y = wallLeap.y;
//print("wallLeap" );
}
ResetJumpQuality();
rigid.velocity = velocity;
return;
}
// Slope Jump
if (_collisionInfo.below && _collisionInfo.slopeAngle > maxSlopeAngle)
{
velocity.y = maxJumpVelocity * _collisionInfo.slopeNormal.y;
velocity.x = maxJumpVelocity * _collisionInfo.slopeNormal.x;
ResetJumpQuality();
rigid.velocity = velocity;
//print("SlopeJump");
return;
}
// Normal Jump
if (_collisionInfo.below)
{
velocity.y = maxJumpVelocity;
rigid.velocity = velocity;
float force = 0.5f * rigid.mass * velocity.sqrMagnitude;
ResetJumpQuality();
//print("Normal Jump");
return;
}
// Coyote Jump
if (_collisionInfo.coyoteBelow)
{
velocity.y = maxJumpVelocity;
rigid.velocity = velocity;
ResetJumpQuality();
//print("Coyote Jump");
return;
}
// Double Jump
if (jumpsLeft > 0)
{
velocity.y = maxAirborneJumpVelocity;
rigid.velocity = velocity;
jumpsLeft--;
ResetJumpQuality();
//print("Double Jump");
return;
}
// Premature Jump
lastJumpBuffer = Time.unscaledTime;
isJumpBuffer = true;
}
public void OnJumpStop()
{
Vector2 velocity = rigid.velocity;
if (velocity.y > minJumpVelocity && velocity.y <= maxJumpVelocity)
{
velocity.y = minJumpVelocity;
}
rigid.velocity = velocity;
}
public void ResetJumpQuality()
{
//Reset Jumpbuffer
isJumpBuffer = false;
//Reset CoyoteTime
lastGroundedTime = 0;
}
#endregion
public struct CollisionInfo
{
public bool above, below;
public bool left, right;
public bool coyoteBelow;
public List<Collision2D> activeCollisions;
public float slopeAngle;
public Vector2 slopeNormal;
public void Reset()
{
above = below = false;
left = right = false;
slopeNormal = Vector2.up;
}
public void DrawDebug(Vector2 position)
{
DrawRay(position, Vector2.up, above);
DrawRay(position, Vector2.down, below);
DrawRay(position, Vector2.left, left);
DrawRay(position, Vector2.right, right);
}
public void DrawRay(Vector2 origin, Vector2 dir, bool flag)
{
Color color = flag ? Color.green : Color.red;
Debug.DrawRay(origin, dir, color);
}
}
}
|
using ND.FluentTaskScheduling.Core;
using ND.FluentTaskScheduling.Model;
using ND.FluentTaskScheduling.Model.request;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
//**********************************************************************
//
// 文件名称(File Name):LogProxy.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-10 17:03:20
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-10 17:03:20
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Command.asyncrequest
{
public class LogProxy
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void AddNodeLog(string msg,LogType logType= LogType.SystemLog)
{
AddLog(msg, 0, logType);
}
public static void AddTaskLog(string msg,int taskid)
{
AddLog(msg, taskid, LogType.CommonLog);
}
public static void AddNodeErrorLog(string msg)
{
AddLog(msg, 0, LogType.SystemError);
}
public static void AddTaskErrorLog(string msg,int taskid)
{
AddLog(msg, taskid, LogType.CommonError);
}
private static void AddLog(string msg,int taskid,LogType logType)
{
var r = NodeProxy.PostToServer<EmptyResponse, AddLogRequest>(ProxyUrl.AddLog_Url, new AddLogRequest() { NodeId = GlobalNodeConfig.NodeID, Source = Source.Node, Msg = msg, LogType = logType, TaskId = taskid });
if (r.Status != ResponesStatus.Success)
{
log.Error("请求" + ProxyUrl.AddLog_Url + "获取节点配置失败,服务端返回信息:" + JsonConvert.SerializeObject(r));
}
}
}
}
|
using Core;
using DBCore;
using MaterialDesignThemes.Wpf;
using ServiceCenter.Helpers;
using ServiceCenter.View.Repair;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace ServiceCenter.ViewModel.Repair
{
class PageOrderWorkSelectCompViewModel : BaseViewModel
{
ICallbackAddToList callback;
//наша форма
private FormOrderWork window = Application.Current.Windows.OfType<FormOrderWork>().FirstOrDefault();
//индикатор ожидания
private bool _isAwait = false;
public bool IsAwait { get => _isAwait; set => Set(ref _isAwait, value); }
private string _searchField;
public string SearchField { get => _searchField; set => Set(ref _searchField, value); }
private ObservableCollection<Component> _components = new ObservableCollection<Component>();
public ObservableCollection<Component> Components { get { return _components; } }
private Component _selectedComponent;
public Component SelectedComponent { get => _selectedComponent; set => Set(ref _selectedComponent, value); }
public ICommand SelectComponentCommand { get; }
public ICommand CanselSearchCommand { get; }
public PageOrderWorkSelectCompViewModel(ICallbackAddToList callback)
{
this.callback = callback;
SelectComponentCommand = new Command(SelectComponentExecute, SelectComponentCanExecute);
CanselSearchCommand = new Command(CanselSearchExecute, CanselSearchCanExecute);
}
#region обработка комманд
private bool CanselSearchCanExecute(object arg)
{
return (String.IsNullOrEmpty(SearchField)) ? false : true;
}
private void CanselSearchExecute(object obj)
{
_components.Clear();
SelectedComponent = null;
SearchField = String.Empty;
}
private bool SelectComponentCanExecute(object arg)
{
return (SelectedComponent == null) ? false : true;
}
private async void SelectComponentExecute(object obj)
{
//спрашиваем количество
View.Dialog.InputNumericDialog dialog = new View.Dialog.InputNumericDialog();
Dialog.InputNumericDialogViewModel model = new Dialog.InputNumericDialogViewModel("Введите количество запчастей");
dialog.DataContext = model;
var result = await DialogHost.Show(dialog, "WorkDialog");
if ((bool)result == true)
{
int count = model.Numeric;
//проверка на максимальное количество
if (count>SelectedComponent.ComponentCount)
{
View.Dialog.QuestionDialog question = new View.Dialog.QuestionDialog();
Dialog.InfoDialogViewModel info = new Dialog.InfoDialogViewModel("Вы ввели больше запчастей, чем есть на складе.\nПерейти к заказу запчастей?");
question.DataContext = info;
var res = await DialogHost.Show(question, "WorkDialog");
if ((bool)result == true)
{
//TODO
}
return;
}
ComponentInstalled componentInstalled = new ComponentInstalled(SelectedComponent);
componentInstalled.InitComponentInstalled(0, 0, count, SelectedComponent.ComponentPrice, DateTime.Now);
callback.AddToList(componentInstalled);
window.frameOrderWork.GoBack();
}
}
#endregion
//из codebehind
public async void SearchComponent()
{
IsAwait = true;
_components.Clear();
List<Component> list = await ComponentDB.SearchComponentInStock(SearchField);
IsAwait = false;
if (list == null) Message("Ошибка чтения информации из базы данных!");
else if (list.Count == 0) Message("Ничего не нейдено!");
else foreach (var item in list) _components.Add(item);
}
//Wpf.DialogHost
private async void Message(string msg)
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel(msg);
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "WorkDialog");
}
}
}
|
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace LaboDotNet.Models
{
public class Reservaties
{
private static Reservaties _instance;
public static Reservaties instance
{
get
{
if (_instance == null) _instance = new Reservaties();
return _instance;
}
set { _instance = value; }
}
private DataTable _table;
private MySqlDataAdapter _da;
private Reservaties()
{
var con = DbConnect.instance.connect();
_da = new MySqlDataAdapter("SELECT nr, klant, van, naar, datum, dagen, auto FROM reservaties", con);
_table = new DataTable("reservaties");
_da.Fill(_table);
new MySqlCommandBuilder(_da);
_table.Columns["nr"].AutoIncrement = true;
}
public DataRow Select(int nr)
{
var rows = _table.Select("nr = " + nr);
return rows.Length == 0 ? null : rows[0];
}
public DataRow[] SelectByKlant(int klant)
{
return _table.Select("klant = " + klant);
}
public DataRow Add(int klant, int van, int naar, DateTime datum, int dagen, int auto)
{
var r = _table.NewRow();
r["klant"] = klant;
r["van"] = van;
r["naar"] = naar;
r["datum"] = datum;
r["dagen"] = dagen;
r["auto"] = auto;
_table.Rows.Add(r);
_da.Update(_table);
Console.WriteLine(r);
return r;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AdventureGame : MonoBehaviour
{
[SerializeField] Text textComponent;
// Start is called before the first frame update
void Start()
{
textComponent.text = "You find yourself facing two doors, each flanked by a single " +
"man. There is a plaque in front of you. 'One of these men always tells the truth; one always lies. " +
"You may ask one question. One door leads to heaven; one leads to hell.' " +
"How will you approach this?\n" +
"1. Shoot one of the men in the balls.\n" +
"2. Figure out a question you can ask that will get you through no matter what.\n" +
"3. Build a lie detector.";
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace DemoFinalExam1
{
class Program
{
static void Main(string[] args)
{
List<string> input = Console.ReadLine().Split(", ").ToList();
Dictionary<string, double> games = new Dictionary<string, double>();
Dictionary<string, string> dlc = new Dictionary<string, string>();
foreach (var item in input)
{
if (item.Contains("-"))
{
string[] current = item.Split("-");
string name = current[0];
double price = double.Parse(current[1]);
games[name] = price;
}
else if (item.Contains(":"))
{
string[] current = item.Split(":");
string name = current[0];
string content = current[1];
if (games.ContainsKey(name))
{
dlc[name] = content;
games[name] *= 1.2;
}
}
}
Dictionary<string, double> final = new Dictionary<string, double>();
Dictionary<string, double> finalDLC = new Dictionary<string, double>();
foreach (var item in games)
{
if (dlc.ContainsKey(item.Key))
{
finalDLC[item.Key] = item.Value * 0.5;
}
}
foreach (var item in games)
{
if (!dlc.ContainsKey(item.Key))
{
final[item.Key] = item.Value * 0.8;
}
}
var listDLC = finalDLC.OrderBy(x => x.Value);
var list = final.OrderByDescending(x => x.Value);
foreach (var item in listDLC)
{
Console.WriteLine($"{item.Key} - {dlc[item.Key]} - {item.Value:f2}");
}
foreach (var item in list)
{
Console.WriteLine($"{item.Key} - {item.Value:f2}");
}
}
}
}
|
using FileSystemServices.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ResponseMessages
{
[Serializable]
[XmlInclude(typeof(ResponseFileService<FileSystemElement>))]
public class ResponseFileService<T> : ResponseFileService
{
public T Data { get; set; }
}
}
|
using ExscelOpenSQL;
using Excel = Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
namespace ExcelOpenSQL
{
public partial class Form1 : Form
{
/// <summary>
/// переменная счётчик строк в dgv2
/// </summary>
private int indexRowDataGrid2 = 0;
/// <summary>
/// имя таблицы используется для вывода в итоговую таблицу
/// </summary>
private string nameTable;
private string connectionString;
/// <summary>
/// подключаемся через стркоу в файле или используем дефолтное подключение
/// </summary>
public void openConnection()
{
try
{
StreamReader sr = new StreamReader(@"connectionString.txt");
connectionString = sr.ReadLine();
}
catch
{
connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=Excel;Integrated Security=True";
}
}
/// <summary>
/// сохранение в файл нового курса
/// </summary>
public void saveRates()
{
using (StreamWriter sw = new StreamWriter(@"rates.txt", false))
{
sw.WriteLine(rates.Text);
sw.Close();
}
}
/// <summary>
/// извлекаем из файла актуальынй курс валют
/// </summary>
/// <returns></returns>
public string openRates()
{
try
{
StreamReader sr = new StreamReader(@"rates.txt");
string str = sr.ReadLine();
sr.Close();
return str;
}
catch
{
InputRates ir = new InputRates("");
return ir.getRates;
}
}
public Form1()
{
try
{
InitializeComponent();
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
openConnection();
rates.Text = openRates();
ExchangeRates er = new ExchangeRates();
rates.Text = (double.Parse(er.convert(rates.Text))).ToString();
DataGridSetting dg = new DataGridSetting();
dg.dataGrid2Size(dataGridView2, "Название товара", "Цена USD", "Цена BYR", "Кол-во");
//MessageBox.Show(er.tutByRates("https://www.tut.by/"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// добавление строки в другую таблицу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
DataGridSetting dg = new DataGridSetting();
dg.addRows(dataGridView1, dataGridView2, rates, indexRowDataGrid2, e.RowIndex, nameTable);
indexRowDataGrid2++;
usd.Text = dg.priceCount(dataGridView2, 1);
byr.Text = dg.priceCount(dataGridView2, 2);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// удаление строки из другой таблицы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView2_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
dataGridView2.Rows.RemoveAt(e.RowIndex);
DataGridSetting dg = new DataGridSetting();
usd.Text = dg.priceCount(dataGridView2, 1);
byr.Text = dg.priceCount(dataGridView2, 2);
indexRowDataGrid2--;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// очищаем вторую таблицу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void очиститьТаблицуToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
dataGridView2.Rows.Clear();
usd.Text = "0";
byr.Text = "0";
indexRowDataGrid2 = 0;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void выйтиToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
/// <summary>
/// событие нажатия энтера когда активен текстбокс, как альтернатива нажатия кнопки
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
if (textBox2.Text != "")
{
DataGridSetting dg = new DataGridSetting();
dg.searchId(dataGridView1, textBox2);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void печататьToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
ParseTextTable ptt = new ParseTextTable();
ptt.parseTextDataGrid(dataGridView2); // парсим текст таблицы что бы влазил в эксель
ExcelFile ex = new ExcelFile();
ex.saveExcel(dataGridView2, usd, byr, ptt.ListDGV2Name, ptt.ListDGV2USD, ptt.ListDGV2BYR, ptt.ListDGV2Count, "File"); // сохраняем в эсель файл
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// вносим изменения в цены после редактирования ячейки количества товара
/// </summary>
/// <param name="sender
/// <param name="e"></param>
private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
DataGridSetting dg = new DataGridSetting();
dg.editPrice(dataGridView2, usd, byr, e.RowIndex);
usd.Text = dg.priceCount(dataGridView2, 1);
byr.Text = dg.priceCount(dataGridView2, 2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// поиск по индексу с переходом на нужную строку
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
DataGridSetting dg = new DataGridSetting();
dg.searchId(dataGridView1, textBox2);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// вывод первого прайса
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void перезагрузитьToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
nameTable = "Price";
DataGridSetting dg = new DataGridSetting();
dg.dataBaseToDataGrid(dataGridView1, connectionString, nameTable, "id", "Название товара", "Цена USD", "Цена BYR");
dg.dataBasePriceUSD(dataGridView1, rates.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// вывод прайса розма
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void рОЗМАToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
nameTable = "ROZMA";
DataGridSetting dg = new DataGridSetting();
dg.dataBaseToDataGrid(dataGridView1, connectionString, nameTable, "id", "Название товара", "Размер", "Цена рублей");
dg.NDS(dataGridView1, 30);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// изменить курс доллара
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void курсДоллараToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
InputRates input = new InputRates(rates.Text);
input.ShowDialog();
rates.Text = input.getRates;
saveRates();
ExchangeRates er = new ExchangeRates();
DataGridSetting dg = new DataGridSetting();
if (nameTable == "Price")
dg.dataBasePriceUSD(dataGridView1, rates.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// печатать
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void печататьToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
ParseTextTable ptt = new ParseTextTable();
ptt.parseTextDataGrid(dataGridView2); // парсим текст таблицы что бы влазил в эксель
ExcelFile ex = new ExcelFile();
ex.saveExcel(dataGridView2, usd, byr, ptt.ListDGV2Name, ptt.ListDGV2USD, ptt.ListDGV2BYR, ptt.ListDGV2Count, "Print");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
} |
//using starteAlkemy.Controllers;
//using starteAlkemy.Models;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Web;
//using System.Web.Mvc;
//namespace starteAlkemy.Filters
//{
// public class VerifySession : ActionFilterAttribute
// {
// public override void OnActionExecuting(ActionExecutingContext filterContext)
// {
// var admin = (Admin)HttpContext.Current.Session["Admin"];
// if (admin == null)
// {
// if (filterContext.Controller is AdminController == false)
// {
// filterContext.HttpContext.Response.Redirect("~/Admin/Index");
// }
// }
// else if (admin != null && filterContext.Controller is AdminController == true)
// {
// filterContext.HttpContext.Response.Redirect("~/Project/Create");
// }
// base.OnActionExecuting(filterContext);
// }
// }
//} |
using JhinBot.GlobalConst;
using JhinBot.Interface;
using System;
using System.Globalization;
namespace JhinBot.Convo.Validators
{
public class DurationValidator : IValidator
{
private string _errorMsg;
public DurationValidator(string errorMsg)
{
_errorMsg = errorMsg;
}
public (bool success, string errorMsg) Validate(string input)
{
if (DateTime.TryParseExact(input, Global.Params.USER_INPUT_DURATION_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime duration))
{
return (duration.Hour + (duration.Minute * 60) > 0, _errorMsg);
}
return (false, _errorMsg);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1.Controllers
{
public class ContactController : Controller
{
glinttEntities gE;
glinttlocalEntities glE;
protected override void Initialize(RequestContext rc)
{
base.Initialize(rc);
gE = new glinttEntities();
glE = new glinttlocalEntities();
}
public ActionResult Index(string id)
{
return View();
}
}
}
|
using Alabo.AutoConfigs;
using Alabo.Domains.Enums;
using Alabo.Web.Mvc.Attributes;
using Alabo.Web.Mvc.ViewModel;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Cloud.People.UserTree.Domain.Configs
{
/// <summary>
/// 组织架构图设置
/// </summary>
[ClassProperty(Name = "组织架构图设置 ", Icon = "fa fa-user", Description = "组织架构图设置")]
public class UserTreeConfig : BaseViewModel, IAutoConfig
{
[Field(ControlsType = ControlsType.Switch, ListShow = true, GroupTabId = 1)]
[Display(Name = "显示门店")]
[HelpBlock("如果该会员是门店,则在家谱上面区分显示出来")]
public bool IsShowServiceCenter { get; set; } = true;
[Field(ControlsType = ControlsType.Switch, ListShow = true, GroupTabId = 1)]
[Display(Name = "显示会员等级")]
[HelpBlock("是否在组织架构图上面显示用户的会员等级")]
public bool IsShowUserGrade { get; set; } = true;
[Field(ControlsType = ControlsType.Switch, ListShow = true, GroupTabId = 1)]
[Display(Name = "显示直推会员数")]
[HelpBlock("是否在组织架构图上面显示用户的直推会员数")]
public bool IsShowDirectMemberNum { get; set; } = true;
/// <summary>
/// </summary>
[Field(ControlsType = ControlsType.Numberic, ListShow = true, GroupTabId = 1)]
[Display(Name = "会员中心显示层数")]
[Range(1, 3, ErrorMessage = "组织架构图在会员中心显示的层数,层数限制在1-3层之间")]
[HelpBlock("组织架构图在会员中心显示的层数")]
public long ShowLevel { get; set; } = 3;
/// <summary>
/// 会员物理删除后修改推荐人
/// </summary>
[Field(ControlsType = ControlsType.Switch, ListShow = true, GroupTabId = 1)]
[Display(Name = "会员物理删除后改推荐人")]
[HelpBlock("物理删除会员后, 将该删除会员下所有的会员推荐人改成,删除会员的推荐人,并重新生成组织架构图")]
public bool AfterDeleteUserUpdateParentMap { get; set; } = false;
public void SetDefault()
{
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollidersManagement : MonoBehaviour
{
public bool isLeft = false;
public float vel = 0.2f;
public States currentState;
public bool StartToDig = false;
public bool isInRightPlace = false;
private GameObject roof;
public enum States
{
relaxed,
scared,
digging
}
// Start is called before the first frame update
void Start()
{
currentState = States.relaxed;
roof = GameObject.Find("UpperWall");
}
// Update is called once per frame
void FixedUpdate()
{
if (currentState == States.relaxed) {
this.vel = 0.2f;
this.GetComponent<AnimatorController>().SetSlimeState(0);
}
else if (currentState == States.scared)
{
this.vel = 0.4f;
this.GetComponent<AnimatorController>().SetSlimeState(0);
}
else if (currentState == States.digging)
{
this.vel = 0f;
this.GetComponent<AnimatorController>().SetSlimeState(isInRightPlace ? 2 : 1);
}
if(currentState != States.digging)
{
if (isNear(this.transform.position, roof.transform.position))
{
currentState = States.scared;
}
else
{
currentState = States.relaxed;
}
}
this.transform.position += isLeft == false ? new Vector3(0.1f * vel, 0f, 0f) : new Vector3(-0.1f * vel, 0f, 0f);
}
private bool isNear(Vector3 pos1, Vector3 pos2)
{
float axisOne = Mathf.Pow((pos1[2] - pos2[2]), 2f);
float axisTwo = Mathf.Pow((pos1[1] - pos2[1]), 2f);
float result = Mathf.Sqrt(axisOne + axisTwo);
return result < 2 ? true : false;
}
private void OnTriggerEnter(Collider other)
{
switch (other.name)
{
case "DigPlace":
this.currentState = States.digging;
GameObject.Find(other.name).SetActive(false);
StartToDig = true;
break;
default:
if (isLeft == true){
isLeft = false;
}else{
isLeft = true;
this.transform.Rotate(new Vector3(0f, 180f, 0f));
}
break;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.name == "Sphere")
{
Debug.Log("You Win");
}
}
public void ReturnNaturalState()
{
this.currentState = States.relaxed;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace AnyTest.Model
{
public class Precondition
{
public long TestId { get; set; }
public long CourseId { get; set; }
public long PreconditionId { get; set; }
public virtual TestCourse Test { get; set; }
public virtual TestCourse PreconditionTest { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Uintra.Core.Member.Profile.Edit.Models
{
public class ProfileEditModel: ProfileModel
{
[Required(AllowEmptyStrings = false)]
public override string FirstName { get; set; }
[Required(AllowEmptyStrings = false)]
public override string LastName { get; set; }
}
} |
using System;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Persons
{
/// <summary>
/// Import notes for those Persons that were imported from a previous database known as 'Sygeco'.
/// </summary>
public class AdminPersonImport : Entity
{
public virtual Person Person { get; set; }
public virtual AdminPersonImportType AdminPersonImportType { get; set; }
public virtual DateTime ImportDate { get; set; }
public virtual int PreviousID { get; set; }
public virtual string Notes { get; set; }
public virtual bool Archive { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareAuthKeyLoader.Kmm
{
public class InventoryCommandListSuIdItems : KmmBody
{
public int InventoryMarker { get; private set; }
public int MaxSuIdRequested { get; private set; }
public override MessageId MessageId
{
get
{
return MessageId.InventoryCommand;
}
}
public InventoryType InventoryType
{
get
{
return InventoryType.ListSuIdItems;
}
}
public override ResponseKind ResponseKind
{
get
{
return ResponseKind.Immediate;
}
}
public InventoryCommandListSuIdItems(int inventoryMarker, int maxSuIdRequested)
{
if (inventoryMarker < 0 || inventoryMarker > 0xFFFFFF)
{
throw new ArgumentOutOfRangeException("inventoryMarker");
}
if (maxSuIdRequested < 0 || maxSuIdRequested > 0xFFFF)
{
throw new ArgumentOutOfRangeException("maxSuIdRequested");
}
InventoryMarker = inventoryMarker;
MaxSuIdRequested = maxSuIdRequested;
}
public override byte[] ToBytes()
{
byte[] contents = new byte[6];
/* inventory type */
contents[0] = (byte)InventoryType;
/* inventory marker */
contents[1] = (byte)((InventoryMarker >> 16) & 0xFF);
contents[2] = (byte)((InventoryMarker >> 8) & 0xFF);
contents[3] = (byte)(InventoryMarker & 0xFF);
/* max number of suid requested */
contents[4] = (byte)((MaxSuIdRequested >> 8) & 0xFF);
contents[5] = (byte)(MaxSuIdRequested & 0xFF);
return contents;
}
protected override void Parse(byte[] contents)
{
throw new NotImplementedException();
}
public override string ToString()
{
return string.Format("[InventoryType: {0} (0x{1:X2}), InventoryMarker: {2}, MaxSuIdRequested: {3}]", InventoryType.ToString(), (byte)InventoryType, InventoryMarker, MaxSuIdRequested);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UIMAYE.businesslayer;
using UIMAYE.classes;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace UIMAYE.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Singing : ContentPage
{
bl b = new bl();
public Singing()
{
InitializeComponent();
}
private async void kayitol(object sender, EventArgs e)
{
if(sifre.Text.Length > 5 )
{
if (Regex.IsMatch(eMail.Text, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase))
{
LocalLoginInformation ll = await b.register(sifre.Text,eMail.Text,adSoyad.Text);
if (ll.Id != 0)
{
Application.Current.Properties["id"] = ll.Id;
await Navigation.PushModalAsync(new ProjeTab());
}
}
else await DisplayAlert("Hata", "Bu doğru bir email değil", "kapat");
}
else await DisplayAlert("Hata", "Şifre 6 haneden az olamaz", "kapat");
}
}
}
|
namespace ForumSystem.Web.Tests.Controllers
{
using ForumSystem.Web.Controllers;
using ForumSystem.Web.ViewModels;
using MyTested.AspNetCore.Mvc;
using Xunit;
public class HomeControllerTests
{
[Fact]
public void GetPrivacyShouldReturnCorrectView()
=> MyController<HomeController>
.Instance()
.Calling(c => c.Privacy())
.ShouldReturn()
.View();
[Fact]
public void GetErrorShouldReturnCorrectView()
=> MyController<HomeController>
.Instance()
.Calling(c => c.Error())
.ShouldHave()
.ActionAttributes(attrs => attrs
.CachingResponse(0))
.AndAlso()
.ShouldReturn()
.View();
}
}
|
using RRExpress.Service.Entity;
using System.Web.Http;
namespace RRExpress.Service.Controllers {
public class AccountController : ApiController {
[HttpPost]
public CommonResult Reg(RegistInfo info) {
return new CommonResult() {
IsSuccess = true,
Msg = "注册成功"
};
}
}
}
|
using gView.Framework.IO;
using System.Windows.Forms;
namespace gView.Framework.UI.Controls
{
public partial class PersistStreamGrid : UserControl
{
public PersistStreamGrid()
{
InitializeComponent();
}
public IPersistStream PersistStream
{
get
{
if (treeView1.Nodes.Count != 1)
{
return null;
}
PersistableClassTreeNode node = treeView1.Nodes[0] as PersistableClassTreeNode;
if (node == null || node.PersistableClass == null)
{
return null;
}
return node.PersistableClass.ToXmlStream();
}
set
{
treeView1.Nodes.Clear();
propertyGrid1.SelectedObject = null;
if (value == null)
{
return;
}
PersistableClass cls = new PersistableClass(value as XmlStream);
AddPersisableClass(cls, null);
if (treeView1.Nodes.Count > 0)
{
treeView1.Nodes[0].Expand();
if (treeView1.Nodes[0].Nodes.Count > 0)
{
treeView1.SelectedNode = treeView1.Nodes[0].Nodes[0];
}
}
}
}
private void AddPersisableClass(PersistableClass cls, TreeNode parent)
{
if (cls == null)
{
return;
}
PersistableClassTreeNode node = new PersistableClassTreeNode(cls);
if (parent == null)
{
treeView1.Nodes.Add(node);
}
else
{
parent.Nodes.Add(node);
}
foreach (PersistableClass child in cls.ChildClasses)
{
AddPersisableClass(child, node);
}
}
#region ItemClasses
private class PersistableClassTreeNode : TreeNode
{
private PersistableClass _class;
public PersistableClassTreeNode(PersistableClass cls)
{
_class = cls;
if (_class == null)
{
return;
}
base.Text = _class.Name;
}
public PersistableClass PersistableClass
{
get { return _class; }
}
}
#endregion
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
PersistableClassTreeNode node = treeView1.SelectedNode as PersistableClassTreeNode;
if (node == null)
{
propertyGrid1.SelectedObject = null;
}
else
{
propertyGrid1.SelectedObject = node.PersistableClass;
}
txtPath.Text = treeView1.SelectedNode.FullPath;
}
}
}
|
public class ControlScheme {
public static bool isOneHanded = false;
} |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Maps.MapControl;
// vis the WMS on the Bing
namespace GeoSearch
{
public class WMSTileSource : Microsoft.Maps.MapControl.LocationRectTileSource
{
public WMSTileSource(string WMSURL, string layerName, Range<double> range, LocationRect locationRect)
: base(WMSURL + "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=" + layerName + "&STYLES=&SRS=EPSG%3A4326&BBOX={0}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=TRUE", locationRect, range)
{
}
public WMSTileSource(string WMSURL, string layerName, string time, Range<double> range, LocationRect locationRect)
: base(WMSURL + "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=" + layerName + "&STYLES=&SRS=EPSG%3A4326&BBOX={0}&WIDTH=256&HEIGHT=256&FORMAT=image/png&TRANSPARENT=TRUE&time=" + time, locationRect, range)
{
}
public override Uri GetUri(int x, int y, int zoomLevel)
{
if (zoomLevel < ZoomRange.From)
return null;
else if (zoomLevel > ZoomRange.To)
return null;
else
return new Uri(String.Format(this.UriFormat, XYZoomToBBox(x, y, zoomLevel)));
}
public string XYZoomToBBox(int x, int y, int zoom)
{
int TILE_HEIGHT = 256, TILE_WIDTH = 256;
// From the grid position and zoom, work out the min and max Latitude / Longitude values of this tile
double W = (float)(x * TILE_WIDTH) * 360 / (float)(TILE_WIDTH * Math.Pow(2, zoom)) - 180;
double N = (float)Math.Asin((Math.Exp((0.5 - (y * TILE_HEIGHT) / (TILE_HEIGHT) / Math.Pow(2, zoom)) * 4 * Math.PI) - 1) / (Math.Exp((0.5 - (y * TILE_HEIGHT) / 256 / Math.Pow(2, zoom)) * 4 * Math.PI) + 1)) * 180 / (float)Math.PI;
double E = (float)((x + 1) * TILE_WIDTH) * 360 / (float)(TILE_WIDTH * Math.Pow(2, zoom)) - 180;
double S = (float)Math.Asin((Math.Exp((0.5 - ((y + 1) * TILE_HEIGHT) / (TILE_HEIGHT) / Math.Pow(2, zoom)) * 4 * Math.PI) - 1) / (Math.Exp((0.5 - ((y + 1) * TILE_HEIGHT) / 256 / Math.Pow(2, zoom)) * 4 * Math.PI) + 1)) * 180 / (float)Math.PI;
string[] bounds = new string[] { W.ToString(), S.ToString(), E.ToString(), N.ToString() };
// Return a comma-separated string of the bounding coordinates
return string.Join(",", bounds);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace Tesseract.WebApi.Controllers
{
public class AnalyseController : ApiController
{
// GET: api/Anaylse
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpPost]
public HttpResponseMessage PostUserImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
string text = string.Empty;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 5; //Size = 2 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 5 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
// where you want to attach your imageurl
//if needed write the code to update the table
string imageName = Guid.NewGuid().ToString();
var filePath = HttpContext.Current.Server.MapPath($"~/images/{imageName}" + extension);
//Userimage myfolder name where i want to save my image
postedFile.SaveAs(filePath);
var image = new Bitmap(filePath);
TesseractEngine engine = new TesseractEngine(HttpContext.Current.Server.MapPath("~/tessdata"), "deu", EngineMode.Default);
Page page = engine.Process(image, PageSegMode.Auto);
text = page.GetText();
}
}
return Request.CreateErrorResponse(HttpStatusCode.Created, text); ;
}
var res = string.Format("Please Upload an image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format(ex.Message + "|InnerException:" + ex.InnerException?.Message);
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System.Net.Http;
using umbraco;
using Umbraco.Core;
using Umbraco.Core.Strings;
using Deploy.Helpers;
using Deploy.Controllers.Api;
namespace Deploy.ActionFilters
{
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public const string AuthorizationToken = "AuthorizationToken";
public const string HeaderOrigin = "origin";
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
{
var headerOrigin = string.Empty;
if (actionExecutedContext.Request.Headers.Contains(HeaderOrigin))
{
headerOrigin = actionExecutedContext.Request.Headers.GetValues(HeaderOrigin).FirstOrDefault();
}
if (!string.IsNullOrWhiteSpace(headerOrigin))
{
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", headerOrigin);
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "content-type, " + AuthorizationToken);
//actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
}
}
base.OnActionExecuted(actionExecutedContext);
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request != null && actionContext.Request.Method != HttpMethod.Options)
{
// Retrieve current site settings
var deployApi = new DeployApiController();
var currentSite = deployApi.GetCurrentSite();
// First of all check whether deploy is enabled for the current site
if (currentSite == null || !currentSite.Enabled)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("Remote deployment is not enabled for this site.")
};
return;
}
// Check whether there is a security key
bool authorized = false;
if (currentSite.SecurityKey != null && !string.IsNullOrWhiteSpace(currentSite.SecurityKey))
{
// If there is a security key, then checks that the origin header has been encripted using the security key
// Check wheter the origin passed by querystring matches
string headerOrigin = string.Empty;
if (actionContext.Request.Headers.Contains(HeaderOrigin))
{
headerOrigin = actionContext.Request.Headers.GetValues(HeaderOrigin).FirstOrDefault();
// Extract Host name
if (!string.IsNullOrWhiteSpace(headerOrigin))
{
var originUri = new Uri(headerOrigin);
if (originUri != null)
headerOrigin = originUri.DnsSafeHost;
}
}
string authorizationToken = string.Empty;
if (actionContext.Request.Headers.Contains(AuthorizationToken))
{
authorizationToken = actionContext.Request.Headers.GetValues(AuthorizationToken).FirstOrDefault();
}
if (headerOrigin != null && !string.IsNullOrWhiteSpace(headerOrigin)
&& authorizationToken != null && !string.IsNullOrWhiteSpace(authorizationToken)
&& CryptographyHelper.Decrypt(authorizationToken.FromUrlBase64(), currentSite.SecurityKey) == headerOrigin)
{
authorized = true;
}
}
// If the request is not authorized, change the response to let know the caller
if (!authorized)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("Missing Authorization-Token")
};
return;
}
}
base.OnActionExecuting(actionContext);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DBTransactions.ViewModel
{
public class CoursesListViewModel
{
public int ID { get; set; }
public List<int> CoursesID { get; set; }
}
}
|
namespace TripDestination.Data.Models
{
using Common.Models;
using System.ComponentModel.DataAnnotations;
using TripDestination.Common.Infrastructure.Constants;
public class Rating : BaseModel<int>
{
public string FromUserId { get; set; }
public User FromUser { get; set; }
public string RatedUserId { get; set; }
public User RatedUser { get; set; }
[Required]
[Range(ModelConstants.RatingValueMin, ModelConstants.RatingValueMax, ErrorMessage = "Rating must be between 0.0 and 5.0.")]
public double Value { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.