content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Data;
using Common;
using Entity;
namespace Service
{
[ServiceContract]
public interface IStudent
{
[OperationContract]
List<Student> GetInfo(string strWhere);
[OperationContract]
bool Add(Student model);
[OperationContract]
bool Update(Student model);
[OperationContract]
bool Delete(int id);
[OperationContract]
bool Exist(int id);
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
namespace FastRange;
public interface IRangeSearch<TObject, TIndex>
where TIndex : IComparable
{
Task<CheckResult> CheckAsync(Action<IRangeCheck<TIndex>> check, CancellationToken cancellationToken);
Task AddAsync(TObject toAdd, IRangeElement<TIndex> range, CancellationToken cancellationToken);
Task AddAsync(TObject toAdd, CancellationToken cancellationToken, params IRangeElement<TIndex>[] ranges);
Task AddAsync(TObject toAdd, TIndex floor, TIndex ceiling, CancellationToken cancellationToken);
Task AddAsync(TObject toAdd, CancellationToken cancellationToken, params (TIndex floor, TIndex ceiling)[] ranges);
Task<FindResult<TObject>> FindAsync(TIndex index, CancellationToken cancellationToken);
Task<FindOneResult<TObject>> FindOneAsync(TIndex index, CancellationToken cancellationToken);
} |
namespace SprinklerApi.AppLogic
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AzureBlob;
using Configuration;
using Models;
public class DataBackupRestoreLogic
{
private readonly AzureBlobClient _azureBlobClient;
private readonly IConfig _config;
private readonly string _dbFileName = "sprinklers";
private readonly string _dbFileExtension = "db";
public DataBackupRestoreLogic(
IConfig config,
AzureBlobClient azureBlobClient)
{
_config = config;
_azureBlobClient = azureBlobClient;
}
public async Task<StandardResponse<string>> BackupDb()
{
var result = new StandardResponse<string>();
var spDbFullPath = Path.GetFullPath(_config.DataLocationRelativeToBin());
if (File.Exists(spDbFullPath))
{
using (var stream = File.Open(spDbFullPath, FileMode.Open))
{
var fileName = $"{_dbFileName}_{DateTime.Now:yyyy-dd-M--HH-mm-ss}.{_dbFileExtension}";
await _azureBlobClient.SaveFile(
fileName: fileName,
containerName: _config.BlobContainerName(),
stream: stream);
result.Payload = fileName;
}
}
else
{
result.ValidationMessages = new List<string>() { $"File not found: {spDbFullPath}" };
}
return result;
}
public async Task<StandardResponse<string>> RestoreFromBlob(string fileName)
{
var result = await _azureBlobClient.RestoreFromCloud(
containerName: _config.BlobContainerName(),
fileName: fileName,
saveAsPathAndFileName: Path.GetFullPath(_config.DataLocationRelativeToBin()));
return result;
}
}
}
|
using System;
using AutoMapper.Configuration;
using DeviceManager.Api.Data.Model;
using DeviceManager.Api.Model;
namespace DeviceManager.Api.Mappings
{
/// <summary>
/// Contains objects mapping
/// </summary>
/// <seealso cref="AutoMapper.Configuration.MapperConfigurationExpression" />
public class MapsProfile : MapperConfigurationExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="MapsProfile"/> class
/// </summary>
public MapsProfile()
{
// Device ViewModel To Device
this.CreateMap<DeviceViewModel, Device>()
.ForMember(dest => dest.DeviceTitle, opt => opt.MapFrom(src => src.Title))
.ForMember(dest => dest.DeviceCode, opt => opt.MapFrom(src => src.DeviceCode))
.ForMember(dest => dest.DeviceId, opt => opt.MapFrom(src => Guid.NewGuid()))
.ForMember(dest => dest.DeviceGroup, opt => opt.MapFrom(src => src));
// Device ViewModel to DeviceDetail
this.CreateMap<DeviceViewModel, DeviceGroup>()
.ForMember(dest => dest.DeviceGroupId, opt => opt.MapFrom(src => Guid.NewGuid()))
.ForMember(dest => dest.Company, opt => opt.MapFrom(src => src.Company))
.ForMember(dest => dest.OperatingSystem, opt => opt.MapFrom(src => src.OperatingSystem));
// Maps Device to Device ViewModel
this.CreateMap<Device, DeviceViewModel>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.DeviceId))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.DeviceTitle))
.ForMember(dest => dest.DeviceCode, opt => opt.MapFrom(src => src.DeviceCode))
.AfterMap((src, dest, context) => context.Mapper.Map(src.DeviceGroup, dest));
// Maps Device Group to Device ViewModel
this.CreateMap<DeviceGroup, DeviceViewModel>()
.ForMember(dest => dest.Company, opt => opt.MapFrom(src => src.Company))
.ForMember(dest => dest.OperatingSystem, opt => opt.MapFrom(src => src.OperatingSystem));
}
}
}
|
using UnityEngine;
using TMPro;
using System.Collections.Generic;
namespace IronManUI {
public static class IMExtensions {
public static AbstractIMComponent GetIronManComponent(this Collider collider) {
return collider.gameObject.GetComponent<AbstractIMComponent>();
}
public static AbstractIMComponent GetIronManComponent(this Collision collision) {
return collision.gameObject.GetComponent<AbstractIMComponent>();
}
public static void DestroyAllGameObjects<T>(this T[] toDestroy) where T : Object {
foreach (var o in toDestroy)
Object.Destroy(o);
}
public static void DestroyChildren(this GameObject o) {
var t = o.transform;
bool editMode = Application.isEditor && !Application.isPlaying;
int count = t.childCount;
for (int i=0; i<count; i++) {
var child = t.GetChild(i).gameObject;
// child.transform.parent = null;
if (editMode)
Object.DestroyImmediate(child);
else
Object.Destroy(child.gameObject);
}
}
//TODO Needs TLC
public static Bounds GetBounds(this GameObject o) {
Bounds bounds = new Bounds();
int i = 0;
foreach (var renderer in o.GetComponentsInChildren<MeshRenderer>()) {
if (i++ == 0)
bounds = renderer.bounds;
else
bounds.Encapsulate(renderer.bounds);
}
foreach (var renderer in o.GetComponentsInChildren<TextMeshPro>()) {
if (i++ == 0)
bounds = renderer.bounds;
else
bounds.Encapsulate(renderer.bounds);
}
return bounds;
}
public static Vector3 MinValue(this Vector3 v, float min) {
var outV = v;
if (outV.x < min) outV.x = min;
if (outV.y < min) outV.y = min;
if (outV.z < min) outV.z = min;
return outV;
}
}
} |
namespace BohoTours.Services.Data.Transports
{
using System.Collections.Generic;
using System.Linq;
using BohoTours.Data.Common.Repositories;
using BohoTours.Data.Models;
using BohoTours.Services.Mapping;
public class TransportsService : ITransportsService
{
private readonly IDeletableEntityRepository<Transport> transportsRepository;
public TransportsService(IDeletableEntityRepository<Transport> transportsRepository)
{
this.transportsRepository = transportsRepository;
}
public IEnumerable<T> GetAll<T>()
{
return this.transportsRepository.AllAsNoTracking().To<T>().ToList();
}
}
}
|
using EIS.AppBase;
using System;
using System.Runtime.CompilerServices;
namespace EIS.WebBase.ModelLib.Model
{
public class BBSTopic : AppModelBase
{
public string AttachId
{
get;
set;
}
public string BBSType
{
get;
set;
}
public string BizId
{
get;
set;
}
public string BizName
{
get;
set;
}
public string Content
{
get;
set;
}
public string DeptName
{
get;
set;
}
public string EmpName
{
get;
set;
}
public string Enable
{
get;
set;
}
public DateTime? EndTime
{
get;
set;
}
public DateTime? LastUpdateTime
{
get;
set;
}
public string NmEnable
{
get;
set;
}
public int ReplyCount
{
get;
set;
}
public DateTime? StartTime
{
get;
set;
}
public string State
{
get;
set;
}
public string Title
{
get;
set;
}
public string ToDeptId
{
get;
set;
}
public string ToDeptName
{
get;
set;
}
public string ToUserId
{
get;
set;
}
public string ToUserName
{
get;
set;
}
public BBSTopic()
{
}
public BBSTopic(UserContext user)
{
base._AutoID = Guid.NewGuid().ToString();
base._UserName = user.EmployeeId;
base._OrgCode = user.DeptWbs;
base._IsDel = 0;
base._CreateTime = DateTime.Now;
base._UpdateTime = DateTime.Now;
base._CompanyID = user.CompanyId;
}
}
} |
@page
@model Swrith.Pages.IndexModel
@{
ViewData["Title"] = "Home page";
}
<partial name="Shared/_PostsDisplay.cshtml"/>
<div class="pagination-display">
@if(Model.CurrentPage != 1)
{
<a class="recent-articles" asp-route-pageNumber=@Model.OldPage>Newer stories</a>
}
@if(Model.TotalPages > Model.CurrentPage)
{
<a class="old-articles" asp-route-pageNumber=@Model.NextPage>Older stories</a>
}
</div> |
using JumpingFrog.Interfaces;
namespace JumpingFrog.Rules
{
internal class GreenFrogSlideRule : IRules
{
int Space = 0;
int BrownFrog = 2;
public bool FollowThisRule(List<int> state, int turnIndex)
{
int Last = state.Count - 1;
if (Last != turnIndex && state[turnIndex + 1] == Space)
return true;
else if (Last != turnIndex && Last - 1 != turnIndex && state[turnIndex + 2] == Space)
return true;
return false;
}
}
}
|
<!--Manage the user account details GUI-->
@{
ViewBag.Title = "ManageAccount";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="home">
<!--banner and breadcrums-->
<div class="home_overlay"></div>
<div class="home_content d-flex flex-column align-items-center justify-content-center">
<h2>User Profile</h2>
</div>
</div>
<ul class="breadcrumb">
<li><a href="@Url.Action("Index", "Home")">Home</a></li>
<li class="active">Profile</li>
</ul>
<div class="container body-content">
<br />
@Html.Partial("_UserDetailsForm") <!--User information form-->
</div> |
using Xunit;
using HelpDesk.Core.ArchitecturalUtilities;
using HelpDesk.Core.BusinessLayer;
using HelpDesk.Core.Interface;
using HelpDesk.Core.Mock.DataRepository;
namespace HelpDesk.Core.Test;
public class MainBusinessLayerTests
{
[Fact]
public void InstantiateBusinessLayer()
{
DependencyInjector.Register<ITicketRepository, MockTicketRepository>();
var bl = new MainBusinessLayer();
Assert.NotNull(bl);
}
} |
using System;
using MediatR;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Application.Commands.TriageDataLocks
{
public sealed class TriageDataLocksCommand : IRequest
{
public long ApprenticeshipId { get; set; }
public TriageStatus TriageStatus { get; set; }
public UserInfo UserInfo { get; set; }
public TriageDataLocksCommand(long apprenticeshipId, TriageStatus triageStatus, UserInfo userInfo)
{
ApprenticeshipId = apprenticeshipId;
TriageStatus = triageStatus;
UserInfo = userInfo ?? throw new ArgumentNullException(nameof(userInfo));
}
}
}
|
#if WINDOWS_CERTIFICATE_STORE_SUPPORT
#nullable disable
using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Calamari.Integration.Certificates.WindowsNative
{
internal static class WindowsX509Native
{
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern SafeCertStoreHandle CertOpenStore(CertStoreProviders lpszStoreProvider, IntPtr notUsed,
IntPtr notUsed2, CertificateSystemStoreLocation location, [MarshalAs(UnmanagedType.LPWStr)] string storeName);
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern bool CertCloseStore(IntPtr hCertStore, int dwFlags);
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern SafeCertStoreHandle PFXImportCertStore(ref CryptoData pPfx,
[MarshalAs(UnmanagedType.LPWStr)] string szPassword, PfxImportFlags dwFlags);
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore,
SafeCertContextHandle pCertContext, AddCertificateDisposition dwAddDisposition, ref IntPtr ppStoreContext);
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore,
CertificateEncodingType dwCertEncodingType, IntPtr notUsed, CertificateFindType dwFindType,
ref CryptoData pvFindPara, IntPtr pPrevCertContext);
[DllImport("Crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext);
[DllImport("Crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
public static extern int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, [In] ref CertNameStringType pvPara, [Out] StringBuilder pszNameString, int cchNameString);
[DllImport("Crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CertCompareCertificateName(CertificateEncodingType dwCertEncodingType,
ref CryptoData pCertName1, ref CryptoData pCertName2);
[DllImport("Crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CertGetCertificateContextProperty(IntPtr pCertContext, CertificateProperty dwPropId,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] pvData, [In, Out] ref int pcbData);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CryptAcquireContextW")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptAcquireContext(out IntPtr psafeProvHandle,
[MarshalAs(UnmanagedType.LPWStr)] string pszContainer,
[MarshalAs(UnmanagedType.LPWStr)] string pszProvider,
int dwProvType, CryptAcquireContextFlags dwFlags);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptGetProvParam(SafeCspHandle hProv, CspProperties dwParam, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbData, ref int pdwDataLen, SecurityDesciptorParts dwFlags);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptSetProvParam(SafeCspHandle hProv, CspProperties dwParam, [In] byte[] pbData, SecurityDesciptorParts dwFlags);
[DllImport("Crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert,
AcquireCertificateKeyOptions dwFlags,
IntPtr pvReserved, // void *
[Out] out SafeCspHandle phCryptProvOrNCryptKey,
[Out] out int dwKeySpec,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
[DllImport("Crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert,
AcquireCertificateKeyOptions dwFlags,
IntPtr pvReserved, // void *
[Out] out SafeNCryptKeyHandle phCryptProvOrNCryptKey,
[Out] out int dwKeySpec,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pfCallerFreeProvOrNCryptKey);
[DllImport("Crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern
bool CertEnumSystemStore(CertificateSystemStoreLocation dwFlags, IntPtr notUsed1, IntPtr notUsed2,
CertEnumSystemStoreCallBackProto fn);
/// <summary>
/// signature of call back function used by CertEnumSystemStore
/// </summary>
internal delegate
bool CertEnumSystemStoreCallBackProto(
[MarshalAs(UnmanagedType.LPWStr)] string storeName, uint dwFlagsNotUsed, IntPtr notUsed1,
IntPtr notUsed2, IntPtr notUsed3);
[DllImport("Ncrypt.dll", SetLastError = true, ExactSpelling = true)]
internal static extern int NCryptGetProperty(SafeNCryptHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string szProperty, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbOutput, int cbOutput, ref int pcbResult, int flags);
[DllImport("Ncrypt.dll", SetLastError = true, ExactSpelling = true)]
internal static extern int NCryptSetProperty(SafeNCryptHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string szProperty, IntPtr pbInputByteArray, int cbInput, int flags);
[DllImport("Ncrypt.dll")]
internal static extern int NCryptDeleteKey(SafeNCryptKeyHandle hKey, int flags);
[Flags]
internal enum CertStoreProviders
{
CERT_STORE_PROV_SYSTEM = 10
}
internal enum AddCertificateDisposition
{
CERT_STORE_ADD_NEW = 1,
CERT_STORE_ADD_REPLACE_EXISTING = 3
}
internal enum CertificateSystemStoreLocation
{
CurrentUser = 1 << 16, // CERT_SYSTEM_STORE_CURRENT_USER
LocalMachine = 2 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE
CurrentService = 4 << 16, // CERT_SYSTEM_STORE_CURRENT_SERVICE
Services = 5 << 16, // CERT_SYSTEM_STORE_SERVICES
Users = 6 << 16, // CERT_SYSTEM_STORE_USERS
UserGroupPolicy = 7 << 16, // CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
MachineGroupPolicy = 8 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
LocalMachineEnterprise = 9 << 16, // CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE
}
internal enum CertificateFindType
{
Sha1Hash = 1 << 16 // CERT_FIND_SHA1_HASH
}
[Flags]
internal enum CertificateEncodingType
{
X509AsnEncoding = 0x00000001, // X509_ASN_ENCODING
Pkcs7AsnEncoding = 0x00010000, // PKCS_7_ASN_ENCODING
Pkcs7OrX509AsnEncoding = X509AsnEncoding | Pkcs7AsnEncoding
}
internal enum CertNameType
{
CERT_NAME_EMAIL_TYPE = 1,
CERT_NAME_RDN_TYPE = 2,
CERT_NAME_ATTR_TYPE = 3,
CERT_NAME_SIMPLE_DISPLAY_TYPE = 4,
CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5,
CERT_NAME_DNS_TYPE = 6,
CERT_NAME_URL_TYPE = 7,
CERT_NAME_UPN_TYPE = 8,
}
[Flags]
internal enum CertNameFlags
{
None = 0x00000000,
CERT_NAME_ISSUER_FLAG = 0x00000001,
}
[Flags]
internal enum CertNameStringType
{
CERT_X500_NAME_STR = 3,
CERT_NAME_STR_REVERSE_FLAG = 0x02000000,
}
// CRYPTOAPI_BLOB
[StructLayout(LayoutKind.Sequential)]
public struct CryptoData
{
public int cbData;
public IntPtr pbData;
}
[StructLayout(LayoutKind.Sequential)]
internal struct KeyProviderInfo
{
[MarshalAs(UnmanagedType.LPWStr)] internal string pwszContainerName;
[MarshalAs(UnmanagedType.LPWStr)] internal string pwszProvName;
internal int dwProvType;
internal int dwFlags;
internal int cProvParam;
internal IntPtr rgProvParam; // PCRYPT_KEY_PROV_PARAM
internal int dwKeySpec;
}
[Flags]
public enum PfxImportFlags
{
CRYPT_EXPORTABLE = 0x00000001,
CRYPT_MACHINE_KEYSET = 0x00000020,
CRYPT_USER_KEYSET = 0x00001000,
PKCS12_PREFER_CNG_KSP = 0x00000100,
PKCS12_ALWAYS_CNG_KSP = 0x00000200
}
/// <summary>
/// Well known certificate property IDs
/// </summary>
public enum CertificateProperty
{
KeyProviderInfo = 2, // CERT_KEY_PROV_INFO_PROP_ID
KeyContext = 5, // CERT_KEY_CONTEXT_PROP_ID
}
/// <summary>
/// Flags for the CryptAcquireCertificatePrivateKey API
/// </summary>
[Flags]
internal enum AcquireCertificateKeyOptions
{
None = 0x00000000,
AcquireSilent = 0x00000040,
AcquireAllowNCryptKeys = 0x00010000, // CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG
AcquireOnlyNCryptKeys = 0x00040000, // CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG
}
[Flags]
internal enum CryptAcquireContextFlags
{
None = 0x00000000,
Delete = 0x00000010, // CRYPT_DELETEKEYSET
MachineKeySet = 0x00000020, // CRYPT_MACHINE_KEYSET
Silent = 0x40 // CRYPT_SILENT
}
public enum CspProperties
{
SecurityDescriptor = 0x8 // PP_KEYSET_SEC_DESCR
}
public static class NCryptProperties
{
public const string SecurityDescriptor = "Security Descr"; // NCRYPT_SECURITY_DESCR_PROPERTY
}
[Flags]
public enum NCryptFlags
{
Silent = 0x00000040,
}
public enum SecurityDesciptorParts
{
DACL_SECURITY_INFORMATION = 0x00000004
}
public enum NCryptErrorCode
{
Success = 0x00000000, // ERROR_SUCCESS
BufferTooSmall = unchecked((int) 0x80090028), // NTE_BUFFER_TOO_SMALL
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_CONTEXT
{
public CertificateEncodingType dwCertEncodingType;
public IntPtr pbCertEncoded;
public int cbCertEncoded;
public IntPtr pCertInfo;
public IntPtr hCertStore;
}
public enum CapiErrorCode
{
CRYPT_E_EXISTS = unchecked((int) 0x80092005)
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_INFO
{
public int dwVersion;
public CryptoData SerialNumber;
public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
public CryptoData Issuer;
public FILETIME NotBefore;
public FILETIME NotAfter;
public CryptoData Subject;
public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo;
public CRYPT_BIT_BLOB IssuerUniqueId;
public CRYPT_BIT_BLOB SubjectUniqueId;
public int cExtension;
public IntPtr rgExtension;
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILETIME
{
private uint ftTimeLow;
private uint ftTimeHigh;
public DateTime ToDateTime()
{
long fileTime = (((long) ftTimeHigh) << 32) + ftTimeLow;
return DateTime.FromFileTime(fileTime);
}
public static FILETIME FromDateTime(DateTime dt)
{
long fileTime = dt.ToFileTime();
return new FILETIME()
{
ftTimeLow = (uint) fileTime,
ftTimeHigh = (uint) (fileTime >> 32),
};
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_PUBLIC_KEY_INFO
{
public CRYPT_ALGORITHM_IDENTIFIER Algorithm;
public CRYPT_BIT_BLOB PublicKey;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CRYPT_ALGORITHM_IDENTIFIER
{
public IntPtr pszObjId;
public CryptoData Parameters;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CRYPT_BIT_BLOB
{
public int cbData;
public IntPtr pbData;
public int cUnusedBits;
}
}
}
#endif |
namespace Messi.Endpoints
{
using System;
public interface IInputEndpoint
{
Messi.Message NextMessage();
}
}
|
using System;
using GB.IO;
namespace GB
{
public class Tile
{
private byte[] byteArr;
public Shade GetPixel(int x, int y)
{
byte pixelValOne = (byte)((byteArr[y*2] >> (7-x)) & 1);
byte pixelValTwo = (byte)((byteArr[(y*2)+1] >> (7-x)) & 1);
return (Shade)((pixelValOne << 1) | pixelValTwo);
}
public Tile(byte[] tileMemArray)
{
byteArr = tileMemArray;
}
}
} |
namespace Naos.Foundation.Domain
{
public enum OrderDirection
{
Ascending = 10,
Descending = 20
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
/// <summary>Equality comparer for hashsets of hashsets</summary>
internal sealed class HashSetEqualityComparer<T> : IEqualityComparer<HashSet<T>?>
{
public bool Equals(HashSet<T>? x, HashSet<T>? y)
{
// If they're the exact same instance, they're equal.
if (ReferenceEquals(x, y))
{
return true;
}
// They're not both null, so if either is null, they're not equal.
if (x == null || y == null)
{
return false;
}
EqualityComparer<T> defaultComparer = EqualityComparer<T>.Default;
// If both sets use the same comparer, they're equal if they're the same
// size and one is a "subset" of the other.
if (HashSet<T>.EqualityComparersAreEqual(x, y))
{
return x.Count == y.Count && y.IsSubsetOfHashSetWithSameComparer(x);
}
// Otherwise, do an O(N^2) match.
foreach (T yi in y)
{
bool found = false;
foreach (T xi in x)
{
if (defaultComparer.Equals(yi, xi))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
public int GetHashCode(HashSet<T>? obj)
{
int hashCode = 0; // default to 0 for null/empty set
if (obj != null)
{
foreach (T t in obj)
{
if (t != null)
{
hashCode ^= t.GetHashCode(); // same hashcode as as default comparer
}
}
}
return hashCode;
}
// Equals method for the comparer itself.
public override bool Equals([NotNullWhen(true)] object? obj) => obj is HashSetEqualityComparer<T>;
public override int GetHashCode() => EqualityComparer<T>.Default.GetHashCode();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Repo1.Core.ns11.Configuration;
using Repo1.Core.ns11.R1Models.D8Models;
using Repo1.Core.ns11.R1Models.D8Models.D8ViewsLists;
using Repo1.WPF45.SDK.Archivers;
using Repo1.WPF45.SDK.Clients;
using Repo1.WPF45.SDK.ErrorHandlers;
using Repo1.WPF45.SDK.Extensions.R1ModelExtensions;
using Repo1.D8Uploader.Lib45.FileIO;
using Repo1.WPF45.SDK.Extensions.FileInfoExtensions;
namespace Repo1.D8Uploader.Lib45.RestClients
{
public class UploaderClient2 : D8SvcStackClientBase
{
private List<string> _partPaths;
private List<R1PackagePart> _pkgParts;
private R1Package _package;
private PackagePartUploader _partUploadr;
public UploaderClient2(RestServerCredentials restServerCredentials) : base(restServerCredentials)
{
OnError = ex => ThreadedAlerter.Show(ex, "Uploader Client 2");
_partUploadr = new PackagePartUploader(restServerCredentials);
}
public async Task<R1Package> GetPackage(string packageFilename)
{
Status = "Querying uploadables for this user ...";
var list = await ViewsList<UploadablesForUserView>();
if (list == null) return null;
var exe = list.SingleOrDefault(x => x.FileName == packageFilename);
return exe;
}
public async Task<bool> UploadInParts(R1Package localPkg, double maxVolumeSizeMB)
{
var tmpCopy = CopyToTemp(localPkg.FullPathOrURL);
_package = localPkg;
_partPaths = await SevenZipper1.Compress(tmpCopy, null, maxVolumeSizeMB, ".data");
_pkgParts = new List<R1PackagePart>();
for (int i = 0; i < _partPaths.Count; i++)
{
var ok = await UploadPartByIndex(i);
if (!ok) return false;
}
return true;
}
private async Task<bool> UploadPartByIndex(int partIndex)
{
var path = _partPaths[partIndex];
var part = LocalFile.AsR1PackagePart(path);
part.PartNumber = partIndex + 1;
part.TotalParts = _partPaths.Count;
part.Package = _package;
part.PackageVersion = _package.LatestVersion;
part.FullPathOrURL = path;
//return await _partUploadr.UploadAndAttachToNewNode(part);
return await _partUploadr.SavePartNode(part);
}
public Task<bool> Edit(R1Package remotePkg, string versionChanges)
{
throw new NotImplementedException();
}
private string CopyToTemp(string filePath)
{
var uniq = "R1_Uploading_" + DateTime.Now.Ticks;
var tmpD = Path.Combine(Path.GetTempPath(), uniq);
Directory.CreateDirectory(tmpD);
var fNme = Path.GetFileName(filePath);
var path = Path.Combine(tmpD, fNme);
File.Copy(filePath, path, true);
return path;
}
}
}
|
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.Text;
namespace LambdaForum.Common.Models
{
public class Post : Entity, IHasCreationTime
{
public string Title { get; set; }
public string Content { get; set; }
public DateTime CreationTime { get; set; }
//Navigation Properties
//Posted By user
public virtual ApplicationUser User { get; set; }
public virtual Forum Forum { get; set; }
//To retreive the replies.
public virtual IEnumerable<PostReply> Replies { get; set; }
public Post()
{
CreationTime = DateTime.Now;
}
}
}
|
namespace StrawberryShake.CodeGeneration.CSharp
{
public class CSharpDocument
{
public CSharpDocument(string name, string source)
{
Name = name;
SourceText = source;
}
public string Name { get; }
public string SourceText { get; }
}
}
|
using System;
namespace UnicornHack.Utils
{
public struct TransientReference<T> : IDisposable where T : IReferenceable
{
public TransientReference(T referenced)
{
referenced.AddReference();
Referenced = referenced;
}
public T Referenced { get; private set; }
public void Dispose()
{
Referenced?.RemoveReference();
Referenced = default;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Newtonsoft.Json;
namespace Gov.Lclb.Cllb.Interfaces.GeoCoder
{
public partial class GeocoderClient
{
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
namespace DocumentFormat.OpenXml.Office.ActiveX
{
/// <summary>
/// <para>Defines the ActiveXControlData Class.</para>
/// <para>This class is available in Office 2007 or above.</para>
/// <para> When the object is serialized out as xml, its qualified name is ax:ocx.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>ActiveXObjectProperty <ax:ocxPr></description></item>
/// </list>
/// </remarks>
[ChildElementInfo(typeof(ActiveXObjectProperty))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "3.0")]
[OfficeAvailability(FileFormatVersions.Office2007)]
public partial class ActiveXControlData : OpenXmlCompositeElement
{
internal const int ElementTypeIdConst = 12688;
/// <inheritdoc/>
public override string LocalName => "ocx";
internal override byte NamespaceId => 35;
internal override int ElementTypeId => ElementTypeIdConst;
internal override FileFormatVersions InitialVersion => FileFormatVersions.Office2007;
private static readonly ReadOnlyArray<AttributeTag> s_attributeTags = new []
{
AttributeTag.Create<StringValue>(35, "classid"),
AttributeTag.Create<StringValue>(35, "license"),
AttributeTag.Create<StringValue>(19, "id"),
AttributeTag.Create<EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues>>(35, "persistence")
};
internal override AttributeTagCollection RawAttributes { get; } = new AttributeTagCollection(s_attributeTags);
/// <summary>
/// <para> classid.</para>
/// <para>Represents the following attribute in the schema: ax:classid </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "classid")]
public StringValue ActiveXControlClassId
{
get { return (StringValue)Attributes[0].Value; }
set { Attributes[0].Value = value; }
}
/// <summary>
/// <para> license.</para>
/// <para>Represents the following attribute in the schema: ax:license </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "license")]
public StringValue License
{
get { return (StringValue)Attributes[1].Value; }
set { Attributes[1].Value = value; }
}
/// <summary>
/// <para> id.</para>
/// <para>Represents the following attribute in the schema: r:id </para>
/// </summary>
///<remark> xmlns:r=http://schemas.openxmlformats.org/officeDocument/2006/relationships
///</remark>
[SchemaAttr(19, "id")]
public StringValue Id
{
get { return (StringValue)Attributes[2].Value; }
set { Attributes[2].Value = value; }
}
/// <summary>
/// <para> persistence.</para>
/// <para>Represents the following attribute in the schema: ax:persistence </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "persistence")]
public EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues> Persistence
{
get { return (EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues>)Attributes[3].Value; }
set { Attributes[3].Value = value; }
}
/// <summary>
/// Initializes a new instance of the ActiveXControlData class.
/// </summary>
public ActiveXControlData():base(){}
/// <summary>
///Initializes a new instance of the ActiveXControlData class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public ActiveXControlData(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the ActiveXControlData class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public ActiveXControlData(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the ActiveXControlData class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public ActiveXControlData(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 35 == namespaceId && "ocxPr" == name)
return new ActiveXObjectProperty();
return null;
}
/// <inheritdoc/>
public override OpenXmlElement CloneNode(bool deep) => CloneImp<ActiveXControlData>(deep);
}
/// <summary>
/// <para>Defines the ActiveXObjectProperty Class.</para>
/// <para>This class is available in Office 2007 or above.</para>
/// <para> When the object is serialized out as xml, its qualified name is ax:ocxPr.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>SharedComFont <ax:font></description></item>
///<item><description>SharedComPicture <ax:picture></description></item>
/// </list>
/// </remarks>
[ChildElementInfo(typeof(SharedComFont))]
[ChildElementInfo(typeof(SharedComPicture))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "3.0")]
[OfficeAvailability(FileFormatVersions.Office2007)]
public partial class ActiveXObjectProperty : OpenXmlCompositeElement
{
internal const int ElementTypeIdConst = 12689;
/// <inheritdoc/>
public override string LocalName => "ocxPr";
internal override byte NamespaceId => 35;
internal override int ElementTypeId => ElementTypeIdConst;
internal override FileFormatVersions InitialVersion => FileFormatVersions.Office2007;
private static readonly ReadOnlyArray<AttributeTag> s_attributeTags = new []
{
AttributeTag.Create<StringValue>(35, "name"),
AttributeTag.Create<StringValue>(35, "value")
};
internal override AttributeTagCollection RawAttributes { get; } = new AttributeTagCollection(s_attributeTags);
/// <summary>
/// <para> name.</para>
/// <para>Represents the following attribute in the schema: ax:name </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "name")]
public StringValue Name
{
get { return (StringValue)Attributes[0].Value; }
set { Attributes[0].Value = value; }
}
/// <summary>
/// <para> value.</para>
/// <para>Represents the following attribute in the schema: ax:value </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "value")]
public StringValue Value
{
get { return (StringValue)Attributes[1].Value; }
set { Attributes[1].Value = value; }
}
/// <summary>
/// Initializes a new instance of the ActiveXObjectProperty class.
/// </summary>
public ActiveXObjectProperty():base(){}
/// <summary>
///Initializes a new instance of the ActiveXObjectProperty class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public ActiveXObjectProperty(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the ActiveXObjectProperty class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public ActiveXObjectProperty(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the ActiveXObjectProperty class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public ActiveXObjectProperty(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 35 == namespaceId && "font" == name)
return new SharedComFont();
if( 35 == namespaceId && "picture" == name)
return new SharedComPicture();
return null;
}
private static readonly string[] eleTagNames = { "font","picture" };
private static readonly byte[] eleNamespaceIds = { 35,35 };
internal override string[] ElementTagNames => eleTagNames;
internal override byte[] ElementNamespaceIds => eleNamespaceIds;
internal override OpenXmlCompositeType OpenXmlCompositeType => OpenXmlCompositeType.OneChoice;
/// <summary>
/// <para> SharedComFont.</para>
/// <para> Represents the following element tag in the schema: ax:font </para>
/// </summary>
/// <remark>
/// xmlns:ax = http://schemas.microsoft.com/office/2006/activeX
/// </remark>
public SharedComFont SharedComFont
{
get => GetElement<SharedComFont>(0);
set => SetElement(0, value);
}
/// <summary>
/// <para> SharedComPicture.</para>
/// <para> Represents the following element tag in the schema: ax:picture </para>
/// </summary>
/// <remark>
/// xmlns:ax = http://schemas.microsoft.com/office/2006/activeX
/// </remark>
public SharedComPicture SharedComPicture
{
get => GetElement<SharedComPicture>(1);
set => SetElement(1, value);
}
/// <inheritdoc/>
public override OpenXmlElement CloneNode(bool deep) => CloneImp<ActiveXObjectProperty>(deep);
}
/// <summary>
/// <para>Defines the SharedComFont Class.</para>
/// <para>This class is available in Office 2007 or above.</para>
/// <para> When the object is serialized out as xml, its qualified name is ax:font.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>ActiveXObjectProperty <ax:ocxPr></description></item>
/// </list>
/// </remarks>
[ChildElementInfo(typeof(ActiveXObjectProperty))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "3.0")]
[OfficeAvailability(FileFormatVersions.Office2007)]
public partial class SharedComFont : OpenXmlCompositeElement
{
internal const int ElementTypeIdConst = 12690;
/// <inheritdoc/>
public override string LocalName => "font";
internal override byte NamespaceId => 35;
internal override int ElementTypeId => ElementTypeIdConst;
internal override FileFormatVersions InitialVersion => FileFormatVersions.Office2007;
private static readonly ReadOnlyArray<AttributeTag> s_attributeTags = new []
{
AttributeTag.Create<EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues>>(35, "persistence"),
AttributeTag.Create<StringValue>(19, "id")
};
internal override AttributeTagCollection RawAttributes { get; } = new AttributeTagCollection(s_attributeTags);
/// <summary>
/// <para> persistence.</para>
/// <para>Represents the following attribute in the schema: ax:persistence </para>
/// </summary>
///<remark> xmlns:ax=http://schemas.microsoft.com/office/2006/activeX
///</remark>
[SchemaAttr(35, "persistence")]
public EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues> Persistence
{
get { return (EnumValue<DocumentFormat.OpenXml.Office.ActiveX.PersistenceValues>)Attributes[0].Value; }
set { Attributes[0].Value = value; }
}
/// <summary>
/// <para> id.</para>
/// <para>Represents the following attribute in the schema: r:id </para>
/// </summary>
///<remark> xmlns:r=http://schemas.openxmlformats.org/officeDocument/2006/relationships
///</remark>
[SchemaAttr(19, "id")]
public StringValue Id
{
get { return (StringValue)Attributes[1].Value; }
set { Attributes[1].Value = value; }
}
/// <summary>
/// Initializes a new instance of the SharedComFont class.
/// </summary>
public SharedComFont():base(){}
/// <summary>
///Initializes a new instance of the SharedComFont class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public SharedComFont(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the SharedComFont class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public SharedComFont(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the SharedComFont class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public SharedComFont(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 35 == namespaceId && "ocxPr" == name)
return new ActiveXObjectProperty();
return null;
}
/// <inheritdoc/>
public override OpenXmlElement CloneNode(bool deep) => CloneImp<SharedComFont>(deep);
}
/// <summary>
/// <para>Defines the SharedComPicture Class.</para>
/// <para>This class is available in Office 2007 or above.</para>
/// <para> When the object is serialized out as xml, its qualified name is ax:picture.</para>
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("DomGen", "3.0")]
[OfficeAvailability(FileFormatVersions.Office2007)]
public partial class SharedComPicture : OpenXmlLeafElement
{
internal const int ElementTypeIdConst = 12691;
/// <inheritdoc/>
public override string LocalName => "picture";
internal override byte NamespaceId => 35;
internal override int ElementTypeId => ElementTypeIdConst;
internal override FileFormatVersions InitialVersion => FileFormatVersions.Office2007;
private static readonly ReadOnlyArray<AttributeTag> s_attributeTags = new []
{
AttributeTag.Create<StringValue>(19, "id")
};
internal override AttributeTagCollection RawAttributes { get; } = new AttributeTagCollection(s_attributeTags);
/// <summary>
/// <para> id.</para>
/// <para>Represents the following attribute in the schema: r:id </para>
/// </summary>
///<remark> xmlns:r=http://schemas.openxmlformats.org/officeDocument/2006/relationships
///</remark>
[SchemaAttr(19, "id")]
public StringValue Id
{
get { return (StringValue)Attributes[0].Value; }
set { Attributes[0].Value = value; }
}
/// <summary>
/// Initializes a new instance of the SharedComPicture class.
/// </summary>
public SharedComPicture():base(){}
/// <inheritdoc/>
public override OpenXmlElement CloneNode(bool deep) => CloneImp<SharedComPicture>(deep);
}
/// <summary>
/// Defines the PersistenceValues enumeration.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public enum PersistenceValues
{
///<summary>
///persistPropertyBag.
///<para>When the item is serialized out as xml, its value is "persistPropertyBag".</para>
///</summary>
[EnumString("persistPropertyBag")]
PersistPropertyBag,
///<summary>
///persistStream.
///<para>When the item is serialized out as xml, its value is "persistStream".</para>
///</summary>
[EnumString("persistStream")]
PersistStream,
///<summary>
///persistStreamInit.
///<para>When the item is serialized out as xml, its value is "persistStreamInit".</para>
///</summary>
[EnumString("persistStreamInit")]
PersistStreamInit,
///<summary>
///persistStorage.
///<para>When the item is serialized out as xml, its value is "persistStorage".</para>
///</summary>
[EnumString("persistStorage")]
PersistStorage,
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Supermercado.API.Domain.Models;
namespace Supermercado.API.Domain.Services
{
public interface ICategoriaService
{
Task<IEnumerable<Categoria>> ListAsync();
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class exercicio_mecanica_1 : MonoBehaviour {
public string[] exe = new string[6];
public string[] responder = new string[2];
public Text[] alternativa = new Text[5];
public int numb, x,quest,aux,resultado_real,resultado_mostrado,contador;
public Text tela,valor,pergunta;
public GameObject fim,inicio;
public Animator anim;
void Start () {
contador = 0;
exe[0] = "x++";
exe[1] = "x+1";
exe[2] = "x--";
exe[3] = "x-1";
exe[4] = "++x";
exe[5] = "--x";
responder[0] = "Qual o valor mostrado ao usuário";
responder[1] = "Qual o valor de X";
anim = GetComponent<Animator>();
iniciar();
}
public void iniciar() {
valor.text = "valor de x = ";
numb = UnityEngine.Random.Range(0, 6);
tela.text = exe[numb];
x = UnityEngine.Random.Range(-10, 10);
valor.text += x.ToString();
quest = UnityEngine.Random.Range(0, 2);
pergunta.text = responder[quest];
opcao();
acertou();
}
public void opcao() {
aux = x - 2;
alternativa[0].text = aux.ToString();
aux = x - 1;
alternativa[1].text = aux.ToString();
aux = x;
alternativa[2].text = aux.ToString();
aux = x +1;
alternativa[3].text = aux.ToString();
aux = x +2;
alternativa[4].text = aux.ToString();
}
public void acertou(){
if (numb == 0) {
resultado_mostrado = x;
resultado_real = x + 1;
}
else if (numb == 1){
resultado_mostrado = x+1;
resultado_real = x;
}
else if (numb == 2)
{
resultado_mostrado = x;
resultado_real = x-1;
}
else if (numb == 3)
{
resultado_mostrado = x -1;
resultado_real = x;
}
else if (numb == 4)
{
resultado_mostrado = x + 1;
resultado_real = x+1;
}
else if (numb == 5)
{
resultado_mostrado = x - 1;
resultado_real = x-1;
}
}
}
|
namespace Stranne.BooliLib.Models
{
/// <summary>
/// Box coordinates.
/// </summary>
public class BoxCoordinates
{
/// <summary>
/// Gets or sets latitude south west.
/// </summary>
public double LatitudeSouthWest { get; set; }
/// <summary>
/// Gets or sets longitude south west.
/// </summary>
public double LongitudeSouthWest { get; set; }
/// <summary>
/// Gets or sets latitude north east.
/// </summary>
public double LatitudeNorthEast { get; set; }
/// <summary>
/// Gets or sets longitude north east.
/// </summary>
public double LongitudeNorthEast { get; set; }
/// <summary>
/// Gets or sets create a box coordinate.
/// </summary>
public BoxCoordinates()
{
}
/// <summary>
/// Create a box coordinate.
/// </summary>
/// <param name="latitudeSouthWest">Latitude south west.</param>
/// <param name="longitudeSouthWest">Longitude south west.</param>
/// <param name="latitudeNorthEast">Longitude north east.</param>
/// <param name="longitudeNorthEast">Longitude north east.</param>
public BoxCoordinates(
double latitudeSouthWest,
double longitudeSouthWest,
double latitudeNorthEast,
double longitudeNorthEast)
{
LatitudeSouthWest = latitudeSouthWest;
LongitudeSouthWest = longitudeSouthWest;
LatitudeNorthEast = latitudeNorthEast;
LongitudeNorthEast = longitudeNorthEast;
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace BBGamelib.flash.imp{
public class TagDefineMovie: TagDefineDisplay
{
ITag[] _tags;
public ITag[] tags{ get { return _tags; } }
int _maxDepth;
public int maxDepth{get{return _maxDepth;} }
Frame[] _frames;
public Frame[] frames{get{return _frames;} }
public TagDefineMovie(Flash flash, byte[] data, Cursor cursor):base(flash, data, cursor){
int tagsCount = Utils.ReadInt32 (data, cursor);
_tags = new ITag[tagsCount];
for (int i=0; i<tagsCount; i++) {
byte type = Utils.ReadByte(data, cursor);
if(type == TagPlaceObject.TYPE){
ITag tag = new TagPlaceObject(this.flash, data, cursor);
_tags[i] = tag;
}else if(type == TagRemoveObject.TYPE){
ITag tag = new TagRemoveObject(this.flash, data, cursor);
_tags[i] = tag;
}
}
_maxDepth = Utils.ReadInt32 (data, cursor);
int framesCount = Utils.ReadInt32 (data, cursor);
_frames = new Frame[framesCount];
for(int i = 0; i<framesCount; i++){
Frame frame = new Frame(i, data, cursor);
_frames[i] = frame;
}
}
public override string trace (int indent){
string indent0 = Utils.RepeatString(indent);
string s = base.trace (indent) + " MaxDepth: " + _maxDepth + "\n";
if (_frames.Length > 0) {
s += indent0 + "FrameCount(" + _frames.Length +"):\n";
for(int i=0; i<_frames.Length; i++){
Frame frame = _frames[i];
s += frame.trace(indent + 2) + "\n";
}
}
return s;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ImGuiNET;
public class ImGuiDemo : MonoBehaviour
{
private bool _show = false;
void toggle()
{
_show = !_show;
if(_show)
ImGuiUn.Layout += OnLayout;
else
ImGuiUn.Layout -= OnLayout;
}
public void Update()
{
if (Input.GetButtonDown("OpenIMGUIDemo"))
{
toggle();
}
}
void OnDisable()
{
if(_show)
ImGuiUn.Layout -= OnLayout;
}
void OnLayout()
{
ImGui.ShowMetricsWindow();
ImGui.ShowDemoWindow();
}
}
|
using System;
using AnotherCM.Library.Common;
using AnotherCM.Library.Import.Common;
namespace AnotherCM.Library.Import.Character {
public class Defenses {
private Stats stats;
public Defenses (Stats stats) {
if (stats == null) {
throw new ArgumentNullException("stats");
}
this.stats = stats;
}
public int ArmorClass { get { return this.stats["AC"]; } }
public int FortitudeDefense { get { return this.stats["Fortitude Defense"]; } }
public int ReflexDefense { get { return this.stats["Reflex Defense"]; } }
public int WillDefense { get { return this.stats["Will Defense"]; } }
public int this[Defense defense] {
get {
switch (defense) {
case Defense.AC:
return this.ArmorClass;
case Defense.Fortitude:
return this.FortitudeDefense;
case Defense.Reflex:
return this.ReflexDefense;
case Defense.Will:
return this.WillDefense;
default:
throw new ArgumentException("defense");;
}
}
}
}
}
|
namespace SizeMattersFishingLib.Spearfishing;
public enum SpearfishingRow
{
Row01,
Row02,
Row03
}
|
namespace IGDB.Models
{
public class GameVersionFeatureValue : IIdentifier, IHasChecksum
{
public string Checksum { get; set; }
public IdentityOrValue<Game> Game { get; set; }
public IdentityOrValue<GameVersionFeature> GameFeature { get; set; }
public long? Id { get; set; }
public IncludedFeature? IncludedFeature { get; set; }
public string Note { get; set; }
}
public enum IncludedFeature
{
NotIncluded = 0,
Included = 1,
PreOrderOnly = 2
}
} |
#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2012 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.Reflection;
using System.Runtime.Serialization;
namespace ImageProcessor
{
/// <summary>Clones objects using reflection</summary>
/// <remarks>
/// <para>
/// This type of cloning is a lot faster than cloning by serialization and
/// incurs no set-up cost, but requires cloned types to provide a default
/// constructor in order to work.
/// </para>
/// </remarks>
public class ReflectionCloner : ICloneFactory
{
/// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A shallow clone of the provided object</returns>
public static TCloned ShallowFieldClone<TCloned>(TCloned objectToClone)
{
Type originalType = objectToClone.GetType();
if (originalType.IsPrimitive || (originalType == typeof(string)))
{
return objectToClone; // Being value types, primitives are copied by default
}
else if (originalType.IsArray)
{
return (TCloned)shallowCloneArray(objectToClone);
}
else if (originalType.IsValueType)
{
return objectToClone; // Value types can be copied directly
}
else
{
return (TCloned)shallowCloneComplexFieldBased(objectToClone);
}
}
/// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A shallow clone of the provided object</returns>
public static TCloned ShallowPropertyClone<TCloned>(TCloned objectToClone)
{
Type originalType = objectToClone.GetType();
if (originalType.IsPrimitive || (originalType == typeof(string)))
{
return objectToClone; // Being value types, primitives are copied by default
}
else if (originalType.IsArray)
{
return (TCloned)shallowCloneArray(objectToClone);
}
else if (originalType.IsValueType)
{
return (TCloned)shallowCloneComplexPropertyBased(objectToClone);
}
else
{
return (TCloned)shallowCloneComplexPropertyBased(objectToClone);
}
}
/// <summary>
/// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A deep clone of the provided object</returns>
public static TCloned DeepFieldClone<TCloned>(TCloned objectToClone)
{
object objectToCloneAsObject = objectToClone;
if (objectToClone == null)
{
return default(TCloned);
}
else
{
return (TCloned)deepCloneSingleFieldBased(objectToCloneAsObject);
}
}
/// <summary>
/// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A deep clone of the provided object</returns>
public static TCloned DeepPropertyClone<TCloned>(TCloned objectToClone)
{
object objectToCloneAsObject = objectToClone;
if (objectToClone == null)
{
return default(TCloned);
}
else
{
return (TCloned)deepCloneSinglePropertyBased(objectToCloneAsObject);
}
}
/// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A shallow clone of the provided object</returns>
TCloned ICloneFactory.ShallowFieldClone<TCloned>(TCloned objectToClone)
{
if (typeof(TCloned).IsClass || typeof(TCloned).IsArray)
{
if (ReferenceEquals(objectToClone, null))
{
return default(TCloned);
}
}
return ReflectionCloner.ShallowFieldClone<TCloned>(objectToClone);
}
/// <summary>
/// Creates a shallow clone of the specified object, reusing any referenced objects
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A shallow clone of the provided object</returns>
TCloned ICloneFactory.ShallowPropertyClone<TCloned>(TCloned objectToClone)
{
if (typeof(TCloned).IsClass || typeof(TCloned).IsArray)
{
if (ReferenceEquals(objectToClone, null))
{
return default(TCloned);
}
}
return ReflectionCloner.ShallowPropertyClone<TCloned>(objectToClone);
}
/// <summary>
/// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A deep clone of the provided object</returns>
TCloned ICloneFactory.DeepFieldClone<TCloned>(TCloned objectToClone)
{
return ReflectionCloner.DeepFieldClone<TCloned>(objectToClone);
}
/// <summary>
/// Creates a deep clone of the specified object, also creating clones of all
/// child objects being referenced
/// </summary>
/// <typeparam name="TCloned">Type of the object that will be cloned</typeparam>
/// <param name="objectToClone">Object that will be cloned</param>
/// <returns>A deep clone of the provided object</returns>
TCloned ICloneFactory.DeepPropertyClone<TCloned>(TCloned objectToClone)
{
return ReflectionCloner.DeepPropertyClone<TCloned>(objectToClone);
}
/// <summary>Clones a complex type using field-based value transfer</summary>
/// <param name="original">Original instance that will be cloned</param>
/// <returns>A clone of the original instance</returns>
private static object shallowCloneComplexFieldBased(object original)
{
Type originalType = original.GetType();
#if (XBOX360 || WINDOWS_PHONE)
object clone = Activator.CreateInstance(originalType);
#else
object clone = FormatterServices.GetUninitializedObject(originalType);
#endif
FieldInfo[] fieldInfos = ClonerHelpers.GetFieldInfosIncludingBaseClasses(
originalType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
);
for (int index = 0; index < fieldInfos.Length; ++index)
{
FieldInfo fieldInfo = fieldInfos[index];
object originalValue = fieldInfo.GetValue(original);
if (originalValue != null)
{
// Everything's just directly assigned in a shallow clone
fieldInfo.SetValue(clone, originalValue);
}
}
return clone;
}
/// <summary>Clones a complex type using property-based value transfer</summary>
/// <param name="original">Original instance that will be cloned</param>
/// <returns>A clone of the original instance</returns>
private static object shallowCloneComplexPropertyBased(object original)
{
Type originalType = original.GetType();
object clone = Activator.CreateInstance(originalType);
PropertyInfo[] propertyInfos = originalType.GetProperties(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.FlattenHierarchy
);
for (int index = 0; index < propertyInfos.Length; ++index)
{
PropertyInfo propertyInfo = propertyInfos[index];
if (propertyInfo.CanRead && propertyInfo.CanWrite)
{
Type propertyType = propertyInfo.PropertyType;
object originalValue = propertyInfo.GetValue(original, null);
if (originalValue != null)
{
if (propertyType.IsPrimitive || (propertyType == typeof(string)))
{
// Primitive types can be assigned directly
propertyInfo.SetValue(clone, originalValue, null);
}
else if (propertyType.IsValueType)
{
// Value types are seen as part of the original type and are thus recursed into
propertyInfo.SetValue(clone, shallowCloneComplexPropertyBased(originalValue), null);
}
else if (propertyType.IsArray)
{ // Arrays are assigned directly in a shallow clone
propertyInfo.SetValue(clone, originalValue, null);
}
else
{ // Complex types are directly assigned without creating a copy
propertyInfo.SetValue(clone, originalValue, null);
}
}
}
}
return clone;
}
/// <summary>Clones an array using field-based value transfer</summary>
/// <param name="original">Original array that will be cloned</param>
/// <returns>A clone of the original array</returns>
private static object shallowCloneArray(object original)
{
return ((Array)original).Clone();
}
/// <summary>Copies a single object using field-based value transfer</summary>
/// <param name="original">Original object that will be cloned</param>
/// <returns>A clone of the original object</returns>
private static object deepCloneSingleFieldBased(object original)
{
Type originalType = original.GetType();
if (originalType.IsPrimitive || (originalType == typeof(string)))
{
return original; // Creates another box, does not reference boxed primitive
}
else if (originalType.IsArray)
{
return deepCloneArrayFieldBased((Array)original, originalType.GetElementType());
}
else
{
return deepCloneComplexFieldBased(original);
}
}
/// <summary>Clones a complex type using field-based value transfer</summary>
/// <param name="original">Original instance that will be cloned</param>
/// <returns>A clone of the original instance</returns>
private static object deepCloneComplexFieldBased(object original)
{
Type originalType = original.GetType();
#if (XBOX360 || WINDOWS_PHONE)
object clone = Activator.CreateInstance(originalType);
#else
object clone = FormatterServices.GetUninitializedObject(originalType);
#endif
FieldInfo[] fieldInfos = ClonerHelpers.GetFieldInfosIncludingBaseClasses(
originalType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
);
for (int index = 0; index < fieldInfos.Length; ++index)
{
FieldInfo fieldInfo = fieldInfos[index];
Type fieldType = fieldInfo.FieldType;
object originalValue = fieldInfo.GetValue(original);
if (originalValue != null)
{
// Primitive types can be assigned directly
if (fieldType.IsPrimitive || (fieldType == typeof(string)))
{
fieldInfo.SetValue(clone, originalValue);
}
else if (fieldType.IsArray)
{ // Arrays need to be cloned element-by-element
fieldInfo.SetValue(
clone,
deepCloneArrayFieldBased((Array)originalValue, fieldType.GetElementType())
);
}
else
{ // Complex types need to be cloned member-by-member
fieldInfo.SetValue(clone, deepCloneSingleFieldBased(originalValue));
}
}
}
return clone;
}
/// <summary>Clones an array using field-based value transfer</summary>
/// <param name="original">Original array that will be cloned</param>
/// <param name="elementType">Type of elements the original array contains</param>
/// <returns>A clone of the original array</returns>
private static object deepCloneArrayFieldBased(Array original, Type elementType)
{
if (elementType.IsPrimitive || (elementType == typeof(string)))
{
return original.Clone();
}
int dimensionCount = original.Rank;
// Find out the length of each of the array's dimensions, also calculate how
// many elements there are in the array in total.
var lengths = new int[dimensionCount];
int totalElementCount = 0;
for (int index = 0; index < dimensionCount; ++index)
{
lengths[index] = original.GetLength(index);
if (index == 0)
{
totalElementCount = lengths[index];
}
else
{
totalElementCount *= lengths[index];
}
}
// Knowing the number of dimensions and the length of each dimension, we can
// create another array of the exact same sizes.
Array clone = Array.CreateInstance(elementType, lengths);
// If this is a one-dimensional array (most common type), do an optimized copy
// directly specifying the indices
if (dimensionCount == 1)
{
// Clone each element of the array directly
for (int index = 0; index < totalElementCount; ++index)
{
object originalElement = original.GetValue(index);
if (originalElement != null)
{
clone.SetValue(deepCloneSingleFieldBased(originalElement), index);
}
}
}
else
{ // Otherwise use the generic code for multi-dimensional arrays
var indices = new int[dimensionCount];
for (int index = 0; index < totalElementCount; ++index)
{
// Determine the index for each of the array's dimensions
int elementIndex = index;
for (int dimensionIndex = dimensionCount - 1; dimensionIndex >= 0; --dimensionIndex)
{
indices[dimensionIndex] = elementIndex % lengths[dimensionIndex];
elementIndex /= lengths[dimensionIndex];
}
// Clone the current array element
object originalElement = original.GetValue(indices);
if (originalElement != null)
{
clone.SetValue(deepCloneSingleFieldBased(originalElement), indices);
}
}
}
return clone;
}
/// <summary>Copies a single object using property-based value transfer</summary>
/// <param name="original">Original object that will be cloned</param>
/// <returns>A clone of the original object</returns>
private static object deepCloneSinglePropertyBased(object original)
{
Type originalType = original.GetType();
if (originalType.IsPrimitive || (originalType == typeof(string)))
{
return original; // Creates another box, does not reference boxed primitive
}
else if (originalType.IsArray)
{
return deepCloneArrayPropertyBased((Array)original, originalType.GetElementType());
}
else
{
return deepCloneComplexPropertyBased(original);
}
}
/// <summary>Clones a complex type using property-based value transfer</summary>
/// <param name="original">Original instance that will be cloned</param>
/// <returns>A clone of the original instance</returns>
private static object deepCloneComplexPropertyBased(object original)
{
Type originalType = original.GetType();
object clone = Activator.CreateInstance(originalType);
PropertyInfo[] propertyInfos = originalType.GetProperties(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.FlattenHierarchy
);
for (int index = 0; index < propertyInfos.Length; ++index)
{
PropertyInfo propertyInfo = propertyInfos[index];
if (propertyInfo.CanRead && propertyInfo.CanWrite)
{
Type propertyType = propertyInfo.PropertyType;
object originalValue = propertyInfo.GetValue(original, null);
if (originalValue != null)
{
if (propertyType.IsPrimitive || (propertyType == typeof(string)))
{
// Primitive types can be assigned directly
propertyInfo.SetValue(clone, originalValue, null);
}
else if (propertyType.IsArray)
{ // Arrays need to be cloned element-by-element
propertyInfo.SetValue(
clone,
deepCloneArrayPropertyBased((Array)originalValue, propertyType.GetElementType()),
null
);
}
else
{ // Complex types need to be cloned member-by-member
propertyInfo.SetValue(clone, deepCloneSinglePropertyBased(originalValue), null);
}
}
}
}
return clone;
}
/// <summary>Clones an array using property-based value transfer</summary>
/// <param name="original">Original array that will be cloned</param>
/// <param name="elementType">Type of elements the original array contains</param>
/// <returns>A clone of the original array</returns>
private static object deepCloneArrayPropertyBased(Array original, Type elementType)
{
if (elementType.IsPrimitive || (elementType == typeof(string)))
{
return original.Clone();
}
int dimensionCount = original.Rank;
// Find out the length of each of the array's dimensions, also calculate how
// many elements there are in the array in total.
var lengths = new int[dimensionCount];
int totalElementCount = 0;
for (int index = 0; index < dimensionCount; ++index)
{
lengths[index] = original.GetLength(index);
if (index == 0)
{
totalElementCount = lengths[index];
}
else
{
totalElementCount *= lengths[index];
}
}
// Knowing the number of dimensions and the length of each dimension, we can
// create another array of the exact same sizes.
Array clone = Array.CreateInstance(elementType, lengths);
// If this is a one-dimensional array (most common type), do an optimized copy
// directly specifying the indices
if (dimensionCount == 1)
{
// Clone each element of the array directly
for (int index = 0; index < totalElementCount; ++index)
{
object originalElement = original.GetValue(index);
if (originalElement != null)
{
clone.SetValue(deepCloneSinglePropertyBased(originalElement), index);
}
}
}
else
{ // Otherwise use the generic code for multi-dimensional arrays
var indices = new int[dimensionCount];
for (int index = 0; index < totalElementCount; ++index)
{
// Determine the index for each of the array's dimensions
int elementIndex = index;
for (int dimensionIndex = dimensionCount - 1; dimensionIndex >= 0; --dimensionIndex)
{
indices[dimensionIndex] = elementIndex % lengths[dimensionIndex];
elementIndex /= lengths[dimensionIndex];
}
// Clone the current array element
object originalElement = original.GetValue(indices);
if (originalElement != null)
{
clone.SetValue(deepCloneSinglePropertyBased(originalElement), indices);
}
}
}
return clone;
}
}
} // namespace Nuclex.Support.Cloning
|
namespace Company.ConsoleApplication1.Hello
{
public interface IHelloCommand : ICommand {}
} |
using UnityEngine;
using System.Collections;
public class playersbodygenerater : Photon.MonoBehaviour {
/*
public GameObject player1;
public GameObject player2;
public GameObject player3;
public GameObject player4;
public GameObject player5;
*/
public bool color = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (color == false)
{
Vector3 playerpos = this.transform.position;
Quaternion playerrot = this.transform.rotation;
int Pnum = playerlocate.Pnum;
if (Pnum != 0)
{
if (Pnum == 1)
{
// プレハブからインスタンスを生成
GameObject obj = PhotonNetwork.Instantiate("BrownBody", playerpos, playerrot, 0);
// 作成したオブジェクトを子として登録
obj.transform.parent = transform;
color = true;
Pnum = 0;
}
else if (Pnum == 2)
{
// プレハブからインスタンスを生成
GameObject obj = PhotonNetwork.Instantiate("PinkBody", playerpos, playerrot, 0);
// 作成したオブジェクトを子として登録
obj.transform.parent = transform;
color = true;
Pnum = 0;
}
else if (Pnum == 3)
{
// プレハブからインスタンスを生成
GameObject obj = PhotonNetwork.Instantiate("BlueBody", playerpos, playerrot, 0);
// 作成したオブジェクトを子として登録
obj.transform.parent = transform;
color = true;
Pnum = 0;
}
else if (Pnum == 4)
{
// プレハブからインスタンスを生成
GameObject obj = PhotonNetwork.Instantiate("YellowBody", playerpos, playerrot, 0);
// 作成したオブジェクトを子として登録
obj.transform.parent = transform;
color = true;
Pnum = 0;
}
else if (Pnum == 5)
{
// プレハブからインスタンスを生成
GameObject obj = PhotonNetwork.Instantiate("GreenBody", playerpos, playerrot, 0);
// 作成したオブジェクトを子として登録
obj.transform.parent = transform;
color = true;
Pnum = 0;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using M3PlusMicrocontroller;
namespace ConsoleTestSimulation {
class Program {
const int to = 100000000;
static void Main(string[] args) {
//Stopwatch timer = new Stopwatch();
//Console.WriteLine("Iniciar");
//Console.ReadLine();
/*
int[] programa = {
0x07, 0xc0, 0x00, 0xdb, 0xe0, 0x07, 0x03, 0x00, 0x03,
};
Command[] Commands = Helpers.GenerateFunctions(programa);
*/
/*
Command c1 = new Command();
Simulator s = new Simulator();
s.NextInstruction = 3;
c1.Execute = delegate (Simulator ss) {
};
*/
string Program =
"MOV 37,A\n"+
"loop:\n"+
"SUB 1,A\n"+
"JMPZ fora\n"+
"JMP loop\n"+
"fora:\n";
TokenAnalyser tka = new TokenAnalyser();
tka.Program = Program;
while(true) {
Token token = tka.NextToken();
Console.WriteLine("Type: \"" + token.Type + "\", Value: \"" + token.Value + "\".");
Console.ReadLine();
}
}
}
enum asd {
nada, alto, baixo
}
}
|
using System;
namespace Simplic.Package
{
// TODO: Think of better name.
/// <summary>
/// Represents an unpacked ObbjectListItem with information regarding the installation of the content.
/// </summary>
public class InstallableObject
{
/// <summary>
/// Gets or sets the target.
/// </summary>
public string Target { get; set; }
/// <summary>
/// Gets or sets the content.
/// <para>
/// Contains the data content of the installable object.
/// </para>
/// </summary>
public IContent Content { get; set; }
/// <summary>
/// Gets or sets the Guid
/// </summary>
public Guid? Guid { get; set; }
/// <summary>
/// Gets or sets the install mode.
/// <para>
/// Dependent on the install mode a migratoin might be needed.
/// </para>
/// </summary>
public InstallMode Mode { get; set; }
/// <summary>
/// Gets or sets the package guid.
/// <para>
/// References a <see cref="Package"/>
/// </para>
/// </summary>
public Guid PackageGuid { get; set; }
/// <summary>
/// Gets or sets the package version.
/// <para>
/// Defines the Version of the package that will be installed.
/// </para>
/// </summary>
public Version PackageVersion { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyCal2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var x = int.Parse(this.textBoxOp1.Text);
var y = int.Parse(this.textBoxOp2.Text);
var z = x + y;
this.labelResult.Text = z.ToString();
}
private void buttonSub_Click(object sender, EventArgs e)
{
var x = int.Parse(this.textBoxOp1.Text);
var y = int.Parse(this.textBoxOp2.Text);
var z = x - y;
this.labelResult.Text = z.ToString();
}
private void buttonMul_Click(object sender, EventArgs e)
{
var x = int.Parse(this.textBoxOp1.Text);
var y = int.Parse(this.textBoxOp2.Text);
var z = x * y;
this.labelResult.Text = z.ToString();
}
private void buttonDiv_Click(object sender, EventArgs e)
{
var x = double.Parse(this.textBoxOp1.Text);
var y = double.Parse(this.textBoxOp2.Text);
if (y != 0) {
var z = x / y;
this.labelResult.Text = z.ToString();
}
else
{
this.labelResult.Text = "The divisor can't be zero.";
}
}
private void buttonTri_Click(object sender, EventArgs e)
{
var a = double.Parse(this.textBoxOp1.Text);
var b = double.Parse(this.textBoxOp2.Text);
var c = double.Parse(this.textBoxOp3.Text);
double p = (a + b + c) / 2;
if (((a + b) >= c)&& ((a + c) >= b)&&((b + c) >= a))
{
var s = Math.Sqrt(p * (p - a) * (p - b) * (p - c));
this.labelResult.Text = s.ToString();
}
else
{
this.labelResult.Text = "The length of these three sides can't form a triangle.";
}
}
}
}
|
using UnityEngine;
public class WallEntity : Entity
{
override public void OnBodyCollisionEnter(Collider2D coll)
{
EventKit.Broadcast("player touching wall", true);
}
override public void OnBodyCollisionStay()
{
EventKit.Broadcast("player touching wall", true);
}
override public void OnBodyCollisionExit()
{
EventKit.Broadcast("player touching wall", false);
}
override public void OnWeaponCollisionEnter(Collider2D coll) {}
override public void OnWeaponCollisionStay() {}
override public void OnWeaponCollisionExit() {}
}
|
using System;
using Armature.Core;
using FluentAssertions;
using NUnit.Framework;
using Tests.Util;
namespace Tests.UnitTests;
public class BuildChainTest
{
[Test]
public void Length()
{
// --arrange
const int arrayLength = 3;
const int startIndex = 1;
var array = new UnitId[arrayLength];
var arrayTail = array.ToBuildChain().GetTail(startIndex);
// --assert
arrayTail.Length.Should().Be(arrayLength - startIndex);
}
[Test]
public void Content()
{
const int startIndex = 2;
// --arrange
var array = new UnitId[] {new(0, null), new(1, null), new (2, 0), new(3, 0)};
var expected = new UnitId[array.Length - startIndex];
for(var i = startIndex; i < array.Length; i++)
expected[i - startIndex] = array[i];
// --act
var actual = array.ToBuildChain().GetTail(startIndex);
// --assert
var actualArray = new UnitId[actual.Length];
for(var i = 0; i < actual.Length; i++)
actualArray[i] = actual[i];
actualArray.Should().Equal(expected);
}
[Test]
public void LastItem()
{
// --arrange
const int startIndex = 2;
var lastItem = new UnitId(23, null);
var array = new UnitId[] {new(0, null), new(1, null), new (2, 0), lastItem};
// --act
var actual = array.ToBuildChain().GetTail(startIndex);
// --assert
actual.TargetUnit.Should().Be(lastItem);
}
[Test]
public void should_allow_default()
{
// --arrange
var actual = default(BuildChain);
// --assert
actual.Should().BeOfType<BuildChain>();
}
[Test]
public void should_not_allow_default_ctor()
{
// --arrange
var actual = () => new BuildChain();
// --assert
actual.Should().ThrowExactly<ArgumentException>();
}
[Test]
public void should_check_array_argument()
{
// --arrange
var actual = () => new BuildChain(null!, 4);
// --assert
actual.Should().ThrowExactly<ArgumentNullException>().WithParameterName("array");
}
[Test]
public void should_check_start_index_argument([Values(-3, 24)] int startIndex)
{
var array = new UnitId[] {new(0, null), new (2, 0)};
// --arrange
startIndex = Math.Min(startIndex, array.Length);
var actual = () => new BuildChain(array, startIndex);
// --assert
actual.Should().ThrowExactly<ArgumentOutOfRangeException>().WithParameterName("startIndex");
}
} |
namespace CUE4Parse.UE4.Assets.Exports.Material
{
public enum EMobileSpecularMask
{
MSM_Constant,
MSM_Luminance,
MSM_DiffuseRed,
MSM_DiffuseGreen,
MSM_DiffuseBlue,
MSM_DiffuseAlpha,
MSM_MaskTextureRGB,
MSM_MaskTextureRed,
MSM_MaskTextureGreen,
MSM_MaskTextureBlue,
MSM_MaskTextureAlpha
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using McMaster.Extensions.CommandLineUtils;
namespace NeinTile.Shell
{
[Command("play", Description = "Play a new game")]
public class PlayGame
{
[Option(Description = "Edition to play (defaults to 'Classic')")]
public GameEdition Edition { get; set; } = GameEdition.Classic;
[Range(1, 12)]
[Option(Description = "Number of columns (defaults to 4)")]
public int Columns { get; set; } = 4;
[Range(1, 12)]
[Option(Description = "Number of rows (defaults to 4)")]
public int Rows { get; set; } = 4;
[Range(1, 12)]
[Option(Description = "Number of layers (defaults to 1)")]
public int Layers { get; set; } = 1;
[Option(Description = "Play on a slippery surface; or not")]
public bool Slippery { get; set; } = false;
public int OnExecute()
{
var maker = new GameMaker
{
ColCount = Columns,
RowCount = Rows,
LayCount = Layers,
Edition = Edition,
Slippery = Slippery
};
var game = maker.MakeGame();
return GameLoop.Run(game);
}
}
}
|
/* Copyright (C) 2004 - 2011 Versant Inc. http://www.db4o.com */
using System.IO;
using System.Text;
using Db4objects.Db4o.Foundation;
using Db4objects.Db4o.Internal.Encoding;
using Db4objects.Db4o.Internal.Handlers;
using Db4objects.Db4o.Internal.Slots;
using Sharpen.IO;
namespace Db4objects.Db4o
{
/// <exclude></exclude>
public class DTrace
{
public static bool enabled = false;
public static bool writeToLogFile = false;
public static bool writeToConsole = true;
private static readonly string logFilePath = "C://";
private static string logFileName;
private static readonly object Lock = new object();
private static readonly LatinStringIO stringIO = new LatinStringIO();
public static RandomAccessFile _logFile;
private static int Unused = -1;
private static void BreakPoint()
{
if (enabled)
{
int xxx = 1;
}
}
private static void Configure()
{
if (enabled)
{
}
}
// addRange(15);
// breakOnEvent(540);
//
// addRangeWithEnd(448, 460);
// addRangeWithLength(770,53);
// breakOnEvent(125);
// trackEventsWithoutRange();
// turnAllOffExceptFor(new DTrace[] {WRITE_BYTES});
// turnAllOffExceptFor(new DTrace[] {
// PERSISTENT_OWN_LENGTH,
// });
// turnAllOffExceptFor(new DTrace[] {
// GET_SLOT,
// FILE_FREE,
// TRANS_COMMIT,
// });
// turnAllOffExceptFor(new DTrace[] {WRITE_BYTES});
// turnAllOffExceptFor(new DTrace[] {BTREE_NODE_REMOVE, BTREE_NODE_COMMIT_OR_ROLLBACK YAPMETA_SET_ID});
private static void Init()
{
if (enabled)
{
AddToClassIndex = new Db4objects.Db4o.DTrace(true, true, "add to class index tree"
, true);
BeginTopLevelCall = new Db4objects.Db4o.DTrace(true, true, "begin top level call"
, true);
Bind = new Db4objects.Db4o.DTrace(true, true, "bind", true);
BlockingQueueStoppedException = new Db4objects.Db4o.DTrace(true, true, "blocking queue stopped exception"
, true);
BtreeNodeRemove = new Db4objects.Db4o.DTrace(true, true, "btreenode remove", true
);
BtreeNodeCommitOrRollback = new Db4objects.Db4o.DTrace(true, true, "btreenode commit or rollback"
, true);
BtreeProduceNode = new Db4objects.Db4o.DTrace(true, true, "btree produce node", true
);
CandidateRead = new Db4objects.Db4o.DTrace(true, true, "candidate read", true);
ClassmetadataById = new Db4objects.Db4o.DTrace(true, true, "classmetadata by id",
true);
ClassmetadataInit = new Db4objects.Db4o.DTrace(true, true, "classmetadata init",
true);
ClientMessageLoopException = new Db4objects.Db4o.DTrace(true, true, "client message loop exception"
, true);
Close = new Db4objects.Db4o.DTrace(true, true, "close", true);
CloseCalled = new Db4objects.Db4o.DTrace(true, true, "close called", true);
CollectChildren = new Db4objects.Db4o.DTrace(true, true, "collect children", true
);
Commit = new Db4objects.Db4o.DTrace(false, false, "commit", true);
Continueset = new Db4objects.Db4o.DTrace(true, true, "continueset", true);
CreateCandidate = new Db4objects.Db4o.DTrace(true, true, "create candidate", true
);
Delete = new Db4objects.Db4o.DTrace(true, true, "delete", true);
Donotinclude = new Db4objects.Db4o.DTrace(true, true, "donotinclude", true);
EndTopLevelCall = new Db4objects.Db4o.DTrace(true, true, "end top level call", true
);
EvaluateSelf = new Db4objects.Db4o.DTrace(true, true, "evaluate self", true);
FatalException = new Db4objects.Db4o.DTrace(true, true, "fatal exception", true);
Free = new Db4objects.Db4o.DTrace(true, true, "free", true);
FileFree = new Db4objects.Db4o.DTrace(true, true, "fileFree", true);
FileRead = new Db4objects.Db4o.DTrace(true, true, "fileRead", true);
FileWrite = new Db4objects.Db4o.DTrace(true, true, "fileWrite", true);
FreespacemanagerGetSlot = new Db4objects.Db4o.DTrace(true, true, "FreespaceManager getSlot"
, true);
FreespacemanagerRamFree = new Db4objects.Db4o.DTrace(true, true, "InMemoryfreespaceManager free"
, true);
FreespacemanagerBtreeFree = new Db4objects.Db4o.DTrace(true, true, "BTreeFreeSpaceManager free"
, true);
FreeOnCommit = new Db4objects.Db4o.DTrace(true, true, "trans freeOnCommit", true);
FreeOnRollback = new Db4objects.Db4o.DTrace(true, true, "trans freeOnRollback", true
);
FreePointerOnRollback = new Db4objects.Db4o.DTrace(true, true, "freePointerOnRollback"
, true);
GetPointerSlot = new Db4objects.Db4o.DTrace(true, true, "getPointerSlot", true);
GetSlot = new Db4objects.Db4o.DTrace(true, true, "getSlot", true);
GetFreespaceRam = new Db4objects.Db4o.DTrace(true, true, "getFreespaceRam", true);
GetYapobject = new Db4objects.Db4o.DTrace(true, true, "get ObjectReference", true
);
IdTreeAdd = new Db4objects.Db4o.DTrace(true, true, "id tree add", true);
IdTreeRemove = new Db4objects.Db4o.DTrace(true, true, "id tree remove", true);
IoCopy = new Db4objects.Db4o.DTrace(true, true, "io copy", true);
JustSet = new Db4objects.Db4o.DTrace(true, true, "just set", true);
NewInstance = new Db4objects.Db4o.DTrace(true, true, "newInstance", true);
NotifySlotCreated = new Db4objects.Db4o.DTrace(true, true, "notifySlotCreated", true
);
NotifySlotUpdated = new Db4objects.Db4o.DTrace(true, true, "notify Slot updated",
true);
NotifySlotDeleted = new Db4objects.Db4o.DTrace(true, true, "notifySlotDeleted", true
);
ObjectReferenceCreated = new Db4objects.Db4o.DTrace(true, true, "new ObjectReference"
, true);
PersistentBaseNewSlot = new Db4objects.Db4o.DTrace(true, true, "PersistentBase new slot"
, true);
PersistentOwnLength = new Db4objects.Db4o.DTrace(true, true, "Persistent own length"
, true);
PersistentbaseWrite = new Db4objects.Db4o.DTrace(true, true, "persistentbase write"
, true);
PersistentbaseSetId = new Db4objects.Db4o.DTrace(true, true, "persistentbase setid"
, true);
ProduceSlotChange = new Db4objects.Db4o.DTrace(true, true, "produce slot change",
true);
QueryProcess = new Db4objects.Db4o.DTrace(true, true, "query process", true);
ReadArrayWrapper = new Db4objects.Db4o.DTrace(true, true, "read array wrapper", true
);
ReadBytes = new Db4objects.Db4o.DTrace(true, true, "readBytes", true);
ReadSlot = new Db4objects.Db4o.DTrace(true, true, "read slot", true);
ReferenceRemoved = new Db4objects.Db4o.DTrace(true, true, "reference removed", true
);
RegularSeek = new Db4objects.Db4o.DTrace(true, true, "regular seek", true);
RemoveFromClassIndex = new Db4objects.Db4o.DTrace(true, true, "trans removeFromClassIndexTree"
, true);
RereadOldUuid = new Db4objects.Db4o.DTrace(true, true, "reread old uuid", true);
ServerMessageLoopException = new Db4objects.Db4o.DTrace(true, true, "server message loop exception"
, true);
SlotMapped = new Db4objects.Db4o.DTrace(true, true, "slot mapped", true);
SlotCommitted = new Db4objects.Db4o.DTrace(true, true, "slot committed", true);
SlotFreeOnCommit = new Db4objects.Db4o.DTrace(true, true, "slot free on commit",
true);
SlotFreeOnRollbackId = new Db4objects.Db4o.DTrace(true, true, "slot free on rollback id"
, true);
SlotFreeOnRollbackAddress = new Db4objects.Db4o.DTrace(true, true, "slot free on rollback address"
, true);
SlotRead = new Db4objects.Db4o.DTrace(true, true, "slot read", true);
TransCommit = new Db4objects.Db4o.DTrace(true, true, "trans commit", true);
TransDelete = new Db4objects.Db4o.DTrace(true, true, "trans delete", true);
TransDontDelete = new Db4objects.Db4o.DTrace(true, true, "trans dontDelete", true
);
TransFlush = new Db4objects.Db4o.DTrace(true, true, "trans flush", true);
WriteBytes = new Db4objects.Db4o.DTrace(true, true, "writeBytes", true);
WritePointer = new Db4objects.Db4o.DTrace(true, true, "write pointer", true);
WriteUpdateAdjustIndexes = new Db4objects.Db4o.DTrace(true, true, "trans writeUpdateDeleteMembers"
, true);
WriteXbytes = new Db4objects.Db4o.DTrace(true, true, "writeXBytes", true);
Configure();
}
}
private static void TrackEventsWithoutRange()
{
_trackEventsWithoutRange = true;
}
private DTrace(bool enabled_, bool break_, string tag_, bool log_)
{
if (enabled)
{
_enabled = enabled_;
_break = break_;
_tag = tag_;
_log = log_;
if (all == null)
{
all = new Db4objects.Db4o.DTrace[100];
}
all[current++] = this;
}
}
private bool _enabled;
private bool _break;
private bool _log;
private string _tag;
private static long[] _rangeStart;
private static long[] _rangeEnd;
private static int _rangeCount;
public static long _eventNr;
private static long[] _breakEventNrs;
private static int _breakEventCount;
private static bool _breakAfterEvent;
private static bool _trackEventsWithoutRange;
public static Db4objects.Db4o.DTrace AddToClassIndex;
public static Db4objects.Db4o.DTrace BeginTopLevelCall;
public static Db4objects.Db4o.DTrace Bind;
public static Db4objects.Db4o.DTrace BlockingQueueStoppedException;
public static Db4objects.Db4o.DTrace BtreeNodeCommitOrRollback;
public static Db4objects.Db4o.DTrace BtreeNodeRemove;
public static Db4objects.Db4o.DTrace BtreeProduceNode;
public static Db4objects.Db4o.DTrace CandidateRead;
public static Db4objects.Db4o.DTrace ClassmetadataById;
public static Db4objects.Db4o.DTrace ClassmetadataInit;
public static Db4objects.Db4o.DTrace ClientMessageLoopException;
public static Db4objects.Db4o.DTrace Close;
public static Db4objects.Db4o.DTrace CloseCalled;
public static Db4objects.Db4o.DTrace CollectChildren;
public static Db4objects.Db4o.DTrace Commit;
public static Db4objects.Db4o.DTrace Continueset;
public static Db4objects.Db4o.DTrace CreateCandidate;
public static Db4objects.Db4o.DTrace Delete;
public static Db4objects.Db4o.DTrace Donotinclude;
public static Db4objects.Db4o.DTrace EndTopLevelCall;
public static Db4objects.Db4o.DTrace EvaluateSelf;
public static Db4objects.Db4o.DTrace FatalException;
public static Db4objects.Db4o.DTrace FileFree;
public static Db4objects.Db4o.DTrace FileRead;
public static Db4objects.Db4o.DTrace FileWrite;
public static Db4objects.Db4o.DTrace Free;
public static Db4objects.Db4o.DTrace FreespacemanagerGetSlot;
public static Db4objects.Db4o.DTrace FreespacemanagerRamFree;
public static Db4objects.Db4o.DTrace FreespacemanagerBtreeFree;
public static Db4objects.Db4o.DTrace FreeOnCommit;
public static Db4objects.Db4o.DTrace FreeOnRollback;
public static Db4objects.Db4o.DTrace FreePointerOnRollback;
public static Db4objects.Db4o.DTrace GetSlot;
public static Db4objects.Db4o.DTrace GetPointerSlot;
public static Db4objects.Db4o.DTrace GetFreespaceRam;
public static Db4objects.Db4o.DTrace GetYapobject;
public static Db4objects.Db4o.DTrace IdTreeAdd;
public static Db4objects.Db4o.DTrace IdTreeRemove;
public static Db4objects.Db4o.DTrace IoCopy;
public static Db4objects.Db4o.DTrace JustSet;
public static Db4objects.Db4o.DTrace NewInstance;
public static Db4objects.Db4o.DTrace NotifySlotCreated;
public static Db4objects.Db4o.DTrace NotifySlotUpdated;
public static Db4objects.Db4o.DTrace NotifySlotDeleted;
public static Db4objects.Db4o.DTrace ObjectReferenceCreated;
public static Db4objects.Db4o.DTrace PersistentBaseNewSlot;
public static Db4objects.Db4o.DTrace PersistentOwnLength;
public static Db4objects.Db4o.DTrace PersistentbaseSetId;
public static Db4objects.Db4o.DTrace PersistentbaseWrite;
public static Db4objects.Db4o.DTrace ProduceSlotChange;
public static Db4objects.Db4o.DTrace QueryProcess;
public static Db4objects.Db4o.DTrace ReadArrayWrapper;
public static Db4objects.Db4o.DTrace ReadBytes;
public static Db4objects.Db4o.DTrace ReadSlot;
public static Db4objects.Db4o.DTrace ReferenceRemoved;
public static Db4objects.Db4o.DTrace RegularSeek;
public static Db4objects.Db4o.DTrace RemoveFromClassIndex;
public static Db4objects.Db4o.DTrace RereadOldUuid;
public static Db4objects.Db4o.DTrace ServerMessageLoopException;
public static Db4objects.Db4o.DTrace SlotMapped;
public static Db4objects.Db4o.DTrace SlotCommitted;
public static Db4objects.Db4o.DTrace SlotFreeOnCommit;
public static Db4objects.Db4o.DTrace SlotFreeOnRollbackId;
public static Db4objects.Db4o.DTrace SlotFreeOnRollbackAddress;
public static Db4objects.Db4o.DTrace SlotRead;
public static Db4objects.Db4o.DTrace TransCommit;
public static Db4objects.Db4o.DTrace TransDontDelete;
public static Db4objects.Db4o.DTrace TransDelete;
public static Db4objects.Db4o.DTrace TransFlush;
public static Db4objects.Db4o.DTrace WriteBytes;
public static Db4objects.Db4o.DTrace WritePointer;
public static Db4objects.Db4o.DTrace WriteXbytes;
public static Db4objects.Db4o.DTrace WriteUpdateAdjustIndexes;
static DTrace()
{
Init();
}
private static Db4objects.Db4o.DTrace[] all;
private static int current;
public virtual void Log()
{
if (enabled)
{
Log(Unused);
}
}
public virtual void Log(string msg)
{
if (enabled)
{
Log(Unused, msg);
}
}
public virtual void Log(long p)
{
if (enabled)
{
LogLength(p, 1);
}
}
public virtual void LogInfo(string info)
{
if (enabled)
{
LogEnd(Unused, Unused, 0, info);
}
}
public virtual void Log(long p, string info)
{
if (enabled)
{
LogEnd(Unused, p, 0, info);
}
}
public virtual void LogLength(long start, long length)
{
if (enabled)
{
LogLength(Unused, start, length);
}
}
public virtual void LogLength(long id, long start, long length)
{
if (enabled)
{
LogEnd(id, start, start + length - 1);
}
}
public virtual void LogLength(Slot slot)
{
if (enabled)
{
LogLength(Unused, slot);
}
}
public virtual void LogLength(long id, Slot slot)
{
if (enabled)
{
if (slot == null)
{
return;
}
LogLength(id, slot.Address(), slot.Length());
}
}
public virtual void LogEnd(long start, long end)
{
if (enabled)
{
LogEnd(Unused, start, end);
}
}
public virtual void LogEnd(long id, long start, long end)
{
if (enabled)
{
LogEnd(id, start, end, null);
}
}
public virtual void LogEnd(long id, long start, long end, string info)
{
// if(! Deploy.log){
// return;
// }
if (enabled)
{
if (!_enabled)
{
return;
}
bool inRange = false;
if (_rangeCount == 0)
{
inRange = true;
}
for (int i = 0; i < _rangeCount; i++)
{
// Case 0 ID in range
if (id >= _rangeStart[i] && id <= _rangeEnd[i])
{
inRange = true;
break;
}
// Case 1 start in range
if (start >= _rangeStart[i] && start <= _rangeEnd[i])
{
inRange = true;
break;
}
if (end != 0)
{
// Case 2 end in range
if (end >= _rangeStart[i] && end <= _rangeEnd[i])
{
inRange = true;
break;
}
// Case 3 start before range, end after range
if (start <= _rangeStart[i] && end >= _rangeEnd[i])
{
inRange = true;
break;
}
}
}
if (inRange || (_trackEventsWithoutRange && (start == Unused)))
{
if (_log)
{
_eventNr++;
StringBuilder sb = new StringBuilder(":");
sb.Append(FormatInt(_eventNr, 6));
sb.Append(":");
sb.Append(FormatInt(id));
sb.Append(":");
sb.Append(FormatInt(start));
sb.Append(":");
if (end != 0 && start != end)
{
sb.Append(FormatInt(end));
sb.Append(":");
sb.Append(FormatInt(end - start + 1));
}
else
{
sb.Append(FormatUnused());
sb.Append(":");
sb.Append(FormatUnused());
}
sb.Append(":");
if (info != null)
{
sb.Append(" " + info + " ");
sb.Append(":");
}
sb.Append(" ");
sb.Append(_tag);
LogToOutput(sb.ToString());
}
if (_break)
{
if (_breakEventCount > 0)
{
for (int i = 0; i < _breakEventCount; i++)
{
if (_breakEventNrs[i] == _eventNr)
{
BreakPoint();
break;
}
}
if (_breakAfterEvent)
{
for (int i = 0; i < _breakEventCount; i++)
{
if (_breakEventNrs[i] <= _eventNr)
{
BreakPoint();
break;
}
}
}
}
else
{
BreakPoint();
}
}
}
}
}
private string FormatUnused()
{
return FormatInt(Unused);
}
private static void LogToOutput(string msg)
{
if (enabled)
{
LogToFile(msg);
LogToConsole(msg);
}
}
private static void LogToConsole(string msg)
{
if (enabled)
{
if (writeToConsole)
{
Sharpen.Runtime.Out.WriteLine(msg);
}
}
}
private static void LogToFile(string msg)
{
if (enabled)
{
if (!writeToLogFile)
{
return;
}
lock (Lock)
{
if (_logFile == null)
{
try
{
_logFile = new RandomAccessFile(LogFile(), "rw");
LogToFile("\r\n\r\n ********** BEGIN LOG ********** \r\n\r\n ");
}
catch (IOException e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
msg = DateHandlerBase.Now() + "\r\n" + msg + "\r\n";
byte[] bytes = stringIO.Write(msg);
try
{
_logFile.Write(bytes);
}
catch (IOException e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
}
}
private static string LogFile()
{
if (enabled)
{
if (logFileName != null)
{
return logFileName;
}
logFileName = "db4oDTrace_" + DateHandlerBase.Now() + "_" + SignatureGenerator.GenerateSignature
() + ".log";
logFileName = logFileName.Replace(' ', '_');
logFileName = logFileName.Replace(':', '_');
logFileName = logFileName.Replace('-', '_');
return logFilePath + logFileName;
}
return null;
}
public static void AddRange(long pos)
{
if (enabled)
{
AddRangeWithEnd(pos, pos);
}
}
public static void AddRangeWithLength(long start, long length)
{
if (enabled)
{
AddRangeWithEnd(start, start + length - 1);
}
}
public static void AddRangeWithEnd(long start, long end)
{
if (enabled)
{
if (_rangeStart == null)
{
_rangeStart = new long[1000];
_rangeEnd = new long[1000];
}
_rangeStart[_rangeCount] = start;
_rangeEnd[_rangeCount] = end;
_rangeCount++;
}
}
// private static void breakFromEvent(long eventNr){
// breakOnEvent(eventNr);
// _breakAfterEvent = true;
// }
private static void BreakOnEvent(long eventNr)
{
if (enabled)
{
if (_breakEventNrs == null)
{
_breakEventNrs = new long[100];
}
_breakEventNrs[_breakEventCount] = eventNr;
_breakEventCount++;
}
}
private string FormatInt(long i, int len)
{
if (enabled)
{
string str = " ";
if (i != Unused)
{
str += i + " ";
}
return Sharpen.Runtime.Substring(str, str.Length - len);
}
return null;
}
private string FormatInt(long i)
{
if (enabled)
{
return FormatInt(i, 10);
}
return null;
}
private static void TurnAllOffExceptFor(Db4objects.Db4o.DTrace[] these)
{
if (enabled)
{
for (int i = 0; i < all.Length; i++)
{
if (all[i] == null)
{
break;
}
bool turnOff = true;
for (int j = 0; j < these.Length; j++)
{
if (all[i] == these[j])
{
turnOff = false;
break;
}
}
if (turnOff)
{
all[i]._break = false;
all[i]._enabled = false;
all[i]._log = false;
}
}
}
}
public static void NoWarnings()
{
BreakOnEvent(0);
TrackEventsWithoutRange();
}
}
}
|
using System;
using System.Collections.Generic;
using ESRI.ArcGIS.Geodatabase;
using ProSuite.Commons.Essentials.Assertions;
using ProSuite.Commons.Essentials.CodeAnnotations;
using Ao = ESRI.ArcGIS.Geometry;
namespace ProSuite.QA.Container.PolygonGrower
{
public abstract class LineListPolygon
{
private readonly List<IRow> _centroids = new List<IRow>();
private readonly bool _isInnerRing;
protected LineListPolygon(bool isInnerRing)
{
_isInnerRing = isInnerRing;
}
public bool IsInnerRing
{
get { return _isInnerRing; }
}
public List<IRow> Centroids
{
get { return _centroids; }
}
public bool Processed { get; set; }
public void Add(LineListPolygon poly) { }
protected abstract void AddCore(LineListPolygon poly);
}
public class LineListPolygon<TDirectedRow> : LineListPolygon
where TDirectedRow : class, IPolygonDirectedRow
{
private readonly LineList<TDirectedRow> _mainRing;
private bool _canProcess;
private List<LineList<TDirectedRow>> _innerRingList = new List<LineList<TDirectedRow>>();
#region Constructors
public LineListPolygon([NotNull] LineList<TDirectedRow> outerRing)
: base(false)
{
Assert.ArgumentNotNull(outerRing, nameof(outerRing));
_mainRing = outerRing;
_canProcess = true;
Processed = true;
foreach (TDirectedRow row in outerRing.DirectedRows)
{
row.RightPoly = this;
}
}
public LineListPolygon([NotNull] LineList<TDirectedRow> ring, bool isInnerRing)
: base(isInnerRing)
{
Assert.ArgumentNotNull(ring, nameof(ring));
if (isInnerRing == false)
{
_canProcess = true;
Processed = false;
}
_mainRing = ring;
foreach (TDirectedRow row in ring.DirectedRows)
{
row.RightPoly = this;
}
}
#endregion
public LineList<TDirectedRow> OuterRing
{
get
{
if (IsInnerRing)
{
throw new ArgumentException("cannot query outer Ring of an innerRing polygon");
}
return _mainRing;
}
}
public List<LineList<TDirectedRow>> InnerRingList
{
get
{
if (IsInnerRing)
{
throw new ArgumentException("cannot query inner rings of an innerRing polygon");
}
return _innerRingList;
}
}
public bool CanProcess
{
get { return _canProcess; }
set { _canProcess = value; }
}
public Ao.IPolygon GetPolygon()
{
Ao.IPolygon polygon = new Ao.PolygonClass();
Ao.IRing ring = new Ao.RingClass();
var polyCollection = (Ao.IGeometryCollection) polygon;
var ringCollection = (Ao.ISegmentCollection) ring;
foreach (TDirectedRow pRow in _mainRing.DirectedRows)
{
Ao.ISegmentCollection nextPart = pRow.GetDirectedSegmentCollection();
ringCollection.AddSegmentCollection(nextPart);
}
object missing = Type.Missing;
ring.Close();
polyCollection.AddGeometry(ring, ref missing, ref missing);
foreach (LineList<TDirectedRow> lc in _innerRingList)
{
polyCollection.AddGeometry(
((Ao.IGeometryCollection) lc.GetPolygon()).Geometry[0],
ref missing, ref missing);
}
((Ao.ITopologicalOperator) polygon).Simplify();
return polygon;
}
protected override void AddCore(LineListPolygon poly)
{
Add((LineListPolygon<TDirectedRow>) poly);
}
public void Add(LineListPolygon<TDirectedRow> innerRing)
{
if (IsInnerRing)
{
throw new ArgumentException("Cannot add rings to an inner ring");
}
if (innerRing.IsInnerRing == false)
{
throw new ArgumentException("Cannot add outer ring to a polygon");
}
if (_innerRingList == null)
{
_innerRingList = new List<LineList<TDirectedRow>>();
}
_innerRingList.Add(innerRing._mainRing);
foreach (TDirectedRow row in innerRing._mainRing.DirectedRows)
{
row.RightPoly = this;
}
}
}
}
|
using System;
using System.Collections;
using UnityEngine;
namespace SpaceWar
{
public class PooledMonoBehaviour : MonoBehaviour
{
[SerializeField] private int initialPoolSize = 25;
public UnityEngine.Events.UnityEvent OnDisabled;
public event Action<PooledMonoBehaviour> OnReturnToPool = delegate { };
public int InitialPoolSize => initialPoolSize;
public T Get<T>(bool enable = true) where T : PooledMonoBehaviour
{
var pool = Pool.GetPool(this);
var pooledObject = pool.Get<T>();
if (enable)
{
pooledObject.gameObject.SetActive(true);
}
return pooledObject;
}
public T Get<T>(Vector3 position, Quaternion rotation) where T : PooledMonoBehaviour
{
var pooledObject = Get<T>();
pooledObject.transform.position = position;
pooledObject.transform.rotation = rotation;
return pooledObject;
}
protected virtual void OnDisable()
{
OnReturnToPool?.Invoke(this);
OnDisabled?.Invoke();
}
public void ReturnToPool(float delay = 0)
{
if (gameObject.activeInHierarchy)
{
StartCoroutine(ReturnToPoolAfterSeconds(delay));
}
}
private IEnumerator ReturnToPoolAfterSeconds(float delay)
{
yield return new WaitForSeconds(delay);
gameObject.SetActive(false);
}
}
} |
using GutenTag;
namespace GutenTag.Hspi
{
public class Ruby : Tag
{
public Ruby() : base("ruby")
{
}
}
} |
using MKProject.UdemyBlog.DataAccess.Interfaces;
using MKProject.UdemyBlog.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace MKProject.UdemyBlog.DataAccess.Concrete.EntityFrameworkCore.Repositories
{
public class EfBlogRepository : EfGenericRepository<Blog>,IBlogDal
{
}
}
|
using System;
namespace AppRopio.ECommerce.Products.Core.ViewModels.ProductCard.Items.Switch
{
public interface ISwitchPciVm : IProductDetailsItemVM, ISelectableProductCardItemVM
{
bool Enabled { get; }
}
}
|
//-----------------------------------------------------------------------------
// <copyright file="IEdmObject.cs" company=".NET Foundation">
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// See License.txt in the project root for license information.
// </copyright>
//------------------------------------------------------------------------------
using Microsoft.OData.Edm;
namespace Microsoft.AspNetCore.OData.Formatter.Value
{
/// <summary>
/// Represents an instance of an <see cref="IEdmType"/>.
/// </summary>
public interface IEdmObject
{
/// <summary>
/// Gets the <see cref="IEdmTypeReference"/> of this instance.
/// </summary>
/// <returns>The <see cref="IEdmTypeReference"/> of this instance.</returns>
IEdmTypeReference GetEdmType();
}
}
|
using UnityEngine;
namespace Main
{
class HomeZone : MonoBehaviour
{
public ETeam Team = ETeam.A;
private float m_SqrRadius;
void Start()
{
m_SqrRadius = Match.instance.GlobalSetting.HomeZoneRadius * Match.instance.GlobalSetting.HomeZoneRadius;
}
void Update()
{
Tank t = Match.instance.GetTank(Team);
if(t == null)
{
return;
}
Vector3 homeZonePos = Match.instance.GetRebornPos(Team);
if((homeZonePos - t.Position).sqrMagnitude < m_SqrRadius)
{
t.HPRecovery(Time.deltaTime * Match.instance.GlobalSetting.HPRecoverySpeed);
}
else
{
t.HPRecovery(0);
}
}
}
}
|
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Handle = Interop.ThumbnailExtractorHandle;
using Native = Interop.ThumbnailExtractor;
namespace Tizen.Multimedia.Util
{
/// <summary>
/// Provides the ability to extract the thumbnail from media files.
/// </summary>
/// <since_tizen> 4 </since_tizen>
public static class ThumbnailExtractor
{
private static Handle CreateHandle()
{
Native.Create(out var handle).ThrowIfError("Failed to extract.");
return handle;
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path.
/// </summary>
/// <since_tizen> 4 </since_tizen>
/// <returns>A task that represents the asynchronous extracting operation.</returns>
/// <remarks>The size of the thumbnail will be the default size (320x240).</remarks>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have required privilege for accessing the <paramref name="path"/>.</exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
public static Task<ThumbnailExtractionResult> ExtractAsync(string path)
{
return RunExtractAsync(path, null, CancellationToken.None);
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path.
/// </summary>
/// <returns>A task that represents the asynchronous extracting operation.</returns>
/// <remarks>The size of the thumbnail will be the default size(320x240).</remarks>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="cancellationToken">The token to stop the operation.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have required privilege for accessing the <paramref name="path"/>.</exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
/// <since_tizen> 4 </since_tizen>
public static Task<ThumbnailExtractionResult> ExtractAsync(string path, CancellationToken cancellationToken)
{
return RunExtractAsync(path, null, cancellationToken);
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// </summary>
/// <since_tizen> 4 </since_tizen>
/// <returns>A task that represents the asynchronous extracting operation.</returns>
/// <remarks>
/// If the width is not a multiple of 8, it can be changed by the inner process.<br/>
/// The width will be a multiple of 8 greater than the set value.
/// </remarks>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="size">The size of the thumbnail.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have required privilege for accessing the <paramref name="path"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The width or the height of <paramref name="size"/> is less than or equal to zero.
/// </exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
public static Task<ThumbnailExtractionResult> ExtractAsync(string path, Size size)
{
return RunExtractAsync(path, size, CancellationToken.None);
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// </summary>
/// <since_tizen> 4 </since_tizen>
/// <returns>A task that represents the asynchronous extracting operation.</returns>
/// <remarks>
/// If the width is not a multiple of 8, it can be changed by the inner process.<br/>
/// The width will be a multiple of 8 greater than the set value.
/// </remarks>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="size">The size of the thumbnail.</param>
/// <param name="cancellationToken">The token to stop the operation.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have required privilege for accessing the <paramref name="path"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The width or the height of <paramref name="size"/> is less than or equal to zero.
/// </exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
public static Task<ThumbnailExtractionResult> ExtractAsync(string path, Size size,
CancellationToken cancellationToken)
{
return RunExtractAsync(path, size, cancellationToken);
}
private static Task<ThumbnailExtractionResult> RunExtractAsync(string path, Size? size,
CancellationToken cancellationToken)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (File.Exists(path) == false)
{
throw new FileNotFoundException("File does not exists.", path);
}
if (size.HasValue)
{
if (size.Value.Width <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Value.Width,
"The width must be greater than zero.");
}
if (size.Value.Height <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Value.Height,
"The height must be greater than zero.");
}
}
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled<ThumbnailExtractionResult>(cancellationToken) :
ExtractAsyncCore(path, size, cancellationToken);
}
private static async Task<ThumbnailExtractionResult> ExtractAsyncCore(string path, Size? size,
CancellationToken cancellationToken)
{
using (var handle = CreateHandle())
{
Native.SetPath(handle, path).ThrowIfError("Failed to extract; failed to set the path.");
if (size.HasValue)
{
Native.SetSize(handle, size.Value.Width, size.Value.Height).
ThrowIfError("Failed to extract; failed to set the size");
}
var tcs = new TaskCompletionSource<ThumbnailExtractionResult>();
IntPtr id = IntPtr.Zero;
try
{
var cb = GetCallback(tcs);
using (var cbKeeper = ObjectKeeper.Get(cb))
{
Native.Extract(handle, cb, IntPtr.Zero, out id)
.ThrowIfError("Failed to extract.");
using (RegisterCancellationToken(tcs, cancellationToken, handle, Marshal.PtrToStringAnsi(id)))
{
return await tcs.Task;
}
}
}
finally
{
LibcSupport.Free(id);
}
}
}
private static Native.ThumbnailExtractCallback GetCallback(TaskCompletionSource<ThumbnailExtractionResult> tcs)
{
return (error, requestId, thumbWidth, thumbHeight, thumbData, dataSize, _) =>
{
if (error == ThumbnailExtractorError.None)
{
try
{
tcs.TrySetResult(new ThumbnailExtractionResult(thumbData, thumbWidth, thumbHeight, dataSize));
}
catch (Exception e)
{
tcs.TrySetException(new InvalidOperationException("[" + error + "] Failed to create ThumbnailExtractionResult instance.", e));
}
finally
{
LibcSupport.Free(thumbData);
}
}
else
{
tcs.TrySetException(error.ToException("Failed to extract."));
}
};
}
private static IDisposable RegisterCancellationToken(TaskCompletionSource<ThumbnailExtractionResult> tcs,
CancellationToken cancellationToken, Handle handle, string id)
{
if (cancellationToken.CanBeCanceled == false)
{
return null;
}
return cancellationToken.Register(() =>
{
if (tcs.Task.IsCompleted)
{
return;
}
Native.Cancel(handle, id).ThrowIfError("Failed to cancel.");
tcs.TrySetCanceled();
});
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// The generated thumbnail will be returned in <see cref="ThumbnailExtractionResult"/>.
/// </summary>
/// <remarks>
/// The size of generated thumbnail will be 320x240.<br/>
/// If the size of <paramref name="path"/> has different ratio from 320x240 (approximately 1.33:1),<br/>
/// thumbnail is generated in a way to keep the ratio of <paramref name="path"/>, which is based on short axis of <paramref name="path"/>.<br/>
/// For example, if the size of <paramref name="path"/> is 900x500 (1.8:1), the size of generated thumbnail is 432x240(1.8:1).<br/>
/// To set the size different from 320x240, please use <see cref="Extract(string, Size)"/>.<br/>
/// <br/>
/// If you want to access internal storage, you should add privilege http://tizen.org/privilege/mediastorage. <br/>
/// If you want to access external storage, you should add privilege http://tizen.org/privilege/externalstorage.
/// </remarks>
/// <privilege>http://tizen.org/privilege/mediastorage</privilege>
/// <privilege>http://tizen.org/privilege/externalstorage</privilege>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
/// <exception cref="UnauthorizedAccessException">The caller has no required privilege.</exception>
/// <returns>The result of extracting operation.</returns>
/// <since_tizen> 6 </since_tizen>
public static ThumbnailExtractionResult Extract(string path)
{
return Extract(path, new Size(320, 240));
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// The generated thumbnail will be returned in <see cref="ThumbnailExtractionResult"/>.
/// </summary>
/// <remarks>
/// The size of generated thumbnail will be <paramref name="size"/>.<br/>
/// But, if the size of <paramref name="path"/> has different ratio with <paramref name="size"/>,<br/>
/// thumbnail will be generated in a way to keep the ratio of <paramref name="path"/>, which based on short axis of <paramref name="path"/>.<br/>
/// For example, if the size of <paramref name="path"/> is 900x500 (1.8:1)) and <paramref name="size"/> is 320x240,<br/>
/// the size of generated thumbnail is 432x240(1.8:1).<br/>
/// <br/>
/// If you want to access internal storage, you should add privilege http://tizen.org/privilege/mediastorage. <br/>
/// If you want to access external storage, you should add privilege http://tizen.org/privilege/externalstorage.
/// </remarks>
/// <privilege>http://tizen.org/privilege/mediastorage</privilege>
/// <privilege>http://tizen.org/privilege/externalstorage</privilege>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="size">The size of the thumbnail.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The width or the height of <paramref name="size"/> is less than or equal to zero.
/// </exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
/// <exception cref="UnauthorizedAccessException">The caller has no required privilege.</exception>
/// <returns>The result of extracting operation.</returns>
/// <since_tizen> 6 </since_tizen>
public static ThumbnailExtractionResult Extract(string path, Size size)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (File.Exists(path) == false)
{
throw new FileNotFoundException("File does not exists.", path);
}
if (size.Width <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Width,
"The width must be greater than zero.");
}
if (size.Height <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Height,
"The height must be greater than zero.");
}
Native.ExtractToBuffer(path, (uint)size.Width, (uint)size.Height, out IntPtr thumbData,
out int dataSize, out uint thumbWidth, out uint thumbHeight).
ThrowIfError("Failed to extract thumbnail to buffer");
try
{
return new ThumbnailExtractionResult(thumbData, (int)thumbWidth, (int)thumbHeight,
dataSize);
}
finally
{
if (thumbData != IntPtr.Zero)
{
LibcSupport.Free(thumbData);
}
}
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// The generated thumbnail will be saved in <paramref name="resultThumbnailPath"/>.
/// </summary>
/// <remarks>
/// The size of <paramref name="resultThumbnailPath"/> image will be 320x240.<br/>
/// If the size of <paramref name="path"/> has different ratio with 320x240 (approximately 1.33:1),<br/>
/// thumbnail is generated in a way to keep the ratio of <paramref name="path"/>, which is based on short axis of <paramref name="path"/>.<br/>
/// For example, if the size of <paramref name="path"/> is 900x500 (1.8:1), the size of <paramref name="resultThumbnailPath"/> is 432x240(1.8:1).<br/>
/// To set the size different from 320x240, please use <see cref="Extract(string, Size, string)"/>.<br/>
/// <br/>
/// If you want to access internal storage, you should add privilege http://tizen.org/privilege/mediastorage. <br/>
/// If you want to access external storage, you should add privilege http://tizen.org/privilege/externalstorage.
/// </remarks>
/// <privilege>http://tizen.org/privilege/mediastorage</privilege>
/// <privilege>http://tizen.org/privilege/externalstorage</privilege>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="resultThumbnailPath">The path to save the generated thumbnail.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> or <paramref name="resultThumbnailPath"/> is invalid.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> or <paramref name="resultThumbnailPath"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
/// <exception cref="UnauthorizedAccessException">The caller has no required privilege.</exception>
/// <since_tizen> 6 </since_tizen>
public static void Extract(string path, string resultThumbnailPath)
{
Extract(path, new Size(320, 240), resultThumbnailPath);
}
/// <summary>
/// Extracts the thumbnail for the given media with the specified path and size.
/// The generated thumbnail will be saved in <paramref name="resultThumbnailPath"/>.
/// </summary>
/// <remarks>
/// The size of <paramref name="resultThumbnailPath"/> image will be <paramref name="size"/>.<br/>
/// But, if the size of <paramref name="path"/> has different ratio with <paramref name="size"/>,<br/>
/// thumbnail will be generated in a way to keep the ratio of <paramref name="path"/>, which based on short axis of <paramref name="path"/>.<br/>
/// For example, if the size of <paramref name="path"/> is 900x500 (1.8:1) and <paramref name="size"/> is 320x240,<br/>
/// the size of <paramref name="resultThumbnailPath"/> is 432x240(1.8:1).<br/>
/// <br/>
/// If you want to access internal storage, you should add privilege http://tizen.org/privilege/mediastorage. <br/>
/// If you want to access external storage, you should add privilege http://tizen.org/privilege/externalstorage.
/// </remarks>
/// <privilege>http://tizen.org/privilege/mediastorage</privilege>
/// <privilege>http://tizen.org/privilege/externalstorage</privilege>
/// <param name="path">The path of the media file to extract the thumbnail.</param>
/// <param name="size">The size of the thumbnail.</param>
/// <param name="resultThumbnailPath">The path to save the generated thumbnail.</param>
/// <exception cref="ArgumentException"><paramref name="path"/> or <paramref name="resultThumbnailPath"/> is invalid.</exception>
/// <exception cref="ArgumentNullException"><paramref name="path"/> or <paramref name="resultThumbnailPath"/> is null.</exception>
/// <exception cref="FileNotFoundException"><paramref name="path"/> does not exist.</exception>
/// <exception cref="InvalidOperationException">An internal error occurs.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The width or the height of <paramref name="size"/> is less than or equal to zero.
/// </exception>
/// <exception cref="FileFormatException">The specified file is not supported.</exception>
/// <exception cref="UnauthorizedAccessException">The caller has no required privilege.</exception>
/// <since_tizen> 6 </since_tizen>
public static void Extract(string path, Size size, string resultThumbnailPath)
{
ValidationUtil.ValidateIsNullOrEmpty(path, nameof(path));
ValidationUtil.ValidateIsNullOrEmpty(resultThumbnailPath, nameof(resultThumbnailPath));
if (File.Exists(path) == false)
{
throw new FileNotFoundException("File does not exists.", path);
}
if (size.Width <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Width,
"The width must be greater than zero.");
}
if (size.Height <= 0)
{
throw new ArgumentOutOfRangeException(nameof(size), size.Height,
"The height must be greater than zero.");
}
Native.ExtractToFile(path, (uint)size.Width, (uint)size.Height, resultThumbnailPath).
ThrowIfError("Failed to extract thumbnail to file.");
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Blish_HUD;
using Blish_HUD.Controls;
using Blish_HUD.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Events_Module {
public class NotificationMover : Control, IWindow {
// This is all very kludgy. I wouldn't use it as a reference for anything.
private const int HANDLE_SIZE = 40;
private readonly SpriteBatchParameters _clearDrawParameters;
private readonly ScreenRegion[] _screenRegions;
private ScreenRegion _activeScreenRegion = null;
private Point _grabPosition = Point.Zero;
private readonly Texture2D _handleTexture;
public NotificationMover(params ScreenRegion[] screenPositions) : this(screenPositions.ToList()) { /* NOOP */ }
public NotificationMover(IEnumerable<ScreenRegion> screenPositions) {
WindowBase2.RegisterWindow(this);
this.ZIndex = int.MaxValue - 10;
_clearDrawParameters = new SpriteBatchParameters(SpriteSortMode.Deferred, BlendState.Opaque);
_screenRegions = screenPositions.ToArray();
_handleTexture = EventsModule.ModuleInstance.ContentsManager.GetTexture("textures/handle.png");
}
protected override void OnLeftMouseButtonPressed(MouseEventArgs e) {
if (_activeScreenRegion == null) {
// Only start drag if we were moused over one.
return;
}
_grabPosition = this.RelativeMousePosition;
}
protected override void OnLeftMouseButtonReleased(MouseEventArgs e) {
_grabPosition = Point.Zero;
}
protected override void OnMouseMoved(MouseEventArgs e) {
if (_grabPosition != Point.Zero && _activeScreenRegion != null) {
var lastPos = _grabPosition;
_grabPosition = this.RelativeMousePosition;
_activeScreenRegion.Location += (_grabPosition - lastPos);
} else {
// Update which screen region the mouse is over.
foreach (var region in _screenRegions) {
if (region.Bounds.Contains(this.RelativeMousePosition)) {
_activeScreenRegion = region;
return;
}
}
_activeScreenRegion = null;
}
}
protected override void Paint(SpriteBatch spriteBatch, Rectangle bounds) {
spriteBatch.DrawOnCtrl(this, ContentService.Textures.Pixel, bounds, Color.Black * 0.8f);
spriteBatch.End();
spriteBatch.Begin(_clearDrawParameters);
foreach (var region in _screenRegions) {
spriteBatch.DrawOnCtrl(this, ContentService.Textures.TransparentPixel, region.Bounds, Color.Transparent);
}
spriteBatch.End();
spriteBatch.Begin(this.SpriteBatchParameters);
foreach (var region in _screenRegions) {
if (region == _activeScreenRegion) {
spriteBatch.DrawOnCtrl(this, ContentService.Textures.Pixel, new Rectangle(region.Location, region.Size), Color.White * 0.5f);
}
spriteBatch.DrawOnCtrl(this, _handleTexture, new Rectangle(region.Bounds.Left, region.Bounds.Top, HANDLE_SIZE, HANDLE_SIZE), _handleTexture.Bounds, Color.White * 0.6f);
spriteBatch.DrawOnCtrl(this, _handleTexture, new Rectangle(region.Bounds.Right - HANDLE_SIZE / 2, region.Bounds.Top + HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE), _handleTexture.Bounds, Color.White * 0.6f, MathHelper.PiOver2, new Vector2(HANDLE_SIZE / 2f, HANDLE_SIZE / 2f));
spriteBatch.DrawOnCtrl(this, _handleTexture, new Rectangle(region.Bounds.Left + HANDLE_SIZE / 2, region.Bounds.Bottom - HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE), _handleTexture.Bounds, Color.White * 0.6f, MathHelper.PiOver2 * 3, new Vector2(HANDLE_SIZE / 2f, HANDLE_SIZE / 2f));
spriteBatch.DrawOnCtrl(this, _handleTexture, new Rectangle(region.Bounds.Right - HANDLE_SIZE / 2, region.Bounds.Bottom - HANDLE_SIZE / 2, HANDLE_SIZE, HANDLE_SIZE), _handleTexture.Bounds, Color.White * 0.6f, MathHelper.Pi, new Vector2(HANDLE_SIZE / 2f, HANDLE_SIZE / 2f));
//spriteBatch.DrawStringOnCtrl(this,
// region.RegionName,
// GameService.Content.DefaultFont32,
// region.Bounds,
// Color.Black,
// false,
// HorizontalAlignment.Center);
}
spriteBatch.DrawStringOnCtrl(this, "Press ESC to close.", GameService.Content.DefaultFont32, bounds, Color.White, false, HorizontalAlignment.Center);
}
public override void Hide() {
this.Dispose();
}
public void BringWindowToFront() { /* NOOP */ }
public bool TopMost => true;
public double LastInteraction { get; }
public bool CanClose => true;
protected override void DisposeControl() {
WindowBase2.UnregisterWindow(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Content.Shared.Text
{
public static class Names
{
public static readonly IReadOnlyList<string> MaleFirstNames;
public static readonly IReadOnlyList<string> FemaleFirstNames;
public static readonly IReadOnlyList<string> LastNames;
static Names()
{
MaleFirstNames = ResourceToLines("Content.Shared.Text.Names.first_male.txt");
FemaleFirstNames = ResourceToLines("Content.Shared.Text.Names.first_female.txt");
LastNames = ResourceToLines("Content.Shared.Text.Names.last.txt");
}
private static string[] ResourceToLines(string resourceName)
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using var reader = new StreamReader(stream);
return reader
.ReadToEnd()
.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
}
}
|
//Do not edit! This file was generated by Unity-ROS MessageGeneration.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Unity.Robotics.ROSTCPConnector.MessageGeneration;
namespace RosMessageTypes.Sensor
{
[Serializable]
public class CompressedImageMsg : Message
{
public const string k_RosMessageName = "sensor_msgs/CompressedImage";
public override string RosMessageName => k_RosMessageName;
// This message contains a compressed image.
public Std.HeaderMsg header;
// Header timestamp should be acquisition time of image
// Header frame_id should be optical frame of camera
// origin of frame should be optical center of cameara
// +x should point to the right in the image
// +y should point down in the image
// +z should point into to plane of the image
public string format;
// Specifies the format of the data
// Acceptable values:
// jpeg, png
public byte[] data;
// Compressed image buffer
public CompressedImageMsg()
{
this.header = new Std.HeaderMsg();
this.format = "";
this.data = new byte[0];
}
public CompressedImageMsg(Std.HeaderMsg header, string format, byte[] data)
{
this.header = header;
this.format = format;
this.data = data;
}
public static CompressedImageMsg Deserialize(MessageDeserializer deserializer) => new CompressedImageMsg(deserializer);
private CompressedImageMsg(MessageDeserializer deserializer)
{
this.header = Std.HeaderMsg.Deserialize(deserializer);
deserializer.Read(out this.format);
deserializer.Read(out this.data, sizeof(byte), deserializer.ReadLength());
}
public override void SerializeTo(MessageSerializer serializer)
{
serializer.Write(this.header);
serializer.Write(this.format);
serializer.WriteLength(this.data);
serializer.Write(this.data);
}
public override string ToString()
{
return "CompressedImageMsg: " +
"\nheader: " + header.ToString() +
"\nformat: " + format.ToString() +
"\ndata: " + System.String.Join(", ", data.ToList());
}
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
#else
[UnityEngine.RuntimeInitializeOnLoadMethod]
#endif
public static void Register()
{
MessageRegistry.Register(k_RosMessageName, Deserialize);
}
}
}
|
using System;
using System.Text.Json.Serialization;
namespace Nu.Plugin
{
internal class PluginConfiguration
{
private PluginConfiguration() { }
private PluginConfiguration(string name, string usage, bool isFilter, int[] positional, object named)
{
IsFilter = isFilter;
Name = name;
Usage = usage;
Named = named;
Positional = positional;
}
public static PluginConfiguration Create() => new PluginConfiguration();
[JsonPropertyName("name")]
public string Name { get; }
[JsonPropertyName("usage")]
public string Usage { get; }
[JsonPropertyName("is_filter")]
public bool IsFilter { get; } = true;
[JsonPropertyName("positional")]
public int[] Positional { get; } = Array.Empty<int>();
[JsonPropertyName("named")]
public object Named { get; } = new { };
public PluginConfiguration WithName(string name) => new PluginConfiguration(
name,
this.Usage,
this.IsFilter,
this.Positional,
this.Named
);
public PluginConfiguration WithUsage(string usage) => new PluginConfiguration(
this.Name,
usage,
this.IsFilter,
this.Positional,
this.Named
);
public PluginConfiguration WithIsFilter(bool isFilter) => new PluginConfiguration(
this.Name,
this.Usage,
isFilter,
this.Positional,
this.Named
);
}
} |
using OpenQA.Selenium;
namespace Core.Elements.BaseElements
{
public class TextInputElement : Element, ITextInputElement
{
public TextInputElement(IWebElement element, IWebDriver webDriver) : base(element, webDriver)
{
}
public string Value
{
get => GetAttribute("value");
set
{
Click();
WebElement.SendKeys(value);
}
}
}
} |
using RimWorld;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Verse;
namespace MTW_Treasures
{
public class StockGenerator_Treasures : StockGenerator
{
private Thing TryMakeForStockSingle(ThingDef thingDef)
{
ThingDef stuff = null;
if (thingDef.MadeFromStuff)
{
stuff = (from st in DefDatabase<ThingDef>.AllDefs
where st.IsStuff && st.stuffProps.CanMake(thingDef)
select st).RandomElementByWeight((ThingDef st) => st.stuffProps.commonality);
}
Thing thing = ThingMaker.MakeThing(thingDef, stuff);
thing.stackCount = 1;
return thing;
}
private bool CanStockTreasure(ThingDef def)
{
if (def.Minifiable)
{
return Find.ListerThings.ThingsOfDef(def).Count == 0 &&
Find.ListerThings.ThingsOfDef(def.minifiedDef).Count == 0;
}
else
{
return Find.ListerThings.ThingsOfDef(def).Count == 0;
}
}
public override IEnumerable<Thing> GenerateThings()
{
// Always generates 1 of every treasure at the moment.
foreach (var def in TreasuresUtils.AllTreasuresDefs.Where(d => this.CanStockTreasure(d)))
{
yield return this.TryMakeForStockSingle(def);
}
yield break;
}
public override bool HandlesThingDef(ThingDef thingDef)
{
return TreasuresUtils.AllTreasuresDefs.Contains(thingDef);
}
}
}
|
namespace GenericEvolutionaryFramework
{
class Program
{
static void Main(string[] args)
{
new EvolutionaryAlgorithm(
new Population(),
new Evaluator(),
new Crossover(),
new Selector(),
new Mutator()).Run();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Fungus;
using BaseFungus = Fungus;
namespace CGTUnity.Fungus.SaveSystem
{
/// <summary>
/// Contains much of the state of a Flowchart.
/// </summary>
public class FlowchartData : SaveData
{
#region Fields
[SerializeField] protected string flowchartName;
[SerializeField] protected FlowchartVariables vars = new FlowchartVariables();
[SerializeField] protected List<BlockData> blocks = new List<BlockData>();
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the name of the encoded Flowchart.
/// </summary>
public string FlowchartName { get { return flowchartName; } set { flowchartName = value; } }
public FlowchartVariables Vars { get { return vars; } set { vars = value; } }
public List<BlockData> Blocks { get { return blocks; } set { blocks = value; } }
#endregion
#region Constructors
public FlowchartData() { }
public FlowchartData(Flowchart flowchart)
{
SetFrom(flowchart);
}
#endregion
#region Public methods
/// <summary>
/// Makes the FlowchartData instance hold the state of only the passed Flowchart.
/// </summary>
public virtual void SetFrom(Flowchart flowchart)
{
Clear(); // Get rid of any old state data first
FlowchartName = flowchart.name;
SetVariablesFrom(flowchart);
SetBlocksFrom(flowchart);
}
/// <summary>
/// Clears all state this FlowchartData has.
/// </summary>
public override void Clear()
{
flowchartName = string.Empty;
ClearVariables();
ClearBlocks();
}
#region Static Methods
public static FlowchartData CreateFrom(Flowchart flowchart)
{
return new FlowchartData(flowchart);
}
#endregion
#region Helpers
protected virtual void ClearVariables()
{
vars.Clear();
}
protected virtual void ClearBlocks()
{
blocks.Clear();
}
protected virtual void SetVariablesFrom(Flowchart flowchart)
{
for (int i = 0; i < flowchart.Variables.Count; i++)
{
var variable = flowchart.Variables[i];
TrySetVariable<string, StringVar, StringVariable>(variable, vars.Strings);
TrySetVariable<int, IntVar, IntegerVariable>(variable, vars.Ints);
TrySetVariable<float, FloatVar, FloatVariable>(variable, vars.Floats);
TrySetVariable<bool, BoolVar, BooleanVariable>(variable, vars.Bools);
TrySetVariable<Color, ColorVar, ColorVariable>(variable, vars.Colors);
TrySetVariable<Vector2, Vec2Var, Vector2Variable>(variable, vars.Vec2s);
TrySetVariable<Vector3, Vec3Var, Vector3Variable>(variable, vars.Vec3s);
}
}
/// <summary>
/// Adds the passed variable to the passed list if it can be cast to the correct type.
///
/// TBase: Base type encapsulated by the variable
///
/// TSVarType: This save system's serializable container for the variable
/// TNSVariableType: Fungus's built-in flowchart-only container for the variable
/// </summary>
protected virtual void TrySetVariable<TBase, TSVarType, TNSVariableType>(BaseFungus.Variable varToSet,
IList<TSVarType> varList)
where TSVarType: Var<TBase>, new()
where TNSVariableType: BaseFungus.VariableBase<TBase>
{
var fungusBaseVar = varToSet as TNSVariableType;
if (fungusBaseVar != null)
{
var toAdd = new TSVarType();
toAdd.Key = fungusBaseVar.Key;
toAdd.Value = fungusBaseVar.Value;
varList.Add(toAdd);
}
}
protected virtual void SetBlocksFrom(Flowchart flowchart)
{
// Register data for the blocks the flowchart is executing
var executingBlocks = flowchart.GetExecutingBlocks();
for (int i = 0; i < executingBlocks.Count; i++)
{
BlockData newBlockData = new BlockData(executingBlocks[i]);
blocks.Add(newBlockData);
}
}
#endregion
#endregion
}
} |
using System;
namespace AndroidXml.Res
{
[Serializable]
public class ResXMLTree_namespaceExt
{
public ResStringPool_ref Prefix { get; set; }
public ResStringPool_ref Uri { get; set; }
}
} |
// Another shape-centric namespace.
using System;
namespace My3DShapes
{
// 3D Circle class.
public class Circle { }
// 3D Hexagon class.
public class Hexagon { }
// 3D Square class.
public class Square { }
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoblinWriter : MonoBehaviour {
public TMPro.TextMeshProUGUI textMesh;
public List<string> goblinJobs;
public int goblinMaxAge = 200;
// Start is called before the first frame update
void Start()
{
UpdateString();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) {
UpdateString();
}
}
void UpdateString() {
string goblinName = GoblinNameGenerator.RandomGoblinName();
string goblinAge = Random.Range(20, goblinMaxAge).ToString();
string goblinJob = goblinJobs[Random.Range(0, goblinJobs.Count)];
textMesh.text = $"{goblinName} is a {goblinAge} years old goblin {goblinJob}.";
}
}
|
namespace test.sacs
{
/// <summary>
/// Create a DomainParticipant and register it by the TestCase as
/// "participant1" with a default qos.
/// </summary>
/// <remarks>
/// Create a DomainParticipant and register it by the TestCase as
/// "participant1" with a default qos.
/// </remarks>
public class CreateParticipantItem : Test.Framework.TestItem
{
/// <summary>
/// Create a DomainParticipant and register it by the TestCase as
/// "participant1" with a default qos.
/// </summary>
/// <remarks>
/// Create a DomainParticipant and register it by the TestCase as
/// "participant1" with a default qos.
/// The DomainParticipantFactory is registered as "theFactory".
/// </remarks>
public CreateParticipantItem()
: base("create a DomainParticipant")
{
}
public override Test.Framework.TestResult Run(Test.Framework.TestCase testCase)
{
Test.Framework.TestResult result;
DDS.DomainParticipantFactory factory;
DDS.DomainParticipantQos qosHolder = null;
DDS.IDomainParticipant participant1;
DDS.ReturnCode rc;
result = new Test.Framework.TestResult("newly created DomainParticipant", "newly created DomainParticipant"
, Test.Framework.TestVerdict.Pass, Test.Framework.TestVerdict.Pass);
factory = DDS.DomainParticipantFactory.Instance;
if (factory == null)
{
result.Result = "failure creating a DomainParticipantFactory";
result.Verdict = Test.Framework.TestVerdict.Fail;
return result;
}
rc = factory.GetDefaultParticipantQos(ref qosHolder);
if (rc != DDS.ReturnCode.Ok)
{
result.Result = "failure resolving the default participant qos (" + rc + ").";
result.Verdict = Test.Framework.TestVerdict.Fail;
return result;
}
participant1 = factory.CreateParticipant(DDS.DomainId.Default, qosHolder);//, null, 0);
if (participant1 == null)
{
result.Result = "failure creating a DomainParticipant using null as qos parameter";
result.Verdict = Test.Framework.TestVerdict.Fail;
return result;
}
testCase.RegisterObject("theFactory", factory);
testCase.RegisterObject("participant1", participant1);
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using SI.Mobile.RPMSGViewer.Lib;
using OpenMcdf;
using System.IO;
using Ionic.Zlib;
using System.Security;
namespace SI.Mobile.RPMSGViewer.Lib
{
public class MessageRpmsg
{
public PublishingLicense _PublishingLicense { get; set; }
public EncryptedDRMContent _EncryptedDRMContent { get; set; }
private const string RPMSG_PREFIX = "\x76\xE8\x04\x60\xC4\x11\xE3\x86";
private const string STORAGE_DATASPACES = "\x0006DataSpaces";
private const string STORAGE_TRANSFOMINFO = "TransformInfo";
private const string STORAGE_DRMTRANSFOM = "\tDRMTransform";
private const string STREAM_ISSUANCELICENSE = "\x0006Primary";
private const string DRMCONTENT_STREAM = "\tDRMContent";
private const string BODYPT_HTML_STREAM = "BodyPT-HTML";
public static MessageRpmsg Parse(string fileUrl)
{
return Parse(File.ReadAllBytes(fileUrl));
}
[SecuritySafeCritical]
public static MessageRpmsg Parse(byte[] compressedRpmsgBytes)
{
LogUtils.Log("");
MessageRpmsg messageRpmsg = new MessageRpmsg ();
byte[] decompressedRpmsgBytes = DecompressRpmsg(compressedRpmsgBytes);
using (MemoryStream ms = new MemoryStream(decompressedRpmsgBytes))
{
using (CompoundFile cf = new CompoundFile (ms))
{
messageRpmsg._PublishingLicense = new PublishingLicense (ExtractPublishingLicenseBytes (cf));
messageRpmsg._EncryptedDRMContent = new EncryptedDRMContent (ExtractDRMContent (cf));
}
}
return messageRpmsg;
}
private static byte[] DecompressRpmsg(byte[] compressedBytes)
{
LogUtils.Log("");
using (MemoryStream fsOut = new MemoryStream())
{
using (MemoryStream fsIn = new MemoryStream(compressedBytes))
{
byte[] header = new byte[12];
byte[] compressedData = new byte[1];
fsIn.Seek(RPMSG_PREFIX.Length, SeekOrigin.Begin);
while (true)
{
if (fsIn.Read(header, 0, 12) != 12)
break;
// int marker = BitConverter.ToInt32(header, 0);
// int sizeUncompressed = BitConverter.ToInt32(header, 4);
int sizeCompressed = BitConverter.ToInt32(header, 8);
if (sizeCompressed > compressedData.Length)
compressedData = new byte[sizeCompressed];
fsIn.Read(compressedData, 0, sizeCompressed);
fsOut.Write(compressedData, 0, sizeCompressed);
}
}
return ZlibStream.UncompressBuffer(fsOut.ToArray());
}
}
[SecuritySafeCritical]
private static byte[] ExtractPublishingLicenseBytes(CompoundFile cf)
{
CFStream PLStream = (CFStream)cf.RootStorage.GetStorage(STORAGE_DATASPACES)
.GetStorage(STORAGE_TRANSFOMINFO)
.GetStorage(STORAGE_DRMTRANSFOM)
.GetStream(STREAM_ISSUANCELICENSE);
int PLSize = (int)PLStream.Size;
byte[] publishingLicenseBytes = PLStream.GetData(173, ref PLSize);
new byte[] { 0xEF, 0xBB, 0xBF }.CopyTo(publishingLicenseBytes, 0);
Array.Resize(ref publishingLicenseBytes, publishingLicenseBytes.Length + 2);
return publishingLicenseBytes;
}
[SecuritySafeCritical]
private static byte[] ExtractDRMContent(CompoundFile cf)
{
CFStream DRMContentStream = (CFStream)cf.RootStorage.GetStream(DRMCONTENT_STREAM);
int DRMContentSize = (int)DRMContentStream.Size;
return DRMContentStream.GetData(0, ref DRMContentSize);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls.Primitives;
namespace DesignScript.Editor
{
using ProtoCore.CodeModel;
using System.Diagnostics;
using DesignScript.Parser;
using DesignScript.Editor.Core;
using System.Windows.Threading;
public partial class TextEditorControl : UserControl
{
int clickedLineIndex = -1;
int breakpointLineY = -1;
bool mouseCursorCaptured = false;
bool ignoreMouseMoveEvent = false;
DispatcherTimer inspectionToolTipTimer = null;
System.Drawing.Point mouseCharacterPosition;
#region Scrollviewer Mouse Events
private void OnScrollViewerMouseMove(object sender, MouseEventArgs e)
{
// When "scrollViewer.CaptureMouse()" is called, mouse-move event will be
// sent before "CaptureMouse" returns. So if this event is sent due to the
// mouse being captured, then we won't process it at all.
//
if (false != ignoreMouseMoveEvent)
return;
IScriptObject activeScript = Solution.Current.ActiveScript;
if (activeScript == null)
return; // There's no active script just yet.
if (IsMouseInClickableRegion(sender, e) == false)
return;
// Retreive the coordinates of the mouse move event. Note that we always
// want the mouse coordinates relative to the top-left corner of the canvas
// instead of the scroll viewer (whose top coordinates are off if scroll
// offset is not at the top of the view).
//
CharPosition cursor = activeScript.CreateCharPosition();
System.Windows.Point screenPoint = GetRelativeCanvasPosition(e);
cursor.SetScreenPosition(screenPoint.X, screenPoint.Y);
mouseCharacterPosition = cursor.GetCharacterPosition();
if (-1 == clickedLineIndex)
{
if (textCore.InternalDragSourceExists == false)
{
// There is nothing being dragged right now.
textCore.SetMouseMovePosition(mouseCharacterPosition.X, mouseCharacterPosition.Y, e);
}
else
{
// Stop caret blinking while dragging.
textCanvas.PauseCaretTimer(true);
DragDrop.AddDragOverHandler(scrollViewer, OnDragOver);
DragDrop.AddDropHandler(scrollViewer, OnDrop);
try
{
string textToMove = textCore.SelectionText;
textToMove = textToMove.Replace("\n", "\r\n");
// Beginning the modal loop of "DoDragDrop" will immediately trigger
// a mouse-mvoe event before it returns (e.g. drop has been made or
// cancelled). So here we set the "ignoreMouseMoveEvent" to true and
// ignore the immediate mouse event from being processed (which will
// result in yet another "DoDragDrop" being called, causing two drop
// operations).
//
ignoreMouseMoveEvent = true;
DragDrop.DoDragDrop(textCanvas, textToMove, DragDropEffects.All);
ignoreMouseMoveEvent = false;
}
finally
{
DragDrop.RemoveDragOverHandler(scrollViewer, OnDragOver);
DragDrop.RemoveDropHandler(scrollViewer, OnDrop);
textCore.ClearDragDropState();
textCanvas.PauseCaretTimer(false); // Resume caret blinking...
}
}
// We turn the cursor to an arrow if it is within the breakpoint or line
// column, and I-beam otherwise. Clicking on the breakpoint column triggers
// a breakpoint and clicking on the line column selects the entire line.
//
scrollViewer.Cursor = Cursors.Arrow;
if (!IsPointWithinLineColumn(screenPoint))
{
if (!IsPointWithinBreakColumn(GetRelativeCanvasPosition(e)))
{
if (!textCore.IsPointInSelection(mouseCharacterPosition.X, mouseCharacterPosition.Y))
scrollViewer.Cursor = Cursors.IBeam;
}
}
if (textCore.ReadOnlyState && (false != TextCanvasHasKeyboardFocus))
{
if (inspectionToolTipTimer == null)
{
inspectionToolTipTimer = new DispatcherTimer();
inspectionToolTipTimer.Tick += new EventHandler(OnInspectionToolTipTimerTick);
// One has to hover over a word for 3/4ths of a second to be considered
// a valid 'Mouse Hover'. Yes, this is decided spontaneously.
inspectionToolTipTimer.Interval = new TimeSpan(0, 0, 0, 0, 200);
}
// Restart timer as cursor moves.
inspectionToolTipTimer.Stop();
inspectionToolTipTimer.Start();
}
}
else
{
scrollViewer.Cursor = Cursors.Arrow;
int currentLine = mouseCharacterPosition.Y;
textCore.SelectLines(clickedLineIndex, currentLine - clickedLineIndex);
}
if ((e.LeftButton & MouseButtonState.Pressed) != 0)
{
// If this message is sent by dragging a thumb on a scrollbar, then the
// user wishes to scroll the text canvas, in which case we should not force
// to bring the caret into view (which is what 'UpdateCaretPosition' does).
//
if ((e.OriginalSource as Thumb) == null)
UpdateCaretPosition();
}
}
/// <summary>
/// Inspection tooltip timer has ticked and a check must be made to see if it is hovering
/// over the same fragment as before the tick and if so, trigger an inspection tooltip if it
/// is a valid variable.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnInspectionToolTipTimerTick(object sender, EventArgs e)
{
inspectionToolTipTimer.Stop();
CodeFragment currFragment = null;
textCore.GetFragmentForInspection(mouseCharacterPosition.X, mouseCharacterPosition.Y, out currFragment);
foreach (EditorExtension extension in editorExtensions)
extension.OnMouseHover(currFragment);
}
private void OnDragOver(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Move;
if ((e.KeyStates & DragDropKeyStates.ControlKey) != 0)
e.Effects = DragDropEffects.Copy;
// First, validate arbitrary screen coordinates...
IScriptObject activeScript = Solution.Current.ActiveScript;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(GetRelativeCanvasPosition(e));
// Here when the content is dragged to the first line in view, try to
// bring it onto the previous line. This is so that the previous line
// gets to scroll into view later on. If the cursor is on the last
// visible line, then try to set it one line beyond that. This is so
// that the next line get to scroll into view the same way.
//
int characterY = mousePoint.CharacterY;
int lastVisibleLine = textCanvas.FirstVisibleLine + textCanvas.MaxVisibleLines;
if (characterY == textCanvas.FirstVisibleLine)
characterY = characterY - 1;
else if (characterY >= lastVisibleLine - 1)
characterY = characterY + 1;
mousePoint.SetCharacterPosition(mousePoint.CharacterX, characterY);
// Then get the precised cursor coordinates, and then set the
// character position so we get screen coordinates at character
// boundaries...
System.Drawing.Point cursor = mousePoint.GetCharacterPosition();
mousePoint.SetCharacterPosition(cursor);
textCanvas.SetCursorScreenPos(mousePoint.GetScreenPosition());
textCanvas.EnsureCursorVisible(mousePoint.CharacterX, mousePoint.CharacterY);
}
private void OnDrop(object sender, DragEventArgs e)
{
if (textCore.ReadOnlyState == true)
DisplayStatusMessage(StatusTypes.Error, Configurations.EditingError, 3);
e.Handled = true;
IScriptObject activeScript = Solution.Current.ActiveScript;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(GetRelativeCanvasPosition(e));
bool copyText = ((e.KeyStates & DragDropKeyStates.ControlKey) != 0);
System.Drawing.Point destination = mousePoint.GetCharacterPosition();
textCore.MoveSelectedText(destination.X, destination.Y, copyText);
textCanvas.BreakpointsUpdated();
UpdateCaretPosition();
UpdateUiForModifiedScript(Solution.Current.ActiveScript);
}
private void OnScrollViewerLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (null == Solution.Current.ActiveScript)
return; // No active script.
if (e.ClickCount > 1)
{
HandleMultipleClicks(e);
return;
}
// We need the canvas to be focusable in order to receive key inputs.
System.Diagnostics.Debug.Assert(textCanvas.Focusable == true);
textCanvas.Focus(); // Set input focus on the canvas.
if (IsMouseInClickableRegion(sender, e) == false)
return;
System.Windows.Point screenPoint = GetRelativeCanvasPosition(e);
IScriptObject activeScript = Solution.Current.ActiveScript;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(screenPoint);
System.Drawing.Point cursor = mousePoint.GetCharacterPosition();
breakpointLineY = -1;
if (IsPointWithinLineColumn(screenPoint))
{
clickedLineIndex = cursor.Y;
textCore.SelectLines(cursor.Y, 0);
}
else
{
clickedLineIndex = -1;
if (IsPointWithinBreakColumn(GetRelativeCanvasPosition(e)))
breakpointLineY = cursor.Y;
textCore.SetMouseDownPosition(cursor.X, cursor.Y, e);
}
// Capturing mouse input results in an immediate mouse-move event,
// but we won't want to handle that as we know that we are
// currently in a button-down event. So here we ignore the immediate
// mouse-move event by setting "stopMouseMoveReentrant" to true.
//
ignoreMouseMoveEvent = true;
TextEditorScrollViewer scrollViewer = sender as TextEditorScrollViewer;
mouseCursorCaptured = scrollViewer.CaptureMouse();
ignoreMouseMoveEvent = false;
UpdateCaretPosition();
}
private void OnScrollViewerLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (false != mouseCursorCaptured)
{
mouseCursorCaptured = false;
// Similarly on Releasing the mouse capture results in a mouse-move
// event, which we ignore.
ignoreMouseMoveEvent = true;
ScrollViewer scrollViewer = sender as ScrollViewer;
scrollViewer.ReleaseMouseCapture();
ignoreMouseMoveEvent = false;
}
IScriptObject activeScript = Solution.Current.ActiveScript;
ITextBuffer textBuffer = ((null == activeScript) ? null : activeScript.GetTextBuffer());
if (null == textBuffer)
return;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(GetRelativeCanvasPosition(e));
System.Drawing.Point cursor = mousePoint.GetCharacterPosition();
System.Windows.Point canvasPosition = GetRelativeCanvasPosition(e);
if (IsPointWithinBreakColumn(canvasPosition))
{
int line = mousePoint.CharacterY;
bool isInDebugMode = false;
if (breakpointLineY == cursor.Y)
{
if (textCore.ToggleBreakpoint())
textCanvas.BreakpointsUpdated();
else if (string.IsNullOrEmpty(activeScript.GetParsedScript().GetScriptPath()))
DisplayStatusMessage(StatusTypes.Warning, Configurations.SaveFileBreakpointWarning, 3);
else if (Solution.Current.ExecutionSession.IsExecutionActive(ref isInDebugMode))
DisplayStatusMessage(StatusTypes.Warning, Configurations.BreakpointDebugWarning, 3);
}
scrollViewer.Cursor = Cursors.Arrow;
}
else
{
if (null != editorExtensions)
{
foreach (EditorExtension extension in editorExtensions)
extension.OnMouseUp(e);
}
if (IsPointOnInlineIconColumn(canvasPosition))
{
int line = mousePoint.CharacterY;
bool runScript = false;
List<InlineMessageItem> outputMessages = Solution.Current.GetInlineMessage();
if (null != outputMessages)
{
foreach (InlineMessageItem message in outputMessages)
{
if (message.Line == line)
{
if (message.Type == InlineMessageItem.OutputMessageType.PossibleError ||
message.Type == InlineMessageItem.OutputMessageType.PossibleWarning)
runScript = true;
}
}
}
if (runScript == true)
{
if (prevRunMode.Equals(RunModes.Run))
{
RunScript();
prevRunMode = RunModes.Run;
}
else
{
if (false == textCore.ReadOnlyState)
OutputWindow.ClearOutput();
// Activate Watch Window tab
if (UpdateUiForStepNext(textCore.Step(RunMode.RunTo)))
editorWidgetBar.ActivateWidget(EditorWidgetBar.Widget.Watch, true);
else
{
int errorcount = ErrorCount();
if (errorcount > 0)
editorWidgetBar.ActivateWidget(EditorWidgetBar.Widget.Errors, true);
else
editorWidgetBar.ActivateWidget(EditorWidgetBar.Widget.Watch, true);
}
prevRunMode = RunModes.RunDebug;
}
}
}
}
if (-1 == clickedLineIndex)
textCore.SetMouseUpPosition(cursor.X, cursor.Y, e);
//For cross highlighting
UpdateScriptDisplay(activeScript);
clickedLineIndex = -1;
UpdateCaretPosition();
}
private void OnScrollViewerRightButtonDown(object sender, MouseButtonEventArgs e)
{
if (textCore.HasSelection != false)
return; // We don't want to destroy selection.
// Compute the coordinates from screen to character.
System.Windows.Point screenPoint = GetRelativeCanvasPosition(e);
IScriptObject activeScript = Solution.Current.ActiveScript;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(screenPoint);
// Finally set the actual cursor position and refresh the display.
textCore.SetCursorPosition(mousePoint.CharacterX, mousePoint.CharacterY);
UpdateCaretPosition();
clickedLineIndex = -1;
}
private void OnTabItemsMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
//Change focus of item on right click
((TabItem)sender).IsSelected = true;
}
private void HandleMultipleClicks(MouseButtonEventArgs e)
{
if (null == textCore)
return;
IScriptObject activeScript = Solution.Current.ActiveScript;
CharPosition mousePoint = activeScript.CreateCharPosition();
mousePoint.SetScreenPosition(GetRelativeCanvasPosition(e));
System.Drawing.Point cursor = mousePoint.GetCharacterPosition();
switch (e.ClickCount)
{
case 2: // Double clicking event.
textCore.SelectFragment(mousePoint.CharacterX, mousePoint.CharacterY);
break;
case 3: // Triple clicking event.
textCore.SelectLines(mousePoint.CharacterY, 0);
break;
}
}
#endregion
}
}
|
using SolastaModApi.Infrastructure;
using static RuleDefinitions;
namespace SolastaModApi.Extensions
{
/// <summary>
/// This helper extensions class was automatically generated.
/// If you find a problem please report at https://github.com/SolastaMods/SolastaModApi/issues.
/// </summary>
[TargetType(typeof(EffectAIParameters))]
public static partial class EffectAIParametersExtensions
{
public static T SetAoeScoreMultiplier<T>(this T entity, float value)
where T : EffectAIParameters
{
entity.SetField("aoeScoreMultiplier", value);
return entity;
}
public static T SetCooldownForBattle<T>(this T entity, int value)
where T : EffectAIParameters
{
entity.SetField("cooldownForBattle", value);
return entity;
}
public static T SetCooldownForCaster<T>(this T entity, int value)
where T : EffectAIParameters
{
entity.SetField("cooldownForCaster", value);
return entity;
}
public static T SetDynamicCooldown<T>(this T entity, bool value)
where T : EffectAIParameters
{
entity.SetField("dynamicCooldown", value);
return entity;
}
}
} |
using GenericSearch.UnitTests.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace GenericSearch.UnitTests.Data
{
public class TestContext : DbContext
{
public static readonly ILoggerFactory Factory = LoggerFactory.Create(x => x.AddConsole());
public TestContext(DbContextOptions<TestContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(Factory);
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Blog>().HasData(Seed.Blogs);
modelBuilder.Entity<Author>().HasData(Seed.Authors);
modelBuilder.Entity<Post>().HasData(Seed.Posts);
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Post> Posts { get; set; }
}
} |
#region Using Statements
using MarkLight.Views.UI;
using System;
using UnityEngine.EventSystems;
#endregion
namespace MarkLight.Views.UI
{
/// <summary>
/// Item selection action data.
/// </summary>
public class ItemSelectionActionData : ActionData
{
#region Fields
public readonly IObservableItem Item;
public readonly bool IsSelected;
#endregion
#region Constructor
public ItemSelectionActionData(IObservableItem item) {
Item = item;
IsSelected = item.IsSelected;
}
#endregion
}
}
|
using Dapper;
using PredicateBuilder.Test.Data;
using PredicateBuilder.Test.Model;
using System.Data;
using System.Data.SqlClient;
namespace PredicateBuilder.IntegrationTest.Data
{
public class PersonData
{
private static readonly string CreateIfNotExistsSql = @"
if not exists (SELECT 1 FROM sysobjects WHERE name='Person' and xtype='U') begin
CREATE TABLE [dbo].[Person](
[PersonId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NOT NULL
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[PersonId] ASC
)
)
end";
private static readonly string InsertSql = @"
INSERT INTO [dbo].[Person]
([FirstName]
,[LastName])
OUTPUT INSERTED.PersonId
VALUES
(@FirstName
,@LastName)";
private string ConnectionString { get; set; }
private AddressData _addressData;
private PhoneNumberData _phoneNumberData;
public PersonData(string connStr)
{
ConnectionString = connStr;
_addressData = new AddressData(connStr);
_phoneNumberData = new PhoneNumberData(connStr);
}
public void Initialize()
{
using (IDbConnection db = new SqlConnection(ConnectionString))
{
db.Execute(CreateIfNotExistsSql);
}
}
public int Add(PersonDto entity)
{
int id = 0;
using (IDbConnection db = new SqlConnection(ConnectionString))
{
id = db.QuerySingle<int>(InsertSql, entity);
}
if (entity.MailingAddress != null)
{
entity.MailingAddress.PersonId = id;
int addressId = _addressData.Add(entity.MailingAddress);
}
else
{
AddressDto address = AddressGenerator.GetAddress(id);
int addressId = _addressData.Add(address);
}
if (entity.AdditionalAddresses != null)
{
foreach (AddressDto address in entity.AdditionalAddresses)
{
address.PersonId = id;
int addressId = _addressData.Add(address);
}
}
if (entity.PhoneNumbers != null)
{
foreach (PhoneNumberDto phoneNumber in entity.PhoneNumbers)
{
phoneNumber.PersonId = id;
int phoneNumberId = _phoneNumberData.Add(phoneNumber);
}
}
else
{
PhoneNumberDto phoneNumber = PhoneNumberGenerator.GetPhoneNumber(id);
int phoneNumberId = _phoneNumberData.Add(phoneNumber);
}
return id;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Drawing;
using System.Windows.Media.Imaging;
using SnipInsight.Util;
using Rectangle = System.Drawing.Rectangle;
namespace SnipInsight.ImageCapture
{
/// <summary>
/// This class is to manage the screen snapshot of the time that user clicks image capture button
/// </summary>
internal class ScreenshotImage : IDisposable
{
private Rectangle _rectangleCaptureImage;
private Bitmap _screenSnapshot;
private double _screenScalor;
public Bitmap ScreenSnapshotImage
{
get { return _screenSnapshot; }
}
public ScreenshotImage()
{
}
public void Dispose()
{
if (_screenSnapshot != null)
{
_screenSnapshot.Dispose();
}
}
~ScreenshotImage()
{
if (_screenSnapshot != null)
{
_screenSnapshot.Dispose();
}
}
public void SnapShot(Rectangle rectangle, double screenScalor)
{
//var screenProps = new ScreenProperties();
//screenProps.GetMonitorsInformation();
//var maxRectangle = screenProps.GetMaxRectangleFromMonitors();
//_rectangleCaptureImage = maxRectangle;
_screenScalor = screenScalor;
_rectangleCaptureImage = new Rectangle(
(int)(rectangle.Left * _screenScalor),
(int)(rectangle.Top * _screenScalor),
(int)(rectangle.Width * _screenScalor),
(int)(rectangle.Height * _screenScalor)
);
var bmDesktop = ScreenCapture.CaptureWindowRegion(IntPtr.Zero, _rectangleCaptureImage.Left, _rectangleCaptureImage.Top,
_rectangleCaptureImage.Width, _rectangleCaptureImage.Height);
_screenSnapshot = bmDesktop;
}
public BitmapSource GetCaptureImage(NativeMethods.RECT rect, DpiScale dpiScaleOfSourceWindow)
{
if (_screenScalor != 1)
{
DpiScale adjustedScale = new DpiScale(dpiScaleOfSourceWindow.X * _screenScalor, dpiScaleOfSourceWindow.Y * _screenScalor);
dpiScaleOfSourceWindow = adjustedScale;
}
// crop the invisible area
var left = rect.left * _screenScalor < _rectangleCaptureImage.Left ? _rectangleCaptureImage.Left : rect.left * _screenScalor;
var top = rect.top * _screenScalor < _rectangleCaptureImage.Top ? _rectangleCaptureImage.Top : rect.top * _screenScalor;
var right = rect.right * _screenScalor > _rectangleCaptureImage.Right ? _rectangleCaptureImage.Right : rect.right * _screenScalor;
var bottom = rect.bottom * _screenScalor > _rectangleCaptureImage.Bottom ? _rectangleCaptureImage.Bottom : rect.bottom * _screenScalor;
var height = bottom - top;
var width = right - left;
left = left - _rectangleCaptureImage.Left;
top = top - _rectangleCaptureImage.Top;
if (left < 0)
{
width = width + left;
left = 0;
}
if (top < 0)
{
height = height + top;
top = 0;
}
Rectangle rectangle = new Rectangle(
(int)left,
(int)top,
(int)width,
(int)height
);
return ScreenCapture.CaptureBmpFromImage(_screenSnapshot, rectangle, dpiScaleOfSourceWindow);
}
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
namespace GenericNEAT.Samples.NeuralNets.Tests
{
[TestClass]
public class TXORFitness
{
XORFitness fit = new XORFitness();
[TestMethod]
public void AllRight()
{
var net = new XORCorrect();
Assert.AreEqual(4, fit.Evaluate(net), float.Epsilon);
}
[TestMethod]
public void AllWrong()
{
var net = new XORWrong();
Assert.AreEqual(0, fit.Evaluate(net), float.Epsilon);
}
[TestMethod]
public void HalfRight()
{
var net = new XORHalfRight();
Assert.AreEqual(2, fit.Evaluate(net), float.Epsilon);
}
}
}
|
namespace UniModules.UniContextData.Runtime.Entities
{
using System;
using UniGame.Context.Runtime.Context;
using UniGame.Core.Runtime.Interfaces;
using UnityEngine;
public class EntityComponent : MonoBehaviour
{
[NonSerialized] private EntityContext _context = new EntityContext();
public IContext Context => _context;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<Item> _cv;
public MainWindow()
{
InitializeComponent();
_cv = new List<Item>();
_cv.Add(new Item { Id = 1, Date= DateTime.Parse("2012/01/10"), Amount = 100, Type = 1});
_cv.Add(new Item { Id = 2, Date= DateTime.Parse("2012/01/15"), Amount = 300, Type = 2});
_cv.Add(new Item { Id = 3, Date= DateTime.Parse("2012/01/15"), Amount = 400, Type = 3});
_cv.Add(new Item { Id = 4, Date= DateTime.Parse("2012/01/15"), Amount = 500, Type = 3});
_cv.Add(new Item { Id = 5, Date= DateTime.Parse("2012/01/30"), Amount = 200, Type = 2});
_cv.Add(new Item { Id = 6, Date= DateTime.Parse("2012/02/01"), Amount = 100, Type = 2});
_cv.Add(new Item { Id = 7, Date= DateTime.Parse("2012/02/10"), Amount =1200, Type = 3});
_cv.Add(new Item { Id = 8, Date= DateTime.Parse("2012/02/20"), Amount = 300, Type = 1});
_cv.Add(new Item { Id = 9, Date= DateTime.Parse("2012/03/10"), Amount = 200, Type = 1});
_cv.Add(new Item { Id =10, Date= DateTime.Parse("2012/03/15"), Amount =1500, Type = 2});
_cv.Add(new Item { Id =11, Date= DateTime.Parse("2012/04/11"), Amount = 100, Type = 2});
_cv.Add(new Item { Id =12, Date= DateTime.Parse("2012/04/16"), Amount = 130, Type = 3});
ICollectionView icv = CollectionViewSource.GetDefaultView(_cv);
// Grouping
icv.GroupDescriptions.Add(new PropertyGroupDescription("Type"));
icv.GroupDescriptions.Add(new PropertyGroupDescription("Date"));
// Sorting
icv.SortDescriptions.Add(new SortDescription("Date", ListSortDirection.Ascending));
this.DataContext = _cv;
}
}
}
|
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace clientcreds.Loggers
{
public class ConsoleLoggerConfig
{
public int EventId { get; set; }
public Dictionary<LogLevel, ConsoleColor> LogLevels { get; set; } = new()
{
[LogLevel.Trace] = ConsoleColor.Gray,
[LogLevel.Debug] = ConsoleColor.Cyan,
[LogLevel.Information] = ConsoleColor.White,
[LogLevel.Warning] = ConsoleColor.Yellow,
[LogLevel.Error] = ConsoleColor.Red,
[LogLevel.Critical] = ConsoleColor.Red
};
}
}
|
using System;
using System.Collections;
using Weborb.Util;
#if FULL_BUILD
using Weborb.Util.Cache;
#endif
using Weborb.Util.Logging;
using Weborb.Writer;
namespace Weborb.V3Types
{
public class BodyHolderWriter : AbstractUnreferenceableTypeWriter
{
#region ITypeWriter Members
public override void write( object obj, IProtocolFormatter formatter )
{
#if FULL_BUILD
// write object and try to cache output if applicable
Cache.WriteAndSave( ( (BodyHolder)obj ).body, formatter );
#else
MessageWriter.writeObject( ((BodyHolder) obj).body, formatter );
#endif
}
#endregion
}
}
|
using FinancialTransactionsApi.V1.Boundary.Response;
using FinancialTransactionsApi.V1.Domain;
using System.Threading.Tasks;
namespace FinancialTransactionsApi.V1.UseCase.Interfaces
{
public interface IUpdateSuspenseAccountUseCase
{
public Task<TransactionResponse> ExecuteAsync(Transaction transaction);
}
}
|
namespace Taller.Dtos
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
//
public class CreateMechanicDto
{
public string Cedula { get; set; }
[Required]
public string Nombre { get; set; }
[Required]
public bool Estado { get; set; }
[Required]
public DateTime FechaNacimiento { get; set; }
[Required]
public int TipoMecanico_Id { get; set; }
}
public class ShowMechanicDto : UpdateMechanicDto
{
public ShowMechanicTypeDto TipoMecanico { get; set; }
public string TipoMecanico_ => $"{TipoMecanico.Tipo}";
public string FechaNacimiento_ => FechaNacimiento.ToString("dd/MM/yyyy");
public int Edad => DateTime.Now.Year - FechaNacimiento.Year;
public ICollection<ShowOrderDto> Ordenes { get; set; }
}
public class UpdateMechanicDto : CreateMechanicDto
{
}
} |
using System;
namespace SistemaClinica.BackEnd.API.Models
{
public class Pacientes
{
public string CedulaPaciente { get; set; }
public string NombrePaciente { get; set; }
public string Apellidos { get; set; }
public string Telefono { get; set; }
public int Edad { get; set; }
public bool Activo { get; set; }
public DateTime FechaCreacion { get; set; }
public DateTime? FechaModificacion { get; set; }
public string CreadoPor { get; set; }
public string ModificadoPor { get; set; }
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Project_OLP_Rest.Domain;
namespace Project_OLP_Rest.Data.Interfaces
{
public interface IRecordService : IGenericService<Record>
{
Task<IEnumerable<Record>> GetAll();
}
}
|
namespace LoESoft.GameServer.realm.mapsetpiece
{
internal class MountainTemple : MapSetPiece
{
public override int Size => 5;
public override void RenderSetPiece(World world, IntPoint pos)
{
Entity cube = Entity.Resolve("Encounter Altar");
cube.Move(pos.X + 2.5f, pos.Y + 2.5f);
world.EnterWorld(cube);
}
}
} |
using DevChatter.Bot.Core.Commands;
namespace DevChatter.Bot.Core.Data.Model
{
public class ChatUser : DataEntity
{
public string UserId { get; set; }
public string DisplayName { get; set; }
public UserRole? Role { get; set; }
public int Tokens { get; set; }
public bool CanRunCommand(IBotCommand botCommand)
{
return IsInThisRoleOrHigher(botCommand.RoleRequired);
}
public bool IsInThisRoleOrHigher(UserRole userRole)
{
return (Role ?? UserRole.Everyone) <= userRole;
}
}
}
|
using System;
namespace Reddit.Inputs.LinksAndComments
{
[Serializable]
public class LinksAndCommentsSubmitInput : APITypeInput
{
/// <summary>
/// boolean value
/// </summary>
public bool ad { get; set; }
/// <summary>
/// string value
/// </summary>
public string app { get; set; }
/// <summary>
/// extension used for redirects
/// </summary>
public string extension { get; set; }
/// <summary>
/// a string no longer than 36 characters
/// </summary>
public string flair_id { get; set; }
/// <summary>
/// a string no longer than 64 characters
/// </summary>
public string flair_text { get; set; }
/// <summary>
/// one of (link, self, image, video, videogif)
/// </summary>
public string kind { get; set; }
/// <summary>
/// boolean value
/// </summary>
public bool nsfw { get; set; }
/// <summary>
/// boolean value
/// </summary>
public bool resubmit { get; set; }
/// <summary>
/// JSON data
/// </summary>
public string richtext_json { get; set; }
/// <summary>
/// boolean value
/// </summary>
public bool sendreplies { get; set; }
/// <summary>
/// boolean value
/// </summary>
public bool spoiler { get; set; }
/// <summary>
/// name of a subreddit
/// </summary>
public string sr { get; set; }
/// <summary>
/// raw markdown text
/// </summary>
public string text { get; set; }
/// <summary>
/// title of the submission. Up to 300 characters long
/// </summary>
public string title { get; set; }
/// <summary>
/// a valid URL
/// </summary>
public string url { get; set; }
/// <summary>
/// a valid URL
/// </summary>
public string video_poster_url { get; set; }
/// <summary>
/// Submit a link to a subreddit.
/// Submit will create a link or self-post in the subreddit sr with the title title.
/// If kind is "link", then url is expected to be a valid URL to link to.
/// Otherwise, text, if present, will be the body of the self-post unless richtext_json is present, in which case it will be converted into the body of the self-post.
/// An error is thrown if both text and richtext_json are present.
/// If a link with the same URL has already been submitted to the specified subreddit an error will be returned unless resubmit is true.
/// extension is used for determining which view-type (e.g.json, compact etc.) to use for the redirect that is generated if the resubmit error occurs.
/// </summary>
/// <param name="ad">boolean value</param>
/// <param name="app"></param>
/// <param name="extension">extension used for redirects</param>
/// <param name="flairId">a string no longer than 36 characters</param>
/// <param name="flairText">a string no longer than 64 characters</param>
/// <param name="kind">one of (link, self, image, video, videogif)</param>
/// <param name="nsfw">boolean value</param>
/// <param name="resubmit">boolean value</param>
/// <param name="richtextJson">JSON data</param>
/// <param name="sendReplies">boolean value</param>
/// <param name="spoiler">boolean value</param>
/// <param name="sr">name of a subreddit</param>
/// <param name="text">raw markdown text</param>
/// <param name="title">title of the submission. up to 300 characters long</param>
/// <param name="url">a valid URL</param>
/// <param name="videoPosterUrl">a valid URL</param>
public LinksAndCommentsSubmitInput(bool ad = false, string app = "", string extension = "", string flairId = "", string flairText = "",
string kind = "", bool nsfw = false, bool resubmit = false, string richtextJson = "", bool sendReplies = true, bool spoiler = false, string sr = "", string text = "",
string title = "", string url = "", string videoPosterUrl = "")
: base()
{
this.ad = ad;
this.app = app;
this.extension = extension;
flair_id = flairId;
flair_text = flairText;
this.kind = kind;
this.nsfw = nsfw;
this.resubmit = resubmit;
richtext_json = richtextJson;
sendreplies = sendReplies;
this.spoiler = spoiler;
this.sr = sr;
this.text = text;
this.title = title;
this.url = url;
video_poster_url = videoPosterUrl;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Common.Operations;
namespace CommonTests
{
[TestClass]
public class MethodResultTests
{
[TestMethod]
public void DefaultConstructorTest()
{
var def = new MethodResult();
isSuccess(def);
}
[TestMethod]
public void IsSuccessASuccessTest()
{
var suc = MethodResult.Success;
isSuccess(suc);
}
[TestMethod]
public void IsFailureAFailureTest()
{
var fail = MethodResult.Failure;
isFailure(fail);
}
[TestMethod]
public void SimpleFailureInitTest()
{
var errMsg = "Failure xd";
var fail = new MethodResult(errMsg);
Assert.IsFalse(fail.isSuccess);
Assert.IsTrue(fail.IsError);
Assert.AreEqual(1, fail.Errors.Count);
Assert.AreEqual(errMsg, fail.Errors[0]);
}
[TestMethod]
public void SimpleResultMadeToAFailureTest()
{
var res = new MethodResult();
var errMsg = "Failure xd";
res.AddError(errMsg);
Assert.IsFalse(res.isSuccess);
Assert.IsTrue(res.IsError);
Assert.AreEqual(1, res.Errors.Count);
Assert.AreEqual(errMsg, res.Errors[0]);
}
[TestMethod]
public void SucessessMergeTest()
{
var suc1 = new MethodResult();
var suc2 = new MethodResult();
var merge = suc1.Merge(suc2);
isSuccess(merge);
}
[TestMethod]
public void FailuresMergeTest()
{
var msg1 = "xxx";
var msg2 = "zzz";
var fail1 = new MethodResult(msg1);
var fail2 = new MethodResult(msg2);
var merge = fail1.Merge(fail2);
isFailure(merge);
Assert.IsTrue(merge.Errors.Contains(msg1));
Assert.IsTrue(merge.Errors.Contains(msg2));
}
[TestMethod]
public void SuccessFailureMergeTest()
{
var msg = "xxx";
var fail = new MethodResult(msg);
var suc = new MethodResult();
var merge = fail.Merge(suc);
isFailure(merge);
Assert.IsTrue(merge.Errors.Contains(msg));
}
private static void isSuccess(MethodResult def)
{
Assert.IsTrue(def.isSuccess);
Assert.IsFalse(def.IsError);
Assert.AreEqual(0, def.Errors.Count);
}
private static void isFailure(MethodResult fail)
{
Assert.IsFalse(fail.isSuccess);
Assert.IsTrue(fail.IsError);
}
}
}
|
// Python Tools for Visual Studio
// 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,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TemplateWizard;
using Project = EnvDTE.Project;
using ProjectItem = EnvDTE.ProjectItem;
namespace Microsoft.PythonTools.ProjectWizards {
public sealed class InstallRequirementsWizard : IWizard {
public void ProjectFinishedGenerating(Project project) {
if (project.DTE.SuppressUI) {
return;
}
ProjectItem requirementsTxt = null;
try {
requirementsTxt = project.ProjectItems.Item("requirements.txt");
} catch (ArgumentException) {
}
if (requirementsTxt == null) {
return;
}
var txt = requirementsTxt.FileNames[0];
if (!File.Exists(txt)) {
return;
}
try {
InstallProjectRequirements(project, txt);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
ex.ReportUnhandledException(
WizardHelpers.GetProvider(project.DTE), // null here is okay
GetType(),
allowUI: true
);
}
}
private static void InstallProjectRequirements(Project project, string requirementsTxt) {
var target = project as IOleCommandTarget;
if (target == null) {
// Project does not implement IOleCommandTarget, so try with DTE
InstallProjectRequirements_DTE(project, requirementsTxt);
return;
}
IntPtr inObj = IntPtr.Zero;
try {
var guid = GuidList.guidPythonToolsCmdSet;
inObj = Marshal.AllocCoTaskMem(16);
Marshal.GetNativeVariantForObject(requirementsTxt, inObj);
ErrorHandler.ThrowOnFailure(target.Exec(
ref guid,
PkgCmdIDList.cmdidInstallProjectRequirements,
(uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
inObj,
IntPtr.Zero
));
} finally {
if (inObj != IntPtr.Zero) {
Marshal.FreeCoTaskMem(inObj);
}
}
}
private static void InstallProjectRequirements_DTE(Project project, string requirementsTxt) {
object inObj = requirementsTxt, outObj = null;
project.DTE.Commands.Raise(
GuidList.guidPythonToolsCmdSet.ToString("B"),
(int)PkgCmdIDList.cmdidInstallProjectRequirements,
ref inObj,
ref outObj
);
}
public void BeforeOpeningFile(ProjectItem projectItem) { }
public void ProjectItemFinishedGenerating(ProjectItem projectItem) { }
public void RunFinished() { }
public void RunStarted(
object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind,
object[] customParams
) { }
public bool ShouldAddProjectItem(string filePath) {
return true;
}
}
}
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Provider;
using Android.Database;
using Java.Lang;
namespace MonoDroid.ApiDemo
{
[Activity (Label = "Views/Auto Complete/4. Contacts")]
[IntentFilter (new[] { Intent.ActionMain }, Categories = new string[] { ApiDemo.SAMPLE_CATEGORY })]
public class AutoComplete4 : Activity
{
public static System.String[] CONTACT_PROJECTION = new System.String[] {
ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName
};
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.autocomplete_4);
ICursor cursor = ContentResolver.Query (ContactsContract.Contacts.ContentUri, CONTACT_PROJECTION, null, null, null);
ContactListAdapter adapter = new ContactListAdapter (this, cursor);
AutoCompleteTextView textView = FindViewById <AutoCompleteTextView> (Resource.Id.edit);
textView.Adapter = adapter;
}
}
// XXX compiler bug in javac 1.5.0_07-164, we need to implement Filterable
// to make compilation work
public class ContactListAdapter : CursorAdapter, IFilterable
{
static int COLUMN_DISPLAY_NAME = 1;
ContentResolver mContent;
public ContactListAdapter (Context context, ICursor c) : base (context, c)
{
mContent = context.ContentResolver;
}
public override View NewView (Context context, Android.Database.ICursor cursor, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.From (context);
TextView view = (TextView) inflater.Inflate (
Android.Resource.Layout.SimpleDropDownItem1Line, parent, false);
view.Text = cursor.GetString (COLUMN_DISPLAY_NAME);
return view;
}
public override void BindView (View view, Context context, Android.Database.ICursor cursor)
{
((TextView) view).Text = cursor.GetString (COLUMN_DISPLAY_NAME);
}
public override ICharSequence ConvertToStringFormatted (ICursor cursor)
{
var convertMe = new string[1];
convertMe [0] = cursor.GetString (COLUMN_DISPLAY_NAME);
var converted = CharSequence.ArrayFromStringArray (convertMe);
return converted [0];
}
public override Android.Database.ICursor RunQueryOnBackgroundThread (Java.Lang.ICharSequence constraint)
{
IFilterQueryProvider filter = FilterQueryProvider;
if (filter != null) {
return filter.RunQuery (constraint);
}
Android.Net.Uri uri = Android.Net.Uri.WithAppendedPath (
ContactsContract.Contacts.ContentFilterUri,
Android.Net.Uri.Encode (""));
if (constraint != null) {
uri = Android.Net.Uri.WithAppendedPath (
ContactsContract.Contacts.ContentFilterUri,
Android.Net.Uri.Encode (constraint.ToString ()));
}
return mContent.Query (uri, AutoComplete4.CONTACT_PROJECTION, null, null, null);
}
}
}
|
using System;
namespace ImpromptuNinjas.ZStd.Utilities {
public sealed partial class MemoryRegionStream {
private static void ValidateReadWriteArgs(byte[] array, int offset, int count) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (array.Length - offset < count)
throw new ArgumentException("Invalid offset or length.");
}
private void ValidateDisposed() {
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
private static unsafe void ValidateSpan(ReadOnlySpan<byte> span, string argName) {
if (AsPointer(span) == null)
throw new ArgumentNullException(argName);
if (span.Length < 0)
throw new ArgumentOutOfRangeException(argName);
}
}
}
|
using AutoMapper;
using HistoricalMysteryAPI.Contracts;
using HM.DataAccess.DB.Models;
namespace HistoricalMysteryAPI.Util
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ArticleItemDto, ArticleItem>().ReverseMap();
CreateMap<ArticleContentDto, ArticleContent>().ReverseMap();
CreateMap<ArticleContentRequest, NewArticleContentRequest>().ReverseMap();
}
}
}
|
using System;
namespace MathVenture.SequenceGen
{
public struct Digit : IComparable<Digit>, IEquatable<Digit>
{
public Digit(int number, int @base = 10)
{
Base = @base;
if (number < 0 || number > @base - 1) {
throw new ArgumentOutOfRangeException($"Digit must be 0-{@base-1}");
}
Value = number;
}
readonly int Value;
readonly int Base;
public int CompareTo(Digit other) {
EnsureSameBase(other);
return this.Value - other.Value;
}
public bool Equals(Digit other) {
EnsureSameBase(other);
return this.Value.Equals(other.Value);
}
public static implicit operator int(Digit d) {
return (int)d.Value;
}
public static explicit operator Digit(int b) {
return new Digit(b);
}
public override string ToString() {
if (Base <= 10 || Value < 10) {
return Value.ToString();
}
else if (Base <= 36) {
return new String((char)(Value + 0x57),1);
}
return "?";
}
void EnsureSameBase(Digit other) {
if (this.Base != other.Base) {
throw new ArithmeticException(
$"Cannot compare numbers from different bases ({this.Base} vs {other.Base})"
);
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Deptorygen.Generator.Interfaces;
using Deptorygen.Utilities;
using Microsoft.CodeAnalysis;
namespace Deptorygen.Generator.Definition
{
public class ResolverDefinition : IDefinitionRequiringNamespace, IAccessibilityClaimer, IResolverContext
{
public string MethodName { get; }
public TypeName ReturnType { get; }
public ResolutionDefinition Resolution { get; }
public VariableDefinition[] Parameters { get; }
public bool IsTransient { get; }
public string CacheVarName { get; }
public string? DelegationKey { get; }
public string ResolutionName => Resolution.TypeName.Name;
public ResolverDefinition(string methodName,
TypeName returnType,
ResolutionDefinition resolution,
VariableDefinition[] parameters,
bool isTransient,
string cacheVarName, string? delegationKey = null)
{
MethodName = methodName;
ReturnType = returnType;
Resolution = resolution;
Parameters = parameters;
IsTransient = isTransient;
CacheVarName = cacheVarName;
DelegationKey = delegationKey;
}
public bool GetRequireDispose(FactoryDefinition factory)
{
return Resolution.IsDisposable && GetIsRequireCache(factory);
}
public bool GetIsRequireCache(FactoryDefinition factory)
{
return !IsTransient
&& !IsAlternatedByCapture(factory)
&& !IsAlternatedByDelegation();
}
public string GetParameterList()
{
return Parameters.Select(x => x.Code).Join(", ");
}
public bool IsAlternatedByDelegation() => !(DelegationKey is null);
public bool IsAlternatedByCapture(FactoryDefinition definition)
{
return definition.Captures.Any(x => x.Resolvers.Any(y => y.ReturnType == ReturnType));
}
public IEnumerable<string> GetRequiredNamespaces()
{
yield return ReturnType.FullNamespace;
yield return Resolution.TypeName.FullNamespace;
foreach (var p in Parameters)
{
yield return p.TypeNamespace;
}
}
public IEnumerable<Accessibility> Accessibilities
{
get
{
yield return ReturnType.Accessibility;
foreach (var parameter in Parameters)
{
yield return parameter.TypeNameInfo.Accessibility;
}
}
}
}
}
|
// See https://aka.ms/new-console-template for more information
using MathNet.Numerics;
// Doing this explicitly would not be needed, but we want to force it here so it fails if there is a problem
Control.UseNativeOpenBLAS();
Console.WriteLine(Control.Describe());
|
using System;
using NUnit.Framework;
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
namespace DemiCode.Logging.log4net.Test
{
[TestFixture]
public class SomeTest
{
[Test]
public void Will_This_Work()
{
Assert.Pass("Yes this works");
}
}
}
|
using System;
namespace Matrix.Framework.Api.Response
{
public class DevelopmentResponseFactory : ProductionResponseFactory
{
public override IResponse GetErrorResponse(Exception exception)
{
var result = base.GetErrorResponse(exception) as ErrorResponse;
if (result != null)
{
result.StackTrace = exception.StackTrace;
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceExample.Web.Utils
{
/// <summary>
/// Contains utilities for file handling.
/// </summary>
public class FileTools
{
/// <summary>
/// Helps appending new lines to text file, creates new file if path does not exists.
/// </summary>
/// <param name="path"></param>
/// <param name="text"></param>
public static void AppendTextToFile(string path, string text)
{
using (var sw = File.AppendText(path))
{
sw.WriteLine(text);
}
}
}
}
|
namespace mc.CodeAnalysis.Syntax
{
public class SyntaxTree
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspnetVnBasics.Entities;
using AspnetVnBasics.Repositories.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AspnetVnBasics.Pages
{
public class ProductModel : PageModel
{
private readonly IProductRepository _productRepository;
private readonly ICartRepository _cartRepository;
public ProductModel(
IProductRepository productRepository,
ICartRepository cartRepository)
{
_productRepository = productRepository ?? throw new ArgumentException(nameof(IProductRepository));
_cartRepository = cartRepository ?? throw new ArgumentException(nameof(ICartRepository));
}
public IEnumerable<Category> Categories { get; set; } = new List<Category>();
public IEnumerable<Product> Products { get; set; } = new List<Product>();
public Product ProductLast { get; set; } = new Product();
[BindProperty(SupportsGet = true)]
public string SelectedCategory { get; set; }
public async Task<IActionResult> OnGetAsync(int? categoryId)
{
Categories = await _productRepository.GetCategories();
var products = await _productRepository.GetProducts();
ProductLast = products.LastOrDefault();
if (categoryId.HasValue)
{
Products = await _productRepository.GetProductByCategory(categoryId.Value);
SelectedCategory = Categories.FirstOrDefault(c => c.Id == categoryId.Value)?.Name;
}
else
{
Products = await _productRepository.GetProducts();
}
return Page();
}
public async Task<IActionResult> OnPostAddToCartAsync(int productId)
{
//if (!User.Identity.IsAuthenticated)
// return RedirectToPage("./Account/Login", new { area = "Identity" });
await _cartRepository.AddItem("test", productId);
return RedirectToPage("Cart");
}
}
} |
using System.Collections.Generic;
namespace SlrrLib.Model
{
public class BinaryInnerPhysEntry : FileEntry
{
protected static readonly int sigantureOffset = 0;
protected static readonly int sizeOffest = 4;
protected static readonly int firstChunkCountOffset = 8;
protected static readonly int firstChunkOffset = 12;
private IEnumerable<BinaryPhysFacingDescriptor> firstChunk = null;
private IEnumerable<BinaryPhysVertex> secondChunk = null;
public string Siganture
{
get
{
return GetFixLengthString(sigantureOffset, 4);
}
set
{
SetFixLengthString(value, 4, sigantureOffset);
}
}
public int FacingPropertyCount
{
get
{
return GetIntFromFile(firstChunkCountOffset);
}
set
{
SetIntInFile(value, firstChunkCountOffset);
}
}
public int VerticesCount
{
get
{
return GetIntFromFile(secondChunkCountOffset);
}
set
{
SetIntInFile(value, secondChunkCountOffset);
}
}
public IEnumerable<BinaryPhysFacingDescriptor> FacingProperties
{
get
{
if (firstChunk == null)
firstChunk = ReLoadFirstChunk();
return firstChunk;
}
set
{
firstChunk = value;
}
}
public IEnumerable<BinaryPhysVertex> Vetices
{
get
{
if (secondChunk == null)
secondChunk = ReLoadSecondChunk();
return secondChunk;
}
set
{
secondChunk = value;
}
}
public override int Size
{
get
{
return GetIntFromFile(sizeOffest, true) + 8;
}
set
{
SetIntInFile(value - 8, sizeOffest);
}
}
private int secondChunkCountOffset
{
get
{
return firstChunkOffset + GetIntFromFile(firstChunkCountOffset, true) * 28;
}
}
private int secondChunkOffset
{
get
{
return secondChunkCountOffset + 4;
}
}
public BinaryInnerPhysEntry(FileCacheHolder file, int offset, bool cache = false)
: base(file, offset, cache)
{
}
public IEnumerable<BinaryPhysFacingDescriptor> ReLoadFirstChunk()
{
List<BinaryPhysFacingDescriptor> ret = new List<BinaryPhysFacingDescriptor>();
int currentOffset = firstChunkOffset;
for (int vert_i = 0; vert_i != FacingPropertyCount; ++vert_i)
{
var toad = new BinaryPhysFacingDescriptor(Cache, Offset + currentOffset, Cache.IsDataCached);
ret.Add(toad);
currentOffset += toad.Size;
}
return ret;
}
public IEnumerable<BinaryPhysVertex> ReLoadSecondChunk()
{
List<BinaryPhysVertex> ret = new List<BinaryPhysVertex>();
int currentOffset = secondChunkOffset;
for (int vert_i = 0; vert_i != VerticesCount; ++vert_i)
{
var toad = new BinaryPhysVertex(Cache, Offset + currentOffset, Cache.IsDataCached);
ret.Add(toad);
currentOffset += toad.Size;
}
return ret;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using App1_Vagas.Modelos;
using App1_Vagas.Banco;
namespace App1_Vagas.Paginas
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConsultarVagas : ContentPage
{
List<Vaga> Lista { get; set; }
public ConsultarVagas ()
{
InitializeComponent();
Database database = new Database();
Lista = database.Consultar();
ListaVagas.ItemsSource = Lista;
lblCount.Text = Lista.Count.ToString();
}
public void GoCadastro(object sender, EventArgs args)
{
Navigation.PushAsync(new CadastrarVaga());
}
public void GoMinhasVagas(object sender, EventArgs args)
{
Navigation.PushAsync(new MinhasVagasCadastradas());
}
public void MaisDetalheAction(object sender, EventArgs args)
{
Label lblDetalhe = (Label)sender;
TapGestureRecognizer tapGest = (TapGestureRecognizer)lblDetalhe.GestureRecognizers[0];
Vaga vaga = tapGest.CommandParameter as Vaga;
Navigation.PushAsync(new DetalharVaga(vaga));
}
public void PesquisarAction(object sender, TextChangedEventArgs args)
{
ListaVagas.ItemsSource = Lista.Where(a => a.NomeVaga.Contains(args.NewTextValue)).ToList();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Shared.Contract.Options
{
public class StuffPackerConfigurationOptionNames
{
public const string Prefix = "StuffPacker:";
public static string SiteOptions => Prefix + "SiteOptions";
public static string StorageOptions => "StorageOptions";
}
}
|
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.PowerToys.Settings.UI.OOBE.Enums
{
public enum PowerToysModulesEnum
{
Overview = 0,
ColorPicker,
Awake,
FancyZones,
FileExplorer,
ImageResizer,
KBM,
PowerRename,
Run,
ShortcutGuide,
VideoConference,
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
namespace Excepticon.Examples.AspNetCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ErrorsController
{
[HttpGet]
public IActionResult Get()
{
// Any errors thrown in the app during the processing of a request will be
// intercepted and sent to Excepticon.
throw new ApplicationException("This error will be sent to Excepticon.");
}
}
}
|
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace IATA.AIDX
{
public sealed class AirportResources : IXmlSerializable
{
public string Usage { get; set; }
[XmlElement]
public ICollection<IAirportResource> Resource { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
Usage = reader.GetAttribute("Usage");
Resource = new List<IAirportResource>();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("AirportResources");
foreach (var airportResoure in Resource)
{
if (airportResoure is IXmlSerializable xmlSerializable)
{
xmlSerializable.WriteXml(writer);
}
}
writer.WriteEndElement();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.