text stringlengths 13 6.01M |
|---|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RepositoryPattern.Repository.Base.Interfaces
{
public interface IRepositoryBase<TEntity>
where TEntity : class
{
Task<IList<TEntity>> GetAllAsync();
Task CreateAsync(TEntity entity);
Task CreateBulkAsync(ICollection<TEntity> entities);
Task UpdateAsync(TEntity entity);
Task UpdateBulkAsync(ICollection<TEntity> entities);
Task DeleteAsync(TEntity entity);
Task DeleteBulkAsync(ICollection<TEntity> entities);
Task SaveAsync();
}
}
|
enum Brot2dEnum
{
Chicken,
Circle,
Mandelbrot,
MantaRay,
Testbrot
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace JWT_AuthendicationExample.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
var dataList = new List<string>();
for (int i = 0; i < 10; i++)
{
var rnd = new Random();
var result = rnd.Next();
dataList.Add("String : " +( result+i).ToString()+", ");
}
return dataList;
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
|
using System.Collections.Generic;
using System.Globalization;
namespace LearningSignalR.Infrastructure.Html
{
public abstract class BaseHtmlArgs
{
protected BaseHtmlArgs() : this(null)
{
}
protected BaseHtmlArgs(int? tabIndex, string cssClass = "form-control")
{
this.TabIndex = tabIndex;
this.CssClass = cssClass;
}
public int? TabIndex { get; set; }
public string CssClass { get; set; }
public string Style { get; set; }
public string ShowIf { get; set; }
protected IDictionary<string, object> GetHtmlAttributes()
{
var htmlAttributes = new Dictionary<string, object>();
if (this.TabIndex.HasValue)
htmlAttributes.Add("tabindex", this.TabIndex.Value.ToString(NumberFormatInfo.InvariantInfo));
if (string.IsNullOrEmpty(this.CssClass) == false)
htmlAttributes.Add("class", this.CssClass.Replace(",", " "));
if (string.IsNullOrEmpty(this.Style) == false)
htmlAttributes.Add("style", this.Style);
if (string.IsNullOrEmpty(this.ShowIf) == false)
htmlAttributes.Add("data-show-if", this.ShowIf);
return htmlAttributes;
}
}
} |
using RestauranteHotel.Domain.Repositories;
namespace RestauranteHotel.Domain.Contracts
{
public interface IUnitOfWork
{
void Commit();
}
}
|
using System;
using System.Linq;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Query;
using System.Web.OData.Routing;
using System.Collections.Generic;
using Microsoft.Data.OData;
using Microsoft.CortanaAnalytics.Models;
using Microsoft.CortanaAnalytics.SolutionRole.DataSource;
using Microsoft.CortanaAnalytics.SolutionAccelerators.Shared;
using Microsoft.Azure.Management.Resources.Models;
using System.Net;
namespace Microsoft.CortanaAnalytics.ResourceService.Controllers
{
public class SolutionController : ODataController
{
/// <summary>
/// Gets the resources.
/// </summary>
/// <param name="token">The token.</param>
/// <param name="subscriptionId">The subscription identifier.</param>
/// <param name="tagName">Name of the tag.</param>
/// <returns></returns>
[HttpGet]
[EnableQuery]
[ODataRoute("GetSolutions(SubscriptionId={subscriptionId},SolutionName={solutionName})")]
public IEnumerable<Solution> GetSolutions([FromODataUri] string subscriptionId, [FromODataUri] string solutionName, ODataQueryOptions<Solution> options)
{
// Since we do not support the filter attribute at this time we are blocking it
// and enabling the request validation for the ODATA query to fail.
// Example of a failed query: http://localhost:14160/GetSolutions(SubscriptionId='',SolutionName='')?$filter=SolutionName%20eq%20%27foo%27
// Example of a successful query: http://localhost:14160/GetSolutions(SubscriptionId='testContainername',SolutionName='Connectedcar01')
var settings = new ODataValidationSettings
{
AllowedFunctions = AllowedFunctions.None,
AllowedLogicalOperators = AllowedLogicalOperators.None,
AllowedArithmeticOperators = AllowedArithmeticOperators.None,
AllowedQueryOptions = AllowedQueryOptions.None
};
try
{
options.Validate(settings);
}
catch (ODataException ex)
{
throw ex;
}
var storage = new StorageDataSource(AzureClientManager.GetBlobClient());
var tmpResults = storage.GetListOfSolutions(subscriptionId, solutionName);
if(tmpResults == null)
{
return Enumerable.Empty<Solution>();
}
else
{
return tmpResults;
}
}
Guid correlationId;
}
} |
using UnityEngine;
using System.Collections;
public class DiverterReleaseBagHeight : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionStay(Collision collision) {
//if(release_fixed_box_height)
//{
collision.rigidbody.constraints = 0;
//}
}
}
|
using CommonFrameWork;
using Dapper;
using Dominio;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class DbCteDestinatario : IDisposable
{
public IEnumerable<CteDestinatario> Listar(string pNuCnpjRemetente, string pNuCnpjEmitente, string pNuCnpjDestinatario,
string pNuCnpjTomadorServico, string pNuCnpjTomExpedidor, string pNuCnpjTomRecebedor,
string pDtInicioIntervalo, string pDtFinalIntervalo, decimal? pCdMunicipio)
{
using (OracleConnection cnn = new OracleConnection(Properties.Settings.Default.ConnectionString))
{
var parameters = new OracleDynamicParameters();
parameters.Add("pNuCnpjRemetente", Formatador.SoNumero(pNuCnpjRemetente));
parameters.Add("pNuCnpjEmitente", Formatador.SoNumero(pNuCnpjEmitente));
parameters.Add("pNuCnpjDestinatario", Formatador.SoNumero(pNuCnpjDestinatario));
parameters.Add("pNuCnpjTomadorServico", Formatador.SoNumero(pNuCnpjTomadorServico));
parameters.Add("pNuCnpjTomExpedidor", Formatador.SoNumero(pNuCnpjTomExpedidor));
parameters.Add("pNuCnpjTomRecebedor", Formatador.SoNumero(pNuCnpjTomRecebedor));
parameters.Add("pDtInicioIntervalo", Convert.ToDateTime(pDtInicioIntervalo).ToString("yyyyMMdd"));
parameters.Add("pDtFinalIntervalo", Convert.ToDateTime(pDtFinalIntervalo).ToString("yyyyMMdd"));
parameters.Add("pCdMunicipio", pCdMunicipio);
parameters.Add("pErro", dbType: OracleDbType.Varchar2, direction: ParameterDirection.Output);
parameters.Add("pCursor", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output);
return cnn.Query<CteDestinatario>("ADM_OBJETOS.CTEPKG_CONHECIMENTO_TRANSPORTE.SP_CONSULTA_CTE_DEST", param: parameters, commandType: CommandType.StoredProcedure);
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
GC.Collect();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Gets event from Ball Counter and updates the corresponding UI text.
/// </summary>
public class BallsCollectedText : MonoBehaviour
{
public Text TextToUpdate;
private void OnEnable()
{
BallCounter.OnBallCounterUpdated += UpdateText;
}
private void OnDisable()
{
BallCounter.OnBallCounterUpdated += UpdateText;
}
private void UpdateText(int count)
{
TextToUpdate.text = $"Balls Collected: {count}";
}
}
|
function Dragon::RemoteTouchDown(%this, %pos)
{
if(!TMPDATA_OBJ.ExplicitMode)return;
if($EXPLICITMODE==0)
{
//Create!
ImageSlicer.createGhostFrameEXP(%pos);
$AnchorPoint = %pos;
}
if($EXPLICITMODE==1)
{
//Determine where we've clicked
%clickedobjects = $IMGASSETSCENE.pickPoint(%pos);
$FRAMEOFFSET = 0;
for(%i=0;%i<%clickedobjects.count;%i++)
{
%obj = getWord(%clickedobjects,%i);
if(%obj == $CURRENTEXTSPRITE)
{
$FRAMEOFFSET = %obj.getPositionX()-%pos.x SPC %obj.getPositionY()-%pos.y;
}
}
if($FRAMEOFFSET==0)
{
//Start another frame!
$EXPLICITMODE=0;
ImageSlicer.createGhostFrameEXP(%pos);
$AnchorPoint = %pos;
}
}
} |
using CMS_Tools.Lib;
using CMS_Tools.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
namespace CMS_Tools.Apis
{
/// <summary>
/// Summary description for Upload
/// </summary>
public class Upload : IHttpHandler
{
UserInfo accountInfo;
int sizeWeb = 1200;
int sizeTable = 768;
int sizePhone = 470;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json; charset=utf-8";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
try
{
accountInfo = Account.GetAccountInfo(context);
if (accountInfo == null)
{
var r = new
{
status = Constants.NUMBER_CODE.ACCOUNT_NOT_LOGIN,
msg = Constants.NUMBER_CODE.ACCOUNT_NOT_LOGIN.ToString()
};
context.Response.Write(JsonConvert.SerializeObject(r));
return;
}
if (context.Request.Files.Count > 0)
{
if (context.Request.Files.Count < 10)
{
var file = context.Request.Files[0];
EditImages objUpload = new EditImages();
string publisherName = accountInfo.PublisherID.ToString();
string path = context.Server.MapPath("../upload/" + publisherName + "/" + DateTime.Now.ToShortDateString().Replace('/', '-') + "/");
string pathTemp = "../upload/" + publisherName + "/" + DateTime.Now.ToShortDateString().Replace('/', '-') + "/";
string typeIMG = System.IO.Path.GetExtension(file.FileName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string _sizeWeb = context.Request.Form["sizeWeb"];
if (string.IsNullOrEmpty(_sizeWeb))
_sizeWeb = context.Request.QueryString["sizeWeb"];
string _sizeTable = context.Request.Form["sizeTable"];
if (string.IsNullOrEmpty(_sizeTable))
_sizeTable = context.Request.QueryString["sizeTable"];
string _sizePhone = context.Request.Form["sizePhone"];
if (string.IsNullOrEmpty(_sizePhone))
_sizePhone = context.Request.QueryString["sizePhone"];
if (!string.IsNullOrEmpty(_sizeWeb))
sizeWeb = Convert.ToInt32(_sizeWeb);
if (!string.IsNullOrEmpty(_sizeTable))
sizeTable = Convert.ToInt32(_sizeTable);
if (!string.IsNullOrEmpty(_sizePhone))
sizePhone = Convert.ToInt32(_sizePhone);
objUpload.iMaxWebWidth = sizeWeb;
objUpload.iMaxTabletWidth = sizeTable;
objUpload.iMaxPhoneWidth = sizePhone;
objUpload.sPath = path;
objUpload.fileUpped = file;
objUpload.sFileName = GetUniqueFileName(file.FileName, path, typeIMG);
objUpload.Process_Upload();
//var result = new { message = "success", urlImage = pathTemp + objUpload.sFileName + typeIMG, urlImageTemp = pathTemp + "temp_" + objUpload.sFileName + typeIMG, id = objUpload.sFileName, fileName = objUpload.sFileName + typeIMG, fileSize = calculatorSizeFile(file.ContentLength) };
ResultImages result = new ResultImages();
result.status = (int)Constants.NUMBER_CODE.SUCCESS;
result.msg = "success";
result.urlWeb = pathTemp + objUpload.sFileName + typeIMG;
result.urlTablet = pathTemp + "ThumbTable_" + objUpload.sFileName + typeIMG;
result.urlPhone = pathTemp + "ThumbPhone_" + objUpload.sFileName + typeIMG;
result.id = objUpload.sFileName;
result.fileName = objUpload.sFileName + typeIMG;
result.size = calculatorSizeFile(file.ContentLength);
context.Response.Write(serializer.Serialize(result));
}
else
{
var result = new { message = "error", name = "Limit upload images to not more than 5!" };
context.Response.Write(serializer.Serialize(result));
}
}
else
{
var result = new { message = "error", name = "No image upload!" };
context.Response.Write(serializer.Serialize(result));
}
}
catch (Exception ex)
{
var result = new { message = "error", name = ex.Message };
context.Response.Write(serializer.Serialize(result));
}
}
public string calculatorSizeFile(float fSize)
{
string[] fSExt = new string[] { "Bytes", "KB", "MB", "GB" };
int i = 0;
while (fSize > 900)
{
fSize /= 1024; i++;
}
return Math.Round(fSize * 100) / 100 + fSExt[i];
}
public static string GetUniqueFileName(string name, string savePath, string ext)
{
name = name.Replace(ext, "").Replace(" ", "_");
name = System.Text.RegularExpressions.Regex.Replace(name, @"[^\w\s]", "");
var newName = name;
var i = 0;
if (System.IO.File.Exists(savePath + newName + ext))
{
do
{
i++;
newName = name + "_" + i;
}
while (System.IO.File.Exists(savePath + newName + ext));
}
return newName;
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class ResultImages
{
public int status { get; set; }
public string msg { get; set; }
public string urlWeb { get; set; }
public string urlTablet { get; set; }
public string urlPhone { get; set; }
public string id { get; set; }
public string fileName { get; set; }
public string size { get; set; }
}
} |
using UnityEngine;
using OpenKnife.Utils;
using UnityEngine.Events;
namespace OpenKnife.Actors
{
public class Knife : MonoBehaviour
{
public bool isPlayer = false;
private Rigidbody2D m_rigidbody2D;
private ConstantForce2D m_Mover;
public UnityEvent onCollisionWood;
public UnityEvent onCollisionKnife;
public UnityEvent onCollisionFruit;
private void Awake()
{
m_rigidbody2D = GetComponent<Rigidbody2D>();
}
private void StopPlayerMovement()
{
isPlayer = false;
m_Mover = GetComponent<ConstantForce2D>();
m_Mover.force = Vector2.zero;
m_Mover.enabled = false;
m_rigidbody2D.velocity = Vector2.zero;
m_rigidbody2D.angularVelocity = 0f;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (!isPlayer) return;
if (other.gameObject.tag == "Fruit")
{
Destroy(other.gameObject);
onCollisionFruit?.Invoke();
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (!isPlayer) return;
if (other.gameObject.tag == "Knife")
{
StopPlayerMovement();
m_rigidbody2D.AddForce(PhysicsUtils.GetRandomForce(32f, 32f),
ForceMode2D.Impulse);
m_rigidbody2D.gravityScale = 1;
onCollisionKnife?.Invoke();
}
else if (other.gameObject.tag == "Wood")
{
m_rigidbody2D.velocity = Vector2.zero;
m_rigidbody2D.bodyType = RigidbodyType2D.Kinematic;
StopPlayerMovement();
gameObject.transform.parent = other.transform.parent;
onCollisionWood?.Invoke();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Cricket_Scoring_App
{
public class Player
{
// Initialises the windows directory for read/write access.
string winDir = System.Environment.GetEnvironmentVariable("windir");
// Initialising all batting variables
public int Bat_Number { get; set; }
public string Bat_Name { get; set; }
public string Bat_How_Out { get; set; }
public string Bat_Out_Bwlr { get; set; }
public int Bat_Fours { get; set; }
public int Bat_Sixes { get; set; }
public int Bat_Balls { get; set; }
public int Bat_Runs { get; set; }
public int Bat_Minutes { get; set; }
public bool Bat_Facing { get; set; }
// Initialising all bowling variables.
public int Bowl_Number { get; set; }
public string Bowl_Name { get; set; }
public int Bowl_Wides { get; set; }
public int Bowl_No_Balls { get; set; }
public double Bowl_Overs { get; set; }
public int Bowl_Maidens { get; set; }
public int Bowl_Runs { get; set; }
public int Bowl_Wickets { get; set; }
public double Bowl_Average { get; set; }
public double Bowl_Economy { get; set; }
public bool Bowl_Bowling { get; set; }
// Creates a new batsman object, all values are defaulted to 0 or 'not out'.
public void Create_Batsman(int BatNumber, string BatsmanName, bool Facing)
{
Bat_Number = BatNumber;
Bat_Name = BatsmanName;
Bat_How_Out = "Not";
Bat_Out_Bwlr = "Out";
Bat_Fours = 0;
Bat_Sixes = 0;
Bat_Balls = 0;
Bat_Runs = 0;
Bat_Minutes = 0;
Bat_Facing = Facing;
}
// Creates a new bowler object, all values are defaulted to 0.
public void Create_Bowler(int BowlNumber, string BowlerName, bool Bowling)
{
Bowl_Number = BowlNumber;
Bowl_Name = BowlerName;
Bowl_Wides = 0;
Bowl_No_Balls = 0;
Bowl_Overs = 0.0;
Bowl_Maidens = 0;
Bowl_Runs = 0;
Bowl_Wickets = 0;
Bowl_Average = 0.0;
Bowl_Economy = 0.0;
Bowl_Bowling = Bowling;
}
// Gets the name of the player in the form Initial.Surname e.g. Joe Bloggs = J.Bloggs
// If player does not have a surname e.g. Pele (if he ever decided to play cricket) then
// this method returns only the singlular name.
public string Get_Player_Short_Name(string player_Name)
{
int spaceIndex = player_Name.IndexOf(" ");
string playerName;
if (player_Name.IndexOf(' ') > -1)
{
string initial = player_Name.Substring(0, 1);
string surname = player_Name.Substring(spaceIndex + 1, ((player_Name.Length - 1)-spaceIndex));
playerName = initial + "." + surname;
}
else
{
playerName = player_Name;
}
return playerName;
}
// Checks if the bowler name provided is currently in the bowling list, if so it returns the bowlers Id.
public int Get_Bowler_Id(List<Player> bowlList, string bowlerName)
{
/* Initialise the bowler Id as -1 to allow new bowler to be created in the main method */
int bowlId = -1;
for (int i = 0; i < bowlList.Count; i = i + 1)
{
if (bowlList[i].Bowl_Name == bowlerName)
{
// bowler Id is set if name provided = a bowler in the list.
bowlId = i;
}
}
return bowlId;
}
// Adds a ball to the batsman facing the last deleivery.
public void Batting_Add_Ball(List<Player> batList, int batid)
{
batList[batid].Bat_Balls = batList[batid].Bat_Balls + 1;
}
// Add a ball to the bowler whom bowled the last delivery.
public void Bowling_Add_Ball(List<Player> bowlList, int bowlId)
{
bowlList[bowlId].Bowl_Overs = bowlList[bowlId].Bowl_Overs + 0.1;
}
// Check which batsman is curently facing the bowler and return their id.
public int Check_Batsman_Facing(List<Player> batList, int batTopId, int batBottomId)
{
int batsmanId;
if (batList[batTopId].Bat_Facing == true)
{
batsmanId = batTopId;
}
else
{
batsmanId = batBottomId;
}
return batsmanId;
}
// Check which bowler is curently bowling and return their id.
public int Check_Bowler_Bowling(List<Player> bowlList, int bowlTopId, int bowlBottomId)
{
int bowlerId;
if (bowlList[bowlTopId].Bowl_Bowling == true)
{
bowlerId = bowlTopId;
}
else
{
bowlerId = bowlBottomId;
}
return bowlerId;
}
// Save all batsmen whom have batted or are currently batting to a file, one file per team.
public void Save_Batsmen(List<Player> batList, string inningsOf, string folderName)
{
StreamWriter batDetailsWriter = new StreamWriter(folderName + "\\" + inningsOf + "\\BatDetails.txt");
for (int i = 0; i < batList.Count; i = i + 1)
{
batDetailsWriter.WriteLine(batList[i].Bat_Number);
batDetailsWriter.WriteLine(batList[i].Bat_Name);
batDetailsWriter.WriteLine(batList[i].Bat_How_Out);
batDetailsWriter.WriteLine(batList[i].Bat_Out_Bwlr);
batDetailsWriter.WriteLine(batList[i].Bat_Fours);
batDetailsWriter.WriteLine(batList[i].Bat_Sixes);
batDetailsWriter.WriteLine(batList[i].Bat_Balls);
batDetailsWriter.WriteLine(batList[i].Bat_Runs);
batDetailsWriter.WriteLine(batList[i].Bat_Minutes);
batDetailsWriter.WriteLine(batList[i].Bat_Facing);
}
batDetailsWriter.Close();
}
// Save all bowlers whom have bowled or are currently bowling to a file, one file per team.
public void Save_Bowlers(List<Player> bowlList, string inningsOf, string folderName)
{
StreamWriter bowlDetailWriter = new StreamWriter(folderName + "\\" + inningsOf + "\\BowlDetails.txt");
for (int j = 0; j < bowlList.Count; j = j + 1)
{
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Number);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Name);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Wides);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_No_Balls);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Overs);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Maidens);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Runs);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Wickets);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Average);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Economy);
bowlDetailWriter.WriteLine(bowlList[j].Bowl_Bowling);
}
bowlDetailWriter.Close();
}
// Load all batsman objects into the batting list, enables a match to be recoverd.
public List<Player> Load_Batsman()
{
List<Player> batsman = new List<Player>();
return batsman;
}
// Load all bowler objects into the bowling list, enables a match to be recoverd.
public List<Player> Load_Bowlers()
{
List<Player> bowler = new List<Player>();
return bowler;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace HackerRank_HomeCode
{
public class AlternatingCharacters
{
public void findNoOfDel()
{
string s = Console.ReadLine();
int deletions = 0;
int currentCount = 1;
for(int i = 1;i<s.Length;i++)
{
if(s[i] != s[i-1])
{
deletions += currentCount - 1;
currentCount = 1;
continue;
}
currentCount++;
}
deletions += currentCount - 1;
Console.WriteLine(deletions);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using Lab3.CriticalSection;
using Lab3.PiCalculator.Types;
namespace Lab3.PiCalculator
{
class MultiThreadPiCalculator : IPiCalculator
{
private const int ThreadsCount = 4;
private static double _pi = 0;
private readonly int _stepsCount;
private readonly int _timeout;
private readonly EnterToCriticalSectionType _enterToCriticalSectionType;
private readonly ICriticalSection _criticalSection;
public MultiThreadPiCalculator(
int stepsCount,
int timeout,
int spinsCount,
EnterToCriticalSectionType enterToCriticalSectionType )
{
_stepsCount = stepsCount;
_timeout = timeout;
_enterToCriticalSectionType = enterToCriticalSectionType;
_criticalSection = new AutoResetEventCriticalSection();
_criticalSection.SetSpinCount( spinsCount );
}
public double CalculatePi()
{
_pi = 0;
Action enterToCriticalSectionAction;
void leaveCriticalSectionAction() => _criticalSection.Leave();
if ( _enterToCriticalSectionType == EnterToCriticalSectionType.Enter )
{
enterToCriticalSectionAction = () => _criticalSection.Enter();
}
else
{
enterToCriticalSectionAction = () => { while ( !_criticalSection.TryEnter( _timeout ) ) { } };
}
List<Thread> workers = BeginCalculatePi( _stepsCount, enterToCriticalSectionAction, leaveCriticalSectionAction );
foreach ( Thread worker in workers )
{
worker.Join();
}
return _pi;
}
private List<Thread> BeginCalculatePi( int stepsCount, Action EnterToCriticalSection, Action LeaveCriticalSection )
{
var workers = new List<Thread>();
int stepsCountPerThread = stepsCount / ThreadsCount;
double step = 1.0 / stepsCount;
for ( int i = 0; i < ThreadsCount; i++ )
{
var newThread = new Thread( CalculatePartOfPi );
newThread.Start( new PiCalculatingSettings
{
LeftBoundary = i * stepsCountPerThread,
RightBoundary = ( i + 1 ) * stepsCountPerThread,
Step = step,
EnterToCriticalSection = EnterToCriticalSection,
LeaveCriticalSection = LeaveCriticalSection
} );
workers.Add( newThread );
}
return workers;
}
private static void CalculatePartOfPi( object piCalculatingSettingsObject )
{
var piCalculatingSettings = ( PiCalculatingSettings )piCalculatingSettingsObject;
for ( long i = piCalculatingSettings.LeftBoundary; i < piCalculatingSettings.RightBoundary; i++ )
{
double x = ( i + 0.5 ) * piCalculatingSettings.Step;
double functionBase = 4.0 / ( 1.0 + x * x );
piCalculatingSettings.EnterToCriticalSection();
_pi += functionBase * piCalculatingSettings.Step;
piCalculatingSettings.LeaveCriticalSection();
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerUI : MonoBehaviour {
public Text ammoText;
public Slider healthBar;
public Text healthText;
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace GenerateMockData
{
class Program
{
static void Main(string[] args)
{
GetReflectionData re = new GetReflectionData();
}
}
public class GetReflectionData
{
public static int count = 10;
private Dictionary<string, int> classCountList;
public GetReflectionData()
{
classCountList = new Dictionary<string, int>();
classCountList.Add("Agency", 2);
classCountList.Add("BusRoute", 20);
classCountList.Add("BusStop", 10);
classCountList.Add("BusStopForRoute", 100);
classCountList.Add("GeoLocationPoint", 3000);
Assembly asm = this.GetType().Assembly;
foreach (Type type in asm.GetTypes())
{
if (classCountList.ContainsKey(type.Name))
{
var genericListType = typeof(List<>).MakeGenericType(new[] { type });
var addMethod = genericListType.GetMethod("Add");
var list = Activator.CreateInstance(genericListType);
for (int i = 0; i < classCountList[type.Name]; i++)
{
addMethod.Invoke(list, new[] { CreateAnInstanceOfAType(type, i) });
}
XmlSerializer serializer = new XmlSerializer(list.GetType());
StringWriter writer = new StringWriter();
serializer.Serialize(writer, list, null);
string s = writer.ToString();
using(StreamWriter outfile = new StreamWriter(type.Name + ".xml",false))
{
outfile.Write(s);
}
}
}
}
private static object CreateAnInstanceOfAType(Type type, int index)
{
object item = Activator.CreateInstance(type);
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
if (propertyInfo.CanWrite)
{
if (propertyInfo.PropertyType == typeof(System.Boolean))
{
type.GetProperty(propertyInfo.Name).SetValue(item, (index % 2 == 0) ? true : false, null);
}
else if (propertyInfo.PropertyType == typeof(int))
{
type.GetProperty(propertyInfo.Name).SetValue(item, index, null);
}
else if (propertyInfo.PropertyType == typeof(double))
{
type.GetProperty(propertyInfo.Name).SetValue(item, index, null);
}
else if (propertyInfo.PropertyType == typeof(float))
{
type.GetProperty(propertyInfo.Name).SetValue(item, index, null);
}
else if (propertyInfo.PropertyType == typeof(string))
{
type.GetProperty(propertyInfo.Name).SetValue(item, propertyInfo.Name + index.ToString(), null);
}
//else if (propertyInfo.PropertyType == typeof(Uri))
//{
// type.GetProperty(propertyInfo.Name).SetValue(item, new Uri("http://wwww.iwportal" + index.ToString() + ".com"), null);
//}
}
}
return item;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ItemPanel : Inventory
{
#region
private static ItemPanel _instance;
public static ItemPanel Instance {
get {
if(_instance == null)
{
_instance = GameObject.Find("ItemPanel").GetComponent<ItemPanel>();
}
return _instance;
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public abstract class GameTask {
public int consumption = 0;
public int cost = 0;
public string description;
public bool enabled = true;
public string currentValue = "0";
public string name;
public bool requireParameter = false;
public string example;
public virtual string Disable() {
if (!enabled)
return "Task " + name + " already killed.";
enabled = false;
consumption = 0;
return "Task " + name + " killed.";
}
public virtual string Enable() {
if (enabled)
return "Task " + name + " already started.";
var mgr = GameManager.Instance;
if (mgr.PowerAvailable >= cost) {
enabled = true;
consumption = cost;
return "Task " + name + " enabled.";
}
else
return "Not enough power to enabled task " + name + ".";
}
public virtual string SetValue(string value) {
int intValue;
if (!int.TryParse(value, out intValue))
return "Integer value expected";
var currentIntValue = int.Parse(currentValue);
var mgr = GameManager.Instance;
var currentTotal = mgr.PowerAvailable;
var newConsumption = Mathf.CeilToInt((float)intValue * (float)cost / 100f);
if (currentTotal - consumption + newConsumption > 0) {
currentValue = value;
consumption = newConsumption;
return "Task " + name + " value updated.";
}
else
return "Not enough power to update task " + name + " value.";
}
public virtual int GetConsumption() {
return consumption;
}
}
|
using System.Collections.ObjectModel;
namespace TQVaultAE.Domain.Entities;
public record ItemAffixes(
ReadOnlyDictionary<GameDlc, ReadOnlyCollection<LootTableCollection>> Broken
, ReadOnlyDictionary<GameDlc, ReadOnlyCollection<LootTableCollection>> Prefix
, ReadOnlyDictionary<GameDlc, ReadOnlyCollection<LootTableCollection>> Suffix
);
|
using System.Text.Json.Serialization;
namespace ZenHub.Models
{
public class RepoDependencies
{
[JsonPropertyName("dependencies")]
public IssueDependency[] Dependencies { get; set; }
}
}
|
using System.Windows;
namespace TariffCreator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private NewTariff.NewTariff newTariff;
private ReadInf.ReadInf readInf;
public MainWindow()
{
InitializeComponent();
}
private void btnTariff_Click(object sender, RoutedEventArgs e)
{
if (newTariff == null || !newTariff.IsVisible)
{
newTariff = new NewTariff.NewTariff();
newTariff.Show();
}
else
newTariff.Activate();
}
private void btnOverview_Click(object sender, RoutedEventArgs e)
{
if (readInf == null || !readInf.IsVisible)
{
readInf = new ReadInf.ReadInf();
readInf.Show();
}
else
readInf.Activate();
}
}
}
|
using System.Collections.Generic;
using FluentAssertions;
using NUnit.Framework;
namespace FileSearch.Test
{
[TestFixture]
public class FilterStackTests
{
private readonly Mocks _mocks;
public FilterStackTests()
{
_mocks = new Mocks(); ;
}
[Test]
public void Most_restrictive_extension_filter_wins()
{
var args = new SearchArgs();
args.Extensions = new List<string> { ".avi", ".mp3" };
args.ExtensionsExclude = new List<string> { ".mp3" };
var file = _mocks.GetMockedExtension(".mp3");
var stack = new FilterStack(args);
stack.ShouldFilter(file).Should().BeTrue();
}
[Test]
public void Most_restrictive_directory_filter_wins()
{
var args = new SearchArgs();
args.DirectoryWildCards = new List<string> { "c:\\chiefs\\players", "c:\\crusaders" };
args.DirectoryExcludeWildCards = new List<string> { "c:\\blues", "chiefs", "c:\\hurricanes" };
var file = _mocks.GetMockedFileDirectory("c:\\chiefs\\games");
var stack = new FilterStack(args);
stack.ShouldFilter(file).Should().BeTrue();
}
}
}
// ReSharper restore InconsistentNaming |
namespace VAT.Business.Model
{
public class Van : Vehicle
{
}
}
|
using TechTalk.SpecFlow;
using Stylelabs.MQA.Core.Utilities;
namespace Stylelabs.MQA.TestCases.Steps
{
[Binding]
public sealed class Hooks
{
[BeforeScenario]
public static void BeforeScenario()
{
Installer.SetUpEnv();
}
[AfterScenario]
public static void AfterScenario()
{
Installer.CleanUpEnv();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SupperStore02
{
public partial class Form1 : Form
{
SupperStoreEntities test;
public Form1()
{
InitializeComponent();
panel.Hide();
btnCancel.Hide();
btnSave.Hide();
panel1.Hide();
}
//When save is clicked
private void Button1_Click(object sender, EventArgs e)
{
try
{
panel.Show();
btnCancel.Show();
panel1.Show();
btnSave.Show();
txtAmount.Show();
lblamount.Show();
panel2.Show();
addnewitem.Show();
txtShemdeg.Hide();
lblShemdeg.Hide();
updateNorP.Hide();
updatenameorprice.Hide();
txtShemdeg.Hide();
lblShemdeg.Hide();
panel2.Hide();
Room1 product = new Room1();
test.Room1.Add(product);
room1BindingSource.Add(product);
room1BindingSource.MoveLast();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//Name or Price Update
private void UpdateNorP_Click(object sender, EventArgs e)
{
panel.Show();
updatenameorprice.Show();
btnCancel.Show();
btnSave.Show();
panel1.Show();
lblamount.Show();
txtAmount.Show();
button1.Hide();
lblShemdeg.Hide();
txtShemdeg.Hide();
panel2.Hide();
addnewitem.Hide();
}
private void Form1_Load(object sender, EventArgs e)
{
test = new SupperStoreEntities();
room1BindingSource.DataSource = test.Room1.ToList();
}
//washlistvis viyeneb gilak 'Deletes'
private void DataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Delete)
{
if(MessageBox.Show("darwmunebuli xar rom gsurs washla ?", "Message",MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
test.Room1.Remove(room1BindingSource.Current as Room1);
room1BindingSource.RemoveCurrent();
}
}
//RATA moxdes cvlilebis shenaxva washlis shemdeg dauyovnebliv bazashi
try
{
room1BindingSource.EndEdit();
test.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
room1BindingSource.ResetBindings(false);
}
}
//Excel - shi gadatana
private void copyAlltoClipboard()
{
//rom wavshalo pirveli blank column from datagridview
dataGridView1.RowHeadersVisible = false;
dataGridView1.SelectAll();
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
private void ExelExp_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value2 = dataGridView1.Columns[j].HeaderText;
}
StartRow++;
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = dataGridView1[j, i].Value == null ? "" : dataGridView1[j, i].Value;
}
catch
{
;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//Cancel gilakis dawerisas mowmdeba tu risi shesrulebaa sawiro
private void BtnCancel_Click(object sender, EventArgs e)
{
if(btnShetana.Visible == true && btnGamotana.Visible == false)
{
lblamount.Enabled = true;
txtAmount.Enabled = true;
button1.Show();
updateNorP.Show();
btnGamotana.Show();
panel1.Hide();
btnCancel.Hide();
btnSave.Hide();
txtShemdeg.Text = "0";
}
else if (btnGamotana.Visible == true && btnGamotana.Visible == true)
{
lblamount.Enabled = true;
txtAmount.Enabled = true;
txtShemdeg.Text = "0";
button1.Show();
updateNorP.Show();
btnShetana.Show();
panel1.Hide();
btnCancel.Hide();
btnSave.Hide();
}
else if (updateNorP.Visible == true && button1.Visible == false)
{
room1BindingSource.ResetBindings(false);
foreach (DbEntityEntry entry in test.ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Modified:
entry.State = EntityState.Unchanged;
break;
case EntityState.Deleted:
entry.Reload();
break;
}
}
button1.Show();
panel1.Hide();
panel2.Show();
btnCancel.Hide();
panel.Hide();
btnSave.Hide();
}
else
{
/*
room1BindingSource.MoveLast();
int rowIndex = dataGridView1.CurrentCell.RowIndex;
dataGridView1.Rows.RemoveAt(rowIndex);
*/
test.Room1.Remove(room1BindingSource.Current as Room1);
room1BindingSource.RemoveCurrent();
try
{
room1BindingSource.EndEdit();
test.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
room1BindingSource.ResetBindings(false);
}
updateNorP.Show();
panel2.Show();
panel.Hide();
btnCancel.Hide();
btnSave.Hide();
txtAmount.Hide();
lblamount.Hide();
txtShemdeg.Hide();
}
}
//save ze daklikebisas
private void BtnSave_Click(object sender, EventArgs e)
{
if (panel1.Visible == true && btnShetana.Visible == true)
{
int Amount = Int32.Parse(txtAmount.Text);
int Shemdeg = Int32.Parse(txtShemdeg.Text);
int Sum = Amount + Shemdeg;
txtAmount.Text = Sum.ToString();
lblamount.Enabled = true;
txtAmount.Enabled = true;
btnGamotana.Show();
panel1.Hide();
btnSave.Hide();
txtShemdeg.Text = "0";
}
if (panel1.Visible == true && btnGamotana.Visible == true)
{
int Amount = Int32.Parse(txtAmount.Text);
int Shemdeg = Int32.Parse(txtShemdeg.Text);
if(Amount < Shemdeg)
{
Shemdeg = 0;
MessageBox.Show("Tqven gagaqvt imaze meti, vidre amjamat sawyobshia");
}
else
{
int Sum = Amount - Shemdeg;
txtAmount.Text = Sum.ToString();
}
lblamount.Enabled = true;
txtAmount.Enabled = true;
btnGamotana.Show();
panel1.Hide();
btnSave.Hide();
btnShetana.Show();
//isev vanuleb meore vels
txtShemdeg.Text = "0";
}
if (button1.Visible == true)
{
btnSave.Hide();
panel2.Show();
btnGamotana.Show();
btnShetana.Show();
panel1.Hide();
}
if (updateNorP.Visible == true)
{
panel2.Show();
panel1.Hide();
}
try
{
room1BindingSource.EndEdit();
test.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
room1BindingSource.ResetBindings(false);
}
panel.Hide();
updateNorP.Show();
button1.Show();
btnCancel.Hide();
}
private void BtnShetana_Click(object sender, EventArgs e)
{
lblamount.Enabled = false;
txtAmount.Enabled = false;
txtShemdeg.Text = "0";
btnSave.Show();
panel.Show();
panel1.Show();
txtAmount.Show();
lblamount.Show();
lblShemdeg.Show();
txtShemdeg.Show();
btnCancel.Show();
btnGamotana.Hide();
panel.Hide();
button1.Hide();
updateNorP.Hide();
}
private void BtnGamotana_Click(object sender, EventArgs e)
{
lblamount.Enabled = false;
txtAmount.Enabled = false;
txtShemdeg.Text = "0";
btnSave.Show();
panel.Show();
panel1.Show();
txtAmount.Show();
lblamount.Show();
txtShemdeg.Show();
lblShemdeg.Show();
btnGamotana.Show();
btnCancel.Show();
panel.Hide();
button1.Hide();
updateNorP.Hide();
btnShetana.Hide();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace ReDefNet
{
/// <summary>
/// Base class for an object that implements <see cref="INotifyPropertyChanged" />.
/// </summary>
[DebuggerStepThrough]
[Serializable]
public abstract class ObservableObject : INotifyPropertyChanged, INotifyPropertyChanging
{
/// <summary>
/// Occurs when a property has changed.
/// </summary>
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Occurs when a property value is changing.
/// </summary>
[field: NonSerialized]
public event PropertyChangingEventHandler PropertyChanging;
/// <summary>
/// Raises the <see cref="PropertyChanged" /> event for the specified property.
/// <para>
/// If <paramref name="propertyName" /> does not refer to a valid property on the current object, an exception is
/// thrown in DEBUG configuration only.
/// </para>
/// </summary>
/// <param name="propertyName">The name of the property that changed.</param>
public virtual void RaisePropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
var handler = this.PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Raises the <see cref="PropertyChanging" /> event for the specified property.
/// <para>
/// If <paramref name="propertyName" /> does not refer to a valid property on the current object, an exception is
/// thrown in DEBUG configuration only.
/// </para>
/// </summary>
/// <param name="propertyName">The name of the property that changed.</param>
public virtual void RaisePropertyChanging(string propertyName)
{
this.VerifyPropertyName(propertyName);
var handler = this.PropertyChanging;
handler?.Invoke(this, new PropertyChangingEventArgs(propertyName));
}
/// <summary>
/// Raises the <see cref="PropertyChanging" /> event for the specified property.
/// </summary>
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
public virtual void RaisePropertyChanging<TProperty>(Expression<Func<TProperty>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression));
}
var handler = this.PropertyChanging;
if (handler == null)
{
return;
}
var propertyName = GetPropertyName(propertyExpression);
handler.Invoke(this, new PropertyChangingEventArgs(propertyName));
}
/// <summary>
/// Verifies that the specified property name exists on the current object. This method can be called before the
/// property is used, for instance before calling <see cref="RaisePropertyChanged" />.
/// <para>This method is only active in DEBUG configuration.</para>
/// </summary>
/// <param name="propertyName">The property name to verify.</param>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
return;
}
var myType = this.GetType();
if (myType.GetProperty(propertyName) == null)
{
return;
}
var descriptor = this as ICustomTypeDescriptor;
if (descriptor != null)
{
if (descriptor.GetProperties()
.Cast<PropertyDescriptor>()
.Any(property => property.Name == propertyName))
{
return;
}
}
throw new ArgumentException("Property not found.", propertyName);
}
/// <summary>
/// Raises the <see cref="PropertyChanged" /> event for the property referred to by the specified property expression.
/// </summary>
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
public virtual void RaisePropertyChanged<TProperty>(Expression<Func<TProperty>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression));
}
var handler = this.PropertyChanged;
if (handler == null)
{
return;
}
var propertyName = GetPropertyName(propertyExpression);
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentException("Argument does not refer to a valid property.", nameof(propertyExpression));
}
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Gets the name of the property referred to by the specified property expression.
/// </summary>
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
/// <returns>
/// The property name.
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="propertyExpression" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">
/// If <paramref name="propertyExpression" /> does not refer to a valid property.
/// </exception>
protected static string GetPropertyName<TProperty>(Expression<Func<TProperty>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression));
}
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("Argument does not refer to a valid property.", nameof(propertyExpression));
}
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("Argument does not refer to a valid property.", nameof(propertyExpression));
}
return property.Name;
}
/// <summary>
/// Sets the backing field for the specified property expression if the new value is different than the current value.
/// </summary>
/// <typeparam name="TProperty">The property and field type.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
/// <param name="field">The field.</param>
/// <param name="newValue">The new value.</param>
/// <returns>
/// <c>true</c>, if the backing field was set; otherwise, <c>false</c>.
/// </returns>
protected bool Set<TProperty>(Expression<Func<TProperty>> propertyExpression, ref TProperty field, TProperty newValue)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression));
}
if (EqualityComparer<TProperty>.Default.Equals(field, newValue))
{
return false;
}
this.RaisePropertyChanging(propertyExpression);
field = newValue;
this.RaisePropertyChanged(propertyExpression);
return true;
}
/// <summary>
/// Sets the backing field for the specified property and raises the <see cref="PropertyChanging" /> and
/// <see cref="PropertyChanged" /> events if the new value is different than the current value.
/// </summary>
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="propertyName">The property name.</param>
/// <param name="field">The backing field.</param>
/// <param name="newValue">The new value.</param>
/// <returns>
/// <c>true</c>, if the backing field was set and the events were raised; otherwise, <c>false</c>.
/// </returns>
protected bool Set<TProperty>(string propertyName, ref TProperty field, TProperty newValue)
{
if (EqualityComparer<TProperty>.Default.Equals(field, newValue))
{
return false;
}
this.RaisePropertyChanging(propertyName);
field = newValue;
this.RaisePropertyChanged(propertyName);
return true;
}
/// <summary>
/// Calls the specified value setter related to the specified property expression if the new value is different
/// than the current value. This method overload allows you to set other properties in addition to just fields.
/// </summary>
/// <typeparam name="TProperty">The property type.</typeparam>
/// <param name="propertyExpression">The property expression.</param>
/// <param name="getter">The delegate used to get the current value.</param>
/// <param name="setter">The delegate used to set a new value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>
/// <c>true</c>, if the specified value setter was called; otherwise, <c>false</c>.
/// </returns>
protected bool Set<TProperty>(
Expression<Func<TProperty>> propertyExpression,
Func<TProperty> getter,
Action<TProperty> setter,
TProperty newValue)
{
if (propertyExpression == null)
{
throw new ArgumentNullException(nameof(propertyExpression));
}
if (getter == null)
{
throw new ArgumentNullException(nameof(getter));
}
if (setter == null)
{
throw new ArgumentNullException(nameof(setter));
}
var current = getter.Invoke();
if (EqualityComparer<TProperty>.Default.Equals(current, newValue))
{
return false;
}
this.RaisePropertyChanging(propertyExpression);
setter.Invoke(newValue);
this.RaisePropertyChanged(propertyExpression);
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections;
namespace logic
{
public class Links : IEnumerable
{
public List<Link> links;
public Links()
{
links = new List<Link>();
}
public Links(List<Link> links)
{
this.links = links;
}
public IEnumerator GetEnumerator()
{
return links.GetEnumerator();
}
public Link Find(String id)
{
foreach (Link link in this)
{
if (link.id == id)
{
return link;
}
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
[CustomLuaClass, RequireComponent(typeof(UIWidget))]
public class OutsideClick : MonoBehaviour
{
private const int GENERAL_WIDTH = 1280;
private const int GENERAL_HEIGHT = 720;
private Vector4 m_rectOnScreen;
private List<Action> m_callbacks = new List<Action>();
private float GeneralRatio
{
get
{
return 1.77777779f;
}
}
private float ScreenRatio
{
get
{
return (float)Screen.get_width() / (float)Screen.get_height();
}
}
private void Start()
{
float num = (float)Screen.get_width();
float num2 = num / 1280f;
Vector2 vector = new Vector2(base.get_transform().get_localPosition().x, base.get_transform().get_localPosition().y);
Vector2 vector2 = vector * num2;
Vector2 vector3 = new Vector2(vector2.x + (float)(Screen.get_width() / 2), vector2.y + (float)(Screen.get_height() / 2));
UIWidget component = base.GetComponent<UIWidget>();
Vector2 localSize = component.localSize;
Vector2 vector4 = localSize * num2;
this.m_rectOnScreen = new Vector4(vector3.x, vector3.y, vector4.x, vector4.y);
}
private void Update()
{
if (Input.GetKeyDown(323))
{
Vector3 mousePosition = Input.get_mousePosition();
Vector2 point = new Vector2(mousePosition.x, mousePosition.y);
if (!this.PointIsInsideOfRect(point))
{
for (int i = 0; i < this.m_callbacks.get_Count(); i++)
{
Action action = this.m_callbacks.get_Item(i);
if (action != null)
{
action.Invoke();
}
}
}
}
}
private bool PointIsInsideOfRect(Vector2 point)
{
float num = Mathf.Abs(point.x - this.m_rectOnScreen.x);
float num2 = Mathf.Abs(point.y - this.m_rectOnScreen.y);
float num3 = this.m_rectOnScreen.z / 2f;
float num4 = this.m_rectOnScreen.w / 2f;
return num <= num3 && num2 <= num4;
}
public void RegisterCallback(Action action)
{
if (!this.m_callbacks.Contains(action))
{
this.m_callbacks.Add(action);
}
}
}
|
using System;
namespace Ecommerce.Api.Models
{
public class CreateOrderModel
{
public Guid ProductId { get; set; }
public int Quantity { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Comprobantes
{
class NotaCredito
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ruminate.GUI.Content;
using Microsoft.Xna.Framework;
using System.Reflection;
using Ruminate.GUI.Framework;
using System.Globalization;
namespace Sandstorm.GUI
{
class ColorSlider
{
private String Text { get; set; }
private Color Value { get; set; }
private Label Label { get; set; }
private Slider SliderR { get; set; }
private Slider SliderG { get; set; }
private Slider SliderB { get; set; }
private Slider SliderA { get; set; }
private Color Min { get; set; }
private Color Max { get; set; }
private object PropertyOwner { get; set; }
private PropertyInfo Property { get; set; }
/// <summary>
/// Creates an instance of ColorSlider.
/// </summary>
/// <param name="parent">The parent where the Slider is append to</param>
/// <param name="propertyOwner">The owner of the connected property</param>
/// <param name="propertyOwner">The name of the connected property</param>
/// <param name="posX">The X position of the OptionSlider</param>
/// <param name="posY">The Y position of the OptionSlider</param>
/// <param name="width">The width of the OptionSlider</param>
/// <param name="min">The minimal value of the OptionSlider</param>
/// <param name="max">The maximal value of the OptionSlider</param>
public ColorSlider(Widget parent, object propertyOwner, string propertyName, int posX, int posY, int width, Color min, Color max)
{
//Set property owner
PropertyOwner = propertyOwner;
//Get property with given name from owner
Property = PropertyOwner.GetType().GetProperty(propertyName);
//Set label text
Text = Property.Name;
//Get initial value from property
Value = (Color)Property.GetValue(PropertyOwner, null);
//Set the minimal slider value
Min = min;
//Set the maximal slider value
Max = max;
//Create new label
Label = new Label(posX, posY, Text + "\n[" + ((float)Value.R / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.G / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.B / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.A / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + "]");
//Add label to parent
parent.AddWidget(Label);
//Create new slider
SliderR = new Slider(posX, posY + 35, width);
SliderG = new Slider(posX, posY + 50, width);
SliderB = new Slider(posX, posY + 65, width);
SliderA = new Slider(posX, posY + 80, width);
//Add ValueChanged event handler
SliderR.ValueChanged += OnValueChangedR;
SliderG.ValueChanged += OnValueChangedG;
SliderB.ValueChanged += OnValueChangedB;
SliderA.ValueChanged += OnValueChangedA;
//Add slider to parent
parent.AddWidgets(new Widget[]{SliderR, SliderG, SliderB, SliderA});
//Set slider initial value (must set after AddWidget!)
SliderR.Value = (float)Value.R / (float)Max.R;
SliderG.Value = (float)Value.G / (float)Max.G;
SliderB.Value = (float)Value.B / (float)Max.B;
SliderA.Value = (float)Value.A / (float)Max.A;
}
/// <summary>
/// Handles r-component slider ValueChanged event.
/// </summary>
/// <param name="widget"></param>
public void OnValueChangedR(Widget widget)
{
//Update value
Value = new Color((byte)(((Slider)widget).Value * (float)Max.R), Value.G, Value.B, Value.A);
//Update label
Label.Value = Text + "\n[" + ((float)Value.R / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.G / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.B / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.A / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + "]";
//Update connected property
Property.SetValue(PropertyOwner, Value, null);
}
/// <summary>
/// Handles g-component slider ValueChanged event.
/// </summary>
/// <param name="widget"></param>
public void OnValueChangedG(Widget widget)
{
//Update value
Value = new Color(Value.R, (byte)(((Slider)widget).Value * Max.G), Value.B, Value.A);
//Update label
Label.Value = Text + "\n[" + ((float)Value.R / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.G / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.B / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.A / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + "]";
//Update connected property
Property.SetValue(PropertyOwner, Value, null);
}
/// <summary>
/// Handles b-component slider ValueChanged event.
/// </summary>
/// <param name="widget"></param>
public void OnValueChangedB(Widget widget)
{
//Update value
Value = new Color(Value.R, Value.G, (byte)(((Slider)widget).Value * Max.B), Value.A);
//Update label
Label.Value = Text + "\n[" + ((float)Value.R / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.G / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.B / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.A / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + "]";
//Update connected property
Property.SetValue(PropertyOwner, Value, null);
}
/// <summary>
/// Handles a-component slider ValueChanged event.
/// </summary>
/// <param name="widget"></param>
public void OnValueChangedA(Widget widget)
{
//Update value
Value = new Color(Value.R, Value.G, Value.B, (byte)(((Slider)widget).Value * Max.A));
//Update label
Label.Value = Text + "\n[" + ((float)Value.R / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.G / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.B / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + ", " +
((float)Value.A / 255.0f).ToString("n1", CultureInfo.InvariantCulture) + "]";
//Update connected property
Property.SetValue(PropertyOwner, Value, null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Xamarin.Essentials;
namespace QRCodeLeitor.Carousel
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Pagina2 : ContentPage
{
public Pagina2()
{
InitializeComponent();
Random random = new Random();
codigoGerado = random.Next(111111, 999999);
var deviceName = DeviceInfo.Name;
NumeroButton.Clicked += async (sender, e) => {
string numeroDigitado = NumeroDigitado.Text.Trim();
if (isValidNumero(numeroDigitado))
{
await DisplayAlert(deviceName, codigoGerado.ToString(), "OK");
App.Current.MainPage = new NavigationPage(new Pagina3());
}
};
}
public static int codigoGerado;
private bool isValidNumero(string numero)
{
bool valid = true;
int numeroDigitadoVerificado = 0;
if (numero.Length != 11)
{
DisplayAlert("ERRO", "手机验证码无效!电话必须包含 DDD 和 9 位数字。", "OK");
valid = false;
}
//if (!int.TryParse(numero, out numeroDigitadoVerificado))
//{
// DisplayAlert("ERRO", "Telefone Inválido! O telefone deve conter apenas números.", "OK");
// valid = false;
//}
return valid;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Proje
{
public partial class AdminOnay : Form
{
public AdminOnay()
{
InitializeComponent();
}
OleDbConnection baglanti;
OleDbDataAdapter adapter;
DataSet ds;
private void AdminOnay_Load(object sender, EventArgs e)
{
UrunlerDoldur();//Admin onayına gönderilmiş ürün varsa getir.
KullaniciDoldur();//Admin onayına gönderilmiş para ekleme isteği varsa getir.
}
private void UrunlerDoldur()
{
//Admin onayına gönderilmiş ürün varsa getir.
baglanti = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:/Users/marsl/OneDrive/Masaüstü/Dönem Projesi/YazılımProje.accdb");
adapter = new OleDbDataAdapter("Select * from OnayBekleyenUrunler", baglanti);
ds = new DataSet();
baglanti.Open();
adapter.Fill(ds, "OnayBekleyenUrunler");
dataGridView1.DataSource = ds.Tables["OnayBekleyenUrunler"];
baglanti.Close();
}
private void KullaniciDoldur()
{
//Admin onayına gönderilmiş para ekleme isteği varsa getir.
baglanti = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:/Users/marsl/OneDrive/Masaüstü/Dönem Projesi/YazılımProje.accdb");
adapter = new OleDbDataAdapter("Select * from OnayBekleyenParalar", baglanti);
ds = new DataSet();
baglanti.Open();
adapter.Fill(ds, "OnayBekleyenParalar");
dataGridView2.DataSource = ds.Tables["OnayBekleyenParalar"];
baglanti.Close();
}
private void btn_urunonayla_Click(object sender, EventArgs e)
{
//Adminin ürünü onaylayabilmesi için gerekli işlemler
try
{
UrunOnay uo = new UrunOnay();
uo.UrunNo =Convert.ToInt32(txt_urunno.Text);
uo.Onayver();
UrunlerDoldur();
txt_urunno.Text = "";
}
catch (Exception)
{
MessageBox.Show("Bir Hata Meydana Geldi Lütfen Tekrar Deneyiniz.");
}
}
private void btn_urunsil_Click(object sender, EventArgs e)
{
//Adminin ürünü silebilmesi için gerekli işlemler.
try
{
UrunOnay uo = new UrunOnay();
uo.UrunNo = Convert.ToInt32(txt_urunno.Text);
uo.Sil();
UrunlerDoldur();
txt_urunno.Text = "";
}
catch (Exception)
{
MessageBox.Show("Bir Hata Meydana Geldi Lütfen Tekrar Deneyiniz.");
}
}
private void btn_paraonayla_Click(object sender, EventArgs e)
{
//Adminin kullanıcıdan gelen yükleme isteğini onaylaması için gerekli işlemler
try
{
ParaOnay po = new ParaOnay();
po.KullaniciNo = txt_kullanicino.Text;
po.Onayver();
KullaniciDoldur();
txt_kullanicino.Text = "";
}
catch (Exception)
{
MessageBox.Show("Bir Hata Meydana Geldi Lütfen Tekrar Deneyiniz.");
}
}
private void btn_parasil_Click(object sender, EventArgs e)
{
//Adminin kullanıcıdan gelen yükleme isteiğini silmesi için gerekli işlemler.
try
{
ParaOnay po = new ParaOnay();
po.KullaniciNo = txt_kullanicino.Text;
po.Sil();
KullaniciDoldur();
txt_kullanicino.Text = "";
}
catch (Exception)
{
MessageBox.Show("Bir Hata Meydana Geldi Lütfen Tekrar Deneyiniz.");
}
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseConcurrentEntityMap.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using FluentNHibernate.Mapping;
namespace CGI.Reflex.Core.Mappings
{
public class BaseConcurrentEntityMap<T> : BaseEntityMap<T>
where T : BaseConcurrentEntity
{
protected BaseConcurrentEntityMap(bool enableCache = true)
: base(enableCache)
{
Version(x => x.ConcurrencyVersion).Access.CamelCaseField(Prefix.Underscore);
}
}
}
|
using System;
namespace MarsRoverProject.Exceptions
{
public class RoverCouldNotLandToOutOfSelectedBorderException : Exception
{
public RoverCouldNotLandToOutOfSelectedBorderException(string message) : base(message)
{
}
}
}
|
#if UNITY_ANDROID || UNITY_IPHONE || UNITY_STANDALONE_OSX || UNITY_TVOS
// WARNING: Do not modify! Generated file.
namespace UnityEngine.Purchasing.Security {
public class AppleTangle
{
private static byte[] data = System.Convert.FromBase64String("KytyPSwsMDlyPzMxcz0sLDA5Pz33/y3OGw8JnfNzHe+kp78skbr/EDA5fBUyP3Jtemx4Wl8JWFdPQR0s3l1cWlV22hTaqz84WV1s3a5sdlqVRS6pAVKJIwPHrnlf5gnTEQFRrSMd9MSljZY6wHg3TYz/57hHdp9DBftZVSBLHApNQiiP69d/Zxv/iTNsTVpfCVhWT1YdLCwwOXwVMj9ybT4wOXwvKD0yOD0uOHwoOS4xL3w9VHdaXVlZW15dSkI0KCgsL2ZzcysVhCrDb0g5/SvIlXFeX11cXf/eXS49Pyg1Pzl8Lyg9KDkxOTIoL3JsycImUPgb1weISmtvl5hTEZJINY1TwWGvdxV0RpSikunlUoUCQIqXYThpf0kXSQVB78irqsDCkwzmnQQMeL63jessg1MZvXuWrTEksbvpS0thejt81m82q1Hek4K3/3OlDzYHOEPNh0IbDLdZsQIl2HG3av4LEAmwfB8dbN5dfmxRWlV22hTaq1FdXV1abFNaXwlBT11do1hZbF9dXaNsQeKoL8eyjjhTlyUTaIT+YqUkozeUWVxf3l1TXGzeXVZe3l1dXLjN9VUoNTo1Pz0oOXw+JXw9MiV8LD0uKHIc+qsbESNUAmxDWl8JQX9YRGxK9IAifmmWeYmFU4o3iP54f02r/fAOOTA1PTI/OXwzMnwoNDUvfD85Lnw9Mjh8PzkuKDU6NT89KDUzMnwsKDQzLjUoJW1KbEhaXwlYX09RHSycP28rq2ZbcAq3hlN9UobmL0UT6UPZ39lHxWEba671xxzScIjtzE6EasUQcSTrsdDHgK8rx64qjitsE50mbN5dKmxSWl8JQVNdXaNYWF9eXWzeWOds3l///F9eXV5eXV5sUVpVWFpPXgkPbU9sTVpfCVhWT1YdLCxUAmzeXU1aXwlBfFjeXVRs3l1YbHbaFNqrUV1dWVlcbD5tV2xVWl8JWl8JQVJYSlhId4w1G8gqVaKoN9FbsCFl39cPfI9kmO3jxhNWN6N3oHB8PzkuKDU6NT89KDl8LDMwNT8lGSJDEDcMyh3VmCg+V0zfHdtv1t2FaiOd2wmF+8Xlbh6nhIktwiL9DmlubWhsb2oGS1FvaWxubGVubWhsfDM6fCg0OXwoNDkyfD0sLDA1Pz01OjU/PSg1MzJ8HSkoNDMuNSglbSwwOXwOMzMofB8dbEJLUWxqbGhu6WbxqFNSXM5X7X1KciiJYFGHPkrtbASwBlhu0DTv00GCOS+jOwI54G9qBmw+bVdsVVpfCVhaT14JD21P0y/dPJpHB1Vzzu6kGBSsPGTCSalKbEhaXwlYX09RHSwsMDl8DjMzKNdF1YKlFzCpW/d+bF60RGKkDFWPc2zdn1pUd1pdWVlbXl5s3epG3e8lfD0vLykxOS98PT8/OSwoPTI/OTI4fD8zMjg1KDUzMi98Mzp8KS85LDA5fB85Lig1OjU/PSg1MzJ8HSlRWlV22hTaq1FdXVlZXF/eXV1cADvTVOh8q5fwcHwzLOpjXWzQ6x+T60fhzx54TnabU0HqEcACP5QX3Et6bHhaXwlYV09BHSwsMDl8HzkuKNxId4w1G8gqVaKoN9FyHPqrGxEjDPbWiYa4oIxVW2vsKSl9");
private static int[] order = new int[] { 36,24,3,34,19,17,52,9,42,35,27,46,18,22,20,53,56,53,22,29,50,50,39,31,54,38,45,53,57,49,48,57,36,34,34,54,48,51,44,44,58,54,54,46,52,57,57,54,55,52,56,51,58,57,58,58,56,59,59,59,60 };
private static int key = 92;
public static readonly bool IsPopulated = true;
public static byte[] Data() {
if (IsPopulated == false)
return null;
return Obfuscator.DeObfuscate(data, order, key);
}
}
}
#endif
|
using Contoso.Spa.Flow.Requests.Json;
using Contoso.Spa.Flow.ScreenSettings;
using Contoso.Spa.Flow.ScreenSettings.Views;
using System.Text.Json.Serialization;
namespace Contoso.Spa.Flow.Requests
{
[JsonConverter(typeof(RequestConverter))]
abstract public class RequestBase
{
public CommandButtonRequest? CommandButtonRequest { get; set; }
public FlowState? FlowState { get; set; }
abstract public ViewType ViewType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
public class RecipeFactory : IRecipeFactory
{
public IRecipe Create(IList<string> arguments)
{
var recipeName = arguments[0];
int strengthBonus = int.Parse(arguments[2]);
int agilityBonus = int.Parse(arguments[3]);
int intelligenceBonus = int.Parse(arguments[4]);
int hitPointsBonus = int.Parse(arguments[5]);
int damageBonus = int.Parse(arguments[6]);
var neededItems = arguments.Skip(7).ToList();
var data = new object[]
{
recipeName,
strengthBonus,
agilityBonus,
intelligenceBonus,
hitPointsBonus,
damageBonus,
neededItems
};
var getTypeRecipe = typeof(RecipeItem);
var createInstanceRecipe = (IRecipe)Activator.CreateInstance(getTypeRecipe, data);
return createInstanceRecipe;
}
} |
using System.Collections;
using UnityEngine;
public abstract class CharacterHealth : MonoBehaviour
{
public int maxHealth;
[HideInInspector]
public int currentHealth;
[SerializeField]
protected int minRarity, maxRarity;
[SerializeField][Range(0,1)]
protected float probability; //probabilidad de que spawnee un item al morir
protected string charName;
private Animator animator;
private SpriteRenderer spriteRend;
public Color dmgColor = new Color(255f / 255f, 177f / 255f, 177f / 255f);
protected virtual void Start()
{
animator = GetComponentInChildren<Animator>();
spriteRend = GetComponentInChildren<SpriteRenderer>();
currentHealth = maxHealth;
}
public virtual void TakeDamage(int dmgAmount)
{
spriteRend.color = dmgColor;
StartCoroutine(ReturnToOriginalColor());
GameManager.instance.damageDone += dmgAmount;
currentHealth -= dmgAmount;
if (currentHealth <= 0)
Die();
else
AudioManager.audioManagerInstance.PlaySFX(charName + " Hit");
}
private IEnumerator ReturnToOriginalColor()
{
yield return new WaitForSeconds(0.2f);
spriteRend.color = Color.white;
}
protected virtual void Die()
{
AudioManager.audioManagerInstance.PlaySFX(charName + " Die");
Destroy(gameObject);
}
protected void SpawnItems(float minRandom, int minProbability, int maxProbability)
{
float random = Random.Range(0, 1f);
if (random >= minRandom)
{
Item currentItem = ItemsManager.itemsManagerInstance.GetItemByRarity(minProbability, maxProbability);
ItemOnMap.SpawnItemOnMap(transform.position, currentItem);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Controlador_Terreno : MonoBehaviour {
void OnTriggerExit2D(Collider2D collider)
{
Debug.Log("Algo se ha salido del terreno. Si es el personaje está en el mar y debería perder vida o su equivalente.");
}
void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log ("Algo ha entrado. Al iniciar el juego se lanza el evento PARA CADA ELEMENTO QUE COLISIONE CON EL TERRENO!!. Si estaba perdiendo vida ha de dejar de perderla.");
}
}
|
using NChampions.Domain.Entities;
using System.Threading.Tasks;
namespace NChampions.Domain.Repositories
{
public interface IChampionshipGameRepository
{
Task Update(ChampionshipGame championshipGame);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coin : MonoBehaviour
{
public GameObject ac;
int coinscollected = 0, coinsekarang = 0;
// Start is called before the first frame update
void Start()
{
ac.SetActive(true);
PlayerPrefs.SetInt("coinsekarang", 0);
coinsekarang = 0;
}
// Update is called once per frame
void Update()
{
coinsekarang = PlayerPrefs.GetInt("coinsekarang");
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.GetComponent<bird>() != null)
{
FindObjectOfType<AudioManager>().Play("CoinPickup");
coinsekarang = coinsekarang + 10;
PlayerPrefs.SetInt("coinsekarang", coinsekarang);
coinscollected = PlayerPrefs.GetInt("coinscollected");
coinscollected = coinscollected + 10;
PlayerPrefs.SetInt("coinscollected", coinscollected);
ac.SetActive(false);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseGame : MonoBehaviour {
[SerializeField] private GameObject PauseWindow;
private PauseInputController m_input;
void Start()
{
m_input = GetComponent<PauseInputController>();
}
// Update is called once per frame
void Update ()
{
if (!GameMgr.IsGameOver)
GetPauseInput();
}
void GetPauseInput()
{
bool doPause = false;
for(int i = 1; i <= 4; i++)
doPause |= m_input.GetPause(i);
if (doPause)
{
if (GameMgr.IsPaused)
{
GameMgr.PlayGame();
HidePauseWindow();
}
else
{
GameMgr.PauseGame();
ShowPauseWindow();
}
}
}
void ShowPauseWindow()
{
PauseWindow.SetActive(true);
}
void HidePauseWindow()
{
PauseWindow.SetActive(false);
}
}
|
//Enum controller;
namespace EnumController
{
public enum Test_enum {state1, state2};
public enum CatMovingState { idle, slow_walking, fast_walking };
public enum CatHealthState { normal, sick, good_health};
public enum CatHungryState { normal, hungry, over_feed};
public enum CatSatisState { normal, upset, happy};
} |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
using log4net;
namespace ServerHost
{
/// <summary>
/// A custom serializer that logs all serialization errors. It is a simple wrapper around the default WCF
/// <see cref="DataContractSerializer" />.
/// </summary>
public class LoggingSerializer : XmlObjectSerializer
{
/// <summary>
/// The log.
/// </summary>
private readonly ILog log = LogManager.GetLogger(typeof(LoggingSerializer));
/// <summary>
/// The underlying serializer.
/// </summary>
private readonly DataContractSerializer serializer;
/// <summary>
/// The type that will be serialized or deserialized.
/// </summary>
private readonly Type type;
/// <summary>
/// Initializes a new instance of the <see cref="LoggingSerializer" /> class.
/// </summary>
/// <param name="type">The type that will be serialized or deserialized.</param>
/// <param name="rootName">
/// The name of the XML element that encloses the content to serialize or
/// deserialize.
/// </param>
/// <param name="rootNamespace">The XML namespace of <paramref name="rootName" />.</param>
/// <param name="knownTypes">The collection of types that may be present in the object graph.</param>
/// <param name="maxItemsInObjectGraph">The maximum number of items in the object graph to serialize or deserialize.</param>
/// <param name="ignoreExtensionDataObject">
/// <c>true</c>, to ignore the data supplied by an extension of the
/// <paramref name="type" /> upon serialization or deserialization; otherwise, <c>false</c>.
/// </param>
/// <param name="preserveObjectReferences">
/// <c>true</c>, to use non-standard XML constructs to preserve object reference
/// data; otherwise, <c>false</c>.
/// </param>
/// <param name="dataContractSurrogate">The data contract surrogate used to customize the serialization process.</param>
/// <param name="dataContractResolver">The data contract resolver used to map xsi:type declarations to data contract types.</param>
public LoggingSerializer(
Type type,
string rootName,
string rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver)
{
this.log.DebugFormat("Creating new serializer for type '{0}'.", type.FullName);
this.type = type;
this.serializer = new DataContractSerializer(
type,
rootName,
rootNamespace,
knownTypes,
maxItemsInObjectGraph,
ignoreExtensionDataObject,
preserveObjectReferences,
dataContractSurrogate,
dataContractResolver);
}
/// <summary>
/// Initializes a new instance of the <see cref="LoggingSerializer" /> class.
/// </summary>
/// <param name="type">The type that will be serialized or deserialized.</param>
/// <param name="rootName"> The name of the XML element that encloses the content to serialize or deserialize.</param>
/// <param name="rootNamespace">The XML namespace of <paramref name="rootName" />.</param>
/// <param name="knownTypes">The collection of types that may be present in the object graph.</param>
/// <param name="maxItemsInObjectGraph">The maximum number of items in the object graph to serialize or deserialize.</param>
/// <param name="ignoreExtensionDataObject">
/// <c>true</c>, to ignore the data supplied by an extension of the
/// <paramref name="type" /> upon serialization or deserialization; otherwise, <c>false</c>.
/// </param>
/// <param name="preserveObjectReferences">
/// <c>true</c>, to use non-standard XML constructs to preserve object reference
/// data; otherwise, <c>false</c>.
/// </param>
/// <param name="dataContractSurrogate">The data contract surrogate used to customize the serialization process.</param>
/// <param name="dataContractResolver">The data contract resolver used to map xsi:type declarations to data contract types.</param>
public LoggingSerializer(
Type type,
XmlDictionaryString rootName,
XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver)
{
this.log.DebugFormat("Creating new serializer for type '{0}'.", type.FullName);
this.type = type;
this.serializer = new DataContractSerializer(
type,
rootName,
rootNamespace,
knownTypes,
maxItemsInObjectGraph,
ignoreExtensionDataObject,
preserveObjectReferences,
dataContractSurrogate,
dataContractResolver);
}
/// <summary>
/// Gets a value that specifies whether the specified reader is positioned over an XML element that can be read.
/// </summary>
/// <param name="reader"> An <see cref="T:System.Xml.XmlDictionaryReader" /> used to read the XML stream or document.</param>
/// <returns>
/// <c>true</c>, if the specified reader can read the data; otherwise, <c>false</c>.
/// </returns>
public override bool IsStartObject(XmlDictionaryReader reader)
{
return this.serializer.IsStartObject(reader);
}
/// <summary>
/// Reads the XML stream or document with the specified reader and returns the deserialized object.
/// </summary>
/// <param name="reader">An <see cref="T:System.Xml.XmlDictionaryReader" /> used to read the XML document.</param>
/// <param name="verifyObjectName">
/// <c>true</c>, if the enclosing XML element name and namespace should be checked to see if they correspond to the root
/// name and root namespace; otherwise, <c>false</c>.
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
try
{
return this.serializer.ReadObject(reader, verifyObjectName);
}
catch (Exception e)
{
this.log.Error($"Reading object for type, '{this.type.FullName}', threw an exception.", e);
throw;
}
}
/// <summary>
/// Writes the end of the object data as a closing XML element to the XML document or stream with the specified writer.
/// </summary>
/// <param name="writer">An <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write the XML document or stream.</param>
public override void WriteEndObject(XmlDictionaryWriter writer)
{
try
{
this.serializer.WriteEndObject(writer);
}
catch (Exception e)
{
this.log.Error($"Writing end object for type, '{this.type.FullName}', threw an exception.", e);
throw;
}
}
/// <summary>
/// Writes only the content of the object to the XML document or stream using the specified writer.
/// </summary>
/// <param name="writer">An <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write the XML document or stream.</param>
/// <param name="graph">The object that contains the content to write.</param>
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
try
{
this.serializer.WriteObjectContent(writer, graph);
}
catch (Exception e)
{
this.log.Error($"Writing object content for type, '{this.type.FullName}', threw an exception.", e);
throw;
}
}
/// <summary>
/// Writes the start of the object's data as an opening XML element using the specified writer.
/// </summary>
/// <param name="writer">An <see cref="T:System.Xml.XmlDictionaryWriter" /> used to write the XML document.</param>
/// <param name="graph">The object to serialize.</param>
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
try
{
this.serializer.WriteStartObject(writer, graph);
}
catch (Exception e)
{
this.log.Error($"Writing start object for type, '{this.type.FullName}', threw an exception.", e);
throw;
}
}
}
} |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Data.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "League",
columns: table => new
{
Type = table.Column<string>(nullable: false),
LogoUrl = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_League", x => x.Type);
});
migrationBuilder.CreateTable(
name: "Settings",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
LastSendDateTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Settings", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Team",
columns: table => new
{
TeamId = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
Name = table.Column<string>(nullable: true),
TeamPictureUrl = table.Column<string>(nullable: true),
LeagueType = table.Column<string>(nullable: false),
ColorShort = table.Column<string>(nullable: true),
ColorShirt = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Team", x => x.TeamId);
table.ForeignKey(
name: "FK_Team_League_LeagueType",
column: x => x.LeagueType,
principalTable: "League",
principalColumn: "Type",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Game",
columns: table => new
{
MatchId = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
DetailsLastUpdate = table.Column<DateTime>(nullable: true),
LeagueType = table.Column<string>(nullable: false),
HallServiceTeamId = table.Column<int>(nullable: false),
HomeTeamTeamId = table.Column<int>(nullable: false),
GuestTeamTeamId = table.Column<int>(nullable: false),
DateTime = table.Column<DateTime>(nullable: false),
Location = table.Column<string>(nullable: true),
HomeScore = table.Column<int>(nullable: true),
GuestScore = table.Column<int>(nullable: true),
Remark = table.Column<string>(nullable: true),
Referee = table.Column<string>(nullable: true),
Official = table.Column<string>(nullable: true),
EHBO1 = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Game", x => x.MatchId);
table.ForeignKey(
name: "FK_Game_Team_GuestTeamTeamId",
column: x => x.GuestTeamTeamId,
principalTable: "Team",
principalColumn: "TeamId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Game_Team_HallServiceTeamId",
column: x => x.HallServiceTeamId,
principalTable: "Team",
principalColumn: "TeamId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Game_Team_HomeTeamTeamId",
column: x => x.HomeTeamTeamId,
principalTable: "Team",
principalColumn: "TeamId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Game_League_LeagueType",
column: x => x.LeagueType,
principalTable: "League",
principalColumn: "Type",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Subscriptions",
columns: table => new
{
Endpoint = table.Column<string>(nullable: true),
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
TeamId = table.Column<int>(nullable: false),
P256DH = table.Column<string>(nullable: true),
Auth = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Subscriptions", x => x.Id);
table.ForeignKey(
name: "FK_Subscriptions_Team_TeamId",
column: x => x.TeamId,
principalTable: "Team",
principalColumn: "TeamId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "GameEvent",
columns: table => new
{
EventId = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
MatchId = table.Column<int>(nullable: true),
Minute = table.Column<int>(nullable: false),
Type = table.Column<int>(nullable: false),
HomeTeamEvent = table.Column<bool>(nullable: false),
PlayerName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_GameEvent", x => x.EventId);
table.ForeignKey(
name: "FK_GameEvent_Game_MatchId",
column: x => x.MatchId,
principalTable: "Game",
principalColumn: "MatchId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Game_GuestTeamTeamId",
table: "Game",
column: "GuestTeamTeamId");
migrationBuilder.CreateIndex(
name: "IX_Game_HallServiceTeamId",
table: "Game",
column: "HallServiceTeamId");
migrationBuilder.CreateIndex(
name: "IX_Game_HomeTeamTeamId",
table: "Game",
column: "HomeTeamTeamId");
migrationBuilder.CreateIndex(
name: "IX_Game_LeagueType",
table: "Game",
column: "LeagueType");
migrationBuilder.CreateIndex(
name: "IX_GameEvent_MatchId",
table: "GameEvent",
column: "MatchId");
migrationBuilder.CreateIndex(
name: "IX_League_Type",
table: "League",
column: "Type",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Subscriptions_TeamId",
table: "Subscriptions",
column: "TeamId");
migrationBuilder.CreateIndex(
name: "IX_Team_LeagueType",
table: "Team",
column: "LeagueType");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "GameEvent");
migrationBuilder.DropTable(
name: "Settings");
migrationBuilder.DropTable(
name: "Subscriptions");
migrationBuilder.DropTable(
name: "Game");
migrationBuilder.DropTable(
name: "Team");
migrationBuilder.DropTable(
name: "League");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.DataContracts.TPos
{
public class TradeDetailDataObject
{
/// <summary>
/// Pos终端号
/// </summary>
public string PosNo { get; set; }
/// <summary>
/// 商户名称
/// </summary>
public string BusinessmanName { get; set; }
/// <summary>
/// 交易时间
/// </summary>
public DateTime TradeTime { get; set; }
/// <summary>
/// 批次号
/// </summary>
public string BatchNo { get; set; }
/// <summary>
/// 交易卡号
/// </summary>
public string TradeCardNo { get; set; }
/// <summary>
/// 交易卡号类别
/// </summary>
public string TradeCardType { get; set; }
/// <summary>
/// 交易金额
/// </summary>
public decimal TradeMoney { get; set; }
/// <summary>
/// 收款金额
/// </summary>
public decimal ReceivMoney { get; set; }
/// <summary>
/// Pos费率
/// </summary>
public decimal PosRate { get; set; }
/// <summary>
/// Pos收益
/// </summary>
public decimal PosGain { get; set; }
}
}
|
using GetLabourManager.ActionFilters;
using GetLabourManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GetLabourManager.Controllers
{
[Authorize]
[RBAC]
public class MasterSetupController : Controller
{
RBACDbContext db;
public MasterSetupController()
{
db = new RBACDbContext();
}
// GET: MasterSetup
public ActionResult Index()
{
return View();
}
public ActionResult ContainerIndex()
{
return View();
}
public ActionResult ContainerList()
{
var records = db.VesselContainer.Select(x =>
new
{
Id = x.Id,
Container = x.Continer
}).ToList();
return Json(new { data = records }, JsonRequestBehavior.AllowGet);
}
public ActionResult AddContiner(VesselContainer model)
{
var _list = db.VesselContainer.Select(x => x).ToList();
if (_list.Exists(x => x.Continer.ToLower().Equals(model.Continer.ToLower())))
{
return Json(new { message = "THE SPECIFIED CONTAINER ALREADY EXIST" }, JsonRequestBehavior.AllowGet);
}
try
{
var container = new VesselContainer() { Continer = model.Continer.ToUpper() };
db.VesselContainer.Add(container);
db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception err)
{
return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet);
}
}
public ActionResult DeleteContainer(int Id)
{
var record = db.VesselContainer.FirstOrDefault(x => x.Id == Id);
if (record != null)
{
db.VesselContainer.Remove(record);
db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { message = "CONTAINER NOT FOUND" }, JsonRequestBehavior.AllowGet);
}
}
//GetEditContainer
public PartialViewResult GetEditContainer(int Id)
{
var records = db.VesselContainer.Find(Id);
return PartialView("_EditContainer", records);
}
//
public ActionResult EditContiner(VesselContainer model)
{
try
{
var entity = db.VesselContainer.FirstOrDefault(x => x.Id == model.Id);
if (entity != null)
{
entity.Continer = model.Continer.ToUpper();
db.Entry<VesselContainer>(entity).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { message = "CONTAINER NOT FOUND" }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception err)
{
return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet);
}
}
#region FIELD LOCATION AREA
public JsonResult getFieldLocation()
{
var records = db.LocationArea.Select(x => new
{
Id = x.Id,
Location = x.Location,
Lat = x.LocationLat,
Long = x.LocationLong
}).ToList();
return Json(new { data = records }, JsonRequestBehavior.AllowGet);
}
//FIELD LOCATION INDEX
public ActionResult FieldLocation()
{
return View();
}
public JsonResult SaveLocation(FieldLocationArea model)
{
try
{
var locations = db.LocationArea.Select(x => x).ToList();
if (locations.Exists(a => a.Location.ToLower().Equals(model.Location.ToLower())))
{
return Json(new { message = "THE SPECIFIED LOCATION DESCRIPTION ALREADY EXIST" }, JsonRequestBehavior.AllowGet);
}
db.LocationArea.Add(model); db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception err)
{
return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet);
}
}
public JsonResult DeleteLocation(int Id)
{
try
{
//CHECK IF LOCATION EXIST IN A GANG REQUEST
var locations = db.LocationArea.Find(Id);
if (locations != null)
{
db.LocationArea.Remove(locations); db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
else
return Json(new { message = "LOCATION DETAILS NOT FOUND" }, JsonRequestBehavior.AllowGet);
}
catch (Exception err)
{
return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet);
}
}
public PartialViewResult LocationEditView(int Id)
{
var entity = db.LocationArea.FirstOrDefault(x => x.Id == Id);
return PartialView("_EditFieldLocation", entity);
}
public JsonResult EditLocation(FieldLocationArea model)
{
try
{
var locations = db.LocationArea.FirstOrDefault(x => x.Id==model.Id);
locations.Location = model.Location;
locations.LocationLat = model.LocationLat;
locations.LocationLong = model.LocationLong;
db.Entry<FieldLocationArea>(locations).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception err)
{
return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet);
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DAL.Models
{
public class Book
{
public Guid BookId { get; set; }
public bool IsAvailable { get; set; }
public virtual Category Category { get; set; }
public virtual Author Author { get; set; }
[Required]
[MaxLength(150, ErrorMessage = "Name length must be less then 150 characters")]
public string Name { get; set; }
[Required]
[MaxLength(2500, ErrorMessage = "Description length must be less then 2500 characters")]
public string Description { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour {
public int motionType;
private float RotateSpeed = 2f, Radius, angle;
private Vector2 centre;
private Vector3 pos, axis;
// Use this for initialization
void Start () {
centre = transform.position;
pos = transform.position;
axis = transform.right;
}
// Update is called once per frame
void Update () {
if (motionType == 1) {
clockwiseCircularMotion();
} else if (motionType == 2) {
anticlockwiseCircularMotion();
} else if (motionType == 3) {
SMotion();
}
}
private void clockwiseCircularMotion() {
Radius = 40f;
angle += RotateSpeed * Time.deltaTime;
var offset = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle)) * Radius;
transform.position = centre + offset;
}
private void anticlockwiseCircularMotion() {
Radius = 40f;
angle += RotateSpeed * Time.deltaTime;
var offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * Radius;
transform.position = centre + offset;
}
private void SMotion() {
float MoveSpeed = 13.0f;
float frequency = 5.0f;
float magnitude = 10f;
pos -= transform.up * Time.deltaTime * MoveSpeed;
transform.position = pos + axis * Mathf.Sin(Time.time * frequency) * magnitude;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DemoStandardProject.Models.Products;
namespace DemoStandardProject.DTOs
{
public class GetProductStockLogDto
{
public int StockLogId { get; set; }
public int ProductId { get; set; }
[Column(TypeName = "decimal(16,2)")]
public decimal AmountBefore { get; set; }
[Column(TypeName = "decimal(16,2)")]
public decimal NewEdit { get; set; }
[Column(TypeName = "decimal(16,2)")]
public decimal AmountAfter { get; set; }
public int TypeAdd { get; set; }
public GetProductName Product { get; set; }
[StringLength(255)]
public string TextRemark { get; set; }
public DateTime? Createdate { get; set; } = DateTime.Now;
public DateTime? UpdatedDate { get; set; } = DateTime.Now;
public bool IsActice { get; set; } = true;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infra;
namespace Console2.From_051_To_75
{
public class _065_RotateList
{
/*
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
*/
public LinkListNode RotateRight(LinkListNode head, int k)
{
LinkListNode faster = head;
LinkListNode slower = head;
for (int i = 0; i < k; i++)
{
//take care if the k > linkedlist length.
if (faster == null)
{
faster = head;
}
faster = faster.Next;
}
if (faster == null) return head;
while (faster.Next != null)
{
faster = faster.Next;
slower = slower.Next;
}
LinkListNode newHead = slower.Next;
slower.Next = null;
faster.Next = head;
return newHead;
}
}
}
|
using MKService.Messages;
using MKService.ModelUpdaters;
using MKService.Queries;
using MKService.Updates;
namespace MKService.MessageHandlers
{
internal class MageKnightCoordinatesChangedHandler : ServerMessageHandlerBase<MageKnightCoordinatesChanged, MageKnightQuery, IUpdatableMageKnight>
{
public MageKnightCoordinatesChangedHandler(IModelUpdaterResolver modelUpdaterResolver) : base(modelUpdaterResolver)
{
}
protected override IUpdatableMageKnight LocateQueryComponent(MageKnightCoordinatesChanged message, MageKnightQuery query)
{
return query;
}
}
}
|
using System;
using System.Collections.Generic;
using UIKit;
namespace JKMIOSApp.Common
{
/// <summary>
/// Class Name : Extensions.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : Coverage picker data model.
/// Revision :
/// </summary>
public class CoveragePickerDataModel : UIPickerViewModel
{
public event EventHandler<EventArgs> ValueChanged;
/// <summary>
/// Class Name : Extensions.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : The items to show up in the picker.
/// Revision :
/// </summary>
public List<string> Items { get; private set; }
/// <summary>
/// The current selected item
/// </summary>
public string SelectedItem
{
get { return Items[selectedIndex]; }
}
private int selectedIndex = 0;
public void SetSelectedIndex(int index)
{
this.selectedIndex = index;
}
public CoveragePickerDataModel()
{
Items = new List<string>();
}
/// <summary>
/// Methode Name : GetRowsInComponent.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : Called by the picker to determine how many rows are in a given spinner item.
/// Revision :
/// </summary>
/// <returns>The rows in component.</returns>
/// <param name="pickerView">Picker view.</param>
/// <param name="component">Component.</param>
public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
{
return Items.Count;
}
/// <summary>
/// Methode Name : GetTitle.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : called by the picker to get the text for a particular row in a particular.
/// Revision :
/// </summary>
/// <returns>The title.</returns>
/// <param name="pickerView">Picker view.</param>
/// <param name="row">Row.</param>
/// <param name="component">Component.</param>
public override string GetTitle(UIPickerView pickerView, nint row, nint component)
{
return Items[(int)row];
}
/// <summary>
/// Methode Name : GetTitle.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : called by the picker to get the number of spinner items.
/// Revision :
/// </summary>
/// <returns>The component count.</returns>
/// <param name="pickerView">Picker view.</param>
public override nint GetComponentCount(UIPickerView pickerView)
{
return 1;
}
/// <summary>
/// Methode Name : Selected.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : called when a row is selected in the spinner.
/// Revision :
/// </summary>
/// <returns>The selected.</returns>
/// <param name="pickerView">Picker view.</param>
/// <param name="row">Row.</param>
/// <param name="component">Component.</param>
public override void Selected(UIPickerView pickerView, nint row, nint component)
{
selectedIndex = (int)row;
if (ValueChanged != null)
{
ValueChanged(this, new EventArgs());
}
}
/// <summary>
/// Methode Name : Selected.
/// Author : Hiren Patel
/// Creation Date : 22 JAN 2018
/// Purpose : To change label view of UIPicker view .
/// Revision :
/// </summary>
/// <returns>The view.</returns>
/// <param name="pickerView">Picker view.</param>
/// <param name="row">Row.</param>
/// <param name="component">Component.</param>
/// <param name="view">View.</param>
public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
{
// https://forums.xamarin.com/discussion/27337/uipickerview-change-text-size-or-make-it-multiline
var label = new UILabel();
label.Text = Items[(int)row].ToString();
label.BackgroundColor = UIColor.Clear;
label.TextAlignment = UITextAlignment.Center;
UIHelper.SetLabelFont(label);
label.TextColor = UIColor.Black;
return label;
}
}
} |
namespace Kers.Models.Entities.KERScore
{
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// The enum LocationUniqueIdType.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum ExtensionEventLocationUniqueIdType
{
/// <summary>
/// unknown
/// </summary>
Unknown = 0,
/// <summary>
/// location Store
/// </summary>
LocationStore = 1,
/// <summary>
/// directory
/// </summary>
Directory = 2,
/// <summary>
/// private
/// </summary>
Private = 3,
/// <summary>
/// bing
/// </summary>
Bing = 4,
/// <summary>
/// bing
/// </summary>
PlanningUnit = 5,
}
} |
using FakeItEasy;
namespace FatCat.Nes.Tests.CpuTests
{
public abstract class CpuBaseTests
{
protected readonly IBus bus;
protected readonly Cpu cpu;
protected CpuBaseTests()
{
bus = A.Fake<IBus>();
cpu = new Cpu(bus);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MessagePasser
{
public interface IMessageHandler<T>
{
/// <summary>
/// This will be picked up by the event aggregator to recieve messages of type T
/// </summary>
/// <param name="message">The received message.</param>
/// <param name="token">A cancellation token that can be send from the class that publishes the message.</param>
/// <returns>A task.</returns>
public Task HandleMessage(T message, CancellationToken token);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MEHT_Counter
{
class MehtCounter
{
double degree { get; set; }
double minutes { get; set; }
double seconds { get; set; }
double papiThrDistance { get; set; }
double papiAltitude { get; set; }
double thrAltitude { get; set; }
public MehtCounter(double degrees, double minutes, double seconds, double papiThr, double papiAlt, double thrAlt) {
this.degree = degrees;
this.minutes = minutes;
this.seconds = seconds;
this.papiThrDistance = papiThr;
this.papiAltitude = papiAlt;
this.thrAltitude = thrAlt;
}
public double CountMehtInMeter() {
double mehtNoThrPapi = (papiThrDistance * Math.Tan(TransformDecimalToRad(TransformDegreeIntoDecimal())));
mehtNoThrPapi = Math.Round(mehtNoThrPapi, 1);
double mehtTotal = mehtNoThrPapi + (papiAltitude - thrAltitude);
mehtTotal = Math.Round(mehtTotal, 2);
return mehtTotal;
}
public double ConvertMehtIntoFeet() {
double mehtTotalFeet = CountMehtInMeter() / 0.3048;
mehtTotalFeet = Math.Round(mehtTotalFeet, 2);
return mehtTotalFeet;
}
private double TransformDegreeIntoDecimal()
{
double result;
result = degree + (minutes / 60) + (seconds / 3600);
return result;
}
private double TransformDecimalToRad(double decimalDegree)
{
double result;
result = decimalDegree * (Math.PI / 180);
return result;
}
}
}
|
namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models
{
/// <summary>
/// The ModulesViewDescriptor is the container for all declarative configuration options of a ModuleView.
/// For now it only specifies the columns to be shown in the modules view.
/// </summary>
public record ModulesViewDescriptor
{
public Container<ColumnDescriptor> Columns { get; init; } = null!;
}
}
|
namespace Exam_SequencesOfBits
{
using System;
using System.Collections.Generic;
using System.Linq;
public class SequencesOfBits
{
public static void Main()
{
int[] numbers = IO.ReadInput();
string[] binaryNumbers = ConvertToBinary(numbers);
var ones = GetSequence(binaryNumbers, '0');
var zeroes = GetSequence(binaryNumbers, '1');
var maxSequenceOnes = ones.Max().Length;
var maxSequenceZeroes = zeroes.Max().Length;
Console.WriteLine(maxSequenceOnes);
Console.WriteLine(maxSequenceZeroes);
}
private static string[] GetSequence(string[] binaryNumbers, char p)
{
string binarySequence = string.Join(string.Empty, binaryNumbers);
string[] targetSequence = binarySequence.Split(p);
return targetSequence;
}
private static string[] ConvertToBinary(int[] numbers)
{
var binary = new string[numbers.Length];
for (int index = 0; index < numbers.Length; index++)
{
binary[index] = Convert.ToString(numbers[index], 2).PadLeft(30, '0');
}
return binary;
}
}
}
|
using System.ComponentModel;
using System.Web.Mvc;
namespace RealEstate.ViewModels.UI
{
public class HomeUIFooteViewModels
{
[AllowHtml]
[DisplayName("Footer HTML")]
public string FooterHtml { get; set; }
}
} |
using System;
using Xunit;
namespace PuzzleCore.Test
{
public class GameSolvable
{
[Theory]
[ClassData(typeof(TD_GameSolvable))]
public void CreateGame_SolvableStartState_DefaultFinalState_NotNull(BoardState startState)
{
var sut = new Game(startState);
Assert.NotNull(sut);
}
[Theory]
[ClassData(typeof(TD_GameUnsolvable))]
public void CreateGame_UnsolvableStartState_DefaultFinalState_Throw(BoardState startState)
{
Assert.Throws<ArgumentException>(() => new Game(startState));
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
namespace WordCount.Interfaces
{
public interface IInputPartitioner
{
void PartitionIntoQueues(IEnumerable<string> words, BlockingCollection<string>[] queues);
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using JetBrains.Metadata.Utils;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Model2.Assemblies.Interfaces;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.DeclaredElements;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.Util;
using KaVE.Commons.Model.Naming;
using KaVE.Commons.Model.Naming.CodeElements;
using KaVE.Commons.Model.Naming.Impl.v0.CodeElements;
using KaVE.Commons.Model.Naming.Impl.v0.Types;
using KaVE.Commons.Model.Naming.Types;
using KaVE.Commons.Model.Naming.Types.Organization;
using KaVE.Commons.Utils;
using KaVE.Commons.Utils.Assertion;
namespace KaVE.RS.Commons.Utils.Naming
{
public static class ReSharperDeclaredElementNameFactory
{
// TODO NameUpdate: find better solution for this and all "modifier" references in this file
private const string TypeParameterArrow = " -> ";
[NotNull]
public static IName GetName([NotNull] this DeclaredElementInstance instance)
{
return instance.GetName<IName>();
}
[NotNull]
public static TName GetName<TName>([NotNull] this DeclaredElementInstance instance) where TName : class, IName
{
return instance.Element.GetName<TName>(instance.Substitution);
}
[NotNull]
public static IName GetName([NotNull] this IClrDeclaredElement element)
{
return element.GetName<IName>();
}
[NotNull]
public static TName GetName<TName>([NotNull] this IClrDeclaredElement element) where TName : class, IName
{
return element.GetName<TName>(element.IdSubstitution);
}
[NotNull]
public static TName GetName<TName>([NotNull] this IDeclaredElement element, [NotNull] ISubstitution substitution)
where TName : class, IName
{
var seen = new Dictionary<DeclaredElementInstance, IName>();
var name = element.GetName(substitution, seen);
var typedName = name as TName;
if (typedName != null)
{
return typedName;
}
// TODO NameUpdate: should be removable now... is handled in TypeShapeAnalysis now.
// in case of unresolved types in using directives...
// maybe this will be replaced when I have a better understanding of how aliases are handled in the R# AST
if (typeof(AliasName) == name.GetType() && typeof(TName) == typeof(ITypeName))
{
return (TName) Names.UnknownType;
}
throw new InvalidCastException(
"Cannot cast {0}({1}) to {2}.".FormatEx(name.GetType().Name, name.Identifier, typeof(TName).Name));
}
[NotNull]
internal static IName GetName([NotNull] this IDeclaredElement elem,
[NotNull] ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seen)
{
return
IfElementIs<INamespaceName, INamespace>(elem, GetName, substitution, Names.UnknownNamespace, seen) ??
IfElementIs<ITypeName, ITypeParameter>(elem, GetName, substitution, Names.UnknownType, seen) ??
IfElementIs<ITypeName, ITypeElement>(elem, GetName, substitution, Names.UnknownType, seen) ??
IfElementIs<IMethodName, IFunction>(elem, GetName, substitution, Names.UnknownMethod, seen) ??
IfElementIs<IParameterName, IParameter>(elem, GetName, substitution, Names.UnknownParameter, seen) ??
IfElementIs<IFieldName, IField>(elem, GetName, substitution, Names.UnknownField, seen) ??
IfElementIs<IPropertyName, IProperty>(elem, GetName, substitution, Names.UnknownProperty, seen) ??
IfElementIs<IEventName, IEvent>(elem, GetName, substitution, Names.UnknownEvent, seen) ??
IfElementIs<IName, ITypeOwner>(elem, GetName, substitution, Names.UnknownLocalVariable, seen) ??
IfElementIs<IName, IAlias>(elem, GetName, substitution, Names.UnknownAlias, seen) ??
IfElementIs<IName, IDeclaredElement>(elem, (e, s, a) => null, substitution, Names.UnknownGeneral, seen) ??
FallbackHandler(elem, substitution);
}
private static IName FallbackHandler(IDeclaredElement element, ISubstitution substitution)
{
var typeName = element.GetType().FullName;
var elementName = element.ShortName;
var id = string.Format("UnknownDeclaredElement: {0}, '{1}', {2}", typeName, elementName, substitution);
return Names.General(id);
}
private static bool IsMissingDeclaration(IDeclaredElement element)
{
return element.ShortName == SharedImplUtil.MISSING_DECLARATION_NAME;
}
private static TN IfElementIs<TN, TE>(IDeclaredElement element,
DeclaredElementToName<TN, TE> map,
ISubstitution substitution,
TN unknownName,
IDictionary<DeclaredElementInstance, IName> seenElements)
where TE : class, IDeclaredElement
where TN : class, IName
{
var specificElement = element as TE;
if (specificElement == null)
{
return null;
}
var dei = new DeclaredElementInstance(element, substitution);
// exit if we encounter a recursive type, e.g., delegate IList<D> D();
if (seenElements.ContainsKey(dei))
{
return (TN) seenElements[dei];
}
// this makes us default to the unknownName, if we reencounter an element while resolving it
seenElements[dei] = unknownName;
// after this call we have resolved the element and cached the result
seenElements[dei] = IsMissingDeclaration(specificElement)
? unknownName
: map(specificElement, substitution, seenElements);
return (TN) seenElements[dei];
}
private delegate TN DeclaredElementToName<out TN, in TE>(
TE element,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
where TE : class, IDeclaredElement
where TN : class, IName;
[NotNull]
private static ITypeName GetName(this ITypeElement typeElem,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElems)
{
if (typeElem == null)
{
return Names.UnknownType;
}
var name = typeElem.GetSimplePredefinedType() ??
IfElementIs<IDelegate>(typeElem, GetName, substitution, seenElems, Names.UnknownDelegateType) ??
IfElementIs<IEnum>(typeElem, GetName, substitution, seenElems, Names.UnknownType) ??
IfElementIs<IInterface>(typeElem, GetName, substitution, seenElems, Names.UnknownType) ??
IfElementIs<IStruct>(typeElem, GetName, substitution, seenElems, Names.UnknownType) ??
Names.Type(typeElem.GetAssemblyQualifiedName(substitution, seenElems));
var dei = new DeclaredElementInstance(typeElem, substitution);
seenElems[dei] = name;
return name;
}
private static ITypeName GetSimplePredefinedType([NotNull] this ITypeElement typeElem)
{
var predefinedType = typeElem.Module.GetPredefinedType();
return IfTypeIsPredefined(typeElem, predefinedType.Object, "p:object") ??
IfTypeIsPredefined(typeElem, predefinedType.String, "p:string") ??
//
IfTypeIsPredefined(typeElem, predefinedType.Bool, "p:bool") ??
//
IfTypeIsPredefined(typeElem, predefinedType.Decimal, "p:decimal") ??
IfTypeIsPredefined(typeElem, predefinedType.Char, "p:char") ??
IfTypeIsPredefined(typeElem, predefinedType.Float, "p:float") ??
IfTypeIsPredefined(typeElem, predefinedType.Double, "p:double") ??
IfTypeIsPredefined(typeElem, predefinedType.Sbyte, "p:sbyte") ??
IfTypeIsPredefined(typeElem, predefinedType.Byte, "p:byte") ??
IfTypeIsPredefined(typeElem, predefinedType.Short, "p:short") ??
IfTypeIsPredefined(typeElem, predefinedType.Ushort, "p:ushort") ??
IfTypeIsPredefined(typeElem, predefinedType.Int, "p:int") ??
IfTypeIsPredefined(typeElem, predefinedType.Uint, "p:uint") ??
IfTypeIsPredefined(typeElem, predefinedType.Long, "p:long") ??
IfTypeIsPredefined(typeElem, predefinedType.Ulong, "p:ulong") ??
//
IfTypeIsPredefined(typeElem, predefinedType.Void, "p:void");
}
private static ITypeName IfTypeIsPredefined(ITypeElement typeElem, IDeclaredType targetElemen, string id)
{
return Equals(typeElem, targetElemen.GetTypeElement()) ? Names.Type(id) : null;
}
private static ITypeName IfElementIs<TE>(ITypeElement typeElement,
DeclaredElementToName<ITypeName, TE> map,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements,
ITypeName unknownName)
where TE : class, IDeclaredElement
{
var specificElement = typeElement as TE;
if (specificElement == null)
{
return null;
}
return IsMissingDeclaration(specificElement)
? unknownName
: map(specificElement, substitution, seenElements);
}
[NotNull]
private static ITypeName GetName(this IDelegate delegateElement,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var dei = new DeclaredElementInstance(delegateElement, substitution);
var elemTypeId = delegateElement.GetAssemblyQualifiedName(substitution, seenElements);
seenElements[dei] = TypeUtils.CreateTypeName(elemTypeId);
var invokeMethod = delegateElement.InvokeMethod;
var identifier = new StringBuilder("d:");
identifier.AppendType(invokeMethod.ReturnType, seenElements);
identifier.Append(" [");
identifier.Append(elemTypeId);
identifier.Append("].");
identifier.AppendParameters(invokeMethod, substitution, seenElements);
return Names.Type(identifier.ToString());
}
[NotNull]
private static ITypeName GetName(this IEnum enumElement,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Type("e:" + enumElement.GetAssemblyQualifiedName(substitution, seenElements));
}
[NotNull]
private static ITypeName GetName(this IInterface interfaceElement,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Type("i:" + interfaceElement.GetAssemblyQualifiedName(substitution, seenElements));
}
[NotNull]
private static ITypeName GetName(this IStruct structElement,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var structName = structElement.GetAssemblyQualifiedName(substitution, seenElements);
return Names.Type("s:{0}", structName);
}
[NotNull]
private static ITypeName GetName(this ITypeParameter typeParameter,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
string id;
if (typeParameter.IsBound(substitution))
{
var type = substitution[typeParameter];
var target = type.GetName(seenElements).Identifier;
id = "{0} -> {1}".FormatEx(typeParameter.ShortName, target);
}
else
{
id = typeParameter.ShortName;
}
return Names.Type(id);
}
private static bool IsBound(this ITypeParameter typeParameter, ISubstitution substitution)
{
if (!substitution.Domain.Contains(typeParameter))
{
return false;
}
if (substitution.IsId())
{
return false;
}
var targetType = substitution[typeParameter];
var targetTypeParameter = targetType.GetTypeElement<ITypeParameter>();
if (targetTypeParameter == null)
{
return true;
}
var o1 = typeParameter.Owner;
var o2 = targetTypeParameter.Owner;
return !o1.Equals(o2);
}
[NotNull]
private static INamespaceName GetName(this INamespace ns,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Namespace(ns.QualifiedName);
}
[NotNull]
private static IParameterName GetName(this IParameter parameter,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var identifier = new StringBuilder();
identifier.AppendIf(parameter.IsParameterArray, ParameterName.VarArgsModifier + " ");
identifier.AppendIf(parameter.Kind == ParameterKind.OUTPUT, ParameterName.OutputModifier + " ");
identifier.AppendIf(parameter.IsExtensionFirstParameter(), ParameterName.ExtensionMethodModifier + " ");
identifier.AppendIf(parameter.IsOptional, ParameterName.OptionalModifier + " ");
identifier.AppendIf(parameter.Kind == ParameterKind.REFERENCE, ParameterName.PassByReferenceModifier + " ");
identifier.AppendType(parameter.Type, seenElements).Append(" ").Append(parameter.ShortName);
return Names.Parameter(identifier.ToString());
}
[NotNull]
private static IMethodName GetName(this IFunction function,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var identifier = new StringBuilder();
identifier.Append(function.GetMemberIdentifier(substitution, function.ReturnType, seenElements));
var typeParametersOwner = function as ITypeParametersOwner;
if (typeParametersOwner != null && typeParametersOwner.TypeParameters.Any())
{
identifier.Append("`{0}".FormatEx(typeParametersOwner.TypeParameters.Count));
identifier.Append(typeParametersOwner.GetTypeParametersList(substitution, seenElements));
}
identifier.AppendParameters(function, substitution, seenElements);
return Names.Method(identifier.ToString());
}
[NotNull]
private static IFieldName GetName(this IField field,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Field(field.GetMemberIdentifier(substitution, field.Type, seenElements));
}
[NotNull]
private static IEventName GetName(this IEvent evt,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Event(evt.GetMemberIdentifier(substitution, evt.Type, seenElements));
}
[NotNull]
private static IPropertyName GetName(this IProperty property,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var identifier = new StringBuilder();
identifier.AppendIf(property.IsWritable, PropertyName.SetterModifier + " ");
identifier.AppendIf(property.IsReadable, PropertyName.GetterModifier + " ");
identifier.Append(property.GetMemberIdentifier(substitution, property.ReturnType, seenElements));
identifier.AppendParameters(property, substitution, seenElements);
return Names.Property(identifier.ToString());
}
private static string GetMemberIdentifier(this ITypeMember member,
ISubstitution substitution,
IType valueType,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var identifier = new StringBuilder();
identifier.AppendIf(member.IsStatic, MemberName.StaticModifier + " ");
identifier.AppendMemberBase(member, substitution, valueType, seenElements);
return identifier.ToString();
}
[NotNull]
private static ILocalVariableName GetName(this ITypeOwner variable,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
var identifier = new StringBuilder();
identifier.AppendType(variable.Type, seenElements).Append(' ').Append(variable.ShortName);
return Names.LocalVariable(identifier.ToString());
}
[NotNull]
private static IName GetName(this IAlias alias,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return Names.Alias(alias.ShortName);
}
[NotNull]
public static ILambdaName GetName([NotNull] this ILambdaExpression lambdaExpression)
{
var seen = new Dictionary<DeclaredElementInstance, IName>();
var identifier = new StringBuilder();
identifier.AppendType(lambdaExpression.ReturnType, seen);
identifier.Append(' ');
identifier.AppendParameters(lambdaExpression.DeclaredParametersOwner, EmptySubstitution.INSTANCE, seen);
return Names.Lambda(identifier.ToString());
}
[NotNull]
public static ILambdaName GetName([NotNull] this IAnonymousMethodExpression anonymousMethodDecl)
{
var seen = new Dictionary<DeclaredElementInstance, IName>();
var identifier = new StringBuilder();
identifier.AppendType(anonymousMethodDecl.ReturnType, seen);
identifier.Append(' ');
identifier.AppendParameters(anonymousMethodDecl.DeclaredParametersOwner, EmptySubstitution.INSTANCE, seen);
return Names.Lambda(identifier.ToString());
}
private static void AppendMemberBase(this StringBuilder identifier,
IClrDeclaredElement member,
ISubstitution substitution,
IType valueType,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
identifier.AppendType(valueType, seenElements);
identifier.Append(' ');
var containingType = member.GetContainingType();
identifier.AppendType(containingType, substitution, seenElements);
identifier.Append('.');
identifier.Append(member.ShortName);
}
private static StringBuilder AppendType(this StringBuilder identifier,
IType type,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return identifier.Append('[').Append(type.GetName(seenElements).Identifier).Append(']');
}
[NotNull]
private static StringBuilder AppendType(this StringBuilder identifier,
ITypeElement type,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return identifier.Append('[').Append(type.GetName(substitution, seenElements).Identifier).Append(']');
}
[NotNull]
private static string GetAssemblyQualifiedName(this ITypeElement type,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
if (type == null)
{
return Names.UnknownType.Identifier;
}
var clrTypeName = type.GetClrName();
var containingModule = type.Module.ContainingProjectModule;
Asserts.NotNull(containingModule, "module is null");
var moduleName = containingModule.GetQualifiedName();
var typeParameters = type.GetTypeParametersList(substitution, seenElements);
string myName;
var parent = type.GetContainingType();
var myFullName = clrTypeName.FullName;
if (parent != null)
{
var parentName = parent.GetName<ITypeName>(substitution);
// including the generic `N ticks
var parentFullName = parentName.FullName;
// shortName does not include the generic `N ticks, so we have to find it in the fullname...
var startOfShortName = myFullName.LastIndexOf("+", StringComparison.Ordinal) + 1;
// ... and ignore the leading part
var fullShortName = myFullName.Substring(startOfShortName);
myName = string.Format("{0}+{1}", parentFullName, fullShortName);
}
else
{
myName = myFullName;
}
return string.Format(
"{0}{1}, {2}",
myName,
typeParameters,
moduleName);
}
private static string GetTypeParametersList(this ITypeParametersOwner typeParametersOwner,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
if (typeParametersOwner.TypeParameters.IsEmpty())
{
return "";
}
var tps = new List<string>();
foreach (var tp in typeParametersOwner.TypeParameters)
{
var name = tp.GetName(substitution, seenElements);
tps.Add(name.Identifier);
}
return "[[{0}]]".FormatEx(tps.Join("],["));
}
/// <summary>
/// Retrieves the module's assembly-qualified name (including the assembly name and version). If the module
/// is a project returned name will only contain the project's name and not its version. According to
/// http://devnet.jetbrains.com/message/5503864#5503864 it is not generally possibly to retrieve the version
/// for projects. Therefore, we decided for this consistent solution.
/// </summary>
[NotNull]
public static string GetQualifiedName([NotNull] this IModule module)
{
AssemblyNameInfo assembly = null;
var containingAssembly = module as IAssembly;
if (containingAssembly != null)
{
assembly = containingAssembly.AssemblyName;
}
return assembly != null ? assembly.NameAndVersion() : SanitizeAssemblyName(module.Name);
}
[NotNull]
private static string NameAndVersion([NotNull] this AssemblyNameInfo assemblyName)
{
return string.Format("{0}, {1}", SanitizeAssemblyName(assemblyName.Name), assemblyName.Version);
}
public static string SanitizeAssemblyName(string input)
{
return Regex.Replace(input, "[^a-zA-Z0-9._-]", "_");
}
private static void AppendParameters(this StringBuilder identifier,
IParametersOwner parametersOwner,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
identifier.Append('(')
.Append(
parametersOwner.Parameters.GetNames(substitution, seenElements)
.Select(p => p.Identifier)
.Join(", "))
.Append(')');
}
[NotNull]
private static IEnumerable<IParameterName> GetNames(this IEnumerable<IParameter> parameters,
ISubstitution substitution,
IDictionary<DeclaredElementInstance, IName> seenElements)
{
return parameters.Select(param => param.GetName(substitution, seenElements));
}
}
} |
using Microsoft.AspNetCore.Authentication.OAuth;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace WaitingListBot.Web
{
public static class DiscordExtensions
{
public static async Task<Claim> GetGuildClaims(OAuthCreatingTicketContext context)
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://discordapp.com/api/users/@me/guilds");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None);
if (!response.IsSuccessStatusCode)
{
throw new Exception("failed to get guilds");
}
var payload = JArray.Parse(await response.Content.ReadAsStringAsync());
Claim claim = new("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/guilds", payload.ToString(), ClaimValueTypes.String);
return claim;
}
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;
namespace ResourcePackage
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", "1.0")]
[Guid(PackageGuidString)]
public sealed class ResourcePackage : AsyncPackage
{
public const string PackageGuidString = "5fdce33e-acee-47da-aaf1-c341d333bbb9";
protected override Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
=> base.InitializeAsync(cancellationToken, progress);
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System.Threading;
using System.Collections;
using System;
public class AIController
{
Faction faction;
AI_Turn_Thread AI_turn;
public bool done_AI_turn = false;
public AIController(Faction AI_faction)
{
faction = AI_faction;
AI_turn = new AI_Turn_Thread(faction, this);
}
public void Do_Turn()
{
// Create a thread to do the work for this turn
Debug.Log("Creating thread for enemy turn");
done_AI_turn = false;
Thread AI_thread = new Thread(new ThreadStart(AI_turn.Execute_AI_Turn));
AI_thread.Start();
}
}
public class AI_Turn_Thread
{
Faction faction;
AIController controller;
public AI_Turn_Thread(Faction cur_faction, AIController cur_controller)
{
faction = cur_faction;
controller = cur_controller;
}
public void Execute_AI_Turn()
{
controller.done_AI_turn = false;
// By this point, all units should have their movable tiles updated
// This AI will evaluate each tile the AI can move to, and pick the best one
List<Unit> units_needing_turns = new List<Unit>();
units_needing_turns.AddRange(faction.units);
foreach (Unit unit in units_needing_turns)
{
try
{
unit.attack_target = null;
Hex best_hex = unit.location; // Start off assuming where they are is the best location
if (!unit.has_moved && !unit.has_attacked)
{
//////// MOVING //////////
best_hex.hex_score = EvaluateHexScore(unit, best_hex);
// Evaluate every hex this unit can move to
foreach (Hex hex in unit.tiles_I_can_move_to)
{
hex.hex_score = EvaluateHexScore(unit, hex);
if (hex.hex_score > best_hex.hex_score)
best_hex = hex;
}
// We've gone through each hex. Move to that hex
unit.PathTo(best_hex);
}
if (!unit.has_attacked)
{
/////// ATTACKING ////////
// Now that we know where we're ending up, evaluate the best target we can attack from there
Unit target = null;
float best_target_score = 0;
int closest_distance = 999;
Unit closest_enemy = null;
foreach (Unit enemy in unit.owner.GetAllEnemyUnits())
{
//////// FACING ////////////
// Check if this is the closest enemy, so we can face towards them
int distance = HexMap.hex_map.DistanceBetweenHexes(unit.location.coordinate, enemy.location.coordinate);
if (distance < closest_distance)
{
// This is the closest enemy we've evaluated.
closest_enemy = enemy;
closest_distance = distance;
}
// Check if we're in range. If we're not in range, we can't attack the unit
if (distance <= unit.GetRange())
{
float cur_score = enemy.CalculateDamage(unit, best_hex) / 10;
if (cur_score > best_target_score)
{
// This is our best target to attack so far. Record it.
target = enemy;
best_target_score = cur_score;
}
}
}
// ROTATION
if (closest_enemy != null)
{
unit.SetDesiredRotationTowards(best_hex.world_coordinates, closest_enemy.location.world_coordinates);//??
}
// If there's a suitable target, have the unit attack it once it gets to the right hex
if (best_target_score > 0)
{
//Debug.Log(unit.u_name + " attacking " + target.u_name);
unit.attack_target = target;
}
}
}
catch (Exception e)
{ Debug.Log("Exception executing " + faction.faction_name + " " + unit.u_name + "'s turn: " + e.Message + e.StackTrace); }
// Wait until the unit is done moving before moving onto the next unit
// This is done so the collection of enemy units is not modified by others attacking and killing enemies while trying to evaluate them
if (unit.attack_target != null)
{
Thread.Sleep(500); // Have a delay after attacking to give the lists a chance to update
while (unit.is_moving)
{
Thread.Sleep(100);
}
}
}
Debug.Log("Finished AI turn");
controller.done_AI_turn = true;
//BattleManager.battle_manager.EndTurn(); //??
}
// Returns the value of this hex to the AI player. High value is good.
public float EvaluateHexScore(Unit unit, Hex hex)
{
// Add the bonuses this hex gives
float hex_score = hex.HexTerrainScoreForUnit(unit);
// Add score based on the damage we can do to enemies from this hex
hex_score += EnemyScoreOnHex(unit, hex);
// Add score based on the number of allies around this hex
hex_score += AllyScoreOnHex(unit, hex);
return hex_score;
}
// Check how much damage we can do to an enemy from this hex
public float EnemyScoreOnHex(Unit cur_unit, Hex hex)
{
float score = 0;
// Check if we can attack a unit from this hex
List<Hex> potential_targets = HexMap.hex_map.HexesWithinRangeContainingEnemies(hex, cur_unit.GetRange(), cur_unit.owner);
foreach (Hex target_hex in potential_targets)
{
score = Mathf.Max(score, target_hex.occupying_unit.CalculateDamage(cur_unit, target_hex));
// Increase the score of this hex if we can attack them without being counterattacked
if (cur_unit.attacks_are_counterable)
{
if (!target_hex.occupying_unit.counter_attacks || !target_hex.occupying_unit.IsFacing(hex)) //??
{
score *= cur_unit.flanking_factor;
}
}
}
// If we can't attack someone from this hex,
if ((score == 0 && cur_unit.owner.offensive_ai_score > 0) || cur_unit.GetRange() > 1)
{
float closest_enemy_distance = 100000;
// Find the closest enemy unit, and make this score higher the closer we are to it
foreach (Unit enemy in cur_unit.owner.GetAllEnemyUnits())
{
int dist = HexMap.hex_map.DistanceBetweenHexes(hex.coordinate, enemy.location.coordinate);
if (dist < closest_enemy_distance)
closest_enemy_distance = dist;
}
// Move towards enemies if we have no target
if (score == 0 && closest_enemy_distance < 100000)
score = (20f - closest_enemy_distance) / 2f;
// This section is for ranged units. They should move to their max range to stay away from enemy melee
// If the value is positive, that means that this unit is closer than this unit's range. We don't like that, so try to move to max range to stay alive
if (cur_unit.GetRange() > 1)
{
float distance_versus_range = closest_enemy_distance - cur_unit.GetRange();
if (distance_versus_range < 0)
{
score += distance_versus_range;
}
}
}
return score;
}
// See how many allies there are around this hex
public float AllyScoreOnHex(Unit cur_unit, Hex hex)
{
float score = 0;
if (cur_unit.ally_grouping_score > 0)
{
// Find all hexes with allies on them
List<Hex> potential_targets = HexMap.hex_map.HexesWithinRangeContainingAllies(hex, cur_unit.GetRange(), cur_unit.owner);
foreach (Hex target_hex in potential_targets)
{
if (target_hex.occupying_unit != cur_unit)
score += cur_unit.ally_grouping_score;
}
}
return score;
}
}
|
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace WF.SDK.Common
{
public class FFResult<T>
{
private Exception _exception = null;
private string _userString = "";
private string _url = "";
private string _warning = "";
private T _result;
public FFResult()
{
}
public FFResult(T result)
{
this._result = result;
}
public FFResult(Exception exception)
{
this._exception = exception;
}
public FFResult(T result, Exception exception)
{
this._result = result;
this._exception = exception;
}
public FFResult(T result, Exception exception, string warning)
{
this._result = result;
this._exception = exception;
this._warning = warning;
}
public FFResult(Exception exception, string warning)
{
this._exception = exception;
this._warning = warning;
}
/// <summary>
/// Optional. The operation did not return an error, but a warning is associated with
/// the operation.
/// </summary>
public string Warning
{
get { return this._warning; }
set { this._warning = value; }
}
/// <summary>
/// The error string to be presented to the user.
/// </summary>
public string UserString
{
get { return this._userString; }
set { this._userString = value; }
}
/// <summary>
/// The url that failed in the case of a web service call. Optional.
/// </summary>
public string Url
{
get { return this._url; }
set { this._url = value; }
}
/// <summary>
/// The result object of type <T>
/// </summary>
public T Result
{
get { return this._result; }
set { this._result = value; }
}
/// <summary>
/// An exception associated with the operation.
/// </summary>
public Exception Exception
{
get { return this._exception; }
set { this._exception = value; }
}
/// <summary>
/// Converts on result type to another. Leaves default(T) in the result field of the current object.
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public void ConvertFrom<U>(FFResult<U> result)
{
this._exception = result._exception;
this._url = result._url;
this._userString = result._userString;
this._warning = result._warning;
this._result = default(T);
}
/// <summary>
/// Get only. True if no exception ocurred.
/// </summary>
[XmlIgnore]
public bool Success
{
get { return this._exception == null; }
}
/// <summary>
/// Get only. Returns a boolean indicating if a warning is associated with the operation.
/// </summary>
[XmlIgnore]
public bool HasWarning
{
get { return this._warning != ""; }
}
/// <summary>
/// Get only. Returns a bool indicating if an exception ocurred.
/// </summary>
[XmlIgnore]
public bool Failure
{
get { return this._exception != null; }
}
}
}
|
namespace UmbracoMapperified.Tests.Handlers
{
using System.Linq;
using System.Web;
using Moq;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Profiling;
using Umbraco.Web;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
public abstract class BaseHandlerTests
{
public virtual void Initialize()
{
var applicationContext = new ApplicationContext(
CacheHelper.CreateDisabledCacheHelper(),
new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())
);
UmbracoContext.EnsureContext(
Mock.Of<HttpContextBase>(),
applicationContext,
new WebSecurity(Mock.Of<HttpContextBase>(), applicationContext),
Mock.Of<IUmbracoSettingsSection>(),
Enumerable.Empty<IUrlProvider>(),
true
);
}
}
}
|
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using StructLinq;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NetFabric.Hyperlinq.Benchmarks
{
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class ToArrayBenchmarks: RandomBenchmarksBase
{
[BenchmarkCategory("Array")]
[Benchmark(Baseline = true)]
public int[] Linq_Array()
=> Enumerable.ToArray(array);
[BenchmarkCategory("Enumerable_Value")]
[Benchmark(Baseline = true)]
public int[] Linq_Enumerable_Value()
=> Enumerable.ToArray(enumerableValue);
[BenchmarkCategory("Collection_Value")]
[Benchmark(Baseline = true)]
public int[] Linq_Collection_Value()
=> Enumerable.ToArray(collectionValue);
[BenchmarkCategory("List_Value")]
[Benchmark(Baseline = true)]
public int[] Linq_List_Value()
=> Enumerable.ToArray(listValue);
[BenchmarkCategory("Enumerable_Reference")]
[Benchmark(Baseline = true)]
public int[] Linq_Enumerable_Reference()
=> Enumerable.ToArray(enumerableReference);
[BenchmarkCategory("Collection_Reference")]
[Benchmark(Baseline = true)]
public int[] Linq_Collection_Reference()
=> Enumerable.ToArray(collectionReference);
[BenchmarkCategory("List_Reference")]
[Benchmark(Baseline = true)]
public int[] Linq_List_Reference()
=> Enumerable.ToArray(listReference);
// ---------------------------------------------------------------------
[BenchmarkCategory("Array")]
[Benchmark]
public int[] StructLinq_Array()
=> array
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("Enumerable_Value")]
[Benchmark]
public int[] StructLinq_Enumerable_Value()
=> enumerableValue
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("Collection_Value")]
[Benchmark]
public int[] StructLinq_Collection_Value()
=> collectionValue
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("List_Value")]
[Benchmark]
public int[] StructLinq_List_Value()
=> listValue
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("Enumerable_Reference")]
[Benchmark]
public int[] StructLinq_Enumerable_Reference()
=> enumerableReference
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("Collection_Reference")]
[Benchmark]
public int[] StructLinq_Collection_Reference()
=> collectionReference
.ToStructEnumerable()
.ToArray(x => x);
[BenchmarkCategory("List_Reference")]
[Benchmark]
public int[] StructLinq_List_Reference()
=> listReference
.ToStructEnumerable()
.ToArray(x => x);
// ---------------------------------------------------------------------
[BenchmarkCategory("Array")]
[Benchmark]
public int[] Hyperlinq_Array()
=> array
.ToArray();
[BenchmarkCategory("Array")]
[Benchmark]
public int[] Hyperlinq_Span()
=> array.AsSpan()
.ToArray();
[BenchmarkCategory("Array")]
[Benchmark]
public int[] Hyperlinq_Memory()
=> memory
.ToArray();
[BenchmarkCategory("Enumerable_Value")]
[Benchmark]
public int[] Hyperlinq_Enumerable_Value()
=> EnumerableExtensions.AsValueEnumerable<TestEnumerable.Enumerable, TestEnumerable.Enumerable.Enumerator, int>(enumerableValue, enumerable => enumerable.GetEnumerator())
.ToArray();
[BenchmarkCategory("Collection_Value")]
[Benchmark]
public int[] Hyperlinq_Collection_Value()
=> ReadOnlyCollectionExtensions.AsValueEnumerable<TestCollection.Enumerable, TestCollection.Enumerable.Enumerator, int>(collectionValue, enumerable => enumerable.GetEnumerator())
.ToArray();
[BenchmarkCategory("List_Value")]
[Benchmark]
public int[] Hyperlinq_List_Value()
=> listValue
.AsValueEnumerable()
.ToArray();
[BenchmarkCategory("AsyncEnumerable_Value")]
[Benchmark]
public ValueTask<int[]> Hyperlinq_AsyncEnumerable_Value()
=> asyncEnumerableValue
.AsAsyncValueEnumerable<TestAsyncEnumerable.Enumerable, TestAsyncEnumerable.Enumerable.Enumerator, int>((enumerable, cancellationToke) => enumerable.GetAsyncEnumerator(cancellationToke))
.ToArrayAsync();
[BenchmarkCategory("Enumerable_Reference")]
[Benchmark]
public int[] Hyperlinq_Enumerable_Reference()
=> enumerableReference
.AsValueEnumerable()
.ToArray();
[BenchmarkCategory("Collection_Reference")]
[Benchmark]
public int[] Hyperlinq_Collection_Reference()
=> collectionReference
.AsValueEnumerable()
.ToArray();
[BenchmarkCategory("List_Reference")]
[Benchmark]
public int[] Hyperlinq_List_Reference()
=> listReference
.AsValueEnumerable()
.ToArray();
[BenchmarkCategory("AsyncEnumerable_Reference")]
[Benchmark]
public ValueTask<int[]> Hyperlinq_AsyncEnumerable_Reference()
=> asyncEnumerableReference
.AsAsyncValueEnumerable()
.ToArrayAsync();
}
}
|
// Author(s): Ryder Roth, Jack Hael, Shaira Alam
// Date: 10/11/2020
// Description: forms a query based off of the given factors,
// then sends it to google bigquery and assembles the data into
// an array list of statedatas and returns the size of that list.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Google.Cloud.BigQuery.V2;
using Google.Apis.Auth;
//using UnityEditor.PackageManager;
using System.Data.SqlTypes;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices.WindowsRuntime;
using Google.Apis.Auth.OAuth2;
/*
SELECT
date,
country_code,
subregion1_name,
location_geometry,
-- case/death count
cumulative_confirmed,
cumulative_deceased,
new_confirmed,
new_deceased
FROM
bigquery-public -data.covid19_open_data.covid19_open_data
WHERE
date > "2020-09-01" --last day with 0 COVID was "2020-01-18" (potential start date)
--AND date < "2020-09-30" --could comment out if we just want from start date to end of value
-- subregion1_code IS NULL --US value only
AND subregion2_code IS NULL --state values only
AND country_code = "US"
AND cumulative_deceased IS NOT NULL --doesn't print anythign that doesn't have data
ORDER BY
date;
*/
public class DataGrabber
{
private String projectCode, //code to access the project, also called project key
source, //what we are using from googles query
table, //table we are getting from
subtable; //subtable that we need to grab the data from within our table
private String[] select = new String[10]; //commas to separate selects
private String[] where = new String[10]; //if more than one where, AND to separate each where
int getDataSize = 0;
//constructor
public DataGrabber(String projectCode, String source, String table, String subtable)
{
this.projectCode = projectCode;
this.source = source;
this.table = table;
this.subtable = subtable;
//initialize arrays to null
for(int i = 0; i < 10; i++)
{
this.select[i] = "";
}
for (int i = 0; i < 10; i++)
{
this.where[i] = "";
}
}
//add data that we want to receive
public bool AddSelect(String select)
{
for(int i = 0; i < 10; i++)
{
if(this.select[i].CompareTo("") == 0) // look for first empty value
{
this.select[i] = select;
return true; //successful select parameter added
}
}
return false; //parameter not added
}
//add data parameters from what we want to specify
public bool AddWhere(String where)
{
for(int i = 0; i < 10; i++)
{
if(this.where[i].CompareTo("") == 0) // look for first empty value
{
this.where[i] = where;
return true; //successful select parameter added
}
}
return false; //parameter not added
}
//forms the query
public String FormQuery()
{
String query = "";
query += "SELECT\n";
if(this.select[0].CompareTo("") != 0)
{
query += this.select[0];
int i = 1;
while( i < 10 && this.select[i].CompareTo("") != 0) //start at index 1, b/c 0 was filled
{
query += ", \n" + this.select[i];
i++;
}
query += "\n";
}
query += "FROM\n";
query += this.source + "." + this.table + "." + this.subtable;
query += "\n";
query += "WHERE\n";
if(this.where[0].CompareTo("") != 0)
{
query += where[0];
int i = 1;
while(i < 10 && this.where[i].CompareTo("") != 0) //start at index 1, b/c 0 was filled
{
query += "\nAND\n";
query += this.where[i];
i++;
}
}
return query;
}
//Method to send query and get response and then assemble the response.
public ArrayList GetData()
{
ArrayList tempArray = new ArrayList();
try
{
//tempArray.Add(System.IO.Directory.GetCurrentDirectory());
//var credentials = GoogleCredential.FromFile("./Assets/Scripts/Additional/authKey.json");
//var credentials = GoogleCredential.FromFile("/Additional/authkey.json");
var credentials = GoogleCredential.FromJson("Not Today");
BigQueryClient ourClient = BigQueryClient.Create(projectCode, credentials);
String query = this.FormQuery();
Debug.Log(query);
BigQueryResults results = ourClient.ExecuteQuery(query, parameters: null);
ArrayList stateData = new ArrayList();
StateData currentState = new StateData();
foreach (BigQueryRow row in results)
{
String date = Convert.ToString(row["date"]);
String country = Convert.ToString(row["country_code"]);
String state = Convert.ToString(row["subregion1_name"]);
String coordinates = Convert.ToString(row["location_geometry"]);
int confirmedCases = Convert.ToInt32(row["cumulative_confirmed"]);
int deceased = Convert.ToInt32(row["cumulative_deceased"]);
if (currentState.IsValidInsertion(state))
{
currentState.AddRow(country, state, coordinates, date, confirmedCases, deceased);
}
else
{
stateData.Add(currentState);
currentState = new StateData();
currentState.AddRow(country, state, coordinates, date, confirmedCases, deceased);
getDataSize++;
}
}
Debug.Log("Made it to data");
return stateData;
}catch(Exception e)
{
tempArray.Add(e.ToString());
return tempArray;
}
}
//returns the size of the ArrayList GetData returns.
public int GetDataSize()
{
return getDataSize;
}
// example of outputting the data to console
// Console.WriteLine($"Name: {row["player"]}; Score: {row["score"]}; Level: {row["level"]}");
}
|
using System;
using System.Collections.Generic;
using System.Text;
using MisMarcadores.Data.Entities;
namespace MisMarcadores.Logic
{
public class FixtureLiga : Fixture
{
private readonly DateTime fechaInicio;
private readonly List<Equipo> equipos;
public FixtureLiga(DateTime fechaInicio, List<Equipo> equipos)
{
this.fechaInicio = fechaInicio;
this.equipos = equipos;
}
public override List<Encuentro> GenerarFixture()
{
List<Encuentro> encuentros = new List<Encuentro>();
int fechaEncuentro = 0;
for (int i = 0; i < equipos.Count; i++)
{
for (int j = 0; j < equipos.Count; j++)
{
if (i != j)
{
Encuentro encuentro = new Encuentro
{
EquipoLocal = equipos[i],
EquipoVisitante = equipos[j],
FechaHora = fechaInicio.AddDays(fechaEncuentro)
};
encuentros.Add(encuentro);
fechaEncuentro += 3;
}
}
}
return encuentros;
}
}
}
|
using System;
using HacktoberfestProject.Web.Tools;
using Xunit;
namespace HacktoberfestProject.Tests.Tools
{
public class NullCheckerTests
{
#region Fields
private static readonly object _nullValue = null;
private static readonly object _nonNullValue = new object();
#endregion
[Fact]
public void IsNotNull_WithArgumentValueNull_ShouldThrowArgumentNullException()
{
var exception = Assert.Throws<ArgumentNullException>(() => NullChecker.IsNotNull(_nullValue, nameof(_nullValue)));
Assert.Equal(nameof(_nullValue), exception.ParamName);
}
[Fact]
public void IsNotNull_WithArgumentValueNotNull_ShouldNotThrowArgumentNullException()
{
NullChecker.IsNotNull(_nonNullValue, nameof(_nonNullValue));
//The fact the testcase was executed up until here means it was successful
}
}
}
|
using Zhouli.DAL.Interface;
using Zhouli.DbEntity.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.Extensions.Configuration;
namespace Zhouli.DAL.Implements
{
public class SysMenuDAL : BaseDAL<SysMenu>, ISysMenuDAL
{
public SysMenuDAL(ZhouLiContext db, IDbConnection dbConnection) : base(db, dbConnection)
{
}
}
}
|
// Copyright (C) 2017 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distribukted 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.Linq;
using DynaJson;
using ExpressionToCodeLib;
using KancolleSniffer.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace KancolleSniffer.Test
{
[TestClass]
public class BattleBriefTest
{
private ItemMaster _itemMaster;
private ItemInventory _itemInventory;
private ItemInfo _itemInfo;
private ShipMaster _shipMaster;
private ShipInventory _shipInventory;
private ShipInfo _shipInfo;
private BattleInfo _battleInfo;
private string[] ReadAllLines(string log)
{
using (var logfile = SnifferTest.OpenLogFile(log))
return logfile.ReadToEnd().Split(new[] {"\r\n"}, StringSplitOptions.None);
}
private void InjectShips(dynamic battle, dynamic item)
{
var deck = (int)battle.api_deck_id - 1;
InjectShips(deck, (int[])battle.api_f_nowhps, (int[])battle.api_f_maxhps, (int[][])item[0]);
if (battle.api_f_nowhps_combined())
InjectShips(1, (int[])battle.api_f_nowhps_combined, (int[])battle.api_f_maxhps_combined,
(int[][])item[1]);
foreach (var enemy in (int[])battle.api_ship_ke)
_shipMaster.InjectSpec(enemy);
if (battle.api_ship_ke_combined())
{
foreach (var enemy in (int[])battle.api_ship_ke_combined)
_shipMaster.InjectSpec(enemy);
}
_itemInfo.InjectItems(((int[][])battle.api_eSlot).SelectMany(x => x));
if (battle.api_eSlot_combined())
_itemInfo.InjectItems(((int[][])battle.api_eSlot_combined).SelectMany(x => x));
}
private void InjectShips(int deck, int[] nowHps, int[] maxHps, int[][] slots)
{
var id = _shipInventory.MaxId + 1;
var ships = nowHps.Zip(maxHps,
(now, max) => new ShipStatus {Id = id++, NowHp = now, MaxHp = max}).ToArray();
_shipInventory.Add(ships);
_shipInfo.Fleets[deck].Deck = (from ship in ships select ship.Id).ToArray();
foreach (var entry in ships.Zip(slots, (ship, slot) => new {ship, slot}))
{
entry.ship.Slot = _itemInfo.InjectItems(entry.slot.Take(5));
if (entry.slot.Length >= 6)
entry.ship.SlotEx = _itemInfo.InjectItems(entry.slot.Skip(5)).First();
}
}
[TestInitialize]
public void Initialize()
{
_itemMaster = new ItemMaster();
_itemInventory = new ItemInventory();
_itemInfo = new ItemInfo(_itemMaster, _itemInventory);
_shipInventory = new ShipInventory();
_shipMaster = new ShipMaster();
_shipInfo = new ShipInfo(_shipMaster, _shipInventory, _itemInventory);
_battleInfo = new BattleInfo(_shipInfo, _itemInfo, new AirBase(_itemInfo));
}
/// <summary>
/// 連撃を受けて女神が発動する
/// </summary>
[TestMethod]
public void CauseRepairGoddessByDoubleAttack()
{
var logs = ReadAllLines("damecon_001");
var items = JsonObject.Parse("[[[],[],[],[],[43]]]");
dynamic battle = JsonObject.Parse(logs[2]);
InjectShips(battle, items);
_battleInfo.InspectBattle(logs[0], logs[1], battle);
dynamic result = JsonObject.Parse(logs[5]);
_battleInfo.InspectBattleResult(result);
PAssert.That(() => _shipInfo.Fleets[2].Ships[4].NowHp == 31);
}
/// <summary>
/// 夜戦で戦艦の攻撃を受ける
/// </summary>
[TestMethod]
public void AttackedByBattleShipInMidnight()
{
var logs = ReadAllLines("midnight_002");
var battle = JsonObject.Parse(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(JsonObject.Parse(logs[6]));
PAssert.That(() => _shipInfo.Fleets[0].Ships[3].NowHp == 12);
}
private dynamic Data(string json) => JsonObject.Parse(json).api_data;
/// <summary>
/// NPC友軍の支援攻撃がある
/// </summary>
[TestMethod]
public void NpcFriendFleetAttack()
{
var logs = ReadAllLines("friendfleet_001");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattle(logs[4], logs[5], Data(logs[6]));
_battleInfo.InspectBattleResult(Data(logs[9]));
PAssert.That(() => !_battleInfo.DisplayedResultRank.IsError);
}
/// <summary>
/// 空襲戦で轟沈する
/// </summary>
[TestMethod]
public void LdAirBattleHaveSunkenShip()
{
var logs = ReadAllLines("ld_airbattle_001");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(Data(logs[6]));
PAssert.That(() => !_battleInfo.DisplayedResultRank.IsError);
}
/// <summary>
/// 空襲戦で女神が発動して復活する
/// </summary>
[TestMethod]
public void LdAirBattleHaveRevivedShip()
{
var logs = ReadAllLines("ld_airbattle_002");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(Data(logs[6]));
PAssert.That(() => !_battleInfo.DisplayedResultRank.IsError);
}
/// <summary>
/// 機動対敵連合の雷撃戦でダメコンが発動する
/// </summary>
[TestMethod]
public void TorpedoTriggerDameConInCombinedBattleAir()
{
var logs = ReadAllLines("damecon_002");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattle(logs[4], logs[5], Data(logs[6]));
_battleInfo.InspectBattleResult(Data(logs[9]));
PAssert.That(() => !_battleInfo.DisplayedResultRank.IsError);
}
/// <summary>
/// 水上対敵連合の雷撃戦でダメコンが発動する
/// </summary>
[TestMethod]
public void TorpedoTriggerDamageControlInCombinedBattleWater()
{
var logs = ReadAllLines("damecon_003");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(Data(logs[6]));
PAssert.That(() => _shipInfo.Fleets[1].Ships[5].NowHp == 6);
}
/// <summary>
/// 護衛退避艦がいるときに勝利判定がずれる
/// </summary>
[TestMethod]
public void WrongResultRankWithEscapedShip()
{
var logs = ReadAllLines("escape_rank_001");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(Data(logs[6]));
PAssert.That(() => !_battleInfo.DisplayedResultRank.IsError);
}
/// <summary>
/// 第一艦隊で単艦退避する
/// </summary>
[TestMethod]
public void EscapeWithoutEscortInFirstFleet()
{
var logs = ReadAllLines("escape_003");
var battle = Data(logs[3]);
InjectShips(battle, JsonObject.Parse(logs[0]));
_battleInfo.InspectBattle(logs[1], logs[2], battle);
_battleInfo.InspectBattleResult(Data(logs[6]));
_battleInfo.CauseEscape();
PAssert.That(() => _shipInfo.Fleets[0].Ships[5].Escaped);
}
}
} |
using Microsoft.AspNetCore.Identity;
namespace RealTimeApp.Models
{
public class User : IdentityUser {
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Image_processing.Processing
{
public abstract class Process : IProcessing, IDrawing
{
protected int[] processData;
public Process()
{
processData = new int[256];
}
public abstract void Draw(Bitmap bitmap, int delta);
public virtual void Processing(Bitmap bitmap, int x, int y)
{
if (x >= bitmap.Width || y >= bitmap.Height) return;
Color color = bitmap.GetPixel(x, y);
int R = color.R;
int G = color.G;
int B = color.B;
R = FindValue(R);
G = FindValue(G);
B = FindValue(B);
bitmap.SetPixel(x, y, Color.FromArgb(R, G, B));
}
private int FindValue(int x)
{
return processData[x];
}
}
}
|
namespace Alfheim.GUI.Model
{
public enum QualityPreset
{
Low,
High
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Type : MonoBehaviour
{
public int State;
public ParticleSystem fire_Effect;
public ParticleSystem water_Effect;
public ParticleSystem void_Effect;
public ParticleSystem wind_Effect;
public ParticleSystem earth_Effect;
// Start is called before the first frame update
void Start()
{
switch (State)
{
case 0:
GetComponent<Renderer>().material.color = new Color(1f, 0.5f, 0.5f, 0.5f);
break;
case 1:
GetComponent<Renderer>().material.color = Color.cyan;
gameObject.tag = "water";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("WaterAttack");
break;
case 2:
GetComponent<Renderer>().material.color = Color.green;
gameObject.tag = "earth";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("EarthAttack");
break;
case 3:
GetComponent<Renderer>().material.color = new Color(0.5f, 0.5f, 0.5f, 0.5f);
gameObject.tag = "air";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("AirAttack");
break;
case 4:
GetComponent<Renderer>().material.color = Color.red;
gameObject.tag = "fire";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("FireAttack");
break;
case 5:
GetComponent<Renderer>().material.color = Color.yellow;
gameObject.tag = "electric";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("ElectricAttack");
break;
case 6:
GetComponent<Renderer>().material.color = Color.magenta;
gameObject.tag = "void";
FindObjectOfType<Audio>().GetComponent<Audio>().Play("VoidAttack");
break;
}
}
// Update is called once per frame
void Update()
{
if(State == 4)
{
var fire_efx = Instantiate(fire_Effect, gameObject.transform.position, Quaternion.identity);
fire_efx.transform.parent = gameObject.transform;
}
if(State == 1)
{
var water_efx = Instantiate(water_Effect, gameObject.transform.position, Quaternion.identity);
water_efx.transform.parent = gameObject.transform;
}
if(State == 6)
{
var void_efx = Instantiate(void_Effect, gameObject.transform.position, Quaternion.identity);
void_efx.transform.parent = gameObject.transform;
}
if(State == 3)
{
var wind_efx = Instantiate(wind_Effect, gameObject.transform.position, Quaternion.identity);
wind_efx.transform.parent = gameObject.transform;
}
if(State == 2)
{
var earth_vfx = Instantiate(earth_Effect, gameObject.transform.position, Quaternion.identity);
earth_vfx.transform.parent = gameObject.transform;
}
}
}
|
using System.Data;
namespace BLL.SYSTEM
{
public class UserBLL
{
DAL.SYSTEM.UserDAL dal = new DAL.SYSTEM.UserDAL();
#region 查询职务列表
/// <summary>
/// 查询人员列表
/// </summary>
/// <param name="PageNo">页数</param>
/// <param name="PageSize">每页显示数量</param>
/// <param name="strWhere">条件</param>
/// <returns></returns>
public DataSet GetList(int PageNo, int PageSize, string UserName, string deptid, string strAuthDataScope)
{
string swhere = "";
//加权限控制
if (!string.IsNullOrEmpty(strAuthDataScope) && strAuthDataScope != "all")//all表示管理员的数据范围
{
swhere += " and Users.UserID in (" + strAuthDataScope + ") ";
}
if (!string.IsNullOrEmpty(UserName))
{
swhere += " and UserName like '%" + UserName + "%' and primaryDept=1 ";
}
if (!string.IsNullOrEmpty(deptid) && string.IsNullOrEmpty(UserName))
{
swhere += " and deptid='" + deptid + "' ";
}
return dal.GetList(PageNo, PageSize, swhere);
}
#endregion
#region 判断是否存在
public bool Exist(string LoginCode)
{
return dal.Exist(LoginCode);
}
public bool Exist(string LoginCode, string UserID)
{
return dal.Exist(LoginCode, UserID);
}
#endregion
#region 根据用户和部门,返回权限内的用户
/// <summary>
/// 根据用户和部门,返回权限内的用户
/// </summary>
/// <param name="PageNo"></param>
/// <param name="PageSize"></param>
/// <param name="usercode"></param>
/// <param name="deptid"></param>
/// <returns></returns>
public DataSet GetDataTable(int PageNo, int PageSize, string usercode, string deptid)
{
string swhere = "";
//加权限控制
//if (usercode != "admin")
//{
// swhere += " and pid in (select typeID from dbo.PositionORstationDept where typeCode='POSITION' AND deptid='') ";
//}
if (usercode.Trim() != "")
{
swhere += " and logincode like '%" + usercode + "%' ";
}
return dal.GetList(PageNo, PageSize, swhere);
}
#endregion
#region 插入用户信息
/// <summary>
/// 插入用户信息
/// </summary>
/// <param name="model"></param>
/// <param name="relation"></param>
/// <returns></returns>
public int Insert(MODEL.SYSTEM.UserModel model)
{
return dal.Insert(model);
}
#endregion
#region 返回用户信息
/// <summary>
/// 返回用户信息
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public DataSet GetDataSet(string userid)
{
return dal.GetDataSet(userid);
}
#endregion
/// <summary>
/// 根据指定的删除条件删除对应的记录
/// </summary>
/// <param name="condition">删除条件</param>
/// <returns></returns>
public int Delete(string condition)
{
return dal.Delete(condition);
} // Delete
#region 修改用户信息
/// <summary>
/// 修改用户信息
/// </summary>
/// <param name="model"></param>
/// <param name="txtRelation"></param>
/// <returns></returns>
public int Update(MODEL.SYSTEM.UserModel model)
{
return dal.Update(model);
}
#endregion
#region 根据用户ID返回用户的信息
/// <summary>
/// 根据用户ID返回用户的信息
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public DataTable GetDataTable(string userid)
{
return dal.GetDataTable(userid);
}
#endregion
#region 修改所有人密码
/// <summary>
/// 修改所有人密码
/// </summary>
/// <param name="pwd"></param>
/// <returns></returns>
public int Update(string pwd)
{
return dal.Update(pwd);
}
#endregion
#region 返回用户信息列表
/// <summary>
/// 返回用户信息列表
/// </summary>
/// <returns></returns>
public DataTable GetDataTable()
{
return dal.GetDataTable();
}
#endregion
#region 返回用户信息列表
/// <summary>
/// 返回用户信息列表
/// </summary>
/// <returns></returns>
public DataTable GetDataTableByDept()
{
return dal.GetDataTableByDept();
}
#endregion
#region 根据用户ID获取相关信息
public DataTable GetDataTableByUserID(int userID)
{
return dal.GetDataTableByUserID(userID);
}
#endregion
#region 根据用户ID获取相关信息,逗号隔开
public DataTable GetDataTableByUserIDs(string userIDs)
{
return dal.GetDataTableByWhere(" and userid in (" + userIDs + ") ");
}
#endregion
#region 根据用户ID获取人事信息
public DataTable GetDataTableDossier(int UserID)
{
return dal.GetDataTableDossier(UserID);
}
#endregion
#region 修改人事信息
public int UpdateDossier(MODEL.SYSTEM.UserModel model)
{
return dal.UpdateDossier(model);
}
#endregion
#region 取出所有删除的用户数据
/// <summary>
/// 取出所有删除的用户数据
/// </summary>
/// <param name="userids"></param>
/// <param name="deptids"></param>
/// <param name="begintime"></param>
/// <param name="endtime"></param>
/// <param name="pageno"></param>
/// <param name="pagesize"></param>
/// <param name="condition"></param>
/// <returns></returns>
public DataSet GetAllData(string userids, string deptids, string begintime, string endtime, int pageno, int pagesize, string condition, string selectcolumns)
{
string swhere = "";
if (condition.Trim() != "")
{
swhere += " and UserName like '%" + condition + "%' ";
}
return dal.GetAllData(pageno, pagesize, swhere, selectcolumns);
}
#endregion
#region 彻底的删除数据
/// <summary>
/// 彻底的删除数据
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public int DeleteUser(string ids)
{
return dal.DeleteUser(ids);
}
#endregion
#region
/// <summary>
/// 恢复删除的用户
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public int Restore(string ids)
{
return dal.Restore(ids);
}
#endregion
}
}
|
using DateTimeExtensions;
using FastSQL.Core;
using FastSQL.Sync.Core.Enums;
using FastSQL.Sync.Core.Models;
using FastSQL.Sync.Core.Repositories;
using Serilog;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
namespace FastSQL.Sync.Workflow.Steps
{
public abstract class BaseStepBodyInvoker : StepBody
{
public ResolverFactory ResolverFactory { get; set; }
public BaseStepBodyInvoker()
{
}
public abstract Task Invoke(IStepExecutionContext context = null);
public override ExecutionResult Run(IStepExecutionContext context)
{
Task runner = null;
var logger = ResolverFactory.Resolve<ILogger>("SyncService");
var errorLogger = ResolverFactory.Resolve<ILogger>("Error");
try
{
runner = Invoke(context);
runner?.Wait();
}
catch (Exception ex)
{
errorLogger.Error(ex, ex.Message);
using (var messageRepository = ResolverFactory.Resolve<MessageRepository>())
{
messageRepository.Create(new
{
CreatedAt = DateTime.Now.ToUnixTimestamp(),
Message = runner?.Exception != null ? runner.Exception.ToString() : ex.ToString(),
MessageType = MessageType.Exception,
Status = MessageStatus.None
});
if (ex.InnerException != null)
{
errorLogger.Error(ex.InnerException, ex.InnerException.Message);
messageRepository.Create(new
{
CreatedAt = DateTime.Now.ToUnixTimestamp(),
Message = ex.InnerException.ToString(),
MessageType = MessageType.Exception,
Status = MessageStatus.None
});
}
}
}
finally
{
ResolverFactory.Release(logger);
ResolverFactory.Release(errorLogger);
logger = null;
errorLogger = null;
runner?.Dispose();
}
return ExecutionResult.Next();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace dbupdate
{
class Program
{
static void Main(string[] args)
{
DBConnect conn = new DBConnect();
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"..\voicepong\LyricsData.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string id = null, artist = null, title = null, lyrics = null, sql = null;
int cFaults = 0;
for (int i = 1; i <= rowCount; i++)
{
//write the value to the console
if (xlRange.Cells[i, 1] != null && xlRange.Cells[i, 1].Value2 != null)
id = xlRange.Cells[i, 1].Value2.ToString();
if (xlRange.Cells[i, 2] != null && xlRange.Cells[i, 2].Value2 != null)
artist = xlRange.Cells[i, 2].Value2.ToString();
if (xlRange.Cells[i, 3] != null && xlRange.Cells[i, 3].Value2 != null)
title = xlRange.Cells[i, 3].Value2.ToString();
if (xlRange.Cells[i, 4] != null && xlRange.Cells[i, 4].Value2 != null)
lyrics = xlRange.Cells[i, 4].Value2.ToString();
if (id != null && artist != null && title != null && lyrics != null && i > 27)
{
sql = "INSERT INTO `Songs` VALUES('" + id + "', \"" + artist + "\", \"" + title + "\", \"" + lyrics + "\")";
try
{
conn.NonQuery(sql);
}
catch(Exception ex)
{
Console.WriteLine("Could not parse id:" + id);
cFaults++;
}
}
}
Console.WriteLine("Ended with " + cFaults + " faults.");
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TesteC_Sharp.Model
{
public sealed class Enumerators
{
public enum SaleStatus
{
sold,
rejectedByMinValue
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace API.Models
{
public partial class Acesso
{
[JsonProperty("idAcesso", Required = Required.Always)]
public int IdAcesso { get; set; }
[JsonProperty("DescricaoAcesso", Required = Required.Always)]
public string DescricaoAcesso { get; set; }
[JsonProperty("NomeAcesso", Required = Required.Always)]
public int NomeAcesso { get; set; }
}
} |
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using JetBrains.Application;
using JetBrains.Application.ActivityTrackingNew;
using JetBrains.Application.Threading;
using KaVE.Commons.Model.Events;
using KaVE.Commons.Utils;
using KaVE.JetBrains.Annotations;
using KaVE.VS.Commons;
using KaVE.VS.Commons.Generators;
namespace KaVE.VS.FeedbackGenerator.Generators.ReSharper
{
[ShellComponent]
internal class ActionEventGenerator : EventGeneratorBase, IActivityTracking
{
public ActionEventGenerator([NotNull] IRSEnv env,
[NotNull] IMessageBus messageBus,
[NotNull] IDateUtils dateUtils,
[NotNull] IThreading threading)
: base(env, messageBus, dateUtils, threading) { }
public void TrackAction(string actionId)
{
FireActionEvent(actionId);
}
public void TrackActivity(string activityGroup, string activityId, int count = 1)
{
FireActionEvent(string.Format("{0}:{1}:{2}", activityGroup, count, activityId));
}
protected void FireActionEvent(string actionId)
{
var actionEvent = Create<CommandEvent>();
actionEvent.CommandId = actionId;
Fire(actionEvent);
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Claytondus.Square.Models;
namespace Claytondus.Square
{
/// <summary>
/// Square Connect Modifier List Management API
/// </summary>
public class SquareModifierListClient : SquareClient
{
private readonly string _locationId;
/// <summary>
/// Instantiate a client for accessing Square modifier lists.
/// </summary>
/// <param name="authToken">Merchant OAuth token or personal access token.</param>
/// <param name="locationId">
/// Your Square-issued location ID, if you've obtained it from another endpoint.
/// If you haven't, specify me for the Connect API to automatically determine your location ID based on your request's access token.
/// </param>
public SquareModifierListClient(string authToken, string locationId = "me") : base(authToken)
{
_locationId = locationId;
}
/// <summary>
/// Creates an item modifier list and at least one modifier option for it.
/// Required permissions: ITEMS_WRITE
/// </summary>
/// <returns cref="SquareModifierList">Item object that represents the updated item.</returns>
/// <exception cref="SquareException">Error returned from Square Connect.</exception>
public async Task<SquareModifierList> CreateModifierListAsync(SquareModifierList list)
{
return await PostAsync<SquareModifierList>("/v1/" + _locationId + "/modifier-lists", list);
}
public async Task<SquareResponse<List<SquareModifierList>>> ListModifierListsAsync()
{
return await GetAsync<List<SquareModifierList>>("/v1/" + _locationId + "/modifier-lists");
}
public async Task<SquareResponse<SquareModifierList>> RetrieveModifierListAsync(string modifierListId)
{
return await GetAsync<SquareModifierList>("/v1/" + _locationId + "/modifier-lists/" + modifierListId);
}
public async Task DeleteModifierListAsync(string modifierListId)
{
await DeleteAsync<string>("/v1/" + _locationId + "/modifier-lists/" + modifierListId);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using Infnet.Engesoft.SysBank.Model.Contratos;
using Infnet.Engesoft.SysBank.Model.Provider;
namespace Infnet.Engesoft.SysBank.Model.Dominio
{
public class TransacoesBancariasRepository : IRepository<TransacoesBancarias>
{
private List<TransacoesBancarias> _operacoes;
public TransacoesBancariasRepository()
{
var tb = new ProviderTransacoesBancarias();
_operacoes = tb.ObterTodos();
}
public IList<TransacoesBancarias> ObterTodos()
{
return _operacoes;
}
public List<TransacoesBancarias> ObterListaPorMes(ContaCorrente conta, int mes, int ano)
{
return _operacoes.Where(operacao => (operacao._dataOperacao.Month == mes) && (operacao._dataOperacao.Year == ano) && (operacao._conta.Numero == conta.Numero)).ToList();
}
public List<TransacoesBancarias> ObterListaPorContaCorrente(ContaCorrente conta)
{
//List<TransacoesBancarias> listaOperacoes = new List<TransacoesBancarias>();
//foreach (TransacoesBancarias operacao in _operacoes)
//{
// if (operacao._conta.Numero == conta.Numero)
// {
// listaOperacoes.Add(operacao);
// }
//}
//return listaOperacoes;
return _operacoes.Where(operacao => operacao._conta.Numero == conta.Numero).ToList();
}
public void Gravar(TransacoesBancarias operacao)
{
_operacoes.Add(operacao);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerStats : MonoBehaviour
{
public int playerHP;
public int keyFragments;
public GameObject[] hearts;
public GameObject[] fragments;
private void Update()
{
if(playerHP >= 3)
{
playerHP = 3;
for(int i = 0; i < hearts.Length; i++)
{
hearts[i].SetActive(true);
}
}
else if(playerHP == 2)
{
hearts[playerHP].SetActive(false);
hearts[playerHP-1].SetActive(true);
}
else if(playerHP == 1)
{
hearts[playerHP].SetActive(false);
hearts[playerHP - 1].SetActive(true);
}
else if( playerHP <= 0)
{
StartCoroutine("gameOver");
}
if(keyFragments > 0)
{
fragments[keyFragments - 1].SetActive(true);
}
}
IEnumerator gameOver()
{
yield return null;
}
public void YouWin()
{
StartCoroutine("youWin");
}
IEnumerator youWin()
{
yield return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPiaoBao.AppServices.Contracts.DomesticTicket;
using BPiaoBao.AppServices.DataContracts;
using BPiaoBao.AppServices.DataContracts.DomesticTicket;
using BPiaoBao.Common;
using BPiaoBao.DomesticTicket.Domain.Models.FrePasser;
using JoveZhao.Framework.DDD;
using StructureMap;
namespace BPiaoBao.AppServices.DomesticTicket
{
public class FrePasserService : BaseService, IFrePasserService
{
IUnitOfWork unitOfWork = ObjectFactory.GetNamedInstance<IUnitOfWork>(EnumModule.DomesticTicket.ToString());
IUnitOfWorkRepository unitOfWorkRepository = ObjectFactory.GetNamedInstance<IUnitOfWorkRepository>(EnumModule.DomesticTicket.ToString());
IFrePasserRepository _frePasserRepository;
private string _code = AuthManager.GetCurrentUser().Code;
public FrePasserService(IFrePasserRepository frePasserRepository)
{
this._frePasserRepository = frePasserRepository;
}
public void SaveFrePasser(FrePasserDto passer)
{
var builder = AggregationFactory.CreateBuiler<FrePasserBuilder>();
var frePasser = builder.CreateFrePasser();
frePasser.PasserType = passer.PasserType;
frePasser.Name = passer.Name.Trim();
frePasser.CertificateType = passer.CertificateType;
frePasser.CertificateNo = passer.CertificateNo;
frePasser.Mobile = passer.Mobile;
frePasser.AirCardNo = passer.AirCardNo;
frePasser.Remark = passer.Remark;
frePasser.Birth = passer.Birth;
frePasser.SexType = passer.SexType;
frePasser.BusinessmanCode = _code;
unitOfWorkRepository.PersistCreationOf(frePasser);
unitOfWork.Commit();
}
[ExtOperationInterceptor("更新常旅客信息")]
public void UpdateFrePasser(FrePasserDto passer)
{
var frePasser = this._frePasserRepository.FindAll(p => p.Id == passer.Id).FirstOrDefault();
frePasser.PasserType = passer.PasserType;
frePasser.Name = passer.Name;
frePasser.CertificateType = passer.CertificateType;
frePasser.CertificateNo = passer.CertificateNo;
frePasser.Mobile = passer.Mobile;
frePasser.AirCardNo = passer.AirCardNo;
frePasser.Remark = passer.Remark;
frePasser.Birth = passer.Birth;
frePasser.SexType = passer.SexType;
frePasser.BusinessmanCode = _code;
unitOfWorkRepository.PersistUpdateOf(frePasser);
unitOfWork.Commit();
}
[ExtOperationInterceptor("删除常旅客信息")]
public void DeleteFrePasser(int id)
{
var passer = this._frePasserRepository.FindAll(p => p.Id == id).FirstOrDefault();
unitOfWorkRepository.PersistDeletionOf(passer);
unitOfWork.Commit();
}
[ExtOperationInterceptor("查询常旅客信息列表")]
public DataPack<FrePasserDto> QueryFrePassers(QueryFrePasser queryDto, int pageIndex, int pageSize)
{
pageIndex = (pageIndex - 1) * pageSize;
var query = this._frePasserRepository.FindAll(p => p.BusinessmanCode == _code);
if (queryDto != null)
{
if (!string.IsNullOrEmpty(queryDto.Name))
{
query = query.Where(p => p.Name.Trim().Equals(queryDto.Name.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.AirCardNo))
{
query = query.Where(p => p.AirCardNo.Trim().Equals(queryDto.AirCardNo.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.CertificateNo))
{
query = query.Where(p => p.CertificateNo.Trim().Equals(queryDto.CertificateNo.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.CertificateType))
{
query = query.Where(p => p.CertificateType.Trim().Equals(queryDto.CertificateType.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.PasserType))
{
//手机端接口传递参数
switch (queryDto.PasserType)
{
case "1":
query = query.Where(p => p.PasserType.Trim().Equals("成人", StringComparison.OrdinalIgnoreCase));
break;
default:
query = query.Where(p => p.PasserType.Trim().Equals(queryDto.PasserType.Trim(), StringComparison.OrdinalIgnoreCase));
break;
}
}
if (!string.IsNullOrEmpty(queryDto.Mobile))
{
query = query.Where(p => p.Mobile.Trim().Equals(queryDto.Mobile.Trim(), StringComparison.OrdinalIgnoreCase));
}
}
query = query.OrderByDescending(p => p.Id);
//var list = query.Skip(pageIndex).Take(pageSize).ToList();
List<FrePasser> list = new List<FrePasser>();
if (pageSize > 0)
list = query.Skip(pageIndex).Take(pageSize).ToList();
else
list = query.ToList();
var dataPack = new DataPack<FrePasserDto>
{
TotalCount = query.Count(),
List = AutoMapper.Mapper.Map<List<FrePasser>, List<FrePasserDto>>(list)
};
return dataPack;
}
[ExtOperationInterceptor("判断常旅客信息是否存在")]
public bool Exists(string name, string certificateNo)
{
var query = this._frePasserRepository.FindAll(p => p.BusinessmanCode == _code);
query = query.Where(p => p.Name == name && p.CertificateNo == certificateNo);
return query.Any();
}
[ExtOperationInterceptor("根据名称查询常旅客")]
public List<FrePasserDto> Query(string name)
{
var query = this._frePasserRepository.FindAll(p => p.BusinessmanCode == _code);
query = from pass in query where pass.Name.Contains(name) select pass;
var list = AutoMapper.Mapper.Map<List<FrePasser>, List<FrePasserDto>>(query.ToList());
return list;
}
[ExtOperationInterceptor("导入常旅客信息")]
public void Import(List<FrePasserDto> list)
{
foreach (var m in list)
{
DeleteByName(m.Name.Trim(), m.CertificateNo.Trim());
SaveFrePasser(m);
}
}
[ExtOperationInterceptor("导出常旅客信息")]
public List<FrePasserDto> Export(QueryFrePasser queryDto)
{
var query = this._frePasserRepository.FindAll(p => p.BusinessmanCode == _code);
if (queryDto != null)
{
if (!string.IsNullOrEmpty(queryDto.Name))
{
query = query.Where(p => p.Name.Trim().Equals(queryDto.Name.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.AirCardNo))
{
query = query.Where(p => p.AirCardNo.Trim().Equals(queryDto.AirCardNo.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.CertificateNo))
{
query = query.Where(p => p.CertificateNo.Trim().Equals(queryDto.CertificateNo.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.CertificateType))
{
query = query.Where(p => p.CertificateType.Trim().Equals(queryDto.CertificateType.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.PasserType))
{
query = query.Where(p => p.PasserType.Trim().Equals(queryDto.PasserType.Trim(), StringComparison.OrdinalIgnoreCase));
}
if (!string.IsNullOrEmpty(queryDto.Mobile))
{
query = query.Where(p => p.Mobile.Trim().Equals(queryDto.Mobile.Trim(), StringComparison.OrdinalIgnoreCase));
}
}
query = query.OrderByDescending(p => p.Id);
var list = AutoMapper.Mapper.Map<List<FrePasser>, List<FrePasserDto>>(query.ToList());
return list;
}
private void DeleteByName(string name, string cardid)
{
if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(cardid))
{
return;
}
var model = this._frePasserRepository.FindAll(p => p.BusinessmanCode == _code && p.Name == name && p.CertificateNo == cardid).FirstOrDefault();
if (model != null)
{
DeleteFrePasser(model.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SKT.WMS.WMSBasicfile.BLL;
using SKT.WMS.WMSBasicfile.Model;
namespace SKT.MES.Web.WMSBasicfile
{
public partial class WMSPositionPrintList : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Boolean hasSearchSettings = false;
hasSearchSettings = (this.txtWhInfo.Text.Trim() != "" || this.hdnWhID.Value.ToString()!="") ? true : false;
if (hasSearchSettings)
{
this.Master.SetSearchSettings = true;
this.Master.PageGridView = this.GridView1;
this.GridView1.DataSourceID = this.ObjectDataSource1.ID;
this.Master.PageObjectDataSource = this.ObjectDataSource1;
this.Master.RecordIDField = "Id";
this.Master.DefaultSortExpression = "Id";
this.Master.DefaultSortDirection = SortDirection.Ascending;
SKT.MES.Model.SearchSettings searchSettings = new SKT.MES.Model.SearchSettings();
//searchSettings.AddCondition("WMSWarehouseId", Request.Form["hdnWhID"].ToString());
searchSettings.ExtensionCondition = "[WMSWarehouseId] = '" + this.hdnWhID.Value.ToString() + "'";
this.Master.SearchSettings = searchSettings;
this.GridView1.PageIndex = 0;
}
else
{
this.Master.SetSearchSettings = false;
}
if (Request.Form["hdnOperate"].ToLower() == "delete")
{
SKT.WMS.WMSBasicfile.BLL.WMSPosition bll = new SKT.WMS.WMSBasicfile.BLL.WMSPosition();
bll.Delete(Request.Form["hdnIdString"].ToString(), AccountController.GetCurrentUser().LoginID);
WebHelper.ShowMessage(Resources.Messages.DeleteSuccess);
}
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//e.Row.Cells[10].Text = "aa";
e.Row.Cells[5].Text = (Convert.ToString(e.Row.Cells[5].Text.Trim()) == "S") ? (String)this.GetGlobalResourceObject("Pages", "wmsInventoryPropertyS") : (String)this.GetGlobalResourceObject("Pages", "wmsInventoryPropertyW");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENTITY;
using Openmiracle.BLL;
using Openmiracle.DAL;
using System.Data;
namespace Openmiracle.BLL
{
public class PaymentDetailsBll
{
PaymentDetailsInfo infoPaymentDetails = new PaymentDetailsInfo();
PaymentDetailsSP spPaymentDetails = new PaymentDetailsSP();
/// <summary>
///
/// </summary>
/// <param name="paymentdetailsinfo"></param>
/// <returns></returns>
public decimal PaymentDetailsAdd(PaymentDetailsInfo paymentdetailsinfo)
{
decimal decResult = 0;
try
{
decResult = spPaymentDetails.PaymentDetailsAdd(paymentdetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("PD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decResult;
}
/// <summary>
///
/// </summary>
/// <param name="PaymentDetailsId"></param>
public void PaymentDetailsDelete(decimal PaymentDetailsId)
{
try
{
spPaymentDetails.PaymentDetailsDelete(PaymentDetailsId);
}
catch (Exception ex)
{
MessageBox.Show("PD2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
///
/// </summary>
/// <param name="paymentdetailsinfo"></param>
/// <returns></returns>
public decimal PaymentDetailsEdit(PaymentDetailsInfo paymentdetailsinfo)
{
decimal decResult = 0;
try
{
decResult = spPaymentDetails.PaymentDetailsEdit(paymentdetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("PD3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decResult;
}
/// <summary>
///
/// </summary>
/// <param name="paymentMastertId"></param>
/// <returns></returns>
public List<DataTable> PaymentDetailsViewByMasterId(decimal paymentMastertId)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = spPaymentDetails.PaymentDetailsViewByMasterId(paymentMastertId);
}
catch (Exception ex)
{
MessageBox.Show("PD4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
}
}
|
using DFe.Classes.Flags;
using DFe.Utils;
using MDFe.Utils.Configuracoes;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Custom;
using PDV.DAO.DB.Utils;
using PDV.DAO.Entidades;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace PDV.CONTROLLER.MDFE.Configuracao
{
public class ConfigMDFe
{
public static void PreencheConfiguracao(string CaminhoSchemas)
{
Emitente _emitente = FuncoesEmitente.GetEmitente();
var configuracaoCertificado = new ConfiguracaoCertificado() { Serial = new X509Certificate2(_emitente.Certificado, Criptografia.DecodificaSenha(_emitente.SenhaCertificado)).GetSerialNumberString() };
MDFeConfiguracao.ConfiguracaoCertificado = configuracaoCertificado;
MDFeConfiguracao.CaminhoSchemas = CaminhoSchemas;
MDFeConfiguracao.IsSalvarXml = false;
MDFeConfiguracao.VersaoWebService.VersaoLayout = MDFe.Utils.Flags.VersaoServico.Versao300;
MDFeConfiguracao.VersaoWebService.TipoAmbiente = "1".Equals(Encoding.UTF8.GetString(FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_NFCE_WEBSERVICE_AMBIENTE_PRODUCAO).Valor)) ? TipoAmbiente.Producao : TipoAmbiente.Homologacao;
MDFeConfiguracao.VersaoWebService.UfEmitente = (DFe.Classes.Entidades.Estado)Enum.Parse(typeof(DFe.Classes.Entidades.Estado), FuncoesEmitente.GetUnidadeFederativaPorEmitente().Sigla);
string TimeOut = Encoding.UTF8.GetString(FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_NFCE_PROTOCOLO_SEGURANCA_TIMEOUT).Valor);
MDFeConfiguracao.VersaoWebService.TimeOut = string.IsNullOrEmpty(TimeOut) ? 3000 : Convert.ToInt32(TimeOut);
}
public static bool IsExibirCaixaDialogo()
{
DAO.Entidades.Configuracao config = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGUACAODANFE_EXIBIRCAIXADIALOGO_MDFE);
if (config == null)
return true;
return "1".Equals(Encoding.UTF8.GetString(config.Valor));
}
public static string GetNomeImpressora()
{
DAO.Entidades.Configuracao config = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGUACAODANFE_NOMEIMPRESSORA_MDFE);
if (config == null)
return null;
return Encoding.UTF8.GetString(config.Valor);
}
}
}
|
using System;
using System.IO;
using System.Security.Cryptography;
namespace FillFile
{
public class Variables
{
public bool? IsRandom { get; set; }
public int FileLength { get; set; }
public string FileName { get; set; }
}
class Program
{
private static string version = "1.0.0";
static void Main(string[] args)
{
try
{
Variables v = ParseArgs(args);
if (v.IsRandom != null)
{
Console.WriteLine("FillFile " + version);
if ((bool)v.IsRandom)
{
Console.WriteLine("Creating Random Filled File...");
File.WriteAllBytes(v.FileName, CreateRandomFilledFile(v.FileLength));
}
else
{
Console.WriteLine("Creating Zero Filled File...");
File.WriteAllBytes(v.FileName, CreateZeroFilledFile(v.FileLength));
}
}
else
Terminate("Invalid input parameters.");
}
catch
{
Terminate("Input parameters incorrect");
}
Console.WriteLine("File Created.");
}
private static Variables ParseArgs(string[] args)
{
//FillFile -z 512 -o FileName
//FillFile -r 512 -o FileName
//FillFile -h
Variables v = new Variables();
if (args.Length == 4 || args.Length == 1)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-z")
{
v.IsRandom = false;
v.FileLength = int.Parse(args[i + 1]);
i++;
}
if (args[i] == "-r")
{
v.IsRandom = true;
v.FileLength = int.Parse(args[i + 1]);
i++;
}
if (args[i] == "-o")
{
v.FileName = args[i + 1];
i++;
}
if (args[i] == "-h" || args[i] == "-help")
{
Console.WriteLine("FillFile " + version);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("To create a zero filled file:");
Console.WriteLine("FillFile -z 512 -o FileName");
Console.WriteLine("To create a random filled file:");
Console.WriteLine("FillFile -r 512 -o FileName");
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Parameters:");
Console.WriteLine("-h - Display help");
Console.WriteLine("-o (Filename) - Output file name");
Console.WriteLine("-r (length) - Random filled file of a given length in bytes");
Console.WriteLine("-z (length) - Zero filled file of a given length in bytes");
Environment.Exit(0);
}
}
}
else
{
Terminate("Invalid number of parameters.");
}
return v;
}
private static byte[] CreateZeroFilledFile(int length)
{
return new byte[length];
}
private static byte[] CreateRandomFilledFile(int length)
{
byte[] rnd = new byte[length];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(rnd);
return rnd;
}
private static void Terminate(string message)
{
Console.WriteLine("FillFile " + version);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(message);
Console.WriteLine("Incorrect usage. Please type 'FillFile -h' for help.");
Environment.Exit(0);
}
}
}
|
using System;
namespace HCL.Academy.Model
{
public class OnboardingHelp
{
public string title { get; set; }
public string description { get; set; }
public Int32 orderingId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NetCode.Synchronisers.Entities
{
internal class SyncDynamicEntity : Synchroniser
{
protected SynchronisableEntity Entity;
protected EntityDescriptorCache Cache;
public SyncDynamicEntity(EntityDescriptorCache descriptorCache)
{
Cache = descriptorCache;
}
public sealed override object GetValue()
{
return Entity?.GetValue();
}
public sealed override bool ContainsRevision(uint revision)
{
// Note, revision must also change on deletion/creation for stability.
if (Revision < revision)
{
return false;
}
else if (Revision == revision)
{
return true;
}
else if (Entity != null)
{
return Entity.ContainsRevision(revision);
}
return false;
}
public sealed override void SetSynchonised(bool sync)
{
Synchronised = sync;
Entity?.SetSynchonised(sync);
}
public sealed override void UpdateReferences(SyncContext context)
{
if (Entity != null)
{
Entity.UpdateReferences(context);
ReferencesPending = Entity.ReferencesPending;
}
else
{
ReferencesPending = false;
}
}
private void GenerateNewEntity(RuntimeTypeHandle newType, uint revision)
{
Entity = Cache.GetEntityFactory(newType).ConstructNewEntity(0);
Revision = revision;
Synchronised = false;
ReferencesPending = false;
}
private void GenerateNewEntity(ushort typeID, uint revision)
{
Entity = Cache.GetEntityFactory(typeID).ConstructNewEntity(0);
Revision = revision;
Synchronised = false;
ReferencesPending = false;
}
private void ClearEntity(uint revision)
{
Revision = revision;
Entity = null;
Synchronised = false;
ReferencesPending = false;
}
public override bool TrackChanges(object newValue, SyncContext context)
{
bool changesFound = false;
if (Entity == null)
{
if (newValue == null)
{
return false;
}
else
{
RuntimeTypeHandle newType = newValue.GetType().TypeHandle;
GenerateNewEntity(newType, context.Revision);
changesFound = true;
}
}
else if (Entity.Value != newValue)
{
if (newValue == null)
{
changesFound = true;
ClearEntity(context.Revision);
}
else
{
RuntimeTypeHandle newType = newValue.GetType().TypeHandle;
if (!Entity.TypeMatches(newType))
{
changesFound = true;
GenerateNewEntity(newType, context.Revision);
}
}
}
if (Entity != null)
{
if (Entity.TrackChanges(newValue, context))
{
changesFound = true;
Synchronised &= Entity.Synchronised;
Revision = context.Revision;
}
}
return changesFound;
}
public sealed override void WriteToBuffer(NetBuffer buffer, SyncContext context)
{
if (Entity == null)
{
buffer.WriteVWidth(EntityDescriptor.NullTypeID);
}
else
{
buffer.WriteVWidth(Entity.TypeID);
Entity.WriteToBuffer(buffer, context);
}
}
public sealed override void WriteToBuffer(NetBuffer buffer)
{
if (Entity == null)
{
buffer.WriteVWidth(EntityDescriptor.NullTypeID);
}
else
{
buffer.WriteVWidth(Entity.TypeID);
Entity.WriteToBuffer(buffer);
}
}
public sealed override int WriteToBufferSize(uint revision)
{
if (Entity == null)
{
return NetBuffer.SizeofVWidth(EntityDescriptor.NullTypeID);
}
else
{
int size = NetBuffer.SizeofVWidth(Entity.TypeID);
size += Entity.WriteToBufferSize(revision);
return size;
}
}
public sealed override int WriteToBufferSize()
{
if (Entity == null)
{
return NetBuffer.SizeofVWidth(EntityDescriptor.NullTypeID);
}
else
{
int size = NetBuffer.SizeofVWidth(Entity.TypeID);
size += Entity.WriteToBufferSize();
return size;
}
}
public sealed override void ReadFromBuffer(NetBuffer buffer, SyncContext context)
{
ushort typeID = buffer.ReadVWidth();
if (context.Revision > Revision)
{
if (typeID == EntityDescriptor.NullTypeID)
{
if (Entity != null)
{
ClearEntity(context.Revision);
}
}
else if (Entity == null || Entity.TypeID != typeID)
{
GenerateNewEntity(typeID, context.Revision);
}
if (Entity != null)
{
Entity.ReadFromBuffer(buffer, context);
Synchronised &= Entity.Synchronised;
ReferencesPending |= Entity.ReferencesPending;
Revision = context.Revision;
}
}
else
{
bool skip = Entity == null || Entity.TypeID != typeID;
if (skip)
{
if (typeID != EntityDescriptor.NullTypeID)
{
Cache.GetEntityFactory(typeID).SkipFromBuffer(buffer);
}
}
else
{
Entity.ReadFromBuffer(buffer, context);
Synchronised &= Entity.Synchronised;
ReferencesPending |= Entity.ReferencesPending;
Revision = context.Revision;
}
}
}
public sealed override void SkipFromBuffer(NetBuffer buffer)
{
ushort typeID = buffer.ReadVWidth();
if (typeID != EntityDescriptor.NullTypeID)
{
Cache.GetEntityFactory(typeID).SkipFromBuffer(buffer);
}
}
}
}
|
using APINet.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace APINet.Api
{
/// <summary>
/// Class to buld api request url.
/// </summary>
public class ApiRequestBuilder
{
private readonly string _baseUrl;
private readonly Dictionary<string, string> _arguments = new Dictionary<string, string>();
public IEnumerable<string> Arguments
{
get { return _arguments.Keys.AsEnumerable(); }
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiRequestBuilder"/> class.
/// </summary>
/// <param name="baseUrl">The base URL.</param>
/// <param name="arguments">The argument names.</param>
public ApiRequestBuilder(string baseUrl, IEnumerable<string> arguments)
{
_baseUrl = baseUrl;
foreach (var s in arguments)
_arguments.Add(s, string.Empty);
}
/// <summary>
/// Sets an argument value if it exists.
/// </summary>
/// <param name="argument">The argument.</param>
/// <param name="value">The argument's value.</param>
public void SetArgumentValue(string argument, string value)
{
if (_arguments.ContainsKey(argument))
_arguments[argument] = value;
}
/// <summary>
/// Gets the built search url.
/// </summary>
/// <returns>System.String</returns>
public string SearchUrl()
{
var sb = new StringBuilder();
sb.Append(_baseUrl);
if (_arguments.Count > 0)
sb.UrlAppend(_arguments.ElementAt(0));
for (var i = 1; i < _arguments.Count; i++)
{
sb.UrlAndAppend(_arguments.ElementAt(i));
}
return sb.ToString();
}
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Waffles;
using Waffles.UserControls;
public partial class admin_modals_template : AdminModal
{
public override void Build ()
{
DataOutput = new WDataOutput();
Modal = new WAdminModal();
bool new_list = ActionID == "new";
Modal.FormAction = "/_admin/list-save";
Modal.Body.Append(@"
<div class='alert alert-danger required-message' style='display: none;'>
<p><i class='fa fa-asterisk'></i> Please fill in all required fields.</p>
</div>
<div class='alert alert-danger list-title-exists' style='display: none;'>
<p><i class='fa fa-exclamation-sign'></i> A list with the name <a href='' class='text-danger' target='_blank'>'<span></span>'</a> already exists.</p>
</div>" +
new WHTML.FieldSet(
/*class*/ "title",
/*id*/ "title",
/*title*/ "Title",
/*required*/ true,
/*input*/ new WInput(WInputType.text, "Title", "Title", List == null ? "" : List.Title, true, "", " data-validate='list_title'"),
/*description*/ "")
);
List<string> values = new List<string>(new string[] { SPListTemplateType.GenericList.ToString() });
StringBuilder settings = new StringBuilder(), fields = new StringBuilder();
fields.Append("<template class='field'>" + list_edit_field("@#random#", null, null) + "</template>");
Dictionary<string, string> fields_type = new Dictionary<string, string>();
if (!new_list)
{
values[0] = List.BaseTemplate.ToString();
if (List.Title != "Pages")
Modal.Label.Append("<a class='wack show-list-data' href='#'></a><a href='#/list-view/" + WList.slug + "'>" +
List.Title + "</a> <i class='fa fa-angle-right'></i> " + "Edit List");
fields.Append(list_edit_field(WRandom.String(10), List.Fields.GetFieldByInternalName("Title")));
List<string> ignore_fields = new List<string>(new string[] { "Title", "Slug", "Workspace", "WorkspaceLink" });
if (List.BaseTemplate == SPListTemplateType.Events)
{
ignore_fields.AddRange(new string[]{
"EventDate",
"EndDate",
"fAllDayEvent",
"fRecurrence",
"EventType",
"UID",
"RecurrenceID",
"EventCanceled",
"Duration",
"RecurrenceData",
"TimeZone",
"XMLTZone",
"MasterSeriesItemID"
});
}
SPContentType content_type = WContext.GetDefaultContentType(List);
foreach (SPFieldLink fieldLink in content_type.FieldLinks)
{
SPField field = List.Fields[fieldLink.Id];
fields_type.Add(field.InternalName, (string)new WList(field.ParentList).field_data(field)["type"]);
if (ignore_fields.Contains(field.InternalName))
continue;
fields.Append(list_edit_field(WRandom.String(10), field));
}
Modal.ButtonsRight.Add(new WHTML.Button("Save", "save", "list-save/" + WList.slug, "btn-primary", "", true));
// Modal.ButtonsLeft.Add(new WHTML.Button("Save Debug", "save", "list-save/" + WList.slug + "/debug", "btn-primary", "", true));
}
else
{
Modal.Label.Append("New List");
fields.Append(list_edit_field(WRandom.String(10), WContext.Current.SP.Site.RootWeb.Lists["Pages"].Fields["Title"]));
Modal.ButtonsRight.Add(new WHTML.Button("Save", "save", "list-save", "btn-primary", "", true));
Modal.ButtonsRight.Add(new WHTML.Button("All Lists", "arrow-left", "#/lists-view", "", "", false));
}
// list properties
if (WContext.Current.User.IsSiteAdmin || (List != null &&
List.DoesUserHavePermissions(WContext.Current.User, SPBasePermissions.ManageLists)))
{
WList = new WList(List);
Dictionary<string, object> listData = WList.Data;
DataOutput.Add("listData", listData);
Dictionary<string, object[]> listPropertyFields = WAdmin.ListPropertyFields(WList);
string field_toggle = null;
bool is_w_list = List != null && List.RootFolder != null && List.RootFolder.Name.StartsWith("w_");
foreach (object[] field in listPropertyFields.Values)
{
string
name = (string)field[0],
title = (string)field[1],
description = (string)field[2],
toggle = (string)field[4],
fieldsetClass = "field-" + name.Replace("_", "-"),
inputAttributes = "",
inputClass = "";
WInputType
type = (WInputType)field[3];
object
value = listData.ContainsKey(name) ? listData[name] : null;
if ((WInputType)type == WInputType.boolean && value != null && value.GetType() != typeof(bool))
{
bool value_bool = false;
bool.TryParse(value.ToString(), out value_bool);
value = value_bool;
}
Dictionary<string, object> extras =
field.Length > 5 && field[5] != null && field[5].GetType() == typeof(Dictionary<string, object>) ? (Dictionary<string, object>)field[5] : null;
if (field.Length > 6)
value = field[6];
if (name == "plural_title" || name == "singular_title")
inputAttributes += " disabled";
if (toggle != null && toggle != "toggle")
fieldsetClass += listData.ContainsKey(toggle) && listData[toggle].GetType() == typeof(bool) &&
(bool)listData[toggle] ? "" : " hide";
if (name == "slug")
{
if (is_w_list)
{
inputClass += " disabled";
inputAttributes += " disabled";
value = List.RootFolder.Name;
}
else
{
inputAttributes += " data-validate='list_slug'";
settings.Append(@"
<div class='alert alert-danger slug-exists' style='display: none;'>
<p><i class='fa fa-exclamation-sign'></i> This slug <a href='' target='_blank'>already exists</a>.</p>
</div>");
}
}
string fieldset = new WHTML.FieldSet(
/*class*/ fieldsetClass,
/*id*/ "field_" + name,
/*title*/ title,
/*required*/ false,
/*input*/ new WInput(type, title, "___" + name, value, false, new Dictionary<string, string>(), inputClass, inputAttributes + " id='field_" + name + "'", extras),
/*description*/ description
);
if (toggle != null)
fieldset = fieldset.Replace("<fieldset ", toggle == "toggle" ?
"<fieldset data-toggle='" + name.Replace("_", "-") + "' " :
"<fieldset data-toggled='" + toggle.Replace("_", "-") + "' ");
settings.Append(fieldset);
}
if (field_toggle != null)
settings.AppendFormat("</div>");
}
Dictionary<string, string> options = new Dictionary<string, string>();
options.Add("Custom List", SPListTemplateType.GenericList.ToString());
options.Add("Events", SPListTemplateType.Events.ToString());
options.Add("Library", SPListTemplateType.DocumentLibrary.ToString());
if (!options.ContainsValue(values[0]))
{
values[0] = "other";
options.Add("Other", "other");
}
settings.Insert(0, new WHTML.FieldSet(
/*class*/ "list-type",
/*id*/ "list_type",
/*title*/ "List Type",
/*required*/ true,
/*input*/ new WInput(WInputType.select, "List Type", "list_type", values[0], true, options, "", (new_list ? "" : " disabled")),
/*description*/ "<span class='text-danger'>List type can not be changed once the list has been created.</span>"
));
if (!new_list)
settings.Append("<p><a href='#/list-delete/" + WList.slug + "' class='btn btn-danger'><i class='fa fa-trash-o'></i> Delete List</a></p>");
Modal.Body.AppendFormat(
edit_list_html.Text,
Web.ID,
List == null ? "" : List.ID + "",
settings,
"<div class='panel-group' id='fields-panel-group'>" + fields + "</div>"
);
Dictionary<string, string>
existing_list_titles = new Dictionary<string, string>(),
existing_web_slugs = new Dictionary<string, string>();
foreach (SPList _list in Web.Lists)
{
existing_list_titles.Add(_list.Title, "#/list-view/" + _list.RootFolder.Name);
existing_web_slugs.Add(_list.RootFolder.Name, "#/list-view/" + _list.RootFolder.Name);
}
foreach (SPFolder Folder in Web.RootFolder.SubFolders)
if (!existing_web_slugs.ContainsKey(Folder.Name))
existing_web_slugs.Add(Folder.Name, Folder.ServerRelativeUrl);
if (!new_list && List != null)
{
existing_list_titles.Remove(List.Title);
existing_web_slugs.Remove(List.RootFolder.Name);
}
Modal.Script.Append(ModalScript.Text
.Replace("'existing_list_titles'", WContext.Serialize(existing_list_titles))
.Replace("'fields_type'", WContext.Serialize(fields_type))
.Replace("'existing_web_slugs'", WContext.Serialize(existing_web_slugs))
);
}
public string list_edit_field(string random, SPField field)
{
return list_edit_field(random, field, null);
}
public string list_edit_field(string random, SPField field, Dictionary<string, object> _data)
{
string
internalName = "",
description = "",
guid = "",
title = "",
attachType = "",
lookup_webs = WAdmin.lookup_web_options(WContext.Current.SP.Site.RootWeb.ID, Guid.Empty),
lookup_lists = WAdmin.lookup_list_options(WContext.Current.SP.Site.RootWeb.ID, Guid.Empty),
type_options = @"
<option value='Text'>Single line of text</option>
<option value='Note'>Multiple lines of text</option>
<option value='Email'>Email</option>
<option value='AttachAssets'>Attach Assets</option>
<option value='Choice'>Choice</option>
<option value='Number'>Number</option>
<option value='DateTime'>Date and Time</option>
<option value='Date'>Date</option>
<option value='Time'>Time</option>
<option value='Lookup'>Lookup</option>
<option value='Boolean'>Yes/No</option>
<option value='Icons'>Icons</option>
<option value='Tags'>Tags</option>
<option value='Choices'>Choices</option>",
attachType_options = @"
<option value='images'>Images</option>
<option value='documents'>Documents</option>",
booleanDefault_options = "<option value='1'>Yes</option><option value='0'>No</option>",
choiceDefault = "",
textDefault = "",
numberDefault = ""
;
bool
required = false,
richText = false,
locked = false,
field_title_disabled = false,
type_disabled = false,
required_disabled = false;
object minimum = null, maximum = null;
string[] choices_array = new string[] { };
WFieldType field_type = WFieldType.Text;
string field_type_value = "";
Dictionary<string, string>
replacements = new Dictionary<string, string>();
if (field != null)
{
if (field.InternalName == "ContentType")
return "";
_data = _data ?? new WList(field.ParentList).field_data(field);
internalName = field.InternalName;
required = field.Required || internalName == "Title" || internalName == "Slug";
title = field.Title;
guid = field.Id.ToString();
field_type = WField.GetWFieldType(field, _data);
field_type_value = field_type.ToString();
required = required || field.Type == SPFieldType.AllDayEvent || field.Type == SPFieldType.Recurrence;
if (_data.ContainsKey("editFormat") && _data["editFormat"] != null)
replacements.Add(
"_editFormat' type='radio' value='" + _data["editFormat"] + "'",
"_editFormat' type='radio' value='" + _data["editFormat"] + "' checked");
if (field_type == WFieldType.AttachAssets)
{
if (_data["attachType"] != null)
attachType_options = attachType_options.Replace(
"'" + _data["attachType"] + "'",
"'" + _data["attachType"] + "' selected"
);
}
else if (field.Type == SPFieldType.Boolean && field.DefaultValue != null)
{
booleanDefault_options = booleanDefault_options.Replace(field.DefaultValue + "'", field.DefaultValue + "' selected");
}
else if (field_type.ToString().StartsWith("Choice_"))
{
field_type_value = "Choice";
try
{
StringCollection fieldChoices = ((SPFieldMultiChoice)field).Choices;
choices_array = new string[fieldChoices.Count];
fieldChoices.CopyTo(choices_array, 0);
choiceDefault = field.DefaultValue;
}
catch { }
}
else if (field_type.ToString().StartsWith("Lookup_"))
{
field_type_value = "Lookup";
SPFieldLookup fieldLookup = (SPFieldLookup)field;
lookup_webs = WAdmin.lookup_web_options(WContext.Current.SP.Site.RootWeb.ID, fieldLookup.LookupWebId);
lookup_lists = WAdmin.lookup_list_options(fieldLookup.LookupWebId, new Guid(fieldLookup.LookupList));
}
else if (field.Type == SPFieldType.Number)
{
minimum = ((SPFieldNumber)field).MinimumValue;
maximum = ((SPFieldNumber)field).MaximumValue;
numberDefault = field.DefaultValue;
}
else if (field.Type == SPFieldType.Text)
textDefault = field.DefaultValue;
else if (field.Type == SPFieldType.AllDayEvent || field.Type == SPFieldType.Recurrence)
{
type_options = "<option value='Boolean' selected>Yes/No</option>";
}
if (field.InternalName == "Title")
{
locked = true;
type_disabled = true;
required_disabled = true;
description = description.Insert(0, "<div class='col-xs-12 text-danger'>The title field type and requirement cannot be changed.</div>");
}
richText = field.Type == SPFieldType.Note && ((SPFieldMultiLineText)field).RichTextMode == SPRichTextMode.FullHtml;
type_options = type_options.Replace("value='" + field_type_value + "'", "value='" + field_type_value + "' selected");
}
else if (field == null)
{
title = "New Field";
field_type = WFieldType.Text;
}
if (minimum != null)
replacements.Add("_minimum' value=''", "_minimum' value='" + minimum + "'");
if (maximum != null)
replacements.Add("_maximum' value=''", "_maximum' value='" + maximum + "'");
if (richText)
replacements.Add("_richText'", "_richText' checked");
replacements.Add("_displayName'", internalName == "Slug" ? "_displayName' disabled" : "_displayName'");
replacements.Add("{{css_class}}", (!locked
? " sortable" : " locked") + (required ? " required" : "") + (field != null && field.Hidden ? " field-hidden" : ""));
replacements.Add("{{choiceDefault}}", choiceDefault);
replacements.Add("{{hideField}}", field != null && field.Hidden ? "true" : "false");
replacements.Add("{{field_title_disabled}}", field_title_disabled ? " disabled" : "");
replacements.Add("{{textDefault}}", textDefault);
replacements.Add("{{numberDefault}}", numberDefault);
replacements.Add("{{action}}", "none");
replacements.Add("{{booleanDefault_options}}", booleanDefault_options);
replacements.Add("{{attachType_options}}", attachType_options);
replacements.Add("{{type_options}}", type_options);
replacements.Add("{{id}}", random);
replacements.Add("{{title}}", title);
replacements.Add("{{title_value}}", HttpUtility.HtmlAttributeEncode(title));
replacements.Add("{{internalName}}", internalName);
replacements.Add("{{description}}", description.Length > 0 ? "<p class='description'>" + description + "</p>" : "");
replacements.Add("{{type_disabled}}", type_disabled ? " disabled" : "");
replacements.Add("{{required}}", required ? " checked" : "");
replacements.Add("{{required_disabled}}", required_disabled ? " disabled" : "");
replacements.Add("{{guid}}", guid);
replacements.Add("{{lookup_webs}}", lookup_webs);
replacements.Add("{{lookup_lists}}", lookup_lists);
replacements.Add("{{choices}}", string.Join("\r\n", choices_array));
string field_html = edit_list_field_html.Text;
StringBuilder fieldInfo = new StringBuilder();
if (field != null)
fieldInfo.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", "field.ParentList", field.ParentList.DefaultViewUrl);
foreach (KeyValuePair<string, string> replacement in replacements)
{
field_html = field_html.Replace(replacement.Key, (replacement.Value ?? ""));
fieldInfo.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", replacement.Key, replacement.Value);
}
fieldInfo.Append("</tbody><thead><tr><th colspan='2'>Field Data</th></tr></thead><tbody>");
if (_data != null)
foreach (KeyValuePair<string, object> attr in _data)
fieldInfo.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", attr.Key, WContext.Serialize(attr.Value));
return field_html// + "~~~"
.Replace("~~~", "<table class='table table-striped'><thead><tr><th colspan='2'>Replacements</th></tr></thead><tbody>" + fieldInfo + "</tbody></table>");
}
} |
using UnityEngine;
namespace UnityEngineExtended
{
public static class TransformExtension
{
/// <summary>
/// Finds a GameObject with the given in this transform's parent hierarchy
/// </summary>
public static GameObject GetObjectWithTagInParent(this Transform transform, string tag)
{
// Walker 'traverses' the hierarchy looking for an object with the 'ComplexCollider' tag
Transform walker = transform;
//Get walker's parent while there is one and while we haven't found the object we're looking for
while (walker != null && walker.tag != tag)
walker = walker.parent;
// If an object with correct tag was found, return it
if (walker != null)
return walker.gameObject;
else
return null; // Otherwise return null
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using MyPersonalBlog.DataAccess.Concrete.EntityFrameworkCore.Contexts;
using MyPersonalBlog.DataAccess.Interfaces;
using MyPersonalBlog.Entities.Concrete;
namespace MyPersonalBlog.DataAccess.Concrete.EntityFrameworkCore.Repositories
{
public class EfAppUserRepository : IAppUserDal
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.