text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[System.Serializable]
public class AbilityVO
{
public const int ABILITY_ACTIONTYPE_OFFENSE_RANGED = 1; // ranged attack targets
public const int ABILITY_ACTIONTYPE_OFFENSE_MELEE = 2; // melee attack targets
public const int ABILITY_ACTIONTYPE_OFFENSE_PROJECTILE = 3; // projectile
public const int ABILITY_ACTIONTYPE_DEFENSE_SELF = 4; // self ability
public const int ABILITY_ACTIONTYPE_DEFENSE_CREW = 5; // party heals, party buffs, party clenses, etc
public const int ACTION_TYPE_REPOSITIONING = 6; // character reposition
public const int ABILITY_ACTIONTYPE_DEFENSE_SIDECAR = 7;
public const int TARGET_TYPE_OPPONENT = 1;
public const int TARGET_TYPE_COLLEAGUE = 2;
public const int WEAPON_TYPE_RIFLE = 1;
public const int WEAPON_TYPE_PISTOL = 2;
public const int WEAPON_TYPE_PUNCH = 3;
public const int WEAPON_TYPE_KICK = 4;
public const int WEAPON_TYPE_FIRE = 5;
public const int WEAPON_TYPE_EXPLOSION = 6;
public const int WEAPON_TYPE_POISON = 7;
public const int WEAPON_TYPE_ACID = 8;
public int uid;
public int id;
public int targets;
public int cooldown = 0;
public int cooldownTotal;
public int positionRequirement;
public string name;
public string floaterText;
public string prefabId;
// private GameObject prefab;
public bool isLocked;
public int level;
public int slot; // 1: weapon, 2: weapon mod, 3: gear mod, 4: gear
public string image;
public int cooldownLength;
public int cooldownValue;
public string animationName;
public int actionType;
public bool isSidecar = false;
public int targetType = TARGET_TYPE_OPPONENT;
public int weaponType;
public int healthModifier = HealthVO.HEALTH_MODIFIER_NONE;
public RngRoller healthRoll = new RngRoller(RngRoller.RNG_DICE_6, 1);
// public int effectModifier = EffectVO.EFFECT_MODIFIER_NONE;
public int effectId;
public EffectVO effect;// = new EffectVO();
public RngRoller effectRoll = new RngRoller(RngRoller.RNG_DICE_4, 1);
public Vector3 positionOffset;
public Vector3 rotationOffset;
public Vector3 localScaleOffset;
public bool positionXRelativeToPrimaryTarget = false;
public bool hasFXSettings = false;
public bool isFloorTriggered = false;
public Dictionary<string, string> effectSettings;
public SoundVO soundOnHit;
public SoundVO soundOnBlockShieldPhysical;
public SoundVO soundOnBlockShieldCyber;
public SoundVO soundOnActivate;
public string hitFx = "Hit 1 Variant";
public CharacterVO owner;
public string filterType = null;
public int cost = 0;
public AbilityVO(int _slot = 0, string _name = "", string _prefabId = "")
{
this.slot = _slot;
this.name = _name;
this.prefabId = _prefabId;
this.effect = new EffectVO();
// this.soundOnActivate = new SoundVO();
// this.soundOnHit = new SoundVO();
}
public AbilityVO getClone(AbilityVO _vo)
{
AbilityVO vo = new AbilityVO();
vo.uid = _vo.uid;
// vo.id = _vo.id;
vo.targets = _vo.targets;
vo.cooldown = _vo.cooldown;
vo.cooldownTotal = _vo.cooldownTotal;
vo.positionRequirement = _vo.positionRequirement;
vo.name = _vo.name;
vo.floaterText = _vo.floaterText;
vo.prefabId = _vo.prefabId;
vo.isLocked = _vo.isLocked;
vo.level = _vo.level;
vo.slot = _vo.slot;
vo.image = _vo.image;
vo.cooldownLength = _vo.cooldownLength;
vo.cooldownValue = _vo.cooldownValue;
vo.animationName = _vo.animationName;
vo.actionType = _vo.actionType;
vo.targetType = _vo.targetType;
vo.weaponType = _vo.weaponType;
vo.positionOffset = _vo.positionOffset;
vo.rotationOffset = _vo.rotationOffset;
vo.localScaleOffset = _vo.localScaleOffset;
vo.positionXRelativeToPrimaryTarget = _vo.positionXRelativeToPrimaryTarget;
vo.hasFXSettings = _vo.hasFXSettings;
vo.isFloorTriggered = _vo.isFloorTriggered;
vo.effectSettings = _vo.effectSettings;
vo.healthModifier = _vo.healthModifier;
vo.healthRoll = _vo.healthRoll;
// vo.effectModifier = _vo.effectModifier;
vo.effect = _vo.effect;
vo.effectRoll = _vo.effectRoll;
vo.soundOnHit = _vo.soundOnHit;
vo.soundOnActivate = _vo.soundOnActivate;
vo.soundOnBlockShieldPhysical = _vo.soundOnBlockShieldPhysical;
vo.hitFx = _vo.hitFx;
vo.owner = _vo.owner;
vo.filterType = _vo.filterType;
vo.cost = _vo.cost;
return vo;
}
} |
using Forca.Dominio.Models;
using Forca.Dominio.Repositorios;
using Forca.Repositorio.ContextoDeDados;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Forca.Repositorio
{
public class RepositorioJogador : IRepositorioJogador
{
public IEnumerable<Jogador> LeaderRanking(int pagina, int tamanhoPagina, Dificuldade dificuldade)
{
using (var contexto = new ContextoBaseDeDados())
{
return contexto.Jogador
.Where(jog => jog.Dificuldade == dificuldade)
.OrderByDescending(_ => _.Pontuacao)
.Skip(tamanhoPagina * (pagina - 1))
.Take(tamanhoPagina)
.ToList();
//return contexto.Jogador.ToList().OrderByDescending(jogador => jogador.Pontuacao).Take(3);
}
}
public int QuantidadeJogadoresPorDificuldade(Dificuldade dificuldade)
{
using (var contexto = new ContextoBaseDeDados())
{
return contexto.Jogador
.Where(jog => jog.Dificuldade == dificuldade)
.Count();
}
}
public void SalvarPontuacaoJogador(Jogador jogador)
{
using (var contexto = new ContextoBaseDeDados())
{
contexto.Entry<Jogador>(jogador).State = EntityState.Added;
contexto.SaveChanges();
}
}
public IEnumerable<Jogador> UltimosJogadores()
{
using (var contexto = new ContextoBaseDeDados())
{
return contexto.Jogador
.OrderByDescending(jogador => jogador.Id)
.Take(10)
.ToList();
}
}
}
}
|
using System;
using System.Collections.Generic;
//using DXF.Tables;
using DXF.Objetos;
using DXF.Utils;
using Configuracion;
namespace DXF.Entidades
{
/// <summary>
/// Representa una <see cref="DXF.Entidades.IEntidadObjeto">entidad</see> circulo.
/// </summary>
public class Circulo :
DxfObjeto,
IEntidadObjeto
{
#region propiedades privadas
private const EntidadTipo TIPO = EntidadTipo.Circulo;
private Vector3f centro;
private Vector3f inicio;
private float radio;
//private float thickness;
//private Layer layer;
//private AciColor color;
//private LineType lineType;
private Vector3f normal;
private bool invertido;
//private Dictionary<ApplicationRegistry, XData> xData;
#endregion
#region constructores
/// <summary>
/// Inicializa una nueva instancia de la clase <c>Circulo</c>.
/// </summary>
/// <param name="centro"><see cref="Vector3f">Centro</see> del circulo en coordenadas</param>
/// <param name="radio">Radio del circulo.</param>
/// <remarks>La coordinada Z del centro representa la elevacion sobre la normal.</remarks>
public Circulo(Vector3f centro, float radio, Vector3f inicio)
: base(DxfCodigoObjeto.Circulo)
{
this.centro = centro;
this.radio = radio;
this.inicio = inicio;
//this.thickness = 0.0f;
//this.layer = Layer.Default;
//this.color = AciColor.ByLayer;
//this.lineType = LineType.ByLayer;
this.normal = Vector3f.UnitarioZ;
}
/// <summary>
/// Inicializa una nueva instancia de la clase <c>Circulo</c>.
/// </summary>
public Circulo()
: base(DxfCodigoObjeto.Circulo)
{
this.centro = Vector3f.Nulo;
this.radio = 1.0f;
this.inicio = Vector3f.Nulo;
//this.thickness = 0.0f;
//this.layer = Layer.Default;
//this.color = AciColor.ByLayer;
//this.lineType = LineType.ByLayer;
this.normal = Vector3f.UnitarioZ;
}
#endregion
#region propiedades publicas
/// <summary>
/// Obtiene o establece el <see cref="netDxf.Vector3f">centro</see> del circulo.
/// </summary>
/// <remarks>La coordinada Z del centro representa la elevacion sobre la normal.</remarks>
public Vector3f Centro
{
get { return this.centro; }
set
{
this.centro = value;
//recalculamos el punto de inicio del circulo sumando el radio a la coordenada X
this.inicio = new Vector3f(this.centro.X + this.radio, centro.Y, centro.Z);
}
}
/// <summary>
/// Obtiene o establece el punto de inicio del circulo
/// </summary>
public Vector3f Inicio
{
get { return this.inicio; }
set { this.inicio = value; }
}
/// <summary>
/// Obtiene o establece el radio del circulo.
/// </summary>
public float Radio
{
get { return this.radio; }
set { this.radio = value; }
}
/// <summary>
/// Gets or sets the arc thickness.
/// </summary>
//public float Thickness
//{
// get { return this.thickness; }
// set { this.thickness = value; }
//}
/// <summary>
/// Obtiene o establece la <see cref="netDxf.Vector3f">normal</see> del circulo.
/// </summary>
public Vector3f Normal
{
get { return this.normal; }
set
{
value.Normalize();
this.normal = value;
}
}
public float MinimoX
{
get { return this.centro.X - radio; }
}
public float MaximoX
{
get { return this.centro.X + radio; }
}
public float MinimoY
{
get { return this.centro.Y - radio; }
}
public float MaximoY
{
get { return this.centro.Y + radio; }
}
#endregion
#region IEntidadObjeto Miembros
/// <summary>
/// Obtiene el <see cref="netDxf.Entities.EntityType">tipo</see> de la entidad.
/// </summary>
public EntidadTipo Tipo
{
get { return TIPO; }
}
/// <summary>
/// Gets or sets the entity <see cref="netDxf.AciColor">color</see>.
/// </summary>
//public AciColor Color
//{
// get { return this.color; }
// set
// {
// if (value == null)
// throw new ArgumentNullException("value");
// this.color = value;
// }
//}
/// <summary>
/// Gets or sets the entity <see cref="netDxf.Tables.Layer">layer</see>.
/// </summary>
//public Layer Layer
//{
// get { return this.layer; }
// set
// {
// if (value == null)
// throw new ArgumentNullException("value");
// this.layer = value;
// }
//}
/// <summary>
/// Gets or sets the entity <see cref="netDxf.Tables.LineType">line type</see>.
/// </summary>
//public LineType LineType
//{
// get { return this.lineType; }
// set
// {
// if (value == null)
// throw new ArgumentNullException("value");
// this.lineType = value;
// }
//}
/// <summary>
/// Gets or sets the entity <see cref="netDxf.XData">extende data</see>.
/// </summary>
//public Dictionary<ApplicationRegistry, XData> XData
//{
// get { return this.xData; }
// set { this.xData = value; }
//}
public Vector3f PInicial
{
get { return this.inicio; }
set { this.inicio = value; }
}
public Vector3f PFinal
{
get { return this.inicio; }
set { this.inicio = value; }
}
public void InvertirPuntos() { this.invertido = true; }
public bool Invertido
{ get { return this.invertido; } set { this.invertido = value; } }
#endregion
#region metodos publicos
/// <summary>
/// Convierte el circulo en una lista de vertices.
/// </summary>
/// <param name="precision">Numero de vertices generados.</param>
/// <returns>Una lista de verices que representa el circulo expresado en coordenadas.</returns>
public List<Vector2f> PoligonalVertices(int precision)
{
if (precision < 3)
throw new ArgumentOutOfRangeException("precision", precision, "La precision del circulo debe ser mayor o igual a tres");
List<Vector2f> ocsVertices = new List<Vector2f>();
float angulo = (float)(MathHelper.TwoPI / precision);
for (int i = 0; i < precision; i++)
{
float seno = (float)(this.radio * Math.Sin(MathHelper.HalfPI + angulo * i));
float coseno = (float)(this.radio * Math.Cos(MathHelper.HalfPI + angulo * i));
ocsVertices.Add(new Vector2f(coseno + this.centro.X, seno + this.centro.Y));
}
return ocsVertices;
}
/// <summary>
/// Convierte el circulo en una lista de vertices.
/// </summary>
/// <param name="precision">Numero de vertices generados.</param>
/// <param name="tolerancia">Tolerancia a considerar para comparar si dos nuevos vertices son iguales.</param>
/// <returns>Una lista de verices que representa el circulo expresado en coordenadas.</returns>
public List<Vector2f> PoligonalVertices(int precision, float tolerancia)
{
if (precision < 3)
throw new ArgumentOutOfRangeException("precision", precision, "La precision del circulo debe ser mayor o igual a tres");
List<Vector2f> ocsVertices = new List<Vector2f>();
if (2 * this.radio >= tolerancia)
{
float angulo = (float)(MathHelper.TwoPI / precision);
Vector2f antPunto;
Vector2f primerPunto;
float seno = (float)(this.radio * Math.Sin(MathHelper.HalfPI * 0.5));
float coseno = (float)(this.radio * Math.Cos(MathHelper.HalfPI * 0.5));
primerPunto = new Vector2f(coseno + this.centro.X, seno + this.centro.Y);
ocsVertices.Add(primerPunto);
antPunto = primerPunto;
for (int i = 1; i < precision; i++)
{
seno = (float)(this.radio * Math.Sin(MathHelper.HalfPI + angulo * i));
coseno = (float)(this.radio * Math.Cos(MathHelper.HalfPI + angulo * i));
Vector2f punto = new Vector2f(coseno + this.centro.X, seno + this.centro.Y);
if (!punto.Equals(antPunto, tolerancia) &&
!punto.Equals(primerPunto, tolerancia))
{
ocsVertices.Add(punto);
antPunto = punto;
}
}
}
return ocsVertices;
}
public bool PerteneceAreaTrabajo(XML_Config config)
{
//por defecto estimamos que la figura estara dentro
bool resultado = true;
//ANALIZAMOS LOS MAXIMOS Y MINIMOS DE CAJA EJE
if (this.MaximoX > config.MaxX || this.MinimoX < 0)
{
return false;
}
if (this.MaximoY > config.MaxY || this.MinimoX < 0)
{
return false;
}
return resultado;
}
#endregion
#region overrides
/// <summary>
/// Convierte el tipo de la instancia a string
/// </summary>
/// <returns>El tipo en string.</returns>
public override string ToString()
{
return TIPO.ToString();
}
#endregion
}
}
|
using UnityEngine;
public class EnergyCoreController : MonoBehaviour
{
public enum CoreShape
{
Block_0 = 0,
Ball_1 = 1
}
public enum CoreType
{
Negative = 0,
Positive = 1
}
[HideInInspector]
public GameArena arena;
public CoreType m_CoreType;
public string redGoalTag; //will be used to check if collided with red goal
public string blueGoalTag; //will be used to check if collided with blue goal
void Awake()
{
arena = transform.parent.GetComponent<GameArena>();
}
void Update()
{
// Check for occasional energy core getting out of arena
// and dropping down.
if (transform.position.y < -0.5f)
{
transform.position = arena.GetRandomSpawnPosInArena();
}
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.CompareTag(redGoalTag)) //ball touched red goal
{
gameObject.SetActive(false);
arena.GoalTouched(AIRobotAgent.Team.Red, m_CoreType);
}
if (col.gameObject.CompareTag(blueGoalTag)) //ball touched blue goal
{
gameObject.SetActive(false);
arena.GoalTouched(AIRobotAgent.Team.Blue, m_CoreType);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// [System.Serializable]
public class SidecarVO
{
CharacterVO owner;
CharacterVO assignee;
int health;
public bool isActivated = false;
public GameObject prefab;
public SidecarVO(CharacterVO _owner, CharacterVO _assignee, GameObject _prefab)
{
if (_owner != null)
owner = _owner;
if (_assignee != null)
assignee = _assignee;
if (_prefab != null)
prefab = _prefab;
}
} |
using Motherload.Interfaces.Unity;
using UnityEngine;
namespace Assets.Services
{
/// <summary>
/// Implementação de <see cref="IResourceLoader"/>
/// </summary>
public class ResourceLoader : IResourceLoader
{
/// <summary>
/// Implementação de <see cref="IResourceLoader.LoadJson(string)"/>
/// </summary>
public string LoadJson(string path) => Resources.Load<TextAsset>(path).text;
}
}
|
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
public class Utility
{
public const string AssetBundlesOutputPath = "AssetBundles";
/// <summary>
/// 获取带本地传输协议的assetbundle文件路径
/// </summary>
/// <returns>The asset bundle LPD isk path.</returns>
/// <param name="assetBundleName">Asset bundle name.</param>
/// <param name="sync">If set to <c>true</c> sync.</param>
public static string GetAssetBundleLPDiskPath(string assetBundleName, bool sync = false)
{
string url = string.Format("{0}/{1}/{2}", Application.persistentDataPath, PlatformName, assetBundleName);
#if UNITY_ANDROID
bool inpersistent = false;
#endif
if (!File.Exists(url))
{
url = string.Format("{0}/{1}/{2}", Application.streamingAssetsPath, PlatformName, assetBundleName);
}
#if UNITY_ANDROID
else
{
inpersistent = true;
}
#endif
#if UNITY_ANDROID
if (!sync && inpersistent)
return "file://" + url;
return url;
#else
if (sync)
return url;
return "file://" + url;
#endif
}
/// <summary>
/// 获取本地磁盘文件路径
/// </summary>
/// <returns>The asset bundle disk path.</returns>
/// <param name="assetBundleName">Asset bundle name.</param>
public static string GetAssetBundleDiskPath(string assetBundleName)
{
string path = string.Format("{0}/{1}/{2}", Application.persistentDataPath, PlatformName, assetBundleName);
if (!File.Exists(path))
{
path = string.Format("{0}/{1}/{2}", Application.streamingAssetsPath, PlatformName, assetBundleName);
}
return path;
}
public static string PlatformName
{
get
{
#if UNITY_EDITOR
return GetPlatformForAssetBundles(EditorUserBuildSettings.activeBuildTarget);
#else
return GetPlatformForAssetBundles(Application.platform);
#endif
}
}
#if UNITY_EDITOR
private static string GetPlatformForAssetBundles(BuildTarget target)
{
switch (target)
{
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.WebGL:
return "WebGL";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.StandaloneOSX:
return "OSX";
// Add more build targets for your own.
// If you add more targets, don't forget to add the same platforms to GetPlatformForAssetBundles(RuntimePlatform) function.
default:
return null;
}
}
#endif
private static string GetPlatformForAssetBundles(RuntimePlatform platform)
{
switch (platform)
{
case RuntimePlatform.Android:
return "Android";
case RuntimePlatform.IPhonePlayer:
return "iOS";
case RuntimePlatform.WebGLPlayer:
return "WebGL";
case RuntimePlatform.WindowsPlayer:
return "Windows";
case RuntimePlatform.OSXPlayer:
return "OSX";
// Add more build targets for your own.
// If you add more targets, don't forget to add the same platforms to GetPlatformForAssetBundles(RuntimePlatform) function.
default:
return null;
}
}
/// <summary>
/// persistentDataPath 持久文件在各平台的路径 没有“File://”
/// </summary>
public static string persistentDataPath
{
get
{
string url = "";
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
url = Application.dataPath + "/../persistentDataPath";
if (!Directory.Exists(url))
Directory.CreateDirectory(url);
#else
url = Application.persistentDataPath;
#endif
return url + "/";
}
}
//删除这个目录下的所有资源
public static void DeleteDir(string dir)
{
foreach (string var in Directory.GetDirectories(dir))
{
Directory.Delete(var, true);
}
foreach (string var in Directory.GetFiles(dir))
{
File.Delete(var);
}
}
}
|
using System;
using System.IO;
using Titan.Proof;
using Xunit;
namespace TitanTest
{
public class ProfileSaverTest
{
[Fact]
public void TestSaveProfile()
{
var saver = new ProfileSaver(new DirectoryInfo(Environment.CurrentDirectory));
Assert.False(string.IsNullOrWhiteSpace(saver.SaveWebsite("https://steamcommunity.com/profiles/marc3842h")));
}
}
}
|
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 BlackJack
{
public partial class Form_jogo : Form
{
public Form_jogo(string jogador1, string jogador2)
{
InitializeComponent();
btn_jogar_1.Enabled = true;
btn_jogar_2.Enabled = false;
btn_parar_1.Enabled = true;
btn_parar_2.Enabled = false;
nomeJogador1.Text = jogador1;
nomeJogador2.Text = jogador2;
pictureBoxResultado.Visible = false;
}
int Pontos_A = 0;
int Pontos_B = 0;
public void resultado()
{
if (Pontos_A <= 21 && Pontos_B <= 21)
{
if (Pontos_A == Pontos_B)
{
lbl_Resultado.Text = "Empate!";
pictureBoxResultado.Image = Properties.Resources.Empate;
pictureBoxResultado.Visible = true;
}
else if (Pontos_A > Pontos_B)
{
// Jogador que tiver mais pontos vence.
lbl_Resultado.Text = nomeJogador1.Text + " ganhou!";
pictureBoxResultado.Image = Properties.Resources.Ganhador;
pictureBoxResultado.Visible = true;
}
else
{
lbl_Resultado.Text = nomeJogador2.Text + " ganhou!";
pictureBoxResultado.Image = Properties.Resources.Ganhador;
pictureBoxResultado.Visible = true;
}
}
else
{
// Jogador que tiver menos ou igual a 21 pontos ganha.
if (Pontos_A > 21 && Pontos_B <= 21)
{
lbl_Resultado.Text = nomeJogador2.Text + " ganhou!";
pictureBoxResultado.Image = Properties.Resources.Ganhador;
pictureBoxResultado.Visible = true;
}
else if (Pontos_A <= 21 && Pontos_B > 21)
{
lbl_Resultado.Text = nomeJogador1.Text + " ganhou!";
pictureBoxResultado.Image = Properties.Resources.Ganhador;
pictureBoxResultado.Visible = true;
}
else
{
lbl_Resultado.Text = "Sem vencedor!";
pictureBoxResultado.Image = Properties.Resources.Perdedor;
pictureBoxResultado.Visible = true;
}
}
}
public void Jogada(PictureBox A, int jogador)
{
int x, total_pontos=0;
Random sorteio = new Random();
x = sorteio.Next(1, 14);
switch (x)
{
case 1: A.Image = Properties.Resources.ImagemA; total_pontos += 1; break;
case 2: A.Image = Properties.Resources.Imagem2; total_pontos += 2; break;
case 3: A.Image = Properties.Resources.Imagem3; total_pontos += 3; break;
case 4: A.Image = Properties.Resources.Imagem4; total_pontos += 4; break;
case 5: A.Image = Properties.Resources.Imagem5; total_pontos += 5; break;
case 6: A.Image = Properties.Resources.Imagem6; total_pontos += 6; break;
case 7: A.Image = Properties.Resources.Imagem7; total_pontos += 7; break;
case 8: A.Image = Properties.Resources.Imagem8; total_pontos += 8; break;
case 9: A.Image = Properties.Resources.Imagem9; total_pontos += 9; break;
case 10: A.Image = Properties.Resources.Imagem10; total_pontos += 10; break;
case 11: A.Image = Properties.Resources.ImagemJ; total_pontos += 11; break;
case 12: A.Image = Properties.Resources.ImagemQ; total_pontos += 12; break;
case 13: A.Image = Properties.Resources.ImagemK; total_pontos += 13; break;
}
if (jogador == 1)
Pontos_A += total_pontos;
else
Pontos_B += total_pontos;
}
private void button1_Click(object sender, EventArgs e)
{
Jogada(pictureBox1, 1);
if(Pontos_A <= 21)
{ // JOGANDO
lbl_Pontos_A.Text = Convert.ToString(Pontos_A);
if(Pontos_A == 21)
{
btn_jogar_1.Enabled = false;
btn_reiniciar.Enabled = true;
}
}
else
{ // PARTIDA PERDIDA
lbl_Pontos_A.Text = Convert.ToString(Pontos_A);
btn_jogar_1.Enabled = false;
btn_parar_1.Enabled = false;
btn_jogar_2.Enabled = true;
btn_parar_2.Enabled = true;
btn_reiniciar.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
Pontos_A = 0;
Pontos_B = 0;
btn_jogar_1.Enabled = true;
btn_jogar_2.Enabled = false;
btn_parar_1.Enabled = true;
btn_parar_2.Enabled = false;
btn_reiniciar.Enabled = false;
lbl_Pontos_A.Text = "0";
lbl_Pontos_B.Text = "0";
lbl_Resultado.Text = "";
pictureBoxResultado.Visible = false;
pictureBox1.Image = Properties.Resources.BlackJack;
pictureBox2.Image = Properties.Resources.BlackJack;
}
private void btn_jogar_2_Click(object sender, EventArgs e)
{
// ESCOLHER AS CARTAS
Jogada(pictureBox2, 2);
if (Pontos_B <= 21)
{ // JOGANDO
lbl_Pontos_B.Text = Convert.ToString(Pontos_B);
if (Pontos_B == 21)
{
//lbl_Resultado.Text = "GANHOU!!!";
btn_jogar_2.Enabled = false;
btn_reiniciar.Enabled = true;
resultado();
}
}
else
{ // PARTIDA PERDIDA
lbl_Pontos_B.Text = Convert.ToString(Pontos_B);
btn_jogar_2.Enabled = false;
btn_parar_2.Enabled = false;
btn_jogar_2.Enabled = false;
btn_parar_2.Enabled = false;
resultado();
btn_reiniciar.Enabled = true;
}
}
private void btn_parar_1_Click(object sender, EventArgs e)
{
btn_jogar_1.Enabled = false;
btn_parar_1.Enabled = false;
btn_jogar_2.Enabled = true;
btn_parar_2.Enabled = true;
}
private void btn_parar_2_Click(object sender, EventArgs e)
{
btn_jogar_2.Enabled = false;
btn_parar_2.Enabled = false;
btn_reiniciar.Enabled = true;
resultado();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void btnMudarJog_Click(object sender, EventArgs e)
{
form_apresentacao novoJogo = new form_apresentacao();
novoJogo.Show();
this.Visible = false;
}
private void Form_jogo_Load(object sender, EventArgs e)
{
}
}
}
|
namespace BettingSystem.Domain.Games.Specifications
{
using System;
using System.Linq.Expressions;
using Common;
using Models.Matches;
public class MatchByAwayTeamSpecification : Specification<Match>
{
private readonly string? awayTeam;
public MatchByAwayTeamSpecification(string? awayTeam)
=> this.awayTeam = awayTeam;
protected override bool Include => this.awayTeam != null;
public override Expression<Func<Match, bool>> ToExpression()
=> match => match.AwayTeam.Name.ToLower()
.Contains(this.awayTeam!.ToLower());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace BootstrapIntroduction.Filters
{
public class ValidationActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.BadRequest, modelState);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CarritoCompras.Modelo
{
public class Tienda
{
public string nombretienda { get; set; }
public string ubicacion { get; set; }
public string direccion1 { get; set; }
public string direccion2 { get; set; }
public string titulo { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SiloReport
{
public enum notificationModes
{
//Report sent over chat
ChatMode,
//Report pop up in UI
UIMode
}
class ModConfig
{
//Changes whether you want to check if you're the master player. Only applicable in the chat mode
public bool checkMasterPlayer { get; set; } = true;
// Changes notification mode. ChatMode for chat mode, UIMode for pop up UI notification mode.
public notificationModes notificationMode { get; set; } = notificationModes.UIMode;
}
}
|
using Benner.Tecnologia.Business;
using Casablanca.Business.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Casablanca.Business
{
public class BusinessComponentCasablanca<T> : BusinessComponent<T> where T : new ()
{
public BusinessComponentCasablanca()
{
if (!CBUtils.EhUsuarioCliente())
throw new Exception("Acesso negado! Usuário não está ligado a nenhum cliente!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SinglePageApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetPercentOfCPULoad()
{
System.Diagnostics.PerformanceCounter perfomanceCounter = new System.Diagnostics.PerformanceCounter();
perfomanceCounter.CategoryName = "Processor";
perfomanceCounter.CounterName = "% Processor Time";
perfomanceCounter.InstanceName = "_Total";
float raw = 0;
while ((raw == 0 || raw == 100))
{
raw = perfomanceCounter.NextValue();
}
return Json(raw, JsonRequestBehavior.AllowGet);
}
}
} |
using Alabo.AutoConfigs.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
namespace Alabo.AutoConfigs.Repositories {
public class AutoConfigRepository : RepositoryEfCore<AutoConfig, long>, IAutoConfigRepository {
public AutoConfigRepository(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
}
} |
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Web.Http;
using CommonUtilities;
using ILogging;
using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tickets;
using ServiceDeskSVC.Managers;
namespace ServiceDeskSVC.Controllers.API
{
public class TicketController:ApiController
{
private readonly IHelpDeskTicketManager _helpDeskTicketManager;
private readonly ILogger _logger;
public TicketController(IHelpDeskTicketManager helpDeskTicketManager, ILogger logger)
{
_helpDeskTicketManager = helpDeskTicketManager;
_logger = logger;
}
/// <summary>
/// Gets this instance.
/// </summary>
/// <returns></returns>
public IEnumerable<HelpDesk_Tickets_View_vm> Get()
{
_logger.Info("Getting all tickets. ");
return _helpDeskTicketManager.GetAllTickets();
}
/// <summary>
/// Gets the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public HelpDesk_Tickets_vm Get(int id)
{
_logger.Info("Getting ticket with id "+id);
return _helpDeskTicketManager.GetTicketByID(id);
}
/// <summary>
/// Gets tickets the by user. If user is IT returns tickets; if it's a normal user returns all related tickets.
/// </summary>
/// <param name="userName">Name of the user - samAccountName </param>
/// <returns></returns>
public IEnumerable<HelpDesk_Tickets_View_vm> GetByUser(string userName)
{
_logger.Info("Getting all tickets for user " + userName);
Principal user = NSActiveDirectory.GetUser(userName);
if(user == null)
{
throw new ArgumentNullException("Did not find any user with specified login name.");
}
GroupPrincipal group = NSActiveDirectory.GetGroup(CommonConstants.ITAdminGroup);
if(user.IsMemberOf(group))
{
// if user is an IT admin return all tickets
_logger.Debug("User is an IT admin.");
return _helpDeskTicketManager.GetAllTickets();
}
else
{
_logger.Debug("User is a normal user.");
// if a normal user return only tickets related to the current user
return _helpDeskTicketManager.GetTicketsByUser(userName);
}
}
/// <summary>
/// Gets the by department.
/// </summary>
/// <param name="departmentID">The department identifier.</param>
/// <returns></returns>
public IEnumerable<HelpDesk_Tickets_View_vm> GetByDepartment(int departmentID)
{
_logger.Info("Getting all tickets for department with id"+ departmentID);
return _helpDeskTicketManager.GetTicketsByDepartment(departmentID);
}
/// <summary>
/// Posts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Post([FromBody]HelpDesk_Tickets_vm value)
{
_logger.Info("Adding a new Simple ticket. ");
return _helpDeskTicketManager.CreateTicket(value);
}
/// <summary>
/// Posts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
[Route("api/Ticket/SimpleTicket")]
public int PostSimpleValue([FromBody]HelpDesk_Tickets_SimplePost_vm value)
{
_logger.Info("Adding a new ticket. ");
return _helpDeskTicketManager.CreateSimpleTicket(value);
}
/// <summary>
/// Puts the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Put(int id, [FromBody]HelpDesk_Tickets_vm value)
{
_logger.Info("Editing the ticket with id "+id);
return _helpDeskTicketManager.EditTicket(id, value);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using MeeToo.Domain.Attributes;
using MeeToo.Domain.Contracts;
namespace MeeToo.Domain
{
[DbCollection("students")]
[JsonObject(MemberSerialization.OptIn)]
public class Student : User, IDocument
{
[JsonProperty("birthDate")]
public DateTimeOffset BirthDate { get; set; }
[JsonProperty("bookNumber")]
public string BookNumber { get; set; }
[Required]
[JsonProperty("group")]
public string Group { get; set; }
[Range(0, 100)]
[JsonProperty("grade")]
public int Grade { get; set; }
[JsonProperty("testIds")]
public List<Guid> TestIds { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace FontAwesome5.Generator
{
public enum EStyles
{
Solid,
Regular,
Brands
}
public class FontAwesomeManager
{
private static readonly Regex REG_PROP = new Regex(@"\([^)]*\)");
public FontAwesomeManager(string iconsJson)
{
Icons = JsonConvert.DeserializeObject<Dictionary<string, Icon>>(File.ReadAllText(iconsJson));
}
public string Convert(string text)
{
var cultureInfo = Thread.CurrentThread.CurrentCulture;
var textInfo = cultureInfo.TextInfo;
var stringBuilder = new StringBuilder(textInfo.ToTitleCase(text.Replace("-", " ")));
stringBuilder
.Replace("-", string.Empty).Replace("/", "_")
.Replace(" ", string.Empty).Replace(".", string.Empty)
.Replace("'", string.Empty);
var matches = REG_PROP.Matches(stringBuilder.ToString());
stringBuilder = new StringBuilder(REG_PROP.Replace(stringBuilder.ToString(), string.Empty));
var hasMatch = false;
for (var i = 0; i < matches.Count; i++)
{
var match = matches[i];
if (match.Value.IndexOf("Hand", StringComparison.InvariantCultureIgnoreCase) > -1)
{
hasMatch = true;
break;
}
}
if (hasMatch)
{
stringBuilder.Insert(0, "Hand");
}
if (char.IsDigit(stringBuilder[0]))
{
stringBuilder.Insert(0, '_');
}
return stringBuilder.ToString();
}
public Dictionary<string, Icon> Icons
{
get; set;
}
public class Icon
{
public string label { get; set; }
public string unicode { get; set; }
public List<string> styles { get; set; }
public Dictionary<string, SVG> svg { get; set; }
}
public class SVG
{
public string[] viewBox { get; set; }
public int width { get; set; }
public int height { get; set; }
public string path { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Interface_Ipayable
{
public class KaryawanBergaji : Karyawan
{
private decimal gajiMingguan;
public KaryawanBergaji(string namaDepan, string namaBelakang, string nomorKTP, decimal gajiMingguan) : base(namaDepan, namaBelakang, nomorKTP)
{
GajiMingguan = gajiMingguan;
}
public decimal GajiMingguan
{
get
{
return gajiMingguan;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(GajiMingguan)} harus >= 0");
}
gajiMingguan = value;
}
}
public override decimal Pendapatan() => GajiMingguan;
public override string ToString() => $"karyawan bergaji: {base.ToString()}\n" + $"gaji mingguan: {GajiMingguan:C}";
}
} |
using System;
namespace SocketLite.Logs
{
public abstract class Logger : ILogger
{
protected Logger(bool addTime)
{
AddTime = addTime;
}
public bool ServerWrite { get; private set; }
public bool AddTime { get; }
public abstract void Clear();
protected abstract void WriteLine(string message);
public void WriteLog(string message)
{
if (string.IsNullOrEmpty(message))
return;
if (AddTime)
message = string.Format("{0:yy-MM-dd HH:mm:ss} {1}", DateTime.Now, message);
WriteLine(message);
System.Threading.Thread.Sleep(100);
}
public void WriteLog(string format, params object[] args)
{
var message = string.Format(format, args);
WriteLog(message);
}
public void WriteServerLog(string message)
{
ServerWrite = true;
WriteLog(message);
ServerWrite = false;
}
public void WriteServerLog(string format, params object[] args)
{
ServerWrite = true;
WriteLog(format, args);
ServerWrite = false;
}
}
}
|
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
public partial class CameraRenderer
{
public const float renderScaleMin = 0.1f, renderScaleMax = 2f;
const string bufferName = "Render Camera";
static ShaderTagId
unlitShaderTagId = new ShaderTagId("SRPDefaultUnlit"),
litShaderTagId = new ShaderTagId("CustomLit");
static int
bufferSizeId = Shader.PropertyToID("_CameraBufferSize"),
colorAttachmentId = Shader.PropertyToID("_CameraColorAttachment"),
depthAttachmentId = Shader.PropertyToID("_CameraDepthAttachment"),
depthNormalsAttachmentId = Shader.PropertyToID("_CameraDepthNormalsAttachment"),
colorTextureId = Shader.PropertyToID("_CameraColorTexture"),
depthTextureId = Shader.PropertyToID("_CameraDepthTexture"),
depthNormalsTextureId = Shader.PropertyToID("_CameraDepthNormalsTexture"),
sourceTextureId = Shader.PropertyToID("_SourceTexture"),
srcBlendId = Shader.PropertyToID("_CameraSrcBlend"),
dstBlendId = Shader.PropertyToID("_CameraDstBlend");
static CameraSettings defaultCameraSettings = new CameraSettings();
static bool copyTextureSupported = SystemInfo.copyTextureSupport > CopyTextureSupport.None;
CommandBuffer buffer = new CommandBuffer
{
name = bufferName
};
ScriptableRenderContext context;
Camera camera;
CullingResults cullingResults;
Lighting lighting = new Lighting();
PostFXStack postFXStack = new PostFXStack();
bool useHDR, useScaledRendering;
bool useColorTexture, useDepthTexture, useDepthNormalsTexture, useIntermediateBuffer;
Vector2Int bufferSize;
Material material;
Texture2D missingTexture;
int kDepthBufferBits = 32;
private RenderTargetHandle depthAttachmentHandle { get; set; }
internal RenderTextureDescriptor descriptor { get; private set; }
private Material depthNormalsMaterial = null;
private FilteringSettings m_FilteringSettings;
string m_ProfilerTag = "DepthNormals Prepass";
ShaderTagId m_ShaderTagId = new ShaderTagId("DepthOnly");
public CameraRenderer (Shader shader)
{
material = CoreUtils.CreateEngineMaterial(shader);
missingTexture = new Texture2D(1, 1)
{
hideFlags = HideFlags.HideAndDontSave,
name = "Missing"
};
missingTexture.SetPixel(0, 0, Color.white * 0.5f);
missingTexture.Apply(true, true);
}
public void Dispose ()
{
CoreUtils.Destroy(material);
CoreUtils.Destroy(missingTexture);
}
public void Render ( ScriptableRenderContext context, Camera camera, CameraBufferSettings bufferSettings, bool useDynamicBatching, bool useGPUInstancing, bool useLightsPerObject, ShadowSettings shadowSettings, PostFXSettings postFXSettings, int colorLUTResolution )
{
this.context = context;
this.camera = camera;
var crpCamera = camera.GetComponent<CustomRenderPipelineCamera>();
CameraSettings cameraSettings = crpCamera ? crpCamera.Settings : defaultCameraSettings;
if (camera.cameraType == CameraType.Reflection)
{
useColorTexture = bufferSettings.copyColorReflection;
useDepthTexture = bufferSettings.copyDepthReflection;
}
else
{
useColorTexture = bufferSettings.copyColor && cameraSettings.copyColor;
useDepthTexture = bufferSettings.copyDepth && cameraSettings.copyDepth;
useDepthNormalsTexture = bufferSettings.copyDepthNormals && cameraSettings.copyDepthNormals;
}
if (cameraSettings.overridePostFX)
{
postFXSettings = cameraSettings.postFXSettings;
}
float renderScaleFactor = 1f;
if ( SetupManager.instance != null )
{
renderScaleFactor = SetupManager.instance.renderScaleFactor;
}
float renderScale = cameraSettings.GetRenderScale(bufferSettings.renderScale) * renderScaleFactor;
useScaledRendering = renderScale < 0.99f || renderScale > 1.01f;
PrepareBuffer();
PrepareForSceneWindow();
if (!Cull(shadowSettings.maxDistance))
{
return;
}
useHDR = bufferSettings.allowHDR && camera.allowHDR;
if (useScaledRendering)
{
renderScale = Mathf.Clamp(renderScale, renderScaleMin, renderScaleMax);
bufferSize.x = (int)(camera.pixelWidth * renderScale);
bufferSize.y = (int)(camera.pixelHeight * renderScale);
}
else
{
bufferSize.x = camera.pixelWidth;
bufferSize.y = camera.pixelHeight;
}
buffer.BeginSample(SampleName);
buffer.SetGlobalVector(bufferSizeId, new Vector4(1f / bufferSize.x, 1f / bufferSize.y,bufferSize.x, bufferSize.y));
ExecuteBuffer();
lighting.Setup(context, cullingResults, shadowSettings, useLightsPerObject,cameraSettings.maskLights ? cameraSettings.renderingLayerMask : -1);
bufferSettings.fxaa.enabled &= cameraSettings.allowFXAA;
postFXStack.Setup(context, camera, bufferSize, postFXSettings, cameraSettings.keepAlpha, useHDR,colorLUTResolution, cameraSettings.finalBlendMode,bufferSettings.bicubicRescaling, bufferSettings.fxaa);
buffer.EndSample(SampleName);
Setup();
DrawVisibleGeometry(useDynamicBatching, useGPUInstancing, useLightsPerObject,cameraSettings.renderingLayerMask);
DrawUnsupportedShaders();
DrawGizmosBeforeFX();
if (postFXStack.IsActive)
{
postFXStack.Render(colorAttachmentId);
}
else if (useIntermediateBuffer)
{
DrawFinal(cameraSettings.finalBlendMode);
ExecuteBuffer();
}
DrawGizmosAfterFX();
Cleanup();
Submit();
}
bool Cull (float maxShadowDistance)
{
if (camera.TryGetCullingParameters(out ScriptableCullingParameters p))
{
p.shadowDistance = Mathf.Min(maxShadowDistance, camera.farClipPlane);
cullingResults = context.Cull(ref p);
return true;
}
return false;
}
void Setup ()
{
context.SetupCameraProperties(camera);
CameraClearFlags flags = camera.clearFlags;
useIntermediateBuffer = useScaledRendering || useColorTexture || useDepthTexture || useDepthNormalsTexture || postFXStack.IsActive;
if (useIntermediateBuffer)
{
if (flags > CameraClearFlags.Color)
{
flags = CameraClearFlags.Color;
}
buffer.GetTemporaryRT(colorAttachmentId, bufferSize.x, bufferSize.y,0, FilterMode.Point, useHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default);
buffer.GetTemporaryRT(depthAttachmentId, bufferSize.x, bufferSize.y,32, FilterMode.Point, RenderTextureFormat.Depth);
//buffer.GetTemporaryRT(depthNormalsAttachmentId, bufferSize.x, bufferSize.y, 32, FilterMode.Point, RenderTextureFormat.Depth);
buffer.SetRenderTarget(colorAttachmentId,RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,depthAttachmentId,RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
}
buffer.ClearRenderTarget(flags <= CameraClearFlags.Depth,flags == CameraClearFlags.Color,flags == CameraClearFlags.Color ? camera.backgroundColor.linear : Color.clear);
buffer.BeginSample(SampleName);
buffer.SetGlobalTexture(colorTextureId, missingTexture);
buffer.SetGlobalTexture(depthTextureId, missingTexture);
//buffer.SetGlobalTexture(depthNormalsTextureId,missingTexture);
ExecuteBuffer();
}
void Cleanup ()
{
lighting.Cleanup();
if (useIntermediateBuffer)
{
buffer.ReleaseTemporaryRT(colorAttachmentId);
buffer.ReleaseTemporaryRT(depthAttachmentId);
//buffer.ReleaseTemporaryRT(depthNormalsAttachmentId);
if (useColorTexture)
{
buffer.ReleaseTemporaryRT(colorTextureId);
}
if (useDepthTexture)
{
buffer.ReleaseTemporaryRT(depthTextureId);
}
//if ( useDepthNormalsTexture )
//{
// buffer.ReleaseTemporaryRT(depthNormalsTextureId);
//}
}
}
void Submit ()
{
buffer.EndSample(SampleName);
ExecuteBuffer();
context.Submit();
}
void ExecuteBuffer ()
{
context.ExecuteCommandBuffer(buffer);
buffer.Clear();
}
void DrawVisibleGeometry ( bool useDynamicBatching, bool useGPUInstancing, bool useLightsPerObject, int renderingLayerMask )
{
PerObjectData lightsPerObjectFlags = useLightsPerObject ? PerObjectData.LightData | PerObjectData.LightIndices : PerObjectData.None;
var sortingSettings = new SortingSettings(camera)
{
criteria = SortingCriteria.CommonOpaque
};
var drawingSettings = new DrawingSettings(unlitShaderTagId, sortingSettings)
{
enableDynamicBatching = useDynamicBatching,
enableInstancing = useGPUInstancing,
perObjectData =
PerObjectData.ReflectionProbes |
PerObjectData.Lightmaps | PerObjectData.ShadowMask |
PerObjectData.LightProbe | PerObjectData.OcclusionProbe |
PerObjectData.LightProbeProxyVolume |
PerObjectData.OcclusionProbeProxyVolume |
lightsPerObjectFlags
};
drawingSettings.SetShaderPassName(1, litShaderTagId);
var filteringSettings = new FilteringSettings(RenderQueueRange.opaque, renderingLayerMask: (uint)renderingLayerMask);
context.DrawRenderers(cullingResults, ref drawingSettings, ref filteringSettings);
context.DrawSkybox(camera);
if (useColorTexture || useDepthTexture || useDepthNormalsTexture )
{
CopyAttachments();
}
sortingSettings.criteria = SortingCriteria.CommonTransparent;
drawingSettings.sortingSettings = sortingSettings;
filteringSettings.renderQueueRange = RenderQueueRange.transparent;
context.DrawRenderers(cullingResults, ref drawingSettings, ref filteringSettings);
}
void CopyAttachments ()
{
if (useColorTexture)
{
buffer.GetTemporaryRT(colorTextureId, bufferSize.x, bufferSize.y,0, FilterMode.Point, useHDR ?RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default);
if (copyTextureSupported)
{
buffer.CopyTexture(colorAttachmentId, colorTextureId);
}
else
{
Draw(colorAttachmentId, colorTextureId);
}
}
if (useDepthTexture)
{
buffer.GetTemporaryRT(depthTextureId, bufferSize.x, bufferSize.y,32, FilterMode.Point, RenderTextureFormat.Depth);
if (copyTextureSupported)
{
buffer.CopyTexture(depthAttachmentId, depthTextureId);
}
else
{
Draw(depthAttachmentId, depthTextureId, true);
}
}
//if (useDepthNormalsTexture)
//{
// buffer.GetTemporaryRT(depthNormalsTextureId, bufferSize.x, bufferSize.y, 32, FilterMode.Point, RenderTextureFormat.Depth);
// if (copyTextureSupported)
// {
// buffer.CopyTexture(depthNormalsAttachmentId, depthNormalsTextureId);
// }
// else
// {
// Draw(depthNormalsAttachmentId, depthNormalsTextureId, true);
// }
//}
if (!copyTextureSupported)
{
buffer.SetRenderTarget(colorAttachmentId,RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,depthAttachmentId,RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
}
ExecuteBuffer();
}
void Draw (RenderTargetIdentifier from, RenderTargetIdentifier to, bool isDepth = false)
{
buffer.SetGlobalTexture(sourceTextureId, from);
buffer.SetRenderTarget(to, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
buffer.SetViewport(camera.pixelRect);
buffer.DrawProcedural(Matrix4x4.identity, material, isDepth ? 1 : 0, MeshTopology.Triangles, 3);
}
void DrawFinal (CameraSettings.FinalBlendMode finalBlendMode)
{
buffer.SetGlobalFloat(srcBlendId, (float)finalBlendMode.source);
buffer.SetGlobalFloat(dstBlendId, (float)finalBlendMode.destination);
buffer.SetGlobalTexture(sourceTextureId, colorAttachmentId);
buffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget,finalBlendMode.destination == BlendMode.Zero ?RenderBufferLoadAction.DontCare : RenderBufferLoadAction.Load,RenderBufferStoreAction.Store);
buffer.SetViewport(camera.pixelRect);
buffer.DrawProcedural(Matrix4x4.identity, material, 0, MeshTopology.Triangles, 3);
buffer.SetGlobalFloat(srcBlendId, 1f);
buffer.SetGlobalFloat(dstBlendId, 0f);
}
} |
using DChild.Gameplay;
using Sirenix.OdinInspector;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpiderTest : MonoBehaviour
{
private enum TargetDirection
{
Left, Right
}
[SerializeField]
[TabGroup("Sensor")]
private RaycastSensor m_wallSensor;
[SerializeField]
[TabGroup("Sensor")]
private RaycastSensor m_cliffSensor;
[SerializeField]
[TabGroup("Config")]
private float m_speed;
[SerializeField]
[TabGroup("Config")]
private TargetDirection m_targetDirection;
private Rigidbody2D m_rigidbody;
private Vector2 m_surfaceDirection;
private float m_facingDirection;
private bool m_isRotated;
private void Update()
{
var direction = Vector2.zero;
var facing = transform.localScale;
facing.x = (m_targetDirection == TargetDirection.Right) ? m_facingDirection : -m_facingDirection;
transform.localScale = facing;
if (m_wallSensor.isDetecting)
{
var rotateDirection = (m_targetDirection == TargetDirection.Right) ? 90 : -90;
transform.Rotate(0, 0, rotateDirection, Space.World);
m_rigidbody.gravityScale = 0;
}
else if (m_cliffSensor.isDetecting)
{
direction = (m_targetDirection == TargetDirection.Right) ? Vector2.right : Vector2.left;
m_isRotated = false;
}
else
{
if (!m_isRotated)
{
var rotateDirection = (m_targetDirection == TargetDirection.Right) ? -90 : 90;
transform.Rotate(0, 0, rotateDirection, Space.World);
m_isRotated = true;
}
m_rigidbody.gravityScale = 0;
direction = (m_targetDirection == TargetDirection.Right) ? Vector2.right : Vector2.left;
}
MoveAlongSurface(direction);
}
private void MoveAlongSurface(Vector2 direction)
{
transform.Translate(direction * Time.deltaTime * m_speed);
}
private void Start()
{
m_rigidbody = GetComponent<Rigidbody2D>();
m_facingDirection = transform.localScale.x;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SimpleShop.Models
{
public class Client
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Birthday { get; set; }
public DateTime SignUpDate { get; set; }
public DateTime? LastPurchaseDate { get; set; }
public ICollection<Purchase> Purchases { get; set; } = new List<Purchase>();
}
}
|
namespace Batcher.Tests.Helpers
{
public interface IAccessHelper
{
object Call(object entity, string methodName, params object[] args);
ReturnType Call<ReturnType>(object entity, string methodName, params object[] args);
object CallGeneric<GenericType>(object entity, string methodName, params object[] args);
ReturnType CallGeneric<GenericType, ReturnType>(object entity, string methodName, params object[] args);
}
} |
using System;
using System.IO;
using System.Web.Configuration;
using Boxofon.Web.Helpers;
using Boxofon.Web.Model;
using Boxofon.Web.Services;
using Boxofon.Web.Twilio;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace Boxofon.Web.Infrastructure
{
public class PhoneNumberVerificationService : IPhoneNumberVerificationService, IRequireInitialization
{
private static readonly Random Random = new Random();
private readonly CloudStorageAccount _storageAccount;
private readonly ITwilioClientFactory _twilioClientFactory;
public PhoneNumberVerificationService(ITwilioClientFactory twilioClientFactory)
{
if (twilioClientFactory == null)
{
throw new ArgumentNullException("twilioClientFactory");
}
_twilioClientFactory = twilioClientFactory;
_storageAccount = CloudStorageAccount.Parse(WebConfigurationManager.AppSettings["azure:StorageConnectionString"]);
}
public void Initialize()
{
Table().CreateIfNotExists();
}
protected CloudTable Table()
{
return _storageAccount.CreateCloudTableClient().GetTableReference("PhoneNumberVerifications");
}
public void BeginVerification(User user, string phoneNumber)
{
if (string.IsNullOrEmpty(user.TwilioPhoneNumber))
{
throw new ArgumentException("The user must have a Twilio phone number.");
}
phoneNumber = phoneNumber.ToE164();
var code = GenerateCode();
var entity = new VerificationEntity(user.Id, phoneNumber, code);
var op = TableOperation.InsertOrReplace(entity);
Table().Execute(op);
var twilio = _twilioClientFactory.GetClientForUser(user);
twilio.SendSmsMessage(user.TwilioPhoneNumber, phoneNumber, code);
}
public bool TryCompleteVerification(User user, string phoneNumber, string code)
{
if (string.IsNullOrEmpty(code) || !phoneNumber.IsPossiblyValidPhoneNumber())
{
return false;
}
phoneNumber = phoneNumber.ToE164();
var op = TableOperation.Retrieve<VerificationEntity>(user.Id.ToString(), phoneNumber);
var entity = (VerificationEntity)Table().Execute(op).Result;
if (entity != null && entity.Code == code)
{
var deleteOp = TableOperation.Delete(entity);
Table().ExecuteAsync(deleteOp);
return true;
}
return false;
}
private static string GenerateCode()
{
return Random.Next(1, 999999).ToString("000000");
}
public class VerificationEntity : TableEntity
{
public string Code { get; set; }
public VerificationEntity()
{
}
public VerificationEntity(Guid userId, string phoneNumber, string code)
{
PartitionKey = userId.ToString();
RowKey = phoneNumber;
Code = code;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Structures
{
class Exc08
{
struct StrExc081
{
public string Text;
public StrExc082 FindSymb(int n)
{
StrExc082 SymbSt = new StrExc082();
if (n < Text.Length)
{
SymbSt.Symb = Text[n];
}
return SymbSt;
}
}
struct StrExc082
{
public char Symb;
}
public static void MainExc08()
{
StrExc081 A;
A.Text = "WoW!";
StrExc082 B;
B = A.FindSymb(4);
Console.WriteLine(B.Symb);
}
}
}
|
using UnityEngine;
using UnityEditor;
using Ardunity;
[CustomEditor(typeof(ColorOutput))]
public class ColorOutputEditor : ArdunityObjectEditor
{
SerializedProperty script;
SerializedProperty color;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
color = serializedObject.FindProperty("color");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
// ColorOutput bridge = (ColorOutput)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
EditorGUILayout.PropertyField(color, new GUIContent("Color"));
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "Unity/Add Bridge/Output/ColorOutput";
if(Selection.activeGameObject != null)
menu.AddItem(new GUIContent(menuName), false, func, typeof(ColorOutput));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Syndication;
using System.ServiceModel.Web;
using System.Text;
namespace Com.Colin.SyndicationServiceLibrary
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Feed1”。
public class Feed1 : IFeed1
{
public SyndicationFeedFormatter CreateFeed()
{
// 新建整合源。
SyndicationFeed feed = new SyndicationFeed("Feed Title", "A WCF Syndication Feed", null);
List<SyndicationItem> items = new List<SyndicationItem>();
// 新建整合项。
SyndicationItem item = new SyndicationItem("An item", "Item content", null);
items.Add(item);
feed.Items = items;
// 根据查询字符串返回 ATOM 或 RSS
// rss -> http://localhost:8733/Design_Time_Addresses/Com.Colin.SyndicationServiceLibrary/Feed1/
// atom -> http://localhost:8733/Design_Time_Addresses/Com.Colin.SyndicationServiceLibrary/Feed1/?format=atom
string query = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
SyndicationFeedFormatter formatter = null;
if (query == "atom")
{
formatter = new Atom10FeedFormatter(feed);
}
else
{
formatter = new Rss20FeedFormatter(feed);
}
return formatter;
}
}
}
|
using FichaTecnica.Dominio;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FichaTecnica.Repositorio.EF
{
public class BaseDeDados : DbContext
{
public DbSet<Usuario> Usuario { get; set; }
public DbSet<Permissao> Permissao { get; set; }
public DbSet<Comentario> Comentario { get; set; }
public DbSet<Projeto> Projeto { get; set; }
public DbSet<LinkFork> LinkFork { get; set; }
public DbSet<Membro> Membro { get; set; }
public DbSet<Cargo> Cargo { get; set; }
public BaseDeDados() : base("FICHA_TECNICA")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UsuarioMap());
modelBuilder.Configurations.Add(new CargoMap());
modelBuilder.Configurations.Add(new ComentarioMap());
modelBuilder.Configurations.Add(new MembroMap());
modelBuilder.Configurations.Add(new PermissaoMap());
modelBuilder.Configurations.Add(new ProjetoMap());
modelBuilder.Configurations.Add(new LinkForkMap());
base.OnModelCreating(modelBuilder);
}
}
class UsuarioMap : EntityTypeConfiguration<Usuario>
{
public UsuarioMap()
{
ToTable("Usuario");
HasKey(p => p.Id);
Property(p => p.Senha).IsRequired().HasMaxLength(200);
Property(p => p.Email).IsRequired().HasMaxLength(255);
Property(p => p.Senha).IsRequired().HasMaxLength(200);
Property(p => p.Nome).IsRequired().HasMaxLength(120);
HasRequired(p => p.Permissao).WithMany().HasForeignKey(x => x.IdPermissao);
}
}
class PermissaoMap : EntityTypeConfiguration<Permissao>
{
public PermissaoMap()
{
ToTable("Permissao");
HasKey(p => p.Id);
Property(p => p.Descricao).IsRequired().HasMaxLength(120);
}
}
class LinkForkMap : EntityTypeConfiguration<LinkFork>
{
public LinkForkMap()
{
ToTable("LinkFork");
HasKey(p => p.Id);
HasRequired(p => p.Projeto).WithMany().HasForeignKey(x => x.IdProjeto);
HasRequired(p => p.Membro).WithMany().HasForeignKey(x => x.IdMembro);
Property(p => p.URL).IsRequired().HasMaxLength(500);
}
}
class ComentarioMap : EntityTypeConfiguration<Comentario>
{
public ComentarioMap()
{
ToTable("Comentario");
HasKey(p => p.Id);
Property(p => p.Assunto).IsRequired().HasMaxLength(500);
Property(p => p.Texto).IsRequired().HasMaxLength(1000);
Property(p => p.Tipo).IsRequired();
Property(p => p.Estado).IsRequired();
Property(p => p.DataCriacao).IsRequired();
HasRequired(p => p.Usuario).WithMany().HasForeignKey(x => x.IdUsuario);
HasRequired(p => p.Projeto).WithMany().HasForeignKey(x => x.IdProjeto);
HasRequired(p => p.Membro).WithMany().HasForeignKey(x => x.IdMembro);
}
}
class ProjetoMap : EntityTypeConfiguration<Projeto>
{
public ProjetoMap()
{
ToTable("Projeto");
HasKey(p => p.Id);
Property(p => p.Nome).IsRequired().HasMaxLength(500);
Property(p => p.DataInicio).IsRequired();
Property(p => p.Descricao).IsRequired().HasMaxLength(8000);
HasMany(p => p.Usuarios).WithMany(u => u.Projetos)
.Map(m => {
m.ToTable("Projeto_Usuario");
m.MapLeftKey("IdProjeto");
m.MapRightKey("IdUsuario");
});
}
}
class MembroMap : EntityTypeConfiguration<Membro>
{
public MembroMap()
{
ToTable("Membro");
HasKey(p => p.Id);
Property(p => p.Nome).IsRequired().HasMaxLength(500);
Property(p => p.Email).IsRequired().HasMaxLength(500);
Property(p => p.DataDeNascimento).IsRequired();
Property(p => p.Telefone).IsOptional().HasMaxLength(18);
Property(p => p.Foto).IsOptional().HasMaxLength(500);
HasRequired(p => p.Cargo).WithMany().HasForeignKey(x => x.IdCargo);
Property(p => p.DataCriacao).IsRequired();
HasMany(u => u.Projetos).WithMany(p => p.Membros)
.Map(m => {
m.ToTable("Membro_Projeto");
m.MapLeftKey("IdMembro");
m.MapRightKey("IdProjeto");
});
}
}
class CargoMap : EntityTypeConfiguration<Cargo>
{
public CargoMap()
{
ToTable("Cargo");
HasKey(p => p.Id);
Property(p => p.Descricao).IsRequired().HasMaxLength(500);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ensage;
using Ensage.Common;
using Ensage.Common.Extensions;
using Ensage.Common.Objects;
using SharpDX;
namespace InvokerLegacyCfg.Abilities
{
public class ColdSnap
{
private Ability ability;
private Ability Q
{
get
{
return Variables.Quas;
}
}
private Ability W
{
get
{
return Variables.Wex;
}
}
private Ability E
{
get
{
return Variables.Exort;
}
}
private Ability R
{
get
{
return Variables.Invoke;
}
}
private Hero me
{
get
{
return Variables.Hero;
}
}
private uint level
{
get
{
return this.ability.Level;
}
}
public ColdSnap()
{
//this.ability = ClassID.Invoker;
//this.abilityIcon = Drawing.GetTexture("materials/ensage_ui/spellicons/storm_spirit_static_remnant");
//this.iconSize = new Vector2(HUDInfo.GetHpBarSizeY() * 2);
}
public void getAbility()
{
if (invoked("invoker_cold_snap"))
{
this.ability = me.FindSpell("invoker_cold_snap");
}
}
public bool invoked(string abilityName)
{
return me.Spellbook.SpellD.Name.Equals(abilityName)
|| me.Spellbook.SpellF.Name.Equals(abilityName);
}
public void invokeColdSnap()
{
if (invoked("invoker_cold_snap"))
{
getAbility();
//cast on enemy
//if (target == null || !target.IsAlive) return;
//if (Utils.SleepCheck("coldsnap")) {
// ability.UseAbility(target);
// Utils.Sleep(50, "coldsnap");
//}
}
else
{
invoke();
getAbility();
}
}
public void invoke()
{
if (!R.CanBeCasted()) return;
if (Utils.SleepCheck("invoke"))
{
Q.UseAbility();
Q.UseAbility();
Q.UseAbility();
R.UseAbility();
E.UseAbility();
E.UseAbility();
E.UseAbility();
Utils.Sleep(250, "invoke");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Math_Problems
{
/// <summary>
/// Find the next largest permutation of a number
/// for eg: 35421 -> 41235
/// 4153 - > 4315
/// 3154 -> 3415
/// </summary>
class NextLargestPermutation
{
/// <summary>
/// Algo: 1. traverse from the end and any digit which is less than the previous digit is the pivot point
/// 2. Get the index of the digit greater than the pivot point digit (use binary search)
/// 3. Swap the pivot digit and the digit greater than the pivot point.
/// 4. Reverse all the char Array from pivot Index +1 to the end (as they are present in descending order)
///
/// The running time of the algo is O(n), as we take O(n) time to do the reverse.
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public int GetNextLargestPermutationOfNum(int num)
{
if (num > 0)
{
char[] number = num.ToString().ToCharArray();
for (int i = number.Length - 2; i >= 0; i--)
{
if (number[i] < number[i + 1])
{
// we have found the pivot point
// now find the element in sb which is greater than
int greaterIndex = BinarySearch(number, i, number[i]);
if (greaterIndex == -1)
{
// we dont have any digit greater than the currentNum
// hence we cannot get a greater permutation
break;
}
// swap the character at greaterIndex and i
Swap(number, i, greaterIndex);
// reverse the char array from index i+1 to number.Length-1
Reverse(number, i + 1, number.Length - 1);
return int.Parse(new string(number));
}
}
}
return -1;
}
/// <summary>
/// Reverses the characters in a char array from startIndex to endIndex
/// </summary>
/// <param name="number"></param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
private void Reverse(char[] number, int startIndex, int endIndex)
{
while ( startIndex<endIndex)
{
Swap(number, startIndex, endIndex);
startIndex++;
endIndex--;
}
}
/// <summary>
/// Swaps the char at index1 and index2
/// </summary>
/// <param name="number"></param>
/// <param name="index1"></param>
/// <param name="index2"></param>
private void Swap(char[] number, int index1, int index2)
{
char temp = number[index1];
number[index1] = number[index2];
number[index2] = temp;
}
/// <summary>
/// does a binary search to get the index of the digit greater than search.
/// the str is present in the descending order from the st index
/// </summary>
/// <param name="str">the ints in the sb is in descending order</param>
/// <param name="search">the number whose greater value needs to be searched</param>
/// <returns>index at which the greater value number is present</returns>
private int BinarySearch(char[] str, int st, char search)
{
int end = str.Length - 1;
int index = -1;
while(st<=end)
{
int mid = end - ((end - st) / 2);
if(str[mid] > search)
{
index = mid;
st = mid + 1;
}
else
{
// str[mid] <= search
end = mid - 1;
}
}
return index;
}
public static void TestNextLargestPermutation()
{
NextLargestPermutation nextLargest = new NextLargestPermutation();
int num = 234966321;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: 236123469", num, nextLargest.GetNextLargestPermutationOfNum(num));
num = 111;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: -1", num, nextLargest.GetNextLargestPermutationOfNum(num));
num = 511;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: -1", num, nextLargest.GetNextLargestPermutationOfNum(num));
num = 0;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: -1", num, nextLargest.GetNextLargestPermutationOfNum(num));
num = 27;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: 72", num, nextLargest.GetNextLargestPermutationOfNum(num));
num = -1;
Console.WriteLine("the next largest permutation of the number {0} is {1}. Expected: -1", num, nextLargest.GetNextLargestPermutationOfNum(num));
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class MilestoneProgressSlider : MonoBehaviour {
[SerializeField]
private Text text = null;
[SerializeField]
private Slider slider = null;
[SerializeField]
private Tooltip tooltip = null;
private string originalText;
private MilestoneRequirerment requirement;
private void Awake() {
this.originalText = this.text.text;
}
public void setRequirement(MilestoneRequirerment requirement, World world) {
this.requirement = requirement;
int progress = this.requirement.getProgress(world);
// Set text
if(this.text != null) {
this.text.text = string.Format(
this.originalText,
this.requirement.title,
Mathf.Min(progress, this.requirement.targetAmount),
this.requirement.targetAmount);
}
// Set slider
if(this.slider != null) {
this.slider.maxValue = this.requirement.targetAmount;
this.slider.value = progress;
}
// Set tooltip
if(this.tooltip != null) {
this.tooltip.text = string.Format(this.requirement.tooltip, this.requirement.targetAmount);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordReverser
{
class Program
{
static void Main(string[] args)
{
ReverseWords("The greatest victory");
//Enter your string here
}
public static string ReverseWords(string str)
{
string[] words = str.Split(' ');
foreach (string word in words)
{
var reversedarray = word.ToCharArray();
Array.Reverse(reversedarray);
Console.Write("" + reversedarray);
}
Console.ReadLine();
return null;
}
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.HR
{
public class SysOrgEntity
{
/// <summary>
/// 组织ID
/// </summary>
[DataMember]
public string Id;
/// <summary>
/// 中文名
/// </summary>
[DataMember]
public string ChineseName;
/// <summary>
/// 英文名
/// </summary>
[DataMember]
public string EnglishName;
/// <summary>
/// 组织类型
/// </summary>
[DataMember]
public string EnumGroupType;
/// <summary>
/// 父组织Id
/// </summary>
[DataMember]
public string ParentGroupId;
/// <summary>
/// 所属子公司
/// </summary>
[DataMember]
public string Area;
/// <summary>
/// 组织级别
/// </summary>
[DataMember]
public string EnumGroupLevel;
/// <summary>
/// 有效开始时间
/// </summary>
[DataMember]
public string StartDate;
/// <summary>
/// 创建时间
/// </summary>
[DataMember]
public string CreationTime;
/// <summary>
/// 最近更新时间
/// </summary>
[DataMember]
public string LastUpdateDate;
/// <summary>
/// 是否删除
/// </summary>
[DataMember]
public string ISDelete;
/// <summary>
/// 组织节点
/// </summary>
[DataMember]
public string RootGroupId { get; set; }
}
}
|
using System.Net;
using System.Threading.Tasks;
using Xunit;
namespace Pobs.Tests.Integration
{
public class ApiTests
{
[Fact]
public async Task NotFoundApiUrl_ShouldReturn404NotFound()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
var response = await client.GetAsync("/api/invalid_endpoint");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal("", responseContent);
}
}
}
}
|
using GardenControlRepositories.Entities;
using GardenControlRepositories.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenControlRepositories
{
public class ScheduleRepository : IScheduleRepository
{
private GardenControlContext _context { get; init; }
private ILogger<ScheduleRepository> _logger { get; init; }
public ScheduleRepository(GardenControlContext context, ILogger<ScheduleRepository> logger)
{
_context = context;
_logger = logger;
}
#region Schedule
public async Task DeleteScheduleAsync(int id)
{
var scheduleEntity = await _context.ScheduleEntities
.Where(t => t.ScheduleId == id).FirstOrDefaultAsync();
if (scheduleEntity == null)
{
_logger.LogWarning($"Tried deleting Schedule that does not exist, ScheduleId: {id}");
return;
}
try
{
_context.ScheduleEntities.Remove(scheduleEntity);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error deleting Schedule ({id}): {ex.Message}");
throw;
}
}
public async Task<IEnumerable<ScheduleEntity>> GetAllSchedulesAsync()
{
var taskScheduleEntities = await _context.ScheduleEntities
.Include(s => s.ScheduleTasks)
.ThenInclude(st => st.ControlDevice)
.ToListAsync();
return taskScheduleEntities;
}
public async Task<IEnumerable<ScheduleEntity>> GetDueSchedulesAsync()
{
var taskScheduleEntities = await _context.ScheduleEntities
.Include(s => s.ScheduleTasks)
.ThenInclude(st => st.ControlDevice)
.Where(t => t.IsActive && t.NextRunDateTime <= DateTime.Now)
.ToListAsync();
return taskScheduleEntities;
}
public async Task<ScheduleEntity> GetScheduleByIdAsync(int id)
{
var scheduleEntity = await _context.ScheduleEntities
.Include(s => s.ScheduleTasks)
.ThenInclude(st => st.ControlDevice)
.Where(t => t.ScheduleId == id)
.FirstOrDefaultAsync();
return scheduleEntity;
}
public async Task<ScheduleEntity> InsertScheduleAsync(ScheduleEntity schedule)
{
if (schedule == null) throw new ArgumentNullException(nameof(schedule));
try
{
_context.ScheduleEntities.Add(schedule);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error inserting Schedule: {ex.Message}");
throw;
}
return schedule;
}
public async Task<ScheduleEntity> UpdateScheduleAsync(ScheduleEntity schedule)
{
try
{
_context.Entry(schedule).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error updating Schedule: {schedule.ScheduleId}, {ex.Message}");
throw;
}
return schedule;
}
public async Task UpdateScheduleNextRunTimeAsync(int id, DateTime nextRunDateTime)
{
var scheduleEntity = await _context.ScheduleEntities
.Where(t => t.ScheduleId == id)
.FirstOrDefaultAsync();
if (scheduleEntity == null)
throw new Exception();
scheduleEntity.NextRunDateTime = nextRunDateTime;
try
{
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error updating Schedule NextRunTime: {id}, {ex.Message}");
throw;
}
}
#endregion
#region Schedule Task
public async Task<ScheduleTaskEntity> InsertScheduleTaskAsync(ScheduleTaskEntity scheduleTask)
{
if (scheduleTask == null) throw new ArgumentNullException(nameof(scheduleTask));
try
{
_context.ScheduleTaskEntities.Add(scheduleTask);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error inserting ScheduleTask: {ex.Message}");
throw;
}
return scheduleTask;
}
public async Task<IEnumerable<ScheduleTaskEntity>> GetAllScheduleTasksAsync()
{
return await _context.ScheduleTaskEntities
.Include(st => st.Schedule)
.Include(st => st.ControlDevice)
.ToListAsync();
}
public async Task<IEnumerable<ScheduleTaskEntity>> GetScheduleTasksAsync(int scheduleId)
{
return await _context.ScheduleTaskEntities
.Include(st => st.Schedule)
.Include(st => st.ControlDevice)
.Where(st => st.ScheduleId == scheduleId)
.ToListAsync();
}
public async Task<ScheduleTaskEntity> GetScheduleTaskByIdAsync(int id)
{
return await _context.ScheduleTaskEntities
.Include(st => st.Schedule)
.Include(st => st.ControlDevice)
.Where(st => st.ScheduleTaskId == id)
.FirstOrDefaultAsync();
}
public async Task<ScheduleTaskEntity> UpdateScheduleTaskAsync(ScheduleTaskEntity scheduleTask)
{
try
{
_context.Entry(scheduleTask).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error updating ScheduleTask: {scheduleTask.ScheduleTaskId}, {ex.Message}");
throw;
}
return scheduleTask;
}
public async Task DeleteScheduleTaskAsync(int id)
{
var scheduleTaskEntity = await _context.ScheduleTaskEntities
.Where(st => st.ScheduleTaskId == id).FirstOrDefaultAsync();
if (scheduleTaskEntity == null)
{
_logger.LogWarning($"Tried deleting Schedule Task that does not exist, ScheduleTaskId: {id}");
return;
}
try
{
_context.ScheduleTaskEntities.Remove(scheduleTaskEntity);
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError($"Error deleting Schedule Task ({id}): {ex.Message}");
throw;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace Crossword_Completer
{
//[Table("Words")]
public class Words
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[MaxLength(25)]
public string word { get; set; }
[MaxLength(500)]
public string definition { get; set; }
public int deleted { get; set; }
public int hidden { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace CollectionsUtility.Mocks
{
/// <summary>
/// <see cref="SortedIntListUnion"/> takes any number of instances of integer collections,
/// where the integers within each instance are already sorted in ascending order, and produces
/// an enumeration of the set union of integers from all of the collections.
///
/// <para>
/// Important.
/// <br/>
/// This implementation (under <see cref="Mocks"/> namespace) is a mock implementation with subpar
/// performance. For production use, refer to the implementation under the parent namespace.
/// </para>
///
/// <para>
/// The integer enumeration produced by this class is sorted ascendingly.
/// </para>
/// </summary>
public class SortedIntListUnion
: IEnumerable<int>
{
private SortedSet<int> _combined;
public SortedIntListUnion(params IEnumerable<int>[] lists)
: this(lists as IEnumerable<IEnumerable<int>>)
{
}
public SortedIntListUnion(IEnumerable<IEnumerable<int>> lists)
{
_combined = new SortedSet<int>();
foreach (var list in lists)
{
foreach (var value in list)
{
_combined.Add(value);
}
}
}
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)_combined).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_combined).GetEnumerator();
}
}
}
|
using Microsoft.AspNetCore.Http;
namespace Sentry.AspNetCore;
/// <summary>
/// Provides the strategy to define the name of a transaction based on the <see cref="HttpContext"/>.
/// </summary>
/// <remarks>
/// The SDK can name transactions automatically when using MVC or Endpoint Routing. In other cases, like when serving static files, it fallback to Unknown Route. This hook allows custom code to define a transaction name given a <see cref="HttpContext"/>.
/// </remarks>
public delegate string? TransactionNameProvider(HttpContext context);
|
using UnityEngine;
using System.Net;
public class GameplayTranslator {
public static void Interpret(IPEndPoint source, Message message, GameplayMessage gameplay) {
NetworkCommon networkCommon = GameObject.FindObjectOfType<Network> ().NetworkCommon;
if (networkCommon == null) return;
Player[] players = GameObject.FindObjectsOfType<Player>();
switch (gameplay.Message) {
case GameplayMessage.MessageValue.MOVE:
foreach (Player player in players) {
if (player.ID == gameplay.PlayerID) {
player.Move(gameplay.MoveDelta, gameplay.OldPosition, !(networkCommon is NetworkServer));
}
}
break;
case GameplayMessage.MessageValue.ATTACK:
foreach (Player player in players) {
if (player.ID == gameplay.PlayerID)
{
player.Attack();
}
}
break;
}
}
public static void Send(GameplayMessage.MessageValue messageValue, int id, Vector2 delta, Vector3 originalPosition) {
Network network = GameObject.FindObjectOfType<Network>();
if (network == null) return;
NetworkCommon networkCommon = network.NetworkCommon;
if (networkCommon == null) return;
Message m = createMessage( networkCommon.ID,
1-networkCommon.ID,
messageValue,
id,
delta,
originalPosition );
if (networkCommon is NetworkClient) {
(networkCommon as NetworkClient).Send (null, MessageTranslator.ToByteArray (m));
} else {
(networkCommon as NetworkServer).Broadcast (MessageTranslator.ToByteArray (m));
}
}
private static byte[] ToByteArray(GameplayMessage message) {
return MessageTranslator.ToByteArray<GameplayMessage>(message);
}
private static Message createMessage(int sourceID, int destID, GameplayMessage.MessageValue message, int playerID, Vector2 delta, Vector3 originPosition) {
Message m = new Message () {
SourceID = sourceID,
DestID = destID,
Type = Message.MessageType.GAMEPLAY
};
GameplayMessage g = new GameplayMessage () {
Message = message,
PlayerID = playerID,
MoveDelta = delta,
OldPosition = originPosition
};
m.SerializedContent = ToByteArray(g);
return m;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp9CronScheduledBackgroudService.Server.BGService.Repository;
namespace WebApp9CronScheduledBackgroudService.Server.BGService
{
public class PromotionService : IPromotionService
{
private readonly IBackgroundContainer _repository;
public PromotionService(IBackgroundContainer repository)
{
_repository = repository;
}
public Task<IQueryable<Promotions>> GetPromotions()
{
return Task.Run(() => _repository.GetPromotions());
}
public Task<Promotions> UpdatePromotions(Promotions promotions)
{
return Task.Run(() => _repository.UpdatePromotion(promotions));
}
}
}
|
namespace Bowling.Src
{
public class Bowling
{
}
}
|
using System;
using CC.Mobile.Routing;
using Android.App;
using System.Collections.Generic;
using Groceries.Domain;
using CC.Utilities;
using System.Linq;
namespace Groceries.MonoDroid.Services
{
public class GroceriesRouter: Router
{
private INavIntent lastActionIntent;
private IScreenFactory factory;
private IScreenFactory screenFactory;
public GroceriesRouter(IScreenFactory factory, IScreenFactory screenFactory){
this.factory = factory;
this.screenFactory = screenFactory;
}
public override void SendHandle(NavigationType navType, NavItem item, object context)
{
if (item != null)
{
if (item.PresentationStyle == PresentationStyle.Screenless && item.ViewModel is IScreenlessEnabled)
{
base.SendHandle(navType, item, context);
}
if (navType == NavigationType.Back && item.ViewModel is IScreenlessEnabled) {
HandleScreenlessItems(NavigationType.Forward, item);
}
else
{
if (item.PresentationStyle == PresentationStyle.Modal && navType == NavigationType.Back)
{
if (context is INavIntent)
{
(context as INavIntent).Stop();
}
}
else
{
Activity navContext = null;
if (context is Activity)
{
navContext = (Activity)context;
}
else if (context is Fragment)
{
navContext = (context as Fragment).Activity;
}
if (navContext != null) {
var actionIntent = screenFactory.Create (item, navContext);
if (actionIntent != null) {
actionIntent.Start ();
if (item.PresentationStyle == PresentationStyle.Modal) {
lastActionIntent = actionIntent;
}
} else {
navContext.Finish ();
}
}
}
}
}
else
{
var navContext = (Activity)context;
if (navContext.IsNotNull ()) {
navContext.Finish ();
}
}
}
public override NavItem[] GoTo (NavItem navItem, bool animated = true, object context=null, Action<bool> completionHandler=null)
{
// if (navItem.IsNetworkConnectionNecessary && !factory.Device.IsOnline) {
//ShowNetworkConnectionIsNeeded (context as Android.Support.V4.App.FragmentActivity);
// return new NavItem[]{ };
// } else {
var existingNav = screenStack.FirstOrDefault (p => p == navItem);
var result = base.GoTo (navItem, animated, context);
if (context is Activity) {
//TODO: Handle notification properly
/*
int enterAnnimation, exitAnniation;
if (existingNav != null && existingNav.ViewModel == navItem.ViewModel) {
enterAnnimation = Resource.Animation.activity_slide_in_from_left;
exitAnniation = Resource.Animation.activity_slide_out_to_right;
} else {
enterAnnimation = Resource.Animation.activity_slide_in_from_right;
exitAnniation = Resource.Animation.activity_slide_out_to_left;
}
(context as Activity).OverridePendingTransition (enterAnnimation, exitAnniation)*/
}
return result;
// }
}
public override void Push (NavItem item, bool animated = true)
{
screenStack.Push (item);
}
public override NavItem Pop(object context=null, bool animated=true)
{
var navItem = screenStack.Peek();
if (CanGoBack)
{
var currentItem = screenStack.Pop();
if (currentItem.ViewModel != null && currentItem.ViewModel is IDisposable)
{
(navItem.ViewModel as IDisposable).Dispose();
}
if (navItem.PresentationStyle != PresentationStyle.Modal)
{
navItem = screenStack.Peek();
}
SendHandle(NavigationType.Back, navItem, context);
/*
if(context is Activity){
(context as Activity).OverridePendingTransition (Resource.Animation.activity_slide_in_from_left, Resource.Animation.activity_slide_out_to_right);
}
*/
}
else
{
//ViewModelFactory.Dispose (); TODO: Destory IOC
SendHandle(NavigationType.Back, null, context);
}
return navItem;
}
public override List<NavItem> PopAllModals(object context = null, bool animated = true){
var popedItems = new List<NavItem>();
NavItem navItem;
while (screenStack.Peek().PresentationStyle == PresentationStyle.Modal)
{
navItem = screenStack.Pop();
if (navItem.ViewModel != null && navItem.ViewModel is IDisposable)
{
(navItem.ViewModel as IDisposable).Dispose();
}
popedItems.Add(navItem);
}
if (popedItems.Count > 0)
{
SendHandle(NavigationType.Back, screenStack.Peek(), context);
}
return popedItems;
}
public override void Clear(){
screenStack.Clear ();
}
public NavItem this [Screens s] {
get {
return screenStack.FirstOrDefault (p => p.Screen == (int)s);
}
}
public IViewModel ViewModelForScreen(Screens screen){
var navItem = screenStack.FirstOrDefault (p => p.Screen == (int)screen);
IViewModel model = null;
if(navItem.IsNotNull()){
model = navItem.ViewModel;
}
return model;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
public class DevelopmentTools : MonoBehaviour
{
void Update()
{
Debug.developerConsoleVisible = false;
}
}
|
using Autofac;
using Autofac.Extensions.DependencyInjection;
using CC.Web.Api.Filter;
using CC.Web.Dao.Core;
using CC.Web.Service.System;
using IdentityModel;
using IdentityServer4;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using ServiceStack.Redis;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using CC.Web.Api.Core;
using Microsoft.IdentityModel.Logging;
using CC.Web.Model.Core;
using AutoMapper;
namespace CC.Web.Api
{
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 IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IRedisClientsManager>(new BasicRedisClientManager());
services.AddControllers(option =>
{
option.Filters.Add(typeof(ActionLogFilter));
option.Filters.Add(typeof(ContextResourceFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext<CCDbContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("CCDatabase"),
b => b.MigrationsAssembly("CC.Web.Dao")));
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddScoped<IWorkContext, WorkContext>();
services.AddSingleton(new AutoMapperProfile().CreateMapper());
//ConfigureIdentityService(services);
// 清除JWT映射关系(会修改返回的token)
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var issuer = Configuration["Auth:JwtIssuer"];
var key = Configuration["Auth:JwtKey"];
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = issuer,
ValidAudience = issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidateLifetime = true,//是否验证失效时间d
};
});
IdentityModelEventSource.ShowPII = true;
//autoFac
var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);
AutofacConfig.RegisterObj(containerBuilder);
var applicationContainer = containerBuilder.Build();
return new AutofacServiceProvider(applicationContainer);
}
public void ConfigureIdentityService(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "CCWebClient";
options.ClientSecret = "CCWebSecret";
options.SaveTokens = true;
options.ResponseType = "code"; ;
options.Scope.Clear();
options.Scope.Add("api1");
options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
options.Scope.Add("roles");
options.Scope.Add(OidcConstants.StandardScopes.OfflineAccess);
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.EnvironmentName == "Development")
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public enum GameState1 { InGame, GameOver};
public class GameController : MonoBehaviour {
public GameObject hazard;
public GameObject gameoverText;
public Text scoreText;
public Vector3 spawnValues;
public float spawnWait;
public float startWait;
public float waveWait;
public bool GameState = false;
public int hazardCount;
private int score = 0;
void Start()
{
StartCoroutine(SpawnWaves());
UpdateSocre();
GameManager.instance.SpawnCount = 0;
}
private void Update()
{
if (GameState == true)
{
gameoverText.gameObject.SetActive(true);
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (!GameState)
{
if (GameManager.instance.SpawnCount != 0 && GameManager.instance.SpawnCount % 10 == 0)
{
waveWait -= 1f;
}
GameManager.instance.SpawnCount += 1;
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x),
spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void SetGameState(bool gameState)
{
GameState = gameState;
}
public void AddSocre(int scoreValue)
{
score = score + scoreValue;
UpdateSocre();
}
void UpdateSocre()
{
scoreText.text = "Score: " + score;
}
}
|
namespace Pentagon.Extensions.Localization.Json {
using Newtonsoft.Json;
public class ResourceJson
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Research.TradingOrder.TranOrder.Output
{
/// <summary>
/// 订单列表返回结果集
/// </summary>
public class OrderListByEsResponse
{
/// <summary>
/// 总数量
/// </summary>
[JsonProperty("count")]
public int Count { get; set; }
/// <summary>
/// 从第几个元素开始
/// </summary>
[JsonProperty("from")]
public int From { get; set; }
/// <summary>
/// 取多少个元素
/// </summary>
[JsonProperty("size")]
public int Size { get; set; }
/// <summary>
/// 是否成功
/// </summary>
[JsonProperty("success")]
public bool Success { get; set; }
/// <summary>
/// 订单信息
/// </summary>
[JsonProperty("infos")]
public List<ESOrderListItem> Orders { get; set; }
}
/// <summary>
/// OrderDetail Item
/// </summary>
public class ESOrderListItem
{
///
/// 摘要:
/// 金额
[JsonProperty("sumMoney")]
public decimal? SumMoney { get; set; }
///
/// 摘要:
/// 制单人邮箱
[JsonProperty("submitor")]
public string Submitor { get; set; }
/// <summary>
/// 拥有人
/// </summary>
[JsonProperty("owner")]
public string Owner { get; set; }
///
/// 摘要:
/// 门店
[JsonProperty("installShop")]
public string InstallShop { get; set; }
///
/// 摘要:
/// 取消时间
public OrderCancelReason OrderCancelReasonInfo { get; set; }
///
/// 摘要:
/// 预约时间bookDatetime
///
[JsonProperty("bookDatetime")]
public DateTime? BookDateTime { get; set; }
///
/// 摘要:
/// 查vip订单
//public int? VipOrderFilter { get; set; }
///
/// 摘要:
/// 订单创建时间
///
[JsonProperty("orderDatetime")]
public DateTime? OrderDatetime { get; set; }
///
/// 摘要:
/// 订单渠道
[JsonProperty("orderChannel")]
public string OrderChannel { get; set; }
///
/// 摘要:
/// 配送方式
[JsonProperty("deliveryType")]
public string DeliveryType { get; set; }
///
/// 摘要:
/// 配送状态
[JsonProperty("deliveryStatus")]
public string DeliveryStatus { get; set; }
///
/// 摘要:
/// 订单状态
[JsonProperty("status")]
public string Status { get; set; }
///
/// 摘要:
/// 提交时间
[JsonProperty("submitDate")]
public DateTime? SubmitDate { get; set; }
///
/// 摘要:
/// 外联单号
[JsonProperty("refNo")]
public string RefNo { get; set; }
///
/// 摘要:
/// 客户电话
[JsonProperty("userTel")]
public string UserTel { get; set; }
///
/// 摘要:
/// 客户姓名
[JsonProperty("userName")]
public string UserName { get; set; }
///
/// 摘要:
/// 订单编号
[JsonProperty("orderId")]
public string OrderId { get; set; }
/// <summary>
///
/// </summary>
[JsonProperty("pkid")]
public int? PKID { get; set; }
///
/// 摘要:
/// 配送时间
///
[JsonProperty("deliveryDatetime")]
public DateTime? DeliveryDateTime { get; set; }
///
/// 摘要:
/// 订单类型
///
[JsonProperty("orderType")]
public string OrderType { get; set; }
}
/// <summary>
/// 订单取消应由
/// </summary>
public class OrderCancelReason
{
/// <summary>
/// ID
/// </summary>
public int? Id { get; set; }
/// <summary>
/// 订单PKID
/// </summary>
public int? OrderPKID { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? CreateTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C2Lab1
{
public class Class1
{
public string fname;
public string lname;
public string major;
public string gpa;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CredNet.Controls;
using CredNet.Interop;
namespace CredNet.Sample
{
public class PersonalizedSampleCredential : UserCredential
{
public ICredentialProviderUser User { get; }
public string Password { get; set; }
public PersonalizedSampleCredential(ICredentialProviderUser user)
{
User = user;
}
public override void Dispose()
{
}
protected override void Initialize()
{
var passwordBox = new PasswordBox
{
Label = "Password",
DataContext = this,
Options = FieldOptions.PasswordReveal,
InteractiveState = FieldInteractiveState.Focused
}.WithBinding("Value", nameof(Password));
Controls.Add(new TileBitmap { Image = Properties.Resources.TileIcon, State = FieldState.DisplayInDeselectedTile });
Controls.Add(new SmallLabel { Label = $"Personalized Credential for {User.GetDisplayName()}" });
Controls.Add(passwordBox);
Controls.Add(new SubmitButton() { AdjacentControl = passwordBox });
}
public override string GetUserSid() => User.GetPrimarySid();
public override uint GetAuthenticationPackage() => SampleCredentialProvider.NegotiateAuthPackage;
public override SerializationResponse GetSerialization(out byte[] serialization, ref string optionalStatus,
ref StatusIcon optionalIcon)
{
if (string.IsNullOrEmpty(Password))
{
serialization = null;
optionalStatus = "Invalid password!";
optionalIcon = StatusIcon.Error;
return SerializationResponse.NoCredentialNotFinished;
}
serialization = Provider.UsageScenario == UsageScenario.Logon ?
CredentialSerializer.SerializeKerbInteractiveLogon(Native.GetComputerName(), User.GetUserName(), Password) :
CredentialSerializer.SerializeKerbWorkstationUnlock(Native.GetComputerName(), User.GetUserName(), Password);
return SerializationResponse.ReturnCredentialFinished;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class colorShoot : MonoBehaviour {
private Color colorStart = Color.red;
private Color colorEnd = Color.green;
public float duration = 1.0F;
private Renderer rend;
Material color;
private void Start () {
rend = GetComponent<Renderer>();
colorStart = randomColor();
colorEnd = randomColor();
}
private void Update()
{
float lerp = Mathf.PingPong(Time.time, duration) / duration;
rend.material.color = Color.Lerp(colorStart, colorEnd, lerp);
}
private Color randomColor()
{
Color color = Color.white;
int num = Random.Range(0, 5);
switch (num)
{
case 0:
color = Color.red;
break;
case 1:
color = Color.yellow;
break;
case 2:
color = Color.blue;
break;
case 3:
color = Color.green;
break;
case 4:
color = Color.magenta;
break;
case 5:
color = Color.cyan;
break;
}
return color;
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Btf.Data.Contexts;
using Btf.Data.Contracts.Base;
using Btf.Data.Contracts.Interfaces;
using Btf.Utilities.Hash;
using Btf.Utilities.SixDigitKey;
using Btf.Data.Model.User;
using Btf.Data.Model.Base;
namespace Btf.Data.Repositories
{
public class UserRepository : BaseRepository<User, UserContext>, IUserRepository
{
private IPasswordHash hashUtility;
private ISixDigitKeyProvider sixDigitKeyPrpvider;
private DbSet<User> Users;
private DbSet<UserStatus> UserStatus;
private DbSet<UserVerificationKey> VerificationKeys;
private DbSet<UserAccess> UserAccess;
private DbSet<UserRole> UserRoles;
private DbSet<UserRolePermission> UserRolePermissions;
private DbSet<Permission> Permissions;
private DbSet<PermissionDependency> PermissionDependency;
public UserRepository(IUnitOfWork<UserContext> uow, IPasswordHash hashUtility, ISixDigitKeyProvider sixDigitKeyPrpvider) : base(uow)
{
this.hashUtility = hashUtility;
this.sixDigitKeyPrpvider = sixDigitKeyPrpvider;
Users = Set;
var userContext = (UserContext)Context;
VerificationKeys = userContext.VerificationKeys;
UserStatus = userContext.UserStatus;
UserAccess = userContext.UserAccess;
UserRoles = userContext.UserRoles;
Permissions = userContext.Permissions;
UserRolePermissions = userContext.UserRolePermissions;
PermissionDependency = userContext.PermissionDependency;
}
public override void Add(User entity)
{
//hashed the password
entity.Password = hashUtility.GetHash(entity.Password);
entity.CreatedOn = entity.UpdatedOn = DateTime.UtcNow;
entity.UpdatedBy = entity.UpdatedBy = 0;
entity.IsActive = true;
base.Add(entity);
}
public override void Update(User entity)
{
//get stored user entity
//var storedUser = GetById(entity.Id);
//if (storedUser == null)
// throw new Exception("User id does not exist.");
//if (entity.UserStatus != null && entity.UserStatusId != 0)
//{
// storedUser.UserStatusId = entity.UserStatusId;
// storedUser.UserStatus = entity.UserStatus;
//}
base.Update(entity);
}
public async Task<User> CheckLogin(string email, string password)
{
var hashedPassword = hashUtility.GetHash(password);
var user = await this.Users.SingleOrDefaultAsync(u => u.Email == email && u.Password == hashedPassword && u.IsActive == true);
return (user);
}
public UserVerificationKey GenerateNewVerificationKey()
{
//generate a new key
UserVerificationKey newKey = new UserVerificationKey();
newKey.CreatedBy = newKey.UpdatedBy = 0;
newKey.UpdatedOn = newKey.CreatedOn = DateTime.UtcNow;
newKey.ExpiresOn = DateTime.UtcNow.AddDays(1);
newKey.IsActive = true;
newKey.VerificationKey = this.sixDigitKeyPrpvider.GenerateNewKey();
newKey.IsUsed = false;
return newKey;
}
public async Task<UserVerificationKey> GetKeyInfo(string key)
{
var keyInfo = await this.VerificationKeys.FirstOrDefaultAsync(k => k.VerificationKey == key && !k.IsUsed && k.IsActive);
return keyInfo;
}
public async Task<UserStatus> GetUserStatusInfo(string status)
{
var statusInfo = await this.UserStatus.FirstOrDefaultAsync(s => s.Status == status && s.IsActive);
return statusInfo;
}
public async Task<User> GetUserInfo(int userId)
{
return await Users
.FirstOrDefaultAsync(u => u.IsActive && u.Id == userId);
}
public async Task<User> GetUserInfoWithoutState(int userId)
{
return await Users.FirstOrDefaultAsync(u => u.IsActive && u.Id == userId);
}
public async Task<User> GetUserWithoutStateAndStatus(int userId)
{
var user = await Users
.FirstOrDefaultAsync(u => u.Id == userId);
return user;
}
public async Task<User> GetByUserGuid(string userGuid)
{
var user = await Users
.FirstOrDefaultAsync(u => u.UserGUID == userGuid && u.IsActive);
if (user == null)
user = await Users.FirstOrDefaultAsync(u => u.UserGUID == userGuid && u.IsActive);
return user;
}
public async Task<List<UserAccess>> GetUserAccess(int userId)
{
var access = await UserAccess.Include(u => u.UserRole.Permissions).ThenInclude(p => p.Permission)
.Where(u => u.UserId == userId && u.IsActive && u.UserRole.IsActive).AsNoTracking()
.ToListAsync();
return access;
}
public void Detach(IEntity entity)
{
var userContext = (UserContext)Context;
userContext.Entry(entity).State = EntityState.Detached;
}
public async Task<List<UserAccess>> GetUserAccessWithoutPermissions(int userId)
{
var access = await UserAccess.Include(u => u.UserRole)
.Where(u => u.UserId == userId && u.IsActive && u.UserRole.IsActive)
.ToListAsync();
return access;
}
public void UpdateKey(UserVerificationKey key)
{
key.UpdatedOn = DateTime.UtcNow;
VerificationKeys.Update(key);
}
public async Task<bool> IsEmailAvailable(string Email)
{
var emailCount = await Users.CountAsync(u => u.Email == Email);
return (emailCount == 0);
}
public async Task<int> GetAllUsersCount()
{
return await Users.
CountAsync();
}
public async Task<int> GetUsersCount(string filter, bool activeOnly, bool inactiveOnly, int userId)
{
string[] filters = filter.Split(' ', ',');
string filterTrimmed = string.Join("", filters);
if (String.IsNullOrEmpty(filter))
{
return await Users
.Where(u => (!activeOnly || u.IsActive) && (!inactiveOnly || !u.IsActive) && u.Id != userId
).CountAsync();
}
return await Users
.Where(u => ((u.FirstName + u.LastName).Contains(filterTrimmed) || u.Email.Contains(filter))
&& (!activeOnly || u.IsActive) && (!inactiveOnly || !u.IsActive) && u.Id != userId
).CountAsync();
}
public async Task<List<User>> GetUsers(int pageIndex, int pageSize, string filter, bool activeOnly, bool inactiveOnly, int userId)
{
string[] filters = filter.Split(' ', ',');
string filterTrimmed = string.Join("", filters);
if (String.IsNullOrEmpty(filter))
{
return await Users
.Where(u => (!activeOnly || u.IsActive) && (!inactiveOnly || !u.IsActive) && u.Id != userId
)
.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
}
return await Users
.Where(u => ((u.FirstName + u.LastName).Contains(filterTrimmed) || u.Email.Contains(filter))
&& (!activeOnly || u.IsActive) && (!inactiveOnly || !u.IsActive) && u.Id != userId
)
.Skip(pageIndex * pageSize)
.Take(pageSize).ToListAsync();
}
public async Task<UserAccess> GetUserAccessByAccessId(int userAccessId)
{
return await UserAccess.FirstOrDefaultAsync(u => u.IsActive && u.Id == userAccessId);
}
public async Task<UserAccess> GetUserAccess(int userId, int userRoleId)
{
return await UserAccess.FirstOrDefaultAsync(u => u.IsActive
&& u.UserId == userId && u.UserRoleId == userRoleId);
}
public void AddAccess(UserAccess userAccess)
{
UserAccess.Add(userAccess);
}
public void UpdateAccess(UserAccess userAccess)
{
UserAccess.Update(userAccess);
}
public async Task<List<UserRole>> GetUserRoles()
{
return await UserRoles.Where(r => r.IsActive).ToListAsync();
}
public async Task<UserRole> GetUserRole(int roleId)
{
return await UserRoles.Include(r => r.Permissions)
.FirstOrDefaultAsync(r => r.IsActive && r.Id == roleId);
}
public async Task<bool> RoleNameAvailable(string roleName, int roleId = 0)
{
var anyRecord = await UserRoles.AnyAsync(r => r.Role == roleName && r.IsActive && r.Id != roleId);
return !anyRecord;
}
public async Task<UserRole> GetUserRoleWithoutPermissions(string roleName)
{
return await UserRoles.FirstOrDefaultAsync(r => r.IsActive && r.Role == roleName);
}
public async Task<int> GetPermissionsCount(string filter)
{
if (filter == "$0")
{
return await Permissions.CountAsync(p => p.IsActive && p.PermissionType != "API");
}
return await Permissions.CountAsync(p => (p.AccessUrl.Contains(filter)
|| p.PermissionCode.Contains(filter)
|| p.PermissionName.Contains(filter)
|| p.PermissionType.Contains(filter))
&& p.IsActive && p.PermissionType != "API");
}
public async Task<List<Permission>> GetPermissions(string filter, int pageIndex, int pageSize)
{
if (filter == "$0")
{
return await Permissions.Where(p => p.IsActive && p.PermissionType != "API")
.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
}
return await Permissions.Where(p => (p.AccessUrl.Contains(filter)
|| p.PermissionCode.Contains(filter)
|| p.PermissionName.Contains(filter)
|| p.PermissionType.Contains(filter))
&& p.IsActive && p.PermissionType != "API")
.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
}
public async Task<int> GetPermissionsCount(int roleId, string filter)
{
if (filter == "$0")
{
return await UserRolePermissions.CountAsync(r => r.Permission.IsActive
&& r.IsActive && r.UserRoleId == roleId && r.Permission.PermissionType != "API");
}
return await UserRolePermissions.CountAsync(r => (r.Permission.AccessUrl.Contains(filter)
|| r.Permission.PermissionCode.Contains(filter)
|| r.Permission.PermissionName.Contains(filter)
|| r.Permission.PermissionType.Contains(filter))
&& r.Permission.IsActive
&& r.IsActive && r.UserRoleId == roleId && r.Permission.PermissionType != "API");
}
public async Task<List<UserRolePermission>> GetPermissions(int roleId, string filter, int pageIndex, int pageSize)
{
if (filter == "$0")
{
return await UserRolePermissions.Include(r => r.Permission)
.Where(r => r.IsActive && r.UserRoleId == roleId && r.Permission.PermissionType != "API")
.Skip(pageIndex * pageSize).Take(pageSize)
.ToListAsync();
}
return await UserRolePermissions.Include(r => r.Permission).Where(r => (r.Permission.AccessUrl.Contains(filter)
|| r.Permission.PermissionCode.Contains(filter)
|| r.Permission.PermissionName.Contains(filter)
|| r.Permission.PermissionType.Contains(filter))
&& r.Permission.IsActive
&& r.IsActive && r.UserRoleId == roleId && r.Permission.PermissionType != "API")
.Skip(pageIndex * pageSize).Take(pageSize)
.ToListAsync();
}
public async Task<List<Permission>> GetPermissionDependencies(int permissionId)
{
return await PermissionDependency.Where(d => d.IsActive
&& d.PermissionId == permissionId)
.Select(d => d.ChildPermission)
.ToListAsync();
}
public void AddRole(UserRole role)
{
UserRoles.Add(role);
}
public void UpdateRole(UserRole role)
{
UserRoles.Update(role);
}
public void AddRolePermission(UserRolePermission permmission)
{
UserRolePermissions.Add(permmission);
}
public void UpdateRolePermission(UserRolePermission permission)
{
UserRolePermissions.Update(permission);
}
public async Task<User> CheckPassword(int userId, string password)
{
var cPass = hashUtility.GetHash(password);
//check if the current password is correct
return await Users.FirstOrDefaultAsync(u => u.IsActive && u.Id == userId && u.Password == cPass);
}
public async Task<List<string>> GetSecurityQuestions(string emailAddress)
{
var user = await Users.FirstOrDefaultAsync(u => u.Email == emailAddress && u.IsActive);
if (user == null) return new List<string>();
var questions = new List<string>();
questions.Add(user.SecretQuestion1);
questions.Add(user.SecretQuestion2);
return questions;
}
public async Task<User> VerifySecurityAnswers(string emailAddress, string answer1, string answer2)
{
return await Users.FirstOrDefaultAsync(u => u.Email == emailAddress
&& u.SecretAnswer1 == answer1 && u.SecretAnswer2 == answer2 && u.IsActive);
}
public void AddUserVerificationKey(UserVerificationKey newKey)
{
VerificationKeys.Add(newKey);
}
public void AddPermission(Permission permission)
{
permission.CreatedOn = permission.UpdatedOn = DateTime.UtcNow;
permission.IsActive = true;
Permissions.Add(permission);
}
public async Task<List<KeyValuePair<string, string>>> GetUsersNamesByGUIDAsync(List<string> gUIDs)
{
return await Users
.Where(u => gUIDs.Any(g => g == u.UserGUID) && u.IsActive)
.Select(u => new KeyValuePair<string, string>(u.UserGUID, u.FirstName + " " + u.LastName))
.ToListAsync();
}
public async Task<List<Permission>> GetPermissionDependenciesAsync(List<int> permissionIds)
{
return await PermissionDependency
.Where(pd => permissionIds.Contains(pd.PermissionId) && pd.IsActive)
.Select(pd => pd.ChildPermission).AsNoTracking()
.ToListAsync();
}
public async Task<List<UserRole>> GetUserRolesAsync(int userId)
{
return await UserAccess
.Where(ua => ua.UserId == userId)
.Select(ua => ua.UserRole)
.ToListAsync();
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ISBNAttribute.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace SmartLibrary.Infrastructure.DataAnnotations
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmartLibrary.Resources;
/// <summary>
/// Proper Name Attribute
/// </summary>
public class ISBNAttribute : RegularExpressionAttribute, IClientValidatable
{
/// <summary>
/// RegEx Pattern
/// </summary>
private const string PATTERN = @"^([a-zA-Z\d]{10}|[a-zA-Z\d]{13})$";
/// <summary>
/// error message constant
/// </summary>
private string eRRORMESSAGE = Messages.InvalidISBNMessage;
/// <summary>
/// Initializes static members of the <see cref="ISBNAttribute"/> class.
/// You need to register an adapter for the new attribute in order to enable client side validation.
/// Since the RegularExpressionAttribute already has an adapter, which is RegularExpressionAttributeAdapter, all you have to do is reuse it.
/// Use a static constructor to keep all the necessary code within the same class.
/// </summary>
static ISBNAttribute()
{
// necessary to enable client side validation
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ISBNAttribute), typeof(RegularExpressionAttributeAdapter));
}
/// <summary>
/// Initializes a new instance of the <see cref="ISBNAttribute" /> class.
/// </summary>
public ISBNAttribute()
: base(PATTERN)
{
this.ErrorMessage = this.eRRORMESSAGE;
}
/// <summary>
/// Get Client Validation Rules
/// </summary>
/// <param name="metadata">metadata object</param>
/// <param name="context">context Object</param>
/// <returns>Return ModelClientValidationRule List</returns>
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mvr = new ModelClientValidationRule();
mvr.ErrorMessage = this.eRRORMESSAGE;
mvr.ValidationType = "isbn";
return new[] { mvr };
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleInt
{
public int MaxValue { get; set; }
int currentValue;
public int CurrentValue
{
get
{
return currentValue;
}
set
{
if(value >= MaxValue)
{
if (currentValue != MaxValue - 1)
currentValue = MaxValue - 1;
else
currentValue = 0;
}
else if(value < 0)
{
currentValue = MaxValue - 1;
}
else
{
currentValue = value;
}
}
}
public CircleInt(int currentValue, int MaxValue)
{
this.currentValue = currentValue;
this.MaxValue = MaxValue;
}
public static CircleInt operator +(CircleInt cInt, int Int)
{
cInt.CurrentValue += Int;
return new CircleInt(cInt.CurrentValue, cInt.MaxValue);
}
public static CircleInt operator -(CircleInt cInt, int Int)
{
cInt.CurrentValue -= Int;
return new CircleInt(cInt.CurrentValue, cInt.MaxValue);
}
public static CircleInt operator --(CircleInt cInt)
{
cInt.CurrentValue--;
return new CircleInt(cInt.CurrentValue, cInt.MaxValue);
}
public static CircleInt operator ++(CircleInt cInt)
{
cInt.CurrentValue++;
return new CircleInt(cInt.CurrentValue, cInt.MaxValue);
}
public static implicit operator int(CircleInt cInt)
{
return cInt.CurrentValue;
}
}
|
using System.Collections.Generic;
namespace Petanque.Web.Models
{
public class TeamDto
{
public string CompetitionId { get; set; }
public string Id { get; set; }
public string Nom { get; set; }
public int Number { get; set; }
}
public class CreateTeamDto
{
public TeamDto TeamDto { get; set; }
public IEnumerable<TeamDto> TeamDtos { get; set; }
}
} |
namespace Nan.Extensions.Information
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
public sealed class ExtensionPackageMessageAttribute : Attribute
{
private readonly string message;
public ExtensionPackageMessageAttribute(string message)
{
this.message = message ?? throw new ArgumentNullException(nameof(message));
}
public string Message => this.message;
}
}
|
using Tomelt.Environment.Extensions;
using Tomelt.Layouts.Elements;
using Tomelt.Layouts.Framework.Drivers;
namespace Tomelt.Layouts.Drivers {
[TomeltFeature("Tomelt.Layouts.Snippets")]
public class SnippetElementDriver : ElementDriver<Snippet> {
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Description résumée de Devis
/// </summary>
public class Devis
{
private int id;
private decimal? estimationPrix;
private DateTime? date;
private string nomProjet;
private String reference;
private short? etat;
private Client client;
private List<Produit> produits;
#region accesseur
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
public decimal? EstimationPrix
{
get
{
return estimationPrix;
}
set
{
estimationPrix = value;
}
}
public DateTime? Date
{
get
{
return date;
}
set
{
date = value;
}
}
public string NomProjet
{
get
{
return nomProjet;
}
set
{
nomProjet = value;
}
}
public string Reference
{
get
{
return reference;
}
set
{
reference = value;
}
}
public short? Etat
{
get
{
return etat;
}
set
{
etat = value;
}
}
public Client Client
{
get
{
return client;
}
set
{
client = value;
}
}
public List<Produit> Produits
{
get
{
return produits;
}
set
{
produits = value;
}
}
#endregion
#region constructeur
public Devis()
{
this.Produits = new List<Produit>();
}
public Devis(string nomProjet, Client SelectedClient)
{
this.NomProjet = nomProjet;
this.Client = SelectedClient;
this.Produits = new List<Produit>();
}
#endregion
public Devis(int id, decimal? estimationPrix, DateTime? date, string nomProjet, string reference, short? etat, Client client)
{
this.id = id;
this.estimationPrix = estimationPrix;
this.date = date;
this.nomProjet = nomProjet;
this.reference = reference;
this.etat = etat;
this.client = client;
this.Produits = new List<Produit>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyClassLibrary;
using System.IO;
namespace Les6Exercise3
{
//Сергей сделал метода для сортировки по 2м поялм в виде MyDelegatСourseAge, правильно ли так?
//или возможно это как то красивее? как быть если по 3м и более полям надо отсортировать?
//Ронжин Л.
//3. Переделать программу Пример использования коллекций для решения следующих задач:
//а) Подсчитать количество студентов учащихся на 5 и 6 курсах;
//б) подсчитать сколько студентов в возрасте от 18 до 20 лет на каком курсе учатся(*частотный массив);
//в) отсортировать список по возрасту студента;
//г) * отсортировать список по курсу и возрасту студента;
class Program
{
static int MyDelegatName(Student st1, Student st2) // Создаем метод для сравнения для экземпляров
{
return String.Compare(st1.firstName, st2.firstName); // Сравниваем две строки
}
static int MyDelegatAge(Student st1, Student st2) // Создаем метод для сравнения для экземпляров
{
return String.Compare(st1.age.ToString(), st2.age.ToString()); // Сравниваем две строки
}
static int MyDelegatСourse(Student st1, Student st2) // Создаем метод для сравнения для экземпляров
{
return String.Compare(st1.course.ToString(), st2.course.ToString()); // Сравниваем две строки
}
static int MyDelegatСourseAge(Student st1, Student st2) // Создаем метод для сравнения для экземпляров
{
int ires = String.Compare(st1.course.ToString(), st2.course.ToString());
if (ires == 0)
{
ires = String.Compare(st1.age.ToString(), st2.age.ToString());
}
return ires; // Сравниваем две строки
}
static void Main(string[] args)
{
int bakalavr = 0;
int magistr = 0;
List<Student> list = new List<Student>(); // Создаем список студентов
DateTime dt = DateTime.Now;
StreamReader sr = new StreamReader("students_6.csv");
while (!sr.EndOfStream)
{
try
{
string[] s = sr.ReadLine().Split(';');
// Добавляем в список новый экземпляр класса Student
list.Add(new Student(s[0], s[1], s[2], s[3], s[4], int.Parse(s[5]), int.Parse(s[6]), int.Parse(s[7]), s[8]));
// Одновременно подсчитываем количество бакалавров и магистров
if (int.Parse(s[6]) < 5) bakalavr++; else magistr++;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Ошибка!ESC - прекратить выполнение программы");
// Выход из Main
if (Console.ReadKey().Key == ConsoleKey.Escape) return;
}
}
sr.Close();
Console.WriteLine("Всего студентов:" + list.Count);
Console.WriteLine("Магистров:{0}", magistr);
Console.WriteLine("Бакалавров:{0}", bakalavr);
Console.WriteLine();
Console.WriteLine("Количество студентов в возрасте от 18 до 20 лет, на каждом курсе:");
list.Sort(new Comparison<Student>(MyDelegatСourse));
Dictionary<int, int> StodentOfCourse = new Dictionary<int, int>();
foreach (var item in list)
{
int count;
if (item.age >= 18 && item.age <= 20)
{
if (StodentOfCourse.TryGetValue(item.course, out count)) StodentOfCourse[item.course] = ++count;
else StodentOfCourse.Add(item.course, 1);
}
}
foreach (KeyValuePair<int, int> item in StodentOfCourse)
{
Console.WriteLine($"{item.Key} курс - {item.Value}");
}
Console.WriteLine();
Console.WriteLine("Список студентов по возрасту:");
list.Sort(new Comparison<Student>(MyDelegatAge));
foreach (var v in list) Console.WriteLine(v.firstName + " - " + v.age);
Console.WriteLine(DateTime.Now - dt);
Console.WriteLine();
Console.WriteLine("Список студентов по курсу и возрасту:");
list.Sort(new Comparison<Student>(MyDelegatСourseAge));
foreach (var v in list) Console.WriteLine(v.firstName + " - " + v.course + " - " + v.age);
Console.WriteLine(DateTime.Now - dt);
MyMetods.Pause();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Phenix.Core.IO;
using Phenix.Core.Security;
using Phenix.Services.Host.Core;
namespace Phenix.Services.Host.Service.Wcf
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public sealed class DownloadFiles : Phenix.Services.Contract.Wcf.IDownloadFiles
{
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public object GetDownloadFileInfos(string applicationName, IList<string> searchPatterns, UserIdentity identity)
{
try
{
ServiceManager.CheckIn(identity);
DataSecurityContext context = DataSecurityHub.CheckIn(identity, false);
return DownloadFileHelper.GetDownloadFileInfos(applicationName, searchPatterns, context.Identity);
}
catch (Exception ex)
{
return ex;
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public object GetDownloadFile(string directoryName, string sourceDirectoryName, string fileName, int chunkNumber)
{
try
{
ServiceManager.CheckActive();
return DownloadFileHelper.GetDownloadFile(directoryName, sourceDirectoryName, fileName, chunkNumber);
}
catch (Exception ex)
{
return ex;
}
}
}
} |
namespace TripDestination.Web.MVC.Areas.UserProfile.ViewModels.ChildAction
{
public class UserStatisticsViewModel
{
public int TotalTrips { get; set; }
public int CommentsCount { get; set; }
public int TripsAsDriverCount { get; set; }
public int TripsAsPassengerCount { get; set; }
}
} |
namespace RosPurcell.Web.ViewModels.Media
{
using RosPurcell.Web.Constants.Images;
using RosPurcell.Web.ViewModels.Media.Base;
public class HeroImage : BaseImage
{
public HeroImage()
{
BreakPointSet = BreakPointSet.Hero;
}
}
} |
using System;
using System.IO;
using System.Threading.Tasks;
using Core.DirectoryOvserver.Contracts;
using Core.FileManipulator.Contracts;
using Core.FileReader.Contracts;
using Core.IO;
using Core.IO.Contracts;
using Core.JsonConverter.Contracts;
using Core.Models;
using System.Threading;
namespace Core.DirectoryOvserver
{
public class DirectoryObserver : IDirectoryObserver
{
private IFileReader fileReader;
private IJsonConverter<ConfigInfo> jsonConverter;
private IFileManipulator fileManipulator;
public DirectoryObserver(
IFileReader fileReader,
IJsonConverter<ConfigInfo> jsonConverter,
IFileManipulator fileManipulator)
{
this.fileReader = fileReader;
this.jsonConverter = jsonConverter;
this.fileManipulator = fileManipulator;
}
public string ConfigFile { get; set; }
public FileSystemWatcher[] Watchers { get; private set; }
public ConfigInfo JsonInfo { get; set; }
public async Task ObserveDirectories(string path)
{
Func<Task> action = async () =>
{
IWriter writer = new ConsoleWriter();
// var configFile = this.fileReader.ReadFile("..\\..\\Configuration\\config.json");
var configFile = this.fileReader.ReadFile(path);
// writer.Write(configFile);
this.JsonInfo = this.jsonConverter.DeserializeJson(configFile);
int watchersCount = this.JsonInfo.configItems.Length;
this.Watchers = new FileSystemWatcher[watchersCount];
for (int i = 0; i < watchersCount; i++)
{
this.Watchers[i] = new FileSystemWatcher();
}
int index = 0;
foreach (var item in this.JsonInfo.configItems)
{
var watcher = this.Watchers[index];
watcher.Path = item.Source;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = item.Filter;
watcher.IncludeSubdirectories = true;
watcher.InternalBufferSize = 19999999;
watcher.Changed += async (sender, eventArgs) =>
{
var fullPath = eventArgs.FullPath;
if (this.IsFileReady(fullPath))
{
var task = Task.Run(() =>
{
var fileName = eventArgs.Name;
if (item.Action == "Move")
{
this.fileManipulator.MoveFileTo(item.Source, item.Destination, fileName);
writer.Write("Moved");
}
else if (item.Action == "Copy")
{
this.fileManipulator.CopyFileTo(item.Source, item.Destination, fileName);
writer.Write("Copied");
}
});
await task.ConfigureAwait(false);
}
await Task.Delay(100);
};
watcher.EnableRaisingEvents = true;
index++;
}
await Task.Delay(100);
// Console.WriteLine(index);
};
await Task.Run(() => action());
}
private bool IsFileReady(String sFilename)
{
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using System.Data.Entity.ModelConfiguration;
namespace DataAccessLayer.Mapping
{
public class ProjectMap: EntityTypeConfiguration<Project>
{
public ProjectMap()
{
HasKey(p => p.ID)
.Property(x => x.ID)
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
Property(p => p.Name)
.HasMaxLength(100).IsRequired();
Property(p => p.Description)
.HasMaxLength(400);
Property(p => p.State)
.HasMaxLength(50);
HasRequired(p => p.Customer)
.WithMany(c => c.Projects)
.HasForeignKey(x => x.CustomerID);
HasMany(p => p.Employees)
.WithMany(e=>e.Projects)
.Map(x=>x.ToTable("ProjectEmployee"));
Property(p => p.RealEndDate)
.IsOptional();
Property(p => p.RealStartDate)
.IsOptional();
//TODO : Buraya Bakarlar
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):CommandPoolManager.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-05 11:10:57
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-05 11:10:57
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Core.CommandHandler
{
public class CommandPoolManager:IDisposable
{
/// <summary>
/// 命令运行池
/// </summary>
private static Dictionary<string, CommandRunTimeInfo> CommandRuntimePool = new Dictionary<string, CommandRunTimeInfo>();
/// <summary>
/// 命令池管理者,全局仅一个实例
/// </summary>
private static CommandPoolManager _commandpoolmanager;
/// <summary>
/// 命令池管理操作锁标记
/// </summary>
private static object _locktag = new object();
/// <summary>
/// 静态初始化
/// </summary>
static CommandPoolManager()
{
_commandpoolmanager = new CommandPoolManager();
}
/// <summary>
/// 获取任务池的全局唯一实例
/// </summary>
/// <returns></returns>
public static CommandPoolManager CreateInstance()
{
return _commandpoolmanager;
}
public void Dispose()
{
CommandRuntimePool.Clear();
CommandRuntimePool = null;
}
/// <summary>
/// 将命令移入命令池
/// </summary>
/// <param name="taskid"></param>
/// <param name="taskruntimeinfo"></param>
/// <returns></returns>
public bool Add(string commanddetailid, CommandRunTimeInfo commandruntimeinfo)
{
lock (_locktag)
{
if (!CommandRuntimePool.ContainsKey(commanddetailid))
{
CommandRuntimePool.Add(commanddetailid, commandruntimeinfo);
return true;
}
return false;
}
}
/// <summary>
/// 将任务移出任务池
/// </summary>
/// <param name="taskid"></param>
/// <returns></returns>
public bool Remove(string commanddetailid)
{
lock (_locktag)
{
if (CommandRuntimePool.ContainsKey(commanddetailid))
{
var taskruntimeinfo = CommandRuntimePool[commanddetailid];
CommandRuntimePool.Remove(commanddetailid);
return true;
}
return false;
}
}
/// <summary>
/// 获取任务池中任务运行时信息
/// </summary>
/// <param name="taskid"></param>
/// <returns></returns>
public CommandRunTimeInfo Get(string commanddetailid)
{
if (!CommandRuntimePool.ContainsKey(commanddetailid))
{
return null;
}
lock (_locktag)
{
if (CommandRuntimePool.ContainsKey(commanddetailid))
{
return CommandRuntimePool[commanddetailid];
}
return null;
}
}
/// <summary>
/// 获取任务列表
/// </summary>
/// <returns></returns>
public List<CommandRunTimeInfo> GetList()
{
return CommandRuntimePool.Values.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Android.Graphics;
using Android.Text;
using Android.Text.Style;
namespace Goosent.Adapters
{
class ChatMessagesArrayAdapter : BaseAdapter<string>
{
List<UserMessage> _messages;
private Context mContext;
public ChatMessagesArrayAdapter(Context context, List<UserMessage> messages)
{
_messages = messages;
mContext = context;
}
public override string this[int position]
{
get { return _messages[position].userName; }
}
public override int Count
{
get { return _messages.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.ChatListViewRow, null, false);
}
TextView chatMessageTextTextView = (TextView)row.FindViewById(Resource.Id.chatMessages_row_textView);
string htmlChatRow = "";
htmlChatRow += "<html><body><font color='" + _messages[position].userColorHex + "'>" + _messages[position].userName + "</font>" + "<font>: " + _messages[position].userMessageText + "</font></body></html>";
//SpannableString chatMessageSpannableString = new SpannableString(new Java.Lang.String(_messages[position].userName + ": " +_messages[position].userMessageText));
//chatMessageSpannableString.SetSpan(new ForegroundColorSpan(_messages[position].userColor), 0, _messages[position].userName.Length, SpanTypes.ExclusiveExclusive);
//chatUserNameTextView.Text = _messages[position].userName;
//chatUserNameTextView.SetTextColor(_messages[position].userColor);
//chatMessageTextTextView.TextFormatted = chatMessageSpannableString;
chatMessageTextTextView.TextFormatted = Html.FromHtml(htmlChatRow);
return row;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CinemaProject.CinemaCervises;
namespace CinemaProject
{
/// <summary>
/// Interaction logic for LoginPage.xaml
/// </summary>
public partial class LoginPage : Page
{
private LoginViewModel VM;
private CancellationTokenSource cts;
public LoginPage(ref CancellationTokenSource cts)
{
InitializeComponent();
this.cts = cts;
}
private void Login_Click(object sender, RoutedEventArgs e)
{
User temp = null;
try
{
temp = Server.ValidateUser(VM.Email, pw.Password.MD5Hash());
}
catch (EndpointNotFoundException)
{
MessageBox.Show("Server is offline");
new Server();
return;
}
switch (temp.UserType1)
{
case UserType.AverageUser:
case UserType.Moderator://moderator will simply see some extra button in comments and no reservation
NavigationService.Navigate(new UserPage(ref cts, temp));
break;
case UserType.Administrator://he will have a unique page
NavigationService.Navigate(new AdminPage());
break;
default:
MessageBox.Show("Email/Password error");
break;
}
}
private void Register_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new RegisterPage(ref cts));
}
private void Email_OnKeyUp(object sender, KeyEventArgs e)
{
if (VM.Email == null || VM.Email == "" || VM.Email.IsEmail())
{
VM.SetWarning(String.Empty, LoginWarningType.Email);
}
else
{
VM.SetWarning("Bad email format: example@example.example", LoginWarningType.Email);
}
}
private void LoginPage_OnLoaded(object sender, RoutedEventArgs e)
{
VM = new LoginViewModel();
DataContext = VM;
}
private void Pw_OnKeyUp(object sender, KeyEventArgs e)
{
if (pw.Password.Length < 4)
{
VM.SetWarning("Pasword is at least 4 characters", LoginWarningType.Password);
}
else
{
VM.SetWarning(String.Empty, LoginWarningType.Password);
}
}
}
}
|
using System.Collections.Generic;
using Assets.Scripts.Models;
using Assets.Scripts.UI.Interactive;
using UnityEngine;
using System.Collections;
namespace Assets.Scripts.Controllers.UsableObjects
{
public class GardenBedInteractive : UsableObject, IInventoryThing
{
public List<Transform> Places;
private GardenBedPanel _panel;
private InventoryBase _inventory;
private bool _slotInited;
private GameManager _gameManager;
private bool _isUsing;
private GardenBedState _currentState = GardenBedState.Available;
private HolderObject _currentItem;
private List<GameObject> _placedItems = new List<GameObject>();
private int _maxSeeds = 10;
private bool _itemsInitialized;
private int _currentStage;
protected override void Init()
{
base.Init();
if (!_slotInited)
{
_inventory = new InventoryBase();
_inventory.Init(1);
}
_gameManager = GameObject.FindWithTag("GameManager").GetComponent<GameManager>();
StartCoroutine(RefreshProgress());
}
public override void Use(GameManager gameManager)
{
if (gameManager.DisplayManager.CurrentInteractPanel != null)
return;
base.Use(gameManager);
if (_panel == null)
{
_panel = NGUITools.AddChild(gameManager.UiRoot.gameObject, InteractPanelPrefab).GetComponent<GardenBedPanel>();
_panel.Init(GameManager, _inventory, OnPlantAction, OnGetHarvestAction);
_panel.Hide();
}
if (!_panel.IsShowing)
StartCoroutine(_panel.ShowDelay(0.2f, _currentItem, _currentState));
}
private IEnumerator RefreshProgress()
{
while (true)
{
yield return new WaitForSeconds(1f);
if (_currentState == GardenBedState.InProgress)
{
if(_currentItem.CurrentDurability > 1)
_currentItem.ChangeDurability(1);
UpdateItemsPrefabs();
if (_currentItem.CurrentDurability <= _currentItem.Item.GardenTimeStage3)
{
_currentState = GardenBedState.Finished;
if (_panel != null)
{
_panel.CurrentState = GardenBedState.Finished;
_panel.UpdateView();
}
}
}
if (_currentState == GardenBedState.Finished && _currentItem.CurrentDurability > 1)
{
_currentItem.ChangeDurability(1);
UpdateItemsPrefabs();
}
}
}
private IEnumerator UpdateItemsPrefabsDelay()
{
bool stop = false;
while (!stop)
{
if (_gameManager == null)
yield return new WaitForSeconds(0.1f);
else
{
UpdateItemsPrefabs();
stop = true;
}
}
yield break;
}
private void InstatiateItems(string prefabPath)
{
//if (_itemsInitialized)
// return;
RemoveItemPrefabs();
for (int i = 0; i < Places.Count; i++)
{
if (_placedItems.Count <= i)
{
var prefab = Resources.Load<GameObject>(prefabPath);
var go = Instantiate(prefab);
go.transform.parent = Places[i];
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
_placedItems.Add(go);
}
}
_itemsInitialized = true;
}
private void UpdateItemsPrefabs()
{
if (_currentItem == null || _currentItem.Item == null)
return;
//var durability = (int)_currentItem.Item.Durability;
var curDurability = (int)_currentItem.CurrentDurability;
//var scaleFactor = 1 - (float)curDurability / durability;
if (curDurability <= 1)
{
if (_currentStage != 4)
{
InstatiateItems(_currentItem.Item.GardenPlacedPrefabWithered);
_currentStage = 4;
if (_panel != null)
_panel.UpdateView();
}
}
else if (_currentItem.CurrentDurability <= _currentItem.Item.GardenTimeStage1 && _currentStage != 1 && _currentStage != 2 && _currentStage != 3 && _currentStage != 4)
{
InstatiateItems(_currentItem.Item.GardenPlacedPrefabStage1);
_currentStage = 1;
}
else if (_currentItem.CurrentDurability <= _currentItem.Item.GardenTimeStage2 && _currentStage != 2 && _currentStage != 3 && _currentStage != 4)
{
InstatiateItems(_currentItem.Item.GardenPlacedPrefabStage2);
_currentStage = 2;
}
else if (_currentItem.CurrentDurability <= _currentItem.Item.GardenTimeStage3 && _currentStage != 3 && _currentStage != 4)
{
InstatiateItems(_currentItem.Item.GardenPlacedPrefabStage3);
_currentStage = 3;
}
//foreach (var placedItem in _placedItems)
//{
// var durability = (int)_currentItem.Item.Durability;
// var curDurability = (int)_currentItem.CurrentDurability;
// var scaleFactor = 1 - (float)curDurability / durability;
// placedItem.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
//}
}
private void RemoveItemPrefabs()
{
foreach (var placedItem in _placedItems)
Destroy(placedItem);
_placedItems.Clear();
}
private void SetCurretnItem(HolderObject itemHolder)
{
_currentItem = itemHolder;
_currentState = GardenBedState.InProgress;
}
private void GeHarvest(HolderObject itemHolder)
{
_currentState = GardenBedState.Available;
var gardenResult = _currentItem.Item.GardenResult;
if (_currentItem.CurrentDurability <= 1)
gardenResult = _currentItem.Item.GardenWitheredResult;
var result = new HolderObject(gardenResult.Key.GetType(), gardenResult.Value * _maxSeeds);
if(!_gameManager.PlayerModel.Inventory.AddItem(result))
GameManager.PlacementItemsController.DropItemToGround(GameManager, result);
_inventory.RemoveItem(_currentItem);
_currentItem = null;
RemoveItemPrefabs();
_itemsInitialized = false;
_currentStage = 0;
}
private void OnPlantAction(HolderObject itemHolder)
{
SetCurretnItem(itemHolder);
}
private void OnGetHarvestAction(HolderObject itemHolder)
{
GeHarvest(itemHolder);
}
public bool IsUsing()
{
_isUsing = false;
if (_panel.IsShowing)
_isUsing = true;
return _isUsing;
}
public List<InventoryBase> GetInventoryList()
{
if (_currentItem != null)
_inventory.AddItem(HolderObjectFactory.GetItem(_currentItem.Item.GetType(), _currentItem.Amount, _currentItem.CurrentDurability));
var list = new List<InventoryBase> {_inventory};
return list;
}
public void SetInventoryList(List<InventoryBase> inventoryList)
{
if (inventoryList != null && inventoryList.Count > 0)
{
_inventory = inventoryList[0];
foreach (var inventorySlot in _inventory.Slots)
{
if (inventorySlot != null && inventorySlot.Item != null)
{
_currentItem = inventorySlot;
if (_currentItem.CurrentDurability > 0)
_currentState = GardenBedState.InProgress;
else
{
_currentState = GardenBedState.Finished;
if (_panel != null)
_panel.CurrentState = GardenBedState.Finished;
StartCoroutine(UpdateItemsPrefabsDelay());
}
}
}
}
_slotInited = true;
}
}
}
|
using System;
namespace PerfectNumber
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 10000; i++)
{
int sum = 0;
for (int j = 1; j < i; j++)
{
if (i % j == 0) sum += j;
}
if (sum == i) Console.WriteLine("Perfect number is " + i);
}
}
}
}
|
using Etherama.Common;
using Nethereum.Hex.HexTypes;
using Nethereum.Web3;
using NLog;
using System;
using System.Numerics;
using System.Threading.Tasks;
using Nethereum.RPC.Eth.DTOs;
namespace Etherama.CoreLogic.Services.Blockchain.Ethereum.Impl {
public sealed class EthereumWriter : EthereumBaseClient, IEthereumWriter {
public EthereumWriter(AppConfig appConfig, LogFactory logFactory) : base(appConfig, logFactory) {
}
public async Task<string> UpdateMaxGaxPrice(BigInteger gasPrice)
{
var txid = await Web3Utils.SendTransaction(AppConfig.Services.Ethereum.EtheramaCoreAddress,
AppConfig.Services.Ethereum.EtheramaCoreAbi, AppConfig.Services.Ethereum.SetMaxGasPriceFunctionName,
AppConfig.Services.Ethereum.ManagerPrivateKey, 100000, gasPrice, 0, gasPrice);
return txid;
}
}
}
|
using System;
using System.Collections.Generic;
using SnowBLL.Service.Interfaces;
using SnowDAL.DBModels;
using SnowDAL.Repositories.Interfaces;
using System.Linq;
using SnowBLL.Models;
using System.Threading.Tasks;
using SnowBLL.Enums;
using SnowBLL.Models.Routes;
using SnowDAL.Searching;
using SnowDAL.Sorting;
using SnowBLL.Resolvers;
using SnowBLL.Helpers;
using SnowBLL.Models.Geo;
using Microsoft.Extensions.Logging;
using System.Globalization;
using SnowBLL.Models.Users;
namespace SnowBLL.Service.Concrete
{
public class RouteBLService : BLService, IRouteBLService
{
#region Members
private IRouteRepository _routeRepository;
private IUserResolver _userResolver;
private IRoutePointRepository _pointRepository;
#endregion Members
#region Constructor
public RouteBLService(ILogger<BLService> logger, IRouteRepository repository, IUserResolver userResolver, IRoutePointRepository pointRepository) : base(logger)
{
_routeRepository = repository;
_userResolver = userResolver;
_pointRepository = pointRepository;
}
#endregion Constructor
#region Public Methods
public async Task<Result<RouteDetailsViewModel>> GetRouteById(IdModel model)
{
try
{
var query = new SearchQuery<RouteInfoEntity>();
RouteInfoEntity result = await _routeRepository.GetSingleWithDependencies(model.Id);
if (result == null)
{
ErrorResult error = GenerateError("Route not found", "Id", "Invalid identifier", ErrorStatus.ObjectNotFound);
return new Result<RouteDetailsViewModel>(error);
}
var viewModel = new RouteDetailsViewModel()
{
Difficulty = result.Difficulty,
Id = result.ID,
Name = result.Name,
UserId = result.UserId,
User = new UserListItemModel()
{
Email = result.User.Email,
Id = result.User.ID,
Name = result.User.Name,
RoutesCount = result.User.Routes.Count
},
Geometry = new RouteGeometry()
{
Id = result.Geometry.ID,
Points = GeoPointConverter.GetPoints(result.Geometry.Line),
},
MainPoint = GeoPointConverter.GetPoint(result.Point.Point)
};
return new Result<RouteDetailsViewModel>(viewModel);
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<RouteDetailsViewModel>(error);
}
}
public async Task<Result<ListResult<RouteInfo>>> GetAllRoutes(CollectionRequestModel model)
{
try
{
var query = new SearchQuery<RouteInfoEntity>();
ApplySorting(model, query);
ApplyFilters(model, query);
ApplyPaging(model, query);
var results = await _routeRepository.Search(query);
var listResult = new ListResult<RouteInfo>()
{
Count = results.Count,
HasNext = results.HasNext,
Results = results.Results.Select(r => new RouteInfo() { Id = r.ID, Name = r.Name, Difficulty = (Difficulty)r.Difficulty, UserId = r.UserId }).ToList()
};
return new Result<ListResult<RouteInfo>>(listResult);
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<ListResult<RouteInfo>>(error);
}
}
public async Task<Result<ListResult<RouteInfo>>> GetRoutesInRange(RoutesInRangeRequestModel model)
{
try
{
var query = new QueryPager();
ApplyPaging(model, query);
string point = $"POINT({model.Point.Lng} {model.Point.Lat})";
var results = await _routeRepository.GetRoutesInRange(query, point, model.Kilometers);
var listResult = new ListResult<RouteInfo>()
{
Count = results.Count,
HasNext = results.HasNext,
Results = results.Results.Select(r => new RouteInfo() { Id = r.ID, Name = r.Name, Difficulty = (Difficulty)r.Difficulty, UserId = r.UserId }).ToList()
};
return new Result<ListResult<RouteInfo>>(listResult);
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<ListResult<RouteInfo>>(error);
}
}
public async Task<Result<IEnumerable<RouteGeometry>>> GetGeometries(string routes)
{
try
{
if (!string.IsNullOrEmpty(routes))
{
var routesArr = routes.Split(',').Select<string, int>(int.Parse).ToArray();
var entities = await _routeRepository.GetGeometries(routesArr);
if (entities.Any())
{
var models = entities.Select(r => new RouteGeometry()
{
Id = r.ID,
Points = GeoPointConverter.GetPoints(r.Line)
});
return new Result<IEnumerable<RouteGeometry>>(models);
}
else
{
ErrorResult error = GenerateError("Routes not found", "Routes", "Invalid identifiers", ErrorStatus.ObjectNotFound);
return new Result<IEnumerable<RouteGeometry>>(error);
}
}
else
{
ErrorResult error = GenerateError("Route not found", "Routes", "Invalid identifier", ErrorStatus.ObjectNotFound);
return new Result<IEnumerable<RouteGeometry>>(error);
}
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<IEnumerable<RouteGeometry>>(error);
}
}
public async Task<Result<ListResult<RoutePoint>>> GetPoints(PagingRequestModel model, string routes)
{
try
{
var pager = new QueryPager();
ApplyPaging(model, pager);
var results = await _pointRepository.Search(pager);
var listResult = new ListResult<RoutePoint>()
{
Count = results.Count,
HasNext = results.HasNext,
Results = results.Results.Select(r => new RoutePoint()
{
Id = r.RouteInfo.ID,
Point = GeoPointConverter.GetPoint(r.Point)
}).ToList()
};
return new Result<ListResult<RoutePoint>>(listResult);
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<ListResult<RoutePoint>>(error);
}
}
public async Task<Result<int>> Create(RouteCreateModel item)
{
try
{
if (await _userResolver.IsConfirmed())
{
string line = $"LINESTRING({item.Line})";
bool isValidLine = _routeRepository.IsValidLine(line);
if (isValidLine)
{
string point = RouteHelper.GetFirstPoint(item.Line);
var user = await _userResolver.GetUser();
var infoEntity = new RouteInfoEntity()
{
Difficulty = item.Difficulty,
Name = item.Name,
Geometry = new RouteGeomEntity()
{
Line = line,
Status = 1
},
UserId = user.Id,
Point = new RoutePointEntity()
{
Point = $"POINT({point})",
Status = 1
}
};
_routeRepository.Add(infoEntity);
await _routeRepository.Commit();
return new Result<int>(infoEntity.ID);
}
else
{
ErrorResult error = GenerateError("Invalid route line", "Line", "Invalid geometry", ErrorStatus.InvalidModel);
return new Result<int>(error);
}
}
else
{
ErrorResult error = GenerateError("User is not confirmed", "", "", ErrorStatus.Forbidden);
return new Result<int>(error);
}
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<int>(error);
}
}
public async Task<Result<object>> Update(int id, RouteUpdateModel item)
{
try
{
var entity = _routeRepository.GetSingle(id);
if (entity != null)
{
if (await CheckUsersPermission(entity))
{
if (await _userResolver.IsConfirmed())
{
entity.Difficulty = item.Difficulty;
entity.Name = item.Name;
_routeRepository.Update(entity);
await _routeRepository.Commit();
return new Result<object>();
}
else
{
ErrorResult error = GenerateError("User is not confirmed", "", "", ErrorStatus.Forbidden);
return new Result<object>(error);
}
}
else
{
ErrorResult error = GenerateError("Action forbidden", "", "", ErrorStatus.Forbidden);
return new Result<object>(error);
}
}
else
{
ErrorResult error = GenerateError("Route not found", "Id", "Invalid identifier", ErrorStatus.ObjectNotFound);
return new Result<object>(error);
}
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<object>(error);
}
}
public async Task<Result<object>> Remove(IdModel item, bool instantCommit = true)
{
try
{
var entity = _routeRepository.GetSingle(item.Id);
if (entity != null)
{
if (await CheckUsersPermission(entity))
{
if (await _userResolver.IsConfirmed())
{
_routeRepository.Delete(entity);
if (entity.Point != null)
{
entity.Point.Status = 1;
}
if (entity.Geometry != null)
{
entity.Geometry.Status = 1;
}
if (instantCommit)
{
await _routeRepository.Commit();
}
return new Result<object>();
}
else
{
ErrorResult error = GenerateError("User is not confirmed", "", "", ErrorStatus.Forbidden);
return new Result<object>(error);
}
}
else
{
ErrorResult error = GenerateError("Action forbidden", "", "", ErrorStatus.Forbidden);
return new Result<object>(error);
}
}
else
{
ErrorResult error = GenerateError("Route not found", "Id", "Invalid identifier", ErrorStatus.ObjectNotFound);
return new Result<object>(error);
}
}
catch (Exception ex)
{
ErrorResult error = GenerateError(ex);
return new Result<object>(error);
}
}
#endregion Public Methods
#region Private Methods
private static void ApplyPaging(IPagingRequestModel model, IQueryPaging query)
{
int page = model.Page ?? 1;
int pagesize = model.PageSize ?? 100;
query.Skip = pagesize * (page - 1);
query.Take = pagesize;
}
private static void ApplySorting(CollectionRequestModel model, SearchQuery<RouteInfoEntity> query)
{
if (!string.IsNullOrEmpty(model.Sort))
{
query.AddSortCriteria(FiltrationHelper.GetSorting<RouteInfoEntity>(model.Sort));
}
else
{
query.AddSortCriteria(new FieldSortOrder<RouteInfoEntity>("Name", SortDirection.Ascending));
}
}
private static void ApplyFilters(CollectionRequestModel model, SearchQuery<RouteInfoEntity> query)
{
if (!string.IsNullOrEmpty(model.Filter))
{
var filters = FiltrationHelper.GetFilter<RouteFiltrationModel>(model.Filter);
query.FiltersDictionary = FiltrationHelper.ConvertToDictionary(filters);
}
}
private async Task<bool> CheckUsersPermission(RouteInfoEntity entity)
{
var user = await _userResolver.GetUser();
return user != null && (user.Id == entity.UserId || user.Role == Role.Admin);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Labb3Lonerevision
{
class Program
{
static void Main(string[] args)
{
do
{
Console.Clear();
int amountOfSalaries = ReadInt("Ange antal löner att mata in: "); //startar metoden ReadInt och skickar med en prompt
Console.WriteLine();
if (amountOfSalaries < 2) //om antal löner är mindre än 2 så får man ett felmeddelande och man får försöka igen...
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Antal löner måste vara 2 eller mer!");
Console.ResetColor();
}
else
{
ProcessSalaries(amountOfSalaries); //...annars startar den metoden ProcessSalaries
}
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("\nTryck valfri tangent för ny uträkning - ESC avslutar ");
Console.ResetColor();
}
while (Console.ReadKey(true).Key != ConsoleKey.Escape); //...när man loopat "do-while"-loopen får man skriva in en key och så länge den inte är ESC så fortsätter loopen
}
static int ReadInt(string prompt) //readint läser in allt.
{
while (true)
{
Console.Write(prompt);
string userInput = Console.ReadLine(); //skriver in userInput innan try catch och innan omvandling till int för att kunna använda den i både try och catch
try
{
int value = int.Parse(userInput);
return value;
}
catch
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("Ogiltig summa. '{0}' kan inte tolkas som ett heltal! Var god försök igen", userInput);
Console.ResetColor();
}
}
}
static void ProcessSalaries(int count) //ProcessSalaries behandlar alla siffror och uträkningar. Tar emot värdet från "amountOfSalaries" som den lägger in i integern "count"
{
int[] salaries = new int[count]; //är min osorterade array
int[] sortedSalaries = new int[count]; // kommer vara min sorterade array
for (int i = 0; i < count; i++) //Loopar lika långt som arrayen är och man får skriva in varje "låda" en efter en.
{ //Count är hur lång arrayen är och det man fick ge ett värde första gången.
salaries[i] = ReadInt(String.Format("Ange lön nummer {0}: ", (i+1)));
}
sortedSalaries = (int[])salaries.Clone();
Array.Sort(sortedSalaries);
int median;
if (count % 2 == 0) //om antal löner är jämnt måste den ta de två mittersta talet och dividera det med varandra för att få medianen.
{
int number1 = count / 2; //Tar det största mittersta "lådnummret" Ex) Längden på arrayen är 6. Då behöver man 2 och 3 (eftersom array börjar på 0, 1, 2...)
int number2 = number1 - 1; //tar det mindre mittersta "lådnummret" ) 6/2=3, 3-1=2
median = (sortedSalaries[number1] + sortedSalaries[number2])/2; // tar värderna från respektive "låda" och lägger ihop dem sedan delar det på två. variabeln "median" får värdet
}
else
{
median = sortedSalaries[count / 2]; //ojämn tal behöver bara delas på 2. ex) 5/2 = 2,5 = 2 eftersom det är en integer.
}
Console.WriteLine("---------------------------------------");
Console.WriteLine("Medianlön: {0,10:C0}", median);
Console.WriteLine("Medellön: {0,10:C0}", sortedSalaries.Average()); //räknar ut medellönen
Console.WriteLine("Lönespridning: {0,10:C0}",sortedSalaries.Max() - sortedSalaries.Min()); //max-min = lönesspridning
Console.WriteLine("---------------------------------------");
for (int i = 0; i < count; i++) //skriver ut lönerna i den ordning man skrev in dem i
{
if (i % 3 == 0) //var tredje rad gör den en radbrytning
{
Console.WriteLine();
}
Console.Write("{0,10}", salaries[i]);
}
}
}
}
|
using MediatR;
using AspNetCoreGettingStarted.Data;
using AspNetCoreGettingStarted.Model;
using AspNetCoreGettingStarted.Features.Core;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Threading;
namespace AspNetCoreGettingStarted.Features.DashboardTiles
{
public class AddOrUpdateDashboardTileCommand
{
public class Request : BaseAuthenticatedRequest, IRequest<Response>
{
public DashboardTileApiModel DashboardTile { get; set; }
public int UserId { get; set; }
}
public class Response { }
public class Handler : IRequestHandler<Request, Response>
{
public Handler(IAspNetCoreGettingStartedContext context)
{
_context = context;
}
public async Task<Response> Handle(Request request, CancellationToken cancellationToken)
{
var entity = await _context.DashboardTiles
.Include(x => x.Tenant)
.Include(x => x.Dashboard)
.Include("Dashboard.DashboardTiles")
.SingleOrDefaultAsync(x => x.DashboardTileId == request.DashboardTile.DashboardTileId && x.Tenant.TenantId == request.TenantId);
if (entity == null)
{
var tenant = await _context.Tenants.SingleAsync(x => x.TenantId == request.TenantId);
var dashboard = _context.Dashboards
.Include(x => x.DashboardTiles)
.Single(x => x.DashboardId == request.DashboardTile.DashboardId.Value
&& x.Tenant.TenantId == request.TenantId);
_context.DashboardTiles.Add(entity = new DashboardTile() { Tenant = tenant });
dashboard.DashboardTiles.Add(entity);
}
entity.Name = request.DashboardTile.Name;
entity.Top = request.DashboardTile.Top;
entity.Left = request.DashboardTile.Left;
entity.Width = request.DashboardTile.Width;
entity.Height = request.DashboardTile.Height;
await _context.SaveChangesAsync(cancellationToken);
return new Response();
}
private readonly IAspNetCoreGettingStartedContext _context;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Level3.Controllers
{
public class ArticleController : Controller
{
public IActionResult article()
{
//Implement here
return View();
}
}
} |
using ND.FluentTaskScheduling.Helper;
using ND.FluentTaskScheduling.Model;
using ND.FluentTaskScheduling.Model.request;
using ND.FluentTaskScheduling.Model.response;
using ND.FluentTaskScheduling.Web.App_Start;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ND.FluentTaskScheduling.Web.Controllers
{
public class LoginController : Controller
{
public LoginController()
{
// HttpContext.Session["LoginUserInfo"] = null;
}
// GET: Login
public ActionResult Index()
{
return View();
}
public ActionResult Logout()
{
HttpContext.Session["LoginUserInfo"] = null;
return RedirectToAction("/Index");
}
[HttpPost]
public JsonResult Index(string username,string password)
{
ResponseBase<CheckUNameAndPwdResponse> result = PostToServer<CheckUNameAndPwdResponse, CheckUNameAndPwdRequest>(ClientProxy.CheckUNameAndPwd_Url, new CheckUNameAndPwdRequest() { Source = Source.Web, UserName = username, Password = password });
if(result.Status == ResponesStatus.Success)//校验成功,则登录
{
//写入session
HttpContext.Session["LoginUserInfo"] = result.Data.UserInfo;
}
return Json(result);
}
public ResponseBase<TResponse> PostToServer<TResponse, TRequest>(string url, TRequest request)
where TResponse : class
where TRequest : RequestBase
{
ResponseBase<TResponse> r = HttpClientHelper.PostResponse<ResponseBase<TResponse>>(url, JsonConvert.SerializeObject(request));
return r;
}
}
} |
using System;
using System.Windows.Forms;
namespace Project_PERT_Add_in_2016
{
public partial class frmSobre : Form
{
public frmSobre()
{
InitializeComponent();
string sVersion = "1.0";
if (Properties.Settings.Default.Language.ToString() == "English")
{
this.Text = "About";
okButton.Text = "Close";
lblVersao.Text = "Version: " + sVersion;
}
else if (Properties.Settings.Default.Language.ToString() == "Italian")
{
this.Text = "Informazioni";
okButton.Text = "Chiudi";
lblVersao.Text = "Versione: " + sVersion;
}
else if (Properties.Settings.Default.Language.ToString() == "Spanish")
{
this.Text = "Sobre";
okButton.Text = "Cerrar";
lblVersao.Text = "Versión: " + sVersion;
}
else if (Properties.Settings.Default.Language.ToString() == "French")
{
this.Text = "A propos";
okButton.Text = "Fermer";
lblVersao.Text = "Version: " + sVersion;
}
else
{
this.Text = "Sobre";
okButton.Text = "Fechar";
lblVersao.Text = "Versão: " + sVersion;
}
}
private void okButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PromoteScript : MonoBehaviour
{
public int MaxPromotes;
public float[] Payments;
public float[] JobExpNeeded;
private int _currentProm;
private int _nextProm = 1;
private WorkManagerScript _workManager;
private ApplyForJobScript _applyForJob;
private PlayerInfoManagerScript _playerInfoManager;
void Start ()
{
MaxPromotes = Payments.Length;
_applyForJob = GetComponent<ApplyForJobScript>();
_workManager = _applyForJob.GetComponent<WorkManagerScript>();
_playerInfoManager = _workManager.GetComponent<PlayerInfoManagerScript>();
}
void CheckForPromotion()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EFCrudDEMO.Model
{
public class CallContext : DbContext
{
public CallContext() : base("name=con")
{
Database.SetInitializer(new CallDbInititializer());
}
public DbSet<Call> Calls { get; set; }
}
}
|
using BHLD.Model.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Data
{
public class BHLDDbContext : DbContext
{
public BHLDDbContext() : base("BHLDConnection")
{
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<hu_district> hu_Districts { set; get; }
public DbSet<hu_employee> hu_Employees { set; get; }
public DbSet<hu_employee_cv> hu_Employee_Cvs { set; get; }
public DbSet<hu_nation> hu_Nations { set; get; }
public DbSet<hu_org_title> hu_Org_Titles { set; get; }
public DbSet<hu_organization> hu_Organizations { set; get; }
public DbSet<hu_protection> hu_Protections { set; get; }
public DbSet<hu_protection_emp> hu_Protection_Emps { set; get; }
public DbSet<hu_protection_emp_setting> hu_Protection_Emp_Settings { set; get; }
public DbSet<hu_protection_setting> hu_Protection_Settings { set; get; }
public DbSet<hu_protection_size> hu_Protection_Sizes { set; get; }
public DbSet<hu_protection_title> hu_Protection_Titles { set; get; }
public DbSet<hu_protection_title_setting> hu_Protection_Title_Settings { set; get; }
public DbSet<hu_province> hu_Provinces { set; get; }
public DbSet<hu_shoes_setting> hu_Shoes_Settings { set; get; }
public DbSet<hu_shoes_size> hu_Shoes_Sizes { set; get; }
public DbSet<hu_title> hu_Titles { set; get; }
public DbSet<hu_ward> hu_Wards { set; get; }
public DbSet<ot_other_list> ot_Other_Lists { set; get; }
public DbSet<ot_other_list_type> ot_Other_List_Types { set; get; }
public DbSet<se_function> se_Functions { set; get; }
public DbSet<se_function_group> se_Function_Groups { set; get; }
public DbSet<se_report> se_Reports { set; get; }
public DbSet<se_user> se_Users { set; get; }
public DbSet<se_user_org_access> se_User_Org_Accesses { set; get; }
public DbSet<se_user_permission> se_User_Permissions { set; get; }
public DbSet<se_user_report> se_User_Reports { set; get; }
public DbSet<synthetic> synthetics { set; get; }
public DbSet<Error> errors { set; get; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CameraInterface.Cameras
{
public class SamsungCamera : ICamera
{
public bool _isActive;
public bool isActive
{
get
{
{ return _isActive; };
}
set
{
{ _isActive = value; }
}
}
public ActionResult Activate()
{
if (!_isActive)
{
_isActive = true;
return new ActionResult("Camera Samsung has been activated", _isActive);
}
else
{
return new ActionResult(" Error Camera Samsung has been already active", _isActive);
}
}
public ActionResult ChargeCamera()
{
return new ActionResult(" Camera was completly Charged!", true);
}
public ActionResult DeActivate()
{
if (_isActive)
{
_isActive = false;
return new ActionResult("Camera Samsung has been Deactivated", _isActive);
}
else
{
return new ActionResult(" Error Camera Samsung has been already Deactived", _isActive);
}
}
public ActionResult SetCamera()
{
if (_isActive)
{
return new ActionResult(" Ok all Camera's Samsung settings has been applied ", _isActive);
}
else
{
return new ActionResult(" Error was not possible set Camera Samsung because was already Deactive ", _isActive);
}
}
public ImagePhoto TakeSnap()
{
if (_isActive)
{
return new ImagePhoto(@"C:\myImagesSamsung\myImage", DateTime.Now, ".jpg", true);
}
else
{
return new ImagePhoto("noActiveSamsungCamera", DateTime.Now, "noActive",true);
}
}
}
}
|
using PhotonInMaze.Common.Model;
using System.Collections.Generic;
using UnityEngine;
namespace PhotonInMaze.Maze {
internal struct ObjectMazeCell {
internal IMazeCell cell;
internal GameObject gameObject;
public ObjectMazeCell(IMazeCell cell, GameObject gameObject) {
this.cell = cell;
this.gameObject = gameObject;
}
public override bool Equals(object obj) {
if(!(obj is ObjectMazeCell)) {
return false;
}
var cell = (ObjectMazeCell)obj;
return EqualityComparer<IMazeCell>.Default.Equals(this.cell, cell.cell) &&
EqualityComparer<int>.Default.Equals(gameObject.GetInstanceID(), cell.gameObject.GetInstanceID());
}
public override int GetHashCode() {
var hashCode = 574081665;
hashCode = hashCode * -1521134295 + EqualityComparer<IMazeCell>.Default.GetHashCode(cell);
hashCode = hashCode * -1521134295 + EqualityComparer<int>.Default.GetHashCode(gameObject.GetInstanceID());
return hashCode;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;
using IRAP.Global;
using IRAP.Entity.MDM;
using IRAP.WebService.Client.UES;
namespace IRAP.MDC.Service
{
public class RecordData
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
/// <summary>
/// 社区标识
/// </summary>
private int communityID = 60010;
private string source = "";
private string data = "";
private RegInstrument instrument = null;
private string activeMQ_BrokerUri = "";
private string activeMQ_QueueName = "";
/// <summary>
/// 实际测量值
/// </summary>
private long metric01 = 0;
private IConnectionFactory factory = null;
public RecordData(string source, string data)
{
this.source =
source.Substring(
0,
source.IndexOf(':'));
this.data = data;
instrument = TRegisterInstruments.Instance.GetItem(this.source);
string strProcedureName =
string.Format(
"{0}.{1}:{2}",
className,
MethodBase.GetCurrentMethod().Name,
source);
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
#region 获取系统配置参数
if (config.AppSettings.Settings["CommunityID"] != null)
{
string temp = config.AppSettings.Settings["CommunityID"].Value.ToString();
Int32.TryParse(temp, out communityID);
if (communityID == 0)
communityID = 60010;
}
#endregion
#region 获取 ActiveMQ 连接参数
if (config.AppSettings.Settings["ActiveMQ_BrokerUri"] != null)
activeMQ_BrokerUri =
config.AppSettings.Settings["ActiveMQ_BrokerUri"].Value.ToString();
if (config.AppSettings.Settings["ActiveMQ_QueueName"] != null)
activeMQ_QueueName =
config.AppSettings.Settings["ActiveMQ_QueueName"].Value.ToString();
#endregion
#region 初始化 ActiveMQ
if (activeMQ_BrokerUri.Trim() != "" &&
activeMQ_QueueName.Trim() != "")
{
try
{
factory = new ConnectionFactory(activeMQ_BrokerUri);
}
catch (Exception error)
{
WriteLog.Instance.Write(
string.Format(
"初始化 ActiveMQ 失败:{0}",
error.Message),
strProcedureName);
}
}
else
{
WriteLog.Instance.Write("无法初始化 ActiveMQ", strProcedureName);
}
#endregion
}
public bool DataValid()
{
string strProcedureName =
string.Format(
"{0}.{1}:{2}",
className,
MethodBase.GetCurrentMethod().Name,
source);
if (instrument == null)
{
// 量仪还未在系统注册,不接受任何测量数据
WriteLog.Instance.Write(
string.Format(
"量仪[{0}]还未在系统中注册,暂时不接受任何测量数据",
source),
strProcedureName);
return false;
}
else
{
if (data.Length == instrument.LengthOfDataMsg)
{
double fltMetric01 = 0;
if (
!double.TryParse(
data.Substring(0, data.Length - 3),
out fltMetric01))
{
WriteLog.Instance.Write(
string.Format(
"测量数据[(0}]不符合格式要求,无法转换成数值",
data),
strProcedureName);
return false;
}
else
{
metric01 = Convert.ToInt64(fltMetric01 * Math.Pow(10, instrument.Scale));
return true;
}
}
else
{
WriteLog.Instance.Write(
string.Format(
"接收到的测量数据[{0}]长度不符合定义[{1}]要求",
data,
instrument.LengthOfDataMsg),
strProcedureName);
return false;
}
}
}
public void Record()
{
string strProcedureName =
string.Format(
"{0}.{1}:{2}",
className,
MethodBase.GetCurrentMethod().Name,
source);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
SaveData(metric01);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private bool SaveData(long metric01)
{
string strProcedureName =
string.Format(
"{0}.{1}:{2}",
className,
MethodBase.GetCurrentMethod().Name,
source);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
EntityWIPIDInfo wipInfo = new EntityWIPIDInfo();
IRAPUESClient.Instance.WIP_WIPID(
communityID,
"Anonymous",
1,
instrument.InstrumentCode,
ref wipInfo,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
IRAPUESClient.Instance.DC_Measure(
communityID,
wipInfo.UserCode,
wipInfo.SysLogID,
wipInfo.ProductNo,
wipInfo.WIPCode,
wipInfo.PWONo,
wipInfo.ContainerNo,
wipInfo.WIPStationCode,
wipInfo.WIPQty,
wipInfo.T20LeafID,
metric01,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
SendMessageToESB(
wipInfo.WIPStationCode,
wipInfo.PWONo,
wipInfo.T47LeafID,
wipInfo.T216LeafID,
wipInfo.T133LeafID,
wipInfo.T20LeafID);
return errCode == 0;
}
else
{
return false;
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
return false;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void SendMessageToESB(
string wipStationCode,
string pwoNo,
int t47LeafID,
int t216LeafID,
int t133LeafID,
int t20LeafID)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
if (factory != null &&
activeMQ_QueueName.Trim() != "")
{
using (IConnection connection = factory.CreateConnection())
{
using (ISession session = connection.CreateSession())
{
IMessageProducer prod =
session.CreateProducer(
new ActiveMQQueue(activeMQ_QueueName));
ITextMessage message = prod.CreateTextMessage();
message.Text =
string.Format(
"<Content><Message T107Code=\"{0}\" " +
"PWONo=\"{1}\" T47LeafID=\"{2}\" "+
"T216LeafID=\"{3}\" T133LeafID=\"{4}\" "+
"T20LeafID=\"{5}\" " +
"SendDateTime=\"{6}\" /></Content>",
wipStationCode, pwoNo, t47LeafID, t216LeafID, t133LeafID, t20LeafID,
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
message.Properties.SetString("filter", wipStationCode);
prod.Send(
message,
MsgDeliveryMode.Persistent,
MsgPriority.Normal,
new TimeSpan(0, 0, 0, 30));
}
}
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Mio.Utils.MessageBus;
using System;
namespace Mio.TileMaster {
public enum ScoreType {
Score,
Star,
Crown
}
public class HighScoreManager : MonoSingleton<HighScoreManager> {
private List<ScoreItemModel> listHighscore;
private bool isInit = false;
private int totalStar = 0;
public int TotalStars {
get { return totalStar; }
}
private int totalCrown = 0;
public int TotalCrowns {
get { return totalCrown; }
}
private static Message MSG_USER_PLAY_RECORD_CHANGED = new Message(MessageBusType.UserPlayRecordChanged);
public void Initialize() {
if (!isInit) {
//print("initializing highscore");
//if(GameManager.Instance != null) {
//print("hAAAAAAAAAAAAAAAAere");
//}
//print("Initialized");
isInit = true;
MessageBus.Instance.Subscribe(MessageBusType.UserPlayRecordChanged, OnUserPlayRecordChanged);
}
RefreshMetric();
}
private void OnUserPlayRecordChanged (Message obj) {
//throw new NotImplementedException();
RefreshMetric();
}
private int oldNumCrown, oldNumStar;
public void RefreshMetric() {
if(!isInit) { Initialize(); }
if (!isInit) return;
listHighscore = ProfileHelper.Instance.ListHighScore;
if (listHighscore == null) {
Debug.LogWarning("Could not initialize high-score manager if player profile has not been initialized first");
return;
}
oldNumCrown = totalCrown;
oldNumStar = totalStar;
totalCrown = totalStar = 0;
//Debug.Log(string.Format("Refreshing metrics old crowns {0}, old stars {1}", oldNumCrown, oldNumStar));
for(int i = 0; i < listHighscore.Count; i++) {
totalStar += Mathf.Clamp(listHighscore[i].highestStar,0,3);
totalCrown += listHighscore[i].highestCrown;
}
//Debug.Log(string.Format("Refreshing metrics new crowns {0}, new stars {1}", totalCrown, totalStar));
if ((oldNumStar != totalStar) || (oldNumCrown != totalCrown)) {
MessageBus.Annouce(MSG_USER_PLAY_RECORD_CHANGED);
}
}
public int GetHighScore(string levelName, ScoreType type = ScoreType.Score) {
// print("Get high-score for level " + levelName + " type: " + type);
if (isInit) {
for (int i = 0; i < listHighscore.Count; i++) {
if (listHighscore[i].itemName.Equals(levelName)) {
//print("Item found");
return GetScore(listHighscore[i], type);
}
}
//print("No item found");
}
return 0;
}
public bool UpdateHighScore(string levelName, int scoreValue, ScoreType type = ScoreType.Score) {
//print("Updating high score for level " + levelName + " type: " + type + " value: " + scoreValue);
if (isInit) {
bool res = false;
foreach (ScoreItemModel item in listHighscore) {
if (item.itemName.Equals(levelName)) {
int currentScore = GetScore(item, type);
if (currentScore >= scoreValue) {
res = false;
}
else {
SetScore(item, type, scoreValue);
res = true;
}
//print(string.Format("Item found for level {0}, score type {1}, need update = {2}", levelName, type, res));
return res;
}
}
//if we reached this point, it's mean the item is not existed. We shall create one
ScoreItemModel scoreitem = new ScoreItemModel();
scoreitem.itemName = levelName;
listHighscore.Add(scoreitem);
SetScore(scoreitem, type, scoreValue);
//print(string.Format("Create new highscore for level {0}, score type {1}, value = {2}", levelName, type, scoreValue));
return true;
}
return false;
}
private int GetScore(ScoreItemModel model, ScoreType type) {
switch (type) {
case ScoreType.Crown:
return model.highestCrown;
case ScoreType.Score:
return model.highestScore;
case ScoreType.Star:
return model.highestStar;
default:
return 0;
}
}
public List<ScoreItemModel> GetCurrentHighScoreList() {
return listHighscore;
}
private void SetScore(ScoreItemModel model, ScoreType type, int score) {
switch (type) {
case ScoreType.Crown:
model.highestCrown = score;
RefreshMetric();
break;
case ScoreType.Score:
model.highestScore = score;
break;
case ScoreType.Star:
model.highestStar = score;
RefreshMetric();
break;
}
//HACKATHON used to speed up programming
//save game state right after update highscore
//if (type == ScoreType.Score) {
// GameManager.Instance.SaveGameData();
//}
}
}
} |
using System;
using System.Threading.Tasks;
namespace FunctionalProgramming.Monad.Outlaws
{
public static class TaskExtensions
{
public static T SafeRun<T>(this Task<T> t)
{
t.SafeStart();
return t.Result;
}
public static void SafeStart<T>(this Task<T> t)
{
if (t.Status == TaskStatus.Created)
{
t.Start();
}
}
public static Task<T2> Select<T, T2>(this Task<T> t, Func<T, T2> f)
{
return new Task<T2>(() => f(t.SafeRun()));
}
public static Task<T2> SelectMany<T, T2>(this Task<T> t, Func<T, Task<T2>> f)
{
return new Task<T2>(() => f(t.SafeRun()).SafeRun());
}
public static Task<IEither<T1, T2>> WhenEither<T1, T2>(Task<T1> t1, Task<T2> t2)
{
return new Task<IEither<T1, T2>>(() =>
{
IEither<T1, T2> result;
t1.SafeStart();
t2.SafeStart();
var tresult = Task.WhenAny(t1, t2).SafeRun();
if (tresult == t1)
{
result = t1.Result.AsLeft<T1, T2>();
}
else
{
result = t2.Result.AsRight<T1, T2>();
}
return result;
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GodaddyWrapper.Responses
{
public class DomainSuggestionResponse
{
public string domain { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Text;
using System.Linq;
using CsvHelper.Configuration.Attributes;
using MOE.Common.Business.WCFServiceLibrary;
using MOE.Common.Models;
using MOE.Common.Models.Repositories;
namespace MOE.Common.Business.TimingAndActuations
{
public class TimingAndActuationsForPhase
{
public readonly int PhaseNumber;
public bool PhaseOrOverlap { get; set; }
public Approach Approach { get; set; }
public List<Plan> Plans { get; set; }
public string PhaseNumberSort { get; set; }
public bool GetPermissivePhase { get; }
public TimingAndActuationsOptions Options { get; }
public List<TimingAndActuationCycle> Cycles { get; set; }
public List<Controller_Event_Log> CycleDataEventLogs { get; set; }
public List<Controller_Event_Log> PedestrianEvents { get; set; }
public List<Controller_Event_Log> PedestrianIntervals { get; set; }
public List<Controller_Event_Log> ForceEventsForAllLanes { get; set; }
public Dictionary<string, List<Controller_Event_Log>> CycleAllEvents { get; set; }
public Dictionary<string, List<Controller_Event_Log>> PedestrianAllEvents { get; set; }
public Dictionary<string, List<Controller_Event_Log>> PedestrianAllIntervals { get; set; }
public Dictionary<string, List<Controller_Event_Log>> AdvanceCountEvents { get; set; }
public Dictionary<string, List<Controller_Event_Log>> AdvancePresenceEvents { get; set; }
public Dictionary<string, List<Controller_Event_Log>> StopBarEvents { get; set; }
public Dictionary<string, List<Controller_Event_Log>> LaneByLanes { get; set; }
public Dictionary<string, List<Controller_Event_Log>> PhaseCustomEvents { get; set; }
public TimingAndActuationsForPhase(int phaseNumber, bool phaseOrOverlap, TimingAndActuationsOptions options)
{
PhaseNumber = phaseNumber;
Options = options;
PhaseOrOverlap = phaseOrOverlap;
GetAllRawCycleData(options.StartDate, options.EndDate, PhaseOrOverlap);
if (Options.ShowPedestrianIntervals)
{
GetPedestrianIntervals(PhaseOrOverlap);
}
//if (Options.ShowPedestrianActuation && !GetPermissivePhase)
if (Options.ShowPedestrianActuation)
{
GetPedestrianEvents();
}
if (Options.PhaseEventCodesList != null)
{
var optionsSignalID = Options.SignalID;
GetRawCustomEvents( optionsSignalID, PhaseNumber, options.StartDate, options.EndDate);
}
}
public TimingAndActuationsForPhase(Approach approach, TimingAndActuationsOptions options,
bool getPermissivePhase)
{
GetPermissivePhase = getPermissivePhase;
Approach = approach;
Options = options;
PhaseNumber = GetPermissivePhase ? Approach.PermissivePhaseNumber.Value : Approach.ProtectedPhaseNumber;
if (Options.ShowVehicleSignalDisplay)
{
GetAllCycleData(Options.StartDate, Options.EndDate, approach, getPermissivePhase);
}
if (Options.ShowStopBarPresence)
{
GetStopBarPresenceEvents();
}
if (Options.ShowPedestrianActuation && !GetPermissivePhase)
{
GetPedestrianEvents();
}
if (Options.ShowPedestrianIntervals && !GetPermissivePhase)
{
var getPhaseOrOverlapEvents = !(approach.IsProtectedPhaseOverlap || approach.IsPermissivePhaseOverlap);
GetPedestrianIntervals(getPhaseOrOverlapEvents);
}
if (Options.ShowLaneByLaneCount)
{
GetLaneByLaneEvents();
}
if (Options.ShowAdvancedDilemmaZone)
{
GetAdvancePresenceEvents();
}
if (Options.ShowAdvancedCount)
{
GetAdvanceCountEvents();
}
if (Options.PhaseEventCodesList != null)
{
GetPhaseCustomEvents();
}
}
private void GetRawCustomEvents(string signalID, int numberPhase, DateTime optionsStartDateTime, DateTime optionsEndDateTime)
{
PhaseCustomEvents = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = Models.Repositories.ControllerEventLogRepositoryFactory.Create();
if (Options.PhaseEventCodesList != null && Options.PhaseEventCodesList.Any() &&
Options.PhaseEventCodesList.Count > 0)
{
foreach (var phaseEventCode in Options.PhaseEventCodesList)
{
var phaseEvents = controllerEventLogRepository.GetEventsByEventCodesParam(signalID,
optionsStartDateTime, optionsEndDateTime, new List<int> {phaseEventCode}, numberPhase);
if (phaseEvents.Count > 0)
{
PhaseCustomEvents.Add("Phase Event Code: " + phaseEventCode, phaseEvents);
}
}
}
}
private void GetAllRawCycleData(DateTime optionsStartDate, DateTime optionsEndDate, bool phasedata)
{
CycleDataEventLogs = new List<Controller_Event_Log>();
CycleAllEvents = new Dictionary<string, List<Controller_Event_Log>>();
var extendLine = 6;
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
var simpleEndDate = optionsEndDate;
var phaseEventCodesForCycles = new List<int> { 1, 3, 8, 9, 11 };
if (!phasedata)
{
phaseEventCodesForCycles = new List<int> { 61, 62, 63, 64, 65 };
}
string keyLabel = "Cycles Intervals " + PhaseNumber + " " + phasedata;
CycleDataEventLogs = controllerEventLogRepository.GetEventsByEventCodesParam(Options.SignalID,
optionsStartDate.AddMinutes(-extendLine), simpleEndDate.AddMinutes(extendLine),
phaseEventCodesForCycles, PhaseNumber);
if (CycleDataEventLogs.Count > 0)
{
CycleAllEvents.Add(keyLabel, CycleDataEventLogs);
}
}
private void GetAllCycleData(DateTime addMinutes, DateTime dateTime, Approach approach, bool getPermissivePhase)
{
CycleDataEventLogs = new List<Controller_Event_Log>();
CycleAllEvents = new Dictionary<string, List<Controller_Event_Log>>();
var extendLine = 6;
var controllerEventLogRepository = Models.Repositories.ControllerEventLogRepositoryFactory.Create();
var simpleEndDate = Options.EndDate;
var phaseEventCodesForCycles = new List<int>{1, 3, 8, 9, 11};
if (approach.IsProtectedPhaseOverlap || approach.IsPermissivePhaseOverlap)
{
phaseEventCodesForCycles = new List<int> {61, 62, 63, 64, 65};
}
int phaseNumber = getPermissivePhase ? approach.PermissivePhaseNumber.Value : approach.ProtectedPhaseNumber;
string keyLabel = "Cycles Intervals " + phaseNumber;
CycleDataEventLogs = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate.AddMinutes(-extendLine), simpleEndDate.AddMinutes(extendLine),
phaseEventCodesForCycles, PhaseNumber);
if (CycleDataEventLogs.Count <= 0)
{
extendLine = 60;
CycleDataEventLogs = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate.AddMinutes(-extendLine), simpleEndDate.AddMinutes(6),
phaseEventCodesForCycles, PhaseNumber);
}
if (CycleDataEventLogs.Count <= 0)
{
extendLine = 24 * 60;
CycleDataEventLogs = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate.AddMinutes(-extendLine), simpleEndDate.AddMinutes(6),
phaseEventCodesForCycles, PhaseNumber);
}
CycleAllEvents.Add(keyLabel, CycleDataEventLogs);
}
private void GetPhaseCustomEvents()
{
PhaseCustomEvents = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = Models.Repositories.ControllerEventLogRepositoryFactory.Create();
if (Options.PhaseEventCodesList != null && Options.PhaseEventCodesList.Any() &&
Options.PhaseEventCodesList.Count > 0)
{
foreach (var phaseEventCode in Options.PhaseEventCodesList)
{
var phaseEvents = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate, Options.EndDate, new List<int> {phaseEventCode}, PhaseNumber);
if (phaseEvents.Count > 0)
{
PhaseCustomEvents.Add(
"Phase Events: " + phaseEventCode,phaseEvents);
}
if (PhaseCustomEvents.Count == 0 && Options.ShowAllLanesInfo)
{
var forceEventsForAllLanes = new List<Controller_Event_Log>();
var tempEvent1 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = phaseEventCode,
EventParam = PhaseNumber,
Timestamp = Options.StartDate.AddSeconds(-10)
};
forceEventsForAllLanes.Add(tempEvent1);
var tempEvent2 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = phaseEventCode,
EventParam = PhaseNumber,
Timestamp = Options.StartDate.AddSeconds(-9)
};
forceEventsForAllLanes.Add(tempEvent2);
PhaseCustomEvents.Add(
"Phase Events: " + phaseEventCode, forceEventsForAllLanes);
}
}
}
}
private void GetLaneByLaneEvents()
{
LaneByLanes = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
var localSortedDetectors = Approach.Detectors.OrderByDescending(d => d.MovementType.DisplayOrder)
.ThenByDescending(l => l.LaneNumber).ToList();
foreach (var detector in localSortedDetectors)
{
if (detector.DetectionTypes.Any(d => d.DetectionTypeID == 4))
{
var laneNumber = "";
if (detector.LaneNumber != null)
{
laneNumber = detector.LaneNumber.Value.ToString();
}
var laneByLane = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate, Options.EndDate, new List<int> {81, 82}, detector.DetChannel);
if (laneByLane.Count > 0)
{
LaneByLanes.Add("Lane-by-lane Count " + detector.MovementType.Abbreviation + " " +
laneNumber + ", ch " + detector.DetChannel, laneByLane);
}
if (LaneByLanes.Count == 0 && Options.ShowAllLanesInfo)
{
var forceEventsForAllLanes = new List<Controller_Event_Log>();
var tempEvent1 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 82,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-10)
};
forceEventsForAllLanes.Add(tempEvent1);
var tempEvent2 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 81,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-9)
};
forceEventsForAllLanes.Add(tempEvent2);
LaneByLanes.Add("Lane-by-Lane Count, ch " + detector.DetChannel + " " +
detector.MovementType.Abbreviation + " " +
laneNumber, forceEventsForAllLanes);
}
}
}
}
private void GetStopBarPresenceEvents()
{
StopBarEvents = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
var localSortedDetectors = Approach.Detectors.OrderByDescending(d => d.MovementType.DisplayOrder)
.ThenByDescending(l => l.LaneNumber).ToList();
foreach (var detector in localSortedDetectors)
{
if (detector.DetectionTypes.Any(d => d.DetectionTypeID == 6))
{
var stopEvents = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate, Options.EndDate, new List<int> {81, 82}, detector.DetChannel);
var laneNumber = "";
if (detector.LaneNumber != null)
{
laneNumber = detector.LaneNumber.Value.ToString();
}
if (stopEvents.Count > 0)
{
StopBarEvents.Add("Stop Bar Presence, " + detector.MovementType.Abbreviation + " " +
laneNumber + ", ch " + detector.DetChannel, stopEvents);
}
if (stopEvents.Count == 0 && Options.ShowAllLanesInfo)
{
var forceEventsForAllLanes = new List<Controller_Event_Log>();
var event1 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 82,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-10)
};
forceEventsForAllLanes.Add(event1);
var event2 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventParam = detector.DetChannel,
EventCode = 81,
Timestamp = Options.StartDate.AddSeconds(-9)
};
forceEventsForAllLanes.Add(event2);
StopBarEvents.Add("Stop Bar Presence, ch " + detector.DetChannel + " " +
detector.MovementType.Abbreviation + " " +
laneNumber, forceEventsForAllLanes);
}
}
}
}
private void GetAdvanceCountEvents()
{
AdvanceCountEvents = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = Models.Repositories.ControllerEventLogRepositoryFactory.Create();
var localSortedDetectors = Approach.Detectors.OrderByDescending(d => d.MovementType.DisplayOrder)
.ThenByDescending(l => l.LaneNumber).ToList();
foreach (var detector in localSortedDetectors)
{
if (detector.DetectionTypes.Any(d => d.DetectionTypeID == 2))
{
var advanceEvents = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate, Options.EndDate, new List<int> {81, 82}, detector.DetChannel);
var laneNumber = "";
if (detector.LaneNumber != null)
{
laneNumber = detector.LaneNumber.Value.ToString();
}
if (advanceEvents.Count > 0)
{
AdvanceCountEvents.Add("Advanced Count (" + detector.DistanceFromStopBar + " ft) " +
detector.MovementType.Abbreviation + " " +
laneNumber +
", ch " + detector.DetChannel, advanceEvents);
}
else if (AdvanceCountEvents.Count == 0 && Options.ShowAllLanesInfo)
{
var forceEventsForAllLanes = new List<Controller_Event_Log>();
var tempEvent1 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 82,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-10)
};
forceEventsForAllLanes.Add(tempEvent1);
var tempEvent2 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 81,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-9)
};
forceEventsForAllLanes.Add(tempEvent2);
AdvanceCountEvents.Add("Advanced Count (" + detector.DistanceFromStopBar + " ft), ch " +
detector.DetChannel + " " + detector.MovementType.Abbreviation + " " +
laneNumber, forceEventsForAllLanes);
}
}
}
}
private void GetAdvancePresenceEvents()
{
AdvancePresenceEvents = new Dictionary<string, List<Controller_Event_Log>>();
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
var localSortedDetectors = Approach.Detectors.OrderByDescending(d => d.MovementType.DisplayOrder)
.ThenByDescending(l => l.LaneNumber).ToList();
foreach (var detector in localSortedDetectors)
{
if (detector.DetectionTypes.Any(d => d.DetectionTypeID == 7))
{
var advancePresence = controllerEventLogRepository.GetEventsByEventCodesParam(Approach.SignalID,
Options.StartDate, Options.EndDate, new List<int> {81, 82}, detector.DetChannel);
var laneNumber = "";
if (detector.LaneNumber != null)
{
laneNumber = detector.LaneNumber.Value.ToString();
}
if (advancePresence.Count > 0)
{
AdvancePresenceEvents.Add("Advanced Presence, " + detector.MovementType.Abbreviation + " " +
laneNumber + ", ch " + detector.DetChannel, advancePresence);
}
else if (AdvancePresenceEvents.Count == 0 && Options.ShowAllLanesInfo)
{
var forceEventsForAllLanes = new List<Controller_Event_Log>();
var tempEvent1 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 82,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-10)
};
forceEventsForAllLanes.Add(tempEvent1);
var tempEvent2 = new Controller_Event_Log()
{
SignalID = Options.SignalID,
EventCode = 81,
EventParam = detector.DetChannel,
Timestamp = Options.StartDate.AddSeconds(-9)
};
forceEventsForAllLanes.Add(tempEvent2);
AdvancePresenceEvents.Add("Advanced Presence, ch " + detector.DetChannel + " " +
detector.MovementType.Abbreviation + " " +
laneNumber, forceEventsForAllLanes);
}
}
}
}
private void GetPedestrianEvents()
{
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
PedestrianEvents = controllerEventLogRepository.GetEventsByEventCodesParam(Options.SignalID,
Options.StartDate, Options.EndDate, new List<int> {89, 90}, PhaseNumber);
}
public void GetPedestrianIntervals(bool phaseOrOverlap)
{
var overlapCodes = new List<int> { 67, 68, 69 };
if (phaseOrOverlap)
{
overlapCodes = new List<int> { 21, 22, 23 };
}
var expandTimeLine = 6;
var controllerEventLogRepository = ControllerEventLogRepositoryFactory.Create();
PedestrianIntervals = controllerEventLogRepository.GetEventsByEventCodesParam(Options.SignalID,
Options.StartDate.AddMinutes(- expandTimeLine), Options.EndDate.AddMinutes(expandTimeLine),overlapCodes,
PhaseNumber);
}
}
}
|
using System;
namespace Compiler.Exceptions
{
public class VariableNotFoundException : Exception
{
public VariableNotFoundException(string identifier)
{
Message = $"Variable \"{identifier}\" not found.";
}
public override string Message { get; }
}
} |
using System.Collections;
using System.Collections.Generic;
using Player;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class InventoryInterface : MonoBehaviour {
private bool open = false;
public FirstPersonController FPS;
public void HandleInventory() {
open = !open;
transform.gameObject.SetActive(open);
FPS.enabled = !open;
Time.timeScale = open ? 0.0f : 1.0f;
}
public bool isOpen() {
return open;
}
}
|
using GraphQL.Types;
using GraphQL.Domain.Entities;
namespace GraphQL.Infra.Data.GraphQL.Type
{
public class AuthorType : ObjectGraphType<Author>
{
public AuthorType()
{
Name = "Author";
Field(_ => _.Id).Description("Author's Id.");
Field(_ => _.FirstName).Description("First name of the author");
Field(_ => _.LastName).Description("Last name of the author");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Hayaa.DataAccess;
using Hayaa.BaseModel;
using Hayaa.Security.Service.Dao;
using Hayaa.Security.Service.Config;
/// <summary>
///代码效率工具生成,此文件不要修改
/// </summary>
namespace Hayaa.Security.Service
{
public partial class AppInstanceTokenServer
{
public FunctionResult<AppInstanceToken> ExchangeToken(int appInstanceId, string appToken)
{
String appInstanceToken = CreateToken(appToken);
var temp = AppInstanceTokenDal.GetByAppInstanceId(appInstanceId);
if (temp != null) return new FunctionResult<AppInstanceToken>() {
ErrorMsg = "实例已有有效token"
};
return Create(new AppInstanceToken() {
AppInstanceId=appInstanceId,
AppToken=appToken,
Token=appInstanceToken
});
}
/// <summary>
/// 通过算法进行内容置换
/// TODO
/// </summary>
/// <param name="appToken"></param>
/// <returns></returns>
private string CreateToken(string appToken)
{
return Guid.NewGuid().ToString().Replace("-","");
}
public FunctionResult<AppInstanceToken> Get(int appInstanceId, string token)
{
var r = new FunctionResult<AppInstanceToken>();
r.Data = AppInstanceTokenDal.GetByAppInstanceIdAndToken(appInstanceId, token);
return r;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fahrzeugverwaltung
{
public abstract class Fahrzeug
{
private uint leistung;
public uint Leistung
{
get { return leistung; }
set { leistung = value; }
}
public string ModellName { get; set; }
public uint Laenge { get; set; }
public uint Breite { get; set; }
public uint Hoehe { get; set; }
public string Hersteller { get; set; }
protected Fahrzeug(uint leistung, string modell, uint laenge, uint breite, uint hoehe, string hersteller)
{
Leistung = leistung;
ModellName = modell;
Laenge = laenge;
Hoehe = hoehe;
Breite = breite;
Hersteller = hersteller;
}
}
}
|
using EventoMundialInter.Dominio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EventoMundialInter.Models
{
public class UsuarioModel
{
public UsuarioModel(string nome, string email)
{
this.Nome = nome;
this.Email = email;
}
public UsuarioModel()
{
}
public int Id { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string Telefone { get; set; }
public string Cidade { get; set; }
public string Cpf { get; set; }
public DataEvento DataEvento { get; set; }
}
} |
using RoboticMovementType.BaseMovementModel;
namespace RoboticMovementType
{
public class RoboticPosition : Position
{
public RoboticPosition(int x, int y) : base(x, y)
{
this.X = x;
this.Y = y;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GameSettings
{
public static Material ballMaterial;
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterStats : MonoBehaviour
{
public int maxHealt = 100;
public int currentHealth { get; private set; }
public Stat attack;
public Stat defense;
private void Awake()
{
currentHealth = maxHealt;
}
private void Update()
{
//por si modificamos el valor base con el uso de 1 item
/* if (Input.GetKeyDown(KeyCode.T))
{
TakeDamage(10);
};*/
}
public void TakeDamage(int damage)
{
damage -= defense.GetValue();
damage = Mathf.Clamp(damage, 0, int.MaxValue);//Esto es para restarle los puntos q tenga de defensa y no pasarse de cero
currentHealth -= damage;
Debug.Log(transform.name+" takes "+ damage+" damage.");
if (currentHealth <= 0)
{
Die();
}
}
public virtual void Die()
{
//Die in some way
//this method is meant to be overwritten
}
}
|
using gView.Framework.Data;
using gView.Framework.Globalisation;
using gView.Framework.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace gView.Framework.UI.Dialogs
{
[gView.Framework.system.RegisterPlugIn("09918356-AB35-4ed1-8C5E-034B79857931")]
public partial class FormLayerSource : Form, ILayerPropertyPage
{
public FormLayerSource()
{
InitializeComponent();
}
#region ILayerPropertyPage Member
public Panel PropertyPage(IDataset dataset, ILayer layer)
{
if (!ShowWith(dataset, layer))
{
return null;
}
if (dataset.ConnectionString.Trim().StartsWith("<"))
{
// Connectionstring ist XML, zB beim EventTable
// TODO: noch nicht implementert, darum geht nicht mit diese Dialog
return null;
}
txtDatasetType.Text = dataset.DatasetGroupName + " (" + dataset.ProviderName + ")";
txtDatasetname.Text = dataset.DatasetName;
txtConnectionString.Text = PrepareConnectionString(dataset.ConnectionString);
txtLayerSID.Text = layer.SID;
return panel1;
}
public bool ShowWith(IDataset dataset, ILayer layer)
{
return (dataset != null);
}
public string Title
{
get { return LocalizedResources.GetResString("String.Source", "Source"); }
}
public void Commit()
{
}
#endregion
private string PrepareConnectionString(string str)
{
Dictionary<string, string> dic = ConfigTextStream.Extract(str);
StringBuilder sb = new StringBuilder();
foreach (string key in dic.Keys)
{
if (String.IsNullOrEmpty(dic[key]))
{
sb.Append(key);
}
else
{
switch (key.ToLower())
{
case "password":
case "pwd":
sb.Append(key + "=*****");
break;
default:
sb.Append(key + "=" + dic[key]);
break;
}
}
sb.Append("\r\n");
}
return sb.ToString();
}
}
} |
using System;
using System.Collections;
namespace _12_5_Self_IEnumerable
{
//WeekEnumerator, который реализует IEnumerator
public class WeekEnumerator : IEnumerator
{
string[] days;
//для хранения текущей позиции определена переменная position, (в исходном состоянии) указатель должен указывать на позицию условно перед первым элементом.
int position = -1;
public WeekEnumerator(string[] days)
{
this.days = days;
}
//Указатель должен указывать на позицию условно перед первым элементомю.
public object Current
{
get
{
if (position == -1 || position >= days.Length)
throw new InvalidOperationException();
return days[position];
}
}
public bool MoveNext()
{
if (position < days.Length - 1)
{
position++;
return true;
}
else
return false;
}
public void Reset()
{
position = -1;
}
}
}
|
namespace BettingSystem.Domain.Games.Factories.Matches
{
using System;
using Common.Models;
using Exceptions;
using Models.Matches;
using Models.Teams;
internal class MatchFactory : IMatchFactory
{
private readonly Status defaultMatchStatus = Status.NotStarted;
private readonly Statistics defaultMatchStatistics = new(homeScore: null, awayScore: null);
private DateTime matchStartDate = default!;
private Team matchHomeTeam = default!;
private Team matchAwayTeam = default!;
private Stadium matchStadium = default!;
private bool isStartDateSet = false;
private bool isHomeTeamSet = false;
private bool isAwayTeamSet = false;
private bool isStadiumSet = false;
public IMatchFactory WithStartDate(DateTime startDate)
{
this.matchStartDate = startDate;
this.isStartDateSet = true;
return this;
}
public IMatchFactory WithHomeTeam(Team team)
{
this.matchHomeTeam = team;
this.isHomeTeamSet = true;
return this;
}
public IMatchFactory WithAwayTeam(Team team)
{
this.matchAwayTeam = team;
this.isAwayTeamSet = true;
return this;
}
public IMatchFactory WithStadium(
string name,
byte[] imageOriginalContent,
byte[] imageThumbnailContent)
{
var image = new Image(imageOriginalContent, imageThumbnailContent);
var stadium = new Stadium(name, image);
return this.WithStadium(stadium);
}
public IMatchFactory WithStadium(Stadium stadium)
{
this.matchStadium = stadium;
this.isStadiumSet = true;
return this;
}
public Match Build()
{
if (!this.isStartDateSet ||
!this.isHomeTeamSet ||
!this.isAwayTeamSet ||
!this.isStadiumSet)
{
throw new InvalidMatchException(
"Start date, home team, away team and stadium must have a value.");
}
return new Match(
this.matchStartDate,
this.matchHomeTeam,
this.matchAwayTeam,
this.matchStadium,
this.defaultMatchStatistics,
this.defaultMatchStatus);
}
}
}
|
using Messaging.Validators;
using Messaging.Resolvers;
using Xunit;
namespace Messaging.Validators.Tests
{
public class CdaValidatorTests
{
private IResourceResolver _fileResolver;
public CdaValidatorTests()
{
_fileResolver = EmbeddedResourceResolver.Create(AssemblyType.Caller);
}
[Fact]
public void Validate_NormalCall()
{
var cdaValidator = new CdaValidator(new EmbeddedResourceResolver(typeof(Mim.V6301.POCD_MT000001UK04Act).Assembly));
Result result = cdaValidator.Validate(_fileResolver.GetResourceStream("POCD_EX150001UK06_05.xml").GetText());
Assert.True(result.Status);
}
[Fact]
public void Validate_SpecifyingTemplateName_NormalCall()
{
var cdaValidator = new CdaValidator(new EmbeddedResourceResolver(typeof(Mim.V6301.POCD_MT000001UK04Act).Assembly));
Result result = cdaValidator.Validate(_fileResolver.GetResourceStream("POCD_EX150001UK06_05.xml").GetText(), Mim.V6301.SchemaNames.POCD_MT150001UK06.ToString());
Assert.True(result.Status);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.