text
stringlengths 13
6.01M
|
|---|
public class Solution {
public int Reverse(int x) {
int res = 0;
while (x != 0) {
if (Math.Abs(res) > int.MaxValue / 10) return 0;
res = res*10 + x%10;
x /= 10;
}
return res;
}
}
|
using System.Collections.Generic;
using UnityEngine;
using SoulHunter;
public static class AudioManager // Mort - Followed Tutorial by Code Monkey, modified/adjusted to suit project
{
public enum Sound
{
PlayerWalkGrass, // Done
PlayerWalkWood, // Done
PlayerJump, // Done
PlayerLandGrass, // Done
PlayerLandWood, // Done
PlayerAttackMiss, // Done
PlayerAttackHit, // Done
PlayerDeath, // Done - subject to change
GrappleThrow, // Done
GrappleDetach, // Done
TeleportDissolve, // Done
TeleportAppear, // Done
CollectSoul, // Done
EnemyDeath, // Done
StartDialogue, // Done
EndDialogue, // Done
ClothFlowing, // Done
AmbientBirds, // Done - TODO: spawn at random spots in the level
EnemyAttack, // Done
EnemyHurt, // Done
PlayerHurt
}
// Dictionary for intervals for some sound types
private static Dictionary<Sound, float> soundTimerDictionary;
/// <summary>
/// Initializes audio timer dictionary values
/// </summary>
public static void Initialize()
{
soundTimerDictionary = new Dictionary<Sound, float>();
soundTimerDictionary[Sound.PlayerWalkGrass] = 0;
soundTimerDictionary[Sound.PlayerWalkWood] = 0;
soundTimerDictionary[Sound.PlayerJump] = 0;
soundTimerDictionary[Sound.TeleportDissolve] = 0;
soundTimerDictionary[Sound.TeleportAppear] = 0;
soundTimerDictionary[Sound.ClothFlowing] = 0;
soundTimerDictionary[Sound.StartDialogue] = 0;
}
/// <summary>
/// Plays sound in 3D space
/// </summary>
/// <param name="sound"></param>
/// <param name="position"></param>
public static void PlaySound(Sound sound, Vector3 position)
{
if (CanPlaySound(sound))
{
GameObject soundGameObject = new GameObject("Sound");
soundGameObject.transform.position = position;
AudioSource audioSource = soundGameObject.AddComponent<AudioSource>();
audioSource.clip = GetAudioClip(sound);
audioSource.maxDistance = 100f;
audioSource.spatialBlend = 1f;
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.dopplerLevel = 0f;
audioSource.Play();
audioSource.outputAudioMixerGroup = GameSettings.Instance.audioMixerGroup;
if (audioSource.clip != null)
{
Object.Destroy(soundGameObject, GetAudioClip(sound).length);
}
else
{
Object.Destroy(soundGameObject);
}
}
}
/// <summary>
/// Plays sound in 2D space
/// </summary>
/// <param name="sound"></param>
public static void PlaySound(Sound sound)
{
if (CanPlaySound(sound))
{
GameObject soundGameObject = new GameObject("Sound");
AudioSource audioSource = soundGameObject.AddComponent<AudioSource>();
audioSource.PlayOneShot(GetAudioClip(sound));
audioSource.outputAudioMixerGroup = GameSettings.Instance.audioMixerGroup;
if (audioSource.clip != null)
{
Object.Destroy(soundGameObject, GetAudioClip(sound).length);
}
else
{
Object.Destroy(soundGameObject);
}
}
}
/// <summary>
/// Sets timers for some sound types to play them in intervals
/// </summary>
/// <param name="sound"></param>
/// <returns></returns>
private static bool CanPlaySound(Sound sound)
{
switch (sound)
{
default:
return true;
case Sound.PlayerWalkGrass:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = .45f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.PlayerWalkWood:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = .45f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.PlayerJump:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = .45f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.TeleportDissolve:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = 1f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.TeleportAppear:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = 1f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.ClothFlowing:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = .3f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
case Sound.StartDialogue:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerMoveTimerMax = .1f;
if (lastTimePlayed + playerMoveTimerMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
}
break;
}
return false;
}
/// <summary>
/// Gets a random audio clip from the array of each respective sound in the library as required
/// </summary>
/// <param name="sound"></param>
/// <returns></returns>
private static AudioClip GetAudioClip(Sound sound)
{
// Go through all sound types in the game
foreach (GameAssets.SoundAudioClip soundAudioClip in GameAssets.Instance.soundAudioClipArray)
{
// If the sound type matches the currently required sound
if (soundAudioClip.sound == sound)
{
// If the audio clip array for the current sound type is not empty
if (soundAudioClip.audioClip.Length > 0)
{
// Pick a random audio clip inside the array of the current sound type
int randomClip = Random.Range(0, soundAudioClip.audioClip.Length);
// Return an error if the currently selected audio clip is null
if (soundAudioClip.audioClip[randomClip] == null)
{
Debug.LogError("Sound " + sound + " is not assigned a valid clip");
}
// Return the currently selected audio clip
return soundAudioClip.audioClip[randomClip];
}
else
{ // Return error if the audio clip array for the current sound type is empty
Debug.LogError("Sound " + sound + " array is empty!");
return null;
}
}
}
// Return error if the currently required sound type doesn't exist
Debug.LogError("Sound " + sound + " not found!");
return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Security;
using ToilluminateModel;
using ToilluminateModel.Models;
namespace ToilluminateModel.Controllers
{
public class UserMastersController : BaseApiController
{
private ToilluminateEntities db = new ToilluminateEntities();
// GET: api/UserMasters
public IQueryable<UserMaster> GetUserMaster()
{
return db.UserMaster.Where(a=>a.UseFlag == true);
}
// GET: api/UserMasters/5
[ResponseType(typeof(UserMaster))]
public async Task<IHttpActionResult> GetUserMaster(int id)
{
UserMaster userMaster = await db.UserMaster.FindAsync(id);
if (userMaster == null)
{
return NotFound();
}
return Ok(userMaster);
}
// PUT: api/UserMasters/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutUserMaster(int id, UserMaster userMaster)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != userMaster.UserID)
{
return BadRequest();
}
userMaster.UpdateDate = DateTime.Now;
db.Entry(userMaster).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserMasterExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/UserMasters
[ResponseType(typeof(UserMaster))]
public async Task<IHttpActionResult> PostUserMaster(UserMaster userMaster)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
userMaster.UpdateDate = DateTime.Now;
userMaster.InsertDate = DateTime.Now;
userMaster.Password = PublicMethods.MD5(userMaster.Password);
userMaster.UseFlag = true;
db.UserMaster.Add(userMaster);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = userMaster.UserID }, userMaster);
}
// DELETE: api/UserMasters/5
[ResponseType(typeof(UserMaster))]
public async Task<IHttpActionResult> DeleteUserMaster(int id)
{
UserMaster userMaster = await db.UserMaster.FindAsync(id);
if (userMaster == null)
{
return NotFound();
}
db.UserMaster.Remove(userMaster);
await db.SaveChangesAsync();
return Ok(userMaster);
}
[AllowAnonymous]
[HttpPost, Route("api/UserMasters/UserLogin")]
public async Task<IHttpActionResult> UserLogin(UserMaster userMaster)
{
var pwForMatch = PublicMethods.MD5(userMaster.Password);
List<UserMaster> userList = await db.UserMaster.Where(a => a.UserName == userMaster.UserName && a.Password == pwForMatch && a.UseFlag == true).ToListAsync();
if (userList.Count == 0)
{
return NotFound();
}
//save ticket in session
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, userList[0].UserName, DateTime.Now,
DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", userList[0].UserName, userList[0].Password),
FormsAuthentication.FormsCookiePath);
var EncryptTicketStr = FormsAuthentication.Encrypt(ticket);
HttpContext.Current.Session[userList[0].UserName] = EncryptTicketStr;
UserLoginInfo uli = new UserLoginInfo();
uli.Ticket = EncryptTicketStr;
uli.UserMaster = userList[0];
return Ok(uli);
}
[AllowAnonymous]
[HttpPost, Route("api/UserMasters/UserLogout")]
public async Task<IHttpActionResult> UserLogout(UserMaster userMaster)
{
HttpContext.Current.Session.Remove(userMaster.UserName);
return Ok();
}
[HttpGet, Route("api/UserMasters/GetUserByName/{userName}")]
public async Task<List<UserMaster>> GetUserByName(string userName)
{
List<UserMaster> userList = await db.UserMaster.Where(a => a.UserName == userName && a.UseFlag == true).ToListAsync();
return userList;
}
[AllowAnonymous]
[HttpGet, Route("api/UserMasters/GetUserLoginInfo")]
public async Task<IHttpActionResult> GetUserLoginInfo()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["userticket"];
if (cookie != null) {
var userticket = cookie.Value;
string userName = PublicMethods.ValidateUserInfo(userticket);
if (userName != "")
{
List<UserMaster> userList = await GetUserByName(userName);
if (userList.Count > 0)
return Ok(userList[0]);
else
return NotFound();
}
else
return NotFound();
} else
return NotFound();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool UserMasterExists(int id)
{
return db.UserMaster.Count(e => e.UserID == id && e.UseFlag == true) > 0;
}
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// 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
//
// https://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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace MP.Json
{
/// <summary>
/// Convenience class for JSON Object
/// </summary>
[DebuggerStepThrough]
public readonly struct JsonProperty
{
#region Constructor
public JsonProperty(string name, MPJson value)
{
Name = name;
Value = value;
}
#endregion
#region Properties
/// <summary>
/// Property name
/// </summary>
public readonly string Name;
/// <summary>
/// Property value
/// </summary>
public readonly MPJson Value;
#endregion
#region Methods
public static implicit operator KeyValuePair<string, object> (JsonProperty prop)
{
return new KeyValuePair<string, object>(prop.Name, prop.Value.Value);
}
public override string ToString()
{
return $"\"{Name}\" : \"{Value}\"";
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using MMDB.Extensions;
using MMDB.Utils;
namespace MMDB.Windows
{
/// <summary>
/// Interaction logic for TableFormWindow.xaml
/// </summary>
public partial class TablePlusSqlWindow : Window
{
#region Properties
public DataTable DataTable { get; set; }
public SearchResultWindow SearchResultWindow { get; set; }
#endregion
#region Ctors
public TablePlusSqlWindow()
{
InitializeComponent();
DataTable = InitializeDataGrid(tableGrid, "Table");
TableNameLabel.Content = DataTable.TableName.ToUpper();
}
#endregion
#region Private methods
private void buttonFromDB_Click(object sender, RoutedEventArgs e)
{
DataTable = TableToFromDb.GetDataFromDb(tableGrid, "Table");
}
private void buttonFromXML_Click(object sender, RoutedEventArgs e)
{
DataTable = TableToFromXml.GetDataFromXml(tableGrid, "Table");
}
private void buttonToDB_Click(object sender, RoutedEventArgs e)
{
TableToFromDb.SaveDataToDb(DataTable, "Table");
}
private void buttonToXML_Click(object sender, RoutedEventArgs e)
{
TableToFromXml.SaveDataToXml(DataTable, "Table");
}
private DataTable GenerateRows(DataTable dataTable)
{
dataTable.Rows.Add(1, "Jan", "Kowalski", 124436, DateTime.Now, "graphic5.xaml", AppDomain.CurrentDomain.BaseDirectory + "..\\..\\examples\\");
dataTable.Rows.Add(2, "Izabela", "Skorpion", 114515, DateTime.Now, "graphic.xaml", AppDomain.CurrentDomain.BaseDirectory + "..\\..\\examples\\");
dataTable.Rows.Add(3, "Grzegorz", "Cebula", 131234, DateTime.Now, "graphic2.xaml", AppDomain.CurrentDomain.BaseDirectory + "..\\..\\examples\\");
dataTable.Rows.Add(4, "Joanna", "Palec", 156789, DateTime.Now, "graphic4.xaml", AppDomain.CurrentDomain.BaseDirectory + "..\\..\\examples\\");
dataTable.Rows.Add(5, "Ewa", "Kot", 185367, DateTime.Now, "graphic3.xaml", AppDomain.CurrentDomain.BaseDirectory + "..\\..\\examples\\");
return dataTable;
}
private DataTable InitializeDataGrid(DataGrid dataGrid, string tableName)
{
DataTable dataTable = TableToFromXml.GetDataFromXml(dataGrid, tableName);
if (dataTable == null)
{
dataTable = new DataTable("Table");
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("NAME", typeof(string));
dataTable.Columns.Add("SURNAME", typeof(string));
dataTable.Columns.Add("NUMBER", typeof(int));
dataTable.Columns.Add("ADD_DATE", typeof(DateTime));
dataTable.Columns.Add("GRAPHIC", typeof(string));
dataTable.Columns.Add("PATH", typeof(string));
dataTable = GenerateRows(dataTable);
dataGrid.DataContext = dataTable.DefaultView;
}
dataGrid.ColumnWidth = (Width - dataTable.Columns.Count * 4) / dataTable.Columns.Count;
return dataTable;
}
private void PrintQueryResults(string[][] results)
{
if (results != null && results.Length > 0)
{
for (var i = 0; i < results[0].Length; ++i)
{
foreach (string[] col in results)
SqlResultsBox.AppendText(col[i] + ' ');
SqlResultsBox.AppendText("\n");
}
}
}
private void StartScriptButton_Click(object sender, RoutedEventArgs e)
{
try
{
// working queries
// select name, id, add_date from table where graphic.Contains(Ellipse >= 2)
// select name, id, add_date from table where graphic.Contains(Ellipse >= 1 with attribute Fill == Blue)
// select name, id, add_date from table where graphic.Contains(Ellipse >= 1 with attribute Area == 14000)
// select name, id, number, graphic from table where graphic.Contains(Elem >= 1 with attribute Perimeter == 500)
string sqlCommand = new TextRange(SqlCommandsBox.Document.ContentStart, SqlCommandsBox.Document.ContentEnd).Text;
SqlResultsBox.Document.Blocks.Clear();
if (sqlCommand.Contains("select") && sqlCommand.Contains("from"))
{
// getting column names
string sqlCommandColumns = sqlCommand.Substring("select ", " from");
// getting array of names
string[] sqlCommandColumnsNames = sqlCommandColumns.Split(new[] {", "}, StringSplitOptions.None);
// get result
var results = new string[sqlCommandColumnsNames.Length][];
if (sqlCommand.Contains("where"))
{
var filesFound = new List<string>();
string sqlMmQuery = sqlCommand.Substring("graphic.Contains(", ")");
var path = DataTable.Rows[0].Field<string>("PATH");
EnumerableRowCollection<string> files = from row in DataTable.AsEnumerable()
select row.Field<string>("GRAPHIC");
if (!sqlMmQuery.Contains("with attribute"))
{
string[] sqlMmQueryParts = sqlMmQuery.Split(' ');
foreach (string file in files)
if (SqlMmParser.SearchResult(path + file, sqlMmQueryParts[0], int.Parse(sqlMmQueryParts[2]), sqlMmQueryParts[1]))
{
filesFound.Add(file);
}
for (var i = 0; i < sqlCommandColumnsNames.Length; ++i)
results[i] = SqlParser.GetSqlWhereResultString(DataTable, sqlCommandColumnsNames[i], filesFound);
PrintQueryResults(results);
}
else
{
string[] sqlMmSplit = sqlMmQuery.Split(new[] {" with attribute "}, StringSplitOptions.None);
string[] sqlMmQueryParams = sqlMmSplit[0].Split(' ');
string[] sqlMmQueryAttributes = sqlMmSplit[1].Split(' ');
foreach (string file in files)
if (SqlMmParser.SearchResult(path + file, sqlMmQueryParams[0], int.Parse(sqlMmQueryParams[2]), sqlMmQueryParams[1], sqlMmQueryAttributes[0], sqlMmQueryAttributes[2]))
{
filesFound.Add(file);
}
for (var i = 0; i < sqlCommandColumnsNames.Length; ++i)
results[i] = SqlParser.GetSqlWhereResultString(DataTable, sqlCommandColumnsNames[i], filesFound);
PrintQueryResults(results);
}
SearchResultWindow = new SearchResultWindow(filesFound, path);
SearchResultWindow.Show();
}
else
{
for (var i = 0; i < sqlCommandColumnsNames.Length; ++i)
results[i] = SqlParser.GetSqlColumnResultString(DataTable, sqlCommandColumnsNames[i]);
PrintQueryResults(results);
}
}
}
catch (Exception ex)
{
SqlResultsBox.AppendText(ex.Message + '\n' + ex.StackTrace);
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.F5)
{
StartScriptButton_Click(sender, e);
}
}
#endregion
}
}
|
using System;
namespace Infrostructure.Exeption
{
public class InvalidInstallmentPaymentExeption : Exception
{
public InvalidInstallmentPaymentExeption(string message = "پرداهت اقساطی به درستی پر نشده است(لیست اقساط خالی است یا مبلغ نهایی ثبت نشده است)") : base(message) { }
}
}
|
using UnityEngine;
namespace ComLib.Unity.Components
{
public abstract class SingletonComponent<T> : SingletonComponent where T : MonoBehaviour
{
public static T Instance
{
get { return instance; }
}
private static T instance = default(T);
public override void Setup()
{
if (instance != this) instance = this as T;
}
public override void Clear()
{
if (instance == this) instance = null;
}
}
public abstract class SingletonComponent : MonoBehaviour
{
public abstract void Setup();
public abstract void Clear();
protected virtual void Awake()
{
Setup();
}
protected virtual void OnDestroy()
{
Clear();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.matrix_problems
{
/// <summary>
/// A matrix is given with 0's and 1's and is sorted in ascending order in the rows and columns.
/// Calculate the number of 0's in the matrix
/// </summary>
class CountZerosInMatrix
{
}
}
|
namespace AddVat
{
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Func<String, double> parser = n => double.Parse(n);
Func<double, double> addVat = n => n + n * 20 / 100;
Func<double, string> output = n => $"{n:f2}";
var input = Console.ReadLine().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parser)
.Select(addVat)
.Select(output);
Console.WriteLine(string.Join("\n", input));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSVHandler
{
class AutomaticPayment : Transaction
{
protected String autoPayName, autoPayNumber;
public AutomaticPayment(String transDate, String transType, String autoPayNumber, String autoPayName,
double transValue, double accBalance)
: base(transDate, transType, transValue, accBalance) {
this.autoPayName = autoPayName;
this.autoPayNumber = autoPayNumber;
}
public override string getVendor()
{
return this.autoPayName;
}
public override String toString() {
return "Auto Pay: "+autoPayName+" on "+transDate+", Value $"+String.Format("{0:0,0.00}", transValue);
}
}
}
|
using System;
namespace Piovra.Ds;
public class RBTree<K, V> where K : IComparable<K> {
readonly Node _nil;
Node _root;
public RBTree() {
_nil = new Node { Color = BLACK };
_root = _nil;
}
public Result<V> GetValue(K key) {
var x = _root;
while (x != _nil) {
var cmp = key.CompareTo(x.Key);
if (cmp == 0) {
break;
}
if (cmp < 0) {
x = x.L;
} else {
x = x.R;
}
}
return x != null ? Result<V>.Of(x.Value) : null;
}
public void Add(K key, V value) {
var z = new Node { Key = key, Value = value, Color = RED };
var y = _nil;
var x = _root;
int cmp;
while (x != _nil) {
y = x;
cmp = z.Key.CompareTo(x.Key);
if (cmp < 0) {
x = x.L;
} else {
x = x.R;
}
}
z.P = y;
if (y == _nil) {
_root = z;
} else {
cmp = z.Key.CompareTo(y.Key);
if (cmp < 0) {
y.L = z;
} else {
y.R = z;
}
}
z.L = _nil;
z.R = _nil;
z.Color = RED;
Restore(z);
}
void Restore(Node z) {
while (z.P.Color == RED) {
if (z.P == z.P.P.L) {
var y = z.P.P.R;
if (y.Color == RED) {
z.P.Color = BLACK;
y.Color = BLACK;
z.P.P.Color = RED;
z = z.P.P;
} else {
if (z == z.P.R) {
z = z.P;
LeftRotate(z);
}
z.P.Color = BLACK;
z.P.P.Color = RED;
RightRotate(z.P.P);
}
} else {
var y = z.P.P.L;
if (y.Color == RED) {
z.P.Color = BLACK;
y.Color = BLACK;
z.P.P.Color = RED;
z = z.P.P;
} else {
if (z == z.P.L) {
z = z.P;
RightRotate(z);
}
z.P.Color = BLACK;
z.P.P.Color = RED;
LeftRotate(z.P.P);
}
}
}
_root.Color = BLACK;
}
void LeftRotate(Node x) {
var y = x.R;
x.R = y.L;
if (y.L != _nil) {
y.L.P = x;
}
y.P = x.P;
if (x.P == _nil) {
_root = y;
} else if (x == x.P.L) {
x.P.L = y;
} else {
x.P.R = y;
}
y.L = x;
x.P = y;
}
void RightRotate(Node x) {
var y = x.L;
x.L = y.R;
if (y.R != _nil) {
y.R.P = x;
}
y.P = x.P;
if (x.P == _nil) {
_root = y;
} else if (x == x.P.R) {
x.P.R = y;
} else {
x.P.L = y;
}
y.R = x;
x.P = y;
}
class Node {
public K Key { get; set; }
public V Value { get; set; }
public Colors Color { get; set; }
public Node P { get; set; }
public Node L { get; set; }
public Node R { get; set; }
}
const Colors RED = Colors.RED;
const Colors BLACK = Colors.BLACK;
enum Colors {
RED, BLACK
}
}
|
using System.IO;
using Microsoft.DeepZoomTools;
namespace Docller.Core.Images
{
public class DeepZoomImageProvider : IZoomableImageProvider
{
public string GenerateZoomableImage(string inputImage, string destFolder)
{
ImageCreator ic = new ImageCreator
{
TileSize = 256,
TileFormat = ImageFormat.Png,
ImageQuality = 0.95,
TileOverlap = 0
};
string target = destFolder + "\\zoomed";
string dziFile = string.Format("{0}\\zoomed.xml", destFolder);
if (!File.Exists(dziFile))
{
ic.Create(inputImage, target);
}
return dziFile;
}
}
}
|
using System;
using CRUD_Razor_2_1.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace CRUD_Razor_2_1.Data
{
public class DbInitializer: IDbInitialize
{
private readonly ApplicationDbContext _db;
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DbInitializer(ApplicationDbContext db, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
_db = db;
_userManager = userManager;
_roleManager = roleManager;
}
public void Initialize()
{
//_db.Database.Migrate();
//if (_db.Roles.Any(r => r.Name == SD.SuperAdminEndUser)) return;
//_roleManager.CreateAsync(new IdentityRole(SD.AdminEndUser)).GetAwaiter().GetResult();
//_roleManager.CreateAsync(new IdentityRole(SD.SuperAdminEndUser)).GetAwaiter().GetResult();
}
}
}
|
using Domain;
using Repository;
using RepositoryInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebAPI.Controllers
{
public class MenuController : ApiController
{
public IList<VMEN> GetMenuByUser(TUSR user)
{
dbEntities db = new dbEntities();
IMenuRepository _repository = new MenuRepository(db);
IList<VMEN> ret = _repository.GetMenuByUser(user);
return ret;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using ApartmentApps.Data;
namespace ApartmentApps.Api.Modules
{
[Persistant]
public class Message : PropertyEntity
{
public string FromId { get; set; }
[ForeignKey("FromId"),Searchable]
public ApplicationUser From
{
get;set;
}
public int SentToCount { get; set; }
[Searchable]
public string Subject { get; set; }
public string Body { get; set; }
[Searchable]
public DateTime? SentOn { get; set; }
public string Filter { get; set; }
public virtual ICollection<MessageReceipt> MessageReceipts { get; set; }
public int TargetsCount { get; set; }
public string TargetsDescription { get; set; }
[Searchable]
public bool Sent { get; set; }
[Searchable]
public MessageStatus Status {get; set; }
public string ErrorMessage { get; set; }
}
public enum MessageStatus
{
Draft,
Sending,
Sent,
Error
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MoodleObjects;
namespace HonsService
{
[TestClass]
public class TestsMoodleDB
{
[TestMethod]
public void GetCourseByID()
{
int ID = 1;
MoodleCourse course =MoodleDB.getMoodleDB().getCourse(ID);
Assert.AreEqual(course.ID, ID);
Assert.IsNotNull(course.desc);
}
[TestMethod]
public void GetUserByID()
{
int ID = 1;
MoodleUser user = MoodleDB.getMoodleDB().getUserByID(ID);
Assert.AreEqual(user.ID, ID);
Assert.IsNotNull(user.fName);
}
}
}
|
using PhotonInMaze.Common.Model;
using System.Collections.Generic;
namespace PhotonInMaze.Common.Controller {
public interface IMazeCellManager {
IMazeCell GetMazeCell(int row, int column);
bool IsPathToGoalVisited(HashSet<IMazeCell> visitedCells);
bool IsATrap(HashSet<IMazeCell> visitedCells, IMazeCell current);
IMazeCell GetExitCell();
IMazeCell GetStartCell();
}
}
|
using System.Collections.Generic;
using Uintra.Core.Activity;
using Uintra.Core.Activity.Entities;
using Uintra.Core.Jobs.Models;
namespace Uintra.Features.Jobs
{
public class UpdateActivityCacheJob : UintraBaseIntranetJob
{
private readonly IEnumerable<IIntranetActivityService<IIntranetActivity>> _activityServices;
public UpdateActivityCacheJob(IEnumerable<IIntranetActivityService<IIntranetActivity>> activityServices)
{
_activityServices = activityServices;
}
public override void Action()
{
ProcessActivities();
}
private void ProcessActivities()
{
foreach (var service in _activityServices)
{
var intranetActivities = service.GetAll();
foreach (var activity in intranetActivities)
{
if (activity.IsPinActual && !service.IsPinActual(activity))
{
var cacheableIntranetActivityService = (ICacheableIntranetActivityService<IIntranetActivity>)service;
cacheableIntranetActivityService.UpdateActivityCache(activity.Id);
}
}
}
}
}
}
|
using System;
using System.IO;
#if WINRT
using Windows.Storage.Streams;
#endif
namespace Jypeli
{
public partial class FileManager
{
/*
public LoadState BeginLoadContent( string assetName )
{
if ( Game.Instance == null )
throw new InvalidOperationException( "Content can not be loaded here, because the game has not been initialized." );
StorageFile contentFile = Game.Instance.Content.Load<StorageFile>( assetName );
return new LoadState( contentFile, assetName );
}
public T LoadContent<T>( T obj, string assetName )
{
if ( Game.Instance == null )
throw new InvalidOperationException( "Content can not be loaded here, because the game has not been initialized." );
byte[] contentData = Game.Instance.Content.Load<byte[]>( assetName );
MemoryStream contentStream = new MemoryStream( contentData );
StorageFile contentFile = new StorageFile( assetName, contentStream );
LoadState state = BeginLoad( contentFile, assetName );
T result = state.Load<T>( obj, "default" );
state.EndLoad();
return result;
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace DSSAHP
{
public class NodeProject
{
public string Name { get; set; }
public int Level { get; set; }
public string Description { get; set; }
public double Coefficient { get; set; }
[XmlArrayItem("Node")]
public NodeProject[] Criterias { get; set; }
[XmlArrayItem("row")]
public double[][] Values { get; set; }
}
}
|
using A4CoreBlog.Data.Infrastructure;
using A4CoreBlog.Data.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace A4CoreBlog.Web.Areas.Admin.ViewComponents
{
public class PaginatedListControllsComponent : ViewComponent
{
public PaginatedListControllsComponent()
{
}
public async Task<IViewComponentResult> InvokeAsync(BasePaginatedList list)
{
return View("Default", list);
}
}
}
|
namespace Sentry.Tests;
public class SessionTests
{
private readonly IDiagnosticLogger _testOutputLogger;
public SessionTests(ITestOutputHelper output)
{
_testOutputLogger = new TestOutputDiagnosticLogger(output);
}
[Fact]
public void Serialization_Session_Success()
{
// Arrange
var session = new Session(
SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"),
"bar",
DateTimeOffset.Parse("2020-01-01T00:00:00+00:00", CultureInfo.InvariantCulture),
"release123",
"env123",
"192.168.0.1",
"Google Chrome");
session.ReportError();
session.ReportError();
session.ReportError();
var sessionUpdate = new SessionUpdate(
session,
true,
DateTimeOffset.Parse("2020-01-02T00:00:00+00:00", CultureInfo.InvariantCulture),
5,
SessionEndStatus.Crashed);
// Act
var json = sessionUpdate.ToJsonString(_testOutputLogger, indented: true);
// Assert
json.Should().Be("""
{
"sid": "75302ac48a024bde9a3b3734a82e36c8",
"did": "bar",
"init": true,
"started": "2020-01-01T00:00:00+00:00",
"timestamp": "2020-01-02T00:00:00+00:00",
"seq": 5,
"duration": 86400,
"errors": 3,
"status": "crashed",
"attrs": {
"release": "release123",
"environment": "env123",
"ip_address": "192.168.0.1",
"user_agent": "Google Chrome"
}
}
""");
}
[Fact]
public void CreateUpdate_IncrementsSequenceNumber()
{
// Arrange
var session = new Session(
SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"),
"bar",
DateTimeOffset.Parse("2020-01-01T00:00:00+00:00", CultureInfo.InvariantCulture),
"release123",
"env123",
"192.168.0.1",
"Google Chrome");
// Act
var sessionUpdate1 = session.CreateUpdate(true, DateTimeOffset.Now);
var sessionUpdate2 = session.CreateUpdate(false, DateTimeOffset.Now);
var sessionUpdate3 = session.CreateUpdate(false, DateTimeOffset.Now);
// Assert
sessionUpdate1.SequenceNumber.Should().Be(0);
sessionUpdate2.SequenceNumber.Should().Be(1);
sessionUpdate3.SequenceNumber.Should().Be(2);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.PrintModel.ORD;
using com.Sconit.Entity;
using com.Sconit.Entity.MRP.TRANS;
using com.Sconit.Entity.MRP.VIEW;
using NPOI.SS.UserModel;
namespace com.Sconit.Utility.Report.Operator
{
public class RepShiftPlanExOperator : RepTemplate1
{
public RepShiftPlanExOperator()
{
}
/**
* 填充报表
*/
protected override bool FillValuesImpl(String templateFileName, IList<object> list, int sheetIndex)
{
try
{
if (sheetIndex == 0)
{
//MrpPlanView dailyPlanView = (MrpPlanView)(list[0]);
//int headColumnIndex = 5;
//int bodyRowIndex = 1;
//foreach (var columnCell in dailyPlanView.PlanHead.ColumnCellList)
//{
// this.SetRowCell(0, headColumnIndex, columnCell.PlanDate.Date);
// headColumnIndex++;
//}
//foreach (var planBody in dailyPlanView.PlanBodyList)
//{
// int bodyColumnIndex = 5;
// this.SetRowCell(bodyRowIndex, 0, planBody.Flow);
// this.SetRowCell(bodyRowIndex, 1, planBody.Item);
// this.SetRowCell(bodyRowIndex, 2, planBody.ItemDescription);
// this.SetRowCell(bodyRowIndex, 3, planBody.Uom);
// this.SetRowCell(bodyRowIndex, 4, planBody.ShiftQuota);
// foreach (var rowCell in planBody.RowCellList)
// {
// this.SetRowCell(bodyRowIndex, bodyColumnIndex, rowCell.PlanQty);
// bodyColumnIndex++;
// }
// bodyRowIndex++;
//}
}
else
{
IList<ShiftPlanView> shiftPlanViews = (IList<ShiftPlanView>)(list[1]);
for (int i = 1; i < shiftPlanViews.Count(); i++)
{
ISheet newSheet = workbook.CreateSheet(shiftPlanViews.ElementAt(i).ProductLine);
newSheet = workbook.CloneSheet(1);
this.sheet = newSheet;
}
foreach (var shiftPlanView in shiftPlanViews)
{
int headColumnIndex = 4;
int bodyRowIndex = 1;
foreach (var columnCell in shiftPlanView.PlanHead.ColumnCellList)
{
if ((headColumnIndex - 4) % 3 == 0)
{
this.SetRowCell(0, headColumnIndex, columnCell.PlanDate);
}
this.SetRowCell(1, headColumnIndex, columnCell.Shift);
headColumnIndex++;
}
foreach (var planBody in shiftPlanView.PlanBodyList)
{
int bodyColumnIndex = 4;
this.SetRowCell(bodyRowIndex, 0, planBody.Item);
this.SetRowCell(bodyRowIndex, 1, planBody.ItemDescription);
this.SetRowCell(bodyRowIndex, 2, planBody.Uom);
this.SetRowCell(bodyRowIndex, 3, planBody.ShiftQuota);
foreach (var rowCell in planBody.RowCellList)
{
this.SetRowCell(bodyRowIndex, bodyColumnIndex, rowCell.Qty);
bodyColumnIndex++;
}
bodyRowIndex++;
}
}
}
}
catch (Exception)
{
return false;
}
return true;
}
/**
* 需要拷贝的数据与合并单元格操作
*
* Param pageIndex 页号
*/
public override void CopyPageValues( int pageIndex)
{
}
}
}
|
using Xunit;
namespace dgPower.KMS.Tests
{
public sealed class MultiTenantFactAttribute : FactAttribute
{
public MultiTenantFactAttribute()
{
if (!KMSConsts.MultiTenancyEnabled)
{
Skip = "MultiTenancy is disabled.";
}
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace SciVacancies.WebApp.ViewModels
{
public class InterestDetailsViewModel : InterestEditViewModel
{
}
public class InterestEditViewModel
{
[MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")]
public string IntName { get; set; }
[MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")]
public string IntNameEn { get; set; }
}
}
|
using DirectFerries.Business;
using DirectFerries.Business.Interfaces;
using DirectFerries.Models;
using System;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
namespace DirectFerries.Controllers
{
public class HomeController : Controller
{
private IDateService _dateOfBirthAndFullNameValidationService;
/* Best to use IoC, but for illustration won't be using it.
*
public HomeController(IDateService dateOfBirthAndFullNameValidationService)
{
_dateOfBirthAndFullNameValidationService = dateOfBirthAndFullNameValidationService;
_dateOfBirthAndFullNameValidationService.Vowels = ConfigurationManager.AppSettings["Vowels"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(ch => ch[0]).ToArray();
}*/
public HomeController()
{
_dateOfBirthAndFullNameValidationService = new DateOfBirthAndFullNameValidationService();
_dateOfBirthAndFullNameValidationService.Vowels = ConfigurationManager.AppSettings["Vowels"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(ch => ch[0]).ToArray();
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(UserDetailViewModel userDetails)
{
if (ModelState.IsValid)
{
var noOfDaysToBirthdayDisplayed = 14;
var actualNumberOfVowels =_dateOfBirthAndFullNameValidationService.NumberOfVowels(userDetails.FirstName);
var userAge = _dateOfBirthAndFullNameValidationService.UsersAge(userDetails.DateOfBirth);
var daysBeforeNextBirthday = _dateOfBirthAndFullNameValidationService.NumberOfDaysBeforeNextBirthDay(userDetails.DateOfBirth);
var f14DaysToBirthday = daysBeforeNextBirthday <= noOfDaysToBirthdayDisplayed;
return Redirect($"~/Home/ResultsPage?firstName={userDetails.FirstName}&noOfVowels={actualNumberOfVowels}&daysBeforeNextBirthDay={daysBeforeNextBirthday}&userAge={userAge}&if14DaysToBirthday={f14DaysToBirthday}");
}
return View(userDetails);
}
[HttpGet]
public ActionResult ResultsPage(string firstName, int noOfVowels, int daysBeforeNextBirthDay, int userAge, bool if14DaysToBirthday)
{
ViewBag.FirstName = firstName;
ViewBag.NoOfVowels = noOfVowels;
ViewBag.UserAge = userAge;
ViewBag.NoOfDaysToNextBirthDay = daysBeforeNextBirthDay;
ViewBag.DateIs14DaysToBD = if14DaysToBirthday;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace WebApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
}
public static IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Add Authentication services.
services.AddAuthentication();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Add the console logger.
loggerFactory.AddConsole(LogLevel.Debug);
// Configure the app to use Jwt Bearer Authentication
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Authority = Configuration["AzureAd:CommonAuthority"],
//Authority = Configuration["AzureAd:TenantAuthority"],
Audience = Configuration["AzureAd:Audience"],
TokenValidationParameters =
new TokenValidationParameters {SaveSigninToken = true, ValidateIssuer = false}
});
app.UseMvc(routes =>
{
routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
public class Solution {
public int MaxPoints(int[][] points) {
int n = points.Length;
int res = 0;
for (int i = 0; i < n; i ++) {
int x1 = points[i][0];
int y1 = points[i][1];
int duplicate = 1;
for (int j = 1; j < n; j ++) {
int x2 = points[j][0];
int y2 = points[j][1];
if (x1 == x2 && y1 == y2) {
duplicate ++;
continue;
}
int currRes = 0;
for (int k = 0; k < n; k ++) {
int x3 = points[k][0];
int y3 = points[k][1];
if ((x3 - x2) * (y2 - y1) == (x2 - x1) * (y3 - y2)) {
currRes ++;
}
}
res = Math.Max(res, currRes);
}
res = Math.Max(res, duplicate);
}
return res;
}
}
|
using PatientService.Model;
namespace PatientService.Repository
{
public interface IPatientRepository
{
Patient Get(string jmbg);
Patient GetLazy(string jmbg);
void Update(Patient patient);
void Add(Patient patient);
}
}
|
using System;
namespace ShoppingListApi.Models.SharedModels
{
public class BasePagination
{
public int? PageSize { get; set; }
public int? PageNumber { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
public partial class Admin_brandlist : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["did"] != null)
{
SqlCommand cmd = new SqlCommand("delete from tbproduct where id=@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", Request.QueryString["did"]);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
string st = "";
if (Request.QueryString["Category"] != null)
{
st = "SELECT * from tbproduct where p_subcat='" + Request.QueryString["Category"] + "'";
}
else if (Request.QueryString["Brand"] != null)
{
st = "SELECT * from tbproduct where p_brand='" + Request.QueryString["Brand"] + "'";
}
else
{
st = "SELECT * from tbproduct";
}
SqlCommand command = new SqlCommand(st, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Literal1.Text += "<div class='col-sm-4'><div class='product-image-wrapper'><div class='single-products'><div class='productinfo text-center'>" +
"<img src = 'product/" + reader.GetString(5) + "' alt = '' /><h2>$" + reader.GetString(10) + " </h2><p> " + reader.GetString(4) + " </p> " +
" <a href = 'productdetail.aspx?id=" + reader.GetInt32(0) + "' class='btn btn-default add-to-cart'><i class='fa fa-info'></i>Detail's</a>" +
" <a href = 'cartproduct.aspx?Product=" + reader.GetInt32(0) + "' class='btn btn-default add-to-cart'><i class='fa fa-shopping-cart'></i>Add To Cart</a>" +
"</div></div><div class='choose'></div></div></div>";
}
}
reader.Close();
con.Close();
}
}
|
using System;
using Juicy.WindowsService;
namespace SampleService.Tasks
{
class DailyReportTask : ScheduledTask
{
readonly static log4net.ILog Log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override void Execute(DateTime scheduledDate)
{
//time to run....
//TODO: write the actual code here
// SalesReport.SendDailySummary();
Log.InfoFormat("Executed: {0}", this.GetType().Name);
}
}
}
|
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace RU.Tinkoff.Core.Log.Internal {
// Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.core.log.internal']/class[@name='AndroidLogger']"
[global::Android.Runtime.Register ("ru/tinkoff/core/log/internal/AndroidLogger", DoNotGenerateAcw=true)]
public partial class AndroidLogger : global::Java.Lang.Object, global::RU.Tinkoff.Core.Log.Internal.ILoggerDelegate {
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("ru/tinkoff/core/log/internal/AndroidLogger", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (AndroidLogger); }
}
protected AndroidLogger (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.core.log.internal']/class[@name='AndroidLogger']/constructor[@name='AndroidLogger' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe AndroidLogger ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
try {
if (((object) this).GetType () != typeof (AndroidLogger)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor);
} finally {
}
}
static Delegate cb_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetLog_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_Handler ()
{
if (cb_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_ == null)
cb_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, IntPtr, IntPtr, IntPtr>) n_Log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_);
return cb_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_;
}
static void n_Log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, int p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3)
{
global::RU.Tinkoff.Core.Log.Internal.AndroidLogger __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Core.Log.Internal.AndroidLogger> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Throwable p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Throwable> (native_p1, JniHandleOwnership.DoNotTransfer);
string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer);
string p3 = JNIEnv.GetString (native_p3, JniHandleOwnership.DoNotTransfer);
__this.Log (p0, p1, p2, p3);
}
#pragma warning restore 0169
static IntPtr id_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.core.log.internal']/class[@name='AndroidLogger']/method[@name='log' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='java.lang.Throwable'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='java.lang.String']]"
[Register ("log", "(ILjava/lang/Throwable;Ljava/lang/String;Ljava/lang/String;)V", "GetLog_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_Handler")]
public virtual unsafe void Log (int p0, global::Java.Lang.Throwable p1, string p2, string p3)
{
if (id_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero)
id_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "log", "(ILjava/lang/Throwable;Ljava/lang/String;Ljava/lang/String;)V");
IntPtr native_p2 = JNIEnv.NewString (p2);
IntPtr native_p3 = JNIEnv.NewString (p3);
try {
JValue* __args = stackalloc JValue [4];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (native_p2);
__args [3] = new JValue (native_p3);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_log_ILjava_lang_Throwable_Ljava_lang_String_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "log", "(ILjava/lang/Throwable;Ljava/lang/String;Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_p2);
JNIEnv.DeleteLocalRef (native_p3);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class addComponent : MonoBehaviour {
public int maxSpeedF;
public int maxSpeedB;
public int maxRotation;
public float rechargeMissileTime;
public float rechargeBulletTime;
public GameObject ship;
public ParticleSystem engineParticles;
private float lastMissileTime;
private float lastBulletTime;
private Animator shipAnimator;
// Use this for initialization
void Start () {
lastMissileTime = 0f;
lastBulletTime = 0f;
shipAnimator = ship.GetComponent<Animator>();
engineParticles.enableEmission = false;
}
void FixedUpdate(){
// transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y+ rot, transform.rotation.z);
// rot = rot + 1.5f;
// transform.Rotate (new Vector3 (0, 1.5f, 0));
lastMissileTime += Time.deltaTime;
lastBulletTime += Time.deltaTime;
if(Input.GetAxis("Vertical") > 0.5f) {
engineParticles.enableEmission = true;
if(rigidbody.velocity.z < maxSpeedF)
rigidbody.AddForce((transform.forward) * 10);
}else
engineParticles.enableEmission = false;
if(Input.GetAxis("Vertical") < -0.5f) {
if(rigidbody.velocity.z > -maxSpeedB)
rigidbody.AddForce((transform.forward) * -10);
}
shipAnimator.SetFloat ("Direction", -Input.GetAxis("Horizontal"));
if(Input.GetAxis("Horizontal") > 0.5f) {
if(rigidbody.angularVelocity.y < maxRotation)
rigidbody.AddTorque(Vector3.up * 1);
//transform.Rotate (new Vector3 (0, 1.5f, 0));
}
if(Input.GetAxis("Horizontal") < -0.5f) {
if(rigidbody.angularVelocity.y > -maxRotation)
rigidbody.AddTorque(Vector3.up * -1);
//transform.Rotate (new Vector3 (0, -1.5f, 0));
}
if(Input.GetKeyDown(KeyCode.Space)) {
if(lastMissileTime > rechargeMissileTime){
shotMissile();
lastMissileTime = 0;
}
}
if(Input.GetKey(KeyCode.LeftShift)) {
if(lastBulletTime > rechargeBulletTime){
shotBullet();
lastBulletTime = 0;
}
}
}
void shotMissile(){
GameObject missile = GameObject.FindGameObjectWithTag("missile");
Vector3 newPos = transform.position + new Vector3 (0, 1, 0);
Quaternion newRot = Quaternion.Euler(transform.eulerAngles.x,transform.eulerAngles.y + 270,transform.eulerAngles.z);
GameObject part = (GameObject)Instantiate(missile, newPos, newRot);
// part.transform.parent = transform;
missileBehavior partBehavior = (missileBehavior) part.GetComponent(typeof(missileBehavior));
partBehavior.setMissile (true);
partBehavior.setParent (gameObject);
partBehavior.launchMissile ();
}
void shotBullet(){
GameObject bullet = GameObject.FindGameObjectWithTag("bullet");
Vector3 newPos = transform.position + new Vector3 (0, 1, 0);
Quaternion newRot = Quaternion.Euler(transform.eulerAngles.x + 90,transform.eulerAngles.y,transform.eulerAngles.z);
GameObject part = (GameObject)Instantiate(bullet, newPos, newRot);
// part.transform.parent = transform;
missileBehavior partBehavior = (missileBehavior) part.GetComponent(typeof(missileBehavior));
partBehavior.setMissile (true);
Rigidbody rigidMissile = part.rigidbody;
rigidMissile.AddForce((part.transform.up) * 500);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomationFramework.KendoWrapper
{
/// <summary>
/// Grid filter
/// </summary>
public class GridFilter
{
public GridFilter(string columnName, FilterOperator filterOperator, string filterValue)
{
this.ColumnName = columnName;
this.FilterOperator = filterOperator;
this.FilterValue = filterValue;
}
public string ColumnName { get; set; }
public FilterOperator FilterOperator { get; set; }
public string FilterValue { get; set; }
}
}
|
using Breeze.AssetTypes;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Breeze.Screens
{
public class XuiDialog
{
public static async Task<int> ShowDialog(SmartSpriteBatch spriteBatch, string title, string body,
List<string> buttons)
{
TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>();
XuiDialog dialog = new XuiDialog();
DialogScreen screen = new DialogScreen
{
Buttons = new List<StaticButtonAsset>()
};
List<StaticButtonAsset> buttonStack = ButtonHelpers.CreateButtonHorizontalStack(new Vector2(0.2f, 0.65f), 0.3f,
0.1f, 0.025f,
buttons.Select(t => new ButtonBasics(t, (args) =>
{
dialog.HandleClick(t, buttons.IndexOf(t), completionSource, screen);
})).ToList());
screen.Buttons.AddRange(buttonStack);
screen.Title = title;
screen.Body = body;
await screen.Initialise();
Solids.Instance.ScreenManager.Add(screen);
return await completionSource.Task;
}
public static async Task<DialogButton> ShowDialog(SmartSpriteBatch spriteBatch, string title, string body, List<DialogButton> buttons)
{
TaskCompletionSource<DialogButton> completionSource = new TaskCompletionSource<DialogButton>();
XuiDialog dialog = new XuiDialog();
DialogScreen screen = new DialogScreen
{
Buttons = new List<StaticButtonAsset>()
};
float margin = 0.005f;
List<StaticButtonAsset> buttonStack = ButtonHelpers.CreateButtonHorizontalStack(new FloatRectangle(0.15f, 0.75f - margin - margin, 0.75f, 0.1f),
0.1f, margin,
buttons.Select(t => new ButtonBasics(t.Text, (args) =>
{
dialog.HandleClick(t, completionSource, screen);
})).ToList());
screen.Buttons.AddRange(buttonStack);
screen.Title = title;
screen.Body = body;
await screen.Initialise();
Solids.Instance.ScreenManager.Add(screen);
Solids.Instance.ScreenManager.BringToFront(screen);
return await completionSource.Task;
}
//public static async Task<DialogButton> ShowTextDialog(SmartSpriteBatch spriteBatch, string title, string body, bool numberOnly, List<DialogButton> buttons)
//{
// TaskCompletionSource<DialogButton> completionSource = new TaskCompletionSource<DialogButton>();
// XuiDialog dialog = new XuiDialog();
// TextEntryScreen screen = new TextEntryScreen
// {
// Buttons = new List<ButtonAsset>(),
// NumberOnly = numberOnly
// };
// float margin = 0.005f;
// List<ButtonAsset> buttonStack = ButtonAsset.CreateButtonHorizontalStack(new FloatRectangle(0.15f, 0.75f - margin - margin, 0.75f, 0.1f),
// 0.1f, margin,
// buttons.Select(t => new ButtonBasics(t.Text, (args) =>
// {
// dialog.HandleTextEntryClick(t, completionSource, screen, screen.EnteredText);
// })).ToList());
// screen.Buttons.AddRange(buttonStack);
// screen.Title = title;
// screen.Body = body;
// await screen.Initialise();
// Solids.Screens.Add(screen);
// Solids.Screens.BringToFront(screen);
// return await completionSource.Task;
//}
public static void FireDialog(SmartSpriteBatch spriteBatch, string title, string body, List<DialogButton> buttons)
{
TaskCompletionSource<DialogButton> completionSource = new TaskCompletionSource<DialogButton>();
XuiDialog dialog = new XuiDialog();
DialogScreen screen = new DialogScreen
{
Buttons = new List<StaticButtonAsset>()
};
float margin = 0.02f;
float fontMargin = 0.03f;
List<StaticButtonAsset> buttonStack = ButtonHelpers.CreateButtonHorizontalStack(new FloatRectangle(0.15f, 0.75f - margin, 0.75f, 0.1f),
0.1f, margin,
buttons.Select(t => new ButtonBasics(t.Text, (args) =>
{
dialog.HandleClick(t, completionSource, screen);
})).ToList(), fontMargin);
screen.Buttons.AddRange(buttonStack);
screen.Title = title;
screen.Body = body;
screen.Initialise();
Solids.Instance.ScreenManager.Add(screen);
Solids.Instance.ScreenManager.BringToFront(screen);
}
public class DialogButton
{
public string Text { get; set; }
public Action Action { get; set; }
public string EnteredText { get; set; }
public DialogButton(string text, Action action)
{
this.Text = text;
this.Action = action;
}
}
public void HandleClick(string clickText, int indexOf, TaskCompletionSource<int> completionSource, DialogScreen screen)
{
Solids.Instance.ScreenManager.Remove(screen);
completionSource.SetResult(indexOf);
}
public void HandleClick(DialogButton button, TaskCompletionSource<DialogButton> completionSource, DialogScreen screen)
{
Solids.Instance.ScreenManager.Remove(screen);
completionSource.SetResult(button);
button.Action?.Invoke();
}
//public void HandleTextEntryClick(DialogButton button, TaskCompletionSource<DialogButton> completionSource, TextEntryScreen screen,string enteredText)
//{
// Solids.Screens.Remove(screen);
// completionSource.SetResult(new DialogButton(button.Text,button.Action){EnteredText = enteredText});
// button.Action?.Invoke();
//}
}
}
|
namespace Ejercicio
{
public abstract class Villano
{
public abstract int poder();
public abstract void realizarMaldad();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MapUI : MonoBehaviour {
// Singleton //
public static MapUI instance { get; protected set;}
void Awake () {
if (instance == null) {
instance = this;
} else if (instance != this) {
Destroy (gameObject);
}
}
// Singleton //
GameObject mapObject;
GameObject bg_asylumOutside;
GameObject bg_asylumOutside_shadow;
GameObject bg_abandonedWing;
GameObject bg_abandonedWing_mirror;
GameObject bg_asylum;
GameObject bg_asylum_mirror;
// Use this for initialization
public void Initialize ()
{
CreateMap();
CloseMap();
EventsHandler.cb_key_m_pressed += OnMapKeyPressed;
}
void OnDestroy()
{
EventsHandler.cb_key_m_pressed -= OnMapKeyPressed;
}
// Update is called once per frame
void Update ()
{
}
public void CreateMap()
{
// If there's already an inventory, display error
if (mapObject != null)
{
Debug.LogError ("There's already a map object");
}
mapObject = Instantiate (Resources.Load<GameObject> ("Prefabs/MapUI"));
bg_asylumOutside = mapObject.transform.Find ("BG").Find ("BG_AsylumOutside").gameObject;
bg_asylumOutside_shadow = mapObject.transform.Find ("BG").Find ("BG_AsylumOutside_Shadow").gameObject;
bg_abandonedWing = mapObject.transform.Find ("BG").Find ("BG_AbandonedWing").gameObject;
bg_abandonedWing_mirror = mapObject.transform.Find ("BG").Find ("BG_AbandonedWing_Mirror").gameObject;
bg_asylum = mapObject.transform.Find ("BG").Find ("BG_Asylum").gameObject;
bg_asylum_mirror = mapObject.transform.Find ("BG").Find ("BG_Asylum_Mirror").gameObject;
}
// When pressing p
public void OnMapKeyPressed()
{
if (GameManager.actionBoxActive)
{
return;
}
if (GameManager.inventoryOpen)
{
return;
}
if (GameManager.settingsOpen)
{
return;
}
if (GameManager.mapOpen == false)
{
if ((RoomManager.instance.myRoom.mapArea == string.Empty) || (RoomManager.instance.myRoom.mapArea == "None"))
{
Debug.Log ("no map");
}
OpenMap ();
} else {
CloseMap ();
}
}
public void OpenMap()
{
mapObject.SetActive (true);
GameManager.mapOpen = true;
SetMapBG ();
EventsHandler.Invoke_cb_inputStateChanged ();
}
void SetMapBG()
{
bg_asylumOutside.SetActive (false);
bg_asylumOutside_shadow.SetActive (false);
bg_abandonedWing.SetActive (false);
bg_abandonedWing_mirror.SetActive (false);
bg_asylum.SetActive (false);
bg_asylum_mirror.SetActive (false);
switch (RoomManager.instance.myRoom.mapArea)
{
case "Asylum":
bg_asylum.SetActive (true);
break;
case "Asylum_mirror":
bg_asylum_mirror.SetActive (true);
break;
case "Asylum_outside":
bg_asylumOutside.SetActive (true);
break;
case "Asylum_outside_shadow":
bg_asylumOutside_shadow.SetActive (true);
break;
case "Abandoned_wing":
bg_abandonedWing.SetActive (true);
break;
case "Abandoned_wing_mirror":
bg_abandonedWing_mirror.SetActive (true);
break;
}
}
// ----- CLOSE MAP ----- //
public void CloseMap()
{
mapObject.SetActive (false);
GameManager.mapOpen = false;
EventsHandler.Invoke_cb_inputStateChanged ();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2019 {
public class Problem02 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2019: 2"; }
}
public override string GetAnswer() {
return Answer1().ToString();
}
public override string GetAnswer2() {
return Answer2().ToString();
}
public ulong Answer1() {
var codes = GetCodes();
int index = 0;
codes[1] = 12;
codes[2] = 2;
do {
var next = codes[index];
if (next == 1) {
codes[codes[index + 3]] = codes[codes[index + 1]] + codes[codes[index + 2]];
} else if (next == 2) {
codes[codes[index + 3]] = codes[codes[index + 1]] * codes[codes[index + 2]];
} else if (next == 99) {
return codes[0];
}
index += 4;
} while (true);
}
public ulong Answer2() {
var codes = GetCodes();
for (ulong code1 = 0; code1 <= 99; code1++) {
for (ulong code2 = 0; code2 <= 99; code2++) {
var temp = codes.ToArray();
int index = 0;
temp[1] = code1;
temp[2] = code2;
do {
var next = temp[index];
if (next == 1) {
temp[temp[index + 3]] = temp[temp[index + 1]] + temp[temp[index + 2]];
} else if (next == 2) {
temp[temp[index + 3]] = temp[temp[index + 1]] * temp[temp[index + 2]];
} else if (next == 99) {
break;
}
index += 4;
} while (true);
if (temp[0] == 19690720) {
return 100 * code1 + code2;
}
}
}
return 0;
}
private ulong[] GetCodes() {
var input = Input().First().Split(',');
var codes = new ulong[input.Length];
for (int index = 0; index < input.Length; index++) {
codes[index] = Convert.ToUInt64(input[index]);
}
return codes;
}
}
}
|
using ScriptableObjectFramework.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ScriptableObjectFramework.Conditions
{
[Flags]
public enum ComparableComparison
{
GreaterThan = 1,
LessThan = 2,
EqualTo = 4,
NotEqualTo = 8,
GreaterOrEqualTo = 5,
LessOrEqualTo = 6,
None = 0
}
/// <summary>
/// A condition that compares IComparables.
/// </summary>
/// <typeparam name="T">The type to compare</typeparam>
/// <typeparam name="Y">The Value type to compare against</typeparam>
/// <typeparam name="Z">The event type to trigger</typeparam>
public class ComparableCondition<T, Y, Z> : Condition<T>
where T : IComparable
where Y : IValue<T>
where Z : IEvent<T>
{
public ComparableComparison Condition;
public Y Argument;
public Z Event;
private ComparableComparison lastState;
public override void Evaluate(T value)
{
ComparableComparison currentState = ComparableComparison.None;
int comparison = value.CompareTo(Argument.Value);
if (comparison == 0)
{
currentState = ComparableComparison.EqualTo;
}
else
{
if (comparison > 0)
{
currentState = ComparableComparison.GreaterThan | ComparableComparison.NotEqualTo;
}
else
{
currentState = ComparableComparison.LessThan | ComparableComparison.NotEqualTo;
}
}
//If we only want to trigger when crossing the threshold, get the dif between the current state and the last
ComparableComparison stateDif = ExecutionMode == ConditionExecutionMode.OnThreshold
? currentState & ~lastState
: currentState;
if ((stateDif & Condition) != 0)
{
Event.Fire(value);
}
lastState = currentState;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using KartObjects;
using DrvFRLib;
using KartObjects.Entities.Documents;
namespace AxisEq
{
public class ShtrihFR:AbstractPrinter
{
DrvFR ptr;
int CashPass, DocumentType;
public override int Open(string portName, string Baud, string OpName, string Psw, params object[] arg)
{
base.Open(portName, Baud, OpName, Psw, arg);
try
{
ptr = new DrvFR();
CashPass = 30;
ptr.Password = 30;
ptr.TableNumber = 2;
ptr.RowNumber = 1;
ptr.FieldNumber = 2;
ptr.ValueOfFieldString = OpName;
ptr.WriteTable();
ptr.ComNumber = Convert.ToInt32(portName.ToUpper().Replace("COM", ""));
ptr.BaudRate = 0;
if (Baud == "2400") ptr.BaudRate = 0;
if (Baud == "4800") ptr.BaudRate = 1;
if (Baud == "9600") ptr.BaudRate = 2;
if (Baud == "19200") ptr.BaudRate = 3;
if (Baud == "38400") ptr.BaudRate = 4;
if (Baud == "57600") ptr.BaudRate = 5;
if (Baud == "115200") ptr.BaudRate = 6;
ptr.Timeout = 1000;
ptr.ComputerName = "local";
ptr.Connect();
}
catch (Exception)
{
throw new Exception("Ошибка инициализации ШтрихФР!");
}
return GetError(ptr.ResultCode);
}
public override int Close()
{
ptr.Disconnect();
ptr = null;
return 0;
}
public override int CancelReceipt()
{
ptr.CancelCheck();
return GetError(ptr.ResultCode);
}
public override int CashIn(long Sum)
{
try
{
ptr.Password = CashPass;
ptr.Summ1 = (decimal)((double)Sum / 100);
ptr.CashIncome();
if (ptr.ResultCode != 0) return GetError(ptr.ResultCode);
while (GetStatus() == 8) Thread.Sleep(10);
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int CashOut(long Sum)
{
try
{
ptr.Password = CashPass;
ptr.Summ1 = (decimal)((double)Sum / 100);
ptr.CashOutcome();
if (ptr.ResultCode != 0) return GetError(ptr.ResultCode);
while (GetStatus() == 8) Thread.Sleep(10);
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int ContinuePrint()
{
int res = 0;
ptr.GetECRStatus();
if (ptr.ECRAdvancedMode == 3)
res = ptr.ContinuePrint();
return GetError(res);
}
public override int GetStatus()
{
int result = 0;
ptr.GetECRStatus();
ptr.Password = CashPass;
if (ptr.ResultCode != 0) { result = 7; return result; }
if (ptr.ECRMode == 0) result = 0;
if (!ptr.IsFMSessionOpen) result = 2;
if (ptr.IsFM24HoursOver) result = 1;
if (ptr.FMOverflow) result = 5;
EKLZEnding = false;
if (ptr.IsEKLZOverflow)
{
EKLZEnding = true;
result = 4;
}
if (ptr.ECRMode == 8) result = 8;
if (ptr.IsBatteryLow) result = 7;
return result;
}
public override int XReport()
{
try
{
ptr.Password = 30;
ptr.PrintReportWithoutCleaning();
if (ptr.ResultCode != 0) return GetError(ptr.ResultCode);
int s = 8;
while (s == 8)
{
s = ptr.ECRMode;
Thread.Sleep(10);
}
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int ZReport(ZReport z)
{
try
{
//Заполняем счетчики
foreach (ZReportPayment p in z.ZReportPayments)
{
ptr.Password = 30;
switch (p.PayType.CounterNum)
{
case 1: ptr.RegisterNumber = 193; break;
case 2: ptr.RegisterNumber = 197; break;
case 3: ptr.RegisterNumber = 201; break;
case 4: ptr.RegisterNumber = 205; break;
}
ptr.GetCashReg();
p.FiscalTotalSale= ptr.ContentsOfCashRegister;
WriteToLog("Счетчик " + p.PayType.CounterNum+" продажа "+p.FiscalTotalSale);
ptr.Password = 30;
switch (p.PayType.CounterNum)
{
case 1: ptr.RegisterNumber = 195; break;
case 2: ptr.RegisterNumber = 199; break;
case 3: ptr.RegisterNumber = 203; break;
case 4: ptr.RegisterNumber = 207; break;
}
ptr.GetCashReg();
p.FiscalTotalReturn= ptr.ContentsOfCashRegister;
WriteToLog("Счетчик " + p.PayType.CounterNum + " возврат " + p.FiscalTotalReturn);
}
ptr.Password = 30;
ptr.PrintReportWithCleaning();
if (ptr.ResultCode != 0) return GetError(ptr.ResultCode);
for (int i = 0; i < 50; i++)
{
if (GetStatus() != 8) break;
Thread.Sleep(25);
}
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int CutOff()
{
ptr.CutCheck();
return 0;
}
public override int isDrawerOpen()
{
return (ptr.IsDrawerOpen) ? ( 1 ) : ( 0 );
}
public override int PrintString(string Text)
{
try
{
ptr.Password = CashPass;
string[] toprint = Text.Split('\n');
foreach (string l in toprint)
{
string tmp = l;
tmp = tmp.Replace("\r", "");
ptr.StringForPrinting = ParseString(tmp);
int res =ptr.PrintString();
//int res = ptr.PrintStringWithFont();
WriteToLog(tmp);
}
// if (ptr.FontType == 0) ptr.FontType = 1;
// int res = ptr.PrintStringWithFont();
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override string ParseString(string st)
{
if (st.Contains("^cut"))
{
if (HeaderStrings.Length > 0)
{
ptr.StringForPrinting = HeaderStrings[0].PadRight(42);
int res = ptr.PrintString();
WriteToLog(HeaderStrings[0].PadRight(42));
}
if (HeaderStrings.Length > 1)
{
ptr.StringForPrinting = HeaderStrings[1].PadRight(42);
int res = ptr.PrintString();
WriteToLog(HeaderStrings[1].PadRight(42));
}
if (HeaderStrings.Length > 2)
{
ptr.StringForPrinting = HeaderStrings[2].PadRight(42);
int res = ptr.PrintString();
WriteToLog(HeaderStrings[2].PadRight(42));
}
if (HeaderStrings.Length > 3)
{
ptr.StringForPrinting = HeaderStrings[3].PadRight(42);
int res = ptr.PrintString();
WriteToLog(HeaderStrings[3].PadRight(42));
}
CutOff();
st = st.Replace("^cut", "");
}
else
if (st.Contains("^"))
{
printBarCode(st.Replace("^", String.Empty));
st = "";
}
return st;
}
private void PrintString(string p, int p_2)
{
throw new NotImplementedException();
}
public override int printBarCode(string barcode)
{
try
{
ptr.Password = CashPass;
if (barcode.Length>12) barcode=barcode.Substring(0,12);
ptr.BarCode = barcode;
ptr.PrintBarCode();
//System.Windows.Forms.MessageBox.Show(ptr.ResultCode.ToString());
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int OpenCashDrawer()
{
try
{
ptr.Password = CashPass;
ptr.DrawerNumber = 0;
//for (int i = 0; i < 5; i++)
//{
ptr.OpenDrawer();
// Thread.Sleep(100);
// if (isDrawerOpen() == 1) break;
//}
}
catch (Exception)
{
}
OpenCashDrawer(false);
return 0;
}
public override int ShiftReport(int ShiftNum)
{
try
{
ptr.Password = 30;
ptr.ReportType = true;
ptr.FirstSessionNumber = ShiftNum;
ptr.LastSessionNumber = ShiftNum;
ptr.SessionNumber = ShiftNum;
ptr.EKLZJournalOnSessionNumber();
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
public override int PrintFreeDoc(Receipt receipt)
{
int discount=0;
//эмуляция ПФД
//открываем обычный документ
if (receipt.DirectOperation == 1)
DocumentType = 0;
else
DocumentType = 2;
var r=BeginReceipt();
//добавляем одну позицию на сумму ПФД
ItemReceipt(0, "", "", (int)(receipt.TotalSum*100), 1000);
try
{
ptr.GetShortECRStatus();
if (ptr.ECRAdvancedMode == 3)
ptr.ContinuePrint();
//закрываем обычный документ
//TenderReceipt(_payType, _sum, 0);
int[] summs = { 0, 0, 0, 0, 0, 0 };
foreach (Payment payment in receipt.Payment)
{
//todo:remove or throw exception
if (payment.PaymentSum > receipt.TotalSum)
payment.PaymentSum = receipt.TotalSum;
if (payment.PayType.IsDiscount)
discount = discount + (int)(payment.PaymentSum * 100);
else
summs[payment.PayType.CounterNum-1] = (int)(payment.PaymentSum * 100);
}
MixTenderReceipt(summs[0]+(int)(receipt.Change*100), summs[1], summs[2], summs[3], summs[4], summs[5], discount);
///Длинное клише после чека
Thread.Sleep(1000);
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
private int BeginReceipt()
{
try
{
ptr.Password = CashPass;
switch (DocumentType)
{
case 0: ptr.CheckType = 0; break;
case 2: ptr.CheckType = 2; break;
default: ptr.CheckType = 0; break;
}
ptr.OpenCheck();
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
private int ItemReceipt(int SecID, string GoodName, string Measure, int Price, int Count)
{
try
{
ptr.Password = CashPass;
ptr.Department = SecID;
ptr.Quantity = (double)Count / 1000.0;//3.0;
ptr.Price = (decimal)((double)Price / 100.0);
ptr.StringForPrinting = GoodName;
if (DocumentType == 0) { ptr.Sale(); }
if (DocumentType == 2) { ptr.ReturnSale(); }
}
catch (Exception)
{
}
return GetError(ptr.ResultCode);
}
/// <summary>
/// Смешанная оплата
/// </summary>
/// <param name="Summ0"></param>
/// <param name="Summ1"></param>
/// <param name="Summ2"></param>
/// <param name="Summ3"></param>
/// <param name="Summ4"></param>
/// <param name="Summ5"></param>
/// <param name="Discount"></param>
/// <returns></returns>
private int MixTenderReceipt(int Summ0, int Summ1, int Summ2, int Summ3, int Summ4, int Summ5, int Discount)
{
try
{
//Скидка
if (Discount>0)
{
ptr.Password=CashPass;
ptr.Summ1=(decimal)((double)Discount/100);
ptr.Discount();
}
ptr.Password=CashPass;
ptr.Summ1=(decimal)((double)Summ0/100);
ptr.Summ2=(decimal)((double)Summ1/100);
ptr.Summ3=(decimal)((double)Summ2/100);
ptr.Summ4=(decimal)((double)Summ3/100);
ptr.StringForPrinting="";
ptr.CloseCheck();
if (ptr.ResultCode != 0) return GetError(ptr.ResultCode);
for (int i = 0; i < 50; i++)
{
if (GetStatus() != 8) break;
Thread.Sleep(25);
}
}
catch (Exception e)
{
throw e;
}
return GetError(ptr.ResultCode);
}
public override int CutOff(int feedCount)
{
return base.CutOff(feedCount);
}
public override int GetData(int ParamID, out long pData, out string pString)
{
throw new NotImplementedException();
}
public override DateTime GetDateTime()
{
return base.GetDateTime();
}
public override PrinterState GetState()
{
ptr.Password = CashPass;
ptr.GetECRStatus();
PrinterState result = PrinterState.STATE_NORMAL;
if (ptr.LidPositionSensor) result = PrinterState.STATE_COVEROPEN;
//if (ptr.IsDrawerOpen) result = PrinterState.STATE_CASHDRAWEROPEN;
if (!ptr.ReceiptRibbonOpticalSensor) result = PrinterState.STATE_PAPEREND;
//if ((ptr.IsPrinterLeftSensorFailure) || (ptr.IsPrinterRightSensorFailure)) result=5;
if (ptr.ECRMode == 3) result = PrinterState.STATE_NEEDSHIFTCLOSE;
if (ptr.ECRMode == 0) result = PrinterState.STATE_NORMAL;
return result;
}
public override int GetLastKPK(out int kpk)
{
kpk = 0;
if (ptr.GetEKLZCode1Report()==0)
kpk = ptr.LastKPKNumber;
return GetError(ptr.ResultCode);
}
public override int SetDateTime()
{
throw new NotImplementedException();
}
public override int GetError(int err)
{
int result = (int)PrinterError.ERR_ERROR;
this.RealError = err;
if ((err >= 160) && (err <= 195)) result = (int)PrinterError.ERR_EKLZ;
if (err == 79) result = (int)PrinterError.ERR_PSW;
if (err == 0) result = (int)PrinterError.ERR_SUCCESS;
if (err == 78) result = (int)PrinterError.ERR_SHIFTCLOSE;
if (err == 200) result = (int)PrinterError.ERR_NOTFOUND;
if (err == 300) result = (int)PrinterError.ERR_TIMECORRECTION;
if (err == 80) result = (int)PrinterError.ERR_NOTREADY;
if (err == 70) result = (int)PrinterError.ERR_NOTENOUGHCASH;
if (err == 88) result = (int)PrinterError.ERR_CONTINUEPRINT;
if (err == 107) result = (int)PrinterError.ERR_PAPEROUT;
return result;
}
public override int LastReceiptNumber
{
get
{
ptr.Password = CashPass;
ptr.RegisterNumber = 152;
ptr.GetOperationReg();
return ptr.ContentsOfOperationRegister;
}
}
public override int LastShiftNumber
{
get
{
ptr.Password = CashPass;
ptr.GetECRStatus();
//трехразовое считывание
if (ptr.ResultCode!=0)
ptr.GetECRStatus();
if (ptr.ResultCode != 0)
ptr.GetECRStatus();
if (ptr.ResultCode != 0)
throw new Exception("Ошибка запроса номера смены");
int result = ptr.SessionNumber+1;
return result;
}
}
public override decimal CashSum
{
get
{
ptr.RegisterNumber = 241;
ptr.GetCashReg();
return (decimal)(ptr.ContentsOfCashRegister);
}
}
/// <summary>
/// Инициализация заголовка
/// </summary>
public override void InitHeaderStrings()
{
HeaderStrings = new string[4];
ptr.Password = 30;
ptr.GetFieldStruct();
ptr.TableNumber = 4;
ptr.FieldNumber = 1;
ptr.RowNumber = 23;
ptr.ReadTable();
HeaderStrings[0]= ptr.ValueOfFieldString;
ptr.TableNumber = 4;
ptr.FieldNumber = 1;
ptr.RowNumber = 24;
ptr.ReadTable();
HeaderStrings[1] = ptr.ValueOfFieldString;
ptr.TableNumber = 4;
ptr.FieldNumber = 1;
ptr.RowNumber = 25;
ptr.ReadTable();
HeaderStrings[2] = ptr.ValueOfFieldString;
ptr.TableNumber = 4;
ptr.FieldNumber = 1;
ptr.RowNumber = 26;
ptr.ReadTable();
HeaderStrings[3] = ptr.ValueOfFieldString;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using k8s;
using k8s.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using nemo_api_service.Models;
namespace nemo_api_service.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EnvironmentsController : library.BaseController
{
public EnvironmentsController(IHttpContextAccessor httpContextAccessor):base(httpContextAccessor)
{
}
// GET: api/Environments
[HttpGet]
public IActionResult Get()
{
var ns = _client.ListNamespace(null, null, "createdfrom=nemo");
return Ok(ns.Items);
}
[HttpGet("GetByName/{name}")]
public IActionResult GetByName(string name)
{
var ns = _client.ReadNamespace(name);
var services = _client.ListNamespacedService(ns.Metadata.Name);
var deployments = _client.ListNamespacedDeployment(ns.Metadata.Name);
var enviroment = new Enviroment
{
Name = ns.Metadata.Name,
Status = ns.Status.Phase,
CreateDate=ns.Metadata.CreationTimestamp.ToString(),
Services=services.Items,
Deployments=deployments.Items
};
return Ok(enviroment);
}
[HttpGet("GetEnvironmentList")]
public IActionResult GetEnvironmentList()
{
var result=new List<Models.Enviroment>();
var nsList = _client.ListNamespace(null, null, "createdfrom=nemo");
foreach (var item in nsList.Items)
{
var services = _client.ListNamespacedService(item.Metadata.Name);
var deployments = _client.ListNamespacedDeployment(item.Metadata.Name);
result.Add(new Enviroment
{
Name = item.Metadata.Name,
Status = item.Status.Phase,
CreateDate = item.Metadata.CreationTimestamp.ToString(),
Services = services.Items,
Deployments = deployments.Items
});
}
return Ok(result);
}
[HttpGet("DeleteByName/{name}")]
public IActionResult DeleteByName(string name)
{
var status =_client.DeleteNamespace(name);
return Ok(status);
}
[HttpGet("GetStatusByName/{name}")]
public IActionResult GetStatusByName(string name)
{
var status = _client.ReadNamespaceStatus(name);
return Ok(status);
}
[HttpGet("IsExist/{name}")]
public IActionResult IsExist(string name)
{
var result = false;
var namespaces = _client.ListNamespace();
foreach (var item in namespaces.Items)
{
if (item.Metadata.Name == name)
{
result = true;
}
}
return Ok(result);
}
// POST: api/Environments
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT: api/Environments/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
|
using System;
using Alabo.Domains.Entities;
using Alabo.Framework.Core.WebApis;
using Alabo.Framework.Core.WebUis;
using Alabo.UI;
using Alabo.UI.Design.AutoForms;
using Alabo.Web.Mvc.Attributes;
namespace Alabo.Industry.Cms.Articles.UI
{
[ClassProperty(Name = "文章", Description = "文章")]
public class ArticleAutoWorkOrder : UIBase, IAutoForm
{
public Alabo.UI.Design.AutoForms.AutoForm GetView(object id, AutoBaseModel autoModel)
{
throw new NotImplementedException();
}
public ServiceResult Save(object model, AutoBaseModel autoModel)
{
throw new NotImplementedException();
}
}
}
|
using AlgorithmProblems.Arrays.ArraysHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Sorting
{
/// <summary>
/// Given a sorted integer array, return a sorted array of the squares.
/// The input sorted array can have negative integers.
/// </summary>
class SortedSquares
{
/// <summary>
/// Algo: Take the square of the elements in arr.
/// 2. Get the pivot point such that all elements arr[pivot->arr.Length-1] are sorted in ascending order
/// and all elements arr[0, pivot-1] are sorted in descending order
/// 3. if pivot point is not found the array is already sorted
/// 4. Else do a merge operation in mergesort and the 2 array segment will be in ascending and descending order.
///
/// The running time for this is O(n)
/// and the space requirement is O(n)
/// </summary>
/// <param name="arr">sorted integer array</param>
/// <returns>sorted squares array of the input integer array</returns>
public int[] GetSquaresArray(int[] arr)
{
int[] squaresArr = new int[arr.Length];
int sqArrIndex = 0;
int pivotIndex = -1;
// Square the input array and get the pivot point
for(int i=0; i<arr.Length; i++)
{
arr[i] = arr[i] * arr[i];
if(i-1>=0 && arr[i]<arr[i-1])
{
// this is the pivot point, all elements arr[pivot->arr.Length-1] are sorted in ascending order
// and all elements arr[0, pivot-1] are sorted in descending order
pivotIndex = i;
}
}
if(pivotIndex == -1)
{
// the arr is already sorted in ascending order
return arr;
}
int decSt = pivotIndex - 1;
int incSt = pivotIndex;
while (decSt >= 0 && incSt < arr.Length)
{
if(arr[decSt] < arr[incSt])
{
squaresArr[sqArrIndex++] = arr[decSt--];
}
else
{
squaresArr[sqArrIndex++] = arr[incSt++];
}
}
// now add all the element left in the decreasing array segment
while(decSt>=0)
{
squaresArr[sqArrIndex++] = arr[decSt--];
}
// now add all the elements left in the increasing array segment
while(incSt <arr.Length)
{
squaresArr[sqArrIndex++] = arr[incSt++];
}
return squaresArr;
}
#region TestArea
public static void TestSortedSquares()
{
SortedSquares ss = new SortedSquares();
int[] arr = new int[] { -9, -8, -5, -1, 1, 3, 4, 6 };
Console.WriteLine("The input arr is as shown below");
ArrayHelper.PrintArray(arr);
Console.WriteLine("The sorted squares arr is as shown below");
ArrayHelper.PrintArray(ss.GetSquaresArray(arr));
arr = new int[] { -1, -1, 1, 3, 4, 6 };
Console.WriteLine("The input arr is as shown below");
ArrayHelper.PrintArray(arr);
Console.WriteLine("The sorted squares arr is as shown below");
ArrayHelper.PrintArray(ss.GetSquaresArray(arr));
}
#endregion
}
}
|
namespace KingNetwork.Shared.Encryptation
{
public class AdlerChecksum
{
public static uint Checksum(byte[] data, int index, int length)
{
const ushort adler = 65521;
uint a = 1, b = 0;
while (length > 0)
{
var tmp = length > 5552 ? 5552 : length;
length -= tmp;
do
{
a += data[index++];
b += a;
} while (--tmp > 0);
a %= adler;
b %= adler;
}
return (b << 16) | a;
}
}
}
|
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SFA.DAS.Tools.Support.Core.Models;
using SFA.DAS.Tools.Support.Infrastructure.Services;
using SFA.DAS.Tools.Support.Web.Configuration;
using SFA.DAS.Tools.Support.Web.Extensions;
using SFA.DAS.Tools.Support.Web.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace SFA.DAS.Tools.Support.Web.Controllers
{
[Route("support/approvals")]
public class PauseApprovalsController : ApprovalsControllerBase
{
public PauseApprovalsController(ILogger<PauseApprovalsController> logger,
IEmployerCommitmentsService employerCommitmentsService,
IMapper mapper,
IOptions<ClaimsConfiguration> claimConfiguration) :
base(logger, employerCommitmentsService, mapper, claimConfiguration)
{
}
[HttpPost("pauseApprenticeship", Name = RouteNames.Approval_PauseApprenticeship)]
public async Task<IActionResult> PauseApprenticeship(ApprenticeshipSearchResultsViewModel model)
{
var ids = model.SelectedIds?.Split(',');
if (ids == null || ids.Count() == 0)
{
return RedirectToAction(RouteNames.Approval_SearchApprenticeships, "SearchApprovals", CreateSearchModel(model, ActionNames.Pause));
}
var results = await Task.WhenAll(GetApprenticeshipsFromApprovals(ids));
if (results.Any(a => a.HasError))
{
return View(new PauseApprenticeshipViewModel
{
HasError = true
});
}
return View(new PauseApprenticeshipViewModel
{
Apprenticeships = _mapper.Map<List<PauseApprenticeshipRow>>(results.Select(s => s.Apprenticeship)),
SearchParams = new SearchParameters
{
ApprenticeNameOrUln = model.ApprenticeNameOrUln,
CourseName = model.CourseName,
EmployerName = model.EmployerName,
ProviderName = model.ProviderName,
Ukprn = model.Ukprn,
SelectedStatus = model.Status,
StartDate = model.StartDate,
EndDate = model.EndDate
}
});
}
[HttpPost("cancelPauseApprenticeship", Name = RouteNames.Approval_CancelPauseApprenticeship)]
public IActionResult CancelPauseApprenticeship(PauseApprenticeshipViewModel model, string act)
{
return RedirectToAction(RouteNames.Approval_SearchApprenticeships, "SearchApprovals", new
{
model.SearchParams.ApprenticeNameOrUln,
model.SearchParams.CourseName,
model.SearchParams.ProviderName,
model.SearchParams.Ukprn,
model.SearchParams.EmployerName,
model.SearchParams.SelectedStatus,
StartDate = model.SearchParams.StartDate.GetUIFormattedDate(),
EndDate = model.SearchParams.EndDate.GetUIFormattedDate(),
act = ActionNames.Pause
});
}
[HttpPost("pauseApprenticeshipConfirmation", Name = RouteNames.Approval_PauseApprenticeshipConfirmation)]
public async Task<IActionResult> PauseApprenticeshipConfirmation(PauseApprenticeshipViewModel model)
{
var claims = GetClaims();
if(!IsValid(model, new string[] {claims.UserId, claims.DisplayName}, out List<PauseApprenticeshipRow> apprenticeshipsData))
{
return View("PauseApprenticeship", model);
}
var tasks = new List<Task<PauseApprenticeshipResult>>();
// is this where unecessary as its captured in the validation?
foreach (var apprenticeship in apprenticeshipsData.Where(a => a.ApiSubmissionStatus != SubmissionStatus.Successful))
{
tasks.Add(_employerCommitmentsService.PauseApprenticeship(new PauseApprenticeshipRequest
{
ApprenticeshipId = apprenticeship.Id,
DisplayName = claims.DisplayName,
EmailAddress = claims.UserEmail,
UserId = claims.UserId
}, new CancellationToken()));
}
var results = await Task.WhenAll(tasks);
foreach (var apprenticeship in apprenticeshipsData)
{
var result = results.Where(s => s.ApprenticeshipId == apprenticeship.Id).FirstOrDefault();
if (result == null)
{
continue;
}
if (!result.HasError)
{
apprenticeship.ApiSubmissionStatus = SubmissionStatus.Successful;
apprenticeship.ApiErrorMessage = string.Empty;
}
else
{
apprenticeship.ApiSubmissionStatus = SubmissionStatus.Errored;
apprenticeship.ApiErrorMessage = result.ErrorMessage;
}
}
model.Apprenticeships = apprenticeshipsData;
return View("PauseApprenticeship", model);
}
public bool IsValid(PauseApprenticeshipViewModel model, IEnumerable<string> claims, out List<PauseApprenticeshipRow> apprenticeshipsData)
{
if(!model.TryDeserialise(out apprenticeshipsData, _logger))
{
ModelState.AddModelError(string.Empty, "Unable to Read apprenticeship information, please return to the search and try again");
model.ApprenticeshipsData = null;
return false;
}
if(claims.Any(c => string.IsNullOrWhiteSpace(c)))
{
model.Apprenticeships = apprenticeshipsData;
ModelState.AddModelError(string.Empty, "Unable to retrieve userId or name from claim for request to Pause Apprenticeship");
return false;
}
return true;
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.DTO;
using FiiiCoin.ServiceAgent;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace FiiiCoin.Wallet.Test.ServiceAgent
{
[TestClass]
public class AccountsTest
{
[TestMethod]
public async Task GetAddressesByTag()
{
Accounts accounts = new Accounts();
AccountInfoOM[] result = await accounts.GetAddressesByTag("");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task GetAccountByAddress()
{
Accounts accounts = new Accounts();
AccountInfoOM result = await accounts.GetAccountByAddress("fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task GetNewAddress()
{
Accounts accounts = new Accounts();
AccountInfoOM result = await accounts.GetNewAddress("新地址");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task GetDefaultAccount()
{
Accounts accounts = new Accounts();
AccountInfoOM result = await accounts.GetDefaultAccount();
Assert.IsNotNull(result);
}
[TestMethod]
public async Task SetDefaultAccount()
{
Accounts accounts = new Accounts();
await accounts.SetDefaultAccount("fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY");
}
[TestMethod]
public async Task ValidateAddress()
{
Accounts accounts = new Accounts();
AddressInfoOM result = await accounts.ValidateAddress("fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task SetAccountTag()
{
Accounts accounts = new Accounts();
//first validate address
string address = "fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY";
AddressInfoOM result = await accounts.ValidateAddress(address);
if (result.IsValid)
{
await accounts.SetAccountTag(address, "new tag");
}
}
}
}
|
using PhotonInMaze.Common;
using System.Collections.Generic;
namespace PhotonInMaze.Maze.Generator {
internal class NextCellToVisitFinder {
private int rows, columns;
public NextCellToVisitFinder(int rows, int columns) {
this.rows = rows;
this.columns = columns;
}
public Optional<CellToVisit> FindNextToVisit(HashSet<Direction> availableMoves, int row, int column) {
bool isEndCell = row + 1 == rows && column + 1 == columns;
switch(GetRandomFromSet(availableMoves)) {
case Direction.Start:
return Optional<CellToVisit>.Empty();
case Direction.Right:
return new CellToVisit(row, column + 1, Direction.Right);
case Direction.Front:
return isEndCell ?
Optional<CellToVisit>.Empty() :
new CellToVisit(row + 1, column, Direction.Front);
case Direction.Left:
return new CellToVisit(row, column - 1, Direction.Left);
case Direction.Back:
return new CellToVisit(row - 1, column, Direction.Back);
}
return Optional<CellToVisit>.Empty();
}
private Direction GetRandomFromSet(HashSet<Direction> availableMoves) {
int randomCell = UnityEngine.Random.Range(0, availableMoves.Count);
int i = 0;
foreach(Direction availableMove in availableMoves) {
if(i == randomCell) {
return availableMove;
}
i++;
}
return Direction.Start;
}
}
}
|
namespace sc80wffmex.WindsorIoC
{
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using sc80wffmex.GlassStructure;
public class ApplicationCastleInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
// Register working dependencies
container.Register(Component.For<IControllerSitecoreContext>().ImplementedBy<ContextSitecoreContext>().LifestylePerWebRequest());
// Register the MVC controllers one by one
// container.Register(Component.For().LifestylePerWebRequest());
// Register all the MVC controllers in the current executing assembly
var controllers = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.BaseType == typeof(Controller)).ToList();
foreach (var controller in controllers)
{
container.Register(Component.For(controller).LifestylePerWebRequest());
using (var file =
new System.IO.StreamWriter(@"C:\Users\Carlos\Documents\Projects\sc80wffmex\registertracking2.txt"))
{
file.WriteLine("Assembly:sc80wffmex - " + controller.Name + " is registered.");
}
}
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;
using OpenMagic.ErrorTracker.WebApi.Logging;
namespace OpenMagic.ErrorTracker.WebApi.Infrastructure
{
public class LibLogExceptionLogger : IExceptionLogger
{
private static readonly ILog DefaultLogger = LogProvider.For<LibLogExceptionLogger>();
private readonly ILog _log;
public LibLogExceptionLogger()
: this(DefaultLogger)
{
}
internal LibLogExceptionLogger(ILog log)
{
_log = log;
}
public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
return Task.Run(() => _log.ErrorException(context.Exception.Message, context.Exception), cancellationToken);
}
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("NewGamePlus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Quicksilver Fox")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System;
public partial class DataBound : System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
//for run server side empty event(refrash)
}
}
|
using RunNerdApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RunNerdApp.Controllers
{
public class UsersController : ApiController
{
// GET: api/Users
public IEnumerable<AthleteModel> Get()
{
List<AthleteModel> vmList = null;
using (var context = new AthleteDbContext())
{
context.Database.Initialize(true);
vmList = context.Athletes.ToList();
}
return vmList;
}
// GET: api/Users/5
public string Get(int id)
{
return "value";
}
// POST: api/Users
public void Post([FromBody]string value)
{
}
// PUT: api/Users/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Users/5
public void Delete(int id)
{
}
}
}
|
using AutoMapper;
using Mbp.Ddd.Application.Mbp.UI;
using Mbp.EntityFrameworkCore.PermissionModel;
using EMS.Application.Contracts.AccountService.Dto;
using EMS.Application.Contracts.Demo.Dto;
using EMS.Application.Contracts.LogService.Dto;
using EMS.Domain.DomainEntities.Demo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mbp.EntityFrameworkCore.Domain;
namespace EMS.Application
{
/// <summary>
/// object to object Map
/// </summary>
public static class AutoMapperConfig
{
public static IMapper CreateMapper()
{
// TO DO 在这里注册所有的类型映射cfg.CreateMap<TSource, TDestination>()
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Blog, BlogDto>();
cfg.CreateMap<Post, PostDto>();
cfg.CreateMap<BlogDto, Blog>();
cfg.CreateMap<PostDto, Post>();
// 用户映射
cfg.CreateMap<UserInputDto, MbpUser>();
cfg.CreateMap<MbpUser, UserOutputDto>();
// 角色映射
cfg.CreateMap<RoleInputDto, MbpRole>();
cfg.CreateMap<MbpRole, RoleOutputDto>();
// 菜单映射
cfg.CreateMap<MenuInputDto, MbpMenu>();
cfg.CreateMap<MbpMenu, MenuOutputDto>();
// 日志映射
cfg.CreateMap<LogInputDto, MbpOperationLog>();
cfg.CreateMap<MbpOperationLog, LogOutInputDto>();
// 路由映射
cfg.CreateMap<MbpMenu, RouteOutputDto>();
// 部门映射
cfg.CreateMap<DeptInputDto, MbpDept>();
cfg.CreateMap<MbpDept, DeptOutputDto>();
// 岗位映射
cfg.CreateMap<PositionInputDto, MbpPosition>();
cfg.CreateMap<MbpPosition, PositionOutputDto>();
});
return config.CreateMapper();
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
public class CardParent : MonoBehaviour
{
public IEnumerable<SendCard> FullSearch(Func<bool, int, bool> func)
{
var cardManager = GameObject.FindWithTag(nameof(CardManager)).GetComponent<CardManager>();
for (int i = 0; i < cardManager.BoardList.GetLength(0); i++)
{
for (int j = 0; j < cardManager.BoardList.GetLength(1); j++)
{
if (cardManager.BoardList[i, j] == null)
continue;
var card = cardManager.CardStatuseList[i, j];
if (card == null || card.IsMonsterCard)
continue;
var enemyPlayer = cardManager.TurnPlayerList[i, j];
if (func(enemyPlayer, j))
{
yield return new SendCard { Lane = j, Player = enemyPlayer, CardStatus = card };
}
}
}
}
}
public class SendCard
{
public int Lane { get; set; }
public bool Player { get; set; }
public CardStatus CardStatus { get; set; }
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WorldState : IState
{
public void Enter()
{
GUIManager.Open<CityUIPanel>("City", "CityUIPanel");
}
public void Exit()
{
GUIManager.CloseAll();
}
public void Update()
{
}
}
|
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CarFinanceCalculator.Domain.Tests
{
[TestClass]
public class AmortizationCalculatorTests
{
[TestMethod]
public void Test1()
{
var car = new Car(2009, "Infiniti", "G37", 38700);
var loan = new CarLoan(car, 39203.27M, .0659M, 72, new DateTime(2012, 12, 3));
var calc = new AmortizationCalculator(660.69M);
var valueCalc = new DepreciationCalculator();
calc.Calculate(loan);
Trace.WriteLine("Date\t\tPayment\t\tInterest\tPrincipal\tRemaining\t\tValue\t\tEquity");
foreach (var line in calc.Lines)
{
var value = Math.Round(valueCalc.Calculate(car, line.PaymentDate), 2);
var equity = value - line.RemainingPrincipal;
Trace.WriteLine($"{line.PaymentDate.ToShortDateString()}\t{line.Payment.ToString("C")}\t\t{line.Interest.ToString("C")}\t\t{line.Principal.ToString("C")}\t\t{line.RemainingPrincipal.ToString("C")}\t\t{value.ToString("C")}\t{equity.ToString("C")}");
}
var one = 1;
}
}
}
|
using UBaseline.Shared.Node;
using UBaseline.Shared.Property;
namespace Uintra.Features.UserList.Models
{
public class UserListPanelModel : NodeModel
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento
{
class Factura
{
FacturaMemento ultimoEstadoCopiado;
public DateTime FechaEmision { get; set; }
public string Cliente { get; set; }
public List<ItemFactura> Items { get; set; }
public Factura()
{
Items = new List<ItemFactura>();
}
public FacturaMemento CrearMemento()
{
FacturaMemento f = new FacturaMemento() { FechaEmision = FechaEmision, Cliente = Cliente};
ultimoEstadoCopiado = f;
return f;
}
public void ReestablecerValores(FacturaMemento f)
{
FechaEmision = f.FechaEmision;
Cliente = f.Cliente;
}
public void MostrarDatosDeFactura()
{
Console.WriteLine("La factura tiene {0} elementos", Items.Count);
Console.WriteLine("La fecha de emision es {0}", FechaEmision.ToShortDateString());
Console.WriteLine("La cliente es {0}", Cliente);
Console.ReadKey();
}
public void Restaurar()
{
ReestablecerValores(ultimoEstadoCopiado);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PatronAbstract_Factory
{
public interface IFabricante
{
//Interfaz que permitira crear bebidas a todas las clases que la implementen
public IBebida crearBebida();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.DataAccess
{
public class Constant
{
public class Format
{
public const string ApiDateFormat = "yyyy-MM-dd HH:mm:ss";
}
public class MimeType
{
public const string PDF = "application/pdf";
public const string JPEG = "image/jpeg";
public const string PNG = "image/png";
public const string MSWORD = "application/msword";
public const string MSEXCEL = "application/excel";
}
public class FileExtension
{
public const string Jpg = ".jpg";
public const string Jpeg = ".jpeg";
public const string Png = ".png";
public const string Bmp = ".bmp";
public const string Pdf = ".pdf";
public const string Xls = ".xls";
public const string Xlsx = ".xlsx";
public const string Doc = ".doc";
public const string Docx = ".docx";
}
public class ServerPath
{
public const string Temp = "/TempUpload";
public const string ImageInspectionPath = "ImageInspection/";
public const string ImageClaimPath = "ImageClaim/";
public const string ImageAccount = "/images/accounts/";
}
public class WaterMark
{
public const string KWatermarkDefaultFileName = "Watermark/watermark_default_v2.png";
}
public class Country
{
public class Label
{
public const string Malaysia = "Malaysia";
public const string Thailand = "Thailand";
}
public class Value
{
public const int Thailand = 1001;
public const int Malaysia = 1002;
}
public class Code
{
public const string MY = "my";
public const string TH = "th";
}
}
public class ApplicationDevice
{
public class Label
{
public const string ConsumerClaimdi = "Claimdi Consumer iOS";
public const string AgentClaimdi = "Claimdi for agent iOS";
}
public class Value
{
public const string ClaimdiConsumer = "024090D9-86D1-4778-BE73-F72B0491F9CE";
public const string ClaimdiAgent = "DA615B28-6076-4A67-9ADC-A43BC0ED42EF";
}
}
public class ErrorCode
{
public const string DuplicateData = "400";
public const string Unauthorized = "401";
public const string ExistingData = "403";
public const string RequiredData = "405";
public const string InvalidData = "406";
public const string WorkflowInvalid = "407";
public const string AcceptTaskInvalid = "408";
public const string ForceUpdate = "409";
public const string UsernameDuplicate = "410";
public const string FacebookIdDuplicate = "411";
public const string InvalidReferenceCode = "412";
public const string SystemError = "500";
public const string ThirdPartyError = "501";
}
public class ErrorMessage
{
public const string SystemError = "กรุณาติดต่อผู้ดูแลระบบ";
public const string DuplicateData = "ข้อมูลซ้ำกรุณากรอกข้อมูลใหม่อีกครั้ง";
public const string ExistingData = "ไม่พบข้อมูลนี้ในระบบกรุณาลองใหม่อีกครั้ง";
public const string InvalidData = "ข้อมูลไม่ถูกต้อง";
public const string Unauthorized = "ไม่สามารถอนุญาติให้ใช้งานในระบบ กรุณารับรองสิทธิ์ก่อนการใช้งาน";
public const string RequiredData = "กรุณากรอกข้อมูลให้ครบถ้วน";
public const string WorkflowInvalid = "ลำดับการทำงานไม่ถูกต้อง";
public const string AcceptTaskInvalid = "ไม่สามารถรับงานได้";
public const string ForceUpdate = "กรุณาอัพเดทโปรแกรม";
public const string UsernameDuplicate = "Username นี้มีผู้ใช้งานอยู่แล้ว กรุณาตรวจสอบอีกครั้ง";
public const string FacebookIdDuplicate = "Facebook Id ซ้ำกับในระบบ";
public const string InvalidReferenceCode = "กรุณาตรวจสอบรหัสอ้างอิงอีกครั้ง";
public const string UnauthorizedTask = "ไม่มีงานนี้ในระบบ";
public const string noApproveImageTask = "งานนี้ยังไม่ถูกตรวจสอบรูป";
}
public class TitleMessage
{
public const string AccpetTask = "";
public const string FinishTask = "ขอขอบคุณเป็นอย่างสูง";
public const string RejectTask = "";
}
public class BodyMessage
{
public const string AccpetTask = "ท่านสามารถดูงานที่ท่านได้เลือกได้ที่เมนู \"นัดหมาย\" และเลือกแถบเมนูย่อย \"คิวนัดหมายที่รออยู่\" ";
public const string FinishTask = "ข้อมูลการทำงานของท่านได้ถูกบันทึกเรียบร้อยแล้วท่านสามารถปฏิบัติงานต่อไปได้";
public const string RejectTask = "ท่านได้ปฏิเสธงานเรียบร้อยแล้ว";
}
public class Permission
{
public const int SystemAdmin = 1;
public const int Admin = 100;
public const int RoleClaimdiBike = 103;
public const int Claimdi_Member = 2;
public const int Call_Center = 3;
public const int Surveyor = 4;
public const int Guest_Member = 99;
public const int SurveyorOS = 109;
public const int Supervisor = 110;
public static int[] SurveyRoleId = new int[] { Constant.Permission.Surveyor, Constant.Permission.SurveyorOS, Constant.Permission.RoleClaimdiBike };
}
public class CompanyId
{
public const string ClaimDi = "13B00D32-D761-4EAA-9BB5-E6FE4905D04C";
}
public class MapGoogleURL
{
public const string DistanceMatrix = "https://maps.googleapis.com/maps/api/distancematrix/";
public const string GeoCode = "https://maps.googleapis.com/maps/api/geocode/";
}
public class CompanyType
{
public const int Insurer = 1001;
}
public class TaskProcessConst
{
public const int PreApprove = 1007;
public const int KeyData = 1013;
public const int Pass = 1009;
public const int NotPass = 1010;
public const int SendReport = 1005;
public const int EditTask = 1006;
public const int Open = 1001;
public const int Recieve = 1002;
public const int Start = 1003;
public const int Arrive = 1004;
public const int Cancel = 1011;
public const int AcceptJobInsurance = 1014;
}
public class PicturePartCode
{
public const string TypeST04 = "PT04";
public const string TypeOT01 = "PT01";
public const string TypeOT06 = "PT06";
public const string TypeDM02 = "PT02";
public const string TypeDM03 = "PT03";
public const string TypeDM05 = "PT05";
}
public class PictureType
{
public const string AroundCar = "PT04";
public const string Accessory = "PT01";
public const string InsDoc = "PT06";
public const string Doc = "PT02";
public const string Damage = "PT03";
public const string Sign = "PT05";
}
public class ReportConts
{
public const string AddressClaimDi = "<strong style='font-size: 11pt;'>บริษัท เอพลัส เคลม เซอร์วิส จำกัด</strong> "
+ "<br>69/8 ซอยราชวิถี 1 ถนนรางน้ำ แขวงถนนพญาไท"
+ "<br>เขตราชเทวี กรุงเทพฯ 10400"
+ "<br>โทร: +66 (0) 2021-1600"
+ "<br>อีเมล: support@anywheretogo.com";
public const string Sign = "<br /><br />.....................................................<br />"
+ "ขอแสดงความนับถือ<br />"
+ "หัวหน้าแผนกอุบัติเหตุรถยนต์<br />"
+ "บริษัท เอพลัส เคลม เซอร์วิส จำกัด<br />"
+ "ผู้มีอำนาจลงนาม";
}
public class Email
{
public const string TaskProcessIdConfirmationOfReceiptInspection = "3001";
public const string TaskProcessIdConfirmAppointment = "3002";
public const string TaskProcessIdChangeAppointment = "3003";
public const string TaskProcessIdNotContact = "3006";
public const string TaskProcessIdPreApprove = "3004";
public const string TaskProcessIdReturnJob = "3005";
public const string TaskProcessIdBlank = "3007";
public const string TaskProcessIdImgInspection = "3008";
public const string TaskProcessIdImgAll = "3009";
public const string TaskProcessIdCallCenter = "4001";
}
public class TaskActionEnum
{
public const int ClaimFRS = 1001;
public const int ClaimAppointment = 1002;
public const int ClaimFollow = 1003;
public const int ClaimDRY = 1004;
public const int GoNow = 1005;
public const int Appointment = 1006;
}
public class AssignClaimDiStatus
{
public const string Waiting = "waiting";
public const string Accept = "accept";
public const string Reject = "reject";
}
public class Endpoint
{
//SEIC
public const string TaskAssignments = "/tasks/assignments";
}
public class ResponseMessageAssignBooking
{
public const string Success = "คุณจองการจ่ายงานนี้แล้ว";
public const string Cancel = "คุณยกเลิกการจ่ายงานนี้แล้ว";
public const string Fail = "การจองงานล้มเหลว";
public const string BookingAlready = "มีพนักงานจองจ่ายงานนี้แล้ว";
public const string DoNotCancel = "คุณไม่ได้จองงานนี้ ไม่สามารถยกเลิกได้";
}
}
}
|
using Alabo.Domains.Enums;
using Alabo.Security.Enums;
using System;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Security {
/// <summary>
/// 基础用户
/// </summary>
public class BasicUser {
/// <summary>
/// 用户ID
/// </summary>
public long Id { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 手机号码
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// 上级用户id
/// </summary>
[Display(Name = "上级用户id")]
public long ParentId { get; set; } = 0;
/// <summary>
/// 用户状态
/// </summary>
public Status Status { get; set; } = Status.Normal;
/// <summary>
/// 用户等级Id 每个类型对应一个等级
/// </summary>
public Guid GradeId { get; set; }
/// <summary>
/// 当前租户
/// </summary>
public string Tenant { get; set; }
/// <summary>
/// 登录方式
/// </summary>
public LoginAuthorizeType LoginAuthorizeType { get; set; } = LoginAuthorizeType.Login;
}
}
|
using System;
using UBaseline.Shared.Node;
namespace Uintra.Features.UserList.Models
{
public class UserListPanelViewModel : NodeViewModel
{
public MembersRowsViewModel Details { get; set; }
public Guid? GroupId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PIBP
{
public partial class Usluge : Form
{
public Usluge()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Usluge_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataUsluge.USLUGE' table. You can move, or remove it, as needed.
this.uSLUGETableAdapter.Fill(this.dataUsluge.USLUGE);
}
}
}
|
using Contracts;
using System.Collections.Generic;
namespace AnalysisEngine.Analyzers
{
public class ForFilesAnalyzer : AnalyzerBase, IAnalyzer
{
public ForFilesAnalyzer()
{
Name = "ForFiles";
Threats = new List<Threat>(){
new Threat{FilePath = @"C:\Windows\System32\forfiles.exe", Name=Name,Type=VulnerabilityType.ForFiles_System32} ,
new Threat{FilePath = @"C:\Windows\SysWOW64\forfiles.exe", Name=Name,Type=VulnerabilityType.ForFiles_SysWow64 }
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace DogFetchApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
var lang = DogFetchApp.Properties.Settings.Default.Language;
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var win = new MainWindow(this);
win.Show();
}
public void Restart()
{
Process.Start(Process.GetCurrentProcess().MainModule.FileName);
Current.Shutdown();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Forms;
using KSF_Surf.ViewModels;
using KSF_Surf.Models;
using System.Collections.ObjectModel;
namespace KSF_Surf.Views
{
[DesignTimeVisible(false)]
public partial class RecordsRecentPage : ContentPage
{
private readonly RecordsViewModel recordsViewModel;
private bool hasLoaded = false;
private bool isLoading = false;
private readonly int CALL_LIMIT = 100;
// objects used by "Recent" call
private List<RRDatum> recentRecordsData;
private List<RR10Datum> recentRecords10Data;
private int list_index = 1;
// variables for filters
private readonly EFilter_Game defaultGame;
private readonly EFilter_Mode defaultMode;
private EFilter_Game game;
private EFilter_Mode mode;
private EFilter_RRType recentRecordsType;
// collection view
public ObservableCollection<Tuple<string, string, string, string>> RecordsRecentCollectionViewItemsSource { get; }
= new ObservableCollection<Tuple<string, string, string, string>>();
public RecordsRecentPage(EFilter_Game game, EFilter_Mode mode, EFilter_Game defaultGame, EFilter_Mode defaultMode)
{
this.game = game;
this.mode = mode;
this.defaultGame = defaultGame;
this.defaultMode = defaultMode;
recentRecordsType = EFilter_RRType.map;
recordsViewModel = new RecordsViewModel();
InitializeComponent();
Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]";
RecordsRecentCollectionView.ItemsSource = RecordsRecentCollectionViewItemsSource;
}
// UI -----------------------------------------------------------------------------------------------
#region UI
private async Task ChangeRecentRecords(bool clearPrev)
{
if (recentRecordsType == EFilter_RRType.top)
{
var recentRecords10Datum = await recordsViewModel.GetRecentRecords10(game, mode, list_index);
recentRecords10Data = recentRecords10Datum?.data;
if (recentRecords10Data is null) return;
if (clearPrev) RecordsRecentCollectionViewItemsSource.Clear();
RRTypeOptionLabel.Text = "Type: Top10";
LayoutRecentRecords10();
}
else
{
var recentRecordsDatum = await recordsViewModel.GetRecentRecords(game, recentRecordsType, mode, list_index);
recentRecordsData = recentRecordsDatum?.data;
if (recentRecordsData is null) return;
if (clearPrev) RecordsRecentCollectionViewItemsSource.Clear();
RRTypeOptionLabel.Text = "Type: " + EFilter_ToString.toString2(recentRecordsType);
LayoutRecentRecords(EFilter_ToString.toString2(recentRecordsType));
}
Title = "Records [" + EFilter_ToString.toString2(game) + ", " + EFilter_ToString.toString(mode) + "]";
}
// Displaying Changes -------------------------------------------------------------------------------
private void LayoutRecentRecords(string typeString)
{
foreach (RRDatum datum in recentRecordsData)
{
string mapZoneString = datum.mapName + " " + EFilter_ToString.zoneFormatter(datum.zoneID, false, false);
string playerServerString = String_Formatter.toEmoji_Country(datum.country) + " " + datum.playerName + " on " + datum.server + " server";
string rrtimeString = "in " + String_Formatter.toString_RankTime(datum.surfTime) + " (";
if (datum.wrDiff == "0")
{
if (datum.r2Diff is null)
{
rrtimeString += "WR N/A";
}
else
{
rrtimeString += "WR-" + String_Formatter.toString_RankTime(datum.r2Diff.Substring(1));
}
}
else
{
rrtimeString += "now WR+" + String_Formatter.toString_RankTime(datum.wrDiff);
}
rrtimeString += ") (" + String_Formatter.toString_LastOnline(datum.date) + ")";
RecordsRecentCollectionViewItemsSource.Add(new Tuple<string, string, string, string>(
mapZoneString, playerServerString, rrtimeString, datum.mapName));
list_index++;
}
}
private void LayoutRecentRecords10()
{
foreach (RR10Datum datum in recentRecords10Data)
{
int rank = int.Parse(datum.newRank);
string mapZoneString = datum.mapName + " [R" + rank + "]";
string playerServerString = String_Formatter.toEmoji_Country(datum.country) + " " + datum.playerName + " on " + datum.server + " server";
string rrtimeString = "in " + String_Formatter.toString_RankTime(datum.surfTime) + " (";
if (datum.wrDiff == "0")
{
rrtimeString += "WR";
}
else
{
rrtimeString += "WR+" + String_Formatter.toString_RankTime(datum.wrDiff);
}
rrtimeString += ") (" + String_Formatter.toString_LastOnline(datum.date) + ")";
RecordsRecentCollectionViewItemsSource.Add(new Tuple<string, string, string, string>(
mapZoneString, playerServerString, rrtimeString, datum.mapName));
list_index++;
}
}
#endregion
// Event Handlers ----------------------------------------------------------------------------------
#region events
protected override async void OnAppearing()
{
if (!hasLoaded)
{
hasLoaded = true;
await ChangeRecentRecords(false);
LoadingAnimation.IsRunning = false;
RecordsRecentStack.IsVisible = true;
}
}
private async void RRTypeOptionLabel_Tapped(object sender, EventArgs e)
{
List<string> types = new List<string>();
string currentTypeString = EFilter_ToString.toString2(recentRecordsType);
foreach (string type in EFilter_ToString.rrtype_arr)
{
if (type != currentTypeString)
{
types.Add(type);
}
}
string newTypeString = await DisplayActionSheet("Choose a different type", "Cancel", null, types.ToArray());
switch (newTypeString)
{
case "Top10": recentRecordsType = EFilter_RRType.top; break;
case "Stage": recentRecordsType = EFilter_RRType.stage; break;
case "Bonus": recentRecordsType = EFilter_RRType.bonus; break;
case "All WRs": recentRecordsType = EFilter_RRType.all; break;
case "Map": recentRecordsType = EFilter_RRType.map; break;
default: return;
}
list_index = 1;
LoadingAnimation.IsRunning = true;
isLoading = true;
await ChangeRecentRecords(true);
LoadingAnimation.IsRunning = false;
isLoading = false;
}
private async void RecordsRecent_ThresholdReached(object sender, EventArgs e)
{
if (isLoading || !BaseViewModel.hasConnection() || list_index == CALL_LIMIT) return;
isLoading = true;
LoadingAnimation.IsRunning = true;
await ChangeRecentRecords(false);
LoadingAnimation.IsRunning = false;
isLoading = false;
}
private async void RecordsRecent_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection.Count == 0) return;
Tuple<string, string, string, string> selectedMap =
(Tuple<string, string, string, string>)RecordsRecentCollectionView.SelectedItem;
RecordsRecentCollectionView.SelectedItem = null;
string mapName = selectedMap.Item4;
if (BaseViewModel.hasConnection())
{
await Navigation.PushAsync(new MapsMapPage(mapName, game));
}
else
{
await DisplayNoConnectionAlert();
}
}
private async void Filter_Pressed(object sender, EventArgs e)
{
if (hasLoaded && BaseViewModel.hasConnection())
{
await Navigation.PushAsync(new RecordsFilterPage(ApplyFilters, game, mode, defaultGame, defaultMode));
}
else
{
await DisplayNoConnectionAlert();
}
}
internal async void ApplyFilters(EFilter_Game newGame, EFilter_Mode newMode)
{
if (newGame == game && newMode == mode) return;
if (BaseViewModel.hasConnection())
{
game = newGame;
mode = newMode;
list_index = 1;
isLoading = true;
LoadingAnimation.IsRunning = true;
await ChangeRecentRecords(true);
LoadingAnimation.IsRunning = false;
isLoading = false;
}
else
{
await DisplayNoConnectionAlert();
}
}
private async Task DisplayNoConnectionAlert()
{
await DisplayAlert("Could not connect to KSF!", "Please connect to the Internet.", "OK");
}
#endregion
}
}
|
using System.ComponentModel.DataAnnotations;
namespace starteAlkemy.Models.ViewModels
{
public class HomeImagesViewModel
{
#region Ctor
public HomeImagesViewModel(){ }
public HomeImagesViewModel(HomeImages h)
{
IdImage = h.Id;
LinkImage = h.Link;
Text = h.Text;
Active = h.Active;
}
#endregion
#region Getter and Setter
[Key]
public int IdImage { get; set; }
[Display(Name = "Link de la imagen")]
[DataType(DataType.Html)]
public string LinkImage { get; set; }
[MaxLength(int.MaxValue, ErrorMessage = "Supero la cantidad máxima de caracteres")]
[Display(Name = "Descripción")]
[Required(ErrorMessage = "La descripción es obligatoria")]
public string Text { get; set; }
public string LinkVideo { get; set; }
[Display(Name = "Activo")]
public bool Active { get; set; }
#endregion
#region Methods
/// <summary>
/// Set Viewmodel to Db
/// </summary>
/// <returns></returns>
public HomeImages ToEntity()
{
var d = new HomeImages()
{
Id = IdImage,
Active = Active,
Link = LinkImage,
Text = Text
};
return d;
}
#endregion
}
}
|
using Microsoft.EntityFrameworkCore;
using Repository.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ArticlesProject.Repository.Interfaces;
using ArticlesProject.DatabaseEntities;
namespace ArticlesProject.Repository.Implementations
{
public class ReplyRepository : Repository<Reply>, IReplyRepository
{
private DatabaseContext context
{
get
{
return _db as DatabaseContext;
}
}
public ReplyRepository(DbContext db) : base(db)
{
}
public IEnumerable<Reply> GetReplyList()
{
// lazy loading // when we access the child object then only the object values will be loaded.
var result = from reply in context.Replys where reply.Comment.CommentId == 1 select reply;
// eager loading // with include keyword we can achive eager loading // when returning the data with child objects then it will be usefull
var data = result.Include("Comment").Include("User").ToList();
return data;
}
}
}
|
using DatVentas;
using EntVenta;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusVenta
{
public class BusKardex
{
public List<Kardex> ListarMovimiento_kardex(int buscar, string opcion)
{
DataTable dt = new DatKardex().BuscarProducto_Kardex(buscar, opcion);
List<Kardex> lsProductosKardex = new List<Kardex>();
foreach (DataRow dr in dt.Rows)
{
Kardex k = new Kardex();
k.Fecha = Convert.ToDateTime(dr["Fecha"]);
k.Producto = dr["Descripcion"].ToString();
k.Motivo= dr["Motivo"].ToString();
k.Habia = Convert.ToDecimal(dr["Habia"]);
k.Tipo = dr["Tipo"].ToString();
k.Cantidad = Convert.ToDecimal(dr["Cantidad"]);
k.Hay = Convert.ToDecimal(dr["Hay"]);
k.Cajero = dr["Cajero"].ToString();
k.Categoria_Producto = dr["Categoria_Producto"].ToString();
k.Categoria_Presentacion = dr["Categoria_Presentacion"].ToString();
k.Empresa = dr["Empresa"].ToString();
lsProductosKardex.Add(k);
}
return lsProductosKardex;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Kulula.com.Models
{
class Aircraft
{
public int AircraftID { get; set; }
public string AircraftName { get; set; }
public string CarrierName { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour {
public static CameraScript instance;
public float idleAmplitude = 0f;
public float shakeAmplitude = 3f;
Vector3 initialRotation;
Cinemachine.CinemachineBasicMultiChannelPerlin m_perlin;
Cinemachine.CinemachineVirtualCamera m_virtualCamera;
void Awake() {
if(instance == null) {
instance = this;
} else {
DontDestroyOnLoad(gameObject);
}
}
void Start() {
m_virtualCamera = GameObject.FindObjectOfType<Cinemachine.CinemachineVirtualCamera>();
m_perlin = GameObject.FindObjectOfType<Cinemachine.CinemachineBasicMultiChannelPerlin>();
ResetCamera();
}
private IEnumerator ShakeRoutine(float duration, float shakeAmplitude) {
Debug.Log("Shaking Screen");
m_perlin.m_AmplitudeGain = shakeAmplitude;
yield return new WaitForSeconds(duration);
ResetCamera();
}
public void ShakeCamera(float duration) {
StartCoroutine(ShakeRoutine(duration, shakeAmplitude));
}
void ResetCamera() {
m_perlin.m_AmplitudeGain = idleAmplitude;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using DBDiff.Schema.Model;
namespace DBDiff.Schema.SQLServer.Generates.Model
{
public class Constraints<T> : SchemaList<Constraint,T> where T:ISchemaBase
{
public Constraints(T parent)
: base(parent, ((parent == null || parent.Parent == null)?null:((Database)parent.Parent).AllObjects))
{
}
public string ToSql(Constraint.ConstraintType type)
{
StringBuilder sql = new StringBuilder();
for (int index = 0; index < this.Count; index++)
{
if (this[index].Type == type)
{
sql.Append("\t" + this[index].ToSql());
if (index != this.Count - 1)
sql.Append(",");
sql.Append("\r\n");
}
}
return sql.ToString();
}
public string ToSQLAdd(Constraint.ConstraintType type)
{
StringBuilder sql = new StringBuilder();
for (int index = 0; index < this.Count; index++)
{
if (this[index].Type == type)
{
sql.Append(this[index].ToSqlAdd());
sql.Append("\r\n");
}
}
return sql.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
namespace UnityAtoms
{
public abstract class BaseObservable<T> : IObservable<T>
{
protected List<IObserver<T>> _observers = new List<IObserver<T>>();
protected abstract bool IsCompleted { get; }
public IDisposable Subscribe(IObserver<T> observer)
{
if (!_observers.Contains(observer))
_observers.Add(observer);
return new ObservableUnsubscriber<T>(_observers, observer);
}
protected void OnCompleted()
{
if (IsCompleted)
{
for (int i = 0; _observers != null && i < _observers.Count; ++i)
{
_observers[i].OnCompleted();
}
}
}
protected void OnError(Exception e)
{
for (int i = 0; _observers != null && i < _observers.Count; ++i)
{
_observers[i].OnError(e);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using MySql.Data.MySqlClient;
using System.Text;
using System.Data;
using System.Collections;
namespace PlanMGMT
{
public class LoginBLL
{
private static LoginBLL _instance;
private static readonly object _lock = new Object();
public List<Entity.User> InCharges = new List<Entity.User>();
public List<Entity.User> Allusers = new List<Entity.User>();
public List<Entity.PlanStatus> PlanStatus = new List<Entity.PlanStatus>();
public List<Entity.Priority> Priorities = new List<Entity.Priority>();
#region 单一实例
/// <summary>
///
/// </summary>
private LoginBLL()
{
GetAllUsers();
GetPlanStatus();
GetPriorities();
}
/// <summary>
///
/// </summary>
~LoginBLL()
{
Dispose();
}
/// <summary>
/// 返回唯一实例
/// </summary>
public static LoginBLL Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new LoginBLL();
}
}
}
return _instance;
}
}
/// <summary>
///
/// </summary>
public void Dispose()
{
//Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
public Error ssp_login(string Uid,string Pwd)
{
MySqlParameter[] paras = new MySqlParameter[4];
paras[0] = new MySqlParameter("UC", MySqlDbType.VarChar, 20);
paras[0].Value = Uid;
paras[1] = new MySqlParameter("UP", MySqlDbType.VarChar, 100);
paras[1].Value = Pwd;
paras[2] = new MySqlParameter("?ErrCode", MySqlDbType.Int32, int.MaxValue, ParameterDirection.Output, false, 0, 0, null, DataRowVersion.Current,9999);
paras[3] = new MySqlParameter("?ErrText", MySqlDbType.VarChar, 100, ParameterDirection.Output, false, 0, 0, null, DataRowVersion.Current, "");
Mysql.Instance.ExecuteProcS("ssp_login", paras);
return new Error((int)(paras[2].Value), paras[3].Value.ToString());
}
public PSPUser GetUser(string Uid,string Pwd)
{
PSPUser p = new PSPUser();
string sql = "SELECT a.UserCode,a.UserName,a.UserPass,a.Email,a.MPHoneNo,a.RoleID,a.deptID,b.RoleName,c.deptname "+
"FROM utb_users AS a LEFT JOIN utb_roles AS b ON a.RoleID = b.RoleID LEFT JOIN utb_dept AS c ON a.`deptID` = c.`deptid` "+
$"WHERE a.UserCode = '{Uid}' AND a.UserPass = MD5('{Pwd}');";
DTUtilis.LoadValueFromDT(Mysql.Instance.Query(sql).Tables["ds"],p);
return p;
}
public void GetInCharges()
{
List<Entity.User> ls = new List<Entity.User>();
string sql = "SELECT UserCode,UserName From utb_users WHERE RoleID>1";
InCharges=DTUtilis.LoadValueFromDT<Entity.User>(Mysql.Instance.Query(sql).Tables["ds"], ls);
}
public string GetDBUserNameByCode(string UserCode)
{
if (string.IsNullOrEmpty(UserCode))
return "";
string sql = $"select UserName from utb_users where UserCode ='{UserCode}'";
object o = Mysql.Instance.GetSingle(sql);
if (o == null)
{
return "";
}
return o.ToString();
}
public string GetUserNameByCode(string UserCode)
{
if(!string.IsNullOrEmpty(UserCode))
{
return Allusers.Find((a) => a.UserCode == UserCode)==null?"":Allusers.Find((a) => a.UserCode == UserCode ).UserName;
}
else
{
return "";
}
}
public void GetPlanStatus()
{
PlanStatus.Add(new Entity.PlanStatus(0, "未开始"));
PlanStatus.Add(new Entity.PlanStatus(1, "进行中"));
PlanStatus.Add(new Entity.PlanStatus(2, "已完成"));
PlanStatus.Add(new Entity.PlanStatus(3, "暂停"));
}
public List<Entity.Department> GetDepts()
{
List<Entity.Department> ls = new List<Entity.Department>();
string sql = "Select * from utb_dept";
return DTUtilis.LoadValueFromDT<Entity.Department>(Mysql.Instance.Query(sql).Tables["ds"], ls);
}
public void GetAllUsers()
{
List<Entity.User> ls = new List<Entity.User>();
string sql = "SELECT UserCode,UserName From utb_users";
Allusers = DTUtilis.LoadValueFromDT<Entity.User>(Mysql.Instance.Query(sql).Tables["ds"], ls);
}
public void GetPriorities()
{
Priorities.Add(new Entity.Priority(0, "低"));
Priorities.Add(new Entity.Priority(1, "一般"));
Priorities.Add(new Entity.Priority(2, "紧急"));
Priorities.Add(new Entity.Priority(3, "非常紧急"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.Data;
namespace MyIVDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
new Task(ShowDatabaseInGrid).Start();
}
public async void ShowDatabaseInGrid()
{
DataSet dataSet = await Connection.ShowDatabaseInGrid();
Dispatcher.Invoke(() =>
{
if (dataSet.Tables.Count > 0)
dataGrid.ItemsSource = dataSet.Tables[0].DefaultView;
});
}
private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
dataGrid.ItemsSource = null;
new Task(ShowDatabaseInGrid).Start();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
AddWindow add = new AddWindow();
add.Show();
}
private async void btnDelete_Click(object sender, RoutedEventArgs e)
{
object item = dataGrid.SelectedItem;
string removetask = (dataGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
if (item == null)
{
await this.ShowMessageAsync("Error","No pokemon selected to remove.");
}
else
{
MessageDialogResult res = await this.ShowMessageAsync("",$"Are you sure you want to remove {removetask}?", MessageDialogStyle.AffirmativeAndNegative);
if (res == MessageDialogResult.Negative)
{
await this.ShowMessageAsync("","Cancelled removal.");
}
else
{
DeletePoke.DeleteRow(removetask);
await this.ShowMessageAsync("", $"Succesfully removed {removetask}.");
}
dataGrid.ItemsSource = null;
new Task(ShowDatabaseInGrid).Start();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectCore.Model.Parameter
{
public class BasePagingParam
{
public string SearchText { get; set; } = null;
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public string SortOrder { get; set; } = null;
public string SortName { get; set; } = null;
public int Offset { get { return (PageNumber - 1) * PageSize; } }
public int Limit { get { return PageSize; } }
public int End { get { return (PageNumber) * PageSize; } }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TWeapon : MonoBehaviour
{
public GameObject bullet;
public IWeaponBase weapon;
public float start_ATK=100, start_range=10, start_speed=5f,start_bullet_speed=15f;
private int atk_mouse_code = 0;
private Transform shoot_point_trans;
void Start()
{
weapon = new Gun(fATK: start_ATK, fAT_speed: start_speed, fAT_range: start_range, fbullet_move_speed: start_bullet_speed, fbullet: bullet);
shoot_point_trans = gameObject.GetComponent<Transform>();
}
void Update()
{
if (Input.GetMouseButton(atk_mouse_code) == true)
{
weapon.Attack(shoot_point_trans.position, shoot_point_trans.forward);
}
}
}
|
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
var res = new List<IList<int>>();
if (nums.Length < 3) return res;
Array.Sort(nums);
for (int i = 0; i < nums.Length - 2; i ++) {
if (i != 0 && nums[i] == nums[i-1]) continue;
int curr = nums[i];
int left = i + 1;
int right = nums.Length - 1;
while (left < right) {
if (nums[left] + nums[right] + curr == 0) {
res.Add(new List<int>(){curr, nums[left], nums[right]});
left ++;
right --;
while (left < nums.Length && nums[left] == nums[left - 1])
left++;
while (right >= 0 && nums[right] == nums[right + 1])
right--;
} else if (nums[left] + nums[right] < -curr) {
left ++;
} else {
right --;
}
}
}
return res;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using alg;
/*
* tags: dp
* Time(n), Space(n), n is width of num
*/
namespace leetcode
{
public class Lc600_Nonnegative_Integers_without_Consecutive_Ones
{
public int FindIntegers(int num)
{
var dp = new int[32];
dp[0] = 1; dp[1] = 2;
for (int i = 2; i < dp.Length; i++)
dp[i] = dp[i - 1] + dp[i - 2];
int res = 1;
for (int prevBit = 0, i = 30; i >= 0; i--)
{
if ((num & (1 << i)) != 0)
{
res += dp[i];
if (prevBit == 1) { res--; break; }
prevBit = 1;
}
else prevBit = 0;
}
return res;
}
public int FindIntegers2(int num)
{
var s = Convert.ToString(num, 2);
int n = s.Length;
var dp = GetDp(n);
int res = dp[0, n - 1] + dp[1, n - 1];
for (int i = 1; i < s.Length; i++)
{
if (s[i] == '0' && s[i - 1] == '0') res -= dp[1, n - 1 - i];
if (s[i] == '1' && s[i - 1] == '1') break;
}
return res;
}
/*
* dp[0, i] is count of satisfied numbers with width (i+1) and first bit is 0
* dp[1, i] is count of satisfied numbers with width (i+1) and first bit is 1
*/
int[,] GetDp(int n)
{
var dp = new int[2, n];
dp[0, 0] = dp[1, 0] = 1;
for (int i = 1; i < n; i++)
{
dp[0, i] = dp[0, i - 1] + dp[1, i - 1];
dp[1, i] = dp[0, i - 1];
}
return dp;
}
public void Test()
{
Console.WriteLine(FindIntegers(5) == 5);
Console.WriteLine(FindIntegers(6) == 5);
Console.WriteLine(FindIntegers(10) == 8);
Console.WriteLine(FindIntegers2(5) == 5);
Console.WriteLine(FindIntegers2(6) == 5);
Console.WriteLine(FindIntegers2(10) == 8);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Serialization;
using AxiRepositories.Repositories;
using KartLib;
using KartLib.Common;
using KartLib.Special;
using KartObjects;
using KartObjects.Entities.Documents;
using Ninject;
namespace KartSystem.Common
{
public partial class ImportDocumentFromExl : Form
{
private const int MaxHeight = 370;
private const int MinHeight = 120;
private readonly ImportDocumentFromExlParamSettings localSettingsPosition =
new ImportDocumentFromExlParamSettings();
private FormWait frmWait;
public ImportDocumentFromExl()
{
InitializeComponent();
localSettingsPosition.ListSettings = new List<ExcelImportSettings>();
Size = new Size(width, MinHeight);
}
public void SaveSettings()
{
var p = new ImportDocumentFromExlSettingsLastSelect {Name = lueFormat.Text};
SaveSettings<ImportDocumentFromExlSettingsLastSelect>(p);
SaveSettings<ImportDocumentFromExlParamSettings>(localSettingsPosition);
}
public void LoadSettings()
{
var ex = (ImportDocumentFromExlParamSettings) LoadSettings<ImportDocumentFromExlParamSettings>();
if (ex != null)
{
localSettingsPosition.ListSettings.AddRange(ex.ListSettings);
exportDocumentFromExlSettingsLastSelectBindingSource.DataSource =
ex.ListSettings.Select(item => new ImportDocumentFromExlSettingsLastSelect {Name = item.Name})
.ToList();
}
var p = (ImportDocumentFromExlSettingsLastSelect) LoadSettings<ImportDocumentFromExlSettingsLastSelect>();
if (p != null)
{
lueFormat.EditValue = p.Name;
}
}
protected Entity LoadSettings<T>()
{
Entity e = null;
string fileName = Settings.GetExecPath() + @"\settings\export\" + typeof (T).Name +
KartDataDictionary.User.Id + ".xml";
if (File.Exists(fileName))
using (var reader = new StreamReader(fileName))
{
var settingsSerializer = new XmlSerializer(typeof (T));
e = settingsSerializer.Deserialize(reader) as Entity;
}
return e;
}
protected void SaveSettings<T>(Entity viewSettings) where T : Entity, new()
{
if (!Directory.Exists(Settings.GetExecPath() + @"\settings"))
Directory.CreateDirectory(Settings.GetExecPath() + @"\settings");
if (!Directory.Exists(Settings.GetExecPath() + @"\settings\export"))
Directory.CreateDirectory(Settings.GetExecPath() + @"\settings\export");
TextWriter writer =
new StreamWriter(Settings.GetExecPath() + @"\settings\export\" + typeof (T).Name +
KartDataDictionary.User.Id + ".xml");
var serializer = new XmlSerializer(viewSettings.GetType());
serializer.Serialize(writer, viewSettings);
writer.Close();
}
private void ExportDocumentFromExl_Load(object sender, EventArgs e)
{
LoadSettings();
}
private void ExportDocumentFromExl_FormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
var excelDocImporter = IocContainer.AppKernel.Get<KartLib.Special.IExcelDocImporter>();
Document document = null;
openFileDialog1.InitialDirectory = Settings.GetExecPath();
openFileDialog1.Filter = @"Таблицы Excel (*.xls; *.xlsx)|*.xls;*.xlsx";
openFileDialog1.FileName = "*.xls";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
frmWait = new FormWait("Импорт документа ...");
KartDataDictionary.ReportRunningFlag = true;
// Процесс формирования запускаем отдельным потоком
var thread = new Thread(new ThreadStart(
delegate
{
document = excelDocImporter.ImportDoc(openFileDialog1.FileName,
localSettingsPosition.ListSettings.First(settings => settings.Name == lueFormat.Text));
Thread.Sleep(100);
// ReSharper disable AccessToDisposedClosure
if (frmWait != null)
frmWait.CloseWaitForm();
// ReSharper restore AccessToDisposedClosure
}));
thread.Start();
frmWait.ShowDialog();
KartDataDictionary.ReportRunningFlag = false;
frmWait.Dispose();
frmWait = null;
var invoiceRepository = IocContainer.AppKernel.Get<IInvoiceDocumentRepository>();
if (document != null)
{
var editor = new InvoiceDocsEditor(invoiceRepository.Get(document));
editor.ShowDialog();
Close();
}
}
}
private void simpleButton2_Click(object sender, EventArgs e)
{
string name;
if (!string.IsNullOrEmpty(teName.Text))
{
name = teName.Text;
}
else if (!string.IsNullOrEmpty(lueFormat.EditValue.ToString()))
{
name = lueFormat.EditValue.ToString();
}
else name = "Новый формат_" + DateTime.Now;
if (localSettingsPosition.ListSettings.Exists(q => q.Name == name))
{
ExcelImportSettings p = localSettingsPosition.ListSettings.FirstOrDefault(q => q.Name == name);
if (p != null)
{
p.Table = teGoodTable.Text;
p.ArticulPosition = Convert.ToInt32(teGoodArticul.Text);
p.GoodPosition = Convert.ToInt32(teGoodName.Text);
p.MeasurePosition = Convert.ToInt32(teGoodMeasure.Text);
p.PricePosition = Convert.ToInt32(teGoodPrice.Text);
p.QuantityPosition = Convert.ToInt32(teGoodQuantity.Text);
p.CreateGood = cbMakeNewGood.Checked;
p.BarcodePosition = Convert.ToInt32(teBarcodePosition.Text);
}
}
else
localSettingsPosition.ListSettings.Add(new ExcelImportSettings
{
Table = teGoodTable.Text,
Name = name,
ArticulPosition = Convert.ToInt32(teGoodArticul.Text),
GoodPosition = Convert.ToInt32(teGoodName.Text),
MeasurePosition = Convert.ToInt32(teGoodMeasure.Text),
PricePosition = Convert.ToInt32(teGoodPrice.Text),
QuantityPosition = Convert.ToInt32(teGoodQuantity.Text),
CreateGood = cbMakeNewGood.Checked,
BarcodePosition = Convert.ToInt32(teBarcodePosition)
});
List<ImportDocumentFromExlSettingsLastSelect> list =
localSettingsPosition.ListSettings.Select(
item2 => new ImportDocumentFromExlSettingsLastSelect {Name = item2.Name}).ToList();
exportDocumentFromExlSettingsLastSelectBindingSource.DataSource = list;
lueFormat.EditValue = name;
SaveSettings();
}
private void lueFormat_EditValueChanged(object sender, EventArgs e)
{
ExcelImportSettings p =
localSettingsPosition.ListSettings.FirstOrDefault(q => q.Name == lueFormat.EditValue.ToString());
if (p != null)
{
teGoodTable.Text = p.Table;
teGoodArticul.Text = p.ArticulPosition.ToString(CultureInfo.InvariantCulture);
teGoodName.Text = p.GoodPosition.ToString(CultureInfo.InvariantCulture);
teGoodMeasure.Text = p.MeasurePosition.ToString(CultureInfo.InvariantCulture);
teGoodPrice.Text = p.PricePosition.ToString(CultureInfo.InvariantCulture);
teGoodQuantity.Text = p.QuantityPosition.ToString(CultureInfo.InvariantCulture);
cbMakeNewGood.Checked = p.CreateGood;
teBarcodePosition.Text = p.BarcodePosition.ToString();
}
}
private void simpleButton3_Click(object sender, EventArgs e)
{
switch (Size.Height)
{
case MinHeight:
Size = new Size(width, MaxHeight);
break;
case MaxHeight:
Size = new Size(width, MinHeight);
break;
}
}
}
}
|
using System.Collections.Generic;
namespace Traffic_Light_Simulator
{
public class TrafficMonitor
{
public IList<BaseCrossing> Crossings { get; set; }
public void Save() { }
public void Load() { }
public void SaveAs() { }
public bool AddCrossing(BaseCrossing crossing) { return true; }
public bool RemoveCrossing(BaseCrossing crossing) { return true; }
public void StartSimulation() { }
public void StopSimulation() { }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lifetime : MonoBehaviour
{
public int lifeLeft = 1;
private Animator animator;
private void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (lifeLeft <= 0)
{
EventManager.Instance.Fire(new PlayerDied());
this.gameObject.transform.Translate(new Vector3(0.0f,-0.6f,-1.0f));
animator.SetBool("notDead", false);
Destroy(GetComponent(typeof(MoveForward)));
Destroy(GetComponent(typeof(Controlledbykeyboard)));
Destroy(GetComponent(typeof(BoxCollider)));
var camera = GameObject.FindGameObjectWithTag("MainCamera");
Destroy(camera.GetComponent(typeof(MoveForward)));
Destroy(this);
}
}
}
|
using BuilderCore;
using ChampionsOfForest.Player;
using TheForest.Items.World;
using UnityEngine;
namespace ChampionsOfForest
{
public class SomeFuckingBowControllerClass : BowController
{
protected override void Start()
{
try
{
if (_bowItemId == 79)
{
gameObject.AddComponent<CustomBowBase>();
}
}
catch (System.Exception)
{
}
base.Start();
}
}
public class CustomBowBase : MonoBehaviour
{
public static GameObject baseBow;
public static BowController baseBowC;
void Start()
{
if (baseBow == null)
{
baseBow = gameObject;
baseBowC = gameObject.GetComponent<BowController>();
var greatbow = Instantiate(gameObject, transform.position, transform.rotation, transform.parent);
CotfUtils.Log("Created greatbow obj");
greatbow.AddComponent<GreatBow>();
}
}
void OnEnable()
{
Start();
}
}
public class GreatBow : MonoBehaviour
{
public static bool isEnabled;
public static GameObject instance;
BowController bc;
GameObject model = null;
void OnEnable()
{
isEnabled = true;
if (BoltNetwork.isRunning)
{
using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
{
using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
{
w.Write(28);
w.Write(ModReferences.ThisPlayerID);
w.Write((int)BaseItem.WeaponModelType.Greatbow);
w.Close();
}
ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others);
answerStream.Close();
}
}
PlayerInventoryMod.ToEquipWeaponType = BaseItem.WeaponModelType.None;
}
void OnDisable()
{
isEnabled = false;
if (BoltNetwork.isRunning)
{
using (System.IO.MemoryStream answerStream = new System.IO.MemoryStream())
{
using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(answerStream))
{
w.Write(28);
w.Write(ModReferences.ThisPlayerID);
w.Write((int)BaseItem.WeaponModelType.None);
w.Close();
}
ChampionsOfForest.Network.NetworkManager.SendLine(answerStream.ToArray(), ChampionsOfForest.Network.NetworkManager.Target.Others);
answerStream.Close();
}
}
}
void Start()
{
bc = GetComponent<BowController>();
instance = gameObject;
try
{
var bow = transform.Find("Bow");
Destroy(transform.Find("TapedLight").gameObject);
//if (modelPrefab == null) modelPrefab = Res.ResourceLoader.GetAssetBundle(2004).LoadAsset<GameObject>("firebow.prefab");
//model = Instantiate(modelPrefab);
model = new GameObject();
model.transform.parent = bow.parent;
model.transform.localScale = Vector3.one * 1.5f;
model.transform.localPosition = new Vector3(0, 0, 0.3f);
model.transform.localRotation = Quaternion.Euler(0,180,0);
model.AddComponent<MeshFilter>().mesh = Res.ResourceLoader.instance.LoadedMeshes[167];
model.AddComponent<MeshRenderer>().material =
Core.CreateMaterial(new BuildingData()
{
BumpMap = Res.ResourceLoader.GetTexture(168),
BumpScale = 1.4f,
Metalic = 0.6f,
Smoothness = 0.6f,
MainTexture = Res.ResourceLoader.GetTexture(169),
EmissionMap = Res.ResourceLoader.GetTexture(169),
});
Destroy(bow.gameObject);
model.transform.localScale *= 1.1f;
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
}
public void OnAmmoFired(GameObject projectile)
{
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace HideAndSeekTests
{
using System;
using HideAndSeek;
using System.Collections.Generic;
using System.Diagnostics;
[TestClass]
public class LocationTests
{
private Location center;
/// <summary>
/// Initializes each unit test by setting creating a new the center location
/// and adding a room in each direction before the test
/// </summary>
[TestInitialize]
public void Initialize()
{
center = new Location("Hallway");
center.Exits.Add(Direction.Northwest, new Location("Kitchen"));
center.Exits.Add(Direction.North, new Location("Bathroom"));
center.Exits.Add(Direction.South, new Location("Living Room"));
center.Exits.Add(Direction.West, new Location("Entry"));
center.Exits.Add(Direction.Up, new Location("Landing"));
}
/// <summary>
/// Make sure GetExit returns the location in a direction only if it exists
/// </summary>
[TestMethod]
public void TestGetExit()
{
foreach (var l in center.Exits) Console.WriteLine(l.Value);
var room = center.GetExit(Direction.Northwest);
Console.WriteLine(room.Name);
Console.WriteLine(center.Name);
}
/// <summary>
/// Validates that the exit lists are working
/// </summary>
[TestMethod]
public void TestExitList()
{
// This test will make sure the ExitList property works
}
/// <summary>
/// Validates that each room’s name and return exit is created correctly
/// </summary>
[TestMethod]
public void TestReturnExits()
{
// This test will test navigating through the center Location
}
/// <summary>
/// Add a hall to one of the rooms and make sure the hall room’s names
/// and return exits are created correctly
/// </summary>
[TestMethod]
public void TestAddHall()
{
// This test will add a hallway with two locations and make sure they work
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using BanSupport;
using System;
public class Example : MonoBehaviour
{
public static int global_index = 0;
public bool useOpenCloseRefreshEvent = false;
public bool useBeginDragEvent = false;
public bool useDragEvent = false;
public bool useEndDragEvent = false;
public Button buttonDeleteAll;
public Button buttonAddChat;
public Button buttonAddChatJump;
public Button buttonCreateDeleteAndAdd;
public Button buttonJumpWithoutAnimation;
public Button buttonReverse;
public Button buttonRemoveFirst;
public Button buttonRemoveLast;
public Button ButtonRefresh;
public Button ButtonChangeData;
public InputField inputField_Number;
public Button buttonAdd;
public Button buttonCheck;
public Button buttonCheckExcept;
public Button buttonA;
public Button buttonB;
public Button buttonC;
public Button buttonD;
public Button buttonE;
public InputField inputField_JumpDataIndex;
public Button buttonJumpData;
public Button buttonLastOne;
public Button buttonNextOne;
public Button buttonJumpBegin;
public Button buttonJumpEnd;
public Button ButtonIsFirstVisible;
public Button ButtonIsLastVisible;
public Button ButtonEnableMovement;
public Button ButtonDisableMovement;
public Slider sliderJumpProgress;
public Text textJumpProgress;
public string[] prefabNames;
public bool[] prefabSelected;
public ScrollSystem scrollSystem;
public InputField inputField_ChatContent;
public bool setWorldPosEnable = true;
public static Example Instance;
public List<string> GetSelectedPrefabNames()
{
List<string> result = new List<string>();
for (int i = 0; i < prefabSelected.Length; i++)
{
if (prefabSelected[i])
{
result.Add(prefabNames[i]);
}
}
return result;
}
public int GetInputFieldCount()
{
return int.Parse(inputField_Number.text);
}
private void Awake()
{
Instance = this;
}
private List<SimpleData> deleteAndAddDatas = new List<SimpleData>();
private List<SimpleData> createdDatas = new List<SimpleData>();
void Start()
{
for (int i = 0; i < 100; i++)
{
deleteAndAddDatas.Add(new SimpleData { index = Example.global_index++ });
}
BindEvent();
scrollSystem.SetItemRefresh((prefabName, root, data) =>
{
if (useOpenCloseRefreshEvent)
{
Debug.Log(string.Format(" {0} Refresh id:{1}", prefabName, (data as SimpleData).index.ToString()));
}
switch (prefabName)
{
case "A":
{
root.GetComponent<ItemA>().OnRefresh(data as SimpleData);
}
break;
case "B":
{
root.GetComponent<ItemB>().OnRefresh(data as SimpleData);
}
break;
case "C":
{
root.GetComponent<ItemC>().OnRefresh(data as SimpleData);
}
break;
case "D":
{
root.GetComponent<ItemD>().OnRefresh(data as SimpleData);
}
break;
case "Chat":
{
root.GetComponent<ItemChat>().OnRefresh(data as ChatData);
}
break;
}
});
scrollSystem.SetItemClose((prefabName, root, data) =>
{
if (useOpenCloseRefreshEvent)
{
Debug.Log(string.Format(" {0} Close", prefabName));
}
});
scrollSystem.SetItemOpen((prefabName, root, data) =>
{
if (useOpenCloseRefreshEvent)
{
Debug.Log(string.Format(" {0} Open", prefabName));
}
});
if (useBeginDragEvent)
{
scrollSystem.SetBeginDrag(data =>
{
Debug.Log("OnBeginDrag");
});
}
if (useEndDragEvent)
{
scrollSystem.SetEndDrag(data =>
{
Debug.Log("OnEndDrag");
});
}
if (useDragEvent)
{
scrollSystem.SetDrag(data =>
{
Debug.Log("OnDrag");
});
}
}
private void BindEvent()
{
Button[] buttons = new Button[] { buttonA, buttonB, buttonC, buttonD, buttonE };
for (int i = 0; i < buttons.Length; i++)
{
var curButton = buttons[i];
var index = i;
Action readAction = () =>
{
curButton.transform.Find("Mark").gameObject.SetActive(prefabSelected[index]);
};
curButton.onClick.AddListener(() =>
{
prefabSelected[index] = !prefabSelected[index];
readAction();
});
readAction();
}
buttonAdd.onClick.AddListener(() =>
{
foreach (var aName in GetSelectedPrefabNames())
{
for (int i = 0; i < GetInputFieldCount(); i++)
{
scrollSystem.Add(aName, GenerateSimpleData());
}
}
});
buttonCheck.onClick.AddListener(() => { Debug.Log(scrollSystem.GetDataCount(GetSelectedPrefabNames().ToArray())); });
buttonCheckExcept.onClick.AddListener(() => { Debug.Log(scrollSystem.GetDataCountExcept(GetSelectedPrefabNames().ToArray())); });
buttonAddChat.onClick.AddListener(() =>
{
AddChat(inputField_ChatContent.text);
});
buttonAddChatJump.onClick.AddListener(() =>
{
AddChat(inputField_ChatContent.text);
scrollSystem.Jump(1);
});
buttonDeleteAll.onClick.AddListener(() =>
{
createdDatas.Clear();
scrollSystem.Clear();
});
buttonCreateDeleteAndAdd.onClick.AddListener(() =>
{
createdDatas.Clear();
scrollSystem.Clear();
foreach (var simpleData in deleteAndAddDatas)
{
createdDatas.Add(simpleData);
scrollSystem.Add("D", simpleData);
}
});
buttonJumpWithoutAnimation.onClick.AddListener(() => { scrollSystem.Jump(1, false); });
buttonReverse.onClick.AddListener(() => { createdDatas.Reverse(); scrollSystem.Reverse(); });
buttonRemoveFirst.onClick.AddListener(() =>
{
if (createdDatas.Count > 0)
{
var removedData = createdDatas[0];
createdDatas.Remove(removedData);
scrollSystem.Remove(removedData);
}
}
);
buttonRemoveLast.onClick.AddListener(() =>
{
if (createdDatas.Count > 0)
{
var removedData = createdDatas[createdDatas.Count - 1];
createdDatas.Remove(removedData);
scrollSystem.Remove(removedData);
}
}
);
ButtonRefresh.onClick.AddListener(() => { scrollSystem.Refresh(); });
ButtonChangeData.onClick.AddListener(() => { createdDatas.ForEach(temp => { temp.index++; Debug.Log("added to index:" + temp.index); }); });
buttonJumpData.onClick.AddListener(() =>
{
if (int.TryParse(inputField_JumpDataIndex.text, out int result))
{
scrollSystem.Jump(result, true);
}
});
buttonLastOne.onClick.AddListener(() =>
{
if (int.TryParse(inputField_JumpDataIndex.text, out int result))
{
if (result > 0)
{
result--;
inputField_JumpDataIndex.text = result.ToString();
scrollSystem.Jump(result, true);
}
}
});
buttonNextOne.onClick.AddListener(() =>
{
if (int.TryParse(inputField_JumpDataIndex.text, out int result))
{
if (result + 1 < scrollSystem.GetDataCount())
{
result++;
inputField_JumpDataIndex.text = result.ToString();
scrollSystem.Jump(result, true);
}
}
});
sliderJumpProgress.onValueChanged.AddListener(progress =>
{
textJumpProgress.text = progress.ToString("0.00");
scrollSystem.Jump(progress);
});
buttonJumpBegin.onClick.AddListener(() =>
{
scrollSystem.Jump(0, !Input.GetKey(KeyCode.S));
});
buttonJumpEnd.onClick.AddListener(() =>
{
scrollSystem.Jump(1, !Input.GetKey(KeyCode.S));
});
ButtonIsFirstVisible.onClick.AddListener(() =>
{
Debug.Log("IsFirstVIsible:"+ scrollSystem.IsFirstVisible().ToString());
});
ButtonIsLastVisible.onClick.AddListener(() =>
{
Debug.Log("IsLastVIsible:" + scrollSystem.IsLastVisible().ToString());
});
ButtonEnableMovement.onClick.AddListener(()=> {
scrollSystem.EnableMovement();
});
ButtonDisableMovement.onClick.AddListener(() => {
scrollSystem.DisableMovement();
});
}
public SimpleData GenerateSimpleData()
{
var returnData = new SimpleData { index = global_index++ };
createdDatas.Add(returnData);
return returnData;
}
private void AddChat(string msg)
{
scrollSystem.Add("Chat", new ChatData { msg = msg}, GetChatHeight);
}
private Vector2 GetChatHeight(object data)
{
ScrollLayout referScrollLayout = scrollSystem.GetOriginPrefab("Chat").GetComponent<ScrollLayout>();
var height = referScrollLayout.GetHeightByStr((data as ChatData).msg);
return new Vector2(-1, height);
}
//private void OnGUI()
//{
// GUILayout.Label(ObjectPool<ScrollSystem.SearchGroup>.GetState());
//}
}
public class SimpleData
{
public int index;
}
public class ChatData : SimpleData
{
public string msg;
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
namespace ExercicioFuncionario
{
class Program
{
static void Main(string[] args)
{
Console.Write("How many employees will be registered? ");
int n = int.Parse(Console.ReadLine());
List<Registro> funcionarios = new List<Registro>();
for (int i = 0; i < n; i++)
{
Console.WriteLine("Employees - " + (i+1));
Console.Write("ID: ");
int id = int.Parse(Console.ReadLine());
Console.Write("Nome: ");
string name = Console.ReadLine();
Console.Write("Salary: ");
double salary = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
funcionarios.Add(new Registro {Id = id, Name = name, Salary = salary});
}
Console.WriteLine("Enter the employees id that will have salary increase: ");
int idIncrease = int.Parse(Console.ReadLine());
Registro comparacao = funcionarios.Find(x => x.Id == idIncrease);
//List<Registro> comparacao = funcionarios.FindAll(x => x.Id == idIncrease);
if (comparacao != null)
{
Console.WriteLine("Enter the percentage: ");
double percentage = Double.Parse(Console.ReadLine());
comparacao.AumentaSalario(percentage);
}
else
{
Console.WriteLine("This id does not exist!");
}
foreach (Registro obj in funcionarios)
{
Console.WriteLine(obj);
}
}
}
}
|
using Unity.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using Klak.Ndi;
namespace Rcam2 {
sealed class Controller : MonoBehaviour
{
#region Editable attributes
[Space]
[SerializeField] Transform _cameraTransform = null;
[SerializeField] ARCameraManager _cameraManager = null;
[SerializeField] ARCameraBackground _cameraBackground = null;
[SerializeField] AROcclusionManager _occlusionManager = null;
[Space]
[SerializeField] float _minDepth = 0.2f;
[SerializeField] float _maxDepth = 3.2f;
[Space]
[SerializeField] Text _statusText = null;
#endregion
#region Hidden external asset reference
[SerializeField, HideInInspector] NdiResources _ndiResources = null;
[SerializeField, HideInInspector] Shader _shader = null;
#endregion
#region Shader IDs
static class ShaderID
{
public static int Y = Shader.PropertyToID("_textureY");
public static int CbCr = Shader.PropertyToID("_textureCbCr");
public static int Mask = Shader.PropertyToID("_HumanStencil");
public static int Depth = Shader.PropertyToID("_EnvironmentDepth");
public static int Range = Shader.PropertyToID("_DepthRange");
}
#endregion
#region Internal-use objects
const int _width = 2048;
const int _height = 1024;
NdiSender _ndiSender;
Matrix4x4 _projection;
Material _bgMaterial;
Material _muxMaterial;
RenderTexture _senderRT;
#endregion
#region Internal-use properties and methods
string StatusText => MakeStatusText();
string MakeStatusText()
{
var pos = _cameraTransform.position;
var rot = _cameraTransform.rotation.eulerAngles;
var text = $"Position: ({pos.x}, {pos.y}, {pos.z})\n";
text += $"Rotation: ({rot.x}, {rot.y}, {rot.z})\n";
text += $"Projection: {_projection}";
return text;
}
Metadata BuildMetadata()
=> new Metadata { CameraPosition = _cameraTransform.position,
CameraRotation = _cameraTransform.rotation,
DepthRange = new Vector2(_minDepth, _maxDepth),
ProjectionMatrix = _projection };
#endregion
#region Camera events
void OnCameraFrameReceived(ARCameraFrameEventArgs args)
{
for (var i = 0; i < args.textures.Count; i++)
{
var id = args.propertyNameIds[i];
var tex = args.textures[i];
if (id == ShaderID.Y)
_muxMaterial.SetTexture(ShaderID.Y, tex);
else if (id == ShaderID.CbCr)
_muxMaterial.SetTexture(ShaderID.CbCr, tex);
}
if (args.projectionMatrix.HasValue)
_projection = args.projectionMatrix.Value;
}
void OnOcclusionFrameReceived(AROcclusionFrameEventArgs args)
{
for (var i = 0; i < args.textures.Count; i++)
{
var id = args.propertyNameIds[i];
var tex = args.textures[i];
if (id == ShaderID.Mask )
_muxMaterial.SetTexture(ShaderID.Mask, tex);
else if (id == ShaderID.Depth)
_muxMaterial.SetTexture(ShaderID.Depth, tex);
}
}
#endregion
#region MonoBehaviour implementation
void Start()
{
// Shader setup
_bgMaterial = new Material(_shader);
_bgMaterial.EnableKeyword("RCAM_MONITOR");
_muxMaterial = new Material(_shader);
_muxMaterial.EnableKeyword("RCAM_MULTIPLEXER");
// Custom background material
_cameraBackground.customMaterial = _bgMaterial;
_cameraBackground.useCustomMaterial = true;
// Render texture as NDI source
_senderRT = new RenderTexture(_width, _height, 0);
_senderRT.Create();
// NDI sender instantiation
_ndiSender = gameObject.AddComponent<NdiSender>();
_ndiSender.SetResources(_ndiResources);
_ndiSender.ndiName = "Rcam";
_ndiSender.captureMethod = CaptureMethod.Texture;
_ndiSender.sourceTexture = _senderRT;
}
void OnDestroy()
{
Destroy(_bgMaterial);
Destroy(_muxMaterial);
Destroy(_senderRT);
}
void OnEnable()
{
_cameraManager.frameReceived += OnCameraFrameReceived;
_occlusionManager.frameReceived += OnOcclusionFrameReceived;
}
void OnDisable()
{
_cameraManager.frameReceived -= OnCameraFrameReceived;
_occlusionManager.frameReceived -= OnOcclusionFrameReceived;
}
void Update()
{
_statusText.text = StatusText;
// Parameter update
var range = new Vector2(_minDepth, _maxDepth);
_bgMaterial.SetVector(ShaderID.Range, range);
_muxMaterial.SetVector(ShaderID.Range, range);
// NDI sender RT update
Graphics.Blit(null, _senderRT, _muxMaterial, 0);
// Metadata
_ndiSender.metadata = BuildMetadata().Serialize();
}
#endregion
}
} // namespace Rcam2
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("Drugie info");
Console.WriteLine("Trzecie info");
Console.WriteLine("Czwarte info");
Console.WriteLine("Piąte info");
Console.WriteLine("Szóste info");
Console.WriteLine("Siódme info");
Console.WriteLine("Ósme info");
Console.WriteLine("999");
}
}
}
|
namespace Properties.Core.Interfaces
{
public interface IPropertyDetailServiceAdvertisingFacade : IPropertyDetailService
{
}
}
|
namespace com.Sconit.Entity.SI.SD_ORD
{
using System;
using System.Collections.Generic;
[Serializable]
public partial class PickListMaster
{
#region O/R Mapping Properties
public string PickListNo { get; set; }
public string Flow { get; set; }
public com.Sconit.CodeMaster.PickListStatus Status { get; set; }
public com.Sconit.CodeMaster.OrderType OrderType { get; set; }
public DateTime StartTime { get; set; }
public DateTime WindowTime { get; set; }
public string PartyFrom { get; set; }
public string PartyTo { get; set; }
public string Dock { get; set; }
public Boolean IsAutoReceive { get; set; }
public Boolean IsReceiveScan { get; set; }
public Boolean IsPrintAsn { get; set; }
public Boolean IsPrintReceipt { get; set; }
public Boolean IsReceiveExceed { get; set; }
public Boolean IsReceiveFulfillUC { get; set; }
public Boolean IsReceiveFifo { get; set; }
public Boolean IsAsnUniqueReceive { get; set; }
public Boolean IsCheckPartyFromAuthority { get; set; }
public Boolean IsCheckPartyToAuthority { get; set; }
public CodeMaster.CreateHuOption CreateHuOption { get; set; }
public com.Sconit.CodeMaster.ReceiveGapTo ReceiveGapTo { get; set; }
public DateTime EffectiveDate { get; set; }
#endregion
#region ¼ð»õµ¥Ã÷ϸ
public List<PickListDetail> PickListDetails { get; set; }
#endregion
}
}
|
using CollaborativeFiltering;
using CollaborativeFilteringUI.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace CollaborativeFilteringUI.Views.AddUser
{
public interface IAddUserViewModel : IViewModel
{
IDataRepository DataRepository { get; set; }
string UserName { get; set; }
ICommand Add { get; set; }
}
}
|
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
namespace IronAHK.Scripting
{
partial class ILMirror
{
private delegate byte[] GetBytes<T>(T arg);
public FieldInfo GrabField(FieldInfo Field)
{
return GrabField(Field, null);
}
protected FieldInfo GrabField(FieldInfo Field, TypeBuilder On)
{
if (Field == null) return null;
if (FieldsDone.ContainsKey(Field))
return FieldsDone[Field];
if (!Sources.Contains(Field.Module))
return Field;
if (On == null)
On = GrabType(Field.DeclaringType) as TypeBuilder;
FieldBuilder CopiedField = On.DefineField(Field.Name, GrabType(Field.FieldType), Field.Attributes);
FieldsDone.Add(Field, CopiedField);
if (Field.IsLiteral && Field.DeclaringType.IsEnum)
CopiedField.SetConstant(Field.GetRawConstantValue());
FieldOffsetAttribute Attr = FindCustomAttribute<FieldOffsetAttribute>(Field);
if (Attr != null)
CopiedField.SetOffset(Attr.Value);
// Fields like these mostly have a backing field that comes with them in the
// <PrivateImplementationDetails> class of the assembly. This backing field
// refers to a bit of data in the .sdata section, which is serialized in a
// way not exposed by the .NET framework. The best thing we can do is to try
// to replicate this format.
if (Field.IsStatic && Field.IsInitOnly)
{
object Val = Field.GetValue(null);
Type ValType = Val.GetType();
if (ValType.IsArray)
{
byte[] Raw = RawSerialize((Array) Val, ValType.GetElementType());
FieldBuilder Backing = ImplementationDetails.DefineInitializedData(Field.Name, Raw, Field.Attributes);
// This is used later on when we recognize the initilization pattern (see TryReplaceBackingField)
BackingFields.Add(CopiedField, Backing);
}
}
return CopiedField;
}
public PropertyInfo GrabProperty(PropertyInfo Orig)
{
return GrabProperty(Orig, null);
}
// Copying the get_ and set_ methods is not enough to register as a property.
protected PropertyInfo GrabProperty(PropertyInfo Orig, TypeBuilder On)
{
if (Orig == null)
return null;
if (PropertiesDone.ContainsKey(Orig))
return PropertiesDone[Orig];
if (!Sources.Contains(Orig.Module))
return Orig;
if (On == null)
On = GrabType(Orig.DeclaringType) as TypeBuilder;
Type PropertyType = GrabType(Orig.PropertyType);
if (PropertiesDone.ContainsKey(Orig))
return PropertiesDone[Orig];
PropertyBuilder Builder = On.DefineProperty(Orig.Name, Orig.Attributes, PropertyType, null);
PropertiesDone.Add(Orig, Builder);
MethodInfo SetMethod = Orig.GetSetMethod(), GetMethod = Orig.GetGetMethod();
if (SetMethod != null)
Builder.SetSetMethod(GrabMethod(SetMethod) as MethodBuilder);
if (GetMethod != null)
Builder.SetGetMethod(GrabMethod(GetMethod) as MethodBuilder);
return Builder;
}
private static byte[] RawSerialize(Array Orig, Type ValType)
{
if (ValType == typeof(char))
return RawSerialize<char>(Orig, sizeof(char), BitConverter.GetBytes);
else if (ValType == typeof(uint))
return RawSerialize<uint>(Orig, sizeof(uint), BitConverter.GetBytes);
else throw new InvalidOperationException("Can not serialize array of type " + ValType);
}
// Helper method to serialize to the raw byte format used for arrays
private static byte[] RawSerialize<T>(Array Orig, int size, GetBytes<T> Bytes)
{
byte[] Ret = new byte[Orig.Length * size + size];
for (int i = 0; i < Ret.Length - size; i += size)
{
byte[] raw = Bytes((T) Orig.GetValue(i / size));
for (int j = 0; j < size; j++)
Ret[i + j] = raw[j];
}
return Ret;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSCI312_HashingExample
{
public class OurHashTable<T>
{
private KeyValuePair<int, T>[] _data;
public OurHashTable()
{
_data = new KeyValuePair<int, T>[100];
}
/// <summary>
/// Helper function to find the next index. Returns an positive index or -1 is no valid index is available
/// </summary>
/// <param name="key">The object's key</param>
/// <param name="hashCode">The object's hash value</param>
/// <returns></returns>
private int FindEmptyIndex(int key, int hashCode)
{
int end = _data.Length - 1;
int index = hashCode;
int pos = index + 1;
end = _data.Length - 1;
pos = index + 1;
while (pos <= end && _data[pos].Key != 0)
pos++;
// if we are past the end, wrap the search
if (pos > end)
{
pos = 0;
end = index - 1;
while (_data[pos].Key != 0 && pos <= end)
pos++;
}
if (pos > end)
pos = -1;
return pos;
}
private int FindIndex(int key, int hashCode)
{
int end = _data.Length - 1;
int index = hashCode;
int pos = index + 1;
end = _data.Length - 1;
pos = index + 1;
if (_data[index].Key == key)
return index;
while (pos <= end && _data[pos].Key != key)
pos++;
// if we are past the end, wrap the search
if (pos > end)
{
pos = 0;
end = index - 1;
while (_data[pos].Key != key && pos <= end)
pos++;
}
if (pos > end)
pos = -1;
return pos;
}
/// <summary>
/// Adds an elment to the hashtable using the linear probing method to handle collisions
/// </summary>
/// <param name="element"></param>
public void Add(int key, T element)
{
int index = element.GetHashCode();
// Update the value if we have a key match (zero is an invalid key in this implementation)
if (_data[index].Key == 0)
_data[index] = new KeyValuePair<int, T>(key, element);
else
{
int pos = FindEmptyIndex(key, index);
if (pos != -1)
_data[pos] = new KeyValuePair<int, T>(key, element);
else
throw new Exception("The table is full!");
}
}
/// <summary>
/// Returns the requested element from the HashTable by key. Note that the element is requried to provide the Hash value
/// </summary>
/// <param name="key"></param>
/// <param name="element"></param>
/// <returns></returns>
public T Get(int key, T element)
{
int pos = FindIndex(key, element.GetHashCode());
if (pos == -1)
return default(T);
else
return _data[pos].Value;
}
}
}
|
using FluentScheduler;
using System;
using System.Collections.Generic;
using System.Text;
using aural_server_console_weather.Job;
namespace aural_server_console_weather.Timer
{
public class RegistryInitializer : Registry
{
public RegistryInitializer()
{
Schedule<GetWeather>()
.NonReentrant()
.ToRunOnceAt(DateTime.Now.AddSeconds(3))
.AndEvery(2).Seconds();
}
}
}
|
// ReSharper disable once CheckNamespace
namespace Sentry;
public static class HttpClientExtensions
{
public static IEnumerable<HttpMessageHandler> GetMessageHandlers(this HttpClient client)
{
var invoker = typeof(HttpMessageInvoker);
var fieldInfo = invoker.GetField("handler", BindingFlags.NonPublic | BindingFlags.Instance)
?? invoker.GetField("_handler", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo.GetValue(client) is not HttpMessageHandler handler)
{
yield break;
}
do
{
yield return handler;
handler = (handler as DelegatingHandler)?.InnerHandler;
} while (handler != null);
}
public static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessage source,
CancellationToken cancellationToken)
{
var clone = new HttpRequestMessage(source.Method, source.RequestUri) { Version = source.Version };
// Headers
foreach (var (key, value) in source.Headers)
{
clone.Headers.TryAddWithoutValidation(key, value);
}
// Content
if (source.Content != null)
{
var cloneContentStream = new MemoryStream();
#if NET5_0_OR_GREATER
await source.Content.CopyToAsync(cloneContentStream, cancellationToken).ConfigureAwait(false);
#else
await source.Content.CopyToAsync(cloneContentStream).ConfigureAwait(false);
#endif
cloneContentStream.Position = 0;
clone.Content = new StreamContent(cloneContentStream);
// Content headers
foreach (var (key, value) in source.Content.Headers)
{
clone.Content.Headers.Add(key, value);
}
}
return clone;
}
#if NET5_0_OR_GREATER
public static HttpRequestMessage Clone(this HttpRequestMessage source, CancellationToken cancellationToken)
{
var clone = new HttpRequestMessage(source.Method, source.RequestUri) { Version = source.Version };
// Headers
foreach (var (key, value) in source.Headers)
{
clone.Headers.TryAddWithoutValidation(key, value);
}
// Content
if (source.Content != null)
{
var cloneContentStream = new MemoryStream();
source.Content.CopyTo(cloneContentStream, default, cancellationToken);
cloneContentStream.Position = 0;
clone.Content = new StreamContent(cloneContentStream);
// Content headers
foreach (var (key, value) in source.Content.Headers)
{
clone.Content.Headers.Add(key, value);
}
}
return clone;
}
public static HttpResponseMessage Get(this HttpClient client, string requestUri,
CancellationToken cancellationToken = default)
{
var message = new HttpRequestMessage(HttpMethod.Get, requestUri);
return client.Send(message, cancellationToken);
}
#endif
}
|
using System.Windows.Input;
using TRPO_labe_1.Model;
using TRPO_labe_1.Model.Command;
using RichTextBox = Xceed.Wpf.Toolkit.RichTextBox;
namespace TRPO_labe_1.ModelView
{
class MainWindowModelView : ModelViewBase
{
#region Fields
private string _text;
private string _findText;
private string _findAndReplaceText;
private string _findAndReplaceOnText;
#endregion
#region CommandProps
public ICommand FindTextCommand { get; }
public ICommand UndoCommand { get; }
public ICommand ReplaceCommand { get; }
public ICommand SaveFileCommand { get; }
public ICommand LoadFileCommand { get; }
#endregion
#region Commands
#region Props of text
public string Text
{
get => _text;
set => SetValue(ref _text, value, nameof(Text));
}
public string FindText
{
get => _findText;
set => SetValue(ref _findText, value, nameof(FindText));
}
public string FindAndReplaceText
{
get => _findAndReplaceText;
set => SetValue(ref _findAndReplaceText, value, nameof(FindAndReplaceText));
}
public string FindAndReplaceOnText
{
get => _findAndReplaceOnText;
set => SetValue(ref _findAndReplaceOnText, value, nameof(FindAndReplaceOnText));
}
#endregion
#region Undo Command
private void OnUndoTextBoxExecuted(object obj)
{
if (obj is RichTextBox rtb)
rtb.Undo();
}
private bool CanUndoTextBoxExecute(object obj) => obj is RichTextBox rtb && rtb.CanUndo;
#endregion
#region FindText Command
private void OnFindTextCommandExecuted(object obj)
{
if (obj is RichTextBox rtb)
RichTextBoxLocator.FillTextWithColor(rtb, FindText);
}
private bool CanFindTextCommandExecute(object obj)
{
if (string.IsNullOrWhiteSpace(FindText)) return false;
return true;
}
#endregion
#region Replace Command
private void OnFindAndReplaceExecuted(object obj)
{
if (obj is RichTextBox rtb)
{
RichTextBoxLocator.FindAndReplace(rtb, FindAndReplaceText, FindAndReplaceOnText);
}
}
private bool CanFindAndReplaceExecute(object obj) =>
!string.IsNullOrWhiteSpace(FindAndReplaceText) &&
!string.IsNullOrWhiteSpace(FindAndReplaceOnText) &&
!string.IsNullOrWhiteSpace(Text);
#endregion
#region FileCommands
private void OnSaveFileCommandExecuted(object obj)
{
FileSaveHelper.SaveInfoToFile(Text);
}
private void OnLoadFileCommandExecuted(object obj)
{
Text = FileLoadHelper.LoadInfoFromFile(FileSettings.FilePath);
}
private bool CanSaveFileCommandExecute(object obj) => Text != string.Empty;
private bool CanLoadFileCommandExecute(object obj) => true;
#endregion
#endregion
public MainWindowModelView()
{
FindTextCommand = new RelayCommand(OnFindTextCommandExecuted, CanFindTextCommandExecute);
UndoCommand = new RelayCommand(OnUndoTextBoxExecuted, CanUndoTextBoxExecute);
ReplaceCommand = new RelayCommand(OnFindAndReplaceExecuted, CanFindAndReplaceExecute);
SaveFileCommand = new RelayCommand(OnSaveFileCommandExecuted, CanSaveFileCommandExecute);
LoadFileCommand = new RelayCommand(OnLoadFileCommandExecuted, CanLoadFileCommandExecute);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
namespace ShengUI.Filters
{
public class ErrorHandlerAttribute:System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
if (filterContext.IsChildAction)
{
return;
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
Exception exception = filterContext.Exception;
var httpException = exception as HttpException;
if (httpException != null && httpException.GetHttpCode() != 500)
{
return;
}
//if (!ExceptionType.IsInstanceOfType(exception))
//{
// return;
//}
//filterContext.Controller.ViewData["ExceptionMessage"] = exception.Message;
//BaseAppContext.Logger.Info(exception);
//var section = System.Configuration.ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
//filterContext.Result = new RedirectResult(section.DefaultRedirect);
//filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
public static class CSingleton {
//MonoBehavoir Singleton
/// <summary>
/// Gets the singleton instance.
/// This function just work for type of classes that inherit form MonoBehavior.
/// </summary>
/// <returns>
/// The singleton instance.
/// </returns>
/// <param name='instances'>
/// list of instance that created.
/// </param>
/// <param name='t'>
/// Type of instances.
/// </param>
/// <param name='tag'>
/// GameObject's tag.
/// </param>
/// <param name='name'>
/// GameObject's name.
/// </param>
public static object GetSingletonInstance(ref ArrayList instances,Type t,string tag,string name){
if (instances.Count == 1)
return instances[0];
if (instances.Count > 1){
CDebug.LogError(CDebug.eMessageTemplate.SomthingIsWrong);
return null;
}
//create instance when no instance exist.
//first create GameObject and then attach script to it and return the instance.
if (instances.Count <= 0){//no instance exist
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag(tag);//looking for game objects that have match tag name.
if(gos.Length > 1){//if more than one game object exist.
for(int j = 0; j < gos.Length; j++){//find the game object that match with "name" parameter.
if (gos[j].name == name){//if name matched then add script to that object and return.
gos[j].AddComponent(t);
return instances[0];
}
}
gos[0].AddComponent(t);//when no game object's name matced then add script to one of theme.
CDebug.LogWarning(//every thing is ok. but you better know what is going on.
"Multiple GameObject with tag \""+ tag +"\" detected." +
"Anyway i add \""+ t.FullName +
"\" script to one of them that name is \""+ gos[0].name + "\"."
);
return instances[0];
}
if(gos.Length == 1){//Just one GameObject exist. so add component to it.
gos[0].AddComponent(t);
return instances[0];
}
if(gos.Length <= 0){//No GameObject exist. Create one and add component to it.
GameObject go = new GameObject(name);
go.AddComponent(t);
go.tag = tag;
return instances[0];
}
}
return null;
}
// Non "MonoBehaviour" Singleton
/// <summary>
/// Get the singleton instance.
/// This overload work just for objects that do not inherit form "MonoBehaviour".
/// </summary>
/// <returns>
/// The singleton instance.
/// </returns>
/// <param name='instances'>
/// List of instance.
/// </param>
/// <param name='t'>
/// Type of the class.
/// </param>
public static object GetSingletonInstance(ref ArrayList instances,Type t){
if (instances.Count == 1)
return instances[0];
if (instances.Count > 1){
CDebug.LogError(CDebug.eMessageTemplate.SomthingIsWrong);
return null;
}
//create instance when no instance exist.
if (instances.Count <= 0){
if (t.IsSubclassOf(typeof(MonoBehaviour))){
CDebug.LogError("This overload of \"GetSingletonInstance()\"" +
"function just worke with non \"MonoBehaviour\" objects." +
" use \"MonoBehaviour\" overload instead."
);
return null;
}
if (t.IsSubclassOf(typeof(ScriptableObject)))//If inherit from "ScriptableObject".
ScriptableObject.CreateInstance(t);//Creat instance that suitable for "ScriptableObject".
else
Activator.CreateInstance(t);//t is not a "ScriptableObject" or "MonoBehavoir".
return instances[0];
}
return null;
}
/// <summary>
/// Destroies the extra instances.
/// this functtion ensure that just one instance of class existed.
/// first add instance to instances array then call this function.
/// you must call this function on top most in the Awake() function.
/// this class work
/// </summary>
///
public static void DestroyExtraInstances(ArrayList instances ){
if( instances.Count > 1){
for(int i = 1; i < instances.Count; i++ ){
if(instances[i] is MonoBehaviour)
MonoBehaviour.Destroy((MonoBehaviour)instances[i]);
else if (instances[i] is ScriptableObject)
ScriptableObject.Destroy((ScriptableObject)instances[i]);
instances.RemoveAt(i);
}
}
}
}
|
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
namespace Inventory.BLL.DTO
{
[DataContract]
public class CustomerDTO
{
[DataMember, Required]
public DateTimeOffset CreatedOn { get; set; }
[DataMember, Required]
public DateTimeOffset? LastModifiedOn { get; set; }
[DataMember, Required]
public Guid RowGuid { get; set; }
[DataMember, Required]
[MaxLength(50)]
public string FirstName { get; set; }
[DataMember, MaxLength(50)]
public string MiddleName { get; set; }
[DataMember, MaxLength(50)]
public string LastName { get; set; }
[DataMember, MaxLength(50)]
public string EmailAddress { get; set; }
[DataMember]
public DateTimeOffset? BirthDate { get; set; }
[DataMember, DefaultValue(true)]
public bool SignOfConsent { get; set; }
[DataMember]
public int? SourceId { get; set; }
[DataMember]
public bool IsBlockList { get; set; }
[DataMember]
public string SearchTerms { get; set; }
[DataMember]
public byte[] Picture { get; set; }
[DataMember]
public byte[] Thumbnail { get; set; }
public string BuildSearchTerms() => $"{LastName} {FirstName} {EmailAddress}".ToLower();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.