text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmokeBehaviour : MonoBehaviour {
void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.tag == "Player" && collision.GetType() == typeof(CapsuleCollider2D)) {
collision.gameObject.GetComponent<PlayerBehavior>().ReceiveDamage();
}
}
}
|
using System.Collections.Generic;
using System;
namespace Enrollment.Common.Configuration.ExpressionDescriptors
{
public class IEnumerableSelectorLambdaOperatorDescriptor : OperatorDescriptorBase
{
public OperatorDescriptorBase Selector { get; set; }
public string SourceElementType { get; set; }
public string ParameterName { get; set; }
}
} |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace Mitheti.Core.Services
{
public class SavingService : ISavingService, IDisposable
{
public const string DelayConfigKey = "database:delay";
public const int DefaultDelay = 1;
public const int MinDelay = 1;
public const int MaxDelay = 2 *60; //? 2 hours;
public const int MillisecondsInMinute = 60 * 1000;
public const int StopWait = 500;
private readonly IDatabaseService _database;
private readonly IAddFilterService _filter;
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private readonly List<AppTimeModel> _records = new List<AppTimeModel>();
private readonly Task _savingTask;
public SavingService(IConfiguration config, IAddFilterService filter, IDatabaseService database)
{
_database = database;
_filter = filter;
var delayMinutes = config.GetValue(DelayConfigKey, DefaultDelay).LimitTo(MinDelay, MaxDelay);
_savingTask = SavingTask(_tokenSource.Token, delayMinutes * MillisecondsInMinute);
}
public void Save(string appName, int duration, DateTime timestamp)
{
if (!_filter.HavePassed(appName))
{
return;
}
lock (_records)
{
var sameRecord = _records.Find(
item => item.Equals(appName) && item.Equals(timestamp));
if (sameRecord == null)
{
_records.Add(new AppTimeModel { AppName = appName, Duration = duration, Time = timestamp});
}
else
{
sameRecord.Duration += duration;
}
}
}
private async Task SavingTask(CancellationToken stoppingToken, int delay)
{
while (!stoppingToken.IsCancellationRequested)
{
SaveToDatabase();
await Task.Delay(delay, stoppingToken);
}
}
private void SaveToDatabase()
{
lock (_records)
{
if (_records.Count == 0)
{
return;
}
_database.AddAsync(_records).Wait();
_records.Clear();
}
}
public void Dispose()
{
_tokenSource.Cancel();
_savingTask.WaitCancelled(StopWait);
_tokenSource.Dispose();
//? save leftovers;
SaveToDatabase();
}
}
} |
namespace GetLabourManager.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class TierOneContribution : DbMigration
{
public override void Up()
{
CreateStoredProcedure("Tier1ContributionProc",
@"
declare @charge as float
set @charge=0.135
SELECT gsh.DateIssued, p.CasualCode,(e.FirstName+' '+e.MiddleName+' '+e.LastName) as FullName,Isnull(c.SSN,'N/A') as SSN ,
sum(P.[BASIC]) as BasicAmount,(sum(p.[Basic]))*@charge as Tier1Amount
FROM EMPLOYEES E
INNER JOIN EmployeeContributions C on e.Id=c.StaffId
INNER join ProcessedSheetCasuals P on p.casualCode=e.code
inner join CostSheets sc on sc.Id=p.CostSheet
inner join GangSheetHeaders gsh on gsh.id=sc.RequestHeader
group by gsh.DateIssued, p.CasualCode,(e.FirstName+' '+e.MiddleName+' '+e.LastName) ,Isnull(c.SSN,'N/A')
");
}
public override void Down()
{
DropStoredProcedure("Tier1ContributionProc");
}
}
}
|
using UnityEngine;
public class EnemyLinearMvtFiveShot : Enemy {
protected override Vector3 MoveVect
{
get => m_Transform.right * m_TranslationSpeed * Time.fixedDeltaTime;
}
public override void ShootBullet()
{
Instantiate(m_BulletPrefab, m_BulletSpawnPoint.position, Quaternion.identity);
Instantiate(m_BulletPrefab, m_BulletSpawnPoint.position + new Vector3(0, 0.6f, 0), new Quaternion(0, 0, -0.05f, 1));
Instantiate(m_BulletPrefab, m_BulletSpawnPoint.position - new Vector3(0, 0.6f, 0), new Quaternion(0, 0, 0.05f, 1));
Instantiate(m_BulletPrefab, m_BulletSpawnPoint.position + new Vector3(0, 1.2f, 0), new Quaternion(0, 0, -0.08f, 1));
Instantiate(m_BulletPrefab, m_BulletSpawnPoint.position - new Vector3(0, 1.2f, 0), new Quaternion(0, 0, 0.08f, 1));
}
}
|
using System;
public class TCPServer {
public TCPServer() {
}
}
|
// <copyright file="ResponseMapperProfile.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Library.Mapper
{
using AutoMapper;
using Library.Models;
/// <summary>
/// The class inherits Profile, a class type that AutoMapper uses to check how our mappings will work.
/// </summary>
public class ResponseMapperProfile : Profile
{
/// <summary>
/// On the constructor, we create a map between the SaveReaderResource model class and the Reader class.
/// </summary>
public ResponseMapperProfile()
{
CreateMap<SaveReaderResource, Reader>();
CreateMap<ReadersQueryResource, ReadersQuery>();
CreateMap<SaveBookResource, Book>();
CreateMap<BooksQueryResource, BooksQuery>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerControl : MonoBehaviour
{
public static PlayerControl instance;
public GameObject One;
public GameObject Two;
public GameObject Three;
public GameObject Middle;
public GameObject Left;
public GameObject Right;
public BoxCollider2D MiddleC;
public BoxCollider2D LeftC;
public BoxCollider2D RightC;
public bool hit;
public float moveSpeed;
private Vector2 moveInput;
public float shotTime;
public Rigidbody2D theRB;
public Animator anim;
public int shotgunAmmo;
public int rifleAmmo;
// public GameObject bulletToFire;
// public Transform firePoint;
// public float timeBetweenShots;
// private float shotTimer;
public int health;
public int maxHealth;
public float deathEffect;
public int currentCoins;
public bool canMove = true;
private float hurtTimer;
public float sizeScale;
public AudioSource hurtSound;
// public Image hurtScreen;
// public GameObject hurt;
// public float hurtFadeSpeed;
// private bool hurtFadeIn, hurtFadeOut;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.localScale = new Vector3(0.75f + health * sizeScale, 0.75f + health * sizeScale, 1);
UI.instance.coinText.text = currentCoins.ToString();
hurtTimer -= Time.deltaTime;
if (hurtTimer <= 0)
{
hit = false;
}
if (health > 30)
{
health--;
}
if (health < 20)
{
Three.SetActive(false);
Right.SetActive(false);
RightC.enabled = false;
}
else
{
Three.SetActive(true);
Right.SetActive(true);
RightC.enabled = true;
}
if (health < 10)
{
Two.SetActive(false);
Left.SetActive(false);
LeftC.enabled = false;
}
else
{
Two.SetActive(true);
Left.SetActive(true);
LeftC.enabled = true;
}
//get wasd input
if (canMove)
{
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
}
else
{
moveInput.x = 0;
moveInput.y = 0;
}
//set velocity equal to wasd input times the move speed
if (canMove && !LevelManager.instance.isPaused)
{
if (moveInput.x != 0 & moveInput.y != 0)
{
theRB.velocity = moveInput * moveSpeed / (1.4f);
}
else
{
theRB.velocity = moveInput * moveSpeed;
}
//fire bullet
// if(Input.GetMouseButtonDown(0))
// {
// Instantiate(bulletToFire, firePoint.position, firePoint.rotation);
// }
// shotTimer -= Time.deltaTime;
// if(Input.GetMouseButton(0))
// {
// if(shotTimer<=0)
// {
// Instantiate(bulletToFire, firePoint.position, firePoint.rotation);
// shotTimer=timeBetweenShots;
// }
// }
}
else
{
theRB.velocity = new Vector2(0f, 0f);
}
}
public void DamagePlayer(int damage)
{
// if (hit == false)
// {
hurtSound.Play();
health -= damage;
hurtTimer = 1;
UI.instance.Hurt();
//}
//hit = true;
if (health <= 0)
{
//Instantiate(deathEffect, transform.position, transform.rotation);
UI.instance.deathScreen.SetActive(true);
UI.instance.healthSlide.enabled = false ;
Destroy(gameObject);
}
else
{
UI.instance.deathScreen.SetActive(false);
}
}
public void GainCoin(int ammount)
{
currentCoins += ammount;
}
public void LoseCoin(int ammount)
{
currentCoins -= ammount;
if (currentCoins < 0)
{
currentCoins = 0;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Enemy")
{
DamagePlayer(5);
}
if (other.tag == "Boss")
{
DamagePlayer(5);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Lavimodiere_Beazer_Midterm_Project
{
static class TileMap
{
public const int TileWidth = 32;//Width of tile
public const int TileHeight = 32;//Height of tile
public const int MapWidth = 50;//Width of Map in tiles
public const int MapHeight = 50;//Height of Map in tiles
//floor sprite range (in list)
public const int FloorTileStart = 0;
public const int FloorTileEnd = 1;
//wall sprite range (in list)
public const int WallTileStart = FloorTileEnd+1;
public const int WallTileEnd = 2;
//wall sprite range (in list)
public const int WeakWallTileStart = WallTileEnd+1;
public const int WeakWallTileEnd = 3;
static public List<Sprite> weakWall = new List<Sprite>();
//door sprite range (in list)
public const int DoorTileStart = WeakWallTileEnd+1;
public const int DoorTileEnd = 4;
static public List<Point> doorTileLoc = new List<Point>();
static private Texture2D texture;
static private List<Rectangle> tiles = new List<Rectangle>();
static public List<Color> tileColors = new List<Color>();//! when all enemies killed, change level color
static public int[,] mapSquares = new int[MapWidth, MapHeight];
private static Random rand = Game1.rand;
#region Map Squares
static public int GetSquareByPixelX(int pixelX)
{
return pixelX / TileWidth;
}
static public int GetSquareByPixelY(int pixelY)
{
return pixelY / TileHeight;
}
static public Vector2 GetSquareAtPixel(Vector2 pixelLocation)
{
return new Vector2(
GetSquareByPixelX((int)pixelLocation.X),
GetSquareByPixelY((int)pixelLocation.Y));
}
static public Vector2 GetSquareCenter(int squareX, int squareY)
{
return new Vector2(
(squareX * TileWidth) + (TileWidth / 2),
(squareY * TileHeight) + (TileHeight / 2));
}
static public Vector2 GetSquareCenter(Vector2 square)
{
return GetSquareCenter((int)square.X, (int)square.Y);
}
static public Rectangle SquareWorldRectangle(int x, int y)
{
return new Rectangle(
x * TileWidth,
y * TileHeight,
TileWidth,
TileHeight);
}
static public Rectangle SquareWorldRectangle(Vector2 square)
{
return SquareWorldRectangle((int)square.X, (int)square.Y);
}
static public Rectangle SquareScreenRectangle(int x, int y)
{
return Camera.Transform(SquareWorldRectangle(x, y));
}
static public Rectangle SquareScreenRectangle(Vector2 square)
{
return SquareScreenRectangle((int)square.X, (int)square.Y);
}
#endregion
#region Map Tiles
static public int GetTileAtSquare(int tileX, int tileY)
{
if ((tileX >= 0) && (tileX < MapWidth) && (tileY >= 0) && (tileY < MapHeight))
{
return mapSquares[tileX, tileY];
}
else
{
return -1;
}
}
static public void SetTileAtSquare(int tileX, int tileY, int tile)
{
if ((tileX >= 0) && (tileX < MapWidth) && (tileY >= 0) && (tileY < MapHeight))
{
mapSquares[tileX, tileY] = tile;
}
}
static public int GetTileAtPixel(int pixelX, int pixelY)
{
return GetTileAtSquare(GetSquareByPixelX(pixelX), GetSquareByPixelY(pixelY));
}
static public int GetTileAtPixel(Vector2 pixelLocation)
{
return GetTileAtPixel((int)pixelLocation.X, (int)pixelLocation.Y);
}
static public bool IsWallTile(int tileX, int tileY)
{
int tileIndex = GetTileAtSquare(tileX, tileY);
if (tileIndex == -1)
{
return false;
}
return tileIndex >= WallTileStart;
}
static public bool IsWallTile(Vector2 square)
{
return IsWallTile((int)square.X, (int)square.Y);
}
static public bool IsWallTileByPixel(Vector2 pixelLocation)
{
return IsWallTile(
GetSquareByPixelX((int)pixelLocation.X),
GetSquareByPixelY((int)pixelLocation.Y));
}
#endregion
static public void GenerateRandomMap()
{
int wallChancePerSquare = 15;
int floorTile = rand.Next(FloorTileStart, FloorTileEnd + 1);
int wallTile = rand.Next(WallTileStart, WallTileEnd + 1);
int weakWallTile = rand.Next(WeakWallTileStart, WeakWallTileEnd + 1);
int doorTile = rand.Next(DoorTileStart, DoorTileEnd + 1);
for (int x = 0; x < MapWidth; x++)
{
for (int y = 0; y < MapHeight; y++)
{
mapSquares[x, y] = floorTile;
if ((x == 0) || (y == 0) || (x == MapWidth - 1) || (y == MapHeight - 1))//world border
{
mapSquares[x, y] = wallTile;
continue;//move onto the next loop iteration
}
//when not on border and inside wall (0-100)
if (rand.Next(0, 100) <= wallChancePerSquare)
{
if (Game1.rand.Next(1, 3) == 1)
{
mapSquares[x, y] = weakWallTile;
}
else
mapSquares[x, y] = wallTile;
}
//set door locations
if ((x == (MapWidth / 2 - MapWidth / 4)) && (y == (MapHeight / 2)))//lower door location
{
mapSquares[x, y] = doorTile;
doorTileLoc.Add(new Point(x, y));
continue;
}
if ((x == (MapWidth / 2)) && (y == (MapHeight / 2 - MapWidth / 4)))//right door location
{
mapSquares[x, y] = doorTile;
doorTileLoc.Add(new Point(x, y));
continue;
}
if ((x == (MapWidth / 2 + MapWidth / 4)) && (y == (MapHeight / 2)))//right lower door location
{
mapSquares[x, y] = doorTile;
doorTileLoc.Add(new Point(x, y));
continue;
}
if ((x == (MapWidth / 2) / (MapWidth / 2)) && (y == (MapHeight / 2) / (MapHeight / 2)))//player spawn location
{
mapSquares[x, y] = floorTile;
continue;
}
//clear front of doors
if ((x == (MapWidth / 2 - MapWidth / 4)) && (y == (MapHeight / 2)-1))//lower door location
{
mapSquares[x, y] = floorTile;
continue;
}
if ((x == (MapWidth / 2 - MapWidth / 4)) && (y == (MapHeight / 2) + 1))//lower door location
{
mapSquares[x, y] = floorTile;
continue;
}
if ((x == (MapWidth / 2)-1) && (y == (MapHeight / 2 - MapWidth / 4)))//right door location
{
mapSquares[x, y] = floorTile;
continue;
}
if ((x == (MapWidth / 2) + 1) && (y == (MapHeight / 2 - MapWidth / 4)))//right door location
{
mapSquares[x, y] = floorTile;
continue;
}
if ((x == (MapWidth / 2 + MapWidth / 4)-1) && (y == (MapHeight / 2)))//right lower door location
{
mapSquares[x, y] = floorTile;
continue;
}
if ((x == (MapWidth / 2 + MapWidth / 4) + 1) && (y == (MapHeight / 2)))//right lower door location
{
mapSquares[x, y] = floorTile;
continue;
}
//set quadrant borders
if ((x == (MapWidth / 2)) || (y == (MapHeight / 2)))
{
mapSquares[x, y] = wallTile;
continue;
}
}
}
}
static public void Initialize(Texture2D tileTexture)
{
texture = tileTexture;
tiles.Clear();
tileColors.Clear();
//floor sprite(s)
tiles.Add(new Rectangle(0, 0, TileWidth, TileHeight));//0
tileColors.Add(Game1.RandomColor());
tiles.Add(new Rectangle(32, 0, TileWidth, TileHeight));//1
tileColors.Add(Game1.RandomColor());
//wall sprite(s)
tiles.Add(new Rectangle(64, 0, TileWidth, TileHeight));//2
tileColors.Add(Game1.RandomColor());
//weak wall sprite(s)
tiles.Add(new Rectangle(96, 0, TileWidth, TileHeight));//3
tileColors.Add(Game1.RandomColor());
//door sprite(s)
tiles.Add(new Rectangle(128, 0, TileWidth, TileHeight));//4
tileColors.Add(Game1.RandomColor());
GenerateRandomMap();
//Sprite e = new Sprite(new Vector2(x, y), texture,
// new Rectangle(
// new Point(96, 0),
// new Point(32, 32)
// ), Vector2.Zero);
//e.Animate = false;
//e.CollisionRadius = 14;
//weakWall.Add(e);
}
static public void Update(GameTime gameTime)
{
for(int x = weakWall.Count - 1; x >= 0; x--)
{
weakWall[x].Update(gameTime);
if (weakWall[x].Expired)
{
weakWall.RemoveAt(x);
}
}
}
static public void Draw(SpriteBatch spriteBatch)
{
int startX = GetSquareByPixelX((int)Camera.Position.X);
int startY = GetSquareByPixelY((int)Camera.Position.Y);
int endX = GetSquareByPixelX((int)Camera.Position.X +
Camera.ViewPortWidth);
int endY = GetSquareByPixelY((int)Camera.Position.Y +
Camera.ViewPortHeight);
foreach(Sprite wall in weakWall)
{
wall.Draw(spriteBatch, Color.White);
}
for (int x = startX; x <= endX; x++)
for (int y = startY; y <= endY; y++)
{
if ((x >= 0) && (y >= 0) && (x < MapWidth) && (y < MapHeight))
{
int a = mapSquares[x, y];//!
if (a > tileColors.Count)//if over limit(error case)
{
a = 0;
}
spriteBatch.Draw(
texture,
SquareScreenRectangle(x, y),
tiles[GetTileAtSquare(x, y)],
tileColors[a]);
}
}
}
static public void RandomizeTileColors()
{
for (int i = 0; i < tileColors.Count; i++)
{
tileColors[i] = Game1.RandomColor();//set random color on level clear
}
}
}
}
|
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestGap.Api.Controllers;
using TestGap.Api.Models;
namespace TestGapUnitTest.Api
{
[TestClass]
public class UnitTestPaciente
{
/// <summary>
/// Metodo que se encarga de validar que la insercion se realice de manera de correcta
/// </summary>
[TestMethod]
public void TestMethodRegistroPaciente()
{
var pController = new PacientesController();
var temp = pController.PostPaciente(new Paciente()
{
Identificacion = "304370390",
Nombre = "Gustavo Perez",
Edad = 29,
Telefono = "304370390",
Fecha_Ultima_Visita = new DateTime(2017,06,06,02,30,25),
Fecha_Proxima_Visita = new DateTime(2017, 06, 06, 02, 30, 25),
Correo = "tavope89@hotmail.com"
});
Assert.IsNotNull(temp);
}
/// <summary>
/// Metodo que se encarga de validar que la obtencion se realice de manera de correcta
/// </summary>
[TestMethod]
public void TestMethodObtenerPaciente()
{
var pController = new PacientesController();
var id =
(((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pController.GetPacientes()))
.Content.Pacientes).ToList().Last().Id_Paciente;
var pacientes = pController.GetPaciente(id);
Assert.IsTrue((((TestGap.Api.Models.RespuestaJsonWebApi)(((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pacientes)).Content)).success));
}
/// <summary>
/// Metodo que se encarga de validar que la obtencion se realice de manera de correcta
/// </summary>
[TestMethod]
public void TestMethodConsultarPacientes()
{
var pController= new PacientesController();
var pacientes =
((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pController.GetPacientes()))
.Content.Pacientes;
Assert.IsTrue(pacientes.Any());
}
/// <summary>
/// Metodo que se encarga de validar que la actualizacion se realice de manera de correcta
/// </summary>
[TestMethod]
public void TestMethodActualizarPaciente()
{
var pController = new PacientesController();
var paciente = ((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pController.GetPacientes()))
.Content.Pacientes.Last();
int edadActual = paciente.Edad;
paciente.Edad = (short)(paciente.Edad + 1);
pController.PutPaciente(paciente.Id_Paciente, paciente);
var pacienteNuevo = ((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pController.GetPacientes()))
.Content.Pacientes.Last();
Assert.IsTrue(pacienteNuevo.Edad != edadActual);
}
/// <summary>
/// Metodo que se encarga de validar que la eliminacion se realice de manera de correcta
/// </summary>
[TestMethod]
public void TestMethodEliminarPaciente()
{
var pController = new PacientesController();
var paciente = ((System.Web.Http.Results.JsonResult<TestGap.Api.Class.RespuestaPaciente>)(pController.GetPacientes()))
.Content.Pacientes.Last();
int idPaciente = paciente.Id_Paciente;
pController.DeletePaciente(idPaciente);
var t = pController.GetPaciente(idPaciente);
Assert.IsTrue(!(((System.Web.Http.Results.JsonResult<TestGap.Api.Models.RespuestaJsonWebApi>)(t)).Content).success);
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace WebApiMiddleware.Filters
{
public class AuthFilter : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var json = new
{
context.Response.StatusCode,
Message = "An error occurred whilst processing your request",
Detailed = exception
};
return context.Response.WriteAsync(JsonConvert.SerializeObject(json));
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace WpfApp1
{
class OverlapCheck
{
public List<string> CheckOverlap(List<string> sbmFileList)
{
HashSet<string> distince = new HashSet<string>(sbmFileList);
List<string> result = new List<String>(distince);
return result;
}
}
}
|
using System;
using VehicleManagement.Domain.Enums;
namespace VehicleManagement.Domain.Entities
{
public class Vehicle : Entity
{
public Vehicle() { }
public Vehicle(Model model, int year, string color, EFuelType fuelType, decimal purchasePrice, decimal salePrice, DateTime? saleDate)
{
Model = model;
Year = year;
Color = color;
FuelType = fuelType;
PurchasePrice = purchasePrice;
SalePrice = salePrice;
SaleDate = saleDate;
}
public Model Model { get; private set; }
public Guid ModelId { get; private set; }
public Announcement Announcement { get; private set; }
public int Year { get; private set; }
public string Color { get; private set; }
public EFuelType FuelType { get; private set; }
public decimal PurchasePrice { get; private set; }
public decimal SalePrice { get; private set; }
public DateTime? SaleDate { get; private set; }
public void AnnounceVehicle(Announcement announcement)
{
Announcement = announcement;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SCT_BL.SCT
{
public class SCT_UpdateOutputEntity
{
public SCT_UpdateOutputEntity()
{
// TODO: Add constructor logic here
}
int _StatusFlag = 0;
string _Message = string.Empty;
public int StatusFlag
{
get { return _StatusFlag; }
set { _StatusFlag = value; }
}
public string Message
{
get { return _Message; }
set { _Message = value; }
}
}
}
|
using Xamarin.Forms;
namespace App1.Controls
{
public class EmptyLabel : Label
{
public EmptyLabel()
{
TextColor = Color.White;
Text = "EmptyLabel";
HorizontalOptions = LayoutOptions.Center;
HorizontalTextAlignment = TextAlignment.Center;
VerticalTextAlignment = TextAlignment.Center;
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label));
AbsoluteLayout.SetLayoutFlags(this, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(this, new Rectangle(.5, .5, 400, 300));
}
}
}
|
using System.Runtime.CompilerServices;
[assembly:TypeForwardedToAttribute(typeof(Slave))]
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Restoran.Models
{
public class QorderModel
{
public string IdMeja { get; set; }
public int Status { get; set; }
public string IdMenu { get; set; }
public string Nama { get; set; }
public string Images { get; set; }
public int Harga { get; set; }
public int Jumlah { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerPlatformerMovemen : MonoBehaviour
{
public float movementSpeed = 5.0f;
public float jumpSpeed = 500.0f;
private Rigidbody2D rigidbody;
private bool isGrounded = true;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float movementX = Input.GetAxis("Horizontal") * movementSpeed *Time.deltaTime;
if (Input.GetButtonDown("Jump") && isGrounded) {
Debug.Log("Jump");
rigidbody.AddForce(new Vector3(0.0f, jumpSpeed, 0.0f));
}
transform.Translate(new Vector3(movementX, 0.0f, 0.0f));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignent1_PrivateSchoolStructure
{
public class Trainer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Subject { get; set; }
public List<Course> Courses { get; set; }
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
public Trainer(int id, string firstName, string lastName, string subject)
{
Id = id;
FirstName = firstName;
LastName = lastName;
Subject = subject;
Courses = new List<Course>();
}
public static Trainer GetRandomTrainer(int id, List<string> firstNames, List<string> lastNames, List<string> trainerSubjects, Random random)
{
var firstName = firstNames[random.Next(firstNames.Count)];
var lastName = lastNames[random.Next(lastNames.Count)];
var subject = trainerSubjects[random.Next(trainerSubjects.Count)];
return new Trainer(id, firstName, lastName, subject);
}
public override string ToString()
{
return $"{$"[{Id}]", -5} {FullName} - Subject: {Subject}";
}
public override bool Equals(object obj)
{
if ((obj is Trainer) && (Id == ((Trainer)obj).Id))
return true;
return false;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.IO;
using DotNetNuke.Services.Scheduling;
#endregion
namespace DotNetNuke.Services.ClientDependency
{
class PurgeClientDependencyFiles : SchedulerClient
{
public PurgeClientDependencyFiles(ScheduleHistoryItem objScheduleHistoryItem)
{
ScheduleHistoryItem = objScheduleHistoryItem; //REQUIRED
}
public override void DoWork()
{
try
{
string[] filePaths = Directory.GetFiles(string.Format("{0}/App_Data/ClientDependency", Common.Globals.ApplicationMapPath));
foreach (string filePath in filePaths)
{
File.Delete(filePath);
}
ScheduleHistoryItem.Succeeded = true; //REQUIRED
ScheduleHistoryItem.AddLogNote("Purging client dependency files task succeeded");
}
catch (Exception exc) //REQUIRED
{
ScheduleHistoryItem.Succeeded = false; //REQUIRED
ScheduleHistoryItem.AddLogNote(string.Format("Purging client dependency files task failed: {0}.", exc.ToString()));
//notification that we have errored
Errored(ref exc); //REQUIRED
//log the exception
Exceptions.Exceptions.LogException(exc); //OPTIONAL
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Master.Contract;
using Master.BusinessFactory;
namespace LogiCon.Areas.Master.Controllers
{
[RoutePrefix("api/master/equipment")]
public class EquipmentSizeTypeController : ApiController
{
[HttpGet]
[Route("size/all")]
public IHttpActionResult GetAllSizes()
{
try
{
var sizes = new EquipmentSizeTypeBO()
.GetList()
.Where(x => x.EquipmentType == 1320)
.Select(x => new {
Value = x.Size,
Text = x.Size
})
.Distinct()
.ToList();
if (sizes != null)
return Ok(sizes);
else
return NotFound();
}
catch (Exception ex)
{
return InternalServerError();
}
}
[HttpGet]
[Route("{size}/type")]
public IHttpActionResult GetTypeBySize(int size)
{
var types = new EquipmentSizeTypeBO()
.GetList()
.Where(x => x.EquipmentType == 1320 && x.Size == size.ToString())
.Select(x => new {
Value = x.Code,
Text = x.Type
})
.Distinct()
.ToList();
if (types != null)
return Ok(types);
else
return NotFound();
}
}
}
|
using AutoMapper;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Moq;
using RollerStore.Core.Store;
using RollerStoreOnion.Controllers;
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace RollerStore.Api.Unit.Tests.Store
{
public class StoresControllerTests
{
private readonly StoresController _controller;
private readonly Mock<IMapper> _mapperMock;
private readonly Mock<IStoreService> _storeServiceMock;
public StoresControllerTests()
{
_mapperMock = new Mock<IMapper>();
_storeServiceMock = new Mock<IStoreService>();
_controller = new StoresController(_mapperMock.Object, _storeServiceMock.Object);
}
[Fact]
public async Task PostAsync_IfServiceReturnStore_ReturnsResponse()
{
//Arrange
var store = new global::RollerStore.Orschestrators.Store.Contracts.CreateStore
{
Name = "Rollerland",
Address = "adress"
};
var storeForService = new global::RollerStore.Core.Store.Store
{
Name = store.Name,
Address = store.Address
};
var storeFromService = new global::RollerStore.Core.Store.Store
{
Id = 2,
Name = storeForService.Name,
Address = storeForService.Address
};
var storeAfterMapping = new global::RollerStore.Orschestrators.Store.Contracts.Store
{
Id = storeFromService.Id,
Name = storeFromService.Name,
Address = storeFromService.Address
};
_mapperMock.Setup(m => m.Map<global::RollerStore.Core.Store.Store>(store))
.Returns(storeForService);
_storeServiceMock.Setup(st => st.AddAsync(storeForService))
.ReturnsAsync(storeFromService);
_mapperMock.Setup(m => m.Map<global::RollerStore.Orschestrators.Store.Contracts.Store>(storeFromService))
.Returns(storeAfterMapping);
//Act
var result = await _controller.PostAsync(store) as OkObjectResult;
//Assert
result.Should().NotBeNull();
result.StatusCode.Should().Be((int)HttpStatusCode.OK);
result.Value.Should().Be(storeAfterMapping);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Improve this!
public class WaterGun : MonoBehaviour
{
public GameObject waterPrefab;
public static float waterLeft = 30f;
/// <summary>
/// Called whenever the attached object is created or enabled in a scene.
/// </summary>
private void OnEnable()
{
BushfireEventManager.OnMouseClick += ShootWater;
}
/// <summary>
/// Called whenever the attached object is disabled or destroyed in a scene.
/// </summary>
private void OnDisable()
{
BushfireEventManager.OnMouseClick -= ShootWater;
}
void ShootWater()
{
if(BushfireGameManager.currentState == BushfireGameManager.GameState.InGame)
{
waterLeft -= Time.deltaTime;
var position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1000f);
position = Camera.main.ScreenToWorldPoint(position);
GameObject newObject = Instantiate(waterPrefab, Camera.main.transform.position + Vector3.down * 2f, Quaternion.identity);
newObject.transform.LookAt(position);
newObject.GetComponent<Rigidbody>().AddForce(newObject.transform.forward * 4000f);
}
}
}
|
namespace PlatformRacing3.Server.Game.Client;
public enum ClientStatus
{
None,
ConnectionConfirmed,
LoggedIn,
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MFW.WF.UX;
namespace MFW.WF
{
public partial class TestWindow : Form
{
public TestWindow()
{
InitializeComponent();
panel3.BackColor = Color.FromArgb(80, 0, 0, 0);
}
private void button1_Click(object sender, EventArgs e)
{
UXMessageMask.ShowMessage(this, false, "fdasfds", MessageBoxButtonsType.AnswerHangup, MessageBoxIcon.Error);
}
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("RankedRewardChest")]
public class RankedRewardChest : MonoBehaviour
{
public RankedRewardChest(IntPtr address) : this(address, "RankedRewardChest")
{
}
public RankedRewardChest(IntPtr address, string className) : base(address, className)
{
}
public bool DoesChestVisualChange(int rank1, int rank2)
{
object[] objArray1 = new object[] { rank1, rank2 };
return base.method_11<bool>("DoesChestVisualChange", objArray1);
}
public static string GetChestEarnedFromRank(int rank)
{
object[] objArray1 = new object[] { rank };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "GetChestEarnedFromRank", objArray1);
}
public static int GetChestIndexFromRank(int rank)
{
object[] objArray1 = new object[] { rank };
return MonoClass.smethod_14<int>(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "GetChestIndexFromRank", objArray1);
}
public static string GetChestNameFromRank(int rank)
{
object[] objArray1 = new object[] { rank };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "GetChestNameFromRank", objArray1);
}
public ChestVisual GetChestVisualFromRank(int rank)
{
object[] objArray1 = new object[] { rank };
return base.method_14<ChestVisual>("GetChestVisualFromRank", objArray1);
}
public void SetRank(int rank)
{
object[] objArray1 = new object[] { rank };
base.method_8("SetRank", objArray1);
}
public MeshRenderer m_baseMeshRenderer
{
get
{
return base.method_3<MeshRenderer>("m_baseMeshRenderer");
}
}
public List<ChestVisual> m_chests
{
get
{
Class267<ChestVisual> class2 = base.method_3<Class267<ChestVisual>>("m_chests");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public MeshRenderer m_glowMeshRenderer
{
get
{
return base.method_3<MeshRenderer>("m_glowMeshRenderer");
}
}
public GameObject m_legendaryGem
{
get
{
return base.method_3<GameObject>("m_legendaryGem");
}
}
public UberText m_rankBanner
{
get
{
return base.method_3<UberText>("m_rankBanner");
}
}
public UberText m_rankNumber
{
get
{
return base.method_3<UberText>("m_rankNumber");
}
}
public GameObject m_starDestinationBone
{
get
{
return base.method_3<GameObject>("m_starDestinationBone");
}
}
public static int NUM_REWARD_TIERS
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "NUM_REWARD_TIERS");
}
}
public static string s_rewardChestEarnedText
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "s_rewardChestEarnedText");
}
}
public static string s_rewardChestNameText
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "RankedRewardChest", "s_rewardChestNameText");
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace BIADTemplate.Model
{
[Serializable]
public class RichQnaResponse
{
public string Title { get; set; }
public string Text { get; set; }
public string Image { get; set; }
public IList<RichQnaButton> Buttons { get; set; }
}
} |
// 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.
#if !NET
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]
internal sealed class AllowNullAttribute : Attribute
{
}
}
#endif
|
using cosmetic_hub__e_shopping_system_.Interfaces;
using cosmetic_hub__e_shopping_system_.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace cosmetic_hub__e_shopping_system_.Repositories
{
public class ShoppingCartItemsRepository: IShoppingCartItemsRepository
{
private readonly AppDbContext _appDbContext;
public ShoppingCartItemsRepository(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public void AddShoppingItems(ShoppingCartItems shoppingCartItem)
{
_appDbContext.ShoppingCartItems.Add(shoppingCartItem);
_appDbContext.SaveChanges();
}
public IEnumerable<ShoppingCartItems> GetAllShoppingItems()
{
return _appDbContext.ShoppingCartItems;
}
public void SaveShoppingItems()
{
_appDbContext.SaveChanges();
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_RuntimeInitializeLoadType : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.RuntimeInitializeLoadType");
LuaObject.addMember(l, 0, "AfterSceneLoad");
LuaObject.addMember(l, 1, "BeforeSceneLoad");
LuaDLL.lua_pop(l, 1);
}
}
|
using APIChallenge;
using System.Collections.Generic;
namespace DependencyInjectionSample.Interfaces
{
public interface IServicosDeEstabelecimento
{
/// <summary>
/// Método responsável por obter a lista de Estabelecimentos cadastrados
/// </summary>
/// <returns></returns>
List<Estabelecimento> obterListaEstabelecimentos();
/// <summary>
/// Método responsável por obter um Estabelecimento por seu id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Estabelecimento obterEstabelecimentoPorId(long id);
/// <summary>
/// Método responsável por validar e cadastrar um Estabelecimento por seu CNPJ recuperando as informações da API receitaws
/// </summary>
/// <param name="cnpj"></param>
void inserirEstabelecimento(string cnpj);
}
}
|
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WF_09_RadioButtons
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
Color color = Color.FromName(rb.Text);
if ((rb.Parent as GroupBox).Text.Equals("Background"))
this.BackColor = color;
else
this.ForeColor = color;
}
private void btnSummary_Click(object sender, EventArgs e)
{
// Background: Green Foreground: Yellow
StringBuilder builder = new StringBuilder();
foreach (var item in this.Controls)
{
if (!(item is GroupBox))
continue;
GroupBox box = item as GroupBox;
builder.Append(box.Text);
builder.Append(": ");
foreach (var control in box.Controls)
{
if (!(control is RadioButton))
continue;
RadioButton btn = control as RadioButton;
if (btn.Checked)
{
builder.Append(btn.Text);
break;
}
}
builder.Append(" ");
}
this.Text = builder.ToString();
}
}
}
|
using System;
using System.Text;
namespace divisible
{
public static class Outputter
{
static readonly string[] _unitsMap = new[] {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
};
static readonly string[] _tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
public static string NumberToEnglish(int num)
{
if (num == 0)
return "zero";
if (num < 0)
return "minus " + NumberToEnglish(Math.Abs(num));
var builder = new StringBuilder();
if ((num / 1000000) > 0)
{
builder.Append(NumberToEnglish(num / 1000000) + " million ");
num %= 1000000;
}
if ((num / 1000) > 0)
{
builder.Append(NumberToEnglish(num / 1000) + " thousand ");
num %= 1000;
}
if ((num / 100) > 0)
{
builder.Append(NumberToEnglish(num / 100) + " hundred ");
num %= 100;
}
if (num > 0)
{
if (num < 20)
builder.Append(_unitsMap[num]);
else
{
builder.Append(_tensMap[num / 10]);
if ((num % 10) > 0)
builder.Append("-" + _unitsMap[num % 10]);
}
}
return builder.ToString();
}
}
}
|
using ServerApp.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServerApp
{
public class Program
{
static void Main(string[] args)
{
var helper = new RoomNameHelper();
var ll = helper.Retrieve();
var tt = helper.Retrieve("admin");
foreach(var r in ll)
{
Console.WriteLine(r.RoomNameId);
Console.WriteLine(r.RoomName);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
foreach (var r in tt)
{
Console.WriteLine(r.RoomNameId);
Console.WriteLine(r.RoomName);
}
//var helper2 = new DeviceTypeHelper();
//var ttt = helper2.Retrieve();
//foreach(var t in ttt)
//{
// Console.WriteLine(t.DeviceTypeId);
// Console.WriteLine(t.DeviceTypeName);
//}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wall : MonoBehaviour
{
//AudioSource shootingWallAudio;
// Start is called before the first frame update
void Start()
{
//shootingWallAudio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
/// <summary>
/// 播放子弹打到墙体的声音;
/// </summary>
/// <param name="collision"></param>
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.gameObject.tag == "Bullet" || collision.collider.gameObject.tag == "AlienBullet")
{
SoundManager.instance.PlayExplosionAtWall();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace Caliburn.Light
{
/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T">The type of elements in the collection.</typeparam>
public class BindableCollection<T> : ObservableCollection<T>, IBindableCollection<T>, IReadOnlyBindableCollection<T>
{
private int _suspensionCount;
/// <summary>
/// Initializes a new instance of BindableCollection that is empty and has default initial capacity.
/// </summary>
public BindableCollection()
{
}
/// <summary>
/// Initializes a new instance of the BindableCollection that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new BindableCollection.</param>
public BindableCollection(IEnumerable<T> collection) : base(collection)
{
}
/// <summary>
/// Suspends the notifications.
/// </summary>
/// <returns></returns>
public IDisposable SuspendNotifications()
{
_suspensionCount++;
return new DisposableAction(ResumeNotifications);
}
private void ResumeNotifications()
{
_suspensionCount--;
}
/// <summary>
/// Determines whether notifications are suspended.
/// </summary>
/// <returns></returns>
protected bool AreNotificationsSuspended()
{
return _suspensionCount > 0;
}
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (AreNotificationsSuspended()) return;
base.OnPropertyChanged(e);
}
/// <summary>
/// Raises the <see cref="INotifyCollectionChanged.CollectionChanged" /> event.
/// </summary>
/// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (AreNotificationsSuspended()) return;
base.OnCollectionChanged(e);
}
/// <summary>
/// Raises a property and collection changed event that notifies that all of the properties on this object have changed.
/// </summary>
protected virtual void OnCollectionRefreshed()
{
if (AreNotificationsSuspended()) return;
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
/// <summary>
/// Raises a property and collection changed event that notifies that all of the properties on this object have changed.
/// </summary>
public void Refresh()
{
CheckReentrancy();
OnCollectionRefreshed();
}
/// <summary>
/// Adds the elements of the specified collection to the end of the BindableCollection.
/// </summary>
/// <param name="items">The collection whose elements should be added to the end of the BindableCollection.</param>
public void AddRange(IEnumerable<T> items)
{
if (items is null)
throw new ArgumentNullException(nameof(items));
CheckReentrancy();
foreach (var item in items) { Items.Add(item); }
OnCollectionRefreshed();
}
/// <summary>
/// Removes a range of elements from the BindableCollection.
/// </summary>
/// <param name="items">The collection whose elements should be removed from the BindableCollection.</param>
public void RemoveRange(IEnumerable<T> items)
{
if (items is null)
throw new ArgumentNullException(nameof(items));
CheckReentrancy();
foreach (var item in items) { Items.Remove(item); }
OnCollectionRefreshed();
}
}
}
|
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Entidades;
using PDV.UTIL;
using PDV.VIEW.App_Context;
using PDV.VIEW.Forms.Cadastro;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Consultas
{
public partial class FCO_Municipio : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CONSULTA DE MUNICÍPIO";
public FCO_Municipio()
{
InitializeComponent();
}
private void AtualizaMunicipios(string Descricao)
{
ovGRD_Municipios.DataSource = FuncoesMunicipio.GetMunicipios(Descricao);
AjustaHeaderTextGrid();
}
private void AjustaHeaderTextGrid()
{
ovGRD_Municipios.RowHeadersVisible = false;
int WidthGrid = ovGRD_Municipios.Width;
foreach (DataGridViewColumn column in ovGRD_Municipios.Columns)
{
switch (column.Name)
{
case "descricao":
column.DisplayIndex = 1;
column.MinimumWidth = Convert.ToInt32(WidthGrid * 0.75);
column.Width = Convert.ToInt32(WidthGrid * 0.75);
column.HeaderText = "DESCRIÇÃO";
break;
case "unidadefederativa":
column.DisplayIndex = 3;
column.MinimumWidth = Convert.ToInt32(WidthGrid * 0.25);
column.Width = Convert.ToInt32(WidthGrid * 0.25);
column.HeaderText = "UNIDADE FEDERATIVA";
break;
default:
column.DisplayIndex = 0;
column.Visible = false;
break;
}
}
}
private void ovBTN_LimparFiltros_Click(object sender, EventArgs e)
{
ovTXT_Descricao.Text = string.Empty;
}
private void ovBTN_Pesquisar_Click(object sender, EventArgs e)
{
AtualizaMunicipios(ovTXT_Descricao.Text);
}
private void ovBTN_Novo_Click(object sender, EventArgs e)
{
FCA_Municipio t = new FCA_Municipio(new Municipio());
t.ShowDialog(this);
AtualizaMunicipios(ovTXT_Descricao.Text);
}
private void ovBTN_Editar_Click(object sender, EventArgs e)
{
decimal IDMunicipio = Convert.ToDecimal(ZeusUtil.GetValueFieldDataRowView((ovGRD_Municipios.CurrentRow.DataBoundItem as DataRowView), "IDMUNICIPIO"));
FCA_Municipio t = new FCA_Municipio(FuncoesMunicipio.GetMunicipio(IDMunicipio));
t.ShowDialog(this);
AtualizaMunicipios(ovTXT_Descricao.Text);
editarmunicipiometroButton4.Enabled = false;
}
private void ovBTN_Excluir_Click(object sender, EventArgs e)
{
if (MessageBox.Show(this, "Deseja remover a Unidade Federativa selecionada?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
decimal IDMunicipio = Convert.ToDecimal(ZeusUtil.GetValueFieldDataRowView((ovGRD_Municipios.CurrentRow.DataBoundItem as DataRowView), "IDMUNICIPIO"));
try
{
if (!FuncoesMunicipio.Remover(IDMunicipio))
throw new Exception("Não foi possível remover o Município.");
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AtualizaMunicipios(ovTXT_Descricao.Text);
}
}
private void FCO_Municipio_Load(object sender, EventArgs e)
{
AtualizaMunicipios(ovTXT_Descricao.Text);
}
private void ovGRD_Municipios_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal IDMunicipio = Convert.ToDecimal(ZeusUtil.GetValueFieldDataRowView((ovGRD_Municipios.CurrentRow.DataBoundItem as DataRowView), "IDMUNICIPIO"));
FCA_Municipio t = new FCA_Municipio(FuncoesMunicipio.GetMunicipio(IDMunicipio));
t.ShowDialog(this);
AtualizaMunicipios(ovTXT_Descricao.Text);
editarmunicipiometroButton4.Enabled = false;
}
private void ovGRD_Municipios_CellClick(object sender, DataGridViewCellEventArgs e)
{
editarmunicipiometroButton4.Enabled = true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Map))]
public class CustomMapInspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
Map map = target as Map;
if (GUILayout.Button("Generate"))
{
map.Generate();
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using W3ChampionsStatisticService.PlayerStats.HeroStats;
using W3ChampionsStatisticService.PlayerStats.RaceOnMapVersusRaceStats;
using W3ChampionsStatisticService.Ports;
namespace W3ChampionsStatisticService.PlayerStats
{
[ApiController]
[Route("api/player-stats")]
public class PlayerStatsController : ControllerBase
{
private readonly IPlayerStatsRepository _playerRepository;
public PlayerStatsController(IPlayerStatsRepository playerRepository)
{
_playerRepository = playerRepository;
}
[HttpGet("{battleTag}/race-on-map-versus-race")]
public async Task<IActionResult> GetRaceOnMapVersusRaceStat([FromRoute] string battleTag, int season)
{
var matches = await _playerRepository.LoadMapAndRaceStat(battleTag, season);
return Ok(matches ?? PlayerRaceOnMapVersusRaceRatio.Create(battleTag, season));
}
[HttpGet("{battleTag}/hero-on-map-versus-race")]
public async Task<IActionResult> GetHeroOnMapVersusRaceStat([FromRoute] string battleTag, int season)
{
var matches = await _playerRepository.LoadHeroStat(battleTag, season);
return Ok(matches ?? PlayerHeroStats.Create(battleTag, season));
}
}
} |
using ScribblersSharp;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// Scribble.rs Pad controllers namespace
/// </summary>
namespace ScribblersPad.Controllers
{
/// <summary>
/// A class that describes a game UI layout controller script
/// </summary>
public class GameUILayoutControllerScript : AScribblersClientControllerScript, IGameUILayoutController
{
/// <summary>
/// Gets invoked when a "ready" game message has been received
/// </summary>
[SerializeField]
private UnityEvent onReadyGameMessageReceived = default;
/// <summary>
/// Gets invoked when a "next-turn" game message has been received
/// </summary>
[SerializeField]
private UnityEvent onNextTurnGameMessageReceived = default;
/// <summary>
/// Gets invoked when a "your-turn" game message has been received
/// </summary>
[SerializeField]
private UnityEvent onYourTurnGameMessageReceived = default;
/// <summary>
/// Gets invoked when a "correct-guess" game message has been received
/// </summary>
[SerializeField]
private UnityEvent onCorrectGuessGameMessageReceived = default;
/// <summary>
/// Gets invoked when drawing board has been shown
/// </summary>
[SerializeField]
private UnityEvent onDrawingBoardShown = default;
/// <summary>
/// Gets invoked when chat has been shown
/// </summary>
[SerializeField]
private UnityEvent onChatShown = default;
/// <summary>
/// Game UI layout state
/// </summary>
private EGameUILayoutState gameUILayoutState = EGameUILayoutState.Nothing;
/// <summary>
/// Game UI layout state
/// </summary>
public EGameUILayoutState GameUILayoutState
{
get => gameUILayoutState;
set
{
if (gameUILayoutState != value)
{
switch (value)
{
case EGameUILayoutState.DrawingBoard:
gameUILayoutState = EGameUILayoutState.DrawingBoard;
if (onDrawingBoardShown != null)
{
onDrawingBoardShown.Invoke();
}
OnDrawingBoardShown?.Invoke();
break;
case EGameUILayoutState.Chat:
gameUILayoutState = EGameUILayoutState.Chat;
if (onChatShown != null)
{
onChatShown.Invoke();
}
OnChatShown?.Invoke();
break;
}
}
}
}
/// <summary>
/// Gets invoked when a "ready" game message has been received
/// </summary>
public event ReadyGameMessageReceivedDelegate OnReadyGameMessageReceived;
/// <summary>
/// Gets invoked when a "next-turn" game message has been received
/// </summary>
public event NextTurnGameMessageReceivedDelegate OnNextTurnGameMessageReceived;
/// <summary>
/// Gets invoked when a "your-turn" game message has been received
/// </summary>
public event YourTurnGameMessageReceivedDelegate OnYourTurnGameMessageReceived;
/// <summary>
/// Gets invoked when a "correct-guess" game message has been received
/// </summary>
public event CorrectGuessGameMessageReceivedDelegate OnCorrectGuessGameMessageReceived;
/// <summary>
/// Gets invoked when drawing board has been shown
/// </summary>
public event DrawingBoardShownDelegate OnDrawingBoardShown;
/// <summary>
/// Gets invoked when chat has been shown
/// </summary>
public event ChatShownDelegate OnChatShown;
/// <summary>
/// Gets invoked when a "ready" game message has been received
/// </summary>
private void ScribblersClientManagerReadyGameMessageReceivedEvent()
{
GameUILayoutState = EGameUILayoutState.DrawingBoard;
if (onReadyGameMessageReceived != null)
{
onReadyGameMessageReceived.Invoke();
}
OnReadyGameMessageReceived?.Invoke();
}
/// <summary>
/// Gets invoked when a "next-turn" game message has been received
/// </summary>
private void ScribblersClientManagerNextTurnGameMessageReceivedEvent()
{
GameUILayoutState = EGameUILayoutState.DrawingBoard;
if (onNextTurnGameMessageReceived != null)
{
onNextTurnGameMessageReceived.Invoke();
}
OnNextTurnGameMessageReceived?.Invoke();
}
/// <summary>
/// Gets invoked when a "your-turn" game message has been received
/// </summary>
/// <param name="words">Words to choose</param>
private void ScribblersClientManagerYourTurnGameMessageReceivedEvent(IReadOnlyList<string> words)
{
GameUILayoutState = EGameUILayoutState.DrawingBoard;
if (onYourTurnGameMessageReceived != null)
{
onYourTurnGameMessageReceived.Invoke();
}
OnYourTurnGameMessageReceived?.Invoke(words);
}
/// <summary>
/// Gets invoked when a "correct-guess" game message has been received
/// </summary>
/// <param name="player">Player who have guessed correctly</param>
private void ScribblersClientManagerCorrectGuessGameMessageReceived(IPlayer player)
{
if (player.ID == ScribblersClientManager.MyPlayer.ID)
{
GameUILayoutState = EGameUILayoutState.Chat;
}
if (onCorrectGuessGameMessageReceived != null)
{
onCorrectGuessGameMessageReceived.Invoke();
}
OnCorrectGuessGameMessageReceived?.Invoke(player);
}
/// <summary>
/// Subscribes to Scribble.rs client events
/// </summary>
protected override void SubscribeScribblersClientEvents()
{
ScribblersClientManager.OnReadyGameMessageReceived += ScribblersClientManagerReadyGameMessageReceivedEvent;
ScribblersClientManager.OnNextTurnGameMessageReceived += ScribblersClientManagerNextTurnGameMessageReceivedEvent;
ScribblersClientManager.OnYourTurnGameMessageReceived += ScribblersClientManagerYourTurnGameMessageReceivedEvent;
ScribblersClientManager.OnCorrectGuessGameMessageReceived += ScribblersClientManagerCorrectGuessGameMessageReceived;
}
/// <summary>
/// Unsubscribes from Scribble.rs client events
/// </summary>
protected override void UnsubscribeScribblersClientEvents()
{
ScribblersClientManager.OnReadyGameMessageReceived -= ScribblersClientManagerReadyGameMessageReceivedEvent;
ScribblersClientManager.OnNextTurnGameMessageReceived -= ScribblersClientManagerNextTurnGameMessageReceivedEvent;
ScribblersClientManager.OnYourTurnGameMessageReceived -= ScribblersClientManagerYourTurnGameMessageReceivedEvent;
ScribblersClientManager.OnCorrectGuessGameMessageReceived -= ScribblersClientManagerCorrectGuessGameMessageReceived;
}
/// <summary>
/// Shows drawing board
/// </summary>
public void ShowDrawingBoard() => GameUILayoutState = EGameUILayoutState.DrawingBoard;
/// <summary>
/// Shows chat
/// </summary>
public void ShowChat() => GameUILayoutState = EGameUILayoutState.Chat;
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Im.Access.GraphPortal.Data
{
public class DbClient
{
[Key]
public int Id { get; set; }
public bool Enabled { get; set; }
[StringLength(200)]
public string ClientId { get; set; }
[StringLength(200)]
public string ClientName { get; set; }
[StringLength(2000)]
public string ClientUri { get; set; }
[StringLength(250)]
public string LogoUri { get; set; }
public bool RequireConsent { get; set; }
public bool AllowRequireConsent { get; set; }
public bool AllowAccessTokensViaBrowser { get; set; }
public int Flow { get; set; }
public bool AllowClientCredentialsOnly { get; set; }
[StringLength(250)]
public string LogoutUri { get; set; }
public bool LogoutSessionRequired { get; set; }
public bool RequireSignOutPrompt { get; set; }
public bool AllowAccessToAllScopes { get; set; }
public int IdentityTokenLifetime { get; set; }
public int AccessTokenLifetime { get; set; }
public int AuthorizationCodeLifetime { get; set; }
public int SlidingRefreshTokenLifetime { get; set; }
public int RefreshTokenUsage { get; set; }
public bool UpdateAccessTokenOnRefresh { get; set; }
public int RefreshTokenExpiration { get; set; }
public int AccessTokenType { get; set; }
public bool EnableLocalLogin { get; set; }
public bool IncludeJwtId { get; set; }
public bool AlwaysSendClientClaims { get; set; }
public bool PrefixClientClaims { get; set; }
public bool AllowAccessToAllGrantTypes { get; set; }
public ICollection<DbClientClaim> Claims { get; set; }
}
public class DbClientClaim
{
public int Id { get; set; }
[StringLength(250)]
public string Type { get; set; }
[StringLength(250)]
public string Value { get; set; }
public int ClientId { get; set; }
}
}
|
using System;
namespace Whale.Shared.Models.GroupMessage
{
public class UnreadGroupMessageDTO
{
public Guid MessageId { get; set; }
public Guid GroupId { get; set; }
public Guid ReceiverId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Planning
{
class Action_Evaluation
{
public double grade = -1;
public Dictionary<string, List<Landmark>> agentLandmarks = null;
public Action_Evaluation()
{
agentLandmarks = new Dictionary<string, List<Landmark>>();
}
}
}
|
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using CarsDb.Data.Repositories;
using CarsDb.Model;
namespace CarsDb.Data
{
public interface ICarsData
{
IGenericRepository<Car> Cars { get; }
IGenericRepository<Dealer> Dealers { get; }
IGenericRepository<Manufacturer> Manufacturers { get; }
IGenericRepository<City> Cities { get; }
DbContextConfiguration Configuration { get; }
int SaveChanges();
DbContextTransaction BeginTransaction();
DbContextTransaction BeginTransaction(IsolationLevel isolationLevel);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _24HR.Imaging.Resize
{
public enum ResizeMethod
{
Distort, Pad, Crop, Constrain
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SaleShop.Common;
using SaleShop.Data.Infrastructure;
using SaleShop.Data.Repositories;
using SaleShop.Model.Models;
namespace SaleShop.Service
{
public interface ICommonService
{
Footer GetFooter();
IEnumerable<Slide> GetSlides();
SystemConfig GetSystemConfig(string code);
}
public class CommonService : ICommonService
{
private IUnitOfWork _unitOfWork;
private IFooterRepository _footerRepository;
private ISlideRepository _slideRepository;
private ISystemConfigRepository _systemConfigRepository;
public CommonService(IFooterRepository footerRepository,ISlideRepository slideRepository, ISystemConfigRepository systemConfigRepository,IUnitOfWork unitOfWork)
{
_footerRepository = footerRepository;
_slideRepository = slideRepository;
_systemConfigRepository = systemConfigRepository;
_unitOfWork = unitOfWork;
}
public Footer GetFooter()
{
return _footerRepository.GetSingleByCondition(n => n.ID == CommonConstants.DefaultFooterId);
}
public IEnumerable<Slide> GetSlides()
{
return _slideRepository.GetMulti(n=>n.Status);
}
public SystemConfig GetSystemConfig(string code)
{
return _systemConfigRepository.GetSingleByCondition(n => n.Code == code);
}
}
}
|
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace NBAFantasy.Models
{
public class Team
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
public string GM { get; set; }
[BsonIgnore]
public IEnumerable<Player> Players { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using UnityEngine;
public class MonsterData
{
}
public class SaveManager : MonoBehaviour
{
public bool haveSavedData { get; }
public string savePath;
public TestData dataTest;
public Dictionary<string, MonsterData> _monstersData;
private void Start()
{
SaveToFile();
}
void LoadMonsters(Dictionary<string, MonsterData> monsterData)
{
_monstersData = monsterData;
char[] separator = new char[] { '\r', '\n' };
foreach (var monsterAssets in Resources.LoadAll<TextAsset>("Monsters/"))
{
List<string> monsterText = monsterAssets.text.Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList();
int index = 2;
while (monsterText[index] != ".end")
{
List<string> data = Regex.Matches(monsterText[index++].Replace("\t", " "),
@"[\""].+?[\""]|[^ ]+").Cast<Match>().Select(m => m.Value).ToList();
for (int i = 0; i < data.Count; i++)
data[i] = data[i].Replace("\"", "").Replace("%", "");
Debug.Log(data[0]);
}
index += 2;
}
}
public void SaveToFile()
{
if (!Directory.Exists(Application.persistentDataPath + "/game_save"))
Directory.CreateDirectory(Application.persistentDataPath + "/game_save");
if (!Directory.Exists(Application.persistentDataPath + "/game_save/chatacter_data/"))
Directory.CreateDirectory(Application.persistentDataPath + "/game_save/chatacter_data");
FileStream file = new FileStream(Application.persistentDataPath + "/game_save/chatacter_data/charatcer_save.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
var json = JsonUtility.ToJson(dataTest, false);
try
{
bf.Serialize(file, json);
}
catch (System.Exception)
{
Debug.Log("Failed ");
throw new System.Exception();
}
finally
{
file.Close();
Debug.Log("Save in " + Application.persistentDataPath);
}
}
public TestData LoadFromFile()
{
TestData td = new TestData();
BinaryFormatter bf = new BinaryFormatter();
if (File.Exists(Application.persistentDataPath + "/game_save/chatacter_data/charatcer_save.txt"))
{
FileStream file = File.Open(Application.persistentDataPath + "/game_save/chatacter_data/charatcer_save.txt", FileMode.Open);
Debug.Log(file.Length);
JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), td);
file.Close();
}
return td;
}
}
|
using System;
using System.Net;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Net.NetworkInformation;
using SenticsLib;
#if MF_FRAMEWORK_VERSION_V4_2
using GHI.Premium.Net;
#if G120
using GHI.Hardware.G120;
#endif
#endif
#if MF_FRAMEWORK_VERSION_V4_3
using GHI.Networking;
#endif
namespace SCII
{
public static class Network
{
public delegate void NetworkDownHandler();
public delegate void NetworkUpHandler(string ip);
#if BUILDIN_ETHERNET
static EthernetBuiltIn _nic;
#endif
#if ENC28J60
private static EthernetENC28J60 _nic;
#endif
public static bool IsConnected
{
#if MF_FRAMEWORK_VERSION_V4_2
get { return _nic != null && _nic.IsCableConnected; }
#endif
#if MF_FRAMEWORK_VERSION_V4_3
get { return _nic != null && _nic.CableConnected; }
//get { return GHI.Networking.BaseInterface.ActiveInterface.NetworkIsAvailable; }
#endif
}
public static event NetworkUpHandler NetworkUp;
private static void OnNetworkUp(string ip)
{
NetworkUpHandler handler = NetworkUp;
if (handler != null) handler(ip);
}
public static event NetworkDownHandler NetworkDown;
private static void OnNetworkDown()
{
NetworkDownHandler handler = NetworkDown;
if (handler != null) handler();
}
#if ENC28J60
public static void InitNIC(EthernetENC28J60 nic)
#endif
#if BUILDIN_ETHERNET
public static void InitNIC(EthernetBuiltIn nic)
#endif
{
_nic = nic;
try
{
#if MF_FRAMEWORK_VERSION_V4_2
_nic.CableConnectivityChanged += NICCableConnectivityChanged;
_nic.NetworkAddressChanged += NetworkAddressChanged;
if (!_nic.IsOpen)
_nic.Open();
NetworkInterfaceExtension.AssignNetworkingStackTo(nic);
SetUpIPaddress();
return;
#endif
#if MF_FRAMEWORK_VERSION_V4_3
NetworkChange.NetworkAvailabilityChanged += NetworkChangeNetworkAvailabilityChanged;
NetworkChange.NetworkAddressChanged += NetworkChangeNetworkAddressChanged;
if (!nic.Opened)
_nic.Open();
#endif
// 2014-02-11 : DNS Work around for static IP
if (Settings.Web.IP != "0.0.0.0")
{
Log.WriteString(LogMessageType.Info, "Set static DNS's");
_nic.NetworkInterface.EnableStaticDns(new[] {"8.8.8.8", "8.8.4.4"});
SetUpIPaddress();
//OnNetworkUp(IPAddress.GetDefaultLocalAddress().ToString());
}
if (!IsConnected)
{
Log.WriteString(LogMessageType.Warning, "No network cable detected at InitNIC");
}
else
{
if (Settings.Web.IP == "0.0.0.0" || _nic.NetworkInterface.IPAddress != Settings.Web.IP | _nic.NetworkInterface.GatewayAddress != Settings.Web.Gateway ||
_nic.NetworkInterface.SubnetMask != Settings.Web.Netmask)
{
SetUpIPaddress();
}
}
}
catch (Exception exception)
{
DebugHelper.Print("Exception: " + exception.Message);
throw;
}
}
#if MF_FRAMEWORK_VERSION_V4_3
static void NetworkChangeNetworkAddressChanged(object sender, EventArgs e)
{
Active.Instance.SetActive();
if (_nic.NetworkInterface.IPAddress == "0.0.0.0")
{
Log.WriteString(LogMessageType.Info, "Network address changed: IP=0.0.0.0");
OnNetworkDown();
}
else
{
Log.WriteString(LogMessageType.Info,
"Network address changed: IP=" + _nic.NetworkInterface.IPAddress);
OnNetworkUp(_nic.NetworkInterface.IPAddress);
}
}
static void NetworkChangeNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Active.Instance.SetActive();
if (IsConnected)
{
Log.WriteString(LogMessageType.Info, "Ethernet cable connected");
SetUpIPaddress();
}
else
{
Log.WriteString(LogMessageType.Info, "Ethernet cable disconnected");
// in case of static IP, network address change is not fired.. Call OnNetWorkDown which in turn shuts down the web server
if (Settings.Web.IP != "0.0.0.0")
{
// force address change event
_nic.NetworkInterface.EnableStaticIP("0.0.0.0", Settings.Web.Netmask, Settings.Web.Gateway);
NetworkAddressChanged(null, null);
}
}
}
#endif
#if MF_FRAMEWORK_VERSION_V4_2
#if BUILDIN_ETHERNET
static void NICCableConnectivityChanged(object sender, GHI.Premium.Net.EthernetBuiltIn.CableConnectivityEventArgs e)
#endif
#if ENC28J60
static void NICCableConnectivityChanged(object sender, EthernetENC28J60.CableConnectivityEventArgs e)
#endif
{
Active.Instance.SetActive();
if (IsConnected)
{
Log.WriteString(LogMessageType.Info, "Ethernet cable connected");
SetUpIPaddress();
}
else
{
Log.WriteString(LogMessageType.Info, "Ethernet cable disconnected");
// in case of static IP, network address change is not fired.. Call OnNetWorkDown which in turn shuts down the web server
if (Settings.Web.IP != "0.0.0.0")
{
// force address change event
_nic.NetworkInterface.EnableStaticIP("0.0.0.0", Settings.Web.Netmask, Settings.Web.Gateway);
NetworkAddressChanged(null, null);
}
}
}
#endif
// will not be fired in case of static IP
private static void NetworkAddressChanged(object sender, EventArgs e)
{
Active.Instance.SetActive();
if (_nic.NetworkInterface.IPAddress == "0.0.0.0")
{
Log.WriteString(LogMessageType.Info, "Network address changed: IP=0.0.0.0");
OnNetworkDown();
}
else
{
Log.WriteString(LogMessageType.Info,
"Network address changed: IP=" + _nic.NetworkInterface.IPAddress);
OnNetworkUp(_nic.NetworkInterface.IPAddress);
}
}
private static void SetUpIPaddress()
{
// do we need to use static or dynamic IP.. User setting 0.0.0.0 means use dynamic IP
var modIP = Settings.Web.IP[0] == '0' ? Settings.Web.IP.Substring(1) : Settings.Web.IP;
IPAddress ip = IPAddress.Parse(Settings.Web.IP); // multiple possibilities can be entered by the user so lets first convert and then test for 0 IP
if (ip.ToString() == "0.0.0.0")
{
GetDynmicIP();
}
else
{
// we use statics ip. Just set it if the current static IP is different as defined in user settings
// this reduces the number of writes to flash memory (netmf 4.2 has issues aftern n writes to config memory)
// if (_nic.NetworkInterface.IPAddress != Settings.Web.IP || _nic.NetworkInterface.GatewayAddress != Settings.Web.Gateway || _nic.NetworkInterface.SubnetMask != Settings.Web.Netmask)
// {
Log.WriteString(LogMessageType.Info, "Set static DNS's");
_nic.NetworkInterface.EnableStaticDns(new[] { "8.8.8.8", "8.8.4.4" });
Log.WriteString(LogMessageType.Info, "Set static IP: " + Settings.Web.IP);
_nic.NetworkInterface.EnableStaticIP(modIP, Settings.Web.Netmask, Settings.Web.Gateway);
while (Equals(IPAddress.GetDefaultLocalAddress(), IPAddress.Any))
{
Debug.Print("IP address is not set yet.");
Thread.Sleep(25);
}
OnNetworkUp(_nic.NetworkInterface.IPAddress);
//}
//else
//{
// OnNetworkUp(_nic.NetworkInterface.IPAddress);
// Log.WriteString(LogMessageType.Info, "System has static IP: " + _nic.NetworkInterface.IPAddress);
//}
}
}
private static void GetDynmicIP()
{
if (!_nic.NetworkInterface.IsDhcpEnabled)
{
_nic.NetworkInterface.EnableDynamicDns(); // 2014-02-11 RvS Added (device could have been switched from static IP to static IP)
_nic.NetworkInterface.EnableDhcp();
Log.WriteString(LogMessageType.Info, "EnableDhcp");
}
else
{
_nic.NetworkInterface.EnableDynamicDns(); // 2014-02-11 RvS Added
_nic.NetworkInterface.RenewDhcpLease();
Log.WriteString(LogMessageType.Info, "RenewDhcpLease");
}
while (Equals(IPAddress.GetDefaultLocalAddress(), IPAddress.Any))
{
Debug.Print("IP address is not set yet.");
Thread.Sleep(50);
}
}
}
} |
using System;
namespace OnlineTrainTicketBooking
{
class User
{
public string UserName { get; set; }
public string Password { get; set; }
public DateTime DateOfBirth { get; set; }
public long MobileNumber{ get; set; }
public User(string UserName,string password, DateTime dateofbirth, long mobileNumber)
{
this.UserName = UserName;
this.Password = password;
this.DateOfBirth = dateofbirth;
this.MobileNumber = mobileNumber;
}
}
}
|
using System.Data;
using System.Data.SqlClient;
using System.IO;
using kpi_lab6.Comparers;
namespace kpi_lab6
{
public class SimpleTblExporter
{
public static void ExportWhereOrderBy()
{
var csvFilePath = @$"{Settings.Path}\Export.csv";
var connectionString = "Server=tcp:blogproject.database.windows.net,1433;Initial Catalog=BlogDB;Persist Security Info=False;User ID=hopping;Password=1NnOoVVII;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
var sqlExpression = "SELECT * FROM Articles WHERE BlogId = 1 ORDER BY Id";
using var connection = new SqlConnection(connectionString);
using var writer = new StreamWriter(csvFilePath);
connection.Open();
var command = new SqlCommand(sqlExpression, connection);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
writer.WriteLine("id,title");
while (reader.Read())
{
var id = reader.GetInt32("Id");
var name = reader.GetString("Title");
writer.WriteLine($"{id},{name}");
}
reader.Close();
}
}
public static void ExportGroupBy()
{
var csvFilePath = @$"{Settings.Path}\Export2.csv";
var connectionString = "Server=tcp:blogproject.database.windows.net,1433;Initial Catalog=BlogDB;Persist Security Info=False;User ID=hopping;Password=1NnOoVVII;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
var sqlExpression = "SELECT BlogId, Name, ArticlesCount FROM Blogs B JOIN (SELECT BlogId, Count(*) AS ArticlesCount FROM Articles GROUP BY BlogId) A ON A.BlogId = B.Id";
using var connection = new SqlConnection(connectionString);
using var writer = new StreamWriter(csvFilePath);
connection.Open();
var command = new SqlCommand(sqlExpression, connection);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
writer.WriteLine("blogId,name,articlesCount");
while (reader.Read())
{
var id = reader.GetInt32("BlogId");
var name = reader.GetString("Name");
var count = reader.GetInt32("ArticlesCount");
writer.WriteLine($"{id},{name},{count}");
}
reader.Close();
}
}
}
} |
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Fluid;
using Kuli.Configuration;
using Kuli.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Kuli.Importing
{
public class TemplateImportService
{
private readonly ILogger<TemplateImportService> _logger;
private readonly DirectoryOptions _options;
private readonly SiteRenderingContext _siteRenderingContext;
public TemplateImportService(IOptions<DirectoryOptions> options, ILogger<TemplateImportService> logger,
SiteRenderingContext siteContext)
{
_logger = logger;
_siteRenderingContext = siteContext;
_options = options.Value;
}
public async Task ImportTemplatesAsync(CancellationToken cancellationToken)
{
var sw = Stopwatch.StartNew();
var basePath = Path.GetFullPath(_options.Templates);
_logger.LogInformation("Importing templates in {path}", basePath);
var files = Directory.GetFiles(basePath, "*.liquid", SearchOption.AllDirectories);
foreach (var file in files)
{
_logger.LogDebug("Importing {file}", file);
var content = await File.ReadAllTextAsync(file, cancellationToken);
if (FluidTemplate.TryParse(content, out var template))
{
var templateName = Path.GetFileNameWithoutExtension(file);
_siteRenderingContext.Templates[templateName] = template;
}
else
{
_logger.LogWarning("Failed to parse template {file}", file);
}
}
sw.Stop();
_logger.LogInformation("Imported {count} templates in {time}ms", _siteRenderingContext.Templates.Count,
sw.ElapsedMilliseconds);
}
}
} |
using System;
namespace Ejercicios
{
class Program
{
static void Main(string[] args)
{
int opc = 0;
do
{
Console.Write("Escoge una opción:\n"
+ "Invertir una cadena (1)\n"
+ "Juntar un Array (2)\n"
+ "Remover los caracteres que se repitan (3)\n"
+ "Ingresa una opción :");
opc = int.Parse(Console.ReadLine());
switch (opc)
{
case 1:
string cadena;
Console.Write("Ingresa una cadena:");
cadena = Console.ReadLine();
Console.WriteLine(InvertirString(cadena));
break;
case 2:
/* Notar que en la sección fuera del método principal se encuentran funciones extras para poder realizar esta opción */
Console.WriteLine("Sumando Arreglos");
int[] ArrayA = { 0, 1, 2, 3, 4 };
int[] ArrayB = { 5, 6, 7, 8 };
int[] ArrayAB = new int[(ArrayA.Length + ArrayB.Length)];
JuntarArreglo(ArrayA, ArrayB, ArrayAB);
break;
case 3:
String CadenaRepetida;
Console.Write("Ingresa una cadena:");
CadenaRepetida = Console.ReadLine();
Console.WriteLine(BorrarRepetidos(CadenaRepetida));
break;
}
} while (opc == 4);
}
private static string BorrarRepetidos(string cadenaRepetida)
{
string cadenaNueva = "";
int comodin = 0;
int[] cont = new int[cadenaRepetida.Length - 1];
/* varificar el caso 1 si no tiene elementos repetidos */
for (int i = 0; i < cadenaRepetida.Length - 1; i++)
{
for (int j = 0; j <= cadenaRepetida.Length - 1; j++)
{
if (cadenaRepetida[i] == cadenaRepetida[j])
{
cont[i] += 1;
comodin += 1;
continue;
}
else
{
comodin += 1;
continue;
}
}
}
for (int i = 0; i <= cont.Length - 1; i++)
{
if(cont[i] != cont[comodin]){
}
}
return cadenaNueva;
}
/* Invierte una cade de caracteres (Ejercicio #1) */
public static string InvertirString(string cadena)
{
string resultado = "";
for (int i = cadena.Length - 1; i >= 0; i--)
{
resultado = resultado + cadena[i].ToString();
}
return resultado;
}
/* Dado dos arreglos, ordenados, luego juntar los arreglos y ordenarlos */
public static void JuntarArreglo(int[] ArrayA, int[] ArrayB, int[] ArrayAB)
{
/* llenando el ArrayAB con los datos de los dos Array's */
int comodin = ArrayA.Length - 1;
try
{
for (int i = 0; i <= ArrayA.Length - 1; i++)
{
ArrayAB[i] = ArrayA[i];
}
for (int i = 0; i <= ArrayB.Length - 1; i++)
{
comodin += 1;
ArrayAB[comodin] = ArrayB[i];
Console.WriteLine(ArrayAB[comodin]);
Console.ReadKey();
}
}
catch (System.Exception)
{
throw;
}
Array.Sort(ArrayAB);
/* mostrar el arreglo ya ordenado */
for (int i = 0; i <= ArrayAB.Length - 1; i++)
{
Console.WriteLine("El ArrayAB tiene como resultado en la posición {0}: " + ArrayAB[i], i);
}
}
public static int[] OrdenarArreglo(int[] array)
{
Array.Sort(array);
return array;
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using PleaseThem.Controls;
using PleaseThem.States;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PleaseThem.Buildings
{
public class Lumber : Building
{
public override Rectangle CollisionRectangle
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, FrameWidth, _texture.Height - 32);
}
}
public override string[] Content => new string[] { $"Minions: {CurrentMinions}/{MaxMinions}" };
public Lumber(GameState parent, Texture2D texture, int frameCount)
: base(parent, texture, frameCount)
{
Resources = new Models.Resources()
{
Food = 25,
Wood = 50,
Stone = 0,
Gold = 0,
};
MinionColor = Color.Brown;
TileType = Tiles.TileType.Tree;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
}
}
|
using System;
namespace Aut.Lab.lab09
{
class lab09Application
{
public void Run()
{
Console.Write("Enter 2 point : ");
string twopoint = Console.ReadLine();
string[] arrpoint = twopoint.Split('|');
Point p1 = new Point(arrpoint[0]);
Point p2 = new Point(arrpoint[1]);
Line l1 = new Line(p1,p2);
string cmd = "";
while(cmd != "exist")
{
Console.Write("Please enter command : ");
string command = Console.ReadLine();
string[]splitcmd = command.Split(' ');
cmd = splitcmd[0];
if(cmd.Equals("length"))
{
double length = l1.Length();
Console.WriteLine("Length = {0}",length);
}
else if(cmd.Equals("slope"))
{
double slope = l1.Slope();
if(slope == -0)
{
Console.WriteLine("Slope = 0");
}
else
{
Console.WriteLine("Slope = {0}",slope);
}
}
else if(cmd.Equals("exit"))
{
return;
}
else if(cmd.Equals("showc"))
{
double length = l1.Length();
double slope = l1.Slope();
l1.ShowC(slope);
}
else if(cmd.Equals("show"))
{
double length = l1.Length();
double slope = l1.Slope();
Console.WriteLine("Length = {0}",length);
if(slope == -0)
{
Console.WriteLine("Slope = 0");
}
else
{
Console.WriteLine("Slope = {0}",slope);
}
l1.ShowC(slope);
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Labb1.Models;
using Labb1.Services;
using Labb1.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace Labb1.Controllers
{
public class OrderController : Controller
{
private readonly string _cartName;
private readonly UserManager<User> _userManager;
private readonly OrderApiHandler _orderApiHandler;
private readonly string _apiRootUrl;
public OrderController(IConfiguration config,UserManager<User> userManager,OrderApiHandler orderapiHandler)
{
this._cartName = config["CartSessionCookie:Name"];
this._userManager = userManager;
this._orderApiHandler = orderapiHandler;
_apiRootUrl = config.GetValue(typeof(string), "OrderApiRoot").ToString();
}
//Assigning values to Order object and calling OrderService to store the Order object
[Authorize]
[HttpPost]
public async Task<IActionResult> CreateOrder([Bind("TotalPrice,productlist")] ShoppingCart form)
{
OrderViewModel vm = new OrderViewModel();
//generate unique orderid (if the order contains different productid, the orderid is unique for that Order)
Guid oriderid = Guid.NewGuid();
var productlist = form.productlist;
Order createorder = null;
//assigning values for the Order object.
foreach (var item in productlist)
{
createorder = new Order()
{
OrderId = oriderid,
OrderDate = DateTime.Now,
UserId = Guid.Parse(_userManager.GetUserId(User)),
ProductId=item.Product.id
};
//calling OrderSevice for storing the Order object
await _orderApiHandler.PostAsync<Order>(createorder, $"{_apiRootUrl}CreateOrder");
}
//assigning totalitems to the order object
int totalitems = 0;
foreach (var item in productlist)
{
totalitems += item.Amount;
}
createorder.TotalItems = totalitems;
//assigning totalprice to the order object
createorder.TotalPrice = form.TotalPrice;
//assigning productlist to the order object
createorder.ProductsList = form.productlist;
//Retriving user information
User user = await _userManager.GetUserAsync(User);
vm.User = user;
//assinging order object to viewmodel
vm.Order = createorder;
//Clear the session cookies once the order is created
if (HttpContext.Session.GetString(_cartName) != null)
HttpContext.Session.Remove(_cartName);
return View(vm);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace FuiteAPI
{
/// <summary>
/// Représente le résultat d'une opération renvoyé à un utilisateur
/// </summary>
[DataContract]
public class Result
{
public Result()
{
this.Code = 0;
this.Message = "OK";
}
public Result(int code, string msg)
{
this.Code = code;
this.Message = msg;
}
[DataMember]
public string Message
{
get; set;
}
/// <summary>
/// Code de résultat, 0 si ok, autre sinon
/// </summary>
[DataMember]
public int Code
{
get;set;
}
}
/// <summary>
/// Représente le résultat d'une opération de récupération de un ou plusieurs reports
/// </summary>
[DataContract]
public class ResultReports : Result
{
/// <summary>
/// Liste des reports contenus dans la réponse
/// </summary>
[DataMember]
public ReportRequest[] Data
{
get; set;
}
}
/// <summary>
/// Représente le résultat d'une opération de récupération de photographies
/// </summary>
[DataContract]
public class ResultPictures : Result
{
/// <summary>
/// Liste des photographies
/// </summary>
[DataMember]
public Picture[] Data
{
get;set;
}
}
/// <summary>
/// Représente le résultat d'une opérations de récupération de changements
/// </summary>
[DataContract]
public class ResultChanges : Result
{
/// <summary>
/// Liste des changements
/// </summary>
[DataMember]
public Change[] Data
{
get; set;
}
}
} |
using UnityEngine;
using System.Collections;
namespace Ph.Bouncer
{
public static class MaterialHelper
{
public static void SetAlpha(GameObject obj, float alpha)
{
obj.renderer.material.color = obj.renderer.material.color.SetAlpha(alpha);
}
}
} |
using System.Windows.Forms;
using System.Collections.Generic;
using System.IO;
using QuanLyTiemGiatLa.Xuly;
namespace QuanLyTiemGiatLa.HeThong
{
public partial class frmCauHinhGhiChu : Form
{
private List<string> _dsGhiChu;
private string _fileName;
public frmCauHinhGhiChu(List<string> listghichu, string fileName)
{
InitializeComponent();
this.Load += new System.EventHandler(frmCauHinhGhiChu_Load);
_dsGhiChu = listghichu;
_fileName = fileName;
dgvGhiChu.AutoGenerateColumns = false;
}
private void frmCauHinhGhiChu_Load(object sender, System.EventArgs e)
{
for (int i = 0; i < _dsGhiChu.Count; i++)
{
dgvGhiChu.Rows.Add(_dsGhiChu[i]);
}
txtKCGhiChu.Text = ThaoTacIniCauHinhGhiChu.ReadKCGhiChu().ToString();
txtChieuNgangForm.Text = ThaoTacIniCauHinhGhiChu.ReadChieuNgangForm().ToString();
}
private void btnThoat_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnGhi_Click(object sender, System.EventArgs e)
{
using (StreamWriter outfile = new StreamWriter(_fileName, false, System.Text.Encoding.Unicode))
{
for (int i = 0; i < dgvGhiChu.Rows.Count - 1; i++)
{
string s = dgvGhiChu[0, i].Value.ToString().Trim();
if (string.IsNullOrEmpty(s)) break;
outfile.WriteLine(s);
}
outfile.Close();
}
int kcghichu, chieungangform;
int.TryParse(txtKCGhiChu.Text, out kcghichu);
int.TryParse(txtChieuNgangForm.Text, out chieungangform);
ThaoTacIniCauHinhGhiChu.Write(kcghichu, chieungangform);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GeradorZumbi : MonoBehaviour
{
public GameObject zumbi;
private float contadorTempo = 0;
public float tempoGerarZumbi = 1;
void Start()
{
}
void Update()
{
contadorTempo += Time.deltaTime;
if (contadorTempo >= tempoGerarZumbi)
{
Instantiate(zumbi, transform.position, transform.rotation);
contadorTempo = 0;
}
}
}
|
using System;
namespace WpfReduxSample
{
public class Reducer
{
public static State OnIncrement(State state, IncrementAction _)
{
return state with
{
Counter = Math.Min(state.Counter + 1, 999),
};
}
public static State OnDecrement(State state, DecrementAction _)
{
return state with
{
Counter = Math.Max(state.Counter - 1, 0),
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ShoesOnContainer.Web.ClientApp.Models
{
/// <summary>
/// Get / set catalog
/// </summary>
public class Catalog
{
public int PageIndex { get; set; }
public int PageSize { get; set; }
public int Count { get; set; }
public List<CatalogItem> Data { get; set; }
}
}
|
using Dynamia.BillingSystem.BusinessManager;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Dynamia.BillingSystem.SQLDAO
{
public class DAOQuote
{
#region Fields
private SqlConnection connect = null;
private SqlCommand cmd = null;
#endregion
#region Methods
public void UpdateQuote(BOQuote quote)
{
string id = quote.id;
string status = quote.status;
//DateTime annulationDate = quote.annulationDate;
try
{
using (connect = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["CurrentConnection"]].ConnectionString))
{
using (cmd = new SqlCommand("spr_UpdateBillingQuoteStatus", connect))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = connect.ConnectionTimeout;
cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
connect.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
string message = "Se presento un error en el proceso de facturacion: " + e.Message + ". quote: " + id;
DAOFacade daoFacade = new DAOFacade();
daoFacade.InsertErrorLog(message);
throw e;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ItlaSocial.Models.ApplicationViewModels
{
public class PublicationViewModel
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
public string Description { get; set; }
[Required]
public PrivacyLevel PrivacyLevel { get; set; } = PrivacyLevel.Public;
[Required]
[DataType(DataType.Date)]
public DateTime Date { get; set; } = DateTime.UtcNow;
[Required]
public bool Reported { get; set; } = false;
[Required]
public bool Deleted { get; set; } = false;
public virtual ApplicationUserViewModel ApplicationUser { get; set; }
public virtual ICollection<PublicationViewModel> Shares { get; set; }
public virtual ICollection<PublicationLike> Likes { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual Publication SharedPublication { get; set; }
public virtual ICollection<PublicationMediaViewModel> PublicationMedia { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreDemos.Services;
using Microsoft.AspNetCore.Mvc;
namespace DotNetCoreDemos.Controllers
{
public class CalculateController : Controller
{
ICalculate calculate;
public CalculateController(ICalculate calculate)
{
this.calculate = calculate;
}
public IActionResult Index()
{
return View();
}
public string KDV()
{
return calculate.Calculate(100).ToString();
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Newtonsoft.Json;
namespace Dnn.PersonaBar.Extensions.Components.Dto
{
[JsonObject]
public class PackageFilesQueryDto : PackageInfoDto
{
[JsonProperty("packageFolder")]
public string PackageFolder { get; set; }
[JsonProperty("includeSource")]
public bool IncludeSource { get; set; }
[JsonProperty("includeAppCode")]
public bool IncludeAppCode { get; set; }
}
}
|
using JCFruit.WeebChat.Server.Tcp;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace JCFruit.WeebChat.Server.Services
{
public class DebugConnectionHandler : IConnectionHandler
{
private readonly ILogger _logger;
public DebugConnectionHandler(ILogger<DebugConnectionHandler> logger)
{
_logger = logger;
}
public Task OnClientConnected(ConnectedClient client)
{
//_logger.LogInformation("OnClientConnected: {clientId}", client.ClientId);
return Task.CompletedTask;
}
public Task OnClientDisconnected(string clientId)
{
//_logger.LogInformation("OnClientDisconnected: {clientId}", clientId);
return Task.CompletedTask;
}
public Task OnMessageReceived(string clientId, ReadOnlySpan<byte> data)
{
var message = data.Length;//Encoding.UTF8.GetString(data);
var arr = data.ToArray();
var errors = arr.Any(x => x == 0);
_logger.LogInformation("OnMessageReceived: {message}. Errors = {errors}", message, errors);
return Task.CompletedTask;
}
}
}
|
using NHibernate.Mapping.ByCode.Conformist;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestInheritance.DomainModels;
namespace TestInheritance.DomainModelMappings
{
public class EmployeeMapping : JoinedSubclassMapping<Employee>
{
public EmployeeMapping()
{
Table("HumanResources.Employee");
Key(k => k.Column("BusinessEntityID"));
Property(x => x.NationalIDNumber);
Property(x => x.JobTitle);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using UnityEngine.SceneManagement;
public class OnPlaySceneLoadManager : MonoBehaviour
{
public SpaceshipController spaceship;
public void Awake()
{
if (PlayerPrefs.HasKey("Spaceship"))
{
SpaceshipData data = JsonConvert.DeserializeObject<SpaceshipData>(PlayerPrefs.GetString("Spaceship"), new SpaceshipDataToJsonConverter());
int count = 0;
foreach (BuiltPart part in data.BuiltParts)
{
if (part.part != null)
{
count++;
}
}
spaceship.LoadSpaceship(data);
}
}
}
|
using System.Collections.Generic;
using Esperecyan.UniVRMExtensions.Utilities;
using UnityEngine;
using VRM;
namespace Esperecyan.UniVRMExtensions.CopyVRMSettingsComponents
{
internal class CopyFirstPerson
{
/// <summary>
/// 一人称表示の設定をコピーします。
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
/// <param name="sourceSkeletonBones"></param>
internal static void Copy(
GameObject source,
GameObject destination,
Dictionary<HumanBodyBones, Transform> sourceSkeletonBones
)
{
var sourceFirstPerson = source.GetComponent<VRMFirstPerson>();
var destinationFirstPerson = destination.GetComponent<VRMFirstPerson>();
if (!sourceFirstPerson)
{
if (destinationFirstPerson)
{
Object.DestroyImmediate(destinationFirstPerson);
}
return;
}
if (sourceFirstPerson.FirstPersonBone)
{
destinationFirstPerson.FirstPersonBone = BoneMapper.FindCorrespondingBone(
sourceBone: sourceFirstPerson.FirstPersonBone,
source: source,
destination: destination,
sourceSkeletonBones: sourceSkeletonBones
);
}
destinationFirstPerson.FirstPersonOffset = sourceFirstPerson.FirstPersonOffset;
foreach (VRMFirstPerson.RendererFirstPersonFlags sourceFlags in sourceFirstPerson.Renderers)
{
if (sourceFlags.FirstPersonFlag == FirstPersonFlag.Auto)
{
continue;
}
Mesh sourceMesh = sourceFlags.SharedMesh;
if (!sourceMesh)
{
continue;
}
var sourceMeshName = sourceMesh.name;
var index = destinationFirstPerson.Renderers.FindIndex(match: flags => {
Mesh destinationMesh = flags.SharedMesh;
return destinationMesh && destinationMesh.name == sourceMeshName;
});
if (index == -1)
{
continue;
}
var destinationFlags = destinationFirstPerson.Renderers[index];
destinationFlags.FirstPersonFlag = sourceFlags.FirstPersonFlag;
destinationFirstPerson.Renderers[index] = destinationFlags;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameFlow: IManageables
{
#region Singleton
private static GameFlow instance = null;
public GameFlow() { }
public static GameFlow Instance {
get
{
if (instance == null)
{
instance = new GameFlow();
}
return instance;
}
}
#endregion
public void Initialize()
{
EnemyManager.Instance.Initialize();
//PlayerManager.Instance.Initialize();
}
public void PostInitialize()
{
EnemyManager.Instance.PostInitialize();
// PlayerManager.Instance.PostInitialize();
}
public void Refresh()
{
EnemyManager.Instance.Refresh();
//PlayerManager.Instance.Refresh();
}
public void PhysicsRefresh()
{
EnemyManager.Instance.PhysicsRefresh();
//PlayerManager.Instance.PhysicsRefresh();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using EWF.Util;
using System.Reflection;
using EWF.Util.Options;
using Microsoft.Extensions.Logging;
using EWF.Util.Log;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace EWF.Application.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Access/Login";
options.LogoutPath = "/Access/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(120);//.FromHours(2);
});
//services.AddSession(options =>
//{
// options.IdleTimeout = TimeSpan.FromMinutes(15);
// options.Cookie.HttpOnly = true;
//});
//注入全局异常捕获
services.AddMvc(o =>
{
o.Filters.Add(typeof(GlobalExceptions));
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
services.Configure<DbOption>("Default_Option", Configuration.GetSection("Default_Option"));
services.Configure<DbOption>("File_Opion", Configuration.GetSection("File_Opion"));
services.Configure<DbOption>("RWDB_Opion", Configuration.GetSection("RWDB_Opion"));
services.Configure<DbOption>("RTDB_Opion", Configuration.GetSection("RTDB_Opion"));
services.Configure<DbOption>("newmanage_Opion", Configuration.GetSection("newmanage_Opion"));
//气象路径
services.Configure<WeaterConfig>("YbWeather", Configuration.GetSection("YbWeather"));
services.Configure<DataOption>("DataOption", Configuration.GetSection("MyDataOption"));
//(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.88)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl88)))
//批量注册服务
services.BatchRegisterService(new Assembly[] {
Assembly.GetExecutingAssembly(),
Assembly.Load("EWF.IRepository"),
//Assembly.Load("EWF.Repository.Oracle"),
Assembly.Load("EWF.Repository"),
Assembly.Load("EWF.IServices"),
Assembly.Load("EWF.Services")}, typeof(IDependency), ServiceLifetime.Transient);
//注册自定义日志服务
services.AddTransient<LoggerHelper>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//加载log4net中间件,替换默认的日志组件
loggerFactory.AddLog4Net();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
//app.UseSession();
app.UseAuthentication();
#region Route路由
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "RealData",
areaName: "RealData",
template: "RealData/{controller=Home}/{action=Index}/{id?}" );
routes.MapAreaRoute(
name: "StationInfo",
areaName: "StationInfo",
template: "StationInfo/{controller=Home}/{action=Index}/{id?}");
routes.MapAreaRoute(
name: "HistoryInfo",
areaName: "HistoryInfo",
template: "HistoryInfo/{controller=Home}/{action=Index}/{id?}");
routes.MapAreaRoute(
name: "MapVideo",
areaName: "MapVideo",
template: "MapVideo/{controller=Home}/{action=Index}/{id?}" );
routes.MapAreaRoute(
name: "SysManage",
areaName: "SysManage",
template: "SysManage/{controller=Home}/{action=Index}/{id?}" );
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
//template: "{controller=Home}/{action=Index}/{id?}");
template: "{controller=Access}/{action=Login}/{id?}");
});
#endregion
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Forms;
namespace Hunabku.VSPasteResurrected.OptionEditors
{
public static class WindowsControlsBindingExtensions
{
public static void Bind(this Form control, ViewModelBase model)
{
if (model == null)
{
return;
}
model.CloseRequest += (sender, args) => control.Close();
control.Closing += (sender, args) =>
{
args.Cancel = !model.CanClose();
};
control.FormClosed += (sender, args) => model.Dispose();
}
public static void Bind(this Button control, ICommand command)
{
command.PropertyChanged += (sender, args) =>
{
if ("CanExecute".Equals(args.PropertyName))
{
control.ThreadSafeInvoke(() => control.Enabled = command.CanExecute);
}
};
control.Enabled = command.CanExecute;
control.Click += (o, e) => command.Execute();
}
public static void BindValue<TModel, TProperty>(this TextBox control, TModel model, Expression<Func<TModel, TProperty>> value, DataSourceUpdateMode mode = DataSourceUpdateMode.OnPropertyChanged)
{
var propertyName = GetPlainPropertyName(control, value);
control.DataBindings.Add("Text", model, propertyName, false, mode);
}
public static void BindValue<TModel>(this CheckBox control, TModel model, Expression<Func<TModel, bool>> value)
{
var propertyName = GetPlainPropertyName(control, value);
control.DataBindings.Add("Checked", model, propertyName, false, DataSourceUpdateMode.OnPropertyChanged);
}
public static void BindValue<TModel, TProperty>(this NumericUpDown control, TModel model, Expression<Func<TModel, TProperty>> value, DataSourceUpdateMode mode = DataSourceUpdateMode.OnPropertyChanged)
{
var propertyName = GetPlainPropertyName(control, value);
control.DataBindings.Add("Value", model, propertyName, false, mode);
}
private static string GetPlainPropertyName<TModel, TProperty>(Control control, Expression<Func<TModel, TProperty>> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null)
{
throw new NotSupportedException($"Bind expression for {control.GetType().Name} control ({control.Name}) not supported.");
}
return memberExpression.Member.Name;
}
private static PropertyInfo GetPlainProperty<TModel, TProperty>(Control control, Expression<Func<TModel, TProperty>> expression)
{
MemberExpression memberExpression = null;
if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
if (memberExpression == null || memberExpression.Member.MemberType != MemberTypes.Property)
{
throw new NotSupportedException($"Bind expression for {control.GetType().Name} control ({control.Name}) not supported.");
}
return (PropertyInfo)memberExpression.Member;
}
public static void ThreadSafeInvoke(this Control source, Action method)
{
if (source.InvokeRequired)
{
source.BeginInvoke(method);
}
else
{
method();
}
}
}
} |
namespace OmniGui.Xaml
{
public enum LinkMode
{
TargetFollowsSource,
SourceFollowsTarget,
FullLink,
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class TitleSceneScript : MonoBehaviour
{
private bool scenechange;
private float timecount;
private Vector2 velo;
GameObject title;
GameObject button1;
GameObject button2;
RectTransform titletransform;
RectTransform buttontransform1;
RectTransform buttontransform2;
//タイトルのメインとなるキャンバス
[SerializeField] private GameObject main_canvas;
//ゲームの説明を記述するキャンバス
[SerializeField] private GameObject option_canvas;
// Start is called before the first frame update
void Start()
{
SoundManager.Instance.StartBGM(SoundManager.BGMType.FANFALE);
scenechange = false;
timecount = 0.5f;
velo = new Vector2(0, 0);
title = GameObject.Find("TitleText");
button1= GameObject.Find("StartButton");
button2 = GameObject.Find("OptionButton");
titletransform = title.GetComponent<RectTransform>();
buttontransform1 = button1.GetComponent<RectTransform>();
buttontransform2 = button2.GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
if (scenechange)
{
timecount -= Time.deltaTime;
titletransform.Translate(velo);
buttontransform1.Translate(velo);
buttontransform2.Translate(velo);
velo.y += 0.025f;
if (timecount < 0)
{
SceneManager.LoadScene(ConstNumbers.SCENE_NAME_GAME);
}
}
InputManager.KillGame();
}
public void OnClickGameStart()
{
scenechange = true;
}
public void OnClickOptionButton()
{
main_canvas.SetActive(false);
option_canvas.SetActive(true);
}
public void OnClickBackTitleButton()
{
main_canvas.SetActive(true);
option_canvas.SetActive(false);
}
}
|
/***********************
@ author:zlong
@ Date:2015-01-11
@ Desc:业务招待费用界面层
* ********************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DriveMgr;
using DriveMgr.BLL;
namespace DriveMgr.WebUI.FinancialMgr
{
/// <summary>
/// bg_businessEntertainHandler 的摘要说明
/// </summary>
public class bg_businessEntertainHandler : IHttpHandler
{
DriveMgr.Model.UserOperateLog userOperateLog = null; //操作日志对象
BusinessEntertainBLL businessEntertainBll = new BusinessEntertainBLL();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string action = context.Request.Params["action"];
try
{
DriveMgr.Model.User userFromCookie = DriveMgr.Common.UserHelper.GetUser(context); //获取cookie里的用户对象
userOperateLog = new Model.UserOperateLog();
userOperateLog.UserIp = context.Request.UserHostAddress;
userOperateLog.UserName = userFromCookie.UserId;
switch (action)
{
case "search":
SearchBusinessEntertain(context);
break;
case "add":
AddBusinessEntertain(userFromCookie, context);
break;
case "edit":
EditBusinessEntertain(userFromCookie, context);
break;
case "delete":
DelBusinessEntertain(userFromCookie, context);
break;
default:
context.Response.Write("{\"msg\":\"参数错误!\",\"success\":false}");
break;
}
}
catch (Exception ex)
{
context.Response.Write("{\"msg\":\"" + DriveMgr.Common.JsonHelper.StringFilter(ex.Message) + "\",\"success\":false}");
userOperateLog.OperateInfo = "用户功能异常";
userOperateLog.IfSuccess = false;
userOperateLog.Description = DriveMgr.Common.JsonHelper.StringFilter(ex.Message);
DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog);
}
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 查询业务招待费用
/// </summary>
/// <param name="context"></param>
private void SearchBusinessEntertain(HttpContext context)
{
string sort = context.Request.Params["sort"]; //排序列
string order = context.Request.Params["order"]; //排序方式 asc或者desc
int pageindex = int.Parse(context.Request.Params["page"]);
int pagesize = int.Parse(context.Request.Params["rows"]);
string ui_businessEntertain_entertainObject = context.Request.Params["ui_businessEntertain_entertainObject"] ?? "";
string ui_businessEntertain_entertainUse = context.Request.Params["ui_businessEntertain_entertainUse"] ?? "";
string ui_businessEntertain_transactor = context.Request.Params["ui_businessEntertain_transactor"] ?? "";
string ui_businessEntertain_createStartDate = context.Request.Params["ui_businessEntertain_createStartDate"] ?? "";
string ui_businessEntertain_createEndDate = context.Request.Params["ui_businessEntertain_createEndDate"] ?? "";
int totalCount; //输出参数
string strJson = businessEntertainBll.GetPagerData(ui_businessEntertain_entertainObject, ui_businessEntertain_entertainUse, ui_businessEntertain_transactor,
ui_businessEntertain_createStartDate, ui_businessEntertain_createEndDate, sort + " " + order, pagesize, pageindex, out totalCount);
context.Response.Write("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
userOperateLog.OperateInfo = "查询业务招待费用";
userOperateLog.IfSuccess = true;
userOperateLog.Description = "排序:" + sort + " " + order + " 页码/每页大小:" + pageindex + " " + pagesize;
DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog);
}
/// <summary>
/// 添加业务招待费用
/// </summary>
/// <param name="userFromCookie"></param>
/// <param name="context"></param>
private void AddBusinessEntertain(DriveMgr.Model.User userFromCookie, HttpContext context)
{
if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("businessEntertain", "add", userFromCookie.Id))
{
string ui_businessEntertain_EntertainObject_add = context.Request.Params["ui_businessEntertain_EntertainObject_add"] ?? "";
string ui_businessEntertain_EntertainUse_add = context.Request.Params["ui_businessEntertain_EntertainUse_add"] ?? "";
string ui_businessEntertain_Transactor_add = context.Request.Params["ui_businessEntertain_Transactor_add"] ?? "";
string ui_businessEntertain_EntertainAmount_add = context.Request.Params["ui_businessEntertain_EntertainAmount_add"] ?? "";
string ui_businessEntertain_TransactDate_add = context.Request.Params["ui_businessEntertain_TransactDate_add"] ?? "";
string ui_businessEntertain_Remark_add = context.Request.Params["ui_businessEntertain_Remark_add"] ?? "";
DriveMgr.Model.BusinessEntertainModel businessEntertainAdd = new Model.BusinessEntertainModel();
businessEntertainAdd.EntertainObject = ui_businessEntertain_EntertainObject_add.Trim();
businessEntertainAdd.EntertainUse = ui_businessEntertain_EntertainUse_add.Trim();
businessEntertainAdd.Transactor = ui_businessEntertain_Transactor_add.Trim();
businessEntertainAdd.EntertainAmount = decimal.Parse(ui_businessEntertain_EntertainAmount_add);
businessEntertainAdd.TransactDate = DateTime.Parse(ui_businessEntertain_TransactDate_add);
businessEntertainAdd.Remark = ui_businessEntertain_Remark_add.Trim();
businessEntertainAdd.CreateDate = DateTime.Now;
businessEntertainAdd.CreatePerson = userFromCookie.UserId;
businessEntertainAdd.UpdatePerson = userFromCookie.UserId;
businessEntertainAdd.UpdateDate = DateTime.Now;
if (businessEntertainBll.AddBusinessEntertain(businessEntertainAdd))
{
userOperateLog.OperateInfo = "添加业务招待费用";
userOperateLog.IfSuccess = true;
userOperateLog.Description = "添加成功,招待对象:" + ui_businessEntertain_EntertainObject_add.Trim();
context.Response.Write("{\"msg\":\"添加成功!\",\"success\":true}");
}
else
{
userOperateLog.OperateInfo = "添加业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "添加失败";
context.Response.Write("{\"msg\":\"添加失败!\",\"success\":false}");
}
}
else
{
userOperateLog.OperateInfo = "添加业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "无权限,请联系管理员";
context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}");
}
DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog);
}
/// <summary>
/// 编辑业务招待费用
/// </summary>
/// <param name="userFromCookie"></param>
/// <param name="context"></param>
private void EditBusinessEntertain(DriveMgr.Model.User userFromCookie, HttpContext context)
{
if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("businessEntertain", "edit", userFromCookie.Id))
{
int id = Convert.ToInt32(context.Request.Params["id"]);
DriveMgr.Model.BusinessEntertainModel businessEntertainEdit = businessEntertainBll.GetBusinessEntertainModel(id);
string ui_businessEntertain_EntertainObject_edit = context.Request.Params["ui_businessEntertain_EntertainObject_edit"] ?? "";
string ui_businessEntertain_EntertainUse_edit = context.Request.Params["ui_businessEntertain_EntertainUse_edit"] ?? "";
string ui_businessEntertain_Transactor_edit = context.Request.Params["ui_businessEntertain_Transactor_edit"] ?? "";
string ui_businessEntertain_EntertainAmount_edit = context.Request.Params["ui_businessEntertain_EntertainAmount_edit"] ?? "";
string ui_businessEntertain_TransactDate_edit = context.Request.Params["ui_businessEntertain_TransactDate_edit"] ?? "";
string ui_businessEntertain_Remark_edit = context.Request.Params["ui_businessEntertain_Remark_edit"] ?? "";
businessEntertainEdit.EntertainObject = ui_businessEntertain_EntertainObject_edit.Trim();
businessEntertainEdit.EntertainUse = ui_businessEntertain_EntertainUse_edit.Trim();
businessEntertainEdit.Transactor = ui_businessEntertain_Transactor_edit.Trim();
businessEntertainEdit.EntertainAmount = decimal.Parse(ui_businessEntertain_EntertainAmount_edit);
businessEntertainEdit.TransactDate = DateTime.Parse(ui_businessEntertain_TransactDate_edit);
businessEntertainEdit.Remark = ui_businessEntertain_Remark_edit.Trim();
businessEntertainEdit.UpdatePerson = userFromCookie.UserId;
businessEntertainEdit.UpdateDate = DateTime.Now;
if (businessEntertainBll.UpdateBusinessEntertain(businessEntertainEdit))
{
userOperateLog.OperateInfo = "修改业务招待费用";
userOperateLog.IfSuccess = true;
userOperateLog.Description = "修改成功,业务招待费用主键:" + businessEntertainEdit.Id;
context.Response.Write("{\"msg\":\"修改成功!\",\"success\":true}");
}
else
{
userOperateLog.OperateInfo = "修改业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "修改失败";
context.Response.Write("{\"msg\":\"修改失败!\",\"success\":false}");
}
}
else
{
userOperateLog.OperateInfo = "修改业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "无权限,请联系管理员";
context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}");
}
DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog);
}
/// <summary>
/// 删除业务招待费用
/// </summary>
/// <param name="userFromCookie"></param>
/// <param name="context"></param>
private void DelBusinessEntertain(DriveMgr.Model.User userFromCookie, HttpContext context)
{
if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("businessEntertain", "delete", userFromCookie.Id))
{
string ids = context.Request.Params["id"].Trim(',');
if (businessEntertainBll.DeleteBusinessEntertainList(ids))
{
userOperateLog.OperateInfo = "删除业务招待费用";
userOperateLog.IfSuccess = true;
userOperateLog.Description = "删除成功,业务招待费用主键:" + ids;
context.Response.Write("{\"msg\":\"删除成功!\",\"success\":true}");
}
else
{
userOperateLog.OperateInfo = "删除业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "删除失败";
context.Response.Write("{\"msg\":\"删除失败!\",\"success\":false}");
}
}
else
{
userOperateLog.OperateInfo = "删除业务招待费用";
userOperateLog.IfSuccess = false;
userOperateLog.Description = "无权限,请联系管理员";
context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}");
}
DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog);
}
}
} |
//
// Copyright 2010, 2020 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// 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 Carbonfrost.Commons.Core;
namespace Carbonfrost.Commons.PropertyTrees {
public class PropertyTreeWriterSettings {
private bool _includeMetadata;
private bool _isReadOnly;
public bool IncludeMetadata {
get {
return _includeMetadata;
}
set {
ThrowIfReadOnly();
_includeMetadata = value;
}
}
public bool IsReadOnly {
get {
return _isReadOnly;
}
}
public PropertyTreeWriterSettings() {
}
public PropertyTreeWriterSettings(PropertyTreeWriterSettings other) {
if (other != null) {
IncludeMetadata = other.IncludeMetadata;
}
}
public PropertyTreeWriterSettings Clone() {
return CloneCore();
}
protected virtual PropertyTreeWriterSettings CloneCore() {
return new PropertyTreeWriterSettings(this);
}
public void MakeReadOnly() {
_isReadOnly = true;
}
protected void ThrowIfReadOnly() {
if (IsReadOnly) {
throw Failure.ReadOnlyCollection();
}
}
}
}
|
namespace ShadowAPI.Models
{
public class FundTransaction : NamedEntity
{
public long Value { get; set; }
public FundTransaction PreviousTransaction { get; set; }
public long CurrentValue // Perhaps method, if conflicts with table struture
{
get
{
return Value + PreviousTransaction.Value;
//... Hmmm have to figure out smart way to chain Transaction without pulling out all the history of previous transaction and just getting the current value as a variable...
}
}
}
} |
//namespace OCP
//{
///**
// * @since 8.2.0
// */
// class SabrePluginEvent extends Event {
//
// /** @var int */
// protected statusCode;
//
// /** @var string */
// protected message;
//
// /** @var Server */
// protected server;
//
// /**
// * @since 8.2.0
// */
// public function __construct(server = null) {
// this.message = '';
// this.statusCode = Http::STATUS_OK;
// this.server = server;
// }
//
// /**
// * @param int statusCode
// * @return self
// * @since 8.2.0
// */
// public function setStatusCode(statusCode) {
// this.statusCode = (int) statusCode;
// return this;
// }
//
// /**
// * @param string message
// * @return self
// * @since 8.2.0
// */
// public function setMessage(message) {
// this.message = (string) message;
// return this;
// }
//
// /**
// * @return int
// * @since 8.2.0
// */
// public function getStatusCode() {
// return this.statusCode;
// }
//
// /**
// * @return string
// * @since 8.2.0
// */
// public function getMessage() {
// return this.message;
// }
//
// /**
// * @return null|Server
// * @since 9.0.0
// */
// public function getServer() {
// return this.server;
// }
// }
//} |
// 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using NuGet.Frameworks;
using NuGet.Packaging.Core;
using NuGet.Versioning;
namespace NuGet.Packaging
{
/// <summary>
/// Reads .nuspec files
/// </summary>
public class NuspecReader : NuspecCoreReaderBase
{
// node names
private const string Dependencies = "dependencies";
private const string Group = "group";
private const string TargetFramework = "targetFramework";
private const string Dependency = "dependency";
private const string References = "references";
private const string Reference = "reference";
private const string File = "file";
private const string FrameworkAssemblies = "frameworkAssemblies";
private const string FrameworkAssembly = "frameworkAssembly";
private const string AssemblyName = "assemblyName";
private const string Language = "language";
private readonly IFrameworkNameProvider _frameworkProvider;
/// <summary>
/// Nuspec file reader
/// </summary>
/// <param name="stream">Nuspec file stream.</param>
public NuspecReader(Stream stream)
: this(stream, DefaultFrameworkNameProvider.Instance)
{
}
/// <summary>
/// Nuspec file reader
/// </summary>
/// <param name="xml">Nuspec file xml data.</param>
public NuspecReader(XDocument xml)
: this(xml, DefaultFrameworkNameProvider.Instance)
{
}
/// <summary>
/// Nuspec file reader
/// </summary>
/// <param name="stream">Nuspec file stream.</param>
/// <param name="frameworkProvider">Framework mapping provider for NuGetFramework parsing.</param>
public NuspecReader(Stream stream, IFrameworkNameProvider frameworkProvider)
: base(stream)
{
_frameworkProvider = frameworkProvider;
}
/// <summary>
/// Nuspec file reader
/// </summary>
/// <param name="xml">Nuspec file xml data.</param>
/// <param name="frameworkProvider">Framework mapping provider for NuGetFramework parsing.</param>
public NuspecReader(XDocument xml, IFrameworkNameProvider frameworkProvider)
: base(xml)
{
_frameworkProvider = frameworkProvider;
}
/// <summary>
/// Read package dependencies for all frameworks
/// </summary>
public IEnumerable<PackageDependencyGroup> GetDependencyGroups()
{
var ns = MetadataNode.GetDefaultNamespace().NamespaceName;
var groupFound = false;
foreach (var depGroup in MetadataNode.Elements(XName.Get(Dependencies, ns)).Elements(XName.Get(Group, ns)))
{
groupFound = true;
var groupFramework = GetAttributeValue(depGroup, TargetFramework);
var packages = new List<PackageDependency>();
foreach (var depNode in depGroup.Elements(XName.Get(Dependency, ns)))
{
VersionRange range = null;
var rangeNode = GetAttributeValue(depNode, Version);
if (!String.IsNullOrEmpty(rangeNode))
{
VersionRange.TryParse(rangeNode, out range);
Debug.Assert(range != null, "Unable to parse range: " + rangeNode);
}
packages.Add(new PackageDependency(GetAttributeValue(depNode, Id), range));
}
var framework = String.IsNullOrEmpty(groupFramework) ? NuGetFramework.AnyFramework : NuGetFramework.Parse(groupFramework, _frameworkProvider);
yield return new PackageDependencyGroup(framework, packages);
}
// legacy behavior
if (!groupFound)
{
var depNodes = MetadataNode.Elements(XName.Get(Dependencies, ns))
.Elements(XName.Get(Dependency, ns));
var packages = new List<PackageDependency>();
foreach (var depNode in depNodes)
{
VersionRange range = null;
var rangeNode = GetAttributeValue(depNode, Version);
if (!String.IsNullOrEmpty(rangeNode))
{
VersionRange.TryParse(rangeNode, out range);
Debug.Assert(range != null, "Unable to parse range: " + rangeNode);
}
packages.Add(new PackageDependency(GetAttributeValue(depNode, Id), range));
}
if (packages.Any())
{
yield return new PackageDependencyGroup(NuGetFramework.AnyFramework, packages);
}
}
yield break;
}
/// <summary>
/// Reference item groups
/// </summary>
public IEnumerable<FrameworkSpecificGroup> GetReferenceGroups()
{
var ns = MetadataNode.GetDefaultNamespace().NamespaceName;
var groupFound = false;
foreach (var group in MetadataNode.Elements(XName.Get(References, ns)).Elements(XName.Get(Group, ns)))
{
groupFound = true;
var groupFramework = GetAttributeValue(group, TargetFramework);
var items = group.Elements(XName.Get(Reference, ns)).Select(n => GetAttributeValue(n, File)).Where(n => !String.IsNullOrEmpty(n)).ToArray();
var framework = String.IsNullOrEmpty(groupFramework) ? NuGetFramework.AnyFramework : NuGetFramework.Parse(groupFramework, _frameworkProvider);
yield return new FrameworkSpecificGroup(framework, items);
}
// pre-2.5 flat list of references, this should only be used if there are no groups
if (!groupFound)
{
var items = MetadataNode.Elements(XName.Get(References, ns))
.Elements(XName.Get(Reference, ns)).Select(n => GetAttributeValue(n, File)).Where(n => !String.IsNullOrEmpty(n)).ToArray();
if (items.Length > 0)
{
yield return new FrameworkSpecificGroup(NuGetFramework.AnyFramework, items);
}
}
yield break;
}
/// <summary>
/// Framework reference groups
/// </summary>
public IEnumerable<FrameworkSpecificGroup> GetFrameworkReferenceGroups()
{
var results = new List<FrameworkSpecificGroup>();
var ns = Xml.Root.GetDefaultNamespace().NamespaceName;
var groups = new Dictionary<NuGetFramework, HashSet<string>>(new NuGetFrameworkFullComparer());
foreach (var group in MetadataNode.Elements(XName.Get(FrameworkAssemblies, ns)).Elements(XName.Get(FrameworkAssembly, ns))
.GroupBy(n => GetAttributeValue(n, TargetFramework)))
{
// Framework references may have multiple comma delimited frameworks
var frameworks = new List<NuGetFramework>();
// Empty frameworks go under Any
if (String.IsNullOrEmpty(group.Key))
{
frameworks.Add(NuGetFramework.AnyFramework);
}
else
{
foreach (var fwString in group.Key.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
if (!String.IsNullOrEmpty(fwString))
{
frameworks.Add(NuGetFramework.Parse(fwString.Trim(), _frameworkProvider));
}
}
}
// apply items to each framework
foreach (var framework in frameworks)
{
HashSet<string> items = null;
if (!groups.TryGetValue(framework, out items))
{
items = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
groups.Add(framework, items);
}
// Merge items and ignore duplicates
items.UnionWith(group.Select(item => GetAttributeValue(item, AssemblyName)).Where(item => !String.IsNullOrEmpty(item)));
}
}
// Sort items to make this deterministic for the caller
foreach (var framework in groups.Keys.OrderBy(e => e, new NuGetFrameworkSorter()))
{
var group = new FrameworkSpecificGroup(framework, groups[framework].OrderBy(item => item, StringComparer.OrdinalIgnoreCase));
results.Add(group);
}
return results;
}
/// <summary>
/// Package language
/// </summary>
public string GetLanguage()
{
var node = MetadataNode.Elements(XName.Get(Language, MetadataNode.GetDefaultNamespace().NamespaceName)).FirstOrDefault();
return node == null ? null : node.Value;
}
private static string GetAttributeValue(XElement element, string attributeName)
{
var attribute = element.Attribute(XName.Get(attributeName));
return attribute == null ? null : attribute.Value;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Project33.Services.Models;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
using Project33.Data;
using Microsoft.AspNet.Identity;
namespace Project33.Controllers
{
public class FavoritesController : Controller
{
FavoritesContext db = new FavoritesContext();
private FavoritesContext _FavoritesContext;
public List<Favorites> FavoritesService()
{
_FavoritesContext = new FavoritesContext();
return _FavoritesContext.Favorites.Select(b => new Favorites()
{
id = b.id,
book_id = b.book_id,
user_id = b.user_id
}).ToList();
}
FavoritesContext db_favors = new FavoritesContext();
private FavoritesContext _favoritesContext;
public async Task<IActionResult> Favored()
{
UserContext user_db = new UserContext();
var userName = User.Identity.GetUserName();
User user = await user_db.Users.FirstOrDefaultAsync(x => x.Login == userName); // UserId found
var favors = from f in db_favors.Favorites select f;
favors = favors.Where(f => f.user_id.Equals(user.Id));
return View(favors.ToList());
}
}
} |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;
using AgentStoryComponents;
namespace AgentStoryHTTP.screens
{
public partial class addSingleUser : SessionAwareWebForm
{
public UserGroupHelper ugh = null;
public User CurrentUser
{
get { return base.currentUser; }
}
protected void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e, this.divToolBarAttachPoint, this.divFooter);
}
}
}
|
using System;
using System.Reflection;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using HPMS.Log;
using HPMS.Splash;
using Tool;
using Application = System.Windows.Forms.Application;
namespace HPMS
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve+=CurrentDomain_AssemblyResolve;
//绑定程序中的异常处理
#if Release
BindExceptionHandler();
#endif
MessageBoxEx.EnableGlass = false;
Softgroup.NetResize.License.LicenseName = "figoba1";
Softgroup.NetResize.License.LicenseUser = "figoba@gmail1.com";
Softgroup.NetResize.License.LicenseKey = "FWAQB8CVZ9GDUBBUCRICXU9WE";
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Splasher.Show(typeof(frmSplash));
Application.Run(new frmMain());
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
return Assembly.LoadFrom("dll");
}
private static void BindExceptionHandler()
{
//设置应用程序处理异常方式:ThreadException处理
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理未捕获的异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Ui.MessageBoxMuti(e.Exception.Message);
LogHelper.WriteLog(null, e.Exception);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Ui.MessageBoxMuti(e.ExceptionObject.ToString());
LogHelper.WriteLog(null, e.ExceptionObject as Exception);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BuyMeCoffee.OrchardCore
{
public class Constants
{
public const string GroupId = "BuyMeCoffee";
public const string BuyMECoffeeUrl = "https://cdnjs.buymeacoffee.com";
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Testownik.Model
{
public class Question : Entity
{
public Question()
{
QuestionAnswers = new List<Answer>();
}
public int RefTest { get; set; }
[ForeignKey("RefTest")]
public virtual Test Test { get; set; }
public int QuestionNo { get; set; }
public string Content { get; set; }
public byte[] Photo { get; set; }
public virtual IList<Answer> QuestionAnswers { get; set; }
/// <summary>
/// Zwracana jest tresc pytania
/// </summary>
/// <returns></returns>
public string ToString()
{
return Content;
}
}
}
|
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 UberFrba.Abm_Turno
{
public partial class ListadoTurno : Form
{
public ListadoTurno()
{
InitializeComponent();
}
private void btnBuscar_Click(object sender, EventArgs e)
{
try
{
//Limpio la tabla de turnos
grillaTurno.Columns.Clear();
//Busco los turnos en la base de datos
DataTable dtTurnos = Turno.buscarTurnos(txtDescripcion.Text);
//Le asigno a la grilla los turnos
grillaTurno.DataSource = dtTurnos;
//Agrego botones para Modificar y Eliminar turno
DataGridViewButtonColumn btnModificar = new DataGridViewButtonColumn();
btnModificar.HeaderText = "Modificar";
btnModificar.Text = "Modificar";
btnModificar.UseColumnTextForButtonValue = true;
grillaTurno.Columns.Add(btnModificar);
DataGridViewButtonColumn btnBorrar = new DataGridViewButtonColumn();
btnBorrar.HeaderText = "Dar de baja";
btnBorrar.Text = "Dar de baja";
btnBorrar.UseColumnTextForButtonValue = true;
grillaTurno.Columns.Add(btnBorrar);
}
catch (Exception ex)
{
MessageBox.Show("Error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
private void btnLimpiar_Click(object sender, EventArgs e)
{
grillaTurno.DataSource = null;
grillaTurno.Columns.Clear();
limpiarFiltrosYErrores();
}
private void limpiarFiltrosYErrores()
{
txtDescripcion.Text = "";
}
private void btnAltaTurno_Click(object sender, EventArgs e)
{
AltaTurno altaTurno = new AltaTurno();
altaTurno.Show();
this.Hide();
}
private void btnRegresar_Click(object sender, EventArgs e)
{
this.Hide();
}
private void grillaTurno_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
//En caso de que se presiono el boton "Modificar" de algun turno, se crea un objeto Turno con los datos de la grilla y se lo manda a modificar
//En caso de que se presiono el boton "Eliminar" de algun turno, se confirma si se quiere eliminar ese Turno y luego se ejecuta la acción.
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Modificar" && e.RowIndex >= 0)
{
try
{
Turno turnoAModificar = new Turno();
turnoAModificar.Codigo = (Int32)senderGrid.CurrentRow.Cells["Turno_Codigo"].Value;
turnoAModificar.HoraFin = (Decimal)senderGrid.CurrentRow.Cells["Turno_Hora_Fin"].Value;
turnoAModificar.HoraInicio = (Decimal)senderGrid.CurrentRow.Cells["Turno_Hora_Inicio"].Value;
turnoAModificar.Descripcion = senderGrid.CurrentRow.Cells["Turno_Descripcion"].Value.ToString();
turnoAModificar.PrecioBase = (Decimal)senderGrid.CurrentRow.Cells["Turno_Precio_Base"].Value;
turnoAModificar.ValorKm = (Decimal)senderGrid.CurrentRow.Cells["Turno_Valor_Kilometro"].Value;
turnoAModificar.Activo = (Byte)senderGrid.CurrentRow.Cells["Turno_Activo"].Value;
ModificarTurno modificarTurno = new ModificarTurno(turnoAModificar);
modificarTurno.Show();
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error al realizar la seleccion del turno: " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
else if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Dar de baja" && e.RowIndex >= 0)
{
try
{
DialogResult dialogResult = MessageBox.Show("Esta seguro que desea dar de baja este turno?", "Confirmación", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
String[] respuesta = Turno.eliminarTurno((Int32)senderGrid.CurrentRow.Cells["Turno_Codigo"].Value);
if (respuesta[0] == "Error")
{
MessageBox.Show("Error al dar de baja turno: " + respuesta[1], "Error", MessageBoxButtons.OK);
}
else
{
MessageBox.Show(respuesta[1], "Operación exitosa", MessageBoxButtons.OK);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error al realizar la seleccion de rol " + ex.Message, "Error", MessageBoxButtons.OK);
}
}
}
}
}
|
namespace AlienEngine
{
/// <summary>
/// Joysticks.
/// </summary>
public enum Joysticks : int
{
Joystick1 = 0,
Joystick2 = 1,
Joystick3 = 2,
Joystick4 = 3,
Joystick5 = 4,
Joystick6 = 5,
Joystick7 = 6,
Joystick8 = 7,
Joystick9 = 8,
Joystick10 = 9,
Joystick11 = 10,
Joystick12 = 11,
Joystick13 = 12,
Joystick14 = 13,
Joystick15 = 14,
Joystick16 = 15,
JoystickLast = Joystick16
}
}
|
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
using OmniSharp.Extensions.LanguageServer.Protocol.Client;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Generation;
using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.LanguageServer.Protocol
{
namespace Models
{
[Parallel]
[Method(TextDocumentNames.DocumentFormatting, Direction.ClientToServer)]
[GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")]
[GenerateHandlerMethods]
[GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))]
[RegistrationOptions(typeof(DocumentFormattingRegistrationOptions))]
[Capability(typeof(DocumentFormattingCapability))]
public partial record DocumentFormattingParams : ITextDocumentIdentifierParams, IRequest<TextEditContainer?>, IWorkDoneProgressParams
{
/// <summary>
/// The document to format.
/// </summary>
public TextDocumentIdentifier TextDocument { get; init; } = null!;
/// <summary>
/// The format options.
/// </summary>
public FormattingOptions Options { get; init; } = null!;
}
[GenerateRegistrationOptions(nameof(ServerCapabilities.DocumentFormattingProvider))]
[RegistrationName(TextDocumentNames.DocumentFormatting)]
public partial class DocumentFormattingRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions
{
}
}
namespace Client.Capabilities
{
[CapabilityKey(nameof(ClientCapabilities.TextDocument), nameof(TextDocumentClientCapabilities.Formatting))]
public partial class DocumentFormattingCapability : DynamicCapability
{
}
}
namespace Document
{
}
}
|
using Kit.Enums;
using Kit.Services.Interfaces;
namespace Kit.WPF.Services
{
public class ScreenManagerService : IScreenManager
{
public ScreenManagerService()
{
}
public void SetScreenMode(ScreenMode ScreenMode)
{
}
}
}
|
namespace OmniSharp.Extensions.LanguageServer.Protocol.Client
{
public interface IGeneralLanguageClient : ILanguageClientProxy
{
}
}
|
using InvestmentForecaster.Service.DTO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace InvestmentForecaster.Service
{
public interface IInvestmentForecastOrchestrator
{
Task<IEnumerable<ForecastResponseDTO>> Orchestration(RequestDTO request);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoogleQuestions
{
public class _001_SortString
{
/*
* http://www.mitbbs.com/article_t/JobHunting/32079701.html
* Given an input string and an order string, e.g., “house” and “soup”, print out
characters in input string according to character order in order string. For characters in
input string but not in order string, output them in the end, their relative order doesn’t
matter.
So for “house”, “souhe” and “soueh” are valid outputs.
*/
/*
* solution: may not match the code below:
* 1. write a hash table put the pattern's string's character and index in the the hashtable
* 2. go through the target string (s1) keep count of each charater. if a character is not in
* the hash table. write it into a tmp string, this tmp string will be append to the end of the res string
* 3. go through the hash table by the index and count, construct the res string
* 4. append the tmp string to the end of the res string and out put.
*
* solution2:
* 1. write a hash table put the pattern's string's character and index in the hashtable.
* 2. sort the first string base on the index in the hashtable. if a character is not in the hash table set it's index as int_Max.
* 3. output the sorted string.
*/
public char[] SortStringBaseOnString(string s1, string s2)
{
char[] res = new char[s1.Length];
for (int i = 0; i < s1.Length; i++)
{
res[i] = s1[i];
}
HashSet<char> visited = new HashSet<char>(); // used to track char's visited in s2, incase s2 has dup char.
int startIndex = 0;
for (int i = 0; i < s2.Length; i++)
{
if (!visited.Contains(s2[i]))
{
visited.Add(s2[i]);
int tmp = startIndex;
while (tmp < res.Length)
{
if (res[tmp] == s2[i])
{
char c = res[startIndex];
res[startIndex] = res[tmp];
res[tmp] = c;
startIndex++;
}
tmp++;
}
}
}
return res;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio03
{
class Program
{/*Mostrar por pantalla todos los números primos que haya hasta el número que ingrese el usuario
por consola.*/
static void Main(string[] args)
{
int numero;
int i;
int contador = 0;
Console.Write("Ingrese numero: ");
numero=int.Parse(Console.ReadLine());
for (i = numero; i > 1; i--)
{
for(int j=1; j<=i;j++)
{
if(i%j==0)
{
contador++;
}
}
if (contador == 2)
{
Console.Write("{0}\n", i);
}
contador = 0;
}
Console.Read();
}
}
}
|
namespace Contoso.Common.Configuration.ExpressionDescriptors
{
public class FirstOrDefaultOperatorDescriptor : FilterMethodOperatorDescriptorBase
{
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace BlogWebApp.Data
{
public class Post
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PostId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Blurb { get; set; }
public DateTime Date { get; set; }
public DateTime LastUpdated { get; set; }
public string ImageUrl { get; set; }
public string Tags { get; set; }
public string Slug { get; set; }
public string Author { get; set; }
public bool Cancelled { get; set; }
public Guid BlogId { get; set; }
public Blog Blog { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Control_de_Inventario_y_ventas
{
class Usuario
{
string codigo;
string nombre;
string nick;
string contrasena;
public string Codigo { get => codigo; set => codigo = value; }
public string Nombre { get => nombre; set => nombre = value; }
public string Nick { get => nick; set => nick = value; }
public string Contrasena { get => contrasena; set => contrasena = value; }
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using NewsApi.Core.Services.Interfaces;
using NewsApi.DataLayer.Context;
using NewsApi.DataLayer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NewsApi.Core.Services
{
public class NewsService : INewsService
{
private ApiContex _context;
private IMemoryCache _catch;
public NewsService(ApiContex context, IMemoryCache cache)
{
_context = context;
_catch = cache;
}
public async Task<News> Add(News news)
{
await _context.News.AddAsync(news);
await _context.SaveChangesAsync();
return news;
}
public async Task<News> Find(int id)
{
var catcheResult = _catch.Get<News>(id);
if (catcheResult != null)
{
return catcheResult;
}
else
{
var news = await _context.News.SingleOrDefaultAsync(n => n.Id == id);
var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(120));
_catch.Set(news.Id, news, cacheOptions);
return news;
}
//return await _context.News.SingleOrDefaultAsync(n => n.Id == id);
}
public async Task<IEnumerable<News>> GetAll()
{
return await _context.News.ToListAsync();
}
public async Task<bool> IsExist(int id)
{
return await _context.News.AnyAsync(n => n.Id == id);
}
public async Task<News> Remove(int id)
{
var news = await _context.News.SingleAsync(n => n.Id == id);
_context.Remove(news);
await _context.SaveChangesAsync();
return news;
}
public async Task<IEnumerable<News>> Search(string searchTerm)
{
IQueryable<News> query = _context.News;
query.Where(s => s.Body.Contains(searchTerm) || s.Title.Contains(searchTerm) || s.SubTitle.Contains(searchTerm));
return await query.ToListAsync();
}
public async Task<News> Update(News news)
{
_context.Update(news);
await _context.SaveChangesAsync();
return news;
}
}
}
|
using System;
using InfluxData.Net.Common.Enums;
using InfluxData.Net.InfluxDb.Infrastructure;
namespace InfluxData.Net.InfluxDb.RequestClients
{
internal class RequestClientFactory
{
private readonly IInfluxDbClientConfiguration _configuration;
internal RequestClientFactory(IInfluxDbClientConfiguration configuration)
{
_configuration = configuration;
}
internal IInfluxDbRequestClient GetRequestClient()
{
switch (_configuration.InfluxVersion)
{
case InfluxDbVersion.Latest:
case InfluxDbVersion.v_0_9_6:
case InfluxDbVersion.v_0_9_5:
return new RequestClient(_configuration);
case InfluxDbVersion.v_0_9_2:
return new RequestClient_v_0_9_2(_configuration);
case InfluxDbVersion.v_0_8_x:
throw new NotImplementedException("InfluxDB v0.8.x is not supported by InfluxData.Net library.");
default:
throw new ArgumentOutOfRangeException("influxDbClientConfiguration", String.Format("Unknown version {0}.", _configuration.InfluxVersion));
}
}
}
}
|
// XAML Map Control - http://xamlmapcontrol.codeplex.com/
// © 2016 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
#if NETFX_CORE
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
#else
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
#endif
namespace MapControl
{
public partial class MapBase
{
public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register(
"Foreground", typeof(Brush), typeof(MapBase),
new PropertyMetadata(new SolidColorBrush(Colors.Black)));
public static readonly DependencyProperty CenterProperty = DependencyProperty.Register(
"Center", typeof(Location), typeof(MapBase),
new PropertyMetadata(new Location(), (o, e) => ((MapBase)o).CenterPropertyChanged((Location)e.NewValue)));
public static readonly DependencyProperty TargetCenterProperty = DependencyProperty.Register(
"TargetCenter", typeof(Location), typeof(MapBase),
new PropertyMetadata(new Location(), (o, e) => ((MapBase)o).TargetCenterPropertyChanged((Location)e.NewValue)));
public static readonly DependencyProperty ZoomLevelProperty = DependencyProperty.Register(
"ZoomLevel", typeof(double), typeof(MapBase),
new PropertyMetadata(1d, (o, e) => ((MapBase)o).ZoomLevelPropertyChanged((double)e.NewValue)));
public static readonly DependencyProperty TargetZoomLevelProperty = DependencyProperty.Register(
"TargetZoomLevel", typeof(double), typeof(MapBase),
new PropertyMetadata(1d, (o, e) => ((MapBase)o).TargetZoomLevelPropertyChanged((double)e.NewValue)));
public static readonly DependencyProperty HeadingProperty = DependencyProperty.Register(
"Heading", typeof(double), typeof(MapBase),
new PropertyMetadata(0d, (o, e) => ((MapBase)o).HeadingPropertyChanged((double)e.NewValue)));
public static readonly DependencyProperty TargetHeadingProperty = DependencyProperty.Register(
"TargetHeading", typeof(double), typeof(MapBase),
new PropertyMetadata(0d, (o, e) => ((MapBase)o).TargetHeadingPropertyChanged((double)e.NewValue)));
partial void Initialize()
{
// set Background by Style to enable resetting by ClearValue in RemoveTileLayers
var style = new Style(typeof(MapBase));
style.Setters.Add(new Setter(Panel.BackgroundProperty, new SolidColorBrush(Colors.Transparent)));
Style = style;
var clip = new RectangleGeometry();
Clip = clip;
SizeChanged += (s, e) =>
{
clip.Rect = new Rect(new Point(), e.NewSize);
ResetTransformOrigin();
UpdateTransform();
};
}
private void SetViewportTransform(Location origin)
{
MapOrigin = mapTransform.Transform(origin);
ViewportScale = Math.Pow(2d, ZoomLevel) * (double)TileSource.TileSize / 360d;
var transform = new Matrix(1d, 0d, 0d, 1d, -MapOrigin.X, -MapOrigin.Y)
.Rotate(-Heading)
.Scale(ViewportScale, -ViewportScale)
.Translate(ViewportOrigin.X, ViewportOrigin.Y);
viewportTransform.Matrix = transform;
}
}
}
|
using System;
namespace RMAT3.Models
{
public class Note
{
public Guid NoteId { get; set; }
public string AddedByUserId { get; set; }
public DateTime AddTs { get; set; }
public string UpdatedByUserId { get; set; }
public DateTime UpdatedTs { get; set; }
public bool IsActiveInd { get; set; }
public string NoteTxt { get; set; }
public string NoteHeaderTxt { get; set; }
public string NoteActionTxt { get; set; }
public string NoteCategoryCd { get; set; }
public string NoteSourceCd { get; set; }
public string NoteTypeCd { get; set; }
public string ParentTableNm { get; set; }
public Guid? ParentId { get; set; }
public bool? IsPrivateInd { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.