content stringlengths 23 1.05M |
|---|
// Compiler options: -doc:xml-049.xml -warnaserror
/// <summary>
/// </summary>
public class Testje {
static void Main () {
}
/// <summary>
/// <see cref="Test" />
/// <see cref="Format(object)" />
/// </summary>
private class A {
/// <summary>
/// <see cref="Test" />
/// <see cref="Format(object)" />
/// </summary>
private class Test {
}
}
/// <summary />
public string Test {
get { return ""; }
}
/// <summary />
public static void Format (object a)
{
}
}
|
@model TodoListWebApp.Models.Task
@{
ViewBag.Title = "Create The Task";
}
Time to create a task
@using (Html.BeginForm())
{
<div>
@Html.EditorFor(m => m.TaskName)
</div>
<input type="submit" value="Create" class="btn btn-default" />
}
|
using System;
using System.Collections.Generic;
using WinApp.Classes.Base;
using System.Drawing;
namespace WinApp.Classes
{
public class ViewRenderer
{
private Model model;
private Pen defaultPen = new Pen(Color.White, 2f);
private Pen debugPen = new Pen(Color.Red, 1f);
private Pen debugLinePen = new Pen(Color.White, 1f);
private Pen debugNormalPen = new Pen(Color.Yellow, 2f);
private const float DEBUG_LINE_SIZE = 10f;
private Vector debugPoint;
private Line debugLine;
private Line debugNormal;
public ViewRenderer(Model model)
{
this.model = model;
}
public void Render(Graphics g) {
foreach(Shape obj in model.objects) {
RenderObject(g, obj);
}
RenderObject(g, model.player);
RenderDebug(g);
}
private void RenderObject(Graphics g, Shape obj) {
if (obj is Circle) {
Circle circle = (Circle)obj;
Rectangle rect = new Rectangle((int)(circle.center.x - circle.rad),
(int)(circle.center.y - circle.rad),
circle.rad * 2,
circle.rad * 2);
g.DrawEllipse(defaultPen, rect);
} else if (obj is Polygon) {
Polygon polygon = (Polygon)obj;
Vector[] dots = polygon.dots.ToArray();
for (int i = 0; i < dots.Length - 1; i++) {
DrawLine(dots[i], dots[i + 1], g);
}
}
}
private void DrawLine(Vector dot1, Vector dot2, Graphics g)
{
g.DrawLine(defaultPen, dot1.x, dot1.y, dot2.x, dot2.y);
}
private void DrawLine(Vector dot1, Vector dot2, Graphics g, Pen pen)
{
g.DrawLine(pen, dot1.x, dot1.y, dot2.x, dot2.y);
}
public void SetDebugPoint(Vector point) {
debugPoint = point;
}
public void SetDebugLine(Line line) {
debugLine = line;
}
public void SetDebugNormal(Line line) {
debugNormal = line;
}
public void RenderDebug(Graphics g) {
if (debugPoint != null) {
Vector a = new Vector(debugPoint.x - DEBUG_LINE_SIZE, debugPoint.y);
Vector b = new Vector(debugPoint.x + DEBUG_LINE_SIZE, debugPoint.y);
DrawLine(a, b, g, debugPen);
a = new Vector(debugPoint.x, debugPoint.y - DEBUG_LINE_SIZE);
b = new Vector(debugPoint.x, debugPoint.y + DEBUG_LINE_SIZE);
DrawLine(a, b, g, debugPen);
}
if (debugLine != null) {
DrawLine(debugLine.a, debugLine.b, g, debugLinePen);
}
if (debugNormal != null) {
DrawLine(debugNormal.a, debugNormal.b, g, debugNormalPen);
}
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using TG.Blazor.IndexedDB;
using TheatreTickets.Client.Repos;
using TheatreTickets.Models;
namespace TheatreTickets.Client
{
public static class RepoServiceCollectionExtension
{
public static void UseRepos(this IServiceCollection services)
{
services.AddIndexedDB(DbStoreOptions);
services.AddScoped<ITheatreRepo, TheatreRepo>();
services.AddScoped<IHallRepo, HallRepo>();
services.AddScoped<IPlayRepo, PlayRepo>();
services.AddScoped<IPlayDateTimeRepo, PlayDateTimeRepo>();
services.AddScoped<ITicketRepo, TicketRepo>();
services.AddScoped<IUserRepo, UserRepo>();
}
private static void DbStoreOptions(DbStore dbStore)
{
dbStore.DbName = "theatreTicketsDb";
dbStore.Version = 1;
dbStore.Stores.Add(TheaterSchema);
dbStore.Stores.Add(HallSchema);
dbStore.Stores.Add(PlaySchema);
dbStore.Stores.Add(PlayDateTimeSchema);
dbStore.Stores.Add(TicketSchema);
dbStore.Stores.Add(UserSchema);
}
private static StoreSchema TheaterSchema => NewSchema<Theatre>()
.SetName(StoreNames.Theatre)
.SetKey(x => x.Id, false, true)
.AddSpec(x => x.Name)
.AddSpec(x => x.Location)
.AddSpec(x => x.Directions)
.AddSpec(x => x.Contact)
.AddSpec(x => x.Info)
//.AddSpec(x => x.Halls)
.AddSpec(x => x.HallsIds)
//.AddSpec(x => x.Plays)
.AddSpec(x => x.PlaysIds)
.AddSpec(x => x.ImagesUrls)
.AddSpec(x => x.Published);
private static StoreSchema HallSchema => NewSchema<Hall>()
.SetName(StoreNames.Hall)
.SetKey(x => x.Id, false, true)
.AddSpec(x => x.Name)
//.AddSpec(x => x.Theatre)
.AddSpec(x => x.TheatreId)
.AddSpec(x => x.Seats)
.AddSpec(x => x.ImagesUrls)
.AddSpec(x => x.Published);
private static StoreSchema PlaySchema => NewSchema<Play>()
.SetName(StoreNames.Play)
.SetKey(x => x.Id, false, true)
.AddSpec(x => x.Name)
.AddSpec(x => x.Description)
.AddSpec(x => x.Duration)
.AddSpec(x => x.ImagesUrls)
//.AddSpec(x => x.Theatre)
.AddSpec(x => x.TheatreId)
//.AddSpec(x => x.PlayDateTimes)
.AddSpec(x => x.PlayDateTimesIds)
.AddSpec(x => x.Published);
private static StoreSchema PlayDateTimeSchema => NewSchema<PlayDateTime>()
.SetName(StoreNames.PlayDateTime)
.SetKey(x => x.Id, false, true)
//.AddSpec(x => x.Play)
.AddSpec(x => x.PlayId)
//.AddSpec(x => x.Hall)
.AddSpec(x => x.HallId)
.AddSpec(x => x.DateTime)
.AddSpec(x => x.SeatsTaken)
.AddSpec(x => x.Published);
private static StoreSchema TicketSchema => NewSchema<Ticket>()
.SetName(StoreNames.Ticket)
.SetKey(x => x.Id, false, true)
.AddSpec(x => x.Seat)
//.AddSpec(x => x.ForDate)
.AddSpec(x => x.ForDateId);
private static StoreSchema UserSchema => NewSchema<User>()
.SetName(StoreNames.User)
.SetKey(x => x.Id, false, true)
.AddSpec(x => x.Name)
.AddSpec(x => x.Email)
.AddSpec(x => x.UserType)
//.AddSpec(x => x.PlaysWatched)
.AddSpec(x => x.PlaysWatchedIds)
//.AddSpec(x => x.Tickets)
.AddSpec(x => x.TicketsIds);
private static StoreSchema<T> NewSchema<T>() where T : class
=> new StoreSchema<T>();
}
} |
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MS-PL license. See LICENSE.txt file in the project root for full license information.
namespace CodeGeneration.Roslyn
{
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
/// <summary>Represents a C# code snippet.</summary>
/// <typeparam name="TSnippetArguments">
/// An argument class that helps transforming the text befor parsing it.
/// </typeparam>
public abstract class CSharpCodeSnippet<TSnippetArguments>
where TSnippetArguments : class
{
/// <summary>
/// Initializes a new instance of the <see cref="CSharpCodeSnippet{TSnippetArguments}"/> class.
/// </summary>
/// <param name="text">
/// The text of the code snippet.
/// </param>
/// <param name="fileName">
/// The file name of the code snippet (optional).
/// </param>
/// <param name="parseOptions">
/// The parse options.
/// </param>
protected CSharpCodeSnippet(string text, string fileName, CSharpParseOptions parseOptions)
{
Text = text;
FileName = fileName;
ParseOptions = parseOptions ?? CSharpParseOptions.Default;
}
/// <summary>Gets the (untransformed) text of the code snippet.</summary>
public string Text { get; }
/// <summary>Gets the file name of the code snippet.</summary>
public string FileName { get; }
/// <summary>Gets the <see cref="CSharpParseOptions"/> to parse the <see cref="Text"/> with.</summary>
public CSharpParseOptions ParseOptions { get; }
/// <summary>Parses the code snippet.</summary>
/// <returns>
/// The parsed <see cref="CompilationUnitSyntax"/> of the code snippet.
/// </returns>
public Task<CompilationUnitSyntax> ParseAsync() => ParseAsync(null);
/// <summary>Parses the code snippet.</summary>
/// <param name="arguments">
/// The (optional) arguments to transform the code snippet before parsing.
/// </param>
/// <returns>
/// The parsed <see cref="CompilationUnitSyntax"/> of the code snippet.
/// </returns>
public async Task<CompilationUnitSyntax> ParseAsync(TSnippetArguments arguments)
{
var transformed = arguments is null ? Text : TransformText(arguments);
var tree = CSharpSyntaxTree.ParseText(transformed, ParseOptions, FileName, Encoding.UTF8, default);
var root = await tree.GetRootAsync(default);
return (CompilationUnitSyntax)root;
}
/// <summary>Parses the code snippet.</summary>
/// <typeparam name="TSyntax">
/// The <see cref="SyntaxNode"/> type of the code snippet.
/// </typeparam>
/// <returns>
/// The parsed <see cref="SyntaxNode"/> of the code snippet.
/// </returns>
public Task<TSyntax> ParseAysnc<TSyntax>()
where TSyntax : SyntaxNode
{
return ParseAsync<TSyntax>(default);
}
/// <summary>Parses the code snippet.</summary>
/// <typeparam name="TSyntax">
/// The <see cref="SyntaxNode"/> type of the code snippet.
/// </typeparam>
/// <param name="arguments">
/// The (optional) arguments to transform the code snippet before parsing.
/// </param>
/// <returns>
/// The parsed <see cref="SyntaxNode"/> of the code snippet.
/// </returns>
public async Task<TSyntax> ParseAsync<TSyntax>(TSnippetArguments arguments)
where TSyntax : SyntaxNode
{
var root = await ParseAsync(arguments);
return (TSyntax)root.ChildNodes().FirstOrDefault(ch => ch is TSyntax);
}
/// <inheritdoc />
public override string ToString() => Text;
/// <summary>Transforms the text before parsing it.</summary>
/// <param name="arguments">
/// The arguments to transform the code snippet before parsing.
/// </param>
/// <returns>
/// The transformed <see cref="Text"/>.
/// </returns>
protected abstract string TransformText(TSnippetArguments arguments);
}
}
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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.
*
* Copyright (c) The DotNetty Project (Microsoft). All rights reserved.
*
* https://github.com/azure/dotnetty
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Codecs.Http
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using DotNetty.Common.Internal;
using DotNetty.Common.Utilities;
/// <summary>
/// Splits an HTTP query string into a path string and key-value parameter pairs.
/// This decoder is for one time use only. Create a new instance for each URI:
/// <para>
/// <code>QueryStringDecoder decoder = new QueryStringDecoder("/hello?recipient=world&x=1;y=2");</code>
/// assert decoder.path().equals("/hello");
/// assert decoder.parameters().get("recipient").get(0).equals("world");
/// assert decoder.parameters().get("x").get(0).equals("1");
/// assert decoder.parameters().get("y").get(0).equals("2");
/// </para>
///
/// This decoder can also decode the content of an HTTP POST request whose
/// content type is <tt>application/x-www-form-urlencoded</tt>:
/// <para>
/// QueryStringDecoder decoder = new QueryStringDecoder("recipient=world&x=1;y=2", false);
/// ...
/// </para>
///
/// <h3>HashDOS vulnerability fix</h3>
///
/// As a workaround to the <a href="https://netty.io/s/hashdos">HashDOS</a> vulnerability, the decoder
/// limits the maximum number of decoded key-value parameter pairs, up to {@literal 1024} by
/// default, and you can configure it when you construct the decoder by passing an additional
/// integer parameter.
/// </summary>
public class QueryStringDecoder
{
private const int DefaultMaxParams = 1024;
private readonly Encoding _charset;
private readonly string _uri;
private readonly int _maxParams;
private readonly bool _semicolonIsNormalChar;
private int _pathEndIdx;
private string _path;
private IDictionary<string, List<string>> _parameters;
public QueryStringDecoder(string uri) : this(uri, HttpConstants.DefaultEncoding)
{
}
public QueryStringDecoder(string uri, bool hasPath) : this(uri, HttpConstants.DefaultEncoding, hasPath)
{
}
public QueryStringDecoder(string uri, Encoding charset) : this(uri, charset, true)
{
}
public QueryStringDecoder(string uri, Encoding charset, bool hasPath) : this(uri, charset, hasPath, DefaultMaxParams)
{
}
public QueryStringDecoder(string uri, Encoding charset, bool hasPath, int maxParams) : this(uri, charset, hasPath, maxParams, false)
{
}
public QueryStringDecoder(string uri, Encoding charset, bool hasPath, int maxParams, bool semicolonIsNormalChar)
{
if (uri is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.uri); }
if (charset is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.charset); }
if ((uint)(maxParams - 1) > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentException_Positive(maxParams, ExceptionArgument.maxParams); }
_uri = uri;
_charset = charset;
_maxParams = maxParams;
_semicolonIsNormalChar = semicolonIsNormalChar;
// -1 means that path end index will be initialized lazily
_pathEndIdx = hasPath ? -1 : 0;
}
public QueryStringDecoder(Uri uri) : this(uri, HttpConstants.DefaultEncoding)
{
}
public QueryStringDecoder(Uri uri, Encoding charset) : this(uri, charset, DefaultMaxParams)
{
}
public QueryStringDecoder(Uri uri, Encoding charset, int maxParams) : this(uri, charset, maxParams, false)
{
}
public QueryStringDecoder(Uri uri, Encoding charset, int maxParams, bool semicolonIsNormalChar)
{
if (uri is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.uri); }
if (charset is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.charset); }
if ((uint)(maxParams - 1) > SharedConstants.TooBigOrNegative) { ThrowHelper.ThrowArgumentException_Positive(maxParams, ExceptionArgument.maxParams); }
string rawPath = uri.AbsolutePath;
// Also take care of cut of things like "http://localhost"
_uri = uri.PathAndQuery;
_charset = charset;
_maxParams = maxParams;
_semicolonIsNormalChar = semicolonIsNormalChar;
_pathEndIdx = rawPath.Length;
}
public override string ToString() => _uri;
public string Path => _path ??= DecodeComponent(_uri, 0, PathEndIdx(), _charset, true);
public IDictionary<string, List<string>> Parameters => _parameters ??= DecodeParams(_uri, PathEndIdx(), _charset, _maxParams, _semicolonIsNormalChar);
public string RawPath() => _uri.Substring(0, PathEndIdx());
public string RawQuery()
{
int start = _pathEndIdx + 1;
return start < _uri.Length ? _uri.Substring(start) : StringUtil.EmptyString;
}
int PathEndIdx()
{
if (_pathEndIdx == -1)
{
_pathEndIdx = FindPathEndIndex(_uri);
}
return _pathEndIdx;
}
static IDictionary<string, List<string>> DecodeParams(string s, int from, Encoding charset, int paramsLimit, bool semicolonIsNormalChar)
{
int len = s.Length;
if ((uint)from >= (uint)len)
{
return ImmutableDictionary<string, List<string>>.Empty;
}
if (s[from] == HttpConstants.QuestionMarkChar)
{
from++;
}
var parameters = new Dictionary<string, List<string>>(StringComparer.Ordinal);
int nameStart = from;
int valueStart = -1;
int i;
//loop:
for (i = from; i < len; i++)
{
switch (s[i])
{
case HttpConstants.EqualsSignChar:
if (nameStart == i)
{
nameStart = i + 1;
}
else if (valueStart < nameStart)
{
valueStart = i + 1;
}
break;
case HttpConstants.SemicolonChar:
if (semicolonIsNormalChar)
{
continue;
}
goto case HttpConstants.AmpersandChar;
// fall-through
case HttpConstants.AmpersandChar:
if (AddParam(s, nameStart, valueStart, i, parameters, charset))
{
paramsLimit--;
if (0u >= (uint)paramsLimit)
{
return parameters;
}
}
nameStart = i + 1;
break;
case HttpConstants.NumberSignChar:
goto loop;
}
}
loop:
_ = AddParam(s, nameStart, valueStart, i, parameters, charset);
return parameters;
}
static bool AddParam(string s, int nameStart, int valueStart, int valueEnd,
Dictionary<string, List<string>> parameters, Encoding charset)
{
if (nameStart >= valueEnd)
{
return false;
}
if (valueStart <= nameStart)
{
valueStart = valueEnd + 1;
}
string name = DecodeComponent(s, nameStart, valueStart - 1, charset, false);
string value = DecodeComponent(s, valueStart, valueEnd, charset, false);
if (!parameters.TryGetValue(name, out List<string> values))
{
values = new List<string>(1); // Often there's only 1 value.
parameters.Add(name, values);
}
values.Add(value);
return true;
}
public static string DecodeComponent(string s) => DecodeComponent(s, HttpConstants.DefaultEncoding);
public static string DecodeComponent(string s, Encoding charset) => s is null
? StringUtil.EmptyString : DecodeComponent(s, 0, s.Length, charset, false);
static string DecodeComponent(string s, int from, int toExcluded, Encoding charset, bool isPath)
{
int len = toExcluded - from;
if (len <= 0)
{
return StringUtil.EmptyString;
}
int firstEscaped = -1;
for (int i = from; i < toExcluded; i++)
{
char c = s[i];
if (c == HttpConstants.PercentChar || c == HttpConstants.PlusSignChar && !isPath)
{
firstEscaped = i;
break;
}
}
if (firstEscaped == -1)
{
return s.Substring(from, len);
}
// Each encoded byte takes 3 characters (e.g. "%20")
int decodedCapacity = (toExcluded - firstEscaped) / 3;
var byteBuf = new byte[decodedCapacity];
int idx;
var strBuf = StringBuilderManager.Allocate(len);
_ = strBuf.Append(s, from, firstEscaped - from);
for (int i = firstEscaped; i < toExcluded; i++)
{
char c = s[i];
if (c != HttpConstants.PercentChar)
{
_ = strBuf.Append(c != HttpConstants.PlusSignChar || isPath ? c : StringUtil.Space);
continue;
}
idx = 0;
do
{
if (i + 3 > toExcluded)
{
StringBuilderManager.Free(strBuf); ThrowHelper.ThrowArgumentException_UnterminatedEscapeSeq(i, s);
}
byteBuf[idx++] = StringUtil.DecodeHexByte(s, i + 1);
i += 3;
}
while (i < toExcluded && s[i] == HttpConstants.PercentChar);
i--;
_ = strBuf.Append(charset.GetString(byteBuf, 0, idx));
}
return StringBuilderManager.ReturnAndFree(strBuf);
}
static int FindPathEndIndex(string uri)
{
int len = uri.Length;
for (int i = 0; i < len; i++)
{
char c = uri[i];
switch (c)
{
case HttpConstants.QuestionMarkChar:
case HttpConstants.NumberSignChar:
return i;
}
}
return len;
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Catalog.Application.Constants;
using Catalog.Application.Interfaces.Repositories;
using MediatR;
using Olcsan.Boilerplate.Aspects.Autofac.Exception;
using Olcsan.Boilerplate.Aspects.Autofac.Logger;
using Olcsan.Boilerplate.Aspects.Autofac.Validation;
using Olcsan.Boilerplate.CrossCuttingConcerns.Logging.Serilog.Loggers;
using Olcsan.Boilerplate.Utilities.Results;
namespace Catalog.Application.Features.Commands.Options.DeleteOptionCommand
{
public class DeleteOptionCommandHandler : IRequestHandler<DeleteOptionCommand, IResult>
{
private readonly IOptionRepository _optionRepository;
private readonly IOptionValueRepository _optionValueRepository;
public DeleteOptionCommandHandler(IOptionRepository optionRepository,
IOptionValueRepository optionValueRepository)
{
_optionRepository = optionRepository;
_optionValueRepository = optionValueRepository;
}
[LogAspect(typeof(FileLogger), "Catalog-Application")]
[ExceptionLogAspect(typeof(FileLogger), "Catalog-Application")]
[ValidationAspect(typeof(DeleteOptionCommandValidator))]
public async Task<IResult> Handle(DeleteOptionCommand request, CancellationToken cancellationToken)
{
var option = await _optionRepository.GetByIdAsync(request.Id);
if (option is null)
{
return new ErrorResult(Messages.DataNotFound);
}
await _optionRepository.DeleteAsync(option);
await _optionValueRepository.DeleteManyByOptionIdAsync(option.Id);
return new SuccessResult();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ButtonFunctions : MonoBehaviour {
public GameObject mainPanel;
public GameObject optionsPanel;
public GameObject classPanel;
public GameObject meleePlayer, rangedPlayer;
void Start () {
optionsPanel.SetActive(false);
classPanel.SetActive(false);
}
void Update () {
}
public void StartGame()
{
classPanel.SetActive(true);
mainPanel.SetActive(false);
}
public void OpenOptions()
{
optionsPanel.SetActive(true);
mainPanel.SetActive(false);
}
public void ExitGame()
{
}
public void BackToMain()
{
optionsPanel.SetActive(false);
classPanel.SetActive(false);
mainPanel.SetActive(true);
}
public void ChooseMelee()
{
SceneManager.LoadScene("Scene");
Scene s = SceneManager.GetSceneByName("Scene");
GameObject player = Instantiate(meleePlayer, Vector3.zero, Quaternion.identity);
// SceneManager.MoveGameObjectToScene(player, s);
// SceneManager.SetActiveScene(s);
}
public void ChooseRanged()
{
SceneManager.LoadScene("Scene");
Scene s = SceneManager.GetSceneByName("Scene");
GameObject player = Instantiate(rangedPlayer, Vector3.zero, Quaternion.identity);
// SceneManager.MoveGameObjectToScene(player, s);
// SceneManager.SetActiveScene(s);
}
}
|
// File: RosOutAppender.cs
// Project: ROS_C-Sharp
//
// ROS.NET
// Eric McCann <emccann@cs.uml.edu>
// UMass Lowell Robotics Laboratory
//
// Reimplementation of the ROS (ros.org) ros_cpp client in C#.
//
// Created: 04/28/2015
// Updated: 02/10/2016
#region USINGZ
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Messages;
using Messages.rosgraph_msgs;
using m = Messages.std_msgs;
using gm = Messages.geometry_msgs;
using nm = Messages.nav_msgs;
#endregion
namespace Ros_CSharp
{
public class RosOutAppender
{
private static object singleton_init_mutex = new object();
private static RosOutAppender _instance;
public static RosOutAppender Instance
{
get
{
if (_instance == null)
lock (singleton_init_mutex)
{
if (_instance == null)
_instance = new RosOutAppender();
}
return _instance;
}
}
internal enum
ROSOUT_LEVEL
{
DEBUG = 1,
INFO = 2,
WARN = 4,
ERROR = 8,
FATAL = 16
}
private Queue<Log> log_queue = new Queue<Log>();
private Thread publish_thread;
private bool shutting_down;
private Publisher<Log> publisher;
public RosOutAppender()
{
publish_thread = new Thread(logThread) { IsBackground = true };
}
public bool started
{
get { return publish_thread != null && (publish_thread.ThreadState == System.Threading.ThreadState.Running || publish_thread.ThreadState == System.Threading.ThreadState.Background); }
}
public void start()
{
if (!shutting_down && !started)
{
if (publisher == null)
publisher = ROS.GlobalNodeHandle.advertise<Log>("/rosout", 0);
publish_thread.Start();
}
}
public void shutdown()
{
shutting_down = true;
publish_thread.Join();
if (publisher != null)
{
publisher.shutdown();
publisher = null;
}
}
internal void Append(string m, ROSOUT_LEVEL lvl)
{
Append(m, lvl, 4);
}
private void Append(string m, ROSOUT_LEVEL lvl, int level)
{
StackFrame sf = new StackTrace(new StackFrame(level, true)).GetFrame(0);
Log logmsg = new Log
{
msg = m, name = this_node.Name, file = sf.GetFileName(), function = sf.GetMethod().Name, line = (uint) sf.GetFileLineNumber(), level = ((byte) ((int) lvl)),
header = new m.Header() { stamp = ROS.GetTime() }
};
TopicManager.Instance.getAdvertisedTopics(out logmsg.topics);
lock (log_queue)
log_queue.Enqueue(logmsg);
}
private void logThread()
{
Queue<Log> localqueue;
while (!shutting_down)
{
lock (log_queue)
{
localqueue = new Queue<Log>(log_queue);
log_queue.Clear();
}
while (!shutting_down && localqueue.Count > 0)
{
publisher.publish(localqueue.Dequeue());
}
if (shutting_down) return;
Thread.Sleep(100);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeleeWeaponBehaviour : WeaponBehaviour
{
public Animator attackAnimator;
public Transform attackPoint;
public float attackPointRadius;
public override void InflictDamage()
{
Collider[] targetColliders = Physics.OverlapSphere(attackPoint.position, attackPointRadius, TargetLayerMask);
if (targetColliders.Length > 0)
{
var targetHealthSystem = targetColliders[0].GetComponentInParent<HealthSystem>();
if (targetHealthSystem != null)
{
bool killed = targetHealthSystem.TakeDamage(damage);
if (killed)
{
KillScored.Invoke();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace cmpctircd {
public class Stdout : BaseLogger {
public Stdout(IRCd ircd, LogType type) : base(ircd, type) {}
override public void Create(IReadOnlyDictionary<string, string> arguments) {}
override public void Close() {}
override public void WriteLine(string msg, LogType type, bool prepared = true) {
if(!prepared) msg = Prepare(msg, type);
Console.Out.WriteLine(msg);
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public enum ScoreType
{
Goblin,
Bomb,
DestroyedObject
}
public class Score : Singleton<Score>
{
int goblinScore = 0;
int bombScore = 0;
int destroyedObjectScore = 0;
public int FinalScore { get => GetFinalScore(); }
public int TimeScore { get => (int)(Time.timeSinceLevelLoad/10f)*10; }
public int GoblinScore { get => goblinScore; }
public int BombScore { get => bombScore; }
public int DestroyedObjectScore { get => destroyedObjectScore; }
private int GetFinalScore()
{
return Mathf.Max(0, TimeScore + goblinScore + bombScore + destroyedObjectScore);
}
public void Add(int amount, ScoreType type)
{
switch (type)
{
case ScoreType.Goblin:
goblinScore += amount;
break;
case ScoreType.Bomb:
bombScore += amount;
break;
case ScoreType.DestroyedObject:
destroyedObjectScore += amount;
break;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using DAL.EF;
using DAL.Tests.Helpers;
using Xunit;
namespace DAL.Tests.DeleteTests
{
[Collection(Constants.CollectionName)]
public class DeleteDataTests : BaseTest
{
public DeleteDataTests()
{
AddRecords.AddCategory(Db, "Foo");
AddRecords.AddProduct(Db, 2, 100, "New Product", "Name", "Number", 90, 5);
AddRecords.AddProduct(Db, 2, 20, "New Product2", "Name2", "Number2", 10, 15);
}
[Fact]
public void ShouldDeleteCategory()
{
var catCount = Db.Categories.Count();
var prodCount = Db.Products.Count();
var cat = Db.Categories.First();
Db.Categories.Remove(cat);
Db.SaveChanges();
Assert.Equal(catCount-1,Db.Categories.Count());
Assert.Equal(prodCount-2,Db.Products.Count());
}
[Fact]
public void ShouldDeleteWithEntityState()
{
var catCount = Db.Categories.Count();
var prodCount = Db.Products.Count();
var cat = Db.Categories.First();
var catProdCount = cat.Products.ToList().Count;
cat.Products.ToList().ForEach(p=>
Db.Entry(p).State = EntityState.Deleted
);
Db.Entry(cat).State = EntityState.Deleted;
Db.SaveChanges();
Assert.Equal(catCount - 1, Db.Categories.Count());
Assert.Equal(prodCount - 2, Db.Products.Count());
}
[Fact]
public void ShouldDeleteCategoryById()
{
var catCount = Db.Categories.Count();
var prodCount = Db.Products.Count();
var cat = Db.Categories.First();
var newDb = new IntroToEfContext();
var catToDelete = new Category {Id=cat.Id, TimeStamp = cat.TimeStamp};
newDb.Entry(catToDelete).State = EntityState.Deleted;
newDb.SaveChanges();
Assert.Equal(catCount - 1, Db.Categories.Count());
Assert.Equal(prodCount - 2, Db.Products.Count());
}
}
}
|
using LibHac;
using LibHac.Fs;
using LibHac.FsSystem;
using LibHac.FsSystem.NcaUtils;
using Ryujinx.Common.Logging;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.HOS.Services.Time.Clock;
using Ryujinx.HLE.Utilities;
using System.Collections.Generic;
using System.IO;
using static Ryujinx.HLE.HOS.Services.Time.TimeZone.TimeZoneRule;
namespace Ryujinx.HLE.HOS.Services.Time.TimeZone
{
class TimeZoneContentManager
{
private const long TimeZoneBinaryTitleId = 0x010000000000080E;
private Switch _device;
private string[] _locationNameCache;
public TimeZoneManager Manager { get; private set; }
public TimeZoneContentManager()
{
Manager = new TimeZoneManager();
}
internal void Initialize(TimeManager timeManager, Switch device)
{
_device = device;
InitializeLocationNameCache();
SteadyClockTimePoint timeZoneUpdatedTimePoint = timeManager.StandardSteadyClock.GetCurrentTimePoint(null);
ResultCode result = GetTimeZoneBinary("UTC", out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
if (result == ResultCode.Success)
{
// TODO: Read TimeZoneVersion from sysarchive.
timeManager.SetupTimeZoneManager("UTC", timeZoneUpdatedTimePoint, (uint)_locationNameCache.Length, new UInt128(), timeZoneBinaryStream);
ncaFile.Dispose();
}
else
{
// In the case the user don't have the timezone system archive, we just mark the manager as initialized.
Manager.MarkInitialized();
}
}
private void InitializeLocationNameCache()
{
if (HasTimeZoneBinaryTitle())
{
using (IStorage ncaFileStream = new LocalStorage(_device.FileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open))
{
Nca nca = new Nca(_device.System.KeySet, ncaFileStream);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
romfs.OpenFile(out IFile binaryListFile, "/binaryList.txt", OpenMode.Read).ThrowIfFailure();
StreamReader reader = new StreamReader(binaryListFile.AsStream());
List<string> locationNameList = new List<string>();
string locationName;
while ((locationName = reader.ReadLine()) != null)
{
locationNameList.Add(locationName);
}
_locationNameCache = locationNameList.ToArray();
}
}
else
{
_locationNameCache = new string[0];
Logger.PrintWarning(LogClass.ServiceTime, "TimeZoneBinary system title not found! TimeZone conversions will not work, provide the system archive to fix this warning. (See https://github.com/Ryujinx/Ryujinx#requirements for more informations)");
}
}
private bool IsLocationNameValid(string locationName)
{
foreach (string cachedLocationName in _locationNameCache)
{
if (cachedLocationName.Equals(locationName))
{
return true;
}
}
return false;
}
public ResultCode SetDeviceLocationName(string locationName)
{
ResultCode result = GetTimeZoneBinary(locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
if (result == ResultCode.Success)
{
result = Manager.SetDeviceLocationNameWithTimeZoneRule(locationName, timeZoneBinaryStream);
ncaFile.Dispose();
}
return result;
}
public ResultCode LoadLocationNameList(uint index, out string[] outLocationNameArray, uint maxLength)
{
List<string> locationNameList = new List<string>();
for (int i = 0; i < _locationNameCache.Length && i < maxLength; i++)
{
if (i < index)
{
continue;
}
string locationName = _locationNameCache[i];
// If the location name is too long, error out.
if (locationName.Length > 0x24)
{
outLocationNameArray = new string[0];
return ResultCode.LocationNameTooLong;
}
locationNameList.Add(locationName);
}
outLocationNameArray = locationNameList.ToArray();
return ResultCode.Success;
}
public string GetTimeZoneBinaryTitleContentPath()
{
return _device.System.ContentManager.GetInstalledContentPath(TimeZoneBinaryTitleId, StorageId.NandSystem, NcaContentType.Data);
}
public bool HasTimeZoneBinaryTitle()
{
return !string.IsNullOrEmpty(GetTimeZoneBinaryTitleContentPath());
}
internal ResultCode GetTimeZoneBinary(string locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile)
{
timeZoneBinaryStream = null;
ncaFile = null;
if (!IsLocationNameValid(locationName))
{
return ResultCode.TimeZoneNotFound;
}
ncaFile = new LocalStorage(_device.FileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open);
Nca nca = new Nca(_device.System.KeySet, ncaFile);
IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);
Result result = romfs.OpenFile(out IFile timeZoneBinaryFile, $"/zoneinfo/{locationName}", OpenMode.Read);
timeZoneBinaryStream = timeZoneBinaryFile.AsStream();
return (ResultCode)result.Value;
}
internal ResultCode LoadTimeZoneRule(out TimeZoneRule outRules, string locationName)
{
outRules = new TimeZoneRule
{
Ats = new long[TzMaxTimes],
Types = new byte[TzMaxTimes],
Ttis = new TimeTypeInfo[TzMaxTypes],
Chars = new char[TzCharsArraySize]
};
if (!HasTimeZoneBinaryTitle())
{
throw new InvalidSystemResourceException($"TimeZoneBinary system title not found! Please provide it. (See https://github.com/Ryujinx/Ryujinx#requirements for more informations)");
}
ResultCode result = GetTimeZoneBinary(locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile);
if (result == ResultCode.Success)
{
result = Manager.ParseTimeZoneRuleBinary(out outRules, timeZoneBinaryStream);
ncaFile.Dispose();
}
return result;
}
}
} |
using System;
using System.Threading.Tasks;
namespace VeDirectCommunication
{
public interface IVictronStream : IDisposable
{
Task Write(byte[] bytes);
Task<bool> DataAvailable();
Task<byte[]> ReadAvailable();
}
}
|
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
namespace QuandlNet.Models
{
public class DataTable
{
[JsonProperty("data")]
public List<IList> Data { get; set; }
[JsonProperty("columns")]
public List<DataTableColumn> Columns { get; set; }
}
} |
using System.Collections.Generic;
using Edelstein.Database.Store;
namespace Edelstein.Service.Social.Entities
{
public class GuildRecord : IDataEntity
{
public int ID { get; set; }
public string Name { get; set; }
public List<string> GradeName { get; set; } // TODO: array?
public int MaxMemberNum { get; set; }
public byte MarkBg { get; set; }
public byte Mark { get; set; }
public byte MarkColor { get; set; }
public string Notice { get; set; }
public int Point { get; set; }
public int Level { get; set; }
// TODO: alliance
// TODO: skill record
}
} |
using UnityEngine;
public class PlatformSpawner : MonoBehaviour
{
public GameObject platform;
public GameObject diamond;
public GameObject clouds;
public Vector3 lastPos;
private float size;
// Start is called before the first frame update
private void Start()
{
lastPos = platform.transform.position;
size = platform.transform.localScale.x;
for (int i = 1; i < 20; i++)
{
SpawnPlatform();
}
}
public void StartSpawningPlatforms()
{
InvokeRepeating("SpawnPlatform", 1f, 0.2f);
}
private void Update()
{
if (JasperMovement.gameOverIs == true)
{
CancelInvoke("SpawnPlatform");
}
}
public void SpawnPlatform()
{
int rand = Random.Range(0, 6);
if (rand < 3)
{
SpawnX();
}
else if (rand >= 3)
{
SpawnZ();
}
}
public void SpawnX()
{
Vector3 pos = lastPos;
pos.x += size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
if (Random.Range(0, 6) == 1)
{
Instantiate(diamond, new Vector3(pos.x, pos.y + 1.2f, pos.z), diamond.transform.rotation);
}
if (Random.Range(0, 10) == 2)
{
Instantiate(clouds, new Vector3(pos.x, pos.y + 10, pos.z), Quaternion.identity);
}
}
public void SpawnZ()
{
Vector3 pos = lastPos;
pos.z += size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
if (Random.Range(0, 6) == 1)
{
Instantiate(diamond, new Vector3(pos.x, pos.y + 1.2f, pos.z), diamond.transform.rotation);
}
if (Random.Range(0, 10) == 2)
{
Instantiate(clouds, new Vector3(pos.x, pos.y - 10, pos.z - 20), Quaternion.identity);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpGL;
namespace Normal
{
public partial class NormalNode
{
private const string vertexShader = @"#version 150 core
in vec3 inPosition;
in vec3 inNormal;
uniform mat4 projectionMat;
uniform mat4 viewMat;
uniform mat4 modelMat;
uniform mat4 normalMatrix;
out vec3 passPosition; // position in eye space.
out vec3 passNormal; // normal in eye space.
void main(void)
{
gl_Position = projectionMat * viewMat * modelMat * vec4(inPosition, 1.0f);
passPosition = (viewMat * modelMat * vec4(inPosition, 1.0f)).xyz;
passNormal = (normalMatrix * vec4(inNormal, 0)).xyz;
}
";
private const string fragmentShader = @"#version 150 core
uniform vec3 ambientColor = vec3(0.2, 0.2, 0.2);
uniform vec3 diffuseColor = vec3(1, 0.8431, 0);
const vec3 lightPosition = vec3(0, 0, 0); // flash light's position in eye space.
in vec3 passPosition;
in vec3 passNormal;
out vec4 outColor;
void main(void)
{
vec3 L = normalize(lightPosition - passPosition);
float diffuse = max(0, dot(L, normalize(passNormal)));
outColor = vec4(ambientColor + diffuse * diffuseColor, 1);
}
";
}
}
|
using System.Collections.Generic;
using ByteNuts.NetCoreControls.Core.Models;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace ByteNuts.NetCoreControls.Models.Grid
{
public class NccGridTagContext : NccTagContext
{
public int RowNumber { get; set; }
public int ColCount { get; set; }
public bool ColCountComplete { get; set; }
public GridRow GridHeader { get; set; } = new GridRow();
public List<GridRow> GridRows { get; set; } = new List<GridRow>();
public GridRow EmptyRow { get; set; }
public string PreContent { get; set; }
public string PostContent { get; set; }
public TagHelperContent HeaderContent { get; set; } = new DefaultTagHelperContent();
public TagHelperContent BodyContent { get; set; } = new DefaultTagHelperContent();
public TagHelperContent FooterContent { get; set; } = new DefaultTagHelperContent();
public TagHelperContent PagerContent { get; set; } = new DefaultTagHelperContent();
public string CssClassGrid { get; set; }
public string CssClassBody { get; set; }
public string CssClassHeader { get; set; }
public string CssClassFooter { get; set; }
public string CssClassHeaderContainer { get; set; }
public string CssClassTableContainer { get; set; }
public string CssClassFooterContainer { get; set; } = "row";
//Grid Pager
public string PagerRecordsCountContent { get; set; }
public string CssClassRecordCountDiv { get; set; }
public string CssClassPagerDiv { get; set; } = "nccGridPagerContainer";
public string CssClassPagerUl { get; set; } = "nccGridPagerPagination";
public string CssClassPagerLi { get; set; }
public string CssClassPagerA { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using System;
namespace UnityEngine.UI.Windows.Components {
public static class ParameterFlag {
public const long None = 0x0;
public const long P1 = 0x00001;
public const long P2 = 0x00002;
public const long P3 = 0x00004;
public const long P4 = 0x00008;
public const long P5 = 0x00010;
public const long P6 = 0x00020;
public const long P7 = 0x00040;
public const long P8 = 0x00080;
public const long P9 = 0x00100;
public const long P10 = 0x00200;
public const long P11 = 0x00400;
public const long P12 = 0x00800;
public const long P13 = 0x01000;
public const long P14 = 0x02000;
public const long P15 = 0x04000;
public const long P16 = 0x08000;
public const long P17 = 0x10000;
public const long P18 = 0x20000;
public const long P19 = 0x40000;
public const long P20 = 0x80000;
public const long AP1 = 0x100000;
public const long AP2 = 0x200000;
public const long AP3 = 0x400000;
public const long AP4 = 0x800000;
public const long AP5 = 0x1000000;
public const long AP6 = 0x2000000;
public const long AP7 = 0x4000000;
public const long AP8 = 0x8000000;
public const long AP9 = 0x10000000;
public const long AP10 = 0x20000000;
public const long AP11 = 0x40000000;
public const long AP12 = 0x80000000;
public const long AP13 = 0x100000000;
public const long AP14 = 0x200000000;
public const long AP15 = 0x400000000;
public const long AP16 = 0x800000000;
public const long AP17 = 0x1000000000;
public const long AP18 = 0x2000000000;
public const long AP19 = 0x4000000000;
public const long AP20 = 0x8000000000;
public const long BP1 = 0x10000000000;
public const long BP2 = 0x20000000000;
public const long BP3 = 0x40000000000;
public const long BP4 = 0x80000000000;
public const long BP5 = 0x100000000000;
public const long BP6 = 0x200000000000;
public const long BP7 = 0x400000000000;
public const long BP8 = 0x800000000000;
public const long BP9 = 0x1000000000000;
public const long BP10 = 0x2000000000000;
public const long BP11 = 0x4000000000000;
public const long BP12 = 0x8000000000000;
public const long BP13 = 0x10000000000000;
public const long BP14 = 0x20000000000000;
public const long BP15 = 0x40000000000000;
public const long BP16 = 0x80000000000000;
public const long BP17 = 0x100000000000000;
public const long BP18 = 0x200000000000000;
public const long BP19 = 0x400000000000000;
public const long BP20 = 0x800000000000000;
};
public interface IParametersEditor {
void OnParametersGUI(Rect rect);
float GetHeight();
}
public class ParamFlagAttribute : PropertyAttribute {
public long flag;
public ParamFlagAttribute(long flag) {
this.flag = flag;
}
}
public interface IComponentParameters {
};
public class WindowComponentParametersBase : MonoBehaviour, IComponentParameters/*, ISerializationCallbackReceiver*/ {
//[HideInInspector]
//[System.NonSerialized]
private long flags {
get {
return this.OnAfterDeserialize();
}
set {
this.OnBeforeSerialize(value);
}
}
//[HideInInspector]
[SerializeField]
private int flags1;
//[HideInInspector]
[SerializeField]
private int flags2;
public void Setup(WindowComponent component) {
// If there was no implementation
}
public long GetFlags() {
return this.flags;
}
public bool IsChanged(long value) {
return (this.flags & value) != 0;
}
public void SetChanged(long flag, bool state) {
if (state == true) {
this.flags |= flag;
} else {
//this.flags &= ~(flag);
this.flags ^= flag;
}
}
public long OnAfterDeserialize() {
/*
if (this.flags1 == 0 && this.flags2 == 0) {
this.OnBeforeSerialize();
}*/
long flags = this.flags2;
flags = flags << 32;
flags = flags | (uint)this.flags1;
return flags;
}
public void OnBeforeSerialize(long flags) {
this.flags1 = (int)(flags & uint.MaxValue);
this.flags2 = (int)(flags >> 32);
}
}
} |
using System;
namespace Xamarin.Android.Prepare
{
partial class MakeRunner
{
static string executableName = String.Empty;
protected override string DefaultToolExecutableName => EnsureExecutableName ();
static string EnsureExecutableName ()
{
if (!String.IsNullOrEmpty (executableName))
return executableName;
// gmake is preferred since it comes from HomeBrew and is a much newer version than the one provided by
// Apple with Xcode. The reason we care is the `--output-sync` option which allows to generate sane output
// when running with `-j`. The option is supported since Make v4, however Apple provide version 3 while
// HomeBrew has v4 installed as `gmake`
string gmake = Context.Instance.OS.Which ("gmake", false);
if (!String.IsNullOrEmpty (gmake)) {
Log.Instance.DebugLine ($"Found gmake at {gmake}, using it instead of the Apple provided make");
executableName = "gmake";
} else
executableName = "make";
return executableName;
}
}
}
|
using System.Linq;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.Metadata.Reader.API;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl;
using JetBrains.ReSharper.Psi.Resolve;
using IType = JetBrains.ReSharper.Psi.IType;
using ITypeParameter = JetBrains.ReSharper.Psi.ITypeParameter;
namespace AsyncConverter.Helpers
{
public static class TypeHelper
{
[Pure]
[ContractAnnotation("type:null => false; otherType:null => false")]
public static bool IsTaskOf([CanBeNull] this IType type, [CanBeNull] IType otherType)
{
if (type.IsTask() && otherType.IsVoid())
return true;
return type.IsGenericTaskOf(otherType);
}
[Pure]
[ContractAnnotation("type:null => false; otherType:null => false")]
public static bool IsGenericTaskOf([CanBeNull] this IType type, [CanBeNull] IType otherType)
{
if (type == null || otherType == null)
return false;
if (!type.IsGenericTask())
return false;
var meaningType = type.GetFirstGenericType();
return meaningType != null && meaningType.IsEquals(otherType);
}
[Pure]
[CanBeNull]
[ContractAnnotation("null => null")]
public static IType GetFirstGenericType(this IType type)
{
var taskDeclaredType = type as IDeclaredType;
if (taskDeclaredType == null)
return null;
var substitution = taskDeclaredType.GetSubstitution();
if (substitution.IsEmpty())
return null;
return substitution.Apply(substitution.Domain[0]);
}
[Pure]
[ContractAnnotation("null => false")]
public static bool IsFunc([CanBeNull]this IType type)
{
var declaredType = type as IDeclaredType;
if (declaredType == null)
return false;
var clrTypeName = declaredType.GetClrName();
return clrTypeName.Equals(PredefinedType.FUNC_FQN) || clrTypeName.FullName.StartsWith(PredefinedType.FUNC_FQN + "`");
}
[Pure]
[ContractAnnotation("null => false")]
public static bool IsGenericIQueryable([CanBeNull]this IType type)
{
var declaredType = type as IDeclaredType;
return declaredType != null && IsPredefinedTypeElement(declaredType.GetTypeElement(), PredefinedType.GENERIC_IQUERYABLE_FQN);
}
[Pure]
[ContractAnnotation("typeElement:null => false")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsPredefinedTypeElement([CanBeNull] ITypeElement typeElement, [NotNull] IClrTypeName clrName)
{
if (typeElement == null)
return false;
var typeElement1 = typeElement.Module.GetPredefinedType().TryGetType(clrName, NullableAnnotation.Unknown).NotNull("NOT PREDEFINED").GetTypeElement();
return DeclaredElementEqualityComparer.TypeElementComparer.Equals(typeElement, typeElement1);
}
[Pure]
[ContractAnnotation("null => false")]
public static bool IsEnumerableClass([CanBeNull]this ITypeElement type)
{
if (type == null)
return false;
var typeName = type.GetClrName();
return typeName.Equals(PredefinedType.ENUMERABLE_CLASS);
}
public static bool IsEquals([NotNull]this IType type, [NotNull] IType otherType)
{
if (!type.IsOpenType && !otherType.IsOpenType)
return Equals(type, otherType);
if (!IsEqualTypeGroup(type, otherType))
return false;
var scalarType = type.GetScalarType();
var otherScalarType = otherType.GetScalarType();
if (scalarType == null || otherScalarType == null)
return false;
if (scalarType.Classify != otherScalarType.Classify)
return false;
var typeElement1 = scalarType.GetTypeElement();
var typeElement2 = otherScalarType.GetTypeElement();
if (typeElement1 == null || typeElement2 == null)
return false;
var typeParameter1 = typeElement1 as ITypeParameter;
var typeParameter2 = typeElement2 as ITypeParameter;
if (typeParameter1 != null && typeParameter2 != null)
{
if(typeParameter1.HasDefaultConstructor != typeParameter2.HasDefaultConstructor
|| typeParameter1.TypeConstraints.Count != typeParameter2.TypeConstraints.Count)
return false;
if (typeParameter1.TypeConstraints.Where((t, i) => !t.IsEquals(typeParameter2.TypeConstraints[i])).Any())
{
return false;
}
}
return EqualSubstitutions(typeElement1, scalarType.GetSubstitution(), typeElement2, otherScalarType.GetSubstitution());
}
public static bool IsAsyncDelegate([NotNull] this IType type, [NotNull] IType otherType)
{
if (type.IsAction() && otherType.IsFunc())
{
var parameterDeclaredType = otherType as IDeclaredType;
var substitution = parameterDeclaredType?.GetSubstitution();
if (substitution?.Domain.Count != 1)
return false;
var valuableType = substitution.Apply(substitution.Domain[0]);
return valuableType.IsTask();
}
if (type.IsFunc() && otherType.IsFunc())
{
var parameterDeclaredType = otherType as IDeclaredType;
var originalParameterDeclaredType = type as IDeclaredType;
var substitution = parameterDeclaredType?.GetSubstitution();
var originalSubstitution = originalParameterDeclaredType?.GetSubstitution();
if (substitution == null || substitution.Domain.Count != originalSubstitution?.Domain.Count)
return false;
var i = 0;
for (; i < substitution.Domain.Count - 1; i++)
{
var genericType = substitution.Apply(substitution.Domain[i]);
var originalGenericType = originalSubstitution.Apply(originalSubstitution.Domain[i]);
if (!genericType.Equals(originalGenericType))
return false;
}
var returnType = substitution.Apply(substitution.Domain[i]);
var originalReturnType = originalSubstitution.Apply(originalSubstitution.Domain[i]);
return returnType.IsGenericTaskOf(originalReturnType);
}
return false;
}
private static bool IsEqualTypeGroup([NotNull] IType sourceType, [NotNull] IType targetType)
{
if (sourceType.IsOpenType != targetType.IsOpenType)
return false;
if (sourceType is IDeclaredType && targetType is IDeclaredType || sourceType is IArrayType && targetType is IArrayType)
return true;
if (sourceType is IPointerType && targetType is IPointerType)
return true;
return false;
}
private static bool EqualSubstitutions([NotNull] ITypeElement referenceOwner, [NotNull] ISubstitution referenceSubstitution, [NotNull] ITypeElement originOwner, [NotNull] ISubstitution originSubstitution)
{
foreach (var substitution1 in referenceOwner.GetAncestorSubstitution(originOwner))
{
var substitution2 = substitution1.Apply(referenceSubstitution);
foreach (var typeParameter in substitution2.Domain)
{
if (originSubstitution.HasInDomain(typeParameter) && !substitution2[typeParameter].IsEquals(originSubstitution[typeParameter]))
return false;
}
}
return true;
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Magia.Domain.Core.Notification
{
public class DomainNotificationHandler : IDomainNotificationHandler
{
private readonly List<DomainNotification> _notifications;
public DomainNotificationHandler()
{
_notifications = new List<DomainNotification>();
}
public void Add(string value)
{
Add(string.Empty, value);
}
public void Add(string key, string value)
{
_notifications.Add(new DomainNotification(key, value));
}
public void Dispose()
{
_notifications.Clear();
}
public IEnumerable<DomainNotification> GetNotifications()
{
return GetNotifications(false);
}
public IEnumerable<DomainNotification> GetNotifications(bool distintas)
{
if (distintas)
return _notifications
.GroupBy(x => new { x.Key, x.Value, x.Versao })
.Select(x => x.First());
return _notifications;
}
public bool HasNotifications => _notifications.Any();
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyWord.Service;
using MyWord.ServiceImpl;
namespace MyWord.Service.Test
{
/// <summary>
/// HashKeywordFilter 测试.
/// </summary>
[TestClass]
public class HashKeywordFilterTest : DefaultKeywordsFilterTest
{
public override IKeywordsFilter GetKeywordsFilter()
{
return new HashKeywordFilter();
}
}
}
|
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using Microsoft.Python.Analysis.Analyzer.Evaluation;
using Microsoft.Python.Analysis.Analyzer.Handlers;
using Microsoft.Python.Analysis.Analyzer.Symbols;
using Microsoft.Python.Analysis.Types;
using Microsoft.Python.Parsing.Ast;
namespace Microsoft.Python.Analysis.Analyzer {
/// <summary>
/// Base class with common functionality to module and function analysis walkers.
/// </summary>
internal abstract class AnalysisWalker : PythonWalker {
protected ImportHandler ImportHandler { get; }
protected LoopHandler LoopHandler { get; }
protected ConditionalHandler ConditionalHandler { get; }
protected AssignmentHandler AssignmentHandler { get; }
protected WithHandler WithHandler { get; }
protected TryExceptHandler TryExceptHandler { get; }
protected NonLocalHandler NonLocalHandler { get; }
public ExpressionEval Eval { get; }
public IPythonModule Module => Eval.Module;
public PythonAst Ast => Eval.Ast;
protected ModuleSymbolTable SymbolTable => Eval.SymbolTable;
protected AnalysisWalker(ExpressionEval eval, IImportedVariableHandler importedVariableHandler) {
Eval = eval;
ImportHandler = new ImportHandler(this, importedVariableHandler);
AssignmentHandler = new AssignmentHandler(this);
LoopHandler = new LoopHandler(this);
ConditionalHandler = new ConditionalHandler(this);
WithHandler = new WithHandler(this);
TryExceptHandler = new TryExceptHandler(this);
NonLocalHandler = new NonLocalHandler(this);
}
#region AST walker overrides
public override bool Walk(AssignmentStatement node) {
AssignmentHandler.HandleAssignment(node);
return base.Walk(node);
}
public override bool Walk(NamedExpression node) {
AssignmentHandler.HandleNamedExpression(node);
return base.Walk(node);
}
public override bool Walk(ExpressionStatement node) {
switch (node.Expression) {
case ExpressionWithAnnotation ea:
AssignmentHandler.HandleAnnotatedExpression(ea, null);
return false;
case Comprehension comp:
Eval.ProcessComprehension(comp);
return false;
case CallExpression callex:
Eval.ProcessCallForReferences(callex);
return true;
default:
return base.Walk(node);
}
}
public override bool Walk(ForStatement node) => LoopHandler.HandleFor(node);
public override bool Walk(FromImportStatement node) => ImportHandler.HandleFromImport(node);
public override bool Walk(GlobalStatement node) => NonLocalHandler.HandleGlobal(node);
public override bool Walk(IfStatement node) => ConditionalHandler.HandleIf(node);
public override bool Walk(ImportStatement node) => ImportHandler.HandleImport(node);
public override bool Walk(NonlocalStatement node) => NonLocalHandler.HandleNonLocal(node);
public override bool Walk(TryStatement node) => TryExceptHandler.HandleTryExcept(node);
public override bool Walk(WhileStatement node) => LoopHandler.HandleWhile(node);
public override bool Walk(WithStatement node) {
WithHandler.HandleWith(node); // HandleWith does not walk the body.
return base.Walk(node);
}
#endregion
protected T[] GetStatements<T>(ScopeStatement s)
=> (s.Body as SuiteStatement)?.Statements.OfType<T>().ToArray() ?? Array.Empty<T>();
}
}
|
using Level.ScriptsMenu.Interface;
using ScriptsLevels.Level;
namespace ScriptsMenu.Modifiers.LevelsModifier.Modifiers
{
public class InstallerRemovalModifier : IModifier
{
private readonly LevelSettings _levelSettings;
public InstallerRemovalModifier(LevelSettings levelSettings)
{
_levelSettings = levelSettings;
}
public void Activate()
{
foreach (var placeInstallationTower in _levelSettings.DestructionSiteInstallationTower)
{
placeInstallationTower.gameObject.SetActive(false);
}
}
}
} |
using System;
using Machine.Fakes.Sdk;
using Rhino.Mocks;
using Rhino.Mocks.Interfaces;
namespace Machine.Fakes.Adapters.Rhinomocks
{
class RhinoQueryOptions<TReturnValue> : IQueryOptions<TReturnValue>
{
private readonly IMethodOptions<TReturnValue> _methodOptions;
public RhinoQueryOptions(IMethodOptions<TReturnValue> methodOptions)
{
Guard.AgainstArgumentNull(methodOptions, "methodOptions");
_methodOptions = methodOptions;
}
public void Return(TReturnValue returnValue)
{
_methodOptions.Return(returnValue);
}
public void Return(Func<TReturnValue> valueFunction)
{
RepeatAny(invocation => { invocation.ReturnValue = valueFunction(); });
}
public void Return<T>(Func<T, TReturnValue> valueFunction)
{
RepeatAny(invocation => { invocation.ReturnValue = valueFunction((T)invocation.Arguments[0]); });
}
public void Return<T1, T2>(Func<T1, T2, TReturnValue> valueFunction)
{
RepeatAny(invocation =>
{
invocation.ReturnValue = valueFunction(
(T1)invocation.Arguments[0],
(T2)invocation.Arguments[1]);
});
}
public void Return<T1, T2, T3>(Func<T1, T2, T3, TReturnValue> valueFunction)
{
RepeatAny(invocation =>
{
invocation.ReturnValue = valueFunction(
(T1)invocation.Arguments[0],
(T2)invocation.Arguments[1],
(T3)invocation.Arguments[2]);
});
}
public void Return<T1, T2, T3, T4>(Func<T1, T2, T3, T4, TReturnValue> valueFunction)
{
RepeatAny(invocation =>
{
invocation.ReturnValue = valueFunction(
(T1)invocation.Arguments[0],
(T2)invocation.Arguments[1],
(T3)invocation.Arguments[2],
(T4)invocation.Arguments[3]);
});
}
public void Throw(Exception exception)
{
_methodOptions.Throw(exception);
}
private void RepeatAny(Action<MethodInvocation> invocationConfig)
{
_methodOptions.WhenCalled(invocationConfig).Return(default(TReturnValue)).Repeat.Any();
}
}
} |
using System;
using ScriptableEvents.Core.EventsDefenitions.Implemented;
using UnityEngine;
using UnityEngine.Events;
namespace ScriptableEvents.Core.Listener.Implemented
{
public class SignalListener : MonoBehaviour
{
[SerializeField] private Signal signal;
[SerializeField] private UnityEvent inspectorEvent;
public event Action EventReceived;
private void OnEnable()
{
if (signal == null)
{
Debug.LogError("Singal is not assigned");
return;
}
signal.RaisedSingal += OnSignalInvoked;
}
private void OnDisable()
{
if (signal == null)
return;
signal.RaisedSingal -= OnSignalInvoked;
}
private void OnSignalInvoked()
{
EventReceived?.Invoke();
inspectorEvent.Invoke();
}
}
} |
using System.Collections.Generic;
using Microsoft.DotNet.XHarness.iOS.Shared;
using Microsoft.DotNet.XHarness.iOS.Shared.Hardware;
namespace Xharness.Jenkins.TestTasks {
public interface IRunXITask<TDevice> : IRunTestTask where TDevice : class, IDevice {
AppRunner Runner { get; set; }
AppRunner AdditionalRunner { get; set; }
TestTarget AppRunnerTarget { get; set; }
IEnumerable<TDevice> Candidates { get; }
TDevice Device { get; set; }
TDevice CompanionDevice { get; set; }
}
}
|
@using Abp.Web.Mvc.Extensions
@{
Layout = null;
}
<ul id="userNotifications" class="notification-body">
<li>
<span>
<a href="@Url.Action("MyProfile", "Users")">See all</a>
</span>
</li>
</ul>
@Html.IncludeScript("~/Areas/SysAdmin/Views/Layout/GetNotifications.js") |
using MusicStoreWcfRestContract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MusicStoreBIL.Services
{
/// <summary>
/// Token存储与查询服务
/// </summary>
public interface ITokenStoreService
{
bool SaveUserName_OAuthEntity(string userName, OAuthEntity oauthEntity);
bool SaveAccessToken(string accessToken, OAuthEntity oauthEntity);
bool SaveRefreshToken(string refeshToken, OAuthEntity oauthEntity);
bool ReomveUserName_OAuthEntity(string userName);
bool ReomveAccessToken(string accessToken);
bool RemoveRefreshToken(string refeshToken);
OAuthEntity FindOAuthEntityByUsername(string userName);
OAuthEntity FindOAuthEntityByAccessToken(string accessToken);
OAuthEntity FindOAuthEntityByRefeshToken(string refeshToken);
}
}
|
using Spfx.Utilities;
using Spfx.Utilities.Threading;
using System;
using System.IO;
using System.Threading.Tasks;
namespace Spfx.Io
{
internal abstract class BaseLengthPrefixedStreamReader : Disposable, ILengthPrefixedStreamReader
{
protected Stream Stream { get; }
protected int MaximumFrameSize { get; }
private readonly AsyncQueue<StreamOrCode> m_readQueue;
private readonly Task m_readLoop;
protected byte[] SizeBuffer { get; } = new byte[4];
public BaseLengthPrefixedStreamReader(Stream stream, int maximumFrameSize = int.MaxValue)
{
Guard.ArgumentNotNull(stream, nameof(stream));
Stream = stream;
MaximumFrameSize = maximumFrameSize;
m_readQueue = new AsyncQueue<StreamOrCode>
{
DisposeIgnoredItems = true
};
m_readLoop = Task.Run(ReadLoop);
}
protected override void OnDispose()
{
m_readLoop.FireAndForget();
Stream.Dispose();
m_readQueue.Dispose();
}
public ValueTask<StreamOrCode> GetNextFrame()
{
return m_readQueue.DequeueAsync();
}
private async Task ReadLoop()
{
try
{
await InitializeAsync().ConfigureAwait(false);
while (true)
{
var frame = await ReceiveNextFrame().ConfigureAwait(false);
if (frame.IsEof)
{
m_readQueue.CompleteAdding().FireAndForget();
}
else
{
m_readQueue.Enqueue(frame);
}
}
}
catch (Exception ex)
{
m_readQueue.Dispose(ex);
}
}
protected virtual Task InitializeAsync()
{
return Task.CompletedTask;
}
internal abstract ValueTask<StreamOrCode> ReceiveNextFrame();
}
}
|
namespace CoreSharp.Cqrs.Grpc.Mapping
{
public interface IPropertyMapValidator
{
bool MapProperty(object obj, string propName);
}
}
|
///This is some uncompleted codes, will finish it in the future if it's necessary
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;
using System;
using LWUtilities;
/// <summary>
/// Prefab that will stored on disk and wont automatically loaded to memory.
/// Assign object under resource folder to it and manipulate it as a normal prefab object.
/// </summary>
/// <typeparam name="T">What kind of prefab</typeparam>
//[System.Serializable]
public class GenericDiskPrefab<T> where T : UnityEngine.Object
{
/// <summary>
/// Where the Target prefab is stored, will be automatically generated when assign obj in inspector
/// </summary>
[SerializeField]
private string Path = null;
/// <summary>
/// Get the path of this prefab under resource folder
/// </summary>
public string GetPath { get { return Path; } }
/// <summary>
/// The instance of this prefab
/// </summary>
public T instance
{
get
{
return Resources.Load(Path,typeof(T)) as T;
}
}
}
#if UNITY_EDITOR
public class GenericDiskPrefabDrawer<T> : PropertyDrawer
{
public UnityEngine.Object obj = null;
//public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
//{
// return base.GetPropertyHeight(property, label) + 3f;
//}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
//position.height = 18f;
//Load obj instance to inspector
SerializedProperty _PathStr = property.FindPropertyRelative("Path");
if (_PathStr.stringValue != null)
{
obj = Resources.Load(_PathStr.stringValue);
}
EditorGUI.BeginChangeCheck();
obj = EditorGUI.ObjectField(position, property.name, obj, typeof(T), false);
// Update instance path when its assigned
if (EditorGUI.EndChangeCheck())
{
if (obj != null) {
string _newPath = AssetDatabase.GetAssetPath(obj);
_newPath = Utilities.GetAssetPath_ClipString(_newPath);
if (_newPath == null)
{
Debug.Log("Failed to locate prefab path, did you place it under any resource folder?");
}
else
{
_PathStr.stringValue = _newPath;
Debug.Log("Path string updated:" + _PathStr.stringValue);
}
}else
{
_PathStr.stringValue = null;
}
}
}
}
#endif
/*
code example
public GameObject_ODP a;
*/
/// <summary>
/// GameObject - On Disk Prefab
/// </summary>
[System.Serializable]
public class GameObject_ODP : GenericDiskPrefab<GameObject> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(GameObject_ODP))]
public class GameObject_ODP_Drawer : GenericDiskPrefabDrawer<GameObject> { }
#endif
/// <summary>
/// Font - On Disk Prefab
/// </summary>
[System.Serializable]
public class Font_ODP : GenericDiskPrefab<Font> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Font_ODP))]
public class Font_ODP_Drawer : GenericDiskPrefabDrawer<Font> { }
#endif
/// <summary>
/// Texture - On Disk Prefab
/// </summary>
[System.Serializable]
public class Texture_ODP : GenericDiskPrefab<Texture> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Texture_ODP))]
public class Texture_ODP_Drawer : GenericDiskPrefabDrawer<Texture> { }
#endif
/// <summary>
/// AnimationClip - On Disk Prefab
/// </summary>
[System.Serializable]
public class AnimationClip_ODP : GenericDiskPrefab<AnimationClip> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(AnimationClip_ODP))]
public class AnimationClip_ODP_Drawer : GenericDiskPrefabDrawer<AnimationClip> { }
#endif
/// <summary>
/// Material - On Disk Prefab
/// </summary>
[System.Serializable]
public class Material_ODP : GenericDiskPrefab<Material> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Material_ODP))]
public class Material_ODP_Drawer : GenericDiskPrefabDrawer<Material> { }
#endif
/// <summary>
/// Mesh - On Disk Prefab
/// </summary>
[System.Serializable]
public class Mesh_ODP : GenericDiskPrefab<Mesh> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Mesh_ODP))]
public class Mesh_ODP_Drawer : GenericDiskPrefabDrawer<Mesh> { }
#endif
/// <summary>
/// Audio - On Disk Prefab
/// </summary>
[System.Serializable]
public class AudioClip_ODP : GenericDiskPrefab<AudioClip> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(AudioClip_ODP))]
public class AudioClip_ODP_Drawer : GenericDiskPrefabDrawer<AudioClip> { }
#endif
/// <summary>
/// Audio - On Disk Prefab
/// </summary>
[System.Serializable]
public class Sprite_ODP : GenericDiskPrefab<Sprite> { }
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(Sprite_ODP))]
public class Sprite_ODP_Drawer : GenericDiskPrefabDrawer<Sprite> { }
#endif |
[Serializable]
public class SerializeDualWorkDataTable : DataTableElementBase<int, DualWorkDataTable> // TypeDefIndex: 10553
{
// Methods
// RVA: 0x1CAE830 Offset: 0x1CAE931 VA: 0x1CAE830
public void .ctor(int id, DualWorkDataTable body) { }
}
|
using Watchdog.Forms.Util;
using Watchdog.Persistence;
namespace Watchdog.Entities
{
public class AssetKind : Persistable
{
private static readonly AssetKind defaultValue = new AssetKind();
[PersistableField(0)]
[TableHeader("BESCHREIBUNG", 600)]
public string Description { get; set; }
public double Index { get; set; }
public AssetKind()
{
}
public AssetKind(string description)
{
Description = description;
}
public string GetTableName()
{
return "wdt_asset_kinds";
}
public double GetIndex()
{
return Index;
}
public void SetIndex(double index)
{
Index = index;
}
public static Persistable GetDefaultValue()
{
return defaultValue;
}
public string GetShortName()
{
return "ak";
}
}
}
|
using GalaSoft.MvvmLight.Command;
using Mobile.Core.ViewModels.Core;
using System.Windows.Input;
namespace Mobile.Core.ViewModels
{
public class EditorViewModel : BaseViewModel, IPopupModel
{
public string Data { get; set; } = string.Empty;
public ICommand DataCommand { get; set; }
public override void OnAppear(params object[] args)
{
base.OnAppear(args);
if (args != null && args.Length > 0 && args[0] is string data)
{
Data = data;
}
}
public ICommand CloseCommand => new RelayCommand(CloseAction);
private void CloseAction()
{
DataCommand?.Execute(Data);
_nav.GoModalBack();
}
}
}
|
using System;
using System.IO;
using System.IO.Abstractions;
using System.Threading.Tasks;
using System.CommandLine;
using System.CommandLine.Invocation;
using LaTeXTools.Project;
using LaTeXTools.Build;
using LaTeXTools.Build.Tasks;
namespace LaTeXTools.CLI
{
public class BuildHandler : ICommandHandler
{
public static Command Command
{
get
{
var command = new Command("build", "Build LaTeX target");
command.Handler = new BuildHandler();
return command;
}
}
public async Task<int> InvokeAsync(InvocationContext context)
{
var logger = new Logger();
LaTeXProject? project = await LaTeXProject.FindAsync("latexproject.json");
if (project == null)
{
await logger.LogErrorAsync("no project found");
return -1;
}
if (Environment.CurrentDirectory != project.WorkingDirectory)
{
Environment.CurrentDirectory = project.WorkingDirectory;
}
var fileSystem = new FileSystem();
var build = new LaTeXBuild(project);
if (!build.CanBuild(fileSystem, out string message))
{
await logger.LogErrorAsync(message);
return -1;
}
ProjectTask task = await build.GetBuildTaskAsync(fileSystem);
var buildContext = new BuildContext(fileSystem, logger);
try
{
await logger.LogAsync($"working directory: {Environment.CurrentDirectory}");
await task.RunAsync(buildContext);
}
catch (AbortException abortException)
{
await logger.LogErrorAsync($"process exited with code {abortException.ExitCode}");
await logger.LogFileAsync(File.ReadAllText(project.GetLogPath()));
}
catch (Exception e)
{
Console.WriteLine(e);
return -1;
}
return 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.UI;
public class ToggleFillLight : MonoBehaviour
{
public GameObject FillLight;
private Toggle toggle;
void Start()
{
toggle = GetComponent<Toggle>();
toggle.onValueChanged.AddListener(delegate
{
toggleValueChanged(toggle);
});
}
void toggleValueChanged(Toggle changed)
{
Debug.Log("status = " + toggle.isOn);
if (toggle.isOn)
{
FillLight.GetComponent<Light>().enabled = true;
}
else
{
FillLight.GetComponent<Light>().enabled = false;
}
}
} |
using System;
using System.Reflection;
using Xunit;
namespace iSukces.UnitedValues.Test
{
internal class Program
{
private static void Main(string[] args)
{
var length = new Length(1, LengthUnits.Meter);
var t = typeof(LengthUnit);
foreach (var i in typeof(Program).Assembly.GetTypes())
{
var methods = i.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic);
foreach (var method in methods)
{
var a = method.GetCustomAttribute<FactAttribute>();
if (a == null)
continue;
object instance = null;
if (!method.IsStatic)
instance = Activator.CreateInstance(method.ReflectedType);
method.Invoke(instance, null);
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kitsune.VM
{
class Push : Instruction
{
private object value;
public Push(VM vm, object value)
:base(vm)
{
this.value = value;
}
public override void Run(Process p)
{
p.operandStack.Push(value);
}
public override string ToString()
{
return string.Format("push {0}", value);
}
}
class PushLocal : Instruction
{
private string name;
public PushLocal(VM vm, string name)
: base(vm)
{
this.name= name;
}
public override void Run(Process p)
{
p.operandStack.Push(p.callStack.Peek().Locals[name]);
}
public override string ToString()
{
return string.Format("pushl {0}", name);
}
}
class Discard : Instruction
{
// Just pop a value from the operand stack
public Discard(VM vm)
: base(vm)
{
}
public override void Run(Process p)
{
p.operandStack.Pop();
}
public override string ToString()
{
return string.Format("discard");
}
}
class PopLocal: Instruction
{
string name;
public PopLocal(VM vm, string name)
: base(vm)
{
this.name = name;
}
public override void Run(Process p)
{
object v = p.operandStack.Pop();
p.callStack.Peek().Locals[name ] = v;
}
public override string ToString()
{
return string.Format("popl {0}", name);
}
}
class ApplyPrim : Instruction
{
private int arity;
private Func<object[], object> primitive;
public ApplyPrim(VM vm, int arity, Func<object[], object> primitive)
: base(vm)
{
this.arity = arity;
this.primitive = primitive;
}
public override void Run(Process p)
{
object[] args = new object[arity];
for (int i = 0; i < arity; ++i)
{
args[i] = p.operandStack.Pop();
}
p.operandStack.Push(primitive(args));
}
public override string ToString()
{
return string.Format("applyprim {0},[closure]", arity);
}
}
class Stop : Instruction
{
public Stop(VM vm) : base(vm) { }
public override void Run(Process p)
{
p.timeSlice = 0;
vm.Stop();
}
public override string ToString()
{
return string.Format("stop");
}
}
class JumpIfNot : Instruction
{
private string label;
public JumpIfNot(VM vm, string label) : base(vm)
{
this.label = label;
}
public override void Run(Process p)
{
bool value = (bool) p.operandStack.Pop();
if (!value)
{
Frame f = p.callStack.Peek();
f.IP = f.Method.Labels[label];
}
}
public override string ToString()
{
return string.Format("jnot {0}", label);
}
}
class Jump : Instruction
{
private string label;
public Jump(VM vm, string label)
: base(vm)
{
this.label = label;
}
public override void Run(Process p)
{
Frame f = p.callStack.Peek();
f.IP = f.Method.Labels[label];
}
public override string ToString()
{
return string.Format("jmp {0}", label);
}
}
class Label : Instruction
{
public string label;
public Label(VM vm, string label)
: base(vm)
{
this.label = label;
}
public override void Run(Process p)
{
}
public override string ToString()
{
return string.Format("label {0}", label);
}
}
class Call : Instruction
{
public Method callee;
public Call(VM vm, Method callee)
: base(vm)
{
this.callee = callee;
}
public override void Run(Process p)
{
p.Call(callee);
}
public override string ToString()
{
return string.Format("call [method]");
}
}
class CallNamed : Instruction
{
public string calleeName;
public CallNamed(VM vm, string calleeName)
: base(vm)
{
this.calleeName = calleeName;
}
public override void Run(Process p)
{
Method m = vm.GetMethod(calleeName);
p.Call(m);
}
public override string ToString()
{
return string.Format("calln {0}", calleeName);
}
}
class Ret : Instruction
{
public Ret(VM vm)
: base(vm)
{
}
public override void Run(Process p)
{
p.callStack.Pop();
if (p.callStack.Count == 0)
{
p.timeSlice = 0;
p.State = ProcessState.Exited;
}
}
public override string ToString()
{
return string.Format("ret");
}
}
class Wait : Instruction
{
public Wait(VM vm)
: base(vm)
{
}
public override void Run(Process p)
{
double duration = (double) p.operandStack.Pop();
vm.Sleepify(p, (long) duration);
p.timeSlice = 0;
}
public override string ToString()
{
return string.Format("wait}");
}
}
}
|
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
namespace iSukces.Binding
{
public sealed class DefaultValueConverter : IBindingValueConverter
{
private DefaultValueConverter() { }
private static TypeConverter TryGetTypeConverter(Type type)
{
var at = type.GetCustomAttribute<TypeConverterAttribute>();
if (at is null) return null;
var ct = Type.GetType(at.ConverterTypeName);
if (ct == null)
throw new Exception("Unable to create " + at.ConverterTypeName);
return (TypeConverter)Activator.CreateInstance(ct);
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is BindingSpecial)
return value;
if (value is null)
return null;
var currentType = value.GetType();
if (targetType.IsAssignableFrom(currentType))
return value;
#region Convertible
{
if (value is IConvertible x)
{
if (targetType == typeof(byte)) return x.ToByte(culture);
if (targetType == typeof(short)) return x.ToInt16(culture);
if (targetType == typeof(int)) return x.ToInt32(culture);
if (targetType == typeof(long)) return x.ToInt64(culture);
if (targetType == typeof(sbyte)) return x.ToSByte(culture);
if (targetType == typeof(ushort)) return x.ToUInt16(culture);
if (targetType == typeof(uint)) return x.ToUInt32(culture);
if (targetType == typeof(ulong)) return x.ToUInt64(culture);
if (targetType == typeof(double)) return x.ToDouble(culture);
if (targetType == typeof(decimal)) return x.ToDecimal(culture);
if (targetType == typeof(float)) return x.ToSingle(culture);
if (targetType == typeof(char)) return x.ToChar(culture);
if (targetType == typeof(bool)) return x.ToBoolean(culture);
if (targetType == typeof(DateTime)) return x.ToDateTime(culture);
}
}
#endregion
#region Type converter
{
var co = TryGetTypeConverter(currentType);
if (co is not null)
{
if (co.CanConvertTo(targetType))
{
var c = co.ConvertTo(null, culture, value, targetType);
return c;
}
}
}
{
var co = TryGetTypeConverter(targetType);
if (co is not null)
{
if (co.CanConvertFrom(currentType))
{
var c = co.ConvertFrom(null!, culture ?? CultureInfo.CurrentCulture, value);
return c;
}
}
}
#endregion
#region To string with optional IFormattable
if (targetType == typeof(string))
{
if (value is IFormattable formattable)
{
if (parameter is string format)
return formattable.ToString(format, culture);
return formattable.ToString(null, culture);
}
return value.ToString();
}
#endregion
#region Integer
if (targetType == typeof(int))
{
if (ValueConverterUtils.TryConvertToInt(value, out var intValue))
return intValue;
}
#endregion
return BindingSpecial.Invalid; // give up
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is BindingSpecial)
return value;
if (value is null)
return null;
var currentType = value.GetType();
if (targetType.IsAssignableFrom(currentType))
return value;
#region Type converter
{
var co = TryGetTypeConverter(targetType);
if (co is not null)
{
if (co.CanConvertFrom(currentType))
{
var c = co.ConvertFrom(null!, culture ?? CultureInfo.CurrentCulture, value);
return c;
}
}
}
{
var co = TryGetTypeConverter(currentType);
if (co is not null)
{
if (co.CanConvertTo(targetType))
{
var c = co.ConvertTo(null!, culture ?? CultureInfo.CurrentCulture, value, targetType);
return c;
}
}
}
#endregion
return BindingSpecial.Invalid; // give up
}
public static DefaultValueConverter Instance => DefaultValueConverterHolder.SingleIstance;
public static class DefaultValueConverterHolder
{
public static readonly DefaultValueConverter SingleIstance = new DefaultValueConverter();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
class HandsOfCards
{
static void Main(string[] args)
{
var playersPowers = new Dictionary<string, int>();
var playersCards = new Dictionary<string, List<string>>();
string input;
while ((input = Console.ReadLine()) != "JOKER")
{
string[] playerArgs = input
.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string name = playerArgs[0];
List<string> cards = playerArgs[1]
.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.ToList();
if (playersCards.ContainsKey(name) == false)
{
playersCards.Add(name, new List<string>());
}
playersCards[name].AddRange(cards);
}
foreach (var player in playersCards)
{
int totalPower = 0;
foreach (string cardSet in player.Value.Distinct())
{
char[] cards = cardSet.ToCharArray();
int power = 0;
switch (cards.First())
{
case '1':
power += 10;
break;
case 'J':
power += 11;
break;
case 'Q':
power += 12;
break;
case 'K':
power += 13;
break;
case 'A':
power += 14;
break;
default:
power += int.Parse(cards.First().ToString());
break;
}
switch (cards.Last())
{
case 'D':
power *= 2;
break;
case 'H':
power *= 3;
break;
case 'S':
power *= 4;
break;
}
totalPower += power;
}
playersPowers.Add(player.Key, totalPower);
}
foreach (var player in playersPowers)
{
Console.WriteLine($"{player.Key}: {player.Value}");
}
}
} |
namespace _10.ExtractDirectoryContentToXmlWithXDocument
{
using System;
using System.IO;
using System.Text;
using System.Xml.Linq;
public class ExtractDirectoryContentToXmlWithXDocument
{
public static void Main(string[] args)
{
string path = @"../../";
Encoding encoding = Encoding.GetEncoding("windows-1251");
var rootDirectory = new DirectoryInfo(path);
XElement directoryInfo = new XElement("root");
directoryInfo.Add(WalkDirectoryTree(rootDirectory));
directoryInfo.Save("../../fileSystem.xml");
Console.WriteLine("The information about the directories was successfuly saved in 'fileSystem.xml'");
}
private static XElement WalkDirectoryTree(DirectoryInfo directory)
{
var currentElement = new XElement("dir", new XAttribute("path", directory.Name));
foreach (var currentFile in directory.GetFiles())
{
currentElement.Add(new XElement("file", currentFile.Name));
}
foreach (var currentDirectory in directory.GetDirectories())
{
currentElement.Add(WalkDirectoryTree(currentDirectory));
}
return currentElement;
}
}
}
|
using FluentAssertions;
using Jacobi.Zim80.CpuZ80.Opcodes;
using Jacobi.Zim80.CpuZ80.UnitTests;
using Jacobi.Zim80.Diagnostics;
using Jacobi.Zim80.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Jacobi.Zim80.CpuZ80.Instructions.UnitTests
{
[TestClass]
public class MathDirectInstructionTest
{
private const byte Value1 = 0x55;
private const byte Value2 = 0xEA;
[TestMethod]
public void ADDn_nc_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue + Value1;
var cpu = TestMathOperation(MathOperations.Add, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ADDn_nc_c()
{
byte expected = CpuZ80TestExtensions.MagicValue + Value1;
var cpu = TestMathOperation(MathOperations.Add, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ADDn_c_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue + Value2));
var cpu = TestMathOperation(MathOperations.Add, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void ADDn_c_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue + Value2));
var cpu = TestMathOperation(MathOperations.Add, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void ADCn_nc_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue + Value1;
var cpu = TestMathOperation(MathOperations.AddWithCarry, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ADCn_nc_c()
{
byte expected = CpuZ80TestExtensions.MagicValue + Value1 + 1;
var cpu = TestMathOperation(MathOperations.AddWithCarry, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ADCn_c_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue + Value2));
var cpu = TestMathOperation(MathOperations.AddWithCarry, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void ADCn_c_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue + Value2 + 1));
var cpu = TestMathOperation(MathOperations.AddWithCarry, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SUBn_nc_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value1));
var cpu = TestMathOperation(MathOperations.Subtract, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SUBn_nc_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value1));
var cpu = TestMathOperation(MathOperations.Subtract, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SUBn_c_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue -Value2));
var cpu = TestMathOperation(MathOperations.Subtract, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SUBn_c_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value2));
var cpu = TestMathOperation(MathOperations.Subtract, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SBCn_nc_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value1));
var cpu = TestMathOperation(MathOperations.SubtractWithCarry, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SBCn_nc_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value1 - 1));
var cpu = TestMathOperation(MathOperations.SubtractWithCarry, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SBCn_c_nc()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value2));
var cpu = TestMathOperation(MathOperations.SubtractWithCarry, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void SBCn_c_c()
{
byte expected = unchecked((byte)(CpuZ80TestExtensions.MagicValue - Value2 - 1));
var cpu = TestMathOperation(MathOperations.SubtractWithCarry, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void ANDn_nc_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue & Value1;
var cpu = TestMathOperation(MathOperations.And, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ANDn_nc_c()
{
byte expected = CpuZ80TestExtensions.MagicValue & Value1;
var cpu = TestMathOperation(MathOperations.And, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ANDn_c_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue & Value2;
var cpu = TestMathOperation(MathOperations.And, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ANDn_c_c()
{
byte expected = CpuZ80TestExtensions.MagicValue & Value2;
var cpu = TestMathOperation(MathOperations.And, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void XORn_nc_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue ^ Value1;
var cpu = TestMathOperation(MathOperations.ExlusiveOr, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void XORn_nc_c()
{
byte expected = CpuZ80TestExtensions.MagicValue ^ Value1;
var cpu = TestMathOperation(MathOperations.ExlusiveOr, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void XORn_c_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue ^ Value2;
var cpu = TestMathOperation(MathOperations.ExlusiveOr, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void XORn_c_c()
{
byte expected = CpuZ80TestExtensions.MagicValue ^ Value2;
var cpu = TestMathOperation(MathOperations.ExlusiveOr, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ORn_nc_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue | Value1;
var cpu = TestMathOperation(MathOperations.Or, Value1, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ORn_nc_c()
{
byte expected = CpuZ80TestExtensions.MagicValue | Value1;
var cpu = TestMathOperation(MathOperations.Or, Value1, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ORn_c_nc()
{
byte expected = CpuZ80TestExtensions.MagicValue | Value2;
var cpu = TestMathOperation(MathOperations.Or, Value2, expected, false);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void ORn_c_c()
{
byte expected = CpuZ80TestExtensions.MagicValue | Value2;
var cpu = TestMathOperation(MathOperations.Or, Value2, expected, true);
cpu.Registers.Flags.C.Should().Be(false);
}
[TestMethod]
public void CPn_nc_nc()
{
var cpu = TestMathOperation(MathOperations.Compare, Value1, null, false);
cpu.Registers.Flags.C.Should().Be(true);
}
[TestMethod]
public void CPn_nc_c()
{
var cpu = TestMathOperation(MathOperations.Compare, Value1, null, true);
cpu.Registers.Flags.C.Should().Be(true);
cpu.Registers.Flags.Z.Should().Be(false);
}
[TestMethod]
public void CPn_c_nc()
{
var cpu = TestMathOperation(MathOperations.Compare, Value2, null, false);
cpu.Registers.Flags.C.Should().Be(true);
cpu.Registers.Flags.Z.Should().Be(false);
}
[TestMethod]
public void CPn_c_c()
{
var cpu = TestMathOperation(MathOperations.Compare, Value2, null, true);
cpu.Registers.Flags.C.Should().Be(true);
cpu.Registers.Flags.Z.Should().Be(false);
}
[TestMethod]
public void CPn_z()
{
var cpu = TestMathOperation(MathOperations.Compare, CpuZ80TestExtensions.MagicValue, null, true);
cpu.Registers.Flags.Z.Should().Be(true);
}
private CpuZ80 TestMathOperation(MathOperations mathOp, byte value, byte? expectedValue,
bool carry)
{
var ob = OpcodeByte.New(x: 3, z: 6, y: (byte)mathOp);
var model = ExecuteTest(ob, value, carry);
if (expectedValue.HasValue)
model.Cpu.Registers.A.Should().Be(expectedValue);
return model.Cpu;
}
private static SimulationModel ExecuteTest(OpcodeByte ob, byte value, bool carry)
{
var cpuZ80 = new CpuZ80();
cpuZ80.Registers.Flags.C = carry;
byte[] buffer = new byte[] { ob.Value, value };
var model = cpuZ80.Initialize(buffer);
cpuZ80.FillRegisters();
model.ClockGen.SquareWave(7);
Console.WriteLine(model.LogicAnalyzer.ToWaveJson());
return model;
}
}
}
|
using System.Text.Json.Serialization;
namespace Ealse.Growatt.Api.Models
{
public class WeatherUpdate
{
[JsonPropertyName("utc")]
public string Utc { get; set; }
[JsonPropertyName("loc")]
public string Loc { get; set; }
}
} |
using Newtonsoft.Json;
namespace Alexa.NET.ProactiveEvents.MediaContentAvailabilityNotification
{
public class ProviderName
{
public ProviderName() { }
public ProviderName(LocaleAttributes name)
{
Name = name;
}
[JsonProperty("name"), JsonConverter(typeof(LocaleAttributeConverter), "providerName")]
public LocaleAttributes Name { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.U2D;
using UnityEngine.UI;
public class LoadGameObjectRequest : LoadObjectRequest
{
//string[] pathList;
//HashSet<string> currNeedLoadSet = new HashSet<string>();
private string path;
private int count;
bool isFinish;
public Action<HashSet<GameObject>> selfFinishCallback;
HashSet<GameObject> currGameObjects = new HashSet<GameObject>();
public LoadGameObjectRequest(string path, int count)
{
this.path = path;
this.count = count;
}
public override void Start()
{
ResourceManager.Instance.GetObject<GameObject>(this.path, OnLoadFinish);
}
public void OnLoadFinish(GameObject obj)
{
//obj 就算已经有一个实例了
currGameObjects.Add(obj);
for (int i = 0; i < count - 1; i++)
{
var insObj = GameObject.Instantiate(obj);
currGameObjects.Add(insObj);
}
selfFinishCallback?.Invoke(currGameObjects);
isFinish = true;
}
public override bool CheckFinish()
{
return isFinish;
}
//public void Start(string[] pathList)
//{
// this.pathList = pathList;
// for (int i = 0; i < pathList.Length; i++)
// {
// var currPath = pathList[i];
// currNeedLoadSet.Add(currPath);
// AssetManager.Instance.Load(currPath, (asset) =>
// {
// this.OnOneResLoadFinish(currPath, asset);
// });
// }
//}
//public void OnOneResLoadFinish(string currPath, UnityEngine.Object asset)
//{
// if (currNeedLoadSet.Contains(currPath))
// {
// currNeedLoadSet.Remove(currPath);
// }
// else
// {
// Logx.LogError("the currPath is not correct : " + currPath);
// }
//}
public override void Finish()
{
}
public override void Release()
{
foreach (var obj in currGameObjects)
{
ResourceManager.Instance.ReturnObject(this.path, obj);
}
//for (int i = this.pathList.Length - 1; i >= 0; i--)
//{
// var path = this.pathList[i];
// AssetManager.Instance.Release(path);
//}
}
}
|
using GenHTTP.Modules.Core.LoadBalancing;
namespace GenHTTP.Modules.Core
{
public static class LoadBalancer
{
public static LoadBalancerBuilder Create() => new LoadBalancerBuilder();
}
}
|
namespace ForkingVirtualMachine
{
using System.Threading.Tasks;
public interface IAsyncExecution : IExecution
{
public Task ExecuteAsync(IContext context);
}
}
|
using System.Threading.Tasks;
using Geocoding.API.Models;
namespace Geocoding.API.Services.Geocoding
{
public class GeocodingFake : IGeocoding
{
public Task<GeocodeInfo> GeocodeAsync(string address)
{
return Task.FromResult(new GeocodeInfo()
{
FormattedAddress = $"Fake location for address: {address}",
Latitude = 5,
Longitude = 5
});
}
public Task<string> ReverseGeocodeAsync(double latitude, double longitude)
{
return Task.FromResult($"Fake address for location: latitude - {latitude} and longitude - {longitude}");
}
}
} |
protected void EncryptConnStrings_Click(object sender, EventArgs e)
{
// Get configuration information about Web.config
Configuration config =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Let's work with the <connectionStrings> section
ConfigurationSection connectionStrings = config.GetSection("connectionStrings");
if (connectionStrings != null)
// Only encrypt the section if it is not already protected
if (!connectionStrings.SectionInformation.IsProtected)
{
// Encrypt the <connectionStrings> section using the
// DataProtectionConfigurationProvider provider
connectionStrings.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
config.Save();
// Refresh the Web.config display
DisplayWebConfig();
}
}
protected void DecryptConnStrings_Click(object sender, EventArgs e)
{
// Get configuration information about Web.config
Configuration config =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Let's work with the <connectionStrings> section
ConfigurationSection connectionStrings =
config.GetSection("connectionStrings");
if (connectionStrings != null)
// Only decrypt the section if it is protected
if (connectionStrings.SectionInformation.IsProtected)
{
// Decrypt the <connectionStrings> section
connectionStrings.SectionInformation.UnprotectSection();
config.Save();
// Refresh the Web.config display
DisplayWebConfig();
}
} |
using Plugin.Media;
using Plugin.Media.Abstractions;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using QSF.Helpers;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace QSF.Examples.ImageEditorControl
{
internal static class MediaHelper
{
public static bool CanTakePhoto
{
get
{
var mediaPlugin = CrossMedia.Current;
return mediaPlugin.IsTakePhotoSupported &&
mediaPlugin.IsCameraAvailable;
}
}
public static bool CanPickPhoto
{
get
{
var mediaPlugin = CrossMedia.Current;
return mediaPlugin.IsPickPhotoSupported;
}
}
public static async Task<bool> InitializeAsync()
{
var mediaPlugin = CrossMedia.Current;
return await mediaPlugin.Initialize();
}
public static async Task<string> TakePhotoAsync()
{
if (!CanTakePhoto)
{
return null;
}
if (!await PermissionsHelper.RequestPermissionsAsync(Permission.Camera, Permission.Storage))
{
return null;
}
var mediaPlugin = CrossMedia.Current;
var mediaOptions = new StoreCameraMediaOptions();
var mediaFile = await mediaPlugin.TakePhotoAsync(mediaOptions);
return mediaFile?.Path;
}
public static async Task<string> PickPhotoAsync()
{
if (!CanPickPhoto)
{
return null;
}
if (!await PermissionsHelper.RequestPermissionsAsync(Permission.Photos, Permission.Storage))
{
return null;
}
var mediaPlugin = CrossMedia.Current;
var mediaOptions = new PickMediaOptions();
var mediaFile = await mediaPlugin.PickPhotoAsync(mediaOptions);
return mediaFile?.Path;
}
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MailGun.Services
{
public class MailGunApiEmailSender: IEmailSender
{
//
// Identify the connection type to the MailGun server
//
public const string ConnectionType = "api";
//
// Identify the external mail service provider.
//
public const string Provider = "MailGun";
//
// Configuration setting for routing email through MailGun API.
//
private readonly MailGunApiEmailSettings _apiEmailConfig;
//
// Accessor for the configuration to send mail via MailGun API.
//
public MailGunApiEmailSettings EmailSettings
{
get
{
return _apiEmailConfig;
}
}
//
// Default constructor with email configuration initialized via
// option configuration.
//
public MailGunApiEmailSender(
IOptions<MailGunApiEmailSettings> apiEmailConfig)
{
_apiEmailConfig = apiEmailConfig.Value;
}
//
// Sends email via MailGun REST api, given email recipient, email
// subject, and email body.
//
public async Task SendEmailAsync(
string email,
string subject,
string message
)
{
string apiKey = EmailSettings.ApiKey;
string baseUri = EmailSettings.BaseUri;
string requestUri = EmailSettings.RequestUri;
string token = HttpBasicAuthHeader("api", apiKey);
FormUrlEncodedContent emailContent = HttpContent(email,
subject,
message
);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", token);
HttpResponseMessage response = await client
.PostAsync(requestUri, emailContent)
.ConfigureAwait(false);
if (false == response.IsSuccessStatusCode)
{
string errMsg = String.Format(
"Failed to send mail to {0} via {1} {2} due to\n{3}.",
email,
Provider,
ConnectionType,
response.ToString()
);
throw new HttpRequestException(errMsg);
}
}
}
//
// Put together the basic authentication header for MailGun
// Rest API (see https://documentation.mailgun.com/quickstart-sending.html#send-via-api).
//
protected string HttpBasicAuthHeader(
string tokenName,
string tokenValue
)
{
string tokenString = string.Format(
"{0}:{1}",
tokenName,
tokenValue
);
byte[] bytes = Encoding.UTF8.GetBytes(tokenString);
string authHeader = Convert.ToBase64String(bytes);
return authHeader;
}
//
// Put together the core elements for the email for MailGun.
//
// For a list of valid fields, please refer to MailGun document
// (see https://documentation.mailgun.com/api-sending.html#sending).
//
protected FormUrlEncodedContent HttpContent(
string recipient,
string subject,
string message
)
{
string sender = EmailSettings.From;
var emailSender = new KeyValuePair<string, string>("from", sender);
var emailRecipient =
new KeyValuePair<string, string>("to", recipient);
var emailSubject =
new KeyValuePair<string, string>("subject", subject);
var emailBody =
new KeyValuePair<string, string>("text", message);
List<KeyValuePair<string, string>> content =
new List<KeyValuePair<string, string>>();
content.Add(emailSender);
content.Add(emailRecipient);
content.Add(emailSubject);
content.Add(emailBody);
FormUrlEncodedContent urlEncodedContent =
new FormUrlEncodedContent(content);
return urlEncodedContent;
}
}
}
|
using System.Drawing;
using System.IO;
namespace ToText.API.Extensions
{
public static class Extensions
{
public static Image ToImage(this byte[] imageBytes)
{
//return (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));
using (var ms = new MemoryStream(imageBytes))
return new Bitmap(ms);
}
}
}
|
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Esri.ArcGISRuntime.UI.Controls;
using Esri.ArcGISRuntime.Mapping;
using Android.Opengl;
using Google.AR.Core;
using Google.AR.Core.Exceptions;
using System;
using Javax.Microedition.Khronos.Egl;
using Javax.Microedition.Khronos.Opengles;
using Android.Support.V4.Content;
using Android.Support.V4.App;
using Android.Support.Design.Widget;
using System.Collections.Generic;
using Esri.ArcGISRuntime.Geometry;
using System.Threading.Tasks;
namespace ARToolkit.SampleApp.Samples
{
[Activity(
Label = "Look around mode",
Theme = "@style/Theme.AppCompat",
ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize, ScreenOrientation = Android.Content.PM.ScreenOrientation.Locked)]
[SampleInfo(DisplayName = "ARCore Disabled", Description = "A sample that doesn't rely on ARCore but only features the ability to look around based on a motion sensor")]
public class LookAroundSample : ARActivityBase
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
try
{
ARView.RenderVideoFeed = false;
ARView.OriginCamera = new Esri.ArcGISRuntime.Mapping.Camera(new MapPoint(-119.622075, 37.720650, 2105), 0, 90, 0); //Yosemite
Surface sceneSurface = new Surface();
sceneSurface.ElevationSources.Add(new ArcGISTiledElevationSource(new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")));
Scene scene = new Scene(Basemap.CreateImagery())
{
BaseSurface = sceneSurface
};
ARView.Scene = scene;
ARView.StartTrackingAsync(Esri.ArcGISRuntime.ARToolkit.ARLocationTrackingMode.Ignore);
}
catch (System.Exception ex)
{
Toast.MakeText(this, "Failed to load scene: \n" + ex.Message, ToastLength.Long).Show();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField]
private float health = 100;
private bool isDead = false;
private bool pursue = false;
private Transform target;
[SerializeField] private AudioClip dieSound;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
target = FindObjectOfType<CharacterManager>().transform;
}
private void Update()
{
if ((target.position - transform.position).magnitude < 40 && !pursue) pursue = true;
}
private void FixedUpdate()
{
if (pursue)
{
rb.AddForce((target.position - transform.position).normalized * 20f);
if ((target.position - transform.position).magnitude > 30)
{
rb.velocity = (target.position - transform.position).normalized * 5f;
}
if ((target.position - transform.position).magnitude < 6)
{
rb.AddForce((target.position - transform.position).normalized * 0.05f, ForceMode.VelocityChange);
}
}
}
public enum EnemyType
{
Rookie,
Veteran,
Elite,
}
public EnemyType type;
public virtual void Damage(float damageAmount)
{
if (isDead) return;
health -= damageAmount;
Debug.Log("Inflicted damage is " + damageAmount);
if(health <= 0)
{
Die();
}
}
public void Die()
{
isDead = true;
pursue = false;
Debug.Log(gameObject.name + " has died.");
GetComponent<AudioSource>().PlayOneShot(dieSound);
FindObjectOfType<CharacterManager>().HealthChange(+50);
Destroy(gameObject, 3f);
}
public virtual void Stop()
{
pursue = false;
rb.velocity = Vector3.zero;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace SAFE.Data.Utils
{
public static class CompressionHelper
{
public static List<byte> Compress(this List<byte> data)
=> data.ToArray().Compress().ToList();
public static List<byte> Decompress(this List<byte> data)
=> data.ToArray().Decompress().ToList();
public static byte[] Compress(this byte[] data)
{
byte[] compressedArray = null;
try
{
using (var memoryStream = new MemoryStream())
{
using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
{
deflateStream.Write(data, 0, data.Length);
}
compressedArray = memoryStream.ToArray();
}
}
catch (Exception ex)
{
// do something !
throw ex;
}
return compressedArray;
}
public static byte[] Decompress(this byte[] data)
{
byte[] decompressedArray = null;
try
{
using (var decompressedStream = new MemoryStream())
{
using (var compressStream = new MemoryStream(data))
using (var deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
decompressedArray = decompressedStream.ToArray();
}
}
catch (InvalidDataException ex) when (ex.HResult == -2146233087) { return data; };
// "The archive entry was compressed using an unsupported compression method."
// i.e. it was never compressed to start with.
//catch
//{
// // do something !
//}
return decompressedArray;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Options;
using SolutionTools.ProjectRemoval;
using SolutionTools.Utils;
namespace SolutionTools.Commands
{
public static class RemoveProjectsCommand
{
public static void Run(string[] args)
{
string solutionFile = string.Empty;
string pattern = string.Empty;
string target = string.Empty;
bool help = false;
var options = new OptionSet
{
{"s|solution=", "the path to solution files.", s => solutionFile = s},
{ "p|pattern=", "the regex pattern for project name", p => pattern = p},
{ "t|target=", "the target solution file to write to", t => target = t},
{ "h|help", "show options", h => help = h != null},
};
try
{
options.Parse(args);
}
catch (OptionException e)
{
// output some error message
Logger.Error(e.Message);
Logger.Error("Try `--help' for more information.");
return;
}
if (help)
{
options.WriteOptionDescriptions(Console.Out);
return;
}
var switcher = new RemoveProjects();
switcher.Execute(Directory.GetCurrentDirectory(), solutionFile, pattern, target);
}
}
}
|
using Memorandum.Core.Repositories;
namespace Memorandum.Core.Domain
{
public abstract class Node
{
public abstract NodeIdentifier NodeId { get; }
public abstract User User { get; set; }
}
} |
using System;
using System.Collections.Generic;
namespace SINTEF.AutoActive.Plugins
{
public interface IPluginInitializer
{
IEnumerable<Type> Plugins { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace sbid._M
{
public enum ProgramPlatform
{
Windows, Unix
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek
{
internal abstract class PeekableItem : IPeekableItem
{
protected readonly IPeekResultFactory PeekResultFactory;
protected PeekableItem(IPeekResultFactory peekResultFactory)
=> this.PeekResultFactory = peekResultFactory;
public string DisplayName =>
// This is unused, and was supposed to have been removed from IPeekableItem.
null;
public abstract IEnumerable<IPeekRelationship> Relationships { get; }
public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName);
}
}
|
using Microsoft.Graph;
namespace FilesExplorer.Models
{
/// <summary>
/// Represents a OneDrive folder
/// </summary>
public class OneDriveFolder : OneDriveItem
{
public OneDriveFolder(DriveItem item) : base(item)
{
}
}
}
|
using UnityEngine;
namespace UnityEngine.Formats.Alembic.Importer
{
internal class AlembicStreamDescriptor : ScriptableObject
{
[SerializeField]
private string pathToAbc;
public string PathToAbc
{
// For standalone builds, the path should be relative to the StreamingAssets
get
{
#if UNITY_EDITOR
return pathToAbc;
#else
return System.IO.Path.Combine(Application.streamingAssetsPath, pathToAbc);
#endif
}
set { pathToAbc = value; }
}
[SerializeField]
private AlembicStreamSettings settings = new AlembicStreamSettings();
public AlembicStreamSettings Settings
{
get { return settings; }
set { settings = value; }
}
[SerializeField]
private bool hasVaryingTopology = false;
public bool HasVaryingTopology
{
get { return hasVaryingTopology; }
set { hasVaryingTopology = value; }
}
[SerializeField]
private bool hasAcyclicFramerate = false;
public bool HasAcyclicFramerate
{
get { return hasAcyclicFramerate; }
set { hasAcyclicFramerate = value; }
}
[SerializeField]
public double abcStartTime = double.MinValue;
[SerializeField]
public double abcEndTime = double.MaxValue;
public double duration { get { return abcEndTime - abcStartTime; } }
}
}
|
using FoodyAPI.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace FoodyAPI.Models
{
public class UsersData
{
public List<User> users { get; set; }
}
public class User
{
[Key]
public string id { get; set; }
public double callories { get; set; }
public virtual List<Product> Favourite {get; set;}
public virtual List<DayIntake> Statistics { get; set; }
public void Addproduct(Product p)
{
if (Favourite == null)
{
Favourite = new List<Product>();
}
this.Favourite.Add(p);
}
public void RemoveProduct(Product p)
{
this.Favourite.Remove(p);
}
}
}
|
#region header
//---------------------------------------------------------------------------------------
// USPExpress Parser .NET Pro
// Copyright (C) 2005 UNISOFT Plus Ltd.
// All rights reserved.
//---------------------------------------------------------------------------------------
#endregion
using System;
namespace USP.Express.Pro
{
/// <summary>
/// Contains a collection of variables.
/// </summary>
public class VariablesCollection: IdentifiersCollection
{
// VariableAdd event
internal delegate void AddEventHandler( string Name );
internal event AddEventHandler VariableAdd;
// Changed event
internal delegate void ChangedEventHandler();
internal event ChangedEventHandler Changed;
internal VariablesCollection()
{}
/// <summary>
/// Adds a variable to the collection
/// </summary>
/// <param name="variable">Variable to be added</param>
/// <returns>The index at which the variable has been added.</returns>
public int Add( Variable variable )
{
return List.Add( variable );
}
/// <summary>
/// Removes a variable from the collection
/// </summary>
/// <param name="variable">Variable to be removed</param>
public void Remove( Variable variable )
{
List.Remove( variable );
}
/// <summary>
/// Get the variable at the specified index.
/// </summary>
public Variable this[ int index ]
{
get
{
return ( Variable )List[ index ];
}
}
/// <summary>
/// Performs additional custom processes before inserting a new element into the collection.
/// </summary>
/// <param name="index">The zero-based index at which to insert value.</param>
/// <param name="value">The new value of the element at index.</param>
protected override void OnInsert( int index, object value )
{
Variable variable = ( Variable )value;
RaiseVariableAddEvent( variable.Name );
}
/// <summary>
/// Performs additional custom processes after inserting a new element into the collection
/// </summary>
/// <param name="index">The zero-based index at which to insert value.</param>
/// <param name="value">The new value of the element at index.</param>
protected override void OnInsertComplete(int index, object value)
{
base.OnInsertComplete( index, value );
Variable variable = ( Variable )value;
for ( int i = 0; i < variable.Aliases.Count; ++i )
{
RaiseVariableAddEvent( variable.Aliases[ i ] );
AddToHashtable( variable.Aliases[ i ], index );
}
variable.AliasAdd += new Variable.AliasAddEventHandler( OnAliasAdd );
variable.AliasRemove += new Variable.AliasRemoveEventHandler( OnAliasRemove );
RaiseChangedEvent();
}
protected override void OnRemoveComplete(int index, object value)
{
Variable variable = ( Variable )value;
variable.AliasAdd -= new Variable.AliasAddEventHandler( OnAliasAdd );
variable.AliasRemove -= new Variable.AliasRemoveEventHandler( OnAliasRemove );
for ( int i = 0; i < variable.Aliases.Count; ++i )
{
RemoveFromHashtable( variable.Aliases[ i ] );
}
base.OnRemoveComplete( index, value );
RaiseChangedEvent();
}
/// <summary>
/// Updates indices in the inner hashtable of names, starting with the specified index.
/// </summary>
/// <param name="start">Index to start with.</param>
/// <remarks>Called when the Variable is removed from the collection.</remarks>
protected override void RefreshIndices( int start )
{
for ( int i = start; i < Count; ++i )
{
Variable variable = ( ( Variable ) this[ i ] );
ReplaceInHashtable( variable.Name, i - 1 );
for ( int j = 0; j < variable.Aliases.Count; ++j )
{
ReplaceInHashtable( variable.Aliases[ j ], i - 1 );
}
}
}
/// <summary>
/// Handles <see cref="Variable.AliasAdd"/> event.
/// Updates inner hashtable.
/// </summary>
/// <param name="variableName">Variable name.</param>
/// <param name="alias">New alias.</param>
private void OnAliasAdd( string variableName, string alias )
{
RaiseVariableAddEvent( alias );
AddToHashtable( alias, Search( variableName ) );
RaiseChangedEvent();
}
/// <summary>
/// Handles <see cref="Variable.AliasRemove"/> event.
/// Updates inner hashtable of variables names.
/// </summary>
/// <param name="alias">Alias.</param>
private void OnAliasRemove( string alias )
{
RemoveFromHashtable( alias );
RaiseChangedEvent();
}
/// <summary>
/// Raises <see cref="VariableAdd"/> event.
/// </summary>
/// <param name="Name">New variable name.</param>
private void RaiseVariableAddEvent( string Name )
{
if ( VariableAdd != null )
{
VariableAdd(Name);
}
}
/// <summary>
/// Raises <see cref="Changed"/> event.
/// </summary>
private void RaiseChangedEvent()
{
if ( Changed != null )
{
Changed();
}
}
}
}
|
using System;
using UnityEngine.Events;
namespace Framework.Events.UnityEvents
{
[Serializable]
public class EventString : UnityEvent<string>
{
}
}
|
using System;
namespace Insma.Mxa.Framework.Graphics {
public enum EffectParameterClass {
Scalar = 0,
Vector = 1,
Matrix = 2,
Object = 3,
Struct = 4,
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PractiseArray
{
class CSVReader
{
private string csvFilePath;
public CSVReader(string csvFilePath)
{
this.csvFilePath = csvFilePath;
}
public Country[] ReadFirstCountries(int nCountries)
{
Country[] countries = new Country[nCountries];
using (StreamReader sr = new StreamReader(csvFilePath))
{
//read header line
sr.ReadLine();
for (int i = 0; i < nCountries; i++)
{
string csvLine = sr.ReadLine();
countries[i] = ReadCountryFromCSV(csvLine);
}
}
return countries;
}
public Country ReadCountryFromCSV(string csvLine)
{
string[] parts = csvLine.Split(new char[] { ','});
string name = parts[0];
string code = parts[1];
string region = parts[2];
int population = int.Parse(parts[3]);
return new Country(name, code, region, population);
}
}
}
|
using Budgetly.Infrastructure.Persistence.Options;
using Microsoft.EntityFrameworkCore;
namespace Budgetly.Infrastructure.Persistence.Providers;
public class SqlServerProvider : IDatabaseProvider
{
public DbContextOptionsBuilder Build(DbContextOptionsBuilder dbContextOptions,
PersistenceOptions persistenceOptions)
{
var assemblyName = typeof(ApplicationDbContext).Assembly.FullName;
return dbContextOptions.UseSqlServer(
persistenceOptions.SqlServerConnectionString,
a => a.MigrationsAssembly(assemblyName));
}
} |
// Copyright (c) Autofac Project. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Xunit;
namespace Autofac.Multitenant.Wcf.Test
{
public class OperationContextTenantIdentificationStrategyFixture
{
[Fact]
public void TryIdentifyTenant_NoOperationContext()
{
var strategy = new OperationContextTenantIdentificationStrategy();
object tenantId;
bool success = strategy.TryIdentifyTenant(out tenantId);
Assert.False(success);
}
}
}
|
using UnityEngine;
using System.Collections;
namespace NewtonVR
{
public class NVRVignette : MonoBehaviour
{
public Shader vignetteShader;
private int vignetteProperty;
private Material material;
public static NVRVignette instance;
void Awake()
{
instance = this;
if (vignetteShader == null)
vignetteShader = Shader.Find("Vignette");
material = new Material(vignetteShader);
vignetteProperty = Shader.PropertyToID("_VignettePower");
}
public void SetAmount(float newFeather)
{
material.SetFloat(vignetteProperty, newFeather);
}
private void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Graphics.Blit(src, dest, material);
}
private void OnDestroy()
{
Destroy(material);
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
namespace Avocado2D.Input
{
public class InputManager : GameComponent
{
/// <summary>
/// Returns the current keyboard state.
/// </summary>
public KeyboardState KeyboardState { get; private set; }
/// <summary>
/// Returns the last known keyboard state.
/// </summary>
public KeyboardState PreviousKeyboardState { get; private set; }
/// <summary>
/// Gets the current mousestate.
/// </summary>
public MouseState MouseState { get; private set; }
/// <summary>
/// Gets the previous mousestate.
/// </summary>
public MouseState PreviousMouseState { get; private set; }
private Dictionary<string, List<Keys>> keybinds { get; }
public InputManager(AvocadoGame game) : base(game)
{
PreviousKeyboardState = Keyboard.GetState();
PreviousMouseState = Mouse.GetState();
keybinds = new Dictionary<string, List<Keys>>();
}
/// <summary>
/// Adds keybindings to the inputmanager.
/// </summary>
/// <param name="name">The name of the keybinding.</param>
/// <param name="keys">The keys.</param>
public void AddKeybind(string name, params Keys[] keys)
{
if (!keybinds.ContainsKey(name))
{
keybinds.Add(name, new List<Keys>());
InsertKeys(name, keys);
}
else
{
InsertKeys(name, keys);
}
}
private void InsertKeys(string name, Keys[] keys)
{
foreach (var key in keys)
{
keybinds[name].Add(key);
}
}
/// <summary>
/// Updates the inputmanager.
/// </summary>
/// <param name="gameTime"></param>
public override void Update(GameTime gameTime)
{
// updates keyboardstates
PreviousKeyboardState = KeyboardState;
KeyboardState = Keyboard.GetState();
// updates mousestates
PreviousMouseState = MouseState;
MouseState = Mouse.GetState();
base.Update(gameTime);
}
/// <summary>
/// Check for releases by comparing the previous state to the current state.
/// In the event of a key release it will have been down, and currently its up
/// </summary>
/// <param name="key">This is the key to check for release</param>
/// <returns></returns>
public bool KeyReleased(Keys key)
{
return KeyboardState.IsKeyUp(key) && PreviousKeyboardState.IsKeyDown(key);
}
/// <summary>
/// Gets the released key by the name of the key.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool KeyReleased(string name)
{
if (!keybinds.ContainsKey(name)) return false;
foreach (var key in keybinds[name])
{
if (KeyboardState.IsKeyUp(key) && PreviousKeyboardState.IsKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Given a previous key state of up determine if its been pressed.
/// </summary>
/// <param name="key">key to check</param>
/// <returns></returns>
public bool KeyHit(Keys key)
{
return KeyboardState.IsKeyDown(key) && PreviousKeyboardState.IsKeyUp(key);
}
/// <summary>
/// Given a previous key state of up determine if its been pressed.
/// </summary>
/// <param name="name">The name of the keybind.</param>
/// <returns></returns>
public bool KeyHit(string name)
{
if (!keybinds.ContainsKey(name)) return false;
foreach (var key in keybinds[name])
{
if (KeyboardState.IsKeyDown(key) && PreviousKeyboardState.IsKeyUp(key))
return true;
}
return false;
}
/// <summary>
/// Don't examine last state just check if a key is down
/// </summary>
/// <param name="key">key to check</param>
/// <returns></returns>
public bool KeyDown(Keys key)
{
// check if a key is down regardless of current/past state
return KeyboardState.IsKeyDown(key);
}
/// <summary>
/// Don't examine last state just check if a key is down
/// </summary>
/// <param name="name">The name of the keybind.</param>
/// <returns></returns>
public bool KeyDown(string name)
{
if (!keybinds.ContainsKey(name)) return false;
foreach (var key in keybinds[name])
{
if (KeyboardState.IsKeyDown(key))
return true;
}
return false;
}
}
} |
//
// Taken from
// https://github.com/transceptor-technology/go-siridb-connector/blob/master/protomap.go
namespace Fantasista.siridb.protocol
{
public enum Protomap : byte
{
// CprotoReqQuery for sending queries
CprotoReqQuery = 0,
// CprotoReqInsert for sending inserts
CprotoReqInsert = 1,
// CprotoReqAuth for authentication
CprotoReqAuth = 2,
// CprotoReqPing for ping on the connection
CprotoReqPing = 3,
// CprotoReqInfo for requesting database info
CprotoReqInfo = 4,
// CprotoReqLoadDB for loading a new database
CprotoReqLoadDB = 5,
// CprotoReqRegisterServer for registering a new server
CprotoReqRegisterServer = 6,
// CprotoReqFileServers for requesting a server.dat file
CprotoReqFileServers = 7,
// CprotoReqFileUsers for requesting a users.dat file
CprotoReqFileUsers = 8,
// CprotoReqFileGroups for requesting a groups.dat file
CprotoReqFileGroups = 9,
//CprotoReqAdmin for a manage server request
CprotoReqAdmin = 32,
// CprotoResQuery on query response
CprotoResQuery = 0,
// CprotoResInsert on insert response
CprotoResInsert = 1,
// CprotoResAuthSuccess on authentication success
CprotoResAuthSuccess = 2,
// CprotoResAck on ack
CprotoResAck = 3,
// CprotoResInfo on database info response
CprotoResInfo = 4,
// CprotoResFile on request file response
CprotoResFile = 5,
//CprotoAckAdmin on successful manage server request
CprotoAckAdmin = 32,
//CprotoAckAdminData on successful manage server request with data
CprotoAckAdminData = 33,
// CprotoErrMsg general error
CprotoErrMsg = 64,
// CprotoErrQuery on query error
CprotoErrQuery = 65,
// CprotoErrInsert on insert error
CprotoErrInsert = 66,
// CprotoErrServer on server error
CprotoErrServer = 67,
// CprotoErrPool on server error
CprotoErrPool = 68,
// CprotoErrUserAccess on server error
CprotoErrUserAccess = 69,
// CprotoErr on server error
CprotoErr = 70,
// CprotoErrNotAuthenticated on server error
CprotoErrNotAuthenticated = 71,
// CprotoErrAuthCredentials on server error
CprotoErrAuthCredentials = 72,
// CprotoErrAuthUnknownDb on server error
CprotoErrAuthUnknownDb = 73,
// CprotoErrLoadingDb on server error
CprotoErrLoadingDb = 74,
// CprotoErrFile on server error
CprotoErrFile = 75,
// CprotoErrAdmin on manage server error with message
CprotoErrAdmin = 96,
// CprotoErrAdminInvalidRequest on invalid manage server request
CprotoErrAdminInvalidRequest = 97,
// AdminNewAccount for create a new manage server account
AdminNewAccount = 0,
// AdminChangePassword for changing a server account password
AdminChangePassword = 1,
// AdminDropAccount for dropping a server account
AdminDropAccount = 2,
// AdminNewDatabase for creating a new database
AdminNewDatabase = 3,
// AdminNewPool for expanding a database with a new pool
AdminNewPool = 4,
// AdminNewReplica for expanding a database with a new replica
AdminNewReplica = 5,
// AdminGetVersion for getting the siridb server version
AdminGetVersion = 64,
// AdminGetAccounts for getting all accounts on a siridb server
AdminGetAccounts = 65,
// AdminGetDatabases for getting all database running on a siridb server
AdminGetDatabases = 66
}
} |
/*
* Copyright (c) 2012 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using org.critterai.nav;
using org.critterai.nmgen;
namespace org.critterai.nmbuild.u3d.editor
{
/// <summary>
/// Undocumented class meant for internal use only. (Editor Only)
/// </summary>
[System.Serializable]
public sealed class BuildDataItem
{
/* Design notes:
*
* Odd design due to the need to support Unity serialization.
*
* Arrays are set to zero length at construction. Zero length represents an invalid
* state.
*
*/
internal const int EmptyId = -1;
internal const int ErrorId = -2;
internal const int QueuedId = -3;
internal const int InProgressId = -4;
/// <summary>
/// Undocumented.
/// </summary>
public int tileX;
/// <summary>
/// Undocumented.
/// </summary>
public int tileZ;
/// <summary>
/// Undocumented.
/// </summary>
public byte[] polyMesh;
/// <summary>
/// Undocumented.
/// </summary>
public byte[] detailMesh;
/// <summary>
/// Undocumented.
/// </summary>
public byte[] bakedTile;
/// <summary>
/// Undocumented.
/// </summary>
public int bakedPolyCount;
/// <summary>
/// Undocumented.
/// </summary>
public byte[] workingTile;
/// <summary>
/// Undocumented.
/// </summary>
public int workingPolyCount;
internal TileBuildState TileState
{
get
{
if (workingPolyCount < 0)
{
// Special informational state.
switch (workingPolyCount)
{
case EmptyId:
return TileBuildState.Empty;
case QueuedId:
return TileBuildState.Queued;
case InProgressId:
return TileBuildState.InProgress;
case ErrorId:
return TileBuildState.Error;
}
}
if (workingTile.Length == 0)
{
if (bakedTile.Length == 0)
return TileBuildState.NotBuilt;
else
return TileBuildState.Baked;
}
return TileBuildState.Built;
}
}
internal BuildDataItem(int tx, int tz)
{
tileX = tx;
tileZ = tz;
Reset();
}
internal void SetAsEmpty()
{
ClearUnbaked();
workingPolyCount = EmptyId;
}
internal void ClearUnbaked()
{
polyMesh = new byte[0];
detailMesh = new byte[0];
workingTile = new byte[0];
workingPolyCount = 0; // This clears special states.
}
internal void SetAsFailed()
{
ClearUnbaked();
workingPolyCount = ErrorId;
}
internal void SetAsQueued()
{
ClearUnbaked();
workingPolyCount = QueuedId;
}
internal void SetAsInProgress()
{
ClearUnbaked();
workingPolyCount = InProgressId;
}
internal void SetWorkingData(PolyMesh polyMesh, PolyMeshDetail detailMesh)
{
if (polyMesh == null
|| polyMesh.PolyCount == 0)
{
SetAsEmpty();
return;
}
this.polyMesh = polyMesh.GetSerializedData(false);
if (detailMesh == null)
this.detailMesh = new byte[0];
else
this.detailMesh = detailMesh.GetSerializedData(false);
}
internal void SetWorkingData(NavmeshTileData tile, int polyCount)
{
if (tile == null || polyCount <= 0)
{
SetAsEmpty();
return;
}
workingTile = tile.GetData();
workingPolyCount = polyCount;
}
internal bool SetAsBaked(byte[] tile, int polyCount)
{
if (tile == null || tile.Length == 0 || polyCount <= 0)
{
return false;
}
ClearUnbaked();
bakedTile = tile;
bakedPolyCount = polyCount;
return true;
}
internal bool SetAsBaked()
{
if (workingTile.Length > 0)
{
bakedTile = workingTile;
bakedPolyCount = workingPolyCount;
ClearUnbaked();
return true;
}
workingPolyCount = 0; // Clears all special states.
return false;
}
internal void Reset()
{
polyMesh = new byte[0];
detailMesh = new byte[0];
workingTile = new byte[0];
workingPolyCount = 0;
bakedTile = new byte[0];
bakedPolyCount = 0;
}
}
}
|
using System;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using ModernRonin.PraeterArtem.Functional;
using ModernRonin.Standard;
using ModernRonin.Terrarium.Logic;
namespace SimulationView
{
public class Renderer : IDisposable
{
readonly DrawingContext mContext;
readonly Size mRenderSize;
readonly Vector2D mScalingFactor;
readonly SimulationState mSimulationState;
public Renderer(DrawingGroup drawingGroup, Size renderSize, SimulationState simulationState)
{
mContext = drawingGroup.Open();
mRenderSize = renderSize;
mSimulationState = simulationState;
mScalingFactor = mSimulationState.Size.ScaleTo(mRenderSize);
}
public void Dispose()
{
mContext.Close();
}
public void Render()
{
mContext.DrawRectangle(Brushes.Black, null, new Rect(mRenderSize));
mSimulationState.Entities.UseIn(Draw);
}
void Draw(Entity entity)
{
void drawRectangle(FilledRectangle rectangle)
{
mContext.DrawRectangle(rectangle.Brush, null, rectangle.Rectangle);
}
entity.Parts.Select(p => ToRectangle(p, entity.Position)).UseIn(drawRectangle);
}
FilledRectangle ToRectangle(Part part, Vector2D origin)
{
var position = (origin + part.RelativePosition).ScaleBy(mScalingFactor);
return new FilledRectangle
{
Brush = ToColor(part.Kind),
Rectangle = new Rect(position.ToPoint(), mScalingFactor.ToSize())
};
}
static Brush ToColor(PartKind kind)
{
switch (kind)
{
case PartKind.Core:
return Brushes.Aquamarine;
case PartKind.Absorber:
return Brushes.LightGreen;
case PartKind.Store:
return Brushes.BurlyWood;
default:
throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
}
}
class FilledRectangle
{
public Rect Rectangle { get; set; }
public Brush Brush { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRealEstate.Core;
using Shouldly;
namespace OpenRealEstate.Testing
{
public static class ListingAssertHelpers
{
public static void AssertCommonData(Listing source,
Listing destination)
{
source.ShouldNotBeNull();
destination.ShouldNotBeNull();
source.AgencyId.ShouldBe(destination.AgencyId);
source.Id.ShouldBe(destination.Id);
source.CreatedOn.ShouldBe(destination.CreatedOn);
source.StatusType.ShouldBe(destination.StatusType);
source.SourceStatus.ShouldBe(destination.SourceStatus, StringCompareShould.IgnoreCase);
source.Description.ShouldBe(destination.Description);
source.Title.ShouldBe(destination.Title);
AssertAddress(source.Address, destination.Address);
AssertAgents(source.Agents, destination.Agents);
AssertFeatures(source.Features, destination.Features);
AssertMedia(source.FloorPlans, destination.FloorPlans);
AssertMedia(source.Images, destination.Images);
AssertInspections(source.Inspections, destination.Inspections);
AssertLandDetails(source.LandDetails, destination.LandDetails);
AssertLinks(source.Links, destination.Links);
AssertMedia(source.Videos, destination.Videos);
}
public static void AssertAddress(Address source,
Address destination)
{
if (source == null &&
destination == null)
{
return;
}
source.ShouldNotBeNull();
destination.ShouldNotBeNull();
source.StreetNumber.ShouldBe(destination.StreetNumber);
source.Street.ShouldBe(destination.Street);
source.Suburb.ShouldBe(destination.Suburb);
source.Municipality.ShouldBe(destination.Municipality);
source.State.ShouldBe(destination.State);
source.CountryIsoCode.ShouldBe(destination.CountryIsoCode);
source.Postcode.ShouldBe(destination.Postcode);
source.Latitude.ShouldBe(destination.Latitude);
source.Longitude.ShouldBe(destination.Longitude);
source.DisplayAddress.ShouldBe(destination.DisplayAddress);
}
public static void AssertAgents(IList<Agent> source,
IList<Agent> destination)
{
if (source == null &&
destination == null)
{
return;
}
destination.Count.ShouldBe(destination.Count);
for (var i = 0; i < destination.Count; i++)
{
source[i].Name.ShouldBe(destination[i].Name);
source[i].Order.ShouldBe(destination[i].Order);
source[i].Communications.Count.ShouldBe(destination[i].Communications.Count);
for (var j = 0; j < destination[i].Communications.Count; j++)
{
AssertCommunication(source[i].Communications[j], destination[i].Communications[j]);
}
}
}
public static void AssertCommunication(Communication source,
Communication destination)
{
if (source == null &&
destination == null)
{
return;
}
source.CommunicationType.ShouldBe(destination.CommunicationType);
source.Details.ShouldBe(destination.Details);
}
public static void AssertInspections(IList<Inspection> source,
IList<Inspection> destination)
{
if (source == null &&
destination == null)
{
return;
}
for (var i = 0; i < destination.Count; i++)
{
source[i].OpensOn.ShouldBe(destination[i].OpensOn);
source[i].ClosesOn.ShouldBe(destination[i].ClosesOn);
}
}
public static void AssertFeatures(Features source,
Features destination)
{
if (source == null &&
destination == null)
{
return;
}
source.Bedrooms.ShouldBe(destination.Bedrooms);
source.Bathrooms.ShouldBe(destination.Bathrooms);
source.Ensuites.ShouldBe(destination.Ensuites);
source.Toilets.ShouldBe(destination.Toilets);
source.LivingAreas.ShouldBe(destination.LivingAreas);
AssertTags(source.Tags, destination.Tags);
AssertCarParking(source.CarParking, destination.CarParking);
}
public static void AssertCarParking(CarParking source,
CarParking destination)
{
if (source == null &&
destination == null)
{
return;
}
source.Garages.ShouldBe(destination.Garages);
source.Carports.ShouldBe(destination.Carports);
source.OpenSpaces.ShouldBe(destination.OpenSpaces);
}
public static void AssertTags(ICollection<string> source,
IEnumerable<string> destination)
{
if (source == null &&
destination == null)
{
return;
}
var missingTags = destination.Except(source, StringComparer.OrdinalIgnoreCase).ToList();
if (missingTags.Any())
{
var errorMessage =
$"Failed to parse - the following tags haven't been handled: {string.Join(", ", missingTags)}.";
throw new Exception(errorMessage);
}
}
public static void AssertMedia(IList<Media> source,
IList<Media> destination)
{
if (source == null &&
destination == null)
{
return;
}
for (var i = 0; i < destination.Count; i++)
{
source[i].Url.ShouldBe(destination[i].Url);
source[i].Order.ShouldBe(destination[i].Order);
source[i].CreatedOn.ShouldBe(destination[i].CreatedOn);
source[i].Tag.ShouldBe(destination[i].Tag);
}
}
public static void AssertLandDetails(LandDetails source,
LandDetails destination)
{
if (source == null &&
destination == null)
{
return;
}
UnitOfMeasureAssertHelpers.AssertUnitOfMeasure(source.Area, destination.Area);
source.CrossOver.ShouldBe(destination.CrossOver);
for (var i = 0; i < destination.Sides.Count; i++)
{
AssertSides(source.Sides[i], destination.Sides[i]);
}
}
public static void AssertSides(Side source,
Side destination)
{
if (source == null &&
destination == null)
{
return;
}
source.Name.ShouldBe(destination.Name);
UnitOfMeasureAssertHelpers.AssertUnitOfMeasure(source, destination);
}
public static void AssertLinks(IList<string> source,
IList<string> destination)
{
if (source == null &&
destination == null)
{
return;
}
destination.Count.ShouldBe(destination.Count);
for (var i = 0; i < destination.Count; i++)
{
source[i].ShouldBe(destination[i]);
}
}
}
}
|
// // Copyright (c) Dennis Aikara. All rights reserved.
// // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Zel.Classes;
namespace Zel
{
public class Result<T>
{
public Result(T value)
{
Value = value;
ValidationList = new ValidationList();
}
public Result(ValidationList validationList)
{
if (validationList == null)
{
throw new ArgumentNullException("validationList");
}
ValidationList = validationList;
}
public T Value { get; private set; }
public ValidationList ValidationList { get; }
public bool IsValid
{
get { return (ValidationList == null) || ValidationList.IsValid; }
}
}
} |
namespace CName.PName.SName
{
public static class SNameErrorCodes
{
// Add your business exception error codes here...
public const string GroupName = "SName:4004";
public static class Demo
{
public const string DemoNotFound = GroupName + "101";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class LiftFloor : MonoBehaviour
{
[SerializeField] string _DisplayName;
[SerializeField] string SupportedTag = "Player";
[SerializeField] LiftController LinkedController;
[SerializeField] Transform LiftTarget;
Animator LinkedAnimator;
public string DisplayName => _DisplayName;
public float TargetY => LiftTarget.position.y;
public bool LiftPresent => LinkedController.ActiveLift.CurrentFloor == this;
List<GameObject> Openers = new List<GameObject>();
private void Awake()
{
LinkedAnimator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(SupportedTag))
{
Openers.Add(other.gameObject);
if (LiftPresent)
{
LinkedAnimator.ResetTrigger("Close");
LinkedAnimator.SetTrigger("Open");
LinkedController.ActiveLift.OpenDoors();
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag(SupportedTag))
{
Openers.Remove(other.gameObject);
LinkedAnimator.ResetTrigger("Open");
LinkedAnimator.SetTrigger("Close");
LinkedController.ActiveLift.CloseDoors();
}
}
public void OnCallLiftForUp()
{
LinkedController.CallLift(this, true);
}
public void OnCallLiftForDown()
{
LinkedController.CallLift(this, false);
}
public void OnLiftDeparted(Lift activeLift)
{
LinkedAnimator.ResetTrigger("Open");
LinkedAnimator.SetTrigger("Close");
LinkedController.ActiveLift.CloseDoors();
}
public void OnLiftArrived(Lift activeLift)
{
if (Openers.Count > 0)
{
LinkedAnimator.ResetTrigger("Close");
LinkedAnimator.SetTrigger("Open");
LinkedController.ActiveLift.OpenDoors();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace HelperAndToolsForTest.IO
{
/// <summary>
/// Determines equality of path strings.
/// </summary>
public class PathEqualityComparer : IEqualityComparer<string>
{
/// <summary>Equality comparer implementation for two string rappresentative for path</summary>
/// <param name="x">Path A</param>
/// <param name="y">Path B</param>
/// <returns>True if equal</returns>
public bool Equals(string x, string y)
{
return PathUtils.ArePathsEqual(x, y);
}
/// <summary>Hashcode For equalit implementation comparer</summary>
/// <param name="obj"></param>
/// <returns>Hash of equailty object value</returns>
public int GetHashCode(string obj)
{
if (string.IsNullOrWhiteSpace(obj))
return 0;
else
return Path.GetFullPath(obj).GetHashCode();
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using Nmro.Shared.Services;
namespace Nmro.Shared
{
public static class DependencyInjection
{
public static IServiceCollection AddCommonServices(this IServiceCollection services)
=> services.AddTransient<IDateTime, MachineDateTime>();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UIButton : MonoBehaviour
{
[SerializeField] private GameObject targetObject;
[SerializeField] private string targetMessage;
//public Color highlightColor = Color.cyan;
/*public void OnMouseEnter()
{
SpriteRenderer sprite = this.gameObject.GetComponent<SpriteRenderer>();
if (sprite != null)
sprite.color = this.highlightColor;
}*/
/*public void OnMouseExit()
{
SpriteRenderer sprite = this.gameObject.GetComponent<SpriteRenderer>();
if (sprite != null)
sprite.color = Color.white;
}*/
/*public void OnMouseDown()
{
this.gameObject.GetComponent<RectTransform>().parent.localScale = new Vector3(0.9f, 0.9f, 0.9f);
}*/
/*public void OnMouseUp()
{
this.gameObject.GetComponent<RectTransform>().parent.localScale = new Vector3(0.9f, 0.9f, 0.9f);
//this.gameObject.GetComponent<RectTransform>().sizeDelta.Scale(Vector2.one);
if (this.targetObject != null)
this.targetObject.SendMessage(this.targetMessage);
}*/
public void OnMouseClick()
{
SceneManager.LoadScene("Main Menu");
/*if (this.targetObject != null)
this.targetObject.SendMessage(this.targetMessage);*/
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
using JupiterCapstone.DTO.Admin;
using JupiterCapstone.DTO.UserDTO;
using JupiterCapstone.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace JupiterCapstone.Services.IService
{
public interface ICategory
{
Task<IEnumerable<ViewCategoryDto>> GetAllCategoriesAsync();
Task<bool> AddCategoryAsync(List<AddCategoryDto> categoriesToAdd);
Task<bool> UpdateCategoryAsync(List<UpdateCategoryDto> categoriesToUpdate);
Task DeleteCategoryAsync(List<string> categoriesToDelete);
}
}
|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Linq;
using Adxstudio.Xrm.Web.Mvc;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Web.UI.WebForms;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Site.Controls
{
public class WebFormPortalUserControl : WebFormPortalViewUserControl
{
private readonly Lazy<OrganizationServiceContext> _xrmContext;
public WebFormPortalUserControl()
{
_xrmContext = new Lazy<OrganizationServiceContext>(CreateXrmServiceContext);
}
public OrganizationServiceContext XrmContext
{
get { return _xrmContext.Value; }
}
public IPortalContext Portal
{
get { return PortalCrmConfigurationManager.CreatePortalContext(PortalName); }
}
public OrganizationServiceContext ServiceContext
{
get { return Portal.ServiceContext; }
}
public Entity Website
{
get { return Portal.Website; }
}
public Entity Contact
{
get { return Portal.User; }
}
public Entity Entity
{
get { return Portal.Entity; }
}
private OrganizationServiceContext CreateXrmServiceContext()
{
return PortalCrmConfigurationManager.CreateServiceContext(PortalName);
}
private enum WebFormStepMode
{
Insert = 100000000,
Edit = 100000001,
ReadOnly = 100000002
}
protected EntityReference GetTargetEntityReference()
{
if (CurrentStepEntityID != Guid.Empty)
{
return new EntityReference(CurrentStepEntityLogicalName, CurrentStepEntityID);
}
var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(PortalName);
var step = serviceContext.CreateQuery("adx_webformstep")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webformstepid") == WebForm.CurrentSessionHistory.CurrentStepId);
if (step == null)
{
return null;
}
var mode = step.GetAttributeValue<OptionSetValue>("adx_mode");
if (mode != null && mode.Value != (int)WebFormStepMode.Insert)
{
return null;
}
var entity = new Entity(CurrentStepEntityLogicalName);
serviceContext.AddObject(entity);
if (SetEntityReference && !string.IsNullOrEmpty(EntityReferenceTargetEntityName) && EntityReferenceTargetEntityID != Guid.Empty)
{
var populateLookupAttribute = step.GetAttributeValue<bool?>("adx_populateentityreferencelookupfield").GetValueOrDefault();
var referenceLookupAttribute = step.GetAttributeValue<string>("adx_referencetargetlookupattributelogicalname");
if (populateLookupAttribute && !string.IsNullOrWhiteSpace(referenceLookupAttribute))
{
entity[referenceLookupAttribute] = new EntityReference(EntityReferenceTargetEntityName, EntityReferenceTargetEntityID);
}
else if (!string.IsNullOrEmpty(EntityReferenceRelationshipName) && !string.IsNullOrEmpty(EntityReferenceTargetEntityPrimaryKeyName))
{
var source = serviceContext.CreateQuery(EntityReferenceTargetEntityName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(EntityReferenceTargetEntityPrimaryKeyName) == EntityReferenceTargetEntityID);
if (source != null)
{
serviceContext.AddLink(source, new Relationship(EntityReferenceRelationshipName), entity);
}
}
}
var associateCurrentPortalUser = step.GetAttributeValue<bool?>("adx_associatecurrentportaluser").GetValueOrDefault();
var portalUserLookupAttribute = step.GetAttributeValue<string>("adx_targetentityportaluserlookupattribute");
if (associateCurrentPortalUser && !string.IsNullOrEmpty(portalUserLookupAttribute) && Contact != null)
{
entity[portalUserLookupAttribute] = Contact.ToEntityReference();
}
serviceContext.SaveChanges();
var reference = entity.ToEntityReference();
UpdateEntityDefinition(new Adxstudio.Xrm.Web.UI.WebForms.WebFormEntitySourceDefinition(reference.LogicalName, CurrentStepEntityPrimaryKeyLogicalName, reference.Id));
return reference;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace TicTacToe.Library.Models
{
public class GameData
{
public enum GameStates
{
PlayerOneMove,
PlayerTwoMove,
GameOver_PlayerOneWins,
GameOver_PlayerTwoWins,
GameOver_Draw,
None
}
public string PlayerOneName { get; set; }
public string PlayerTwoName { get; set; }
public string PlayerOneCharacterId { get; set; }
public string PlayerTwoCharacterId { get; set; }
public bool PlayerOneIsAI { get; set; }
public bool PlayerTwoIsAI { get; set; }
public GameStates GameState { get; set; }
public int GamesPlayed { get; set; }
public TicTacToe.Board GameBoard { get; set; }
public List<string> AISmackTalkPhrases;
public List<string> AILostPhrases;
public List<string> AIWonPhrases;
public List<string> AIDrawPhrases;
}
}
|
using shootandRun1.Abstracts.Movements;
using shootandRun1.Controllers;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using shootandRun1.Abstracts.Controllers;
namespace shootandRun1.Movements
{
public class MoveWithCharacterController : IMover
{
CharacterController _characterController;
public MoveWithCharacterController(IEntityController entityController)
{
_characterController = entityController.transform.GetComponent<CharacterController>();
}
public void MoveAction(Vector3 direction, float moveSpeed)
{
if (direction == Vector3.zero) return;
Vector3 worldPosition = _characterController.transform.TransformDirection(direction);
Vector3 movement = worldPosition * Time.deltaTime * moveSpeed;
_characterController.Move(movement);
}
}
} |
namespace Vurdalakov
{
using Nancy;
using Nancy.TinyIoc;
public class WebServiceBootstrapper : DefaultNancyBootstrapper
{
private WebServiceContext _webServiceContext;
public WebServiceBootstrapper(MainForm mainForm)
{
this._webServiceContext = new WebServiceContext(mainForm);
}
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
container.Register<WebServiceContext>(this._webServiceContext);
}
}
}
|
namespace CoreBoilerplate.Infrastructure
{
internal class InfrastructureLayer
{
}
} |
using System;
using FluentValidation;
namespace Prime.ViewModels.PaperEnrollees
{
public class PaperEnrolleeDemographicViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GivenNames { get; set; }
public DateTime DateOfBirth { get; set; }
public AddressViewModel PhysicalAddress { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string PhoneExtension { get; set; }
public string SmsPhone { get; set; }
}
public class PaperEnrolleeDemographicValidator : AbstractValidator<PaperEnrolleeDemographicViewModel>
{
public PaperEnrolleeDemographicValidator()
{
RuleFor(x => x.FirstName).NotEmpty();
RuleFor(x => x.LastName).NotEmpty();
RuleFor(x => x.DateOfBirth).NotEmpty();
RuleFor(x => x.PhysicalAddress).NotNull();
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Phone).NotEmpty();
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Checkout.ApiServices.SharedModels;
using FluentAssertions;
using System.Net;
using System.Collections.Generic;
namespace Tests
{
[TestFixture(Category = "ShoppingListApi")]
public class ShoppingListTests : BaseServiceTests
{
[TearDown]
public void TearDown()
{
CheckoutClient.ShoppingListService.ClearList();
}
[Test]
public void AddItem()
{
var response = CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct("Test Drink",2));
response.Should().NotBeNull();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
}
[Test]
public void GetItem()
{
var name = "Test";
CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct(name, 1));
var response = CheckoutClient.ShoppingListService.GetItem(name);
response.Should().NotBeNull();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.Model.Should().BeOfType(typeof(Product));
response.Model.Name.Should().Be("Test");
response.Model.Quantity.Should().Be(1);
}
[Test]
public void DeleteItem()
{
var name = "Test";
CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct(name, 1));
var response = CheckoutClient.ShoppingListService.DeleteItem(name);
response.Should().NotBeNull();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
}
[Test]
public void UpdateItem()
{
var name = "Test";
CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct(name, 1));
var response = CheckoutClient.ShoppingListService.UpdateItem(new Product() { Name = name, Quantity = 5 });
response.Should().NotBeNull();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
}
[Test]
public void GetList()
{
CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct("Test_Product", 2));
CheckoutClient.ShoppingListService.AddItem(TestHelper.CreateTestProduct("Test_Product_2", 10));
var response = CheckoutClient.ShoppingListService.GetList();
response.Should().NotBeNull();
response.HttpStatusCode.Should().Be(HttpStatusCode.OK);
response.Model.Should().BeOfType(typeof(List<Product>));
response.Model.Count.Should().Be(2);
}
}
}
|
using gView.DataSources.Fdb.MSAccess;
using gView.Framework.Data;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.DataSources.Fdb.UI.MSSql
{
public partial class FormRepairSpatialIndexProgress : Form
{
private gView.DataSources.Fdb.MSAccess.AccessFDB _fdb;
private IFeatureClass _fc;
private bool _finished = true;
private Task _processTask = null;
public FormRepairSpatialIndexProgress(gView.DataSources.Fdb.MSAccess.AccessFDB fdb, IFeatureClass fc)
{
InitializeComponent();
_fdb = fdb;
_fc = fc;
if (_fc != null)
{
this.Text += ": " + _fc.Name;
}
}
private void FormRepairSpatialIndexProgress_Load(object sender, EventArgs e)
{
}
private void FormRepairSpatialIndexProgress_Shown(object sender, EventArgs e)
{
if (_fdb != null && _fc != null)
{
_finished = false;
_processTask = Process();
}
else
{
this.Close();
}
}
private void FormRepairSpatialIndexProgress_FormClosing(object sender, FormClosingEventArgs e)
{
if (!_finished)
{
e.Cancel = true;
}
}
// Thread
async private Task Process()
{
if (!await _fdb.RepairSpatialIndex(_fc.Name, new EventHandler(ProcessEventHandler)))
{
MessageBox.Show(_fdb.LastErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_finished = true;
ProcessEventHandler(this, new EventArgs());
}
private void ProcessEventHandler(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
EventHandler d = new EventHandler(ProcessEventHandler);
this.Invoke(d, new object[] { sender, e });
}
else
{
if (sender == this)
{
btnClose.Enabled = true;
this.Refresh();
}
else if (e is RepairSICheckNodes)
{
if(((RepairSICheckNodes)e).Pos == 1)
{
this.Refresh();
}
if (((RepairSICheckNodes)e).Pos == ((RepairSICheckNodes)e).Count ||
((RepairSICheckNodes)e).Pos % 100 == 0)
{
if (progressBar1.Maximum != ((RepairSICheckNodes)e).Count)
{
progressBar1.Maximum = ((RepairSICheckNodes)e).Count;
}
progressBar1.Value = Math.Min(progressBar1.Maximum, ((RepairSICheckNodes)e).Pos);
plabel1.Text = progressBar1.Value + "/" + progressBar1.Maximum;
if (((RepairSICheckNodes)e).WrongNIDs != progressBar2.Maximum)
{
progressBar2.Maximum = ((RepairSICheckNodes)e).WrongNIDs;
plabel2.Text = "0/" + progressBar2.Maximum;
}
progressBar1.Refresh();
plabel1.Refresh();
plabel2.Refresh();
}
}
else if (e is RepairSIUpdateNodes)
{
if (((RepairSIUpdateNodes)e).Pos == ((RepairSIUpdateNodes)e).Count ||
((RepairSIUpdateNodes)e).Pos % 100 == 0)
{
if (progressBar2.Maximum != ((RepairSIUpdateNodes)e).Count)
{
progressBar2.Maximum = ((RepairSIUpdateNodes)e).Count;
}
progressBar2.Value = Math.Min(progressBar2.Maximum, ((RepairSIUpdateNodes)e).Pos);
plabel2.Text = progressBar2.Value + "/" + progressBar2.Maximum;
if (((RepairSIUpdateNodes)e).Count % 100 == 0)
{
progressBar2.Refresh();
plabel2.Refresh();
}
}
}
}
}
}
} |
using System;
using System.Linq;
using Plugin.AppShortcuts;
using Plugin.AppShortcuts.Icons;
using Xamarin.Forms;
namespace AppShortcutsFormsSample
{
public partial class App : Application
{
public const string AppShortcutUriBase = "asfs://appshortcutsformssample/";
public const string ShortcutOption1 = "DETAIL1";
public const string ShortcutOption2 = "DETAIL2";
public App()
{
AddShortcuts();
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
async void AddShortcuts()
{
if (CrossAppShortcuts.IsSupported)
{
var shortCurts= await CrossAppShortcuts.Current.GetShortcuts();
if (shortCurts.FirstOrDefault(prop => prop.Label == "Detail")==null)
{
var shortcut = new Shortcut()
{
Label = "Detail",
Description = "Go to Detail",
Icon = new ContactIcon(),
Uri = $"{AppShortcutUriBase}{ShortcutOption1}"
};
await CrossAppShortcuts.Current.AddShortcut(shortcut);
}
if (shortCurts.FirstOrDefault(prop => prop.Label == "Detail 2") == null)
{
var shortcut = new Shortcut()
{
Label = "Detail 2",
Description = "Go to Detail 2",
Icon = new UpdateIcon(),
Uri = $"{AppShortcutUriBase}{ShortcutOption2}"
};
await CrossAppShortcuts.Current.AddShortcut(shortcut);
}
}
}
protected override void OnAppLinkRequestReceived(Uri uri)
{
var option = uri.ToString().Replace(AppShortcutUriBase, "");
if (!string.IsNullOrEmpty(option))
{
MainPage = new NavigationPage(new MainPage());
switch (option)
{
case ShortcutOption1:
MainPage.Navigation.PushAsync(new DetailPage());
break;
case ShortcutOption2:
MainPage.Navigation.PushAsync(new Detail2Page());
break;
}
}
else
base.OnAppLinkRequestReceived(uri);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace GCL.Syntax.Data
{
public class NodeArea : HashSet<Element>
{
private int hashCode = 0;
public NodeArea()
{
}
public NodeArea(IEnumerable<Element> collection) : base(collection)
{
}
public override int GetHashCode()
{
if (this.hashCode == 0)
this.hashCode = this.Aggregate(0, (current, element) => current ^ (486187739 & element.GetHashCode()));
return this.hashCode;
}
public override bool Equals(object obj)
{
if (obj == null || (obj is NodeArea) == false)
return false;
var otherNodeArea = obj as NodeArea;
return SetEquals(otherNodeArea);
}
public static bool operator ==(NodeArea n1, NodeArea n2)
{
if ((object) n1 == null || (object) n2 == null)
return false;
return n1.Equals(n2);
}
public static bool operator !=(NodeArea n1, NodeArea n2)
{
return !(n1 == n2);
}
public override string ToString()
{
return $"Count = {Count}";
}
}
}
|
namespace CurrencyExchanger.DL.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
/// <summary>
/// An class to map the response from the third-party service of get lastest convertion tax.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class ExchangerApiResponseModel
{
/// <summary>
/// Gets or sets a value indicating whether is success.
/// </summary>
[JsonProperty("success")]
public bool Success { get; set; }
/// <summary>
/// Gets or sets a value to timestamp of the ExchangerApiResponseModel.
/// </summary>
[JsonProperty("timestamp")]
public double Timestamp { get; set; }
/// <summary>
/// Gets or sets a value to base currency symbol of the ExchangerApiResponseModel.
/// </summary>
[JsonProperty("base")]
public string Base { get; set; }
/// <summary>
/// Gets or sets a value to date of the ExchangerApiResponseModel.
/// </summary>
[JsonProperty("date")]
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets a value to rates of destination currency symbol of the ExchangerApiResponseModel.
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> Rates { get; set; }
/// <summary>
/// Gets or sets a value to rate of destination currency symbol of the ExchangerApiResponseModel.
/// </summary>
public decimal Rate { get; set; }
/// <summary>
/// Gets or sets a value to error of the ExchangerApiResponseModel.
/// </summary>
[JsonProperty("error")]
public ExchangerApiErrorResponseModel Error { get; set; }
}
} |
using System.Collections;
using FourRoads.TelligentCommunity.Splash.Interfaces;
namespace FourRoads.TelligentCommunity.Splash.Extensions
{
public class SplashExtension
{
private ISplashLogic _splashLogic;
public SplashExtension(ISplashLogic splashLogic)
{
_splashLogic = splashLogic;
}
public string GetUserListDownloadUrl()
{
return _splashLogic.GetUserListDownloadUrl();
}
public string ValidateAndHashAccessCode(string password)
{
return _splashLogic.ValidateAndHashAccessCode(password);
}
public bool SaveDetails(string email , IDictionary additionalFields)
{
return _splashLogic.SaveDetails(email, additionalFields);
}
}
} |
// -----------------------------------------------------------------------------
// <copyright file=”OctaneGherkinReportFileManager.cs" company=”Microfocus, Inc”>
//
// Copyright (c) Microfocus, Inc. 2006-2017. All Rights Reserved.
//
// This computer software is Licensed Material belonging to Microfocus.
// It is considered a trade secret and not to be used or divulged by parties
// who have not received written authorization from Microfocus.
//
// This file and its contents are protected by United States and
// International copyright laws. Unauthorized reproduction and/or
// distribution of all or any portion of the code contained herein
// is strictly prohibited and will result in severe civil and criminal
// penalties. Any violations of this copyright will be prosecuted
// to the fullest extent possible under law.
//
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.
//
// </copyright>
// ----------------------------------------------------------------------------
using SpecFlow.ALMOctane.GherkinResults;
namespace SBM.OctaneGherkinResults.SpecFlowPlugin
{
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using NLog;
public class OctaneGherkinReportFileManager
{
public String ResultsFileNamePostfix = "OctaneGherkinResults.xml";
public String ResultsFolder = "gherkin-results";
public String ErrorPrefix = "<HPEAlmOctaneGherkinFormatter Error>";
public String XmlVersion = "1";
private static readonly Logger log = LogManager.GetCurrentClassLogger();
public OctaneGherkinReportFileManager()
{
this.OctaneSpecflowReport = new OctaneSpecflowFormat();
this.OctaneSpecflowReport.Version = this.XmlVersion;
}
public OctaneSpecflowFormat OctaneSpecflowReport { get; set; }
public FeatureElement CurrentFeature { get; set; }
public ScenarioElement CurrentScenario { get; set; }
public StepElement CurrentStep { get; set; }
public static long GetStartUnixTime()
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((DateTime.UtcNow.ToUniversalTime() - epoch).TotalSeconds);
}
#region Writing xml content into file
public void UpdateCurrentFeatureWithFileContent(string featureFilePath, string fullFeatureFilePath)
{
try
{
if (this.CurrentFeature != null && this.OctaneSpecflowReport != null)
{
if (string.IsNullOrEmpty(this.CurrentFeature.Path))
{
var featureFileContent = string.Empty;
if (!string.IsNullOrEmpty(featureFilePath) & !string.IsNullOrEmpty(fullFeatureFilePath))
{
log.Debug("Read feature file " + fullFeatureFilePath);
featureFileContent = File.ReadAllText(fullFeatureFilePath);
log.Debug("File content: " + featureFileContent);
}
this.CurrentFeature.Path = featureFilePath;
this.CurrentFeature.FileContentString = featureFileContent;
}
}
}
catch (Exception ex)
{
log.Warn(ex);
}
}
public void WriteToXml(string testResultsDirectory)
{
log.Trace(MethodBase.GetCurrentMethod().Name);
log.Debug(this.OctaneSpecflowReport);
try
{
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
var xmlSerializer = new XmlSerializer(typeof(OctaneSpecflowFormat));
if (!string.IsNullOrEmpty(testResultsDirectory))
{
log.Trace("Results directory: " + testResultsDirectory);
var fileName = string.Format("{0}\\{1}\\{2}", testResultsDirectory, this.ResultsFolder,
this.ResultsFileNamePostfix);
var resultsDir = Path.GetDirectoryName(fileName);
if (!Directory.Exists(resultsDir))
{
Directory.CreateDirectory(resultsDir);
}
log.Info("Saving results to file: " + fileName);
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
{
xmlSerializer.Serialize(fs, this.OctaneSpecflowReport, ns);
}
}
}
catch (IOException ex)
{
log.Error(ex);
Console.WriteLine(this.ErrorPrefix + "IO exception: {0}", ex.Message);
}
catch (SerializationException ex)
{
log.Error(ex);
Console.WriteLine(this.ErrorPrefix + "Serialization exception: {0}", ex.Message);
}
catch (Exception ex)
{
log.Fatal(ex);
Console.WriteLine(this.ErrorPrefix + ex);
}
}
#endregion
}
}
|
using System.Runtime.Serialization;
namespace SocialApis.Twitter
{
[DataContract]
public class TwitterErrorContainer
{
[DataMember(Name = "errors")]
public TwitterError[] Errors { get; private set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.