text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using sfShareLib;
using System.ComponentModel.DataAnnotations;
namespace sfAPIService.Models
{
public class EventInActionModels
{
public class Detail
{
public int? ApplicationId { get; set; }
public string ApplicationName { get; set; }
}
public class Edit
{
public int[] ApplicationIdList { get; set; }
}
public List<Detail> GetAllApplicationByEventRuleCatalogId(int EventRuleCatalogId)
{
DBHelper._EventInAction dbhelp = new DBHelper._EventInAction();
return dbhelp.GetAllByEventRuleCatalogId(EventRuleCatalogId).Select(s => new Detail()
{
ApplicationId = s.ApplicationId,
ApplicationName = (s.Application == null) ? "" : s.Application.Name
}).ToList<Detail>();
}
public void AttachApplication(int EventRuleCatalogId, Edit EventInAction)
{
DBHelper._EventInAction dbhelp = new DBHelper._EventInAction();
List<EventInAction> newExternalApplicationList = new List<EventInAction>();
List<EventInAction> existExternalApplicationList = dbhelp.GetAllByEventRuleCatalogId(EventRuleCatalogId);
dbhelp.Delete(existExternalApplicationList);
if (EventInAction != null)
{
foreach (int applicationId in EventInAction.ApplicationIdList)
{
if (applicationId > 0)
{
newExternalApplicationList.Add(new EventInAction()
{
EventRuleCatalogId = EventRuleCatalogId,
ApplicationId = applicationId
});
}
}
}
dbhelp.Add(newExternalApplicationList);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using IronMan.Core;
namespace IronMan.Weapons
{
public class Launcher : ILauncher
{
private ICollection<IMissile> missiles;
public Launcher(ICollection<IMissile> missiles)
{
this.missiles = missiles;
}
public int MissileCount => missiles.Count;
public void Launch()
{
var missile = missiles.First();
missiles.Remove(missile);
}
}
} |
using HouseParty.Client.Contracts.Questions;
using HouseParty.Client.Repositories.QuestionRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HouseParty.Client.Services.QuestionService
{
public class QuestionService : IQuestionService
{
private readonly IQuestionRepository questionRepository;
public QuestionService(IQuestionRepository questionRepository)
{
this.questionRepository = questionRepository ?? throw new ArgumentNullException(nameof(questionRepository));
}
public List<Question> GetQuestions(string userQuestionType)
{
// Get the type of the question
QuestionType questionType = (QuestionType)Enum.Parse(typeof(QuestionType), userQuestionType);
var questions = this.questionRepository
.GetAll(x => x.QuestionType == questionType)
.OrderBy(x => x.QuestionUploaded)
.ToList();
return questions;
}
public int SubmitQuestion(QuestionInputViewModel viewModel)
{
var question = new Question
{
Title = viewModel.Title,
QuestionUrl = viewModel.QuestionUrl,
Notes = viewModel.Notes,
QuestionUploaded = DateTime.UtcNow,
QuestionType = viewModel.QuestionType
};
this.questionRepository.Insert(question);
this.questionRepository.SaveChanges();
return question.Id;
}
public void SubmitSolution(QuestionUpdateViewModel viewModel)
{
var question = this.questionRepository.GetFirstOrDefault(x => x.Id == viewModel.Id);
if (question == null)
{
throw new ArgumentNullException(nameof(viewModel.Id));
}
//question.Title = viewModel.Title;
//// TODO: Update seen status
//question.WontDo = viewModel.WontDo;
//question.WontDoReason = viewModel.WontDoReason;
if (!string.IsNullOrEmpty(viewModel.ShubhiSolution))
{
question.WhetherShubhiSubmitted = true;
question.ShubhiSolution = viewModel.ShubhiSolution;
question.ShubhiSolutionUpdatedOn = DateTime.UtcNow;
}
if (!string.IsNullOrEmpty(viewModel.AdityaSolution))
{
question.WhetherAdityaSubmitted = true;
question.AdityaSolution = viewModel.AdityaSolution;
question.AdityaSolutionUpdatedOn = DateTime.UtcNow;
}
//question.QuestionUrl = viewModel.QuestionUrl;
//question.Notes = viewModel.Notes;
//question.QuestionType = viewModel.QuestionType;
this.questionRepository.Update(question);
this.questionRepository.SaveChanges();
}
public void SubmitShubhiSolution(int questionId)
{
var question = this.questionRepository.GetFirstOrDefault(x => x.Id == questionId);
if (question == null)
{
throw new ArgumentNullException(nameof(questionId));
}
question.WhetherShubhiSubmitted = true;
this.questionRepository.Update(question);
this.questionRepository.SaveChanges();
}
public void SubmitAdityaSolution(int questionId)
{
var question = this.questionRepository.GetFirstOrDefault(x => x.Id == questionId);
if (question == null)
{
throw new ArgumentNullException(nameof(questionId));
}
question.WhetherAdityaSubmitted = true;
this.questionRepository.Update(question);
this.questionRepository.SaveChanges();
}
public void WontDoThisQuestion(int questionId)
{
var question = this.questionRepository.GetFirstOrDefault(x => x.Id == questionId);
if (question == null)
{
throw new ArgumentNullException(nameof(questionId));
}
question.WontDo = true;
this.questionRepository.Update(question);
this.questionRepository.SaveChanges();
}
public int[] GetScore()
{
int questionsShubhiSolved = this.questionRepository
.GetAll(x => x.WhetherShubhiSubmitted == true)
.Count();
int questionsAdiSolved = this.questionRepository
.GetAll(x => x.WhetherAdityaSubmitted == true)
.Count();
return new int[] { questionsShubhiSolved, questionsAdiSolved };
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace radl_pps.domain
{
public class Produktion
{
private int menge;
private Artikel artikel;
public int Menge
{
get { return menge; }
set
{
menge = value;
}
}
public Artikel Artikel
{
get { return artikel; }
set { artikel = value; }
}
public Produktion(int Menge, Artikel Artikel)
{
this.Menge = Menge;
this.Artikel = Artikel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Pelmanism
{
//カードクラス
class Card : Button
{
//カードのサイズ
private const int SizeW = 50, SizeH = 70;
//絵柄
public String Picture { get; set; }
//状態(True:表 False:裏)
public bool State { get; set; }
//表面の色
public Color OpenColor { get; } = Color.White;
//裏面の色
public Color CloseColor { get; } = Color.LightSeaGreen;
public Card(string picture)
{
Picture = picture;
State = false;
Size = new Size(SizeW, SizeH);
BackColor = CloseColor;
Font = new Font("MS UI Goshic", 14, FontStyle.Bold);
Enabled = false;
}
//カードオープン
public void Open()
{
State = true;
BackColor = OpenColor;
Text = Picture;
Enabled = false;
}
//カードクローズ
public void Close()
{
State = false;
BackColor = CloseColor;
Text = "";
Enabled = true;
}
public void Turn()
{
if (State)
Close();
else
Open();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace SatNav
{
public class Map
{
private readonly IList<CalcNode> _priorities = new List<CalcNode>();
private readonly IList<Edge> _route = new List<Edge>();
public Map()
{
Nodes = new Dictionary<string, Node>
{
{"A", new Node("A", 5, 5)},
{"B", new Node("B", 4, 5)},
{"C", new Node("C", 3, 5)},
{"D", new Node("D", 2, 5)},
{"E", new Node("E", 1, 4)},
{"F", new Node("F", 1, 3)},
{"G", new Node("G", 2, 1)},
{"H", new Node("H", 3, 4)},
{"I", new Node("I", 3, 3)},
{"J", new Node("J", 2, 3)},
{"K", new Node("K", 5, 3)},
{"L", new Node("L", 5, 1)},
{"M", new Node("M", 3, 1)},
{"N", new Node("N", 1, 1)}
};
Edges = new List<Edge>
{
new Edge(Nodes["A"], Nodes["B"]),
new Edge(Nodes["A"], Nodes["K"]),
new Edge(Nodes["B"], Nodes["C"]),
new Edge(Nodes["C"], Nodes["D"]),
new Edge(Nodes["C"], Nodes["H"]),
new Edge(Nodes["D"], Nodes["E"]),
new Edge(Nodes["E"], Nodes["F"]),
new Edge(Nodes["F"], Nodes["G"]),
new Edge(Nodes["G"], Nodes["N"]),
new Edge(Nodes["H"], Nodes["I"]),
new Edge(Nodes["I"], Nodes["J"]),
new Edge(Nodes["J"], Nodes["F"]),
new Edge(Nodes["K"], Nodes["L"]),
new Edge(Nodes["L"], Nodes["M"]),
new Edge(Nodes["M"], Nodes["N"])
};
}
public IList<Edge> GetRoute(string start, string end)
{
var startNode = Nodes[start];
var endNode = Nodes[end];
_priorities.Clear();
_priorities.Add(new CalcNode(startNode, 0, new Edge(startNode, endNode).Length));
FindNextNode(startNode, endNode);
return _route;
}
private void FindNextNode(Node currentNode, Node endNode)
{
while (_priorities.Any())
{
_priorities.Remove(_priorities.FirstOrDefault(p => p.Node == currentNode));
var availableEdges = GetAvailableEdges(currentNode);
foreach (var edge in availableEdges)
{
if (edge.End == endNode)
{
_route.Add(edge);
return;
}
var g = new Edge(currentNode, edge.End).Length;
var h = new Edge(edge.End, endNode).Length;
_priorities.Add(new CalcNode(edge.End, g, h));
}
if (LastNodeIsEndOfRoute(endNode)) return;
var priority = GetNextBestPoint();
var start = _route.Any() ? _route.Last().End : currentNode;
AddEdgeMatchingTheseNodes(start, priority.Node);
FindNextNode(priority.Node, endNode);
}
}
private bool LastNodeIsEndOfRoute(Node endNode)
{
return _route.Any() && _route.Last().End == endNode;
}
private void AddEdgeMatchingTheseNodes(Node start, Node end)
{
_route.Add(Edges.Single(e => e.Start.Name == start.Name && e.End.Name == end.Name));
}
private CalcNode GetNextBestPoint()
{
var minF = _priorities.Min(p => p.F);
var priority = _priorities.First(p => p.F == minF);
return priority;
}
private IEnumerable<Edge> GetAvailableEdges(Node currentNode)
{
return Edges.Where(e => e.Start == currentNode);
}
private IList<Edge> Edges { get; }
private IDictionary<string, Node> Nodes { get; }
}
} |
using FluentValidation;
using Ninject.Modules;
using ZeyrekFramework.Business.ValidationRules.FluentValidation;
using ZeyrekFramework.Entities.Concrete;
namespace ZeyrekFramework.Business.DependencyResolvers.Ninject
{
public class ValidationModule : NinjectModule
{
public override void Load()
{
Bind<IValidator<Message>>().To<MessageValidatior>().InSingletonScope();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters;
namespace OmniSharp.Extensions.LanguageServer.Protocol
{
/// <summary>
/// Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
/// This class is a simple parser which creates the basic component parts
/// (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
/// and encoding.
///
/// ```txt
/// foo://example.com:8042/over/there?name=ferret#nose
/// \_/ \______________/\_________/ \_________/ \__/
/// | | | | |
/// scheme authority path query fragment
/// | _____________________|__
/// / \ / \
/// urn:example:animal:ferret:nose
/// ```
/// </summary>
/// <summary>
/// This class describes a document uri as defined by https://microsoft.github.io/language-server-protocol/specifications/specification-current/#uri
/// </summary>
/// <remarks>This exists because of some non-standard serialization in vscode around uris and .NET's behavior when deserializing those uris</remarks>
[JsonConverter(typeof(DocumentUriConverter))]
public partial class DocumentUri : IEquatable<DocumentUri?>
{
/// <summary>
/// scheme is the "http' part of 'http://www.msft.com/some/path?query#fragment".
/// The part before the first colon.
/// </summary>
public string? Scheme { get; }
/// <summary>
/// authority is the "www.msft.com' part of 'http://www.msft.com/some/path?query#fragment".
/// The part between the first double slashes and the next slash.
/// </summary>
public string Authority { get; }
/// <summary>
/// path is the "/some/path' part of 'http://www.msft.com/some/path?query#fragment".
/// </summary>
public string Path { get; }
/// <summary>
/// query is the "query' part of 'http://www.msft.com/some/path?query#fragment".
/// </summary>
public string Query { get; }
/// <summary>
/// fragment is the "fragment' part of 'http://www.msft.com/some/path?query#fragment".
/// </summary>
public string Fragment { get; }
/// <summary>
/// Convert the uri to a <see cref="Uri" />
/// </summary>
/// <returns></returns>
/// <remarks>This will produce a uri where asian and cyrillic characters will be encoded</remarks>
public Uri ToUri()
{
if (Authority.IndexOf(":", StringComparison.Ordinal) > -1)
{
var parts = Authority.Split(':');
var host = parts[0];
var port = int.Parse(parts[1]);
return new UriBuilder
{
Scheme = Scheme,
Host = host,
Port = port,
Path = Path,
Fragment = Fragment,
Query = Query
}.Uri;
}
return new UriBuilder
{
Scheme = Scheme,
Host = Authority,
Path = Path,
Fragment = Fragment,
Query = Query
}.Uri;
}
// ---- printing/externalize ---------------------------
/// <summary>
/// Creates a string representation for this URI. It's guaranteed that calling
/// `URI.parse` with the result of this function creates an URI which is equal
/// to this URI.
///
/// * The result shall *not* be used for display purposes but for externalization or transport.
/// * The result will be encoded using the percentage encoding and encoding happens mostly
/// ignore the scheme-specific encoding rules.
///
/// @param skipEncoding Do not encode the result, default is `false`
/// </summary>
public override string ToString()
{
return _asFormatted(this, false);
}
public string ToUnencodedString()
{
return _asFormatted(this, true);
}
/// <summary>
/// Gets the file system path prefixed with / for unix platforms
/// </summary>
/// <returns></returns>
/// <remarks>This will not a uri encode asian and cyrillic characters</remarks>
public string GetFileSystemPath()
{
return UriToFsPath(this, false);
}
/// <inheritdoc />
public bool Equals(DocumentUri? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
// It's possible mac can have case insensitive file systems... we can always come back and change this.
var comparison = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? StringComparison.Ordinal
: StringComparison.OrdinalIgnoreCase;
return string.Equals(Path, other.Path, comparison) &&
string.Equals(Scheme, other.Scheme, comparison) &&
string.Equals(Authority, other.Authority, comparison) &&
string.Equals(Query, other.Query, comparison) &&
string.Equals(Fragment, other.Fragment, comparison);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((DocumentUri)obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
// It's possible mac can have case insensitive file systems... we can always come back and change this.
var comparer = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? StringComparer.Ordinal
: StringComparer.OrdinalIgnoreCase;
unchecked
{
var hashCode = comparer.GetHashCode(Path);
hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Scheme ?? "");
hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Authority);
hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Query);
hashCode = ( hashCode * 397 ) ^ comparer.GetHashCode(Fragment);
return hashCode;
}
}
/// <summary>
/// Deconstruct the document uri into it's different parts
/// </summary>
/// <param name="scheme"></param>
/// <param name="authority"></param>
/// <param name="path"></param>
/// <param name="query"></param>
/// <param name="fragment"></param>
/// <returns></returns>
public void Deconstruct(
out string? scheme, out string authority, out string path, out string query,
out string fragment
)
{
scheme = Scheme;
authority = Authority;
path = Path;
query = Query;
fragment = Fragment;
}
/// <summary>
/// Check if two uris are equal
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(DocumentUri left, DocumentUri right)
{
return Equals(left, right);
}
/// <summary>
/// Check if two uris are not equal
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(DocumentUri left, DocumentUri right)
{
return !Equals(left, right);
}
/// <summary>
/// Convert this uri into a <see cref="string" />.
/// </summary>
/// <param name="uri"></param>
/// <remarks>
/// This is explicit because to string gives the schema string with file:// but if you want the file system you use <see cref="GetFileSystemPath()" />
/// </remarks>
/// <returns></returns>
public static explicit operator string(DocumentUri uri)
{
return uri.ToString();
}
/// <summary>
/// Convert this into a <see cref="Uri" />.
/// </summary>
/// <param name="uri"></param>
/// <remarks>The uri class has issues with higher level utf8 characters such as asian and cyrillic characters</remarks>
/// <returns></returns>
public static explicit operator Uri(DocumentUri uri)
{
return uri.ToUri();
}
/// <summary>
/// Automatically convert a string to a uri for both filesystem paths or uris in a string
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static implicit operator DocumentUri(string url)
{
return From(url);
}
/// <summary>
/// Automatically convert a uri to a document uri
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static implicit operator DocumentUri(Uri uri)
{
return From(uri);
}
/// <summary>
/// Create a new document uri from the given <see cref="Uri" />
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static DocumentUri From(Uri uri)
{
if (uri.OriginalString.IndexOf(EncodeTable[CharCode.Colon], StringComparison.OrdinalIgnoreCase) > -1)
return From(uri.OriginalString);
if (uri.Scheme == Uri.UriSchemeFile)
{
return From(uri.LocalPath);
}
return From(uri.ToString());
}
/// <summary>
/// Create a new document uri from a string
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static DocumentUri From(string url)
{
if (string.IsNullOrWhiteSpace(url))
{
throw new UriFormatException("Given uri is null or empty");
}
if (url.StartsWith(@"\\") || url.StartsWith("/") || WindowsPath.IsMatch(url))
{
return File(url);
}
return Parse(url);
}
/// <summary>
/// Get the local file-system path for the specified document URI.
/// </summary>
/// <param name="textDocumentIdentifierParams">
/// The text document params object
/// </param>
/// <returns>
/// The file-system path, or <c>null</c> if the URI does not represent a file-system path.
/// </returns>
public static string? GetFileSystemPath(ITextDocumentIdentifierParams textDocumentIdentifierParams)
{
return GetFileSystemPath(textDocumentIdentifierParams.TextDocument.Uri);
}
/// <summary>
/// Get the local file-system path for the specified document URI.
/// </summary>
/// <param name="textDocumentIdentifier">
/// The text document identifier
/// </param>
/// <returns>
/// The file-system path, or <c>null</c> if the URI does not represent a file-system path.
/// </returns>
public static string? GetFileSystemPath(TextDocumentIdentifier textDocumentIdentifier)
{
return GetFileSystemPath(textDocumentIdentifier.Uri);
}
/// <summary>
/// Get the local file-system path for the specified document URI.
/// </summary>
/// <param name="documentUri">
/// The LSP document URI.
/// </param>
/// <returns>
/// The file-system path, or <c>null</c> if the URI does not represent a file-system path.
/// </returns>
public static string? GetFileSystemPath(DocumentUri documentUri)
{
if (documentUri == null!) throw new ArgumentNullException(nameof(documentUri));
if (documentUri.Scheme != Uri.UriSchemeFile)
return null;
return documentUri.GetFileSystemPath();
}
/// <summary>
/// Convert a file-system path to an LSP document URI.
/// </summary>
/// <param name="fileSystemPath">
/// The file-system path.
/// </param>
/// <returns>
/// The LSP document URI.
/// </returns>
public static DocumentUri FromFileSystemPath(string fileSystemPath)
{
return File(fileSystemPath);
}
private sealed class DocumentUriEqualityComparer : IEqualityComparer<DocumentUri>
{
public bool Equals(DocumentUri? x, DocumentUri? y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null) return false;
if (y is null) return false;
return x.GetType() == y.GetType() && x.Equals(y);
}
public int GetHashCode(DocumentUri obj)
{
return obj.GetHashCode();
}
}
/// <summary>
/// A default comparer that can be used for equality
/// </summary>
public static IEqualityComparer<DocumentUri> Comparer { get; } = new DocumentUriEqualityComparer();
// for a while we allowed uris *without* schemes and this is the migration
// for them, e.g. an uri without scheme and without strict-mode warns and falls
// back to the file-scheme. that should cause the least carnage and still be a
// clear warning
// implements a bit of https://tools.ietf.org/html/rfc3986#section-5
// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
// --- decode
/// <summary>
/// @internal
/// </summary>
public DocumentUri(string? scheme, string? authority, string? path, string? query, string? fragment, bool? strict = null)
{
Scheme = SchemeFix(scheme, strict);
Authority = authority ?? Empty;
Path = ReferenceResolution(Scheme, path ?? Empty);
Query = query ?? Empty;
Fragment = fragment ?? Empty;
_validateUri(this, strict);
}
// ---- parse & validate ------------------------
/// <summary>
/// Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
/// `file:///usr/home`, or `scheme:with/path`.
///
/// @param value A string which represents an URI (see `URI#toString`).
/// </summary>
public static DocumentUri Parse(string value, bool strict = false)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new UriFormatException("Given uri is null or empty");
}
var match = Regexp.Match(value);
if (!match.Success)
{
return new DocumentUri(Empty, Empty, Empty, Empty, Empty);
}
return new DocumentUri(
match.Groups[2].Value ?? Empty,
PercentDecode(match.Groups[4].Value ?? Empty),
PercentDecode(match.Groups[5].Value ?? Empty),
PercentDecode(match.Groups[7].Value ?? Empty),
PercentDecode(match.Groups[9].Value ?? Empty),
strict
);
}
/// <summary>
/// Creates a new URI from a file system path, e.g. `c:\my\files`,
/// `/usr/home`, or `\\server\share\some\path`.
///
/// The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
/// as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
/// `URI.parse("file://" + path)` because the path might contain characters that are
/// interpreted (# and ?). See the following sample:
///
/// @param path A file system path (see `URI#fsPath`)
/// </summary>
public static DocumentUri File(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new UriFormatException("Given path is null or empty");
}
var authority = Empty;
// normalize to fwd-slashes on windows,
// on other systems bwd-slashes are valid
// filename character, eg /f\oo/ba\r.txt
if (path[0] != Slash)
{
path = path.Replace('\\', Slash);
}
// check for authority as used in UNC shares
// or use the path as given
if (path[0] == Slash && path[1] == Slash)
{
var idx = path.IndexOf(Slash, 2);
if (idx == -1)
{
authority = path.Substring(2);
path = StrSlash;
}
else
{
authority = path.Substring(2, idx - 2);
path = path.Substring(idx);
if (string.IsNullOrWhiteSpace(path)) path = StrSlash;
}
}
if (path.IndexOf("%3A", StringComparison.OrdinalIgnoreCase) > -1)
{
path = path.Replace("%3a", ":").Replace("%3A", ":");
}
return new DocumentUri("file", authority, path, Empty, Empty);
}
public DocumentUri With(DocumentUriComponents components)
{
return new DocumentUri(
components.Scheme ?? Scheme,
components.Authority ?? Authority,
components.Path ?? Path,
components.Query ?? Query,
components.Fragment ?? Fragment
);
}
public static DocumentUri From(DocumentUriComponents components)
{
return new DocumentUri(
components.Scheme ?? string.Empty,
components.Authority ?? string.Empty,
components.Path ?? string.Empty,
components.Query ?? string.Empty,
components.Fragment ?? string.Empty
);
}
}
}
|
using System;
using Psub.Domain.Abstract;
namespace Psub.Domain.Entities
{
public class FullDataParameter : Base
{
public virtual string Value { get; set; }
public virtual ControlObject ControlObject { get; set; }
public virtual DateTime LastUpdate { get; set; }
}
}
|
using LabLife.Contorols;
using LabLife.Data;
using Microsoft.Kinect;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpenCvSharp.CPlusPlus;
namespace LabLife.Editor
{
public class KinectPanel : AImageResourcePanel
{
LLCheckBox KinectButton = new LLCheckBox();
TextBlock Bonestatus = new TextBlock();
Canvas canvas1 = new Canvas();
KinectSensor kinect;
//bodyindex関連
BodyIndexFrameReader bodyIndexFrameReader;
FrameDescription bodyIndexFrameDesc;
byte[] bodyIndexBuffer;
WriteableBitmap bodyIndexColorImage;
Int32Rect bodyIndexColorRect;
int bodyIndexColorStride;
int bodyIndexColorBytesPerPixel = 4;
byte[] bodyIndexColorBuffer;
System.Windows.Media.Color[] bodyIndexColors;
//depth関連
DepthFrameReader depthFrameReader;
FrameDescription depthFrameDescription;
Int32Rect depthRect;
int depthStride;
ushort[] depthBuffer;
int depthImageWidth;
int depthImageHeight;
WriteableBitmap depthImage;
private int[] depthBitdata;
//colorimage関連
ColorImageFormat colorImageFormat;
ColorFrameReader colorFrameReader;
FrameDescription colorFrameDescription;
WriteableBitmap colorimage;
WriteableBitmap calibImg;
Int32Rect bitmapRect;
int bitmapStride;
byte[] colors;
int imageWidth;
int imageHeight;
//骨格情報
BodyFrameReader bodyFrameReader;
Body[] bodies;
int NumberofPlayer;
//Mat
Mat bodyindexMat;
Mat depthMat;
Mat colorimageMat;
OpenCvSharp.CPlusPlus.Size size;
OpenCvSharp.CPlusPlus.Size size1;
int stump;
public KinectPanel()
{
base.TitleName = "Kinect Condition";
kinect = KinectSensor.GetDefault();
//Mat
this.bodyindexMat = new Mat();
this.depthMat = new Mat();
this.colorimageMat = new Mat();
//bodyindex関連
this.bodyIndexFrameDesc = kinect.DepthFrameSource.FrameDescription;
this.bodyIndexBuffer = new byte[bodyIndexFrameDesc.LengthInPixels];
this.bodyIndexColorImage = new WriteableBitmap(bodyIndexFrameDesc.Width, bodyIndexFrameDesc.Height,
96, 96, PixelFormats.Bgra32, null);
this.bodyIndexColorRect = new Int32Rect(0, 0, bodyIndexFrameDesc.Width, bodyIndexFrameDesc.Height);
this.bodyIndexColorStride = (int)(bodyIndexFrameDesc.Width * bodyIndexColorBytesPerPixel);
this.bodyIndexColorBuffer = new byte[bodyIndexFrameDesc.LengthInPixels * bodyIndexColorBytesPerPixel];
bodyIndexColors = new System.Windows.Media.Color[]{
Colors.Red, Colors.Blue, Colors.Green, Colors.Yellow, Colors.Pink, Colors.Purple,
};
bodyIndexFrameReader = kinect.BodyIndexFrameSource.OpenReader();
bodyIndexFrameReader.FrameArrived += bodyIndexFrameReader_FrameArrived;
//depth関連
this.depthFrameReader = this.kinect.DepthFrameSource.OpenReader();
this.depthFrameReader.FrameArrived += DepthFrame_Arrived;
this.depthFrameDescription = this.kinect.DepthFrameSource.FrameDescription;
this.depthBuffer = new ushort[this.depthFrameDescription.LengthInPixels];
this.depthImageWidth = this.depthFrameDescription.Width;
this.depthImageHeight = this.depthFrameDescription.Height;
this.depthImage = new WriteableBitmap(depthFrameDescription.Width, depthFrameDescription.Height, 96, 96, PixelFormats.Gray16, null);
this.depthRect = new Int32Rect(0, 0, depthFrameDescription.Width, depthFrameDescription.Height);
this.depthStride = (int)(depthFrameDescription.Width * depthFrameDescription.BytesPerPixel);
//colorimage
this.colorImageFormat = ColorImageFormat.Bgra;
this.colorFrameDescription = this.kinect.ColorFrameSource.CreateFrameDescription(this.colorImageFormat);
this.colorFrameReader = this.kinect.ColorFrameSource.OpenReader();
this.colorFrameReader.FrameArrived += ColorFrame_Arrived;
this.colors = new byte[this.colorFrameDescription.Width
* this.colorFrameDescription.Height
* this.colorFrameDescription.BytesPerPixel];
this.imageWidth = this.colorFrameDescription.Width;
this.imageHeight = this.colorFrameDescription.Height;
this.colorimage = new WriteableBitmap(this.colorFrameDescription.Width, this.colorFrameDescription.Height, 96, 96, PixelFormats.Bgr32, null);
this.calibImg = new WriteableBitmap(this.colorFrameDescription.Width, this.colorFrameDescription.Height, 96, 96, PixelFormats.Bgr32, null);
this.bitmapRect = new Int32Rect(0, 0, this.colorFrameDescription.Width, this.colorFrameDescription.Height);
this.bitmapStride = this.colorFrameDescription.Width * (int)this.colorFrameDescription.BytesPerPixel;
//bone
this.bodyFrameReader = this.kinect.BodyFrameSource.OpenReader();
this.bodyFrameReader.FrameArrived += BodyFrame_Arrived;
this.bodies = new Body[this.kinect.BodyFrameSource.BodyCount]; //bodycountに骨格情報の数
this.size = new OpenCvSharp.CPlusPlus.Size(512, 424);
this.size1 = new OpenCvSharp.CPlusPlus.Size(imageWidth, imageHeight);
//this.bodyindexMat = new Mat(size, MatType.CV_8UC1);
//this.depthMat = bodyindexMat.Clone();
//this.colorimageMat = new Mat(size1, MatType.CV_8UC3);
stump = 0;
}
public override void Initialize(MainWindow mainwindow)
{
base.Initialize(mainwindow);
var p = new System.Windows.Controls.Image();
var q = new System.Windows.Controls.Image();
var r = new System.Windows.Controls.Image();
Border b = new Border();
b.Style = (Style)App.Current.Resources["Border_Default"];
b.Child = this.KinectButton;
base.AddContent(b, Dock.Top);
KinectButton.Content = "Kinect Start";
KinectButton.Click += KinectButton_Click;
base.AddContent(Bonestatus, Dock.Top);
base.SetImageToGridChildren(p);
p.Source = bodyIndexColorImage;
base.SetImageToGridChildren(q);
q.Source = depthImage;
base.SetImageToGridChildren(r);
r.Source = colorimage;
this.AddContent(base.Grid_Image, Dock.Top);
//this.AddContent(canvas1, Dock.Bottom);
}
//close処理
public override void Close(object sender, RoutedEventArgs e)
{
this.KinectClose();
base.Close(sender, e);
}
//Kinect
#region
public void KinectButton_Click(object sender, RoutedEventArgs e)
{
if (this.kinect == null) this.kinect = KinectSensor.GetDefault();
if (!this.kinect.IsOpen)
{
this.KinectStart();
}
else
{
this.KinectClose();
}
}
private void KinectStart()
{
//kinect Start
try
{
this.kinect.Open();
this.KinectButton.Content = "Kinect Stop";
if (this.kinect == null) this.kinect = KinectSensor.GetDefault();
}
catch
{
Console.WriteLine("error:kinectstart");
}
}
private void KinectClose()
{
//kinect Stop
try
{
if (this.kinect != null) this.kinect.Close();
this.KinectButton.Content = "Kinect Start";
}
catch
{
Console.WriteLine("error:kinectstop");
}
}
#endregion
//bodyindex
#region
void bodyIndexFrameReader_FrameArrived(object sender, BodyIndexFrameArrivedEventArgs e)
{
UpdateBodyIndexFrame(e);
DrawBodyIndexFrame();
}
private void UpdateBodyIndexFrame(BodyIndexFrameArrivedEventArgs e)
{
using (var bodyIndexFrame = e.FrameReference.AcquireFrame())
{
if (bodyIndexFrame == null)
{
return;
}
// ボディインデックスデータを取得する
bodyIndexFrame.CopyFrameDataToArray(bodyIndexBuffer);
//bodyIndexFrame.Dispose();
}
}
private void DrawBodyIndexFrame()
{
try
{
// ボディインデックスデータをBGRAデータに変換する
for (int i = 0; i < bodyIndexBuffer.Length; i++)
{
var index = bodyIndexBuffer[i];
var colorIndex = i * 4;
if (index != 255 )
{
var color = bodyIndexColors[index];
bodyIndexColorBuffer[colorIndex + 0] = 0;
bodyIndexColorBuffer[colorIndex + 1] = 0;
bodyIndexColorBuffer[colorIndex + 2] = 0;
bodyIndexColorBuffer[colorIndex + 3] = 255;
}
if (index == 255)
{
bodyIndexColorBuffer[colorIndex + 0] = 255;
bodyIndexColorBuffer[colorIndex + 1] = 255;
bodyIndexColorBuffer[colorIndex + 2] = 255;
bodyIndexColorBuffer[colorIndex + 3] = 255;
}
}
// ビットマップにする
this.bodyIndexColorImage.WritePixels(bodyIndexColorRect, bodyIndexColorBuffer, bodyIndexColorStride, 0);
//this.bodyindexMat = WriteableBitmapConverter.ToMat(bodyIndexColorImage);
this.bodyindexMat = new Mat(424, 512, MatType.CV_8UC4, bodyIndexColorBuffer);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
#endregion
//Depth
#region
void DepthFrame_Arrived(object sender, DepthFrameArrivedEventArgs e)
{
using (DepthFrame depthFrame = e.FrameReference.AcquireFrame())
{
//フレームがなければ終了、あれば格納
if (depthFrame == null) return;
if (depthBitdata == null)
{
depthBitdata = new int[depthBuffer.Length];
}
depthFrame.CopyFrameDataToArray(this.depthBuffer);
//取得範囲指定するときはコメントアウト解除
//var max = 3500;
//var min = 1000;
for (int i = 0; i < depthBuffer.Length; i++)
{
//if (max > depthBuffer[i] &&
// min < depthBuffer[i])
//{
depthBuffer[i] = (ushort)(depthBuffer[i] * 65535 / 8000);
//}
//else
//{
// depthBuffer[i] = ushort.MinValue;
//}
}
this.depthImage.WritePixels(depthRect, depthBuffer, depthStride, 0);
depthMat = new Mat(424, 512, MatType.CV_16UC1, depthBuffer);
}
}
#endregion
//ColorImage
#region
void ColorFrame_Arrived(object sender, ColorFrameArrivedEventArgs e)
{
try
{
ColorFrame colorFrame = e.FrameReference.AcquireFrame();
//フレームがなければ終了、あれば格納
if (colorFrame == null) return;
colorFrame.CopyConvertedFrameDataToArray(this.colors, this.colorImageFormat);
//表示
this.colorimage.WritePixels(this.bitmapRect, this.colors, this.bitmapStride, 0);
this.colorimageMat = new Mat(480,640,MatType.CV_8UC3,colors);
if (depthMat != null && bodyindexMat != null && colorimageMat != null)
{
OnImageFrameArrived(new ImageFrameArrivedEventArgs(new Mat[] { bodyindexMat, depthMat, colorimageMat}));
}
//破棄
colorFrame.Dispose();
}
catch
{
General.Log(this, "ColorImageError");
}
}
#endregion
//Bone
void BodyFrame_Arrived(object sender, BodyFrameArrivedEventArgs e)
{
try
{
// キャンバスをクリアする
canvas1.Children.Clear();
BodyFrame bodyFrame = e.FrameReference.AcquireFrame();
if (bodyFrame == null) return;
bodyFrame.GetAndRefreshBodyData(this.bodies);
foreach (var body in bodies.Where(b => b.IsTracked))
{
foreach (Joint joint in body.Joints.Values)
{
Bonestatus.Text = "X=" + body.Joints[JointType.SpineBase].Position.X + "Y=" + body.Joints[JointType.SpineBase].Position.Y + "Z=" + body.Joints[JointType.SpineBase].Position.Z;
//CameraSpacePoint jointPosition = joint.Position;
//ColorSpacePoint Colorpoint = new ColorSpacePoint();
//kinect.CoordinateMapper.MapCameraPointsToColorSpace(joint.Position, Colorpoint);
}
//Ellipse ellipse = new Ellipse
//{
// Fill = System.Windows.Media.Brushes.Red,
// Width = 15,
// Height = 15
//};
//Canvas.SetLeft(ellipse, body.Joints[JointType.SpineBase].Position.X);
//Canvas.SetTop(ellipse, body.Joints[JointType.SpineBase].Position.Y);
//canvas1.Children.Add(ellipse);
}
//破棄
bodyFrame.Dispose();
}
catch
{
General.Log(this, "BoneError");
}
}
}
}
|
using System;
using System.Threading.Tasks;
using LubyClocker.Application.BoundedContexts.Developers.Commands.Create;
using LubyClocker.Application.BoundedContexts.Developers.Commands.Delete;
using LubyClocker.Application.BoundedContexts.Developers.Commands.Update;
using LubyClocker.Application.BoundedContexts.Developers.Queries.FindAll;
using LubyClocker.Application.BoundedContexts.Developers.Queries.FindById;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LubyClocker.Api.Controllers
{
[Route("api/v1/developers")]
[Produces("application/json")]
[ApiController]
[Authorize]
public class DevelopersController : ControllerBase
{
private readonly IMediator _mediator;
public DevelopersController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> Add([FromBody] CreateDeveloperCommand command)
{
var result = await _mediator.Send(command);
return CreatedAtAction(nameof(Add), result);
}
[HttpPut("{id:guid}")]
public async Task<IActionResult> Edit([FromBody] UpdateDeveloperCommand command, [FromRoute] Guid id)
{
var result = await _mediator.Send(command.IncludeId(id));
return Ok(result);
}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
await _mediator.Send(new DeleteDeveloperCommand().IncludeId(id));
return Ok();
}
[HttpGet]
public async Task<IActionResult> FindAll([FromQuery] FindDevelopersQuery query)
{
var result = await _mediator.Send(query);
return Ok(result);
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> FindById([FromRoute] Guid id)
{
var result = await _mediator.Send(new FindDeveloperByIdQuery().IncludeId(id));
return Ok(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace GistManager.Controls
{
public class OverflowlessToolbar : ToolBar
{
public OverflowlessToolbar()
{
this.Loaded += OverflowlessToolbar_Loaded;
}
// https://stackoverflow.com/questions/1050953/wpf-toolbar-how-to-remove-grip-and-overflow
private void OverflowlessToolbar_Loaded(object sender, RoutedEventArgs e)
{
if (this.Template.FindName("OverflowGrid", this) is FrameworkElement overflowGrid)
{
overflowGrid.Visibility = Visibility.Collapsed;
}
if (this.Template.FindName("MainPanelBorder", this) is FrameworkElement mainPanelBorder)
{
mainPanelBorder.Margin = new Thickness();
}
}
}
}
|
using System;
using System.Threading.Tasks;
namespace JCFruit.WeebChat.Server.Tcp
{
public interface IConnectionHandler
{
Task OnClientConnected(ConnectedClient client);
Task OnMessageReceived(string clientId, ReadOnlySpan<byte> data);
Task OnClientDisconnected(string clientId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Parser.Html;
using WinCompetitionsParsing.BL.Models;
namespace WinCompetitionsParsing.Utils
{
public class ParsingSite
{
private string userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
private string language = "en-us;q=0.5,en;q=0.3";
private HtmlParser parser;
public ParsingSite()
{
parser = new HtmlParser();
}
public string GetHtml(string uri)
{
try
{
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add(HttpRequestHeader.UserAgent, userAgent);
webClient.Headers.Add(HttpRequestHeader.AcceptLanguage, language);
webClient.Encoding = Encoding.UTF8;
var html = webClient.DownloadString(uri);
return html;
}
}
catch (Exception ex)
{
return String.Empty;
}
}
public IElement FindOneElement(string html, string find)
{
var document = parser.Parse(html);
return document.QuerySelector(find);
}
public string FindOneElement(string html, string find, string attr)
{
var document = parser.Parse(html);
return document.QuerySelector(find).GetAttribute(attr);
}
public IEnumerable<IElement> FindElements(string html, string find)
{
var document = parser.Parse(html);
return document.QuerySelectorAll(find);
}
public IEnumerable<string> FindElements(string html, string find, string attr)
{
var document = parser.Parse(html);
return document.QuerySelectorAll(find).Select(x => x.GetAttribute(attr));
}
public void GetDefaultInformationAboutProduct(string html, ProductModel productModel)
{
//проверить рабочий или нет
var price = FindOneElement(html, "span.product-item__price");
if (price != null)
productModel.IsWorking = true;
//найти категорию
var category = FindOneElement(html, "div.bread-crumbs li:nth-child(2)");
if (category != null)
productModel.Category = FindOneElement(category.Html(), "span").Text();
//найти подкатигорию
var subCategory = FindOneElement(html, "div.bread-crumbs li:nth-child(3)");
if (subCategory != null)
productModel.SubCategory = FindOneElement(subCategory.Html(), "span").Text();
//найти имя
var name = FindOneElement(html, ".product-item__name");
if (name != null)
productModel.Name = name.Text();
}
public bool CheckFindLink(string uri, string findLink)
{
var html = GetHtml(uri);
if (html == string.Empty) return false;
var link = FindOneElement(html, "div.product-info__description a", "href");
if (link == null) return false;
if (link == findLink) return true;
return false;
}
}
}
|
using AutoMapper;
using CryptoInvestor.Core.Domain;
using CryptoInvestor.Core.Repositories;
using CryptoInvestor.Infrastructure.DTO;
using CryptoInvestor.Infrastructure.Exceptions;
using CryptoInvestor.Infrastructure.Services.Interfaces;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CryptoInvestor.Infrastructure.Services
{
public class FavouritesService : IFavouritesService
{
private readonly IFavouritesRepository _favouritesRepository;
private readonly IUserRepository _userRepository;
private readonly ICoinRepository _coinRepository;
private readonly IMapper _mapper;
public FavouritesService(IFavouritesRepository favouritesRepository, IUserRepository userRepository,
ICoinRepository coinRepository, IMapper mapper)
{
_favouritesRepository = favouritesRepository;
_userRepository = userRepository;
_coinRepository = coinRepository;
_mapper = mapper;
}
public async Task<FavouritesDto> GetAsync(Guid userId)
{
var favourites = await _favouritesRepository.GetAsync(userId);
favourites = await UpdateCoins(favourites);
return _mapper.Map<FavouritesDto>(favourites);
}
public async Task CreateAsync(Guid userId)
{
var user = await _userRepository.GetAsync(userId);
if (user == null)
{
throw new ServiceException(ErrorCodes.UserNotFound,
$"User with id: {userId} does not exists.");
}
var localFavourites = await _favouritesRepository.GetAsync(userId);
if (localFavourites != null)
{
throw new ServiceException(ErrorCodes.FavouritesAlreadyExists,
$"User with id: {userId} already has a favourites collection.");
}
var favourites = new Favourites(user.Id);
await _favouritesRepository.AddAsync(favourites);
}
public async Task<CoinDto> GetCoinAsync(Guid userId, string coinSymbol)
{
coinSymbol = coinSymbol.ToLowerInvariant();
var favourites = await _favouritesRepository.GetAsync(userId);
if (favourites == null)
{
throw new ServiceException(ErrorCodes.FavouritesNotFound,
$"Favourites collection with id: {userId} does not exists.");
}
var coin = favourites.Coins.SingleOrDefault(x => x.Symbol == coinSymbol);
return _mapper.Map<CoinDto>(coin);
}
public async Task AddCoinAsync(Guid userId, string coinSymbol)
{
coinSymbol = coinSymbol.ToLowerInvariant();
var favourites = await _favouritesRepository.GetAsync(userId);
if (favourites == null)
{
throw new ServiceException(ErrorCodes.FavouritesNotFound,
$"Favourites collection with id: {userId} does not exists.");
}
var coin = await _coinRepository.GetAsync(coinSymbol);
if (coin == null)
{
throw new ServiceException(ErrorCodes.InvalidCoin,
$"Coin with symbol: {coinSymbol} was not found.");
}
favourites.AddCoin(coin);
await _favouritesRepository.UpdateAsync(favourites);
}
public async Task DeleteCoinAsync(Guid userId, string coinSymbol)
{
coinSymbol = coinSymbol.ToLowerInvariant();
var favourites = await _favouritesRepository.GetAsync(userId);
if (favourites == null)
{
throw new ServiceException(ErrorCodes.FavouritesNotFound,
$"Favourites collection with id: {userId} does not exists.");
}
var coin = await _coinRepository.GetAsync(coinSymbol);
if (coin == null)
{
throw new ServiceException(ErrorCodes.InvalidCoin,
$"Coin with symbol: {coinSymbol} was not found.");
}
favourites.RemoveCoin(coin);
await _favouritesRepository.UpdateAsync(favourites);
}
private async Task<Favourites> UpdateCoins(Favourites favourites)
{
var temp = new Favourites(favourites.Id);
foreach (var coin in favourites.Coins)
{
var newCoin = await _coinRepository.GetAsync(coin.Symbol);
temp.AddCoin(newCoin);
}
return temp;
}
}
} |
using System;
using System.IO;
using UnityEngine;
namespace Ghost.Config
{
public static class PathConfig
{
public const string DIRECTORY_RESOURCES = "Resources";
public const string DIRECTORY_STANDARD_ASSETS = "Standard Assets";
public const string DIRECTORY_MATERIALS = "Materials";
public const string EXTENSION_SCENE = "unity";
public const string EXTENSION_PREFAB = "prefab";
public const string EXTENSION_FBX = "fbx";
public const string EXTENSION_ASSET = "asset";
public const string EXTENSION_ASSET_BUNDLE = "assetbundle";
public const string EXTENSION_SCENE_PACKAGE = "unity3d";
public const string EXTENSION_MATERIAL = "mat";
public const string EXTENSION_ANIMATION = "anim";
public const string EXTENSION_JSON = "json";
public const string EXTENSION_LIGHT_MAP = "exr";
public const string FILE_NAV_MESH = "NavMesh.asset";
public static readonly char[] SEPARATORS;
public static readonly string DIRECTORY_ASSETS;
public static readonly string DIRECTORY_STREAMING_ASSETS;
public static readonly string DIRECTORY_PERSISTENT_ASSETS;
public static readonly string LOCAL_URL_PREFIX;
static PathConfig()
{
PathConfig.SEPARATORS = new char[]
{
Path.AltDirectorySeparatorChar,
Path.DirectorySeparatorChar,
Path.PathSeparator,
Path.VolumeSeparatorChar
};
PathConfig.DIRECTORY_ASSETS = Path.GetFileName(Application.get_dataPath().TrimEnd(PathConfig.SEPARATORS));
PathConfig.DIRECTORY_STREAMING_ASSETS = Path.GetFileName(Application.get_streamingAssetsPath().TrimEnd(PathConfig.SEPARATORS));
PathConfig.DIRECTORY_PERSISTENT_ASSETS = Path.GetFileName(Application.get_persistentDataPath().TrimEnd(PathConfig.SEPARATORS));
switch (Application.get_platform())
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 7:
case 8:
PathConfig.LOCAL_URL_PREFIX = "file://";
return;
case 11:
PathConfig.LOCAL_URL_PREFIX = "jar:file://";
return;
}
PathConfig.LOCAL_URL_PREFIX = string.Empty;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlantAttack : MonoBehaviour {
public GameObject leaf;
public Sprite mouthClosed;
public Sprite mouthOpen;
public bool isOpened;
public int spriteInterval;
private int spriteCounter;
bool facingRight;
private GameObject player;
void Start () {
this.GetComponent<SpriteRenderer>().sprite = mouthClosed;
isOpened = false;
spriteCounter = spriteInterval;
facingRight = false;
player = GameObject.FindWithTag("Player");
}
void Update () {
if(spriteCounter == 0 && !isOpened)
{
this.GetComponent<SpriteRenderer>().sprite = mouthOpen;
Invoke("CreateLeaf", 0.3f);
isOpened = !isOpened;
spriteCounter = spriteInterval;
}
else
{
if(spriteCounter == 0 && isOpened)
{
this.GetComponent<SpriteRenderer>().sprite = mouthClosed;
isOpened = !isOpened;
spriteCounter = spriteInterval;
}
}
spriteCounter -= 1;
if(!facingRight && player.transform.position.x > transform.position.x)
{
Flip();
}
if (facingRight && player.transform.position.x < transform.position.x)
{
Flip();
}
}
void CreateLeaf()
{
Vector3 position = transform.position + new Vector3(1, 0, 0);
GameObject newLeaf = Instantiate(leaf, position, transform.rotation);
newLeaf.GetComponent<LeafManager>().IsFacingRight(facingRight);
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyMedicine.Context.Medicine;
using Newtonsoft.Json;
using MyMedicine.Controllers.Services;
using System.Collections.Generic;
namespace MyMedicine.Controllers
{
[ValidateAntiForgeryToken]
[Route("apiadm/post")]
public class PostAdminController : Controller
{
private MedicineContext _context;
public PostAdminController([FromServices] MedicineContext context)
{
_context = context;
}
[HttpPost("[action]")]
public async Task<string> CreateOrEdit([FromQuery] int postid, [FromBody] Post post)
{
if (postid <= 0)
{
await _context.AddNewPostAsync(post, User.Identity.Name);
}
else
{
await _context.EditPostAsync(post, postid);
}
return "true";
}
[HttpDelete("[action]")]
public async Task<string> DeleteCommentsList([FromQuery] int postid, [FromBody] List<int> commentsListId)
{
await _context.DeleteCommentsListAsync(postid, commentsListId);
return "true";
}
[HttpDelete("[action]")]
public async Task<string> DeletePost([FromQuery] int postid)
{
await _context.DeletePostAsync(postid);
return "true";
}
}
} |
using MediaOrganiser.Media;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Logger;
namespace MediaOrganiser.Console.Organisers
{
public enum OrganiserConversionOptions
{
Default,
Force,
Skip
}
public class Organiser
{
private IFileSystem _fileSystem = new FileSystem();
public DirectoryInfoBase WorkingDirectory;
public TextWriter StdOut
{
get { return Logger.Log("Organiser").StdOut; }
set { Logger.Log("Organiser").StdOut = value; }
}
public TextWriter StdErr
{
get { return Logger.Log("Organiser").StdErr; }
set { Logger.Log("Organiser").StdErr = value; }
}
public void Organise(IMedia media, DirectoryInfoBase outputDirectory, OrganiserConversionOptions conversionOption, bool strictSeason)
{
// Create working directory.
WorkingDirectory = _fileSystem.DirectoryInfo.FromDirectoryName(_fileSystem.Path.Combine(_fileSystem.Path.GetTempPath(), "WorkingArea"));
// Create working directory if it does not exist.
if(!WorkingDirectory.Exists)
{
WorkingDirectory.Create();
}
// Copy to working area.
CopyMediaToWorkingArea(media);
// Convert if required.
if(conversionOption == OrganiserConversionOptions.Force)
{
Logger.Log("Organiser").StdOut.WriteLine("Conversion set to \"force\". Will convert. {0}", media.MediaFile.FullName);
ConvertMedia(media);
}
else if(media.RequiresConversion)
{
if(conversionOption == OrganiserConversionOptions.Skip)
{
Logger.Log("Organiser").StdOut.WriteLine("Media requires conversion. Conversion set to \"skip\", skipping conversion. {0}", media.MediaFile.FullName);
}
else
{
Logger.Log("Organiser").StdOut.WriteLine("Media requires conversion. Will convert. {0}", media.MediaFile.FullName);
ConvertMedia(media);
}
}
// Extract media details exhaustivly.
ExtractExhaustiveMediaDetails(media, strictSeason);
// Save media meta data.
var saveResponse = SaveMediaMetaData(media);
if(!saveResponse)
{
if(conversionOption == OrganiserConversionOptions.Skip)
{
Logger.Log("Organiser").StdOut.WriteLine("Unable to save metadata. Conversion set to \"skip\", skipping conversion. {0}", media.MediaFile.FullName);
}
else
{
Logger.Log("Organiser").StdOut.WriteLine("Unable to save metadata. Will convert. {0}", media.MediaFile.FullName);
ConvertMedia(media);
SaveMediaMetaData(media);
}
}
// Rename media.
RenameMediaToCleanFileName(media);
// If output directory not provided, delete file. Otherwise move to output directory.
MoveMediaToOutputDirectory(media, outputDirectory);
}
private bool CopyMediaToWorkingArea(IMedia media)
{
Logger.Log("Organiser").StdOut.WriteLine("Copying media to working area. {0}", media.MediaFile.FullName);
// Create file for working area version of media.
var WorkingAreaMediaFile = _fileSystem.FileInfo.FromFileName(_fileSystem.Path.Combine(WorkingDirectory.FullName, media.MediaFile.Name));
// Copy the media and then assign the new file to the media.
media.MediaFile.CopyTo(WorkingAreaMediaFile.FullName, true);
media.MediaFile = WorkingAreaMediaFile;
Logger.Log("Organiser").StdOut.WriteLine("Copied media to working area. {0}", media.MediaFile.FullName);
return true;
}
private bool ConvertMedia(IMedia media)
{
Logger.Log("Organiser").StdOut.WriteLine("Starting media conversion. {0}", media.MediaFile.FullName);
if(media.Convert())
{
Logger.Log("Organiser").StdOut.WriteLine("Converted media. {0}", media.MediaFile.FullName);
return true;
}
Logger.Log("Organiser").StdOut.WriteLine("Unable to convert media. {0}", media.MediaFile.FullName);
return false;
}
private bool ExtractExhaustiveMediaDetails(IMedia media, bool strictSeason)
{
Logger.Log("Organiser").StdOut.WriteLine("Extracting Details Exhaustive. {0}", media.MediaFile.FullName);
var response = media.ExtractDetails(true, strictSeason);
Logger.Log("Organiser").StdOut.WriteLine("Extracted Details Exhaustive. {0}", media.MediaFile.FullName);
return response;
}
private bool SaveMediaMetaData(IMedia media)
{
Logger.Log().StdOut.WriteLine("Saving details. {0}", media.MediaFile.FullName);
if(media.SaveDetails())
{
Logger.Log().StdOut.WriteLine("Saved details. {0}", media.MediaFile.FullName);
return true;
}
Logger.Log().StdOut.WriteLine("Unable to save details. {0}", media.MediaFile.FullName);
return false;
}
private bool RenameMediaToCleanFileName(IMedia media)
{
Logger.Log("Organiser").StdOut.WriteLine("Renaming media. {0}", media.MediaFile.FullName);
var outputFileName = _fileSystem.Path.GetFileName(media.OrganisedMediaFileOutputPath);
var OrganisedMediaFile = _fileSystem.FileInfo.FromFileName(_fileSystem.Path.Combine(WorkingDirectory.FullName, outputFileName));
// Delete the file it already exists.
if(OrganisedMediaFile.Exists)
{
OrganisedMediaFile.Delete();
}
media.MediaFile.MoveTo(OrganisedMediaFile.FullName);
Logger.Log("Organiser").StdOut.WriteLine("Renamed media. {0}", media.MediaFile.FullName);
return true;
}
private bool MoveMediaToOutputDirectory(IMedia media, DirectoryInfoBase outputDirectory)
{
// Get the output file location of the media.
var OrganisedFile = _fileSystem.FileInfo.FromFileName(_fileSystem.Path.Combine(outputDirectory.FullName, media.OrganisedMediaFileOutputPath));
if(OrganisedFile.Exists)
{
Logger.Log("Organiser").StdOut.WriteLine("Media file already exists. Will not overwriting. {0}", media.MediaFile.FullName);
return false;
}
Logger.Log("Organiser").StdOut.WriteLine("Copying media to output directory. {0}", media.MediaFile.FullName);
if(!OrganisedFile.Directory.Exists)
{
OrganisedFile.Directory.Create();
}
media.MediaFile.MoveTo(OrganisedFile.FullName);
Logger.Log("Organiser").StdOut.WriteLine("Copied media to output directory. {0}", media.MediaFile.FullName);
return true;
}
}
}
|
using CouponsLtd.UpsertModels;
using System.Collections.Generic;
using System.Linq;
namespace CouponsLtd.ViewModels
{
public class CollectionResponse<TResult>
{
public CollectionResponse(List<TResult> collectionResponse,SearchParams searchParams,List<string> errors=null,bool isSuccessful=true)
{
Count = collectionResponse.Count();
IsSuccessful = isSuccessful;
Items = collectionResponse;
Errors = errors;
SearchParams = searchParams;
}
public int Count { get; set; }
public SearchParams SearchParams { get; set; }
public List<string> Errors { get; set; }
public bool IsSuccessful { get; set; }
public List<TResult> Items { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Calcifer.Engine.Components;
using Calcifer.Engine.Content;
using Calcifer.Engine.Scenery;
namespace Calcifer.Engine.Graphics.Animation
{
public class BlendAnimationController : AnimationComponent, ISaveable, IConstructable
{
private readonly Dictionary<string, AnimationData> anims;
private Pose invRestPose;
private LinearSequence backup;
private LinearSequence current;
private float fadeLeft;
private float fadeTime;
private Pose pose;
public BlendAnimationController()
{
anims = new Dictionary<string, AnimationData>();
}
public override string Name
{
get { return current != null ? current.Name : ""; }
}
public float Speed
{
get { return current != null ? current.Speed : 0; }
set
{
if (current != null) current.Speed = value;
if (backup != null) backup.Speed = value;
}
}
public float Length
{
get { return current != null ? current.Length : 0; }
}
public float Time
{
get { return current != null ? current.Time : 0; }
}
public override Pose Pose
{
get { return pose; }
}
public void SaveState(BinaryWriter writer)
{
writer.Write(current == null ? "" : current.Name);
if (current != null)
{
writer.Write(current.Loop);
writer.Write(current.Speed);
writer.Write(current.Time);
}
writer.Write(backup == null ? "" : backup.Name);
if (backup != null)
{
writer.Write(backup.Loop);
writer.Write(backup.Speed);
writer.Write(backup.Time);
}
writer.Write(fadeLeft);
writer.Write(fadeTime);
}
public void RestoreState(BinaryReader reader)
{
var curName = reader.ReadString();
if (curName != "")
{
var loop = reader.ReadBoolean();
current = new LinearSequence(anims[curName], loop)
{
Speed = reader.ReadSingle(),
Time = reader.ReadSingle()
};
}
var backupName = reader.ReadString();
if (backupName != "")
{
var loop = reader.ReadBoolean();
backup = new LinearSequence(anims[backupName], loop)
{
Speed = reader.ReadSingle(),
Time = reader.ReadSingle()
};
}
fadeLeft = reader.ReadSingle();
fadeTime = reader.ReadSingle();
}
public void AddAnimation(AnimationData anim)
{
anims.Add(anim.Name, anim);
}
public void Start(string name, bool loop)
{
current = new LinearSequence(anims[name], loop);
}
public void Crossfade(string name, float time, bool loop)
{
if (current != null)
{
var linearSequence = new LinearSequence(anims[name], loop);
backup = linearSequence;
fadeLeft = time;
fadeTime = time;
}
else Start(name, loop);
}
public override void Update(double time)
{
if (fadeLeft > 0f)
{
fadeLeft = Math.Max(fadeLeft - (float) time, 0f);
}
if (current == null)
{
return;
}
current.Update((float) time);
if (backup != null)
{
backup.Update((float) time);
}
pose = new Pose(current.Pose);
if (backup != null && fadeLeft > 0f)
for (int i = 0; i < pose.BoneCount; i++)
pose.SetTransform(i,
Transform.Interpolate(current.Pose[i].Transform, backup.Pose[i].Transform,
1f - fadeLeft/fadeTime));
pose.CalculateWorld();
if (backup != null && fadeLeft <= 0.01f)
{
current = backup;
backup = null;
}
pose.MergeWith(invRestPose);
}
void IConstructable.Construct(IDictionary<string, string> param)
{
invRestPose = new Pose(ResourceFactory.LoadAsset<AnimationData>(param["restPose"]).Frames[0]);
invRestPose.Invert();
pose = new Pose(invRestPose.BoneCount);
if (param["animations"] != null)
foreach (var animName in param["animations"].Split(';'))
AddAnimation(ResourceFactory.LoadAsset<AnimationData>(animName));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Filter.Infrastructure;
namespace Filter.Controllers
{
public class HomeController : Controller
{
// GET: Home
[Authorize(Users ="admin")]
public string Index()
{
return "This is the Index action on the Home controller";
}
}
} |
using System;
namespace Checkout.Payment.Gateway.Seedwork.Interfaces
{
public interface IAuthenticationSettings
{
string ClientId { get; }
string ClientSecret { get; }
string Authority { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTCT.Components.Contacts;
using CTCT.Components;
using CTCT.Util;
using CTCT.Exceptions;
using CTCT.Components.AccountService;
namespace CTCT.Services
{
/// <summary>
/// Performs all actions pertaining to getting list of verified email addresses
/// </summary>
public class AccountService : BaseService, IAccountService
{
/// <summary>
/// Retrieve a list of all the account owner's email addresses
/// </summary>
/// <param name="accessToken">Constant Contact OAuth2 access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <returns>list of all verified account owner's email addresses</returns>
public IList<VerifiedEmailAddress> GetVerifiedEmailAddress(string accessToken, string apiKey)
{
IList<VerifiedEmailAddress> emails = new List<VerifiedEmailAddress>();
// Construct access URL
string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.AccountVerifiedEmailAddressess);
// Get REST response
CUrlResponse response = RestClient.Get(url, accessToken, apiKey);
if (response.HasData)
{
IList<VerifiedEmailAddress> result = response.Get<IList<VerifiedEmailAddress>>();
return result;
}
else
if (response.IsError)
{
throw new CtctException(response.GetErrorMessage());
}
return emails;
}
/// <summary>
/// Get account summary information
/// </summary>
/// <param name="accessToken">Constant Contact OAuth2 access token</param>
/// <param name="apiKey">The API key for the application</param>
/// <returns>An AccountSummaryInformation object</returns>
public AccountSummaryInformation GetAccountSummaryInformation(string accessToken, string apiKey)
{
// Construct access URL
string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.AccountSummaryInformation);
// Get REST response
CUrlResponse response = RestClient.Get(url, accessToken, apiKey);
if (response.HasData)
{
AccountSummaryInformation result = response.Get<AccountSummaryInformation>();
return result;
}
else if (response.IsError)
{
throw new CtctException(response.GetErrorMessage());
}
return new AccountSummaryInformation();
}
/// <summary>
/// Updates account summary information
/// </summary>
/// <param name="accessToken">Constant Contact OAuth2 access token</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="accountSumaryInfo">An AccountSummaryInformation object</param>
/// <returns>An AccountSummaryInformation object</returns>
public AccountSummaryInformation PutAccountSummaryInformation(string accessToken, string apiKey, AccountSummaryInformation accountSumaryInfo)
{
// Construct access URL
string url = String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.AccountSummaryInformation);
string json = accountSumaryInfo.ToJSON();
// Get REST response
CUrlResponse response = RestClient.Put(url, accessToken, apiKey, json);
if (response.HasData)
{
AccountSummaryInformation result = response.Get<AccountSummaryInformation>();
return result;
}
else if (response.IsError)
{
throw new CtctException(response.GetErrorMessage());
}
return new AccountSummaryInformation();
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Ambassador.Entities
{
[DisplayName("Message")]
public class Message
{
[Key]
[Required]
[MaxLength(450)]
public string Id { get; set; }
[Required]
public string Body { get; set; }
[MaxLength(450)]
public string ReplyToId { get; set; }
public Message ReplyTo { get; set; }
[MaxLength(450)]
public string SenderId { get; set; }
public User Sender { get; set; }
public ICollection<MessageReceiver> MessageReceivers { get; set; }
public ICollection<Message> Replies { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Mvc5IdentityExample.Web.Models
{
public class BootGridResponse<TEntity> where TEntity : class
{
public int current { get; set; }
public int rowCount { get; set; }
public List<TEntity> rows { get; set; }
public int total { get; set; }
public string msg { get; set; }
public BootGridResponse()
{
rows = new List<TEntity>();
}
}
} |
using Ambassador.Entities;
namespace System.Security.Claims
{
public static class ClaimsPrincipalExtensions
{
public static string GetId(this ClaimsPrincipal principal)
{
return principal.FindFirstValue(nameof(User.Id));
}
public static string GetAmbassadorId(this ClaimsPrincipal principal)
{
return principal.FindFirstValue(nameof(User.AmbassadorId));
}
public static string GetOrganizationId(this ClaimsPrincipal principal)
{
return principal.FindFirstValue(nameof(User.OrganizationId));
}
public static string GetUserType(this ClaimsPrincipal principal)
{
return principal.FindFirstValue(nameof(User.UserType));
}
}
}
|
using System;
namespace Soko.Data.QueryModel
{
[Serializable]
public enum AssociationFetchMode
{
Default = 0,
Lazy = 1,
Eager = 2,
}
public class AssociationFetch
{
private string associationPath;
public string AssociationPath
{
get { return associationPath; }
set { associationPath = value; }
}
private AssociationFetchMode fetchMode;
public AssociationFetchMode FetchMode
{
get { return fetchMode; }
set { fetchMode = value; }
}
public AssociationFetch(string associationPath, AssociationFetchMode fetchMode)
{
this.associationPath = associationPath;
this.fetchMode = fetchMode;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using entidades = RegistroPersonas.Dominio;
namespace RegistroPersonas.Repositorio
{
public class Foto
{
Contexto context;
public Foto()
{
context = new Contexto();
}
public void GuardarFoto(entidades.Foto foto)
{
foto.Id = Guid.NewGuid();
context.Fotos.Add(foto);
context.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPF_Converter
{
class Aktie
{
public string Unternehmen { get; set; }
public double Wert { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProyectoFinalParadigmas
{
public partial class ver_viajes : Form
{
Basededatos bd;
public ver_viajes()
{
InitializeComponent();
//abre el archivo y carga en el combobox la lista de viajes comprados por el usuario
bd = Archivo.Open();
List<viaje> viajes = bd.usuario_activo.viajes;
foreach (var item in viajes)
comboBox1.Items.Add(item);
}
//carga en los campos la información del viaje seleccionado
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
button2.Enabled = true;
viaje selec = comboBox1.SelectedItem as viaje;
textBox1.Text = selec.dev_origen(); //ORIGEN
textBox2.Text = selec.dev_destino(); //DESTINO
textBox3.Text = selec.dev_categoria(); //CATEGORIA
textBox4.Text = selec.dev_empresa(); //EMPRESA
textBox5.Text = selec.dev_fecha(); //FECHA
textBox6.Text = selec.dev_hora(); //HORA
textBox7.Text = (selec.asientos_libres().Last()).ToString(); //ASIENTO COMPRADO
textBox8.Text = selec.devolver_tipo(); //TIPO DE PASAJE
}
//cancela el viaje seleccionado
private void button2_Click(object sender, EventArgs e)
{
//vacia los campos
textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
textBox5.Text = textBox6.Text = textBox7.Text = "";
textBox8.Text = comboBox1.Text = "";
viaje selec = comboBox1.SelectedItem as viaje;
string empresa = selec.dev_empresa();
//recoge el asiento devuelto...
int asiento_devuelto = selec.asientos_libres().Last();
//elimina el viaje
bd.usuario_activo.viajes.Remove(selec);
//devuelve el asiento al viaje
foreach (var item in bd.viajes)
if (item.dev_colectivo() == selec.dev_colectivo())
{
item.cargar_asiento(asiento_devuelto);
}
//y actualiza los viajes disponibles en el combobox
comboBox1.Items.Clear();
foreach (var item in bd.usuario_activo.viajes)
comboBox1.Items.Add(item);
bd.Save();
}
//cierra ventana y abre ventana de "Seleccionar nuevo viaje"
private void button3_Click(object sender, EventArgs e)
{
this.Close();
seleccionar_viaje nuevo = new seleccionar_viaje();
nuevo.Show();
}
//cierra la ventana
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using mTransport.Methodes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mTransport.Models
{
public partial class Vehicule : ICRUD
{
public void Insert()
{
using (DB db = new DB())
{
db.Vehicules.Add(this);
db.SaveChanges();
}
}
public void Update()
{
using (DB db = new DB())
{
db.Entry(this).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
//Méthode ne necessitant pas la création d'un objet est a déclarée static
public static List<Vehicule> getAll()
{
using (DB db = new DB())
{
List<Vehicule> l = db.Vehicules.Where(i => i.Supprime == false).ToList();
foreach (var item in l)
{
item.BenneEngin = BenneEngin.getUnBenneEngin(item.IdBenneEngins.Value);
item.TeteEngin = TeteEngin.getTeteEngin(item.IdTeteEngins.Value);
}
return l;
}
}
public static Vehicule getVehicule(int Id)
{
using (DB db = new DB())
{
Vehicule c = new Vehicule();
c = db.Vehicules.SingleOrDefault(i => i.Id == Id);
return c;
}
}
public void Delete()
{
Update();
}
}
}
|
using Insurance.Model.Poco;
namespace Insurance.Model.App.Osago
{
public class OsagoCompanyGroup
{
public int GroupId { get; set; }
public double K { get; set; }
public static explicit operator OsagoCompanyGroup(CompanyGroup companyGroup)
{
return new OsagoCompanyGroup
{
GroupId = companyGroup.GroupId,
K = companyGroup.K,
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace MKService.Messages
{
public class UserAddedMageToArmy : MessageBase
{
[DataMember]
public Guid Id { get; set; }
[DataMember]
public Guid UserId { get; set; }
[DataMember]
public Guid InstantiatedId { get; set; }
}
public class UserAddedMageToInventory : MessageBase
{
[DataMember]
public Guid Id { get; set; }
[DataMember]
public Guid UserId { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
// Ability that the unit can cast if they're on a retreatable hex.
// Removes the unit from combat.
public class Retreat : Ability
{
public Retreat(Unit owner)
: base("Retreat", "There is no honour in pointless defeat. Retreats this unit from combat.", owner, 0, false,
"PowerSmash")
{
cast_before_attack = true;
effects_self = false;
}
public override void CastAbility()
{
base.CastAbility();
Debug.Log("Retreat ability on unit: " + caster.u_name);
caster.RetreatUnit();
}
}
|
using Sitecore.Collections;
using Sitecore.Search;
namespace Aqueduct.SitecoreLib.Search.Parameters
{
public class FieldValueSearchParam : SearchParam
{
public FieldValueSearchParam()
{
Refinements = new SafeDictionary<string>();
}
public QueryOccurance Occurance { get; set; }
public SafeDictionary<string> Refinements { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class Drone : MonoBehaviour {
static int moveLayerMask = (1<<8) + (1<<9); // avoid wall and objects
public float speed = 1.0f;
public float flyForce = 100.0f;
public float flySpeedMax = 3.0f;
public Vector2 Home;
Vector2 goal;
Animator animator;
CircleCollider2D cc2;
AgentHealth ah;
void Start() {
animator = GetComponent<Animator>();
cc2 = (CircleCollider2D)this.collider2D;
ah = GetComponent<AgentHealth>();
goal = Home;
}
void SetRandomGoal() {
goal = Home + 2.7f*Random.insideUnitCircle;
}
bool CanMove(Vector2 m) {
return !Tools.ThreeRayTest2D(cc2, transform, m, 0.1f, 0.5f, moveLayerMask);
}
void Update() {
animator.SetBool("dead", ah.IsDead);
if(ah.IsDead) return;
if(needNewGoal) {
SetRandomGoal();
needNewGoal = false;
}
}
bool needNewGoal = false;
void FixedUpdate() {
if(ah.IsDead) return;
Vector2 dx = goal - this.transform.position.XY();
float dxb = dx.magnitude;
if(dxb < 0.1) {
needNewGoal = true;
return;
}
// check if move possible
if(!CanMove(dx)) {
needNewGoal = true;
return;
}
// move
Vector2 move = (Time.deltaTime*speed/dxb)*dx;
this.transform.position += move.XY0();
// Vector2 force = (flyForce/dxb)*dx;
// rigidbody2D.AddForce(force);
// // limit speed for horizontal movement
// float vx = rigidbody2D.velocity.x;
// if(Mathf.Abs(vx) > flySpeedMax) {
// rigidbody2D.velocity = new Vector2(Mathf.Sign(vx)*flySpeedMax, rigidbody2D.velocity.y);
// }
// flip if necessary
this.transform.localScale = new Vector3((dx.x < 0 ? -1 : +1), 1, 1);
}
}
|
using System.Collections.Generic;
namespace Microsoft.DataStudio.Solutions.Model
{
public class SolutionResource
{
public string ResourceId;
public string ResourceUrl;
public string ResourceName;
public string ResourceType;
public string ResourceNamespace;
public string ProvisioningState;
public ProvisioningState State;
public ProvisioningState CombinedState;
public string StatusCode;
public string StatusMessage;
public string OperationId;
public List<SolutionResource> Dependencies;
public SolutionResource()
{
}
public SolutionResource(SolutionResource solnResource)
{
this.ResourceId = solnResource.ResourceId;
this.ResourceUrl = solnResource.ResourceUrl;
this.ResourceName = solnResource.ResourceName;
this.ResourceType = solnResource.ResourceType;
this.ResourceNamespace = solnResource.ResourceNamespace;
this.ProvisioningState = solnResource.ProvisioningState;
this.State = solnResource.State;
this.CombinedState = solnResource.CombinedState;
this.StatusCode = solnResource.StatusCode;
this.StatusMessage = solnResource.StatusMessage;
this.OperationId = solnResource.OperationId;
}
}
}
|
using heitech.MediatorMessenger.Exceptions;
using heitech.MediatorMessenger.Interface;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("heitech.MediatorMessenger.Tests")]
namespace heitech.MediatorMessenger.Implementation.Registerer
{
internal class Registerer<TKey> : IRegisterer<TKey>
{
public IMediator<TKey> Mediator { get; }
protected Dictionary<TKey, IMessenger<TKey>> Messengers { get; }
= new Dictionary<TKey, IMessenger<TKey>>();
internal Registerer(IInternalMediatorMessenger<TKey> mediator)
{
Mediator = mediator;
mediator.SetRegisterer(this);
}
public void Register(IMessenger<TKey> messenger)
{
TKey key = messenger.MessengerIdentifier;
if (!Messengers.ContainsKey(key))
{
Messengers.Add(messenger.MessengerIdentifier, messenger);
}
else throw new MessengerIdentifierAlreadyRegisteredException($"{key.ToString()} already registered");
}
public void Unregister(TKey address)
{
if (Messengers.ContainsKey(address))
{
Messengers.Remove(address);
}
else throw new MessengerIdentifierNotRegisteredException($"{address.ToString()} not registered");
}
public void Unregister(IMessenger<TKey> messenger)
{
Unregister(messenger.MessengerIdentifier);
}
public bool IsRegistered(TKey key)
{
return Messengers.ContainsKey(key);
}
public IMessenger<TKey> Get(TKey key)
{
if (Messengers.TryGetValue(key, out IMessenger<TKey> messenger))
{
return messenger;
}
else
{
throw new MessengerIdentifierNotRegisteredException($"{key.ToString()} not registered");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FeedBackPlatformWeb.Models
{
public class SidebarModel
{
public string CurrentPage { get; set; }
}
} |
using System;
using Microsoft.Xna.Framework;
using SprintFour.Player;
using SprintFour.Player.MarioStates;
using SprintFour.Utilities;
using SprintFour.Background;
namespace SprintFour.Triggers
{
class TransitionToUndergroundTrigger : ITrigger
{
public Vector2 Position { get; protected set; }
public Rectangle Bounds { get { return new Rectangle((int)Position.X, (int)Position.Y, Utility.BLOCK_POSITION_SCALE*Utility.TWO, Utility.BLOCK_POSITION_SCALE); } }
bool playerTransitioning;
IMario player;
float timer;
float playerY;
public TransitionToUndergroundTrigger(Vector2 position){
Position = position;
playerTransitioning = false;
}
public void PlayerTrigger(IMario mario) {
if (!(mario.CurrentState is CrouchingMarioState) || playerTransitioning) return;
playerTransitioning = true;
player = mario;
timer = Utility.ZERO;
playerY = mario.Position.Y;
mario.IsInWarpPipe = true;
SoundManager.Pause();
SoundManager.PlayDamageOrPipeSound();
}
public void Update() {
if (!playerTransitioning) return;
player.Position = new Vector2(Bounds.X + Bounds.Width / (int)Math.Pow(Utility.TWO, Utility.TWO), playerY);
player.Velocity = Vector2.Zero;
timer++;
playerY++;
if (!(timer >= Utility.TRANSITION_DOWN_DELAY)) return;
player.Position = Utility.UndergroundEntryPoint;
playerTransitioning = false;
player.IsInWarpPipe = false;
player.CurrentState = new JumpingMarioState(true, player.CurrentState.Row, player);
Camera.SetCameraBoundariesForUnderground();
SoundManager.State = BGMusicState.Underground;
BackgroundImageCollection.Instance.Visible = false;
}
}
}
|
using Microsoft.Practices.Prism.Regions;
namespace Torshify.Radio.Framework
{
public interface IRadioStation
{
void OnTuneIn(NavigationContext context);
void OnTuneAway(NavigationContext context);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartMenu : MonoBehaviour {
public OSButton button;
private bool hover = false;
public void OnMouseEnter() {
hover = true;
}
public void OnMouseExit() {
hover = false;
}
public void Update() {
if (Input.GetMouseButtonDown(0)) {
if(!hover) {
if (gameObject.activeSelf)
gameObject.SetActive(false);
button.InActive();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise1 {
class Program {
static void Main(string[] args) {
//2.1.3
var songs = new Song[] {
new Song("あいうえお", "かきくけこ", 200),
new Song("あいうえお", "かきくけこ", 100),
new Song("あいうえお", "かきくけこ", 220)
};
PrintSongs(songs);
}
private static void PrintSongs(Song[] songs) {
foreach(var song in songs) {
Console.WriteLine("タイトル:{0}",song.Title);
Console.WriteLine("アーティスト名:{0}", song.ArtistName);
Console.WriteLine("演奏時間:{0}:{1}",song.Length/60,song.Length%60);
}
}
}
}
|
using Frontend.Core.Model.Interfaces;
namespace Frontend.Core.Helpers
{
public interface IDirectoryHelper
{
string GetConverterWorkingDirectory(IConverterSettings currentConverter);
}
} |
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.VisualBasic;
namespace trpo_lw7.Models
{
public class TracksByYear
{
public int Year { get; set; }
public int TrNum { get; set; }
}
public class AvgByGenre
{
public genre Genre { get; set; }
public double AvgDur { get; set; }
}
public class TracksByMusician
{
public string Mus { get; set; }
public int TrNum { get; set; }
}
public class StatisticsData
{
public int NumOfTracks;
public int NumOfMusicians;
public List<TracksByYear> NumOfTracksByYear;
public List<AvgByGenre> AvgDurationByGenre;
public List<TracksByMusician> NumOfTracksByMusician;
public TracksDBContext db;
public StatisticsData(TracksDBContext db)
{
this.db = db;
this.NumOfTracks = this.db.Tracks.ToList().Count();
this.NumOfMusicians = this.db.Musicians.Count();
this.NumOfTracksByYear = this.db.Tracks.ToList().GroupBy(
track => track.Year,
track => track.Id,
(year, id) => new TracksByYear
{
Year = year,
TrNum = id.Count(),
}).ToList();
this.AvgDurationByGenre = this.db.Tracks.ToList().GroupBy(
track => track.Genre,
track => track.DurationInSeconds,
(genre, dur) => new AvgByGenre
{
Genre = genre,
AvgDur = dur.Average(),
}).ToList();
this.NumOfTracksByMusician = this.db.Musicians.ToList().GroupBy(
musician => musician,
musician => musician.Tracks?.Count() ?? 0,
(musician, trNum) => new TracksByMusician
{
Mus = musician.StageName,
TrNum = trNum.ToArray()[0],
}).ToList();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TemporaryEmploymentCorp.Helpers.ReportViewer;
using TemporaryEmploymentCorp.Modules;
namespace TemporaryEmploymentCorp.Reports.Qualifications
{
/// <summary>
/// Interaction logic for QualificationsReportWindow.xaml
/// </summary>
public partial class QualificationsReportWindow : Window
{
private ReportViewBuilder _reportView;
private string _titleFilter = string.Empty;
public QualificationsReportWindow()
{
InitializeComponent();
_reportView = new ReportViewBuilder("TemporaryEmploymentCorp.Reports.Qualifications.QualificationsReport.rdlc", UpdateDatasetSource());
_reportView.RefreshDataSourceCallback = UpdateDatasetSource;
ReportContainer.Content = _reportView.ReportContent;
DataContext = this;
}
private IReadOnlyCollection<DataSetValuePair> UpdateDatasetSource()
{
var sources = new List<DataSetValuePair>();
//var selectedPublisher = (Application.Current.Resources["Locator"] as ViewModelLocator).PublisherModule;
var qualifications = ViewModelLocatorStatic.Locator.QualificationModule.Qualifications.Select(c => c.Model);
//var books = selectedPublisher.Books.Select(c => c.Model);
//clear sources for filtering. use where.
sources.Add(new DataSetValuePair("QualificationDataset", qualifications.Where(c => TitleFilter != null && c.QualificationCode.ToLowerInvariant().Contains(TitleFilter.ToLowerInvariant()))));
//sources.Add(new DataSetValuePair("BooksDataset", books.Where(c => TitleFilter != null && c.Title.ToLowerInvariant().Contains(TitleFilter.ToLowerInvariant()))));
return sources;
}
public string TitleFilter
{
get { return _titleFilter; }
set
{
_titleFilter = value;
_reportView.ReportContent.UpdateDataSource(UpdateDatasetSource());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace adDataWeb.Models
{
public class Advertiser
{
public int? ID { get; set; }
public string Month { get; set; }
public int? PublicationId { get; set; }
public string PublicationName { get; set; }
public string ParentCompany { get; set; }
public int? ParentCompanyId { get; set; }
public string BrandName { get; set; }
public int? BrandId { get; set; }
public string ProductCategory { get; set; }
public float? AdPages { get; set; }
public int? EstPrintSpend { get; set; }
}
public class ProductCategoryClass
{
public string ProductCategory { get; set; }
public int? EstPrintSpend { get; set; }
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Business.Generics;
using Core.Utilities.Results;
using Entities.Concrete;
using Entities.DTOs;
namespace Business.Abstract
{
public interface IProductService:IGenericCrudOperationService<Product>
{
Task<IDataResult<int>> GetByIdAdd(Product product);
IDataResult<List<ProductDetailDto>> GetProductDetails();
IDataResult<List<ProductDetailDto>> GetProductDetailsByMinPriceAndMaxPrice(decimal minPrice,decimal maxPrice);
IDataResult<List<ProductDetailDto>> GetProductDetailsFilteredDesc();
IDataResult<List<ProductDetailDto>> GetProductDetailsFilteredAsc();
IDataResult<List<ProductDetailDto>> GetProductDetailsEvaluation();
IDataResult<List<ProductDetailDto>> GetProductDetailByCategoryId(int categoryId);
IDataResult<List<ProductDetailDto>> GetProductDetailByProductId(int productId);
IDataResult<List<ProductDetailDto>> GetProductDetailByBrandId(int brandId);
IDataResult<List<ProductDetailDto>> GetLimitedProductDetailsByProduct(int limit);
IDataResult<List<ProductDetailDto>> GetAllProductDetailsByProductWithPage(int page, int pageSize);
Task<IDataResult<List<Product>>> GetAllByCategory(int categoryId);
}
} |
namespace RMAT3.Models
{
public class StateLookup
{
public int StateLookupId { get; set; }
public string StateCd { get; set; }
public string StateTxt { get; set; }
public int? CountryLookupId { get; set; }
public virtual CountryLookup CountryLookup { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using InControl;
public class PlayerActions : PlayerActionSet {
public PlayerAction Left;
public PlayerAction Right;
public PlayerOneAxisAction Horizontal;
public PlayerAction Down;
public PlayerAction Up;
public PlayerOneAxisAction Vertical;
public PlayerAction Shoot;
public PlayerAction Special;
public PlayerAction Dash;
public PlayerAction Confirm;
public PlayerAction Back;
public PlayerAction Pause;
public PlayerActions()
{
Left = CreatePlayerAction("Left");
Right = CreatePlayerAction("Right");
Horizontal = CreateOneAxisPlayerAction(Left, Right);
Down = CreatePlayerAction("Down");
Up = CreatePlayerAction("Up");
Vertical = CreateOneAxisPlayerAction(Down, Up);
Shoot = CreatePlayerAction("Shoot");
Special = CreatePlayerAction("Special");
Dash = CreatePlayerAction("Dash");
Confirm = CreatePlayerAction("Confirm");
Back = CreatePlayerAction("Back");
Pause = CreatePlayerAction("Pause");
}
}
|
// Problem 6. Strings and Objects
// Declare two string variables and assign them with Hello and World .
// Declare an object variable and assign it with the concatenation of the first
// two variables (mind adding an interval between).
// Declare a third string variable and initialize it with the value of the object
// variable (you should perform type casting).
using System;
namespace Problem06StringsAndObjects
{
class StringsAndObjects
{
static void Main()
{
string str1 = "Hello";
string str2 = "World";
object newObj = str1 + " " + str2;
string finalString = (string)newObj;
Console.WriteLine("Final string is: {0}", finalString);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Toggles : MonoBehaviour
{
public Color[] UiColors;
public GameObject UIgeneral;
public GameObject UIminiatura;
public GameObject panel_rotacion;
public GameObject panel_fuerza;
public GameObject modelo;
public GameObject F_Y;
public GameObject F_X;
public InputField F_X_text;
public InputField F_Y_text;
public InputField F_Z_text;
public Toggle r_X;
public Toggle r_Z;
public Text num;
public Text controlador;
public GameObject Image_R;
public GameObject Image_F;
public GameObject cube;
public PackageManajer packageManajer;
private bool rotar;
float angle = 360.0f; // Degree per time unit
float time = 1.0f; // Time unit in sec
Vector3 axis = Vector3.up; // Rotation axis, here it the yaw axis
// Start is called before the first frame update
void Start()
{
// Image_F.SetActive(false);
}
// Update is called once per frame
void Update()
{
bool cargado=true;
if (controlador.text != num.text)
{
UIminiatura.SetActive(true);
UIgeneral.SetActive(false);
RectTransform rt = modelo.GetComponent<RectTransform>();
rt.sizeDelta = new Vector2(153f, 26f);
}
foreach(float i in packageManajer.intermedio.Keys)
{
float num_f = float.Parse(num.text);
if (num_f== i && packageManajer.pTypes[int.Parse(num_f+"")].quantity==packageManajer.intermedio[i])
{
UIminiatura.GetComponent<Image>().color = UiColors[0];
cargado = false;
}
if (num_f == i && packageManajer.pTypes[int.Parse(num_f + "")].quantity > packageManajer.intermedio[i])
{
UIminiatura.GetComponent<Image>().color = UiColors[1];
cargado = false;
}
}
if(cargado)
{
UIminiatura.GetComponent<Image>().color = UiColors[2];
}
}
public void Rotacion ( bool mostrar)
{
panel_rotacion.SetActive(mostrar);
if (r_X.isOn) {F_X.SetActive(mostrar); }
if (r_Z.isOn) { F_Y.SetActive(mostrar); }
Image_R.SetActive(mostrar);
rotar = mostrar;
//var rot = cube.transform.rotation;
}
public void fuerza(bool mostrar)
{
panel_fuerza.SetActive(mostrar);
Image_F.SetActive(mostrar);
if (mostrar)
{
F_X_text.text = 0f + "";
F_Y_text.text = 0f + "";
F_Z_text.text = 0f + "";
}
else
{
F_X_text.text = 400000f + "";
F_Y_text.text = 4000000f + "";
F_Z_text.text = 400000f + " ";
}
}
public void R_X(bool mostrar)
{
if (mostrar)
{
F_X_text.text = 0f + " ";
}
else
{
F_X_text.text = 40000f + " ";
}
F_X.SetActive(mostrar);
}
public void R_Z(bool mostrar)
{
if (mostrar)
{
F_Y_text.text = 0f + " ";
}
else
{
F_Y_text.text = 40000f + " ";
}
F_Y.SetActive(mostrar);
}
public void deletePackage()
{
GameObject.Destroy(modelo);
PackageManajer.instance.deletePackageType(int.Parse(num.text));
}
}
|
using ApplicationCore.Entities.PatientAggregate;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ApplicationCore.Entities.DoctorAggregate;
using ApplicationCore.Entities;
namespace Infrastructure.Persistence
{
public class DataSeed
{
public static void Initialize(RegisterContext context)
{
context.Database.EnsureCreated();
// DB has seeded
if (context.Enrollments.Any()) return;
var patients = new Patient[]
{
new Patient
{
PatientId="A001",
PatientName="Nguyen Ha",
Gender = true,
Birthday = System.DateTime.Parse("1989-12-6"),
Address = new Address("198","Đường số 12","Quận 1", "TPHCM","Việt Nam"),
Phone = "0337859647"
},
new Patient
{
PatientId = "B004",
PatientName="Van Duc",
Gender = false,
Birthday = System.DateTime.Parse("1996-8-9"),
Address = new Address("19","Nguyễn Thượng Hiền","Quận 1", "TPHCM","Việt Nam"),
Phone = "09794567895"
},
new Patient
{
PatientId = "T008",
PatientName="Văn Trung",
Gender = false,
Birthday = System.DateTime.Parse("1996-8-10"),
Address = new Address("19","Nguyễn Thượng Hiền","Quận 1", "TPHCM","Việt Nam"),
Phone = "09794567878"
},
new Patient
{
PatientId = "T745",
PatientName="Nguyễn Thị Hoa",
Gender = true,
Birthday = System.DateTime.Parse("1996-10-9"),
Address = new Address("19","Nguyễn Thượng Hiền","Quận 1", "TPHCM","Việt Nam"),
Phone = "03694567895"
}
};
foreach (Patient p in patients)
{
context.Patients.Add(p); // cung ten voi DbSet<Patient> Patient trong RegisterContext
}
context.SaveChanges();
var doctors = new Doctor[]
{
new Doctor("S001","Nguyen A", System.DateTime.Parse("1986-8-7"), "0334578965"),
new Doctor("H008","Nguyen B", System.DateTime.Parse("1988-5-1"), "0975658745")
};
foreach (Doctor d in doctors)
{
context.Doctors.Add(d); // cung ten voi DbSet<Patient> Patient trong RegisterContext
}
context.SaveChanges();
var enrollments = new Enrollments[]
{
// new Enrollment {
// StudentID = students.Single(s => s.LastName == "Alexander").ID,
// CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
// Grade = Grade.A
// },
new Enrollments {
PatientId = patients.Single(p => p.PatientName == "Nguyen Ha").PatientId,
DoctorId = doctors.Single(d => d.DoctorName == "Nguyen A").DoctorId,
enrollmentDate = new EnrollmentDate{
Date = System.DateTime.Parse("14"),
Month = System.DateTime.Parse("2"),
Year = System.DateTime.Parse("2020"),
Time = System.DateTime.Parse("14:00:00")
}
},
new Enrollments {
PatientId = patients.Single(p => p.PatientName == "Van Duc").PatientId,
DoctorId = doctors.Single(d => d.DoctorName == "Nguyen B").DoctorId,
enrollmentDate = new EnrollmentDate{
Date = System.DateTime.Parse("11"),
Month = System.DateTime.Parse("1"),
Year = System.DateTime.Parse("2020"),
Time = System.DateTime.Parse("11:30:00")
}
}
};
foreach (Enrollments e in enrollments)
{
var enrollmentInData = context.Enrollments.Where(
s =>
s.patient.PatientId == e.PatientId &&
s.doctor.DoctorId == e.DoctorId).SingleOrDefault();
if (enrollmentInData == null)
{
context.Enrollments.Add(e);
}
context.Enrollments.Add(e); // cung ten voi DbSet<Patient> Patient trong RegisterContext
}
context.SaveChanges();
}
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_Particle : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
Particle particle = default(Particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_position(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_position());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_position(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
Vector3 position;
LuaObject.checkType(l, 2, out position);
particle.set_position(position);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_velocity(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_velocity());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_velocity(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
Vector3 velocity;
LuaObject.checkType(l, 2, out velocity);
particle.set_velocity(velocity);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_energy(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_energy());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_energy(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
float energy;
LuaObject.checkType(l, 2, out energy);
particle.set_energy(energy);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_startEnergy(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_startEnergy());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_startEnergy(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
float startEnergy;
LuaObject.checkType(l, 2, out startEnergy);
particle.set_startEnergy(startEnergy);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_size(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_size());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_size(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
float size;
LuaObject.checkType(l, 2, out size);
particle.set_size(size);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_rotation(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_rotation());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_rotation(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
float rotation;
LuaObject.checkType(l, 2, out rotation);
particle.set_rotation(rotation);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_angularVelocity(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_angularVelocity());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_angularVelocity(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
float angularVelocity;
LuaObject.checkType(l, 2, out angularVelocity);
particle.set_angularVelocity(angularVelocity);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_color(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, particle.get_color());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_color(IntPtr l)
{
int result;
try
{
Particle particle;
LuaObject.checkValueType<Particle>(l, 1, out particle);
Color color;
LuaObject.checkType(l, 2, out color);
particle.set_color(color);
LuaObject.setBack(l, particle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.Particle");
LuaObject.addMember(l, "position", new LuaCSFunction(Lua_UnityEngine_Particle.get_position), new LuaCSFunction(Lua_UnityEngine_Particle.set_position), true);
LuaObject.addMember(l, "velocity", new LuaCSFunction(Lua_UnityEngine_Particle.get_velocity), new LuaCSFunction(Lua_UnityEngine_Particle.set_velocity), true);
LuaObject.addMember(l, "energy", new LuaCSFunction(Lua_UnityEngine_Particle.get_energy), new LuaCSFunction(Lua_UnityEngine_Particle.set_energy), true);
LuaObject.addMember(l, "startEnergy", new LuaCSFunction(Lua_UnityEngine_Particle.get_startEnergy), new LuaCSFunction(Lua_UnityEngine_Particle.set_startEnergy), true);
LuaObject.addMember(l, "size", new LuaCSFunction(Lua_UnityEngine_Particle.get_size), new LuaCSFunction(Lua_UnityEngine_Particle.set_size), true);
LuaObject.addMember(l, "rotation", new LuaCSFunction(Lua_UnityEngine_Particle.get_rotation), new LuaCSFunction(Lua_UnityEngine_Particle.set_rotation), true);
LuaObject.addMember(l, "angularVelocity", new LuaCSFunction(Lua_UnityEngine_Particle.get_angularVelocity), new LuaCSFunction(Lua_UnityEngine_Particle.set_angularVelocity), true);
LuaObject.addMember(l, "color", new LuaCSFunction(Lua_UnityEngine_Particle.get_color), new LuaCSFunction(Lua_UnityEngine_Particle.set_color), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Particle.constructor), typeof(Particle), typeof(ValueType));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02_Uygulama
{
interface IYuzebilir
{
string Yuz();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PushoverQ.PerformanceConsole
{
/// <summary>
/// The program.
/// </summary>
public class Program
{
static void Main(string[] args)
{
using (var large = new LargePublishPerformance())
{
large.Run().Wait();
}
using (var small = new SmallPublishPerformance())
{
small.Run().Wait();
}
}
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("AdventureMissionDisplay")]
public class AdventureMissionDisplay : MonoBehaviour
{
public AdventureMissionDisplay(IntPtr address) : this(address, "AdventureMissionDisplay")
{
}
public AdventureMissionDisplay(IntPtr address, string className) : base(address, className)
{
}
public void AddAssetToLoad(int assetCount)
{
object[] objArray1 = new object[] { assetCount };
base.method_8("AddAssetToLoad", objArray1);
}
public void AssetLoadCompleted()
{
base.method_8("AssetLoadCompleted", Array.Empty<object>());
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public int BossCreateParamsSortComparison(BossCreateParams params1, BossCreateParams params2)
{
object[] objArray1 = new object[] { params1, params2 };
return base.method_11<int>("BossCreateParamsSortComparison", objArray1);
}
public void BringWingToFocus(float scrollPos)
{
object[] objArray1 = new object[] { scrollPos };
base.method_8("BringWingToFocus", objArray1);
}
public List<WingCreateParams> BuildWingCreateParamsList()
{
Class267<WingCreateParams> class2 = base.method_14<Class267<WingCreateParams>>("BuildWingCreateParamsList", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public void ChangeToDeckPicker()
{
base.method_8("ChangeToDeckPicker", Array.Empty<object>());
}
public Vector3 DetermineCharacterQuotePos(GameObject coin)
{
object[] objArray1 = new object[] { coin };
return base.method_11<Vector3>("DetermineCharacterQuotePos", objArray1);
}
public void DisableSelection(bool yes)
{
object[] objArray1 = new object[] { yes };
base.method_8("DisableSelection", objArray1);
}
public void DoAutoPurchaseWings(AdventureDbId selectedAdv, AdventureModeDbId selectedMode)
{
object[] objArray1 = new object[] { selectedAdv, selectedMode };
base.method_8("DoAutoPurchaseWings", objArray1);
}
public static AdventureMissionDisplay Get()
{
return MonoClass.smethod_15<AdventureMissionDisplay>(TritonHs.MainAssemblyPath, "", "AdventureMissionDisplay", "Get", Array.Empty<object>());
}
public void HideHeroPowerBigCard()
{
base.method_8("HideHeroPowerBigCard", Array.Empty<object>());
}
public bool IsDisabledSelection()
{
return base.method_11<bool>("IsDisabledSelection", Array.Empty<object>());
}
public Actor OnActorLoaded(string actorName, GameObject actorObject, GameObject container)
{
object[] objArray1 = new object[] { actorName, actorObject, container };
return base.method_14<Actor>("OnActorLoaded", objArray1);
}
public void OnAdventureProgressUpdate(bool isStartupAction, AdventureMission.WingProgress oldProgress, AdventureMission.WingProgress newProgress, object userData)
{
object[] objArray1 = new object[] { isStartupAction, oldProgress, newProgress, userData };
base.method_8("OnAdventureProgressUpdate", objArray1);
}
public void OnBackButtonPress(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnBackButtonPress", objArray1);
}
public void OnBossSelected(AdventureBossCoin coin, ScenarioDbId mission, bool showDetails)
{
object[] objArray1 = new object[] { coin, mission, showDetails };
base.method_8("OnBossSelected", objArray1);
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void OnEndUnlockPlate(AdventureWing wing)
{
object[] objArray1 = new object[] { wing };
base.method_8("OnEndUnlockPlate", objArray1);
}
public void OnHeroActorLoaded(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("OnHeroActorLoaded", objArray1);
}
public void OnHeroFullDefLoaded(string cardId, FullDef def, object userData)
{
object[] objArray1 = new object[] { cardId, def, userData };
base.method_8("OnHeroFullDefLoaded", objArray1);
}
public void OnHeroPowerActorLoaded(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("OnHeroPowerActorLoaded", objArray1);
}
public void OnHeroPowerBigCardLoaded(string actorName, GameObject actorObject, object callbackData)
{
object[] objArray1 = new object[] { actorName, actorObject, callbackData };
base.method_8("OnHeroPowerBigCardLoaded", objArray1);
}
public void OnHeroPowerFullDefLoaded(string cardId, FullDef def, object userData)
{
object[] objArray1 = new object[] { cardId, def, userData };
base.method_8("OnHeroPowerFullDefLoaded", objArray1);
}
public void OnHideRewardsPreview()
{
base.method_8("OnHideRewardsPreview", Array.Empty<object>());
}
public static bool OnNavigateBack()
{
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "AdventureMissionDisplay", "OnNavigateBack", Array.Empty<object>());
}
public void OnRewardObjectLoaded(Reward reward, object callbackData)
{
object[] objArray1 = new object[] { reward, callbackData };
base.method_8("OnRewardObjectLoaded", objArray1);
}
public void OnStartUnlockPlate(AdventureWing wing)
{
object[] objArray1 = new object[] { wing };
base.method_8("OnStartUnlockPlate", objArray1);
}
public void OnStoreHidden(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnStoreHidden", objArray1);
}
public void OnStoreShown(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnStoreShown", objArray1);
}
public void OnSubSceneLoaded()
{
base.method_8("OnSubSceneLoaded", Array.Empty<object>());
}
public void OnSubSceneTransitionComplete()
{
base.method_8("OnSubSceneTransitionComplete", Array.Empty<object>());
}
public void OnZeroCostTransactionStoreExit(bool authorizationBackButtonPressed, object userData)
{
object[] objArray1 = new object[] { authorizationBackButtonPressed, userData };
base.method_8("OnZeroCostTransactionStoreExit", objArray1);
}
public void PlayMissionQuote(AdventureBossDef bossDef, Vector3 position)
{
object[] objArray1 = new object[] { bossDef, position };
base.method_8("PlayMissionQuote", objArray1);
}
public void PositionReward(Reward reward)
{
object[] objArray1 = new object[] { reward };
base.method_8("PositionReward", objArray1);
}
public void ResumeMainMusic()
{
base.method_8("ResumeMainMusic", Array.Empty<object>());
}
public void ShowAdventureComplete()
{
base.method_8("ShowAdventureComplete", Array.Empty<object>());
}
public void ShowAdventureStore(AdventureWing selectedWing)
{
object[] objArray1 = new object[] { selectedWing };
base.method_8("ShowAdventureStore", objArray1);
}
public void ShowBossFrame(ScenarioDbId mission)
{
object[] objArray1 = new object[] { mission };
base.method_8("ShowBossFrame", objArray1);
}
public void ShowHeroPowerBigCard()
{
base.method_8("ShowHeroPowerBigCard", Array.Empty<object>());
}
public void UnselectBoss()
{
base.method_8("UnselectBoss", Array.Empty<object>());
}
public void Update()
{
base.method_8("Update", Array.Empty<object>());
}
public void UpdateWingPositions()
{
base.method_8("UpdateWingPositions", Array.Empty<object>());
}
public int WingCreateParamsSortComparison(WingCreateParams params1, WingCreateParams params2)
{
object[] objArray1 = new object[] { params1, params2 };
return base.method_11<int>("WingCreateParamsSortComparison", objArray1);
}
public float BossWingHeight
{
get
{
return base.method_11<float>("get_BossWingHeight", Array.Empty<object>());
}
}
public Vector3 BossWingOffset
{
get
{
return base.method_11<Vector3>("get_BossWingOffset", Array.Empty<object>());
}
}
public UberText m_AdventureTitle
{
get
{
return base.method_3<UberText>("m_AdventureTitle");
}
}
public int m_AssetsLoading
{
get
{
return base.method_2<int>("m_AssetsLoading");
}
}
public PegUIElement m_BackButton
{
get
{
return base.method_3<PegUIElement>("m_BackButton");
}
}
public Actor m_BossActor
{
get
{
return base.method_3<Actor>("m_BossActor");
}
}
public UberText m_BossDescription
{
get
{
return base.method_3<UberText>("m_BossDescription");
}
}
public bool m_BossJustDefeated
{
get
{
return base.method_2<bool>("m_BossJustDefeated");
}
}
public GameObject m_BossPortraitContainer
{
get
{
return base.method_3<GameObject>("m_BossPortraitContainer");
}
}
public Actor m_BossPowerActor
{
get
{
return base.method_3<Actor>("m_BossPowerActor");
}
}
public Actor m_BossPowerBigCard
{
get
{
return base.method_3<Actor>("m_BossPowerBigCard");
}
}
public float m_BossPowerCardScale
{
get
{
return base.method_2<float>("m_BossPowerCardScale");
}
}
public GameObject m_BossPowerContainer
{
get
{
return base.method_3<GameObject>("m_BossPowerContainer");
}
}
public PegUIElement m_BossPowerHoverArea
{
get
{
return base.method_3<PegUIElement>("m_BossPowerHoverArea");
}
}
public UberText m_BossTitle
{
get
{
return base.method_3<UberText>("m_BossTitle");
}
}
public GameObject m_BossWingBorder
{
get
{
return base.method_3<GameObject>("m_BossWingBorder");
}
}
public GameObject m_BossWingContainer
{
get
{
return base.method_3<GameObject>("m_BossWingContainer");
}
}
public float m_BossWingHeight
{
get
{
return base.method_2<float>("m_BossWingHeight");
}
}
public Vector3 m_BossWingOffset
{
get
{
return base.method_2<Vector3>("m_BossWingOffset");
}
}
public List<AdventureWing> m_BossWings
{
get
{
Class267<AdventureWing> class2 = base.method_3<Class267<AdventureWing>>("m_BossWings");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public PlayButton m_ChooseButton
{
get
{
return base.method_3<PlayButton>("m_ChooseButton");
}
}
public int m_ClassChallengeUnlockShowing
{
get
{
return base.method_2<int>("m_ClassChallengeUnlockShowing");
}
}
public GameObject m_ClickBlocker
{
get
{
return base.method_3<GameObject>("m_ClickBlocker");
}
}
public float m_CoinFlipAnimationTime
{
get
{
return base.method_2<float>("m_CoinFlipAnimationTime");
}
}
public float m_CoinFlipDelayTime
{
get
{
return base.method_2<float>("m_CoinFlipDelayTime");
}
}
public int m_DisableSelectionCount
{
get
{
return base.method_2<int>("m_DisableSelectionCount");
}
}
public MusicPlaylistType m_mainMusic
{
get
{
return base.method_2<MusicPlaylistType>("m_mainMusic");
}
}
public AdventureRewardsPreview m_PreviewPane
{
get
{
return base.method_3<AdventureRewardsPreview>("m_PreviewPane");
}
}
public AdventureWingProgressDisplay m_progressDisplay
{
get
{
return base.method_3<AdventureWingProgressDisplay>("m_progressDisplay");
}
}
public AdventureRewardsDisplayArea m_RewardsDisplay
{
get
{
return base.method_3<AdventureRewardsDisplayArea>("m_RewardsDisplay");
}
}
public UIBScrollable m_ScrollBar
{
get
{
return base.method_3<UIBScrollable>("m_ScrollBar");
}
}
public AdventureBossCoin m_SelectedCoin
{
get
{
return base.method_3<AdventureBossCoin>("m_SelectedCoin");
}
}
public FullDef m_SelectedHeroPowerFullDef
{
get
{
return base.method_3<FullDef>("m_SelectedHeroPowerFullDef");
}
}
public bool m_ShowingRewardsPreview
{
get
{
return base.method_2<bool>("m_ShowingRewardsPreview");
}
}
public int m_TotalBosses
{
get
{
return base.method_2<int>("m_TotalBosses");
}
}
public int m_TotalBossesDefeated
{
get
{
return base.method_2<int>("m_TotalBossesDefeated");
}
}
public bool m_WaitingForClassChallengeUnlocks
{
get
{
return base.method_2<bool>("m_WaitingForClassChallengeUnlocks");
}
}
public MeshRenderer m_WatermarkIcon
{
get
{
return base.method_3<MeshRenderer>("m_WatermarkIcon");
}
}
public List<AdventureWing> m_WingsToGiveBigChest
{
get
{
Class267<AdventureWing> class2 = base.method_3<Class267<AdventureWing>>("m_WingsToGiveBigChest");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public static Vector3 REWARD_PUNCH_SCALE
{
get
{
return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "AdventureMissionDisplay", "REWARD_PUNCH_SCALE");
}
}
public static Vector3 REWARD_SCALE
{
get
{
return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "AdventureMissionDisplay", "REWARD_SCALE");
}
}
public static float s_ScreenBackTransitionDelay
{
get
{
return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "AdventureMissionDisplay", "s_ScreenBackTransitionDelay");
}
}
[Attribute38("AdventureMissionDisplay.BossCreateParams")]
public class BossCreateParams : MonoClass
{
public BossCreateParams(IntPtr address) : this(address, "BossCreateParams")
{
}
public BossCreateParams(IntPtr address, string className) : base(address, className)
{
}
public string m_CardDefId
{
get
{
return base.method_4("m_CardDefId");
}
}
public ScenarioDbId m_MissionId
{
get
{
return base.method_2<ScenarioDbId>("m_MissionId");
}
}
public ScenarioDbfRecord m_ScenarioRecord
{
get
{
return base.method_3<ScenarioDbfRecord>("m_ScenarioRecord");
}
}
}
[Attribute38("AdventureMissionDisplay.BossInfo")]
public class BossInfo : MonoClass
{
public BossInfo(IntPtr address) : this(address, "BossInfo")
{
}
public BossInfo(IntPtr address, string className) : base(address, className)
{
}
public string m_Description
{
get
{
return base.method_4("m_Description");
}
}
public string m_Title
{
get
{
return base.method_4("m_Title");
}
}
}
[Attribute38("AdventureMissionDisplay.WingCreateParams")]
public class WingCreateParams : MonoClass
{
public WingCreateParams(IntPtr address) : this(address, "WingCreateParams")
{
}
public WingCreateParams(IntPtr address, string className) : base(address, className)
{
}
public List<AdventureMissionDisplay.BossCreateParams> m_BossCreateParams
{
get
{
Class267<AdventureMissionDisplay.BossCreateParams> class2 = base.method_3<Class267<AdventureMissionDisplay.BossCreateParams>>("m_BossCreateParams");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public AdventureWingDef m_WingDef
{
get
{
return base.method_3<AdventureWingDef>("m_WingDef");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Framework.Remote.Mobile
{
[DataContract(Name = "CxClientClassMetadata", Namespace = "http://schemas.datacontract.org/2004/07/FulcrumWeb")]
public partial class CxClientClassMetadata
{
//----------------------------------------------------------------------------
[DataMember]
public string Id;
//----------------------------------------------------------------------------
[DataMember]
public string AssemblyId;
//----------------------------------------------------------------------------
[DataMember]
public string Name;
//----------------------------------------------------------------------------
public string ClientSideFolder;
}
}
|
namespace Newtonsoft.Json.Linq
{
using ns20;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
public static class Extensions
{
[CompilerGenerated]
private static Func<JObject, IEnumerable<JProperty>> func_0;
public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T: JToken
{
Class203.smethod_2(source, "source");
return source.SelectMany<T, JToken>(new Func<T, IEnumerable<JToken>>(Extensions.smethod_3<T>)).AsJEnumerable();
}
public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source)
{
return source.AsJEnumerable<JToken>();
}
public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T: JToken
{
if (source == null)
{
return null;
}
if (source is IJEnumerable<T>)
{
return (IJEnumerable<T>) source;
}
return new JEnumerable<T>(source);
}
public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T: JToken
{
return source.Children<T, JToken>().AsJEnumerable();
}
public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T: JToken
{
Class203.smethod_2(source, "source");
return source.SelectMany<T, JToken>(new Func<T, IEnumerable<JToken>>(Extensions.smethod_6<T, U>)).smethod_1<JToken, U>();
}
public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T: JContainer
{
Class203.smethod_2(source, "source");
return source.SelectMany<T, JToken>(new Func<T, IEnumerable<JToken>>(Extensions.smethod_4<T>)).AsJEnumerable();
}
public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source)
{
Class203.smethod_2(source, "source");
if (func_0 == null)
{
func_0 = new Func<JObject, IEnumerable<JProperty>>(Extensions.smethod_5);
}
return source.SelectMany<JObject, JProperty>(func_0).AsJEnumerable<JProperty>();
}
internal static IEnumerable<U> smethod_0<T, U>(this IEnumerable<T> ienumerable_0, object object_0) where T: JToken
{
Class203.smethod_2(ienumerable_0, "source");
this.ienumerator_0 = ienumerable_0.GetEnumerator();
Label_00FB:
while (this.ienumerator_0.MoveNext())
{
this.jtoken_0 = this.ienumerator_0.Current;
if (object_0 == null)
{
if (this.jtoken_0 is JValue)
{
goto Label_0115;
}
this.ienumerator_1 = this.jtoken_0.Children().GetEnumerator();
while (this.ienumerator_1.MoveNext())
{
this.jtoken_1 = this.ienumerator_1.Current;
yield return this.jtoken_1.smethod_2<JToken, U>();
}
this.method_1();
continue;
}
this.jtoken_2 = this.jtoken_0[object_0];
if (this.jtoken_2 != null)
{
yield return this.jtoken_2.smethod_2<JToken, U>();
continue;
}
}
this.method_0();
Label_0115:
yield return ((JValue) this.jtoken_0).smethod_2<JValue, U>();
goto Label_00FB;
}
internal static IEnumerable<U> smethod_1<T, U>(this IEnumerable<T> ienumerable_0) where T: JToken
{
Class203.smethod_2(ienumerable_0, "source");
this.ienumerator_0 = ienumerable_0.GetEnumerator();
while (true)
{
if (!this.ienumerator_0.MoveNext())
{
this.method_0();
}
this.gparam_1 = this.ienumerator_0.Current;
yield return this.gparam_1.smethod_2<JToken, U>();
}
}
internal static U smethod_2<T, U>(this T gparam_0) where T: JToken
{
if (gparam_0 == null)
{
return default(U);
}
if (((gparam_0 is U) && (typeof(U) != typeof(IComparable))) && (typeof(U) != typeof(IFormattable)))
{
return (U) gparam_0;
}
JValue value2 = gparam_0 as JValue;
if (value2 == null)
{
throw new InvalidCastException("Cannot cast {0} to {1}.".smethod_1(CultureInfo.InvariantCulture, gparam_0.GetType(), typeof(T)));
}
if (value2.Value is U)
{
return (U) value2.Value;
}
Type underlyingType = typeof(U);
if (Class194.smethod_10(underlyingType))
{
if (value2.Value == null)
{
return default(U);
}
underlyingType = Nullable.GetUnderlyingType(underlyingType);
}
return (U) Convert.ChangeType(value2.Value, underlyingType, CultureInfo.InvariantCulture);
}
[CompilerGenerated]
private static IEnumerable<JToken> smethod_3<T>(T gparam_0) where T: JToken
{
return gparam_0.Ancestors();
}
[CompilerGenerated]
private static IEnumerable<JToken> smethod_4<T>(T gparam_0) where T: JContainer
{
return gparam_0.Descendants();
}
[CompilerGenerated]
private static IEnumerable<JProperty> smethod_5(JObject jobject_0)
{
return jobject_0.Properties();
}
[CompilerGenerated]
private static IEnumerable<JToken> smethod_6<T, U>(T gparam_0) where T: JToken
{
return gparam_0.Children();
}
public static U Value<U>(this IEnumerable<JToken> value)
{
return value.Value<JToken, U>();
}
public static U Value<T, U>(this IEnumerable<T> value) where T: JToken
{
Class203.smethod_2(value, "source");
JToken token = value as JToken;
if (token == null)
{
throw new ArgumentException("Source value must be a JToken.");
}
return token.smethod_2<JToken, U>();
}
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source)
{
return source.Values(null);
}
public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source)
{
return source.smethod_0<JToken, U>(null);
}
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key)
{
return source.smethod_0<JToken, JToken>(key).AsJEnumerable();
}
public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key)
{
return source.smethod_0<JToken, U>(key);
}
[CompilerGenerated]
private sealed class Class113<T, U> : IDisposable, IEnumerable<U>, IEnumerator<U>, IEnumerable, IEnumerator where T: JToken
{
private U gparam_0;
public IEnumerable<T> ienumerable_0;
public IEnumerable<T> ienumerable_1;
public IEnumerator<T> ienumerator_0;
public IEnumerator<JToken> ienumerator_1;
private int int_0;
private int int_1;
public JToken jtoken_0;
public JToken jtoken_1;
public JToken jtoken_2;
public object object_0;
public object object_1;
[DebuggerHidden]
public Class113(int <>1__state)
{
this.int_0 = <>1__state;
this.int_1 = Thread.CurrentThread.ManagedThreadId;
}
private void method_0()
{
this.int_0 = -1;
if (this.ienumerator_0 != null)
{
this.ienumerator_0.Dispose();
}
}
private void method_1()
{
this.int_0 = 1;
if (this.ienumerator_1 != null)
{
this.ienumerator_1.Dispose();
}
}
private bool MoveNext()
{
try
{
switch (this.int_0)
{
case 0:
this.int_0 = -1;
Class203.smethod_2(this.ienumerable_0, "source");
this.ienumerator_0 = this.ienumerable_0.GetEnumerator();
this.int_0 = 1;
goto Label_00FB;
case 2:
this.int_0 = 1;
goto Label_00FB;
case 4:
this.int_0 = 3;
goto Label_00C7;
case 5:
this.int_0 = 1;
goto Label_00FB;
default:
goto Label_0111;
}
Label_007C:
this.jtoken_0 = this.ienumerator_0.Current;
if (this.object_0 != null)
{
goto Label_00DC;
}
if (this.jtoken_0 is JValue)
{
goto Label_0115;
}
this.ienumerator_1 = this.jtoken_0.Children().GetEnumerator();
this.int_0 = 3;
Label_00C7:
if (this.ienumerator_1.MoveNext())
{
goto Label_0136;
}
this.method_1();
goto Label_00FB;
Label_00DC:
this.jtoken_2 = this.jtoken_0[this.object_0];
if (this.jtoken_2 != null)
{
goto Label_0163;
}
Label_00FB:
if (this.ienumerator_0.MoveNext())
{
goto Label_007C;
}
this.method_0();
Label_0111:
return false;
Label_0115:
this.gparam_0 = ((JValue) this.jtoken_0).smethod_2<JValue, U>();
this.int_0 = 2;
return true;
Label_0136:
this.jtoken_1 = this.ienumerator_1.Current;
this.gparam_0 = this.jtoken_1.smethod_2<JToken, U>();
this.int_0 = 4;
return true;
Label_0163:
this.gparam_0 = this.jtoken_2.smethod_2<JToken, U>();
this.int_0 = 5;
return true;
}
fault
{
this.System.IDisposable.Dispose();
}
}
[DebuggerHidden]
IEnumerator<U> IEnumerable<U>.GetEnumerator()
{
Extensions.Class113<T, U> class2;
if ((Thread.CurrentThread.ManagedThreadId == this.int_1) && (this.int_0 == -2))
{
this.int_0 = 0;
class2 = (Extensions.Class113<T, U>) this;
}
else
{
class2 = new Extensions.Class113<T, U>(0);
}
class2.ienumerable_0 = this.ienumerable_1;
class2.object_0 = this.object_1;
return class2;
}
[DebuggerHidden]
IEnumerator IEnumerable.GetEnumerator()
{
return this.System.Collections.Generic.IEnumerable<U>.GetEnumerator();
}
[DebuggerHidden]
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
switch (this.int_0)
{
case 1:
case 2:
case 3:
case 4:
case 5:
try
{
switch (this.int_0)
{
case 3:
case 4:
try
{
}
finally
{
this.method_1();
}
return;
}
}
finally
{
this.method_0();
}
break;
default:
return;
}
}
U IEnumerator<U>.Current
{
[DebuggerHidden]
get
{
return this.gparam_0;
}
}
object IEnumerator.Current
{
[DebuggerHidden]
get
{
return this.gparam_0;
}
}
}
[CompilerGenerated]
private sealed class Class114<T, U> : IDisposable, IEnumerable<U>, IEnumerator<U>, IEnumerable, IEnumerator where T: JToken
{
private U gparam_0;
public T gparam_1;
public IEnumerable<T> ienumerable_0;
public IEnumerable<T> ienumerable_1;
public IEnumerator<T> ienumerator_0;
private int int_0;
private int int_1;
[DebuggerHidden]
public Class114(int <>1__state)
{
this.int_0 = <>1__state;
this.int_1 = Thread.CurrentThread.ManagedThreadId;
}
private void method_0()
{
this.int_0 = -1;
if (this.ienumerator_0 != null)
{
this.ienumerator_0.Dispose();
}
}
private bool MoveNext()
{
try
{
switch (this.int_0)
{
case 0:
this.int_0 = -1;
Class203.smethod_2(this.ienumerable_0, "source");
this.ienumerator_0 = this.ienumerable_0.GetEnumerator();
this.int_0 = 1;
break;
case 2:
this.int_0 = 1;
break;
default:
goto Label_0066;
}
if (this.ienumerator_0.MoveNext())
{
goto Label_006A;
}
this.method_0();
Label_0066:
return false;
Label_006A:
this.gparam_1 = this.ienumerator_0.Current;
this.gparam_0 = this.gparam_1.smethod_2<JToken, U>();
this.int_0 = 2;
return true;
}
fault
{
this.System.IDisposable.Dispose();
}
}
[DebuggerHidden]
IEnumerator<U> IEnumerable<U>.GetEnumerator()
{
Extensions.Class114<T, U> class2;
if ((Thread.CurrentThread.ManagedThreadId == this.int_1) && (this.int_0 == -2))
{
this.int_0 = 0;
class2 = (Extensions.Class114<T, U>) this;
}
else
{
class2 = new Extensions.Class114<T, U>(0);
}
class2.ienumerable_0 = this.ienumerable_1;
return class2;
}
[DebuggerHidden]
IEnumerator IEnumerable.GetEnumerator()
{
return this.System.Collections.Generic.IEnumerable<U>.GetEnumerator();
}
[DebuggerHidden]
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
switch (this.int_0)
{
case 1:
case 2:
try
{
}
finally
{
this.method_0();
}
return;
}
}
U IEnumerator<U>.Current
{
[DebuggerHidden]
get
{
return this.gparam_0;
}
}
object IEnumerator.Current
{
[DebuggerHidden]
get
{
return this.gparam_0;
}
}
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
namespace DotNetNuke.Services.UserRequest
{
/// <summary>
/// IP address family
/// </summary>
public enum IPAddressFamily
{
IPv4,
IPv6
}
}
|
using NutritionalResearchBusiness.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NutritionalResearchBusiness.Dtos
{
public class InvestigationRecord4Export
{
/// <summary>
/// 队列编号
/// </summary>
public string QueueId { get; set; }
/// <summary>
/// 孕期
/// </summary>
public PregnancyType Pregnancy
{
get
{
if(Week < 13)
{
return PregnancyType.A;
}
else if(Week > 28)
{
return PregnancyType.C;
}
else
{
return PregnancyType.B;
}
}
}
/// <summary>
/// 围产保健手册编号
/// </summary>
public string HealthBookId { get; set; }
/// <summary>
/// 孕妇姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 孕妇生日
/// </summary>
public string Birthday { get; set; }
/// <summary>
/// 孕周
/// </summary>
public int Week { get; set; }
/// <summary>
/// 身高
/// </summary>
public double Height { get; set; }
/// <summary>
/// 当前体重
/// </summary>
public double CurrentWeight { get; set; }
/// <summary>
/// 孕前体重
/// </summary>
public double BeforeWeight { get; set; }
/// <summary>
/// 调查时间
/// </summary>
public string InvestionTime { get; set; }
/// <summary>
/// 调查者姓名
/// </summary>
public string InvestigatorName { get; set; }
/// <summary>
/// 审核者名字
/// </summary>
public string AuditorName { get; set; }
/// <summary>
/// 食物分类编码
/// </summary>
public string FoodCategoryCode { get; set; }
/// <summary>
/// 月摄入频率
/// </summary>
public int MonthlyIntakeFrequency { get; set; }
/// <summary>
/// 平均每次摄入量
/// </summary>
public double? AverageIntakePerTime { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
}
}
|
namespace Task02_Todos.Data
{
using System;
using System.Data.Entity;
using System.Linq;
public class TodosDbContext : DbContext
{
public TodosDbContext()
: base("name=ModelTodos")
{
}
public virtual DbSet<Todo> Todo { get; set; }
public virtual DbSet<Category> Category { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Garage.Cars
{
class Car : Vehicles.Vehicle
{
//public string Fuel { get; set; }
public string BatteryCapacity{ get; set; }
//public string Color { get; set; }
public override void Refuel()
{
Console.WriteLine("I'm refueling my car right now");
}
public override void Driving()
{
Console.WriteLine("I'm driving my car right now");
}
public void Braking()
{
Console.WriteLine("Oops... almost hit somebody lol");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OracleClient;
namespace MyDB
{
class Program
{
static void Main(string[] args)
{
String oledb = "Data Source=XE:User id=hr;Password=1234;";
OracleConnection conn = new OracleConnection(oledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from jobs";
OracleDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("{0} {1}", reader[0], reader[1]);
}
reader.Close();
conn.Close();
}
}
}
|
using System;
namespace algorithms {
class Program {
static void Main (string[] args) {
Console.WriteLine ("*************************** Algorithms **********************");
algorithm algorithm = new algorithm ();
/********** Binary Search **************/
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1001 };
Console.WriteLine ("Binary Search: O(log n)");
Console.WriteLine (algorithm.binarySearch (sortedArray, 1001, 0, sortedArray.Length));
Console.WriteLine ();
/************ Counting Sort *************/
int[] a = { 0, 5, 6, 10, 4, 7, 4, 1000000, 1, 1, 1, 1, 1, 1, 1, 0, 200 };
int[] b = new int[a.Length];
Console.WriteLine ("Counting Sort: O(n)");
Console.Write ("unsorted array: ");
for (int i = 0; i < a.Length; i++) {
Console.Write (a[i] + " ");
}
algorithm.countingSort (a, b, 1000000);
Console.WriteLine ();
Console.Write ("sorted array: ");
for (int i = 0; i < b.Length; i++) {
Console.Write (b[i] + " ");
}
Console.WriteLine ();
/**************** Matrix **************/
Console.WriteLine ();
int[, ] matrix = { { 0, 20, 15, -1 },
{ 101, 1, 1, 6 },
{-1, 0, -4, 10 },
{ 1, 1, 3, 1 },
{ 0, 0, 0, -1 },
{ 5, 5, 1, 1 },
{ 1, 1, -100, 1 },
{ 16, 77, 0, 2 },
{ 1, 7, 1, 5 }
};
Console.WriteLine ("Matrix has all ones");
Console.WriteLine("Input Matrix:");
for (int i = 0; i < matrix.GetLength (0); i++) {
Console.Write(" ");
for (int j = 0; j < matrix.GetLength (1); j++) {
Console.Write (matrix[i, j] + " ");
}
Console.WriteLine();
}
int[, ] result = algorithm.manipulateZeroValue (matrix);
Console.WriteLine ();
Console.WriteLine(" Output Matrix:");
for (int i = 0; i < result.GetLength (0); i++) {
Console.Write(" ");
for (int j = 0; j < result.GetLength (1); j++) {
Console.Write (result[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine ();
int[] notbst = { 21, 30, 10, 15, 16, 18, 22, 100, 1000, 20, 50, 30, 60, 1001, 999, 1, 2, 19, 13, 99 };
BinarySearchTree bst = new BinarySearchTree ();
for (int i = 0; i < notbst.Length; i++) {
bst.insert (new TreeNode (notbst[i]));
}
Console.WriteLine ();
Console.WriteLine ("Binary Search Tree");
Console.WriteLine (" Tree Size: " + bst.getSize ());
Console.Write (" Pre-order Traversal: ");
bst.preOrderTraversal ();
Console.WriteLine ();
Console.Write (" In-order Traversal: ");
bst.InOrderTraversal ();
Console.WriteLine ();
Console.Write (" Post-order Traversal: ");
bst.postOrderTraversal ();
Console.WriteLine();
Console.WriteLine (" Maximum value: " + bst.maximum ().getKey ());
Console.WriteLine (" Minumum value: " + bst.minimum ().getKey ());
Console.WriteLine ();
Console.WriteLine ("Search for 50 information ");
Console.WriteLine (" Parent: " + bst.search (50).getParent ().getKey ());
Console.WriteLine (" Right Child: " + bst.search (50).getRightChild ().getKey ());
Console.WriteLine (" Left Child: " + bst.search (50).getLeftChild ().getKey ());
Console.WriteLine ();
Console.WriteLine ("Bubble Sort");
int[] bubbleSort = { 1, -10, 1000, 39 };
Console.Write (" Unsorted array: ");
for (int i = 0; i < bubbleSort.Length; i++) {
Console.Write (bubbleSort[i] + " ");
}
algorithm.bubbleSort (bubbleSort);
Console.WriteLine ();
Console.Write (" Sorted array: ");
for (int i = 0; i < bubbleSort.Length; i++) {
Console.Write (bubbleSort[i] + " ");
}
Console.WriteLine ();
Console.WriteLine ();
Console.WriteLine ("Reverse an input array");
int[] reverse = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] reversed = algorithm.reverseArray (reverse);
Console.Write (" Input Array: ");
for (int i = 0; i < reverse.Length; i++) {
Console.Write (reverse[i] + " ");
}
Console.WriteLine ();
Console.Write (" Reversed array: ");
for (int i = 0; i < reversed.Length; i++) {
Console.Write (reversed[i] + " ");
}
Console.WriteLine ();
}
}
} |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Promact.Oauth.Server.Repository;
using Promact.Oauth.Server.Models;
using Promact.Oauth.Server.Models.ManageViewModels;
using Microsoft.AspNetCore.Identity;
using Promact.Oauth.Server.Models.ApplicationClasses;
using System.Threading.Tasks;
using System.Collections.Generic;
using Promact.Oauth.Server.Constants;
using Promact.Oauth.Server.ExceptionHandler;
using Promact.Oauth.Server.Repository.ProjectsRepository;
using System;
using System.Globalization;
namespace Promact.Oauth.Server.Controllers
{
[Route(BaseUrl)]
public class UserController : BaseController
{
#region "Private Variable(s)"
private readonly IUserRepository _userRepository;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IStringConstant _stringConstant;
private readonly IProjectRepository _projectRepository;
public const string ReadUser = "ReadUser";
public const string BaseUrl = "api/users";
public const string Admin = "Admin";
public const string ReadProject = "ReadProject";
#endregion
#region "Constructor"
public UserController(IUserRepository userRepository, UserManager<ApplicationUser> userManager, IStringConstant stringConstant, IProjectRepository projectRepository)
{
_userRepository = userRepository;
_userManager = userManager;
_stringConstant = stringConstant;
_projectRepository = projectRepository;
}
#endregion
#region "Public Methods"
/**
* @api {get} api/users
* @apiVersion 1.0.0
* @apiName GetAllUsersAsync
* @apiGroup User
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "John",
* "Email" : "jone@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null
* }
* ]
*/
[HttpGet]
[Route("")]
[Authorize(Roles = Admin)]
public async Task<IActionResult> GetAllUsersAsync()
{
return Ok(await _userRepository.GetAllUsersAsync());
}
/**
* @api {get} api/users/orderby/name
* @apiVersion 1.0.0
* @apiName GetEmployeesAsync
* @apiGroup User
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "John",
* "Email" : "jone@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null
* }
* ]
*/
[HttpGet]
[Route("orderby/name")]
[Authorize(Roles = Admin)]
public async Task<IActionResult> GetEmployeesAsync()
{
return Ok(await _userRepository.GetAllEmployeesAsync());
}
/**
* @api {get} api/users/roles
* @apiVersion 1.0.0
* @apiName GetRoleAsync
* @apiGroup User
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* [
* {
* Id: 452dsf34,
* Name: Employee
* },
* ]
* }
*/
[HttpGet]
[Route("roles")]
[Authorize]
public async Task<IActionResult> GetRoleAsync()
{
return Ok(await _userRepository.GetRolesAsync());
}
/**
* @api {get} api/users/:id
* @apiVersion 1.0.0
* @apiName GetUserByIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id": "34d1af3d-062f-4bcd-b6f9-b8fd5165e367"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "John",
* "Email" : "jone@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null
* }
* @apiError UserNotFound user id not found.
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 404 Not Found
* {
* "error": "UserNotFound"
* }
*/
[HttpGet]
[Route("{id}")]
[Authorize]
public async Task<IActionResult> GetUserByIdAsync(string id)
{
try
{
return Ok(await _userRepository.GetByIdAsync(id));
}
catch (UserNotFound)
{
return NotFound();
}
}
/**
* @api {post} api/users
* @apiVersion 1.0.0
* @apiName RegisterUserAsync
* @apiParam {object} newUser object
* @apiParamExample {json} Request-Example:
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "John",
* "Email" : "jone@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* true
* }
* @apiError BadRequest
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error": "Problems parsing JSON object"
* }
*/
[HttpPost]
[Route("")]
[Authorize(Roles = Admin)]
public async Task<IActionResult> RegisterUserAsync([FromBody] UserAc newUser)
{
if (ModelState.IsValid)
{
newUser.JoiningDate = DateTime.ParseExact(newUser.JoinDate, _stringConstant.DateFormatForJoinnigDate, CultureInfo.InvariantCulture);
string createdBy = _userManager.GetUserId(User);
await _userRepository.AddUserAsync(newUser, createdBy);
return Ok(true);
}
return BadRequest();
}
/**
* @api {put} api/users/:id
* @apiVersion 1.0.0
* @apiName UpdateUserAsync
* @apiGroup User
* @apiParam {string} id
* @apiParam {object} editedUser object
* @apiParamExample {json} Request-Example:
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "John",
* "Email" : "jone@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* true
* }
* @apiError BadRequest
* @apiError SlackUserNotFound the slack user was not found.
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error": "Problems parsing JSON object"
* }
*/
[HttpPut]
[Route("{id}")]
[Authorize(Roles = "Admin, Employee")]
public async Task<IActionResult> UpdateUserAsync(string id, [FromBody] UserAc editedUser)
{
if (ModelState.IsValid)
{
string updatedBy = _userManager.GetUserId(User);
editedUser.Id = id;
await _userRepository.UpdateUserDetailsAsync(editedUser, updatedBy);
return Ok(true);
}
return BadRequest();
}
/**
* @api {delete} api/users/:id
* @apiVersion 1.0.0
* @apiName DeleteUserAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* ''
* }
*/
[HttpDelete]
[Route("{id}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> DeleteUserAsync(string id)
{
return Ok(await _userRepository.DeleteUserAsync(id));
}
/**
* @api {post} api/users/password
* @apiVersion 1.0.0
* @apiName ChangePasswordAsync
* @apiGroup User
* @apiParam {object} passwordModel object
* @apiParamExample {json} Request-Example:
* {
* "OldPassword":"OldPassword",
* "NewPassword":"NewPassword",
* "ConfirmPassword":"ConfirmPassword"
*
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* Message : If password is changed successfully, return empty otherwise error message
* }
* @apiError UserNotFound the slack user was not found.
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 404 Not Found
* {
* "error": "UserNotFound"
* }
*/
[HttpPost]
[Route("password")]
[Authorize]
public async Task<IActionResult> ChangePasswordAsync([FromBody] ChangePasswordViewModel passwordModel)
{
try
{
var user = await _userManager.GetUserAsync(User);
passwordModel.Email = user.Email;
return Ok(await _userRepository.ChangePasswordAsync(passwordModel));
}
catch (UserNotFound)
{
return NotFound();
}
}
/**
* @api {get} api/users/:password/available
* @apiVersion 1.0.0
* @apiName CheckPasswordAsync
* @apiGroup User
* @apiParam {string} password User OldPassword
* @apiParamExample {json} Request-Example:
* {
* "password":"OldPassword123"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* true
* }
*/
[HttpGet]
[Route("{password}/available")]
[Authorize]
public async Task<ActionResult> CheckPasswordAsync(string password)
{
var user = await _userManager.GetUserAsync(User);
return Ok(await _userManager.CheckPasswordAsync(user, password));
}
/**
* @api {get} api/users/available/email/:email
* @apiVersion 1.0.0
* @apiName CheckEmailIsExistsAsync
* @apiGroup User
* @apiParam {string} email user email
* @apiParamExample {json} Request-Example:
* {
* "email":"jone@promactinfo.com"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* true
* }
*/
[HttpGet]
[Route("available/email/{email}")]
[Authorize(Roles = Admin)]
public async Task<IActionResult> CheckEmailIsExistsAsync(string email)
{
return Ok(await _userRepository.CheckEmailIsExistsAsync(email + _stringConstant.DomainAddress));
}
/**
* @api {get} api/users/email/:id/send
* @apiVersion 1.0.0
* @apiName ReSendMailAsync
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id": "adssdvvsdv55gdfgdsgbc"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "true"
* }
*/
[HttpGet]
[Route("email/{id}/send")]
[Authorize(Roles = Admin)]
public async Task<IActionResult> ReSendMailAsync(string id)
{
await _userRepository.ReSendMailAsync(id);
return Ok(true);
}
#region External Call APIs
/**
* @api {get} api/users/:id/detail
* @apiVersion 1.0.0
* @apiName UserDetailByIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id": "95151b57-42c5-48d5-84b6-6d20e2fb05cd"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "description":"Object of type UserAc "
* {
* "Id": "95151b57-42c5-48d5-84b6-6d20e2fb05cd",
* "FirstName": "Admin",
* "LastName": "Promact",
* "IsActive": true,
* "Role": "Admin",
* "NumberOfCasualLeave": 14,
* "NumberOfSickLeave": 7,
* "JoiningDate": "0001-01-01T00:00:00",
* "Email": "roshni@promactinfo.com",
* "UserName": "roshni@promactinfo.com",
* "UniqueName": "Admin-roshni@promactinfo.com",
* }
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("{id}/detail")]
public async Task<IActionResult> UserDetailByIdAsync(string id)
{
return Ok(await _userRepository.UserDetailByIdAsync(id));
}
/**
* @api {get} api/users/:id/role
* @apiVersion 1.0.0
* @apiName GetUserRoleAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "UserId": "34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "UserName": "smith@promactinfo.com",
* "Name":"Smith",
* "Role":"Admin"
* }
*]
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("{id}/role")]
public async Task<IActionResult> GetUserRoleAsync(string id)
{
return Ok(await _userRepository.GetUserRoleAsync(id));
}
/**
* @api {get} api/users/:id/teammembers
* @apiVersion 1.0.0
* @apiName GetTeamMembersAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "UserId": "34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "UserName": "smith@promactinfo.com",
* "Name":"Smith",
* "Role":"Admin"
* },
* {
* "UserId": "avd1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "UserName": "john@promactinfo.com",
* "Name":"John",
* "Role":"Employee"
* }
* ]
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("{id}/teammembers")]
public async Task<IActionResult> GetTeamMembersAsync(string id)
{
return Ok(await _userRepository.GetTeamMembersAsync(id));
}
/**
* @api {get} api/users/:teamLeaderId/project
* @apiVersion 1.0.0
* @apiName GetProjectUsersByTeamLeaderIdAsync
* @apiGroup User
* @apiParam {string} teamLeaderId
* @apiParamExample {json} Request-Example:
* {
* "teamLeaderId": "95151b57-42c5-48d5-84b6-6d20e2fb05cd"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "description":"list of projects with users for that specific teamleader"
*
* [
* {
* "Id": "95151b57-42c5-48d5-84b6-6d20e2fb05cd",
* "FirstName": "Admin",
* "LastName": "Promact",
* "IsActive": true,
* "Role": "TeamLeader",
* "NumberOfCasualLeave": 14,
* "NumberOfSickLeave": 7,
* "JoiningDate": "0001-01-01T00:00:00",
* "Email": "roshni@promactinfo.com",
* "UserName": "roshni@promactinfo.com",
* "UniqueName": "Admin-roshni@promactinfo.com",
* },
* {
* "Id": "bbd66866-8e35-430a-9f66-8cb550e72f9e",
* "FirstName": "gourav",
* "LastName": "gourav",
* "IsActive": true,
* "Role": "Employee",
* "NumberOfCasualLeave": 14,
* "NumberOfSickLeave": 7,
* "JoiningDate": "2016-07-20T18:30:00",
* "Email": "gourav@promactinfo.com",
* "UserName": "gourav@promactinfo.com",
* "UniqueName": "gourav-gourav@promactinfo.com",
* }
* ]
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("{teamLeaderId}/project")]
public async Task<IActionResult> GetProjectUsersByTeamLeaderIdAsync(string teamLeaderId)
{
List<UserAc> projectUsers = await _userRepository.GetProjectUsersByTeamLeaderIdAsync(teamLeaderId);
return Ok(projectUsers);
}
/**
* @api {get} api/users/detail/:id
* @apiVersion 1.0.0
* @apiName UserDetialByUserIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* slackUserId : ADF4HY54H
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "Id":"34d1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "ABC",
* "Email" : "abc@promactinfo.com",
* "LastName" : "DEF",
* "SlackUserId" : "ADF4HY54H",
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error" : "SlackUserNotFound"
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("detail/{id}")]
public async Task<IActionResult> UserDetialByUserIdAsync(string id)
{
try
{
return Ok(await _userRepository.UserBasicDetialByUserIdAsync(id));
}
catch (SlackUserNotFound ex)
{
return BadRequest(ex.StackTrace);
}
}
/**
* @api {get} api/users/teamLeaders/:id
* @apiVersion 1.0.0
* @apiName ListOfTeamLeaderByUserIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* id : ADF4HY54H
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* [
* {
* "Email" : "abc@promactinfo.com",
* "UserName" : "abc@promactinfo.com",
* "SlackUserId" : "ADF4HY54H",
* }
* ]
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error" : "SlackUserNotFound"
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("teamLeaders/{id}")]
public async Task<IActionResult> ListOfTeamLeaderByUserIdAsync(string id)
{
try
{
return Ok(await _userRepository.ListOfTeamLeaderByUserIdAsync(id));
}
catch (UserNotFound ex)
{
return BadRequest(ex.StackTrace);
}
}
/**
* @api {get} api/users/managements
* @apiVersion 1.0.0
* @apiName ManagementDetailsAsync
* @apiGroup User
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* [
* {
* "Email" : "abc@promactinfo.com",
* "UserName" : "abc@promactinfo.com",
* "SlackUserId" : "ADF4HY54H",
* }
* ]
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error" : "FailedToFetchDataException"
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("managements")]
public async Task<IActionResult> ListOfManagementDetailsAsync()
{
try
{
return Ok(await _userRepository.ListOfManagementDetailsAsync());
}
catch (FailedToFetchDataException ex)
{
return BadRequest(ex.StackTrace);
}
}
/**
* @api {get} api/users/leaveAllowed/:id
* @apiVersion 1.0.0
* @apiName GetUserAllowedLeaveByUserIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* id : ADF4HY54Hscacsasccdsc
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "CasualLeave" : "14",
* "SickLeave" : "7"
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error" : "UserNotFound"
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("leaveAllowed/{id}")]
public async Task<IActionResult> GetUserAllowedLeaveByUserIdAsync(string id)
{
try
{
return Ok(await _userRepository.GetUserAllowedLeaveByUserIdAsync(id));
}
catch (UserNotFound ex)
{
return BadRequest(ex.StackTrace);
}
}
/**
* @api {get} api/users/isAdmin/:id
* @apiVersion 1.0.0
* @apiName id
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* id : ADF4HY5dvsdvs4Hd453dsaf
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "true"
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "error" : "UserNotFound"
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("isAdmin/{id}")]
public async Task<IActionResult> UserIsAdminAsync(string id)
{
try
{
return Ok(await _userRepository.IsAdminAsync(id));
}
catch (UserNotFound ex)
{
return BadRequest(ex.StackTrace);
}
}
/**
* @api {get} api/users/email
* @apiVersion 1.0.0
* @apiName GetUserEmailListBasedOnRoleAsync
* @apiGroup User
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* [
* {
* "TeamLeader" : "[abc@promactinfo.com,test@gmail.com]",
* "TamMemeber" : "[abc@promactinfo.com,xyz@gmail.com]",
* "Management" : "[obc@promactinfo.com,mnc@gmail.com]",
* }
* ]
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("email")]
public async Task<IActionResult> GetUserEmailListBasedOnRoleAsync()
{
return Ok(await _userRepository.GetUserEmailListBasedOnRoleAsync());
}
/**
* @api {get} api/users/detail/:projectId
* @apiVersion 1.0.0
* @apiName GetListOfTeamMemberByProjectIdAsync
* @apiGroup User
* @apiParam {int} projectId projectId
* @apiParamExample {json} Request-Example:
* {
* "projectId": "1"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [{
* "Id":"abcd1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "Smith",
* "Email" : "Smith@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null,
* "RoleName": null
* }]
*/
[Authorize(Policy = ReadProject)]
[HttpGet]
[Route("detail/{projectId:int}")]
public async Task<IActionResult> GetListOfTeamMemberByProjectIdAsync(int projectId)
{
return Ok(await _projectRepository.GetListOfTeamMemberByProjectIdAsync(projectId));
}
/**
* @api {get} api/users/details/:id
* @apiVersion 1.0.0
* @apiName GetUserDetailWithProjectListByUserIdAsync
* @apiGroup User
* @apiParam {string} id
* @apiParamExample {json} Request-Example:
* {
* "id": "dsadu4521fsfdsfr1"
* }
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "UserAc" : {
* "Id":"abcd1af3d-062f-4bcd-b6f9-b8fd5165e367",
* "FirstName" : "Smith",
* "Email" : "Smith@promactinfo.com",
* "LastName" : "Doe",
* "IsActive" : "True",
* "JoiningDate" :"10-02-2016",
* "NumberOfCasualLeave":0,
* "NumberOfSickLeave":0,
* "UniqueName":null,
* "Role":null,
* "UserName": null,
* "RoleName": null
* },
* "UserDetailWithProjectList" :
* [{
* "Id": "1"
* "Name": "slack"
* "IsActive":"true"
* "TeamLeaderId":"Null"
* "CreatedBy":"Test"
* "CreatedDate":"10-02-2017"
* "UpdatedBy":"Null"
* "UpdatedDate":"Null"
* },
* {
* "Id": "2"
* "Name": "slack"
* "IsActive":"true"
* "TeamLeaderId":"dsadu4521fsfdsfr1"
* "CreatedBy":"Test"
* "CreatedDate":"10-02-2017"
* "UpdatedBy":"Null"
* "UpdatedDate":"Null"
* }]
* }
*/
[Authorize(Policy = ReadUser)]
[HttpGet]
[Route("details/{id}")]
public async Task<IActionResult> GetUserDetailWithProjectListByUserIdAsync(string id)
{
return Ok(await _userRepository.GetUserDetailWithProjectListByUserIdAsync(id));
}
#endregion
#endregion
}
}
|
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace OLinqProvider
{
public abstract class QueryProvider:IQueryProvider
{
public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
return new OQuery<TElement>(this, expression);
}
public IQueryable CreateQuery(Expression expression)
{
Type elementType = expression.Type;
try
{
return (IQueryable)Activator.CreateInstance(typeof(OQuery<>).MakeGenericType(elementType), new object[] { this, expression });
}
catch (TargetInvocationException tie)
{
throw tie.InnerException;
}
}
public abstract TResult Execute<TResult>(Expression expression);
public object Execute(Expression expression)
{
return Execute<object>(expression);
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class GameOverHit : MonoBehaviour
{
public GUIText messageText;
public DoorsCamControl cameras;
public GameObject cam;
private string message;
private GameObject player;
private Vector3 origPlayerPos;
private bool moveBack = false;
private UnityChanDoors uc2;
private bool doRestart = false;
private DoorsGameController dgc;
Animator playerAnimator;
// Use this for initialization
void Start()
{
message = "Better luck next time!";
player = GameObject.FindGameObjectWithTag ("Orange");
origPlayerPos = player.transform.position;
uc2 = player.GetComponent<UnityChanDoors> ();
playerAnimator = player.GetComponent<Animator> ();
cameras = cam.GetComponent<DoorsCamControl> ();
dgc = GameObject.FindGameObjectWithTag ("GameController").GetComponent<DoorsGameController> ();
//playerAnimator.SetBool ("PushedBack", true);
}
// Update is called once per frame
void Update()
{
if (moveBack) {
player.transform.position = Vector3.MoveTowards (player.transform.position, origPlayerPos, 29 * Time.deltaTime);
}
if (player.transform.position == origPlayerPos) {
moveBack = false;
uc2.controlsEnabled = true;
playerAnimator.SetBool ("PushedBack", false);
player.GetComponent<CapsuleCollider> ().isTrigger = false;
if (doRestart) {
doRestart = false;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Orange")
{
//messageText.text = message;
//moveBack = true;
//uc2.controlsEnabled = false;
//StartCoroutine(Waiter());
}
}
void OnCollisionEnter(Collision other){
if (other.gameObject.tag == "Orange") {
moveBack = true;
uc2.controlsEnabled = false;
playerAnimator.SetBool ("PushedBack", true);
player.GetComponent<CapsuleCollider> ().isTrigger = true;
cameras.reset ();
doRestart = true;
dgc.loseLife ();
}
}
IEnumerator Waiter()
{
print(Time.time);
yield return new WaitForSeconds(5);
print(Time.time);
}
} |
namespace Plus.Communication.Packets.Outgoing.Catalog
{
internal class GiftWrappingErrorComposer : MessageComposer
{
public GiftWrappingErrorComposer()
: base(ServerPacketHeader.GiftWrappingErrorMessageComposer)
{
}
public override void Compose(ServerPacket packet)
{
}
}
} |
using System;
using TNBase.Objects;
using TNBase.DataStorage;
using Microsoft.Extensions.DependencyInjection;
namespace TNBase
{
public partial class FormTempShowNewListener
{
private readonly IServiceLayer serviceLayer = Program.ServiceProvider.GetRequiredService<IServiceLayer>();
public void setupForm(int walletId)
{
Listener theListener = default(Listener);
theListener = serviceLayer.GetListenerById(walletId);
lblWallet.Text = "" + walletId;
lblName.Text = theListener.Title + " " + theListener.Forename + " " + theListener.Surname;
}
private void tmrClose_Tick(object sender, EventArgs e)
{
this.Close();
}
public FormTempShowNewListener()
{
InitializeComponent();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Player2MoveScript : MonoBehaviour {
private Vector3 _startPosition;
private Animator _animator;
private float _fireAnimation = 0;
private float _maxTrackWidth = 6;
private bool _moveVertical = false;
private bool _moveHorizontal = false;
private int _bodyPlayer2;
private Player2LevelScript _p2LevelScript;
private ConfirmScript _confirmScript;
private AudioSource _playerMovementAudio;
private Animator[] _animatorList;
// Use this for initialization
void Start () {
_startPosition = transform.position;
//_animator = this.GetComponentInChildren<Animator>();
_animatorList = GetComponentsInChildren<Animator>();
_bodyPlayer2 = GameObject.FindObjectOfType<ConfirmScript>().bodyPlayer2;
_confirmScript = GameObject.FindObjectOfType<ConfirmScript>();
_p2LevelScript = GameObject.FindObjectOfType<Player2LevelScript>();
_playerMovementAudio = GameObject.FindGameObjectWithTag("PlayerMovement").GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
if (_p2LevelScript.LevelStarted)
{
Vector3 moveDir = Vector3.zero;
moveDir.x = Input.GetAxis("Horizontal P2") * 12; // get result of AD keys in X
moveDir.z = Input.GetAxis("Vertical P2") * 12; // get result of WS keys in Z
transform.position -= moveDir * Time.deltaTime;
if (transform.position.x > (_startPosition.x + _maxTrackWidth))
{
Vector3 newPos = new Vector3(0, 0, 0);
newPos.x = _startPosition.x + _maxTrackWidth;
newPos.y = transform.position.y;
newPos.z = transform.position.z;
transform.position = newPos;
}
else if (transform.position.x < (_startPosition.x - _maxTrackWidth))
{
Vector3 newPos = new Vector3(0, 0, 0);
newPos.x = _startPosition.x - _maxTrackWidth;
newPos.y = transform.position.y;
newPos.z = transform.position.z;
transform.position = newPos;
}
if (transform.position.z > (_startPosition.z + 4f))
{
Vector3 newPos = new Vector3(0, 0, 0);
newPos.x = transform.position.x;
newPos.y = transform.position.y;
newPos.z = _startPosition.z + 4f;
transform.position = newPos;
}
else if (transform.position.z < (_startPosition.z - 4f))
{
Vector3 newPos = new Vector3(0, 0, 0);
newPos.x = transform.position.x;
newPos.y = transform.position.y;
newPos.z = _startPosition.z - 4f;
transform.position = newPos;
}
Animation();
PlayerSound();
}
}
void PlayerSound()
{
if (Input.GetAxisRaw("Vertical P2") != 0)
{
if (_moveVertical == false)
{
// Call your event function here.
_moveVertical = true;
_playerMovementAudio.Play();
}
}
if (Input.GetAxisRaw("Vertical P2") == 0)
{
_moveVertical = false;
}
if (Input.GetAxisRaw("Horizontal P2") != 0)
{
if (_moveHorizontal == false)
{
// Call your event function here.
_moveHorizontal = true;
_playerMovementAudio.Play();
}
}
if (Input.GetAxisRaw("Horizontal P2") == 0)
{
_moveHorizontal = false;
}
}
void Animation()
{
if (Input.GetAxis("Vertical P2") < 0)
{
if (_p2LevelScript.Speed == 0)
{
_animatorList[_bodyPlayer2].Play("idle");
}
else if (transform.position.z > (_startPosition.z + 3.9f))
{
_animatorList[_bodyPlayer2].Play("speed 1 L");
}
else
{
_animatorList[_bodyPlayer2].Play("speed 1 S");
}
}
if (_p2LevelScript.Speed == 0 && _fireAnimation < Time.time)
{
_animatorList[_bodyPlayer2].Play("idle");
}
else if (Input.GetAxis("Vertical P2") > 0)
{
//Debug.Log(transform.position.z);
_animatorList[_bodyPlayer2].Play("stop");
if (_startPosition.z < -3.9f)
{
_animatorList[_bodyPlayer2].Play("stop");
}
else if (transform.position.z < (_startPosition.z - 4.0f))
{
_animatorList[_bodyPlayer2].Play("speed 1 L");
}
}
if (Input.GetButtonDown("Fire2P2"))
{
_animatorList[_bodyPlayer2].Play("fire");
_fireAnimation = Time.time + 1.5f;
}
else if (Input.GetAxis("Vertical P2") == 0 && _fireAnimation < Time.time && !_p2LevelScript.SuperWallHit)
{
_animatorList[_bodyPlayer2].Play("speed 1 L");
}
}
}
|
using Apache.Ignite.Core.Binary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace IgniteDemo
{
class Reflective
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employee
{
static void Main(string[] args)
{
Binarizable a = new Binarizable();
}
}
class Binarizable : IBinarizable
{
public int Id { get; set; }
public string Name { get; set; }
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("Id", Id);
writer.WriteString("Name", Name);
}
public void ReadBinary(IBinaryReader reader)
{
Id = reader.ReadInt("Id");
Name = reader.ReadString("Name");
}
}
class Serializable : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
public Serializable() { }
protected Serializable(SerializationInfo info, StreamingContext context)
{
Id = info.GetInt32("Id");
Name = info.GetString("Name");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Id", Id);
info.AddValue("Name", Name);
}
}
}
|
namespace MvcMonitor.Data.Repositories
{
public interface IErrorRepositoryFactory
{
IErrorRepository GetRepository();
}
} |
using System;
namespace GlobalModels
{
/// <summary>
/// DTO Model for frontend -> backend
/// </summary>
public sealed class Comment : IEquatable<Comment>
{
public Guid Commentid { get; set; } = Guid.NewGuid();
public Guid Discussionid { get; set; }
public string Userid { get; set; }
public string Text { get; set; }
public bool Isspoiler { get; set; }
public string ParentCommentid { get; set; }
public int Likes { get; set; }
public Comment(Guid commentid, Guid discussionid, string uid, string text, bool isspoiler, string parentcommentid, int likes)
{
Commentid = commentid;
Discussionid = discussionid;
Userid = uid;
Text = text;
Isspoiler = isspoiler;
ParentCommentid = parentcommentid;
Likes = likes;
}
public bool Equals(Comment other)
{
if (Object.ReferenceEquals(other, null))
{
return false;
}
if (Object.ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
return Commentid == other.Commentid;
}
public override bool Equals(object obj)
{
return this.Equals(obj as Comment);
}
public static bool operator ==(Comment lhs, Comment rhs)
{
if (Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null))
{
return true;
}
return false;
}
return lhs.Equals(rhs);
}
public static bool operator !=(Comment lhs, Comment rhs)
{
return !(lhs == rhs);
}
public static int CompareLikes(Comment c1, Comment c2)
{
return c1.Likes.CompareTo(c2.Likes);
}
public override int GetHashCode()
{
return Commentid.GetHashCode();
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Text;
namespace SearchEnginePopularityChecker
{
public class Google : ISearchEngine
{
#region Private Methods
private const string GoogleUrl = "https://www.google.com.au";
private string GetHtml(string url)
{
using (WebClient webClient = new WebClient())
{
byte[] buffer = webClient.DownloadData(url);
string searchResults = Encoding.UTF8.GetString(buffer);
return searchResults;
}
}
private int FindStartIndex(string htmlString, int startIndex)//returns starting index of a search result
{
string tag = "<div class=\"g\">";
return htmlString.IndexOf(tag, startIndex);
}
private int FindEndIndex(string htmlString, int index)//returns ending index of a search result
{
string startTag = "<div";
string endTag = "/div>";
int tagCount = 0;
int startTagIndex = 0;
int endTagIndex = 0;
do
{
startTagIndex = htmlString.IndexOf(startTag, index);
endTagIndex = htmlString.IndexOf(endTag, index);
if (startTagIndex < endTagIndex)
{
tagCount++;
index = startTagIndex + startTag.Length;
}
else
{
tagCount--;
index = endTagIndex + startTag.Length;
}
} while (tagCount != 0);
return index;
}
#endregion
public List<SearchResult> Search(string keyword, int searchCount)
{
if (string.IsNullOrEmpty(keyword))
throw new ArgumentNullException(nameof(keyword));
if (searchCount <= 0)
throw new ArgumentOutOfRangeException(nameof(searchCount));
try
{
List<SearchResult> resultArray = new List<SearchResult>();
string url = String.Format("{0}/search?num={1}&q={2}",GoogleUrl, searchCount,keyword);
//e.g. "https://www.google.com.au/search?num=100&q=conveyancing+software"
string searchResults = GetHtml(url);
int startIndex = 0;
int endIndex = 0;
for (int i = 1; i <= searchCount; i++)
{
startIndex = FindStartIndex(searchResults, endIndex);
if (startIndex == -1)
return resultArray;
endIndex = FindEndIndex(searchResults, startIndex);
if (endIndex == -1)
return resultArray;
string searchResult = searchResults.Substring(startIndex, endIndex - startIndex + 1);
//creates a list of all search results
resultArray.Add(new SearchResult() { SearchContent = searchResult, Index = i });
}
return resultArray;
}
catch
{
throw;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BackPropagation
{
/// <summary>
/// An interface to define the input and output functions which
/// all trainer IOs must provide and the number of inputs and output to
/// the network.
/// </summary>
interface TrainerIO
{
double LearningRate { get; }
int Inputs { get; }
int Outputs { get; }
int MedialNeurons { get; }
int Layers { get; }
double[] GetExpectedOutput(double[] input);
double[] GetValidInput();
Network GetValidNetwork();
}
}
|
using System.Collections.Generic;
using System.Linq;
using Faust.PetShopApp.Core.Models;
using Faust.PetShopApp.Domain.IRepositories;
using Faust.PetShopApp.Infrastructure.Entities;
namespace Faust.PetShopApp.Infrastructure.RepositoriesEF
{
public class OwnerRepositoryEF:IOwnerRepository
{
private readonly PetAppContext _ctx;
public OwnerRepositoryEF(PetAppContext ctx)
{
_ctx = ctx;
}
public Owner Create(Owner owner)
{
var entity = new OwnerEntity()
{
Id = owner.Id,
Address = owner.Address,
Email = owner.Email,
FirstName = owner.FirstName,
LastName = owner.LastName,
PhoneNumber = owner.PhoneNumber
};
var savedEntity = _ctx.Owners.Add(entity).Entity;
_ctx.SaveChanges();
return new Owner()
{
Id = savedEntity.Id,
Address = savedEntity.Address,
Email = savedEntity.Email,
FirstName = savedEntity.FirstName,
LastName = savedEntity.LastName,
PhoneNumber = savedEntity.PhoneNumber
};
}
public IEnumerable<Owner> ReadAll()
{
return _ctx.Owners.Select(entity => new Owner
{
Id = entity.Id,
Address = entity.Address,
Email = entity.Email,
FirstName = entity.FirstName,
LastName = entity.LastName,
PhoneNumber = entity.PhoneNumber
});
}
public Owner Read(int id)
{
return _ctx.Owners.Select(entity => new Owner()
{
Id = entity.Id,
Address = entity.Address,
Email = entity.Email,
FirstName = entity.FirstName,
LastName = entity.LastName,
PhoneNumber = entity.PhoneNumber
}).FirstOrDefault(owner => owner.Id == id);
}
public Owner Update(Owner owner)
{
var updatedEntity = _ctx.Update(new OwnerEntity
{
Id = owner.Id,
Address = owner.Address,
Email = owner.Email,
FirstName = owner.FirstName,
LastName = owner.LastName,
PhoneNumber = owner.PhoneNumber
}).Entity;
_ctx.SaveChanges();
return new Owner()
{
Id = updatedEntity.Id,
Address = updatedEntity.Address,
Email = updatedEntity.Email,
FirstName = updatedEntity.FirstName,
LastName = updatedEntity.LastName,
PhoneNumber = updatedEntity.PhoneNumber
};
}
public Owner Delete(int id)
{
var entity = _ctx.Owners.FirstOrDefault(owner => owner.Id == id);
var deletedEntity = _ctx.Remove(entity).Entity;
_ctx.SaveChanges();
return new Owner()
{
Id = deletedEntity.Id,
Address = deletedEntity.Address,
Email = deletedEntity.Email,
FirstName = deletedEntity.FirstName,
LastName = deletedEntity.LastName,
PhoneNumber = deletedEntity.PhoneNumber
};
}
}
} |
using System.IO;
using System.Threading.Tasks;
namespace FlipLeaf.Core.Pipelines
{
public class CopyPipeline : IPipeline
{
public bool Accept(IStaticSite ctx, IInput input) => true;
public Task<InputItems> PrepareAsync(IStaticSite site, IInput input) => Task.FromResult(InputItems.Empty);
public async Task TransformAsync(IStaticSite ctx, IInput input)
{
var origin = input.GetFullInputPath(ctx);
var destination = input.GetFullOuputPath(ctx);
var destinationdir = Path.GetDirectoryName(destination);
if (!Directory.Exists(destinationdir))
{
Directory.CreateDirectory(destinationdir);
}
using (var reader = File.OpenRead(origin))
using (var writer = new FileStream(destination, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
await reader.CopyToAsync(writer).ConfigureAwait(false);
}
}
}
}
|
using MetroFramework;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.DB.Utils;
using PDV.DAO.Entidades.Financeiro;
using PDV.DAO.Enum;
using PDV.DAO.Custom;
using PDV.UTIL;
using PDV.VIEW.Forms.Cadastro.Financeiro.Modulo;
using System;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraReports.UI;
using System.Text;
using PDV.DAO.Entidades;
using PDV.REPORTS.Reports.CarneVendaTermica;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections.Generic;
using PDV.VIEW.App_Context;
using DevExpress.XtraPrinting;
using DevExpress.XtraEditors.Filtering.Templates;
using PDV.REPORTS.Recibo;
using Sequence = PDV.DAO.DB.Utils.Sequence;
using PDV.DAO.Entidades.PDV;
using PDV.VIEW.Forms.Util;
using System.Linq;
using DevExpress.Office.Drawing;
using System.Drawing;
using FastReport.Design;
using DevExpress.XtraRichEdit.Import.Rtf;
using DevExpress.DataProcessing;
using PDV.VIEW.Forms.Gerenciamento.DAV;
namespace PDV.VIEW.Forms.Consultas.Financeiro.Modulo
{
public partial class FCOFIN_ContaReceber : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CONSULTA DE CONTAS A RECEBER";
private DataTable table = null;
private List<decimal> IdsSelecionados
{
get
{
var ids = new List<decimal>();
foreach (var linha in gridView1.GetSelectedRows())
{
var id = Grids.GetValorDec(gridView1, "idcontareceber", linha);
ids.Add(id);
}
return ids;
}
}
private DataTable BAIXAS = null;
private ContaReceber Conta = null;
public bool ExibirSoAbertas = false;
public decimal linha = 0;
public decimal IDFLUXOCAIXA = 0;
public FCOFIN_ContaReceber()
{
InitializeComponent();
dateEdit1.DateTime = DateTime.Today;
dateEdit2.DateTime = dateEdit1.DateTime.AddDays(1);
LimparTela();
}
private void metroButton1_Click(object sender, EventArgs e)
{
LimparTela();
}
private void LimparTela()
{
}
private void FIN_ContaReceber_Load(object sender, EventArgs e)
{
if (ExibirSoAbertas)
CarregarSoAbertas();
else
Atualizar();
}
private void Atualizar()
{
table = FuncoesContaReceber.GetContas(dateEdit1.DateTime.Date, dateEdit2.DateTime.Date.AddDays(1));
gridControl1.DataSource = table;
gridView1.OptionsBehavior.Editable = false;
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView1.FocusRectStyle = DrawFocusRectStyle.RowFocus;
FormatarGrid();
gridView1.BestFitColumns();
}
private void CarregarSoAbertas()
{
table = FuncoesContaReceber.GetContasComSaldoEmAberto("", "", "");
gridControl1.DataSource = table;
FormatarGrid();
}
private void Receber()
{
//CONTASRECEBER = FuncoesContaReceber.GetContas(ovTXT_Cliente.Text, ovTXT_VencimentoInicio.Value, ovTXT_VencimentoFim.Value, ovTXT_EmissaoInicio.Value, ovTXT_EmissaoFim.Value, ovTXT_FormaPagamento.Text, ovTXT_Origem.Text);
// ovGRD_Contas.DataSource = CONTASRECEBER;
// AjustaHeaderTextGrid();
//IDCONTARECEBER, 0
//IDCLIENTE,1
//CLIENTE,2
//PARCELA,3
//EMISSAO,4
//VENCIMENTO,5
//FORMAPAGAMENTO,6
//ORIGEM,7
//VALORTOTAL,8
//SITUACAO9
if (linha == 0)
throw new Exception("Selecione uma conta.");
table = FuncoesContaReceber.GetContaReceberDT(linha);
Conta = new ContaReceber();
DataRow row = table.Rows[0];
string sAux = row[0].ToString();
Conta.IDContaReceber = decimal.Parse(row[0].ToString());
Conta.IDCliente = decimal.Parse(row[3].ToString());
Conta.Parcela = decimal.Parse(row[8].ToString());
Conta.Vencimento = DateTime.Parse(row[10].ToString());
Conta.Emissao = DateTime.Parse(row[9].ToString());
Conta.Valor = decimal.Parse(row[19].ToString());
Conta.ValorTotal = decimal.Parse(row[19].ToString());
Conta.IDVenda = decimal.Parse(row[24].ToString());
Conta.IDUsuario = Contexto.USUARIOLOGADO.IDUsuario;
FCAFIN_BaixaRecebimento Form = new FCAFIN_BaixaRecebimento(Conta, new BaixaRecebimento()
{
IDBaixaRecebimento = Sequence.GetNextID("BAIXARECEBIMENTO", "IDBAIXARECEBIMENTO"),
IDContaBancaria = 1,
IDHistoricoFinanceiro = 1,
IDFluxoCaixa = IDFLUXOCAIXA,
Baixa = DateTime.Now
});
Form.ShowDialog(this);
BAIXAS = new DataTable();
if (Form.Salvou)
{
DataRow dr = BAIXAS.NewRow();
AtualizaSaldo(Conta.ValorTotal);
CarregarBaixas(false);
DataTable dt = ZeusUtil.GetChanges(BAIXAS, TipoOperacao.INSERT);
// dr["IDCONTARECEBER"] = Conta.IDContaReceber;
// BaixaRecebimento BaixaRec = EntityUtil<BaixaRecebimento>.ParseDataRow(row);
/* Movimentação Bancária */
Form.BaixaRec.IDContaReceber = Conta.IDContaReceber;
Conta.Situacao = 3;
Conta.IDContaBancaria = Form.BaixaRec.IDContaBancaria;
Conta.IDHistoricoFinanceiro = Form.BaixaRec.IDHistoricoFinanceiro;
Conta.ComplmHisFin = Form.BaixaRec.ComplmHisFin;
Conta.IDFormaDePagamento = Form.BaixaRec.IDFormaDePagamento;
Conta.IDCentroCusto = 1;
Conta.Pagamento = DateTime.Now;
// if (Form.BaixaRec.Valor < )
TipoOperacao Op = TipoOperacao.UPDATE;
if (!FuncoesContaReceber.Salvar(Conta, Op))
throw new Exception("Não foi possível salvar o Lançamento.");
if (!FuncoesBaixaRecebimento.Salvar(Form.BaixaRec, TipoOperacao.INSERT))
throw new Exception("Não foi possível salvar as Baixas");
if (!FuncoesMovimentoBancario.Salvar(new MovimentoBancario()
{
IDMovimentoBancario = Sequence.GetNextID("MOVIMENTOBANCARIO", "IDMOVIMENTOBANCARIO"),
IDContaBancaria = Form.BaixaRec.IDContaBancaria,
IDNatureza = null,
Historico = FuncoesHistoricoFinanceiro.GetHistoricoFinanceiro(Form.BaixaRec.IDHistoricoFinanceiro).Descricao,
Conciliacao = null,
Sequencia = Conta.Parcela,
DataMovimento = DateTime.Now,
Documento = $"{Conta.Titulo}_{Form.BaixaRec.IDBaixaRecebimento}T",
Tipo = 1,
Valor = Form.BaixaRec.Valor,
}, TipoOperacao.INSERT))
throw new Exception("Não foi possível salvar o Movimento Bancário.");
try
{
//Configuracao Config_FormaPagamentoCarne = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAONFCE_PARAMETROSFINANCEIRO_FORMACARNE);
//if (Config_FormaPagamentoCarne == null)
// return;
// if (MessageBox.Show(this, "Deseja Gerar o Carnê de Duplicata Loja?", NOME_TELA, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
// {
Configuracao Config_NomeImpressora = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOPEDIDOVENDA_NOMEIMPRESSORA);
Configuracao Config_ExibirCaixaDialogo = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOPEDIDOVENDA_EXIBIRCAIXADIALOGO);
ContaReceber idvenda = FuncoesContaReceber.GetIDVendaContaReceber(Conta.IDContaReceber);
Crediario _Crediario = new Crediario(idvenda.IDVenda.Value);
// DuplicataNFCe dup = FuncoesDuplicataNFe.GetDuplicata(idvenda.Vencimento, idvenda.IDVenda.Value, idvenda.Valor);
// dup.DataPagamento = DateTime.Now;
// FuncoesDuplicataNFe.AtualizaConta(dup.IDDuplicataNFCe, DateTime.Now);
using (ReportPrintTool printTool = new ReportPrintTool(_Crediario))
{
if (Config_NomeImpressora != null && !string.IsNullOrEmpty(Encoding.UTF8.GetString(Config_NomeImpressora.Valor)))
printTool.PrinterSettings.PrinterName = Encoding.UTF8.GetString(Config_NomeImpressora.Valor);
printTool.PrinterSettings.Copies = 1;
printTool.Print();
}
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, NOME_TELA);
}
//using (ReportPrintTool printTool = new ReportPrintTool(_CarneVenda))
//{
// if (Config_NomeImpressora != null && !string.IsNullOrEmpty(Encoding.UTF8.GetString(Config_NomeImpressora.Valor)))
// printTool.PrinterSettings.PrinterName = Encoding.UTF8.GetString(Config_NomeImpressora.Valor);
// printTool.PrintDialog();
//}
}
// VerificaCheques(Form.BaixaRec.IDBaixaRecebimento, false, Form.Cheques);
}
private void CarregarBaixas(bool Banco)
{
// if (Banco)
// BAIXAS = FuncoesBaixaRecebimento.GetBaixas(Conta.IDContaReceber);
//ovGRD_Baixas.DataSource = BAIXAS;
//AjustaTextHeaderBaixas();
}
private void AtualizaSaldo(decimal total)
{
if (BAIXAS == null)
return;
// decimal ValorSaldo = total - BAIXAS.AsEnumerable().Where(o => o.RowState != DataRowState.Deleted).Sum(o => Convert.ToDecimal(o["TOTAL"]));
// ovTXT_Saldo.Value = ValorSaldo < 0 ? 0 : ValorSaldo;
}
private void FormatarGrid()
{
Grids.FormatGrid(ref gridView1);
Grids.FormatColumnType(ref gridView1, new List<string>
{
"idcliente"
}, GridFormats.VisibleFalse);
Grids.FormatColumnType(ref gridView1, "valortotal", GridFormats.Finance);
Grids.FormatColumnType(ref gridView1, "valortotal", GridFormats.SumFinance);
}
private void metroButton5_Click(object sender, EventArgs e)
{
new FCAFIN_ContaReceber(new ContaReceber()).ShowDialog(this);
Atualizar();
}
private void metroButton4_Click(object sender, EventArgs e)
{
try
{
new FCAFIN_ContaReceber(FuncoesContaReceber.GetContaReceber(IdsSelecionados[0])).ShowDialog();
Atualizar();
}
catch (NullReferenceException)
{
}
}
private void metroButton3_Click(object sender, EventArgs e)
{
if (Confirm("Deseja remover?") == DialogResult.Yes)
{
foreach (decimal id in IdsSelecionados)
{
try
{
PDVControlador.BeginTransaction();
var conta = FuncoesContaReceber.GetContaReceber(id);
if (conta.IDVenda != null || conta.Situacao != StatusConta.Aberto)
{
PDVControlador.Commit();
continue;
}
if (!FuncoesContaReceber.Remover(id))
throw new Exception($"Não foi possível remover o Lançamento {id}.");
PDVControlador.Commit();
}
catch (Exception ex)
{
PDVControlador.Rollback();
Alert(ex.Message);
}
}
Atualizar();
}
}
public void MudaParaReceber()
{
btnEditar.Visible = false;
btnNovo.Visible = false;
btnRemover.Visible = false;
btnReceber.Visible = true;
ExibirSoAbertas = true;
}
private void btnReceber_Click(object sender, EventArgs e)
{
Receber();
CarregarSoAbertas();
}
private void imprimriMetroButton_Click(object sender, EventArgs e)
{
gridView1.ShowPrintPreview();
}
private void atualizarMetroButton_Click(object sender, EventArgs e)
{
Atualizar();
}
private void gridControl1_DoubleClick_1(object sender, EventArgs e)
{
try
{
FCAFIN_ContaReceber Form = new FCAFIN_ContaReceber(FuncoesContaReceber.GetContaReceber(Convert.ToDecimal(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idcontareceber").ToString())));
Form.ShowDialog(this);
if (ExibirSoAbertas)
CarregarSoAbertas();
else
Atualizar();
}
catch (NullReferenceException)
{
}
}
private void baixarMetroButton_Click(object sender, EventArgs e)
{
if (IdsSelecionados.Count == 1)
{
var id = IdsSelecionados.First();
var form = new FCAFIN_ContaReceber(FuncoesContaReceber.GetContaReceber(id));
form.NovaBaixa();
if (form.botaoSalvar)
form.SalvarTudo();
}
else
{
var msg = "Confirmar a baixa das contas selecionadas?";
if (Confirm(msg) == DialogResult.Yes)
Baixar();
}
Atualizar();
}
private void Baixar()
{
try
{
PDVControlador.BeginTransaction();
foreach (var id in IdsSelecionados)
{
var conta = FuncoesContaReceber.GetContaReceber(id);
if (conta.Situacao == StatusConta.Baixado && conta.Situacao == StatusConta.Cancelado)
continue;
var baixa = new BaixaRecebimento()
{
IDContaReceber = conta.IDContaReceber,
IDBaixaRecebimento = Sequence.GetNextID("BAIXARECEBIMENTO", "IDBAIXARECEBIMENTO"),
IDFormaDePagamento = (decimal)conta.IDFormaDePagamento,
IDContaBancaria = Convert.ToDecimal(conta.IDContaBancaria),
IDHistoricoFinanceiro = (decimal)conta.IDHistoricoFinanceiro,
Valor = conta.Saldo,
Baixa = DateTime.Now
};
if (!FuncoesBaixaRecebimento.Salvar(baixa, TipoOperacao.INSERT))
throw new Exception($"Não foi possível baixar a conta na baixa {id}");
if (conta.IDContaBancaria == null)
conta.IDContaBancaria = conta.IDContaBancaria;
conta.Situacao = StatusConta.Baixado;
conta.Saldo = 0;
conta.IDUsuario = Contexto.USUARIOLOGADO.IDUsuario;
if (!FuncoesContaReceber.Salvar(conta, TipoOperacao.UPDATE))
throw new Exception($"Não foi possível salvar a conta {conta.IDContaReceber}");
}
PDVControlador.Commit();
}
catch (Exception ex)
{
PDVControlador.Rollback();
MessageBox.Show(this, ex.ToString());
}
}
private DialogResult Confirm(string msg)
{
return MessageBox.Show(msg, NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
{
if (e.Column.FieldName == "situacao")
FormatarCoresSituacao(e);
}
private void FormatarCoresSituacao(RowCellStyleEventArgs e)
{
string valor;
try
{
var cellValue = gridView1.GetRowCellValue(e.RowHandle, "situacao");
if (cellValue != null)
valor = cellValue.ToString();
else throw new Exception();
}
catch (Exception)
{
valor = "";
}
switch (valor)
{
case "BAIXADO":
e.Appearance.ForeColor = Color.Green;
break;
case "CANCELADO":
e.Appearance.ForeColor = Color.Red;
break;
case "ABERTO":
e.Appearance.ForeColor = Color.Blue;
break;
case "PARCIAL":
e.Appearance.ForeColor = Color.Yellow;
e.Appearance.BackColor = e.Appearance.BackColor2 = Color.Gray;
break;
}
}
private void simpleButtonDuplicar_Click(object sender, EventArgs e)
{
if (Confirm("Deseja duplicar?") == DialogResult.Yes)
foreach (var id in IdsSelecionados)
DuplicarConta(id);
Atualizar();
}
private void DuplicarConta(decimal id)
{
try
{
PDVControlador.BeginTransaction();
ContaReceber conta = FuncoesContaReceber.GetContaReceber(id);
conta.IDContaReceber = Sequence.GetNextID("CONTARECEBER", "IDCONTARECEBER");
conta.Situacao = 1;
conta.Emissao = conta.Vencimento = conta.Fluxo = DateTime.Now;
conta.Parcela = 1;
conta.Saldo = conta.ValorTotal;
conta.IDUsuario = Contexto.USUARIOLOGADO.IDUsuario;
conta.IDVenda = null;
if (!FuncoesContaReceber.Salvar(conta, TipoOperacao.INSERT))
throw new Exception($"Não foi possível duplicar a conta {id}");
PDVControlador.Commit();
}
catch (Exception ex)
{
PDVControlador.Rollback();
Alert(ex.Message);
}
}
private void Alert(string message)
{
MessageBox.Show(message, NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
}
private void gridView1_PrintInitialize(object sender, DevExpress.XtraGrid.Views.Base.PrintInitializeEventArgs e)
{
GridImprimir.FormatarImpressão(ref e);
}
private void dateEdit1_EditValueChanged(object sender, EventArgs e)
{
if (dateEdit1.DateTime > dateEdit2.DateTime)
dateEdit2.DateTime = dateEdit1.DateTime.AddDays(1);
}
private void dateEdit2_EditValueChanged(object sender, EventArgs e)
{
if (dateEdit1.DateTime > dateEdit2.DateTime)
{
dateEdit1.DateTime = dateEdit2.DateTime;
dateEdit2.DateTime = dateEdit1.DateTime.AddDays(1);
}
}
private void simpleButton1_Click(object sender, EventArgs e)
{
try
{
ContaReceber cr = FuncoesContaReceber.GetContaReceber(IdsSelecionados[0]);
Emitente emitente = FuncoesEmitente.GetEmitente();
Cliente cliente = FuncoesCliente.GetCliente(cr.IDCliente.Value);
Endereco endereco = FuncoesEndereco.GetEndereco(cliente.IDEndereco.Value);
Recibo recibo = new Recibo()
{
Pessoa = cliente.NomeFantasia != null ? cliente.NomeFantasia : cliente.Nome,
PessoaEndereco = $"{endereco.Logradouro}, Nº {endereco.Numero}, {endereco.Bairro}, {endereco.Municipio}, {endereco.UnidadeFederativa}",
Referente = "COMPRA DE PRODUTO E SERVIÇOS.",
Valor = cr.ValorTotal,
Importancia = ClsExtenso.Extenso_Valor(cr.ValorTotal),
Emitente = emitente.RazaoSocial,
EmitenteDocumento = emitente.CNPJ,
Data = DateTime.Now.ToString("dd/MM/yyyy")
};
var rel = new ReciboPagamento(recibo);
using (ReportPrintTool printTool = new ReportPrintTool(rel))
{
printTool.ShowPreviewDialog();
}
}
catch (Exception ex)
{
}
}
private void botaoPesquisarProduto_Click(object sender, EventArgs e)
{
try
{
decimal idMovimento = 0;
try
{
idMovimento = Convert.ToDecimal(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idvenda"));
}
catch (Exception)
{
}
if (idMovimento > 0)
{
ItemVenda itemVenda = FuncoesItemVenda.GetItemVenda(Convert.ToDecimal(idMovimento));
new PedidoVendaItem(Convert.ToInt16(itemVenda.IDVenda)).ShowDialog();
botaoPesquisarProduto.Enabled = false;
}
}
catch (NullReferenceException)
{
}
finally
{
botaoPesquisarProduto.Enabled = false;
}
}
private void gridView1_Click(object sender, EventArgs e)
{
botaoPesquisarProduto.Enabled = true;
}
}
}
|
using System;
using GalaSoft.MvvmLight;
namespace XamarinSample.ViewModels
{
public class SecondPageViewModel : ViewModelBase
{
public SecondPageViewModel(string messageParameter)
{
int result;
string textToShow;
if (Int32.TryParse(messageParameter, out result))
textToShow = (result * result).ToString();
else
textToShow = messageParameter;
Services.UserDialogService.Alert(textToShow);
}
}
}
|
// Use static
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StaticMethod214
{
class StaticDemo
{
// A static variable
public static int Val = 100;
// A static method
public static int ValDiv2()
{
return Val/2;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Initial value of StaticDemo.Val is " + StaticDemo.Val);
StaticDemo.Val = 8;
Console.WriteLine("StaticDemo.Val is " + StaticDemo.Val);
Console.WriteLine("StaticDemo.ValDemo2(): " +
StaticDemo.ValDiv2());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Gomoku {
public class MinMax
: IAI {
private Board Map = null;
private uint MaxDepth = 1;
public bool Finished = false;
private uint Offset = 0;
private List<Tuple<uint, uint>> PossibleMoves = null;
private Tuple<uint, uint> best = null;
public Tuple<uint, uint> MakeMove(Board board) {
if (board.Empty())
return new Tuple<uint, uint>(board.Size / 2, board.Size / 2);
InitBoard(board);
var begin = DateTime.Now;
var t = new Thread(new ThreadStart(this.DecideMove));
t.Start();
while ((DateTime.Now - begin).TotalMilliseconds < 4700 && !Finished)
Thread.Sleep(100);
if (!Finished)
t.Abort();
var res = new Tuple<uint, uint>(best.Item1 + Offset, best.Item2 + Offset);
Map = null;
Offset = 0;
Finished = false;
best = null;
PossibleMoves = null;
return res;
}
private void InitBoard(Board board) {
uint off;
uint eoff = 0;
for (off = 0; off < board.Size; ++off) {
if (CheckBorderUp(board, off))
break;
}
if (off > 0)
--off;
for (eoff = board.Size - 1; eoff >= 0; --eoff) {
if (CheckBorderDown(board, eoff, off))
break;
}
if (eoff < board.Size - 1)
++eoff;
Offset = off;
Map = new Board(eoff - off + 1);
for (int i = 0; i < Map.Size; i++)
for (int j = 0; j < Map.Size; j++)
Map.Map[i, j] = board.Map[Offset + i, Offset + j];
}
private bool CheckBorderUp(Board board, uint offset) {
for (var x = offset; x < board.Size; ++x) {
if (board.Map[x, offset] != State.Empty)
return true;
}
for (var y = offset; y < board.Size; ++y) {
if (board.Map[offset, y] != State.Empty)
return true;
}
return false;
}
private bool CheckBorderDown(Board board, uint eoffset, uint offset)
{
if (eoffset == offset)
return true;
for (var x = eoffset; x > offset; --x) {
if (board.Map[x, eoffset] != State.Empty)
return true;
}
for (var y = eoffset; y > offset; --y) {
if (board.Map[eoffset, y] != State.Empty)
return true;
}
return false;
}
private void DecideMove() {
double bestScore = double.MinValue;
PossibleMoves = Map.PossibleMoves();
double currentScore = 0;
var depth = MaxDepth;
if (PossibleMoves.Count() == 1) {
best = PossibleMoves.ElementAt(0);
Finished = true;
return;
}
RemoveUselessMoves();
var moves = new List<Tuple<uint, uint>>(PossibleMoves);
foreach (var move in moves) {
Map.Play(move.Item1, move.Item2, State.Myself);
PossibleMoves.Remove(move);
currentScore = MinimiseMove(depth, double.MinValue, double.MaxValue, move);
if (currentScore == double.MaxValue) {
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
best = move;
Finished = true;
return;
}
if (best == null || bestScore < currentScore) {
best = move;
bestScore = currentScore;
}
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
}
Finished = true;
}
private void RemoveUselessMoves() {
var moves = new List<Tuple<uint, uint>>();
foreach (var move in PossibleMoves) {
if (CheckAround(move))
moves.Add(move);
}
PossibleMoves = moves;
}
private bool CheckAround(Tuple<uint, uint> move) {
for (var x = -2; x < 3; ++x) {
if (x < 0 && Math.Abs(x) > move.Item1)
continue;
if (move.Item1 + x >= Map.Size)
continue;
for (var y = -2; y < 3; ++y) {
if (y < 0 && Math.Abs(y) > move.Item2)
continue;
if (move.Item2 + y >= Map.Size)
continue;
if (x == 0 && y == 0)
continue;
if (Map.Map[move.Item1 + x, move.Item2 + y] != State.Empty)
return true;
}
}
return false;
}
private double MinimiseMove(uint depth, double alpha, double beta, Tuple<uint, uint> madeMove) {
double res;
Evaluator eval = new Evaluator();
res = eval.Evaluate(Map);
if (depth == 0 || res == double.MaxValue || res == double.MinValue) {
return res;
}
res = double.MaxValue;
var moves = new List<Tuple<uint, uint>>(PossibleMoves);
foreach (var move in moves) {
PossibleMoves.Remove(move);
Map.Play(move.Item1, move.Item2, State.Opponent);
double score = MaximiseMove(depth - 1, alpha, beta, move);
if (score == double.MaxValue) {
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
return score;
}
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
res = Math.Min(res, score);
beta = Math.Min(beta, score);
if (beta <= alpha)
break;
}
return res;
}
private double MaximiseMove(uint depth, double alpha, double beta, Tuple<uint, uint> madeMove) {
double res;
Evaluator eval = new Evaluator();
res = eval.Evaluate(Map);
if (depth == 0 || res == double.MaxValue || res == double.MinValue) {
return res;
}
res = double.MinValue;
var moves = new List<Tuple<uint, uint>>(PossibleMoves);
foreach (var move in moves) {
PossibleMoves.Remove(move);
Map.Play(move.Item1, move.Item2, State.Myself);
double score = MinimiseMove(depth - 1, alpha, beta, move);
if (score == double.MaxValue) {
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
return score;
}
PossibleMoves.Add(move);
Map.Unplay(move.Item1, move.Item2);
res = Math.Max(res, score);
alpha = Math.Max(alpha, score);
if (beta <= alpha)
break;
}
return res;
}
}
}
|
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_TileMapGraph : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int GetTileValue(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
var ret=self.GetTileValue(a1,a2);
pushValue(l,true);
pushEnum(l,(int)ret);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetTileValue(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
TileType a3;
a3 = (TileType)LuaDLL.luaL_checkinteger(l, 4);
self.SetTileValue(a1,a2,a3);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int SetTileValues(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
self.SetTileValues();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_width(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
pushValue(l,true);
pushValue(l,self.width);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_width(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
System.Single v;
checkType(l,2,out v);
self.width=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_length(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
pushValue(l,true);
pushValue(l,self.length);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_length(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
System.Single v;
checkType(l,2,out v);
self.length=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_nodeSize(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
pushValue(l,true);
pushValue(l,self.nodeSize);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_nodeSize(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
System.Single v;
checkType(l,2,out v);
self.nodeSize=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_xNode(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
pushValue(l,true);
pushValue(l,self.xNode);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_zNode(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
TileMapGraph self=(TileMapGraph)checkSelf(l);
pushValue(l,true);
pushValue(l,self.zNode);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"TileMapGraph");
addMember(l,GetTileValue);
addMember(l,SetTileValue);
addMember(l,SetTileValues);
addMember(l,"width",get_width,set_width,true);
addMember(l,"length",get_length,set_length,true);
addMember(l,"nodeSize",get_nodeSize,set_nodeSize,true);
addMember(l,"xNode",get_xNode,null,true);
addMember(l,"zNode",get_zNode,null,true);
createTypeMetatable(l,null, typeof(TileMapGraph),typeof(UnityEngine.MonoBehaviour));
}
}
|
using UnityEngine;
public class Asteroid : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
var playerHealth = other.GetComponent<PlayerHealth>();
if (!playerHealth) return;
playerHealth.Crash();
}
private void OnBecameInvisible()
{
Destroy(gameObject);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OldTimeRail
{
class SunEastPM
{
static String trainName = "Sunday East PM";
static String[,] carriageA = new String[32, 2];
static String[,] carriageB = new String[32, 2];
static String[,] carriageC = new String[50, 2];
static String[,] carriageD = new String[50, 2];
public static int baggageSpaces = 0;
public static void initialiseA()
{
for (int i = 0; i < 32; i++)
{
StringBuilder seatNumber = new StringBuilder();
seatNumber.Append('A');
if (i < 10)
{
seatNumber.Append('0');
}
seatNumber.Append(i);
carriageA[i, 0] = seatNumber.ToString();
carriageA[i, 1] = null;
}
}
public static void initialiseB()
{
for (int i = 0; i < 32; i++)
{
StringBuilder seatNumber = new StringBuilder();
seatNumber.Append('B');
if (i < 10)
{
seatNumber.Append('0');
}
seatNumber.Append(i);
carriageB[i, 0] = seatNumber.ToString();
carriageB[i, 1] = null;
}
}
public static void initialiseC()
{
for (int i = 0; i < 50; i++)
{
StringBuilder seatNumber = new StringBuilder();
seatNumber.Append('C');
if (i < 10)
{
seatNumber.Append('0');
}
seatNumber.Append(i);
carriageC[i, 0] = seatNumber.ToString();
carriageC[i, 1] = null;
}
}
public static void initialiseD()
{
for (int i = 0; i < 50; i++)
{
StringBuilder seatNumber = new StringBuilder();
seatNumber.Append('D');
if (i < 10)
{
seatNumber.Append('0');
}
seatNumber.Append(i);
carriageD[i, 0] = seatNumber.ToString();
carriageD[i, 1] = null;
}
}
public static String[,] returnCarriageA()
{
return carriageA;
}
public static String[,] returnCarriageB()
{
return carriageB;
}
public static String[,] returnCarriageC()
{
return carriageC;
}
public static String[,] returnCarriageD()
{
return carriageD;
}
public static void bookCarriageA(int partySize, String name, int baggage)
{
if (partySize <= 8)
{
if (bookBaggage(baggage) == true)
{
int freeSpaces = 0;
int seatNumber = 0;
int compartmentNumber = 0;
int amountBooked = 0;
bool success = false;
String[] seatNumbers = new String[partySize];
while (success == false)
{
for (seatNumber = 8 * compartmentNumber; seatNumber < 8 * (compartmentNumber + 1) && freeSpaces < partySize && seatNumber < 32; seatNumber++)
{
if (carriageA[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = compartmentNumber * 8; seatNumber < 8 * (compartmentNumber + 1); seatNumber++)
{
if (carriageA[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageA[seatNumber, 0];
carriageA[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 3)
{
Console.WriteLine("Your booking has failed. There are not enough seats on this train.");
success = true;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
}
else
{
Console.WriteLine("Booking cancelled.");
}
}
else
{
Console.WriteLine("The maximum booking size is 8 for a compartment carriage");
}
}
public static void bookCarriageB(int partySize, String name, int baggage)
{
if (partySize <= 8)
{
if (bookBaggage(baggage) == true)
{
int freeSpaces = 0;
int seatNumber = 0;
int compartmentNumber = 0;
int amountBooked = 0;
bool success = false;
String[] seatNumbers = new String[partySize];
while (success == false)
{
for (seatNumber = 8 * compartmentNumber; seatNumber < 8 * (compartmentNumber + 1) && freeSpaces < partySize && seatNumber < 32; seatNumber++)
{
if (carriageB[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = compartmentNumber * 8; seatNumber < 8 * (compartmentNumber + 1); seatNumber++)
{
if (carriageB[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageB[seatNumber, 0];
carriageB[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 3)
{
Console.WriteLine("Your booking has failed. There are not enough seats on this train.");
success = true;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
}
else
{
Console.WriteLine("Booking cancelled.");
}
}
else
{
Console.WriteLine("The maximum booking size is 8 for a compartment carriage");
}
}
public static void bookCarriageC(int partySize, String name, int baggage)
{
if (bookBaggage(baggage) == true)
{
int freeSpaces = 0;
int seatNumber = 0;
int compartmentNumber = 0;
int amountBooked = 0;
bool success = false;
String[] seatNumbers = new String[partySize];
while (success == false)
{
if (partySize <= 4)
{
//Search the first 4 out of 10 as they are the group of 4 seats (0-3)(10-13)
for (seatNumber = compartmentNumber * 10; seatNumber < (compartmentNumber * 10) + 4; seatNumber++)
{
if (carriageC[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = compartmentNumber * 10; seatNumber < (compartmentNumber * 10) + 4; seatNumber++)
{
if (carriageC[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageC[seatNumber, 0];
carriageC[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
//success = true;
bookCarriageD(partySize, name, baggage);
break;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else if (partySize > 4 && partySize <= 6)
{
// Else check the last 6 (4-9)
for (seatNumber = (compartmentNumber * 10) + 4; seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageC[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = (compartmentNumber * 10) + 4; seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageC[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageC[seatNumber, 0];
carriageC[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
success = true;
bookCarriageD(partySize, name, baggage);
break;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else if (partySize > 6 && partySize <= 10)
{
//Else check in the set of 10 to assign seats
for (seatNumber = (compartmentNumber * 10); seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageC[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = (compartmentNumber * 10); seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageC[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageC[seatNumber, 0];
carriageC[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
bookCarriageD(partySize, name, baggage);
success = true;
break;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else
{
Console.WriteLine("You have entered too many people. You can only book a maximum 10 tickets at a time.");
success = true;
}
}
}
else
{
Console.WriteLine("Booking cancelled.");
}
}
public static void bookCarriageD(int partySize, String name, int baggage)
{
if (bookBaggage(baggage) == true)
{
int freeSpaces = 0;
int seatNumber = 0;
int compartmentNumber = 0;
int amountBooked = 0;
bool success = false;
String[] seatNumbers = new String[partySize];
while (success == false)
{
if (partySize <= 4)
{
//Search the first 4 out of 10 as they are the group of 4 seats (0-3)(10-13)
for (seatNumber = compartmentNumber * 10; seatNumber < (compartmentNumber * 10) + 4; seatNumber++)
{
if (carriageD[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = compartmentNumber * 10; seatNumber < (compartmentNumber * 10) + 4; seatNumber++)
{
if (carriageD[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageD[seatNumber, 0];
carriageD[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
Console.WriteLine("Your booking has failed. There are not enough seats on this train.");
success = true;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else if (partySize > 4 && partySize <= 6)
{
// Else check the last 6 (4-9)
for (seatNumber = (compartmentNumber * 10) + 4; seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageD[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = (compartmentNumber * 10) + 4; seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageD[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageD[seatNumber, 0];
carriageD[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
Console.WriteLine("Your booking has failed. There are not enough seats on this train.");
success = true;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else if (partySize > 6 && partySize <= 10)
{
//Else check in the set of 10 to assign seats
for (seatNumber = (compartmentNumber * 10); seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageD[seatNumber, 1] == null)
{
freeSpaces++;
}
}
if (freeSpaces >= partySize)
{
while (amountBooked < partySize)
{
for (seatNumber = (compartmentNumber * 10); seatNumber < (compartmentNumber + 1) * 10; seatNumber++)
{
if (carriageD[seatNumber, 1] == null && amountBooked < partySize)
{
seatNumbers[amountBooked] = carriageD[seatNumber, 0];
carriageD[seatNumber, 1] = name;
amountBooked++;
}
}
}
success = true;
Console.WriteLine("Booking successful. Please remember your seat numbers:");
for (int i = 0; i < seatNumbers.Length; i++)
{
Console.WriteLine(seatNumbers[i] + " ");
}
Console.WriteLine("You have been booked onto " + trainName);
}
else
{
if (compartmentNumber == 4)
{
Console.WriteLine("Your booking has failed. There are not enough seats on this train.");
success = true;
}
else
{
compartmentNumber++;
seatNumber = 0;
}
}
}
else
{
Console.WriteLine("You have entered too many people. You can only book a maximum 10 tickets at a time.");
success = true;
}
}
}
else
{
Console.WriteLine("Booking cancelled.");
}
}
public static bool bookBaggage(int baggage)
{
if (baggageSpaces + baggage <= 40)
{
baggageSpaces = baggageSpaces + baggage;
Console.WriteLine(baggage + " bags have been added.");
return true;
}
else
{
string userSelection = "";
int userInput = 0;
Console.WriteLine("There are only " + (40 - baggageSpaces) + " available. Please select one of the following options:");
Console.WriteLine("1) Enter less baggage.");
Console.WriteLine("2) Continue without bags.");
Console.WriteLine("3) Cancel booking.");
userSelection = Console.ReadLine();
userInput = Int32.Parse(userSelection);
switch (userSelection)
{
case "1":
Console.WriteLine("Please enter how many bags you would like.");
bookBaggage(Int32.Parse(Console.ReadLine()));
return true;
case "2":
return true;
case "3":
return false;
default:
Console.WriteLine("Please enter a correct number.");
break;
}
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AdventOfCode2019
{
public static class Day25
{
public static void RunDay()
{
Console.WriteLine("Day 25");
Console.WriteLine("**************");
Console.WriteLine(Environment.NewLine);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class arcade : MonoBehaviour {
public UnityEngine.UI.Text[] Info;
public GameObject[] Enemies;
public int Amount;
void Start () {
Amount = (PlayerPrefs.GetInt("Level") + 1) * Random.Range(1, 3);
}
// Update is called once per frame
void Update () {
Info[0].text = "HIGHSCORE: " + PlayerPrefs.GetInt("Highscore");
Info[1].text = "LEVEL " + PlayerPrefs.GetInt("Level");
Info[2].text = "SCORE: " + PlayerPrefs.GetInt("Score");
if (Amount <= 0 && Amount != null) {
PlayerPrefs.SetInt("Level", PlayerPrefs.GetInt("Level") + 1);
SceneManager.LoadScene("Arcade");
}
if (PlayerPrefs.GetInt("Score") > PlayerPrefs.GetInt("Highscore")) {
PlayerPrefs.SetInt("Highscore", PlayerPrefs.GetInt("Score"));
}
}
public void Restart () {
PlayerPrefs.SetInt("Level", 0);
PlayerPrefs.SetInt("Score", 0);
SceneManager.LoadScene("Arcade");
}
public void Enemy_Generation (Vector3[] Positions) {
float Size = Enemies[0].GetComponent<SpriteRenderer>().size.x * Enemies[0].GetComponent<Transform>().localScale.x;
Vector3[] More_Positions = new Vector3[Positions.Length + Amount + 16];
for (int i = 0; i < Positions.Length; i++) {
More_Positions[i] = Positions[i];
}
for (int a = 0; a < 4; a++) {
for (int b = 0; b < 4; b++) {
More_Positions[Positions.Length + b + a * 4] = new Vector3(Size * a - 2, Size * b - 2, 0);
}
}
for (int i = 0; i < Amount; i++) {
GameObject Item = Enemies[0];
GameObject Clone = Instantiate(Item);
Vector3 Spot = new Vector3(Size * Random.Range(-15, 15), Size * Random.Range(-10, 10), 0);
for (int a = 0; a < More_Positions.Length; a++) {
if (Spot == More_Positions[a]) {
Spot = new Vector3(Size * Random.Range(-15, 15), Size * Random.Range(-10, 10), 0);
a = 0;
}
}
Clone.transform.position = Spot;
Clone.transform.name = Item.name;
}
}
} |
/*
* ProWritingAid API V2
*
* Official ProWritingAid API Version 2
*
* OpenAPI spec version: v2
* Contact: hello@prowritingaid.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using ProWritingAid.SDK.Api;
using ProWritingAid.SDK.Model;
using ProWritingAid.SDK.Client;
using System.Reflection;
namespace ProWritingAid.SDK.Test
{
/// <summary>
/// Class for testing UserDocument
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class UserDocumentTests
{
// TODO uncomment below to declare an instance variable for UserDocument
//private UserDocument instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of UserDocument
//instance = new UserDocument();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of UserDocument
/// </summary>
[Test]
public void UserDocumentInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" UserDocument
//Assert.IsInstanceOfType<UserDocument> (instance, "variable 'instance' is a UserDocument");
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Test]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
/// <summary>
/// Test the property 'Created'
/// </summary>
[Test]
public void CreatedTest()
{
// TODO unit test for the property 'Created'
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Content'
/// </summary>
[Test]
public void ContentTest()
{
// TODO unit test for the property 'Content'
}
/// <summary>
/// Test the property 'Preview'
/// </summary>
[Test]
public void PreviewTest()
{
// TODO unit test for the property 'Preview'
}
/// <summary>
/// Test the property 'LastModified'
/// </summary>
[Test]
public void LastModifiedTest()
{
// TODO unit test for the property 'LastModified'
}
/// <summary>
/// Test the property 'DocumentId'
/// </summary>
[Test]
public void DocumentIdTest()
{
// TODO unit test for the property 'DocumentId'
}
/// <summary>
/// Test the property 'AutoSaveLastModified'
/// </summary>
[Test]
public void AutoSaveLastModifiedTest()
{
// TODO unit test for the property 'AutoSaveLastModified'
}
/// <summary>
/// Test the property 'GrammarScore'
/// </summary>
[Test]
public void GrammarScoreTest()
{
// TODO unit test for the property 'GrammarScore'
}
/// <summary>
/// Test the property 'StyleScore'
/// </summary>
[Test]
public void StyleScoreTest()
{
// TODO unit test for the property 'StyleScore'
}
/// <summary>
/// Test the property 'SpellingScore'
/// </summary>
[Test]
public void SpellingScoreTest()
{
// TODO unit test for the property 'SpellingScore'
}
/// <summary>
/// Test the property 'TermScore'
/// </summary>
[Test]
public void TermScoreTest()
{
// TODO unit test for the property 'TermScore'
}
/// <summary>
/// Test the property 'OverallScore'
/// </summary>
[Test]
public void OverallScoreTest()
{
// TODO unit test for the property 'OverallScore'
}
}
}
|
/*
* 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 NUnit.Framework;
namespace KaVE.RS.Commons.Tests_Integration.Analysis.SmokeTests
{
[TestFixture]
internal class CodeCompletionWithIncompleteReferenceSmokeTest : BaseCSharpCodeCompletionTest
{
[Test]
public void UsingKeyword()
{
CompleteInCSharpFile(@"
usin$
");
}
[Test]
public void UsingNamespace()
{
CompleteInCSharpFile(@"
using $
");
}
[Test]
public void UsingNamespaceContinuation()
{
CompleteInCSharpFile(@"
using Sys$
");
}
[Test]
public void UsingSubNamespace()
{
CompleteInCSharpFile(@"
using Sytem.$
");
}
[Test]
public void UsingSubNamespaceContinuation()
{
CompleteInCSharpFile(@"
using Sytem.Coll$
");
}
[Test]
public void UsingWithAlias()
{
CompleteInCSharpFile(@"
using MyAlias = $
");
}
[Test]
public void ClassAnntation()
{
CompleteInCSharpFile(@"
[$]
public class C {}
");
}
[Test]
public void ClassAnntationContinuation()
{
CompleteInCSharpFile(@"
[Not$]
public class C {}
");
}
[Test]
public void ConstructorDelegationKeyword()
{
CompleteInCSharpFile(@"
class C
{
public C(int i) : th$
public C(string s) {}
}");
}
[Test]
public void ConstructorDelegationDisambiguation()
{
CompleteInCSharpFile(@"
class C
{
public C(int i) : this$
public C(string s) {}
}");
}
[Test]
public void ConstructorDelegationParameter()
{
CompleteInCSharpFile(@"
class C
{
public C(int i) : this($)
public C(string s) {}
}");
}
[Test]
public void MemberAnnotation()
{
CompleteInClass(@"
[$]
public int _f;");
}
[Test]
public void MemberAnnotationContinuation()
{
CompleteInClass(@"
[Ha$]
public int _f;");
}
[Test]
public void MemberAccessDirect()
{
CompleteInClass(@"
public void M(object o)
{
o.$
}
");
}
[Test]
public void MemberAccessDirectContinuation()
{
CompleteInClass(@"
public void M(object o)
{
o.ToS$
}
");
}
[Test]
public void MemberAccessUnknownType()
{
CompleteInClass(@"
public void M()
{
o.$
}
");
}
[Test]
public void MemberAccessUnknownTypeContinuation()
{
CompleteInClass(@"
public void M()
{
o.Get$
}
");
}
[Test]
public void MemberAccessInCast()
{
CompleteInClass(@"
public void M(object o)
{
var u = (int) o.$
}
");
}
[Test]
public void MemberAccessInCastContinuation()
{
CompleteInClass(@"
public void M(object o)
{
var u = (int) o.GetH$
}
");
}
[Test]
public void CastSource()
{
CompleteInClass(@"
public void M()
{
var u = (int) $
}
");
}
[Test]
public void MemberAccessOnReturnValue()
{
CompleteInClass(@"
public void M()
{
GetHashCode().$
}
");
}
[Test]
public void MemberAccessOnReturnValueContinuation()
{
CompleteInClass(@"
public void M()
{
GetHashCode().GetH$
}
");
}
[Test]
public void MemberAccessOnField()
{
CompleteInClass(@"
private object _f;
public void M()
{
_f.$
}
");
}
[Test]
public void MemberAccessOnFieldContinuation()
{
CompleteInClass(@"
private object _f;
public void M()
{
_f.Eq$
}
");
}
[Test]
public void MissingReturn()
{
CompleteInClass(@"
public int M()
{
$
}
");
}
[Test]
public void MissingArgument()
{
CompleteInMethod(@"
this.Equals($);
");
}
[Test]
public void MissingArgumentContinuation()
{
CompleteInMethod(@"
this.Equals(th$);
");
}
}
} |
using UnityEngine;
using Crypto;
using System;
class TestCrypto : MonoBehaviour
{
void Start ()
{
Signature.Generate("abc", "example@gmail.com");
// Signature.Import(string signingKey);
Debug.Log(
Signature.Validate(
"hello world",
Signature.Sign("hello world")
)
);
Debug.Log(Signature.signingKey); // secret
Debug.Log(Signature.publicKey); // public
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for PropertyService
/// </summary>
public class PropertyService :DataService
{
public PropertyService()
{
//
// TODO: Add constructor logic here
//
}
public int infoid { get; set; }
public string fname { get; set; }
public string lname { get; set; }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
namespace ServerKinect.Video
{
public class DepthBitmapFactory : DepthImageFactoryBase, IBitmapFactory
{
public DepthBitmapFactory(int maxDepth)
: base(maxDepth)
{ }
[HandleProcessCorruptedStateExceptions]
public unsafe void CreateImage(Bitmap targetImage, IntPtr pointer)
{
var area = new System.Drawing.Rectangle(0, 0, targetImage.Width, targetImage.Height);
this.CreateHistogram(pointer, area.Width, area.Height);
var data = targetImage.LockBits(area, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
try
{
ushort* pDepth = (ushort*)pointer;
for (int y = 0; y < area.Height; y++)
{
byte* pDest = (byte*)data.Scan0.ToPointer() + y * data.Stride;
for (int x = 0; x < area.Width; x++, ++pDepth, pDest += 3)
{
byte pixel = (byte)histogram.GetValue(*pDepth);
pDest[0] = pixel;
pDest[1] = pixel;
pDest[2] = pixel;
}
}
}
catch (AccessViolationException)
{ }
catch (SEHException)
{ }
targetImage.UnlockBits(data);
}
}
}
|
[System.ComponentModel.TypeConverter(typeof(StringIdTypeConverter))]
[Newtonsoft.Json.JsonConverter(typeof(StringIdJsonConverter))]
readonly partial struct StringId : System.IComparable<StringId>, System.IEquatable<StringId>
{
public string Value { get; }
public StringId(string value)
{
Value = value;
}
public static readonly StringId Empty = new StringId(string.Empty);
public bool Equals(StringId other) => this.Value.Equals(other.Value);
public int CompareTo(StringId other) => Value.CompareTo(other.Value);
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is StringId other && Equals(other);
}
public override int GetHashCode() => Value.GetHashCode();
public override string ToString() => Value.ToString();
public static bool operator ==(StringId a, StringId b) => a.CompareTo(b) == 0;
public static bool operator !=(StringId a, StringId b) => !(a == b);
class StringIdTypeConverter : System.ComponentModel.TypeConverter
{
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
var stringValue = value as string;
if (!string.IsNullOrEmpty(stringValue))
{
return new StringId(stringValue);
}
return base.ConvertFrom(context, culture, value);
}
}
class StringIdJsonConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(System.Type objectType)
{
return objectType == typeof(StringId);
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
var id = (StringId)value;
serializer.Serialize(writer, id.Value);
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
return new StringId(serializer.Deserialize<string>(reader));
}
}
} |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Threading;
using System.Windows.Forms;
using Ayende.NHibernateQueryAnalyzer.Core.Model;
using Ayende.NHibernateQueryAnalyzer.UserInterface.Interfaces;
using Ayende.NHibernateQueryAnalyzer.Utilities;
using NHibernate.Mapping.Cfg;
using NHibernate.Mapping.Hbm;
namespace Ayende.NHibernateQueryAnalyzer.UserInterface.Presenters
{
/// <summary>
/// Summary description for MainPresenter.
/// </summary>
public class MainPresenter : IMainPresenter
{
protected IQueue queue;
protected readonly IProjectsRepository repository;
private Thread workThread;
private ThreadedCommandExecutioner executioner;
private IMainView view;
private Project currentProject;
private IProjectView currentPrjView;
private NHibernate.Cfg.Configuration nHibernateConfiguration;
public IProjectsRepository Repository
{
get { return repository; }
}
public MainPresenter(IMainView view, IProjectsRepository repository)
{
this.view = view;
this.repository = repository;
this.queue = new ThreadSafeQueue();
this.executioner = new ThreadedCommandExecutioner(queue);
this.workThread = new Thread(new ThreadStart(executioner.Run));
this.workThread.IsBackground = true;
this.workThread.Start();
}
internal virtual int GetLastDefaultProjectNamePostfix()
{
IList list = repository.GetProjectsStartingWith(MainForm.DefaultNamePrefix);
if (list.Count == 0)
return 0;
int max = 0;
int parsedProjectPostFix;
foreach (Project project in list)
{
parsedProjectPostFix = int.Parse(project.Name.Substring(MainForm.DefaultNamePrefix.Length));
max = Math.Max(max, parsedProjectPostFix);
}
return max;
}
public virtual Project CreateNewProject()
{
int lastId = GetLastDefaultProjectNamePostfix();
int newId = lastId + 1;
return repository.CreateProject(MainForm.DefaultNamePrefix + newId);
}
public virtual IProjectPresenter DisplayNewProject()
{
if (CloseProject() == false)
return null;
Project newProject = CreateNewProject();
return DisplayProject(newProject);
}
protected virtual IProjectPresenter DisplayProject(Project project)
{
CurrentProject = project;
IProjectPresenter projectPresenter = new ProjectPresenter(project, this);
projectPresenter.View.Closed+=new EventHandler(currentPrjCfg_Closed);
projectPresenter.View.TitleChanged+=new EventHandler(prjCfg_TitleChanged);
CurrentProjectView = projectPresenter.View;
view.Display(projectPresenter.View);
return projectPresenter;
}
public virtual bool CloseProject()
{
if (ShowUnsavedDialog() == false)
return false;
foreach (IView doc in view.Documents)
{
doc.Close(false);
}
return true;
}
protected bool ShowUnsavedDialog()
{
ArrayList unSavedList = new ArrayList();
foreach (IView doc in view.Documents)
{
if (doc.HasChanges)
unSavedList.Add(doc);
}
IView[] toSave, unsaved = (IView[]) unSavedList.ToArray(typeof (IView));
if (unsaved.Length > 0)
{
toSave = view.ShowUnsavedDialog(unsaved);
if ( toSave == null)
return false;
foreach (IView document in toSave)
{
document.Save();
}
}
return true;
}
public virtual void SaveDocument()
{
IView doc = view.ActiveDocument;
if (doc != null)
doc.Save();
}
public IProjectView CurrentProjectView
{
get { return currentPrjView; }
set { currentPrjView = value; }
}
public Project CurrentProject
{
get { return currentProject; }
set { currentProject = value; }
}
public IProjectPresenter OpenProject()
{
if (CloseProject() == false)
return null;
Project prj = view.SelectExistingProject();
if (prj != null)
{
return DisplayProject(prj);
}
return null;
}
/// <summary>
/// Executes the active query.
/// This assume that the active windows is a QueryForm
/// </summary>
public void ExecuteActiveQuery()
{
IQueryView qv = view.ActiveDocument as IQueryView;
if (qv != null)
{
//qv.QueryPresenter.NHibernateConfiguration =
qv.QueryPresenter.ExecuteQuery();
}
}
public IQueue Queue
{
get { return this.queue; }
}
public void AddNewQuery()
{
IQueryPresenter qp = new QueryPresenter(this);
//qp.NHibernateConfiguration = this.nHibernateConfiguration;
view.Display(qp.View);
}
public void OpenQuery()
{
Query q = view.SelectProjectQuery(CurrentProject);
if (q != null)
{
IQueryPresenter qp = new QueryPresenter(this,q);
view.Display(qp.View);
}
}
public void SaveDocumentAs()
{
IView doc = view.ActiveDocument as IView;
if (doc != null)
doc.SaveAs();
}
public void CloseCurrentDocument()
{
IView doc = view.ActiveDocument as IView;
if (doc != null)
doc.Close(true);
}
public bool DeleteProject(Project project)
{
if (view.AskYesNo("Are you sure you want to delete project: " + project.Name, "Delete Project?"))
{
Repository.RemoveProject(project);
return true;
}
return false;
}
public bool CloseProjectChildren()
{
if(ShowUnsavedDialog()==false)
return false;
foreach (IView document in view.Documents)
{
if ((document is IProjectView) == false)
document.Close(false);
}
return true;
}
public void EnqueueCommand(ICommand command)
{
queue.Enqueue(command);
}
public void CreateNewHbmDocument()
{
CreateSchemaDocument(typeof(hibernatemapping), View.SaveMappingDialog);
}
private void CreateSchemaDocument(Type t, SaveFileDialog dlg)
{
SchemaEditorView editor = new SchemaEditorView(View,dlg,t);
View.Display(editor);
}
public void CreateNewCfgDocument()
{
CreateSchemaDocument(typeof(hibernateconfiguration), View.SaveConfigDialog);
}
public void OpenHbmDocument(string name)
{
OpenSchemaDocument(typeof(hibernatemapping), name, View.SaveMappingDialog);
}
public void OpenCfgDocument(string name)
{
OpenSchemaDocument(typeof(hibernateconfiguration), name, View.SaveConfigDialog);
}
private void OpenSchemaDocument(Type t, string name, SaveFileDialog dlg)
{
try
{
SchemaEditorView editor = new SchemaEditorView(
View,
dlg,
t,
name);
View.Display(editor);
}
catch(Exception e)
{
View.AddException(e);
}
}
public IMainView View
{
get { return view; }
}
private void currentPrjCfg_Closed(object sender, EventArgs e)
{
view.Title = null;
CurrentProject = null;
CurrentProjectView = null;
}
private void prjCfg_TitleChanged(object sender, EventArgs e)
{
if(CurrentProjectView!=null)
view.Title = CurrentProjectView.Title;
}
public NHibernate.Cfg.Configuration NHibernateConfiguration
{
get { return nHibernateConfiguration; }
set { nHibernateConfiguration = value; }
}
public ICollection MappingFiles
{
get { return currentProject.MappingFiles; }
}
}
}
|
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public float cameraSpeed = 5f;
public float maxX = 32f;
public float minX = 0f;
private Transform player;
private AudioManager audioManager;
private AudioSource audioSource;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
audioSource = GetComponent<AudioSource>();
audioSource.loop = true;
audioManager.Play(audioManager.BGM, audioSource, true);
}
private void Start()
{
player = FindObjectOfType<PlayerControl>().transform;
}
private void FixedUpdate()
{
Vector3 temp = transform.position;
if (player.position.x <= maxX && player.position.x >= minX)
{
//temp.x = Mathf.Lerp(temp.x, player.position.x, Mathf.SmoothStep(0, cameraSpeed,Time.deltaTime * cameraSpeed));
temp.x = player.position.x;
}
temp.y = Mathf.Lerp(temp.y, player.position.y, Time.deltaTime * cameraSpeed);
transform.position = temp;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NSL.DotNet.Attributes;
using NSL.DotNet.Enums;
using System.Reflection;
using NSL.DotNet.Extensions;
namespace NSL.TextProcessing.Common {
public enum HyphenAction : byte {
None = 0,
Remove = 1
}
public enum WordBreakAction : byte {
None = 0,
Join = 1
}
[Flags]
public enum FillingWordBreakSymbols : byte {
[StringValue("\\s")] Spaces = 1,
[StringValue("\\d")] Digits = 2,
[StringValue("\\W")] NonWords = 4,
All = Spaces | Digits | NonWords
}
internal static class FillingWordBreakSymbolsExtensions {
internal static string GetPattern(this FillingWordBreakSymbols value) {
var flags = value.GetFlags();
var pattern = "";
foreach (var flag in flags) {
pattern += flag.GetStringValue();
}
return RegexPattern.ToFormat(pattern);
}
internal const string RegexPattern = "^[{0}]*$";
}
//[Flags]
//public enum Combines : byte {
// [IntValue(0)] None = 0,
// [IntValue(1)] One = 1,
// [IntValue(2)] Two = 2,
// [IntValue(3)] Three = 4,
// [IntValue(4)] Four = 8,
// [IntValue(5)] Five = 16,
// [IntValue(6)] Six = 32,
// [IntValue(7)] Seven = 64,
// [IntValue(8)] Eight = 128,
// All = One | Two | Three | Four | Five | Six | Seven | Eight,
//}
//public static class CombinesExtensions {
// public static int[] GetInts(this Combines combines) {
// return combines.GetFlags().Select(x=>x.GetIntValue()).ToArray();
// }
// public static int MaxCombineLevel => 8;
//}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Helpers;
namespace BetaDota2StatsMVC.Models
{
public class ProfileViewModel
{
[Display(Name ="Tracked")]
public string Tracked_until { get; set; }
[Display(Name = "Old Solo/Core MMR")]
public string Solo_competitive_rank { get; set; }
[Display(Name = "Old Party/Support MMR")]
public string Competitive_rank { get; set; }
public int Rank_tier { get; set; }
//public int Leaderboard_rank { get; set; }
public Profile Profile { get; set; }
public Mmr_Estimate Mmr_Estimate { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test15._3and15._4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static Color[] color = { Color.Black, Color.Blue, Color.Cyan,
Color.Green, Color.Orange, Color.Yellow,Color.Red, Color.Pink, Color.LightGray };
private static Color getC()// 获取随机颜色值的方法
{
// 随机产生一个color数组长度范围内的数字,以此为索引获取颜色
return color[new Random().Next(color.Length)];
}
int x = 30;//定义初始坐标
int y = 50;
void Draw()
{
while (true)
{//无限循环
Thread.Sleep(100);// 线程休眠0.1秒
//获取组件绘图上下文对象
Graphics graphics = this.CreateGraphics();
Pen pen = new Pen(getC());//设置画笔
//绘制直线并递增垂直坐标
graphics.DrawLine(pen, x, y, 700, y+=10);
if (y >= 300)
{
y = 50;
}
}
}
Thread th;
private void Form1_Load(object sender, EventArgs e)
{
th = new Thread(new ThreadStart(Draw));
th.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
th.Abort();
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AorFramework.NodeGraph
{
public interface IPrefabProcess
{
/// <summary>
/// 处理结果描述
/// </summary>
string ResultInfoDescribe();
/// <summary>
/// NodeGraph预制体自定义处理方法
/// </summary>
/// <param name="prefab">输入的预制体</param>
/// <returns>返回true为通过Process</returns>
bool PrefabProcess(GameObject prefab, ref List<string> ResultInfoList);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.