text stringlengths 13 6.01M |
|---|
namespace QueryMess
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
var regex = new Regex("(\\+|%20)+");
var input = Console.ReadLine();
var builder = new StringBuilder();
while (input != "END")
{
var pairs = new Dictionary<string, List<string>>();
input = regex.Replace(input, " ");
var args = input.Split(new[] { '&', '?' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < args.Length; i++)
{
if (!args[i].Contains("="))
{
continue;
}
var split = args[i].Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
var key = split[0].Trim();
if (!pairs.ContainsKey(key))
{
pairs.Add(key, new List<string>());
}
pairs[key].Add(split[1].Trim());
}
foreach (var pair in pairs)
{
builder.Append($"{pair.Key}=[{string.Join(", ", pair.Value)}]");
}
builder.AppendLine();
input = Console.ReadLine();
}
Console.WriteLine(builder.ToString());
}
}
}
|
namespace OptionalTypes.JsonConverters.Tests.TestDtos
{
public class NonOptionalApplicationReceivedSubscription
{
public NonOptionalApplicationReceived Criteria { get; set; }
public string SubscriptionUri { get; set; }
}
} |
using System;
using System.IO;
using System.Threading.Tasks;
namespace DisposingAndFinalizing
{
class Program
{
static async Task Main(string[] args)
{
{
using var gfs = new MyGoodFileStream();
gfs.Open("file.txt");
using var bfs = new MyBadFileStream();
bfs.Open("file2.txt");
new MyGoodFileStream().Open("file3.txt");
new MyBadFileStream().Open("file4.txt");
}
GC.Collect();
await Task.Delay(TimeSpan.FromSeconds(5));
GC.Collect();
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
class MyGoodFileStream : IDisposable
{
private FileStream _file;
public void Open(string path)
{
_file = new FileStream(path, FileMode.Open);
}
public void Close()
{
Console.WriteLine("MyGoodFileStream is closing...");
_file?.Dispose();
}
private void Dispose(bool disposing)
{
Console.WriteLine("MyGoodFileStream is disposing...");
if (disposing)
{
Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyGoodFileStream()
{
Dispose(false);
}
}
class MyBadFileStream : IDisposable
{
private FileStream _file;
public void Open(string path)
{
_file = new FileStream(path, FileMode.Open);
}
public void Close()
{
Console.WriteLine("MyBadFileStream is closing...");
_file?.Dispose();
}
private void Dispose(bool disposing)
{
Console.WriteLine("MyBadFileStream is disposing...");
if (disposing)
{
Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyBadFileStream()
{
Console.WriteLine("Good bye file resource");
}
}
}
|
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace BashSoft.Network
{
public class DowloadManager
{
public static void Download(string fileURL)
{
WebClient webClient = new WebClient();
try
{
OutputWriter.WriteMessageOnNewLine("Started download ...");
string nameOfFile = ExtractNameOfFile(fileURL);
string pathToDownload = Path.Combine(SessionData.currentPath, nameOfFile);
webClient.DownloadFile(fileURL, pathToDownload);
OutputWriter.WriteMessageOnNewLine("Download complete");
}
catch (WebException ex)
{
OutputWriter.DisplayException(ex.Message);
}
}
public static void DownloadAsync(string fileURL)
{
Task.Run(() => Download(fileURL));
}
private static string ExtractNameOfFile(string fileURL)
{
int indexOfLastBackSlash = fileURL.IndexOf("/", StringComparison.Ordinal);
if (indexOfLastBackSlash != -1)
{
return fileURL.Substring(indexOfLastBackSlash + 1);
}
else
{
throw new WebException(ExceptionMessages.InvalidPath);
}
}
}
} |
public class Solution {
public int RemoveElement(int[] nums, int val) {
if (nums.Length == 0) return 0;
int size = 0;
for (int index=0; index<nums.Length; index++) {
if (nums[index] != val) {
nums[size] = nums[index];
size ++;
}
}
return size;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextRandom : MonoBehaviour {
Text chapter_text;
int _randam;
string[] chapter = {"スケルトンは骨が脆い","イモムシは骨魔法が効きやすい","エレメンタルに魔法は効かない","ゴーストに剣は当たらない","ヘルプにはたくさんの情報が書いてある","仲間にしたモンスターは忠実な部下となる",
"アイスの魔法は防御がアップし、傷が癒える","剣をモンスターに当てるとエッセンスが手に入る","死んだ仲間は戻ってこない","宝箱からは武具が手に入ることがある","モンスターにはそれぞれ弱点がある"};
// Use this for initialization
void Start () {
chapter_text = GetComponent<Text>();
_randam = Random.Range(0,chapter.Length);
chapter_text.text = chapter[_randam];
}
// Update is called once per frame
void Update () {
}
}
|
using OrbCore.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrbCore.Interfaces.EventLogger {
public interface IEventLoggerReceiver {
void ReceiveVerboseEvent(CoreLogMessage message);
void ReceiveWarningEvent(CoreLogMessage message);
void ReceiveErrorEvent(CoreLogMessage message);
void ReceiveCriticalEvent(CoreLogMessage message);
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using VRTK;
using IO;
namespace VR_Interaction
{
public class VRScreenCaptureTool : IControllerTool
{
private VRCameraViewer VRCamera;
protected VRTK_ControllerEvents _controller;
BitmapEncoder encoder;
public override void OnToolActivated()
{
_controller = GetComponent<VRTK_ControllerEvents>();
_controller.TouchpadPressed += OnTriggerClicked;
VRCamera = new VRCameraViewer();
VRCamera.CreateCamera();
VRCamera.Sphere.transform.SetParent(this.transform);
VRCamera.Sphere.transform.localScale = new Vector3(0.017f, 0.017f, 0.017f);
VRCamera.Sphere.transform.localPosition = (Vector3.forward+Vector3.up) * 0.05f;
VRCamera.Sphere.transform.localEulerAngles = Vector3.zero;
VRCamera.Screen.transform.SetParent(this.transform, false);
VRCamera.Screen.transform.localPosition = new Vector3(0, 0.15f, 0.05f);
VRCamera.Screen.transform.localScale = new Vector3(0.4f, 0.25f, 0.001f);
VRCamera.Screen.transform.Rotate(new Vector3(0f, 180f, 0f));
}
public void OnTriggerClicked(object sender, ControllerInteractionEventArgs e)
{
int screenWidth = VRCamera.MobileCamera.pixelWidth;
int screenHeight = VRCamera.MobileCamera.pixelHeight;
Texture2D tempTexture2D = new Texture2D(screenWidth, screenHeight, TextureFormat.RGB24, false);
RenderTexture.active = VRCamera.CameraFeed;
tempTexture2D.ReadPixels(new Rect(0, 0, screenWidth, screenHeight), 0, 0);
RenderTexture.active = null;
string persistentDataPath = Application.dataPath + "/Records/ScreenCaptures/";
if (!System.IO.Directory.Exists(persistentDataPath))
{
System.IO.Directory.CreateDirectory(persistentDataPath);
}
DateTime now = DateTime.Now;
string outputname = now.Year.ToString() + "-" + now.Month.ToString() + "-" + now.Day.ToString() + "-" +
now.Hour.ToString() + "-" + now.Minute.ToString() + "-" + now.Second.ToString();
string path = persistentDataPath + "Capture " + outputname + ".bmp";
// Dequeue the frame, encode it as a bitmap, and write it to the file
using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
BitmapEncoder.WriteBitmap(fileStream, screenWidth, screenHeight, tempTexture2D.GetRawTextureData());
fileStream.Close();
}
}
public override void OnToolDeactivated()
{
_controller.TouchpadPressed -= OnTriggerClicked;
VRCamera.DestroyObjects();
VRCamera = null;
//Destroy(VRCamera);
}
public override void OnDisabled()
{
throw new System.NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Uintra.Infrastructure.Extensions;
using Uintra.Infrastructure.TypeProviders;
namespace Uintra.Features.Notification.Configuration.BackofficeSettings.Providers
{
public class NotificationTypeProvider : EnumTypeProviderBase, INotificationTypeProvider
{
public NotificationTypeProvider(params Type[] enums) : base(enums)
{
}
public IEnumerable<Enum> PopupNotificationTypes() => new List<Enum>() { NotificationTypeEnum.Welcome };
public IEnumerable<Enum> UiNotificationTypes() => All.Except(base[NotificationTypeEnum.Welcome.ToInt()].ToListOfOne());
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MusicAPI.Models
{
public class Artist : IArtist
{
public string MbId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; } = new List<Album>();
public async Task<Album> CreateCompleteAlbum(string id, string title, Task<string> GetFrontCoverUrl)
{
Album completeAlbum = new Album { Id = id, Title = title, Image = await GetFrontCoverUrl };
return completeAlbum;
}
}
}
|
using System;
namespace gView.Interoperability.GeoServices.Rest.Json.Exceptions
{
public class TokenRequiredException : Exception
{
}
}
|
using System;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.HighLevel.UI;
namespace ShootingApp
{
public partial class CharacterStatus : Scene
{
public CharacterStatus()
{
InitializeWidget();
this.Button_1.TouchEventReceived += new EventHandler<TouchEventArgs>(ChangeToTitleScene);
}
public void ChangeToTitleScene(object sender, TouchEventArgs e){
Sounds.PlayCancel();
UISystem.SetScene(Scenes.titleScene);
}
public void UpdateValue(){
this.Label_level.Text = ""+Global.characterLevel;
this.Label_exp.Text = Global.characterExp + "/" + Global.expTable[Global.characterLevel + 1];
this.Label_rem.Text = ""+(Global.expTable[Global.characterLevel + 1] - Global.characterExp);
this.ProgressBar_1.Progress = (float)((float)(Global.characterExp) / (float)(Global.expTable[Global.characterLevel + 1]));
}
}
}
|
using System;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Base;
namespace Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual
{
/// <summary>
/// Representa el objeto Logic de Requerimiento Parrafo
/// </summary>
/// <remarks>
/// Creación : GMD 20150515 <br />
/// Modificación : <br />
/// </remarks>
public class RequerimientoParrafoLogic : Logic
{
/// <summary>
/// Codigo de Requerimiento Parrafo
/// </summary>
public Guid CodigoRequerimientoParrafo { get; set; }
/// <summary>
/// Codigo de Requerimiento
/// </summary>
public Guid CodigoRequerimiento { get; set; }
/// <summary>
/// Codigo de Plantilla Parrafo
/// </summary>
public Guid CodigoPlantillaParrafo { get; set; }
/// <summary>
/// Título del Párrafo
/// </summary>
public string Titulo { get; set; }
/// <summary>
/// Contenido del párrafo
/// </summary>
public string Contenido { get; set; }
/// <summary>
/// Orden del párrafo
/// </summary>
public byte Orden { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Tilemaps;
public class ContuBoard
{
private int width, height;
private TileType[,] tiles;
private Token[] tokens;
public event System.Action<int, int, TileType> TileChanged;
public event System.Action TokensUpdated;
public int Width { get => width; }
public int Height { get => height; }
public int TokenCount { get => tokens.Length; }
public static ContuBoard CreateDefault()
{
ContuBoard board = new ContuBoard();
board.width = 5;
board.height = 10;
board.tiles = new TileType[5, 10];
board.tokens = new Token[4];
board.tokens[0] = new Token(TokenType.Archer, 2);
board.tokens[1] = new Token(TokenType.Guard, 2);
board.tokens[2] = new Token(TokenType.Knight, 2);
board.tokens[3] = new Token(TokenType.Veteran, 2);
board.tiles[2, 2] = TileType.Player1;
board.tiles[2, 7] = TileType.Player2;
return board;
}
public static ContuBoard Clone(ContuBoard b1)
{
ContuBoard b2 = new ContuBoard();
b2.width = b1.width;
b2.height = b1.height;
b2.tiles = (TileType[,]) b1.tiles.Clone();
b2.tokens = new Token[b1.TokenCount];
for (int i = 0; i < b1.TokenCount; i++)
{
b2.tokens[i] = Token.Clone(b1.GetToken(i));
}
return b2;
}
public TileType GetTile(int x, int y)
{
if (x < 0 || x >= width || y < 0 || y >= height)
return TileType.Null;
return tiles[x, y];
}
public void SetTile(int x, int y, TileType type, bool onlyIfEmpty = false)
{
if (x < 0 || x >= width || y < 0 || y >= height)
return;
//Dont allow change of spawn pieces
if (x == width / 2 && (y == 2 || y == height - 3))
return;
if (onlyIfEmpty && tiles[x, y] != TileType.Empty)
return;
tiles[x, y] = type;
TileChanged?.Invoke(x, y, type);
}
public bool CanPlaceTile(int x, int y, int playerId)
{
if(GetTile(x,y) == TileType.Empty)
{
return IsPlayerTileInNeighbours(x, y, playerId);
}
return false;
}
public bool IsPlayerTileInNeighbours(int x, int y, int playerId)
{
TileType type = (playerId == 0 ? TileType.Player1 : TileType.Player2);
bool res = GetTile(x + 1, y) == type;;
res = res | GetTile(x-1, y) == type;
res = res | GetTile(x, y+1) == type;
res = res | GetTile(x, y-1) == type;
return res;
}
public bool TileIsInPlayersHalf(int x, int y, int playerId)
{
//XNOR(P1, y<5)
return !(playerId == 0 ^ y < height / 2);
}
public Token GetFirstTokenOfType(TokenType type)
{
foreach (var token in tokens)
{
if (token.Type == type)
return token;
}
return null;
}
public int GetTokenCountForUser(int userid)
{
int tokencount = 0;
foreach (var token in tokens)
{
if (token.State == (userid == 0 ? TokenState.P1Owned : TokenState.P2Owned))
tokencount++;
}
return tokencount;
}
public Token GetToken(int index)
{
if (index < 0 || index > tokens.Length)
return null;
return tokens[index];
}
public BoardState GetBoardState()
{
if (GetTile(2, 0) == TileType.Player2)
{
return BoardState.P2Won;
}
else if (GetTile(2, 9) == TileType.Player1)
{
return BoardState.P1Won;
}
return BoardState.Playing;
}
public void TickTokens()
{
bool changed = false;
foreach (var t in tokens)
{
if (t.Tick())
changed = true;
}
if (changed)
TokensUpdated?.Invoke();
}
public bool CheckRuleOf5()
{
if(CheckHorizontalRuleOf5())
{
return true;
}
else
{
return CheckVerticalRuleOf5();
}
}
private bool CheckHorizontalRuleOf5()
{
for (int y = 0; y < height; y++)
{
TileType type = GetTile(0, y);
if (type != TileType.Player1 && type != TileType.Player2)
continue;
bool broken = false;
for (int x = 1; x < width; x++)
{
if (type != GetTile(x, y))
{
broken = true;
break;
}
}
if (!broken) //Rule of 5 found
{
for (int i = 0; i < width; i++)
{
SetTile(i, y, TileType.Empty);
}
return true;
}
}
return false;
}
private bool CheckVerticalRuleOf5()
{
for (int x = 0; x < width; x++)
{
for (int y1 = 0; y1 < height-4; y1++)
{
TileType type = GetTile(x, y1);
if (type != TileType.Player1 && type != TileType.Player2)
continue;
bool broken = false;
for (int y2 = 0; y2 < 5; y2++)
{
if (type != GetTile(x, y1 + y2))
{
broken = true;
break;
}
}
if (!broken) //Rule of 5 found
{
for (int y2 = 0; y2 < 5; y2++)
{
SetTile(x, y1 + y2, TileType.Empty);
}
return true;
}
}
}
return false;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
sb.Append(TileTypeToString(tiles[x, y]));
}
sb.Append(Environment.NewLine);
}
sb.Append(Environment.NewLine);
sb.Append("Tokens:");
for (int i = 0; i < tokens.Length; i++)
{
sb.Append(Environment.NewLine);
sb.Append(tokens[i].ToString());
}
return sb.ToString();
}
private string TileTypeToString(TileType t)
{
switch (t)
{
case TileType.Empty:
return "_";
case TileType.Player2:
return "□";
case TileType.Player1:
return "■";
}
return "E";
}
public byte[] NormalAsBytes()
{
byte[] bytes = new byte[15];
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 5; x++)
{
int piece = y * 5 + x;
int b = piece / 4;
int subB = piece % 4;
bytes[b] |= (byte) (((int)GetTile(x,y))<<(subB*2));
}
}
for (int i = 0; i < 4; i++)
{
var t = GetToken(i);
bytes[13 + (i / 2)] |= (byte)(((int)t.State) << (i % 2));
}
return bytes;
}
public string NormalAsString()
{
return BitConverter.ToString(NormalAsBytes()).Replace("-","");
}
}
public enum BoardState
{
Playing,
P1Won,
P2Won
}
public enum TileType
{
Empty,
Player1,
Player2,
Null
}
|
using StarlightRiver.Abilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.GameInput;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;
namespace StarlightRiver.Abilities
{
public partial class AbilityHandler : ModPlayer
{
//All players store 1 instance of each ability. This instance is changed to the infusion variant if an infusion is equipped.
public Dash dash = new Dash(Main.LocalPlayer);
public Wisp wisp = new Wisp(Main.LocalPlayer);
public Pure pure = new Pure(Main.LocalPlayer);
public Smash smash = new Smash(Main.LocalPlayer);
public Superdash sdash = new Superdash(Main.LocalPlayer);
//A list of all ability instances is kept to easily check things globally across the player's abilities.
public List<Ability> Abilities = new List<Ability>();
//The players stamina stats.
public int StatStaminaMax = 0;
public int StatStaminaMaxTemp = 0;
public int StatStaminaMaxPerm = 1;
public int StatStamina = 1;
public int StatStaminaRegenMax = 210;
public int StatStaminaRegen = 0;
//Holds the player's wing or rocket boot timer, since they must be disabled to move upwards correctly.
private float StoredAccessoryTime = 0;
public override TagCompound Save()
{
return new TagCompound
{
//ability unlock data
[nameof(dash)] = dash.Locked,
[nameof(wisp)] = wisp.Locked,
[nameof(pure)] = pure.Locked,
[nameof(smash)] = smash.Locked,
[nameof(sdash)] = sdash.Locked,
//permanent stamina amount
[nameof(StatStaminaMaxPerm)] = StatStaminaMaxPerm,
//infusion data
[nameof(slot1)] = slot1,
[nameof(slot2)] = slot2,
[nameof(HasSecondSlot)] = HasSecondSlot
};
}
public override void Load(TagCompound tag)
{
//dash
dash = new Dash(player);
dash.Locked = tag.GetBool(nameof(dash));
Abilities.Add(dash);
//wisp
wisp = new Wisp(player);
wisp.Locked = tag.GetBool(nameof(wisp));
Abilities.Add(wisp);
//pure
pure = new Pure(player);
pure.Locked = tag.GetBool(nameof(pure));
Abilities.Add(pure);
//smash
smash = new Smash(player);
smash.Locked = tag.GetBool(nameof(smash));
Abilities.Add(smash);
//shadow dash
sdash = new Superdash(player);
sdash.Locked = tag.GetBool(nameof(sdash));
Abilities.Add(sdash);
//loads the player's maximum stamina.
StatStaminaMaxPerm = tag.GetInt(nameof(StatStaminaMaxPerm));
//loads infusion data.
slot1 = tag.Get<Item>(nameof(slot1)); if (slot1.Name == "") { slot1 = null; }
slot2 = tag.Get<Item>(nameof(slot2)); if (slot2.Name == "") { slot2 = null; }
HasSecondSlot = tag.GetBool(nameof(HasSecondSlot));
}
//Updates the Ability list with the latest info
public void SetList()
{
Abilities.Clear();
Abilities.Add(dash);
Abilities.Add(wisp);
Abilities.Add(pure);
Abilities.Add(smash);
Abilities.Add(sdash);
}
public override void ResetEffects()
{
//Resets the player's stamina to prevent issues with gaining infinite stamina or stamina regeneration.
StatStaminaMax = StatStaminaMaxTemp + StatStaminaMaxPerm;
StatStaminaMaxTemp = 0;
StatStaminaRegenMax = 210;
if (Abilities.Any(ability => ability.Active))
{
// The player cant use items while casting an ability.
player.noItems = true;
player.noBuilding = true;
}
SetList(); //Update the list to ensure all interactions work correctly
}
public override void ProcessTriggers(TriggersSet triggersSet)
{
//Activates one of the player's abilities on the appropriate keystroke.
if (StarlightRiver.Dash.JustPressed) { dash.StartAbility(player); }
if (StarlightRiver.Wisp.JustPressed) { wisp.StartAbility(player); }
if (StarlightRiver.Purify.JustPressed) { pure.StartAbility(player); }
if (StarlightRiver.Smash.JustPressed) { smash.StartAbility(player); }
if (StarlightRiver.Superdash.JustPressed) { sdash.StartAbility(player); }
}
public override void PreUpdate()
{
//Executes the ability's use code while it's active.
if(player.GetModPlayer<Dragons.DragonHandler>().DragonMounted)
foreach (Ability ability in Abilities.Where(ability => ability.Active)) { ability.InUseDragon(); ability.UseEffectsDragon(); }
else
foreach (Ability ability in Abilities.Where(ability => ability.Active)) { ability.InUse(); ability.UseEffects(); }
//Decrements internal cooldowns of abilities.
foreach (Ability ability in Abilities.Where(ability => ability.Cooldown > 0)) { ability.Cooldown--; }
//Ability cooldown Effects
foreach (Ability ability in Abilities.Where(ability => ability.Cooldown == 1)) { ability.OffCooldownEffects(); }
//Physics fuckery due to redcode being retarded
if (Abilities.Any(ability => ability.Active))
{
player.velocity.Y += 0.01f; //Required to ensure that the game never thinks we hit the ground when using an ability. Thanks redcode!
// We need to store the player's wing or rocket boot time and set the effective time to zero while an ability is active to move upwards correctly. Thanks redcode!
if (StoredAccessoryTime == 0) { StoredAccessoryTime = ((player.wingTimeMax > 0) ? player.wingTime : player.rocketTime + 1); }
player.wingTime = 0;
player.rocketTime = 0;
player.rocketRelease = true;
}
//This restores the player's wings or rocket boots after the ability is over.
else if (StoredAccessoryTime > 0)
{
player.velocity.Y += 0.01f; //We need to do this the frame after also.
//Makes the determination between which of the two flight accessories the player has.
if (player.wingTimeMax > 0) { player.wingTime = StoredAccessoryTime; }
else { player.rocketTime = (int)StoredAccessoryTime - 1; }
StoredAccessoryTime = 0;
}
//Dont exceed max stamina or regenerate stamina when full.
if(StatStamina >= StatStaminaMax)
{
StatStamina = StatStaminaMax;
StatStaminaRegen = StatStaminaRegenMax;
}
//The player's stamina regeneration.
if (StatStaminaRegen <= 0 && StatStamina < StatStaminaMax)
{
StatStamina++;
StatStaminaRegen = StatStaminaRegenMax;
}
//Regenerate only when abilities are not active.
if (!Abilities.Any(a => a.Active)) { StatStaminaRegen--; }
//If the player is dead, drain their stamina and disable all of their abilities.
if (player.dead)
{
StatStamina = 0;
StatStaminaRegen = StatStaminaRegenMax;
foreach (Ability ability in Abilities) { ability.Active = false; }
}
}
public override void ModifyDrawLayers(List<PlayerLayer> layers)
{
if(wisp.Active || sdash.Active)
{
foreach (PlayerLayer layer in layers) { layer.visible = false; }
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Client.Internal
{
public static class StaticFolders
{
public static string GetUserFolder()
{
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
folder = Path.Combine(folder, GlobalValues.AppName);
return GetFolder(folder);
}
public static string GetApplicationFolder()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
public static string GetFolder(string folder)
{
try
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
}
catch (Exception)
{
return null;
}
return folder;
}
public static bool IsValidFolder(string folder)
{
try
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
return true;
}
catch (Exception)
{
return false;
}
}
public static void OpenDirectory(string directory, string filename = null, string extension = null)
{
if (!string.IsNullOrWhiteSpace(extension))
{
if (!extension.StartsWith("."))
extension = "." + extension;
}
string filePath;
if (!string.IsNullOrWhiteSpace(filename))
{
if (!string.IsNullOrWhiteSpace(extension))
filePath = System.IO.Path.Combine(directory, filename + extension);
else
filePath = System.IO.Path.Combine(directory, filename);
} else
{
filePath = directory;
}
string argument = "/select, \"" + filePath + "\"";
System.Diagnostics.Process.Start("explorer.exe", argument);
}
}
}
|
/*
Generated by KBEngine!
Please do not modify this file!
tools = kbcmd
*/
namespace KBEngine
{
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class DATATYPE_CHESS_INFO : DATATYPE_BASE
{
public CHESS_INFO createFromStreamEx(MemoryStream stream)
{
CHESS_INFO datas = new CHESS_INFO();
datas.id = stream.readUint64();
datas.name = stream.readUnicode();
datas.level = stream.readUint64();
return datas;
}
public void addToStreamEx(Bundle stream, CHESS_INFO v)
{
stream.writeUint64(v.id);
stream.writeUnicode(v.name);
stream.writeUint64(v.level);
}
}
public class DATATYPE_CHESS_INFO_LIST : DATATYPE_BASE
{
private DATATYPE__CHESS_INFO_LIST_values_ArrayType_ChildArray values_DataType = new DATATYPE__CHESS_INFO_LIST_values_ArrayType_ChildArray();
public class DATATYPE__CHESS_INFO_LIST_values_ArrayType_ChildArray : DATATYPE_BASE
{
private DATATYPE_CHESS_INFO itemType = new DATATYPE_CHESS_INFO();
public List<CHESS_INFO> createFromStreamEx(MemoryStream stream)
{
UInt32 size = stream.readUint32();
List<CHESS_INFO> datas = new List<CHESS_INFO>();
while(size > 0)
{
--size;
datas.Add(itemType.createFromStreamEx(stream));
};
return datas;
}
public void addToStreamEx(Bundle stream, List<CHESS_INFO> v)
{
stream.writeUint32((UInt32)v.Count);
for(int i=0; i<v.Count; ++i)
{
itemType.addToStreamEx(stream, v[i]);
};
}
}
public CHESS_INFO_LIST createFromStreamEx(MemoryStream stream)
{
CHESS_INFO_LIST datas = new CHESS_INFO_LIST();
datas.values = values_DataType.createFromStreamEx(stream);
return datas;
}
public void addToStreamEx(Bundle stream, CHESS_INFO_LIST v)
{
values_DataType.addToStreamEx(stream, v.values);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using HTB.Database;
using System.Collections;
using HTBReports;
using HTBUtilities;
using HTBAktLayer;
using HTBInvoiceManager;
using System.Reflection;
using HTB.Database.Views;
using HTBServices;
using HTBServices.Mail;
namespace HTBDailyKosten
{
public class KostenCalculator
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly InvoiceManager _invMgr = new InvoiceManager();
private readonly tblControl _control = HTBUtils.GetControlRecord();
private bool _hasAktWorkflow;
// Constructor used for testing
public KostenCalculator(IEnumerable<int> aktId)
{
foreach (var id in aktId)
{
Log.Info("============== NEW ================");
CalculateKosten(id);
Log.Info("============== END NEW ===============");
}
}
public KostenCalculator()
{
}
public void CalculateKosten()
{
// Do NOT process King Bill Cases
// string qry = "SELECT * FROM qryCustInkAkt WHERE CustInkAktIsPartial = 0 AND CustInkAktIsWflStopped = 0 AND CustInkAktSource <> 'King Bill' AND CustInkAktStatus NOT IN (" + _control.InkassoAktInterventionStatus + ", " + _control.InkassoAktMeldeStatus + ", " + _control.InkassoAktStornoStatus + ", " + _control.InkassoAktFertigStatus + ", " + _control.InkassoAktWflDoneStatus + ", " + _control.InkassoAktSentToPartnerStatus + " ) AND CustInkAktCurrentStep >= 0 AND CustInkAktNextWFLStep <= '" + DateTime.Now + "' ORDER BY CustInkAktCurrentStep ASC";
// Process King Bill Cases
string qry = "SELECT * FROM qryCustInkAkt WHERE CustInkAktIsPartial = 0 AND CustInkAktIsWflStopped = 0 AND CustInkAktStatus NOT IN (" +
_control.InkassoAktInterventionStatus + ", " +
_control.InkassoAktMeldeStatus + ", " +
_control.InkassoAktStornoStatus + ", " +
_control.InkassoAktFertigStatus + ", " +
_control.InkassoAktWflDoneStatus + ", " +
_control.InkassoAktSentToPartnerStatus +
" ) AND CustInkAktCurrentStep >= 0 AND CustInkAktNextWFLStep <= '" + DateTime.Now + "' ORDER BY CustInkAktCurrentStep ASC";
ArrayList custInAktProcessList = HTBUtils.GetSqlRecords(qry, typeof(tblCustInkAkt));
Log.Info(qry);
foreach (tblCustInkAkt custInkAkt in custInAktProcessList)
{
// Just to make sure the database did not take a crap
if (!custInkAkt.CustInkAktIsWflStopped &&
custInkAkt.CustInkAktStatus != _control.InkassoAktInterventionStatus &&
custInkAkt.CustInkAktStatus != _control.InkassoAktMeldeStatus &&
custInkAkt.CustInkAktStatus != _control.InkassoAktStornoStatus)
{
if (custInkAkt.CustInkAktStatus == _control.InkassoAktInkassoStatus && (custInkAkt.CustInkAktCurStatus == _control.InkassoAktInstallmentStatus || custInkAkt.CustInkAktCurStatus == _control.InkassoAktOverchargeStatus))
{
// Skip Installments (RA) and Overcharges (TVL)
}
else
{
CalculateKosten(custInkAkt.CustInkAktID);
}
}
}
}
private void CalculateKosten(int aktId)
{
tblCustInkAkt akt = HTBUtils.GetInkassoAkt(aktId);
if (akt == null)return;
if(new AktUtils(aktId).GetAktBalance() <= 0) return;
if (akt.CustInkAktStatus == _control.InkassoAktWaitingForReMeldeStatus)
{
CreateMeldeAkt(aktId);
}
else
{
#region Normal Costs Generation
akt.CustInkAktCurrentStep += 1;
tblWFA wfa = GetWFA(akt.CustInkAktCurrentStep, aktId, akt.CustInkAktKlient);
if (wfa == null) return;
var aktActionKostenList = GetAktAktionKosten(akt.CustInkAktCurrentStep, aktId, akt.CustInkAktKlient);
var mahnungSet = new tblMahnungSet();
// Fälligkeitsdatum Schuldner Mahnungsdok (WFL Datum -5 Tage)
DateTime dueDte = DateTime.Now.AddDays(wfa.WFPPreTime - 5);
DateTime endZinsenDte = DateTime.Now.AddDays(wfa.WFPPreTime);
var inv = _invMgr.GetInvoiceByAktAndType(aktId, tblCustInkAktInvoice.INVOICE_TYPE_ORIGINAL);
decimal kapital = inv.InvoiceAmount > 0 ? Convert.ToDecimal(inv.InvoiceAmount) : 0;
inv = _invMgr.GetInvoiceByAktAndType(aktId, tblCustInkAktInvoice.INVOICE_TYPE_CLIENT_COST);
decimal klientKosten = inv != null && inv.InvoiceAmount > 0 ? Convert.ToDecimal(inv.InvoiceAmount) : 0;
Log.Info("Total Client Kosten " + klientKosten);
decimal forderung = kapital + klientKosten;
Log.Info("Total Forderung: " + forderung);
// Load Kosten Art Ids for next step
var kostenArtIdList = (from qryAktAktionKosten aktActionKosten in aktActionKostenList select aktActionKosten.KostenArtID).ToList();
#region Calculate WKF (Current Step) Kosten
var wset = new qryKostenSet();
wset.LoadKostenBasedOnForderungAndArtId(forderung, kostenArtIdList);
foreach (qryKosten record in wset.qryKostenList)
{
decimal amount = HTBUtils.GetCalculatedKost(forderung, record, akt.CustInkAktInvoiceDate); // calc based on balance
Log.Info("[ID: " + record.KostenArtId + "] [Cost: " + record.KostenArtText.Trim() + "] [Send Mahnung: " + record.SendMahnung + "] [Amount: " + amount + "] [IsKlage: " + record.IsKlage + "] [IsKlageErinnerung: " + record.IsKlageErinnerung + "]");
if (record.IsTaxable)
{
}
if (amount > 0)
{
CreateInvoiceRecord(aktId, record, amount);
}
if (record.SendMahnung)
{
tblMahnung mahnung = mahnungSet.GetNewMahnung();
mahnung.MahnungAktID = akt.CustInkAktID;
mahnungSet.UpdateMahnung(mahnung);
}
if (record.IsKlage || record.IsKlageErinnerung)
{
var mail = ServiceFactory.Instance.GetService<IHTBEmail>();
if (record.IsKlageErinnerung)
{
mail.SendLawyerReminder(HTBUtils.GetInkassoAktQry(aktId));
}
if (record.IsKlage)
{
new AktUtils(aktId).SendInkassoPackageToLawyer(new HTBEmailAttachment(ReportFactory.GetZwischenbericht(aktId), "Zwischenbericht.pdf", "Application/pdf"));
}
}
// Change inkasso akt to indicate current status
if (record.KostenCustInkAktStatus >= 0)
{
akt.CustInkAktStatus = record.KostenCustInkAktStatus;
if (akt.CustInkAktStatus == _control.InkassoAktInterventionStatus)
{
var aktUtils = new AktUtils(akt.CustInkAktID);
int workPeriod = 0;
tblWFA workflowNext = GetWFA(wfa.WFPPosition+1, aktId, akt.CustInkAktKlient);
if (workflowNext != null)
{
workPeriod = workflowNext.WFPPreTime;
}
aktUtils.CreateNewInterventionAkt((qryCustInkAkt)HTBUtils.GetSqlSingleRecord("SELECT * FROM qryCustInkAkt WHERE CustInkAktID = " + akt.CustInkAktID, typeof(qryCustInkAkt)), akt.CustInkAktMemo, workPeriod);
}
}
if (record.KostenCustInkAktCurStatus >= 0)
{
akt.CustInkAktCurStatus = record.KostenCustInkAktCurStatus;
}
if (record.KostenKZID > 0)
{
var aktUtils = new AktUtils(akt.CustInkAktID);
aktUtils.CreateAktAktion(record.KostenKZID, _control.AutoUserId);
}
Log.Info(record.KostenArtText.Trim() + " " + amount);
}
#endregion
#region Calculate General Costs (Skip them if indicated)
if (!akt.CustInkAktSkipInitialInvoices && akt.CustInkAktCurrentStep == 1)
{
// first step calculate Costs that take place once (evidenzgebuhren, ratenangebott...)
wset.LoadInitialKostenBasedOnForderung(forderung);
foreach (qryKosten record in wset.qryKostenList)
{
decimal amount = HTBUtils.GetCalculatedKost(forderung, record, akt.CustInkAktInvoiceDate); // calc based on balance
if (record.IsTaxable)
{
}
if (amount > 0)
{
CreateInvoiceRecord(aktId, record, amount);
}
Log.Info(record.KostenArtText.Trim() + " " + amount);
}
}
#endregion
#region Create and Insert CustInkAktDok
RecordSet.Insert(new tblCustInkAktDok
{
CustInkAktDokAkt = aktId,
CustInkAktDokDate = DateTime.Now,
CustInkAktDokDelFlag = 0,
CustInkAktDokDueDate = dueDte,
CustInkAktNextWorkflowStep = endZinsenDte,
CustInkAktDokCapital = Convert.ToDouble(forderung),
CustInkAktDokType = 1,
CustInkAktDokPrintFlag = 0,
CustInkAktDokEnterUser = 0,
CustInkAktDokCostClient = akt.CustInkAktKlient
});
#endregion
#region Update akt
wfa = GetWFA(akt.CustInkAktCurrentStep + 1, aktId, akt.CustInkAktKlient);
if (wfa == null)
{
SetWFLStatusDone(akt);
}
else
{
akt.CustInkAktNextWFLStep = DateTime.Now.AddDays(wfa.WFPPreTime);
}
UpdateAktStatus(akt);
#endregion
#endregion
}
return;
}
public void GenerateNewMahnung(int aktId)
{
tblCustInkAkt akt = HTBUtils.GetInkassoAkt(aktId);
var aktUtl = new AktUtils(aktId);
var mahnungSet = new tblMahnungSet();
int mahnungNumber = MahnungManager.GetNextMahnungNumber(aktId);
// Fälligkeitsdatum Schuldner Mahnungsdok (WFL Datum -5 Tage)
decimal forderung = Convert.ToDecimal(aktUtl.GetAktOriginalInvoiceAmount());
List<int> kostenArtIdList = GetKostenArtIdForMahnung(mahnungNumber);
#region Create Mahnung
var wset = new qryKostenSet();
wset.LoadKostenBasedOnForderungAndArtId(forderung, kostenArtIdList);
foreach (qryKosten record in wset.qryKostenList)
{
decimal amount = HTBUtils.GetCalculatedKost(forderung, record, akt.CustInkAktInvoiceDate);
Log.Info("[Mahnung Cost: " + record.KostenArtText + "] [Send Mahnung: " + record.SendMahnung + "] [Amount: " + amount + "]");
if (amount > 0)
{
CreateInvoiceRecord(aktId, record, amount);
}
tblMahnung mahnung = mahnungSet.GetNewMahnung();
mahnung.MahnungAktID = akt.CustInkAktID;
mahnungSet.UpdateMahnung(mahnung);
if (record.KostenKZID > 0)
{
var aktUtils = new AktUtils(akt.CustInkAktID);
aktUtils.CreateAktAktion(record.KostenKZID, _control.AutoUserId);
}
Log.Info(record.KostenArtText.Trim() + " " + amount);
}
#endregion
}
private void CreateMeldeAkt(int aktId)
{
var aktUtils = new AktUtils(aktId);
qryCustInkAkt qryInkAkt = HTBUtils.GetInkassoAktQry(aktId);
int meldeAktId = aktUtils.CreateMeldeAkt(HTBUtils.GetInkassoAktQry(aktId));
int meldeKostenArtId = _control.MeldeKostenArtId;
if (!qryInkAkt.GegnerZipPrefix.Trim().ToUpper().Equals("") && !qryInkAkt.GegnerZipPrefix.Trim().ToUpper().Equals("A"))
meldeKostenArtId = aktUtils.control.MeldeKostenAuslandArtId;
aktUtils.SetInkassoStatusBasedOnWflAction(meldeKostenArtId, _control.AutoUserId, null, "", _control.MeldePeriod);
Log.Info("MELDE CREATED");
ServiceFactory.Instance.GetService<IHTBEmail>().SendGenericEmail(new string[] { HTBUtils.GetConfigValue("Melde_Email"), HTBUtils.GetConfigValue("Default_EMail_Addr") }, "Neu Meldeakt: " + meldeAktId + " Akt: " + aktId, "Melde: " + meldeAktId + " InkassoAkt: " + aktId);
}
private void SetWFLStatusDone(tblCustInkAkt akt)
{
var aktUtils = new AktUtils(akt.CustInkAktID);
// akt.CustInkAktStatus = _control.InkassoAktWflDoneStatus;
// akt.CustInkAktCurStatus = 68; // Workflow Fertig
akt.CustInkAktCurrentStep = -1; // DONE !!!
if(HTBUtils.IsZero(aktUtils.GetAktBalance()))
{
akt.CustInkAktStatus = _control.InkassoAktFertigStatus;
akt.CustInkAktCurStatus = 25; // Erledigt: Fal abgeschlossen
}
else
{
int stornoCode = 27; // tblKZ: Storno auf Ihren Wunsch (kostenfrei für Sie)
if(HTBUtils.IsZero(aktUtils.GetAktKlientTotalBalance()))
{
stornoCode = 31; // tblKZ: Forderung direkt an Sie bezahlt (Kein Kosteneingang)
}
else if (aktUtils.IsLaywerInWorkflow())
{
stornoCode = 32; // tblKZ: Storno - Uneinbringlich (gerichtliche Betreibung)
}
aktUtils.CreateAktAktion(stornoCode, _control.AutoUserId);
akt.CustInkAktCurStatus = stornoCode;
akt.CustInkAktStatus = _control.InkassoAktStornoStatus;
}
RecordSet.Update(akt);
Log.Info("WFL DONE");
// Notify Client (copy office)
// new AktUtils(akt.CustInkAktID).SendAbschlusBerichtToClient(akt, ReportFactory.GetZwischenbericht(akt.CustInkAktID), "Klient_Akt_Done_Text", string.Format("Abschlussbericht [ {0} ]", string.IsNullOrEmpty(akt.CustInkAktKunde) ? akt.CustInkAktID.ToString() : akt.CustInkAktKunde));
}
#region DB I/O Utility Methods
private tblWFA GetWFA(int wfpPosition, int aktId, int klientId)
{
_hasAktWorkflow = false;
tblWFA ret = null;
ArrayList wfaList = HTBUtils.GetSqlRecords("SELECT * FROM tblWFA WHERE WFPAkt = " + aktId, typeof(tblWFA));
if (wfaList.Count > 0)
{
foreach (tblWFA wfa in wfaList)
{
if (wfa.WFPPosition == wfpPosition)
{
_hasAktWorkflow = true;
return wfa;
}
}
}
else // Get Akt Work-Flow from Client
{
var wfk = (tblWFK)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblWFK WHERE WFPPosition = " + wfpPosition + " AND WFPKlient = " + klientId, typeof(tblWFK));
if (wfk != null)
{
ret = new tblWFA();
ret.Assign(wfk);
}
}
return ret;
}
private ArrayList GetAktAktionKosten(int wfpPosition, int aktId, int klientId)
{
if (_hasAktWorkflow)
return HTBUtils.GetSqlRecords("SELECT * FROM qryAktAktionKosten WHERE WFPPosition = " + wfpPosition + " AND WFPAkt = " + aktId, typeof(qryAktAktionKosten));
return HTBUtils.GetSqlRecords("SELECT * FROM qryAktAktionKostenKlient WHERE WFPPosition = " + wfpPosition +" AND WFPKlient = "+klientId, typeof(qryAktAktionKosten));
}
private List<int> GetKostenArtIdForMahnung(int mahnungNumber)
{
return (from tblMahnungKostenArtId kostArtId in HTBUtils.GetSqlRecords("SELECT * FROM tblMahnungKostenArtId WHERE MahKostMahnungNummer = " + mahnungNumber, typeof (tblMahnungKostenArtId)) select kostArtId.MahKostArtId).ToList();
}
private void UpdateAktStatus(tblCustInkAkt akt)
{
akt.CustInkAktLastChange = DateTime.Now;
RecordSet.Update(akt);
}
private void CreateInvoiceRecord(int aktID, qryKosten record, decimal amount)
{
int invType = tblCustInkAktInvoice.INVOICE_TYPE_COLLECTION_INVOICE; // collection 'inkasso' cost
if (record.KostenInvoiceType > 0)
{
invType = record.KostenInvoiceType;
}
_invMgr.CreateAndSaveInvoice(aktID, invType, Convert.ToDouble(amount), record.KostenArtText, true);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jogging.Model.Models
{
public class Session
{
public int Id { get; set; }
public DateTime End { get; set; }
public DateTime Start { get; set; }
public List<Temperature> Temperatures { get; set; }
public List<Pressure> Pressures { get; set; }
public List<Humidity> Humidities { get; set; }
public List<AcceleroMeter> AcceleroMeters { get; set; }
public Session()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace DelftTools.Utils
{
/// <summary>
/// Provides culture invariant string conversion
/// </summary>
public static class ConversionHelper
{
/// <summary>
/// Converts a string to single with a decimal separator '.'
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static float ToSingle(string s)
{
return Convert.ToSingle(s, CultureInfo.InvariantCulture);
}
public static double ToDouble(string s)
{
return Convert.ToDouble(s, CultureInfo.InvariantCulture);
}
}
}
|
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace aairvid.UIUtils
{
public class AspectRatioImageView : ImageView
{
public AspectRatioImageView(Context context)
: base(context)
{
}
public AspectRatioImageView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public AspectRatioImageView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
}
protected AspectRatioImageView(IntPtr javaReference,
JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (Drawable != null)
{
int width = MeasureSpec.GetSize(widthMeasureSpec);
if (Drawable.IntrinsicWidth > 0)
{
int height = width * Drawable.IntrinsicHeight / Drawable.IntrinsicWidth;
SetMeasuredDimension(width, height);
}
else
{
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
else
{
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ModelTransformationComponent;
namespace TransformationComponentUnitTest
{
public partial class TransformUnitTest
{
[TestClass]
public partial class TransformFromStrings
{
[TestMethod]
[TestCategory("FullTransform")]
public void HasTwoLang_BNF()
{
//arrange
var rules = "/start\n" +
"Program\n" +
"/language_start a\n" +
"Program ::= a\n" +
"/language_end\n" +
"/language_start b\n" +
"Program ::= b\n" +
"/language_end\n" +
"/end";
var text = "a";
var component = new TransformationComponent();
var expected = "b";
//act
var actual = component.Transform(text, rules, "a", "b");
//assert
Assert.IsNotNull(actual);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void PascalToCSharp()
{
//arrange
var rules = TransformationComponentUnitTest.Resource1.CSharpPascalRules;
var source = TransformationComponentUnitTest.Resource1.PascalSource;
var component = new TransformationComponent();
//act
var actual = component.Transform(source, rules, "Pascal", "CSharp");
System.Diagnostics.Debug.WriteLine(actual);
}
}
}
}
|
using UnityEngine;
using Random = System.Random;
using Exception = System.Exception;
using CombinablesCollection = System.Collections.Generic.IList<Thesis.Interface.ICombinable>;
namespace Thesis {
public class Util
{
public static Random random = new Random();
/// <summary>
/// Rolls a weighted dice.
/// </summary>
/// <param name='chances'>
/// The chances for each possible result.
/// </param>
/// <param name='numbers'>
/// A set of the possible result values.
/// </param>
/// <param name='precision'>
/// The maximum of decimal digits that a number has.
/// </param>
public static int RollDice (float[] chances, int[] numbers = null, int precision = 2)
{
if (numbers == null)
{
numbers = new int[chances.Length];
for (var i = 0; i < chances.Length; ++i)
numbers[i] = i + 1;
}
precision = (int) Mathf.Pow(10, precision);
int[] expanded = new int[precision];
int start = 0;
int end = 0;
for (var i = 0; i < chances.Length; ++i)
{
start = end;
end += Mathf.FloorToInt(chances[i] * precision);
for (var j = start; j < end; ++j)
expanded[j] = numbers[i];
}
return expanded[random.Next(precision)];
}
public static GameObject CombineMeshes (string name,
string materialName,
CombinablesCollection objects,
GameObject parent = null)
{
var gameObject = new GameObject(name);
gameObject.SetActive(false);
if (parent != null)
gameObject.transform.parent = parent.transform;
var meshFilter = gameObject.AddComponent<MeshFilter>();
var meshRenderer = gameObject.AddComponent<MeshRenderer>();
meshRenderer.sharedMaterial = Resources.Load("Materials/" + materialName,
typeof(Material)) as Material;
MeshFilter[] meshFilters = new MeshFilter[objects.Count];
for (var i = 0; i < objects.Count; ++i)
{
meshFilters[i] = objects[i].meshFilter;
GameObject.Destroy(objects[i].gameObject);
}
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
for (var i = 0; i < meshFilters.Length; ++i)
{
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
}
meshFilter.mesh = new Mesh();
meshFilter.mesh.CombineMeshes(combine);
return gameObject;
}
public static Vector3 IntersectionPoint (Vector3 p1, Vector3 dir1,
Vector3 p2, Vector3 dir2)
{
var dir_cross = Vector3.Cross(dir1, dir2);
var tmp_cross = Vector3.Cross(p2 - p1, dir2);
float c1;
if (dir_cross.x != 0f)
c1 = tmp_cross.x / dir_cross.x;
else if (dir_cross.y != 0f)
c1 = tmp_cross.y / dir_cross.y;
else if (dir_cross.z != 0f)
c1 = tmp_cross.z / dir_cross.z;
else
throw new System.DivideByZeroException("Result of cross product is Vector3(0,0,0)!");
return p1 + c1 * dir1;
}
public static void PrintVector (string s, Vector3 v)
{
Debug.Log(s + " " + v.x + " " + v.y + " " + v.z);
}
}
} // namespace Thesis |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace autovezeto
{
class Vezeto
{
private string nev;
private bool bentul;
public string bemutatkozik()
{
return "A neve: " + nev;
}
public Vezeto(string nev)
{
this.nev = nev;
}
public bool isBentul() { return bentul; }
public void setBentul (bool ul)
{
bentul = ul;
}
public override string ToString()
{
return $"név: {nev}, bentül: {bentul}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IWorkFlow.Host;
using Newtonsoft.Json;
using BizService;
using System.Data;
using IWorkFlow.ORM;
namespace BizService.Services
{
class UserSelectControlSvc : BaseDataHandler
{
[DataAction("GetData","FilterText","userid")]
public string GetData(string FilterText,string userid)
{
StringBuilder strSql = new StringBuilder();
IDbTransaction tran = Utility.Database.BeginDbTransaction();
GetDataModel dataModel = new GetDataModel();
dataModel.dt = new DataTable();
try
{
if (FilterText == "dcry")
{
//调查人员
strSql.Append(@"SELECT
A.UserID AS id, B.CnName AS name, B.DPID AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
WHERE
A.UserType = 1
UNION
SELECT
C.DPID AS id, C.DPName AS name, '0' AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
INNER JOIN FX_Department C ON C.DPID = B.DPID
WHERE
A.UserType = 1");
}
else if (FilterText == "xwry")
{
//询问人员
strSql.Append(@"SELECT
A.UserID AS id, B.CnName AS name, B.DPID AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
WHERE
A.UserType = 2
UNION
SELECT
C.DPID AS id, C.DPName AS name, '0' AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
INNER JOIN FX_Department C ON C.DPID = B.DPID
WHERE
A.UserType = 2");
}
else if (FilterText == "zfry")
{
//执法人员
strSql.Append(@"SELECT
A.UserID AS id, B.CnName AS name, B.DPID AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
WHERE
A.UserType = 3
UNION
SELECT
C.DPID AS id, C.DPName AS name, '0' AS ParentId
FROM FX_RYLXInfo A
INNER JOIN FX_UserInfo B ON B.UserID = A.UserID
INNER JOIN FX_Department C ON C.DPID = B.DPID
WHERE
A.UserType = 3");
}
else
{
//加载所有科室人员
strSql.Append(@"
select a.id,a.name,a.ParentId,a.flag,a.drag,a.RankID from (
select DPID as id,DPName as name ,PDPID as ParentId,'0' as flag,'false' as drag,RankID from FX_Department
union all
select UserId as id,CnName as name,DPID as ParentId,'1' as flag,'true' as drag,RankID from FX_UserInfo
where EnName is not null
) as a GROUP BY a.id,a.name,a.ParentId,a.flag,a.drag,a.RankID order by ParentId asc,a.RankID asc
");
}
DataSet dataSet = Utility.Database.ExcuteDataSet(strSql.ToString(), tran);
dataModel.dt = dataSet.Tables[0];
dataModel.dpName = ComClass.GetDeptByUserId(userid).DPName;
Utility.Database.Commit(tran);
return JsonConvert.SerializeObject( dataModel);//将对象转为json字符串并返回到客户端
}
catch (Exception ex)
{
ComBase.Logger(ex);
return Utility.JsonMsg(false, ex.Message);
}
}
public class GetDataModel
{
public DataTable dt;
public string dpName;//部门名称
}
public override string Key
{
get
{
return "UserSelectControlSvc";
}
}
}
}
|
using System;
class Task05
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n / 2; i++)
{
string dots = new string('.', n + i);
string sharp = new string('#', 3 * n - 2 * i);
Console.WriteLine(dots + sharp + dots);
}
for (int i = 0; i < n / 2 + 1; i++)
{
string dots = new string('.', n / 2 * 3 + i);
string sharpDots = new string('.', 2 * n - 2 - 2 * i);
Console.WriteLine(dots + "#" + sharpDots + "#" + dots);
}
Console.WriteLine(new string('.', 2 * n) + new string('#', n) + new string('.', 2 * n));
string endDots = new string('.', n * 2 - 2);
string endSharp = new string('#', n + 4);
for (int i = 0; i < n / 2; i++)
{
Console.WriteLine(endDots + endSharp + endDots);
};
Console.WriteLine(new string('.', (5 * n - 10) / 2) + "D^A^N^C^E^" + new string('.', (5 * n - 10) / 2));
for (int i = 0; i <= n / 2; i++)
{
Console.WriteLine(endDots + endSharp + endDots);
};
}
}
|
//****************************************************************************************************
// Program Name: Chapter 2 Case Study, Christopher's Car Center
// Programmer: Christopher M. Anderson
// Date: 02.04.08
// Purpose: This program demonstrates picture boxes, ToolTips, radio buttons, and a checkbox
//****************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Module2
{
public partial class Module2 : Form
{
public Module2()
{
InitializeComponent();
// Hours Hidden When Program Starts
lblHours.Visible = false;
}
private void cbHours_CheckedChanged(object sender, EventArgs e)
{
// Display Hours If Checked
lblHours.Visible = cbHours.Checked;
}
private void pbSales_Click(object sender, EventArgs e)
{
// Display Sales Information
lblMessage.Text = "Family wagon, immaculate condition $12,995";
}
private void pbService_Click(object sender, EventArgs e)
{
// Display Service Information
lblMessage.Text = "Lube, oil, filter $25.99";
}
private void pcDetail_Click(object sender, EventArgs e)
{
// Display Detail Shop Information
lblMessage.Text = "Complete detail $79.95 for most cars";
}
private void pbEmployment_Click(object sender, EventArgs e)
{
// Display Employment Information
lblMessage.Text = "Sales position, contact Mr. Mann 551-2134 x475";
}
private void rbGrey_CheckedChanged(object sender, EventArgs e)
{
// Set Background Color And Text Color
lblMessage.BackColor = SystemColors.Control;
lblMessage.ForeColor = SystemColors.ControlText;
}
private void rbRed_CheckedChanged(object sender, EventArgs e)
{
// Set Background Color And Text Color
lblMessage.BackColor = Color.Red;
lblMessage.ForeColor = Color.White;
}
private void rbGreen_CheckedChanged(object sender, EventArgs e)
{
// Set Background Color And Text Color
lblMessage.BackColor = Color.Green;
lblMessage.ForeColor = Color.White;
}
private void rbBlue_CheckedChanged(object sender, EventArgs e)
{
// Set Background Color And Text Color
lblMessage.BackColor = Color.Blue;
lblMessage.ForeColor = Color.White;
}
private void pbClear_Click(object sender, EventArgs e)
{
// Clear Message And Reset Colors
lblMessage.Text = "";
rbGrey.Checked = true;
}
private void pbExit_Click(object sender, EventArgs e)
{
// Exit The Program
this.Close();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetUpCityInfector : CityInfector
{
public IEnumerator initialInfection(){
yield return StartCoroutine(firstRoundInitialInfection());
yield return StartCoroutine(secondRoundInitialInfection());
yield return StartCoroutine(thirdRoundInitialInfection());
}
protected IEnumerator initialInfectionRound(int cubesPerInfectionCard){
for(int i = 0; i < Vals.CARDS_PER_INITIAL_INFECTION_ROUND; i++){
InfectionCard drawn = drawInfectionCard();
yield return StartCoroutine(addCubesbyInfectionCard(drawn, cubesPerInfectionCard));
}
}
protected IEnumerator firstRoundInitialInfection(){
yield return StartCoroutine(initialInfectionRound(Vals.INITIAL_INFECTION_FIRST_PHASE));
}
protected IEnumerator secondRoundInitialInfection(){
yield return StartCoroutine(initialInfectionRound(Vals.INITIAL_INFECTION_SECOND_PHASE));
}
protected IEnumerator thirdRoundInitialInfection(){
yield return StartCoroutine(initialInfectionRound(Vals.INITIAL_INFECTION_THIRD_PHASE));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.CompareArrays
{
class CompareTwoArrays
{
static void Main()
{
Console.WriteLine("Enter the size of the first array:");
int sizeFirst = int.Parse(Console.ReadLine());
int [] firstArray = new int[sizeFirst];
for (int i = 0; i < firstArray.Length; i++)
{
Console.WriteLine("Enter element {0}: ", i);
firstArray[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the size of the second array:");
int sizeSecond = int.Parse(Console.ReadLine());
int[] secondArray = new int[sizeSecond];
for (int i = 0; i < secondArray.Length; i++)
{
Console.WriteLine("Enter element {0}: ", i);
secondArray[i] = int.Parse(Console.ReadLine());
}
int lengthFi = firstArray.Length;
int lengthSe = secondArray.Length;
for (int index = 0; index < firstArray.Length; index++)
{
for (int index2 = 0; index2 < secondArray.Length; index2++)
{
if (index != index2 && lengthFi != lengthSe)
{
Console.WriteLine("Those two arrays elements are NOT equal!");
}
else
{
Console.WriteLine("Those two arrays elements are equal!");
}
}
};
Console.WriteLine();
}
}
}
|
namespace SignInCheckIn.Models.DTO
{
public class RoomDto
{
public int RoomId { get; set; }
public string RoomName { get; set; }
public string RoomNumber { get; set; }
public int? KcSortOrder { get; set; }
}
} |
using CarRental.API.DAL.Entities;
using CarRental.API.DAL.CustomEntities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CarRental.API.DAL.DataServices.Prices
{
public interface IPriceDataService
{
Task<PriceItem> GetAsync(Guid id);
Task<IEnumerable<PriceItem>> GetAllAsync();
Task<IEnumerable<DetailedPriceItem>> GetDetailedPrices();
Task<IEnumerable<PriceItem>> GetCarPriceAsync(Guid id);
Task<PriceItem> CreateAsync(PriceItem price);
Task<PriceItem> DeleteAsync(Guid Id);
Task<PriceItem> UpsertAsync(PriceItem price);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Business.OnlinePay.Company.Lianlian.Message
{
public class MessageBase
{
public virtual string InterFaceUrl
{
get
{
return "";
}
}
/// <summary>
/// 商户编号
/// </summary>
public string oid_partner;
/// <summary>
/// 签名方式
/// </summary>
public string sign_type;
/// <summary>
/// 签名
/// </summary>
public string sign;
SortedDictionary<string, string> GetDic()
{
var fields = GetType().GetFields();
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
foreach (var item in fields)
{
if (item.Name != "sign")
{
dic.Add(item.Name, item.GetValue(this) + "");
}
}
return dic;
}
public void SetSign()
{
var dic = GetDic();
string sign2 = YinTongUtil.addSign(dic, PartnerConfig.TRADER_PRI_KEY, PartnerConfig.MD5_KEY);
sign = sign2;
}
public bool CheckSign()
{
var dic = GetDic();
var a = YinTongUtil.checkSign(dic, PartnerConfig.YT_PUB_KEY, //验证失败
PartnerConfig.MD5_KEY);
return a;
}
public static T FromRequest<T>(string json) where T : class,new()
{
var obj = CoreHelper.SerializeHelper.SerializerFromJSON(json, typeof(T), Encoding.UTF8);
return obj as T;
}
public static T FromRequest<T>(System.Collections.Specialized.NameValueCollection c) where T : class,new()
{
var fields = typeof(T).GetFields();
var obj = new T();
foreach (var item in fields)
{
item.SetValue(obj, c[item.Name]);
}
return obj;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartLib
{
public class AlcoBeverageType:SimpleNamedEntity
{
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public override string FriendlyName
{
get
{
return "Тип алкогольной продукции";
}
}
public string Code
{
get;
set;
}
}
}
|
using mvvm.Utils;
using mvvm.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
namespace mvvm.ViewModels
{
class MainViewModel : PropertyNotifier
{
private UserControl currentUserControl;
private static StudentsInformationView studentsInformation = new StudentsInformationView();
public UserControl CurrentUserControl
{
get { return currentUserControl; }
set
{
if (currentUserControl != value)
{
currentUserControl = value;
RaisePropertyChanged("CurrentUserControl");
}
}
}
void StudentsInformationViewCommandExecute() { CurrentUserControl = studentsInformation; }
public ICommand StudentsInformationViewCommand { get { return new RelayCommand(StudentsInformationViewCommandExecute); } }
}
} |
using DatVentas;
using EntVenta;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusVenta
{
public class BusUser
{
public List<User> getUsersList(User u)
{
DataTable dt = new DataTable();
dt = new DatUser().getUsers(u);
List<User> lstUser = new List<User>();
foreach (DataRow dr in dt.Rows)
{
User user = new User();
user.Id = Convert.ToInt32(dr["Id_Usuario"].ToString());
user.Nombre = dr["Nombre"].ToString();
user.Apellidos = dr["Apellidos"].ToString();
user.Direccion = dr["Localidad"].ToString();
user.Foto = (byte[])dr["Foto"];
user.NombreFoto = dr["Nombre_Foto"].ToString();
user.Usuario = dr["Usuario"].ToString();
user.Contraseña = dr["Contrasenia"].ToString();
user.Correo = dr["Correo"].ToString();
user.RolID = Convert.ToInt32(dr["Rol_Id"]);
user.Estado = Convert.ToBoolean(dr["Estado"].ToString());
user.Rol = dr["Rol"].ToString();
lstUser.Add(user);
}
return lstUser;
}
public List<User> ListarUsuarios()
{
DataTable dt = new DataTable();
dt = new DatUser().MostrarUsuarios();
List<User> lstUser = new List<User>();
foreach (DataRow dr in dt.Rows)
{
User user = new User();
user.Id = Convert.ToInt32(dr["Id_Usuario"].ToString());
user.Nombre = dr["Nombre"].ToString();
user.Apellidos = dr["Apellidos"].ToString();
user.Direccion = dr["Localidad"].ToString();
user.Foto = (byte[])dr["Foto"];
user.NombreFoto = dr["Nombre_Foto"].ToString();
user.Usuario = dr["Usuario"].ToString();
user.Contraseña = dr["Contrasenia"].ToString();
user.Correo = dr["Correo"].ToString();
user.RolID = Convert.ToInt32(dr["Rol_Id"]);
user.Estado = Convert.ToBoolean(dr["Estado"].ToString());
lstUser.Add(user);
}
return lstUser;
}
public void AddUser(User u)//string nombre, string direccion, string usuario, string contraseña, byte[] foto, string nombreFoto, string correo, string rol, bool estado)
{
int filasAfectadas = new DatUser().AddUser(u);//nombre, direccion,usuario, contraseña, foto, nombreFoto, correo, rol, estado);
if (filasAfectadas != 1)
{
throw new ApplicationException("Ocurrio un error al insertar");
}
}
public void DeleteUser(User u)
{
int filasAfectadas = new DatUser().DeleteUser(u);
if (filasAfectadas != 1)
{
throw new ApplicationException("Ocurrio un error al insertar");
}
}
public void EditUser(User u)
{
int filasAfectadas = new DatUser().EditUser(u);
if (filasAfectadas != 1)
{
throw new ApplicationException("Ocurrió un error al editar");
}
}
public string ShowPermision(string user)
{
string user1 = new DatUser().ShowPremission(user);
return user1;
}
public User ObtenerUsuario(string serialPC)
{
DataRow dr = new DatCatGenerico().Obtener_InicioSesion(serialPC);
User u = new User();
u.Id = Convert.ToInt32(dr["Usuario_Id"]);
u.Foto = (byte[])dr["Foto"];
u.Rol = dr["Tipo_Usuario"].ToString();
u.Nombre = dr["Nombre"].ToString();
return u;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GameProject
{
class UserValidationManager : IUserValidationService
{
public bool Validation(Gamer gamer)
{
if(gamer.FirstName == "Berke" && gamer.LastName == "Özden" && gamer.ID == 1 && gamer.IdendityNumber == 123123 && gamer.BirthYear == 1999)
{
return true;
}
else
{
return false;
}
}
}
}
|
using UnityEngine;
using System;
using System.Reflection;
using System.Collections.Generic;
public partial class Sway : MonoBehaviour
{
private interface ITween
{
void Start();
void Start(float time);
void Update();
void Stop();
bool IsRun { get; }
bool IsDone { get; }
}
private abstract class Base<T> : ITween where T : class
{
protected readonly Transform m_target = null;
private static AnimationCurve s_easeTypeLinear = new AnimationCurve(new Keyframe(0, 0, 1, 1), new Keyframe(1, 1, 1, 1));
private float m_time = 0;
private float m_delay = 0; // Может быть отрицательный, чтобы начать с 0,5 сек например
private bool m_ignoreTimeScale = false;
private AnimationCurve m_easeTypeCurve = s_easeTypeLinear;
private bool m_canSetup = true;
private float m_startTime = float.NaN;
private float m_currentTime = 0;
private bool m_done = false;
private float m_overtime = 0;
private Action m_onStart = null;
private Action m_onUpdate = null;
private Action<float> m_onComplete = null;
public bool CanSetup { get { return m_canSetup; } }
public bool IsRun { get { return !float.IsNaN(m_startTime); } }
public bool IsDone { get { return m_done; } }
public Base(Transform target, float time)
{
m_target = target;
m_time = (time < 0) ? (0) : (time);
}
public void Start()
{
float startTime = (m_delay < 0) ? (Mathf.Abs(m_delay)) : (0);
Start(startTime);
}
public void Start(float time)
{
if (IsRun)
{
Debug.LogError("Tween already started");
return;
}
m_canSetup = false;
m_startTime = GetUnityTime() - Mathf.Clamp(time, 0, m_time);
m_currentTime = 0;
m_done = false;
if (m_delay < 0)
m_delay = 0;
OnStart();
if (m_onStart != null)
m_onStart();
}
public void Update()
{
if (!IsRun)
return;
m_currentTime = GetUnityTime() - m_startTime;
if (m_currentTime < m_delay)
return;
m_currentTime -= m_delay;
if (m_currentTime > m_time)
m_currentTime = m_time;
// Target has been destroyed
if (m_target == null)
{
m_done = true;
return;
}
// Update values
if (m_currentTime <= m_time)
{
float easeTypeCurveValue = GetEasyTypeCurveValue(m_currentTime);
easeTypeCurveValue = Mathf.Clamp(easeTypeCurveValue, 0, 1);
OnUpdate(m_currentTime, easeTypeCurveValue);
if (m_onUpdate != null)
m_onUpdate();
}
//
if (m_currentTime >= m_time)
{
m_done = true;
m_overtime = m_currentTime - m_time;
}
}
public void Stop()
{
if (!IsRun)
return;
m_startTime = float.NaN;
if (!m_done)
{
m_done = true;
m_overtime = m_currentTime - m_time;
}
OnStop();
if (m_onComplete != null)
m_onComplete(m_overtime);
}
protected abstract void OnUpdate(float currentTime, float easeTypeCurveValue);
protected virtual void OnStart()
{ }
protected virtual void OnStop()
{ }
private float GetEasyTypeCurveValue(float currentTime)
{
float time = (m_time != 0) ? (currentTime / m_time) : (1);
return m_easeTypeCurve.Evaluate(time);
}
private float GetUnityTime()
{
return m_ignoreTimeScale ? UnityEngine.Time.realtimeSinceStartup : UnityEngine.Time.time;
}
#region --- Setup Functions ---
public T Delay(float value)
{
if (CanSetup)
m_delay = value;
return this as T;
}
public T IgnoreTimeScale(bool value)
{
if (CanSetup)
m_ignoreTimeScale = value;
return this as T;
}
public T EaseType(AnimationCurve curve)
{
if (CanSetup)
m_easeTypeCurve = (curve != null) ? (curve) : (s_easeTypeLinear);
return this as T;
}
public T OnStart(Action action)
{
if (CanSetup)
m_onStart = action;
return this as T;
}
public T OnUpdate(Action action)
{
if (CanSetup)
m_onUpdate = action;
return this as T;
}
public T OnComplete(Action<float> action)
{
if (CanSetup)
m_onComplete = action;
return this as T;
}
#endregion
}
} |
using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
namespace Microsoft.UnifiedPlatform.Service.Telemetry.Initializers
{
public class TimestampAdjustmentInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (!((ISupportProperties)telemetry).Properties.ContainsKey("ActualTimestamp"))
return;
var actualTimestampStr = ((ISupportProperties)telemetry).Properties["ActualTimestamp"];
if (!DateTimeOffset.TryParse(actualTimestampStr, out DateTimeOffset actualTimestamp))
return;
telemetry.Timestamp = actualTimestamp;
}
}
}
|
namespace NetSix.Errors.Exceptions;
class UserExistsException : ServiceException
{
public override int HttpStatusCode => StatusCodes.Status409Conflict;
public override string ErrorMessage => "User already exists.";
} |
using Profiling2.Domain.Prf;
namespace Profiling2.Domain.Contracts.Queries
{
public interface IAdminUserQueries
{
AdminUser GetAdminUser(string userId);
}
}
|
using System.Windows;
using System.Windows.Input;
using Administration.Properties;
using Administration.ViewModel;
using DataAccess;
using DataAccess.Model;
using DataAccess.Repository;
namespace Administration.View
{
public partial class MovieListPage
{
private readonly MovieListPageViewModel viewModel;
private readonly MainWindow window;
public MovieListPage(MainWindow window)
{
this.window = window;
InitializeComponent();
var connectionString = ConnectionStringBuilder.Build(
Settings.Default.server,
Settings.Default.database,
Settings.Default.user,
Settings.Default.password);
var repository = new MovieRepository(connectionString);
viewModel = new MovieListPageViewModel(this, repository);
DataContext = viewModel.Movies;
}
private Movie SelectedMovie
{
get { return (Movie) listView.SelectedItem; }
}
public int ListCount
{
set { window.StatusBarCount.Content = value; }
}
private void listView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
viewModel.OpenEditor(SelectedMovie);
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
viewModel.OpenEditor(null);
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
viewModel.OpenEditor(SelectedMovie);
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (SelectedMovie == null) return;
viewModel.Delete(SelectedMovie);
}
}
} |
using UnityEngine;
public static class TransformExt{
public static void Clear(this Transform x) {
x.localPosition = Vector3.zero;
x.localRotation = Quaternion.identity;
x.localScale = Vector3.one;
}
public static float Serial(this Transform x){
return x.localPosition.Serial()
+ x.localRotation.Serial()
+ x.localScale.Serial();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DraftManager
{
private string currentMode;
private double totalStoredEnergy;
private double totalMinedOre;
private List<Harvester> harvesters;
private List<Provider> providers;
public DraftManager()
{
this.currentMode = "Full";
this.harvesters = new List<Harvester>();
this.providers = new List<Provider>();
}
public string RegisterHarvester(List<string> arguments)
{
var type = arguments[0];
var id = arguments[1];
var oreOutput = double.Parse(arguments[2]);
var energyRequirement = double.Parse(arguments[3]);
try
{
if (type == "Sonic")
{
var sonicFactor = int.Parse(arguments[4]);
harvesters.Add(new SonicHarvester(id, oreOutput, energyRequirement, sonicFactor));
}
else
{
harvesters.Add(new HammerHarvester(id, oreOutput, energyRequirement));
}
}
catch (ArgumentException ae)
{
return ae.Message;
}
return $"Successfully registered {type} Harvester - {id}";
}
public string RegisterProvider(List<string> arguments)
{
var type = arguments[0];
var id = arguments[1];
var energyOutput = double.Parse(arguments[2]);
try
{
if (type == "Solar")
{
providers.Add(new SolarProvider(id, energyOutput));
}
else
{
providers.Add(new PressureProvider(id, energyOutput));
}
}
catch (ArgumentException ae)
{
return ae.Message;
}
return $"Successfully registered {type} Provider - {id}";
}
public string Day()
{
double totalEnergyNeeded = 0;
double summedOreOutput = 0;
double summedEnergyOutput = providers.Sum(p => p.EnergyOutput);
this.totalStoredEnergy += summedEnergyOutput;
switch (currentMode)
{
case "Full":
totalEnergyNeeded = harvesters.Sum(e => e.EnergyRequirement);
if (totalStoredEnergy >= totalEnergyNeeded)
{
summedOreOutput = this.harvesters.Sum(h => h.OreOutput);
this.totalMinedOre += summedOreOutput;
this.totalStoredEnergy -= totalEnergyNeeded;
}
break;
case "Half":
totalEnergyNeeded = harvesters.Sum(e => e.EnergyRequirement)*0.6;
if (totalStoredEnergy >= totalEnergyNeeded)
{
summedOreOutput = this.harvesters.Sum(h => h.OreOutput)*0.5;
this.totalMinedOre += summedOreOutput;
this.totalStoredEnergy -= totalEnergyNeeded;
}
break;
case "Energy":
break;
}
var sb = new StringBuilder();
sb.AppendLine("A day has passed.");
sb.AppendLine($"Energy Provided: {summedEnergyOutput}");
sb.Append($"Plumbus Ore Mined: {summedOreOutput}");
return sb.ToString();
}
public string Mode(List<string> arguments)
{
var mode = arguments[0];
this.currentMode = mode;
return $"Successfully changed working mode to {mode} Mode";
}
public string Check(List<string> arguments)
{
var id = arguments[0];
if (this.harvesters.Any(h => h.Id == id))
{
return this.harvesters.First(h => h.Id == id).ToString();
}
if (this.providers.Any(h => h.Id == id))
{
return this.providers.First(h => h.Id == id).ToString();
}
return $"No element found with id - {id}";
}
public string ShutDown()
{
var sb = new StringBuilder();
sb.AppendLine("System Shutdown");
sb.AppendLine($"Total Energy Stored: {totalStoredEnergy}");
sb.Append($"Total Mined Plumbus Ore: {totalMinedOre}");
return sb.ToString();
}
} |
using System;
namespace Math_power
{
class Program
{
static void Main(string[] args)
{
double num = double.Parse(Console.ReadLine());
int power = int.Parse(Console.ReadLine());
double result = GetPower(num, power);
Console.WriteLine(result);
}
static double GetPower(double num, int power)
{
return Math.Pow(num, power);
}
}
}
|
using ArgumentRes.Attributes;
using ArgumentRes.Services.interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ArgumentRes.Services.implementations
{
/// <summary>
/// Manages the setting of properties of an object of type T based on the argument attributes
/// on the class.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Properties<T> : IProperties<T>
{
private readonly IEnumerable<PropertyInfo> _properties;
private readonly IDictionary<PropertyInfo, string> _mandatoryArguments;
private int _propertyNumber;
/// <summary>
/// Default constructor
/// </summary>
public Properties()
{
// Get the properties on this class
_properties = typeof(T).GetProperties();
// Initialise mandatory arguments
_mandatoryArguments = MandatoryArguments;
}
/// <summary>
/// Returns the property info object for a switch with the given key. If key is not valid,
/// throws an argument exception.
/// </summary>
/// <param name="key">Switch key to set</param>
/// <returns>Related property info object</returns>
public PropertyInfo Switch(string key)
{
if (Flags.ContainsKey(key))
{
return Flags[key];
}
throw new ArgumentException($"Unknown parameter {key}");
}
/// <summary>
/// Is the value passed a simple boolean switch with no argument? (ie. is the property
/// for this key a bool?)
/// </summary>
/// <param name="param">Property key</param>
/// <returns>True if the property is boolean</returns>
public bool IsBooleanSwitch(string param)
{
return Flags.ContainsKey(param) && Flags[param].PropertyType == typeof(bool);
}
/// <summary>
/// Returns a list of missing arguments. As arguments are provided to SetFlagValue,
/// any that are mandatory are removed from this collection
/// </summary>
public IEnumerable<string> MissingArguments => _mandatoryArguments.Select(arg => arg.Value);
/// <summary>
/// Sets the value of a property
/// </summary>
/// <param name="obj">Instance of a T with properties matching the arguments</param>
/// <param name="param">Flag name of the Flag property</param>
/// <param name="arg">Value to set on the Flag property</param>
public void SetFlagValue(T obj, string param, object arg)
{
// Expecting a switch parameter
var propertyInfo = Switch(param);
var type = propertyInfo.PropertyType;
try
{
// Attempt to convert the string value into the property type
var value = Convert.ChangeType(arg, type);
propertyInfo.SetValue(obj, value, null);
// Check off this mandatory argument
_mandatoryArguments.Remove(propertyInfo);
}
catch (Exception e)
{
throw new Exception($"Unable to cast value {arg} for switch {param} to {type.Name}", e);
}
}
/// <summary>
/// Sets the value of the next parameter type property of an object of type T.
/// </summary>
/// <param name="obj">Instance of a T with parameter properties</param>
/// <param name="arg">Value of this parameter</param>
public void SetPropertyValue(T obj, object arg)
{
// This is a simple text argument
var propertyInfo = Parameters[_propertyNumber];
if (propertyInfo.PropertyType == typeof(List<string>))
{
// The argument is a string list - create the list if required then add our argument to it
var list = (List<string>)propertyInfo.GetValue(obj);
if (null == list)
{
list = new List<string>();
propertyInfo.SetValue(obj, list, null);
}
list.Add(arg as string);
}
else
{
// The argument is a simgple string value - just set the value
propertyInfo.SetValue(obj, arg);
_propertyNumber++;
}
// Check off this mandatory argument
_mandatoryArguments.Remove(propertyInfo);
}
/// <summary>
/// Helper function to get the Flag properties
/// </summary>
private IDictionary<string, PropertyInfo> Flags =>_properties
.Where(p => p.GetCustomAttributes<FlagAttribute>().Any())
.ToDictionary(t => t.GetCustomAttributes<FlagAttribute>().First().Key, t => t);
/// <summary>
/// Helper function to get a list of parameter properties
/// </summary>
private IList<PropertyInfo> Parameters => _properties
.Where(p => p.GetCustomAttributes<ParameterAttribute>().Any())
.ToList();
/// <summary>
/// Helper function that returns properties identified as mandatory
/// </summary>
private IDictionary<PropertyInfo, string> MandatoryArguments => _properties
.Where(p => p.GetCustomAttributes<MandatoryAttribute>().Any())
.ToDictionary(t => t, t => t.GetCustomAttributes<ParameterAttribute>().FirstOrDefault()?.Key);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
class ClientInstance
{
public Socket sClient { get; private set; }
public String RemoteEndpoint { get; private set; }
public bool Authed { get; private set; }
public String Name { get; private set; }
public String X { get; private set; }
public String Y { get; private set; }
public String Pressing { get; private set; }
public String Reset { get; private set; }
public ClientInstance(Socket cli)
{
this.sClient = cli;
this.RemoteEndpoint = cli.RemoteEndPoint.ToString();
this.Name = "Unknown";
this.X = "0";
this.Y = "0";
this.Pressing = "0";
this.Reset = "0";
}
public void Authenticate() {
this.Authed = true;
}
public void setName(string name) {
this.Name = name;
}
public void setX(string x)
{
this.X = x;
}
public void setY(string y)
{
this.Y = y;
}
public void setP(string p)
{
this.Pressing = p;
}
public void setR(string r)
{
this.Reset = r;
}
}
|
namespace Bookinist.Services.Interfaces
{
internal interface IDataService
{
}
}
|
using UnityEngine;
public class RotateArm : MonoBehaviour {
private void Update() {
if (!GameController.GamePaused) {
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mouseDir = mousePos - (Vector2)transform.position;
mouseDir = mouseDir.normalized;
float angle = Mathf.Atan2(mouseDir.y, mouseDir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;
namespace Cyber_FerCesar_Sistema
{
class Banco
{
private static SQLiteConnection conexao;
private static SQLiteConnection ConexaoBanco()
{
conexao = new SQLiteConnection("Data Source = " + Globais.caminhoBanco + Globais.nomeBanco);
conexao.Open();
return conexao;
}
public static DataTable dql(string sql)
{
SQLiteDataAdapter da = null;
DataTable dt = new DataTable();
try
{
var vcon = ConexaoBanco();
var cmd = vcon.CreateCommand();
cmd.CommandText = sql;
da = new SQLiteDataAdapter(cmd.CommandText, vcon);
da.Fill(dt);
return dt;
}
catch(Exception ex)
{
throw ex;
}
}
public static void dml(string sql)
{
try
{
var vcon = ConexaoBanco();
var cmd = vcon.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
vcon.Close();
}
catch(Exception ex)
{
MessageBox.Show("Erro: "+ ex);
return;
}
}
}
}
|
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityAtoms.Editor;
using UnityAtoms.BaseAtoms;
namespace UnityAtoms.FSM.Editor
{
/// <summary>
/// Custom property drawer for type `FiniteStateMachine`.
/// </summary>
[CustomEditor(typeof(FiniteStateMachine))]
public sealed class FiniteStateMachineEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(serializedObject.FindProperty("_developerDescription"));
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serializedObject.FindProperty("_id"));
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("_initialValue"), true);
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("_value"), true);
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("_oldValue"), true);
EditorGUI.EndDisabledGroup();
const int raiseButtonWidth = 52;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("_changed"));
var changed = serializedObject.FindProperty("_changed").objectReferenceValue;
if (changed != null && changed is AtomEventBase evt && target is AtomBaseVariable atomTarget)
{
GUILayout.Space(2);
if (GUILayout.Button("Raise", GUILayout.Width(raiseButtonWidth), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
{
evt.GetType().GetMethod("RaiseEditor", BindingFlags.Public | BindingFlags.Instance)?.Invoke(evt, new[] { atomTarget.BaseValue });
}
}
}
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("_changedWithHistory"));
var changedWithHistory = serializedObject.FindProperty("_changedWithHistory").objectReferenceValue;
if (changedWithHistory != null && changedWithHistory is AtomEventBase evt && target is AtomBaseVariable atomTarget)
{
GUILayout.Space(2);
if (GUILayout.Button("Raise", GUILayout.Width(raiseButtonWidth), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
{
var oldValueProp = serializedObject.FindProperty("_oldValue");
object oldValue = oldValueProp.GetPropertyValue();
evt.GetType().GetMethod("RaiseEditor", BindingFlags.Public | BindingFlags.Instance)?.Invoke(evt, new[] { (object)(new StringPair() { Item1 = (string)atomTarget.BaseValue, Item2 = (string)oldValue }) });
}
}
}
var transitionStartedProp = serializedObject.FindProperty("_transitionStarted");
EditorGUILayout.PropertyField(transitionStartedProp, new GUIContent() { tooltip = "Event raised when a transition is started.", text = transitionStartedProp.displayName }, true);
var completeCurrentTransitionProp = serializedObject.FindProperty("_completeCurrentTransition");
EditorGUILayout.PropertyField(completeCurrentTransitionProp, new GUIContent() { tooltip = "A Bool Event that is passed along in the Transition Started event (an event that is required when using this event). The transition needs also to be marked with 'Raise Event To Complete Transition in order to use this event.'", text = completeCurrentTransitionProp.displayName }, true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("_states"), true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("_transitions"), true);
serializedObject.ApplyModifiedProperties();
}
}
}
|
using UnityEngine;
using System.Collections;
public class FisheyeStop : MonoBehaviour {
public AllScripts allScripts;
public int drugOrder;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = allScripts.mainCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
if (hit.collider.gameObject == gameObject) {
if(hit.distance < 2) {
//play relived sound
allScripts.fishEyeScript.stopping = true;
allScripts.gameManager.DrugTaken(drugOrder, gameObject);
Destroy(gameObject);
}
}
}
}
}
}
|
using PhotonInMaze.Common.Controller;
using PhotonInMaze.Common.Flow;
using PhotonInMaze.Common.Model;
using PhotonInMaze.Provider;
using UnityEngine;
namespace PhotonInMaze.GameCamera {
internal partial class CameraController : FlowObserverBehaviour<IPhotonMovementController, IPhotonState>, ICameraController {
private CameraViewCalculator viewCalculator;
private CameraViewChanger viewChanger;
private CameraInputControl inputControl;
private CameraConfiguration configuration;
private CameraEventController eventController;
private new Camera camera;
private Vector3 currentPhotonPosition, previousPhotonPosition;
public override void OnNext(IPhotonState state) {
if(state.RealPosition.Equals(currentPhotonPosition)) {
return;
}
previousPhotonPosition = currentPhotonPosition;
currentPhotonPosition = state.RealPosition;
if(configuration.type == GameCameraType.Moved) {
ICameraEvent cameraEvent;
if(configuration.followThePhoton) {
configuration.type = GameCameraType.AbovePhoton;
cameraEvent = viewChanger.BackAbovePosition(() => currentPhotonPosition);
} else {
configuration.type = GameCameraType.Area;
cameraEvent = viewChanger.BackToInitialPosition();
}
eventController.AddEventToQueue(cameraEvent);
inputControl.Reset();
} else if(configuration.type == GameCameraType.BetweenPhotonAndArrow || configuration.type == GameCameraType.Zoomed) {
configuration.type = GameCameraType.AbovePhoton;
ICameraEvent cameraEvent = viewChanger.BackAbovePosition(() => currentPhotonPosition);
eventController.AddEventToQueue(cameraEvent);
} else if(configuration.followThePhoton || !viewCalculator.IsPhotonVisibleOnCamera(currentPhotonPosition)) {
Vector3 targetCamPosition = viewCalculator.CalculatePositionBasedOnPhotonPositions(currentPhotonPosition, previousPhotonPosition);
camera.transform.position = targetCamPosition;
}
}
public override void OnInit() {
camera = GetComponent<Camera>();
currentPhotonPosition = previousPhotonPosition =
ObjectsProvider.Instance.GetPhotonConfiguration().InitialPosition;
eventController = camera.GetComponent<CameraEventController>();
configuration = camera.GetComponent<CameraConfiguration>();
viewCalculator = new CameraViewCalculator(camera);
viewChanger = new CameraViewChanger(camera, viewCalculator);
inputControl = new CameraInputControl(camera, viewChanger);
}
public override IInvoke OnLoop() {
return GameFlowManager.Instance.Flow
.WhenIsAnyAnd(() => eventController.IsQueueEmpty())
.ThenDo(inputControl.Check)
.Build();
}
public override int GetInitOrder() {
return (int) InitOrder.CameraController;
}
public void ResizeCameraTo(Frame frame) {
if(frame.IsFrameBoundsVisibleOnCamera(camera)) {
return;
}
Vector3 targetCamPosition = viewCalculator.CalculateResizePosition(frame);
float ortSize = frame.GetXDistance() * camera.aspect > frame.GetYDistance() ?
frame.GetXDistance() / 2 :
(frame.GetYDistance() / 2) / camera.aspect;
ICameraEvent cameraEvent = viewChanger.GetResizeEvent(() => targetCamPosition, () => currentPhotonPosition, ortSize);
eventController.AddEventToQueue(cameraEvent);
}
}
} |
namespace debatesWebApi.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class MigracionBaseDeDatos : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Int(nullable: false, identity: true),
IdDebate = c.Int(nullable: false),
Descripcion = c.String(),
AutorId = c.Int(nullable: false),
FechaPublicacion = c.DateTime(precision: 7, storeType: "datetime2"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Debates",
c => new
{
Id = c.Int(nullable: false, identity: true),
Titulo = c.String(),
Tema = c.String(),
Autor = c.Int(nullable: false),
Estado = c.Boolean(nullable: false),
FechaPublicacion = c.DateTime(precision: 7, storeType: "datetime2"),
FechaVencimiento = c.DateTime(precision: 7, storeType: "datetime2"),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.User", t => t.Autor, cascadeDelete: true)
.Index(t => t.Autor);
CreateTable(
"dbo.MenuRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
Rol = c.String(),
CreateDebate = c.Boolean(nullable: false),
Report = c.Boolean(nullable: false),
Scroll = c.Boolean(nullable: false),
UserInfo = c.Boolean(nullable: false),
RegisterUser = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Rating",
c => new
{
Id = c.Int(nullable: false, identity: true),
AutorId = c.Int(nullable: false),
DebateId = c.Int(nullable: false),
CommentId = c.Int(nullable: false),
Rate = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
AddColumn("dbo.User", "Email", c => c.String());
AddColumn("dbo.User", "Password", c => c.String());
AlterColumn("dbo.User", "Rol", c => c.String());
DropColumn("dbo.User", "TagName");
}
public override void Down()
{
AddColumn("dbo.User", "TagName", c => c.String());
DropForeignKey("dbo.Debates", "Autor", "dbo.User");
DropIndex("dbo.Debates", new[] { "Autor" });
AlterColumn("dbo.User", "Rol", c => c.Int(nullable: false));
DropColumn("dbo.User", "Password");
DropColumn("dbo.User", "Email");
DropTable("dbo.Rating");
DropTable("dbo.MenuRoles");
DropTable("dbo.Debates");
DropTable("dbo.Comments");
}
}
}
|
using Anywhere2Go.DataAccess.Entity;
using System;
using System.Collections.Generic;
namespace Anywhere2Go.DataAccess.Object
{
public class ExportTask
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public string InsId { get; set; }
public string TaskTypeId { get; set; }
public string TaskProcessId { get; set; }
public string DepId { get; set; }
public string InsDeptId { get; set; }
public string FindSchedultDate { get; set; }
}
} |
namespace Backpressure
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
internal class BackpressureDropOperator<T> : ISubscriber<T>, IBackpressureOperator
{
private readonly IObserver<T> _observer;
private readonly Action<T> _onDrop;
private int _count;
public BackpressureDropOperator(
IObserver<T> subscriber,
int initialCount,
Action<T> onDrop)
{
this._observer = subscriber;
this._count = initialCount;
this._onDrop = onDrop;
}
public void OnCompleted()
{
this._observer.OnCompleted();
}
public void OnError(Exception error)
{
this._observer.OnError(error);
}
public void OnNext(T value)
{
if (this._count > 0 || this._count == -1)
{
this._observer.OnNext(value);
if (this._count > 0)
{
--this._count;
}
}
else
{
this._onDrop(value);
}
}
public void OnSubscribe(ISubscription subscription)
{
var subscriber = this._observer as ISubscriber<T>;
if (subscriber != null)
{
subscriber.OnSubscribe(subscription);
}
}
public void Request(int count)
{
this._count = count;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
public class BPMInstTasks
{
public int TaskID { get; set; }
/// <summary>
///
/// </summary>
public string ProcessName { get; set; }
/// <summary>
///
/// </summary>
public string OwnerAccount { get; set; }
/// <summary>
///
/// </summary>
public string AgentAccount { get; set; }
/// <summary>
///
/// </summary>
public DateTime CreateAt { get; set; }
/// <summary>
///
/// </summary>
public string Description { get; set; }
/// <summary>
///
/// </summary>
public DateTime FinishAt { get; set; }
/// <summary>
///
/// </summary>
public string State { get; set; }
/// <summary>
///
/// </summary>
public string SerialNum { get; set; }
/// <summary>
///
/// </summary>
public string OptUser { get; set; }
/// <summary>
///
/// </summary>
public DateTime OptAt { get; set; }
/// <summary>
///
/// </summary>
public string OptMemo { get; set; }
/// <summary>
///
/// </summary>
public int FormDataSetID { get; set; }
/// <summary>
///
/// </summary>
public int ExtYear { get; set; }
/// <summary>
///
/// </summary>
public string ExtInitiator { get; set; }
/// <summary>
///
/// </summary>
public bool ExtDeleted { get; set; }
/// <summary>
///
/// </summary>
public int OwnerPositionID { get; set; }
/// <summary>
///
/// </summary>
public int ParentTaskID { get; set; }
/// <summary>
///
/// </summary>
public int ParentStepID { get; set; }
/// <summary>
///
/// </summary>
public string ParentStepName { get; set; }
/// <summary>
///
/// </summary>
public string ProcessVersion { get; set; }
/// <summary>
///
/// </summary>
public string ParentServerIdentity { get; set; }
/// <summary>
///
/// </summary>
public bool ReturnToParent { get; set; }
/// <summary>
///
/// </summary>
public string UrlParams { get; set; }
/// <summary>
///
/// </summary>
public string Context { get; set; }
}
}
|
using SpaceOpDeath.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpaceOpDeath.Members
{
class Commander : Member
{
public Commander()
:base()
{
_type = MemberType.Commander;
}
public override void Action()
{
base.Action();
int pointsToRepair = int.Parse( Alea.Config.Get( "CommanderActionRepair" )["Value"].Value );
module.Repair( pointsToRepair );
}
public override string ToStringAction()
{
string res = "Peut fournir 10 points de réparation supplémentaire";
return res;
}
}
}
|
using Business.Abstract;
using Business.Constants;
using Core.Utilities;
using Core.Utilities.Results;
using DataAccess.Abstract;
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Concrete
{
public class UserManager : IUserServices
{
IUserDal _userDal;
public UserManager(IUserDal userDal)
{
_userDal = userDal;
}
public IResult Add(User user)
{
if (user.FirstName.Length<2)
{
return new ErrorDataResult<User>(Messages.UserNameInvalid);
}
_userDal.Add(user);
return new SuccessDataResult<User>(Messages.UserAdded);
}
public IResult Delete(User user)
{
_userDal.Delete(user);
return new SuccessDataResult<User>(Messages.CarsListed);
}
public IResult Find(User user)
{
if (user.FirstName==user.FirstName)
{
return new ErrorDataResult<User>(Messages.UserFound);
}
return new SuccessDataResult<User>(Messages.UserNotFound);
}
public IDataResult<List<User>> GetById(int userId)
{
return new SuccessDataResult<List<User>>(_userDal.GetAll(u => u.UserId == userId));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utility;
/**************************************************************************************************
MAIN SELECTOR CTRL
**************************************************************************************************/
namespace FileBrowser
{
public partial class MainSelector : UserControl, IFileBrowserCtrl
{
#region Control Basics
// constructor
public MainSelector()
{
InitializeComponent();
}
// implement IFileBrowserCtrl
public void Initialize()
{
(this.Parent as BaseForm).Text = "FileBrowser Main";
(this.Parent as BaseForm).SetMode_Dialog();
f_close.Click += new EventHandler((this.Parent as BaseForm).ctrlCloseClick);
}
public bool StopCtrlThread()
{
return false;
}
#endregion
#region User Controls
// Set Files' Property
private void f_setSortProp_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
BaseForm nf = new BaseForm(new SetFilesProperty());
nf.Show();
}
// Replace File Names
private void f_replaceFileNames_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
BaseForm nf = new BaseForm(new ReplaceFileNames());
nf.Show();
}
// File Standardizor
private void f_standardize_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
BaseForm nf = new BaseForm(new FileStandardizorCtrl());
nf.Show();
}
// Create Sorted File Names
private void sortedFileNames_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
BaseForm bf = new BaseForm(new SortFileNames());
bf.Show();
}
// Create Entry Sort Names
private void f_createEntrySeries_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
BaseForm nf = new BaseForm(new EntrySortCtrl());
nf.Show();
}
// Folder Browser button
private void f_folderBrowser_Click(object sender, EventArgs e)
{
// Program.MainForm.Hide();
FolderBrowser fs = new FolderBrowser();
fs.Show();
}
#endregion
#region Common Form Config
public static string GetLastFolder()
{
if (System.IO.Directory.Exists(Properties.Settings.Default.LastInputFolder) == true)
return Properties.Settings.Default.LastInputFolder;
else if (System.IO.Directory.Exists(
Utility.StringFormat.GoUpDirectory(Properties.Settings.Default.LastInputFolder)) == true)
return Utility.StringFormat.GoUpDirectory(Properties.Settings.Default.LastInputFolder);
else
return Properties.Settings.Default.DocFolder;
}
public static void SetLastFolder(string p_lastFolder)
{
Properties.Settings.Default.LastInputFolder = p_lastFolder;
Properties.Settings.Default.Save();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SeleniumTests
{
class Program
{
//static void Main(string[] args)
//{
//AllSalonSiteBusinessCreation obj1 = new AllSalonSiteBusinessCreation();
//obj1.SetupTest();
//obj1.TheAllSalonSiteBusinessLoginTest();
//for (int i = 1; i <= 10; i++)
//{
// obj1.TheAllSalonSiteBusinessCreationTest(i);
//}
//obj1.BusinessProfileCreationCheck(1);
//obj1.BusinessProfileNextPage(1);
//Console.ReadLine();
//FDCalculator obj1 = new FDCalculator();
//obj1.SetupTest();
//obj1.TheFDCalculatorTest();
//}
}
}
|
using Alabo.Domains.Repositories;
using Alabo.Industry.Offline.Order.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Industry.Offline.Order.Domain.Repositories
{
public interface IMerchantCartRepository : IRepository<MerchantCart, ObjectId>
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TaiKhoan : MonoBehaviour
{
private int idTK;
private string tenNV, tenTK, pass;
public int IdTK { get => idTK; set => idTK = value; }
public string TenNV { get => tenNV; set => tenNV = value; }
public string TenTK { get => tenTK; set => tenTK = value; }
public string Pass { get => pass; set => pass = value; }
public void LayThongTinTaiKhoan(int id)
{
this.IdTK = PlayerPrefs.GetInt("idTK" + id.ToString());
this.TenNV = PlayerPrefs.GetString("ten" + id.ToString());
this.TenTK = PlayerPrefs.GetString("tenDN" + id.ToString());
this.Pass = PlayerPrefs.GetString("pass" + id.ToString());
}
}
|
using System;
using System.Collections.Generic;
namespace PizzaBox.Data.Entities
{
public partial class Location
{
public Location()
{
InventoryItem = new HashSet<InventoryItem>();
Order = new HashSet<Order>();
}
public int LocId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public virtual ICollection<InventoryItem> InventoryItem { get; set; }
public virtual ICollection<Order> Order { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FastReport;
using KartLib.Reports;
using KartObjects;
using System.IO;
using KartLib;
using KartObjects.Entities.Documents;
namespace KartSystem
{
public class RevaluationReportViewer:BaseReportViewer
{
public RevaluationReportViewer(Form parentForm, string ReportPath)
: base(parentForm, ReportPath)
{
}
public override void ShowReport(SimpleDbEntity d)
{
using (Report report = new Report())
{
RevaluationReport doc = new RevaluationReport(d as Document);
if (doc == null) return;
if (!File.Exists(ReportPath + @"\RevaluationAct.frx"))
{
MessageBox.Show(@"Не найдена форма печати RevaluationAct.frx.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
report.Load(ReportPath + @"\RevaluationAct.frx");
if (report == null || doc == null) return;
List<RevaluationGoodSpecRecord> docs = doc.Records ?? Loader.DbLoad<RevaluationGoodSpecRecord>("", 0, doc.Id, 0, 0, 0, 0, 0) ?? new List<RevaluationGoodSpecRecord>();
if (doc == null) return;
DataSource.DataSource = docs;
report.RegisterData(DataSource, "invoiceGoodSpecRecordBindingSource");
report.GetDataSource("invoiceGoodSpecRecordBindingSource").Enabled = true;
TextObject docDate = (TextObject)report.FindObject("Date");
if (docDate != null && doc.DateDoc != null)
docDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject Number = (TextObject)report.FindObject("Number");
if (Number != null && doc.DateDoc != null)
Number.Text = doc.Number.ToString();
TextObject docBottomPrintDate = (TextObject)report.FindObject("BottomPrintDate");
if (docBottomPrintDate != null && doc.DateDoc != null)
docBottomPrintDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject Base = (TextObject)report.FindObject("Base");
if (Base != null && (d as Document).Comment != null)
Base.Text = (d as Document).Comment;
if (report.Prepare())
report.ShowPrepared(true, ParentForm);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TellMeMoreBlazor.Constants;
using TellMeMoreBlazor.Exceptions;
using TellMeMoreBlazor.Interfaces;
using TellMeMoreBlazor.Models.urlscanio;
using TellMeMoreBlazor.Shared.ConfigurationLogger;
using TellMeMoreBlazor.Shared.Interfaces;
namespace TellMeMoreBlazor.Services
{
public class UrlScanIoService : IUrlScanIoService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ITellMeMoreLogger _config;
const string BaseUrlScan = "https://urlscan.io/api/v1/scan/";
const string BaseUrlUUID = "https://urlscan.io/api/v1/result/";
public UrlScanIoService(IHttpClientFactory httpClientFactory, ITellMeMoreLogger configuration)
{
_httpClientFactory = httpClientFactory;
_config = configuration;
}
/// <summary>
/// Submit scan job to urlscan.io
/// </summary>
/// <param name="hostName"></param>
/// <returns></returns>
public async Task<urlScanIoNewScanResponse> PostAsync(string hostName)
{
try
{
var client = _httpClientFactory.CreateClient(HttpClientNames.urlScanIoHttpClient);
string apiKey = await _config.ReadConfiguration(TellMeMoreLogger.UrlScanApiKey);
client.DefaultRequestHeaders.Add("API-Key", apiKey);
var reqObject = new urlScanIoRequestObject() { url = hostName };
var res = await client.PostAsync(BaseUrlScan,
new StringContent(
JsonConvert.SerializeObject(reqObject), Encoding.UTF8, "application/json")
);
if (res.IsSuccessStatusCode)
{
var json = JsonConvert.DeserializeObject<urlScanIoNewScanResponse>(await res?.Content?.ReadAsStringAsync());
return json;
}
else if (res.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
throw new urlScanIoException("We're quite busy at the moment, please try again in a minute or so.");
}
else
{
throw new HttpRequestException($"Failed request to {BaseUrlScan}. Failed to start scan for URL: {hostName}");
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Get current scan by UUID
/// </summary>
/// <param name="uuid">UUID of previously preformed scan</param>
/// <returns></returns>
public async Task<urlScanIo> GetStatusAsync(string uuid)
{
try
{
var client = _httpClientFactory.CreateClient(HttpClientNames.urlScanIoHttpClient);
var res = await client.GetAsync(BaseUrlUUID + uuid);
if (res.IsSuccessStatusCode)
{
var json = JsonConvert.DeserializeObject<urlScanIo>(await res?.Content?.ReadAsStringAsync());
return json;
}
else
{
throw new HttpRequestException($"Failed request to {BaseUrlUUID}. Failed to check job ID: {uuid ?? "UUID was blank."}");
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BethanyShop.Models;
namespace BethanyShop.Controllers
{
public class HomeController : Controller
{
private readonly IPieRepository _pieRepository;
public HomeController(IPieRepository pieRepository)
{
_pieRepository =pieRepository;
}
// GET: /Home/
public IActionResult Index()
{
var pies=_pieRepository.GetPies();
return View(pies);
}
// GET: /Home/Details/{id}
public IActionResult Details(int id)
{
var pie = _pieRepository.GetPieById(id);
if (pie == null)
return NotFound();
else
return View(pie);
}
}
} |
using UnityEngine;
using System.Collections;
public class Companion : MonoBehaviour {
public Transform player;
public Transform lookAtPlayer;
public Transform wayPoint;
public GameObject rightWayPoint;
public GameObject leftWayPoint;
public float speed = 10;
public Rigidbody rb;
public Timer timer;
public bool rightStep = false;
public bool leftStep = false;
// Use this for initialization
void Start () {
player = GameObject.FindWithTag("Player").GetComponent<Transform>();
rb = GetComponent<Rigidbody>();
timer = new Timer();
//timer.GetComponent<Timer>()
}
// Update is called once per frame
void Update () {
Quaternion rotation = Quaternion.Euler(0, lookAtPlayer.rotation.y , 0);
//Quaternion rotation = Quaternion.identity;
//rotation.eulerAngles = new Vector3(0, 0, lookAtPlayer.rotation.y);
Vector3 movement = transform.forward * speed * Time.deltaTime;
if(/*wayPoint != null*/ rightStep ){
if(timer.CountDown(0.2F)){
rightStep = false;
timer.ResetTimer();
}
//transform.position = Vector3.Lerp(transform.position, wayPoint.position, 0.05F);
//transform.position = Vector3.Lerp(transform.position, transform.position, 0.05F);
gameObject.GetComponent<Rigidbody>().AddForce(transform.right * 20);
//transform.LookAt(wayPoint);
//transform.rotation = Quaternion.RotateTowards(transform.rotation, lookAtPlayer.rotation, 100*Time.deltaTime);
}else if(/*wayPoint != null*/ leftStep ){
if(timer.CountDown(0.2F)){
leftStep = false;
timer.ResetTimer();
}
gameObject.GetComponent<Rigidbody>().AddForce(transform.right * -20);
}else if(Vector3.Distance(transform.position, player.position) > 4 && wayPoint == null){
//rb.MovePosition(transform.position + movement);
transform.position = Vector3.Lerp(transform.position, transform.position + movement, 0.5F);
//transform.Rotate(Vector3.up, Time.deltaTime * 200);
//transform.rotation = Quaternion.Lerp(transform.rotation, rotation, 0.5F);
}
transform.rotation = Quaternion.RotateTowards(transform.rotation, lookAtPlayer.rotation, 100*Time.deltaTime);
if(wayPoint!=null && Vector3.Distance(transform.position, wayPoint.position)<= 0.1){
//Destroy(wayPoint.gameObject);
wayPoint = null;
}
//transform.LookAt(player);
}
void OnTriggerEnter(Collider collider){
Companion otherAI = collider.gameObject.GetComponentInParent<Companion>();
if(collider.gameObject.tag == "Enemy" /*&& wayPoint == null*/){
float rightDis = Vector3.Distance(transform.position, otherAI.rightWayPoint.transform.position);
float leftDis = Vector3.Distance(transform.position, otherAI.leftWayPoint.transform.position);
if(rightDis < leftDis){
rightStep = true;
//wayPoint = otherAI.rightWayPoint.transform;
//wayPoint = Instantiate(otherAI.rightWayPoint.transform, otherAI.rightWayPoint.transform.position, transform.rotation) as Transform;
}else{
leftStep = true;
//wayPoint = otherAI.leftWayPoint.transform;
//wayPoint = Instantiate(otherAI.leftWayPoint.transform, otherAI.leftWayPoint.transform.position, transform.rotation) as Transform;
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EPI.Strings;
namespace EPI.UnitTests.Strings
{
[TestClass]
public class WordsReversalUnitTest
{
[TestMethod]
public void ReverseWords_Cases()
{
Assert.IsNull(WordsReversal.ReverseWords(null));
Assert.AreEqual("", WordsReversal.ReverseWords(""));
Assert.AreEqual(" a ", WordsReversal.ReverseWords(" a "));
Assert.AreEqual("Bob likes Alice", WordsReversal.ReverseWords("Alice likes Bob"));
Assert.AreEqual(" World Hello ", WordsReversal.ReverseWords(" Hello World "));
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Ball : MonoBehaviour {
Rigidbody rb;
Transform tr;
int score;
int highscore;
public Text counttext;
public Text highscorecount;
public AudioSource a;
void Start ()
{
rb = GetComponent<Rigidbody> ();
tr = GetComponent<Transform> ();
highscore = 0;
NeueRunde ();
}
public void NeueRunde ()
{
score = 0;
Scores (1);
Scores (2);
tr.position = new Vector3 (0, 5, 0);
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.AddForce (Random.Range(-50f,50f),0,Random.Range(-50f,50f));
}
void Update ()
{
}
void OnCollisionEnter()
{
a.Play ();
score++;
Scores (1);
if (score>highscore)
{
highscore=score;
Scores (2);
Debug.Log (highscore);
}
}
void Scores(int a)
{
switch (a)
{
case 1:
counttext.text = "Points: " + score;
break;
case 2:
highscorecount.text = "Highscore: " + highscore;
break;
default:
break;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SA
{
public class NetworkPrint : Photon.MonoBehaviour
{
public int photonId;
public bool isLocal;
public string[] GetStartingCardIds()
{
return cardIds;
}
string[] cardIds;
void onPhotonInstantiate(PhotonMessageInfo info)
{
photonId = photonView.ownerId;
isLocal = photonView.isMine;
object[] data = photonView.instantiationData;
cardIds = (string[])data[0];
MultiplayerManager.singleton.AddPlayer(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LoadAndSave
{
class MainMenu
{
public Datahandler dataHandler;
public MainMenu()
{
}
public MainMenu(Datahandler dataHandler)
{
this.dataHandler = dataHandler;
}
public void InitializeMainMenu()
{
bool showMenu = true;
while (showMenu)
{
showMenu = ShowMainMenu();
}
}
private bool ShowMainMenu()
{
Console.Clear();
Console.WriteLine("1) Syötä uusi henkilö");
Console.WriteLine("2) Tarkastele listaa");
Console.WriteLine("3) Tallenna henkilöt");
Console.WriteLine("4) Exit");
Console.Write("\nValitse vaihtoehto: ");
switch (Console.ReadLine())
{
case "1":
dataHandler.AddPersonToList();
return true;
case "2":
dataHandler.PersonList();
break;
case "3":
break;
case "4":
return false;
default:
return true;
}
Console.WriteLine("\nEnter jatkaaksesi");
Console.ReadKey();
return true;
}
}
}
|
using System.Linq;
using Efa.Domain.Entities;
using Efa.Domain.Interfaces.Repository;
using Efa.Domain.Interfaces.Specification;
namespace Efa.Domain.Specification.Professores
{
public class CpfNaoCadastrado : ISpecification<Professor>
{
private readonly IProfessorRepository _professorRepository;
public CpfNaoCadastrado(IProfessorRepository professorRepository)
{
_professorRepository = professorRepository;
}
public bool IsSatisfiedBy(Professor professor)
{
var professorBase = _professorRepository.GetById(professor.ProfessorId);
if (!string.IsNullOrEmpty(professor.CPF))
{
// Se forem iguais estou editando sem alterar o cpf do mesmo
if (professorBase != null && professorBase.CPF == professor.CPF)
return true;
return !_professorRepository.Find(p => p.CPF == professor.CPF).Any();
}
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestES.Map
{
/// <summary>
/// http://www.oschina.net/code/snippet_260395_39205
/// WGS-84:是国际标准,GPS坐标(Google Earth使用、或者GPS模块)
///GCJ-02:中国坐标偏移标准,Google Map、高德、腾讯使用
///BD-09:百度坐标偏移标准,Baidu Map使用
///WGS-84 to GCJ-02
///GPS.gcj_encrypt();
///GCJ-02 to WGS-84 粗略
///GPS.gcj_decrypt();
///GCJ-02 to WGS-84 精确(二分极限法)
///var threshold = 0.000000001; 目前设置的是精确到小数点后9位,这个值越小,越精确,但是javascript中,浮点运算本身就不太精确,九位在GPS里也偏差不大了
///GSP.gcj_decrypt_exact();
///GCJ-02 to BD-09
///GPS.bd_encrypt();
///BD-09 to GCJ-02
///GPS.bd_decrypt();
///求距离
///GPS.distance();
/*示例:
document.write("GPS: 39.933676862706776,116.35608315379092<br />");
var arr2 = GPS.gcj_encrypt(39.933676862706776, 116.35608315379092);
document.write("中国:" + arr2['lat']+","+arr2['lon']+'<br />');
var arr3 = GPS.gcj_decrypt_exact(arr2['lat'], arr2['lon']);
document.write('逆算:' + arr3['lat']+","+arr3['lon']+' 需要和第一行相似(目前是小数点后9位相等)');
本算法 gcj算法、bd算法都非常精确,已经测试通过。
(BD转换的结果和百度提供的接口精确到小数点后4位)
请放心使用*/
/// </summary>
public class GPS
{
static double PI = 3.14159265358979324;
static double X_PI = 3.14159265358979324 * 3000.0 / 180.0;
private static double[] Delta(double lat, double lon)
{
// Krasovsky 1940
//
// a = 6378245.0, 1/f = 298.3
// b = a * (1 - f)
// ee = (a^2 - b^2) / a^2;
var a = 6378245.0; // a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
var ee = 0.00669342162296594323; // ee: 椭球的偏心率。
var dLat = TransformLat(lon - 105.0, lat - 35.0);
var dLon = TransformLon(lon - 105.0, lat - 35.0);
var radLat = lat / 180.0 * PI;
var magic = Math.Sin(radLat);
magic = 1 - ee * magic * magic;
var sqrtMagic = Math.Sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.Cos(radLat) * PI);
return new[] { dLat, dLon };
}
//WGS-84 to GCJ-02
public static double[] Gcj_encrypt(double wgsLat, double wgsLon)
{
if (OutOfChina(wgsLat, wgsLon))
return new[] { wgsLat, wgsLon };
var d = Delta(wgsLat, wgsLon);
return new[] { wgsLat + d[0], wgsLon + d[1] };
}
//GCJ-02 to WGS-84
public static double[] Gcj_decrypt(double gcjLat, double gcjLon)
{
if (OutOfChina(gcjLat, gcjLon))
return new[] { gcjLat, gcjLon };
var d = Delta(gcjLat, gcjLon);
return new[] { gcjLat - d[0], gcjLon - d[1] };
}
//GCJ-02 to WGS-84 exactly
public static double[] Gcj_decrypt_exact(double gcjLat, double gcjLon)
{
var initDelta = 0.01;
var threshold = 0.000000001;
var dLat = initDelta;
var dLon = initDelta;
var mLat = gcjLat - dLat;
var mLon = gcjLon - dLon;
var pLat = gcjLat + dLat;
var pLon = gcjLon + dLon;
double wgsLat;
double wgsLon;
var i = 0;
while (true)
{
wgsLat = (mLat + pLat) / 2;
wgsLon = (mLon + pLon) / 2;
var tmp = Gcj_encrypt(wgsLat, wgsLon);
dLat = tmp[0] - gcjLat;
dLon = tmp[1] - gcjLon;
if ((Math.Abs(dLat) < threshold) && (Math.Abs(dLon) < threshold))
break;
if (dLat > 0) pLat = wgsLat; else mLat = wgsLat;
if (dLon > 0) pLon = wgsLon; else mLon = wgsLon;
if (++i > 10000) break;
}
return new[] { wgsLat, wgsLon };
}
//GCJ-02 to BD-09
public static double[] Bd_encrypt(double gcjLat, double gcjLon)
{
var x = gcjLon;
var y = gcjLat;
var z = Math.Sqrt(x * x + y * y) + 0.00002 * Math.Sin(y * X_PI);
var theta = Math.Atan2(y, x) + 0.000003 * Math.Cos(x * X_PI);
var bdLon = z * Math.Cos(theta) + 0.0065;
var bdLat = z * Math.Sin(theta) + 0.006;
return new[] { bdLat, bdLon };
}
//BD-09 to GCJ-02
public static double[] Bd_decrypt(double bdLat, double bdLon)
{
var x = bdLon - 0.0065;
var y = bdLat - 0.006;
var z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * X_PI);
var theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * X_PI);
var gcjLon = z * Math.Cos(theta);
var gcjLat = z * Math.Sin(theta);
return new[] { gcjLat, gcjLon };
}
//WGS-84 to Web mercator
//mercatorLat -> y mercatorLon -> x
public static double[] Mercator_encrypt(double wgsLat, double wgsLon)
{
var x = wgsLon * 20037508.34 / 180.0;
var y = Math.Log(Math.Tan((90.0 + wgsLat) * PI / 360.0)) / (PI / 180.0);
y = y * 20037508.34 / 180.0;
return new[] { y, x };
}
// Web mercator to WGS-84
// mercatorLat -> y mercatorLon -> x
public static double[] Mercator_decrypt(double mercatorLat, double mercatorLon)
{
var x = mercatorLon / 20037508.34 * 180.0;
var y = mercatorLat / 20037508.34 * 180.0;
y = 180 / PI * (2 * Math.Atan(Math.Exp(y * PI / 180.0)) - PI / 2);
return new[] { y, x };
}
// two point's distance
public static double Distance(double latA, double lonA, double latB, double lonB)
{
var earthR = 6371000.0;
var x = Math.Cos(latA * PI / 180.0) * Math.Cos(latB * PI / 180.0) * Math.Cos((lonA - lonB) * PI / 180);
var y = Math.Sin(latA * PI / 180.0) * Math.Sin(latB * PI / 180.0);
var s = x + y;
if (s > 1) s = 1;
if (s < -1) s = -1;
var alpha = Math.Acos(s);
var distance = alpha * earthR;
return distance;
}
private static bool OutOfChina(double lat, double lon)
{
if (lon < 72.004 || lon > 137.8347)
return true;
if (lat < 0.8293 || lat > 55.8271)
return true;
return false;
}
private static double TransformLat(double x, double y)
{
var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.Sqrt(Math.Abs(x));
ret += (20.0 * Math.Sin(6.0 * x * PI) + 20.0 * Math.Sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(y * PI) + 40.0 * Math.Sin(y / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.Sin(y / 12.0 * PI) + 320 * Math.Sin(y * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double TransformLon(double x, double y)
{
var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
ret += (20.0 * Math.Sin(6.0 * x * PI) + 20.0 * Math.Sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(x * PI) + 40.0 * Math.Sin(x / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.Sin(x / 12.0 * PI) + 300.0 * Math.Sin(x / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
}
}
|
using System;
namespace par_ou_impar
{
class Program
{
static void Main(string[] args)
{
int numero, escolha_Par_Impar, num_Computador, soma;
Console.WriteLine("Digite 0 = Par ou 1 = Impar");
escolha_Par_Impar = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Digite um numero");
numero = Convert.ToInt32(Console.ReadLine());
Random rnd = new Random();
num_Computador = rnd.Next(0, 10);
if((numero + num_Computador) % 2 == escolha_Par_Impar)
{
Console.WriteLine("Jogo roubado, numero anterior = " + num_Computador);
//num_Computador++;
num_Computador += 1;
}
Console.WriteLine("Numero do computador" + num_Computador);
soma = numero + num_Computador;
if ( soma % 2 == escolha_Par_Impar)
{
Console.WriteLine("Voce Ganhou!");
}
else
{
Console.WriteLine("O computador Ganhou!");
}
}
}
}
|
using EmberKernel.Services.EventBus;
using EmberMemory.Components.Collector;
using EmberMemory.Readers;
using System;
namespace EmberMemoryReader.Abstract.Data
{
public class GameStatus : IComparableCollector<GameStatusInfo>
{
private static readonly string GameModePattern = "\x80\xb8\x0\x0\x0\x0\x0\x75\x19\xa1\x0\x0\x0\x0\x83\xf8\x0b\x74\x0b";
private static readonly string GameModePatternMask = "xx????xxxx????xxxxx";
public int ReadInterval { get; set; } = 500;
public int RetryLimit { get; set; } = int.MaxValue;
private IntPtr GameModeAddressPtr;
private IntPtr GameModeAddress;
private DirectMemoryReader Reader { get; set; }
public GameStatus(DirectMemoryReader reader)
{
this.Reader = reader;
}
public bool TryInitialize()
{
try
{
Reader.Reload();
if (!Reader.TryFindPattern(GameModePattern.ToBytes(), GameModePatternMask, 10, out GameModeAddressPtr))
return false;
if (!Reader.TryReadIntPtr(GameModeAddressPtr, out GameModeAddress))
return false;
if (GameModeAddress == IntPtr.Zero)
return false;
return true;
}
finally
{
Reader.ResetRegion();
}
}
public bool TryRead(out Event result)
{
if (!Reader.TryReadInt(GameModeAddress, out var value))
{
result = new GameStatusInfo() { HasValue = false };
return true;
}
var Status = (OsuInternalStatus)value;
result = new GameStatusInfo() { HasValue = true, Status = Status, StringStatus = Status.ToString() };
return true;
}
}
}
|
using System.Collections.Generic;
using EPI.StacksAndQueues;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.StacksAndQueues
{
[TestClass]
public class ShortestStraightLineUnitTest
{
[TestMethod]
public void ShortestStraightLineSequence()
{
ShortestStraightLine.GetShortestStraightLine(7).ShouldBeEquivalentTo(new List<int> { 1, 2, 3, 4, 7});
ShortestStraightLine.GetShortestStraightLine(1).ShouldBeEquivalentTo(new List<int> { 1 });
ShortestStraightLine.GetShortestStraightLine(10).ShouldBeEquivalentTo(new List<int> { 1, 2, 3, 5, 10 });
ShortestStraightLine.GetShortestStraightLine(15).ShouldBeEquivalentTo(new List<int> { 1, 2, 3, 5, 10, 15 });
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace Needle.Demystify
{
internal static class CodePreview
{
private static readonly Dictionary<string, string[]> cache = new Dictionary<string, string[]>();
public static string GetPreviewText(string filePath, int lineNumber, out int lines)
{
lines = 0;
if (!cache.ContainsKey(filePath))
{
if (!File.Exists(filePath)) return null;
var content = File.ReadAllLines(filePath);
cache.Add(filePath, content);
}
var windowText = GetText(cache[filePath], lineNumber - 1, 8, out lines);
return windowText;
}
private static string TypesPatterns;
private static string GetText(IReadOnlyList<string> lines, int line, int showLinesAboveAndBelow, out int lineCount)
{
if (TypesPatterns == null)
{
var patterns = SyntaxHighlighting.GetCodeSyntaxHighlightingPatterns();
TypesPatterns = string.Join("|", patterns);
if(DemystifySettings.DevelopmentMode)
Debug.Log("Code Preview Patterns: " + TypesPatterns);
}
lineCount = 0;
if (lines == null || lines.Count <= 0) return null;
showLinesAboveAndBelow = Mathf.Max(0, showLinesAboveAndBelow);
var from = Mathf.Max(0, line - showLinesAboveAndBelow);
var to = Mathf.Min(lines.Count - 1, line + showLinesAboveAndBelow);
var str = string.Empty;
var lastLineWasEmpty = false;
for (var index = from; index < to; index++)
{
var l = lines[index];
var empty = string.IsNullOrWhiteSpace(l);
if (lastLineWasEmpty && empty) continue;
lastLineWasEmpty = empty;
// if (index == line) l = $"<color={HighlightTextColor}><b>{l}</b></color>";
// else
{
SyntaxHighlighting.AddSyntaxHighlighting(TypesPatterns, SyntaxHighlighting.CurrentTheme, ref l, false);
if (index == line) l = "<b>" + l + "</b>";
// l = $"<color={NormalTextColor}>{l}</color>";
}
str += l + "\n";
lineCount += 1;
}
return str;
}
internal class Window : EditorWindow
{
// Hacky workaround to remove instances created during previous
[InitializeOnLoadMethod]
private static async void InitStart()
{
await Task.Delay(100);
foreach (var prev in Resources.FindObjectsOfTypeAll<Window>())
{
if (prev)
prev.Close();
}
}
internal static Window Create()
{
var window = CreateInstance<Window>();
window.minSize = Vector2.zero;
window.ShowPopup();
style = EditorStyles.wordWrappedLabel;
style.richText = true;
return window;
}
public string Text;
public Vector2 Mouse;
private static GUIStyle style;
private void OnGUI()
{
if (string.IsNullOrEmpty(Text))
{
position = Rect.zero;
minSize = Vector2.zero;
return;
}
EditorGUI.DrawRect(new Rect(0,0, position.width,position.height), new Color(0,0,0,.2f));
DrawBorders(Color.gray * .8f, 1);
EditorGUILayout.LabelField(Text, style);
}
private void DrawBorders(Color color, float thickness)
{
EditorGUI.DrawRect(new Rect(0, 0, position.width, thickness), color);
EditorGUI.DrawRect(new Rect(0, position.height - thickness, position.width, thickness), color);
EditorGUI.DrawRect(new Rect(0, 0, thickness, position.height), color);
EditorGUI.DrawRect(new Rect(position.width - thickness, 0, thickness, position.height), color);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// Created by Anders Bolin AB2633 datum: 2013-06-02 email: anders@bolin.nu
/// Eget Project i Programmering i .NET: Fortsättningskurs
/// </summary>
namespace InstaControlLibrary
{
[Serializable]
public class Train
{
//Declaring Variables
private int m_wagon;
private InstaControlLibrary.Color m_color;
public Train(int wagon, InstaControlLibrary.Color c)
{
m_wagon = wagon;
m_color = c;
}
public int getNumber()
{
return m_wagon;
}
public InstaControlLibrary.Color getColor()
{
return m_color;
}
}
}
|
namespace SubC.Attachments {
using UnityEngine;
using System.Collections.Generic;
public abstract class ChainAttachStrategy : AttachStrategy {
public enum Categories {
Head,
Links,
Tail
}
AttachCategoryDefinition[] categories;
public override AttachCategoryDefinition[] GetCategories() {
if (categories == null) {
categories = new AttachCategoryDefinition[] {
new AttachCategoryDefinition(GetLabelForHead(), GetLabelForHead(), 0, 1),
new AttachCategoryDefinition(GetLabelForLinks(), GetLabelForLink(), 0, -1),
new AttachCategoryDefinition(GetLabelForTail(), GetLabelForTail(), 0, 1)
};
}
return categories;
}
public virtual string GetLabelForHead() {
return "Head";
}
public virtual string GetLabelForTail() {
return "Tail";
}
public virtual string GetLabelForLinks() {
return "Links";
}
public virtual string GetLabelForLink() {
return "Link";
}
public virtual string GetLabelForPreviousLink() {
return "Previous " + GetLabelForLink();
}
public virtual string GetLabelForNextLink() {
return "Next " + GetLabelForLink();
}
protected enum Providers {
Head, Link, PreviousLink, NextLink, Tail
}
public override string GetLabelForProvider(int provider) {
if (provider == (int) Providers.Link)
return GetLabelForLink();
if (provider == (int) Providers.NextLink)
return GetLabelForNextLink();
if (provider == (int) Providers.PreviousLink)
return GetLabelForPreviousLink();
if (provider == (int) Providers.Head)
return GetLabelForHead();
if (provider == (int) Providers.Tail)
return GetLabelForTail();
throw new System.InvalidOperationException("Unknown provider");
}
public override int[] GetProvidersForTransitioner(int category) {
if (category == (int) Categories.Head)
return new int[] { (int) Providers.Head, (int) Providers.NextLink, (int) Providers.Tail };
if (category == (int) Categories.Tail)
return new int[] { (int) Providers.Head, (int) Providers.PreviousLink, (int) Providers.Tail };
return new int[] { (int) Providers.Head, (int) Providers.Link, (int) Providers.NextLink,
(int) Providers.PreviousLink, (int) Providers.Tail };
}
public override AttachObject ResolveProvider(int provider, Attachment attachment) {
if (provider == (int) Providers.Head)
return GetHead(attachment);
if (provider == (int) Providers.Tail)
return GetTail(attachment);
throw new System.NotSupportedException("Ambiguous provider; use ResolveProvider(int provider, "
+ "AttachObject reference)");
}
public override AttachObject ResolveProvider(int provider, AttachObject reference) {
if (provider == (int) Providers.Link)
return reference;
if (provider == (int) Providers.NextLink)
return GetNextLink(reference);
if (provider == (int) Providers.PreviousLink)
return GetPreviousLink(reference);
if (provider == (int) Providers.Head)
return GetHead(reference.attachment);
if (provider == (int) Providers.Tail)
return GetTail(reference.attachment);
throw new System.InvalidOperationException("Unknown provider");
}
protected AttachObject GetHead(Attachment attachment) {
return attachment.objects.Get((int) Categories.Head, 0);
}
protected AttachObject GetTail(Attachment attachment) {
return attachment.objects.Get((int) Categories.Tail, 0);
}
protected AttachObject GetNextLink(AttachObject link) {
if (link.category == (int) Categories.Head) {
if (link.attachment.objects.Count((int) Categories.Links) == 0)
return GetTail(link.attachment);
return link.attachment.objects.Get((int) Categories.Links, 0);
}
if (link.category == (int) Categories.Tail)
return null;
if (link.indexInCategory + 1 == link.attachment.objects.Count(category: (int) Categories.Links))
return GetTail(link.attachment);
return link.attachment.objects.Get((int) Categories.Links, link.indexInCategory + 1);
}
protected AttachObject GetPreviousLink(AttachObject link) {
if (link.category == (int) Categories.Tail) {
if (link.attachment.objects.Count((int) Categories.Links) == 0)
return GetHead(link.attachment);
return link.attachment.objects.Get((int) Categories.Links,
link.attachment.objects.Count((int) Categories.Links) - 1);
}
if (link.category == (int) Categories.Head)
return null;
int indexInCategory = link.indexInCategory - 1;
if (indexInCategory == -1)
return GetHead(link.attachment);
return link.attachment.objects.Get((int) Categories.Links, indexInCategory);
}
protected abstract void ConnectLinks(AttachObject link, AttachObject nextLink);
protected abstract void DisconnectLinks(AttachObject link, AttachObject nextLink);
public override bool ConnectObject(AttachObject link) {
AttachObject nextLink = GetNextLink(link);
AttachObject previousLink = GetPreviousLink(link);
if (nextLink != null && nextLink.isConnected && previousLink != null && previousLink.isConnected)
DisconnectLinks(previousLink, nextLink);
if (previousLink != null && previousLink.isConnected)
ConnectLinks(previousLink, link);
if (nextLink != null && nextLink.isConnected)
ConnectLinks(link, nextLink);
return true;
}
public override bool DisconnectObject(AttachObject link) {
DisconnectObjectImmediate(link);
return true;
}
public override void DisconnectObjectImmediate(AttachObject link) {
AttachObject nextLink = GetNextLink(link);
AttachObject previousLink = GetPreviousLink(link);
if (previousLink != null && previousLink.isConnected)
DisconnectLinks(previousLink, link);
if (nextLink != null && nextLink.isConnected)
DisconnectLinks(link, nextLink);
}
public override void OnObjectWasRemoved(Attachment attachment, AttachObject obj, int oldIndexInCategory) {
if (obj.category != (int) Categories.Links)
return;
AttachObject link;
if (oldIndexInCategory == 0)
link = GetHead(attachment);
else
link = attachment.objects.Get((int) Categories.Links, oldIndexInCategory - 1);
if (link == null || !link.isConnected)
return;
AttachObject nextLink = GetNextLink(link);
if (nextLink != null && nextLink.isConnected)
ConnectLinks(link, nextLink);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
namespace Boxofon.Web.Helpers
{
public static class StringExtensions
{
private const string PhoneNumberPattern = @"\+?(\d+-)?\d+";
private static readonly Regex PhoneNumberRegex = new Regex("^" + PhoneNumberPattern + "$", RegexOptions.Compiled);
private static readonly Regex PhoneNumbersRegex = new Regex(@"(\s|,|;|^|\G)+(?<phoneNumber>" + PhoneNumberPattern + @")(\s|,|;|$)+", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
private static readonly Regex EmailSubjectAbbrevationRegex = new Regex(@"^((re|fw|sv|vs|antw|doorst|vl|tr|aw|wg|r|rif|i|fs|rv|res|enc|odp|pd|vb):\s*)+", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
public static bool IsPossiblyValidPhoneNumber(this string phoneNumber)
{
if (string.IsNullOrWhiteSpace(phoneNumber))
{
return false;
}
phoneNumber = phoneNumber
.Replace(" ", string.Empty)
.Replace("-", string.Empty)
.Replace("(", string.Empty)
.Replace(")", string.Empty);
return PhoneNumberRegex.IsMatch(phoneNumber);
}
public static string ToE164(this string phoneNumber)
{
if (!IsPossiblyValidPhoneNumber(phoneNumber))
{
throw new FormatException("The input is not a valid phone number.");
}
phoneNumber = phoneNumber
.Replace(" ", string.Empty)
.Replace("-", string.Empty)
.Replace("(", string.Empty)
.Replace(")", string.Empty);
if (phoneNumber.StartsWith("+"))
{
return phoneNumber;
}
if (phoneNumber.StartsWith("00"))
{
return "+" + phoneNumber.Remove(0, 2);
}
if (phoneNumber.StartsWith("0"))
{
return "+46" + phoneNumber.Remove(0, 1);
}
return "+46" + phoneNumber;
}
public static string[] GetAllPhoneNumbers(this string text)
{
if (string.IsNullOrEmpty(text))
{
return new string[0];
}
return (from Match match in PhoneNumbersRegex.Matches(text)
where match.Groups["phoneNumber"].Success
select match.Groups["phoneNumber"].Value.ToE164()).Distinct().ToArray();
}
public static bool IsValidEmail(this string email)
{
try
{
new System.Net.Mail.MailAddress(email);
return true;
}
catch
{
return false;
}
}
public static string ZBase32Encode(this string unencodedValue)
{
var bytes = Encoding.UTF8.GetBytes(unencodedValue);
return new ZBase32().Encode(bytes);
}
public static string ZBase32Decode(this string encodedValue)
{
var bytes = new ZBase32().Decode(encodedValue);
return Encoding.UTF8.GetString(bytes);
}
public static string HmacSha256HexDigestEncode(this string value, string key)
{
var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(value));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
public static string HmacSha1Base64Encode(this string value, string key)
{
var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value));
return Convert.ToBase64String(hash);
}
public static string Truncate(this string value, int maxLength, string suffixWhenTruncated = "...")
{
if (string.IsNullOrEmpty(value) || value.Length <= maxLength)
{
return value;
}
return value.Substring(0, maxLength) + suffixWhenTruncated;
}
public static string RemoveCommonEmailSubjectAbbrevations(this string subject)
{
return string.IsNullOrEmpty(subject) ? subject : EmailSubjectAbbrevationRegex.Replace(subject, string.Empty);
}
}
} |
using DFrame;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace DPYM
{
/*
* 1、工具管理来完成工具的调度
* 2、实际的工具类来完成工具的行为特性
* 3、工具和工具管理的关系,更像是一种状态的关系
*
* 先以单例的形式实现,暂时未想到更好的处理方式
*/
/// <summary>
/// 工具管理
/// </summary>
public class ToolSwitcher
{
/* 创建 */
public ToolSwitcher()
{
}
/* 属性 */
/// <summary>
/// 当前使用道具的类型
/// </summary>
public EToolType currToolType
{
get
{
return _currToolType;
}
set
{
// 要么配置为 Unavailable,相当于清空
if (EToolType.Unavailable == value)
{
if (null != _currTool)
{
_currTool.Deactivate();
_currTool = null;
}
_currToolType = EToolType.Unavailable;
}
// 要么配置为一个有效的
else if (_toolKit.ContainsKey(value) && IsToolAvailable(_toolKit[value]))
{
// 老道具反激活
if (null != _currTool)
_currTool.Deactivate();
// 设置新道具
_currToolType = value;
_currTool = _toolKit[value].tool;
// 激活新道具
_currTool.Activate();
DLogger.DBGMD(string.Format("[WARNING] ToolSwitcher._currToolType.set : Current tool changed to {0}.", value));
}
// 非法操作给出提示
else
{
DLogger.MD(string.Format("[WARNING] ToolSwitcher._currToolType.set : Tool {0} not available or not exist.", value));
}
}
}
/// <summary>
/// 当前使用道具
/// </summary>
public Tool currTool
{
get
{
return _currTool;
}
}
/* 接口 */
/// <summary>
/// 道具选择
/// </summary>
/// <param name="toolType"></param>
public void ChooseTool(EToolType toolType)
{
currToolType = toolType;
}
/// <summary>
/// 增加道具
/// </summary>
/// <param name="toolType"></param>
/// <param name="toolInfo"></param>
public void AddTool(EToolType toolType, ToolInfo toolInfo)
{
// 记录日志
DLogger.MD(string.Format(
"[INFO] ToolSwitcher.AddTool : tool of type {0} was added, tool info : {1}.",
toolType, toolInfo));
// 这里对道具类型做一个校验,校验失败则取消添加操作(不能添加空道具)
if (toolInfo.NotToolType(toolType))
{
DLogger.MD("[ERROR] ToolSwitcher.AddTool : tool check failed, add operation aborted.");
return;
}
// 对道具的存在性进行校验,若重复添加,给出警告并覆盖添加
if (_toolKit.ContainsKey(toolType))
{
DLogger.MD(string.Format(
"[WARNING] ToolSwitcher.AddTool : Duplicated tool({0}) added, overwrite.",
toolType));
}
// 添加道具信息
_toolKit[toolType] = toolInfo;
// 如果是第一个被添加的可用道具,那么将其配置为当前道具
if (EToolType.Unavailable == currToolType && IsToolAvailable(toolInfo))
{
DLogger.MD(string.Format(
"[INFO] ToolSwitcher.AddTool : The only available tool({0}) added, forced to be current tool",
toolType));
currToolType = toolType;
}
}
/// <summary>
/// 清除道具
/// </summary>
public void Clear()
{
currToolType = EToolType.Unavailable;
foreach (ToolInfo toolInfo in _toolKit.Values)
{
toolInfo.Dispose();
}
_toolKit.Clear();
}
/// <summary>
/// 检测道具切换(每个周期检测)
/// </summary>
public void CheckToolSwitch()
{
// 检测直接切换(切换成功后直接跳出,最高优先级)
CheckDirectSwitch();
// 检测快速切换
CheckFastSwitch();
// 检测依次切换
CheckSortedSwitch();
}
/// <summary>
/// 绑定道具切换方式和道具类型
/// </summary>
/// <param name="keyCode"></param>
/// <param name="toolType"></param>
public void SetSwitchMethod(EToolType toolType, IToolSwitchMethod switchMethod)
{
GetToolInfo(toolType).switchMethod = switchMethod;
}
/// <summary>
/// 配置道具的
/// </summary>
/// <param name="toolType"></param>
/// <param name="enable"></param>
public void SetEnable(EToolType toolType, bool enable)
{
GetToolInfo(toolType).enable = enable;
}
/// <summary>
/// 获取道具信息
/// </summary>
/// <param name="toolType"></param>
/// <returns></returns>
public ToolInfo GetToolInfo(EToolType toolType)
{
if (!_toolKit.ContainsKey(toolType))
{
_toolKit[toolType] = new ToolInfo();
}
return _toolKit[toolType];
}
/// <summary>
/// 判断道具是否可用
/// </summary>
/// <param name="toolInfo"></param>
/// <returns></returns>
public bool IsToolAvailable(ToolInfo toolInfo)
{
if (null == toolInfo) return false;
if (null == toolInfo.tool) return false;
// switchmethod 是用来切换到自身的,若没有切换到自身的方法,那么不会切过来,除非外部切换,因而不用检测
// if (null == toolInfo.switchMethod) return false;
if (false == toolInfo.enable) return false;
return true;
}
/* 功能实现 */
/// <summary>
/// 检测道具的直接切换
/// </summary>
void CheckDirectSwitch()
{
foreach (ToolInfo toolInfo in _toolKit.Values)
{
if (toolInfo.CanSwitch())
{
// 内部切换的话(玩家操作),相同道具不进行切换
if(toolInfo.NotToolType(currToolType))
{
ChooseTool(toolInfo.tool.toolType);
break;
}
}
}
}
/// <summary>
/// 检测道具的快速切换操作
/// </summary>
void CheckFastSwitch()
{
}
/// <summary>
/// 检测顺序切换
/// </summary>
void CheckSortedSwitch()
{
}
/* 内部组件 */
/// <summary>
/// 道具箱
/// </summary>
Dictionary<EToolType, ToolInfo> _toolKit = new Dictionary<EToolType, ToolInfo>();
/* 受限组件*/
EToolType _currToolType = EToolType.Unavailable;
/* 间接维护组件 */
/// <summary>
/// 当前使用道具(由 _currToolType 维护)
/// </summary>
Tool _currTool = null;
}
} |
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.AccountEntity;
using Anywhere2Go.DataAccess.Object;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.AccountingLogic.Master
{
public class ProcessStatusLogic
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ProcessStatusLogic));
private MyContext _context = null;
public ProcessStatusLogic()
{
_context = new MyContext(Configurator.CrmAccountingConnection);
}
public List<ProcessStatus> GetProcessStatus(int processId = 0, bool? isActive = null)
{
var req = new Repository<ProcessStatus>(_context);
List<ProcessStatus> result = new List<ProcessStatus>();
var query = req.GetQuery();
if (processId != 0)
{
query = query.Where(t => t.ProcessId == processId);
}
if (isActive != null)
{
query = query.Where(t => t.isActive == isActive);
}
return query.ToList();
}
}
}
|
using DrivingSchool_Api;
using Repository.Interfaces;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Services.Implementations
{
public class BookingTypeService : IBookingTypeService
{
private readonly IBookingTypeRepository _bookingTypeRepository;
public BookingTypeService(IBookingTypeRepository bookingTypeRepository)
{
_bookingTypeRepository = bookingTypeRepository;
}
public void Add(BookingType bookingType)
{
_bookingTypeRepository.Add(bookingType);
}
public void Delete(int? bkTId)
{
_bookingTypeRepository.Delete(bkTId);
}
public IQueryable<BookingType> GatAll()
{
return _bookingTypeRepository.GetAll();
}
public BookingType GetSingle(int? bkTId)
{
return _bookingTypeRepository.GetSingleRecord(bkTId);
}
public void Update(BookingType bookingType)
{
_bookingTypeRepository.Update(bookingType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace StringCalculatorIntegrationTests.POCOs
{
public class CalculatorString
{
public string StringValue { get; set; }
public CalculatorString(string calculatorString)
{
StringValue = calculatorString;
}
}
}
|
using UnityEngine;
using System.Collections;
public class TransitionsSetting : MonoBehaviour {
public GameObject SettingObj;
private bool isButton_startPressed;
// Use this for initialization
void Start () {
this.isButton_startPressed = false;
}
// Update is called once per frame
void Update () {
}
/// <summary>スタートボタン押された</summary>
void Button_startPressed() { this.isButton_startPressed = true; }
/// <summary>左ボタン離れた</summary>
void Button_startReleased() {
if (Setting.isSetting || GameGuide.isGuide || MapAction.animation_flag)
return;
// フェード中の操作をはじく
if (Fade.NowFade != FADE.FADE_NONE)
return;
if (this.isButton_startPressed) {
this.isButton_startPressed = false;
Setting.isSetting = true;
PlaySE.isPlaySelect = true;
SettingObj.SetActive (true);
Setting.isStart = true;
}
this.isButton_startPressed = false;
}
}
|
namespace AsNum.XFControls.Services {
public interface IToast {
void Show(string msg, bool longShow = false);
}
}
|
namespace Sentry.PlatformAbstractions;
/// <summary>
/// Details of the runtime
/// </summary>
public class Runtime : IEquatable<Runtime>
{
/// <summary>
/// Gets the current runtime
/// </summary>
/// <value>
/// The current runtime.
/// </value>
public static Runtime Current { get; } = RuntimeInfo.GetRuntime();
/// <summary>
/// The name of the runtime
/// </summary>
/// <example>
/// .NET Framework, .NET Native, Mono
/// </example>
public string? Name { get; }
/// <summary>
/// The version of the runtime
/// </summary>
/// <example>
/// 4.7.2633.0
/// </example>
public string? Version { get; }
#if NETFRAMEWORK
/// <summary>
/// The .NET Framework installation which is running the process
/// </summary>
/// <value>
/// The framework installation or null if not running .NET Framework
/// </value>
public FrameworkInstallation? FrameworkInstallation { get; }
#endif
/// <summary>
/// The raw value parsed to extract Name and Version
/// </summary>
/// <remarks>
/// This property will contain a value when the underlying API
/// returned Name and Version as a single string which required parsing.
/// </remarks>
public string? Raw { get; }
/// <summary>
/// The .NET Runtime Identifier of the runtime
/// </summary>
/// <remarks>
/// This property will be populated for .NET 5 and newer, or <c>null</c> otherwise.
/// </remarks>
public string? Identifier
{
get => _identifier;
[Obsolete("This setter is nonfunctional, and will be removed in a future version.")]
// ReSharper disable ValueParameterNotUsed
set { }
// ReSharper restore ValueParameterNotUsed
}
// TODO: Convert to get-only auto-property in next major version
private readonly string? _identifier;
/// <summary>
/// Creates a new Runtime instance
/// </summary>
#if NETFRAMEWORK
public Runtime(
string? name = null,
string? version = null,
FrameworkInstallation? frameworkInstallation = null,
string? raw = null)
{
Name = name;
Version = version;
FrameworkInstallation = frameworkInstallation;
Raw = raw;
_identifier = null;
}
#else
public Runtime(
string? name = null,
string? version = null,
string? raw = null,
string? identifier = null)
{
Name = name;
Version = version;
Raw = raw;
_identifier = identifier;
}
#endif
/// <summary>
/// The string representation of the Runtime
/// </summary>
public override string? ToString()
{
if (Name == null && Version == null)
{
return Raw;
}
if (Name != null && Version == null)
{
return Raw?.Contains(Name) == true
? Raw
: $"{Name} {Raw}";
}
return $"{Name} {Version}";
}
/// <summary>
/// Compare instances for equality.
/// </summary>
/// <param name="other">The instance to compare against.</param>
/// <returns>True if the instances are equal by reference or its state.</returns>
public bool Equals(Runtime? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return string.Equals(Name, other.Name)
&& string.Equals(Version, other.Version)
&& string.Equals(Raw, other.Raw)
#if NETFRAMEWORK
&& Equals(FrameworkInstallation, other.FrameworkInstallation);
#else
&& Equals(Identifier, other.Identifier);
#endif
}
/// <summary>
/// Compare instances for equality.
/// </summary>
/// <param name="obj">The instance to compare against.</param>
/// <returns>True if the instances are equal by reference or its state.</returns>
public override bool Equals(object? obj)
{
if (obj is null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((Runtime)obj);
}
/// <summary>
/// Get the hashcode of this instance.
/// </summary>
/// <returns>The hashcode of the instance.</returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = Name?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ (Version?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (Raw?.GetHashCode() ?? 0);
#if NETFRAMEWORK
hashCode = (hashCode * 397) ^ (FrameworkInstallation?.GetHashCode() ?? 0);
#else
hashCode = (hashCode * 397) ^ (_identifier?.GetHashCode() ?? 0);
#endif
return hashCode;
}
}
}
|
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.Interfaces.Servicos
{
public interface IServicoParteConjuntos: IServicoBase<ParteConjuntos>
{
List<ParteConjuntos> ListarPorIdAto(int idAto);
List<ParteConjuntos> ListarPorIdNome(int idNome);
List<ParteConjuntos> ObterNomesPorIdProcuracao(int IdProcuracao);
}
}
|
namespace ostranauts_modding
{
public class Ad
{
public string strDesc { get; set; }
public string strName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FIVIL.Litentity
{
public class LitentityConfiguration
{
internal static bool Cookie = false;
internal static bool Header = true;
internal static string PrivateTokenName = "LPT";
internal static string PublicTokenName = "LPuT";
internal static Action<LitentityUsers> callBack;
internal static TimeSpan IdleTime = TimeSpan.FromMinutes(40);
internal static Guid PublicToken = Guid.NewGuid();
internal static Type type;
public LitentityConfiguration()
{
}
public LitentityConfiguration UseCookie(bool Use)
{
Cookie = Use;
return this;
}
public LitentityConfiguration UserHeader(bool Use)
{
Header = Use;
return this;
}
public LitentityConfiguration SetPublicTokenName(string publicTokenName)
{
PublicTokenName = publicTokenName;
return this;
}
public LitentityConfiguration SetPrivateTokenName(string privateTokenName)
{
PrivateTokenName = privateTokenName;
return this;
}
public LitentityConfiguration SetCallBackFunction(Action<LitentityUsers> CallBack)
{
callBack = CallBack;
return this;
}
public LitentityConfiguration SetIdleTimeOut(TimeSpan idle)
{
IdleTime = idle;
return this;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.ValuesObject
{
public class TipoLivroProcuracao
{
public string Sigla { get; set; }
public string Descricao { get; set; }
public List<TipoLivroProcuracao> ObterTipoLivroProcuracaoOrigem()
{
TipoLivroProcuracao tipo = new TipoLivroProcuracao();
List<TipoLivroProcuracao> listaRetorno = new List<TipoLivroProcuracao>();
tipo.Sigla = "P";
tipo.Descricao = "PROCURAÇÃO";
listaRetorno.Add(tipo);
tipo = new TipoLivroProcuracao();
tipo.Sigla = "E";
tipo.Descricao = "ESCRITURA";
listaRetorno.Add(tipo);
tipo = new TipoLivroProcuracao();
tipo.Sigla = "M";
tipo.Descricao = "MISTO";
listaRetorno.Add(tipo);
return listaRetorno;
}
public List<TipoLivroProcuracao> ObterTipoLivroProcuracao()
{
TipoLivroProcuracao tipo = new TipoLivroProcuracao();
List<TipoLivroProcuracao> listaRetorno = new List<TipoLivroProcuracao>();
tipo.Sigla = "P";
tipo.Descricao = "PROCURAÇÃO";
listaRetorno.Add(tipo);
tipo = new TipoLivroProcuracao();
tipo.Sigla = "M";
tipo.Descricao = "MISTO";
listaRetorno.Add(tipo);
return listaRetorno;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ImagoCore.Models.Events
{
public class AttributChangedEventArgs : EventArgs
{
public AttributChangedEventArgs(Attribut attributChanged)
{
AttributChanged = attributChanged;
}
public AttributChangedEventArgs()
{
}
public Attribut AttributChanged { get; }
}
}
|
namespace Pobs.Domain
{
public enum PostStatus
{
OK = 0,
AwaitingApproval = 1,
}
} |
using System;
using System.Diagnostics;
using System.Windows.Forms;
using NLog;
namespace UseFul.Uteis
{
public static class AppLogging
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static void Log(string message, LogType logType)
{
switch (logType)
{
case LogType.Debug:
Logger.Debug(message);
break;
case LogType.Info:
Logger.Info(message);
break;
case LogType.Warn:
Logger.Warn(message);
break;
case LogType.Error:
Logger.Error(message);
break;
case LogType.Fatal:
Logger.Fatal(message);
break;
default:
Logger.Info(message);
break;
}
}
public static void LogException(string message, Exception exception, LogType logType)
{
switch (logType)
{
case LogType.Debug:
Logger.Debug(message, exception, null);
break;
case LogType.Info:
Logger.Info(message, exception, null);
break;
case LogType.Warn:
Logger.Warn(message, exception, null);
break;
case LogType.Error:
Logger.Error(message, exception, null);
break;
case LogType.Fatal:
Logger.Fatal(message, exception, null);
break;
default:
Logger.Debug(message, exception, null);
break;
}
}
public static void OpenLogFolder()
{
string myDocspath = Application.StartupPath + @"\log";
string windir = Environment.GetEnvironmentVariable("WINDIR");
Process process = new Process
{
StartInfo =
{
FileName = windir + @"\explorer.exe",
Arguments = myDocspath
}
};
process.Start();
}
}
} |
using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using Profiling2.Domain.Contracts.Queries;
using Profiling2.Domain.DTO;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Events;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Prf.Sources;
using Profiling2.Domain.Prf.Units;
using SharpArch.NHibernate;
namespace Profiling2.Infrastructure.Queries
{
public class FeedingSourceQuery : NHibernateQuery, IFeedingSourceQuery
{
public IList<FeedingSourceDTO> GetFeedingSourceDTOs(bool canViewAndSearchAll, bool includeRestricted, string uploadedByUserId)
{
FeedingSourceDTO output = null;
FeedingSource feedingSourceAlias = null;
AdminUser uploadedByAlias = null;
AdminUser approvedByAlias = null;
AdminUser rejectedByAlias = null;
Source sourceAlias = null;
PersonSource personSourceAlias = null;
EventSource eventSourceAlias = null;
UnitSource unitSourceAlias = null;
OperationSource operationSourceAlias = null;
var q = Session.QueryOver<FeedingSource>(() => feedingSourceAlias)
.JoinAlias(() => feedingSourceAlias.UploadedBy, () => uploadedByAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => feedingSourceAlias.ApprovedBy, () => approvedByAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => feedingSourceAlias.RejectedBy, () => rejectedByAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => feedingSourceAlias.Source, () => sourceAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => sourceAlias.PersonSources, () => personSourceAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => sourceAlias.EventSources, () => eventSourceAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => sourceAlias.UnitSources, () => unitSourceAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => sourceAlias.OperationSources, () => operationSourceAlias, JoinType.LeftOuterJoin)
.SelectList(list => list
.Select(Projections.Group(() => feedingSourceAlias.Id)).WithAlias(() => output.Id)
.Select(Projections.Group(() => feedingSourceAlias.Name)).WithAlias(() => output.Name)
.Select(Projections.Group(() => feedingSourceAlias.Restricted)).WithAlias(() => output.Restricted)
.Select(Projections.Group(() => feedingSourceAlias.FileModifiedDateTime)).WithAlias(() => output.FileModifiedDateTime)
.Select(Projections.Group(() => uploadedByAlias.UserName)).WithAlias(() => output.UploadedBy)
.Select(Projections.Group(() => feedingSourceAlias.UploadDate)).WithAlias(() => output.UploadDate)
.Select(Projections.Group(() => approvedByAlias.UserName)).WithAlias(() => output.ApprovedBy)
.Select(Projections.Group(() => feedingSourceAlias.ApprovedDate)).WithAlias(() => output.ApproveDate)
.Select(Projections.Group(() => rejectedByAlias.UserName)).WithAlias(() => output.RejectedBy)
.Select(Projections.Group(() => feedingSourceAlias.RejectedDate)).WithAlias(() => output.RejectedDate)
.Select(Projections.Group(() => feedingSourceAlias.RejectedReason)).WithAlias(() => output.RejectedReason)
.Select(Projections.Group(() => feedingSourceAlias.UploadNotes)).WithAlias(() => output.UploadNotes)
.Select(Projections.Group(() => feedingSourceAlias.Source.Id)).WithAlias(() => output.SourceID)
.Select(Projections.Group(() => feedingSourceAlias.IsReadOnly)).WithAlias(() => output.IsReadOnly)
.Select(Projections.Group(() => feedingSourceAlias.IsPublic)).WithAlias(() => output.IsPublic)
.Select(Projections.Count(() => personSourceAlias.Person.Id)).WithAlias(() => output.PersonSourceCount)
.Select(Projections.Count(() => eventSourceAlias.Event.Id)).WithAlias(() => output.EventSourceCount)
.Select(Projections.Count(() => unitSourceAlias.Unit.Id)).WithAlias(() => output.UnitSourceCount)
.Select(Projections.Count(() => operationSourceAlias.Operation.Id)).WithAlias(() => output.OperationSourceCount)
);
if (canViewAndSearchAll)
{
if (!includeRestricted)
{
q = q.Where(() => feedingSourceAlias.Restricted == false);
}
}
else
{
// user can access sources they uploaded as well as sources marked public
q = q.Where(() => uploadedByAlias.UserID == uploadedByUserId || feedingSourceAlias.IsPublic);
}
return q.TransformUsing(Transformers.AliasToBean<FeedingSourceDTO>())
.List<FeedingSourceDTO>();
}
// for statistics purposes, hence no security permissions
public IList<FeedingSourceDTO> GetFeedingSourceDTOs(ISession session, DateTime start, DateTime end, bool includeRestricted)
{
FeedingSource fsAlias = null;
FeedingSourceDTO output = null;
AdminUser uploadedByAlias = null;
AdminUser approvedByAlias = null;
AdminUser rejectedByAlias = null;
ISession thisSession = session == null ? this.Session : session;
var q = thisSession.QueryOver<FeedingSource>(() => fsAlias)
.JoinAlias(() => fsAlias.UploadedBy, () => uploadedByAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => fsAlias.ApprovedBy, () => approvedByAlias, JoinType.LeftOuterJoin)
.JoinAlias(() => fsAlias.RejectedBy, () => rejectedByAlias, JoinType.LeftOuterJoin)
.Where(Restrictions.Disjunction()
.Add(Restrictions.On(() => fsAlias.UploadDate).IsBetween(start).And(end))
.Add(Restrictions.On(() => fsAlias.ApprovedDate).IsBetween(start).And(end))
.Add(Restrictions.On(() => fsAlias.RejectedDate).IsBetween(start).And(end))
)
.SelectList(list => list
.Select(() => fsAlias.Id).WithAlias(() => output.Id)
.Select(() => fsAlias.Name).WithAlias(() => output.Name)
.Select(() => fsAlias.Restricted).WithAlias(() => output.Restricted)
.Select(() => fsAlias.FileModifiedDateTime).WithAlias(() => output.FileModifiedDateTime)
.Select(() => uploadedByAlias.UserName).WithAlias(() => output.UploadedBy)
.Select(() => fsAlias.UploadDate).WithAlias(() => output.UploadDate)
.Select(() => approvedByAlias.UserName).WithAlias(() => output.ApprovedBy)
.Select(() => fsAlias.ApprovedDate).WithAlias(() => output.ApproveDate)
.Select(() => rejectedByAlias.UserName).WithAlias(() => output.RejectedBy)
.Select(() => fsAlias.RejectedDate).WithAlias(() => output.RejectedDate)
.Select(() => fsAlias.RejectedReason).WithAlias(() => output.RejectedReason)
.Select(() => fsAlias.UploadNotes).WithAlias(() => output.UploadNotes)
);
if (!includeRestricted)
q = q.Where(() => !fsAlias.Restricted);
return q.TransformUsing(Transformers.AliasToBean<FeedingSourceDTO>())
.List<FeedingSourceDTO>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using XL.Util.Log;
namespace HPYL_API.XLAttribute
{
/// <summary>
/// 版 本 1.0
/// Copyright (c) 2017-2018 北京佰云信息技术有限公司
/// 创建人:DXL
/// 日 期:2017-09-09 21:40:37
/// 描 述: 接口运行效率监控
/// </summary>
public class TimeRunAttribute : ActionFilterAttribute
{
private const string Key = "__XL_Log__";
//private Log _logger;
///// <summary>
///// 日志操作
///// </summary>
//public Log Logger
//{
// get { return _logger ?? (_logger = LogFactory.GetLogger(this.GetType().ToString())); }
//}
private readonly Log logger = LogFactory.GetLogger("TimeRunAttribute");
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (SkipLogging(actionContext))
{
return;
}
var stopWatch = new Stopwatch();
actionContext.Request.Properties[Key] = stopWatch;
stopWatch.Start();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
{
return;
}
var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
if (stopWatch != null)
{
stopWatch.Stop();
var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
//Debug.Print(string.Format("[API {0}- {1}: time {2}.]", controllerName, actionName, stopWatch.Elapsed));
logger.Info(string.Format("[API {0}- {1}: time {2}.]", controllerName, actionName, stopWatch.Elapsed));
}
}
private static bool SkipLogging(HttpActionContext actionContext)
{
return actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>().Any() ||
actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<NoLogAttribute>().Any();
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
public class NoLogAttribute : Attribute
{
}
}
|
using Common;
using IBLLService;
using IDALRepository;
using MODEL;
using MODEL.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace BLLService
{
public partial class MST_PRD_MANAGER : BaseBLLService<MST_PRD>, IMST_PRD_MANAGER
{
public MODEL.DataTableModel.DataTableGrid GetProductsForGrid(MODEL.DataTableModel.DataTableRequest request)
{
try
{
var predicate = PredicateBuilder.True<MST_PRD>();
DateTime time = TypeParser.ToDateTime("1975-1-1");
int total = 0;
predicate = predicate.And(p => p.ISCHECK ==true);
var data = base.LoadPagedList(request.PageNumber, request.PageSize, ref total, predicate, request.Model, p => true, request.SortOrder, request.SortName).Select(p => new VIEW_MST_PRD(){
SEQ_NO=p.SEQ_NO,
PRD_CD=p.PRD_CD,
PRD_NAME=p.PRD_NAME,
PRD_SHORT_DESC=p.PRD_SHORT_DESC,
PRICE=p.PRICE,
ARKETPRICE=p.ARKETPRICE,
FRONTPRICE=p.FRONTPRICE,
CATEGORY_NAME=p.MST_CATEGORY.CATEGORY_NAME,
ISHOT=p.ISHOT,
STATUS=p.STATUS,
CREATE_DT=p.CREATE_DT,
MODIFY_DT=p.MODIFY_DT
});
//var list = ViewModelProduct.ToListViewModel(data);
return new MODEL.DataTableModel.DataTableGrid()
{
draw = request.Draw,
data = data,
total = total
};
}
catch (Exception)
{
throw;
}
}
public MODEL.DataTableModel.DataTableGrid GetProductsForHot()
{
try
{
var predicate = PredicateBuilder.True<MST_PRD>();
DateTime time = TypeParser.ToDateTime("1975-1-1");
int total = 0;
predicate = predicate.And(p => p.ISCHECK == true&&p.ISHOT==true);
var data = base.LoadListBy(predicate).Select(p => new VIEW_MST_PRD()
{
SEQ_NO = p.SEQ_NO,
PRD_CD = p.PRD_CD,
PRD_SHORT_DESC = p.PRD_SHORT_DESC,
CATE_ID=p.CATE_ID
});
//var list = ViewModelProduct.ToListViewModel(data);
return new MODEL.DataTableModel.DataTableGrid()
{
draw = "",
data = data,
total = total
};
}
catch (Exception)
{
throw;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PangyaFileCore
{
public class Mascot: PangyaFile<Mascot>
{
public bool Enabled { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public int Price30 { get; set; }
public int PriceType { get; set; }
public int Power { get; set; }
public int Control { get; set; }
public int Accuracy { get; set; }
public int Spin { get; set; }
public int Curve { get; set; }
public int Lounge { get; set; }
public int PowerSlot { get; set; }
public int ControlSlot { get; set; }
public int AccuracySlot { get; set; }
public int SpinSlot { get; set; }
public int CurveSlot { get; set; }
protected override int ItemHeaderLength
{
get
{
return 284;
}
}
protected override Mascot Get(byte[] data)
{
return new Mascot()
{
Enabled = Convert.ToBoolean(data[0]),
Id = data.ToIntenger(startIndex: 4, count: 4),
Name = Encoding.ASCII.GetString(data.Skip(8).TakeWhile(x => x != 0x00).ToArray()),
PriceType = data.ToIntenger(startIndex: 105, count: 2),
};
}
}
}
|
/*
* Created by SharpDevelop.
* User: Admin
* Date: 5/6/2019
* Time: 6:46 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace proyeto_poo
{
/// <summary>
/// Description of Luxor.
/// </summary>
public class Luxor: Room
{
public Luxor(int Hour)
{
if (Convert.ToInt32(Hour) >= 12 && Convert.ToInt32(Hour) < 13) {
PriceRoom = 850;
} else{
PriceRoom = 1000;
}
}
}
}
|
using UnityEngine;
using System.Collections;
using FMOD;
using FMODUnity;
public class BankTrigger : MonoBehaviour
{
[SerializeField]
System.Collections.Generic.Dictionary<string, EventRef> m_banks;
private static BankTrigger m_instance;
//Use this for initialization
void Start()
{
m_instance = this;
}
public bool PlayTrigger(string a_eventKey)
{
EventRef toRun;
bool isValidRef = m_banks.TryGetValue(a_eventKey, out toRun);
if (isValidRef)
RuntimeManager.CreateInstance(toRun).start();
return isValidRef;
}
//Update is called once per frame
void Update()
{
}
public BankTrigger Instance
{
get { return m_instance; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.