content stringlengths 23 1.05M |
|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
public class Handler
{
private int _totalTestCount = 0;
public bool GetInitialThresholdTest()
{
_totalTestCount++;
int count = 0;
HandleCollector hc = null;
int[] initialValues = { 0, 1, 2, 3, 1000, 10000, Int32.MaxValue / 2, Int32.MaxValue };
foreach (int i in initialValues)
{
hc = new HandleCollector(null, i);
if (hc.InitialThreshold == i)
count++;
}
if (count != initialValues.Length)
{
Console.WriteLine("GetInitialThresholdTest Failed!");
return false;
}
return true;
}
public bool GetMaximumThresholdTest()
{
_totalTestCount++;
int count = 0;
HandleCollector hc = null;
int[] maxValues = { 0, 1, 2, 3, 1000, 10000, Int32.MaxValue / 2, Int32.MaxValue };
foreach (int i in maxValues)
{
hc = new HandleCollector(null, 0, i);
if (hc.MaximumThreshold == i)
count++;
}
if (count != maxValues.Length)
{
Console.WriteLine("GetMaximumThresholdTest Failed!");
return false;
}
return true;
}
public bool GetName()
{
_totalTestCount++;
int count = 0;
HandleCollector hc = null;
string[] names = { String.Empty, "a", "name", "name with spaces", new String('a', 50000), "\uA112\uA0E4\uA0F9" };
foreach (string s in names)
{
hc = new HandleCollector(s, 0);
if (hc.Name == s)
count++;
}
if (count != names.Length)
{
Console.WriteLine("GetNameTest Failed!");
return false;
}
return true;
}
public bool RunTest()
{
int count = 0;
if (GetInitialThresholdTest())
{
count++;
}
if (GetMaximumThresholdTest())
{
count++;
}
if (GetName())
{
count++;
}
return (count == _totalTestCount);
}
public static int Main()
{
Handler h = new Handler();
if (h.RunTest())
{
Console.WriteLine("Test Passed!");
return 100;
}
Console.WriteLine("Test Failed!");
return 1;
}
}
|
namespace SmartHub.Application.UseCases.DeviceState
{
public abstract class DeviceStateDto
{
public string? DeviceId { get; set; }
public bool? ToggleLight { get; set; } // on = true
}
}
|
namespace InAudioSystem
{
public class MultiData : InAudioNodeData
{
}
}
|
using SisoDb.Dac;
using SisoDb.Querying;
using SisoDb.Querying.Sql;
namespace SisoDb.Azure
{
public class SqlAzureQueryGenerator : DbQueryGenerator
{
public SqlAzureQueryGenerator(ISqlStatements sqlStatements, ISqlExpressionBuilder sqlExpressionBuilder)
: base(sqlStatements, sqlExpressionBuilder) {}
}
} |
using System;
using Urho;
using Urho.Actions;
using Urho.Gui;
using Urho.Shapes;
namespace Playgrounds.Console
{
public class EarthDemo : SimpleApplication
{
Node earthNode;
MonoDebugHud hud;
[Preserve]
public EarthDemo(ApplicationOptions options) : base(options) { }
public static void RunApp()
{
var app = new EarthDemo(
new ApplicationOptions(@"..\..\Samples\HoloLens\02_HelloWorldAdvanced\Data") {
Width = 960,
Height = 720,
UseDirectX11 = false
});
app.Run();
}
protected override async void Start()
{
base.Start();
hud = new MonoDebugHud(this);
hud.Show(Color.Yellow, 24);
var timeLabel = new Text {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Top
};
timeLabel.SetColor(new Color(0f, 1f, 0f));
timeLabel.SetFont(font: CoreAssets.Fonts.AnonymousPro , size: 30);
UI.Root.AddChild(timeLabel);
var azAltLabel = new Text {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom
};
azAltLabel.SetColor(new Color(0f, 1f, 0f));
azAltLabel.SetFont(font: CoreAssets.Fonts.AnonymousPro, size: 30);
UI.Root.AddChild(azAltLabel);
ResourceCache.AutoReloadResources = true;
Viewport.SetClearColor(Color.Black);
earthNode = RootNode.CreateChild();
earthNode.SetScale(5f);
earthNode.Rotation = new Quaternion(0, -180, 0);
var earthModel = earthNode.CreateComponent<Sphere>();
earthModel.Material = Material.FromImage("Textures/Earth.jpg");
Zone.AmbientColor = new Color(0.2f, 0.2f, 0.2f);
LightNode.ChangeParent(Scene);
LightNode.Position = Vector3.Zero;
Light.Range = 10;
Light.Brightness = 1f;
Light.LightType = LightType.Directional;
AddMarker(0, 0, "(0, 0)");
AddMarker(53.9045f, 27.5615f, "Minsk");
AddMarker(51.5074f, 0.1278f, "London");
AddMarker(40.7128f, -74.0059f, "New-York");
AddMarker(37.7749f, -122.4194f, "San Francisco");
AddMarker(39.9042f, 116.4074f, "Beijing");
AddMarker(-31.9505f, 115.8605f, "Perth");
var sunNode = RootNode.CreateChild();
var sunModelNode = sunNode.CreateChild();
sunModelNode.Position = new Vector3(0, 4, 0);
sunModelNode.SetScale(1);
var sun = sunModelNode.CreateComponent<Sphere>();
sun.Color = new Color(15, 10, 5);
// update the Sun's position based on time
var time = DateTime.Now;
float alt, az;
SunPosition.CalculateSunPosition(time, 0f, 0f, out az, out alt);
sunNode.Rotation = new Quaternion(-az, 0, alt);
LightNode.SetDirection(RootNode.WorldPosition - sunModelNode.WorldPosition);
timeLabel.Value = time.ToShortTimeString();
azAltLabel.Value = $"Azimuth: {az:F1}, Altitude: {alt:F1}";
}
public void AddMarker(float lat, float lon, string name)
{
var height = earthNode.Scale.Y / 2f;
lat = (float) Math.PI * lat / 180f - (float)Math.PI/2f;
lon = (float) Math.PI * lon / 180f;
float x = height * (float)Math.Sin(lat) * (float)Math.Cos(lon);
float z = height * (float)Math.Sin(lat) * (float)Math.Sin(lon);
float y = height * (float)Math.Cos(lat);
var markerNode = RootNode.CreateChild();
markerNode.Scale = Vector3.One * 0.1f;
markerNode.Position = new Vector3((float)x, (float)y, (float)z);
markerNode.CreateComponent<Sphere>();
markerNode.RunActionsAsync(new RepeatForever(
new TintTo(0.5f, Color.White),
new TintTo(0.5f, Color.Cyan)));
var textPos = markerNode.Position;
textPos.Normalize();
var textNode = markerNode.CreateChild();
textNode.Position = textPos * 1;
textNode.SetScale(2f);
textNode.LookAt(Vector3.Zero, Vector3.Up, TransformSpace.Parent);
var text = textNode.CreateComponent<Text3D>();
text.SetFont(CoreAssets.Fonts.AnonymousPro, 150);
text.EffectColor = Color.Black;
text.TextEffect = TextEffect.Stroke;
text.Text = name;
}
// http://guideving.blogspot.com.by/2010/08/sun-position-in-c.html
public static class SunPosition
{
private const double Deg2Rad = Math.PI / 180.0;
private const double Rad2Deg = 180.0 / Math.PI;
/*!
* \brief Calculates the sun light.
*
* CalcSunPosition calculates the suns "position" based on a
* given date and time in local time, latitude and longitude
* expressed in decimal degrees. It is based on the method
* found here:
* http://www.astro.uio.no/~bgranslo/aares/calculate.html
* The calculation is only satisfiably correct for dates in
* the range March 1 1900 to February 28 2100.
* \param dateTime Time and date in local time.
* \param latitude Latitude expressed in decimal degrees.
* \param longitude Longitude expressed in decimal degrees.
*/
public static void CalculateSunPosition(
DateTime dateTime, double latitude, double longitude, out float az, out float alt)
{
// Convert to UTC
dateTime = dateTime.ToUniversalTime();
// Number of days from J2000.0.
double julianDate = 367 * dateTime.Year -
(int)((7.0 / 4.0) * (dateTime.Year +
(int)((dateTime.Month + 9.0) / 12.0))) +
(int)((275.0 * dateTime.Month) / 9.0) +
dateTime.Day - 730531.5;
double julianCenturies = julianDate / 36525.0;
// Sidereal Time
double siderealTimeHours = 6.6974 + 2400.0513 * julianCenturies;
double siderealTimeUT = siderealTimeHours +
(366.2422 / 365.2422) * (double)dateTime.TimeOfDay.TotalHours;
double siderealTime = siderealTimeUT * 15 + longitude;
// Refine to number of days (fractional) to specific time.
julianDate += (double)dateTime.TimeOfDay.TotalHours / 24.0;
julianCenturies = julianDate / 36525.0;
// Solar Coordinates
double meanLongitude = CorrectAngle(Deg2Rad *
(280.466 + 36000.77 * julianCenturies));
double meanAnomaly = CorrectAngle(Deg2Rad *
(357.529 + 35999.05 * julianCenturies));
double equationOfCenter = Deg2Rad * ((1.915 - 0.005 * julianCenturies) *
Math.Sin(meanAnomaly) + 0.02 * Math.Sin(2 * meanAnomaly));
double elipticalLongitude =
CorrectAngle(meanLongitude + equationOfCenter);
double obliquity = (23.439 - 0.013 * julianCenturies) * Deg2Rad;
// Right Ascension
double rightAscension = Math.Atan2(
Math.Cos(obliquity) * Math.Sin(elipticalLongitude),
Math.Cos(elipticalLongitude));
double declination = Math.Asin(
Math.Sin(rightAscension) * Math.Sin(obliquity));
// Horizontal Coordinates
double hourAngle = CorrectAngle(siderealTime * Deg2Rad) - rightAscension;
if (hourAngle > Math.PI)
{
hourAngle -= 2 * Math.PI;
}
double altitude = Math.Asin(Math.Sin(latitude * Deg2Rad) *
Math.Sin(declination) + Math.Cos(latitude * Deg2Rad) *
Math.Cos(declination) * Math.Cos(hourAngle));
// Nominator and denominator for calculating Azimuth
// angle. Needed to test which quadrant the angle is in.
double aziNom = -Math.Sin(hourAngle);
double aziDenom =
Math.Tan(declination) * Math.Cos(latitude * Deg2Rad) -
Math.Sin(latitude * Deg2Rad) * Math.Cos(hourAngle);
double azimuth = Math.Atan(aziNom / aziDenom);
if (aziDenom < 0) // In 2nd or 3rd quadrant
{
azimuth += Math.PI;
}
else if (aziNom < 0) // In 4th quadrant
{
azimuth += 2 * Math.PI;
}
alt = (float)(altitude * Rad2Deg);
az = (float)(azimuth * Rad2Deg);
}
private static double CorrectAngle(double angleInRadians)
{
if (angleInRadians < 0)
return 2 * Math.PI - (Math.Abs(angleInRadians) % (2 * Math.PI));
if (angleInRadians > 2 * Math.PI)
return angleInRadians % (2 * Math.PI);
return angleInRadians;
}
}
}
}
|
using System;
using System.Linq.Expressions;
using NRules.RuleModel;
namespace NRules.Fluent.Dsl
{
/// <summary>
/// Rule's right-hand side (actions) expression builder.
/// </summary>
public interface IRightHandSideExpression
{
/// <summary>
/// Defines rule's action that engine executes for a given trigger.
/// </summary>
/// <param name="action">Action expression.</param>
/// <param name="actionTrigger">Events that should trigger this action.</param>
/// <returns>Right hand side expression builder.</returns>
IRightHandSideExpression Action(Expression<Action<IContext>> action, ActionTrigger actionTrigger);
/// <summary>
/// Defines rule's action that engine executes when the rule fires
/// due to the initial rule match or due to an update.
/// </summary>
/// <param name="action">Action expression.</param>
/// <returns>Right hand side expression builder.</returns>
IRightHandSideExpression Do(Expression<Action<IContext>> action);
/// <summary>
/// Defines rule's action that engine executes when the rule fires
/// due to the match removal (provided the rule previously fired on the match).
/// </summary>
/// <param name="action">Action expression.</param>
/// <returns>Right hand side expression builder.</returns>
IRightHandSideExpression Undo(Expression<Action<IContext>> action);
/// <summary>
/// Defines rule's action that yields a linked fact when the rule fires.
/// If the rule fires due to an update, the linked fact is also updated with the new yielded value.
/// </summary>
/// <typeparam name="TFact">Type of fact to yield.</typeparam>
/// <param name="yield">Action expression that yields the linked fact.</param>
/// <returns>Right hand side expression builder.</returns>
IRightHandSideExpression Yield<TFact>(Expression<Func<IContext, TFact>> yield);
/// <summary>
/// Defines rule's action that yields a linked fact when the rule fires.
/// If the rule fires due to an update, the update expression is evaluated to produce an updated linked fact.
/// </summary>
/// <typeparam name="TFact">Type of fact to yield.</typeparam>
/// <param name="yieldInsert">Action expression that yields a new linked fact.</param>
/// <param name="yieldUpdate">Action expression that yields an updated linked fact.</param>
/// <returns>Right hand side expression builder.</returns>
IRightHandSideExpression Yield<TFact>(Expression<Func<IContext, TFact>> yieldInsert, Expression<Func<IContext, TFact, TFact>> yieldUpdate);
}
} |
namespace DSPPlugins_ALT.Statistics
{
public class StationItemStat
{
internal StationStore item;
internal ItemProto itemProto;
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using CaptainHook.Platform.OSX;
using CaptainHook.Platform.Windows;
namespace CaptainHook
{
public class KeyboardHook : IDisposable
{
public readonly IKeyboardHook Hook;
public KeyboardHook()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Hook = new WindowsKeyboardHook();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Hook = new OsxKeyboardHook();
}
else
{
throw new PlatformNotSupportedException("Platform not yet supported. Maybe you should do a PR.");
}
}
public void Start()
{
Hook.Start();
}
public void Dispose()
{
}
}
}
|
// Mileage Tracker: Unit Tests
// Copyright (c) bfren - licensed under https://mit.bfren.dev/2022
using Jeebs.Auth.Data;
using Jeebs.Messages;
using Mileage.Persistence.Common.StrongIds;
using Mileage.Persistence.Entities;
using Mileage.Persistence.Repositories;
namespace Mileage.Domain.SaveSettings.Internals.CreateSettingsHandler_Tests;
public class HandleAsync_Tests : Abstracts.TestHandler
{
private class Setup : Setup<ISettingsRepository, SettingsEntity, SettingsId, CreateSettingsHandler>
{
internal override CreateSettingsHandler GetHandler(Vars v) =>
new(v.Repo, v.Log);
}
private (CreateSettingsHandler, Setup.Vars) GetVars() =>
new Setup().GetVars();
[Fact]
public async Task Calls_Logs_Vrb__With_UserId()
{
// Arrange
var (handler, v) = GetVars();
var userId = LongId<AuthUserId>();
var command = new CreateSettingsCommand(userId, new());
v.Repo.CreateAsync(default!)
.ReturnsForAnyArgs(Create.None<SettingsId>());
// Act
await handler.HandleAsync(command);
// Assert
v.Log.Received().Vrb("Creating new settings for user {UserId}.", userId.Value);
}
[Fact]
public async Task Calls_Repo_CreateAsync__With_Correct_Values()
{
// Arrange
var (handler, v) = GetVars();
var userId = LongId<AuthUserId>();
var settingsId = LongId<SettingsId>();
var carId = LongId<CarId>();
var placeId = LongId<PlaceId>();
var rateId = LongId<RateId>();
var command = new CreateSettingsCommand(userId, new(new(), 0L, carId, placeId, rateId));
v.Repo.CreateAsync(default!)
.ReturnsForAnyArgs(settingsId);
// Act
await handler.HandleAsync(command);
// Assert
await v.Repo.Received().CreateAsync(Arg.Is<SettingsEntity>(
x => x.UserId == userId && x.DefaultCarId == carId && x.DefaultFromPlaceId == placeId && x.DefaultRateId == rateId
));
}
[Fact]
public async Task Calls_Repo_CreateAsync__Receives_Some__Audits_To_Vrb()
{
// Arrange
var (handler, v) = GetVars();
var userId = LongId<AuthUserId>();
var settingsId = LongId<SettingsId>();
var command = new CreateSettingsCommand(userId, new());
v.Repo.CreateAsync(default!)
.ReturnsForAnyArgs(settingsId);
// Act
await handler.HandleAsync(command);
// Assert
v.Log.Received().Vrb("Created settings {SettingsId} for user {UserId}.", settingsId.Value, userId.Value);
}
[Fact]
public async Task Calls_Repo_CreateAsync__Receives_Some__Returns_True()
{
// Arrange
var (handler, v) = GetVars();
var command = new CreateSettingsCommand(new(), new());
v.Repo.CreateAsync(default!)
.ReturnsForAnyArgs(LongId<SettingsId>());
// Act
var result = await handler.HandleAsync(command);
// Assert
result.AssertTrue();
}
[Fact]
public async void Calls_Repo_CreateAsync__Receives_None__Returns_Result()
{
// Arrange
var (handler, v) = GetVars();
var command = new CreateSettingsCommand(new(), new());
var msg = new TestMsg();
var failed = F.None<SettingsId>(msg);
v.Repo.CreateAsync(default!)
.ReturnsForAnyArgs(failed);
// Act
var result = await handler.HandleAsync(command);
// Assert
var none = result.AssertNone();
Assert.Same(msg, none);
}
public sealed record class TestMsg : Msg;
}
|
namespace GroupDocs.Viewer.UI.Api.Cloud.Storage.Configuration
{
public class Config
{
internal string ApiEndpoint = "https://api.groupdocs.cloud/v2.0/";
internal string ClientId = string.Empty;
internal string ClientSecret = string.Empty;
internal string StorageName = string.Empty;
/// <summary>
/// Setup the API endpoint. By default it is "https://api-qa.groupdocs.cloud/v2.0/".
/// </summary>
/// <param name="apiEndpoint">GroupDocs.Viewer Cloud API endpoint.</param>
/// <returns>This instance</returns>
public Config SetApiEndpoint(string apiEndpoint)
{
ApiEndpoint = apiEndpoint;
return this;
}
/// <summary>
/// The client ID, get it at https://dashboard.groupdocs.cloud/applications
/// </summary>
/// <param name="clientId">The client ID</param>
/// <returns>This instance</returns>
public Config SetClientId(string clientId)
{
ClientId = clientId;
return this;
}
/// <summary>
/// The client secret, get it at https://dashboard.groupdocs.cloud/applications
/// </summary>
/// <param name="clientSecret">The secret</param>
/// <returns>This instance</returns>
public Config SetClientSecret(string clientSecret)
{
ClientSecret = clientSecret;
return this;
}
/// <summary>
/// Set storage name, you can find storage list at https://dashboard.groupdocs.cloud/storages.
/// When not set default storage is used.
/// </summary>
/// <param name="storageName">The storage name</param>
/// <returns>This instance</returns>
public Config SetStorageName(string storageName)
{
StorageName = storageName;
return this;
}
}
}
|
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
namespace SATREMI.Win.Utils
{
class ExcelBuilder
{
public string Plantilla { get; set; }
public string Titulo { get; set; }
public string SubTitulo { get; set; }
public string[] Cabeceras { get; set; }
public string HojaContenido { get; set; }
public object[][] DatosAdicionales { get; set; }
private Posicion PosicionContenido;
private Posicion PosicionDatosAdicionales;
private Posicion PosicionSubTitulo;
public int[] ColumnasOcultas { get; set; }
private Posicion PosicionTitulo;
private List<Contenido> Contenidos { get; set; }
private string HojaTitulo { get; set; }
public ExcelBuilder()
{
Plantilla = null;
Titulo = null;
SubTitulo = null;
Cabeceras = null;
HojaContenido = null;
PosicionContenido = null;
PosicionDatosAdicionales = null;
PosicionSubTitulo = null;
PosicionTitulo = null;
ColumnasOcultas = null;
Contenidos = new List<Contenido>();
HojaTitulo = null;
}
public void agregarContenido(DataTable datos, string hoja, int x, int y)
{
Contenidos.Add(new Contenido()
{
Datos = datos,
HojaExcel = hoja,
X = x,
Y = y
});
}
public void agregarContenido(object[][] datos, string hoja, int x, int y, string sColor = "")
{
Contenidos.Add(new Contenido()
{
Datos = datos,
HojaExcel = hoja,
X = x,
Y = y,
Color = sColor//PROY-ABSA-2015-001 JZAMUDIO
});
}
public void SetTitulo(string hojatitulo, string titulo, int x, int y)
{
this.HojaTitulo = hojatitulo;
this.Titulo = titulo;
this.PosicionTitulo = new Posicion() { X = x, Y = y };
}
public void SetDatosAdicionales(object[][] datos, int x, int y)
{
this.DatosAdicionales = datos;
this.PosicionDatosAdicionales = new Posicion() { X = x, Y = y };
}
public void SetTitulo(string titulo, int x, int y)
{
this.Titulo = titulo;
this.PosicionTitulo = new Posicion() { X = x, Y = y };
}
public void SetSubTitulo(string titulo, int x, int y)
{
this.SubTitulo = titulo;
this.PosicionSubTitulo = new Posicion() { X = x, Y = y };
}
public void SetHojaContenido(string hoja, int x, int y)
{
this.HojaContenido = hoja;
this.PosicionContenido = new Posicion() { X = x, Y = y };
}
public byte[] Crear(DataTable dt)
{
byte[] buffer = null;
ExcelPackage pck = null;
ExcelWorksheet sheet = null;
try
{
if (String.IsNullOrEmpty(this.Plantilla))
{
pck = new ExcelPackage();
sheet = pck.Workbook.Worksheets.Add("datos");
}
else
{
FileInfo template = new FileInfo(this.Plantilla);
pck = new ExcelPackage(template, true);
}
if (!string.IsNullOrEmpty(this.HojaContenido))
{
sheet = pck.Workbook.Worksheets[this.HojaContenido];
}
if (!String.IsNullOrEmpty(this.Titulo))
{
sheet.Cells[PosicionTitulo.X, PosicionTitulo.Y].Value = this.Titulo;
}
if (!String.IsNullOrEmpty(this.SubTitulo))
{
sheet.Cells[PosicionSubTitulo.X, PosicionSubTitulo.Y].Value = this.SubTitulo;
}
//TODO: falta implementar la funcionalidad de la cabecera
int row = PosicionContenido == null ? 1 : PosicionContenido.X;
int col = PosicionContenido == null ? 1 : PosicionContenido.Y;
sheet.Cells[row, col].LoadFromDataTable(dt, false);
if (DatosAdicionales != null)
{
sheet.Cells[PosicionDatosAdicionales.X, PosicionDatosAdicionales.Y]
.LoadFromArrays(DatosAdicionales);
}
if (ColumnasOcultas != null)
{
foreach (int indexCol in ColumnasOcultas)
{
sheet.Column(indexCol).Hidden = true;
}
}
buffer = pck.GetAsByteArray();
}
finally
{
if (pck != null) { pck.Dispose(); }
}
return buffer;
}
public byte[] Crear()
{
byte[] buffer = null;
ExcelPackage pck = null;
ExcelWorksheet sheet = null;
try
{
if (String.IsNullOrEmpty(this.Plantilla))
{
pck = new ExcelPackage();
}
else
{
FileInfo template = new FileInfo(this.Plantilla);
template.IsReadOnly = false;
pck = new ExcelPackage(template, true);
}
if (!(String.IsNullOrEmpty(this.HojaTitulo)))
{
if (String.IsNullOrEmpty(this.Plantilla))
{
sheet = pck.Workbook.Worksheets.Add(this.HojaTitulo);
}
else
{
sheet = pck.Workbook.Worksheets[this.HojaTitulo];
}
sheet.Cells[this.PosicionTitulo.X, this.PosicionTitulo.Y].Value = this.Titulo;
}
if (!String.IsNullOrEmpty(this.Titulo))
{
sheet.Cells[PosicionTitulo.X, PosicionTitulo.Y].Value = this.Titulo;
}
foreach (Contenido contenido in this.Contenidos)
{
if (String.IsNullOrEmpty(this.Plantilla))
{
sheet = pck.Workbook.Worksheets.Add(contenido.HojaExcel);
}
else
{
sheet = pck.Workbook.Worksheets[contenido.HojaExcel];
}
int row = contenido.X;
int col = contenido.Y;
if (contenido.Datos is DataTable)
{
var aux = (DataTable)contenido.Datos;
sheet.Cells[row, col].LoadFromDataTable(aux, false);
}
else if (contenido.Datos is Array)
{
var aux = (object[][])contenido.Datos;
sheet.Cells[row, col].LoadFromArrays(aux);
if (contenido.Color.Trim().Length > 0)
{
Color colFromHex = System.Drawing.ColorTranslator.FromHtml(contenido.Color.Trim());
sheet.Cells[row + 1, col].Style.Fill.PatternType = ExcelFillStyle.Solid;
sheet.Cells[row + 1, col].Style.Fill.BackgroundColor.SetColor(colFromHex);
}
}
if (ColumnasOcultas != null)
{
foreach (int indexCol in ColumnasOcultas)
{
sheet.Column(indexCol).Hidden = true;
}
}
}
buffer = pck.GetAsByteArray();
}
finally
{
if (sheet != null) { sheet.Dispose(); }
if (pck != null) { pck.Dispose(); }
}
return buffer;
}
public class Posicion
{
public int X { get; set; }
public int Y { get; set; }
}
private class Contenido
{
public object Datos { get; set; }
public String HojaExcel { get; set; }
public int X { get; set; }
public int Y { get; set; }
public string Color { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Three.Net.Math
{
public struct Vector4 : IEquatable<Vector4>
{
public float x, y, z, w;
public Vector4(float x, float y, float z, float w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public void Set(float x, float y, float z, float w)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public float this[int key]
{
get
{
switch (key)
{
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return w;
default: throw new Exception("index is out of range: " + key);
}
}
set
{
switch (key)
{
case 0: x = value; break;
case 1: y = value; break;
case 2: z = value; break;
case 3: w = value; break;
default: throw new Exception("index is out of range: " + key);
}
}
}
public void Set(Vector4 v)
{
x = v.x;
y = v.y;
z = v.z;
w = v.w;
}
public void Add(Vector4 v)
{
this.x += v.x;
this.y += v.y;
this.z += v.z;
this.w += v.w;
}
public void Add(float s)
{
x += s;
y += s;
z += s;
w += s;
}
public void AddVectors(Vector4 a, Vector4 b)
{
x = a.x + b.x;
y = a.y + b.y;
z = a.z + b.z;
w = a.w + b.w;
}
public void Subtract(Vector4 v)
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
}
public void SubtractVectors(Vector4 a, Vector4 b)
{
x = a.x - b.x;
y = a.y - b.y;
z = a.z - b.z;
w = a.w - b.w;
}
public void Multiply(float scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
w *= scalar;
}
public void Apply(Matrix4 m)
{
var x = this.x;
var y = this.y;
var z = this.z;
var w = this.w;
var e = m.elements;
this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
}
public void Divide(float scalar)
{
if (scalar != 0)
{
var invScalar = 1 / scalar;
x *= invScalar;
y *= invScalar;
z *= invScalar;
w *= invScalar;
}
else
{
x = 0;
y = 0;
z = 0;
w = 1;
}
}
public void SetAxisAngleFromQuaternion(Quaternion q)
{
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
// q is assumed to be normalized
w = 2 * Mathf.Acos(q.w);
var s = Mathf.Sqrt(1 - q.w * q.w);
if (s < 0.0001f)
{
x = 1;
y = 0;
z = 0;
}
else
{
x = q.x / s;
y = q.y / s;
z = q.z / s;
}
}
public void SetAxisAngleFromRotationMatrix(Matrix4 m)
{
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
float angle, x, y, z, // variables for result
epsilon = 0.01f, // margin to allow for rounding errors
epsilon2 = 0.1f; // margin to distinguish between 0 and 180 degrees
var te = m.elements;
float m11 = te[0], m12 = te[4], m13 = te[8];
float m21 = te[1], m22 = te[5], m23 = te[9];
float m31 = te[2], m32 = te[6], m33 = te[10];
if ((Mathf.Abs(m12 - m21) < epsilon)
&& (Mathf.Abs(m13 - m31) < epsilon)
&& (Mathf.Abs(m23 - m32) < epsilon))
{
// singularity found
// first check for identity matrix which must have +1 for all terms
// in leading diagonal and zero in other terms
if ((Mathf.Abs(m12 + m21) < epsilon2)
&& (Mathf.Abs(m13 + m31) < epsilon2)
&& (Mathf.Abs(m23 + m32) < epsilon2)
&& (Mathf.Abs(m11 + m22 + m33 - 3) < epsilon2))
{
// this singularity is identity matrix so angle = 0
Set(1, 0, 0, 0);
return; // zero angle, arbitrary axis
}
// otherwise this singularity is angle = 180
angle = Mathf.Pi;
var xx = (m11 + 1) / 2;
var yy = (m22 + 1) / 2;
var zz = (m33 + 1) / 2;
var xy = (m12 + m21) / 4;
var xz = (m13 + m31) / 4;
var yz = (m23 + m32) / 4;
if ((xx > yy) && (xx > zz))
{ // m11 is the largest diagonal term
if (xx < epsilon)
{
x = 0;
y = 0.707106781f;
z = 0.707106781f;
}
else
{
x = Mathf.Sqrt(xx);
y = xy / x;
z = xz / x;
}
}
else if (yy > zz)
{ // m22 is the largest diagonal term
if (yy < epsilon)
{
x = 0.707106781f;
y = 0;
z = 0.707106781f;
}
else
{
y = Mathf.Sqrt(yy);
x = xy / y;
z = yz / y;
}
}
else
{ // m33 is the largest diagonal term so base result on this
if (zz < epsilon)
{
x = 0.707106781f;
y = 0.707106781f;
z = 0;
}
else
{
z = Mathf.Sqrt(zz);
x = xz / z;
y = yz / z;
}
}
Set(x, y, z, angle);
return; // return 180 deg rotation
}
// as we have reached here there are no singularities so we can handle normally
var s = Mathf.Sqrt((m32 - m23) * (m32 - m23)
+ (m13 - m31) * (m13 - m31)
+ (m21 - m12) * (m21 - m12)); // used to normalize
if (Mathf.Abs(s) < 0.001f) s = 1;
// prevent divide by zero, should not happen if matrix is orthogonal and should be
// caught by singularity test above, but I've left it in just in case
this.x = (m32 - m23) / s;
this.y = (m13 - m31) / s;
this.z = (m21 - m12) / s;
this.w = Mathf.Acos((m11 + m22 + m33 - 1) / 2);
}
public void Min(Vector4 v)
{
if (x > v.x) x = v.x;
if (y > v.y) y = v.y;
if (z > v.z) z = v.z;
if (w > v.w) w = v.w;
}
public void Max(Vector4 v)
{
if (x < v.x) x = v.x;
if (y < v.y) y = v.y;
if (z < v.z) z = v.z;
if (w < v.w) w = v.w;
}
public void Clamp(Vector4 min, Vector4 max)
{
// This function assumes min < max, if this assumption isn't true it will not operate correctly
if (x < min.x) x = min.x;
else if (x > max.x) x = max.x;
if (y < min.y) y = min.y;
else if (y > max.y) y = max.y;
if (z < min.z) this.z = min.z;
else if (z > max.z) z = max.z;
if (w < min.w) w = min.w;
else if (w > max.w) w = max.w;
}
public void Clamp(float minVal, float maxVal)
{
var min = new Vector4(minVal, minVal, minVal, minVal);
var max = new Vector4(maxVal, maxVal, maxVal, maxVal);
Clamp(min, max);
}
public void Floor()
{
x = Mathf.Floor(x);
y = Mathf.Floor(y);
z = Mathf.Floor(z);
w = Mathf.Floor(w);
}
public void Ceiling()
{
x = Mathf.Ceiling(x);
y = Mathf.Ceiling(y);
z = Mathf.Ceiling(z);
w = Mathf.Ceiling(w);
}
public void Round()
{
x = Mathf.Round(x);
y = Mathf.Round(y);
z = Mathf.Round(z);
w = Mathf.Round(w);
}
public void RoundToZero()
{
x = (x < 0) ? Mathf.Ceiling(x) : Mathf.Floor(x);
y = (y < 0) ? Mathf.Ceiling(y) : Mathf.Floor(y);
z = (z < 0) ? Mathf.Ceiling(z) : Mathf.Floor(z);
w = (w < 0) ? Mathf.Ceiling(w) : Mathf.Floor(w);
}
public void Negate()
{
x = -x;
y = -y;
z = -z;
w = -w;
}
public float Dot(Vector4 v)
{
return x * v.x + y * v.y + z * v.z + w * v.w;
}
public float LengthSquared()
{
return x * x + y * y + z * z + w * w;
}
public float Length()
{
return Mathf.Sqrt(Length());
}
public float LengthManhattan()
{
return Mathf.Abs(x) + Mathf.Abs(y) + Mathf.Abs(z) + Mathf.Abs(w);
}
public void Normalize()
{
Divide(Length());
}
public void SetLength(float l)
{
var oldLength = Length();
if (oldLength != 0 && l != oldLength) Multiply(l / oldLength);
}
public void Lerp(Vector4 v, float alpha)
{
x += (v.x - x) * alpha;
y += (v.y - y) * alpha;
z += (v.z - z) * alpha;
w += (v.w - w) * alpha;
}
public bool Equals(Vector4 v)
{
return ((v.x == x) && (v.y == y) && (v.z == z) && (v.w == w));
}
public void FromArray(float[] array)
{
x = array[0];
y = array[1];
z = array[2];
w = array[3];
}
public float[] ToArray()
{
return new float[] { x, y, z, w };
}
public override string ToString()
{
return string.Format("{0},{1},{2},{3}", x, y, z, w);
}
}
} |
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using ToolsUtilities;
namespace FRBDKUpdater.Actions
{
public static class ActionStarter
{
static string UserApplicationData =>
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\";
private static bool IsAdministrator
{
get
{
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi);
return wp.IsInRole(WindowsBuiltInRole.Administrator);
}
}
private static bool StartAsAdmin(string[] args)
{
for (var i = 0; i < args.Count(); i++)
{
args[i] = "\"" + args[i] + "\"";
}
var process = new Process
{
StartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location,
"\"" + UserApplicationData + "\" " + String.Join(" ", args))
{
Verb = "runas"
}
};
process.StartInfo.Arguments = process.StartInfo.Arguments.Replace("\\\"", "\\\\\"");
process.Start();
process.WaitForExit();
return process.ExitCode == 1;
}
public static bool CleanAndZipAction(string directoryToClear, string saveFile, string extractionPath)
{
try
{
Actions.CleanAndZipAction.CleanAndZip(UserApplicationData, directoryToClear, saveFile, extractionPath);
return true;
}
//Need to run in admin mode
catch (UnauthorizedAccessException ex)
{
Logger.Log("Restarting Updater in admin mode...");
return StartAsAdmin(new[] { "CleanAndZip", directoryToClear, saveFile, extractionPath, Messaging.ShowAlerts.ToString()});
}
catch (InvalidOperationException ioe)
{
Messaging.AlertError(@"Unzip failed.", ioe);
Logger.LogAndShowImmediately(UserApplicationData, @"Unzip failed.\n\nException Info:\n" + ioe);
return false;
}
}
}
}
|
namespace AutoHelp.web.netcore.Models
{
public class Event
{
}
}
|
using Crm.Domain.SeedWork;
using System;
namespace Crm.Domain.Companies.Activities
{
public class Activity : Entity
{
internal ActivityId Id;
private string _sectorType;
private string _activityType;
private bool _value;
private bool _isRemoved;
private Activity() {
_isRemoved = false;
}
private Activity(string sectorType, string activityType, bool value)
{
Id = new ActivityId(Guid.NewGuid());
_sectorType = sectorType;
_activityType = activityType;
_value = value;
_isRemoved = false;
}
internal static Activity CreateNew(string sectorType, string activityType, bool value)
{
return new Activity(sectorType, activityType, value);
}
internal void Remove()
{
_isRemoved = true;
}
}
}
|
using Windows.UI.Xaml.Input;
namespace ReactNative.Views.TextInput
{
static class InputScopeHelpers
{
public static InputScopeNameValue FromString(string inputScope)
{
switch (inputScope)
{
case "url":
return InputScopeNameValue.Url;
case "number-pad":
return InputScopeNameValue.NumericPin;
case "phone-pad":
return InputScopeNameValue.TelephoneNumber;
case "name-phone-pad":
return InputScopeNameValue.NameOrPhoneNumber;
case "email-address":
return InputScopeNameValue.EmailNameOrAddress;
case "decimal-pad":
return InputScopeNameValue.Digits;
case "web-search":
return InputScopeNameValue.Search;
case "numeric":
return InputScopeNameValue.Number;
default:
return InputScopeNameValue.Default;
}
}
}
}
|
using CodePathFinder.CodeAnalysis.PathFinding;
using CodePathFinder.Test.CodeAnalysis.PathFinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace CodePathFinder.Test.TestGraphImpl
{
[Serializable]
public class GraphCodePathResult
{
/// <summary>
/// End node ID
/// </summary>
[XmlAttribute(AttributeName = "ids", DataType = "string")]
public string Ids { get; set; }
public CodePath ToCodePath()
{
var path = new CodePath();
var idList = this.Ids.Split(',');
foreach (var id in idList)
{
path.AddLast(new MockMethod(int.Parse(id)));
}
return path;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Web.UI;
using NUnit.Framework;
using ComLib.Paging;
namespace CommonLibrary.Tests
{
[TestFixture]
public class PagerTests
{
[Test]
public void IsNotMultiplePages()
{
Pager pager = new Pager(1, 1);
Assert.IsFalse(pager.IsMultiplePages);
CheckNavigation(pager, false, false, false, false);
CheckPages(pager, 1, 1, 1, 1, 1);
}
[Test]
public void IsMultiplePages()
{
Pager pager = new Pager(1, 4);
Assert.IsTrue(pager.IsMultiplePages);
CheckNavigation(pager, false, false, false, false);
CheckPages(pager, 1, 1, 1, 4, 2);
}
[Test]
public void CanMoveToNextPage_SingleRange()
{
Pager pager = new Pager(1, 4);
CheckPages(pager, 1, 1, 1, 4, 2);
CheckNavigation(pager, false, false, false, false);
pager.MoveNext();
CheckPages(pager, 2, 1, 1, 4, 3);
CheckNavigation(pager, false, false, false, false);
}
[Test]
public void CanMoveToNextPage_ManyRanges()
{
Pager pager = new Pager(1, 18, new PagerSettings() { NumberPagesToDisplay = 5 });
CheckPages(pager, 1, 1, 1, 5, 2);
CheckNavigation(pager, false, false, true, true);
pager.MoveNext();
CheckPages(pager, 2, 1, 1, 5, 3);
CheckNavigation(pager, false, false, true, true);
}
[Test]
public void CanMoveToNextRange_2Ranges()
{
Pager pager = new Pager(1, 10, new PagerSettings() { NumberPagesToDisplay = 5 });
CheckPages(pager, 1, 1, 1, 5, 2);
CheckNavigation(pager, false, false, true, true);
// Move to last page in first range ( 1 - 5 )
pager.MoveToPage(5);
CheckPages(pager, 5, 4, 1, 5, 6);
CheckNavigation(pager, false, false, true, true);
// Move to first page in next range ( 6 - 10 )
pager.MoveNext();
CheckPages(pager, 6, 5, 6, 10, 7);
CheckNavigation(pager, true, true, false, false);
}
[Test]
public void CanMoveTo2ndRange_3Ranges()
{
Pager pager = new Pager(1, 15, new PagerSettings() { NumberPagesToDisplay = 5 });
CheckPages(pager, 1, 1, 1, 5, 2);
CheckNavigation(pager, false, false, true, true);
// Move to last page in first range ( 1 - 5 )
pager.MoveToPage(5);
CheckPages(pager, 5, 4, 1, 5, 6);
CheckNavigation(pager, false, false, true, true);
// Move to first page in next range ( 6 - 10 )
pager.MoveNext();
CheckPages(pager, 6, 5, 6, 10, 7);
CheckNavigation(pager, true, true, true, true);
}
[Test]
public void CanMoveTo3rdRange_3Ranges()
{
Pager pager = new Pager(1, 13, new PagerSettings() { NumberPagesToDisplay = 5 });
CheckPages(pager, 1, 1, 1, 5, 2);
CheckNavigation(pager, false, false, true, true);
// Move to last page 5 in first range ( 1 - 5 )
pager.MoveToPage(5);
CheckPages(pager, 5, 4, 1, 5, 6);
CheckNavigation(pager, false, false, true, true);
// Move to first page 6 in next range ( 6 - 10 )
pager.MoveNext();
CheckPages(pager, 6, 5, 6, 10, 7);
CheckNavigation(pager, true, true, true, true);
// Move to last page 10 in 2nd range ( 6 - 10 )
pager.MoveToPage(10);
CheckPages(pager, 10, 9, 6, 10, 11);
CheckNavigation(pager, true, true, true, true);
// Move to first page 11 in last range ( 9 - 13 )
pager.MoveNext();
CheckPages(pager, 11, 10, 9, 13, 12);
CheckNavigation(pager, true, true, false, false);
// Move to previous page 10 in 2nd range ( 6 - 10 )
pager.MovePrevious();
CheckPages(pager, 10, 9, 6, 10, 11);
CheckNavigation(pager, true, true, true, true);
}
private void CheckPages(Pager pager, int current, int previous, int starting, int ending, int next)
{
Assert.AreEqual(pager.CurrentPage, current);
Assert.AreEqual(pager.PreviousPage, previous);
Assert.AreEqual(pager.StartingPage, starting);
Assert.AreEqual(pager.EndingPage, ending);
Assert.AreEqual(pager.NextPage, next);
}
private void CheckNavigation(Pager pager, bool showFirst, bool showPrevious, bool showNext, bool showLast)
{
Assert.AreEqual(pager.CanShowFirst, showFirst);
Assert.AreEqual(pager.CanShowPrevious, showPrevious);
Assert.AreEqual(pager.CanShowNext, showNext);
Assert.AreEqual(pager.CanShowLast, showLast);
}
}
}
|
using Microsoft.Web.WebView2.Core;
namespace WebView2.DOM
{
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/svg/svg_fe_image_element.idl
public partial class SVGFEImageElement : SVGElement
{
protected internal SVGFEImageElement(CoreWebView2 coreWebView, string referenceId)
: base(coreWebView, referenceId) { }
public SVGAnimatedPreserveAspectRatio preserveAspectRatio =>
Get<SVGAnimatedPreserveAspectRatio>();
}
public partial class SVGFEImageElement : SVGFilterPrimitiveStandardAttributes
{
public SVGAnimatedLength x => Get<SVGAnimatedLength>();
public SVGAnimatedLength y => Get<SVGAnimatedLength>();
public SVGAnimatedLength width => Get<SVGAnimatedLength>();
public SVGAnimatedLength height => Get<SVGAnimatedLength>();
public SVGAnimatedString result => Get<SVGAnimatedString>();
}
public partial class SVGFEImageElement : SVGURIReference
{
public SVGAnimatedString href => Get<SVGAnimatedString>();
}
} |
using UnityEngine;
using UnityEditor;
using System.Linq;
namespace uDesktopDuplication
{
[CustomEditor(typeof(Texture))]
public class TextureEditor : Editor
{
Texture texture
{
get { return target as Texture; }
}
Monitor monitor
{
get { return texture.monitor; }
}
bool isAvailable
{
get { return monitor == null || !Application.isPlaying; }
}
bool basicsFolded_ = true;
bool invertFolded_ = true;
bool clipFolded_ = true;
bool matFolded_ = true;
SerializedProperty invertX_;
SerializedProperty invertY_;
SerializedProperty useClip_;
SerializedProperty clipPos_;
SerializedProperty clipScale_;
void OnEnable()
{
invertX_ = serializedObject.FindProperty("invertX_");
invertY_ = serializedObject.FindProperty("invertY_");
useClip_ = serializedObject.FindProperty("useClip_");
clipPos_ = serializedObject.FindProperty("clipPos");
clipScale_ = serializedObject.FindProperty("clipScale");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.Space();
DrawMonitor();
DrawInvert();
DrawClip();
DrawMaterial();
serializedObject.ApplyModifiedProperties();
}
void Fold(string name, ref bool folded, System.Action func)
{
folded = Utils.Foldout(name, folded);
if (folded) {
++EditorGUI.indentLevel;
func();
--EditorGUI.indentLevel;
}
}
void DrawMonitor()
{
Fold("Monitor", ref basicsFolded_, () => {
if (isAvailable) {
EditorGUILayout.HelpBox("Monitor information is available only in runtime.", MessageType.Info);
return;
}
var id = EditorGUILayout.Popup("Monitor", monitor.id, Manager.monitors.Select(x => x.name).ToArray());
if (id != monitor.id) { texture.monitorId = id; }
EditorGUILayout.IntField("ID", monitor.id);
EditorGUILayout.Toggle("Is Primary", monitor.isPrimary);
EditorGUILayout.EnumPopup("Rotation", monitor.rotation);
EditorGUILayout.Vector2Field("Resolution", new Vector2(monitor.width, monitor.height));
EditorGUILayout.Vector2Field("DPI", new Vector2(monitor.dpiX, monitor.dpiY));
EditorGUILayout.Toggle("Is HDR", monitor.isHDR);
});
}
void DrawInvert()
{
Fold("Invert", ref invertFolded_, () => {
texture.invertX = EditorGUILayout.Toggle("Invert X", invertX_.boolValue);
texture.invertY = EditorGUILayout.Toggle("Invert Y", invertY_.boolValue);
});
}
void DrawClip()
{
Fold("Clip", ref clipFolded_, () => {
texture.useClip = EditorGUILayout.Toggle("Use Clip", useClip_.boolValue);
EditorGUILayout.PropertyField(clipPos_);
EditorGUILayout.PropertyField(clipScale_);
});
}
void DrawMaterial()
{
Fold("Material", ref matFolded_, () => {
if (!Application.isPlaying) {
EditorGUILayout.HelpBox("These parameters are applied to the shared material when not playing.", MessageType.Info);
}
texture.meshForwardDirection = (Texture.MeshForwardDirection)EditorGUILayout.EnumPopup("Mesh Forward Direction", texture.meshForwardDirection);
texture.bend = EditorGUILayout.Toggle("Use Bend", texture.bend);
texture.width = EditorGUILayout.FloatField("Bend Width", texture.width);
texture.radius = EditorGUILayout.Slider("Bend Radius", texture.radius, texture.worldWidth / (2 * Mathf.PI), 100f);
texture.thickness = EditorGUILayout.Slider("Thickness", texture.thickness, 0f, 30f);
texture.culling = (Texture.Culling)EditorGUILayout.EnumPopup("Culling", texture.culling);
});
}
}
} |
using DevUser.Repositories;
using System;
using System.Web.Security;
using System.Web.UI;
namespace DevUser
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
var userRepo = new UserRepository();
if (userRepo.IsCorrectUser(txtUserID.Text, txtPassword.Text))
{
//[!] 인증 부여
if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
// 인증 쿠키값 부여
FormsAuthentication.RedirectFromLoginPage(txtUserID.Text, false);
}
else
{
// 인증 쿠키값 부여
FormsAuthentication.SetAuthCookie(txtUserID.Text, false);
Response.Redirect("~/Welcome.aspx");
}
}
else
{
Page.ClientScript.RegisterStartupScript(
this.GetType(), "showMsg",
"<script>alert('잘못된 사용자입니다.');</script>");
}
}
}
} |
using AccountsApi.V1.Domain;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
namespace AccountsApi.V1.Boundary.BaseModel
{
public abstract class AccountResponseModel : AccountBaseModel
{
/// <example>
/// 74c5fbc4-2fc8-40dc-896a-0cfa671fc832
/// </example>
[JsonProperty(Order = 1)]
public Guid Id { get; set; }
/// <example>
/// Admin
/// </example>
[Required]
[JsonProperty(Order = 14)]
public string LastUpdatedBy { get; set; }
/// <example>
/// 2021-03-29T15:10:37.471Z
/// </example>
[JsonProperty(Order = 10)]
public DateTime StartDate { get; set; }
/// <example>
/// 2021-03-29T15:10:37.471Z
/// </example>
[JsonProperty(Order = 11)]
public DateTime? EndDate { get; set; }
/// <example>
/// 123.01
/// </example>
[JsonProperty(Order = 2)]
public decimal AccountBalance { get; set; } = 0;
/// <example>
/// 278.05
/// </example>
[JsonProperty(Order = 13)]
public decimal ConsolidatedBalance { get; set; } = 0;
[NotNull]
public IEnumerable<ConsolidatedCharge> ConsolidatedCharges { get; set; }
}
}
|
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
namespace Najlot.Log.Destinations
{
/// <summary>
/// Common interface for all destinations
/// </summary>
public interface IDestination : IDisposable
{
/// <summary>
/// Tells the destination to log the messages
/// </summary>
/// <param name="messages">Messages to be logged</param>
void Log(IEnumerable<LogMessage> messages);
/// <summary>
/// Forces the destination to flush all cached messages
/// </summary>
void Flush();
}
} |
using System;
using System.Text.Json.Serialization;
namespace Modcomposer
{
[Serializable]
internal class ConfigModel
{
[JsonPropertyName("Version")]
public string Version { get; set; }
[JsonPropertyName("ModContainerPath")]
public string ModPath { get; set; }
[JsonPropertyName("ServerPath")]
public string ServerPath { get; set; }
[JsonPropertyName("Mods")]
public Mod[] Mods { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace ChakraCore.NET.Debug
{
public struct Variable
{
//"name":"this","type":"object","className":"Object","display":"{...}","propertyAttributes":3,"handle":2,"value":123
[JsonProperty(propertyName: "name")]
public string Name;
[JsonProperty(propertyName: "type")]
public string Type;
[JsonProperty(propertyName: "className")]
public string ClassName;
[JsonProperty(propertyName: "display")]
public string Display;
[JsonProperty(propertyName: "propertyAttributes")]
public PropertyAttributesEnum PropertyAttributes;
[JsonProperty(propertyName: "handle")]
public uint Handle;
[JsonProperty(propertyName: "value")]
public string Value;
}
}
|
using System;
using Manatee.Json.Pointer;
using Manatee.Json.Serialization.Internal;
namespace Manatee.Json.Serialization
{
/// <summary>
/// Serializes and deserializes objects and types to and from JSON structures.
/// </summary>
public class JsonSerializer
{
private int _callCount;
private JsonSerializerOptions _options;
private AbstractionMap _abstractionMap;
/// <summary>
/// Gets or sets a set of options for this serializer.
/// </summary>
public JsonSerializerOptions Options
{
get { return _options ?? (_options = new JsonSerializerOptions(JsonSerializerOptions.Default)); }
set { _options = value; }
}
/// <summary>
/// Gets or sets the abstraction map used by this serializer.
/// </summary>
public AbstractionMap AbstractionMap
{
get { return _abstractionMap ?? (_abstractionMap = new AbstractionMap(AbstractionMap.Default)); }
set { _abstractionMap = value; }
}
/// <summary>
/// Serializes an object to a JSON structure.
/// </summary>
/// <typeparam name="T">The type of the object to serialize.</typeparam>
/// <param name="obj">The object to serialize.</param>
/// <returns>The JSON representation of the object.</returns>
public JsonValue Serialize<T>(T obj)
{
var context = new SerializationContext(this)
{
InferredType = obj?.GetType() ?? typeof(T),
RequestedType = typeof(T),
CurrentLocation = new JsonPointer("#"),
Source = obj
};
return Serialize(context);
}
/// <summary>
/// Serializes an object to a JSON structure.
/// </summary>
/// <param name="type">The type of the object to serialize.</param>
/// <param name="obj">The object to serialize.</param>
/// <returns>The JSON representation of the object.</returns>
public JsonValue Serialize(Type type, object obj)
{
var context = new SerializationContext(this)
{
InferredType = obj?.GetType() ?? type,
RequestedType = type,
CurrentLocation = new JsonPointer("#"),
Source = obj
};
return Serialize(context);
}
internal JsonValue Serialize(SerializationContext context)
{
_callCount++;
var serializer = SerializerFactory.GetSerializer(context);
var json = serializer.Serialize(context);
if (--_callCount == 0)
{
context.SerializationMap.Clear();
}
return json;
}
/// <summary>
/// Serializes the public static properties of a type to a JSON structure.
/// </summary>
/// <typeparam name="T">The type to serialize.</typeparam>
/// <returns>The JSON representation of the type.</returns>
public JsonValue SerializeType<T>()
{
var serializer = SerializerFactory.GetTypeSerializer();
var json = serializer.SerializeType<T>(this);
return json;
}
/// <summary>
/// Generates a template JSON inserting default values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public JsonValue GenerateTemplate<T>()
{
return TemplateGenerator.FromType<T>(this);
}
/// <summary>
/// Deserializes a JSON structure to an object of the appropriate type.
/// </summary>
/// <typeparam name="T">The type of the object that the JSON structure represents.</typeparam>
/// <param name="json">The JSON representation of the object.</param>
/// <returns>The deserialized object.</returns>
/// <exception cref="TypeDoesNotContainPropertyException">Optionally thrown during automatic
/// deserialization when the JSON contains a property which is not defined by the requested
/// type.</exception>
public T Deserialize<T>(JsonValue json)
{
return (T) Deserialize(typeof(T), json);
}
/// <summary>
/// Deserializes a JSON structure to an object of the appropriate type.
/// </summary>
/// <param name="type">The type of the object that the JSON structure represents.</param>
/// <param name="json">The JSON representation of the object.</param>
/// <returns>The deserialized object.</returns>
/// <exception cref="TypeDoesNotContainPropertyException">Optionally thrown during automatic
/// deserialization when the JSON contains a property which is not defined by the requested
/// type.</exception>
public object Deserialize(Type type, JsonValue json)
{
var context = new SerializationContext(this, json)
{
InferredType = type,
RequestedType = type,
CurrentLocation = new JsonPointer("#"),
LocalValue = json
};
return Deserialize(context);
}
internal object Deserialize(SerializationContext context)
{
_callCount++;
var serializer = SerializerFactory.GetSerializer(context);
var obj = serializer.Deserialize(context);
if (--_callCount == 0)
{
context.SerializationMap.Complete(obj);
}
return obj;
}
/// <summary>
/// Deserializes a JSON structure to the public static properties of a type.
/// </summary>
/// <typeparam name="T">The type to deserialize.</typeparam>
/// <param name="json">The JSON representation of the type.</param>
/// <exception cref="TypeDoesNotContainPropertyException">Optionally thrown during automatic
/// deserialization when the JSON contains a property which is not defined by the requested
/// type.</exception>
public void DeserializeType<T>(JsonValue json)
{
var serializer = SerializerFactory.GetTypeSerializer();
serializer.DeserializeType<T>(json, this);
}
}
}
|
using NYTimes.NET.Clients;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace NYTimes.NET.Models
{
[XmlRoot("rss")]
public class Rss
{
[XmlElement("channel")]
public Channel Channel { get; set; }
}
public class Channel : ModelBase
{
[XmlElement("link", Namespace = Constants.XmlNamespaces.Atom)]
public AtomLinkWrapper AtomLinkWrapperObj { get; set; }
public class AtomLinkWrapper
{
[XmlAttribute("href")]
public string AtomLinkHrefAttr { get; set; }
}
/// <summary>
/// Get Atomlink
/// </summary>
public string Atomlink
{
get => this.AtomLinkWrapperObj?.AtomLinkHrefAttr;
}
/// <summary>
/// Gets or Sets Copyright
/// </summary>
[XmlElement("copyright")]
public string Copyright { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[XmlElement("description")]
public string Description { get; set; }
/// <summary>
/// Gets or Sets Image
/// </summary>
[XmlElement("image")]
public ChannelImage Image { get; set; }
/// <summary>
/// Gets or Sets Articles
/// </summary>
[XmlElement("item")]
public List<ChannelArticle> Articles { get; set; }
/// <summary>
/// Gets or Sets Language
/// </summary>
[XmlElement("language")]
public string Language { get; set; }
/// <summary>
/// Gets or Sets LastBuildDate
/// </summary>
[XmlElement("lastBuildDate")]
public string LastBuildDate { get; set; }
/// <summary>
/// Gets or Sets Link
/// </summary>
[XmlElement("link")]
public string Link { get; set; }
/// <summary>
/// Gets or Sets Title
/// </summary>
[XmlElement("title")]
public string Title { get; set; }
}
}
|
#if NET_4_6
using UnityEngine;
using UnityEngine.Assertions;
namespace Unity.Properties.Serialization
{
public static class JsonPropertyContainerWriter
{
private static readonly JsonPropertyVisitor s_DefaultVisitor = new JsonPropertyVisitor();
public static string Write<TContainer>(TContainer container, JsonPropertyVisitor visitor = null)
where TContainer : class, IPropertyContainer
{
if (null == visitor)
{
visitor = s_DefaultVisitor;
}
WritePrefix(visitor);
container.Visit(visitor);
WriteSuffix(visitor);
return visitor.ToString();
}
public static string Write<TContainer>(ref TContainer container, JsonPropertyVisitor visitor = null)
where TContainer : struct, IPropertyContainer
{
if (null == visitor)
{
visitor = s_DefaultVisitor;
}
WritePrefix(visitor);
PropertyContainer.Visit(ref container, visitor);
WriteSuffix(visitor);
return visitor.ToString();
}
private static void WritePrefix(JsonPropertyVisitor visitor)
{
Assert.IsNotNull(visitor);
visitor.StringBuffer.Clear();
visitor.StringBuffer.Append(' ', JsonPropertyVisitor.Style.Space * visitor.Indent);
visitor.StringBuffer.Append("{\n");
visitor.Indent++;
}
private static void WriteSuffix(JsonPropertyVisitor visitor)
{
Debug.Assert(visitor != null);
visitor.Indent--;
visitor.StringBuffer.Length -= 2;
visitor.StringBuffer.Append("\n");
visitor.StringBuffer.Append(' ', JsonPropertyVisitor.Style.Space * visitor.Indent);
visitor.StringBuffer.Append("}");
}
}
}
#endif // NET_4_6
|
using System;
using System.Collections.Generic;
namespace SocketIOClient.UriConverters
{
public interface IUriConverter
{
Uri GetServerUri(bool ws, Uri serverUri, int eio, string path, IEnumerable<KeyValuePair<string, string>> queryParams);
}
}
|
namespace OfaSchlupfer.MSSQLReflection.SqlCode {
using OfaSchlupfer.MSSQLReflection.AST;
/// <summary>
/// AST bound inforamtion.
/// </summary>
public class AnalyseNodeState {
private ISqlCodeType _SqlCodeType;
/// <summary>
/// Gets or sets the Fragment
/// </summary>
public readonly SqlNode Fragment;
/// <summary>
/// Initializes a new instance of the <see cref="AnalyseNodeState"/> class.
/// </summary>
/// <param name="node">the owner</param>
public AnalyseNodeState(SqlNode node) {
this.Fragment = node;
}
/// <summary>
/// Gets or sets the Scope.
/// </summary>
public SqlCodeScope SqlCodeScope { get; set; }
/// <summary>
/// Gets or sets result value
/// </summary>
public ISqlCodeResult ResultValue { get; set; }
/// <summary>
/// Gets or sets sqlCodeType
/// </summary>
public ISqlCodeType ResultType {
get {
return this._SqlCodeType;
}
set {
if (this._SqlCodeType == null) {
this._SqlCodeType = value;
} else {
if (value != null) {
if (this._SqlCodeType is SqlCodeTypeLazy lazy) {
// if this instance is shared solve it
lazy.SetResolvedCodeType(value);
// but use the new information.
this._SqlCodeType = value;
}
}
}
}
}
/// <summary>
/// Gets or sets OutputType - the outgoing data.
/// </summary>
public ISqlCodeType OutputType { get; set; }
}
}
|
/*
* SmeshLink.Misty.Util.PagedList.cs
*
* Copyright (c) 2009-2014 SmeshLink Technology Corporation.
* All rights reserved.
*
* Authors:
* Longxiang He
*
* This file is part of the Misty, a sensor cloud for IoT.
*/
using System;
using System.Collections.Generic;
namespace SmeshLink.Misty.Util
{
/// <summary>
/// A list with paging infomation.
/// </summary>
public class PagedList<T> : List<T>
{
/// <summary>
/// Gets or sets the total number of items.
/// </summary>
public Int32 Total { get; set; }
/// <summary>
/// Gets or sets the offset of this page.
/// </summary>
public Int32 Offset { get; set; }
/// <summary>
/// Gets or sets the limit number of each page.
/// </summary>
public Int32 Limit { get; set; }
/// <summary>
///
/// </summary>
public PagedList()
{ }
/// <summary>
///
/// </summary>
public PagedList(IEnumerable<T> collection)
: base(collection)
{ }
/// <summary>
///
/// </summary>
public PagedList(Int32 capacity)
: base(capacity)
{ }
}
}
|
// Copyright (c) 2020 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.ComponentModel.DataAnnotations;
using BizDbAccess.Orders;
using BizLogic.BasketServices;
using BizLogic.Orders;
using BizLogic.Orders.Concrete;
using DataLayer.EfClasses;
using DataLayer.EfCode;
using Microsoft.AspNetCore.Http;
using ServiceLayer.BizRunners;
using ServiceLayer.CheckoutServices.Concrete;
namespace ServiceLayer.OrderServices.Concrete
{
public class PlaceOrderServiceWithVal
{
private readonly BasketCookie _basketCookie;
private readonly RunnerWriteDbWithValidation<PlaceOrderInDto, Order> _runner;
public PlaceOrderServiceWithVal(
IRequestCookieCollection cookiesIn,
IResponseCookies cookiesOut,
EfCoreContext context)
{
_basketCookie = new BasketCookie(cookiesIn, cookiesOut);
_runner = new RunnerWriteDbWithValidation<PlaceOrderInDto, Order>(
new PlaceOrderAction(
new PlaceOrderDbAccess(context)),
context);
}
public IImmutableList<ValidationResult> Errors => _runner.Errors;
/// <summary>
/// This creates the order and, if successful clears the cookie
/// </summary>
/// <returns>Returns the OrderId, or zero if errors</returns>
public int PlaceOrder(bool acceptTAndCs)
{
var checkoutService = new CheckoutCookieService(
_basketCookie.GetValue());
var order = _runner.RunAction(
new PlaceOrderInDto(acceptTAndCs,
checkoutService.UserId, checkoutService.LineItems));
if (_runner.HasErrors) return 0;
//successful so clear the cookie line items
checkoutService.ClearAllLineItems();
_basketCookie.AddOrUpdateCookie(
checkoutService.EncodeForCookie());
return order.OrderId;
}
}
} |
//
// Basic Authentication implementation
//
// Authors:
// Greg Reinacker (gregr@rassoc.com)
// Sebastien Pouliot (spouliot@motus.com)
//
// Copyright 2002-2003 Greg Reinacker, Reinacker & Associates, Inc. All rights reserved.
// Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
//
// Based on "DigestAuthenticationModule.cs". Original source code available at
// http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Xml;
namespace Mono.Http.Modules
{
public class BasicAuthenticationModule : AuthenticationModule
{
static char[] separator = {':'};
public BasicAuthenticationModule () : base ("Basic") {}
protected override bool AcceptCredentials (HttpApplication app, string authentication)
{
byte[] userpass = Convert.FromBase64String (authentication);
string[] up = Encoding.UTF8.GetString (userpass).Split (separator);
string username = up [0];
string password = up [1];
string userFileName = app.Request.MapPath (ConfigurationSettings.AppSettings ["Basic.Users"]);
if (userFileName == null || !File.Exists (userFileName))
return false;
XmlDocument userDoc = new XmlDocument ();
userDoc.Load (userFileName);
string xPath = String.Format ("/users/user[@name='{0}']", username);
XmlNode user = userDoc.SelectSingleNode (xPath);
if (user == null)
return false;
XmlAttribute att = user.Attributes ["password"];
if (att == null || password != att.Value)
return false;
XmlNodeList roleNodes = user.SelectNodes ("role");
string[] roles = new string [roleNodes.Count];
int i = 0;
foreach (XmlNode xn in roleNodes) {
XmlAttribute rolename = xn.Attributes ["name"];
if (rolename == null)
continue;
roles [i++] = rolename.Value;
}
app.Context.User = new GenericPrincipal (new GenericIdentity (username, AuthenticationMethod), roles);
return true;
}
#region Event Handlers
// We add the WWW-Authenticate header here, so if an authorization
// fails elsewhere than in this module, we can still request authentication
// from the client.
public override void OnEndRequest (object source, EventArgs eventArgs)
{
HttpApplication app = (HttpApplication) source;
if (app.Response.StatusCode != 401 || !AuthenticationRequired)
return;
string realm = ConfigurationSettings.AppSettings ["Basic.Realm"];
string challenge = String.Format ("{0} realm=\"{1}\"", AuthenticationMethod, realm);
app.Response.AppendHeader ("WWW-Authenticate", challenge);
}
#endregion
}
}
|
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Driver.Linq;
using System;
namespace GraemSheppardOnline.Services.MongoDBContext
{
public class ItemCollection<T> : ContextCollection<T>
{
public ItemCollection(IMongoCollection<T> col) : base(col) { }
/// <summary>
/// Finds the first parent where the specified field exists and returns it.
/// Currently cannot search for nested fields.
/// </summary>
/// <typeparam name="T1">The type of object to return</typeparam>
/// <param name="id">Id of the start document</param>
/// <param name="itemField">Field to search for</param>
/// <returns>First non-null value of the specified field</returns>
public T1 FirstResultFor<T1>(string id, ItemField itemField)
{
var field = itemField.ToString();
T1 temp = default;
#region pipeline
var pipeline = new[]
{
new BsonDocument("$match",
new BsonDocument("_id",
new ObjectId(id))),
new BsonDocument("$graphLookup",
new BsonDocument
{
{ "from", "Items" },
{ "startWith", "$_id" },
{ "connectFromField", "ParentId" },
{ "connectToField", "_id" },
{ "as", "Parents" },
{ "depthField", "Depth" }
}),
new BsonDocument("$unwind",
new BsonDocument("path", "$Parents")),
new BsonDocument("$replaceRoot",
new BsonDocument("newRoot", "$Parents")),
new BsonDocument("$sort",
new BsonDocument("Depth", 1)),
new BsonDocument("$match",
new BsonDocument(field,
new BsonDocument("$ne", BsonNull.Value)))
};
#endregion
var result = Collection.Aggregate<Item>(pipeline).FirstOrDefault();
if (result == null) { return temp; }
var prop = typeof(Item).GetProperty(field);
temp = (T1)prop?.GetValue(result);
return temp;
}
public List<T1> GetAncestry<T1>(string id, ItemField itemField)
{
string field = itemField.ToString();
List<T1> temp = null;
#region pipeline
var pipeline = new[]
{
new BsonDocument("$match",
new BsonDocument("_id",
new ObjectId(id))),
new BsonDocument("$graphLookup",
new BsonDocument
{
{ "from", "Items" },
{ "startWith", "$_id" },
{ "connectFromField", "ParentId" },
{ "connectToField", "_id" },
{ "as", "Parents" },
{ "depthField", "Depth" }
}),
new BsonDocument("$unwind",
new BsonDocument("path", "$Parents")),
new BsonDocument("$replaceRoot",
new BsonDocument("newRoot", "$Parents")),
new BsonDocument("$sort",
new BsonDocument("Depth", 1))
};
#endregion
var result = Collection.Aggregate<Item>(pipeline).ToEnumerable();
var prop = typeof(Item).GetProperty(field);
temp = result.Select(x => (T1)prop.GetValue(x)).ToList();
return temp;
}
public List<T1> Accummulate<T1>(string id, ItemField itemField)
{
string field = itemField.ToString();
List<T1> temp = null;
#region pipeline
var pipeline = new[]
{
new BsonDocument("$match",
new BsonDocument("_id",
new ObjectId(id))),
new BsonDocument("$graphLookup",
new BsonDocument
{
{ "from", "Items" },
{ "startWith", "$_id" },
{ "connectFromField", "ParentId" },
{ "connectToField", "_id" },
{ "as", "Parents" },
{ "depthField", "Depth" }
}),
new BsonDocument("$unwind",
new BsonDocument("path", "$Parents")),
new BsonDocument("$replaceRoot",
new BsonDocument("newRoot", "$Parents")),
new BsonDocument("$sort",
new BsonDocument("Depth", 1))
};
#endregion
var result = Collection.Aggregate<Item>(pipeline).ToEnumerable();
var prop = typeof(Item).GetProperty(field);
var lists = from t1 in result
select (IEnumerable<T1>)prop.GetValue(t1);
var query = from t1 in lists
where t1 != null
from t2 in t1
select t2;
temp = query.ToList();
return temp;
}
public TOut TestMethod<TOut>(Func<Item, TOut> func, Item item)
{
return func(item);
}
}
public enum ItemField
{
PriceId,
Nested,
Alphabet,
}
}
|
@{
ViewBag.Title = "About";
}
<div class="row">
<div class="col-12">
<button id="RequestForbidden" type="button" class="btn btn-danger">Request Forbidden</button>
</div>
</div>
<div class="row">
<div class="col-12">
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
</div>
</div>
@section scripts{
<script type="text/javascript">
$(document).ready(function () {
var RequestForbiddenPartialView = function () {
$.get("/Dashboard/MyPartial", function (data) {
alert("Load was performed.");
});
};
$('#RequestForbidden').on('click', RequestForbiddenPartialView);
});
</script>
}
|
namespace KorneiDontsov.Sql {
using Microsoft.AspNetCore.Builder;
public static class EndpointFunctions {
public static IEndpointConventionBuilder WithoutDbMigration (this IEndpointConventionBuilder epConv) =>
epConv.WithMetadata(WithoutDbMigrationAttribute.shared);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace MSBuildCodeMetrics.VisualStudioMetrics.XML
{
/// <summary>
/// Used to parse Visual Studio Metrics XML
/// </summary>
public class MetricsReport
{
/// <summary>
/// Maintainability index
/// </summary>
public int MaintainabilityIndex
{
get;
set;
}
/// <summary>
/// Cyclomatic complexity
/// </summary>
public int CyclomaticComplexity
{
get;
set;
}
/// <summary>
/// Class coupling
/// </summary>
public int ClassCoupling
{
get;
set;
}
/// <summary>
/// Depth of inheritance
/// </summary>
public int DepthOfInheritance
{
get;
set;
}
/// <summary>
/// Lines of code
/// </summary>
public int LinesOfCode
{
get;
set;
}
private int ReturnValueOrZeroIfNull(MetricReport m)
{
if (m == null)
return 0;
return Convert.ToInt32(m.Value);
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="l">A list of MetricReports that wil be parsed to this members properties</param>
public MetricsReport(List<MetricReport> l)
{
MaintainabilityIndex = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "MaintainabilityIndex"));
CyclomaticComplexity = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "CyclomaticComplexity"));
ClassCoupling = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "ClassCoupling"));
DepthOfInheritance = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "DepthOfInheritance"));
LinesOfCode = ReturnValueOrZeroIfNull(l.FirstOrDefault(m => m.Name == "LinesOfCode"));
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Used to configure identity cookie options.
/// </summary>
public class IdentityCookiesBuilder
{
/// <summary>
/// Used to configure the application cookie.
/// </summary>
public OptionsBuilder<CookieAuthenticationOptions> ApplicationCookie { get; set; }
/// <summary>
/// Used to configure the external cookie.
/// </summary>
public OptionsBuilder<CookieAuthenticationOptions> ExternalCookie { get; set; }
/// <summary>
/// Used to configure the two factor remember me cookie.
/// </summary>
public OptionsBuilder<CookieAuthenticationOptions> TwoFactorRememberMeCookie { get; set; }
/// <summary>
/// Used to configure the two factor user id cookie.
/// </summary>
public OptionsBuilder<CookieAuthenticationOptions> TwoFactorUserIdCookie { get; set; }
}
}
|
//*******************************************************************************************//
// //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer //
// //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup //
// //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved. //
// https://www.bytescout.com //
// https://pdf.co //
// //
//*******************************************************************************************//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ByteScoutWebApiExample
{
// Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
// If it's not then please replace this with with your hosting url.
class Program
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co/documentation/api
const String API_KEY = "************************************";
// Result file name
const string ResultFileName = @".\barcode.png";
// Barcode type. See valid barcode types in the documentation https://apidocs.pdf.co/#barcode-generator
const string BarcodeType = "QRCode";
// Barcode value
const string BarcodeValue = "QR123456\nhttps://pdf.co\nhttps://bytescout.com";
static void Main(string[] args)
{
// Create standard .NET web client instance
WebClient webClient = new WebClient();
// Set API Key
webClient.Headers.Add("x-api-key", API_KEY);
/*
Valid error correction levels:
----------------------------------
Low - [default] Lowest error correction level. (Approx. 7% of codewords can be restored).
Medium - Medium error correction level. (Approx. 15% of codewords can be restored).
Quarter - Quarter error correction level (Approx. 25% of codewords can be restored).
High - Highest error correction level (Approx. 30% of codewords can be restored).
*/
// Set "Custom Profiles" parameter
var Profiles = @"{ ""profiles"": [ { ""profile1"": { ""Options.QRErrorCorrectionLevel"": ""Quarter"" } } ] }";
// Prepare requests params as JSON
// See documentation: https://apidocs.pdf.co/#barcode-generator
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("name", Path.GetFileName(ResultFileName));
parameters.Add("type", BarcodeType);
parameters.Add("value", BarcodeValue);
parameters.Add("profiles", Profiles);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// URL of "Barcode Generator" endpoint
string url = "https://localhost/barcode/generate";
// Execute POST request with JSON payload
string response = webClient.UploadString(url, jsonPayload);
// Parse JSON response
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Get URL of generated barcode image file
string resultFileURI = json["url"].ToString();
// Download generated image file
webClient.DownloadFile(resultFileURI, ResultFileName);
Console.WriteLine("Generated barcode saved to \"{0}\" file.", ResultFileName);
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
finally
{
webClient.Dispose();
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
|
// Copyright (c) Nick Frederiksen. All Rights Reserved.
namespace QVZ.Api.Constants.Authorization
{
internal static class Scopes
{
internal const string Player = "API.Player";
internal const string Creator = "API.Creator";
}
}
|
/*
* 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 java = biz.ritter.javapi;
using org.apache.commons.collections;
using org.apache.commons.collections.iterators;
namespace org.apache.commons.collections.collection
{
/**
* Decorates another <code>Collection</code> to ensure it can't be altered.
* <p>
* This class is java.io.Serializable from Commons Collections 3.1.
*
* @since Commons Collections 3.0
* @version $Revision: 7174 $ $Date: 2011-06-06 22:24:01 +0200 (Mo, 06. Jun 2011) $
*
* @author Stephen Colebourne
*/
public sealed class UnmodifiableCollection
: AbstractSerializableCollectionDecorator
, Unmodifiable
{
/** Serialization version */
private static readonly long serialVersionUID = -239892006883819945L;
/**
* Factory method to create an unmodifiable collection.
* <p>
* If the collection passed in is already unmodifiable, it is returned.
*
* @param coll the collection to decorate, must not be null
* @return an unmodifiable collection
* @throws IllegalArgumentException if collection is null
*/
public static java.util.Collection<Object> decorate(java.util.Collection<Object> coll)
{
if (coll is Unmodifiable)
{
return coll;
}
return new UnmodifiableCollection(coll);
}
//-----------------------------------------------------------------------
/**
* Constructor that wraps (not copies).
*
* @param coll the collection to decorate, must not be null
* @throws IllegalArgumentException if collection is null
*/
private UnmodifiableCollection(java.util.Collection<Object> coll)
: base(coll)
{
}
//-----------------------------------------------------------------------
public override java.util.Iterator<Object> iterator()
{
return UnmodifiableIterator.decorate(getCollection().iterator());
}
public override bool add(Object obj)
{
throw new java.lang.UnsupportedOperationException();
}
public override bool addAll(java.util.Collection<Object> coll)
{
throw new java.lang.UnsupportedOperationException();
}
public override void clear()
{
throw new java.lang.UnsupportedOperationException();
}
public override bool remove(Object obj)
{
throw new java.lang.UnsupportedOperationException();
}
public override bool removeAll(java.util.Collection<Object> coll)
{
throw new java.lang.UnsupportedOperationException();
}
public override bool retainAll(java.util.Collection<Object> coll)
{
throw new java.lang.UnsupportedOperationException();
}
}
} |
using Anticaptcha_example.Helper;
using Newtonsoft.Json.Linq;
namespace Anticaptcha_example.Api
{
public class NoCaptcha : NoCaptchaProxyless
{
public enum ProxyTypeOption
{
Http,
Socks4,
Socks5
}
public string Cookies { protected get; set; }
public string ProxyLogin { protected get; set; }
public string ProxyPassword { protected get; set; }
public int? ProxyPort { protected get; set; }
public ProxyTypeOption? ProxyType { protected get; set; }
public string UserAgent { protected get; set; }
public string ProxyAddress { protected get; set; }
public override JObject GetPostData()
{
var postData = base.GetPostData();
postData["type"] = "NoCaptchaTask";
if (ProxyType == null || ProxyPort == null || ProxyPort < 1 || ProxyPort > 65535 ||
string.IsNullOrEmpty(ProxyAddress))
{
DebugHelper.Out("Proxy data is incorrect!", DebugHelper.Type.Error);
return null;
}
postData.Add("proxyType", ProxyType.ToString().ToLower());
postData.Add("proxyAddress", ProxyAddress);
postData.Add("proxyPort", ProxyPort);
postData.Add("proxyLogin", ProxyLogin);
postData.Add("proxyPassword", ProxyPassword);
postData.Add("userAgent", UserAgent);
postData.Add("cookies", Cookies);
return postData;
}
}
} |
using Xunit;
namespace _892_SurfaceAreaOf3DShapes
{
class Program
{
static void Main(string[] args)
{
var solution = new Solution();
Assert.Equal(10, solution.SurfaceArea(new[] { new[] { 2 } }));
Assert.Equal(34, solution.SurfaceArea(new[] { new[] { 1, 2 }, new[] { 3, 4 } }));
Assert.Equal(16, solution.SurfaceArea(new[] { new[] { 1, 0 }, new[] { 0, 2 } }));
Assert.Equal(32, solution.SurfaceArea(new[] { new[] { 1, 1, 1 }, new[] { 1, 0, 1 }, new[] { 1, 1, 1 } }));
Assert.Equal(46, solution.SurfaceArea(new[] { new[] { 2, 2, 2 }, new[] { 2, 1, 2 }, new[] { 2, 2, 2 } }));
}
}
}
|
namespace Simple.Sqlite
{
/// <summary>
/// Represents a Sqlite internal type
/// </summary>
public enum SqliteType
{
/// <summary>
/// Numeric without decimal places
/// </summary>
INTEGER,
/// <summary>
/// Sqlite text
/// </summary>
TEXT,
/// <summary>
/// Binary data or anythng (sqlite is dynamic typed)
/// </summary>
BLOB,
/// <summary>
/// Numeric with decimal places
/// </summary>
REAL,
/// <summary>
/// Numeric value. Includes Bool, Date and Datetime
/// </summary>
NUMERIC,
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Backlog4net.Api
{
using Option;
/// <summary>
/// Executes Backlog Watch APIs.
/// </summary>
public interface WatchingMethods
{
/// <summary>
/// Returns the Watch.
/// </summary>
/// <param name="watchingId">watchingId</param>
/// <returns>the Watch</returns>
Task<Watch> GetWatchAsync(long watchingId, CancellationToken? token = null);
/// <summary>
/// Adds a watching to the issue.
/// </summary>
/// <param name="issueIdOrKey">the issue identifier</param>
/// <param name="note">note</param>
/// <returns></returns>
Task<Watch> AddWatchToIssueAsync(IdOrKey issueIdOrKey, String note, CancellationToken? token = null);
/// <summary>
/// Updates the existing watching.
/// </summary>
/// <param name="params">the updating project parameters</param>
/// <returns>the updated Watching</returns>
Task<Watch> UpdateWatchAsync(UpdateWatchParams @params, CancellationToken? token = null);
/// <summary>
/// Deletes the existing watching.
/// </summary>
/// <param name="watchingId">the watching identifier</param>
/// <returns>the deleted watching</returns>
Task<Watch> DeleteWatchAsync(long watchingId, CancellationToken? token = null);
/// <summary>
/// Marks the watching as already read.
/// </summary>
/// <param name="numericUserId">Marks the watching as already read.</param>
Task MarkAsCheckedUserWatchesAsync(long numericUserId, CancellationToken? token = null);
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Xunit.Performance;
using System;
using System.Threading;
namespace PerfLabTests
{
public class JITIntrinsics
{
private static int s_i;
private static string s_s;
[Benchmark(InnerIterationCount = 100000)]
public static void CompareExchangeIntNoMatch()
{
s_i = 0;
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.CompareExchange(ref s_i, 5, -1);
}
[Benchmark(InnerIterationCount = 100000)]
public static void CompareExchangeIntMatch()
{
foreach (var iteration in Benchmark.Iterations)
{
s_i = 1;
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.CompareExchange(ref s_i, 5, 1);
}
}
[Benchmark(InnerIterationCount = 100000)]
public static void CompareExchangeObjNoMatch()
{
s_s = "Hello";
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.CompareExchange(ref s_s, "World", "What?");
}
[Benchmark(InnerIterationCount = 100000)]
public static void CompareExchangeObjMatch()
{
foreach (var iteration in Benchmark.Iterations)
{
s_s = "What?";
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.CompareExchange(ref s_s, "World", "What?");
}
}
[Benchmark(InnerIterationCount = 100000)]
public static void InterlockedIncrement()
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.Increment(ref s_i);
}
[Benchmark(InnerIterationCount = 100000)]
public static void InterlockedDecrement()
{
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < Benchmark.InnerIterationCount; i++)
Interlocked.Decrement(ref s_i);
}
}
} |
using SilupostMobileApp.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace SilupostMobileApp.Models
{
public class SilupostMediaModel : FileModel
{
public string CrimeIncidentReportMediaId { get; set; }
public bool IsNew { get; set; }
public string IconSource { get; set; }
public SilupostDocReportMediaTypeEnums MediaType { get; set; }
}
}
|
using Catan.CodeGenerator.TsGenerator;
using Catan.Core.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Catan.CodeGenerator
{
public class TypeScriptGenerator
{
public static void Generate(string outputFile, bool events)
{
var output = TsGenerator.TsGenerator.Generate(new CatanTsGeneratorSettings { Events = events});
File.WriteAllText(outputFile, output);
}
private class CatanTsGeneratorSettings : TsGeneratorSettings
{
public bool Events { get; set; }
public override IEnumerable<Type> GetTypes()
{
var assembly = Assembly.Load("Catan.Core");
Type[] types;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types;
}
return types.Where(t => t != null).Where(MapType);
}
private bool MapType(Type type)
{
return Events
? type.GetCustomAttributes(typeof(EventAttribute), true).Length > 0
: type.GetCustomAttributes(typeof(ContractAttribute), true).Length > 0;
}
public override string GetModuleName(string @namespace)
{
return @namespace.Replace("Catan.Core", "Scripts.Data");
}
public override void WriteModuleContent(StringBuilder result, TsModule module)
{
result.Append(" 'use strict';\r\n");
base.WriteModuleContent(result, module);
}
public override string GetPropertyName(PropertyInfo propertyInfo)
{
return GetCamelCase(propertyInfo.Name);
}
public override string GetFieldName(FieldInfo fieldInfo)
{
return GetCamelCase(fieldInfo.Name);
}
public override void WriteTypeContent(StringBuilder result, TsType type)
{
if (type.Name.EndsWith("Request") || type.Name.EndsWith("Command"))
{
var controllerStart = type.TsModule.Name.Replace("Scripts.Data.", "").Replace(".", "_");
var controllerEnd = type.Name;
if (controllerEnd.EndsWith("Request"))
{
controllerEnd = controllerEnd.Substring(0, controllerEnd.Length - "Request".Length);
}
if (controllerEnd.EndsWith("Command"))
{
controllerEnd = controllerEnd.Substring(0, controllerEnd.Length - "Command".Length);
}
if (type.Type != "interface")
result.Append(string.Format(" path='{0}_{1}';\r\n", controllerStart, controllerEnd));
}
base.WriteTypeContent(result, type);
}
public override string GetTypescriptType(TsProperty property)
{
if (property.Type == "System.Guid")
return "Guid";
if (property.Type == "System.Guid[]")
return "Guid[]";
return base.GetTypescriptType(property);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlixSharp.Holders.RottenTomatoes
{
public class ReleaseDate
{
public ReleaseDateType ReleaseType { get; set; }
public DateTime? Date { get; set; }
}
public class Rating
{
public RottenRatingType Type { get; set; }
public RottenRating RottenTomatoRating { get; set; }
public Int32 Score { get; set; }
}
public enum ReleaseDateType
{
Theater,
DVD
}
public enum RottenRatingType
{
Critic,
Audience
}
public enum RottenRating
{
Fresh,
CertifiedFresh,
Upright,
/// some others in here
Spilled,
Rotten,
None
}
public class Poster
{
public PosterType Type { get; set; }
public String Url { get; set; }
}
public enum PosterType
{
Thumbnail,
Profile,
Detailed,
Original
}
public class AlternateId
{
public AlternateIdType Type { get; set; }
public String Id { get; set; }
}
public enum AlternateIdType
{
Imdb
}
public class Clip
{
public String Title { get; set; }
public Int32 Duration { get; set; }
public String ThumbnailUrl { get; set; }
public String SourceUrl { get; set; }
}
public class Review
{
public String Critic { get; set; }
public DateTime? Date { get; set; }
public RottenRating Freshness { get; set; }
public String Publication { get; set; }
public String Quote { get; set; }
public String SourceUrl { get; set; }
}
public enum ReviewType
{
All,
Top_Critic,
DVD
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking.NetworkSystem;
public class Scale : Trigger
{
public int WaitingTime = 500;
public float IntervalAngle = 0.2f;
public float MaxAngle = 45;
private bool _busy = false;
void Update()
{
Debug.Log(transform.eulerAngles.x);
if (transform.eulerAngles.x > MaxAngle && transform.eulerAngles.x < 180)
transform.eulerAngles = new Vector3(MaxAngle, 0, 0);
if (transform.eulerAngles.x < -MaxAngle && transform.eulerAngles.x > 180)
transform.eulerAngles = new Vector3(-MaxAngle, 0, 0);
if (Equals() && !_busy)
{
var timer = Timer();
StartCoroutine(timer);
}
}
private IEnumerator Timer()
{
for (var i = 0; i < WaitingTime; i++)
{
if (!Equals())
yield break;
yield return new WaitForSeconds(0.01f);
}
Action();
}
private bool Equals()
{
if (transform.rotation.eulerAngles.x > -IntervalAngle && transform.rotation.eulerAngles.x < IntervalAngle)
return true;
return false;
}
protected override void Action()
{
Triggering();
}
}
|
// WaitForUseInvitationalItemAction
using ClubPenguin.Core;
using ClubPenguin.Interactables.Domain;
using Disney.LaunchPadFramework;
using Disney.MobileNetwork;
using HutongGames.PlayMaker;
[ActionCategory("Props")]
public class WaitForUseInvitationalItemAction : FsmStateAction
{
public FsmString ItemName;
public FsmEvent UseEvent;
public FsmEvent CompleteEvent;
public FsmEvent CancelEvent;
public override void OnEnter()
{
Service.Get<EventDispatcher>().AddListener<InteractablesEvents.InvitationalItemUsed>(onItemUsed);
Service.Get<EventDispatcher>().AddListener<InputEvents.ActionEvent>(onAction);
}
public override void OnExit()
{
Service.Get<EventDispatcher>().RemoveListener<InteractablesEvents.InvitationalItemUsed>(onItemUsed);
Service.Get<EventDispatcher>().RemoveListener<InputEvents.ActionEvent>(onAction);
}
private bool onItemUsed(InteractablesEvents.InvitationalItemUsed evt)
{
string a = evt.Item.name.Replace("(Clone)", "");
if (a == ItemName.Value)
{
if (evt.QuantityLeft <= 0)
{
base.Fsm.Event(CompleteEvent);
}
else
{
base.Fsm.Event(UseEvent);
}
}
return false;
}
private bool onAction(InputEvents.ActionEvent evt)
{
if (evt.Action == InputEvents.Actions.Cancel)
{
base.Fsm.Event(CancelEvent);
}
return false;
}
}
|
using Akavache;
using Autofac;
using Framework.Autofac;
using System;
using System.Reflection;
namespace BaseTest
{
public class AbstractUnitTest
{
static AbstractUnitTest() {
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Profiling;
public class Container : MonoBehaviour
{
public float safeZone;
public float resolution;
public float threshold;
public ComputeShader computeShader;
public bool calculateNormals;
private CubeGrid grid;
// Mesh cache
Mesh mesh;
public void Start()
{
this.grid = new CubeGrid(this, this.computeShader);
mesh = GetComponent<MeshFilter>().mesh;
}
public void Update()
{
Profiler.BeginSample("evaluateAll");
this.grid.evaluateAll(this.GetComponentsInChildren<MetaBall>());
Profiler.EndSample();
Profiler.BeginSample("Mesh setting");
mesh.Clear();
mesh.SetVertices(grid.vertices);
mesh.SetTriangles(grid.getTriangleList(), 0);
if (this.calculateNormals)
{
mesh.RecalculateNormals();
}
Profiler.EndSample();
}
} |
/*
Copyright (C) 2012-2014 de4dot@gmail.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.Collections.Generic;
using System.IO;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Writer {
/// <summary>
/// Base class of chunk list types
/// </summary>
/// <typeparam name="T">Chunk type</typeparam>
public abstract class ChunkListBase<T> : IChunk where T : IChunk {
/// <summary>All chunks</summary>
protected List<Elem> chunks;
uint length;
uint virtualSize;
/// <summary><c>true</c> if <see cref="SetOffset"/> has been called</summary>
protected bool setOffsetCalled;
FileOffset offset;
RVA rva;
/// <summary>
/// Helper struct
/// </summary>
protected struct Elem {
/// <summary>Data</summary>
public readonly T chunk;
/// <summary>Alignment</summary>
public readonly uint alignment;
/// <summary>
/// Constructor
/// </summary>
/// <param name="chunk">Chunk</param>
/// <param name="alignment">Alignment</param>
public Elem(T chunk, uint alignment) {
this.chunk = chunk;
this.alignment = alignment;
}
}
/// <summary>
/// Equality comparer for <see cref="Elem"/>
/// </summary>
protected sealed class ElemEqualityComparer : IEqualityComparer<Elem> {
IEqualityComparer<T> chunkComparer;
/// <summary>
/// Constructor
/// </summary>
/// <param name="chunkComparer">Compares the chunk type</param>
public ElemEqualityComparer(IEqualityComparer<T> chunkComparer) {
this.chunkComparer = chunkComparer;
}
/// <inheritdoc/>
public bool Equals(Elem x, Elem y) {
return x.alignment == y.alignment &&
chunkComparer.Equals(x.chunk, y.chunk);
}
/// <inheritdoc/>
public int GetHashCode(Elem obj) {
return (int)obj.alignment + chunkComparer.GetHashCode(obj.chunk);
}
}
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <inheritdoc/>
public virtual void SetOffset(FileOffset offset, RVA rva) {
setOffsetCalled = true;
this.offset = offset;
this.rva = rva;
length = 0;
virtualSize = 0;
foreach (var elem in chunks) {
uint paddingF = (uint)offset.AlignUp(elem.alignment) - (uint)offset;
uint paddingV = (uint)rva.AlignUp(elem.alignment) - (uint)rva;
offset += paddingF;
rva += paddingV;
elem.chunk.SetOffset(offset, rva);
uint chunkLenF = elem.chunk.GetFileLength();
uint chunkLenV = elem.chunk.GetVirtualSize();
offset += chunkLenF;
rva += chunkLenV;
length += paddingF + chunkLenF;
virtualSize += paddingV + chunkLenV;
}
}
/// <inheritdoc/>
public uint GetFileLength() {
return length;
}
/// <inheritdoc/>
public uint GetVirtualSize() {
return virtualSize;
}
/// <inheritdoc/>
public void WriteTo(BinaryWriter writer) {
FileOffset offset2 = offset;
foreach (var elem in chunks) {
int paddingF = (int)offset2.AlignUp(elem.alignment) - (int)offset2;
writer.WriteZeros(paddingF);
elem.chunk.VerifyWriteTo(writer);
offset2 += (uint)paddingF + elem.chunk.GetFileLength();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MuteMusic : MonoBehaviour
{
private bool isMuted = false;
private void Awake()
{
GameObject[] musicPlayers = GameObject.FindGameObjectsWithTag("music");
if (musicPlayers.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
public void PausePlayBGM()
{
isMuted = !isMuted;
if(isMuted)
{
GetComponent<AudioSource>().Pause();
}
else
{
GetComponent<AudioSource>().UnPause();
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NPay.Modules.Wallets.Core.Wallets.Exceptions;
using NPay.Modules.Wallets.Core.Wallets.Repositories;
using NPay.Modules.Wallets.Core.Wallets.ValueObjects;
using NPay.Modules.Wallets.Shared.Events;
using NPay.Shared.Commands;
using NPay.Shared.Messaging;
using NPay.Shared.Time;
namespace NPay.Modules.Wallets.Application.Wallets.Commands.Handlers
{
internal sealed class AddFundsHandler : ICommandHandler<AddFunds>
{
private readonly IWalletRepository _walletRepository;
private readonly IClock _clock;
private readonly IMessageBroker _messageBroker;
private readonly ILogger<AddFundsHandler> _logger;
public AddFundsHandler(IWalletRepository walletRepository, IClock clock, IMessageBroker messageBroker,
ILogger<AddFundsHandler> logger)
{
_walletRepository = walletRepository;
_clock = clock;
_messageBroker = messageBroker;
_logger = logger;
}
public async Task HandleAsync(AddFunds command, CancellationToken cancellationToken = default)
{
var (walletId, amount) = command;
var wallet = await _walletRepository.GetAsync(walletId);
if (wallet is null)
{
throw new WalletNotFoundException(walletId);
}
var now = _clock.CurrentDate();
var transfer = wallet.AddFunds(new TransferId(), amount, now);
await _walletRepository.UpdateAsync(wallet);
await _messageBroker.PublishAsync(new FundsAdded(walletId, wallet.OwnerId, transfer.Currency,
transfer.Amount), cancellationToken);
_logger.LogInformation($"Added {transfer.Amount} {transfer.Currency} to the wallet: '{wallet.Id}'");
}
}
} |
using System;
using MyBox.Internal;
using UnityEngine;
namespace MyBox
{
[Serializable]
public class PlayerPrefsInt : PlayerPrefsType
{
public int Value
{
get => PlayerPrefs.GetInt(Key, 0);
set => PlayerPrefs.SetInt(Key, value);
}
public static PlayerPrefsInt WithKey(string key) => new PlayerPrefsInt(key);
public PlayerPrefsInt(string key) => Key = key;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlacableUI : MonoBehaviour
{
public RectTransform ContentParent;
public GameObject PlacableButtonPrefab;
public PlacableData[] Placables;
private void Start()
{
for (int i = 0; i < Placables.Length; i++)
{
GameObject obj = Instantiate(PlacableButtonPrefab);
obj.transform.SetParent(ContentParent, false);
(obj.transform as RectTransform).anchoredPosition = new Vector2(200 * i + 100, 0);
obj.GetComponent<PlacableButton>().SetPlacable(Placables[i]);
}
ContentParent.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 200 * Placables.Length);
ContentParent.anchoredPosition = Vector2.zero;
}
} |
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public static GameManager instance = null;
public static GameObject canvas = null;
public static GameObject music = null;
public static GameObject eventSystem;
int canvas_children;
public GameObject menu_principal;
public GameObject menu_perder;
public GameObject menu_control;
public GameObject menu_ganar;
public GameObject menu_pausa;
public GameObject audio_escena;
AudioSource audio_scene;
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
}
else
{
Destroy(this.gameObject);
}
if (canvas == null)
{
canvas = GameObject.FindGameObjectWithTag("Menu");
DontDestroyOnLoad(canvas);
}
else
{
Destroy(canvas.gameObject);
}
if (music == null)
{
music = GameObject.FindGameObjectWithTag("Sound");
DontDestroyOnLoad(music);
}
else
{
Destroy(music.gameObject);
}
}
private void Start() {
menu_perder = canvas.transform.GetChild(0).gameObject;
menu_control = canvas.transform.GetChild(1).gameObject;
menu_ganar = canvas.transform.GetChild(2).gameObject;
menu_principal = canvas.transform.GetChild(4).gameObject;
menu_pausa = menu_principal.transform.GetChild(3).gameObject;
canvas_children = canvas.transform.childCount;
audio_escena = music.transform.GetChild(0).gameObject;
audio_scene = audio_escena.GetComponent<AudioSource>();
}
void Update() {
PauseGame();
if (Input.GetKeyUp(KeyCode.KeypadPlus))
{
LoadScene();
}
if (Input.GetKeyUp(KeyCode.KeypadMinus))
{
BackScene();
}
}
public void LoadScene()
{
int level;
if (SceneManager.GetActiveScene().buildIndex != 0)
{
level = int.Parse(SceneManager.GetActiveScene().name);
level += 1;
if (level <= 10)
SceneManager.LoadScene(level);
else
menu_ganar.transform.GetChild(2).gameObject.SetActive(false);
}
else
{
SceneManager.LoadScene(1);
}
}
void BackScene()
{
int level;
if (SceneManager.GetActiveScene().buildIndex > 1)
{
level = SceneManager.GetActiveScene().buildIndex;
level -= 1;
SceneManager.LoadScene(level);
}
}
public void SetScene()
{
Time.timeScale = 1;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
DesactivateCanvasChildren();
}
public void ExitGame()
{
Application.Quit();
}
private void PauseGame()
{
if(Input.GetKeyUp(KeyCode.Escape) && SceneManager.GetActiveScene().buildIndex != 0)
{
if(Time.timeScale == 1)
{
Time.timeScale = 0;
showPaused();
}
else if (Time.timeScale == 0)
{
Time.timeScale = 1;
hidePaused();
}
}
}
public void showPaused()
{
menu_principal.SetActive(true);
menu_principal.transform.GetChild(2).gameObject.SetActive(false);
menu_pausa.SetActive(true);
Cursor.lockState = CursorLockMode.Confined;
Cursor.visible = true;
}
public void hidePaused()
{
menu_principal.SetActive(false);
menu_pausa.SetActive(false);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
DesactivateCanvasChildren();
Time.timeScale = 1;
}
public void DesactivateCanvasChildren()
{
for (int i=0; i < canvas_children; i++)
{
canvas.transform.GetChild(i).gameObject.SetActive(false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace EnforceScript
{
class SymbolTable
{
public enum Type
{
root,
scope_enter,
variable_definition,
function_definition,
}
public struct Symbol
{
public Type type;
public AST.Definition def;
}
private Stack<Symbol> table = new Stack<Symbol>();
public SymbolTable()
{
table.Push(root());
}
public void AddDefinition(AST.FunctionDefinition def)
{
table.Push(new Symbol { type = Type.function_definition, def = def });
}
public void AddDefinition(AST.VariableDefinition def)
{
table.Push(new Symbol { type = Type.variable_definition, def = def });
}
public bool IsVariableDefined(string variable_name)
{
foreach (var symbol in reversed_table())
if(symbol.type == Type.variable_definition)
if (symbol.def is AST.VariableDefinition)
if (((AST.VariableDefinition)symbol.def).name == variable_name)
return true;
return false;
}
public AST.VariableDefinition GetVariableDefinition(string variable_name)
{
foreach (var symbol in reversed_table())
{
if (symbol.type != Type.variable_definition)
continue;
if (symbol.def is AST.VariableDefinition)
{
var def = (AST.VariableDefinition)symbol.def;
if (def.name == variable_name)
return def;
}
}
return null;
}
public AST.FunctionDefinition GetFunctionDefinition(string function_name)
{
foreach (var symbol in reversed_table())
{
if (symbol.type != Type.function_definition)
continue;
if (symbol.def is AST.FunctionDefinition)
{
var def = (AST.FunctionDefinition)symbol.def;
if (def.name == function_name)
return def;
}
}
return null;
}
public bool IsFunctionDefined(string function_name)
{
foreach (var symbol in reversed_table())
if(symbol.type == Type.function_definition)
if (symbol.def is AST.FunctionDefinition)
if (((AST.FunctionDefinition)symbol.def).name == function_name)
return true;
return false;
}
public void EnterScope()
{
table.Push(new Symbol { type = Type.scope_enter });
}
private Symbol root()
{
return new Symbol { type = Type.root };
}
public void ExitScope()
{
while(true) {
var popped = table.Pop();
if (popped.type == Type.scope_enter)
break;
if (popped.type == Type.root)
{
table.Push(root());
break;
}
}
}
private Symbol[] reversed_table()
{
var arr = table.ToArray();
Array.Reverse(arr);
return arr;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Helper : MonoBehaviour {
[TextArea]
[Tooltip("help messages for each page")]
public string[] helps;
[Tooltip ("current page")]
public int current;
[Tooltip("help message text")]
public Text mytext;
[Tooltip("current page indicator")]
public Text page;
void Start () {
//mytext = transform.Find ("helpText").GetComponent<Text>();
//page = transform.Find ("pageText").GetComponent<Text>();
SetPage ();
}
public void Back () {
if (current <= 0) return;
current--;
SetPage ();
}
public void Next () {
if (current >= helps.Length - 1) return;
current++;
SetPage ();
}
void SetPage () {
mytext.text = helps [current];
page.text = "Page " + (current + 1) + "/" + helps.Length;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Holon.Remoting.Introspection
{
/// <summary>
/// Implements INodeQuery001
/// </summary>
internal class NodeQueryImpl : INodeQuery001
{
private Node _node;
public Task<NodeInformation> GetInfo() {
// build tags
Dictionary<string, string> tags = new Dictionary<string, string>(Node.DefaultTags);
return Task.FromResult(new NodeInformation() {
ApplicationId = _node.ApplicationId,
UUID = _node.UUID,
ApplicationVersion = _node.ApplicationVersion,
ServiceCount = _node.ServiceCount,
Tags = tags.Select((kv) => new NodeTagInformation() { Name = kv.Key, Value = kv.Value }).ToArray()
});
}
public Task<NodeServiceInformation[]> GetServices() {
return Task.FromResult(_node.Services.Select((s) => new NodeServiceInformation() {
Address = s.Address.ToString(),
Type = s.Type,
Execution = s.Execution,
Uptime = (long)(DateTimeOffset.UtcNow - s.TimeSetup).TotalSeconds,
RequestsCompleted = s.RequestsCompleted,
RequestsFaulted = s.RequestsFaulted,
RequestsPending = s.RequestsPending
}).ToArray());
}
public NodeQueryImpl(Node node) {
_node = node;
}
}
}
|
using System.Collections.Generic;
namespace Smellyriver.TankInspector.Pro.Modularity.Input
{
public interface ICommandManager<TCommand>
where TCommand : ICommand
{
IEnumerable<TCommand> Commands { get; }
void Register(TCommand command);
}
}
|
#Tue Nov 30 21:54:55 EST 2021
lib/features/com.ibm.websphere.appserver.httptransport-1.0.mf=4f42e0df19d53667d9d1f13505489d05
dev/spi/ibm/com.ibm.websphere.appserver.spi.httptransport_4.1.59.jar=c4fe248241be5c86edfb613a16a11e66
lib/com.ibm.ws.transport.http_1.0.59.jar=1011114cb93848c6d82507dfc0bd2540
dev/spi/ibm/javadoc/com.ibm.websphere.appserver.spi.httptransport_4.1-javadoc.zip=f40b2ae117ab1599faa3203cf8b163ba
|
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the kafkaconnect-2021-09-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KafkaConnect.Model
{
/// <summary>
/// Container for the parameters to the CreateConnector operation.
/// Creates a connector using the specified properties.
/// </summary>
public partial class CreateConnectorRequest : AmazonKafkaConnectRequest
{
private Capacity _capacity;
private Dictionary<string, string> _connectorConfiguration = new Dictionary<string, string>();
private string _connectorDescription;
private string _connectorName;
private KafkaCluster _kafkaCluster;
private KafkaClusterClientAuthentication _kafkaClusterClientAuthentication;
private KafkaClusterEncryptionInTransit _kafkaClusterEncryptionInTransit;
private string _kafkaConnectVersion;
private LogDelivery _logDelivery;
private List<Plugin> _plugins = new List<Plugin>();
private string _serviceExecutionRoleArn;
private WorkerConfiguration _workerConfiguration;
/// <summary>
/// Gets and sets the property Capacity.
/// <para>
/// Information about the capacity allocated to the connector. Exactly one of the two
/// properties must be specified.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public Capacity Capacity
{
get { return this._capacity; }
set { this._capacity = value; }
}
// Check to see if Capacity property is set
internal bool IsSetCapacity()
{
return this._capacity != null;
}
/// <summary>
/// Gets and sets the property ConnectorConfiguration.
/// <para>
/// A map of keys to values that represent the configuration for the connector.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public Dictionary<string, string> ConnectorConfiguration
{
get { return this._connectorConfiguration; }
set { this._connectorConfiguration = value; }
}
// Check to see if ConnectorConfiguration property is set
internal bool IsSetConnectorConfiguration()
{
return this._connectorConfiguration != null && this._connectorConfiguration.Count > 0;
}
/// <summary>
/// Gets and sets the property ConnectorDescription.
/// <para>
/// A summary description of the connector.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=1024)]
public string ConnectorDescription
{
get { return this._connectorDescription; }
set { this._connectorDescription = value; }
}
// Check to see if ConnectorDescription property is set
internal bool IsSetConnectorDescription()
{
return this._connectorDescription != null;
}
/// <summary>
/// Gets and sets the property ConnectorName.
/// <para>
/// The name of the connector.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string ConnectorName
{
get { return this._connectorName; }
set { this._connectorName = value; }
}
// Check to see if ConnectorName property is set
internal bool IsSetConnectorName()
{
return this._connectorName != null;
}
/// <summary>
/// Gets and sets the property KafkaCluster.
/// <para>
/// Specifies which Apache Kafka cluster to connect to.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public KafkaCluster KafkaCluster
{
get { return this._kafkaCluster; }
set { this._kafkaCluster = value; }
}
// Check to see if KafkaCluster property is set
internal bool IsSetKafkaCluster()
{
return this._kafkaCluster != null;
}
/// <summary>
/// Gets and sets the property KafkaClusterClientAuthentication.
/// <para>
/// Details of the client authentication used by the Apache Kafka cluster.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public KafkaClusterClientAuthentication KafkaClusterClientAuthentication
{
get { return this._kafkaClusterClientAuthentication; }
set { this._kafkaClusterClientAuthentication = value; }
}
// Check to see if KafkaClusterClientAuthentication property is set
internal bool IsSetKafkaClusterClientAuthentication()
{
return this._kafkaClusterClientAuthentication != null;
}
/// <summary>
/// Gets and sets the property KafkaClusterEncryptionInTransit.
/// <para>
/// Details of encryption in transit to the Apache Kafka cluster.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public KafkaClusterEncryptionInTransit KafkaClusterEncryptionInTransit
{
get { return this._kafkaClusterEncryptionInTransit; }
set { this._kafkaClusterEncryptionInTransit = value; }
}
// Check to see if KafkaClusterEncryptionInTransit property is set
internal bool IsSetKafkaClusterEncryptionInTransit()
{
return this._kafkaClusterEncryptionInTransit != null;
}
/// <summary>
/// Gets and sets the property KafkaConnectVersion.
/// <para>
/// The version of Kafka Connect. It has to be compatible with both the Apache Kafka cluster's
/// version and the plugins.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string KafkaConnectVersion
{
get { return this._kafkaConnectVersion; }
set { this._kafkaConnectVersion = value; }
}
// Check to see if KafkaConnectVersion property is set
internal bool IsSetKafkaConnectVersion()
{
return this._kafkaConnectVersion != null;
}
/// <summary>
/// Gets and sets the property LogDelivery.
/// <para>
/// Details about log delivery.
/// </para>
/// </summary>
public LogDelivery LogDelivery
{
get { return this._logDelivery; }
set { this._logDelivery = value; }
}
// Check to see if LogDelivery property is set
internal bool IsSetLogDelivery()
{
return this._logDelivery != null;
}
/// <summary>
/// Gets and sets the property Plugins.
/// <para>
/// Specifies which plugins to use for the connector.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<Plugin> Plugins
{
get { return this._plugins; }
set { this._plugins = value; }
}
// Check to see if Plugins property is set
internal bool IsSetPlugins()
{
return this._plugins != null && this._plugins.Count > 0;
}
/// <summary>
/// Gets and sets the property ServiceExecutionRoleArn.
/// <para>
/// The Amazon Resource Name (ARN) of the IAM role used by the connector to access the
/// Amazon Web Services resources that it needs. The types of resources depends on the
/// logic of the connector. For example, a connector that has Amazon S3 as a destination
/// must have permissions that allow it to write to the S3 destination bucket.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ServiceExecutionRoleArn
{
get { return this._serviceExecutionRoleArn; }
set { this._serviceExecutionRoleArn = value; }
}
// Check to see if ServiceExecutionRoleArn property is set
internal bool IsSetServiceExecutionRoleArn()
{
return this._serviceExecutionRoleArn != null;
}
/// <summary>
/// Gets and sets the property WorkerConfiguration.
/// <para>
/// Specifies which worker configuration to use with the connector.
/// </para>
/// </summary>
public WorkerConfiguration WorkerConfiguration
{
get { return this._workerConfiguration; }
set { this._workerConfiguration = value; }
}
// Check to see if WorkerConfiguration property is set
internal bool IsSetWorkerConfiguration()
{
return this._workerConfiguration != null;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RPA.Interfaces.Activities
{
public class ActivityGroupItem : ActivityGroupOrLeafItem
{
public List<ActivityGroupOrLeafItem> Children = new List<ActivityGroupOrLeafItem>();
}
}
|
using System.Linq;
using FashiShop.Core.Entity;
using System.Collections.Generic;
namespace FashiShop.Model
{
public class User:BaseEntity
{
public User()
{
RoleId=Roles.User;
}
public string Firstname { get; set; }
public string Lastname { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public Roles RoleId { get; set; }
//Mapping
public virtual List<Order> Orders { get; set; }
public string EmailSplit(string mail){
UserName=mail.Split('@').First();
return UserName;
}
}
}
public enum Roles{
User=1,
Admin=2
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UIPopup_Victory : MonoBehaviour
{
public int rewardCash;
public UIButton btnLobby;
public UIButton btnRestart;
public UIButton btnNextStage;
public System.Action OnBtnLobbyClicked;
public UILabel Lb_rewardCash;
void Start()
{
this.btnLobby.onClick.Add(new EventDelegate(() =>
{
SoundEffectManager.effectSoundAction();
OnBtnLobbyClicked();
GetReward();
}));
this.btnNextStage.onClick.Add(new EventDelegate(() => {
SoundEffectManager.effectSoundAction();
if (App.instance.stageNumber < 16)
{
App.instance.stageNumber += 1;
}
GetReward();
SceneManager.LoadScene("DefenseMode");
}));
this.btnRestart.onClick.Add(new EventDelegate(() => {
SoundEffectManager.effectSoundAction();
GetReward();
SceneManager.LoadScene("DefenseMode");
}));
}
public void GetReward()
{
DataManager.GetInstance().userInfo.cash += (ulong)rewardCash;
Debug.Log($"보상을 {rewardCash} 받았습니다.");
DataManager.GetInstance().SaveUserInfo();
}
public void Init(int rewardCash)
{
this.rewardCash = rewardCash;
Lb_rewardCash.text = this.rewardCash.ToString();
}
}
|
// <copyright file="GameRepository.MoveDto.cs" company="RJ">
// Copyright (c) RJ. All rights reserved.
// </copyright>
namespace Chess.DomainServices
{
using System.Linq;
using System.Runtime.Serialization;
using Chess.Domain;
/// <summary>
/// Manages game persistence.
/// </summary>
public partial class GameRepository
{
[DataContract]
private class MoveDto
{
public MoveDto()
{
}
public MoveDto(Move move)
{
this.PieceId = move.Piece.Id;
this.FromFile = move.From.File.Index;
this.FromRank = move.From.Rank.Index;
this.File = move.Position.File.Index;
this.Rank = move.Position.Rank.Index;
this.IsCheck = move.IsCheck;
this.IsCheckMate = move.IsCheckMate;
this.Kind = move.Kind;
this.PromotedTo = move.PromotedTo;
}
[DataMember]
public long PieceId { get; set; }
[DataMember]
public int FromFile { get; set; }
[DataMember]
public int FromRank { get; set; }
[DataMember]
public int File { get; set; }
[DataMember]
public int Rank { get; set; }
[DataMember]
public MoveKind Kind { get; set; }
[DataMember]
public bool IsCheck { get; set; }
[DataMember]
public bool IsCheckMate { get; set; }
[DataMember]
public PieceKind? PromotedTo { get; set; }
public Move ToMove(ChessBoard board, Army army)
{
return new Move(
army.Pieces.First(p => p.Id == this.PieceId),
board[new File(this.FromFile), new Rank(this.FromRank)],
this.Kind,
board[new File(this.File), new Rank(this.Rank)],
this.IsCheck,
this.IsCheckMate,
this.PromotedTo);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeSight.Data.Models
{
public class Project
{
public string ProjectId { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
public string DateCreated { get; set; }
/// <summary>
/// 1 - Save log to Flat File
/// 2 - Azure Database
/// 3 - SQL Database
/// </summary>
public int LogSaveFormat { get; set; }
public List<MessageLog> MessageLogs { get; set; }
public List<ExceptionLog> ExceptionLogs { get; set; }
}
}
|
using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Amns.GreyFox.Web.UI.WebControls;
using System.Reflection;
namespace Amns.Tessen.Web.UI.WebControls
{
/// <summary>
/// Summary description for TessenAboutDialog.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:TessenAboutDialog runat=server></{0}:TessenAboutDialog>")]
public class TessenAboutDialog : AboutDialog
{
Assembly aspNetAssembly;
double timeOffset;
protected override void Render(HtmlTextWriter output)
{
// Retrieve reflection information on ASP.net
aspNetAssembly = Assembly.GetCallingAssembly();
// Retrieve reflection information on this assembly
EnsureAssembly();
// Retrieve Tessen runtime configuration
timeOffset = double.Parse(ConfigurationManager.AppSettings["Tessen_TimeOffset"]);
base.Render(output);
}
protected override void RenderDetails(HtmlTextWriter output)
{
// Output Tessen Configuration
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Tessen Runtime Configuration");
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Tessen DateTime Offset
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Time Offset");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(timeOffset);
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Tessen DateTime Offset
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Local Time");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(DateTime.Now.AddHours(timeOffset));
output.WriteEndTag("td");
output.WriteEndTag("tr");
#region Client Details
// Output Server Asp.Net Version
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Client Details");
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Client Host Name
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("valign", "top");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Client Agent");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(Context.Request.UserAgent);
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Client Host Address
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Client Host Address");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(Context.Request.UserHostAddress);
output.WriteEndTag("td");
output.WriteEndTag("tr");
#endregion
#region ASP.net Details
// Output Server Asp.Net Version
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", SubHeaderCssClass);
output.WriteAttribute("colspan", "2");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Server Details on ");
output.Write(Context.Server.MachineName);
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Server Asp.Net Version
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("ASP.net Version");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(aspNetAssembly.GetName().Version.ToString(4));
output.WriteEndTag("td");
output.WriteEndTag("tr");
// Output Server DateTime
output.WriteFullBeginTag("tr");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row1");
output.WriteAttribute("nowrap", "true");
output.Write(HtmlTextWriter.TagRightChar);
output.Write("Time");
output.WriteEndTag("td");
output.WriteBeginTag("td");
output.WriteAttribute("class", "row2");
output.WriteAttribute("width", "100%");
output.Write(HtmlTextWriter.TagRightChar);
output.Write(DateTime.Now);
output.WriteEndTag("td");
output.WriteEndTag("tr");
#endregion
}
}
} |
using System.Text;
using System.Runtime.InteropServices.WindowsRuntime;
using System;
using System.IO;
using System.Security.Cryptography;
namespace FFImageLoading.Helpers
{
public class MD5Helper : IMD5Helper
{
[ThreadStatic]
private static MD5 md5;
private byte[] SafeHash(byte[] input)
{
if(md5 == null)
{
md5 = System.Security.Cryptography.MD5.Create();
}
return md5.ComputeHash(input);
}
public byte[] ComputeHash(byte[] input)
{
return SafeHash(input);
}
public string MD5(Stream input)
{
var bytes = ComputeHash(StreamToByteArray(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
public string MD5(string input)
{
var bytes = ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
} |
using MxNet;
using System;
using System.Collections.Generic;
using System.Text;
using MxNet.NN.Initializers;
using MxNet.NN.Constraints;
using MxNet.NN.Regularizers;
namespace MxNet.NN.Layers
{
public abstract class BaseLayer
{
public string Name { get; set; }
public string ID { get; set; }
public Dictionary<string, BaseInitializer> InitParams;
public Dictionary<string, BaseConstraint> ConstraintParams;
public Dictionary<string, BaseRegularizer> RegularizerParams;
public BaseLayer(string name)
{
Name = name;
ID = UUID.GetID(name);
InitParams = new Dictionary<string, BaseInitializer>();
ConstraintParams = new Dictionary<string, BaseConstraint>();
RegularizerParams = new Dictionary<string, BaseRegularizer>();
}
public abstract Symbol Build(Symbol x);
}
}
|
using UdonSharp;
using UnityEngine;
public class CalculatingContextHandler : UdonSharpBehaviour
{
// 이 클래스는 static class처럼 씁니다. 별도의 멤버변수를 갖게 하지 맙시다
const int MAN_START_INDEX = 0;
const int MAN_END_INDEX = 8;
const int PIN_START_INDEX = 9;
const int PIN_END_INDEX = 17;
const int SOU_START_INDEX = 18;
const int SOU_END_INDEX = 26;
const int GLOBALORDERS = 0;
const int CHILIST = 1;
const int CHICOUNT = 2;
const int PONLIST = 3;
const int PONCOUNT = 4;
public object[] CreateContext(int[] typedGlobalOrders)
{
var context = new object[5];
context[GLOBALORDERS] = Clone(typedGlobalOrders);
context[CHILIST] = new int[10] { 999, 999, 999, 999, 999, 999, 999, 999, 999, 999 };
context[CHICOUNT] = 0;
context[PONLIST] = new int[10] { 999, 999, 999, 999, 999, 999, 999, 999, 999, 999 };
context[PONCOUNT] = 0;
return context;
}
public object[] CopyContext(object[] context)
{
var newContext = new object[5];
newContext[GLOBALORDERS] = Clone(ReadGlobalOrders(context));
newContext[CHILIST] = Clone(ReadChiList(context));
newContext[CHICOUNT] = ReadChiCount(context);
newContext[PONLIST] = Clone(ReadPonList(context));
newContext[PONCOUNT] = ReadPonCount(context);
return newContext;
}
public void ApplyGlobalOrders(object[] ctx, int[] globalOrders)
{
ctx[GLOBALORDERS] = Clone(globalOrders);
}
public int[] GetGlobalOrdersFromChiPon(object[] ctx)
{
var globalOrders = new int[34];
var chis = ReadChiList(ctx);
for (var i = 0; i < ReadChiCount(ctx); ++i)
{
var chiStartGlobalOrder = chis[i];
globalOrders[chiStartGlobalOrder] += 1;
globalOrders[chiStartGlobalOrder + 1] += 1;
globalOrders[chiStartGlobalOrder + 2] += 1;
}
var pons = ReadPonList(ctx);
for (var i = 0; i < ReadPonCount(ctx); ++i)
{
var ponStartGlobalOrder = pons[i];
globalOrders[ponStartGlobalOrder] += 3;
}
return globalOrders;
}
public object[] AddContextAll(object[] ctx1, object[] ctx2, object[] ctx3, object[] ctx4)
{
var added1 = AddContext(ctx1, ctx2);
var added2 = AddContext(ctx3, ctx4);
return AddContext(added1, added2);
}
public object[] AddContext(object[] ctx1, object[] ctx2)
{
if (ctx1 == null) { return ctx2; }
if (ctx2 == null) { return ctx1; }
if (ctx1 == null && ctx2 == null) { return null; }
var context = CreateContext(new int[34]);
// NOTE) 글로벌오더는 여기서 합치지 않는다
//var newGlobalOrders = ReadGlobalOrders(context);
//var ctx1GlobalOrders = ReadGlobalOrders(ctx1);
//var ctx2GlobalOrders = ReadGlobalOrders(ctx2);
//for (var i = 0; i < 34; ++i)
//{
// newGlobalOrders[i] = ctx1GlobalOrders[i] + ctx2GlobalOrders[i];
//}
var ctx1Chis = ReadChiList(ctx1);
for (var i = 0; i < ReadChiCount(ctx1); ++i)
{
AppendChiList(context, ctx1Chis[i]);
}
var ctx2Chis = ReadChiList(ctx2);
for (var i = 0; i < ReadChiCount(ctx2); ++i)
{
AppendChiList(context, ctx2Chis[i]);
}
var ctx1Pons = ReadPonList(ctx1);
for (var i = 0; i < ReadPonCount(ctx1); ++i)
{
AppendPonList(context, ctx1Pons[i]);
}
var ctx2Pons = ReadPonList(ctx2);
for (var i = 0; i < ReadPonCount(ctx2); ++i)
{
AppendPonList(context, ctx2Pons[i]);
}
return context;
}
public int[] ReadGlobalOrders(object[] context)
{
if(context == null)
{
Debug.LogError("[Debug] 어어 왜 NULL이지??");
}
return (int[])context[GLOBALORDERS];
}
public int[] ReadChiList(object[] context)
{
return (int[])context[CHILIST];
}
public int ReadChiCount(object[] context)
{
return (int)context[CHICOUNT];
}
public int[] ReadPonList(object[] context)
{
return (int[])context[PONLIST];
}
public int ReadPonCount(object[] context)
{
return (int)context[PONCOUNT];
}
public void ApplyPon(object[] context, int startGlobalOrder)
{
var globalOrders = ReadGlobalOrders(context);
// -3 하지 않는다. 4개인 깡 상태도 몸1개로 치기 때문
//globalOrders[startGlobalOrder] -= 3;
globalOrders[startGlobalOrder] = 0;
AppendPonList(context, startGlobalOrder);
}
public void ApplyChi(object[] context, int startGlobalOrder)
{
var globalOrders = ReadGlobalOrders(context);
globalOrders[startGlobalOrder]--;
globalOrders[startGlobalOrder + 1]--;
globalOrders[startGlobalOrder + 2]--;
AppendChiList(context, startGlobalOrder);
}
public void AppendPonList(object[] context, int ponGlobalOrder)
{
var ponList = ReadPonList(context);
var ponCount = ReadPonCount(context);
ponList[ponCount++] = ponGlobalOrder;
context[PONCOUNT] = ponCount;
Sort(ponList, ponCount);
}
public void AppendChiList(object[] context, int chiGlobalOrder)
{
var chiList = ReadChiList(context);
var chiCount = ReadChiCount(context);
chiList[chiCount++] = chiGlobalOrder;
context[CHICOUNT] = chiCount;
Sort(chiList, chiCount);
}
public bool IsRemainsChiCountEqual(object[] context, int startGlobalOrder)
{
var globalOrders = ReadGlobalOrders(context);
return globalOrders[startGlobalOrder] == globalOrders[startGlobalOrder + 1]
&& globalOrders[startGlobalOrder + 1] == globalOrders[startGlobalOrder + 2];
}
public object[] CloneObject(object[] arr)
{
var clone = new object[arr.Length];
for (var i = 0; i < arr.Length; ++i)
{
clone[i] = arr[i];
}
return clone;
}
public int[] Clone(int[] arr)
{
var clone = new int[arr.Length];
for (var i = 0; i < arr.Length; ++i)
{
clone[i] = arr[i];
}
return clone;
}
public void PrintContexts(object[] contexts)
{
foreach (object[] context in contexts)
{
PrintContext(context);
}
}
public void PrintContext(object[] context)
{
var globalOrders = ReadGlobalOrders(context);
var chi = ReadChiList(context);
var chiCount = ReadChiCount(context);
var pon = ReadPonList(context);
var ponCount = ReadPonCount(context);
var str = "";
for (var i = 0; i < chiCount; ++i)
{
var globalOrder = chi[i];
var cardNumber = globalOrder % 9 + 1;
var type = GobalOrderToType(globalOrder);
str += $"({type + (cardNumber)}, {type + (cardNumber + 1)}, {type + (cardNumber + 2)})";
}
for (var i = 0; i < ponCount; ++i)
{
var index = pon[i];
var cardNumber = index % 9 + 1;
var type = GobalOrderToType(index);
str += $"({type + (cardNumber)}, {type + (cardNumber)}, {type + (cardNumber)})";
}
str += " ";
for (var i = 0; i < globalOrders.Length; ++i)
{
for (var k = 0; k < globalOrders[i]; ++k)
{
var index = i;
var cardNumber = index % 9 + 1;
var type = GobalOrderToType(index);
str += $"({type + (cardNumber)})";
}
}
if (!string.IsNullOrEmpty(str))
{
Debug.Log(str);
}
}
public int[] Fit(int[] arr, int count)
{
var newArr = new int[count];
for (var i = 0; i < count; ++i)
{
newArr[i] = arr[i];
}
return newArr;
}
public object[] FitObject(object[] arr, int count)
{
var newArr = new object[count];
for (var i = 0; i < count; ++i)
{
newArr[i] = arr[i];
}
return newArr;
}
public bool HasSameGlobalOrders(object[] ctxs, object[] ctx2)
{
var globalOrders2 = ReadGlobalOrders(ctx2);
foreach (object[] ctx1 in ctxs)
{
var globalOrders1 = ReadGlobalOrders(ctx1);
if (HasSameValue(globalOrders1, globalOrders1.Length, globalOrders2, globalOrders2.Length))
{
return true;
}
}
return false;
}
public bool HasSameChiPons(object[] ctxs, object[] ctx2)
{
foreach (object[] ctx1 in ctxs)
{
var chiIsSame = HasSameValue(ReadChiList(ctx1), ReadChiCount(ctx1), ReadChiList(ctx2), ReadChiCount(ctx2));
var ponIsSame = HasSameValue(ReadPonList(ctx1), ReadPonCount(ctx1), ReadPonList(ctx2), ReadPonCount(ctx2));
if (chiIsSame && ponIsSame)
{
return true;
}
}
return false;
}
bool HasSameValue(int[] arr1, int arr1Count, int[] arr2, int arr2Count)
{
if (arr1Count != arr2Count) { return false; }
for (var i = 0; i < arr1Count; ++i)
{
if (arr1[i] != arr2[i])
{
return false;
}
}
return true;
}
void Sort(int[] arr, int count)
{
for (var i = count; i >= 0; i--)
{
for (var j = 1; j <= i; j++)
{
if (arr[j - 1] > arr[j])
{
var temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
public string GobalOrderToType(int globalORder)
{
if (MAN_START_INDEX <= globalORder && globalORder <= MAN_END_INDEX) return "만";
if (PIN_START_INDEX <= globalORder && globalORder <= PIN_END_INDEX) return "통";
if (SOU_START_INDEX <= globalORder && globalORder <= SOU_END_INDEX) return "삭";
if (globalORder == 27) return "동";
if (globalORder == 28) return "서";
if (globalORder == 29) return "남";
if (globalORder == 30) return "북";
if (globalORder == 31) return "백";
if (globalORder == 32) return "발";
if (globalORder == 33) return "중";
return "";
}
public int TEST__GetChiCount(object[] contexts, int ctxIndex, int chiIndex)
{
var count = 0;
var context = (object[])contexts[ctxIndex];
var chi = ReadChiList(context);
for (var i = 0; i < ReadChiCount(context); ++i)
{
if (chi[i] == chiIndex)
{
count++;
}
}
return count;
}
public int TEST__GetPonCount(object[] contexts, int ctxIndex, int ponGlobalOrder)
{
var count = 0;
var context = (object[])contexts[ctxIndex];
var pon = ReadPonList(context);
for (var i = 0; i < ReadPonCount(context); ++i)
{
if (pon[i] == ponGlobalOrder)
{
count++;
}
}
return count;
}
} |
// # SPDX-License-Identifier: MIT
// # Copyright 2021
// # Sebastian Fischer sebfischer@gmx.net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Datatent2.Core.Scripting.Validator
{
internal class BeforeInsertValidator
{
//private readonly string _tableName;
//private readonly ScriptingProvider _provider;
//private readonly IScriptingEngine _scriptingEngine;
//public BeforeInsertValidator(string tableName, string script, ScriptingProvider provider)
//{
// _tableName = tableName;
// _provider = provider;
// _scriptingEngine = provider switch
// {
// ScriptingProvider.Lua => new LuaScriptingEngine(script),
// ScriptingProvider.Javascript => new JavascriptScriptingEngine(script),
// _ => throw new ArgumentOutOfRangeException(nameof(provider), provider, null)
// };
//}
//public bool IsValid(object obj)
//{
// return _scriptingEngine.Execute<bool>(obj);
//}
//public bool IsTableSupported(string tableName)
//{
// return string.Equals(_tableName, tableName, StringComparison.Ordinal);
//}
}
}
|
using Newtonsoft.Json;
namespace Backpack.Net
{
/// <summary>
/// Represents a <see cref="BackpackUser"/>'s voting and suggestion stats.
/// </summary>
public sealed class Voting
{
internal Voting()
{ }
/// <summary>
/// This user's site voting reputation.
/// </summary>
[JsonProperty("reputation")]
public int Reputation { get; private set; }
/// <summary>
/// This user's total <see cref="Net.Votes"/>.
/// </summary>
[JsonProperty("votes")]
public Votes Votes { get; private set; } = new Votes();
/// <summary>
/// This user's <see cref="PriceSuggestions"/> stats.
/// </summary>
[JsonProperty("suggestions")]
public PriceSuggestions Suggestions { get; private set; } = new PriceSuggestions();
}
} |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Murtain;
using Murtain.Extensions.Gemini.Builder;
namespace Microsoft.Extensions.DependencyInjection
{
public static class IServiceCollectionExtensions
{
public static IGeminiApplicationServiceCollection AddGemini(this IServiceCollection services)
{
services.AddSingleton<IGeminiApplicationServiceCollection, GeminiApplicationServiceCollection>();
return new GeminiApplicationServiceCollection(services);
}
}
}
|
using System;
using Intersect.Client.Framework.File_Management;
using Intersect.Client.Framework.Graphics;
using Intersect.Client.Framework.Gwen.Control;
using Intersect.Client.Framework.Gwen.Input;
using Newtonsoft.Json.Linq;
namespace Intersect.Client.Framework.Gwen.ControlInternal
{
/// <summary>
/// Base for controls that can be dragged by mouse.
/// </summary>
public class Dragger : Base
{
public enum ControlState
{
Normal = 0,
Hovered,
Clicked,
Disabled,
}
private GameTexture mClickedImage;
private string mClickedImageFilename;
private GameTexture mDisabledImage;
private string mDisabledImageFilename;
protected bool mHeld;
protected Point mHoldPos;
private GameTexture mHoverImage;
private string mHoverImageFilename;
//Sound Effects
private string mHoverSound;
private string mMouseDownSound;
private string mMouseUpSound;
private GameTexture mNormalImage;
private string mNormalImageFilename;
protected Base mTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Dragger" /> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public Dragger( Base parent, string name = "" ) : base( parent, name )
{
MouseInputEnabled = true;
mHeld = false;
}
internal Base Target
{
get => mTarget;
set => mTarget = value;
}
/// <summary>
/// Indicates if the control is being dragged.
/// </summary>
public bool IsHeld => mHeld;
/// <summary>
/// Event invoked when the control position has been changed.
/// </summary>
public event GwenEventHandler<EventArgs> Dragged;
/// <summary>
/// Handler invoked on mouse click (left) event.
/// </summary>
/// <param name="x">X coordinate.</param>
/// <param name="y">Y coordinate.</param>
/// <param name="down">If set to <c>true</c> mouse button is down.</param>
protected override void OnMouseClickedLeft( int x, int y, bool down, bool automated = false )
{
if( null == mTarget )
{
return;
}
if( down )
{
mHeld = true;
//Play Mouse Down Sound
if( !automated )
{
base.PlaySound( mMouseDownSound );
}
mHoldPos = mTarget.CanvasPosToLocal( new Point( x, y ) );
InputHandler.MouseFocus = this;
}
else
{
mHeld = false;
//Play Mouse Up Sound
base.PlaySound( mMouseUpSound );
InputHandler.MouseFocus = null;
}
}
/// <summary>
/// Handler invoked on mouse moved event.
/// </summary>
/// <param name="x">X coordinate.</param>
/// <param name="y">Y coordinate.</param>
/// <param name="dx">X change.</param>
/// <param name="dy">Y change.</param>
protected override void OnMouseMoved( int x, int y, int dx, int dy )
{
if( null == mTarget )
{
return;
}
if( !mHeld )
{
return;
}
var p = new Point( x - mHoldPos.X, y - mHoldPos.Y );
// Translate to parent
if( mTarget.Parent != null )
{
p = mTarget.Parent.CanvasPosToLocal( p );
}
//m_Target->SetPosition( p.x, p.y );
mTarget.MoveTo( p.X, p.Y );
if( Dragged != null )
{
Dragged.Invoke( this, EventArgs.Empty );
}
}
/// <summary>
/// Renders the control using specified skin.
/// </summary>
/// <param name="skin">Skin to use.</param>
protected override void Render( Skin.Base skin )
{
}
public override JObject GetJson()
{
var obj = base.GetJson();
obj.Add( "NormalImage", GetImageFilename( ControlState.Normal ) );
obj.Add( "HoveredImage", GetImageFilename( ControlState.Hovered ) );
obj.Add( "ClickedImage", GetImageFilename( ControlState.Clicked ) );
obj.Add( "DisabledImage", GetImageFilename( ControlState.Disabled ) );
obj.Add( "HoverSound", mHoverSound );
obj.Add( "MouseUpSound", mMouseUpSound );
obj.Add( "MouseDownSound", mMouseDownSound );
return base.FixJson( obj );
}
public override void LoadJson( JToken obj )
{
base.LoadJson( obj );
if( obj["NormalImage"] != null )
{
SetImage(
GameContentManager.Current.GetTexture(
GameContentManager.TextureType.Gui, (string)obj["NormalImage"]
), (string)obj["NormalImage"], ControlState.Normal
);
}
if( obj["HoveredImage"] != null )
{
SetImage(
GameContentManager.Current.GetTexture(
GameContentManager.TextureType.Gui, (string)obj["HoveredImage"]
), (string)obj["HoveredImage"], ControlState.Hovered
);
}
if( obj["ClickedImage"] != null )
{
SetImage(
GameContentManager.Current.GetTexture(
GameContentManager.TextureType.Gui, (string)obj["ClickedImage"]
), (string)obj["ClickedImage"], ControlState.Clicked
);
}
if( obj["DisabledImage"] != null )
{
SetImage(
GameContentManager.Current.GetTexture(
GameContentManager.TextureType.Gui, (string)obj["DisabledImage"]
), (string)obj["DisabledImage"], ControlState.Disabled
);
}
if( obj["HoverSound"] != null )
{
mHoverSound = (string)obj["HoverSound"];
}
if( obj["MouseUpSound"] != null )
{
mMouseUpSound = (string)obj["MouseUpSound"];
}
if( obj["MouseDownSound"] != null )
{
mMouseDownSound = (string)obj["MouseDownSound"];
}
}
public string GetMouseUpSound()
{
return mMouseUpSound;
}
/// <summary>
/// Sets the button's image.
/// </summary>
/// <param name="textureName">Texture name. Null to remove.</param>
public virtual void SetImage( GameTexture texture, string fileName, ControlState state )
{
switch( state )
{
case ControlState.Normal:
mNormalImageFilename = fileName;
mNormalImage = texture;
break;
case ControlState.Hovered:
mHoverImageFilename = fileName;
mHoverImage = texture;
break;
case ControlState.Clicked:
mClickedImageFilename = fileName;
mClickedImage = texture;
break;
case ControlState.Disabled:
mDisabledImageFilename = fileName;
mDisabledImage = texture;
break;
default:
throw new ArgumentOutOfRangeException( nameof( state ), state, null );
}
}
public virtual GameTexture GetImage( ControlState state )
{
switch( state )
{
case ControlState.Normal:
return mNormalImage;
case ControlState.Hovered:
return mHoverImage;
case ControlState.Clicked:
return mClickedImage;
case ControlState.Disabled:
return mDisabledImage;
default:
return null;
}
}
public virtual string GetImageFilename( ControlState state )
{
switch( state )
{
case ControlState.Normal:
return mNormalImageFilename;
case ControlState.Hovered:
return mHoverImageFilename;
case ControlState.Clicked:
return mClickedImageFilename;
case ControlState.Disabled:
return mDisabledImageFilename;
default:
return null;
}
}
protected override void OnMouseEntered()
{
base.OnMouseEntered();
//Play Mouse Entered Sound
if( ShouldDrawHover )
{
base.PlaySound( mHoverSound );
}
}
public void ClearSounds()
{
mHoverSound = "";
mMouseDownSound = "";
mMouseUpSound = "";
}
}
}
|
namespace BinarySerializer.Nintendo.NDS
{
public class DS3D_CommandBlock : BinarySerializable
{
public DS3D_Command[] Commands { get; set; }
public override void SerializeImpl(SerializerObject s)
{
Commands = s.SerializeObjectArray<DS3D_Command>(Commands, 4, name: nameof(Commands));
foreach (DS3D_Command cmd in Commands)
cmd.SerializeData(s);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using POYA.Models;
using POYA.Areas.FunAdmin.Models;
using POYA.Areas.FunFiles.Models;
using POYA.Areas.WeEduHub.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace POYA.Data
{
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<POYA.Models.X_doveUserInfo> X_DoveUserInfos { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.FContentCheck> FContentCheck { get; set; }
public DbSet<POYA.Areas.FunFiles.Models.FunDir> FunDir { get; set; }
public DbSet<POYA.Areas.FunFiles.Models.FunFileByte> FunFileByte { get; set; }
public DbSet<POYA.Areas.FunFiles.Models.FunYourFile> FunYourFile { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.WeArticle> WeArticle { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.WeArticleSet> WeArticleSet { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.WeArticleFile> WeArticleFile { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.FunComment> FunComment { get; set; }
public DbSet<POYA.Areas.WeEduHub.Models.WeArticleSign> WeArticleSign { get; set; }
public DbSet<POYA.Areas.LarryUserManagement.Models.LarryUser> LarryUsers { get; set; }
public DbSet<POYA.Areas.LarryUserManagement.Models.LarryRole> LarryRoles { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Chapter_03_QuickStart.DataManager;
using Chapter_03_QuickStart.Models;
using System.Diagnostics;
using System.Collections.Generic;
namespace Chapter_03_QuickStart.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IMusicManager _musicManager;
private readonly InstrumentalMusicManager _insMusicManager;
public HomeController(ILogger<HomeController> logger,
IMusicManager musicManager,
InstrumentalMusicManager insMusicManager)
{
_logger = logger;
_musicManager = musicManager;
_insMusicManager = insMusicManager;
}
////Dealing With Multiple Service Implementations Example
//private readonly IEnumerable<IMusicManager> _musicManagers;
//public HomeController(IEnumerable<IMusicManager> musicManagers)
//{
// _musicManagers = musicManagers;
//}
public IActionResult Index()
{
//DEPENDENCY LIFETIME EXAMPLE
var musicManagerReqId = _musicManager.RequestId;
var insMusicManagerReqId = _insMusicManager.RequestId;
//CONSTRUCTOR INJECTION EXAMPLE
//var songs = _musicManager.GetAllMusic();
//METHOD INJECTION EXAMPLE
//var songs = _musicManager.GetAllMusicThenNotify(new Notifier());
//PROPERTY INJECTION EXAMPLE
_musicManager.Notify = new Notifier();
var songs = _musicManager.GetAllMusicThenNotify();
return View(songs);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using OrienteeringToolWPF.DAO;
using OrienteeringToolWPF.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace OrienteeringToolWPF.Utils
{
public static class ClassificationUtils
{
// Performs corectness check on all competitors
private static void CheckCorrectness(List<Relay> RelayList, DependencyObject obj = null)
{
foreach (var relay in RelayList)
{
foreach (var competitor in relay.Competitors)
{
var db = DatabaseUtils.GetDatabase();
var punchesList = (List<Punch>)competitor.Punches;
var routeStepsList = RouteStepsHelper.RouteStepsWhereChip((long)competitor.Chip);
try
{
Punch.CheckCorrectnessSorted(ref punchesList, routeStepsList);
}
catch (Exception e)
{
MessageUtils.ShowException(obj, "Nie wszyscy zawodnicy mają wyniki", e);
}
competitor.Punches = punchesList;
}
}
}
// Performs general classification
public static void ClassifyAll(List<Relay> RelayList)
{
ClassifyCompetitors(RelayList);
ClassifyRelays(RelayList);
}
// Classifies competitors
private static void ClassifyCompetitors(List<Relay> RelayList)
{
CheckCorrectness(RelayList);
foreach (var relay in RelayList)
{
((List<Competitor>)relay.Competitors).Sort();
}
}
// Classifies relays
private static void ClassifyRelays(List<Relay> RelayList)
{
RelayList.Sort();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeInfo
{
class PartialClass2
{
}
public partial class Employee
{
public void Emphoyees() { }
public partial void InitializeEmployee()
{
string str = "Employee Details";
Console.WriteLine(str);
}
}
public partial class EmployeeDetails
{
public void PrintEmployeeInfo()
{
Console.WriteLine("Employee ID:" + empID);
Console.WriteLine("Employee Name:" + empName);
}
}
} |
using UnityEngine;
using System.Collections;
public class Variador : MonoBehaviour {
///public GameObject variador;
public int Status;// Essa variavel eh atualizada pela classe botao
public float Variador_Valor=0;
//void Start (){
// variador.GetComponent<Renderer> ().transform.Rotate (0, 0, -7);
//}
void Update () {
if (Status == 1&&Variador_Valor<120) {// Sentido positivo
gameObject.GetComponent<Renderer> ().transform.Rotate (0, 0, 1.83f);
Variador_Valor = Variador_Valor + 1;
} else if (Status == -1&&Variador_Valor>0) {// sentido negativo
gameObject.GetComponent<Renderer> ().transform.Rotate (0, 0, -1.83f);
Variador_Valor = Variador_Valor - 1;
} else {// Caso parado
gameObject.GetComponent<Renderer> ().transform.Rotate (0, 0, 0);
}
}
}
|
/* csvorbis
* Copyright (C) 2000 ymnk, JCraft,Inc.
*
* Written by: 2000 ymnk<ymnk@jcraft.com>
* Ported to C# from JOrbis by: Mark Crichton <crichton@gimp.org>
*
* Thanks go to the JOrbis team, for licencing the code under the
* LGPL, making my job a lot easier.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
* This program 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
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
using System;
using System.Text;
using csogg;
namespace csvorbis
{
public class Comment
{
// unlimited user comment fields. libvorbis writes 'libvorbis'
// whatever vendor is set to in encode
public byte[][] user_comments;
public int comments;
public byte[] vendor;
public void init()
{
user_comments = null;
comments = 0;
vendor = null;
}
internal int unpack(csBuffer opb)
{
int vendorlen = opb.read(32);
vendor = new byte[vendorlen + 1];
opb.read(vendor, vendorlen);
comments = opb.read(32);
user_comments = new byte[comments + 1][];
for(int i = 0; i < comments; i++) {
int len = opb.read(32);
user_comments[i] = new byte[len+1];
opb.read(user_comments[i], len);
}
opb.read(1);
return(0);
}
internal void clear()
{
user_comments = null;
vendor = null;
}
public string getVendor()
{
return Encoding.UTF8.GetString(vendor);
}
public string getComment(int i)
{
Encoding AE = Encoding.UTF8;
if(comments <= i)return null;
return Encoding.UTF8.GetString(user_comments[i]);
}
public string toString()
{
String sum = "Vendor: " + getVendor();
for(int i = 0; i < comments; i++)
sum = sum + "\nComment: " + getComment(i);
sum = sum + "\n";
return sum;
}
}
}
|
using BetterMe.Models;
using BetterMe.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace BetterMe.Controllers
{
public class RulesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
//// PUT api/<controller>/5
//public void Put(int id, [FromBody]string value)
//{
//}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
public void Put(int id, [FromBody]Exam e)
{
try
{
Exam ex = new Exam();
ex.UpdateGrade(id, e);
}
catch
{
}
}
[HttpPost]
[Route("api/Rules/RandomAddPoints")]
public HttpResponseMessage RandomAddPoints(RandomAddPoints[] RandomAddPointsArr)
{
try
{
RandomAddPoints RAP = new RandomAddPoints();
RAP.InsertRandomPoints(RandomAddPointsArr);
return Request.CreateResponse(HttpStatusCode.OK, RandomAddPointsArr);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשמירת החוק");
}
}
[HttpPost]
[Route("api/Rules/subPoints")]
public HttpResponseMessage subPoints(Remark[] subPointsArr)
{
try
{
Remark r = new Remark();
r.InsertRemark(subPointsArr);
return Request.CreateResponse(HttpStatusCode.OK, subPointsArr);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשמירת החוק");
}
}
[HttpPost]
[Route("api/Rules/InsertPrizesWithout")]
public HttpResponseMessage InsertPrizesWithout(PrizeWithout[] prizewithout)
{
try
{
PrizeWithout pwo = new PrizeWithout();
pwo.InsertPrizesWithout(prizewithout);
return Request.CreateResponse(HttpStatusCode.OK, prizewithout);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשמירת החוק");
}
}
[HttpPost]
[Route("api/Rules/InsertPrizesWith")]
public HttpResponseMessage InsertPrizesWith(PrizeWith[] prizewith)
{
try
{
PrizeWith pw = new PrizeWith();
pw.InsertPrizesWith(prizewith);
return Request.CreateResponse(HttpStatusCode.OK, prizewith);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשמירת החוק");
}
}
[HttpDelete]
[Route("api/Rules/DeleteRandomAddPoints")]
public HttpResponseMessage DeleteRandomAddPoints(RandomAddPoints RAP)
{
try
{
RandomAddPoints rap = new RandomAddPoints();
rap.DeleteRAP(RAP);
return Request.CreateResponse(HttpStatusCode.OK, RAP);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה במחיקה");
}
}
[HttpDelete]
[Route("api/Rules/DeleteRemark")]
public HttpResponseMessage DeleteRemark(Remark R)
{
try
{
Remark r = new Remark();
r.DeleteR(R);
return Request.CreateResponse(HttpStatusCode.OK, R);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה במחיקה");
}
}
[HttpDelete]
[Route("api/Rules/DeletePrizeWith")]
public HttpResponseMessage DeletePrizeWith(PrizeWith PW)
{
try
{
PrizeWith pw = new PrizeWith();
pw.DeletePW(PW);
return Request.CreateResponse(HttpStatusCode.OK, PW);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה במחיקה");
}
}
[HttpDelete]
[Route("api/Rules/DeletePrizeWithOut")]
public HttpResponseMessage DeletePrizeWithOut(PrizeWithout PWO)
{
try
{
PrizeWithout pwo = new PrizeWithout();
pwo.DeletePWO(PWO);
return Request.CreateResponse(HttpStatusCode.OK, PWO);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה במחיקה");
}
}
[HttpPost]
[Route("api/Rules/SetRemark")]
public HttpResponseMessage SetRemark(StudentRemark[] SetRemarkArr)
{
try
{
StudentRemark sr = new StudentRemark();
sr.SetRemark(SetRemarkArr);
return Request.CreateResponse(HttpStatusCode.OK, sr);
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "!שגיאה בשמירת הערה");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SecretSantaProject.Models;
using Medallion;
namespace SecretSantaProject.Utils
{
public class SecretSantaMatchMaker : IMatchMaker<Contact>
{
private Random randomizer;
private IValidator<IEnumerable<Tuple<Contact, Contact>>> validator;
public SecretSantaMatchMaker(IValidator<IEnumerable<Tuple<Contact, Contact>>> validator)
{
randomizer = new Random();
this.validator = validator;
}
public IEnumerable<Tuple<Contact, Contact>> MatchMake(IEnumerable<Contact> contacts, int retry=20)
{
List<Contact> shuffledContacts = contacts.Shuffled(randomizer).Shuffled(randomizer).ToList();
List<Tuple<Contact, Contact>> ret = new List<Tuple<Contact, Contact>>();
for(int i = 0; i < shuffledContacts.Count - 1; i++)
{
ret.Add(new Tuple<Contact, Contact> (shuffledContacts[i], shuffledContacts[i + 1]));
}
ret.Add(new Tuple<Contact, Contact>(shuffledContacts[shuffledContacts.Count-1], shuffledContacts[0]));
if (validator.Validate(ret))
{
return ret;
}
else if(retry <= 0)
{
throw new Exception("Unable to match make.");
}
Console.WriteLine("Validation failed. Retrying...");
return MatchMake(shuffledContacts, retry - 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using eRestoran.Data;
using eRestoran.Models;
using Microsoft.AspNetCore.Authorization;
using X.PagedList;
using Microsoft.AspNetCore.Identity;
namespace eRestoran.Areas.Uposlenik.Controllers
{
[Area("Uposlenik")]
[Authorize(Roles = "Uposlenik")]
public class NarudzbeController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<OnlineGost> _userManager;
public NarudzbeController(ApplicationDbContext context, UserManager<OnlineGost> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: Uposlenik/Narudzbe
public async Task<IActionResult> Index(int? page)
{
var applicationDbContext = _context.OnlineNarudzba;
var list = await applicationDbContext.ToListAsync();
return View(list.ToPagedList(page ?? 1, 10));
}
// GET: Uposlenik/Narudzbe/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var onlineNarudzba = await _context.OnlineNarudzba
.Include(o => o.DostavaNalog.Uposlenik)
.Include(o => o.DostavaNalog.VoziloZaDostavu)
.FirstOrDefaultAsync(m => m.Id == id);
if (onlineNarudzba == null)
{
return NotFound();
}
return View(onlineNarudzba);
}
// GET: Uposlenik/Narudzbe/Racun/5
public async Task<IActionResult> Racun(int? id, bool printaj = false)
{
if (id == null)
{
return NotFound();
}
var narudzba = await _context.OnlineNarudzba
.Include(o => o.Restoran)
.Include(o => o.IzdavateljRačuna)
.Include(o => o.DostavaNalog.Uposlenik)
.Include(o => o.DostavaNalog.VoziloZaDostavu)
.FirstOrDefaultAsync(m => m.Id == id);
IEnumerable<NarudzbaStavka> stavke = await _context.NarudzbaStavka
.Where(x=>x.OnlineNarudzbaID == id)
.Include(o => o.DnevnaPonuda)
.Include(o => o.Meni)
.ToListAsync();
ViewBag.Stavke = stavke;
ViewBag.CijenaStavki = stavke.Sum(x => x.Meni.Cijena * int.Parse(x.Kolicina));
ViewBag.Popust = ViewBag.CijenaStavki - narudzba.Cijena;
ViewBag.PrintajRacun = printaj;
if (narudzba == null)
{
return NotFound();
}
return View(narudzba);
}
public async Task<IActionResult> IzdajRacun(int? id)
{
if (id == null)
{
return NotFound();
}
var narudzba = await _context.OnlineNarudzba
.FirstOrDefaultAsync(m => m.Id == id);
narudzba.IzdavateljRačuna = await _userManager.GetUserAsync(User);
await _context.SaveChangesAsync();
return RedirectToAction("Racun", new { Id = id, printaj = true });
}
}
}
|
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 Ejemplo1
{
public partial class FRMEJEMPLO1 : Form
{
public FRMEJEMPLO1()
{
InitializeComponent();
}
private void CMDAREA_Click(object sender, EventArgs e)
{
//Programa que calcula el area de un triangulo
//Silva Reyes Luis Adrian 19210549
//Ejemplo 1
//Declaracion de variables
float Base, Altura;
float Area;
//Asignacion de valores
Base = System.Single.Parse(TXT_BASE.Text);
Altura = System.Single.Parse(TXT_ALTURA.Text);
//Calculo de area
Area =Base * Altura /2;
//Salida del area
TXT_AREA.Text = Area.ToString();
}
private void CMDSALIDA_Click(object sender, EventArgs e) =>
Close();
private void CMDOTRO_Click(object sender, EventArgs e)
{
TXT_BASE.Clear();
TXT_ALTURA.Clear();
TXT_AREA.Clear();
TXT_BASE.Focus();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using Newtonsoft.Json;
namespace Plcway.Communication
{
/// <summary>
/// 超时操作的类。
/// </summary>
/// <remarks>
/// 本类自动启动一个静态线程来处理
/// </remarks>
public class HslTimeOut
{
private static long hslTimeoutId = 0L;
private static readonly List<HslTimeOut> WaitHandleTimeOut = new(128);
private static readonly object listLock = new();
private static Thread threadCheckTimeOut;
private static long threadUniqueId = 0L;
private static DateTime threadActiveTime;
private static int activeDisableCount = 0;
/// <summary>
/// 当前超时对象的唯一ID信息,没实例化一个对象,id信息就会自增1
/// </summary>
public long UniqueId { get; private set; }
/// <summary>
/// 操作的开始时间
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// 操作是否成功,当操作完成的时候,需要设置为<c>True</c>,超时检测自动结束。如果一直为<c>False</c>,超时检测到超时,设置<see cref="IsTimeout" />为<c>True</c>
/// </summary>
public bool IsSuccessful { get; set; }
/// <summary>
/// 延时的时间,单位毫秒。
/// </summary>
public int DelayTime { get; set; }
/// <summary>
/// 连接超时用的Socket,本超时对象主要针对套接字的连接,接收数据的超时检测,也可以设置为空,用作其他用途的超时检测。
/// </summary>
[JsonIgnore]
public Socket WorkSocket { get; set; }
/// <summary>
/// 是否发生了超时的操作,当调用方因为异常结束的时候,需要对<see cref="IsTimeout" />进行判断,是否因为发送了超时导致的异常。
/// </summary>
public bool IsTimeout { get; set; }
/// <summary>
/// 获取当前检查超时对象的个数
/// </summary>
public static int TimeOutCheckCount => WaitHandleTimeOut.Count;
/// <summary>
/// 实例化一个默认的对象
/// </summary>
public HslTimeOut()
{
UniqueId = Interlocked.Increment(ref hslTimeoutId);
StartTime = DateTime.Now;
IsSuccessful = false;
IsTimeout = false;
}
static HslTimeOut()
{
CreateTimeoutCheckThread();
}
/// <summary>
/// 获取到目前为止所花费的时间。
/// </summary>
/// <returns>时间信息</returns>
public TimeSpan GetConsumeTime()
{
return DateTime.Now - StartTime;
}
/// <inheritdoc />
public override string ToString()
{
return $"TimeOut[{DelayTime}]";
}
/// <summary>
/// 新增一个超时检测的对象,当操作完成的时候,需要自行标记<see cref="HslTimeOut" />对象的<see cref="IsSuccessful" />为<c>True</c>
/// </summary>
/// <param name="timeOut">超时对象</param>
public static void HandleTimeOutCheck(HslTimeOut timeOut)
{
lock (listLock)
{
if ((DateTime.Now - threadActiveTime).TotalSeconds > 60.0)
{
threadActiveTime = DateTime.Now;
if (Interlocked.Increment(ref activeDisableCount) >= 2)
{
CreateTimeoutCheckThread();
}
}
WaitHandleTimeOut.Add(timeOut);
}
}
/// <summary>
/// 获取当前的所有的等待超时检查对象列表,请勿手动更改对象的属性值
/// </summary>
/// <returns>HslTimeOut数组,请勿手动更改对象的属性值</returns>
public static HslTimeOut[] GetHslTimeOutsSnapShoot()
{
lock (listLock)
{
return WaitHandleTimeOut.ToArray();
}
}
/// <summary>
/// 新增一个超时检测的对象,需要指定socket,超时时间,返回<see cref="HslTimeOut" />对象,用作标记完成信息
/// </summary>
/// <param name="socket">网络套接字</param>
/// <param name="timeout">超时时间,单位为毫秒</param>
public static HslTimeOut HandleTimeOutCheck(Socket socket, int timeout)
{
var hslTimeOut = new HslTimeOut
{
DelayTime = timeout,
IsSuccessful = false,
StartTime = DateTime.Now,
WorkSocket = socket
};
if (timeout > 0)
{
HandleTimeOutCheck(hslTimeOut);
}
return hslTimeOut;
}
private static void CreateTimeoutCheckThread()
{
threadActiveTime = DateTime.Now;
threadCheckTimeOut = new Thread(CheckTimeOut)
{
IsBackground = true,
Priority = ThreadPriority.AboveNormal,
};
threadCheckTimeOut.Start(Interlocked.Increment(ref threadUniqueId));
}
/// <summary>
/// 检测超时的核心方法,由一个单独的线程运行,线程的优先级很高,当前其他所有的超时信息都可以放到这里处理
/// </summary>
/// <param name="obj">需要传入线程的id信息</param>
private static void CheckTimeOut(object obj)
{
long num = (long)obj;
while (true)
{
Thread.Sleep(100);
if (num != threadUniqueId)
{
break;
}
threadActiveTime = DateTime.Now;
activeDisableCount = 0;
lock (listLock)
{
for (int num2 = WaitHandleTimeOut.Count - 1; num2 >= 0; num2--)
{
HslTimeOut hslTimeOut = WaitHandleTimeOut[num2];
if (hslTimeOut.IsSuccessful)
{
WaitHandleTimeOut.RemoveAt(num2);
}
else if ((DateTime.Now - hslTimeOut.StartTime).TotalMilliseconds > hslTimeOut.DelayTime)
{
if (!hslTimeOut.IsSuccessful)
{
hslTimeOut.WorkSocket?.Close();
hslTimeOut.IsTimeout = true;
}
WaitHandleTimeOut.RemoveAt(num2);
}
}
}
}
}
}
}
|
using System;
using Spect.Net.Assembler.Generated;
namespace Spect.Net.Assembler.SyntaxTree.Expressions
{
/// <summary>
/// This class represents an UNARY logical NOT operation
/// </summary>
public sealed class UnaryLogicalNotNode : UnaryExpressionNode
{
/// <summary>
/// Retrieves the value of the expression
/// </summary>
/// <param name="evalContext">Evaluation context</param>
/// <returns>Evaluated expression value</returns>
public override ExpressionValue Evaluate(IEvaluationContext evalContext)
{
var oper = Operand.Evaluate(evalContext);
switch (oper.Type)
{
case ExpressionValueType.Bool:
case ExpressionValueType.Integer:
return new ExpressionValue(oper.AsLong() == 0);
case ExpressionValueType.Real:
case ExpressionValueType.String:
EvaluationError = "Unary logical not operation can be applied only on integral types";
return ExpressionValue.Error;
default:
throw new ArgumentOutOfRangeException();
}
}
public UnaryLogicalNotNode(Z80AsmParser.LogicalNotExprContext context, Z80AsmVisitor visitor)
: base(context.expr(), visitor)
{
}
}
} |
using Orleans.Serialization.Activators;
namespace Orleans.Serialization.Serializers
{
/// <summary>
/// Provides activators.
/// </summary>
public interface IActivatorProvider
{
/// <summary>
/// Gets an activator for the specified type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
/// <returns>The activator.</returns>
IActivator<T> GetActivator<T>();
}
} |
using MagiCore.Model;
using System.ComponentModel.DataAnnotations;
namespace CourseShop.Services.Catalog.Model.Requests;
public class CategoryUpdateRequest : IRequest
{
/// <summary>Must match the id in the route.</summary>
/// <example>61e403e7a459734dc052afac</example>
[Required]
public string Id { get; set; } = default!;
/// <summary>Must be unique.</summary>
/// <example>Python</example>
[Required]
public string? Name { get; set; }
} |
using System.Linq;
using System.Runtime.CompilerServices;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Uno.Collections;
namespace Uno.UI.Tests.Foundation
{
[TestClass]
public class Given_StackVector
{
private struct MyStruct
{
internal int A;
}
[TestMethod]
public void EmptyStackVector()
{
var sut = new StackVector<MyStruct>(2);
sut.Count.Should().Be(0);
sut.Should().HaveCount(0);
sut.ToArray().Should().HaveCount(0);
sut.Memory.Length.Should().Be(0);
}
[TestMethod]
public void NonEmptyStackVector_Then_CountCheck()
{
var sut = new StackVector<MyStruct>(2, 2);
sut.Count.Should().Be(2);
sut.Should().HaveCount(2);
sut.ToArray().Should().HaveCount(2);
sut.Memory.Length.Should().Be(2);
}
[TestMethod]
public unsafe void ItemsInStackVector()
{
var sut = new StackVector<MyStruct>(2);
ref var item1 = ref sut.PushBack();
item1.A = 1;
sut.Count.Should().Be(1);
sut.Should().HaveCount(1);
ref var item2 = ref sut.PushBack();
item2.A = 2;
sut.Count.Should().Be(2);
sut.Should().HaveCount(2);
sut.Select(i => i.A)
.Should()
.BeEquivalentTo(new[] {1, 2});
var ptr1 = Unsafe.AsPointer(ref item1);
var ptr2 = Unsafe.AsPointer(ref item2);
foreach (ref var item in sut.Memory.Span)
{
// Ensure we're getting the same references
var ptr = Unsafe.AsPointer(ref item);
if (ptr != ptr1 && ptr != ptr2)
{
Assert.Fail("Lost reference");
}
}
}
}
}
|
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Threading.Tasks;
namespace Mahamudra.ParallelDots.CustomExtensions
{
public static class ApiClientExtensions
{
public static T Deserialize<T>(this string json, bool map = true)
{
try
{
JsonSerializerSettings jsonSettings;
if (map)
{
// Throws error if JSON does not exactly maps into class
jsonSettings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
};
return JsonConvert.DeserializeObject<T>(json, jsonSettings);
}
else
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
// if doesn't bind it might probably 'cause the ParallelDots service
// gave an error inside the 200 json
throw new Exception($"json: {json} ex:{ex.ToString()}");
}
}
public static async Task<string> ResolveRequest(this string serviceUri, ApiClientSettings
apiClientSettings)
{
var myServiceUri = new Uri(serviceUri).ToString(); //throws exception if not well formed
var client = new RestClient(myServiceUri);
var request = AddParameters(apiClientSettings);
IRestResponse response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return response.Content.ToString();
else
throw new Exception($"Error call {myServiceUri} with code {response.StatusCode}");
}
private static IRestRequest AddParameters(ApiClientSettings
apiClientSettings)
{
var request = new RestRequest(Method.POST)
.AddParameter("api_key", apiClientSettings.ApiKey)
.AddHeader("cache-control", "no-cache")
.AddHeader("source", "c#wrapper")
.AddParameter("lang_code", apiClientSettings.LangCode.Name);
if (apiClientSettings.Entity != null)
request.AddParameter("entity", apiClientSettings.Entity.ToString());
if (apiClientSettings.Text != null)
request.AddParameter("text", apiClientSettings.Text.ToString());
if (apiClientSettings.Category != null)
request.AddParameter("category", apiClientSettings.Category.ToString());
if (apiClientSettings.Url != null)
request.AddParameter("url", apiClientSettings.Url.ToString());
if (apiClientSettings.Compare != null)
{
request.AddParameter("text_1", apiClientSettings.Compare.Text1.ToString());
request.AddParameter("text_2", apiClientSettings.Compare.Text2.ToString());
}
if (apiClientSettings.FilePath != null)
{
request.AddParameter("file", apiClientSettings.FilePath);
request.AlwaysMultipartFormData = true;
}
return request;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BootNet.Commands
{
public class Messages
{
public static void ErrorMessage()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Command not found.");
Console.ForegroundColor = ConsoleColor.White;
}
public static void HelpMessage()
{
Console.WriteLine("=====Commands=====");
}
public static void NetMessage()
{
Console.WriteLine("Network connected. Your ip is: "); Network.WriteIp();
}
public static void Clear()
{
Console.Clear();
}
}
}
|
using System.Xml.Linq;
using Cassette.Manifests;
namespace Cassette.Stylesheets.Manifests
{
class StylesheetBundleManifestWriter<T> : BundleManifestWriter<T>
where T : StylesheetBundleManifest
{
protected StylesheetBundleManifestWriter(XContainer container)
: base(container)
{
}
protected override XElement CreateElement()
{
var element = base.CreateElement();
if (Manifest.Condition != null)
{
element.Add(new XAttribute("Condition", Manifest.Condition));
}
if (Manifest.Media != null)
{
element.Add(new XAttribute("Media", Manifest.Media));
}
return element;
}
}
class StylesheetBundleManifestWriter : StylesheetBundleManifestWriter<StylesheetBundleManifest>
{
public StylesheetBundleManifestWriter(XContainer container)
: base(container)
{
}
}
} |
using RakDotNet.IO;
namespace InfectedRose.Nif
{
public class NiSkinInstance : NiObject
{
public override void Serialize(BitWriter writer)
{
throw new System.NotImplementedException();
}
public override void Deserialize(BitReader reader)
{
throw new System.NotImplementedException();
}
}
} |
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ConceptualThinking.Model;
namespace ConceptualThinking.Student
{
public partial class Form12 : Form
{
private int _id = 0;
public Form12()
{
InitializeComponent();
_id = 4;
WriteToDataGrid(_id);
}
public Form12(int id)
{
InitializeComponent();
_id = id;
WriteToDataGrid(_id);
}
private void button5_Click(object sender, EventArgs e)
{
var nForm = new Form7();
nForm.FormClosed += (o, ep) => this.Close();
nForm.Show();
this.Hide();
}
private void WriteToDataGrid(int id)
{
dataGridView1.Rows.Clear();
var context = new ConceptualThinkingContext();
var data = context.Experiment2Result.Where(x => x.IdUser == id);
var row = 0;
var points = 0;
foreach (var result in data)
{
dataGridView1.Rows.Add();
var numberDisplay = (DataGridViewTextBoxCell)dataGridView1.Rows[row].Cells[0];
numberDisplay.Value = result.NumberDisplay;
var PairNotions = (DataGridViewTextBoxCell)dataGridView1.Rows[row].Cells[1];
PairNotions.Value = result.Experiment2Data.PairNotions;
var UserAnswer = (DataGridViewTextBoxCell)dataGridView1.Rows[row].Cells[2];
UserAnswer.Value = result.UserAnswer;
var CorrectAnswer = (DataGridViewTextBoxCell)dataGridView1.Rows[row].Cells[3];
CorrectAnswer.Value = result.Experiment2Data.CorrectAnswer;
row++;
points += result.NumberPoints;
}
if (dataGridView1.RowCount > 0)
{
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[0];
}
label3.Text = points.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
var context = new ConceptualThinkingContext();
var user = context.Users.FirstOrDefault(x => x.Id == _id);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "~/../";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
saveFileDialog1.FileName = user.Name + " Опыт №2";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
var result = new StringBuilder();
var name = "Имя испытуемого: " + user.Name + "\n";
var date = "Дата: " + user.Date + "\n";
var group = "Номер группы: " + user.Group + "\n";
result.Append(name);
result.Append(date);
result.Append(group);
result.Append(ExperimentResult());
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
var filename = saveFileDialog1.FileName;
System.IO.File.WriteAllText(filename, result.ToString());
}
}
private string ExperimentResult()
{
var context = new ConceptualThinkingContext();
var result = new StringBuilder();
var numberExperiment = "Опыт №2\n\n";
result.Append(numberExperiment);
var points = 0;
foreach (var item in context.Experiment2Result.Where(x => x.IdUser == _id))
{
result.Append("Предъявляемая пара понятий: ");
result.Append(item.Experiment2Data.PairNotions + "\n");
result.Append("Ответ испытуемого: " + item.UserAnswer + " Правильный ответ: " +
item.Experiment2Data.CorrectAnswer + "\n\n");
points += item.NumberPoints;
}
result.Append("Набранное количество балов: " + points);
return result.ToString();
}
}
}
|
using UnityEngine;
public class RotateBehaviour : MonoBehaviour
{
[SerializeField] private Vector3 RotationAmount;
void Update() => transform.Rotate(RotationAmount * Time.deltaTime);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.