content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
/* _BEGIN_TEMPLATE_
{
"id": "OG_162",
"name": [
"克苏恩的信徒",
"Disciple of C'Thun"
],
"text": [
"<b>战吼:</b>\n造成2点伤害。使你的克苏恩获得+2/+2<i>(无论它在哪里)。</i>",
"<b>Battlecry:</b> Deal 2 damage. Give your C'Thun +2/+2 <i>(wherever it is)</i>."
],
"cardClass": "NEUTRAL",
"type": "MINION",
"cost": 3,
"rarity": "RARE",
"set": "OG",
"collectible": true,
"dbfId": 38547
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_OG_162 : SimTemplate //* Disciple of C'Thun
{
//Battlecry: Deal 2 damage. Give your C'Thun +2/+2 (wherever it is)
public override void getBattlecryEffect(Playfield p, Minion own, Minion target, int choice)
{
p.minionGetDamageOrHeal(target, 2);
if (own.own)
{
p.cthunGetBuffed(2, 2, 0);
}
}
}
} | 21.820513 | 99 | 0.53819 | [
"MIT"
] | chi-rei-den/Silverfish | cards/OG/OG/Sim_OG_162.cs | 915 | C# |
using System.Runtime.CompilerServices;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;
using OzzyEntityLibraries.Repository;
using OzzyEntityLibraries.DTO.Models;
using OzzyEntityLibraries.ORM.Models;
namespace OzzyEntityLibraries.Services
{
public class CustomersService
{
CustomersRepository customersRepository;
public CustomersService()
{
if (customersRepository == null)
{
customersRepository = new CustomersRepository();
}
}
public IEnumerable<CustomersDTO> GetAllCustomers()
{
return customersRepository.GetAll().Select(x => new CustomersDTO
{
CustomerId = x.CustomerId,
ContactName = x.ContactName,
ContactTitle = x.ContactTitle,
Phone = x.Phone,
Email = x.Email,
Fax=x.Fax,
CompanyName=x.CompanyName,
Address=x.Address,
PostalCode=x.PostalCode,
TerritoryId=(int)x.TerritoryId,
RegionId=(int)x.RegionId,
CountryId=(int)x.CountryId
}).ToList();
}
public void AddCustomers(CustomersDTO entity)
{
Customers customers = new Customers
{
ContactName = entity.ContactName,
ContactTitle = entity.ContactTitle,
Phone = entity.Phone,
Email = entity.Email,
Fax = entity.Fax,
CompanyName = entity.CompanyName,
Address = entity.Address,
PostalCode = entity.PostalCode,
TerritoryId = entity.TerritoryId,
RegionId = entity.RegionId,
CountryId = entity.CountryId
};
customersRepository.Add(customers);
}
public void UpdateCustomers(CustomersDTO entity)
{
var customer = customersRepository.GetAll().Where(x => x.CustomerId == entity.CustomerId).FirstOrDefault();
customer.ContactName = entity.ContactName;
customer.ContactTitle = entity.ContactTitle;
customer.Phone = entity.Phone;
customer.Email = entity.Email;
customer.Fax = entity.Fax;
customer.CompanyName = entity.CompanyName;
customer.Address = entity.Address;
customer.PostalCode = entity.PostalCode;
customer.TerritoryId = entity.TerritoryId;
customer.RegionId = entity.RegionId;
customer.CountryId = entity.CountryId;
customersRepository.Update(customer);
}
public void DeleteCustomers(CustomersDTO entity)
{
var customer = customersRepository.GetAll().Where(x => x.CustomerId == entity.CustomerId).FirstOrDefault();
customer.ContactName = entity.ContactName;
customer.ContactTitle = entity.ContactTitle;
customer.Phone = entity.Phone;
customer.Email = entity.Email;
customer.Fax = entity.Fax;
customer.CompanyName = entity.CompanyName;
customer.Address = entity.Address;
customer.PostalCode = entity.PostalCode;
customer.TerritoryId = entity.TerritoryId;
customer.RegionId = entity.RegionId;
customer.CountryId = entity.CountryId;
customersRepository.Delete(customer);
}
public bool DeleteCustomersById(int id)
{
return customersRepository.DeletebyEntity(x => x.CustomerId==id);
}
}
}
| 32.991071 | 119 | 0.582679 | [
"MIT"
] | OzzyOzmen/Entity-Asp.Net-Core-CodeFirst-MVC-Project | OzzyEntityLibraries.Services/CustomersService.cs | 3,697 | C# |
using Main;
using AI.Blackboard;
using AI.BehaviourTree;
using AI.Base;
using UnityEngine;
using AI.RuleBased;
namespace BT
{
class ConditionCanSeeEnemy : Condition
{
public override bool IsTrue(IAgent agent)
{
Tank t = (Tank)agent;
Tank oppTank = Match.instance.GetOppositeTank(t.Team);
if (oppTank != null)
{
return t.CanSeeOthers(oppTank);
}
return false;
}
}
class TurnTurret : ActionNode
{
protected override ERunningStatus OnExecute(IAgent agent, BlackboardMemory workingMemroy)
{
Tank t = (Tank)agent;
Tank oppTank = Match.instance.GetOppositeTank(t.Team);
if (oppTank != null && oppTank.IsDead == false)
{
t.TurretTurnTo(oppTank.Position);
}
else
{
t.TurretTurnTo(t.Position + t.Forward);
}
return ERunningStatus.Executing;
}
}
class Fire : ActionNode
{
protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
{
Tank t = (Tank)agent;
return t.CanFire();
}
protected override ERunningStatus OnExecute(IAgent agent, BlackboardMemory workingMemroy)
{
Tank t = (Tank)agent;
t.Fire();
return ERunningStatus.Executing;
}
}
class BackToHome : ActionNode
{
protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
{
Tank t = (Tank)agent;
if(t.HP <= 30)
{
workingMemory.SetValue((int)EBBKey.MovingTargetPos, Match.instance.GetRebornPos(t.Team));
return true;
}
return false;
}
}
class GetStarMove : ActionNode
{
protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
{
Tank t = (Tank)agent;
bool hasStar = false;
float nearestDist = float.MaxValue;
Vector3 nearestStarPos = Vector3.zero;
foreach (var pair in Match.instance.GetStars())
{
Star s = pair.Value;
if (s.IsSuperStar)
{
hasStar = true;
nearestStarPos = s.Position;
break;
}
else
{
float dist = (s.Position - t.Position).sqrMagnitude;
if (dist < nearestDist)
{
hasStar = true;
nearestDist = dist;
nearestStarPos = s.Position;
}
}
}
if(hasStar)
{
workingMemory.SetValue((int)EBBKey.MovingTargetPos, nearestStarPos);
}
return hasStar;
}
}
class RandomMove : ActionNode
{
protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
{
Vector3 targetPos;
if(workingMemory.TryGetValue((int)EBBKey.MovingTargetPos, out targetPos))
{
Tank t = (Tank)agent;
if(Vector3.Distance(targetPos, t.Position) >= 1f)
{
return false;
}
}
workingMemory.SetValue((int)EBBKey.MovingTargetPos, GetNextDestination());
return true;
}
private Vector3 GetNextDestination()
{
float halfSize = PhysicsUtils.MaxFieldSize * 0.5f;
return new Vector3(Random.Range(-halfSize, halfSize), 0, Random.Range(-halfSize, halfSize));
}
}
class MoveTo : ActionNode
{
protected override bool OnEvaluate(IAgent agent, BlackboardMemory workingMemory)
{
return workingMemory.HasValue((int)EBBKey.MovingTargetPos);
}
protected override ERunningStatus OnExecute(IAgent agent, BlackboardMemory workingMemory)
{
Tank t = (Tank)agent;
t.Move(workingMemory.GetValue<Vector3>((int)EBBKey.MovingTargetPos));
return ERunningStatus.Finished;
}
}
enum EBBKey
{
MovingTargetPos
}
class MyTank : Tank
{
private BlackboardMemory m_WorkingMemory;
private Node m_BTNode;
protected override void OnStart()
{
base.OnStart();
m_WorkingMemory = new BlackboardMemory();
m_BTNode = new ParallelNode(1).AddChild(
new TurnTurret(),
new Fire().SetPrecondition(new ConditionCanSeeEnemy()),
new SequenceNode().AddChild(
new SelectorNode().AddChild(
new BackToHome(),
new GetStarMove(),
new RandomMove()),
new MoveTo()));
}
protected override void OnUpdate()
{
BehaviourTreeRunner.Exec(m_BTNode, this, m_WorkingMemory);
}
public override string GetName()
{
return "BTTank";
}
}
}
| 31.590643 | 105 | 0.509071 | [
"MIT"
] | FinneyTang/TankBattle | Assets/Scripts/ExampleAI/BT/MyTank.cs | 5,404 | C# |
using System;
public class Gandalf
{
private int happinessIndex;
private Mood mood;
private MoodFactory moodFactory;
public Gandalf()
{
this.moodFactory = new MoodFactory();
}
private void SetMood()
{
if (this.happinessIndex < -5)
{
this.mood = moodFactory.CreateMood("Angry");
}
else if (this.happinessIndex < 0)
{
this.mood = moodFactory.CreateMood("Sad");
}
else if (this.happinessIndex < 15)
{
this.mood = moodFactory.CreateMood("Happy");
}
else
{
this.mood = moodFactory.CreateMood("JavaScript");
}
}
public void Eat(Food food)
{
this.happinessIndex += food.Happiness;
}
public override string ToString()
{
this.SetMood();
var result = $"{this.happinessIndex}"
+ Environment.NewLine
+ $"{this.mood}";
return result;
}
} | 20.897959 | 61 | 0.515625 | [
"MIT"
] | stStoyanov93/SoftUni-CSharp-Fundamentals-2018 | C# OOP Basics/04 Inheritance/EXE_Inheritance/P05_MordorsCruelPlan/Models/Gandalf.cs | 1,026 | C# |
namespace BenchmarkDotNet.Horology
{
public class FrequencyUnit
{
public string Name { get; }
public string Description { get; }
public long HertzAmount { get; }
private FrequencyUnit(string name, string description, long hertzAmount)
{
Name = name;
Description = description;
HertzAmount = hertzAmount;
}
public static readonly FrequencyUnit Hz = new FrequencyUnit("Hz", "Hertz", 1);
public static readonly FrequencyUnit KHz = new FrequencyUnit("KHz", "Kilohertz", 1000);
public static readonly FrequencyUnit MHz = new FrequencyUnit("MHz", "Megahertz", 1000 * 1000);
public static readonly FrequencyUnit GHz = new FrequencyUnit("GHz", "Gigahertz", 1000 * 1000 * 1000);
public static readonly FrequencyUnit[] All = { Hz, KHz, MHz, GHz };
public Frequency ToFrequency(long value = 1) => new Frequency(value, this);
}
} | 40.208333 | 109 | 0.640415 | [
"MIT"
] | AlexGhiondea/BenchmarkDotNet | src/BenchmarkDotNet.Core/Horology/FrequencyUnit.cs | 967 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MetalFistUpgrade : PlayerUpgrade
{
[SerializeField]
protected float cooldown = 5.0f;
[SerializeField]
protected bool canPunch = true;
[SerializeField]
protected float wait = 0.1f;
protected bool canDestroy = false;
[SerializeField]
protected SpriteRenderer sprender;
//when player interacts with enemy type" breakable wall" && player pressing use metal fist button, destroy(wall)
// Start is called before the first frame update
void Awake()
{
sprender.enabled = false;
}
void Start()
{
sprender.enabled = false;
}
public override void UseUpgrade(int direction)
{
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("Punchu");
canPunch = false;
CheckWallBreak(direction);
}
}
void CheckWallBreak(int direction)
{
if(sprender)
sprender.enabled = true;
StartCoroutine(Punch(direction));
//StartCoroutine(CooldownTimer());
}
public IEnumerator CooldownTimer()
{
yield return new WaitForSeconds(cooldown);
canPunch = true;
}
public IEnumerator Punch(int direction)
{
if (direction > 0)
{
Vector3 pos = transform.position;
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x - 0.1f, transform.position.y, transform.position.z);
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x + 0.3f, transform.position.y, transform.position.z);
canDestroy = true;
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x - 0.2f, transform.position.y, transform.position.z);
canDestroy = false;
sprender.enabled = false;
StartCoroutine(CooldownTimer());
}
else if(direction < 0)
{
Vector3 pos = transform.position;
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x + 0.1f, transform.position.y, transform.position.z);
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x -0.3f, transform.position.y, transform.position.z);
canDestroy = true;
yield return new WaitForSeconds(wait);
transform.position = new Vector3(transform.position.x + 0.2f, transform.position.y, transform.position.z);
canDestroy = false;
sprender.enabled = false;
StartCoroutine(CooldownTimer());
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Wall" && canDestroy)
{
Destroy(collision.gameObject);
}
}
}
| 31.547368 | 118 | 0.617618 | [
"MIT"
] | HassaanAbbasi/Robo-Repair | Assets/Standard Assets/Scripts/Player/Upgrades/MetalFistUpgrade.cs | 2,999 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Management.V20190501.Outputs
{
[OutputType]
public sealed class OnErrorDeploymentExtendedResponse
{
/// <summary>
/// The deployment to be used on error case.
/// </summary>
public readonly string? DeploymentName;
/// <summary>
/// The state of the provisioning for the on error deployment.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
/// </summary>
public readonly string? Type;
[OutputConstructor]
private OnErrorDeploymentExtendedResponse(
string? deploymentName,
string provisioningState,
string? type)
{
DeploymentName = deploymentName;
ProvisioningState = provisioningState;
Type = type;
}
}
}
| 29.72093 | 109 | 0.640845 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Management/V20190501/Outputs/OnErrorDeploymentExtendedResponse.cs | 1,278 | C# |
using System;
using System.Collections.Generic;
using Comet.Samples.Models;
namespace Comet.Samples
{
public class ListViewSample1 : View
{
//This should come from a database or something
List<Song> Songs = new List<Song> {
new Song {
Title = "All the Small Things",
Artist = "Blink-182",
Album = "Greatest Hits",
ArtworkUrl = "http://lh3.googleusercontent.com/9Ofo9ZHQODFvahjpq2ZVUUOog4v5J1c4Gw9qjTw-KADTQZ6sG98GA1732mZA165RBoyxfoMblA"
},
new Song {
Title = "Monster",
Artist = "Skillet",
Album = "Awake",
ArtworkUrl = "http://lh3.googleusercontent.com/uhjRXO19CiZbT46srdXSM-lQ8xCsurU-xaVg6lvJvNy8TisdjlaHrHsBwcWAzpu_vkKXAA9SdbA",
}
};
[Body]
View body() => new ListView<Song>(Songs)
{
ViewFor = (song) => new HStack
{
new Image (song.ArtworkUrl).Frame(52, 52).Margin(4),
new VStack(HorizontalAlignment.Leading, spacing:2)
{
new Text (song.Title).FontSize(17),
new Text (song.Artist).Color(Color.Grey),
new Text (song.Album).Color(Color.Grey),
}.FontSize(12)
}.Frame(height: 60, alignment: Alignment.Leading),
}.OnSelectedNavigate((song) => new ListViewDetails(song));
}
}
| 28.731707 | 128 | 0.687606 | [
"MIT"
] | davidwengier/Comet | sample/Comet.Samples/ListViewSample1.cs | 1,180 | C# |
namespace FreshBooks.Api.EstimateList {
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class request {
private byte client_idField;
private System.DateTime date_fromField;
private System.DateTime date_toField;
private byte pageField;
private byte per_pageField;
private string folderField;
private string methodField = "estimate.list";
/// <remarks/>
public byte client_id {
get {
return this.client_idField;
}
set {
this.client_idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
public System.DateTime date_from {
get {
return this.date_fromField;
}
set {
this.date_fromField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date")]
public System.DateTime date_to {
get {
return this.date_toField;
}
set {
this.date_toField = value;
}
}
/// <remarks/>
public byte page {
get {
return this.pageField;
}
set {
this.pageField = value;
}
}
/// <remarks/>
public byte per_page {
get {
return this.per_pageField;
}
set {
this.per_pageField = value;
}
}
/// <remarks/>
public string folder {
get {
return this.folderField;
}
set {
this.folderField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string method {
get {
return this.methodField;
}
set {
this.methodField = value;
}
}
}
}
| 25.745098 | 79 | 0.472963 | [
"MIT"
] | mattjcowan/FreshBooks.Api | src/FreshBooks.Api/EstimateListRequest.cs | 2,628 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace PromiseTechnology.DesktopTiles {
public partial class RefreshEditor : UserControl {
private CPUTile _Tile;
public RefreshEditor() {
InitializeComponent();
}
public RefreshEditor(CPUTile tile) : this() {
_Tile = tile;
textBox1.Text = _Tile.RefreshRate.ToString();
textBox1.Focus();
}
private void textBox1_TextChanged(object sender, EventArgs e) {
int result = 0;
if (int.TryParse(textBox1.Text, out result)) {
if (result > 0 && result < 10000) {
_Tile.RefreshRate = result;
}
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
DesktopTiles.ContextMenu.Close();
}
}
}
}
| 27.142857 | 71 | 0.592982 | [
"MIT"
] | ntindle/CPUTile | RefreshEditor.cs | 1,142 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace LiveSplit.Celeste {
public static class MemoryReader {
private static Dictionary<int, Module64[]> ModuleCache = new Dictionary<int, Module64[]>();
public static bool is64Bit;
public static void Update64Bit(Process program) {
is64Bit = program.Is64Bit();
}
public static T Read<T>(this Process targetProcess, IntPtr address, params int[] offsets) where T : unmanaged {
if (targetProcess == null || address == IntPtr.Zero) { return default(T); }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return default(T); }
unsafe {
int size = sizeof(T);
if (typeof(T) == typeof(IntPtr)) { size = is64Bit ? 8 : 4; }
byte[] buffer = Read(targetProcess, address + last, size);
fixed (byte* ptr = buffer) {
return *(T*)ptr;
}
}
}
public static byte[] Read(this Process targetProcess, IntPtr address, int numBytes) {
byte[] buffer = new byte[numBytes];
if (targetProcess == null || address == IntPtr.Zero) { return buffer; }
int bytesRead;
WinAPI.ReadProcessMemory(targetProcess.Handle, address, buffer, numBytes, out bytesRead);
return buffer;
}
public static byte[] Read(this Process targetProcess, IntPtr address, int numBytes, params int[] offsets) {
byte[] buffer = new byte[numBytes];
if (targetProcess == null || address == IntPtr.Zero) { return buffer; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return buffer; }
int bytesRead;
WinAPI.ReadProcessMemory(targetProcess.Handle, address + last, buffer, numBytes, out bytesRead);
return buffer;
}
public static string ReadString(this Process targetProcess, IntPtr address) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int length = Read<int>(targetProcess, address, 0x4);
if (length < 0 || length > 2048) { return string.Empty; }
return Encoding.Unicode.GetString(Read(targetProcess, address + 0x8, 2 * length));
}
public static string ReadString(this Process targetProcess, IntPtr address, params int[] offsets) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return string.Empty; }
return ReadString(targetProcess, address + last);
}
public static string ReadAscii(this Process targetProcess, IntPtr address) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
StringBuilder sb = new StringBuilder();
byte[] data = new byte[128];
int bytesRead;
int offset = 0;
bool invalid = false;
do {
WinAPI.ReadProcessMemory(targetProcess.Handle, address + offset, data, 128, out bytesRead);
int i = 0;
while (i < bytesRead) {
byte d = data[i++];
if (d == 0) {
i--;
break;
} else if (d > 127) {
invalid = true;
break;
}
}
if (i > 0) {
sb.Append(Encoding.ASCII.GetString(data, 0, i));
}
if (i < bytesRead || invalid) {
break;
}
offset += 128;
} while (bytesRead > 0);
return invalid ? string.Empty : sb.ToString();
}
public static string ReadAscii(this Process targetProcess, IntPtr address, params int[] offsets) {
if (targetProcess == null || address == IntPtr.Zero) { return string.Empty; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return string.Empty; }
return ReadAscii(targetProcess, address + last);
}
public static void Write<T>(this Process targetProcess, IntPtr address, T value, params int[] offsets) where T : unmanaged {
if (targetProcess == null) { return; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return; }
byte[] buffer;
unsafe {
buffer = new byte[sizeof(T)];
fixed (byte* bufferPtr = buffer) {
Buffer.MemoryCopy(&value, bufferPtr, sizeof(T), sizeof(T));
}
}
int bytesWritten;
WinAPI.WriteProcessMemory(targetProcess.Handle, address + last, buffer, buffer.Length, out bytesWritten);
}
public static void Write(this Process targetProcess, IntPtr address, byte[] value, params int[] offsets) {
if (targetProcess == null) { return; }
int last = OffsetAddress(targetProcess, ref address, offsets);
if (address == IntPtr.Zero) { return; }
int bytesWritten;
WinAPI.WriteProcessMemory(targetProcess.Handle, address + last, value, value.Length, out bytesWritten);
}
private static int OffsetAddress(this Process targetProcess, ref IntPtr address, params int[] offsets) {
byte[] buffer = new byte[is64Bit ? 8 : 4];
int bytesRead;
for (int i = 0; i < offsets.Length - 1; i++) {
WinAPI.ReadProcessMemory(targetProcess.Handle, address + offsets[i], buffer, buffer.Length, out bytesRead);
if (is64Bit) {
address = (IntPtr)BitConverter.ToUInt64(buffer, 0);
} else {
address = (IntPtr)BitConverter.ToUInt32(buffer, 0);
}
if (address == IntPtr.Zero) { break; }
}
return offsets.Length > 0 ? offsets[offsets.Length - 1] : 0;
}
public static bool Is64Bit(this Process process) {
if (process == null) { return false; }
bool flag;
WinAPI.IsWow64Process(process.Handle, out flag);
return Environment.Is64BitOperatingSystem && !flag;
}
public static Module64 MainModule64(this Process p) {
Module64[] modules = p.Modules64();
return modules == null || modules.Length == 0 ? null : modules[0];
}
public static Module64 Module64(this Process p, string moduleName) {
Module64[] modules = p.Modules64();
if (modules != null) {
for (int i = 0; i < modules.Length; i++) {
Module64 module = modules[i];
if (module.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) {
return module;
}
}
}
return null;
}
public static Module64[] Modules64(this Process p) {
lock (ModuleCache) {
if (ModuleCache.Count > 100) { ModuleCache.Clear(); }
IntPtr[] buffer = new IntPtr[1024];
uint cb = (uint)(IntPtr.Size * buffer.Length);
uint totalModules;
if (!WinAPI.EnumProcessModulesEx(p.Handle, buffer, cb, out totalModules, 3u)) {
return null;
}
uint moduleSize = totalModules / (uint)IntPtr.Size;
int key = p.StartTime.GetHashCode() + p.Id + (int)moduleSize;
if (ModuleCache.ContainsKey(key)) { return ModuleCache[key]; }
List<Module64> list = new List<Module64>();
StringBuilder stringBuilder = new StringBuilder(260);
int count = 0;
while ((long)count < (long)((ulong)moduleSize)) {
stringBuilder.Clear();
if (WinAPI.GetModuleFileNameEx(p.Handle, buffer[count], stringBuilder, (uint)stringBuilder.Capacity) == 0u) {
return list.ToArray();
}
string fileName = stringBuilder.ToString();
stringBuilder.Clear();
if (WinAPI.GetModuleBaseName(p.Handle, buffer[count], stringBuilder, (uint)stringBuilder.Capacity) == 0u) {
return list.ToArray();
}
string moduleName = stringBuilder.ToString();
ModuleInfo modInfo = default(ModuleInfo);
if (!WinAPI.GetModuleInformation(p.Handle, buffer[count], out modInfo, (uint)Marshal.SizeOf(modInfo))) {
return list.ToArray();
}
list.Add(new Module64 {
FileName = fileName,
BaseAddress = modInfo.BaseAddress,
MemorySize = (int)modInfo.ModuleSize,
EntryPointAddress = modInfo.EntryPoint,
Name = moduleName
});
count++;
}
ModuleCache.Add(key, list.ToArray());
return list.ToArray();
}
}
}
internal static class WinAPI {
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool wow64Process);
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumProcessModulesEx(IntPtr hProcess, [Out] IntPtr[] lphModule, uint cb, out uint lpcbNeeded, uint dwFilterFlag);
[DllImport("psapi.dll", SetLastError = true)]
public static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, uint nSize);
[DllImport("psapi.dll")]
public static extern uint GetModuleBaseName(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, uint nSize);
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out ModuleInfo lpmodinfo, uint cb);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MemInfo lpBuffer, int dwLength);
}
public class Module64 {
public IntPtr BaseAddress { get; set; }
public IntPtr EntryPointAddress { get; set; }
public string FileName { get; set; }
public int MemorySize { get; set; }
public string Name { get; set; }
public FileVersionInfo FileVersionInfo { get { return FileVersionInfo.GetVersionInfo(FileName); } }
public override string ToString() {
return Name ?? base.ToString();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ModuleInfo {
public IntPtr BaseAddress;
public uint ModuleSize;
public IntPtr EntryPoint;
}
[StructLayout(LayoutKind.Sequential)]
public struct MemInfo {
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
public override string ToString() {
return BaseAddress.ToString("X") + " " + Protect.ToString("X") + " " + State.ToString("X") + " " + Type.ToString("X") + " " + RegionSize.ToString("X");
}
}
public class MemorySearcher {
private const int BUFFER_SIZE = 2097152;
private List<MemInfo> memoryInfo = new List<MemInfo>();
private byte[] buffer = new byte[BUFFER_SIZE];
public Func<MemInfo, bool> MemoryFilter = delegate (MemInfo info) {
return (info.State & 0x1000) != 0 && (info.Protect & 0x100) == 0;
};
public int ReadMemory(Process process, int index, int startIndex, out int bytesRead) {
MemInfo info = memoryInfo[index];
int returnIndex = -1;
int amountToRead = (int)((uint)info.RegionSize - (uint)startIndex);
if (amountToRead > BUFFER_SIZE) {
returnIndex = startIndex + BUFFER_SIZE;
amountToRead = BUFFER_SIZE;
}
WinAPI.ReadProcessMemory(process.Handle, info.BaseAddress + startIndex, buffer, amountToRead, out bytesRead);
return returnIndex;
}
public IntPtr FindSignature(Process process, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
GetMemoryInfo(process.Handle);
int[] offsets = GetCharacterOffsets(pattern, mask);
for (int i = 0; i < memoryInfo.Count; i++) {
MemInfo info = memoryInfo[i];
int index = 0;
do {
int previousIndex = index;
int bytesRead;
index = ReadMemory(process, i, index, out bytesRead);
int result = ScanMemory(buffer, bytesRead, pattern, mask, offsets);
if (result != int.MinValue) {
return info.BaseAddress + result + previousIndex;
}
if (index > 0) { index -= pattern.Length - 1; }
} while (index > 0);
}
return IntPtr.Zero;
}
public List<IntPtr> FindSignatures(Process process, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
GetMemoryInfo(process.Handle);
int[] offsets = GetCharacterOffsets(pattern, mask);
List<IntPtr> pointers = new List<IntPtr>();
for (int i = 0; i < memoryInfo.Count; i++) {
MemInfo info = memoryInfo[i];
int index = 0;
do {
int previousIndex = index;
int bytesRead;
index = ReadMemory(process, i, index, out bytesRead);
info.BaseAddress += previousIndex;
ScanMemory(pointers, info, buffer, bytesRead, pattern, mask, offsets);
info.BaseAddress -= previousIndex;
if (index > 0) { index -= pattern.Length - 1; }
} while (index > 0);
}
return pointers;
}
public bool VerifySignature(Process process, IntPtr pointer, string signature) {
byte[] pattern;
bool[] mask;
GetSignature(signature, out pattern, out mask);
int[] offsets = GetCharacterOffsets(pattern, mask);
MemInfo memInfoStart = default(MemInfo);
MemInfo memInfoEnd = default(MemInfo);
if (WinAPI.VirtualQueryEx(process.Handle, pointer, out memInfoStart, Marshal.SizeOf(memInfoStart)) == 0 ||
WinAPI.VirtualQueryEx(process.Handle, pointer + pattern.Length, out memInfoEnd, Marshal.SizeOf(memInfoStart)) == 0 ||
memInfoStart.BaseAddress != memInfoEnd.BaseAddress || !MemoryFilter(memInfoStart)) {
return false;
}
byte[] buff = new byte[pattern.Length];
int bytesRead;
WinAPI.ReadProcessMemory(process.Handle, pointer, buff, buff.Length, out bytesRead);
return ScanMemory(buff, buff.Length, pattern, mask, offsets) == 0;
}
public void GetMemoryInfo(IntPtr pHandle) {
memoryInfo.Clear();
IntPtr current = (IntPtr)65536;
while (true) {
MemInfo memInfo = new MemInfo();
int dump = WinAPI.VirtualQueryEx(pHandle, current, out memInfo, Marshal.SizeOf(memInfo));
if (dump == 0) { break; }
long regionSize = (long)memInfo.RegionSize;
if (regionSize <= 0 || (int)regionSize != regionSize) {
if (MemoryReader.is64Bit) {
current = (IntPtr)((ulong)memInfo.BaseAddress + (ulong)memInfo.RegionSize);
continue;
}
break;
}
if (MemoryFilter(memInfo)) {
memoryInfo.Add(memInfo);
}
current = memInfo.BaseAddress + (int)regionSize;
}
}
private int ScanMemory(byte[] data, int dataLength, byte[] search, bool[] mask, int[] offsets) {
int current = 0;
int end = search.Length - 1;
while (current <= dataLength - search.Length) {
for (int i = end; data[current + i] == search[i] || mask[i]; i--) {
if (i == 0) {
return current;
}
}
int offset = offsets[data[current + end]];
current += offset;
}
return int.MinValue;
}
private void ScanMemory(List<IntPtr> pointers, MemInfo info, byte[] data, int dataLength, byte[] search, bool[] mask, int[] offsets) {
int current = 0;
int end = search.Length - 1;
while (current <= dataLength - search.Length) {
for (int i = end; data[current + i] == search[i] || mask[i]; i--) {
if (i == 0) {
pointers.Add(info.BaseAddress + current);
break;
}
}
int offset = offsets[data[current + end]];
current += offset;
}
}
private int[] GetCharacterOffsets(byte[] search, bool[] mask) {
int[] offsets = new int[256];
int unknown = 0;
int end = search.Length - 1;
for (int i = 0; i < end; i++) {
if (!mask[i]) {
offsets[search[i]] = end - i;
} else {
unknown = end - i;
}
}
if (unknown == 0) {
unknown = search.Length;
}
for (int i = 0; i < 256; i++) {
int offset = offsets[i];
if (unknown < offset || offset == 0) {
offsets[i] = unknown;
}
}
return offsets;
}
private void GetSignature(string searchString, out byte[] pattern, out bool[] mask) {
int length = searchString.Length >> 1;
pattern = new byte[length];
mask = new bool[length];
length <<= 1;
for (int i = 0, j = 0; i < length; i++) {
byte temp = (byte)(((int)searchString[i] - 0x30) & 0x1F);
pattern[j] |= temp > 0x09 ? (byte)(temp - 7) : temp;
if (searchString[i] == '?') {
mask[j] = true;
pattern[j] = 0;
}
if ((i & 1) == 1) {
j++;
} else {
pattern[j] <<= 4;
}
}
}
}
} | 45.365471 | 163 | 0.53388 | [
"MIT"
] | ShootMe/LiveSplit.Celeste | MemoryReader.cs | 20,235 | C# |
using Uno.UI.Samples.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
#if NETFX_CORE
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
#elif HAS_UNO
using Windows.UI.Xaml.Controls;
using System.Globalization;
#endif
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace Uno.UI.Samples.UITests.BorderTestsControl
{
[SampleControlInfo("Border", "AutoBorderStretchwithtopmargin")]
public sealed partial class AutoBorderStretchwithtopmargin : UserControl
{
public AutoBorderStretchwithtopmargin()
{
this.InitializeComponent();
}
}
}
| 25.777778 | 96 | 0.806034 | [
"Apache-2.0"
] | 06needhamt/uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/BorderTests/AutoBorderStretchwithtopmargin.xaml.cs | 928 | C# |
namespace SIS.Framework.Utilities
{
public static class ControllerUtilities
{
public static string GetControllerName(object controller)
{
return controller.GetType()
.Name
.Replace(MvcContext.Get.ControllersSuffix, string.Empty);
}
}
}
| 24.384615 | 73 | 0.605678 | [
"MIT"
] | KolyaPetrova/SoftUni--CSharp-Web | C# Web Development Basics/11. Exam Preparations/1. Mish-Mash/SIS.Framework/Utilities/ControllerUtilities.cs | 319 | C# |
using UnityEngine;
using System.Collections;
public class WallGame : IGame
{
public void Begin(IHost host)
{
host.RelocateTargets();
host.UpdatePoseTime(HoleConfiguration.INSTANCE.SkillTime, -1);
}
public void Update(IHost host, float timeRemaining, float poseTime)
{
if (poseTime == 0)
{
if (host.Aligned())
{
host.Pulse();
host.AddScore(1);
}
if (timeRemaining > 0)
{
host.RelocateTargets();
host.UpdatePoseTime(HoleConfiguration.INSTANCE.SkillTime, -1);
}
else
{
host.StopGame();
}
}
}
public void End(IHost host)
{
}
}
| 20.333333 | 78 | 0.486759 | [
"MIT",
"CC0-1.0",
"Unlicense"
] | sixtostart/walls | Assets/Games/WallGame.cs | 795 | C# |
namespace Sims1WidescreenPatcher.Far.Models
{
public interface IJob
{
byte[] Bytes { get; set; }
string Output { get; set; }
int Width { get; set; }
int Height { get; set; }
void Extract();
}
} | 22.363636 | 44 | 0.536585 | [
"MIT"
] | FaithBeam/Sims-1-Complete-Collection-Widescreen-Patcher | Sims1WidescreenPatcher.Far/Models/IJob.cs | 248 | C# |
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace CommandLineDotnetCore.Text
{
/// <summary>
/// Models a command line usage example.
/// </summary>
public sealed class Example : IEquatable<Example>
{
private readonly string helpText;
private readonly IEnumerable<UnParserSettings> formatStyles;
private readonly object sample;
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.Example"/> class.
/// </summary>
/// <param name="helpText">Example description.</param>
/// <param name="formatStyles">A <see cref="CommandLine.UnParserSettings"/> instances sequence that defines command line arguments format.</param>
/// <param name="sample">A sample instance.</param>
public Example(string helpText, IEnumerable<UnParserSettings> formatStyles, object sample)
{
if (string.IsNullOrEmpty(helpText)) throw new ArgumentException("helpText can't be null or empty", "helpText");
if (formatStyles == null) throw new ArgumentNullException("formatStyles");
if (sample == null) throw new ArgumentNullException("sample");
this.helpText = helpText;
this.formatStyles = formatStyles;
this.sample = sample;
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.Example"/> class.
/// </summary>
/// <param name="helpText">Example description.</param>
/// <param name="formatStyle">A <see cref="CommandLine.UnParserSettings"/> instance that defines command line arguments format.</param>
/// <param name="sample">A sample instance.</param>
public Example(string helpText, UnParserSettings formatStyle, object sample)
: this(helpText, new[] { formatStyle }, sample)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CommandLine.Text.Example"/> class.
/// </summary>
/// <param name="helpText">Example description.</param>
/// <param name="sample">A sample instance.</param>
public Example(string helpText, object sample)
: this(helpText, Enumerable.Empty<UnParserSettings>(), sample)
{
}
/// <summary>
/// Example description.
/// </summary>
public string HelpText
{
get { return helpText; }
}
/// <summary>
/// A sequence of format styles.
/// </summary>
public IEnumerable<UnParserSettings> FormatStyles
{
get { return this.formatStyles; }
}
/// <summary>
/// A sample instance.
/// </summary>
public object Sample
{
get { return sample; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="System.Object"/>.</param>
/// <returns><value>true</value> if the specified <see cref="System.Object"/> is equal to the current <see cref="System.Object"/>; otherwise, <value>false</value>.</returns>
public override bool Equals(object obj)
{
var other = obj as Example;
if (other != null)
{
return Equals(other);
}
return base.Equals(obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <remarks>A hash code for the current <see cref="System.Object"/>.</remarks>
public override int GetHashCode()
{
return new { HelpText, FormatStyles, Sample }.GetHashCode();
}
/// <summary>
/// Returns a value that indicates whether the current instance and a specified <see cref="CommandLine.Text.Example"/> have the same value.
/// </summary>
/// <param name="other">The <see cref="CommandLine.Text.Example"/> instance to compare.</param>
/// <returns><value>true</value> if this instance of <see cref="CommandLine.Text.Example"/> and <paramref name="other"/> have the same value; otherwise, <value>false</value>.</returns>
public bool Equals(Example other)
{
if (other == null)
{
return false;
}
return HelpText.Equals(other.HelpText)
&& FormatStyles.SequenceEqual(other.FormatStyles)
&& Sample.Equals(other.Sample);
}
}
static class ExampleExtensions
{
public static IEnumerable<UnParserSettings> GetFormatStylesOrDefault(this Example example)
{
return example.FormatStyles.Any()
? example.FormatStyles
: new[] { new UnParserSettings { Consumed = true } };
}
}
}
| 39.165414 | 192 | 0.591092 | [
"MIT"
] | sfspacov/CommandLineDotnetCore | Text/Example.cs | 5,211 | C# |
// ------------------------------------------------------------------
// Copyright (c) Microsoft. All Rights Reserved.
// ------------------------------------------------------------------
namespace Microsoft.ServiceFabric.Common
{
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A strongly-typed chunk of a paged dataset.
/// </summary>
/// <typeparam name="T"><see cref="System.Type"/> of the items this PagedData contains.</typeparam>
public class PagedData<T>
{
private static readonly PagedData<T> EmptyPagedData = new PagedData<T>(ContinuationToken.Empty, Enumerable.Empty<T>());
/// <summary>
/// Initializes a new instance of the <see cref="PagedData{T}"/> class.
/// </summary>
/// <param name="continuationToken">Continuation Token.</param>
/// <param name="data">List of data.</param>
public PagedData(ContinuationToken continuationToken, IEnumerable<T> data)
{
this.ContinuationToken = continuationToken;
this.Data = data;
}
/// <summary>
/// Gets an empty PagedData class.
/// </summary>
public static PagedData<T> Empty
{
get
{
return EmptyPagedData;
}
}
/// <summary>
/// Gets a ContinuationToken to get the next set of paged data.
/// </summary>
/// <value><see cref="Microsoft.ServiceFabric.Common.ContinuationToken"/> to get the next set of paged data.</value>
public ContinuationToken ContinuationToken { get; }
/// <summary>
/// Gets a segment of data returned in this page of the total dataset.
/// </summary>
/// <value>Enumerator, which supports a simple iteration over the data.</value>
public IEnumerable<T> Data { get; }
}
}
| 35.886792 | 127 | 0.547844 | [
"MIT"
] | aL3891/service-fabric-client-dotnet | src/Microsoft.ServiceFabric.Common/PagedData.cs | 1,904 | C# |
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Reports;
namespace LinqToDB.Benchmarks
{
public static class Config
{
public static IConfig Instance { get; } = Create();
private static IConfig Create()
{
var net472 = Job.Default.WithRuntime(ClrRuntime.Net472).WithDefault().AsBaseline();
var core21 = Job.Default.WithRuntime(CoreRuntime.Core21).WithDefault();
var core31 = Job.Default.WithRuntime(CoreRuntime.Core31).WithDefault();
return new ManualConfig()
.AddLogger (DefaultConfig.Instance.GetLoggers ().ToArray())
.AddAnalyser (DefaultConfig.Instance.GetAnalysers ().ToArray())
.AddValidator (DefaultConfig.Instance.GetValidators ().ToArray())
.AddColumnProvider (DefaultConfig.Instance.GetColumnProviders().Select(p => new FilteredColumnProvider(p)).ToArray())
.WithOptions (ConfigOptions.DisableLogFile)
.AddExporter (MarkdownExporter.GitHub)
.AddDiagnoser (MemoryDiagnoser.Default)
.WithArtifactsPath (@"..\..\..")
.AddJob (net472, core21, core31);
}
private static Job WithDefault(this Job job)
{
return job.WithJit(Jit.RyuJit)
.WithPlatform(Platform.X64);
//.WithWarmupCount(2)
//.WithMinIterationCount(3)
//.WithMaxIterationCount(6);
}
class FilteredColumnProvider : IColumnProvider
{
private readonly IColumnProvider _provider;
public FilteredColumnProvider(IColumnProvider provider)
{
_provider = provider;
}
IEnumerable<IColumn> IColumnProvider.GetColumns(Summary summary)
{
return _provider
.GetColumns(summary)
// Job is not useful at all, other columns could be enabled later if somebody will find them useful
.Where(c => c.ColumnName != "Job"
&& c.ColumnName != "Error"
&& c.ColumnName != "StdDev"
&& c.ColumnName != "RatioSD");
}
}
}
}
| 33.276923 | 122 | 0.684697 | [
"MIT"
] | Edward-Alchikha/linq2db | Tests/Tests.Benchmarks/Config.cs | 2,101 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Bot.Connector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft Bot Framework")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9f1a81ee-c6fe-474e-a3e2-c581435d55bf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("3.5.3.0")]
[assembly: AssemblyFileVersion("3.5.3.0")]
| 40.457143 | 85 | 0.734463 | [
"MIT"
] | haritha91/BotBuilder | CSharp/Library/Microsoft.Bot.Connector.NetFramework/Properties/AssemblyInfo.cs | 1,419 | C# |
using System;
namespace TheDefenseofCosolas
{
class Program
{
static void Main(string[] args)
{
/*
Objectives:
Ask the user for the target row and column.
Compute the neighboring rows and columns of where to deploy the squad
Display the deployment instructions in a different color of your choosing.
Change the window title to be "Defense of Consolas"
Play a sound with Console.Beep when the results have been computed and displayed
*/
Console.Title = "Defense of Consolas";
Console.Write("Targe Row? ");
int row = Convert.ToInt32(Console.ReadLine());
Console.Write("Target Column? ");
int column = Convert.ToInt32(Console.ReadLine());
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Deploy to:");
Console.WriteLine($"{row}, {column - 1}");
Console.WriteLine($"{row - 1}, {column}");
Console.WriteLine($"{row}, {column + 1}");
Console.WriteLine($"{row + 1}, {column}");
Console.Beep(440, 1000);
}
}
}
| 35.054054 | 96 | 0.55744 | [
"MIT"
] | bofur24/TheCSharpPlayersGuide | Challenges/TheDefenseofCosolas/Program.cs | 1,299 | C# |
#pragma checksum "..\..\..\Views\MainView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4B65D1118399A068EB6A3A5CAD7A5C7432C85D7C"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using DevExpress.Core;
using DevExpress.Mvvm;
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Core.ConditionalFormatting;
using DevExpress.Xpf.Core.DataSources;
using DevExpress.Xpf.Core.Serialization;
using DevExpress.Xpf.Core.ServerMode;
using DevExpress.Xpf.DXBinding;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Grid.ConditionalFormatting;
using DevExpress.Xpf.Grid.LookUp;
using DevExpress.Xpf.Grid.TreeList;
using Gamma;
using Gamma.Common;
using Gamma.ViewModels;
using Gamma.Views;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Gamma {
/// <summary>
/// MainView
/// </summary>
public partial class MainView : System.Windows.Window, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/Gamma;component/views/mainview.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Views\MainView.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) {
return System.Delegate.CreateDelegate(delegateType, this, handler);
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 39.534653 | 141 | 0.697471 | [
"Unlicense"
] | Polimat/Gamma | obj/Release/Views/MainView.g.cs | 3,995 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.PrivateDns
{
/// <summary>
/// Enables you to manage Private DNS zone Virtual Network Links. These Links enable DNS resolution and registration inside Azure Virtual Networks using Azure Private DNS.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Azure = Pulumi.Azure;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs
/// {
/// Location = "West US",
/// });
/// var exampleZone = new Azure.PrivateDns.Zone("exampleZone", new Azure.PrivateDns.ZoneArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// });
/// var exampleZoneVirtualNetworkLink = new Azure.PrivateDns.ZoneVirtualNetworkLink("exampleZoneVirtualNetworkLink", new Azure.PrivateDns.ZoneVirtualNetworkLinkArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// PrivateDnsZoneName = exampleZone.Name,
/// VirtualNetworkId = azurerm_virtual_network.Example.Id,
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Private DNS Zone Virtual Network Links can be imported using the `resource id`, e.g.
///
/// ```sh
/// $ pulumi import azure:privatedns/zoneVirtualNetworkLink:ZoneVirtualNetworkLink link1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/privateDnsZones/zone1.com/virtualNetworkLinks/myVnetLink1
/// ```
/// </summary>
public partial class ZoneVirtualNetworkLink : Pulumi.CustomResource
{
/// <summary>
/// The name of the Private DNS Zone Virtual Network Link. Changing this forces a new resource to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The name of the Private DNS zone (without a terminating dot). Changing this forces a new resource to be created.
/// </summary>
[Output("privateDnsZoneName")]
public Output<string> PrivateDnsZoneName { get; private set; } = null!;
/// <summary>
/// Is auto-registration of virtual machine records in the virtual network in the Private DNS zone enabled? Defaults to `false`.
/// </summary>
[Output("registrationEnabled")]
public Output<bool?> RegistrationEnabled { get; private set; } = null!;
/// <summary>
/// Specifies the resource group where the Private DNS Zone exists. Changing this forces a new resource to be created.
/// </summary>
[Output("resourceGroupName")]
public Output<string> ResourceGroupName { get; private set; } = null!;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The ID of the Virtual Network that should be linked to the DNS Zone. Changing this forces a new resource to be created.
/// </summary>
[Output("virtualNetworkId")]
public Output<string> VirtualNetworkId { get; private set; } = null!;
/// <summary>
/// Create a ZoneVirtualNetworkLink resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ZoneVirtualNetworkLink(string name, ZoneVirtualNetworkLinkArgs args, CustomResourceOptions? options = null)
: base("azure:privatedns/zoneVirtualNetworkLink:ZoneVirtualNetworkLink", name, args ?? new ZoneVirtualNetworkLinkArgs(), MakeResourceOptions(options, ""))
{
}
private ZoneVirtualNetworkLink(string name, Input<string> id, ZoneVirtualNetworkLinkState? state = null, CustomResourceOptions? options = null)
: base("azure:privatedns/zoneVirtualNetworkLink:ZoneVirtualNetworkLink", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ZoneVirtualNetworkLink resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ZoneVirtualNetworkLink Get(string name, Input<string> id, ZoneVirtualNetworkLinkState? state = null, CustomResourceOptions? options = null)
{
return new ZoneVirtualNetworkLink(name, id, state, options);
}
}
public sealed class ZoneVirtualNetworkLinkArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the Private DNS Zone Virtual Network Link. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the Private DNS zone (without a terminating dot). Changing this forces a new resource to be created.
/// </summary>
[Input("privateDnsZoneName", required: true)]
public Input<string> PrivateDnsZoneName { get; set; } = null!;
/// <summary>
/// Is auto-registration of virtual machine records in the virtual network in the Private DNS zone enabled? Defaults to `false`.
/// </summary>
[Input("registrationEnabled")]
public Input<bool>? RegistrationEnabled { get; set; }
/// <summary>
/// Specifies the resource group where the Private DNS Zone exists. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// The ID of the Virtual Network that should be linked to the DNS Zone. Changing this forces a new resource to be created.
/// </summary>
[Input("virtualNetworkId", required: true)]
public Input<string> VirtualNetworkId { get; set; } = null!;
public ZoneVirtualNetworkLinkArgs()
{
}
}
public sealed class ZoneVirtualNetworkLinkState : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the Private DNS Zone Virtual Network Link. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the Private DNS zone (without a terminating dot). Changing this forces a new resource to be created.
/// </summary>
[Input("privateDnsZoneName")]
public Input<string>? PrivateDnsZoneName { get; set; }
/// <summary>
/// Is auto-registration of virtual machine records in the virtual network in the Private DNS zone enabled? Defaults to `false`.
/// </summary>
[Input("registrationEnabled")]
public Input<bool>? RegistrationEnabled { get; set; }
/// <summary>
/// Specifies the resource group where the Private DNS Zone exists. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName")]
public Input<string>? ResourceGroupName { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// The ID of the Virtual Network that should be linked to the DNS Zone. Changing this forces a new resource to be created.
/// </summary>
[Input("virtualNetworkId")]
public Input<string>? VirtualNetworkId { get; set; }
public ZoneVirtualNetworkLinkState()
{
}
}
}
| 42.642241 | 255 | 0.616092 | [
"ECL-2.0",
"Apache-2.0"
] | suresh198526/pulumi-azure | sdk/dotnet/PrivateDns/ZoneVirtualNetworkLink.cs | 9,893 | C# |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using netcore_rest_api.Models;
namespace netcore_rest_api.Data {
public class ApiDbContext : IdentityDbContext {
public virtual DbSet<ItemData> Items { get; set; }
public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) {
}
}
}
| 25.785714 | 81 | 0.778393 | [
"MIT"
] | dmfabritius/netcore-rest-api | Data/ApiDbContext.cs | 361 | C# |
namespace Dotnet9.Application.Contracts;
public class EntityDto
{
public int Id { get; set; }
public override string ToString()
{
return $"[DTO: {GetType().Name}] Id = {Id}";
}
} | 18.636364 | 52 | 0.609756 | [
"MIT"
] | dotnet9/Dotnet9 | src/Dotnet9.Application.Contracts/EntityDto.cs | 207 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OnvifVideoSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
address.GotFocus += InitTextbox;
user.GotFocus += InitTextbox;
password.GotFocus += InitTextbox;
button.Click += OnConnect;
}
private void TestThis()
{
//
//or "/onvif_device"));
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
var services = device.GetServices(false);
}
catch(Exception ex)
{
listBox.Items.Add(address.Text);
listBox.Items.Add("GetServices throw an exception:");
listBox.Items.Add(ex.Message);
}
string Model = "";
string FirmwareVersion = "";
string SerialNumber = "";
string HardwareId = "";
string returnDeviceInformation = "";
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
returnDeviceInformation = device.GetDeviceInformation(out Model, out FirmwareVersion, out SerialNumber, out HardwareId);
}
catch (Exception ex)
{
listBox.Items.Add(address.Text);
listBox.Items.Add("GetDeviceInformation throw an exception:");
listBox.Items.Add(ex.Message);
}
//OnvifVideoSample.device.RelayOutput[] outputnum = device.GetRelayOutputs();
listBox.Items.Add("Device under test: " + returnDeviceInformation);
listBox.Items.Add("Model: " + Model);
listBox.Items.Add("FW: " + FirmwareVersion);
listBox.Items.Add("SerialNumber: " + SerialNumber);
listBox.Items.Add("");
listBox.Items.Add("Result for GetSystemLog with \"Access\"");
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
device.SystemLog Log = device.GetSystemLog(OnvifVideoSample.device.SystemLogType.Access); //OnvifVideoSample.device.SystemLogType.Access
string output = "Log-String: " + Log.String;
listBox.Items.Add(output);
if (Log.Binary == null)
listBox.Items.Add("Log-Binary was NULL");
else
{
output = "Log-Binary" + Log.Binary;
listBox.Items.Add(output);
}
}
catch (Exception ex)
{
listBox.Items.Add("GetSystemLog with \"Access\" did throw an exception:");
listBox.Items.Add(ex.Message);
}
listBox.Items.Add("");
listBox.Items.Add("");
listBox.Items.Add("Result for GetSystemLog with \"System\"");
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
device.SystemLog Log = device.GetSystemLog(OnvifVideoSample.device.SystemLogType.System); //OnvifVideoSample.device.SystemLogType.Access
string output = "Log-String: " + Log.String;
listBox.Items.Add(output);
if (Log.Binary == null)
listBox.Items.Add("Log-Binary was NULL");
else
{
output = "Log-Binary" + Log.Binary;
listBox.Items.Add(output);
}
}
catch (Exception ex)
{
listBox.Items.Add("GetSystemLog with \"System\" did throw an exception: ");
listBox.Items.Add(ex.Message);
}
listBox.Items.Add("");
listBox.Items.Add("");
listBox.Items.Add("GetSystemSupportInformation TEST: ");
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
OnvifVideoSample.device.SupportInformation supportInfo = device.GetSystemSupportInformation();
listBox.Items.Add("SupportInformation got string: " + supportInfo.String);
}
catch (Exception ex)
{
listBox.Items.Add("GetSystemSupportInformation did throw an exception: ");
listBox.Items.Add(ex.Message);
}
listBox.Items.Add("");
listBox.Items.Add("");
listBox.Items.Add("GetSystemBackup TEST: ");
try
{
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
OnvifVideoSample.device.BackupFile[] backupFile = device.GetSystemBackup();
listBox.Items.Add("BackupFile did return.");
}
catch (Exception ex)
{
listBox.Items.Add("GetSystemBackup did throw an exception: ");
listBox.Items.Add(ex.Message);
}
listBox.Items.Add("");
listBox.Items.Add("");
listBox.Items.Add("GetSystemUris TEST: ");
try
{
string SupportInfoUri;
string SystemBackupUri;
var device = new device.DeviceClient(WsdlBinding, new EndpointAddress("http://" + address.Text + "/onvif/device_service"));
device.ClientCredentials.HttpDigest.ClientCredential.UserName = user.Text;
device.ClientCredentials.HttpDigest.ClientCredential.Password = password.Password;
device.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
OnvifVideoSample.device.GetSystemUrisResponseExtension Extension;
OnvifVideoSample.device.SystemLogUri[] systemUris = device.GetSystemUris(out SupportInfoUri, out SystemBackupUri, out Extension);
listBox.Items.Add("systemUris: " + systemUris);
listBox.Items.Add("SupportInfoUri: " + SupportInfoUri);
listBox.Items.Add("SystemBackupUri: " + SystemBackupUri);
listBox.Items.Add("Extension: " + Extension);
}
catch (Exception ex)
{
listBox.Items.Add("GetSystemUris did throw an exception: ");
listBox.Items.Add(ex.Message);
}
int b = 0;
}
private void OnConnect(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(address.Text))
{
TestThis();
}
}
private void InitTextbox(object sender, RoutedEventArgs e)
{
if (((sender as Control).Foreground as SolidColorBrush)?.Color == Colors.DarkGray) {
if (sender is TextBox) {
(sender as TextBox).Text = "";
}
else if (sender is PasswordBox) {
(sender as PasswordBox).Password = "";
}
(sender as Control).Foreground = new SolidColorBrush(Colors.Black);
}
}
System.ServiceModel.Channels.Binding WsdlBinding
{
get
{
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest;
return new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8), httpTransport);
}
}
}
}
| 42.186992 | 155 | 0.614087 | [
"MIT"
] | BigOtzelot/OnvifLogInfoTester | OnvifLogInfoTester/MainWindow.xaml.cs | 10,380 | C# |
namespace gamepad
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.yButtonImage = new System.Windows.Forms.PictureBox();
this.xButtonImage = new System.Windows.Forms.PictureBox();
this.bButtonImage = new System.Windows.Forms.PictureBox();
this.aButtonImage = new System.Windows.Forms.PictureBox();
this.rightImage = new System.Windows.Forms.PictureBox();
this.downImage = new System.Windows.Forms.PictureBox();
this.leftImage = new System.Windows.Forms.PictureBox();
this.upImage = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.yButtonImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xButtonImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bButtonImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.aButtonImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rightImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.downImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.leftImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.upImage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
this.SuspendLayout();
//
// yButtonImage
//
this.yButtonImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.yButtonImage.Image = global::gamepad.Properties.Resources.y;
this.yButtonImage.Location = new System.Drawing.Point(1084, 258);
this.yButtonImage.Name = "yButtonImage";
this.yButtonImage.Size = new System.Drawing.Size(128, 128);
this.yButtonImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.yButtonImage.TabIndex = 7;
this.yButtonImage.TabStop = false;
this.yButtonImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.yButtonPress);
//
// xButtonImage
//
this.xButtonImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.xButtonImage.Image = global::gamepad.Properties.Resources.x;
this.xButtonImage.Location = new System.Drawing.Point(950, 392);
this.xButtonImage.Name = "xButtonImage";
this.xButtonImage.Size = new System.Drawing.Size(128, 128);
this.xButtonImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.xButtonImage.TabIndex = 6;
this.xButtonImage.TabStop = false;
this.xButtonImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.xButtonPress);
//
// bButtonImage
//
this.bButtonImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bButtonImage.Image = global::gamepad.Properties.Resources.b;
this.bButtonImage.Location = new System.Drawing.Point(1218, 392);
this.bButtonImage.Name = "bButtonImage";
this.bButtonImage.Size = new System.Drawing.Size(128, 128);
this.bButtonImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.bButtonImage.TabIndex = 5;
this.bButtonImage.TabStop = false;
this.bButtonImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.bButtonPress);
//
// aButtonImage
//
this.aButtonImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.aButtonImage.Image = global::gamepad.Properties.Resources.a;
this.aButtonImage.Location = new System.Drawing.Point(1084, 526);
this.aButtonImage.Name = "aButtonImage";
this.aButtonImage.Size = new System.Drawing.Size(128, 128);
this.aButtonImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.aButtonImage.TabIndex = 4;
this.aButtonImage.TabStop = false;
this.aButtonImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.aButtonPress);
//
// rightImage
//
this.rightImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.rightImage.Image = global::gamepad.Properties.Resources.right;
this.rightImage.Location = new System.Drawing.Point(274, 392);
this.rightImage.Name = "rightImage";
this.rightImage.Size = new System.Drawing.Size(128, 128);
this.rightImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.rightImage.TabIndex = 3;
this.rightImage.TabStop = false;
this.rightImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.rightPress);
//
// downImage
//
this.downImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.downImage.Image = global::gamepad.Properties.Resources.down;
this.downImage.Location = new System.Drawing.Point(140, 526);
this.downImage.Name = "downImage";
this.downImage.Size = new System.Drawing.Size(128, 128);
this.downImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.downImage.TabIndex = 2;
this.downImage.TabStop = false;
this.downImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.downPress);
//
// leftImage
//
this.leftImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.leftImage.Image = global::gamepad.Properties.Resources.left;
this.leftImage.Location = new System.Drawing.Point(6, 392);
this.leftImage.Name = "leftImage";
this.leftImage.Size = new System.Drawing.Size(128, 128);
this.leftImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.leftImage.TabIndex = 1;
this.leftImage.TabStop = false;
this.leftImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.leftPress);
//
// upImage
//
this.upImage.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.upImage.Image = global::gamepad.Properties.Resources.up;
this.upImage.Location = new System.Drawing.Point(140, 258);
this.upImage.Name = "upImage";
this.upImage.Size = new System.Drawing.Size(128, 128);
this.upImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.upImage.TabIndex = 0;
this.upImage.TabStop = false;
this.upImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.upPress);
//
// pictureBox1
//
this.pictureBox1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.pictureBox1.Image = global::gamepad.Properties.Resources.menu;
this.pictureBox1.Location = new System.Drawing.Point(616, 526);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(128, 128);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 8;
this.pictureBox1.TabStop = false;
this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.menuButtonPress);
//
// pictureBox2
//
this.pictureBox2.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.pictureBox2.Image = global::gamepad.Properties.Resources.select;
this.pictureBox2.Location = new System.Drawing.Point(482, 526);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(128, 128);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox2.TabIndex = 9;
this.pictureBox2.TabStop = false;
this.pictureBox2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.selectButtonPress);
//
// pictureBox3
//
this.pictureBox3.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.pictureBox3.Image = global::gamepad.Properties.Resources.start;
this.pictureBox3.Location = new System.Drawing.Point(750, 526);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(128, 128);
this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox3.TabIndex = 10;
this.pictureBox3.TabStop = false;
this.pictureBox3.MouseDown += new System.Windows.Forms.MouseEventHandler(this.startButtonPress);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Magenta;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.ClientSize = new System.Drawing.Size(1348, 697);
this.Controls.Add(this.pictureBox3);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.yButtonImage);
this.Controls.Add(this.xButtonImage);
this.Controls.Add(this.bButtonImage);
this.Controls.Add(this.aButtonImage);
this.Controls.Add(this.rightImage);
this.Controls.Add(this.downImage);
this.Controls.Add(this.leftImage);
this.Controls.Add(this.upImage);
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.Name = "Form1";
this.Text = "Gamepad";
this.TopMost = true;
this.TransparencyKey = System.Drawing.Color.Magenta;
((System.ComponentModel.ISupportInitialize)(this.yButtonImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xButtonImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bButtonImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.aButtonImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rightImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.downImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.leftImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.upImage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox upImage;
private System.Windows.Forms.PictureBox leftImage;
private System.Windows.Forms.PictureBox downImage;
private System.Windows.Forms.PictureBox rightImage;
private System.Windows.Forms.PictureBox aButtonImage;
private System.Windows.Forms.PictureBox bButtonImage;
private System.Windows.Forms.PictureBox xButtonImage;
private System.Windows.Forms.PictureBox yButtonImage;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox3;
}
}
| 57.26971 | 163 | 0.644472 | [
"MIT"
] | ioawnen/TouchGamepad | GamePad/Form1.Designer.cs | 13,804 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if !DONOTREFPRINTINGASMMETA
//
//
// Description: Manages plug-in document serializers
//
// See spec at <Need to post existing spec>
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Windows.Xps.Serialization;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using MS.Internal.PresentationFramework;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows.Documents.Serialization
{
/// <summary>
/// SerializerProvider enumerates plug-in serializers
/// </summary>
public sealed class SerializerProvider
{
#region Constructors
/// <summary>
/// creates a SerializerProvider
/// The constructor accesses the registry to find all installed plug-ins
/// </summary>
/// <remarks>
/// Create a SerializerProvider listing all installed serializers (from the registry)
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Safe: The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Critical: Full trust is required, so that partial trust applications do not load or use potentially
/// unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
public SerializerProvider()
{
SecurityHelper.DemandPlugInSerializerPermissions();
SerializerDescriptor sd = null;
List<SerializerDescriptor> installedSerializers = new List<SerializerDescriptor>();
sd = CreateSystemSerializerDescriptor();
if (sd != null)
{
installedSerializers.Add(sd);
}
RegistryKey plugIns = _rootKey.CreateSubKey(_registryPath);
if ( plugIns != null )
{
foreach ( string keyName in plugIns.GetSubKeyNames())
{
sd = SerializerDescriptor.CreateFromRegistry(plugIns, keyName);
if (sd != null)
{
installedSerializers.Add(sd);
}
}
plugIns.Close();
}
_installedSerializers = installedSerializers.AsReadOnly();
}
#endregion
#region Public Methods
/// <summary>
/// Registers the serializer plug-in identified by serializerDescriptor in the registry
/// </summary>
///<SecurityNote>
/// Safe: The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Critical: Full trust is required, so that partial trust applications do not install
/// potentially unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
public static void RegisterSerializer(SerializerDescriptor serializerDescriptor, bool overwrite)
{
SecurityHelper.DemandPlugInSerializerPermissions();
if (serializerDescriptor == null)
{
throw new ArgumentNullException("serializerDescriptor");
}
RegistryKey plugIns = _rootKey.CreateSubKey(_registryPath);
string serializerKey = serializerDescriptor.DisplayName + "/" + serializerDescriptor.AssemblyName + "/" + serializerDescriptor.AssemblyVersion + "/" + serializerDescriptor.WinFXVersion;
if (!overwrite && plugIns.OpenSubKey(serializerKey) != null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderAlreadyRegistered), serializerKey);
}
RegistryKey newPlugIn = plugIns.CreateSubKey(serializerKey);
serializerDescriptor.WriteToRegistryKey(newPlugIn);
newPlugIn.Close();
}
/// <summary>
/// Un-Registers the serializer plug-in identified by serializerDescriptor in the registry
/// </summary>
/// <remarks>
/// Removes a previously installed plug-n serialiazer from the registry
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Safe: The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Critical: Full trust is required, so that partial trust applications do not uninstall
/// serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
public static void UnregisterSerializer(SerializerDescriptor serializerDescriptor)
{
SecurityHelper.DemandPlugInSerializerPermissions();
if (serializerDescriptor == null)
{
throw new ArgumentNullException("serializerDescriptor");
}
RegistryKey plugIns = _rootKey.CreateSubKey(_registryPath);
string serializerKey = serializerDescriptor.DisplayName + "/" + serializerDescriptor.AssemblyName + "/" + serializerDescriptor.AssemblyVersion + "/" + serializerDescriptor.WinFXVersion;
if (plugIns.OpenSubKey(serializerKey) == null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderNotRegistered), serializerKey);
}
plugIns.DeleteSubKeyTree(serializerKey);
}
/// <summary>
/// Create a SerializerWriter identified by the passed in SerializerDescriptor on the passed in stream
/// </summary>
/// <remarks>
/// With a SerializerProvider (which requires full trust to ctor) and a SerializerDescriptor (which requires
/// full trust to obtain) create a SerializerWriter
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Safe : The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Critical : Full trust is required, so that partial trust applications do not load or use potentially
/// unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
public SerializerWriter CreateSerializerWriter(SerializerDescriptor serializerDescriptor, Stream stream)
{
SecurityHelper.DemandPlugInSerializerPermissions();
SerializerWriter serializerWriter = null;
if (serializerDescriptor == null)
{
throw new ArgumentNullException("serializerDescriptor");
}
string serializerKey = serializerDescriptor.DisplayName + "/" + serializerDescriptor.AssemblyName + "/" + serializerDescriptor.AssemblyVersion + "/" + serializerDescriptor.WinFXVersion;
if (!serializerDescriptor.IsLoadable)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderWrongVersion), serializerKey);
}
if (stream == null)
{
throw new ArgumentNullException("stream");
}
bool found = false;
foreach (SerializerDescriptor sd in InstalledSerializers)
{
if (sd.Equals(serializerDescriptor))
{
found = true;
break;
}
}
if (!found)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderUnknownSerializer), serializerKey);
}
try
{
ISerializerFactory factory = serializerDescriptor.CreateSerializerFactory();
serializerWriter = factory.CreateSerializerWriter(stream);
}
catch (FileNotFoundException)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderCannotLoad), serializerDescriptor.DisplayName);
}
catch (FileLoadException)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderCannotLoad), serializerDescriptor.DisplayName);
}
catch (BadImageFormatException)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderCannotLoad), serializerDescriptor.DisplayName);
}
catch (MissingMethodException)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderCannotLoad), serializerDescriptor.DisplayName);
}
return serializerWriter;
}
#endregion
#region Private Methods
/// <summary>
/// Uses reflection to create the XpsSerializer
/// </summary>
/// <remarks>
/// Creates the Xps default serializer
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Critical: XpsSerializerFactory..ctor is defined in a non-APTCA assembly.
/// TreatAsSafe: demands appropriate permissions.
/// The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Full trust is required, so that partial trust applications do not load the ReachFramework.dll
/// which does not the Aptca attribute set
///</SecurityNote>
/// <returns>SerializerDescriptor for new serializer</returns>
[SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")]
[SecurityCritical, SecurityTreatAsSafe]
private SerializerDescriptor CreateSystemSerializerDescriptor()
{
SecurityHelper.DemandPlugInSerializerPermissions();
SerializerDescriptor serializerDescriptor = null;
// The XpsSerializer (our default document serializer) is defined in ReachFramework.dll
// But callers can only get here if the above demand succeeds, so they are already fully trusted
serializerDescriptor = SerializerDescriptor.CreateFromFactoryInstance(
new XpsSerializerFactory()
);
return serializerDescriptor;
}
#endregion
#region Public Properties
/// <summary>
/// Returns collection of installed serializers
/// </summary>
public ReadOnlyCollection<SerializerDescriptor> InstalledSerializers
{
get
{
return _installedSerializers;
}
}
#endregion
#region Data
private const string _registryPath = @"SOFTWARE\Microsoft\WinFX Serializers";
private static readonly RegistryKey _rootKey = Registry.LocalMachine;
private ReadOnlyCollection<SerializerDescriptor> _installedSerializers;
#endregion
}
}
#endif | 38.185811 | 197 | 0.617889 | [
"MIT"
] | KodamaSakuno/wpf | src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Documents/Serialization/SerializerProvider.cs | 11,303 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FinalView : MonoBehaviour {
public GameObject thanks;
public GameObject jiewubiao;
public GameObject playerName;
private bool isLocked;
private int waitForZ;
private Animator ani;
// Use this for initialization
void Start() {
isLocked = true;
waitForZ = 0;
ani = GetComponent<Animator>();
SetPLayerName();
}
// Update is called once per frame
void Update() {
if(Input.GetKeyDown(KeyCode.Z)) {
if(isLocked == false) {
LoadSceneOne();
}
if(waitForZ == 1) {
SetSadTrigger();
}
}
}
public void OnClear() {
if(FullDataManager.Instance.clearCount == 0)
UnlockFinalView();
else
WaitForZ();
}
public void WaitForZ() {
waitForZ++;
}
public void UnlockFinalView() {
isLocked = false;
}
public void SetSadTrigger() {
waitForZ++;
FullMusicManager.Instance.Stop();
ani.SetTrigger("Sad");
}
public void LoadSceneOne() {
FullGameFlowManager.Instance.LoadScene(1);
FullDataManager.Instance.clearCount++;
}
private void SetPLayerName() {
Text playerNameText = playerName.GetComponent<Text>();
playerNameText.fontSize = (int)Mathf.Clamp((450f / (float)FullDataManager.Instance.playerNameList.Count),3f,45f);
playerNameText.text = "Thank you again!\n\n";
foreach(string playerName in FullDataManager.Instance.playerNameList) {
playerNameText.text += playerName + "\n";
}
playerNameText.text += "\nAnd\n\n车万众们~" ;
}
}
| 25.125 | 121 | 0.591487 | [
"MIT"
] | IdlessChaye/TouhouNingyoMatsuri | TouhouNingyoMatsuri/Assets/C_Scripts/UI/UIView/FinalView.cs | 1,819 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnGrid : MonoBehaviour
{
public GameObject[] gridElements;
private int playerPos;
[SerializeField] private GameObject playerCard;
[SerializeField] private float playerSpeed;
[SerializeField] private float cardSpeed;
public IEnumerator MoveToPosition(Transform transform, Vector3 position, int cardposition,Struct.CardType type_)
{
var timeToMove = playerSpeed;
transform.gameObject.GetComponent<playerAnimationState>().walk();
var currentPos = transform.position;
var t = 0f;
while(t < 1)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, position, t);
yield return null;
}
transform.gameObject.GetComponent<playerAnimationState>().idle();
if (type_.type == Struct.CardType.Type.Mix)
{
playerPos = cardposition;
respawnCards();
}
else
{
moveCards(cardposition,playerPos);
}
}
public IEnumerator MoveToCardsCoroutine(int card,int cardTo,bool isLast)
{
float timeToMove = cardSpeed;
Transform transform=gridElements[card].GetComponent<GridElement>().currentCard.transform;
Vector3 position=gridElements[cardTo].transform.position;
gridElements[cardTo].GetComponent<GridElement>().currentCard = transform.gameObject;
var currentPos = transform.position;
var t = 0f;
while(t < 1)
{
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp(currentPos, position, t);
yield return null;
}
if (isLast)
{
spawncard(card);
Singletone.canMove = true;
}
}
public void spawncard(int count)
{
GameObject generatedCard = Generator.instance.GenerateCard();
generatedCard.transform.position = gridElements[count].transform.position;
generatedCard.transform.parent = gridElements[count].transform;
// generatedCard.transform.position=Vector3.zero;
gridElements[count].GetComponent<GridElement>().currentCard = generatedCard ;
}
public void replaceCards(int cardID)
{
Singletone.canMove = false;
GridElement targetGridElement = gridElements[cardID].GetComponent<GridElement>();
GridElement playerGridElement = gridElements[playerPos].GetComponent<GridElement>();
Vector3 position = targetGridElement.currentCard.transform.position;
Master.instance.DoStep();
//вызов onBump
targetGridElement.currentCard.GetComponent<Card>().OnBump();
Struct.CardType type_=targetGridElement.currentCard.GetComponent<Card>().type_;
FindObjectOfType<bonusParticle>().sendBonus(targetGridElement.currentCard.GetComponent<Card>().type_,targetGridElement.currentCard.GetComponent<Card>().gender_,targetGridElement.currentCard.GetComponent<Card>().media_,targetGridElement.currentCard.transform.position);
//Destroy(targetGridElement.currentCard);
targetGridElement.currentCard = playerGridElement.currentCard;
playerGridElement.currentCard = null;
foreach (var VARIABLE in FindObjectsOfType<Card>())
{
VARIABLE.OnIdle();
}
StartCoroutine(MoveToPosition(targetGridElement.currentCard.transform,position,cardID,type_));
}
public void movePlayer(CheckSwipe.SwipeType typeMove)
{
if (Singletone.canMove && Singletone.canGo)
{
switch (typeMove)
{
case CheckSwipe.SwipeType.up:
if (playerPos - 3 >= 0)
{
replaceCards(playerPos - 3 );
}
break;
case CheckSwipe.SwipeType.down:
if (playerPos + 3 < 9)
{
replaceCards(playerPos + 3 );
}
break;
case CheckSwipe.SwipeType.left :
if (playerPos - 1 >= 0&&playerPos!=3&&playerPos!=6)
{
replaceCards(playerPos - 1 );
}
break;
case CheckSwipe.SwipeType.rigth:
if (playerPos + 1 < 9&&playerPos!=2&&playerPos!=5)
{
replaceCards(playerPos + 1 );
}
break;
}
}
}
public void destoyAllCards()
{
for (int i = 0; i < 9; i++)
{
if (i != playerPos)
{
print(playerPos);
Destroy(gridElements[i].GetComponent<GridElement>().currentCard);
}
}
}
public void respawnCards()
{
destoyAllCards();
for (int i = 0; i < 9; i++)
{
if(i!=playerPos)
{
spawncard(i);
}
}
StartCoroutine("startAnimation");
}
public void Start()
{
for (int i = 0; i < 9; i++)
{
if(i!=4)
{
spawncard(i);
}
else
{
playerPos = i;
gridElements[i].GetComponent<GridElement>().setCard(Instantiate(playerCard, gridElements[i].GetComponent<Transform>()));
}
}
StartCoroutine("startAnimation");
}
IEnumerator startAnimation()
{
Singletone.canMove = false;
int rotation = 90;
int rotationAngle = 5;
foreach (GameObject gridElementGO in gridElements)
{
gridElementGO.GetComponent<GridElement>().currentCard.transform.Rotate(new Vector3(0,rotation,0));
}
while (rotation!=0)
{
yield return new WaitForSeconds(0.03f);
rotation -= rotationAngle;
foreach (GameObject gridElementGO in gridElements)
{
gridElementGO.GetComponent<GridElement>().currentCard.transform.Rotate(new Vector3(0,-rotationAngle,0));
}
}
Singletone.canMove = true;
}
public void moveCards(int newPosition, int oldPosition)
{
playerPos = newPosition;
if (Singletone.calculateColumnsRovs(newPosition)[0] != Singletone.calculateColumnsRovs(oldPosition)[0])
{
if (Singletone.calculateColumnsRovs(oldPosition)[0] == 2 && Singletone.calculateColumnsRovs(newPosition)[0] == 3)
{
if (Singletone.calculateColumnsRovs(oldPosition)[1] == 1)
{
StartCoroutine(MoveToCardsCoroutine(0,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2)
{
StartCoroutine(MoveToCardsCoroutine(1,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 3)
{
StartCoroutine(MoveToCardsCoroutine(2,oldPosition,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0] == 2 && Singletone.calculateColumnsRovs(newPosition)[0] == 1)
{
if (Singletone.calculateColumnsRovs(oldPosition)[1] == 1)
{
StartCoroutine(MoveToCardsCoroutine(6,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2)
{
StartCoroutine(MoveToCardsCoroutine(7,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 3)
{
StartCoroutine(MoveToCardsCoroutine(8,oldPosition,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0] == 1 && Singletone.calculateColumnsRovs(newPosition)[0] == 2)
{
if (Singletone.calculateColumnsRovs(oldPosition)[1] == 1)
{
StartCoroutine(MoveToCardsCoroutine(1,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(2,1,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2)
{
StartCoroutine(MoveToCardsCoroutine(2,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 3)
{
StartCoroutine(MoveToCardsCoroutine(1,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(0,1,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0] == 3 && Singletone.calculateColumnsRovs(newPosition)[0] == 2)
{
if (Singletone.calculateColumnsRovs(oldPosition)[1] == 1)
{
StartCoroutine(MoveToCardsCoroutine(7,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(8,7,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2)
{
StartCoroutine(MoveToCardsCoroutine(8,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 3)
{
StartCoroutine(MoveToCardsCoroutine(7,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(6,7,true));
}
}
}
else if (Singletone.calculateColumnsRovs(newPosition)[1] != Singletone.calculateColumnsRovs(oldPosition)[1])
{
if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2 && Singletone.calculateColumnsRovs(newPosition)[1] == 1)
{
if (Singletone.calculateColumnsRovs(oldPosition)[0]==1)
{
StartCoroutine(MoveToCardsCoroutine(2,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==2)
{
StartCoroutine(MoveToCardsCoroutine(5,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==3)
{
StartCoroutine(MoveToCardsCoroutine(8,oldPosition,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 2 && Singletone.calculateColumnsRovs(newPosition)[1] == 3)
{
if (Singletone.calculateColumnsRovs(oldPosition)[0]==1)
{
StartCoroutine(MoveToCardsCoroutine(0,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==2)
{
StartCoroutine(MoveToCardsCoroutine(3,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==3)
{
StartCoroutine(MoveToCardsCoroutine(6,oldPosition,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 3 && Singletone.calculateColumnsRovs(newPosition)[1] == 2)
{
if (Singletone.calculateColumnsRovs(oldPosition)[0]==1)
{
StartCoroutine(MoveToCardsCoroutine(5,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(8,5,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==2)
{
StartCoroutine(MoveToCardsCoroutine(2,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==3)
{
StartCoroutine(MoveToCardsCoroutine(5,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(2,5,true));
}
}
else if (Singletone.calculateColumnsRovs(oldPosition)[1] == 1 && Singletone.calculateColumnsRovs(newPosition)[1] == 2)
{
if (Singletone.calculateColumnsRovs(oldPosition)[0]==1)
{
StartCoroutine(MoveToCardsCoroutine(3,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(6,3,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==2)
{
StartCoroutine(MoveToCardsCoroutine(0,oldPosition,true));
}
else if (Singletone.calculateColumnsRovs(oldPosition)[0]==3)
{
StartCoroutine(MoveToCardsCoroutine(3,oldPosition,false));
StartCoroutine(MoveToCardsCoroutine(0,3,true));
}
}
}
}
}
| 36.735211 | 276 | 0.555632 | [
"Artistic-2.0"
] | artgtx/SibGameJam2020Memes | Assets/Scripts/Ultranyan/SpawnGrid.cs | 13,048 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Wheather2_to_Bacnet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("F. Chaxel")]
[assembly: AssemblyProduct("Wheather2_to_Bacnet")]
[assembly: AssemblyCopyright("Copyright © F. Chaxel 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("793f11bf-ae81-40c1-acf3-ff19e1403737")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 32.421053 | 59 | 0.769481 | [
"MIT"
] | DHSERVICE56/DH-SERVICRES | BacnetExplore/CodeExamples/Wheather2_to_Bacnet/Properties/AssemblyInfo.cs | 619 | C# |
using Thriot.Framework.Azure.DataAccess;
using Thriot.Framework.Azure.TableOperations;
using Thriot.Framework.Exceptions;
using Thriot.Management.Model;
using Thriot.Management.Model.Operations;
using Thriot.Management.Operations.Azure.DataAccess;
namespace Thriot.Management.Operations.Azure
{
public class SettingOperations : ISettingOperations
{
private readonly ITableEntityOperation _tableEntityOperation;
public SettingOperations(ICloudStorageClientFactory cloudStorageClientFactory)
{
_tableEntityOperation = cloudStorageClientFactory.GetTableEntityOperation();
}
public void Create(Setting setting)
{
var settingKey = new PartionKeyRowKeyPair(setting.Category, setting.Config);
var settingRepository = new SettingRepository(_tableEntityOperation);
var settingTableEntity = new SettingTableEntity(settingKey, setting.Value);
settingRepository.Create(settingTableEntity);
}
public Setting Get(SettingId id)
{
var settingKey = new PartionKeyRowKeyPair(id.Category, id.Config);
var settingRepository = new SettingRepository(_tableEntityOperation);
var settingTableEntity = settingRepository.Get(settingKey);
if (settingTableEntity == null)
throw new NotFoundException();
return new Setting
{
Category = id.Category,
Config = id.Config,
Value = settingTableEntity.Value
};
}
public void Update(Setting setting)
{
var settingKey = new PartionKeyRowKeyPair(setting.Category, setting.Config);
var settingRepository = new SettingRepository(_tableEntityOperation);
var settingTableEntity = settingRepository.Get(settingKey);
if (settingTableEntity == null)
throw new NotFoundException();
settingTableEntity.Value = setting.Value;
settingRepository.Update(settingTableEntity);
}
public void Delete(SettingId id)
{
var settingKey = new PartionKeyRowKeyPair(id.Category, id.Config);
var settingRepository = new SettingRepository(_tableEntityOperation);
var settingTableEntity = settingRepository.Get(settingKey);
if (settingTableEntity == null)
throw new NotFoundException();
settingRepository.Delete(settingTableEntity);
}
}
} | 34.810811 | 88 | 0.656444 | [
"MIT"
] | kpocza/thriot | Service/Management/Thriot.Management.Operations.Azure/SettingOperations.cs | 2,578 | C# |
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using NAudio.CoreAudioApi;
using NAudio.Wave;
namespace NAudioDemo.MediaFoundationDemo
{
/// <summary>
/// An experimental example of how WASAPI could be used on a GUI thread
/// (to get round STA/MTA threading issues)
/// Uses the WinForms timer, for WPF might be best to use the DispatcherTimer
/// </summary>
public class WasapiOutGuiThread : IWavePlayer
{
private readonly AudioClientShareMode shareMode;
private readonly Timer timer;
private readonly int latencyMilliseconds;
private AudioClient audioClient;
private AudioRenderClient renderClient;
private IWaveProvider sourceProvider;
private int bufferFrameCount;
private int bytesPerFrame;
private byte[] readBuffer;
private PlaybackState playbackState;
private WaveFormat outputFormat;
private ResamplerDmoStream resamplerDmoStream;
/// <summary>
/// Playback Stopped
/// </summary>
public event EventHandler<StoppedEventArgs> PlaybackStopped;
/// <summary>
/// WASAPI Out using default audio endpoint
/// </summary>
public WasapiOutGuiThread() :
this(GetDefaultAudioEndpoint(), AudioClientShareMode.Shared, 200)
{
}
/// <summary>
/// Creates a new WASAPI Output device
/// </summary>
/// <param name="device">Device to use</param>
/// <param name="shareMode">Share mode to use</param>
/// <param name="latency">Latency in milliseconds</param>
public WasapiOutGuiThread(MMDevice device, AudioClientShareMode shareMode, int latency)
{
audioClient = device.AudioClient;
outputFormat = audioClient.MixFormat;
this.shareMode = shareMode;
latencyMilliseconds = latency;
timer = new Timer();
timer.Tick += TimerOnTick;
timer.Interval = latency/2;
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
if (playbackState == PlaybackState.Playing)
{
try
{
// See how much buffer space is available.
int numFramesPadding = audioClient.CurrentPadding;
int numFramesAvailable = bufferFrameCount - numFramesPadding;
if (numFramesAvailable > 0)
{
FillBuffer(sourceProvider, numFramesAvailable);
}
}
catch (Exception e)
{
PerformStop(e);
}
}
else if (playbackState == PlaybackState.Stopped)
{
// user requested stop
PerformStop(null);
}
}
private void PerformStop(Exception e)
{
timer.Enabled = false;
audioClient.Stop();
RaisePlaybackStopped(e);
audioClient.Reset();
}
static MMDevice GetDefaultAudioEndpoint()
{
if (Environment.OSVersion.Version.Major < 6)
{
throw new NotSupportedException("WASAPI supported only on Windows Vista and above");
}
var enumerator = new MMDeviceEnumerator();
return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
}
private void RaisePlaybackStopped(Exception e)
{
var handler = PlaybackStopped;
if (handler != null)
{
handler(this, new StoppedEventArgs(e));
}
}
private void FillBuffer(IWaveProvider playbackProvider, int frameCount)
{
IntPtr buffer = renderClient.GetBuffer(frameCount);
int readLength = frameCount * bytesPerFrame;
int read = playbackProvider.Read(readBuffer, 0, readLength);
if (read == 0)
{
playbackState = PlaybackState.Stopped;
}
Marshal.Copy(readBuffer, 0, buffer, read);
int actualFrameCount = read / bytesPerFrame;
/*if (actualFrameCount != frameCount)
{
Debug.WriteLine(String.Format("WASAPI wanted {0} frames, supplied {1}", frameCount, actualFrameCount ));
}*/
renderClient.ReleaseBuffer(actualFrameCount, AudioClientBufferFlags.None);
}
#region IWavePlayer Members
/// <summary>
/// Begin Playback
/// </summary>
public void Play()
{
if (playbackState == PlaybackState.Stopped)
{
// fill a whole buffer
FillBuffer(sourceProvider, bufferFrameCount);
audioClient.Start();
playbackState = PlaybackState.Playing;
timer.Enabled = true;
}
else if (playbackState == PlaybackState.Paused)
{
playbackState = PlaybackState.Playing;
}
}
/// <summary>
/// Stop playback and flush buffers
/// </summary>
public void Stop()
{
playbackState = PlaybackState.Stopped;
}
/// <summary>
/// Stop playback without flushing buffers
/// </summary>
public void Pause()
{
if (playbackState == PlaybackState.Playing)
{
playbackState = PlaybackState.Paused;
}
}
/// <summary>
/// Initialize for playing the specified wave stream
/// </summary>
/// <param name="waveProvider">IWaveProvider to play</param>
public void Init(IWaveProvider waveProvider)
{
long latencyRefTimes = latencyMilliseconds * 10000;
outputFormat = waveProvider.WaveFormat;
// first attempt uses the WaveFormat from the WaveStream
WaveFormatExtensible closestSampleRateFormat;
if (shareMode == AudioClientShareMode.Exclusive && !audioClient.IsFormatSupported(shareMode, outputFormat, out closestSampleRateFormat))
{
// Use closesSampleRateFormat (in sharedMode, it equals usualy to the audioClient.MixFormat)
// See documentation : http://msdn.microsoft.com/en-us/library/ms678737(VS.85).aspx
// They say : "In shared mode, the audio engine always supports the mix format"
// The MixFormat is more likely to be a WaveFormatExtensible.
if (closestSampleRateFormat == null)
{
WaveFormat correctSampleRateFormat = audioClient.MixFormat;
if (!audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
{
// Iterate from Worst to Best Format
WaveFormatExtensible[] bestToWorstFormats = {
new WaveFormatExtensible(
outputFormat.SampleRate, 32,
outputFormat.Channels),
new WaveFormatExtensible(
outputFormat.SampleRate, 24,
outputFormat.Channels),
new WaveFormatExtensible(
outputFormat.SampleRate, 16,
outputFormat.Channels),
};
// Check from best Format to worst format ( Float32, Int24, Int16 )
for (int i = 0; i < bestToWorstFormats.Length; i++)
{
correctSampleRateFormat = bestToWorstFormats[i];
if (audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
{
break;
}
correctSampleRateFormat = null;
}
// If still null, then test on the PCM16, 2 channels
if (correctSampleRateFormat == null)
{
// Last Last Last Chance (Thanks WASAPI)
correctSampleRateFormat = new WaveFormatExtensible(outputFormat.SampleRate, 16, 2);
if (!audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
{
throw new NotSupportedException("Can't find a supported format to use");
}
}
}
outputFormat = correctSampleRateFormat;
}
else
{
outputFormat = closestSampleRateFormat;
}
// just check that we can make it.
resamplerDmoStream = new ResamplerDmoStream(waveProvider, outputFormat);
sourceProvider = resamplerDmoStream;
}
else
{
sourceProvider = waveProvider;
}
// Normal setup for both sharedMode
var flags = AudioClientStreamFlags.None;
if (shareMode == AudioClientShareMode.Shared)
flags = AudioClientStreamFlags.AutoConvertPcm | AudioClientStreamFlags.SrcDefaultQuality;
audioClient.Initialize(shareMode, flags, latencyRefTimes, 0,
outputFormat, Guid.Empty);
// Get the RenderClient
renderClient = audioClient.AudioRenderClient;
// set up the read buffer
bufferFrameCount = audioClient.BufferSize;
bytesPerFrame = outputFormat.Channels * outputFormat.BitsPerSample / 8;
readBuffer = new byte[bufferFrameCount * bytesPerFrame];
}
/// <summary>
/// Playback State
/// </summary>
public PlaybackState PlaybackState
{
get { return playbackState; }
}
/// <summary>
/// Volume
/// </summary>
public float Volume
{
get
{
return 1.0f;
}
set
{
if (value != 1.0f)
{
throw new NotImplementedException();
}
}
}
public WaveFormat OutputWaveFormat => outputFormat;
#endregion
#region IDisposable Members
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
if (audioClient != null)
{
Stop();
audioClient.Dispose();
audioClient = null;
renderClient = null;
}
if (resamplerDmoStream != null)
{
resamplerDmoStream.Dispose();
resamplerDmoStream = null;
}
}
#endregion
}
} | 38.184127 | 149 | 0.486947 | [
"MIT"
] | Glepooek/NAudio | NAudioDemo/MediaFoundationDemo/WasapiOutGuiThread.cs | 12,030 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Xenon.Editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Xenon.Editor")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7054b21-2e7d-44ca-821c-2b5be612e467")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.621622 | 84 | 0.746408 | [
"Apache-2.0"
] | Xenation/Xenon | XenonBuild/Properties/AssemblyInfo.Editor.cs | 1,395 | C# |
using Esfa.Recruit.Vacancies.Client.Application.Validation;
using Esfa.Recruit.Vacancies.Client.Domain.Entities;
using FluentAssertions;
using Xunit;
namespace Esfa.Recruit.UnitTests.Vacancies.Client.Application.VacancyValidation.SingleField
{
public class ExternalApplicationUrlValidationTests : VacancyValidationTestsBase
{
[Theory]
[InlineData("applyhere.com")]
[InlineData("www.applyhere.com")]
[InlineData("http://www.applyhere.com")]
[InlineData("https://www.applyhere.com")]
[InlineData("applyhere.com#anchor")]
[InlineData("applyhere.com?term=query")]
public void NoErrorsWhenExternalApplicationUrlIsValid(string url)
{
var vacancy = new Vacancy
{
ApplicationMethod = ApplicationMethod.ThroughExternalApplicationSite,
ApplicationUrl = url
};
var result = Validator.Validate(vacancy, VacancyRuleSet.ApplicationMethod);
result.HasErrors.Should().BeFalse();
result.Errors.Should().HaveCount(0);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void ExternalApplicationUrlMustHaveAValue(string url)
{
var vacancy = new Vacancy
{
ApplicationMethod = ApplicationMethod.ThroughExternalApplicationSite,
ApplicationUrl = url
};
var result = Validator.Validate(vacancy, VacancyRuleSet.ApplicationMethod);
result.HasErrors.Should().BeTrue();
result.Errors[0].PropertyName.Should().Be(nameof(vacancy.ApplicationUrl));
result.Errors[0].ErrorCode.Should().Be("85");
result.Errors[0].RuleId.Should().Be((long)VacancyRuleSet.ApplicationMethod);
}
[Fact]
public void ExternalApplicationUrlMustBe200CharactersOrLess()
{
var vacancy = new Vacancy
{
ApplicationMethod = ApplicationMethod.ThroughExternalApplicationSite,
ApplicationUrl = "http://www.applyhere.com".PadRight(201, 'w')
};
var result = Validator.Validate(vacancy, VacancyRuleSet.ApplicationMethod);
result.HasErrors.Should().BeTrue();
result.Errors[0].PropertyName.Should().Be(nameof(vacancy.ApplicationUrl));
result.Errors[0].ErrorCode.Should().Be("84");
result.Errors[0].RuleId.Should().Be((long)VacancyRuleSet.ApplicationMethod);
}
[Theory]
[InlineData("Invalid Url")]
[InlineData("applyhere")]
[InlineData("domain.com ?term=query")]
[InlineData(".com")]
[InlineData(".org.uk")]
[InlineData(",com")]
public void ExternalApplicationUrlMustBeAValidWebAddress(string invalidUrl)
{
var vacancy = new Vacancy
{
ApplicationMethod = ApplicationMethod.ThroughExternalApplicationSite,
ApplicationUrl = invalidUrl
};
var result = Validator.Validate(vacancy, VacancyRuleSet.ApplicationMethod);
result.HasErrors.Should().BeTrue();
result.Errors[0].PropertyName.Should().Be(nameof(vacancy.ApplicationUrl));
result.Errors[0].ErrorCode.Should().Be("86");
result.Errors[0].RuleId.Should().Be((long)VacancyRuleSet.ApplicationMethod);
}
}
} | 38.155556 | 91 | 0.62318 | [
"MIT"
] | SkillsFundingAgency/das-recru | src/Shared/UnitTests/Vacancies.Client/Application/VacancyValidation/SingleField/ExternalApplicationUrlValidationTests.cs | 3,436 | C# |
namespace WindowsFormsApplication1
{
partial class EntryDeleteView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.label2 = new System.Windows.Forms.Label();
this.textBox9 = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.textBox8 = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.textBox7 = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.textBox6 = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.textBox5 = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label1.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label1.Location = new System.Drawing.Point(901, 47);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(105, 36);
this.label1.TabIndex = 0;
this.label1.Text = "Admin";
//
// button1
//
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.Location = new System.Drawing.Point(537, 769);
this.button1.Margin = new System.Windows.Forms.Padding(4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(216, 64);
this.button1.TabIndex = 1;
this.button1.Text = "Insert Bus Schedule";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Location = new System.Drawing.Point(812, 769);
this.button2.Margin = new System.Windows.Forms.Padding(4);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(216, 64);
this.button2.TabIndex = 2;
this.button2.Text = "Delete Bus Schedule";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button3.Location = new System.Drawing.Point(1087, 769);
this.button3.Margin = new System.Windows.Forms.Padding(4);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(216, 66);
this.button3.TabIndex = 3;
this.button3.Text = "Update Records";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button4.Location = new System.Drawing.Point(1379, 769);
this.button4.Margin = new System.Windows.Forms.Padding(4);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(216, 64);
this.button4.TabIndex = 4;
this.button4.Text = "View Customer Details";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button5.Location = new System.Drawing.Point(52, 44);
this.button5.Margin = new System.Windows.Forms.Padding(4);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(117, 38);
this.button5.TabIndex = 5;
this.button5.Text = "Previous";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// dataGridView1
//
this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.ButtonHighlight;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(460, 126);
this.dataGridView1.Margin = new System.Windows.Forms.Padding(4);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(1324, 575);
this.dataGridView1.TabIndex = 6;
this.dataGridView1.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_RowHeaderMouseClick);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label2.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label2.Location = new System.Drawing.Point(455, 97);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(161, 25);
this.label2.TabIndex = 7;
this.label2.Text = "Bus information";
//
// textBox9
//
this.textBox9.Location = new System.Drawing.Point(232, 438);
this.textBox9.Margin = new System.Windows.Forms.Padding(4);
this.textBox9.Name = "textBox9";
this.textBox9.Size = new System.Drawing.Size(183, 22);
this.textBox9.TabIndex = 40;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label11.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label11.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label11.Location = new System.Drawing.Point(47, 438);
this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(158, 25);
this.label11.TabIndex = 39;
this.label11.Text = "Date of journey";
//
// textBox8
//
this.textBox8.Location = new System.Drawing.Point(232, 192);
this.textBox8.Margin = new System.Windows.Forms.Padding(4);
this.textBox8.Name = "textBox8";
this.textBox8.Size = new System.Drawing.Size(183, 22);
this.textBox8.TabIndex = 38;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label10.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label10.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label10.Location = new System.Drawing.Point(47, 192);
this.label10.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(73, 25);
this.label10.TabIndex = 37;
this.label10.Text = "Bus Id";
//
// textBox7
//
this.textBox7.Location = new System.Drawing.Point(232, 676);
this.textBox7.Margin = new System.Windows.Forms.Padding(4);
this.textBox7.Name = "textBox7";
this.textBox7.Size = new System.Drawing.Size(183, 22);
this.textBox7.TabIndex = 36;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label9.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label9.Location = new System.Drawing.Point(47, 676);
this.label9.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(56, 25);
this.label9.TabIndex = 35;
this.label9.Text = "Fare";
//
// textBox6
//
this.textBox6.Location = new System.Drawing.Point(232, 619);
this.textBox6.Margin = new System.Windows.Forms.Padding(4);
this.textBox6.Name = "textBox6";
this.textBox6.Size = new System.Drawing.Size(183, 22);
this.textBox6.TabIndex = 34;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label8.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label8.Location = new System.Drawing.Point(47, 619);
this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(152, 25);
this.label8.TabIndex = 33;
this.label8.Text = "Available Seat";
//
// textBox5
//
this.textBox5.Location = new System.Drawing.Point(232, 254);
this.textBox5.Margin = new System.Windows.Forms.Padding(4);
this.textBox5.Name = "textBox5";
this.textBox5.Size = new System.Drawing.Size(183, 22);
this.textBox5.TabIndex = 32;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label7.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label7.Location = new System.Drawing.Point(47, 254);
this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(135, 25);
this.label7.TabIndex = 31;
this.label7.Text = "Name of Bus";
//
// textBox4
//
this.textBox4.Location = new System.Drawing.Point(232, 561);
this.textBox4.Margin = new System.Windows.Forms.Padding(4);
this.textBox4.Name = "textBox4";
this.textBox4.Size = new System.Drawing.Size(183, 22);
this.textBox4.TabIndex = 30;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label6.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label6.Location = new System.Drawing.Point(47, 561);
this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(101, 25);
this.label6.TabIndex = 29;
this.label6.Text = "Arr. Time";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(232, 502);
this.textBox3.Margin = new System.Windows.Forms.Padding(4);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(183, 22);
this.textBox3.TabIndex = 28;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label5.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label5.Location = new System.Drawing.Point(47, 502);
this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(111, 25);
this.label5.TabIndex = 27;
this.label5.Text = "Dep. Time";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(232, 374);
this.textBox2.Margin = new System.Windows.Forms.Padding(4);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(183, 22);
this.textBox2.TabIndex = 26;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label4.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label4.Location = new System.Drawing.Point(47, 374);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(38, 25);
this.label4.TabIndex = 25;
this.label4.Text = "To";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(232, 313);
this.textBox1.Margin = new System.Windows.Forms.Padding(4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(183, 22);
this.textBox1.TabIndex = 24;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label3.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label3.Location = new System.Drawing.Point(47, 313);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(61, 25);
this.label3.TabIndex = 23;
this.label3.Text = "From";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label12.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label12.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label12.Location = new System.Drawing.Point(47, 114);
this.label12.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(241, 25);
this.label12.TabIndex = 22;
this.label12.Text = "Entry Buses Information";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label13.ForeColor = System.Drawing.Color.Red;
this.label13.Image = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.label13.Location = new System.Drawing.Point(532, 720);
this.label13.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(691, 36);
this.label13.TabIndex = 41;
this.label13.Text = "Select a row before update or delete a schedule";
//
// EntryDeleteView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::WindowsFormsApplication1.Properties.Resources.fondo_azul;
this.ClientSize = new System.Drawing.Size(1902, 1033);
this.Controls.Add(this.label13);
this.Controls.Add(this.textBox9);
this.Controls.Add(this.label11);
this.Controls.Add(this.textBox8);
this.Controls.Add(this.label10);
this.Controls.Add(this.textBox7);
this.Controls.Add(this.label9);
this.Controls.Add(this.textBox6);
this.Controls.Add(this.label8);
this.Controls.Add(this.textBox5);
this.Controls.Add(this.label7);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.label6);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label5);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label12);
this.Controls.Add(this.label2);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "EntryDeleteView";
this.Text = "Form4";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox9;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox textBox8;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox textBox7;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox textBox6;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox textBox5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
}
} | 55.9375 | 230 | 0.610335 | [
"MIT"
] | ibrahimsumon1994/Ticket_Reservation_System_with_testing | WindowsFormsApplication1/EntryDeleteView.Designer.cs | 25,062 | C# |
using System;
using System.Diagnostics;
namespace HttpCapture
{
class DiagnosticObserver : IObserver<DiagnosticListener>
{
void IObserver<DiagnosticListener>.OnCompleted()
{
}
void IObserver<DiagnosticListener>.OnError(Exception error)
{
}
void IObserver<DiagnosticListener>.OnNext(DiagnosticListener value)
{
if (value.Name.Contains("System.Net.Http"))
{
value.Subscribe(new HttpObserver());
}
}
}
}
| 21.64 | 75 | 0.5878 | [
"Apache-2.0"
] | joymon/dotnet-demos | diagnostics/HttpCapture/HttpCapture/DiagnosticObserver.cs | 543 | C# |
using System;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// AUTOGENERATED: DO NOT EDIT!
/// </summary>
public partial class TdApi
{
public class RemoveFavoriteSticker : Function<Ok>
{
[JsonProperty("@type")] public override string DataType { get; set; } = "removeFavoriteSticker";
[JsonProperty("@extra")] public override string Extra { get; set; }
[JsonConverter(typeof(Converter))]
[JsonProperty("sticker")]
public InputFile Sticker { get; set; }
}
}
} | 26.272727 | 108 | 0.586505 | [
"MIT"
] | Behnam-Emamian/tdsharp | TDLib.Api/Functions/RemoveFavoriteSticker.cs | 578 | C# |
namespace Sudoku.Solving.Manual.Chaining;
/// <summary>
/// Indicates a type code for a chain.
/// </summary>
[Closed]
public enum ChainingTypeCode : byte
{
/// <summary>
/// Indicates the M-Wing.
/// </summary>
MWing = 1,
/// <summary>
/// Indicates the split wing.
/// </summary>
SplitWing,
/// <summary>
/// Indicates the local wing.
/// </summary>
LocalWing,
/// <summary>
/// Indicates the hybrid wing.
/// </summary>
HybridWing,
/// <summary>
/// Indicates the X-Chain.
/// </summary>
XChain,
/// <summary>
/// Indicates the X-Cycle (Fishy Cycle).
/// </summary>
FishyCycle,
/// <summary>
/// Indicates the XY-Chain.
/// </summary>
XyChain,
/// <summary>
/// Indicates the XY-Cycle.
/// </summary>
XyCycle,
/// <summary>
/// Indicates the continuous nice loop.
/// </summary>
ContinuousNiceLoop,
/// <summary>
/// Indicates the XY-X-Chain.
/// </summary>
XyXChain,
/// <summary>
/// Indicates the discontinuous nice loop.
/// </summary>
DiscontinuousNiceLoop,
/// <summary>
/// Indicates the alternating inference chain.
/// </summary>
Aic,
/// <summary>
/// Indicates the cell forcing chains.
/// </summary>
CellFc,
/// <summary>
/// Indicates the region forcing chains.
/// </summary>
RegionFc,
/// <summary>
/// Indicates the contradiction forcing chains.
/// </summary>
ContradictionFc,
/// <summary>
/// Indicates the double forcing chains.
/// </summary>
DoubleFc,
/// <summary>
/// Indicates the dynamic cell forcing chains.
/// </summary>
DynamicCellFc,
/// <summary>
/// Indicates the dynamic region forcing chains.
/// </summary>
DynamicRegionFc,
/// <summary>
/// Indicates the dynamic contradiction forcing chains.
/// </summary>
DynamicContradictionFc,
/// <summary>
/// Indicates the dynamic double forcing chains.
/// </summary>
DynamicDoubleFc,
}
| 17.155963 | 56 | 0.631016 | [
"MIT"
] | XiaoXin1900/Sudoku | src/Sudoku.Solving.Old/Solving/Manual/Chaining/ChainingTypeCode.cs | 1,872 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
namespace Users.Api
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureAppConfiguration(options =>
{
options.AddJsonFile("./secretsettings.json", false, true);
});
});
}
} | 30.16 | 82 | 0.557029 | [
"MIT"
] | Inozpavel/WorkPlanner | Users.Api/Program.cs | 754 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLite.Scaffolder
{
public enum Unique
{
Yes,
No
}
}
| 13.933333 | 33 | 0.674641 | [
"MIT"
] | mmaloparic/SQLiteScaffolder | SQLite Scaffolder/SQLite.Scaffolder/Enum/Unique.cs | 211 | C# |
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo.Web
{
using System;
[Flags]
public enum HttpVersions
{
HttpV10 = 1 << 0,
HttpV11 = 1 << 1,
Any = HttpV10 | HttpV11
}
public static class HttpVersionsExtensions
{
public static bool Contains(this HttpVersions @this, HttpVersions versions) => (@this & versions) != 0;
}
}
| 21.363636 | 112 | 0.62766 | [
"BSD-2-Clause"
] | chtoucas/Narvalo.NET | src/Narvalo.Web/HttpVersions.cs | 472 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using WindowsAppChatClient.ViewModels;
namespace WinAppChatClient.Views;
public sealed partial class GroupChatUC : UserControl
{
public GroupChatUC()
{
InitializeComponent();
if (Application.Current is App app)
{
_scope = app.Services.CreateScope();
ViewModel = _scope.ServiceProvider.GetRequiredService<GroupChatViewModel>();
}
else
{
throw new InvalidOperationException("Application.Current is not App");
}
}
private readonly IServiceScope? _scope;
public GroupChatViewModel ViewModel { get; }
}
| 24.133333 | 88 | 0.680939 | [
"MIT"
] | christiannagel/ProfessionalCSharp2021 | 3_Web/SignalR/SignalRSample/WinAppChatClient/Views/GroupChatUC.xaml.cs | 726 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using AuthorizationServer.ViewModels.Shared;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
namespace AuthorizationServer.Controllers
{
public class ErrorController : Controller
{
[HttpGet, HttpPost, Route("~/error")]
public IActionResult Error()
{
// If the error was not caused by an invalid
// OIDC request, display a generic error page.
var response = HttpContext.GetOpenIdConnectResponse();
if (response == null)
{
return View(new ErrorViewModel());
}
return View(new ErrorViewModel
{
Error = response.Error,
ErrorDescription = response.ErrorDescription
});
}
}
} | 31.727273 | 94 | 0.626552 | [
"Apache-2.0"
] | RossGao/OpenIddictSample | samples/ImplicitFlow/AuthorizationServer/Controllers/ErrorController.cs | 1,049 | C# |
// -----------------------------------------------------------------------
// <copyright file="InstallerIdentifierValidator.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. Licensed under the MIT License.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.WinGet.RestSource.Utils.Validators.StringValidators
{
/// <summary>
/// InstallerIdentifierValidatorValidator.
/// </summary>
public class InstallerIdentifierValidator : ApiStringValidator
{
private const uint Max = 128;
/// <summary>
/// Initializes a new instance of the <see cref="InstallerIdentifierValidator"/> class.
/// </summary>
public InstallerIdentifierValidator()
{
this.MaxLength = Max;
}
}
}
| 34.92 | 96 | 0.52921 | [
"MIT"
] | RDMacLachlan/winget-cli-restsource | src/WinGet.RestSource.Utils/Validators/StringValidators/InstallerIdentifierValidator.cs | 875 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon Resource Name (ARN) of the Regex Pattern Set that this statement references.
/// </summary>
[Input("arn", required: true)]
public Input<string> Arn { get; set; } = null!;
/// <summary>
/// Part of a web request that you want AWS WAF to inspect. See Field to Match below for details.
/// </summary>
[Input("fieldToMatch")]
public Input<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchGetArgs>? FieldToMatch { get; set; }
[Input("textTransformations", required: true)]
private InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationGetArgs>? _textTransformations;
/// <summary>
/// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details.
/// </summary>
public InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationGetArgs> TextTransformations
{
get => _textTransformations ?? (_textTransformations = new InputList<Inputs.WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationGetArgs>());
set => _textTransformations = value;
}
public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementGetArgs()
{
}
}
}
| 54.068182 | 247 | 0.769231 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementGetArgs.cs | 2,379 | C# |
namespace BookLovers.Seed.Models.Configuration
{
public class OwnResourceConfiguration
{
public int UserCount { get; set; }
public int SeriesCount { get; set; }
public int TicketsCount { get; set; }
public int QuotesCount { get; set; }
public int ReviewsCount { get; set; }
private OwnResourceConfiguration()
{
}
public static OwnResourceConfiguration Initialize()
{
return new OwnResourceConfiguration();
}
public OwnResourceConfiguration WithUsers(int count)
{
this.UserCount = count;
return this;
}
public OwnResourceConfiguration WithSeries(int count)
{
this.SeriesCount = count;
return this;
}
public OwnResourceConfiguration WithTickets(int count)
{
this.TicketsCount = count;
return this;
}
public OwnResourceConfiguration WithQuotes(int count)
{
this.QuotesCount = count;
return this;
}
public OwnResourceConfiguration WithReviews(int count)
{
this.ReviewsCount = count;
return this;
}
}
} | 21.457627 | 62 | 0.559242 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Seed/Models/Configuration/OwnResourceConfiguration.cs | 1,268 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 這段程式碼是由工具產生的。
// 執行階段版本:4.0.30319.42000
//
// 變更這個檔案可能會導致不正確的行為,而且如果已重新產生
// 程式碼,則會遺失變更。
// </auto-generated>
//------------------------------------------------------------------------------
namespace USBEventHooking.Properties
{
/// <summary>
/// 用於查詢當地語系化字串等的強類型資源類別
/// </summary>
// 這個類別是自動產生的,是利用 StronglyTypedResourceBuilder
// 類別透過 ResGen 或 Visual Studio 這類工具產生。
// 若要加入或移除成員,請編輯您的 .ResX 檔,然後重新執行 ResGen
// (利用 /str 選項),或重建您的 VS 專案。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 傳回這個類別使用的快取的 ResourceManager 執行個體。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("USBEventHooking.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆寫目前執行緒的 CurrentUICulture 屬性,對象是所有
/// 使用這個強類型資源類別的資源查閱。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 34.25 | 181 | 0.580697 | [
"Apache-2.0"
] | bxxxjxxg/USBEventHooking | USBEventHooking/Properties/Resources.Designer.cs | 2,846 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection;
using System.Collections.Specialized;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Core.PropertyEditors;
using umbraco.BusinessLogic;
using System.Collections.Generic;
using MacroProperty = umbraco.cms.businesslogic.macro.MacroProperty;
using UserControl = System.Web.UI.UserControl;
namespace umbraco.developer
{
/// <summary>
/// Summary description for assemblyBrowser.
/// </summary>
public partial class assemblyBrowser : BasePages.UmbracoEnsuredPage
{
public assemblyBrowser()
{
CurrentApp = DefaultApps.developer.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
var isUserControl = false;
var errorReadingControl = false;
try
{
Type type = null;
if (Request.QueryString["type"] == null)
{
isUserControl = true;
var fileName = Request.GetItemAsString("fileName");
if (!fileName.StartsWith("~"))
{
if (fileName.StartsWith("/"))
{
fileName = "~" + fileName;
}
else
{
fileName = "~/" + fileName;
}
}
IOHelper.ValidateEditPath(fileName, SystemDirectories.UserControls);
if (System.IO.File.Exists(IOHelper.MapPath(fileName)))
{
var oControl = (UserControl)LoadControl(fileName);
type = oControl.GetType();
}
else
{
errorReadingControl = true;
ChooseProperties.Visible = false;
AssemblyName.Text = "<span style=\"color: red;\">User control doesn't exist</span><br /><br />Please verify that you've copied the file to:<br />" + IOHelper.MapPath("~/" + fileName);
}
}
else
{
var currentAss = IOHelper.MapPath(SystemDirectories.Bin + "/" + Request.QueryString["fileName"] + ".dll");
var asm = Assembly.LoadFrom(currentAss);
type = asm.GetType(Request.QueryString["type"]);
}
if (!errorReadingControl)
{
string fullControlAssemblyName;
if (isUserControl)
{
AssemblyName.Text = "Choose Properties from " + type.BaseType.Name;
fullControlAssemblyName = type.BaseType.Namespace + "." + type.BaseType.Name;
}
else
{
AssemblyName.Text = "Choose Properties from " + type.Name;
fullControlAssemblyName = type.Namespace + "." + type.Name;
}
if (!IsPostBack && type != null)
{
MacroProperties.Items.Clear();
foreach (var pi in type.GetProperties())
{
if (pi.CanWrite && ((fullControlAssemblyName == pi.DeclaringType.Namespace + "." + pi.DeclaringType.Name) || pi.DeclaringType == type))
{
MacroProperties.Items.Add(new ListItem(pi.Name + " <span style=\"color: #99CCCC\">(" + pi.PropertyType.Name + ")</span>", pi.PropertyType.Name));
}
foreach (ListItem li in MacroProperties.Items)
li.Selected = true;
}
}
}
}
catch (Exception err)
{
AssemblyName.Text = "Error reading " + Request.CleanForXss("fileName");
Button1.Visible = false;
ChooseProperties.Controls.Add(new LiteralControl("<p class=\"guiDialogNormal\" style=\"color: red;\">" + err.ToString() + "</p><p/><p class=\"guiDialogNormal\">"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var result = "";
// Get the macro object
var macroObject = ApplicationContext.Current.Services.MacroService.GetById(Convert.ToInt32(Request.QueryString["macroID"]));
//// Load all macroPropertyTypes
//var macroPropertyTypes = new Hashtable();
//var macroPropertyIds = new Hashtable();
//var macroPropTypes = ParameterEditorResolver.Current.ParameterEditors.ToArray();
//foreach (var mpt in macroPropTypes)
//{
// macroPropertyIds.Add(mpt.Alias, mpt.Id.ToString());
// macroPropertyTypes.Add(mpt.Alias, mpt.BaseType);
//}
var changed = false;
foreach (ListItem li in MacroProperties.Items)
{
if (li.Selected && MacroHasProperty(macroObject, li.Text.Substring(0, li.Text.IndexOf(" ", StringComparison.Ordinal)).ToLower()) == false)
{
result += "<li>Added: " + SpaceCamelCasing(li.Text) + "</li>";
var macroPropertyTypeAlias = GetMacroTypeFromClrType(li.Value);
macroObject.Properties.Add(new Umbraco.Core.Models.MacroProperty
{
Name = SpaceCamelCasing(li.Text),
Alias = li.Text.Substring(0, li.Text.IndexOf(" ", StringComparison.Ordinal)),
EditorAlias = macroPropertyTypeAlias
});
changed = true;
}
else if (li.Selected)
{
result += "<li>Skipped: " + SpaceCamelCasing(li.Text) + " (already exists as a parameter)</li>";
}
}
if (changed)
{
ApplicationContext.Current.Services.MacroService.Save(macroObject);
}
ChooseProperties.Visible = false;
ConfigProperties.Visible = true;
resultLiteral.Text = result;
}
private static bool MacroHasProperty(IMacro macroObject, string propertyAlias)
{
return macroObject.Properties.Any(mp => mp.Alias.ToLower() == propertyAlias);
}
private static string SpaceCamelCasing(string text)
{
var tempString = text.Substring(0, 1).ToUpper();
for (var i = 1; i < text.Length; i++)
{
if (text.Substring(i, 1) == " ")
break;
if (text.Substring(i, 1).ToUpper() == text.Substring(i, 1))
tempString += " ";
tempString += text.Substring(i, 1);
}
return tempString;
}
private static string GetMacroTypeFromClrType(string baseTypeName)
{
switch (baseTypeName)
{
case "Int32":
return Constants.PropertyEditors.IntegerAlias;
case "Decimal":
//we previously only had an integer editor too! - this would of course
// fail if someone enters a real long number
return Constants.PropertyEditors.IntegerAlias;
case "Boolean":
return Constants.PropertyEditors.TrueFalseAlias;
case "String":
default:
return Constants.PropertyEditors.TextboxAlias;
}
}
}
}
| 38.483721 | 207 | 0.496374 | [
"MIT"
] | filipesousa20/Umbraco-CMS-V7 | src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.cs | 8,274 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Hinode.Izumi.Services.DiscordServices.DiscordGuildService.Queries;
using MediatR;
namespace Hinode.Izumi.Services.DiscordServices.DiscordGuildService.Commands
{
public record RenameDiscordUserCommand(long Id, string NewName) : IRequest;
public class RenameDiscordUserHandler : IRequestHandler<RenameDiscordUserCommand>
{
private readonly IMediator _mediator;
public RenameDiscordUserHandler(IMediator mediator)
{
_mediator = mediator;
}
public async Task<Unit> Handle(RenameDiscordUserCommand request, CancellationToken cancellationToken)
{
var (id, newName) = request;
var socketGuild = await _mediator.Send(new GetDiscordSocketGuildQuery(), cancellationToken);
var socketGuildUser = socketGuild.GetUser((ulong) id);
try
{
await socketGuildUser.ModifyAsync(x => x.Nickname = newName + " 🌺");
}
catch (Exception e)
{
Console.WriteLine(e);
}
return new Unit();
}
}
}
| 30.333333 | 109 | 0.64497 | [
"MIT"
] | envyvox/Hinode.Izumi | Hinode.Izumi.Services/DiscordServices/DiscordGuildService/Commands/RenameDiscordUserCommand.cs | 1,188 | C# |
using System.Collections.Generic;
#if !NETSTANDARD2_1
using System.Runtime.Serialization;
#else
using System.Text.Json.Serialization;
#endif
namespace Docker.DotNet.Models
{
#if !NETSTANDARD2_1
[DataContract]
#endif
public class ImagesPruneParameters // (main.ImagesPruneParameters)
{
[QueryStringParameter("filters", false, typeof(MapQueryStringConverter))]
public IDictionary<string, IDictionary<string, bool>> Filters { get; set; }
}
}
| 24.842105 | 83 | 0.745763 | [
"Apache-2.0"
] | ewisted/Docker.DotNet | src/Docker.DotNet/Models/ImagesPruneParameters.Generated.cs | 472 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace ButtonGlide.Droid
{
[Activity(Label = "ButtonGlide", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| 26.36 | 160 | 0.698027 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter21/ButtonGlide/ButtonGlide/ButtonGlide.Droid/MainActivity.cs | 659 | C# |
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
static class DotNetBuildSettingsExtensions
{
public static DotNetBuildSettings SetContinuousIntegrationBuild(this DotNetBuildSettings settings, bool value) =>
settings.SetProcessArgumentConfigurator(a => a.Add($"/p:ContinuousIntegrationBuild={value.ToString().ToLower()}"));
} | 43.625 | 123 | 0.796562 | [
"MIT"
] | KuraiAndras/CsprojToAsmdef | Build/DotNetBuildSettingsExtensions.cs | 351 | C# |
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Rock;
using Rock.Attribute;
using Rock.Data;
using Rock.Model;
using Rock.Security;
using Rock.Web.Cache;
using Rock.Web.UI;
using Rock.Web.UI.Controls;
namespace RockWeb.Blocks.Event
{
/// <summary>
///
/// </summary>
[DisplayName("Calendar Item Occurrence Content Channel Item List")]
[Category("Event")]
[Description("Lists the content channel items associated to a particular calendar item occurrence.")]
[LinkedPage("Detail Page")]
public partial class CalendarContentChannelItemList : RockBlock, ISecondaryBlock
{
#region Properties
private int? OccurrenceId { get; set; }
private List<ContentChannel> ContentChannels { get; set; }
private List<int> ExpandedPanels { get; set; }
#endregion
#region Control Methods
/// <summary>
/// Restores the view-state information from a previous user control request that was saved by the <see cref="M:System.Web.UI.UserControl.SaveViewState" /> method.
/// </summary>
/// <param name="savedState">An <see cref="T:System.Object" /> that represents the user control state to be restored.</param>
protected override void LoadViewState( object savedState )
{
base.LoadViewState( savedState );
OccurrenceId = ViewState["OccurrenceId"] as int?;
string json = ViewState["ContentChannels"] as string;
if ( string.IsNullOrWhiteSpace( json ) )
{
ContentChannels = new List<ContentChannel>();
}
else
{
ContentChannels = JsonConvert.DeserializeObject<List<ContentChannel>>( json );
}
ExpandedPanels = ViewState["ExpandedPanels"] as List<int>;
CreateGrids( new RockContext() );
BindGrids();
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnInit( EventArgs e )
{
base.OnInit( e );
// this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
this.BlockUpdated += Block_BlockUpdated;
this.AddConfigurationUpdateTrigger( upnlContent );
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnLoad( EventArgs e )
{
if ( !Page.IsPostBack )
{
var rockContext = new RockContext();
OccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
ContentChannels = new List<ContentChannel>();
ExpandedPanels = new List<int>();
if ( OccurrenceId.HasValue && OccurrenceId.Value != 0 )
{
var channels = new Dictionary<int, ContentChannel>();
var eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( OccurrenceId.Value );
if ( eventItemOccurrence != null && eventItemOccurrence.EventItem != null && eventItemOccurrence.EventItem.EventCalendarItems != null )
{
eventItemOccurrence.EventItem.EventCalendarItems
.SelectMany( i => i.EventCalendar.ContentChannels )
.Select( c => c.ContentChannel )
.ToList()
.ForEach( c => channels.AddOrIgnore( c.Id, c ) );
ExpandedPanels = eventItemOccurrence.ContentChannelItems
.Where( i => i.ContentChannelItem != null )
.Select( i => i.ContentChannelItem.ContentChannelId )
.Distinct()
.ToList();
}
foreach( var channel in channels )
{
if ( channel.Value.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
{
ContentChannels.Add( channel.Value );
}
}
}
CreateGrids( rockContext );
BindGrids();
}
base.OnLoad( e );
}
protected override object SaveViewState()
{
var jsonSetting = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new Rock.Utility.IgnoreUrlEncodedKeyContractResolver()
};
ViewState["OccurrenceId"] = OccurrenceId;
ViewState["ContentChannels"] = JsonConvert.SerializeObject( ContentChannels, Formatting.None, jsonSetting );
ViewState["ExpandedPanels"] = ExpandedPanels;
return base.SaveViewState();
}
#endregion
#region Events
/// <summary>
/// Handles the Add event of the gItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
protected void gItems_Add( object sender, EventArgs e )
{
var grid = ( (Control)sender ).DataKeysContainer;
if ( grid != null )
{
int contentChannelId = grid.ID.Substring( 7 ).AsInteger();
NavigateToDetailPage( 0, contentChannelId );
}
}
/// <summary>
/// Handles the Edit event of the gItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
protected void gItems_Edit( object sender, RowEventArgs e )
{
NavigateToDetailPage( e.RowKeyId );
}
/// <summary>
/// Handles the Delete event of the gItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
protected void gItems_Delete( object sender, RowEventArgs e )
{
var rockContext = new RockContext();
ContentChannelItemService contentItemService = new ContentChannelItemService( rockContext );
ContentChannelItem contentItem = contentItemService.Get( e.RowKeyId );
if ( contentItem != null )
{
string errorMessage;
if ( !contentItemService.CanDelete( contentItem, out errorMessage ) )
{
mdGridWarning.Show( errorMessage, ModalAlertType.Information );
return;
}
contentItemService.Delete( contentItem );
rockContext.SaveChanges();
}
BindGrids();
}
/// <summary>
/// Handles the GridRebind event of the gItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void gItems_GridRebind( object sender, EventArgs e )
{
BindGrids();
}
/// <summary>
/// Handles the BlockUpdated event of the control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Block_BlockUpdated( object sender, EventArgs e )
{
BindGrids();
}
#endregion
#region Internal Methods
/// <summary>
/// Hook so that other blocks can set the visibility of all ISecondaryBlocks on it's page
/// </summary>
/// <param name="visible">if set to <c>true</c> [visible].</param>
public void SetVisible( bool visible )
{
pnlContent.Visible = visible;
}
private void CreateGrids( RockContext rockContext )
{
if ( ContentChannels.Any() )
{
this.Visible = true;
phContentChannelGrids.Controls.Clear();
foreach ( var contentChannel in ContentChannels )
{
bool canEdit = UserCanEdit || contentChannel.IsAuthorized( Authorization.EDIT, CurrentPerson );
string iconClass = "fa fa-bullhorn";
if ( !string.IsNullOrWhiteSpace( contentChannel.IconCssClass ) )
{
iconClass = contentChannel.IconCssClass;
}
var pwItems = new PanelWidget();
phContentChannelGrids.Controls.Add( pwItems );
pwItems.ID = string.Format( "pwItems_{0}", contentChannel.Id );
pwItems.Title = string.Format( "<i class='{0}'></i> {1}", iconClass, contentChannel.Name );
pwItems.Expanded = ExpandedPanels.Contains( contentChannel.Id );
var divItems = new HtmlGenericControl( "div" );
pwItems.Controls.Add( divItems );
divItems.ID = string.Format( "divItems_{0}", contentChannel.Id );
divItems.AddCssClass( "grid" );
divItems.AddCssClass( "grid-panel" );
Grid gItems = new Grid();
divItems.Controls.Add( gItems );
gItems.ID = string.Format( "gItems_{0}", contentChannel.Id );
gItems.DataKeyNames = new string[] { "Id" };
gItems.EmptyDataText = "No Items Found";
gItems.RowItemText = "Item";
gItems.AllowSorting = true;
gItems.Actions.ShowAdd = canEdit;
gItems.IsDeleteEnabled = canEdit;
gItems.Actions.AddClick += gItems_Add;
gItems.RowSelected += gItems_Edit;
gItems.GridRebind += gItems_GridRebind;
gItems.Columns.Add( new RockBoundField
{
DataField = "Title",
HeaderText = "Title",
SortExpression = "Title"
} );
if ( contentChannel.ContentChannelType.IncludeTime )
{
gItems.Columns.Add( new DateTimeField
{
DataField = "StartDateTime",
HeaderText = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active",
SortExpression = "StartDateTime"
} );
if ( contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
{
gItems.Columns.Add( new DateTimeField
{
DataField = "ExpireDateTime",
HeaderText = "Expire",
SortExpression = "ExpireDateTime"
} );
}
}
else
{
gItems.Columns.Add( new DateField
{
DataField = "StartDateTime",
HeaderText = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active",
SortExpression = "StartDateTime"
} );
if ( contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
{
gItems.Columns.Add( new DateField
{
DataField = "ExpireDateTime",
HeaderText = "Expire",
SortExpression = "ExpireDateTime"
} );
}
}
if ( !contentChannel.ContentChannelType.DisablePriority )
{
var priorityField = new RockBoundField
{
DataField = "Priority",
HeaderText = "Priority",
SortExpression = "Priority",
DataFormatString = "{0:N0}",
};
priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
gItems.Columns.Add( priorityField );
}
// Add attribute columns
int entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.ContentChannelItem ) ).Id;
string qualifier = contentChannel.ContentChannelTypeId.ToString();
foreach ( var attribute in new AttributeService( rockContext ).Queryable()
.Where( a =>
a.EntityTypeId == entityTypeId &&
a.IsGridColumn &&
a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
a.EntityTypeQualifierValue.Equals( qualifier ) )
.OrderBy( a => a.Order )
.ThenBy( a => a.Name ) )
{
string dataFieldExpression = attribute.Key;
bool columnExists = gItems.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
if ( !columnExists )
{
AttributeField boundField = new AttributeField();
boundField.DataField = dataFieldExpression;
boundField.HeaderText = attribute.Name;
boundField.SortExpression = string.Empty;
var attributeCache = Rock.Web.Cache.AttributeCache.Read( attribute.Id );
if ( attributeCache != null )
{
boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
}
gItems.Columns.Add( boundField );
}
}
if ( contentChannel.RequiresApproval )
{
var statusField = new BoundField();
gItems.Columns.Add( statusField );
statusField.DataField = "Status";
statusField.HeaderText = "Status";
statusField.SortExpression = "Status";
statusField.HtmlEncode = false;
}
var deleteField = new DeleteField();
gItems.Columns.Add( deleteField );
deleteField.Click += gItems_Delete;
}
}
else
{
this.Visible = false;
}
}
/// <summary>
/// Binds the grid.
/// </summary>
private void BindGrids()
{
if ( ContentChannels.Any() )
{
var allContentItems = new EventItemOccurrenceChannelItemService( new RockContext() )
.Queryable()
.Where( c => c.EventItemOccurrenceId == OccurrenceId.Value )
.Select( c => c.ContentChannelItem )
.ToList();
foreach ( var contentChannel in ContentChannels )
{
var pwItems = phContentChannelGrids.FindControl( string.Format( "pwItems_{0}", contentChannel.Id ) ) as PanelWidget;
if ( pwItems != null )
{
var gItems = pwItems.FindControl( string.Format( "gItems_{0}", contentChannel.Id ) ) as Grid;
if ( gItems != null )
{
var contentItems = allContentItems
.Where( c => c.ContentChannelId == contentChannel.Id );
var items = new List<ContentChannelItem>();
foreach ( var item in contentItems.ToList() )
{
items.Add( item );
}
SortProperty sortProperty = gItems.SortProperty;
if ( sortProperty != null )
{
items = items.AsQueryable().Sort( sortProperty ).ToList();
}
else
{
items = items.OrderByDescending( p => p.StartDateTime ).ToList();
}
gItems.ObjectList = new Dictionary<string, object>();
items.ForEach( i => gItems.ObjectList.Add( i.Id.ToString(), i ) );
gItems.EntityTypeId = EntityTypeCache.Read<ContentChannelItem>().Id;
gItems.DataSource = items.Select( i => new
{
i.Id,
i.Guid,
i.Title,
i.StartDateTime,
i.ExpireDateTime,
i.Priority,
Status = DisplayStatus( i.Status )
} ).ToList();
gItems.DataBind();
}
}
}
}
}
private string DisplayStatus (ContentChannelItemStatus contentItemStatus)
{
string labelType = "default";
if ( contentItemStatus == ContentChannelItemStatus.Approved )
{
labelType = "success";
}
else if ( contentItemStatus == ContentChannelItemStatus.Denied )
{
labelType = "danger";
}
return string.Format( "<span class='label label-{0}'>{1}</span>", labelType, contentItemStatus.ConvertToString() );
}
private void NavigateToDetailPage( int contentItemId, int? contentChannelId = null )
{
var qryParams = new Dictionary<string, string>();
qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) );
qryParams.Add( "EventItemId", PageParameter( "EventItemId" ) );
qryParams.Add( "EventItemOccurrenceId", PageParameter( "EventItemOccurrenceId" ) );
qryParams.Add( "ContentItemId", contentItemId.ToString() );
if ( contentChannelId.HasValue )
{
qryParams.Add( "ContentChannelId", contentChannelId.Value.ToString() );
}
NavigateToLinkedPage( "DetailPage", qryParams );
}
#endregion
}
} | 41.700599 | 171 | 0.502537 | [
"Apache-2.0",
"Unlicense"
] | ThursdayChurch/rockweb.thursdaychurch.org | Blocks/Event/CalendarContentChannelItemList.ascx.cs | 20,894 | C# |
using System;
using NUnit.Framework;
using UnityEngine;
namespace Mirror.Tests.RemoteAttrributeTest
{
class RpcNetworkIdentityBehaviour : NetworkBehaviour
{
public event Action<NetworkIdentity> onSendNetworkIdentityCalled;
public event Action<GameObject> onSendGameObjectCalled;
public event Action<NetworkBehaviour> onSendNetworkBehaviourCalled;
public event Action<RpcNetworkIdentityBehaviour> onSendNetworkBehaviourDerivedCalled;
[ClientRpc]
public void SendNetworkIdentity(NetworkIdentity value)
{
onSendNetworkIdentityCalled?.Invoke(value);
}
[ClientRpc]
public void SendGameObject(GameObject value)
{
onSendGameObjectCalled?.Invoke(value);
}
[ClientRpc]
public void SendNetworkBehaviour(NetworkBehaviour value)
{
onSendNetworkBehaviourCalled?.Invoke(value);
}
[ClientRpc]
public void SendNetworkBehaviourDerived(RpcNetworkIdentityBehaviour value)
{
onSendNetworkBehaviourDerivedCalled?.Invoke(value);
}
}
[Description("Test for sending NetworkIdentity fields (NI/GO/NB) in RPC")]
public class RpcNetworkIdentityTest : RemoteTestBase
{
[Test]
public void RpcCanSendNetworkIdentity()
{
// spawn with owner
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour hostBehaviour, NetworkServer.localConnection);
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity expected, out RpcNetworkIdentityBehaviour _, NetworkServer.localConnection);
int callCount = 0;
hostBehaviour.onSendNetworkIdentityCalled += actual =>
{
callCount++;
Assert.That(actual, Is.EqualTo(expected));
};
hostBehaviour.SendNetworkIdentity(expected);
ProcessMessages();
Assert.That(callCount, Is.EqualTo(1));
}
[Test]
public void RpcCanSendGameObject()
{
// spawn with owner
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour hostBehaviour, NetworkServer.localConnection);
CreateNetworkedAndSpawn(out GameObject expected, out NetworkIdentity _, out RpcNetworkIdentityBehaviour _, NetworkServer.localConnection);
int callCount = 0;
hostBehaviour.onSendGameObjectCalled += actual =>
{
callCount++;
Assert.That(actual, Is.EqualTo(expected));
};
hostBehaviour.SendGameObject(expected);
ProcessMessages();
Assert.That(callCount, Is.EqualTo(1));
}
[Test]
public void RpcCanSendNetworkBehaviour()
{
// spawn with owner
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour hostBehaviour, NetworkServer.localConnection);
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour expected, NetworkServer.localConnection);
int callCount = 0;
hostBehaviour.onSendNetworkBehaviourCalled += actual =>
{
callCount++;
Assert.That(actual, Is.EqualTo(expected));
};
hostBehaviour.SendNetworkBehaviour(expected);
ProcessMessages();
Assert.That(callCount, Is.EqualTo(1));
}
[Test]
public void RpcCanSendNetworkBehaviourDerived()
{
// spawn with owner
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour hostBehaviour, NetworkServer.localConnection);
CreateNetworkedAndSpawn(out GameObject _, out NetworkIdentity _, out RpcNetworkIdentityBehaviour expected, NetworkServer.localConnection);
int callCount = 0;
hostBehaviour.onSendNetworkBehaviourDerivedCalled += actual =>
{
callCount++;
Assert.That(actual, Is.EqualTo(expected));
};
hostBehaviour.SendNetworkBehaviourDerived(expected);
ProcessMessages();
Assert.That(callCount, Is.EqualTo(1));
}
}
}
| 38.382609 | 155 | 0.644767 | [
"MIT"
] | 10allday/OpenMMO | Plugins/3rdParty/Mirror/Tests/Editor/RpcNetworkIdentityTest.cs | 4,414 | C# |
using System;
using System.Collections;
using TripolistMailAdapter;
namespace TripolisDialogueAdapter.Action
{
class ContactAction
{
private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ContactAction));
private cn.tripolis.dialogue.contact.ContactService contactService = null;
private cn.tripolis.dialogue.contact.AuthInfo contactAuthInfo = null;
private const String OK_RESULT = MailAdapter.OK_RESULT;
private string userName;
private string password;
private string client;
/// <summary>
/// Initial the webservice API.
/// </summary>
/// <param name="client">client</param>
/// <param name="userName">user name</param>
/// <param name="password">password</param>
public ContactAction(String client, String userName, String password, System.Net.WebProxy oWebProxy)
{
this.client = client;
this.userName = userName;
this.password = password;
contactService = new cn.tripolis.dialogue.contact.ContactService();
contactAuthInfo = new cn.tripolis.dialogue.contact.AuthInfo
{
client = client,
username = userName,
password = password
};
contactService.authInfo = contactAuthInfo;
contactService.Proxy = oWebProxy;
}
/// <summary>
/// Create contact
/// </summary>
/// <param name="contactDatabaseId">contact database id</param>
/// <param name="contactJsonList">contact list</param>
/// <returns>contact id</returns>
public String createContact(String contactDatabaseId, ArrayList contactJsonList)
{
if (logger.IsDebugEnabled)
{
logger.Debug("createContact:createContactcontactDatabaseId=" + contactDatabaseId );
}
String result = OK_RESULT;
ContactDatabaseFieldAction contactDatabaseFieldAction = new ContactDatabaseFieldAction(client, userName, password, (System.Net.WebProxy)contactService.Proxy);
Hashtable contactFieldTable = contactDatabaseFieldAction.getContactDatabaseFields(contactDatabaseId);
foreach (String str in contactJsonList)
{
int index = 0;
if (!String.IsNullOrEmpty(str))
{
String[] arrContact = str.Split(',');
cn.tripolis.dialogue.contact.CreateContactRequest request = new cn.tripolis.dialogue.contact.CreateContactRequest
{
contactDatabaseId = contactDatabaseId,
contactFields = new cn.tripolis.dialogue.contact.ContactFieldValue[arrContact.Length]
};
foreach (String strContact in arrContact)
{
String[] arryFiled = strContact.Split(new[] { "#" }, StringSplitOptions.None);
cn.tripolis.dialogue.contact.ContactFieldValue field = new cn.tripolis.dialogue.contact.ContactFieldValue
{
name = arryFiled[0].ToLower(),
value = arryFiled[1]
};
request.contactFields.SetValue(field, index++);
//add contact filed to table
if (contactFieldTable != null && !contactFieldTable.ContainsKey(field.name))
{
contactDatabaseFieldAction.addContactField(contactDatabaseId, field.name, field.value);
}
}
try
{
cn.tripolis.dialogue.contact.IDResponse response = contactService.create(request);
result = response.id;
if (logger.IsDebugEnabled)
{
logger.Debug("new contact id=" + result);
}
}
catch (System.Web.Services.Protocols.SoapException ex)
{
// if the error is not caused by exist id, continue the loop
if (!Util.isCodeExist(ex.Detail) || Util.getExistId(ex.Detail).Equals(""))
{
result = ex.Detail.InnerXml;
if (logger.IsDebugEnabled)
{
logger.Debug("error happens in create contact, error is" + result);
}
continue;
// throw new Exception(ex.Detail.InnerXml);
}
result = Util.getExistId(ex.Detail);
if (logger.IsDebugEnabled)
{
logger.Debug("exist contact id=" + result);
}
}
// addContactToGroup(result, contactGroupId);
}
}
return result;
}
/// <summary>
/// add contact to group
/// </summary>
/// <param name="contactId">contact Id</param>
/// <param name="contactGroupId">contact group id</param>
/// <returns></returns>
private String addContactToGroup(String contactId, String contactGroupId)
{
if (logger.IsDebugEnabled)
{
logger.Debug("addContactToGroup:contactId=" + contactId + ",contactGroupId=" + contactGroupId);
}
String result;
cn.tripolis.dialogue.contact.AddToContactGroupRequest groupRequest = new cn.tripolis.dialogue.contact.AddToContactGroupRequest();
try
{
cn.tripolis.dialogue.contact.ContactGroupSubscriptionRequestObject subOBject = new cn.tripolis.dialogue.contact.ContactGroupSubscriptionRequestObject();
groupRequest.contactId = contactId;
subOBject.contactGroupId = contactGroupId;//"MjYwMTMyNjAot_oDDCr0mA";
subOBject.confirmed = true;
groupRequest.contactGroupSubscriptions = new cn.tripolis.dialogue.contact.ContactGroupSubscriptionRequestObject[1];
groupRequest.contactGroupSubscriptions.SetValue(subOBject, 0);
cn.tripolis.dialogue.contact.IDResponse response = contactService.addToContactGroup(groupRequest);
result = response.id;
}
catch (System.Web.Services.Protocols.SoapException ex)
{
if (!Util.isCodeExist(ex.Detail) || Util.getExistId(ex.Detail).Equals(""))
{
result = ex.Detail.InnerXml;
if (logger.IsDebugEnabled)
{
logger.Debug("error happens in add contact to contact group, error is" + result);
}
throw new Exception(ex.Detail.InnerXml);
}
result = Util.getExistId(ex.Detail);
}
return result;
}
private String getCommunicateHistory(String contactId)
{
if (logger.IsDebugEnabled)
{
logger.Debug("getCommunicateHistory:contactId=" + contactId);
}
String result;
cn.tripolis.dialogue.contact.GetCommunicationHistoryRequest request = new cn.tripolis.dialogue.contact.GetCommunicationHistoryRequest();
try
{
request.contactId = contactId;
request.includeFullDetails = true;
cn.tripolis.dialogue.contact.CommunicationHistoryResponse response = contactService.getCommunicationHistory(request);
result = response.message;
}
catch (System.Web.Services.Protocols.SoapException ex)
{
if (!Util.isCodeExist(ex.Detail) || Util.getExistId(ex.Detail).Equals(""))
{
result = ex.Detail.InnerXml;
if (logger.IsDebugEnabled)
{
logger.Debug("error happens in add contact to contact group, error is" + result);
}
throw new Exception(ex.Detail.InnerXml);
}
result = Util.getExistId(ex.Detail);
}
return result;
}
}
}
| 42.221154 | 170 | 0.526076 | [
"Apache-2.0"
] | ZhouAnPing/Mail | Mail/TripolisDialogueAdapter/Action/ContactAction.cs | 8,784 | C# |
using System;
namespace NWaves.Filters.OnePole
{
/// <summary>
/// Represents one-pole highpass filter.
/// </summary>
public class HighPassFilter : OnePoleFilter
{
/// <summary>
/// Gets cutoff frequency.
/// </summary>
public double Frequency { get; protected set; }
/// <summary>
/// Constructs <see cref="HighPassFilter"/> with given cutoff <paramref name="frequency"/>.
/// </summary>
/// <param name="frequency">Cutoff frequency</param>
public HighPassFilter(double frequency)
{
SetCoefficients(frequency);
}
/// <summary>
/// Sets filter coefficients based on given cutoff <paramref name="frequency"/>.
/// </summary>
/// <param name="frequency">Cutoff frequency</param>
private void SetCoefficients(double frequency)
{
Frequency = frequency;
_a[0] = 1;
_a[1] = (float)(Math.Exp(-2 * Math.PI * (0.5 - frequency)));
_b[0] = 1 - _a[1];
}
/// <summary>
/// Changes filter coefficients (preserving the state of the filter).
/// </summary>
/// <param name="frequency">Cutoff frequency</param>
public void Change(double frequency)
{
SetCoefficients(frequency);
}
}
}
| 28.541667 | 99 | 0.545255 | [
"MIT"
] | ar1st0crat/NWaves | NWaves/Filters/OnePole/HighPassFilter.cs | 1,370 | C# |
// -----------------------------------------------------------------------
// <copyright file="DesignTimeDefaultDbContextFactory.cs" company="OSharp开源团队">
// Copyright (c) 2014-2020 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2020-08-25 23:16</last-date>
// -----------------------------------------------------------------------
using System;
using Microsoft.Extensions.DependencyInjection;
using OSharp.Entity;
namespace Liuliu.Demo.Web.Startups
{
public class DesignTimeDefaultDbContextFactory : DesignTimeDbContextFactoryBase<DefaultDbContext>
{
public DesignTimeDefaultDbContextFactory()
: base(null)
{ }
public DesignTimeDefaultDbContextFactory(IServiceProvider serviceProvider)
: base(serviceProvider)
{ }
/// <summary>
/// 创建设计时使用的ServiceProvider,主要用于执行 Add-Migration 功能
/// </summary>
/// <returns></returns>
protected override IServiceProvider CreateDesignTimeServiceProvider()
{
IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider provider = services.BuildServiceProvider();
return provider;
}
}
}
| 32.27907 | 101 | 0.590778 | [
"Apache-2.0"
] | 1051324354/osharp | samples/web/Liuliu.Demo.Web/Startups/DesignTimeDefaultDbContextFactory.cs | 1,438 | C# |
using MoneyNote.Identity.Enities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyNote.YoutubeManagement.Models
{
public class JsGridFilter
{
public int pageIndex { get; set; } = 0;
public int pageSize { get; set; } = 0;
public Guid? parentId { get; set; } = Guid.Empty;
public Guid? contentId { get; set; } = Guid.Empty;
public List<Guid>? categoryIds { get; set; } = new List<Guid>();
public bool? findRootItem { get; set; } = false;
public string title { get; set; }
public string thumbnail { get; set; }
public string description { get; set; }
public string urlRef { get; set; }
public string moduleCode { get; set; }
public string permissionCode { get; set; }
/// <summary>
/// image | video | all
/// </summary>
public string Type { get; set; }
/// <summary>
/// newest | oldest | random
/// </summary>
public string SortType { get; set; }
}
public interface IJsGridResult<T>
{
public List<T> data { get; set; }
public long itemsCount { get; set; }
}
public class CategoryJsGridResult : IJsGridResult<CmsCategory>
{
public List<CmsCategory> data { get; set; }
public long itemsCount { get; set; }
}
public class ContentJsGridResult: IJsGridResult<CmsContent>
{
public List<CmsContent> data { get; set; }
public long itemsCount { get; set; }
//public List<CmsCategory> listCategory { get; set; }
public List<CmsRelation.Dto> listRelation { get; set; }
}
public class UserJsGridResult : IJsGridResult<User>
{
public List<User> data { get; set; }
public long itemsCount { get; set; }
//public List<CmsCategory> listCategory { get; set; }
public List<UserAcl.Dto> ListUserAcl { get; set; }
}
public class ContentRequest
{
public Guid id { get; set; }
}
public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
public class ContentRelatedRequest
{
public Guid? ContentId { get; set; }
/// <summary>
/// image | video | all
/// </summary>
public string Type { get; set; }
/// <summary>
/// newest | oldest | random
/// </summary>
public string SortType { get; set; }
public string Keywords { get; set; }
public int? pageIndex { get; set; } = 0;
public int? pageSize { get; set; } = 0;
}
}
| 28.368421 | 72 | 0.571058 | [
"MIT"
] | badpaybad/youtube-video-management | MoneyNote.YoutubeManagement/Models/JsGridFilter.cs | 2,697 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
namespace Duktape
{
using UnityEngine;
using UnityEditor;
public class EventAdderCodeGen : IDisposable
{
protected CodeGenerator cg;
protected EventBindingInfo bindingInfo;
public EventAdderCodeGen(CodeGenerator cg, EventBindingInfo bindingInfo)
{
this.cg = cg;
this.bindingInfo = bindingInfo;
var eventInfo = this.bindingInfo.eventInfo;
var declaringType = eventInfo.DeclaringType;
var caller = this.cg.AppendGetThisCS(bindingInfo);
this.cg.cs.AppendLine("{0} value;", this.cg.bindingManager.GetCSTypeFullName(eventInfo.EventHandlerType));
this.cg.cs.AppendLine(this.cg.bindingManager.GetDuktapeGetter(eventInfo.EventHandlerType, "ctx", "0", "value"));
this.cg.cs.AppendLine("{0}.{1} += value;", caller, eventInfo.Name);
if (declaringType.IsValueType && !eventInfo.GetAddMethod().IsStatic)
{
// 非静态结构体属性修改, 尝试替换实例
this.cg.cs.AppendLine($"duk_rebind_this(ctx, {caller});");
}
this.cg.cs.AppendLine("return 0;");
}
public virtual void Dispose()
{
}
}
public class EventRemoverCodeGen : IDisposable
{
protected CodeGenerator cg;
protected EventBindingInfo bindingInfo;
public EventRemoverCodeGen(CodeGenerator cg, EventBindingInfo bindingInfo)
{
this.cg = cg;
this.bindingInfo = bindingInfo;
var eventInfo = this.bindingInfo.eventInfo;
var declaringType = eventInfo.DeclaringType;
var caller = this.cg.AppendGetThisCS(bindingInfo);
this.cg.cs.AppendLine("{0} value;", this.cg.bindingManager.GetCSTypeFullName(eventInfo.EventHandlerType));
this.cg.cs.AppendLine(this.cg.bindingManager.GetDuktapeGetter(eventInfo.EventHandlerType, "ctx", "0", "value"));
this.cg.cs.AppendLine("{0}.{1} -= value;", caller, eventInfo.Name);
if (declaringType.IsValueType && !eventInfo.GetAddMethod().IsStatic)
{
// 非静态结构体属性修改, 尝试替换实例
this.cg.cs.AppendLine($"duk_rebind_this(ctx, {caller});");
}
this.cg.cs.AppendLine("return 0;");
}
public virtual void Dispose()
{
}
}
public class EventProxyCodeGen : IDisposable
{
protected CodeGenerator cg;
protected EventBindingInfo eventBindingInfo;
public EventProxyCodeGen(CodeGenerator cg, EventBindingInfo eventBindingInfo)
{
this.cg = cg;
this.eventBindingInfo = eventBindingInfo;
var eventInfo = this.eventBindingInfo.eventInfo;
var declaringType = eventInfo.DeclaringType;
var tsFieldVar = BindingManager.GetTSVariable(eventBindingInfo.regName);
this.cg.cs.AppendLine("DuktapeDLL.duk_push_this(ctx);");
this.cg.cs.AppendLine($"duk_add_event_instanced(ctx, \"{tsFieldVar}\", {this.eventBindingInfo.adderName}, {this.eventBindingInfo.removerName}, -1);");
this.cg.cs.AppendLine("DuktapeDLL.duk_remove(ctx, -2);");
this.cg.cs.AppendLine("return 1;");
}
public virtual void Dispose()
{
}
}
}
| 36.729167 | 163 | 0.606069 | [
"MIT"
] | ialex32x/duktape-framework | Assets/Duktape/Editor/CodeGenHelper_Event.cs | 3,590 | C# |
using Ardalis.Specification.UnitTests.Fixture.Specs;
using FluentAssertions;
using Xunit;
namespace Ardalis.Specification.UnitTests.BuilderTests
{
public class SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution
{
[Fact]
public void DoesNothing_GivenSpecWithoutAsNoTrackingWithIdentityResolution()
{
var spec = new StoreEmptySpec();
spec.AsNoTrackingWithIdentityResolution.Should().Be(false);
}
[Fact]
public void DoesNothing_GivenAsNoTrackingWithIdentityResolutionWithFalseCondition()
{
var spec = new CompanyByIdWithFalseConditions(1);
spec.AsNoTrackingWithIdentityResolution.Should().Be(false);
}
[Fact]
public void FlagsAsNoTracking_GivenSpecWithAsNoTrackingWithIdentityResolution()
{
var spec = new CompanyByIdAsUntrackedWithIdentityResolutionSpec(1);
spec.AsNoTrackingWithIdentityResolution.Should().Be(true);
}
}
}
| 27.441176 | 87 | 0.768489 | [
"MIT"
] | Allann/Specification | Specification/tests/Ardalis.Specification.UnitTests/BuilderTests/SpecificationBuilderExtensions_AsNoTrackingWithIdentityResolution.cs | 935 | C# |
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EnergonSoftware.Core.IO;
using EnergonSoftware.Core.Packet;
namespace EnergonSoftware.Backend.Packet
{
/// <summary>
///
/// </summary>
/// <remarks>
/// Binary Packet Format:
/// MARKER | ID | ENCODING | CONTENT TYPE | CONTENT LEN | SEPARATOR | CONTENT
/// </remarks>
[Serializable]
public class NetworkPacket : IPacket
{
#region Id Generator
private static int _nextId;
private static int NextId => ++_nextId;
#endregion
/// <summary>
/// The packet type
/// </summary>
public const string PacketType = "Network";
/// <summary>
/// The packet header (ESNP)
/// </summary>
public static readonly byte[] Header = { (byte)'E', (byte)'S', (byte)'N', (byte)'P' };
/// <summary>
/// The separator between the packet header and the conten
/// </summary>
public static readonly byte[] Separator = { (byte)'\r', (byte)'\n' };
public string Type => PacketType;
public int Id { get; protected set; } = NextId;
public string ContentType { get; set; }
public string Encoding { get; set; }
public int ContentLength => Content?.Length ?? 0;
public byte[] Content { get; set; }
public async Task SerializeAsync(Stream stream)
{
await stream.WriteAsync(Header, 0, Header.Length).ConfigureAwait(false);
await stream.WriteNetworkAsync(Id).ConfigureAwait(false);
await stream.WriteNetworkAsync(ContentType).ConfigureAwait(false);
await stream.WriteNetworkAsync(Encoding).ConfigureAwait(false);
await stream.WriteNetworkAsync(ContentLength).ConfigureAwait(false);
await stream.WriteAsync(Separator, 0, Separator.Length).ConfigureAwait(false);
await stream.WriteAsync(Content, 0, Content.Length).ConfigureAwait(false);
}
public async Task<bool> DeserializeAsync(Stream stream)
{
// look for the header separator
long separatorIndex = await stream.IndexOfAsync(Separator).ConfigureAwait(false);
if(-1 == separatorIndex) {
return false;
}
// read the header values
byte[] header = new byte[Header.Length];
await stream.ReadAsync(header, 0, header.Length).ConfigureAwait(false);
if(!header.SequenceEqual(Header)) {
throw new PacketException("Invalid packet header!");
}
Id = await stream.ReadNetworkIntAsync().ConfigureAwait(false);
ContentType = await stream.ReadNetworkStringAsync().ConfigureAwait(false);
Encoding = await stream.ReadNetworkStringAsync().ConfigureAwait(false);
int contentLength = await stream.ReadNetworkIntAsync().ConfigureAwait(false);
// make sure we have the entire message
if(stream.GetRemaining() < Separator.Length + contentLength) {
return false;
}
// consume the separator
await stream.ConsumeAsync(Separator.Length).ConfigureAwait(false);
// read the content
Content = new byte[contentLength];
await stream.ReadAsync(Content, 0, Content.Length).ConfigureAwait(false);
return true;
}
public int CompareTo(object obj)
{
NetworkPacket rhs = obj as NetworkPacket;
if(null == rhs) {
return 0;
}
return Id - rhs.Id;
}
public override bool Equals(object obj)
{
NetworkPacket packet = obj as NetworkPacket;
if(null == packet) {
return false;
}
return Type == packet.Type && Id == packet.Id;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return $"NetworkPacket(Type: {Type}, Id: {Id}, ContentType: {ContentType}, Encoding: {Encoding}, ContentLength: {ContentLength})";
}
}
}
| 32.945736 | 142 | 0.585412 | [
"Apache-2.0"
] | Luminoth/EnergonBackend | Backend/Packet/NetworkPacket.cs | 4,252 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MeetUpPlanner.Shared
{
/// <summary>
/// Describes a "tracking report": A list of all persons who had participated with the user in an event in the past
/// </summary>
public class TrackingReport
{
/// <summary>
/// Details about the requested report
/// </summary>
public TrackingReportRequest ReportRequest { get; set; }
public DateTime CreationDate { get; set; } = DateTime.Now;
/// <summary>
/// List of all events in scope
/// </summary>
public IEnumerable<CompanionCalendarInfo> CalendarList { get; set; }
/// <summary>
/// List of all companions in scope
/// </summary>
public IList<Companion> CompanionList { get; set; }
public TrackingReport()
{
}
/// <summary>
/// Constructs a TrackingReport with the given request
/// </summary>
/// <param name="request"></param>
public TrackingReport(TrackingReportRequest request)
{
ReportRequest = request;
}
}
}
| 29.846154 | 119 | 0.585052 | [
"MIT"
] | BlazorHub/MeetUpPlanner | MeetUpPlanner/Shared/TrackingReport.cs | 1,166 | C# |
namespace MyForum.Web.ViewModels.Votes
{
public class VoteResponseModel
{
public int VotesCount { get; set; }
}
}
| 16.875 | 43 | 0.644444 | [
"MIT"
] | BorisLechev/MyForum | Server/Web/MyForum.Web.ViewModels/Votes/VoteResponseModel.cs | 137 | C# |
using System;
using Csla.Core;
using System.ComponentModel;
using Csla.Serialization.Mobile;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace Csla
{
/// <summary>
/// This is the base class from which most business collections
/// or lists will be derived.
/// </summary>
/// <typeparam name="C">Type of the child objects contained in the list.</typeparam>
public interface IBusinessListBase<C>
: IEditableCollection, IBusinessObject, ISupportUndo, ITrackStatus, IUndoableObject,
ICloneable, ISavable, IParent, INotifyBusy, INotifyUnhandledAsyncException,
IObservableBindingList, INotifyChildChanged, ISerializationNotification, IMobileObject,
INotifyCollectionChanged, INotifyPropertyChanged,
ICollection<C>, IList<C>, IEnumerable<C>
{ }
}
| 35.565217 | 93 | 0.765281 | [
"MIT"
] | Alstig/csla | Source/Csla.Shared/IBusinessListBase.cs | 820 | C# |
namespace Ecology.API.Models
{
public class SpeciesViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
| 15.8 | 40 | 0.575949 | [
"MIT"
] | encounter12/AnimalHabitat | EcologyServer/Ecology.API/Models/SpeciesViewModel.cs | 160 | C# |
/*
Sharp86 - 8086 Emulator
Copyright (C) 2017-2018 Topten Software.
Sharp86 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Sharp86 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Sharp86. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PetaJson;
namespace Sharp86
{
class ExpressionBreakPoint : BreakPoint
{
public ExpressionBreakPoint()
{
}
public ExpressionBreakPoint(Expression expression)
{
_expression = expression;
}
[Json("expression")]
public string ExpressionText
{
get { return _expression == null ? null : _expression.OriginalExpression; }
set { _expression = value == null ? null : new Expression(value); }
}
Expression _expression;
object _prevValue;
public override string ToString()
{
return base.ToString(string.Format("expr {0}", _expression == null ? "null" : _expression.OriginalExpression));
}
public override string EditString
{
get
{
return string.Format("expr {0}", _expression.OriginalExpression);
}
}
public override bool ShouldBreak(DebuggerCore debugger)
{
var newValue = _expression.Eval(debugger.ExpressionContext);
if (_prevValue == null)
{
_prevValue = newValue;
return false;
}
bool changed = (bool)Operators.compare_ne(newValue, _prevValue);
_prevValue = newValue;
return changed;
}
}
}
| 27.948718 | 123 | 0.633028 | [
"MIT"
] | mediaexplorer74/Win3Mu | Sharp86/Sharp86DebuggerCore/ExpressionBreakPoint.cs | 2,182 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.CognitoIdentityProvider.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InvalidParameterException Object
/// </summary>
public class InvalidParameterExceptionUnmarshaller : IErrorResponseUnmarshaller<InvalidParameterException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public InvalidParameterException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public InvalidParameterException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
InvalidParameterException unmarshalledObject = new InvalidParameterException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static InvalidParameterExceptionUnmarshaller _instance = new InvalidParameterExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InvalidParameterExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.882353 | 141 | 0.678033 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/CognitoIdentityProvider/Generated/Model/Internal/MarshallTransformations/InvalidParameterExceptionUnmarshaller.cs | 3,050 | C# |
namespace UblTr.Common
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("Declaration", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable = false)]
public partial class DeclarationType
{
private NameType1[] nameField;
private DeclarationTypeCodeType declarationTypeCodeField;
private DescriptionType[] descriptionField;
private EvidenceSuppliedType[] evidenceSuppliedField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Name", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public NameType1[] Name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public DeclarationTypeCodeType DeclarationTypeCode
{
get
{
return this.declarationTypeCodeField;
}
set
{
this.declarationTypeCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Description", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public DescriptionType[] Description
{
get
{
return this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("EvidenceSupplied")]
public EvidenceSuppliedType[] EvidenceSupplied
{
get
{
return this.evidenceSuppliedField;
}
set
{
this.evidenceSuppliedField = value;
}
}
}
} | 31.92 | 170 | 0.585631 | [
"MIT"
] | enisgurkann/UblTr | Ubl-Tr/Common/CommonAggregateComponents/DeclarationType.cs | 2,394 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletMove : MonoBehaviour {
public GameObject bullet;
float elapsedTime = 0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(0, 0, 10 * Time.deltaTime);
elapsedTime += Time.deltaTime;
if(elapsedTime >= 5)
{
Destroy(bullet);
}
}
}
| 17.555556 | 55 | 0.624473 | [
"MIT"
] | RustedBot/Game-Engines | Lab 1/Assets/BulletMove.cs | 476 | C# |
namespace Machete.X12Schema.V5010
{
using X12;
public interface L2330C_837I :
X12Layout
{
Segment<NM1> AttendingProvider { get; }
SegmentList<REF> SecondaryIdentification { get; }
}
} | 18.076923 | 57 | 0.608511 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.X12Schema/Generated/V5010/Layouts/L2330C_837I.cs | 237 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Nsxt.Inputs
{
public sealed class PolicyVlanSegmentSubnetDhcpV6ConfigGetArgs : Pulumi.ResourceArgs
{
[Input("dnsServers")]
private InputList<string>? _dnsServers;
public InputList<string> DnsServers
{
get => _dnsServers ?? (_dnsServers = new InputList<string>());
set => _dnsServers = value;
}
[Input("domainNames")]
private InputList<string>? _domainNames;
public InputList<string> DomainNames
{
get => _domainNames ?? (_domainNames = new InputList<string>());
set => _domainNames = value;
}
[Input("excludedRanges")]
private InputList<Inputs.PolicyVlanSegmentSubnetDhcpV6ConfigExcludedRangeGetArgs>? _excludedRanges;
public InputList<Inputs.PolicyVlanSegmentSubnetDhcpV6ConfigExcludedRangeGetArgs> ExcludedRanges
{
get => _excludedRanges ?? (_excludedRanges = new InputList<Inputs.PolicyVlanSegmentSubnetDhcpV6ConfigExcludedRangeGetArgs>());
set => _excludedRanges = value;
}
[Input("leaseTime")]
public Input<int>? LeaseTime { get; set; }
[Input("preferredTime")]
public Input<int>? PreferredTime { get; set; }
[Input("serverAddress")]
public Input<string>? ServerAddress { get; set; }
[Input("sntpServers")]
private InputList<string>? _sntpServers;
public InputList<string> SntpServers
{
get => _sntpServers ?? (_sntpServers = new InputList<string>());
set => _sntpServers = value;
}
public PolicyVlanSegmentSubnetDhcpV6ConfigGetArgs()
{
}
}
}
| 33.245902 | 138 | 0.641026 | [
"ECL-2.0",
"Apache-2.0"
] | nvpnathan/pulumi-nsxt | sdk/dotnet/Inputs/PolicyVlanSegmentSubnetDhcpV6ConfigGetArgs.cs | 2,028 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreditsMenuController : UIMenuBase
{
// Update is called once per frame
new void Update()
{
base.Update();
if (Input.GetButtonDown("A_Button"))
{
if (_currentSelection == 0)
GetComponent<SceneLoader>().LoadByIndex(0);
}
}
}
| 19.666667 | 59 | 0.583535 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Q-ro/ColdLineElpoblado | Assets/Scripts/UI/CreditsMenuController.cs | 415 | C# |
#region
using LoESoft.Core;
#endregion
namespace LoESoft.GameServer.networking.outgoing
{
public class PETYARDUPDATE : OutgoingMessage
{
public int Type { get; set; }
public override MessageID ID => MessageID.PETYARDUPDATE;
public override Message CreateInstance() => new PETYARDUPDATE();
protected override void Read(NReader rdr)
{
Type = rdr.ReadInt32();
}
protected override void Write(NWriter wtr)
{
wtr.Write(Type);
}
}
} | 20.074074 | 72 | 0.608856 | [
"MIT"
] | Devwarlt/LOE-V7-SERVER | gameserver/networking/messages/outgoing/PETYARDUPDATE.cs | 544 | C# |
using System;
using System.Collections.Generic;
using ESC2.Library.Data.Interfaces;
// This file is generated from the database. Do not manually edit.
// Generated by: https://github.com/brian-nelson/repo-generator
// To extend the class beyond a POCO, create a additional partial class
// named AssetType.cs
namespace ESC2.Module.System.Data.DataObjects.Operational
{
public partial class AssetType : IDataObject<Guid>
{
public AssetType()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Version { get; set; }
public Guid? ImplementationGuideId { get; set; }
public Guid AssetGroupId { get; set; }
public Guid CreatedById { get; set; }
public DateTime CreatedOn { get; set; }
public Guid LastModifiedById { get; set; }
public DateTime LastModifiedOn { get; set; }
}
}
| 32.878788 | 71 | 0.642396 | [
"MIT"
] | brian-nelson/ESC2 | src/modules/System/ESC2.Module.System.Data/DataObjects/Operational/AssetType_generated.cs | 1,085 | C# |
namespace SharpIpp.Model
{
public enum ResolutionUnit
{
DotsPerInch = 3,
DotsPerCm = 4
}
} | 14.875 | 30 | 0.571429 | [
"MIT"
] | KittyDotNet/SharpIpp | SharpIpp/Model/ResolutionUnit.cs | 121 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("JobScheduleSample.Resource", IsApplication=true)]
namespace JobScheduleSample
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
}
public partial class Attribute
{
// aapt resource value: 0x7f010007
public const int font = 2130771975;
// aapt resource value: 0x7f010000
public const int fontProviderAuthority = 2130771968;
// aapt resource value: 0x7f010003
public const int fontProviderCerts = 2130771971;
// aapt resource value: 0x7f010004
public const int fontProviderFetchStrategy = 2130771972;
// aapt resource value: 0x7f010005
public const int fontProviderFetchTimeout = 2130771973;
// aapt resource value: 0x7f010001
public const int fontProviderPackage = 2130771969;
// aapt resource value: 0x7f010002
public const int fontProviderQuery = 2130771970;
// aapt resource value: 0x7f010006
public const int fontStyle = 2130771974;
// aapt resource value: 0x7f010008
public const int fontWeight = 2130771976;
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Boolean
{
// aapt resource value: 0x7f050000
public const int abc_action_bar_embed_tabs = 2131034112;
static Boolean()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Boolean()
{
}
}
public partial class Color
{
// aapt resource value: 0x7f070000
public const int notification_action_color_filter = 2131165184;
// aapt resource value: 0x7f070001
public const int notification_icon_bg_color = 2131165185;
// aapt resource value: 0x7f070002
public const int ripple_material_light = 2131165186;
// aapt resource value: 0x7f070003
public const int secondary_text_default_material_light = 2131165187;
static Color()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Color()
{
}
}
public partial class Dimension
{
// aapt resource value: 0x7f060004
public const int compat_button_inset_horizontal_material = 2131099652;
// aapt resource value: 0x7f060005
public const int compat_button_inset_vertical_material = 2131099653;
// aapt resource value: 0x7f060006
public const int compat_button_padding_horizontal_material = 2131099654;
// aapt resource value: 0x7f060007
public const int compat_button_padding_vertical_material = 2131099655;
// aapt resource value: 0x7f060008
public const int compat_control_corner_material = 2131099656;
// aapt resource value: 0x7f060009
public const int notification_action_icon_size = 2131099657;
// aapt resource value: 0x7f06000a
public const int notification_action_text_size = 2131099658;
// aapt resource value: 0x7f06000b
public const int notification_big_circle_margin = 2131099659;
// aapt resource value: 0x7f060001
public const int notification_content_margin_start = 2131099649;
// aapt resource value: 0x7f06000c
public const int notification_large_icon_height = 2131099660;
// aapt resource value: 0x7f06000d
public const int notification_large_icon_width = 2131099661;
// aapt resource value: 0x7f060002
public const int notification_main_column_padding_top = 2131099650;
// aapt resource value: 0x7f060003
public const int notification_media_narrow_margin = 2131099651;
// aapt resource value: 0x7f06000e
public const int notification_right_icon_size = 2131099662;
// aapt resource value: 0x7f060000
public const int notification_right_side_padding_top = 2131099648;
// aapt resource value: 0x7f06000f
public const int notification_small_icon_background_padding = 2131099663;
// aapt resource value: 0x7f060010
public const int notification_small_icon_size_as_large = 2131099664;
// aapt resource value: 0x7f060011
public const int notification_subtext_size = 2131099665;
// aapt resource value: 0x7f060012
public const int notification_top_pad = 2131099666;
// aapt resource value: 0x7f060013
public const int notification_top_pad_large_text = 2131099667;
static Dimension()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Dimension()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int notification_action_background = 2130837504;
// aapt resource value: 0x7f020001
public const int notification_bg = 2130837505;
// aapt resource value: 0x7f020002
public const int notification_bg_low = 2130837506;
// aapt resource value: 0x7f020003
public const int notification_bg_low_normal = 2130837507;
// aapt resource value: 0x7f020004
public const int notification_bg_low_pressed = 2130837508;
// aapt resource value: 0x7f020005
public const int notification_bg_normal = 2130837509;
// aapt resource value: 0x7f020006
public const int notification_bg_normal_pressed = 2130837510;
// aapt resource value: 0x7f020007
public const int notification_icon_background = 2130837511;
// aapt resource value: 0x7f02000a
public const int notification_template_icon_bg = 2130837514;
// aapt resource value: 0x7f02000b
public const int notification_template_icon_low_bg = 2130837515;
// aapt resource value: 0x7f020008
public const int notification_tile_bg = 2130837512;
// aapt resource value: 0x7f020009
public const int notify_panel_notification_icon_bg = 2130837513;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f09000e
public const int action_container = 2131296270;
// aapt resource value: 0x7f09001a
public const int action_divider = 2131296282;
// aapt resource value: 0x7f09000f
public const int action_image = 2131296271;
// aapt resource value: 0x7f090010
public const int action_text = 2131296272;
// aapt resource value: 0x7f09001b
public const int actions = 2131296283;
// aapt resource value: 0x7f090006
public const int async = 2131296262;
// aapt resource value: 0x7f090007
public const int blocking = 2131296263;
// aapt resource value: 0x7f090019
public const int chronometer = 2131296281;
// aapt resource value: 0x7f09000c
public const int download_button = 2131296268;
// aapt resource value: 0x7f09000b
public const int fibonacci_start_value = 2131296267;
// aapt resource value: 0x7f090008
public const int forever = 2131296264;
// aapt resource value: 0x7f090012
public const int icon = 2131296274;
// aapt resource value: 0x7f09001c
public const int icon_group = 2131296284;
// aapt resource value: 0x7f090015
public const int info = 2131296277;
// aapt resource value: 0x7f090009
public const int italic = 2131296265;
// aapt resource value: 0x7f090000
public const int line1 = 2131296256;
// aapt resource value: 0x7f090001
public const int line3 = 2131296257;
// aapt resource value: 0x7f09000a
public const int normal = 2131296266;
// aapt resource value: 0x7f090017
public const int notification_background = 2131296279;
// aapt resource value: 0x7f090013
public const int notification_main_column = 2131296275;
// aapt resource value: 0x7f090011
public const int notification_main_column_container = 2131296273;
// aapt resource value: 0x7f09000d
public const int results_textview = 2131296269;
// aapt resource value: 0x7f090016
public const int right_icon = 2131296278;
// aapt resource value: 0x7f090014
public const int right_side = 2131296276;
// aapt resource value: 0x7f090002
public const int tag_transition_group = 2131296258;
// aapt resource value: 0x7f090003
public const int text = 2131296259;
// aapt resource value: 0x7f090004
public const int text2 = 2131296260;
// aapt resource value: 0x7f090018
public const int time = 2131296280;
// aapt resource value: 0x7f090005
public const int title = 2131296261;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Integer
{
// aapt resource value: 0x7f0a0000
public const int status_bar_notification_info_maxnum = 2131361792;
static Integer()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Integer()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
// aapt resource value: 0x7f030001
public const int notification_action = 2130903041;
// aapt resource value: 0x7f030002
public const int notification_action_tombstone = 2130903042;
// aapt resource value: 0x7f030003
public const int notification_template_custom_big = 2130903043;
// aapt resource value: 0x7f030004
public const int notification_template_icon_group = 2130903044;
// aapt resource value: 0x7f030005
public const int notification_template_part_chronometer = 2130903045;
// aapt resource value: 0x7f030006
public const int notification_template_part_time = 2130903046;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040001
public const int app_name = 2130968577;
// aapt resource value: 0x7f040002
public const int fibonacci_button_text = 2130968578;
// aapt resource value: 0x7f040006
public const int fibonacci_calculation_in_progress = 2130968582;
// aapt resource value: 0x7f040007
public const int fibonacci_calculation_problem = 2130968583;
// aapt resource value: 0x7f040008
public const int fibonacci_calculation_result = 2130968584;
// aapt resource value: 0x7f040005
public const int fibonacci_start_textview = 2130968581;
// aapt resource value: 0x7f040003
public const int fibonacci_start_value_default = 2130968579;
// aapt resource value: 0x7f040004
public const int fibonacci_textview = 2130968580;
// aapt resource value: 0x7f040000
public const int status_bar_notification_info_overflow = 2130968576;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
public partial class Style
{
// aapt resource value: 0x7f080000
public const int TextAppearance_Compat_Notification = 2131230720;
// aapt resource value: 0x7f080001
public const int TextAppearance_Compat_Notification_Info = 2131230721;
// aapt resource value: 0x7f080006
public const int TextAppearance_Compat_Notification_Line2 = 2131230726;
// aapt resource value: 0x7f080002
public const int TextAppearance_Compat_Notification_Time = 2131230722;
// aapt resource value: 0x7f080003
public const int TextAppearance_Compat_Notification_Title = 2131230723;
// aapt resource value: 0x7f080004
public const int Widget_Compat_NotificationActionContainer = 2131230724;
// aapt resource value: 0x7f080005
public const int Widget_Compat_NotificationActionText = 2131230725;
static Style()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Style()
{
}
}
public partial class Styleable
{
public static int[] FontFamily = new int[] {
2130771968,
2130771969,
2130771970,
2130771971,
2130771972,
2130771973};
// aapt resource value: 0
public const int FontFamily_fontProviderAuthority = 0;
// aapt resource value: 3
public const int FontFamily_fontProviderCerts = 3;
// aapt resource value: 4
public const int FontFamily_fontProviderFetchStrategy = 4;
// aapt resource value: 5
public const int FontFamily_fontProviderFetchTimeout = 5;
// aapt resource value: 1
public const int FontFamily_fontProviderPackage = 1;
// aapt resource value: 2
public const int FontFamily_fontProviderQuery = 2;
public static int[] FontFamilyFont = new int[] {
16844082,
16844083,
16844095,
2130771974,
2130771975,
2130771976};
// aapt resource value: 0
public const int FontFamilyFont_android_font = 0;
// aapt resource value: 2
public const int FontFamilyFont_android_fontStyle = 2;
// aapt resource value: 1
public const int FontFamilyFont_android_fontWeight = 1;
// aapt resource value: 4
public const int FontFamilyFont_font = 4;
// aapt resource value: 3
public const int FontFamilyFont_fontStyle = 3;
// aapt resource value: 5
public const int FontFamilyFont_fontWeight = 5;
static Styleable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Styleable()
{
}
}
}
}
#pragma warning restore 1591
| 26.792381 | 111 | 0.703896 | [
"MIT"
] | topgenorth/xamarin.android-jobschedulersample | JobScheduleSample/Resources/Resource.Designer.cs | 14,066 | C# |
using TUNING;
using UnityEngine;
public class LiquidPumpingStationConfig : IBuildingConfig
{
public const string ID = "LiquidPumpingStation";
public override BuildingDef CreateBuildingDef()
{
BuildingDef obj = BuildingTemplates.CreateBuildingDef("LiquidPumpingStation", 2, 4, "waterpump_kanim", 100, 10f, BUILDINGS.CONSTRUCTION_MASS_KG.TIER4, MATERIALS.RAW_MINERALS, 1600f, BuildLocationRule.Anywhere, noise: NOISE_POLLUTION.NONE, decor: BUILDINGS.DECOR.NONE);
obj.Floodable = false;
obj.Entombable = true;
obj.AudioCategory = "Metal";
obj.AudioSize = "large";
obj.UtilityInputOffset = new CellOffset(0, 0);
obj.UtilityOutputOffset = new CellOffset(0, 0);
obj.DefaultAnimState = "on";
obj.ShowInBuildMenu = true;
return obj;
}
public override void ConfigureBuildingTemplate(GameObject go, Tag prefab_tag)
{
go.AddOrGet<LoopingSounds>();
go.AddOrGet<BuildingComplete>().isManuallyOperated = true;
go.AddOrGet<LiquidPumpingStation>().overrideAnims = new KAnimFile[1] { Assets.GetAnim("anim_interacts_waterpump_kanim") };
Storage storage = go.AddOrGet<Storage>();
storage.showInUI = false;
storage.allowItemRemoval = true;
storage.showDescriptor = true;
storage.SetDefaultStoredItemModifiers(Storage.StandardInsulatedStorage);
go.AddTag(GameTags.CorrosionProof);
}
private static void AddGuide(GameObject go, bool occupy_tiles)
{
GameObject gameObject = new GameObject();
gameObject.transform.parent = go.transform;
gameObject.transform.SetLocalPosition(Vector3.zero);
KBatchedAnimController kBatchedAnimController = gameObject.AddComponent<KBatchedAnimController>();
kBatchedAnimController.Offset = go.GetComponent<Building>().Def.GetVisualizerOffset();
kBatchedAnimController.AnimFiles = new KAnimFile[1] { Assets.GetAnim(new HashedString("waterpump_kanim")) };
kBatchedAnimController.initialAnim = "place_guide";
kBatchedAnimController.visibilityType = KAnimControllerBase.VisibilityType.OffscreenUpdate;
kBatchedAnimController.isMovable = true;
PumpingStationGuide pumpingStationGuide = gameObject.AddComponent<PumpingStationGuide>();
pumpingStationGuide.parent = go;
pumpingStationGuide.occupyTiles = occupy_tiles;
}
public override void DoPostConfigureComplete(GameObject go)
{
AddGuide(go.GetComponent<Building>().Def.BuildingPreview, occupy_tiles: false);
AddGuide(go.GetComponent<Building>().Def.BuildingUnderConstruction, occupy_tiles: true);
go.AddOrGet<FakeFloorAdder>().floorOffsets = new CellOffset[2]
{
new CellOffset(0, 0),
new CellOffset(1, 0)
};
}
}
| 41.306452 | 270 | 0.787193 | [
"MIT"
] | undancer/oni-data | Managed/main/LiquidPumpingStationConfig.cs | 2,561 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Majestics.Data.Migrations
{
public partial class contestsAndMarks : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Ip",
table: "Marks",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsOpen",
table: "Contests",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Ip",
table: "Marks");
migrationBuilder.DropColumn(
name: "IsOpen",
table: "Contests");
}
}
}
| 26.575758 | 71 | 0.526796 | [
"Apache-2.0"
] | obodnar0/majestics | Data/Migrations/20200528200733_contestsAndMarks.cs | 879 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
internal class IOServices
{
public static IEnumerable<string> GetReadyDrives()
{
foreach (string drive in GetLogicalDrives())
{
if (IsReady(drive))
yield return drive;
}
}
public static string GetNotReadyDrive()
{
string[] drives = GetLogicalDrives();
foreach (string drive in drives)
{
if (!IsReady(drive))
return drive;
}
return null;
}
public static string GetNonExistentDrive()
{
string[] availableDrives = GetLogicalDrives();
for (char drive = 'A'; drive <= 'Z'; drive++)
{
if (!availableDrives.Contains(drive + @":\"))
return drive + @":\";
}
return null;
}
public static string GetNtfsDriveOtherThanCurrent()
{
return GetNtfsDriveOtherThan(GetCurrentDrive());
}
public static string GetNtfsDriveOtherThan(string drive)
{
foreach (string otherDrive in GetLogicalDrives())
{
if (string.Equals(drive, otherDrive, StringComparison.OrdinalIgnoreCase))
continue;
if (!IsFixed(otherDrive))
continue;
if (!IsReady(otherDrive))
continue;
if (IsDriveNTFS(otherDrive))
return otherDrive;
}
return null;
}
public static string GetNonNtfsDriveOtherThanCurrent()
{
return GetNonNtfsDriveOtherThan(GetCurrentDrive());
}
public static string GetNonNtfsDriveOtherThan(string drive)
{
foreach (string otherDrive in GetLogicalDrives())
{
if (string.Equals(drive, otherDrive, StringComparison.OrdinalIgnoreCase))
continue;
if (!IsReady(otherDrive))
continue;
if (!IsDriveNTFS(otherDrive))
return otherDrive;
}
return null;
}
public static string GetPath(string rootPath, int characterCount, bool extended)
{
if (extended)
rootPath = IOInputs.ExtendedPrefix + rootPath;
return GetPath(rootPath, characterCount);
}
public static string GetPath(string rootPath, int characterCount)
{
rootPath = rootPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
StringBuilder path = new StringBuilder(characterCount);
path.Append(rootPath);
while (path.Length < characterCount)
{
// Add directory seperator after each dir but not at the end of the path
path.Append(Path.DirectorySeparatorChar);
// Continue adding unique path segments until the character count is hit
int remainingChars = characterCount - path.Length;
string guid = Guid.NewGuid().ToString("N"); // No dashes
if (remainingChars < guid.Length)
{
path.Append(guid.Substring(0, remainingChars));
}
else
{
// Long paths can be over 32K characters. Given that a guid is just 36 chars, this
// can lead to 800+ recursive call depths. We'll create large segments to
// make tests more manageable.
path.Append(guid);
remainingChars = characterCount - path.Length;
path.Append('g', Math.Min(remainingChars, 200));
}
if (path.Length + 1 == characterCount)
{
// If only one character is missing add a k!
path.Append('k');
}
}
Assert.Equal(path.Length, characterCount);
return path.ToString();
}
public static IEnumerable<string> CreateDirectories(string rootPath, params string[] names)
{
List<string> paths = new List<string>();
foreach (string name in names)
{
string path = Path.Combine(rootPath, name);
Directory.CreateDirectory(path);
paths.Add(path);
}
return paths;
}
public static IEnumerable<string> CreateFiles(string rootPath, params string[] names)
{
List<string> paths = new List<string>();
foreach (string name in names)
{
string path = Path.Combine(rootPath, name);
FileStream stream = File.Create(path);
stream.Dispose();
paths.Add(path);
}
return paths;
}
public static string AddTrailingSlashIfNeeded(string path)
{
if (
path.Length > 0
&& path[path.Length - 1] != Path.DirectorySeparatorChar
&& path[path.Length - 1] != Path.AltDirectorySeparatorChar
)
{
path = path + Path.DirectorySeparatorChar;
}
return path;
}
public static string RemoveTrailingSlash(string path)
{
return path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
private static string[] GetLogicalDrives()
{ // From .NET Framework's Directory.GetLogicalDrives
int drives = DllImports.GetLogicalDrives();
if (drives == 0)
throw new InvalidOperationException();
uint d = (uint)drives;
int count = 0;
while (d != 0)
{
if (((int)d & 1) != 0)
count++;
d >>= 1;
}
string[] result = new string[count];
char[] root = new char[] { 'A', ':', '\\' };
d = (uint)drives;
count = 0;
while (d != 0)
{
if (((int)d & 1) != 0)
{
result[count++] = new string(root);
}
d >>= 1;
root[0]++;
}
return result;
}
public static string GetCurrentDrive()
{
return Path.GetPathRoot(Directory.GetCurrentDirectory());
}
public static bool IsDriveNTFS(string drive)
{
if (PlatformDetection.IsInAppContainer)
{
// we cannot determine filesystem so assume NTFS
return true;
}
var di = new DriveInfo(drive);
return string.Equals(di.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase);
}
public static long GetAvailableFreeBytes(string drive)
{
long ignored;
long userBytes;
if (!DllImports.GetDiskFreeSpaceEx(drive, out userBytes, out ignored, out ignored))
{
throw new IOException(
"DriveName: " + drive + " ErrorCode:" + Marshal.GetLastWin32Error()
);
}
return userBytes;
}
private static bool IsReady(string drive)
{
const int ERROR_NOT_READY = 0x00000015;
long ignored;
if (!DllImports.GetDiskFreeSpaceEx(drive, out ignored, out ignored, out ignored))
{
return Marshal.GetLastWin32Error() != ERROR_NOT_READY;
}
return true;
}
private static bool IsFixed(string drive)
{
return DllImports.GetDriveType(drive) == 3;
}
}
| 26.838129 | 98 | 0.565742 | [
"MIT"
] | belav/runtime | src/libraries/System.IO.FileSystem/tests/PortedCommon/IOServices.cs | 7,461 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from include/vulkan/vulkan_core.h in the KhronosGroup/Vulkan-Headers repository for tag v1.2.198
// Original source is Copyright © 2015-2021 The Khronos Group Inc.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Vulkan.UnitTests
{
/// <summary>Provides validation of the <see cref="VkPhysicalDeviceFragmentDensityMapFeaturesEXT" /> struct.</summary>
public static unsafe partial class VkPhysicalDeviceFragmentDensityMapFeaturesEXTTests
{
/// <summary>Validates that the <see cref="VkPhysicalDeviceFragmentDensityMapFeaturesEXT" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<VkPhysicalDeviceFragmentDensityMapFeaturesEXT>(), Is.EqualTo(sizeof(VkPhysicalDeviceFragmentDensityMapFeaturesEXT)));
}
/// <summary>Validates that the <see cref="VkPhysicalDeviceFragmentDensityMapFeaturesEXT" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(VkPhysicalDeviceFragmentDensityMapFeaturesEXT).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="VkPhysicalDeviceFragmentDensityMapFeaturesEXT" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(VkPhysicalDeviceFragmentDensityMapFeaturesEXT), Is.EqualTo(32));
}
else
{
Assert.That(sizeof(VkPhysicalDeviceFragmentDensityMapFeaturesEXT), Is.EqualTo(20));
}
}
}
}
| 43.795455 | 158 | 0.697457 | [
"MIT"
] | tannergooding/terrafx.interop.vulkan | tests/Interop/Vulkan/Vulkan/vulkan/vulkan_core/VkPhysicalDeviceFragmentDensityMapFeaturesEXTTests.cs | 1,929 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AddPairwiseWideningAndAdd_Vector128_SByte()
{
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, SByte[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if (
(alignment != 16 && alignment != 8)
|| (alignment * 2) < sizeOfinArray1
|| (alignment * 2) < sizeOfinArray2
|| (alignment * 2) < sizeOfoutArray
)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray1Ptr),
ref Unsafe.As<Int16, byte>(ref inArray1[0]),
(uint)sizeOfinArray1
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray2Ptr),
ref Unsafe.As<SByte, byte>(ref inArray2[0]),
(uint)sizeOfinArray2
);
}
public void* inArray1Ptr =>
Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr =>
Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr =>
Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt16();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1),
ref Unsafe.As<Int16, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2),
ref Unsafe.As<SByte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<SByte>>()
);
return testStruct;
}
public void RunStructFldScenario(
SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass
)
{
var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(
SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte testClass
)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount =
Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount =
Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount =
Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte()
{
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt16();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1),
ref Unsafe.As<Int16, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2),
ref Unsafe.As<SByte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<SByte>>()
);
}
public SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt16();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1),
ref Unsafe.As<Int16, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2),
ref Unsafe.As<SByte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<SByte>>()
);
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt16();
}
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetSByte();
}
_dataTable = new DataTable(
_data1,
_data2,
new Int16[RetElementCount],
LargestVectorSize
);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.AddPairwiseWideningAndAdd(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.AddPairwiseWideningAndAdd),
new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }
)
.Invoke(
null,
new object[]
{
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.AddPairwiseWideningAndAdd),
new Type[] { typeof(Vector128<Int16>), typeof(Vector128<SByte>) }
)
.Invoke(
null,
new object[]
{
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AddPairwiseWideningAndAdd(_clsVar1, _clsVar2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(pClsVar1)),
AdvSimd.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.AddPairwiseWideningAndAdd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.AddPairwiseWideningAndAdd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte();
var result = AdvSimd.AddPairwiseWideningAndAdd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddPairwiseWideningAndAdd_Vector128_SByte();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AddPairwiseWideningAndAdd(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AddPairwiseWideningAndAdd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AddPairwiseWideningAndAdd(
AdvSimd.LoadVector128((Int16*)(&test._fld1)),
AdvSimd.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(
Vector128<Int16> op1,
Vector128<SByte> op2,
void* result,
[CallerMemberName] string method = ""
)
{
Int16[] inArray1 = new Int16[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int16, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
void* op1,
void* op2,
void* result,
[CallerMemberName] string method = ""
)
{
Int16[] inArray1 = new Int16[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int16, byte>(ref inArray1[0]),
ref Unsafe.AsRef<byte>(op1),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<SByte, byte>(ref inArray2[0]),
ref Unsafe.AsRef<byte>(op2),
(uint)Unsafe.SizeOf<Vector128<SByte>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int16, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int16>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
Int16[] left,
SByte[] right,
Int16[] result,
[CallerMemberName] string method = ""
)
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AddPairwiseWideningAndAdd(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation(
$"{nameof(AdvSimd)}.{nameof(AdvSimd.AddPairwiseWideningAndAdd)}<Int16>(Vector128<Int16>, Vector128<SByte>): {method} failed:"
);
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation(
$" result: ({string.Join(", ", result)})"
);
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.487768 | 145 | 0.547253 | [
"MIT"
] | belav/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddPairwiseWideningAndAdd.Vector128.SByte.cs | 24,517 | C# |
using PlanetaryDiversity.API;
using System;
using System.Linq;
using UnityEngine;
//using Report = PlanetaryDiversity.Report;
namespace PlanetaryDiversity.CelestialBodies.Atmosphere
{
/// <summary>
/// Changes the pressure and temperature curves of the planets
/// </summary>
public class AtmospherePressureTweak : CelestialBodyTweaker
{
/// <summary>
/// Returns the name of the config node that stores the configuration
/// </summary>
public override String GetConfig() => "PD_CELESTIAL";
/// <summary>
/// Returns the name of the config option that can be used to disable the tweak
/// </summary>
public override String GetSetting() => "AtmospherePressure";
/// <summary>
/// Changes the parameters of the body
/// </summary>
public override Boolean Tweak(CelestialBody body)
{
// Does this body have an atmosphere?
if (!body.atmosphere)
return false;
//Report::Report.fetch.SetPrefix("PlanetaryBody: " + body.bodyDisplayName);
// Prefab
PSystemBody pSystemBody = Resources.FindObjectsOfTypeAll<PSystemBody>().FirstOrDefault(b => b.celestialBody.bodyName == body.transform.name);
// Get a multiplier
Single mult = (Single)GetRandomDouble(HighLogic.CurrentGame.Seed, 0.9, 1.1);
// Apply it to both curves
if (body.atmosphereUsePressureCurve)
{
//Report::Report.fetch.ReportLine("Original atmospheric pressure curve: " + body.atmospherePressureCurve.ToString());
//Report::Report.fetch.ReportLine("Original atmospheric pressure sea level: " + body.atmospherePressureSeaLevel.ToString());
body.atmospherePressureCurve = new FloatCurve(pSystemBody.celestialBody.atmospherePressureCurve.Curve.keys.Select(k => new Keyframe(k.time, k.value * mult, k.inTangent, k.outTangent)).ToArray());
body.atmospherePressureSeaLevel *= mult;
//Report::Report.fetch.ReportLine("New atmospheric pressure curve: " + body.atmospherePressureCurve.ToString());
//Report::Report.fetch.ReportLine("New atmospheric pressure sea level: " + body.atmospherePressureSeaLevel.ToString());
}
if (body.atmosphereUseTemperatureCurve)
{
//Report::Report.fetch.ReportLine("Original atmospheric temperature curve: " + body.atmosphereTemperatureCurve.ToString());
//Report::Report.fetch.ReportLine("Original atmospheric temperature sea level: " + body.atmosphereTemperatureSeaLevel.ToString());
body.atmosphereTemperatureCurve = new FloatCurve(pSystemBody.celestialBody.atmosphereTemperatureCurve.Curve.keys.Select(k => new Keyframe(k.time, k.value * mult, k.inTangent, k.outTangent)).ToArray());
body.atmosphereTemperatureSeaLevel *= mult;
//Report::Report.fetch.ReportLine("New atmospheric temperature curve: " + body.atmosphereTemperatureCurve.ToString());
//Report::Report.fetch.ReportLine("New atmospheric temperature sea level: " + body.atmosphereTemperatureSeaLevel.ToString());
}
if (body.atmosphereUsePressureCurve || body.atmosphereUseTemperatureCurve)
{
//Report::Report.fetch.ReportSection();
}
//Report::Report.fetch.ClearPrefix();
// Did we tweak something?
return body.atmosphereUsePressureCurve || body.atmosphereUseTemperatureCurve;
}
}
}
| 49.243243 | 217 | 0.649835 | [
"MIT"
] | linuxgurugamer/Planetary-Diversity | src/celestialbodies/atmosphere/AtmospherePressureTweak.cs | 3,646 | C# |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Data;
using System.Text;
using DotNetNuke.Common.Utilities;
using DotNetNuke.ComponentModel;
using DotNetNuke.Tests.Utilities.Mocks;
using NUnit.Framework;
namespace DotNetNuke.Tests.Core.Providers.Caching
{
/// <summary>
/// Summary description for DataCacheTests
/// </summary>
[TestFixture]
public class CBOTest
{
[SetUp]
public void SetUp()
{
//Create a Container
ComponentFactory.Container = new SimpleContainer();
MockComponentProvider.CreateDataCacheProvider();
}
[Test]
public void CBO_FillObject_int()
{
var cboTable = new DataTable("CBOTable");
var colValue = 12;
cboTable.Columns.Add("IntProp", typeof (int));
cboTable.Rows.Add(colValue);
//Assert.AreEqual(12, moq.Object["TestColumn"]);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.IntProp);
}
[Test]
public void CBO_FillObject_string()
{
var cboTable = new DataTable("CBOTable");
var colValue = Guid.NewGuid().ToString();
cboTable.Columns.Add("StringProp", typeof (String));
cboTable.Rows.Add(colValue);
//Assert.AreEqual(12, moq.Object["TestColumn"]);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.StringProp);
}
[Test]
public void CBO_FillObject_datetime()
{
var cboTable = new DataTable("CBOTable");
var colValue = new DateTime(2010, 12, 11, 10, 9, 8);
cboTable.Columns.Add("DateTimeProp", typeof (DateTime));
cboTable.Rows.Add(colValue);
//Assert.AreEqual(12, moq.Object["TestColumn"]);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.DateTimeProp);
}
[Test]
//DNNPRO-13404 - Object does not implement IConvertible
public void CBO_FillObject_binary()
{
var cboTable = new DataTable("CBOTable");
var colValue = Encoding.ASCII.GetBytes("Hello This is test");
cboTable.Columns.Add("ByteArrayProp", typeof (byte[]));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.ByteArrayProp);
}
[Test]
public void CBO_FillObject_binary_to_Array()
{
var cboTable = new DataTable("CBOTable");
var colValue = Encoding.ASCII.GetBytes("Hello This is test");
cboTable.Columns.Add("ArrayProp", typeof (byte[]));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.ArrayProp);
}
[Test]
public void CBO_FillObject_bit()
{
var cboTable = new DataTable("CBOTable");
var colValue = true;
cboTable.Columns.Add("BitProp", typeof (Boolean));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.BitProp);
}
[Test]
public void CBO_FillObject_decimal()
{
var cboTable = new DataTable("CBOTable");
decimal colValue = 12.99m;
cboTable.Columns.Add("DecimalProp", typeof (decimal));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(colValue, result.DecimalProp);
}
[Test]
public void CBO_FillObject_int_to_boolean_true()
{
var cboTable = new DataTable("CBOTable");
decimal colValue = 1;
cboTable.Columns.Add("BitProp", typeof (int));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(true, result.BitProp);
}
[Test]
public void CBO_FillObject_int_to_boolean_false()
{
var cboTable = new DataTable("CBOTable");
decimal colValue = 0;
cboTable.Columns.Add("BitProp", typeof (int));
cboTable.Rows.Add(colValue);
var result = CBO.FillObject<IntPoco>(cboTable.CreateDataReader());
Assert.IsInstanceOf<IntPoco>(result);
Assert.IsNotNull(result);
Assert.AreEqual(false, result.BitProp);
}
}
public class IntPoco
{
public int IntProp { get; set; }
public string StringProp { get; set; }
public DateTime DateTimeProp { get; set; }
public Byte[] ByteArrayProp { get; set; }
public Array ArrayProp { get; set; }
public Boolean BitProp { get; set; }
public decimal DecimalProp { get; set; }
}
} | 32.981395 | 116 | 0.616415 | [
"MIT"
] | Mhtshum/Dnn.Platform | DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs | 7,094 | C# |
using SharpCircuit.src;
using System;
using System.Collections;
using System.Collections.Generic;
namespace SharpCircuit.src.elements
{
// Contributed by Edward Calver.
public class SchmittTrigger : InvertingSchmittTrigger
{
public override void step(Circuit sim)
{
double v0 = lead_volt[1];
double @out;
if (state)
{
// Output is high
if (lead_volt[0] > upperTrigger)
{
// Input voltage high enough to set output high
state = false;
@out = 5;
}
else
{
@out = 0;
}
}
else
{
// Output is low
if (lead_volt[0] < lowerTrigger)
{
// Input voltage low enough to set output low
state = true;
@out = 0;
}
else
{
@out = 5;
}
}
double maxStep = slewRate * sim.timeStep * 1e9;
@out = Math.Max(Math.Min(v0 + maxStep, @out), v0 - maxStep);
sim.updateVoltageSource(0, lead_node[1], voltSource, @out);
}
/*public override void getInfo(String[] arr) {
arr[0] = "Schmitt";
}*/
}
} | 25.696429 | 72 | 0.421821 | [
"MIT"
] | HDG-Gabriel/Electrophorus | SharpCircuits/src/elements/SchmittTrigger.cs | 1,439 | C# |
using Microsoft.EntityFrameworkCore;
namespace DL_Core_WebAPP_Release.Models
{
public class DLContext : DbContext
{
public DLContext(DbContextOptions<DLContext> options)
: base(options)
{ }
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<Issue> Issues { get; set; }
}
}
| 26.238095 | 61 | 0.624319 | [
"MIT"
] | Krish-Chandra/DL_ASPNET_CORE | src/DL_Core_WebAPP_Release/Models/DLContext.cs | 551 | C# |
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using RestClient;
using RestClientVS;
namespace MarkdownEditor.Outlining
{
[Export(typeof(ITaggerProvider))]
[TagType(typeof(IErrorTag))]
[ContentType(RestLanguage.LanguageName)]
[Name(RestLanguage.LanguageName)]
public class RestErrorTaggerProvider : ITaggerProvider
{
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag =>
buffer.Properties.GetOrCreateSingletonProperty(() => new RestErrorTagger(buffer)) as ITagger<T>;
}
public class RestErrorTagger : ITagger<IErrorTag>
{
private readonly ITextBuffer _buffer;
private readonly RestDocument _document;
public RestErrorTagger(ITextBuffer buffer)
{
_buffer = buffer;
_document = RestDocument.FromTextbuffer(buffer);
}
public IEnumerable<ITagSpan<IErrorTag>> GetTags(NormalizedSnapshotSpanCollection spans)
{
if (spans.Count == 0 || _document.IsParsing)
{
yield return null;
}
SnapshotSpan span = spans[0];
ITextSnapshot snapshot = _buffer.CurrentSnapshot;
IEnumerable<ParseItem> tokens = _document.Tokens.Where(t => t.Start <= span.Start && t.End >= span.End).ToArray();
foreach (RestClient.Reference reference in tokens.SelectMany(t => t.References))
{
if (!reference.Value.IsValid)
{
var tooltip = string.Join(Environment.NewLine, reference.Value.Errors);
var simpleSpan = new Span(reference.Value.Start, reference.Value.Length);
var snapShotSpan = new SnapshotSpan(snapshot, simpleSpan);
var errorTag = new ErrorTag(PredefinedErrorTypeNames.CompilerError, tooltip);
yield return new TagSpan<IErrorTag>(snapShotSpan, errorTag);
}
}
}
public event EventHandler<SnapshotSpanEventArgs> TagsChanged
{
add { }
remove { }
}
}
}
| 34.731343 | 126 | 0.637731 | [
"Apache-2.0"
] | timheuer/RestClientVS | src/RestClientVS/Language/RestErrorTagger.cs | 2,327 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow
{
/// <summary>
/// <para>
/// Primary entity for which analysis data is tracked by <see cref="DataFlowAnalysis"/>.
/// </para>
/// <para>
/// The entity is based on one or more of the following:
/// 1. An <see cref="ISymbol"/>.
/// 2. One or more <see cref="AbstractIndex"/> indices to index into the parent key.
/// 3. "this" or "Me" instance.
/// 4. An allocation or an object creation.
/// </para>
/// <para>
/// Each entity has:
/// 1. An associated non-null <see cref="Type"/> and
/// 2. A non-null <see cref="InstanceLocation"/> indicating the abstract location at which the entity is located and
/// 3. An optional parent key if this key has the same <see cref="InstanceLocation"/> as the parent (i.e. parent is a value type).
/// </para>
/// </summary>
public sealed class AnalysisEntity : CacheBasedEquatable<AnalysisEntity>
{
private readonly ImmutableArray<int> _ignoringLocationHashCodeParts;
private AnalysisEntity(
ISymbol? symbol,
ImmutableArray<AbstractIndex> indices,
SyntaxNode? instanceReferenceOperationSyntax,
InterproceduralCaptureId? captureId,
PointsToAbstractValue location,
ITypeSymbol type,
AnalysisEntity? parent,
bool isThisOrMeInstance)
{
Debug.Assert(!indices.IsDefault);
Debug.Assert(symbol != null || !indices.IsEmpty || instanceReferenceOperationSyntax != null || captureId.HasValue);
Debug.Assert(parent == null || parent.Type.HasValueCopySemantics() || !indices.IsEmpty);
Symbol = symbol;
Indices = indices;
InstanceReferenceOperationSyntax = instanceReferenceOperationSyntax;
CaptureId = captureId;
InstanceLocation = location;
Type = type;
Parent = parent;
IsThisOrMeInstance = isThisOrMeInstance;
_ignoringLocationHashCodeParts = ComputeIgnoringLocationHashCodeParts();
EqualsIgnoringInstanceLocationId = HashUtilities.Combine(_ignoringLocationHashCodeParts);
}
private AnalysisEntity(ISymbol? symbol, ImmutableArray<AbstractIndex> indices, PointsToAbstractValue location, ITypeSymbol type, AnalysisEntity? parent)
: this(symbol, indices, instanceReferenceOperationSyntax: null, captureId: null, location: location, type: type, parent: parent, isThisOrMeInstance: false)
{
Debug.Assert(symbol != null || !indices.IsEmpty);
}
private AnalysisEntity(IInstanceReferenceOperation instanceReferenceOperation, PointsToAbstractValue location)
: this(symbol: null, indices: ImmutableArray<AbstractIndex>.Empty, instanceReferenceOperationSyntax: instanceReferenceOperation.Syntax,
captureId: null, location: location, type: instanceReferenceOperation.Type, parent: null, isThisOrMeInstance: false)
{
Debug.Assert(instanceReferenceOperation != null);
}
private AnalysisEntity(InterproceduralCaptureId captureId, ITypeSymbol capturedType, PointsToAbstractValue location)
: this(symbol: null, indices: ImmutableArray<AbstractIndex>.Empty, instanceReferenceOperationSyntax: null,
captureId: captureId, location: location, type: capturedType, parent: null, isThisOrMeInstance: false)
{
}
private AnalysisEntity(INamedTypeSymbol namedType, PointsToAbstractValue location, bool isThisOrMeInstance)
: this(symbol: namedType, indices: ImmutableArray<AbstractIndex>.Empty, instanceReferenceOperationSyntax: null,
captureId: null, location: location, type: namedType, parent: null, isThisOrMeInstance: isThisOrMeInstance)
{
}
public static AnalysisEntity Create(ISymbol? symbol, ImmutableArray<AbstractIndex> indices,
ITypeSymbol type, PointsToAbstractValue instanceLocation, AnalysisEntity? parent)
{
Debug.Assert(symbol != null || !indices.IsEmpty);
Debug.Assert(parent == null || parent.InstanceLocation == instanceLocation);
return new AnalysisEntity(symbol, indices, instanceLocation, type, parent);
}
public static AnalysisEntity Create(IInstanceReferenceOperation instanceReferenceOperation, PointsToAbstractValue instanceLocation)
{
return new AnalysisEntity(instanceReferenceOperation, instanceLocation);
}
public static AnalysisEntity Create(
InterproceduralCaptureId interproceduralCaptureId,
ITypeSymbol type,
PointsToAbstractValue instanceLocation)
{
return new AnalysisEntity(interproceduralCaptureId, type, instanceLocation);
}
public static AnalysisEntity CreateThisOrMeInstance(INamedTypeSymbol typeSymbol, PointsToAbstractValue instanceLocation)
{
Debug.Assert(instanceLocation.Locations.Count == 1);
Debug.Assert(instanceLocation.Locations.Single().Creation == null);
Debug.Assert(Equals(instanceLocation.Locations.Single().Symbol, typeSymbol));
return new AnalysisEntity(typeSymbol, instanceLocation, isThisOrMeInstance: true);
}
public AnalysisEntity WithMergedInstanceLocation(AnalysisEntity analysisEntityToMerge)
{
Debug.Assert(EqualsIgnoringInstanceLocation(analysisEntityToMerge));
Debug.Assert(!InstanceLocation.Equals(analysisEntityToMerge.InstanceLocation));
var mergedInstanceLocation = PointsToAnalysis.PointsToAnalysis.PointsToAbstractValueDomainInstance.Merge(InstanceLocation, analysisEntityToMerge.InstanceLocation);
return new AnalysisEntity(Symbol, Indices, InstanceReferenceOperationSyntax, CaptureId, mergedInstanceLocation, Type, Parent, IsThisOrMeInstance);
}
public bool IsChildOrInstanceMember
{
get
{
if (IsThisOrMeInstance)
{
return false;
}
bool result;
if (Symbol != null)
{
result = Symbol.Kind != SymbolKind.Parameter &&
Symbol.Kind != SymbolKind.Local &&
!Symbol.IsStatic;
}
else if (!Indices.IsEmpty)
{
result = true;
}
else
{
result = false;
}
Debug.Assert(Parent == null || result);
return result;
}
}
internal bool IsChildOrInstanceMemberNeedingCompletePointsToAnalysis()
{
if (!IsChildOrInstanceMember)
{
return false;
}
// PERF: This is the core performance optimization for partial PointsToAnalysisKind.
// We avoid tracking PointsToValues for all entities that are child or instance members,
// except when they are fields or members of a value type (for example, tuple elements or struct members).
return Parent == null || !Parent.Type.HasValueCopySemantics();
}
public bool HasConstantValue
{
get
{
return Symbol switch
{
IFieldSymbol field => field.HasConstantValue,
ILocalSymbol local => local.HasConstantValue,
_ => false,
};
}
}
public ISymbol? Symbol { get; }
public ImmutableArray<AbstractIndex> Indices { get; }
public SyntaxNode? InstanceReferenceOperationSyntax { get; }
public InterproceduralCaptureId? CaptureId { get; }
public PointsToAbstractValue InstanceLocation { get; }
public ITypeSymbol Type { get; }
public AnalysisEntity? Parent { get; }
public bool IsThisOrMeInstance { get; }
public bool HasUnknownInstanceLocation
{
get
{
return InstanceLocation.Kind switch
{
PointsToAbstractValueKind.Unknown
or PointsToAbstractValueKind.UnknownNull
or PointsToAbstractValueKind.UnknownNotNull => true,
_ => false,
};
}
}
public bool IsLValueFlowCaptureEntity => CaptureId.HasValue && CaptureId.Value.IsLValueFlowCapture;
public bool EqualsIgnoringInstanceLocation(AnalysisEntity? other)
{
// Perform fast equality checks first.
if (ReferenceEquals(this, other))
{
return true;
}
if (other == null ||
EqualsIgnoringInstanceLocationId != other.EqualsIgnoringInstanceLocationId)
{
return false;
}
// Now perform slow check that compares individual hash code parts sequences.
return _ignoringLocationHashCodeParts.SequenceEqual(other._ignoringLocationHashCodeParts);
}
public int EqualsIgnoringInstanceLocationId { get; private set; }
protected override void ComputeHashCodeParts(Action<int> addPart)
{
addPart(InstanceLocation.GetHashCode());
ComputeHashCodePartsIgnoringLocation(addPart);
}
private void ComputeHashCodePartsIgnoringLocation(Action<int> addPart)
{
addPart(Symbol.GetHashCodeOrDefault());
addPart(HashUtilities.Combine(Indices));
addPart(InstanceReferenceOperationSyntax.GetHashCodeOrDefault());
addPart(CaptureId.GetHashCodeOrDefault());
addPart(Type.GetHashCode());
addPart(Parent.GetHashCodeOrDefault());
addPart(IsThisOrMeInstance.GetHashCode());
}
private ImmutableArray<int> ComputeIgnoringLocationHashCodeParts()
{
var builder = ArrayBuilder<int>.GetInstance(7);
ComputeHashCodePartsIgnoringLocation(builder.Add);
return builder.ToImmutableAndFree();
}
public bool HasAncestor(AnalysisEntity ancestor)
{
AnalysisEntity? current = this.Parent;
while (current != null)
{
if (current == ancestor)
{
return true;
}
current = current.Parent;
}
return false;
}
internal bool IsCandidatePredicateEntity()
=> Type.SpecialType == SpecialType.System_Boolean ||
Type.IsNullableOfBoolean() ||
Type.Language == LanguageNames.VisualBasic && Type.SpecialType == SpecialType.System_Object;
}
} | 41.498195 | 175 | 0.628273 | [
"Apache-2.0"
] | JakeYallop/roslyn-analyzers | src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs | 11,497 | C# |
/*
* Copyright © 2010 Intuit Inc. All rights reserved.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/eclipse-1.0.php
*/
using System.Xml.XPath;
namespace Intuit.QuickBase.Client
{
internal class QRecordFactory : QRecordFactoryBase
{
private static QRecordFactoryBase _instance;
private QRecordFactory() { }
internal static QRecordFactoryBase GetInstance()
{
if(_instance == null)
{
_instance = new QRecordFactory();
}
return _instance;
}
internal override IQRecord CreateInstance(IQApplication application, IQTable table, QColumnCollection columns)
{
return new QRecord(application, table, columns);
}
internal override IQRecord CreateInstance(IQApplication application, IQTable table, QColumnCollection columns, XPathNavigator recordNode)
{
return new QRecord(application, table, columns, recordNode);
}
}
}
| 32.5 | 146 | 0.648583 | [
"BSD-3-Clause"
] | KarderCorp/QuickBase-C-Sharp-SDK | Intuit.QuickBase.Client/QRecordFactory.cs | 1,238 | C# |
namespace Zu.ChromeDevTools.Runtime
{
using Newtonsoft.Json;
/// <summary>
/// Object internal property descriptor. This property isn't normally visible in JavaScript code.
/// </summary>
public sealed class InternalPropertyDescriptor
{
/// <summary>
/// Conventional property name.
///</summary>
[JsonProperty("name")]
public string Name
{
get;
set;
}
/// <summary>
/// The value associated with the property.
///</summary>
[JsonProperty("value", DefaultValueHandling = DefaultValueHandling.Ignore)]
public RemoteObject Value
{
get;
set;
}
}
} | 25.275862 | 101 | 0.548431 | [
"Apache-2.0"
] | DoctorDump/AsyncChromeDriver | ChromeDevToolsClient/Runtime/InternalPropertyDescriptor.cs | 733 | C# |
using Bullseye;
using Bullseye.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using static Bullseye.Targets;
using OperatingSystem = Bullseye.Internal.OperatingSystem;
namespace build
{
class Program
{
public static string BasePath { get; private set; } = default!;
private static Palette palette = default!;
public static bool NoPrerelease { get; private set; }
private static bool verbose;
private static readonly Dictionary<Type, object> state = new Dictionary<Type, object>();
private static T GetState<T>() where T : notnull
{
return state.TryGetValue(typeof(T), out var value)
? (T)value
: throw new InvalidOperationException($"The target that produces state '{typeof(T).FullName}' has not been executed yet.");
}
private static void SetState<T>(T value) where T : notnull
{
state.Add(typeof(T), value);
}
private static void RegisterTargets()
{
var getState = typeof(Program).GetMethod(nameof(GetState), BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Method not found", nameof(GetState));
var setState = typeof(Program).GetMethod(nameof(SetState), BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Method not found", nameof(SetState));
var providerTargets = new Dictionary<Type, string>();
var targetMethods = typeof(BuildDefinition).GetMethods(BindingFlags.Static | BindingFlags.Public);
var targets = new List<(string name, Action action, IEnumerable<Type> dependencies)>();
foreach (var targetMethod in targetMethods)
{
var dependencies = targetMethod
.GetParameters()
.Select(p => p.ParameterType)
.ToList();
Expression actionExpression = Expression.Call(
targetMethod,
dependencies.Select(d => Expression.Call(getState.MakeGenericMethod(d)))
);
if (targetMethod.ReturnType != typeof(void))
{
actionExpression = Expression.Call(
setState.MakeGenericMethod(targetMethod.ReturnType),
actionExpression
);
if (providerTargets.ContainsKey(targetMethod.ReturnType))
{
var duplicates = targetMethods.Where(m => m.ReturnType == targetMethod.ReturnType).Select(m => m.Name);
throw new InvalidOperationException($"Multiple targets provide the same type '{targetMethod.ReturnType.FullName}': {string.Join(", ", duplicates)}");
}
providerTargets.Add(targetMethod.ReturnType, targetMethod.Name);
}
var action = Expression.Lambda<Action>(actionExpression);
targets.Add((targetMethod.Name, action.Compile(), dependencies));
}
foreach (var (name, action, dependencies) in targets)
{
var dependendsOn = dependencies
.Where(d => !state.ContainsKey(d))
.Select(d => providerTargets.TryGetValue(d, out var dependencyName) ? dependencyName : throw new InvalidOperationException($"Target '{name}' depends on '{d.FullName}', but no target provides it."));
Target(name, dependendsOn, action);
}
}
static int Main(string[] args)
{
var filteredArguments = args
.Where(a =>
{
switch (a)
{
case "--no-prerelease":
NoPrerelease = true;
return false;
default:
return true;
}
})
.ToList();
var (options, targets) = Options.Parse(filteredArguments);
verbose = options.Verbose;
var operatingSystem =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? OperatingSystem.Windows
: RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
? OperatingSystem.Linux
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
? OperatingSystem.MacOS
: OperatingSystem.Unknown;
palette = new Palette(options.NoColor, options.NoExtendedChars, options.Host, operatingSystem);
if (targets.Count == 0 && !options.ShowHelp)
{
switch (options.Host)
{
case Host.Appveyor:
// Default CI targets for AppVeyor
var isBuildingRelease = Environment.GetEnvironmentVariable("APPVEYOR_REPO_TAG")?.Equals("true", StringComparison.OrdinalIgnoreCase) ?? false;
if (isBuildingRelease)
{
WriteInformation("Release build detected");
targets.Add(nameof(BuildDefinition.SetBuildVersion));
targets.Add(nameof(BuildDefinition.Publish));
}
else
{
WriteInformation("Non-release build detected");
targets.Add(nameof(BuildDefinition.SetBuildVersion));
targets.Add(nameof(BuildDefinition.Pack));
}
break;
default:
(options, targets) = Options.Parse(filteredArguments.Append("-?"));
break;
}
}
SetState(options);
var initialDirectory = Directory.GetCurrentDirectory();
BasePath = initialDirectory;
while (!File.Exists(Path.Combine(BasePath, "YamlDotNet.sln")))
{
BasePath = Path.GetDirectoryName(BasePath) ?? throw new InvalidOperationException($"Could not find YamlDotNet.sln starting from '{initialDirectory}'.");
}
WriteVerbose($"BasePath: {BasePath}");
RegisterTargets();
int exitCode = 0;
try
{
RunTargetsWithoutExiting(targets, options);
}
catch (TargetFailedException)
{
exitCode = 1;
}
if (options.ShowHelp)
{
Console.WriteLine();
Console.WriteLine($"{palette.Default}Additional options:");
Console.WriteLine($" {palette.Option}--no-prerelease {palette.Default}Force the current version to be considered final{palette.Reset}");
}
return exitCode;
}
public static void WriteVerbose(string text)
{
if (verbose)
{
Write(text, palette.Verbose);
}
}
public static void WriteInformation(string text)
{
Console.WriteLine($" {palette.Default}(i) {text}{palette.Reset}");
}
public static void WriteWarning(string text)
{
Console.WriteLine($" {palette.Option}/!\\ {text}{palette.Reset}");
}
public static void WriteImportant(string text)
{
WriteBoxed(text, palette.Warning);
}
private static void WriteBoxed(string text, string color)
{
const int boxWidth = 50;
var boxElements = palette.Dash == '─'
? "┌┐└┘│─"
: "++++|-";
Console.WriteLine();
Write($" {boxElements[0]}{new string(boxElements[5], boxWidth - 2)}{boxElements[1]}", color);
foreach (var line in WrapText(text, boxWidth - 4))
{
Write($" {boxElements[4]} {line,-(boxWidth - 4)} {boxElements[4]}", color);
}
Write($" {boxElements[2]}{new string(boxElements[5], boxWidth - 2)}{boxElements[3]}", color);
Console.WriteLine();
}
private static IEnumerable<string> WrapText(string text, int length)
{
foreach (var textLine in text.Split('\n'))
{
var line = new StringBuilder();
foreach (var word in textLine.Split(' '))
{
if (line.Length == 0)
{
line.Append(word);
}
else if (line.Length + word.Length + 1 < length)
{
line.Append(' ').Append(word);
}
else
{
yield return line.ToString();
line.Clear().Append(word);
}
}
if (line.Length > 0 || textLine.Length == 0)
{
yield return line.ToString();
}
}
}
private static void Write(string text, string color)
{
Console.WriteLine($"{color}{text}{palette.Reset}");
}
public static IEnumerable<string> ReadLines(string name, string? args = null, string? workingDirectory = null) => SimpleExec.Command
.Read(name, args, workingDirectory)
.Split('\n')
.Select(l => l.TrimEnd('\r'));
public static string UnIndent(string text)
{
var lines = text
.Split('\n')
.Select(l => l.TrimEnd('\r', '\n'))
.SkipWhile(l => l.Trim(' ', '\t').Length == 0)
.ToList();
while (lines.Count > 0 && lines[lines.Count - 1].Trim(' ', '\t').Length == 0)
{
lines.RemoveAt(lines.Count - 1);
}
if (lines.Count > 0)
{
var indent = Regex.Match(lines[0], @"^(\s*)");
if (!indent.Success)
{
throw new ArgumentException("Invalid indentation");
}
lines = lines
.Select(l => l.Substring(indent.Groups[1].Length))
.ToList();
}
return string.Join("\n", lines.ToArray());
}
}
}
| 38.047619 | 219 | 0.490166 | [
"MIT"
] | FSDKO/YamlDotNet | tools/build/Program.cs | 11,202 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WriterSetup.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Generator.Output
{
using Newtonsoft.Json;
using Sundew.Generator.Core;
/// <summary>
/// Default implementation of <see cref="IWriterSetup"/>.
/// </summary>
/// <seealso cref="IWriterSetup" />
public class WriterSetup : IWriterSetup
{
/// <summary>
/// Initializes a new instance of the <see cref="WriterSetup" /> class.
/// </summary>
/// <param name="target">The target.</param>
public WriterSetup(string target)
{
this.Target = target;
}
/// <summary>
/// Initializes a new instance of the <see cref="WriterSetup" /> class.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="writer">The writer.</param>
[JsonConstructor]
public WriterSetup(string target, TypeOrObject<IWriter> writer)
{
this.Target = target;
this.Writer = writer;
}
/// <summary>
/// Gets the target.
/// </summary>
/// <value>
/// The type.
/// </value>
public string Target { get; init; }
/// <summary>
/// Gets the writer.
/// </summary>
/// <value>
/// The type.
/// </value>
public TypeOrObject<IWriter>? Writer { get; init; }
}
} | 32.589286 | 120 | 0.472329 | [
"MIT"
] | cdrnet/Sundew.Generator | Source/Sundew.Generator/Output/WriterSetup.cs | 1,827 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SMVisualization
{
public partial class RenderOptionsForm : Form
{
private VisualizationRenderOptions m_RenderOptions;
private SubjectRenderOptions m_SelectedSubjectRenderOptions;
// Changes in the RenderOptionsForm directly change the referenceRenderOptions object
public RenderOptionsForm(VisualizationRenderOptions referenceRenderOptions)
{
InitializeComponent();
m_RenderOptions = referenceRenderOptions;
}
private void RenderOptionsForm_Load(object sender, EventArgs e)
{
PopulateOptionsListFromRenderOptionsType();
cblRenderOptions.ItemCheck += cblRenderOptions_ItemCheck;
ddlSelectedSubject.SelectedItem = "All";
// m_SelectedSubjectRenderOptions = null; // 'null' is global
// AssignOptionsListUIFromRenderOptions(m_SelectedSubjectRenderOptions);
}
void cblRenderOptions_ItemCheck(object sender, ItemCheckEventArgs e)
{
String itemName = cblRenderOptions.Items[e.Index] as String;
String propertyName = itemName.Replace(" ", ""); // Remove all spaces to get the name of the property
bool isEnabled = e.NewValue == CheckState.Checked;
FieldInfo field = typeof(SubjectRenderOptions).GetField(propertyName);
if (m_SelectedSubjectRenderOptions != null)
{
// Update that field based on the new checked-ness
field.SetValue(m_SelectedSubjectRenderOptions, isEnabled);
}
else
{
m_RenderOptions.SetAllSubjectsOptionToValue(field, isEnabled);
}
}
private void ddlSelectedSubject_SelectedIndexChanged(object sender, EventArgs e)
{
String selectedItem = ddlSelectedSubject.SelectedItem.ToString();
if (selectedItem == "All")
m_SelectedSubjectRenderOptions = null;
else
{
// Assume the "Subjects" are assigned in the format of "Subject 1", "Subject 2",
// etc., extract the index from the end of that name and use it to determine which
// subject options to render. (Not pretty, works for now)
String subjectIndexText = selectedItem.Substring(selectedItem.Length - 1);
int subjectIndex = int.Parse(subjectIndexText) - 1; // Values in the list are 1-indexed
m_SelectedSubjectRenderOptions = m_RenderOptions.SubjectOptions[subjectIndex];
}
AssignOptionsListUIFromRenderOptions(m_SelectedSubjectRenderOptions);
}
private void PopulateOptionsListFromRenderOptionsType()
{
// Fills in the available render options from the values that are in the
// SubjectRenderOptions type. This assumes that all types in a SubjectRenderOptions
// are bool
FieldInfo[] fields = typeof(SubjectRenderOptions).GetFields();
foreach (FieldInfo field in fields)
{
cblRenderOptions.Items.Add(FormatUpperCamelCaseStringToSpaces(field.Name));
}
}
// Turn "SomeThing" to "Some Thing"
private String FormatUpperCamelCaseStringToSpaces(String upperCamelCaseString)
{
List<String> wordsList = new List<string>();
String currentWord = "";
foreach (char currentCharacter in upperCamelCaseString)
{
if (char.IsUpper(currentCharacter) && currentWord.Length > 0)
{
wordsList.Add(currentWord);
currentWord = "";
}
currentWord += currentCharacter;
}
if (currentWord.Length > 0)
wordsList.Add(currentWord);
return String.Join(" ", wordsList);
}
private void AssignOptionsListUIFromRenderOptions(SubjectRenderOptions options)
{
// Prevent ItemChecked events
cblRenderOptions.ItemCheck -= cblRenderOptions_ItemCheck;
FieldInfo[] fields = typeof(SubjectRenderOptions).GetFields();
foreach (FieldInfo field in fields)
{
String listName = FormatUpperCamelCaseStringToSpaces(field.Name);
int itemIndex = cblRenderOptions.Items.IndexOf(listName);
if (options != null)
{
bool value = (bool)field.GetValue(options);
cblRenderOptions.SetItemChecked(itemIndex, value);
}
else
{
// If the options are null then we're updating based on all subjects
if (m_RenderOptions.AllSubjectsHaveOptionEnabled(field))
cblRenderOptions.SetItemCheckState(itemIndex, CheckState.Checked);
else if (m_RenderOptions.AllSubjectsHaveOptionDisabled(field))
cblRenderOptions.SetItemCheckState(itemIndex, CheckState.Unchecked);
// If all items aren't checked and all items aren't unchecked, we need the little square-thingy
else
cblRenderOptions.SetItemCheckState(itemIndex, CheckState.Indeterminate);
}
}
cblRenderOptions.ItemCheck += cblRenderOptions_ItemCheck;
}
private void cblRenderOptions_SelectedIndexChanged(object sender, EventArgs e)
{
// Toggle the selected index
cblRenderOptions.SetItemChecked(cblRenderOptions.SelectedIndex, !cblRenderOptions.GetItemChecked(cblRenderOptions.SelectedIndex));
}
}
}
| 32.246753 | 133 | 0.754329 | [
"MIT"
] | dgerding/Construct | SeeingMachinesVisualization/SeeingMachinesProject/SMVisualization/SMVisualization/RenderOptionsForm.cs | 4,968 | C# |
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using NuGetPackageExplorer.Types;
namespace PackageExplorer
{
[PackageContentViewerMetadata(99, ".jpg", ".gif", ".png", ".tif", ".bmp", ".ico")]
internal class ImageFileViewer : IPackageContentViewer
{
#region IPackageContentViewer Members
public object GetView(string extension, Stream stream)
{
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = stream;
source.EndInit();
return new Image
{
Source = source,
Width = source.Width,
Height = source.Height
};
}
#endregion
}
} | 28 | 86 | 0.557604 | [
"MIT"
] | ItsMrQ/NugetPE-Mod | PackageExplorer/MefServices/ImageFileViewer.cs | 870 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The source user image virtual hard disk. The virtual hard disk will be
/// copied before being attached to the virtual machine. If SourceImage is
/// provided, the destination virtual hard drive must not exist.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class Image : Resource
{
/// <summary>
/// Initializes a new instance of the Image class.
/// </summary>
public Image()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Image class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="sourceVirtualMachine">The source virtual machine from
/// which Image is created.</param>
/// <param name="storageProfile">Specifies the storage settings for the
/// virtual machine disks.</param>
/// <param name="provisioningState">The provisioning state.</param>
/// <param name="hyperVGeneration">Gets the HyperVGenerationType of the
/// VirtualMachine created from the image. Possible values include:
/// 'V1', 'V2'</param>
/// <param name="extendedLocation">The extended location of the
/// Image.</param>
public Image(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), SubResource sourceVirtualMachine = default(SubResource), ImageStorageProfile storageProfile = default(ImageStorageProfile), string provisioningState = default(string), string hyperVGeneration = default(string), ExtendedLocation extendedLocation = default(ExtendedLocation))
: base(location, id, name, type, tags)
{
SourceVirtualMachine = sourceVirtualMachine;
StorageProfile = storageProfile;
ProvisioningState = provisioningState;
HyperVGeneration = hyperVGeneration;
ExtendedLocation = extendedLocation;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the source virtual machine from which Image is
/// created.
/// </summary>
[JsonProperty(PropertyName = "properties.sourceVirtualMachine")]
public SubResource SourceVirtualMachine { get; set; }
/// <summary>
/// Gets or sets specifies the storage settings for the virtual machine
/// disks.
/// </summary>
[JsonProperty(PropertyName = "properties.storageProfile")]
public ImageStorageProfile StorageProfile { get; set; }
/// <summary>
/// Gets the provisioning state.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets the HyperVGenerationType of the VirtualMachine created from
/// the image. Possible values include: 'V1', 'V2'
/// </summary>
[JsonProperty(PropertyName = "properties.hyperVGeneration")]
public string HyperVGeneration { get; set; }
/// <summary>
/// Gets or sets the extended location of the Image.
/// </summary>
[JsonProperty(PropertyName = "extendedLocation")]
public ExtendedLocation ExtendedLocation { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (StorageProfile != null)
{
StorageProfile.Validate();
}
}
}
}
| 40.352941 | 475 | 0.627447 | [
"MIT"
] | MahmoudYounes/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/Models/Image.cs | 4,802 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Powershell
{
using System;
using System.Fabric.Strings;
using System.Management.Automation;
using System.Security.Cryptography.X509Certificates;
[Cmdlet(VerbsCommon.Remove, "ServiceFabricClusterPackage", SupportsShouldProcess = true)]
public sealed class RemoveClusterPackage : ClusterCmdletBase
{
public RemoveClusterPackage()
{
this.CertStoreLocation = StoreLocation.LocalMachine;
}
[Parameter(Mandatory = true, ParameterSetName = "Code")]
public SwitchParameter Code
{
get;
set;
}
[Parameter(Mandatory = true, ParameterSetName = "Config")]
public SwitchParameter Config
{
get;
set;
}
[Parameter(Mandatory = true, ParameterSetName = "Code")]
[Parameter(Mandatory = false, ParameterSetName = "Config")]
[Parameter(Mandatory = true, ParameterSetName = "Both")]
public string CodePackagePathInImageStore
{
get;
set;
}
[Parameter(Mandatory = false, ParameterSetName = "Code")]
[Parameter(Mandatory = true, ParameterSetName = "Config")]
[Parameter(Mandatory = true, ParameterSetName = "Both")]
public string ClusterManifestPathInImageStore
{
get;
set;
}
[Parameter(Mandatory = false)]
public string ImageStoreConnectionString
{
get;
set;
}
[Parameter(Mandatory = false)]
public StoreLocation CertStoreLocation
{
get;
set;
}
protected override void ProcessRecord()
{
if (!string.IsNullOrEmpty(this.CodePackagePathInImageStore) && !this.ShouldProcess(this.CodePackagePathInImageStore))
{
return;
}
if (!string.IsNullOrEmpty(this.ClusterManifestPathInImageStore) && !this.ShouldProcess(this.ClusterManifestPathInImageStore))
{
return;
}
if (!string.IsNullOrEmpty(this.CodePackagePathInImageStore))
{
if (!this.ValidateImageStorePath(this.CodePackagePathInImageStore))
{
return;
}
}
if (!string.IsNullOrEmpty(this.ClusterManifestPathInImageStore))
{
if (!this.ValidateImageStorePath(this.ClusterManifestPathInImageStore))
{
return;
}
}
this.RemoveClusterPackage(
this.CodePackagePathInImageStore,
this.ClusterManifestPathInImageStore,
this.TryFetchImageStoreConnectionString(this.ImageStoreConnectionString, this.CertStoreLocation));
}
}
} | 31.693069 | 137 | 0.558263 | [
"MIT"
] | AndreyTretyak/service-fabric | src/prod/src/managed/powershell/RemoveClusterPackage.cs | 3,201 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Effect2DEditor
{
public class CustomUserControl : UserControl
{
private BufferedGraphics grafx;
private BufferedGraphicsContext context;
protected void InitializeBuffer()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
context = BufferedGraphicsManager.Current;
context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
grafx = context.Allocate(this.CreateGraphics(), new Rectangle(0, 0, this.Width, this.Height));
this.SizeChanged += CustomUserControl_SizeChanged;
this.Paint += CustomUserControl_Paint;
}
void CustomUserControl_Paint(object sender, PaintEventArgs e)
{
grafx.Render(e.Graphics);
}
void CustomUserControl_SizeChanged(object sender, EventArgs e)
{
if (this.Width > 0 && this.Height > 0)
{
context = BufferedGraphicsManager.Current;
context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1);
grafx = context.Allocate(this.CreateGraphics(), new Rectangle(0, 0, this.Width, this.Height));
DrawAndRefresh();
}
}
protected virtual void DrawToBuffer(Graphics g)
{
g.Clear(this.BackColor == Color.Transparent ? Color.White : this.BackColor);
}
public void DrawAndRefresh()
{
DrawToBuffer(grafx.Graphics);
Refresh();
}
}
}
| 35.4375 | 110 | 0.610229 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/Effect2DEditor/CustomUserControl.cs | 1,703 | C# |
namespace Ange.Domain.Entities
{
using System;
using System.Collections.Generic;
using Enumerations;
public class Room
{
public Room()
{
Participants = new HashSet<UserRoom>();
Messages = new HashSet<ChatMessage>();
}
public Guid Id { get; set; }
public string Title { get; set; }
public Guid RoomCreator { get; set; }
public RoomType Type { get; set; }
public ICollection<UserRoom> Participants { get; private set; }
public ICollection<ChatMessage> Messages { get; private set; }
}
} | 27.545455 | 71 | 0.592409 | [
"MIT"
] | v4rden/Ange | Ange.Domain/Entities/Room.cs | 606 | C# |
namespace JobPortal.Authentication.External
{
public class ExternalAuthUserInfo
{
public string ProviderKey { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string Surname { get; set; }
public string Provider { get; set; }
}
}
| 20.625 | 48 | 0.615152 | [
"MIT"
] | akshaygopi26/JobPortalDotnetAngular | aspnet-core/src/JobPortal.Web.Core/Authentication/External/ExternalAuthUserInfo.cs | 332 | C# |
//==============================================================
// Copyright (C) 2020 Inc. All rights reserved.
//
//==============================================================
// Create by 种道洋 at 2020/5/26 12:44:42.
// Version 1.0
// 种道洋
//==============================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Cdy.Spider
{
public static class LogoHelper
{
#region ... Variables ...
#endregion ...Variables...
#region ... Events ...
#endregion ...Events...
#region ... Constructor...
#endregion ...Constructor...
#region ... Properties ...
#endregion ...Properties...
#region ... Methods ...
/// <summary>
///
/// </summary>
public static void Print()
{
//"Cdy.Tag.Common.Logo.Logo.txt"
Console.WriteLine(new StreamReader(typeof(LogoHelper).Assembly.GetManifestResourceStream("Cdy.Spider.Common.Logo.Logo.txt")).ReadToEnd());
}
/// <summary>
///
/// </summary>
public static void PrintAuthor()
{
Console.WriteLine(new StreamReader(typeof(LogoHelper).Assembly.GetManifestResourceStream("Cdy.Spider.Common.Logo.Author.txt")).ReadToEnd());
Console.WriteLine("Created by chongdaoyang.Powered by dotnet core.");
}
#endregion ...Methods...
#region ... Interfaces ...
#endregion ...Interfaces...
}
}
| 25.274194 | 152 | 0.490108 | [
"Apache-2.0"
] | bingwang12/Spider | Common/Cdy.Spider.Common/Logo/LogoHelper.cs | 1,581 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine.EventSystems;
namespace Microsoft.MixedReality.Toolkit.Experimental.InteractiveElement
{
/// <summary>
/// The internal event receiver for the events defined in the Focus Interaction Event Configuration.
/// </summary>
public class FocusReceiver : BaseEventReceiver
{
public FocusReceiver(BaseInteractionEventConfiguration eventConfiguration) : base(eventConfiguration) { }
private FocusEvents focusEventConfig => EventConfiguration as FocusEvents;
private FocusInteractionEvent onFocusOn => focusEventConfig.OnFocusOn;
private FocusInteractionEvent onFocusOff => focusEventConfig.OnFocusOff;
private bool hadFocus;
/// <inheritdoc />
public override void OnUpdate(StateManager stateManager, BaseEventData eventData)
{
bool hasFocus = stateManager.GetState(StateName).Value > 0;
if (hadFocus != hasFocus)
{
if (hasFocus)
{
onFocusOn.Invoke(eventData as FocusEventData);
}
else
{
onFocusOff.Invoke(eventData as FocusEventData);
}
}
hadFocus = hasFocus;
}
}
}
| 32 | 114 | 0.615278 | [
"MIT"
] | HyperLethalVector/ProjectEsky-UnityIntegration | Assets/MRTK/SDK/Experimental/InteractiveElement/IE/EvtReceivers/FocusReceiver.cs | 1,442 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.