hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c0277721c75f41e70a12560b541589612c871d2 | 1,284 | cs | C# | Oxozle.MiniRPG.GameConfig/Models/ShopsConfiguration.cs | oxozle/mini-rpg | 954f2f71f1b7fcf6dca4178c3ead6261a6469049 | [
"MIT"
] | 1 | 2019-02-03T15:08:03.000Z | 2019-02-03T15:08:03.000Z | Oxozle.MiniRPG.GameConfig/Models/ShopsConfiguration.cs | oxozle/mini-rpg | 954f2f71f1b7fcf6dca4178c3ead6261a6469049 | [
"MIT"
] | null | null | null | Oxozle.MiniRPG.GameConfig/Models/ShopsConfiguration.cs | oxozle/mini-rpg | 954f2f71f1b7fcf6dca4178c3ead6261a6469049 | [
"MIT"
] | 1 | 2018-10-12T11:46:42.000Z | 2018-10-12T11:46:42.000Z | // *********************************************************************************
// Author: Azarov Dmitriy
// Email: oxozle@gmail.com
// Date: 20.02.2015
// Project: Oxozle.MiniRPG.GameConfig.ShopsConfiguration.cs
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// *********************************************************************************
namespace Oxozle.MiniRPG.GameConfig.Models
{
/// <summary>
/// Все магазины в игре
/// </summary>
public class ShopsConfiguration
{
public ShopsConfiguration()
{
Armor = new ShopConfiguration();
Weapon = new ShopConfiguration();
Heal = new ShopConfiguration();
}
public ShopConfiguration Armor { get; set; }
public ShopConfiguration Weapon { get; set; }
public ShopConfiguration Heal { get; set; }
}
/// <summary>
/// Магазин
/// </summary>
public sealed class ShopConfiguration
{
public int Price { get; set; }
public int EffectFrom { get; set; }
public int EffectTo { get; set; }
}
} | 31.317073 | 85 | 0.545171 |
f34731450253a10e83c35978c978b5345b552a48 | 4,228 | cs | C# | Algorithms/Algorithms/Form1.Designer.cs | shenhx/DotNetAll | e59996ba1ef9240b2594cd86b5d4b3924666c19f | [
"MIT"
] | 3 | 2018-10-16T05:37:58.000Z | 2019-11-22T06:44:52.000Z | Algorithms/Algorithms/Form1.Designer.cs | shenhx/DotNetAll | e59996ba1ef9240b2594cd86b5d4b3924666c19f | [
"MIT"
] | 1 | 2018-11-12T05:09:09.000Z | 2018-11-12T05:09:09.000Z | Algorithms/Algorithms/Form1.Designer.cs | shenhx/DotNetAll | e59996ba1ef9240b2594cd86b5d4b3924666c19f | [
"MIT"
] | 1 | 2019-11-22T06:46:15.000Z | 2019-11-22T06:46:15.000Z | namespace Algorithms
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnHannuo = new System.Windows.Forms.Button();
this.btnCalPrimeNumber = new System.Windows.Forms.Button();
this.btnPyramid = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnHannuo
//
this.btnHannuo.Location = new System.Drawing.Point(17, 16);
this.btnHannuo.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnHannuo.Name = "btnHannuo";
this.btnHannuo.Size = new System.Drawing.Size(100, 29);
this.btnHannuo.TabIndex = 0;
this.btnHannuo.Text = "汉诺";
this.btnHannuo.UseVisualStyleBackColor = true;
this.btnHannuo.Click += new System.EventHandler(this.btnHannuo_Click);
//
// btnCalPrimeNumber
//
this.btnCalPrimeNumber.Location = new System.Drawing.Point(125, 16);
this.btnCalPrimeNumber.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnCalPrimeNumber.Name = "btnCalPrimeNumber";
this.btnCalPrimeNumber.Size = new System.Drawing.Size(100, 29);
this.btnCalPrimeNumber.TabIndex = 1;
this.btnCalPrimeNumber.Text = "求质数";
this.btnCalPrimeNumber.UseVisualStyleBackColor = true;
this.btnCalPrimeNumber.Click += new System.EventHandler(this.btnCalPrimeNumber_Click);
//
// btnPyramid
//
this.btnPyramid.Location = new System.Drawing.Point(233, 16);
this.btnPyramid.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnPyramid.Name = "btnPyramid";
this.btnPyramid.Size = new System.Drawing.Size(100, 29);
this.btnPyramid.TabIndex = 2;
this.btnPyramid.Text = "金字塔";
this.btnPyramid.UseVisualStyleBackColor = true;
this.btnPyramid.Click += new System.EventHandler(this.btnPyramid_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(341, 13);
this.button1.Margin = new System.Windows.Forms.Padding(4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(126, 29);
this.button1.TabIndex = 3;
this.button1.Text = "拓扑排序";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1140, 576);
this.Controls.Add(this.button1);
this.Controls.Add(this.btnPyramid);
this.Controls.Add(this.btnCalPrimeNumber);
this.Controls.Add(this.btnHannuo);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnHannuo;
private System.Windows.Forms.Button btnCalPrimeNumber;
private System.Windows.Forms.Button btnPyramid;
private System.Windows.Forms.Button button1;
}
}
| 39.886792 | 98 | 0.573321 |
ee63fb2d6d27991c8f4ebb98f80ede6974ea07f7 | 2,898 | cs | C# | AdsInstaller/AdsInstaller/Setup.cs | Andrew-Miranti/ClementineMalware | a84722d3e62b6cfd76c6fcd3aefe145192433471 | [
"MS-PL",
"MIT"
] | null | null | null | AdsInstaller/AdsInstaller/Setup.cs | Andrew-Miranti/ClementineMalware | a84722d3e62b6cfd76c6fcd3aefe145192433471 | [
"MS-PL",
"MIT"
] | null | null | null | AdsInstaller/AdsInstaller/Setup.cs | Andrew-Miranti/ClementineMalware | a84722d3e62b6cfd76c6fcd3aefe145192433471 | [
"MS-PL",
"MIT"
] | null | null | null | using System;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.TaskScheduler;
namespace Installer
{
static class Install
{
static void Main(string[] args)
{
Console.WriteLine("Installing");
WriteToRegistry();
StartAdsTask();
Console.ReadLine();
}
private static void WriteToRegistry()
{
try
{
using (var entry = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\clementine"))
{
entry.SetValue("DisplayName", "Clementine");
entry.SetValue("DisplayVersion", 0);
entry.SetValue("Publisher", "Not Andrew Miranti");
entry.SetValue("VersionMinor", 0);
entry.SetValue("VersionMajor", 0);
entry.SetValue("Version", "0");
entry.SetValue("HelpLink", "http://www.google.com");
entry.SetValue("HelpTelephone", "911");
entry.SetValue("InstallDate", "September 25, 1066");
entry.SetValue("InstallLocation", "C:\\");
entry.SetValue("InstallSource", "A:\\");
entry.SetValue("URLInfoAbout", "http://en.wikipedia.org");
entry.SetValue("URLUpdateInfo", "http://en.wikipedia.org/wiki/Philosophy");
entry.SetValue("AuthorizedCDFPrefix", "Cupcakes");
entry.SetValue("Comments", "Oh my darling...");
entry.SetValue("Contact", "Direct all hate mail to Santa.");
entry.SetValue("EstimatedSize", 0x50000000);
entry.SetValue("Language", 1033);
entry.SetValue("ModifyPath", "B:\\");
entry.SetValue("Readme", "");
entry.SetValue("UninstallString", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "clementine", "Clementine.exe"));
entry.SetValue("SettingsIdentifier", "");
}
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void StartAdsTask()
{
using (var scheduler = new TaskService())
{
var adTask = scheduler.NewTask();
adTask.Actions.Add(new ExecAction(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "clementine", "adTask.exe")));
var trigger = new TimeTrigger();
trigger.Repetition.Interval = TimeSpan.FromMinutes(1);
adTask.Triggers.Add(trigger);
TaskService.Instance.RootFolder.RegisterTaskDefinition("Check Printer Drivers", adTask);
}
}
}
}
| 43.253731 | 166 | 0.537612 |
29503f733dbf309710428d866d14510711b81871 | 185 | cs | C# | Cethleann.Structure/Resource/Model/ShaderType.cs | TGEnigma/Cethleann | 42d0dc7d671d1c0ee7a7b2c70378311153eeeed1 | [
"MIT"
] | 20 | 2020-09-18T20:47:48.000Z | 2022-03-30T19:41:17.000Z | Cethleann.Structure/Resource/Model/ShaderType.cs | TGEnigma/Cethleann | 42d0dc7d671d1c0ee7a7b2c70378311153eeeed1 | [
"MIT"
] | 28 | 2020-01-19T13:30:32.000Z | 2020-04-26T00:13:53.000Z | Cethleann.Structure/Resource/Model/ShaderType.cs | TGEnigma/Cethleann | 42d0dc7d671d1c0ee7a7b2c70378311153eeeed1 | [
"MIT"
] | 9 | 2020-06-27T10:13:40.000Z | 2021-12-09T17:46:44.000Z | namespace Cethleann.Structure.Resource.Model
{
public enum ShaderType : short
{
Float32 = 0x1,
Matrix4X4X2 = 0x20 // assumption, it contains 32 floats.
}
}
| 20.555556 | 64 | 0.637838 |
7765228f7bc050517e2d03c79518179bf05a5f28 | 4,400 | cs | C# | frmAdminForm.cs | kougyokugentou/GreatHomeChildcare | e8bba4484aa39865d7c90120a740d732c8506a2c | [
"Unlicense"
] | null | null | null | frmAdminForm.cs | kougyokugentou/GreatHomeChildcare | e8bba4484aa39865d7c90120a740d732c8506a2c | [
"Unlicense"
] | null | null | null | frmAdminForm.cs | kougyokugentou/GreatHomeChildcare | e8bba4484aa39865d7c90120a740d732c8506a2c | [
"Unlicense"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using GreatHomeChildcare.Models;
/* Refs:
* https://stackoverflow.com/questions/10063770/how-to-add-a-new-row-to-datagridview-programmatically
* https://stackoverflow.com/questions/3370236/changing-the-row-height-of-a-datagridview
*/
namespace GreatHomeChildcare
{
public partial class frmAdminForm : Form
{
//globals for cheap access.
SqliteDataAccess SqliteDataAccess = new SqliteDataAccess();
public static int child_id = 0;
public frmAdminForm()
{
InitializeComponent();
}
// Load the datagridview of children when this form opens.
private void frmAdminForm_Load(object sender, EventArgs e)
{
RefreshAdminView();
}
/* Load the admin form with a datagridview of
* all the children in the sql database.
* the 'id' field is present in the datagridview for easy access
* but is hidden in the UI.
* INPUT: List of all children
* OUTPUT: Datagridview.
*/
private void RefreshAdminView()
{
dgvChildren.Rows.Clear();
List<Child> children = new List<Child>();
children = SqliteDataAccess.GetAllChildren();
foreach (Child c in children)
{
Image photo = (c.photo != null) ? ImageWrangler.ByteArrayToImage(c.photo) : Properties.Resources.child;
dgvChildren.Rows.Add(c.id, photo, c.DisplayName);
}
}
//Close this screen, we're all done here.
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
/* VS generated delegate to handle report button clicking
* Pops up the report form and hides this one.
*/
private void btnReports_Click(object sender, EventArgs e)
{
Form frmRep = new frmReports();
//We can use the same event handler here, don't mind the name.
frmRep.FormClosed += new FormClosedEventHandler(CrudFormClosed);
frmRep.Show();
Hide();
}
/* Pop-open a new form for crud operations for children
* and their guardians. Be sure you set the child_id
* to -1 here just to be on the super-safe side.
*/
private void btnAdd_Click(object sender, EventArgs e)
{
child_id = -1; //ENSURE!!!!
ShowChildCrudForm();
}
/* Call the same crud form for adding a new child
* but store the child_id so the crud form
* can pick it up on form load.
*/
private void btnUpdate_Click(object sender, EventArgs e)
{
/* Get the child's database ID which is secretly hidden
* in the datagrid view at column 0. Since value is an
* Object, cast it to Int because that's what we know it is.
*/
child_id = (int)dgvChildren.CurrentRow.Cells[0].Value;
ShowChildCrudForm();
}
/* Seperate function to show the crud form
* because both the add and the update buttons
* will show the same crud form.
* INPUT: void
* OUTPUT: void
*/
private void ShowChildCrudForm()
{
Form frmCrud = new frmChildCrud();
frmCrud.FormClosed += new FormClosedEventHandler(CrudFormClosed);
frmCrud.Show();
Hide();
}
//Show this admin screen after the child crud form is closed.
private void CrudFormClosed(object sender, FormClosedEventArgs e)
{
RefreshAdminView();
Show();
}
/* Allow the admin to quit the program as a normal login
* will not be able to exit the attendence program
* from the main pin screen on the shared tablet.
*/
private void btnQuit_Click(object sender, EventArgs e)
{
MessageBox.Show("Thank you for using the program! Your data has been saved. Good bye!", "Great Home Childcare", MessageBoxButtons.OK, MessageBoxIcon.None);
//TODO: I got the program to crash here by exiting from reports form then clicking quit??
Environment.Exit(0);
}
}
}
| 33.846154 | 167 | 0.591136 |
b17bd29681f6dea1bbada038686071353b9c4309 | 2,572 | cs | C# | ClForms/Elements/Canvas.cs | Ahatornn/clforms | 75d000f220cb48034571706b47408fb7aa8189e7 | [
"Apache-2.0"
] | 3 | 2020-04-17T20:27:02.000Z | 2020-06-25T04:07:03.000Z | ClForms/Elements/Canvas.cs | Ahatornn/clforms | 75d000f220cb48034571706b47408fb7aa8189e7 | [
"Apache-2.0"
] | null | null | null | ClForms/Elements/Canvas.cs | Ahatornn/clforms | 75d000f220cb48034571706b47408fb7aa8189e7 | [
"Apache-2.0"
] | null | null | null | using System;
using ClForms.Abstractions;
using ClForms.Abstractions.Engine;
using ClForms.Common;
using ClForms.Common.EventArgs;
using ClForms.Core;
using ClForms.Elements.Abstractions;
namespace ClForms.Elements
{
/// <summary>
/// Control for drawing some pseudographics chars
/// </summary>
public class Canvas: Control, IElementStyle<Canvas>
{
/// <summary>
/// Initialize a new instance <see cref="Canvas"/>
/// </summary>
public Canvas()
{
Background = Application.SystemColors.WindowBackground;
Foreground = Application.SystemColors.WindowForeground;
AutoSize = true;
}
#region Methods
/// <inheritdoc cref="Control.Measure"/>
public override void Measure(Size availableSize)
{
var contentArea = new Rect(new Size(availableSize.Width, availableSize.Height))
.Reduce(Margin)
.Reduce(Padding);
contentArea.Width = Width ?? contentArea.Width;
contentArea.Height = Height ?? contentArea.Height;
if (AutoSize)
{
var value = new Size(Math.Min(contentArea.Width + (Margin + Padding).Horizontal, availableSize.Width),
Math.Min(contentArea.Height + (Margin + Padding).Vertical, availableSize.Height));
base.Measure(value);
}
else
{
base.Measure(new Size(Math.Min(Width ?? availableSize.Width, availableSize.Width),
Math.Min(Height ?? availableSize.Height, availableSize.Height)));
}
}
/// <inheritdoc cref="IElementStyle{T}.SetStyle"/>
public void SetStyle(Action<Canvas> styleAction) => styleAction?.Invoke(this);
/// <inheritdoc cref="Control.OnRender"/>
protected override void OnRender(IDrawingContext context)
{
InheritRender(context);
var reducedArea = context.ContextBounds.Reduce(Padding);
if (reducedArea.HasEmptyDimension())
{
return;
}
OnPaint?.Invoke(this, new PaintEventArgs(reducedArea, context));
}
protected virtual void InheritRender(IDrawingContext context) => base.OnRender(context);
#endregion
#region Events
/// <summary>
/// Occurs when the <see cref="Canvas"/> control is rendering
/// </summary>
public event EventHandler<PaintEventArgs> OnPaint;
#endregion
}
}
| 32.974359 | 118 | 0.594479 |
edb02ec540fc38468194a9b1b94f8447053c7124 | 115,897 | cs | C# | src/src/Interop.cs | VasiliyZhushma/atapi.net | d97714881313ce20cc1d661ba9e483c5444e2c9f | [
"MIT"
] | null | null | null | src/src/Interop.cs | VasiliyZhushma/atapi.net | d97714881313ce20cc1d661ba9e483c5444e2c9f | [
"MIT"
] | 1 | 2020-07-19T15:42:18.000Z | 2020-07-19T15:42:18.000Z | src/src/Interop.cs | VasiliyZhushma/atapi.net | d97714881313ce20cc1d661ba9e483c5444e2c9f | [
"MIT"
] | null | null | null | // Interop.cs
//
// This is a part of the TAPI Applications Classes .NET library (ATAPI)
//
// Copyright (c) 2005-2018 JulMar Technology, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
namespace JulMar.Atapi.Interop
{
/// <summary>
/// Messages for phones and lines
/// </summary>
internal enum TapiEvent
{
LINE_ADDRESSSTATE = 0,
LINE_CALLINFO,
LINE_CALLSTATE,
LINE_CLOSE,
LINE_DEVSPECIFIC,
LINE_DEVSPECIFICFEATURE,
LINE_GATHERDIGITS,
LINE_GENERATE,
LINE_LINEDEVSTATE,
LINE_MONITORDIGITS,
LINE_MONITORMEDIA,
LINE_MONITORTONE,
LINE_REPLY,
LINE_REQUEST,
PHONE_BUTTON,
PHONE_CLOSE,
PHONE_DEVSPECIFIC,
PHONE_REPLY,
PHONE_STATE,
LINE_CREATE,
PHONE_CREATE,
LINE_AGENTSPECIFIC,
LINE_AGENTSTATUS,
LINE_APPNEWCALL,
LINE_PROXYREQUEST,
LINE_REMOVE,
PHONE_REMOVE,
LINE_AGENTSESSIONSTATUS,
LINE_QUEUESTATUS,
LINE_AGENTSTATUSEX,
LINE_GROUPSTATUS,
LINE_PROXYSTATUS,
LINE_APPNEWCALLHUB,
LINE_CALLHUBCLOSE,
LINE_DEVSPECIFICEX,
};
/// <summary>
/// This class holds a TAPI call handle
/// </summary>
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class HTCALL : SafeHandle
{
internal HTCALL()
: base(IntPtr.Zero, true)
{
}
internal HTCALL(IntPtr preexistingHandle, bool ownsHandle)
: base(preexistingHandle, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero)
{
NativeMethods.lineDeallocateCall(this);
handle = IntPtr.Zero;
}
return true;
}
/// <summary>
/// Fixed according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.isinvalid(v=vs.80).aspx
/// </summary>
public override bool IsInvalid
{
get { return IsClosed || handle == IntPtr.Zero; }
}
}
/// <summary>
/// This class holds a TAPI line handle
/// </summary>
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class HTLINE : SafeHandle
{
internal HTLINE()
: base(IntPtr.Zero, true)
{
}
internal HTLINE(IntPtr preexistingHandle, bool ownsHandle)
: base(preexistingHandle, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero)
{
NativeMethods.lineClose(this);
handle = IntPtr.Zero;
}
return true;
}
/// <summary>
/// Fixed according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.isinvalid(v=vs.80).aspx
/// </summary>
public override bool IsInvalid
{
get { return IsClosed || handle == IntPtr.Zero; }
}
}
/// <summary>
/// This class holds a TAPI phone handle
/// </summary>
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class HTPHONE : SafeHandle
{
internal HTPHONE()
: base(IntPtr.Zero, true)
{
}
internal HTPHONE(IntPtr preexistingHandle, bool ownsHandle)
: base(preexistingHandle, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero)
{
NativeMethods.phoneClose(this);
handle = IntPtr.Zero;
}
return true;
}
/// <summary>
/// Fixed according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.isinvalid(v=vs.80).aspx
/// </summary>
public override bool IsInvalid => IsClosed || handle == IntPtr.Zero;
}
/// <summary>
/// This class holds a TAPI application handle
/// </summary>
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class HTLINEAPP : SafeHandle
{
internal HTLINEAPP()
: base(IntPtr.Zero, true)
{
}
internal HTLINEAPP(IntPtr preexistingHandle, bool ownsHandle)
: base(preexistingHandle, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero)
{
NativeMethods.lineShutdown(this);
handle = IntPtr.Zero;
}
return true;
}
/// <summary>
/// Fixed according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.isinvalid(v=vs.80).aspx
/// </summary>
public override bool IsInvalid
{
get { return IsClosed || handle == IntPtr.Zero; }
}
}
/// <summary>
/// This class holds a TAPI phone application handle
/// </summary>
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class HTPHONEAPP : SafeHandle
{
internal HTPHONEAPP()
: base(IntPtr.Zero, true)
{
}
internal HTPHONEAPP(IntPtr preexistingHandle, bool ownsHandle)
: base(preexistingHandle, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero)
{
NativeMethods.phoneShutdown(this);
handle = IntPtr.Zero;
}
return true;
}
/// <summary>
/// Fixed according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.isinvalid(v=vs.80).aspx
/// </summary>
public override bool IsInvalid => IsClosed || handle == IntPtr.Zero;
}
/// <summary>
/// Delegate used to describe the PHONECALLBACK and LINECALLBACK used by TAPI32.DLL to notify the application of events
/// </summary>
/// <param name="dwMessage">TAPI Message</param>
/// <param name="dwParam1">Param1</param>
/// <param name="dwParam2">Param2</param>
/// <param name="dwParam3">Param3</param>
internal delegate void TapiEventCallback(TapiEvent dwMessage, IntPtr dwParam1, IntPtr dwParam2, IntPtr dwParam3);
/// <summary>
/// This class holds all the API and structures/constants used by TAPI 2.x
/// </summary>
internal static class NativeMethods
{
private const string _tapi = "tapi32.dll";
#region TAPI Api definitions
#pragma warning disable IDE1006 // Naming Styles
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineAccept(HTCALL hCall, byte[] UserUserInfo, int dwSize);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineAddToConference(HTCALL hConfCall, HTCALL hConsultCall);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineAnswer(HTCALL hCall, byte[] UserUserInfo, int dwSize);
[DllImport(_tapi, EntryPoint = "lineBlindTransferW", CharSet = CharSet.Auto)]
internal static extern int lineBlindTransfer(HTCALL hCall, [MarshalAs(UnmanagedType.LPWStr)] string destAddress, int countryCode);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineClose(HTLINE hLine);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineCompleteCall(HTCALL hCall, IntPtr lpCompletionId, int mode, int messageId);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineCompleteTransfer(HTCALL hCall, HTCALL htConsult, out IntPtr htConfCall, int dwTransferMode);
[DllImport(_tapi, EntryPoint = "lineConfigDialogW", CharSet = CharSet.Auto)]
internal static extern int lineConfigDialog(int dwDeviceID, IntPtr hwndOwner, [MarshalAs(UnmanagedType.LPWStr)] string lpszDeviceClass);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineDeallocateCall(HTCALL hCall);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineDevSpecific(HTLINE hLine, int dwAddressID, uint hCall, IntPtr lpParams, int dwSize);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineDevSpecificFeature(HTLINE hLine, int dwFeature, IntPtr lpParams, int dwSize);
[DllImport(_tapi, EntryPoint = "lineDialW", CharSet = CharSet.Auto)]
internal static extern int lineDial(HTCALL hCall, [MarshalAs(UnmanagedType.LPWStr)] string destAddress, int countryCode);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineDrop(HTCALL hCall, byte[] UserInfo, int dwSize);
[DllImport(_tapi, EntryPoint="lineForwardW", CharSet = CharSet.Auto)]
internal static extern int lineForward(HTLINE hLine, int bAllAddresses, int dwAddressID, IntPtr lpForwardList, int dwNumRingsNoAnswer, out IntPtr lphConsultCall, IntPtr lpCallParams);
[DllImport(_tapi, EntryPoint = "lineGatherDigitsW", CharSet = CharSet.Auto)]
internal static extern int lineGatherDigits(HTCALL hCall, int dwDigitModes, [MarshalAs(UnmanagedType.LPWStr)] out StringBuilder buffer, int numDigits, [MarshalAs(UnmanagedType.LPWStr)] string termDigits, int firstDigitTimeout, int interDigitTimeout);
[DllImport(_tapi, EntryPoint="lineGatherDigitsW", CharSet = CharSet.Auto)]
internal static extern int lineCancelGatherDigits(HTCALL hCall, int dwDigitModes, [MarshalAs(UnmanagedType.LPWStr)] string buffer, int numDigits, [MarshalAs(UnmanagedType.LPWStr)] string termDigits, int firstDigitTimeout, int interDigitTimeout);
[DllImport(_tapi, EntryPoint="lineGenerateDigitsW", CharSet = CharSet.Auto)]
internal static extern int lineGenerateDigits(HTCALL hCall, int dwDigitMode, [MarshalAs(UnmanagedType.LPWStr)] string buffer, int dwDuration);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGenerateTone(HTCALL hCall, int dwToneMode, int dwDuration, int dwNumTones, LINEGENERATETONE[] arrTones);
[DllImport(_tapi, EntryPoint = "lineGetAddressCapsW", CharSet = CharSet.Auto)]
internal static extern int lineGetAddressCaps(HTLINEAPP hLineApp, int dwDeviceID, int dwAddressID, int dwApiVersion, int dwExtVersion, IntPtr lpAddressCaps);
[DllImport(_tapi, EntryPoint = "lineGetAddressStatusW", CharSet = CharSet.Auto)]
internal static extern int lineGetAddressStatus(HTLINE hLine, int dwAddressID, IntPtr lpAddressStatus);
[DllImport(_tapi, EntryPoint = "lineGetCallInfoW", CharSet = CharSet.Auto)]
internal static extern int lineGetCallInfo(HTCALL hCall, IntPtr lpCallInfo);
[DllImport(_tapi, EntryPoint = "lineGetCallStatus", CharSet = CharSet.Auto)]
internal static extern int lineGetCallStatus(HTCALL hCall, IntPtr lpCallStatus);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetConfRelatedCalls(HTCALL hCall, IntPtr lpCallList);
[DllImport(_tapi, EntryPoint = "lineGetCountryW", CharSet = CharSet.Auto)]
internal static extern int lineGetCountry(int dwCountryID, int dwApiVersion, IntPtr lpLineCountryList);
[DllImport(_tapi, EntryPoint = "lineGetDevCapsW", CharSet = CharSet.Auto)]
internal static extern int lineGetDevCaps(HTLINEAPP hLineApp, int dwDeviceID, int dwApiVersion, int dwExtVersion, IntPtr lpLineDevCaps);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetDevConfig(int dwDeviceID, IntPtr deviceConfig, [MarshalAs(UnmanagedType.LPWStr)] string deviceClass);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetID(HTLINE hLine, int dwAddressID, HTCALL hCall, int dwSelect, IntPtr deviceID, [MarshalAs(UnmanagedType.LPWStr)] string deviceClass);
[DllImport(_tapi, EntryPoint = "lineGetLineDevStatusW", CharSet = CharSet.Auto)]
internal static extern int lineGetLineDevStatus(HTLINE htLine, IntPtr lpLineStatus);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetMessage(HTLINEAPP hLineApp, ref LINEMESSAGE lpMessage, int dwTimeout);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetNewCalls(HTLINE hLine, int dwAddressID, int dwSelect, IntPtr lpCallList);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineGetNumRings(HTLINE hLine, int dwAddressID, out int lpdwNumRings);
[DllImport(_tapi, EntryPoint = "lineGetProviderListW", CharSet = CharSet.Auto)]
internal static extern int lineGetProviderList(int dwAPIVersion, IntPtr lpProviderList);
[DllImport(_tapi, EntryPoint = "lineGetTranslateCapsW", CharSet = CharSet.Auto)]
internal static extern int lineGetTranslateCaps(HTLINEAPP hLineApp, int dwApiVersion, IntPtr lpTranslateCaps);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineHold(HTCALL hCall);
[DllImport(_tapi, EntryPoint = "lineInitializeExW", CharSet = CharSet.Auto)]
internal static extern int lineInitializeEx(out IntPtr hLineApp, IntPtr hAppHandle, TapiEventCallback CalllBack, [MarshalAs(UnmanagedType.LPWStr)] string friendlyAppName, out int numDevices, ref int apiVersion, ref LINEINITIALIZEEXPARAMS lineExParms);
[DllImport(_tapi, EntryPoint = "lineMakeCallW", CharSet = CharSet.Auto)]
internal static extern int lineMakeCall(HTLINE hLine, out IntPtr hCall, [MarshalAs(UnmanagedType.LPWStr)] string destAddress, int countryCode, IntPtr lpCallParams);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineNegotiateAPIVersion(HTLINEAPP hLineApp, int dwDeviceID, int dwApiLowVersion, int dwApiHighVersion, out int lpdwApiVersion, out LINEEXTENSIONID lpExtensionID);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineNegotiateExtVersion(HTLINEAPP hLineApp, int dwDeviceID, int dwApiVersion, int dwExtLowVersion, int dwExtHighVersion, out int dwExtVersion);
[DllImport(_tapi, EntryPoint = "lineOpenW", CharSet = CharSet.Auto)]
internal static extern int lineOpen(HTLINEAPP hLineApp, int dwDeviceID, out IntPtr hLine, int dwApiVersion, int dwExtVersion, IntPtr dwCallbackInstance, int dwPrivileges, int dwMediaModes, ref LINECALLPARAMS lpCallParams);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineMonitorDigits(HTCALL hCall, int digitModes);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineMonitorMedia(HTCALL hCall, int mediaModes);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineMonitorTones(HTCALL hCall, LINEMONITORTONE[] tones, int numEntries);
[DllImport(_tapi, EntryPoint = "lineParkW", CharSet = CharSet.Auto)]
internal static extern int linePark(HTCALL hCall, int parkMode, [MarshalAs(UnmanagedType.LPWStr)] string address, IntPtr ndAddress);
[DllImport(_tapi, EntryPoint = "linePickupW", CharSet = CharSet.Auto)]
internal static extern int linePickup(HTLINE hLine, int addressId, out IntPtr hCall, [MarshalAs(UnmanagedType.LPWStr)] string destAddress, string groupId);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int linePrepareAddToConference(HTCALL hConfCall, out IntPtr hConsultCall, IntPtr lpCallParams);
[DllImport(_tapi, EntryPoint = "lineRedirectW", CharSet = CharSet.Auto)]
internal static extern int lineRedirect(HTCALL hCall, [MarshalAs(UnmanagedType.LPWStr)] string address, int countryCode);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineReleaseUserUserInfo(HTCALL hCall);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineRemoveFromConference(HTCALL hConfCall, HTCALL hConsultCall);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSecureCall(HTCALL hCall);
[DllImport(_tapi, CharSet = CharSet.Ansi)]
internal static extern int lineSendUserUserInfo(HTCALL hCall, [MarshalAs(UnmanagedType.LPStr)] string data, int dwLength);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetAppSpecific(HTCALL hCall, int appData);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetCallData(HTCALL hCall, byte[] pBuffer, int dwLength);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetCallParams(HTCALL hCall, int dwBearerMode, int dwMinRate, int dwMaxRate, LINEDIALPARAMS ldp);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetCallPrivilege(HTCALL hCall, int privilege);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetCallTreatment(HTCALL hCall, int dwCallTreatment);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetCurrentLocation(HTLINEAPP hLineApp, int currLocation);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetDevConfig(int deviceId, IntPtr devConfig, int dwSize, string deviceConfig);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetLineDevStatus(HTLINE hLine, int dwStatus, int onOff);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetMediaMode(HTCALL hCall, int mediaMode);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetNumRings(HTLINE hLine, int dwAddressID, int lpdwNumRings);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetStatusMessages(HTLINE hLine, int dwLineStates, int dwAddressStates);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetupConference(HTCALL hCall, HTLINE hLine, out IntPtr htConferenceCall, out IntPtr htConsultCall, int dwNumParties, IntPtr lpCallParams);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSetupTransfer(HTCALL hCall, out IntPtr htConsultCall, IntPtr lpCallParams);
[DllImport(_tapi, CharSet = CharSet.Auto), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int lineShutdown(HTLINEAPP hLine);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineSwapHold(HTCALL hCall, HTCALL otherCall);
[DllImport(_tapi, EntryPoint = "lineTranslateAddressW", CharSet = CharSet.Auto)]
internal static extern int lineTranslateAddress(HTLINEAPP hLineApp, int dwDeviceID, int dwAPIVersion, [MarshalAs(UnmanagedType.LPWStr)] string sAddressIn, int dwCard, int dwTranslateOptions, IntPtr lpTranslateOutput);
[DllImport(_tapi, EntryPoint = "lineTranslateDialogW", CharSet = CharSet.Auto)]
internal static extern int lineTranslateDialog(HTLINEAPP hLineApp, int dwDeviceID, int dwAPIVersion, IntPtr hwndOwner, string lpszAddressIn);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineUncompleteCall(HTLINE hLine, int completionId);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int lineUnhold(HTCALL hCall);
[DllImport(_tapi, EntryPoint = "lineUnparkW", CharSet = CharSet.Auto)]
internal static extern int lineUnpark(HTLINE hLine, int addressID, out IntPtr hCall, [MarshalAs(UnmanagedType.LPWStr)] string parkAddress);
[DllImport(_tapi, EntryPoint = "phoneClose", CharSet = CharSet.Auto)]
internal static extern int phoneClose(HTPHONE hPhone);
[DllImport(_tapi, EntryPoint = "phoneConfigDialogW", CharSet = CharSet.Auto)]
internal static extern int phoneConfigDialog(int dwDeviceID, IntPtr hwndOwner, string deviceClass);
[DllImport(_tapi, EntryPoint = "phoneDevSpecific", CharSet = CharSet.Auto)]
internal static extern int phoneDevSpecific(HTPHONE hPhone, IntPtr lpParams, int dwSize);
[DllImport(_tapi, EntryPoint = "phoneGetButtonInfoW", CharSet = CharSet.Auto)]
internal static extern int phoneGetButtonInfo(HTPHONE hPhone, int dwButtonLampID, IntPtr lpButtonInfo);
[DllImport(_tapi, EntryPoint = "phoneGetData", CharSet = CharSet.Auto)]
internal static extern int phoneGetData(HTPHONE hPhone, int dwDataID, IntPtr lpData, int dwSize);
[DllImport(_tapi, EntryPoint = "phoneGetDevCapsW", CharSet = CharSet.Auto)]
internal static extern int phoneGetDevCaps(HTPHONEAPP hPhoneApp, int dwDeviceID, int dwAPIVersion, int dwExtVersion, IntPtr lpPhoneCaps);
[DllImport(_tapi, EntryPoint = "phoneGetDisplay", CharSet = CharSet.Auto)]
internal static extern int phoneGetDisplay(HTPHONE hPhone, IntPtr lpDisplay);
[DllImport(_tapi, EntryPoint = "phoneGetGain", CharSet = CharSet.Auto)]
internal static extern int phoneGetGain(HTPHONE hPhone, int dwHookSwitchDev, ref int lpdwGain);
[DllImport(_tapi, EntryPoint = "phoneGetHookSwitch", CharSet = CharSet.Auto)]
internal static extern int phoneGetGain(HTPHONE hPhone, ref int lpdwHookSwitchDevs);
[DllImport(_tapi, EntryPoint = "phoneGetHookIDW", CharSet = CharSet.Auto)]
internal static extern int phoneGetID(HTPHONE hPhone, IntPtr lpDeviceID, string lpszDeviceClass);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneGetLamp(HTPHONE hPhone, int dwButtonLampID, out int lpdwLampMode);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneGetMessage(HTPHONEAPP hPhoneApp, ref LINEMESSAGE lpMessage, int dwTimeout);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneGetRing(HTPHONE hPhone, ref int lpdwRingMode, ref int lpdwVolume);
[DllImport(_tapi, EntryPoint="phoneGetStatusW", CharSet = CharSet.Auto)]
internal static extern int phoneGetStatus(HTPHONE hPhone, IntPtr lpPhoneStatus);
[DllImport(_tapi, EntryPoint="phoneGetStatusMessages", CharSet = CharSet.Auto)]
internal static extern int phoneGetStatusMessages(HTPHONE hPhone, ref int lpdwPhoneStates, ref int lpdwButtonModes, ref int lpdwButtonStates);
[DllImport(_tapi, EntryPoint="phoneGetVolume", CharSet = CharSet.Auto)]
internal static extern int phoneGetVolume(HTPHONE hPhone, int dwHookSwitchDev, ref int lpdwVolume);
[DllImport(_tapi, EntryPoint = "phoneInitializeExW", CharSet = CharSet.Auto)]
internal static extern int phoneInitializeEx(out IntPtr hPhoneApp, IntPtr hAppHandle, TapiEventCallback CalllBack, string friendlyAppName, out int numDevices, ref int apiVersion, ref PHONEINITIALIZEEXPARAMS phoneExParms);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneNegotiateAPIVersion(HTPHONEAPP hPhoneApp, int dwDeviceID, int dwAPILowVersion, int dwAPIHighVersion, out int lpdwAPIVersion, out PHONEEXTENSIONID lpExtensionID);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneNegotiateExtVersion(HTPHONEAPP hPhoneApp, int dwDeviceID, int dwAPIVersion, int dwExtLowVersion, int dwExtHighVersion, out int dwExtVersion);
[DllImport(_tapi, CharSet = CharSet.Auto)]
internal static extern int phoneOpen(HTPHONEAPP hPhoneApp, int dwDeviceID, out IntPtr hPhone, int dwAPIVersion, int dwExtVersion, IntPtr dwCallbackInstance, int dwPrivileges);
[DllImport(_tapi, EntryPoint = "phoneSetButtonInfoW", CharSet = CharSet.Auto)]
internal static extern int phoneSetButtonInfo(HTPHONE hPhone, int dwButtonLampID, IntPtr lpButtonInfo);
[DllImport(_tapi, EntryPoint = "phoneSetData", CharSet = CharSet.Auto)]
internal static extern int phoneSetData(HTPHONE hPhone, int dwDataID, IntPtr lpData, int dwSize);
[DllImport(_tapi, EntryPoint = "phoneSetDisplay", CharSet = CharSet.Ansi)]
internal static extern int phoneSetDisplay(HTPHONE hPhone, int dwRow, int dwColumn, [MarshalAs(UnmanagedType.LPStr)] string lpsDisplay, int dwSize);
[DllImport(_tapi, EntryPoint = "phoneSetGain", CharSet = CharSet.Auto)]
internal static extern int phoneSetGain(HTPHONE hPhone, int dwHookSwitchDev, int dwGain);
[DllImport(_tapi, EntryPoint = "phoneSetHookSwitch", CharSet = CharSet.Auto)]
internal static extern int phoneSetHookSwitch(HTPHONE hPhone, int dwHookSwitchDev, int dwHookSwitchMode);
[DllImport(_tapi, EntryPoint = "phoneSetLamp", CharSet = CharSet.Auto)]
internal static extern int phoneSetLamp(HTPHONE hPhone, int dwButtonLampID, int dwLampMode);
[DllImport(_tapi, EntryPoint = "phoneSetRing", CharSet = CharSet.Auto)]
internal static extern int phoneSetRing(HTPHONE hPhone, int dwRingMode, int dwVolume);
[DllImport(_tapi, EntryPoint = "phoneSetStatusMessages", CharSet = CharSet.Auto)]
internal static extern int phoneSetStatusMessages(HTPHONE hPhone, int dwPhoneStates, int dwButtonModes, int dwButtonStates);
[DllImport(_tapi, EntryPoint = "phoneSetVolume", CharSet = CharSet.Auto)]
internal static extern int phoneSetVolume(HTPHONE hPhone, int dwHookSwitchDev, int dwVolume);
[DllImport(_tapi, CharSet = CharSet.Auto), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int phoneShutdown(HTPHONEAPP htPhoneApp);
#pragma warning restore IDE1006 // Naming Styles
#endregion
#region Constants
internal const int LINEADDRCAPFLAGS_FWDNUMRINGS = unchecked((int)0x00000001);
internal const int LINEADDRCAPFLAGS_PICKUPGROUPID = unchecked((int)0x00000002);
internal const int LINEADDRCAPFLAGS_SECURE = unchecked((int)0x00000004);
internal const int LINEADDRCAPFLAGS_BLOCKIDDEFAULT = unchecked((int)0x00000008);
internal const int LINEADDRCAPFLAGS_BLOCKIDOVERRIDE = unchecked((int)0x00000010);
internal const int LINEADDRCAPFLAGS_DIALED = unchecked((int)0x00000020);
internal const int LINEADDRCAPFLAGS_ORIGOFFHOOK = unchecked((int)0x00000040);
internal const int LINEADDRCAPFLAGS_DESTOFFHOOK = unchecked((int)0x00000080);
internal const int LINEADDRCAPFLAGS_FWDCONSULT = unchecked((int)0x00000100);
internal const int LINEADDRCAPFLAGS_SETUPCONFNULL = unchecked((int)0x00000200);
internal const int LINEADDRCAPFLAGS_AUTORECONNECT = unchecked((int)0x00000400);
internal const int LINEADDRCAPFLAGS_COMPLETIONID = unchecked((int)0x00000800);
internal const int LINEADDRCAPFLAGS_TRANSFERHELD = unchecked((int)0x00001000);
internal const int LINEADDRCAPFLAGS_TRANSFERMAKE = unchecked((int)0x00002000);
internal const int LINEADDRCAPFLAGS_CONFERENCEHELD = unchecked((int)0x00004000);
internal const int LINEADDRCAPFLAGS_CONFERENCEMAKE = unchecked((int)0x00008000);
internal const int LINEADDRCAPFLAGS_PARTIALDIAL = unchecked((int)0x00010000);
internal const int LINEADDRCAPFLAGS_FWDSTATUSVALID = unchecked((int)0x00020000);
internal const int LINEADDRCAPFLAGS_FWDINTEXTADDR = unchecked((int)0x00040000);
internal const int LINEADDRCAPFLAGS_FWDBUSYNAADDR = unchecked((int)0x00080000);
internal const int LINEADDRCAPFLAGS_ACCEPTTOALERT = unchecked((int)0x00100000);
internal const int LINEADDRCAPFLAGS_CONFDROP = unchecked((int)0x00200000);
internal const int LINEADDRCAPFLAGS_PICKUPCALLWAIT = unchecked((int)0x00400000);
internal const int LINEADDRCAPFLAGS_PREDICTIVEDIALER = unchecked((int)0x00800000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_QUEUE = unchecked((int)0x01000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_ROUTEPOINT = unchecked((int)0x02000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_HOLDMAKESNEW = unchecked((int)0x04000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_NOINTERNALCALLS = unchecked((int)0x08000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_NOEXTERNALCALLS = unchecked((int)0x10000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_SETCALLINGID = unchecked((int)0x20000000); // TAPI v2.0
internal const int LINEADDRCAPFLAGS_ACDGROUP = unchecked((int)0x40000000); // TAPI v2.2
internal const int LINEADDRCAPFLAGS_NOPSTNADDRESSTRANSLATION = unchecked((int)0x80000000); // TAPI v3.0
internal const int LINEADDRESSMODE_ADDRESSID = unchecked((int)0x00000001);
internal const int LINEADDRESSMODE_DIALABLEADDR = unchecked((int)0x00000002);
internal const int LINEADDRESSSHARING_PRIVATE = unchecked((int)0x00000001);
internal const int LINEADDRESSSHARING_BRIDGEDEXCL = unchecked((int)0x00000002);
internal const int LINEADDRESSSHARING_BRIDGEDNEW = unchecked((int)0x00000004);
internal const int LINEADDRESSSHARING_BRIDGEDSHARED = unchecked((int)0x00000008);
internal const int LINEADDRESSSHARING_MONITORED = unchecked((int)0x00000010);
internal const int LINEADDRESSSTATE_OTHER = unchecked((int)0x00000001);
internal const int LINEADDRESSSTATE_DEVSPECIFIC = unchecked((int)0x00000002);
internal const int LINEADDRESSSTATE_INUSEZERO = unchecked((int)0x00000004);
internal const int LINEADDRESSSTATE_INUSEONE = unchecked((int)0x00000008);
internal const int LINEADDRESSSTATE_INUSEMANY = unchecked((int)0x00000010);
internal const int LINEADDRESSSTATE_NUMCALLS = unchecked((int)0x00000020);
internal const int LINEADDRESSSTATE_FORWARD = unchecked((int)0x00000040);
internal const int LINEADDRESSSTATE_TERMINALS = unchecked((int)0x00000080);
internal const int LINEADDRESSSTATE_CAPSCHANGE = unchecked((int)0x00000100); // TAPI v1.4
internal const int LINEADDRESSTYPE_PHONENUMBER = unchecked((int)0x00000001);
internal const int LINEADDRESSTYPE_SDP = unchecked((int)0x00000002);
internal const int LINEADDRESSTYPE_EMAILNAME = unchecked((int)0x00000004);
internal const int LINEADDRESSTYPE_DOMAINNAME = unchecked((int)0x00000008);
internal const int LINEADDRESSTYPE_IPADDRESS = unchecked((int)0x00000010);
internal const int LINEADDRFEATURE_FORWARD = unchecked((int)0x00000001);
internal const int LINEADDRFEATURE_MAKECALL = unchecked((int)0x00000002);
internal const int LINEADDRFEATURE_PICKUP = unchecked((int)0x00000004);
internal const int LINEADDRFEATURE_SETMEDIACONTROL = unchecked((int)0x00000008);
internal const int LINEADDRFEATURE_SETTERMINAL = unchecked((int)0x00000010);
internal const int LINEADDRFEATURE_SETUPCONF = unchecked((int)0x00000020);
internal const int LINEADDRFEATURE_UNCOMPLETECALL = unchecked((int)0x00000040);
internal const int LINEADDRFEATURE_UNPARK = unchecked((int)0x00000080);
internal const int LINEADDRFEATURE_PICKUPHELD = unchecked((int)0x00000100); // TAPI v2.0
internal const int LINEADDRFEATURE_PICKUPGROUP = unchecked((int)0x00000200); // TAPI v2.0
internal const int LINEADDRFEATURE_PICKUPDIRECT = unchecked((int)0x00000400); // TAPI v2.0
internal const int LINEADDRFEATURE_PICKUPWAITING = unchecked((int)0x00000800); // TAPI v2.0
internal const int LINEADDRFEATURE_FORWARDFWD = unchecked((int)0x00001000); // TAPI v2.0
internal const int LINEADDRFEATURE_FORWARDDND = unchecked((int)0x00002000); // TAPI v2.0
internal const int LINEANSWERMODE_NONE = unchecked((int)0x00000001);
internal const int LINEANSWERMODE_DROP = unchecked((int)0x00000002);
internal const int LINEANSWERMODE_HOLD = unchecked((int)0x00000004);
internal const int LINEBEARERMODE_VOICE = unchecked((int)0x00000001);
internal const int LINEBEARERMODE_SPEECH = unchecked((int)0x00000002);
internal const int LINEBEARERMODE_MULTIUSE = unchecked((int)0x00000004);
internal const int LINEBEARERMODE_DATA = unchecked((int)0x00000008);
internal const int LINEBEARERMODE_ALTSPEECHDATA = unchecked((int)0x00000010);
internal const int LINEBEARERMODE_NONCALLSIGNALING = unchecked((int)0x00000020);
internal const int LINEBEARERMODE_PASSTHROUGH = unchecked((int)0x00000040); // TAPI v1.4
internal const int LINEBEARERMODE_RESTRICTEDDATA = unchecked((int)0x00000080); // TAPI v2.0
internal const int LINEBUSYMODE_STATION = unchecked((int)0x00000001);
internal const int LINEBUSYMODE_TRUNK = unchecked((int)0x00000002);
internal const int LINEBUSYMODE_UNKNOWN = unchecked((int)0x00000004);
internal const int LINEBUSYMODE_UNAVAIL = unchecked((int)0x00000008);
internal const int LINECALLCOMPLCOND_BUSY = unchecked((int)0x00000001);
internal const int LINECALLCOMPLCOND_NOANSWER = unchecked((int)0x00000002);
internal const int LINECALLFEATURE_ACCEPT = unchecked((int)0x00000001);
internal const int LINECALLFEATURE_ADDTOCONF = unchecked((int)0x00000002);
internal const int LINECALLFEATURE_ANSWER = unchecked((int)0x00000004);
internal const int LINECALLFEATURE_BLINDTRANSFER = unchecked((int)0x00000008);
internal const int LINECALLFEATURE_COMPLETECALL = unchecked((int)0x00000010);
internal const int LINECALLFEATURE_COMPLETETRANSF = unchecked((int)0x00000020);
internal const int LINECALLFEATURE_DIAL = unchecked((int)0x00000040);
internal const int LINECALLFEATURE_DROP = unchecked((int)0x00000080);
internal const int LINECALLFEATURE_GATHERDIGITS = unchecked((int)0x00000100);
internal const int LINECALLFEATURE_GENERATEDIGITS = unchecked((int)0x00000200);
internal const int LINECALLFEATURE_GENERATETONE = unchecked((int)0x00000400);
internal const int LINECALLFEATURE_HOLD = unchecked((int)0x00000800);
internal const int LINECALLFEATURE_MONITORDIGITS = unchecked((int)0x00001000);
internal const int LINECALLFEATURE_MONITORMEDIA = unchecked((int)0x00002000);
internal const int LINECALLFEATURE_MONITORTONES = unchecked((int)0x00004000);
internal const int LINECALLFEATURE_PARK = unchecked((int)0x00008000);
internal const int LINECALLFEATURE_PREPAREADDCONF = unchecked((int)0x00010000);
internal const int LINECALLFEATURE_REDIRECT = unchecked((int)0x00020000);
internal const int LINECALLFEATURE_REMOVEFROMCONF = unchecked((int)0x00040000);
internal const int LINECALLFEATURE_SECURECALL = unchecked((int)0x00080000);
internal const int LINECALLFEATURE_SENDUSERUSER = unchecked((int)0x00100000);
internal const int LINECALLFEATURE_SETCALLPARAMS = unchecked((int)0x00200000);
internal const int LINECALLFEATURE_SETMEDIACONTROL = unchecked((int)0x00400000);
internal const int LINECALLFEATURE_SETTERMINAL = unchecked((int)0x00800000);
internal const int LINECALLFEATURE_SETUPCONF = unchecked((int)0x01000000);
internal const int LINECALLFEATURE_SETUPTRANSFER = unchecked((int)0x02000000);
internal const int LINECALLFEATURE_SWAPHOLD = unchecked((int)0x04000000);
internal const int LINECALLFEATURE_UNHOLD = unchecked((int)0x08000000);
internal const int LINECALLFEATURE_RELEASEUSERUSERINFO = unchecked((int)0x10000000); // TAPI v1.4
internal const int LINECALLFEATURE_SETTREATMENT = unchecked((int)0x20000000); // TAPI v2.0
internal const int LINECALLFEATURE_SETQOS = unchecked((int)0x40000000); // TAPI v2.0
internal const int LINECALLFEATURE_SETCALLDATA = unchecked((int)0x80000000); // TAPI v2.0
internal const int LINECALLFEATURE2_NOHOLDCONFERENCE = unchecked((int)0x00000001); // TAPI v2.0
internal const int LINECALLFEATURE2_ONESTEPTRANSFER = unchecked((int)0x00000002); // TAPI v2.0
internal const int LINECALLFEATURE2_COMPLCAMPON = unchecked((int)0x00000004); // TAPI v2.0
internal const int LINECALLFEATURE2_COMPLCALLBACK = unchecked((int)0x00000008); // TAPI v2.0
internal const int LINECALLFEATURE2_COMPLINTRUDE = unchecked((int)0x00000010); // TAPI v2.0
internal const int LINECALLFEATURE2_COMPLMESSAGE = unchecked((int)0x00000020); // TAPI v2.0
internal const int LINECALLFEATURE2_TRANSFERNORM = unchecked((int)0x00000040); // TAPI v2.0
internal const int LINECALLFEATURE2_TRANSFERCONF = unchecked((int)0x00000080); // TAPI v2.0
internal const int LINECALLFEATURE2_PARKDIRECT = unchecked((int)0x00000100); // TAPI v2.0
internal const int LINECALLFEATURE2_PARKNONDIRECT = unchecked((int)0x00000200); // TAPI v2.0
internal const int LINECALLINFOSTATE_OTHER = unchecked((int)0x00000001);
internal const int LINECALLINFOSTATE_DEVSPECIFIC = unchecked((int)0x00000002);
internal const int LINECALLINFOSTATE_BEARERMODE = unchecked((int)0x00000004);
internal const int LINECALLINFOSTATE_RATE = unchecked((int)0x00000008);
internal const int LINECALLINFOSTATE_MEDIAMODE = unchecked((int)0x00000010);
internal const int LINECALLINFOSTATE_APPSPECIFIC = unchecked((int)0x00000020);
internal const int LINECALLINFOSTATE_CALLID = unchecked((int)0x00000040);
internal const int LINECALLINFOSTATE_RELATEDCALLID = unchecked((int)0x00000080);
internal const int LINECALLINFOSTATE_ORIGIN = unchecked((int)0x00000100);
internal const int LINECALLINFOSTATE_REASON = unchecked((int)0x00000200);
internal const int LINECALLINFOSTATE_COMPLETIONID = unchecked((int)0x00000400);
internal const int LINECALLINFOSTATE_NUMOWNERINCR = unchecked((int)0x00000800);
internal const int LINECALLINFOSTATE_NUMOWNERDECR = unchecked((int)0x00001000);
internal const int LINECALLINFOSTATE_NUMMONITORS = unchecked((int)0x00002000);
internal const int LINECALLINFOSTATE_TRUNK = unchecked((int)0x00004000);
internal const int LINECALLINFOSTATE_CALLERID = unchecked((int)0x00008000);
internal const int LINECALLINFOSTATE_CALLEDID = unchecked((int)0x00010000);
internal const int LINECALLINFOSTATE_CONNECTEDID = unchecked((int)0x00020000);
internal const int LINECALLINFOSTATE_REDIRECTIONID = unchecked((int)0x00040000);
internal const int LINECALLINFOSTATE_REDIRECTINGID = unchecked((int)0x00080000);
internal const int LINECALLINFOSTATE_DISPLAY = unchecked((int)0x00100000);
internal const int LINECALLINFOSTATE_USERUSERINFO = unchecked((int)0x00200000);
internal const int LINECALLINFOSTATE_HIGHLEVELCOMP = unchecked((int)0x00400000);
internal const int LINECALLINFOSTATE_LOWLEVELCOMP = unchecked((int)0x00800000);
internal const int LINECALLINFOSTATE_CHARGINGINFO = unchecked((int)0x01000000);
internal const int LINECALLINFOSTATE_TERMINAL = unchecked((int)0x02000000);
internal const int LINECALLINFOSTATE_DIALPARAMS = unchecked((int)0x04000000);
internal const int LINECALLINFOSTATE_MONITORMODES = unchecked((int)0x08000000);
internal const int LINECALLINFOSTATE_TREATMENT = unchecked((int)0x10000000); // TAPI v2.0
internal const int LINECALLINFOSTATE_QOS = unchecked((int)0x20000000); // TAPI v2.0
internal const int LINECALLINFOSTATE_CALLDATA = unchecked((int)0x40000000); // TAPI v2.0
internal const int LINECALLORIGIN_OUTBOUND = unchecked((int)0x00000001);
internal const int LINECALLORIGIN_INTERNAL = unchecked((int)0x00000002);
internal const int LINECALLORIGIN_EXTERNAL = unchecked((int)0x00000004);
internal const int LINECALLORIGIN_UNKNOWN = unchecked((int)0x00000010);
internal const int LINECALLORIGIN_UNAVAIL = unchecked((int)0x00000020);
internal const int LINECALLORIGIN_CONFERENCE = unchecked((int)0x00000040);
internal const int LINECALLORIGIN_INBOUND = unchecked((int)0x00000080); // TAPI v1.4
internal const int LINECALLPARAMFLAGS_SECURE = unchecked((int)0x00000001);
internal const int LINECALLPARAMFLAGS_IDLE = unchecked((int)0x00000002);
internal const int LINECALLPARAMFLAGS_BLOCKID = unchecked((int)0x00000004);
internal const int LINECALLPARAMFLAGS_ORIGOFFHOOK = unchecked((int)0x00000008);
internal const int LINECALLPARAMFLAGS_DESTOFFHOOK = unchecked((int)0x00000010);
internal const int LINECALLPARAMFLAGS_NOHOLDCONFERENCE = unchecked((int)0x00000020); // TAPI v2.0
internal const int LINECALLPARAMFLAGS_PREDICTIVEDIAL = unchecked((int)0x00000040); // TAPI v2.0
internal const int LINECALLPARAMFLAGS_ONESTEPTRANSFER = unchecked((int)0x00000080); // TAPI v2.0
internal const int LINECALLPARTYID_BLOCKED = unchecked((int)0x00000001);
internal const int LINECALLPARTYID_OUTOFAREA = unchecked((int)0x00000002);
internal const int LINECALLPARTYID_NAME = unchecked((int)0x00000004);
internal const int LINECALLPARTYID_ADDRESS = unchecked((int)0x00000008);
internal const int LINECALLPARTYID_PARTIAL = unchecked((int)0x00000010);
internal const int LINECALLPARTYID_UNKNOWN = unchecked((int)0x00000020);
internal const int LINECALLPARTYID_UNAVAIL = unchecked((int)0x00000040);
internal const int LINECALLPRIVILEGE_NONE = unchecked((int)0x00000001);
internal const int LINECALLPRIVILEGE_MONITOR = unchecked((int)0x00000002);
internal const int LINECALLPRIVILEGE_OWNER = unchecked((int)0x00000004);
internal const int LINECALLREASON_DIRECT = unchecked((int)0x00000001);
internal const int LINECALLREASON_FWDBUSY = unchecked((int)0x00000002);
internal const int LINECALLREASON_FWDNOANSWER = unchecked((int)0x00000004);
internal const int LINECALLREASON_FWDUNCOND = unchecked((int)0x00000008);
internal const int LINECALLREASON_PICKUP = unchecked((int)0x00000010);
internal const int LINECALLREASON_UNPARK = unchecked((int)0x00000020);
internal const int LINECALLREASON_REDIRECT = unchecked((int)0x00000040);
internal const int LINECALLREASON_CALLCOMPLETION = unchecked((int)0x00000080);
internal const int LINECALLREASON_TRANSFER = unchecked((int)0x00000100);
internal const int LINECALLREASON_REMINDER = unchecked((int)0x00000200);
internal const int LINECALLREASON_UNKNOWN = unchecked((int)0x00000400);
internal const int LINECALLREASON_UNAVAIL = unchecked((int)0x00000800);
internal const int LINECALLREASON_INTRUDE = unchecked((int)0x00001000); // TAPI v1.4
internal const int LINECALLREASON_PARKED = unchecked((int)0x00002000); // TAPI v1.4
internal const int LINECALLREASON_CAMPEDON = unchecked((int)0x00004000); // TAPI v2.0
internal const int LINECALLREASON_ROUTEREQUEST = unchecked((int)0x00008000); // TAPI v2.0
internal const int LINECALLSELECT_LINE = unchecked((int)0x00000001);
internal const int LINECALLSELECT_ADDRESS = unchecked((int)0x00000002);
internal const int LINECALLSELECT_CALL = unchecked((int)0x00000004);
internal const int LINECALLSELECT_DEVICEID = unchecked((int)0x00000008); // TAPI v2.1
internal const int LINECALLSELECT_CALLID = unchecked((int)0x00000010); // TAPI v3.0
internal const int LINECALLSTATE_IDLE = unchecked((int)0x00000001);
internal const int LINECALLSTATE_OFFERING = unchecked((int)0x00000002);
internal const int LINECALLSTATE_ACCEPTED = unchecked((int)0x00000004);
internal const int LINECALLSTATE_DIALTONE = unchecked((int)0x00000008);
internal const int LINECALLSTATE_DIALING = unchecked((int)0x00000010);
internal const int LINECALLSTATE_RINGBACK = unchecked((int)0x00000020);
internal const int LINECALLSTATE_BUSY = unchecked((int)0x00000040);
internal const int LINECALLSTATE_SPECIALINFO = unchecked((int)0x00000080);
internal const int LINECALLSTATE_CONNECTED = unchecked((int)0x00000100);
internal const int LINECALLSTATE_PROCEEDING = unchecked((int)0x00000200);
internal const int LINECALLSTATE_ONHOLD = unchecked((int)0x00000400);
internal const int LINECALLSTATE_CONFERENCED = unchecked((int)0x00000800);
internal const int LINECALLSTATE_ONHOLDPENDCONF = unchecked((int)0x00001000);
internal const int LINECALLSTATE_ONHOLDPENDTRANSFER = unchecked((int)0x00002000);
internal const int LINECALLSTATE_DISCONNECTED = unchecked((int)0x00004000);
internal const int LINECALLSTATE_UNKNOWN = unchecked((int)0x00008000);
internal const int LINECALLTREATMENT_SILENCE = unchecked((int)0x00000001); // TAPI v2.0
internal const int LINECALLTREATMENT_RINGBACK = unchecked((int)0x00000002); // TAPI v2.0
internal const int LINECALLTREATMENT_BUSY = unchecked((int)0x00000003); // TAPI v2.0
internal const int LINECALLTREATMENT_MUSIC = unchecked((int)0x00000004); // TAPI v2.0
internal const int LINECARDENTRY_PREDEFINED = unchecked((int)0x00000001); // TAPI v1.4
internal const int LINECARDENTRY_HIDDEN = unchecked((int)0x00000002); // TAPI v1.4
internal const int LINECARDOPTION_PREDEFINED = unchecked((int)0x00000001); // TAPI v1.4
internal const int LINECARDOPTION_HIDDEN = unchecked((int)0x00000002); // TAPI v1.4
internal const int LINECALLCOMPLMODE_CAMPON = unchecked((int)0x00000001);
internal const int LINECALLCOMPLMODE_CALLBACK = unchecked((int)0x00000002);
internal const int LINECALLCOMPLMODE_INTRUDE = unchecked((int)0x00000004);
internal const int LINECALLCOMPLMODE_MESSAGE = unchecked((int)0x00000008);
internal const int LINECONNECTEDMODE_ACTIVE = unchecked((int)0x00000001); // TAPI v1.4
internal const int LINECONNECTEDMODE_INACTIVE = unchecked((int)0x00000002); // TAPI v1.4
internal const int LINECONNECTEDMODE_ACTIVEHELD = unchecked((int)0x00000004); // TAPI v2.0
internal const int LINECONNECTEDMODE_INACTIVEHELD = unchecked((int)0x00000008); // TAPI v2.0
internal const int LINECONNECTEDMODE_CONFIRMED = unchecked((int)0x00000010); // TAPI v2.0
internal const int LINEDEVCAPFLAGS_CROSSADDRCONF = unchecked((int)0x00000001);
internal const int LINEDEVCAPFLAGS_HIGHLEVCOMP = unchecked((int)0x00000002);
internal const int LINEDEVCAPFLAGS_LOWLEVCOMP = unchecked((int)0x00000004);
internal const int LINEDEVCAPFLAGS_MEDIACONTROL = unchecked((int)0x00000008);
internal const int LINEDEVCAPFLAGS_MULTIPLEADDR = unchecked((int)0x00000010);
internal const int LINEDEVCAPFLAGS_CLOSEDROP = unchecked((int)0x00000020);
internal const int LINEDEVCAPFLAGS_DIALBILLING = unchecked((int)0x00000040);
internal const int LINEDEVCAPFLAGS_DIALQUIET = unchecked((int)0x00000080);
internal const int LINEDEVCAPFLAGS_DIALDIALTONE = unchecked((int)0x00000100);
internal const int LINEDEVCAPFLAGS_MSP = unchecked((int)0x00000200); // TAPI v3.0
internal const int LINEDEVCAPFLAGS_CALLHUB = unchecked((int)0x00000400); // TAPI v3.0
internal const int LINEDEVCAPFLAGS_CALLHUBTRACKING = unchecked((int)0x00000800); // TAPI v3.0
internal const int LINEDEVCAPFLAGS_PRIVATEOBJECTS = unchecked((int)0x00001000); // TAPI v3.0
internal const int LINEDEVCAPFLAGS_LOCAL = unchecked((int)0x00002000);
internal const int LINEDEVSTATE_OTHER = unchecked((int)0x00000001);
internal const int LINEDEVSTATE_RINGING = unchecked((int)0x00000002);
internal const int LINEDEVSTATE_CONNECTED = unchecked((int)0x00000004);
internal const int LINEDEVSTATE_DISCONNECTED = unchecked((int)0x00000008);
internal const int LINEDEVSTATE_MSGWAITON = unchecked((int)0x00000010);
internal const int LINEDEVSTATE_MSGWAITOFF = unchecked((int)0x00000020);
internal const int LINEDEVSTATE_INSERVICE = unchecked((int)0x00000040);
internal const int LINEDEVSTATE_OUTOFSERVICE = unchecked((int)0x00000080);
internal const int LINEDEVSTATE_MAINTENANCE = unchecked((int)0x00000100);
internal const int LINEDEVSTATE_OPEN = unchecked((int)0x00000200);
internal const int LINEDEVSTATE_CLOSE = unchecked((int)0x00000400);
internal const int LINEDEVSTATE_NUMCALLS = unchecked((int)0x00000800);
internal const int LINEDEVSTATE_NUMCOMPLETIONS = unchecked((int)0x00001000);
internal const int LINEDEVSTATE_TERMINALS = unchecked((int)0x00002000);
internal const int LINEDEVSTATE_ROAMMODE = unchecked((int)0x00004000);
internal const int LINEDEVSTATE_BATTERY = unchecked((int)0x00008000);
internal const int LINEDEVSTATE_SIGNAL = unchecked((int)0x00010000);
internal const int LINEDEVSTATE_DEVSPECIFIC = unchecked((int)0x00020000);
internal const int LINEDEVSTATE_REINIT = unchecked((int)0x00040000);
internal const int LINEDEVSTATE_LOCK = unchecked((int)0x00080000);
internal const int LINEDEVSTATE_CAPSCHANGE = unchecked((int)0x00100000); // TAPI v1.4
internal const int LINEDEVSTATE_CONFIGCHANGE = unchecked((int)0x00200000); // TAPI v1.4
internal const int LINEDEVSTATE_TRANSLATECHANGE = unchecked((int)0x00400000); // TAPI v1.4
internal const int LINEDEVSTATE_COMPLCANCEL = unchecked((int)0x00800000); // TAPI v1.4
internal const int LINEDEVSTATE_REMOVED = unchecked((int)0x01000000); // TAPI v1.4
internal const int LINEDEVSTATUSFLAGS_CONNECTED = unchecked((int)0x00000001);
internal const int LINEDEVSTATUSFLAGS_MSGWAIT = unchecked((int)0x00000002);
internal const int LINEDEVSTATUSFLAGS_INSERVICE = unchecked((int)0x00000004);
internal const int LINEDEVSTATUSFLAGS_LOCKED = unchecked((int)0x00000008);
internal const int LINEDIALTONEMODE_NORMAL = unchecked((int)0x00000001);
internal const int LINEDIALTONEMODE_SPECIAL = unchecked((int)0x00000002);
internal const int LINEDIALTONEMODE_INTERNAL = unchecked((int)0x00000004);
internal const int LINEDIALTONEMODE_EXTERNAL = unchecked((int)0x00000008);
internal const int LINEDIALTONEMODE_UNKNOWN = unchecked((int)0x00000010);
internal const int LINEDIALTONEMODE_UNAVAIL = unchecked((int)0x00000020);
internal const int LINEDIGITMODE_PULSE = unchecked((int)0x00000001);
internal const int LINEDIGITMODE_DTMF = unchecked((int)0x00000002);
internal const int LINEDIGITMODE_DTMFEND = unchecked((int)0x00000004);
internal const int LINEDISCONNECTMODE_NORMAL = unchecked((int)0x00000001);
internal const int LINEDISCONNECTMODE_UNKNOWN = unchecked((int)0x00000002);
internal const int LINEDISCONNECTMODE_REJECT = unchecked((int)0x00000004);
internal const int LINEDISCONNECTMODE_PICKUP = unchecked((int)0x00000008);
internal const int LINEDISCONNECTMODE_FORWARDED = unchecked((int)0x00000010);
internal const int LINEDISCONNECTMODE_BUSY = unchecked((int)0x00000020);
internal const int LINEDISCONNECTMODE_NOANSWER = unchecked((int)0x00000040);
internal const int LINEDISCONNECTMODE_BADADDRESS = unchecked((int)0x00000080);
internal const int LINEDISCONNECTMODE_UNREACHABLE = unchecked((int)0x00000100);
internal const int LINEDISCONNECTMODE_CONGESTION = unchecked((int)0x00000200);
internal const int LINEDISCONNECTMODE_INCOMPATIBLE = unchecked((int)0x00000400);
internal const int LINEDISCONNECTMODE_UNAVAIL = unchecked((int)0x00000800);
internal const int LINEDISCONNECTMODE_NODIALTONE = unchecked((int)0x00001000); // TAPI v1.4
internal const int LINEDISCONNECTMODE_NUMBERCHANGED = unchecked((int)0x00002000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_OUTOFORDER = unchecked((int)0x00004000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_TEMPFAILURE = unchecked((int)0x00008000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_QOSUNAVAIL = unchecked((int)0x00010000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_BLOCKED = unchecked((int)0x00020000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_DONOTDISTURB = unchecked((int)0x00040000); // TAPI v2.0
internal const int LINEDISCONNECTMODE_CANCELLED = unchecked((int)0x00080000); // TAPI v2.0
internal const int LINEERR_OK = unchecked((int)0x00000000);
internal const int LINEERR_ALLOCATED = unchecked((int)0x80000001);
internal const int LINEERR_BADDEVICEID = unchecked((int)0x80000002);
internal const int LINEERR_BEARERMODEUNAVAIL = unchecked((int)0x80000003);
internal const int LINEERR_CALLUNAVAIL = unchecked((int)0x80000005);
internal const int LINEERR_COMPLETIONOVERRUN = unchecked((int)0x80000006);
internal const int LINEERR_CONFERENCEFULL = unchecked((int)0x80000007);
internal const int LINEERR_DIALBILLING = unchecked((int)0x80000008);
internal const int LINEERR_DIALDIALTONE = unchecked((int)0x80000009);
internal const int LINEERR_DIALPROMPT = unchecked((int)0x8000000A);
internal const int LINEERR_DIALQUIET = unchecked((int)0x8000000B);
internal const int LINEERR_INCOMPATIBLEAPIVERSION = unchecked((int)0x8000000C);
internal const int LINEERR_INCOMPATIBLEEXTVERSION = unchecked((int)0x8000000D);
internal const int LINEERR_INIFILECORRUPT = unchecked((int)0x8000000E);
internal const int LINEERR_INUSE = unchecked((int)0x8000000F);
internal const int LINEERR_INVALADDRESS = unchecked((int)0x80000010);
internal const int LINEERR_INVALADDRESSID = unchecked((int)0x80000011);
internal const int LINEERR_INVALADDRESSMODE = unchecked((int)0x80000012);
internal const int LINEERR_INVALADDRESSSTATE = unchecked((int)0x80000013);
internal const int LINEERR_INVALAPPHANDLE = unchecked((int)0x80000014);
internal const int LINEERR_INVALAPPNAME = unchecked((int)0x80000015);
internal const int LINEERR_INVALBEARERMODE = unchecked((int)0x80000016);
internal const int LINEERR_INVALCALLCOMPLMODE = unchecked((int)0x80000017);
internal const int LINEERR_INVALCALLHANDLE = unchecked((int)0x80000018);
internal const int LINEERR_INVALCALLPARAMS = unchecked((int)0x80000019);
internal const int LINEERR_INVALCALLPRIVILEGE = unchecked((int)0x8000001A);
internal const int LINEERR_INVALCALLSELECT = unchecked((int)0x8000001B);
internal const int LINEERR_INVALCALLSTATE = unchecked((int)0x8000001C);
internal const int LINEERR_INVALCALLSTATELIST = unchecked((int)0x8000001D);
internal const int LINEERR_INVALCARD = unchecked((int)0x8000001E);
internal const int LINEERR_INVALCOMPLETIONID = unchecked((int)0x8000001F);
internal const int LINEERR_INVALCONFCALLHANDLE = unchecked((int)0x80000020);
internal const int LINEERR_INVALCONSULTCALLHANDLE = unchecked((int)0x80000021);
internal const int LINEERR_INVALCOUNTRYCODE = unchecked((int)0x80000022);
internal const int LINEERR_INVALDEVICECLASS = unchecked((int)0x80000023);
internal const int LINEERR_INVALDEVICEHANDLE = unchecked((int)0x80000024);
internal const int LINEERR_INVALDIALPARAMS = unchecked((int)0x80000025);
internal const int LINEERR_INVALDIGITLIST = unchecked((int)0x80000026);
internal const int LINEERR_INVALDIGITMODE = unchecked((int)0x80000027);
internal const int LINEERR_INVALDIGITS = unchecked((int)0x80000028);
internal const int LINEERR_INVALEXTVERSION = unchecked((int)0x80000029);
internal const int LINEERR_INVALGROUPID = unchecked((int)0x8000002A);
internal const int LINEERR_INVALLINEHANDLE = unchecked((int)0x8000002B);
internal const int LINEERR_INVALLINESTATE = unchecked((int)0x8000002C);
internal const int LINEERR_INVALLOCATION = unchecked((int)0x8000002D);
internal const int LINEERR_INVALMEDIALIST = unchecked((int)0x8000002E);
internal const int LINEERR_INVALMEDIAMODE = unchecked((int)0x8000002F);
internal const int LINEERR_INVALMESSAGEID = unchecked((int)0x80000030);
internal const int LINEERR_INVALPARAM = unchecked((int)0x80000032);
internal const int LINEERR_INVALPARKID = unchecked((int)0x80000033);
internal const int LINEERR_INVALPARKMODE = unchecked((int)0x80000034);
internal const int LINEERR_INVALPOINTER = unchecked((int)0x80000035);
internal const int LINEERR_INVALPRIVSELECT = unchecked((int)0x80000036);
internal const int LINEERR_INVALRATE = unchecked((int)0x80000037);
internal const int LINEERR_INVALREQUESTMODE = unchecked((int)0x80000038);
internal const int LINEERR_INVALTERMINALID = unchecked((int)0x80000039);
internal const int LINEERR_INVALTERMINALMODE = unchecked((int)0x8000003A);
internal const int LINEERR_INVALTIMEOUT = unchecked((int)0x8000003B);
internal const int LINEERR_INVALTONE = unchecked((int)0x8000003C);
internal const int LINEERR_INVALTONELIST = unchecked((int)0x8000003D);
internal const int LINEERR_INVALTONEMODE = unchecked((int)0x8000003E);
internal const int LINEERR_INVALTRANSFERMODE = unchecked((int)0x8000003F);
internal const int LINEERR_LINEMAPPERFAILED = unchecked((int)0x80000040);
internal const int LINEERR_NOCONFERENCE = unchecked((int)0x80000041);
internal const int LINEERR_NODEVICE = unchecked((int)0x80000042);
internal const int LINEERR_NODRIVER = unchecked((int)0x80000043);
internal const int LINEERR_NOMEM = unchecked((int)0x80000044);
internal const int LINEERR_NOREQUEST = unchecked((int)0x80000045);
internal const int LINEERR_NOTOWNER = unchecked((int)0x80000046);
internal const int LINEERR_NOTREGISTERED = unchecked((int)0x80000047);
internal const int LINEERR_OPERATIONFAILED = unchecked((int)0x80000048);
internal const int LINEERR_OPERATIONUNAVAIL = unchecked((int)0x80000049);
internal const int LINEERR_RATEUNAVAIL = unchecked((int)0x8000004A);
internal const int LINEERR_RESOURCEUNAVAIL = unchecked((int)0x8000004B);
internal const int LINEERR_REQUESTOVERRUN = unchecked((int)0x8000004C);
internal const int LINEERR_STRUCTURETOOSMALL = unchecked((int)0x8000004D);
internal const int LINEERR_TARGETNOTFOUND = unchecked((int)0x8000004E);
internal const int LINEERR_TARGETSELF = unchecked((int)0x8000004F);
internal const int LINEERR_UNINITIALIZED = unchecked((int)0x80000050);
internal const int LINEERR_USERUSERINFOTOOBIG = unchecked((int)0x80000051);
internal const int LINEERR_REINIT = unchecked((int)0x80000052);
internal const int LINEERR_ADDRESSBLOCKED = unchecked((int)0x80000053);
internal const int LINEERR_BILLINGREJECTED = unchecked((int)0x80000054);
internal const int LINEERR_INVALFEATURE = unchecked((int)0x80000055);
internal const int LINEERR_NOMULTIPLEINSTANCE = unchecked((int)0x80000056);
internal const int LINEERR_INVALAGENTID = unchecked((int)0x80000057);
internal const int LINEERR_INVALAGENTGROUP = unchecked((int)0x80000058);
internal const int LINEERR_INVALPASSWORD = unchecked((int)0x80000059);
internal const int LINEERR_INVALAGENTSTATE = unchecked((int)0x8000005A);
internal const int LINEERR_INVALAGENTACTIVITY = unchecked((int)0x8000005B);
internal const int LINEERR_DIALVOICEDETECT = unchecked((int)0x8000005C);
internal const int PHONEERR_OK = 0;
internal const int PHONEERR_ALLOCATED = unchecked((int)0x90000001);
internal const int PHONEERR_BADDEVICEID = unchecked((int)0x90000002);
internal const int PHONEERR_INCOMPATIBLEAPIVERSION = unchecked((int)0x90000003);
internal const int PHONEERR_INCOMPATIBLEEXTVERSION = unchecked((int)0x90000004);
internal const int PHONEERR_INIFILECORRUPT = unchecked((int)0x90000005);
internal const int PHONEERR_INUSE = unchecked((int)0x90000006);
internal const int PHONEERR_INVALAPPHANDLE = unchecked((int)0x90000007);
internal const int PHONEERR_INVALAPPNAME = unchecked((int)0x90000008);
internal const int PHONEERR_INVALBUTTONLAMPID = unchecked((int)0x90000009);
internal const int PHONEERR_INVALBUTTONMODE = unchecked((int)0x9000000A);
internal const int PHONEERR_INVALBUTTONSTATE = unchecked((int)0x9000000B);
internal const int PHONEERR_INVALDATAID = unchecked((int)0x9000000C);
internal const int PHONEERR_INVALDEVICECLASS = unchecked((int)0x9000000D);
internal const int PHONEERR_INVALEXTVERSION = unchecked((int)0x9000000E);
internal const int PHONEERR_INVALHOOKSWITCHDEV = unchecked((int)0x9000000F);
internal const int PHONEERR_INVALHOOKSWITCHMODE = unchecked((int)0x90000010);
internal const int PHONEERR_INVALLAMPMODE = unchecked((int)0x90000011);
internal const int PHONEERR_INVALPARAM = unchecked((int)0x90000012);
internal const int PHONEERR_INVALPHONEHANDLE = unchecked((int)0x90000013);
internal const int PHONEERR_INVALPHONESTATE = unchecked((int)0x90000014);
internal const int PHONEERR_INVALPOINTER = unchecked((int)0x90000015);
internal const int PHONEERR_INVALPRIVILEGE = unchecked((int)0x90000016);
internal const int PHONEERR_INVALRINGMODE = unchecked((int)0x90000017);
internal const int PHONEERR_NODEVICE = unchecked((int)0x90000018);
internal const int PHONEERR_NODRIVER = unchecked((int)0x90000019);
internal const int PHONEERR_NOMEM = unchecked((int)0x9000001A);
internal const int PHONEERR_NOTOWNER = unchecked((int)0x9000001B);
internal const int PHONEERR_OPERATIONFAILED = unchecked((int)0x9000001C);
internal const int PHONEERR_OPERATIONUNAVAIL = unchecked((int)0x9000001D);
internal const int PHONEERR_RESOURCEUNAVAIL = unchecked((int)0x9000001F);
internal const int PHONEERR_REQUESTOVERRUN = unchecked((int)0x90000020);
internal const int PHONEERR_STRUCTURETOOSMALL = unchecked((int)0x90000021);
internal const int PHONEERR_UNINITIALIZED = unchecked((int)0x90000022);
internal const int PHONEERR_REINIT = unchecked((int)0x90000023);
internal const int PHONEERR_DISCONNECTED = unchecked((int)0x90000024);
internal const int PHONEERR_SERVICE_NOT_RUNNING = unchecked((int)0x90000025);
internal const int LINEFEATURE_DEVSPECIFIC = unchecked((int)0x00000001);
internal const int LINEFEATURE_DEVSPECIFICFEAT = unchecked((int)0x00000002);
internal const int LINEFEATURE_FORWARD = unchecked((int)0x00000004);
internal const int LINEFEATURE_MAKECALL = unchecked((int)0x00000008);
internal const int LINEFEATURE_SETMEDIACONTROL = unchecked((int)0x00000010);
internal const int LINEFEATURE_SETTERMINAL = unchecked((int)0x00000020);
internal const int LINEFEATURE_SETDEVSTATUS = unchecked((int)0x00000040); // TAPI v2.0
internal const int LINEFEATURE_FORWARDFWD = unchecked((int)0x00000080); // TAPI v2.0
internal const int LINEFEATURE_FORWARDDND = unchecked((int)0x00000100); // TAPI v2.0
internal const int LINEFORWARDMODE_UNCOND = unchecked((int)0x00000001);
internal const int LINEFORWARDMODE_UNCONDINTERNAL = unchecked((int)0x00000002);
internal const int LINEFORWARDMODE_UNCONDEXTERNAL = unchecked((int)0x00000004);
internal const int LINEFORWARDMODE_UNCONDSPECIFIC = unchecked((int)0x00000008);
internal const int LINEFORWARDMODE_BUSY = unchecked((int)0x00000010);
internal const int LINEFORWARDMODE_BUSYINTERNAL = unchecked((int)0x00000020);
internal const int LINEFORWARDMODE_BUSYEXTERNAL = unchecked((int)0x00000040);
internal const int LINEFORWARDMODE_BUSYSPECIFIC = unchecked((int)0x00000080);
internal const int LINEFORWARDMODE_NOANSW = unchecked((int)0x00000100);
internal const int LINEFORWARDMODE_NOANSWINTERNAL = unchecked((int)0x00000200);
internal const int LINEFORWARDMODE_NOANSWEXTERNAL = unchecked((int)0x00000400);
internal const int LINEFORWARDMODE_NOANSWSPECIFIC = unchecked((int)0x00000800);
internal const int LINEFORWARDMODE_BUSYNA = unchecked((int)0x00001000);
internal const int LINEFORWARDMODE_BUSYNAINTERNAL = unchecked((int)0x00002000);
internal const int LINEFORWARDMODE_BUSYNAEXTERNAL = unchecked((int)0x00004000);
internal const int LINEFORWARDMODE_BUSYNASPECIFIC = unchecked((int)0x00008000);
internal const int LINEFORWARDMODE_UNKNOWN = unchecked((int)0x00010000); // TAPI v1.4
internal const int LINEFORWARDMODE_UNAVAIL = unchecked((int)0x00020000); // TAPI v1.4
internal const int LINEGATHERTERM_BUFFERFULL = unchecked((int)0x00000001);
internal const int LINEGATHERTERM_TERMDIGIT = unchecked((int)0x00000002);
internal const int LINEGATHERTERM_FIRSTTIMEOUT = unchecked((int)0x00000004);
internal const int LINEGATHERTERM_INTERTIMEOUT = unchecked((int)0x00000008);
internal const int LINEGATHERTERM_CANCEL = unchecked((int)0x00000010);
internal const int LINEGENERATETERM_DONE = unchecked((int)0x00000001);
internal const int LINEGENERATETERM_CANCEL = unchecked((int)0x00000002);
internal const int LINEINITIALIZEEXOPTION_USEHIDDENWINDOW = unchecked((int)0x00000001); // TAPI v2.0
internal const int LINEINITIALIZEEXOPTION_USEEVENT = unchecked((int)0x00000002); // TAPI v2.0
internal const int LINEINITIALIZEEXOPTION_USECOMPLETIONPORT = unchecked((int)0x00000003); // TAPI v2.0
internal const int PHONEINITIALIZEEXOPTION_USEHIDDENWINDOW = unchecked((int)0x00000001); // TAPI v2.0
internal const int PHONEINITIALIZEEXOPTION_USEEVENT = unchecked((int)0x00000002); // TAPI v2.0
internal const int PHONEINITIALIZEEXOPTION_USECOMPLETIONPORT = unchecked((int)0x00000003); // TAPI v2.0
internal const int LINELOCATIONOPTION_PULSEDIAL = unchecked((int)0x00000001);
internal const int LINEMEDIAMODE_UNKNOWN = unchecked((int)0x00000002);
internal const int LINEMEDIAMODE_INTERACTIVEVOICE = unchecked((int)0x00000004);
internal const int LINEMEDIAMODE_AUTOMATEDVOICE = unchecked((int)0x00000008);
internal const int LINEMEDIAMODE_DATAMODEM = unchecked((int)0x00000010);
internal const int LINEMEDIAMODE_G3FAX = unchecked((int)0x00000020);
internal const int LINEMEDIAMODE_TDD = unchecked((int)0x00000040);
internal const int LINEMEDIAMODE_G4FAX = unchecked((int)0x00000080);
internal const int LINEMEDIAMODE_DIGITALDATA = unchecked((int)0x00000100);
internal const int LINEMEDIAMODE_TELETEX = unchecked((int)0x00000200);
internal const int LINEMEDIAMODE_VIDEOTEX = unchecked((int)0x00000400);
internal const int LINEMEDIAMODE_TELEX = unchecked((int)0x00000800);
internal const int LINEMEDIAMODE_MIXED = unchecked((int)0x00001000);
internal const int LINEMEDIAMODE_ADSI = unchecked((int)0x00002000);
internal const int LINEMEDIAMODE_VOICEVIEW = unchecked((int)0x00004000);
internal const int LINEMEDIAMODE_VIDEO = unchecked((int)0x00008000);
internal const int LINEOFFERINGMODE_ACTIVE = unchecked((int)0x00000001); // TAPI v1.4
internal const int LINEOFFERINGMODE_INACTIVE = unchecked((int)0x00000002); // TAPI v1.4
internal const int LINEOPENOPTION_SINGLEADDRESS = unchecked((int)0x80000000); // TAPI v2.0
internal const int LINEOPENOPTION_PROXY = unchecked((int)0x40000000); // TAPI v2.0
internal const int LINEPARKMODE_DIRECTED = unchecked((int)0x00000001);
internal const int LINEPARKMODE_NONDIRECTED = unchecked((int)0x00000002);
internal const int LINEROAMMODE_UNKNOWN = unchecked((int)0x00000001);
internal const int LINEROAMMODE_UNAVAIL = unchecked((int)0x00000002);
internal const int LINEROAMMODE_HOME = unchecked((int)0x00000004);
internal const int LINEROAMMODE_ROAMA = unchecked((int)0x00000008);
internal const int LINEROAMMODE_ROAMB = unchecked((int)0x00000010);
internal const int LINEREMOVEFROMCONF_NONE = unchecked((int)0x00000001);
internal const int LINEREMOVEFROMCONF_LAST = unchecked((int)0x00000002);
internal const int LINEREMOVEFROMCONF_ANY = unchecked((int)0x00000003);
internal const int LINESPECIALINFO_NOCIRCUIT = unchecked((int)0x00000001);
internal const int LINESPECIALINFO_CUSTIRREG = unchecked((int)0x00000002);
internal const int LINESPECIALINFO_REORDER = unchecked((int)0x00000004);
internal const int LINESPECIALINFO_UNKNOWN = unchecked((int)0x00000008);
internal const int LINESPECIALINFO_UNAVAIL = unchecked((int)0x00000010);
internal const int LINETERMDEV_PHONE = unchecked((int)0x00000001);
internal const int LINETERMDEV_HEADSET = unchecked((int)0x00000002);
internal const int LINETERMDEV_SPEAKER = unchecked((int)0x00000004);
internal const int LINETERMMODE_BUTTONS = unchecked((int)0x00000001);
internal const int LINETERMMODE_LAMPS = unchecked((int)0x00000002);
internal const int LINETERMMODE_DISPLAY = unchecked((int)0x00000004);
internal const int LINETERMMODE_RINGER = unchecked((int)0x00000008);
internal const int LINETERMMODE_HOOKSWITCH = unchecked((int)0x00000010);
internal const int LINETERMMODE_MEDIATOLINE = unchecked((int)0x00000020);
internal const int LINETERMMODE_MEDIAFROMLINE = unchecked((int)0x00000040);
internal const int LINETERMMODE_MEDIABIDIRECT = unchecked((int)0x00000080);
internal const int LINETERMSHARING_PRIVATE = unchecked((int)0x00000001);
internal const int LINETERMSHARING_SHAREDEXCL = unchecked((int)0x00000002);
internal const int LINETERMSHARING_SHAREDCONF = unchecked((int)0x00000004);
internal const int LINETONEMODE_CUSTOM = unchecked((int)0x00000001);
internal const int LINETONEMODE_RINGBACK = unchecked((int)0x00000002);
internal const int LINETONEMODE_BUSY = unchecked((int)0x00000004);
internal const int LINETONEMODE_BEEP = unchecked((int)0x00000008);
internal const int LINETONEMODE_BILLING = unchecked((int)0x00000010);
internal const int LINETRANSFERMODE_TRANSFER = unchecked((int)0x00000001);
internal const int LINETRANSFERMODE_CONFERENCE = unchecked((int)0x00000002);
internal const int LINETRANSLATEOPTION_CARDOVERRIDE = unchecked((int)0x00000001);
internal const int LINETRANSLATEOPTION_CANCELCALLWAITING = unchecked((int)0x00000002); // TAPI v1.4
internal const int LINETRANSLATEOPTION_FORCELOCAL = unchecked((int)0x00000004); // TAPI v1.4
internal const int LINETRANSLATEOPTION_FORCELD = unchecked((int)0x00000008); // TAPI v1.4
internal const int LINETRANSLATERESULT_CANONICAL = unchecked((int)0x00000001);
internal const int LINETRANSLATERESULT_INTERNATIONAL = unchecked((int)0x00000002);
internal const int LINETRANSLATERESULT_LONGDISTANCE = unchecked((int)0x00000004);
internal const int LINETRANSLATERESULT_LOCAL = unchecked((int)0x00000008);
internal const int LINETRANSLATERESULT_INTOLLLIST = unchecked((int)0x00000010);
internal const int LINETRANSLATERESULT_NOTINTOLLLIST = unchecked((int)0x00000020);
internal const int LINETRANSLATERESULT_DIALBILLING = unchecked((int)0x00000040);
internal const int LINETRANSLATERESULT_DIALQUIET = unchecked((int)0x00000080);
internal const int LINETRANSLATERESULT_DIALDIALTONE = unchecked((int)0x00000100);
internal const int LINETRANSLATERESULT_DIALPROMPT = unchecked((int)0x00000200);
internal const int LINETRANSLATERESULT_VOICEDETECT = unchecked((int)0x00000400); // TAPI v2.0
internal const int LINETRANSLATERESULT_NOTRANSLATION = unchecked((int)0x00000800); // TAPI v3.0
internal const int PHONESTATE_OTHER = unchecked((int)0x00000001);
internal const int PHONESTATE_CONNECTED = unchecked((int)0x00000002);
internal const int PHONESTATE_DISCONNECTED = unchecked((int)0x00000004);
internal const int PHONESTATE_OWNER = unchecked((int)0x00000008);
internal const int PHONESTATE_MONITORS = unchecked((int)0x00000010);
internal const int PHONESTATE_DISPLAY = unchecked((int)0x00000020);
internal const int PHONESTATE_LAMP = unchecked((int)0x00000040);
internal const int PHONESTATE_RINGMODE = unchecked((int)0x00000080);
internal const int PHONESTATE_RINGVOLUME = unchecked((int)0x00000100);
internal const int PHONESTATE_HANDSETHOOKSWITCH = unchecked((int)0x00000200);
internal const int PHONESTATE_HANDSETVOLUME = unchecked((int)0x00000400);
internal const int PHONESTATE_HANDSETGAIN = unchecked((int)0x00000800);
internal const int PHONESTATE_SPEAKERHOOKSWITCH = unchecked((int)0x00001000);
internal const int PHONESTATE_SPEAKERVOLUME = unchecked((int)0x00002000);
internal const int PHONESTATE_SPEAKERGAIN = unchecked((int)0x00004000);
internal const int PHONESTATE_HEADSETHOOKSWITCH = unchecked((int)0x00008000);
internal const int PHONESTATE_HEADSETVOLUME = unchecked((int)0x00010000);
internal const int PHONESTATE_HEADSETGAIN = unchecked((int)0x00020000);
internal const int PHONESTATE_SUSPEND = unchecked((int)0x00040000);
internal const int PHONESTATE_RESUME = unchecked((int)0x00080000);
internal const int PHONESTATE_DEVSPECIFIC = unchecked((int)0x00100000);
internal const int PHONESTATE_REINIT = unchecked((int)0x00200000);
internal const int PHONESTATE_CAPSCHANGE = unchecked((int)0x00400000); // TAPI v1.4
internal const int PHONESTATE_REMOVED = unchecked((int)0x00800000); // TAPI v1.4
internal const int PHONEFEATURE_GETBUTTONINFO = unchecked((int)0x00000001); // TAPI v2.0
internal const int PHONEFEATURE_GETDATA = unchecked((int)0x00000002); // TAPI v2.0
internal const int PHONEFEATURE_GETDISPLAY = unchecked((int)0x00000004); // TAPI v2.0
internal const int PHONEFEATURE_GETGAINHANDSET = unchecked((int)0x00000008); // TAPI v2.0
internal const int PHONEFEATURE_GETGAINSPEAKER = unchecked((int)0x00000010); // TAPI v2.0
internal const int PHONEFEATURE_GETGAINHEADSET = unchecked((int)0x00000020); // TAPI v2.0
internal const int PHONEFEATURE_GETHOOKSWITCHHANDSET = unchecked((int)0x00000040); // TAPI v2.0
internal const int PHONEFEATURE_GETHOOKSWITCHSPEAKER = unchecked((int)0x00000080); // TAPI v2.0
internal const int PHONEFEATURE_GETHOOKSWITCHHEADSET = unchecked((int)0x00000100); // TAPI v2.0
internal const int PHONEFEATURE_GETLAMP = unchecked((int)0x00000200); // TAPI v2.0
internal const int PHONEFEATURE_GETRING = unchecked((int)0x00000400); // TAPI v2.0
internal const int PHONEFEATURE_GETVOLUMEHANDSET = unchecked((int)0x00000800); // TAPI v2.0
internal const int PHONEFEATURE_GETVOLUMESPEAKER = unchecked((int)0x00001000); // TAPI v2.0
internal const int PHONEFEATURE_GETVOLUMEHEADSET = unchecked((int)0x00002000); // TAPI v2.0
internal const int PHONEFEATURE_SETBUTTONINFO = unchecked((int)0x00004000); // TAPI v2.0
internal const int PHONEFEATURE_SETDATA = unchecked((int)0x00008000); // TAPI v2.0
internal const int PHONEFEATURE_SETDISPLAY = unchecked((int)0x00010000); // TAPI v2.0
internal const int PHONEFEATURE_SETGAINHANDSET = unchecked((int)0x00020000); // TAPI v2.0
internal const int PHONEFEATURE_SETGAINSPEAKER = unchecked((int)0x00040000); // TAPI v2.0
internal const int PHONEFEATURE_SETGAINHEADSET = unchecked((int)0x00080000); // TAPI v2.0
internal const int PHONEFEATURE_SETHOOKSWITCHHANDSET = unchecked((int)0x00100000); // TAPI v2.0
internal const int PHONEFEATURE_SETHOOKSWITCHSPEAKER = unchecked((int)0x00200000); // TAPI v2.0
internal const int PHONEFEATURE_SETHOOKSWITCHHEADSET = unchecked((int)0x00400000); // TAPI v2.0
internal const int PHONEFEATURE_SETLAMP = unchecked((int)0x00800000); // TAPI v2.0
internal const int PHONEFEATURE_SETRING = unchecked((int)0x01000000); // TAPI v2.0
internal const int PHONEFEATURE_SETVOLUMEHANDSET = unchecked((int)0x02000000); // TAPI v2.0
internal const int PHONEFEATURE_SETVOLUMESPEAKER = unchecked((int)0x04000000); // TAPI v2.0
internal const int PHONEFEATURE_SETVOLUMEHEADSET = unchecked((int)0x08000000); // TAPI v2.0
internal const int PHONEFEATURE_GENERICPHONE = unchecked((int)0x10000000); // TAPI v3.1
internal const int PHONEHOOKSWITCHDEV_HANDSET = unchecked((int)0x00000001);
internal const int PHONEHOOKSWITCHDEV_SPEAKER = unchecked((int)0x00000002);
internal const int PHONEHOOKSWITCHDEV_HEADSET = unchecked((int)0x00000004);
internal const int PHONEHOOKSWITCHMODE_ONHOOK = unchecked((int)0x00000001);
internal const int PHONEHOOKSWITCHMODE_MIC = unchecked((int)0x00000002);
internal const int PHONEHOOKSWITCHMODE_SPEAKER = unchecked((int)0x00000004);
internal const int PHONEHOOKSWITCHMODE_MICSPEAKER = unchecked((int)0x00000008);
internal const int PHONEHOOKSWITCHMODE_UNKNOWN = unchecked((int)0x00000010);
internal const int PHONELAMPMODE_DUMMY = unchecked((int)0x00000001);
internal const int PHONELAMPMODE_OFF = unchecked((int)0x00000002);
internal const int PHONELAMPMODE_STEADY = unchecked((int)0x00000004);
internal const int PHONELAMPMODE_WINK = unchecked((int)0x00000008);
internal const int PHONELAMPMODE_FLASH = unchecked((int)0x00000010);
internal const int PHONELAMPMODE_FLUTTER = unchecked((int)0x00000020);
internal const int PHONELAMPMODE_BROKENFLUTTER = unchecked((int)0x00000040);
internal const int PHONELAMPMODE_UNKNOWN = unchecked((int)0x00000080);
internal const int PHONEPRIVILEGE_MONITOR = unchecked((int)0x00000001);
internal const int PHONEPRIVILEGE_OWNER = unchecked((int)0x00000002);
internal const int PHONESTATUSFLAGS_CONNECTED = unchecked((int)0x00000001);
internal const int PHONESTATUSFLAGS_SUSPENDED = unchecked((int)0x00000002);
internal const int PHONEBUTTONFUNCTION_UNKNOWN = unchecked((int)0x00000000);
internal const int PHONEBUTTONFUNCTION_CONFERENCE = unchecked((int)0x00000001);
internal const int PHONEBUTTONFUNCTION_TRANSFER = unchecked((int)0x00000002);
internal const int PHONEBUTTONFUNCTION_DROP = unchecked((int)0x00000003);
internal const int PHONEBUTTONFUNCTION_HOLD = unchecked((int)0x00000004);
internal const int PHONEBUTTONFUNCTION_RECALL = unchecked((int)0x00000005);
internal const int PHONEBUTTONFUNCTION_DISCONNECT = unchecked((int)0x00000006);
internal const int PHONEBUTTONFUNCTION_CONNECT = unchecked((int)0x00000007);
internal const int PHONEBUTTONFUNCTION_MSGWAITON = unchecked((int)0x00000008);
internal const int PHONEBUTTONFUNCTION_MSGWAITOFF = unchecked((int)0x00000009);
internal const int PHONEBUTTONFUNCTION_SELECTRING = unchecked((int)0x0000000A);
internal const int PHONEBUTTONFUNCTION_ABBREVDIAL = unchecked((int)0x0000000B);
internal const int PHONEBUTTONFUNCTION_FORWARD = unchecked((int)0x0000000C);
internal const int PHONEBUTTONFUNCTION_PICKUP = unchecked((int)0x0000000D);
internal const int PHONEBUTTONFUNCTION_RINGAGAIN = unchecked((int)0x0000000E);
internal const int PHONEBUTTONFUNCTION_PARK = unchecked((int)0x0000000F);
internal const int PHONEBUTTONFUNCTION_REJECT = unchecked((int)0x00000010);
internal const int PHONEBUTTONFUNCTION_REDIRECT = unchecked((int)0x00000011);
internal const int PHONEBUTTONFUNCTION_MUTE = unchecked((int)0x00000012);
internal const int PHONEBUTTONFUNCTION_VOLUMEUP = unchecked((int)0x00000013);
internal const int PHONEBUTTONFUNCTION_VOLUMEDOWN = unchecked((int)0x00000014);
internal const int PHONEBUTTONFUNCTION_SPEAKERON = unchecked((int)0x00000015);
internal const int PHONEBUTTONFUNCTION_SPEAKEROFF = unchecked((int)0x00000016);
internal const int PHONEBUTTONFUNCTION_FLASH = unchecked((int)0x00000017);
internal const int PHONEBUTTONFUNCTION_DATAON = unchecked((int)0x00000018);
internal const int PHONEBUTTONFUNCTION_DATAOFF = unchecked((int)0x00000019);
internal const int PHONEBUTTONFUNCTION_DONOTDISTURB = unchecked((int)0x0000001A);
internal const int PHONEBUTTONFUNCTION_INTERCOM = unchecked((int)0x0000001B);
internal const int PHONEBUTTONFUNCTION_BRIDGEDAPP = unchecked((int)0x0000001C);
internal const int PHONEBUTTONFUNCTION_BUSY = unchecked((int)0x0000001D);
internal const int PHONEBUTTONFUNCTION_CALLAPP = unchecked((int)0x0000001E);
internal const int PHONEBUTTONFUNCTION_DATETIME = unchecked((int)0x0000001F);
internal const int PHONEBUTTONFUNCTION_DIRECTORY = unchecked((int)0x00000020);
internal const int PHONEBUTTONFUNCTION_COVER = unchecked((int)0x00000021);
internal const int PHONEBUTTONFUNCTION_CALLID = unchecked((int)0x00000022);
internal const int PHONEBUTTONFUNCTION_LASTNUM = unchecked((int)0x00000023);
internal const int PHONEBUTTONFUNCTION_NIGHTSRV = unchecked((int)0x00000024);
internal const int PHONEBUTTONFUNCTION_SENDCALLS = unchecked((int)0x00000025);
internal const int PHONEBUTTONFUNCTION_MSGINDICATOR = unchecked((int)0x00000026);
internal const int PHONEBUTTONFUNCTION_REPDIAL = unchecked((int)0x00000027);
internal const int PHONEBUTTONFUNCTION_SETREPDIAL = unchecked((int)0x00000028);
internal const int PHONEBUTTONFUNCTION_SYSTEMSPEED = unchecked((int)0x00000029);
internal const int PHONEBUTTONFUNCTION_STATIONSPEED = unchecked((int)0x0000002A);
internal const int PHONEBUTTONFUNCTION_CAMPON = unchecked((int)0x0000002B);
internal const int PHONEBUTTONFUNCTION_SAVEREPEAT = unchecked((int)0x0000002C);
internal const int PHONEBUTTONFUNCTION_QUEUECALL = unchecked((int)0x0000002D);
internal const int PHONEBUTTONFUNCTION_NONE = unchecked((int)0x0000002E);
internal const int PHONEBUTTONFUNCTION_SEND = unchecked((int)0x0000002F); // TAPI v3.1
internal const int PHONEBUTTONMODE_DUMMY = unchecked((int)0x00000001);
internal const int PHONEBUTTONMODE_CALL = unchecked((int)0x00000002);
internal const int PHONEBUTTONMODE_FEATURE = unchecked((int)0x00000004);
internal const int PHONEBUTTONMODE_KEYPAD = unchecked((int)0x00000008);
internal const int PHONEBUTTONMODE_LOCAL = unchecked((int)0x00000010);
internal const int PHONEBUTTONMODE_DISPLAY = unchecked((int)0x00000020);
internal const int PHONEBUTTONSTATE_UP = unchecked((int)0x00000001);
internal const int PHONEBUTTONSTATE_DOWN = unchecked((int)0x00000002);
internal const int PHONEBUTTONSTATE_UNKNOWN = unchecked((int)0x00000004); // TAPI v1.4
internal const int PHONEBUTTONSTATE_UNAVAIL = unchecked((int)0x00000008); // TAPI v1.4
internal const int STRINGFORMAT_ASCII = unchecked((int)0x00000001);
internal const int STRINGFORMAT_DBCS = unchecked((int)0x00000002);
internal const int STRINGFORMAT_UNICODE = unchecked((int)0x00000003);
internal const int STRINGFORMAT_BINARY = unchecked((int)0x00000004);
#endregion
internal static string GetString(byte[] buff, int offset, int len, int stringType)
{
if (buff == null || buff.Length == 0 || len == 0)
return string.Empty;
Encoding enc = GetTextEncoding(stringType);
if (enc == null)
return string.Empty;
if ((len - offset) > (buff.Length - offset))
len = buff.Length - offset;
return enc.GetString(buff, offset, len).Replace("\0", "");
}
internal static void WriteByteArray(byte[] buff, IntPtr ptr, int offset)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (buff == null || buff.Length == 0)
return;
IntPtr dataPtr = Marshal.AllocHGlobal(buff.Length);
try
{
Marshal.Copy(buff, 0, dataPtr, buff.Length);
Marshal.WriteIntPtr(ptr, offset, dataPtr);
}
finally
{
Marshal.FreeHGlobal(dataPtr);
}
}
private static Encoding GetTextEncoding(int stringType)
{
switch (stringType)
{
case STRINGFORMAT_ASCII:
return ASCIIEncoding.ASCII;
case STRINGFORMAT_UNICODE:
return UnicodeEncoding.Default;
case STRINGFORMAT_DBCS:
return Encoding.GetEncoding(1252);
default:
break;
}
return null;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEINITIALIZEEXPARAMS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwOptions;
internal IntPtr hEvent;
internal int dwCompletionKey;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PHONEINITIALIZEEXPARAMS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwOptions;
internal IntPtr hEvent;
internal int dwCompletionKey;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEADDRESSCAPS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwLineDeviceID;
internal int dwAddressSize;
internal int dwAddressOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwAddressSharing;
internal int dwAddressStates;
internal int dwCallInfoStates;
internal int dwCallerIDFlags;
internal int dwCalledIDFlags;
internal int dwConnectedIDFlags;
internal int dwRedirectionIDFlags;
internal int dwRedirectingIDFlags;
internal int dwCallStates;
internal int dwDialToneModes;
internal int dwBusyModes;
internal int dwSpecialInfo;
internal int dwDisconnectModes;
internal int dwMaxNumActiveCalls;
internal int dwMaxNumOnHoldCalls;
internal int dwMaxNumOnHoldPendingCalls;
internal int dwMaxNumConference;
internal int dwMaxNumTransConf;
internal int dwAddrCapFlags;
internal int dwCallFeatures;
internal int dwRemoveFromConfCaps;
internal int dwRemoveFromConfState;
internal int dwTransferModes;
internal int dwParkModes;
internal int dwForwardModes;
internal int dwMaxForwardEntries;
internal int dwMaxSpecificEntries;
internal int dwMinFwdNumRings;
internal int dwMaxFwdNumRings;
internal int dwMaxCallCompletions;
internal int dwCallCompletionConds;
internal int dwCallCompletionModes;
internal int dwNumCompletionMessages;
internal int dwCompletionMsgTextEntrySize;
internal int dwCompletionMsgTextSize;
internal int dwCompletionMsgTextOffset;
internal int dwAddressFeatures;
internal int dwPredictiveAutoTransferStates;
internal int dwNumCallTreatments;
internal int dwCallTreatmentListSize;
internal int dwCallTreatmentListOffset;
internal int dwDeviceClassesSize;
internal int dwDeviceClassesOffset;
internal int dwMaxCallDataSize;
internal int dwCallFeatures2;
internal int dwMaxNoAnswerTimeout;
internal int dwConnectedModes;
internal int dwOfferingModes;
internal int dwAvailableMediaModes;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEADDRESSSTATUS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwNumInUse;
internal int dwNumActiveCalls;
internal int dwNumOnHoldCalls;
internal int dwNumOnHoldPendCalls;
internal int dwAddressFeatures;
internal int dwNumRingsNoAnswer;
internal int dwForwardNumEntries;
internal int dwForwardSize;
internal int dwForwardOffset;
internal int dwTerminalModesSize;
internal int dwTerminalModesOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECALLINFO
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int hLine;
internal int dwLineDeviceID;
internal int dwAddressID;
internal int dwBearerMode;
internal int dwRate;
internal int dwMediaMode;
internal int dwAppSpecific;
internal int dwCallID;
internal int dwRelatedCallID;
internal int dwCallParamFlags;
internal int dwCallStates;
internal int dwMonitorDigitModes;
internal int dwMonitorMediaModes;
internal LINEDIALPARAMS DialParams;
internal int dwOrigin;
internal int dwReason;
internal int dwCompletionID;
internal int dwNumOwners;
internal int dwNumMonitors;
internal int dwCountryCode;
internal int dwTrunk;
internal int dwCallerIDFlags;
internal int dwCallerIDSize;
internal int dwCallerIDOffset;
internal int dwCallerIDNameSize;
internal int dwCallerIDNameOffset;
internal int dwCalledIDFlags;
internal int dwCalledIDSize;
internal int dwCalledIDOffset;
internal int dwCalledIDNameSize;
internal int dwCalledIDNameOffset;
internal int dwConnectedIDFlags;
internal int dwConnectedIDSize;
internal int dwConnectedIDOffset;
internal int dwConnectedIDNameSize;
internal int dwConnectedIDNameOffset;
internal int dwRedirectionIDFlags;
internal int dwRedirectionIDSize;
internal int dwRedirectionIDOffset;
internal int dwRedirectionIDNameSize;
internal int dwRedirectionIDNameOffset;
internal int dwRedirectingIDFlags;
internal int dwRedirectingIDSize;
internal int dwRedirectingIDOffset;
internal int dwRedirectingIDNameSize;
internal int dwRedirectingIDNameOffset;
internal int dwAppNameSize;
internal int dwAppNameOffset;
internal int dwDisplayableAddressSize;
internal int dwDisplayableAddressOffset;
internal int dwCalledPartySize;
internal int dwCalledPartyOffset;
internal int dwCommentSize;
internal int dwCommentOffset;
internal int dwDisplaySize;
internal int dwDisplayOffset;
internal int dwUserUserInfoSize;
internal int dwUserUserInfoOffset;
internal int dwHighLevelCompSize;
internal int dwHighLevelCompOffset;
internal int dwLowLevelCompSize;
internal int dwLowLevelCompOffset;
internal int dwChargingInfoSize;
internal int dwChargingInfoOffset;
internal int dwTerminalModesSize;
internal int dwTerminalModesOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwCallTreatment;
internal int dwCallDataSize;
internal int dwCallDataOffset;
internal int dwSendingFlowspecSize;
internal int dwSendingFlowspecOffset;
internal int dwReceivingFlowspecSize;
internal int dwReceivingFlowspecOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECALLLIST
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwCallsNumEntries;
internal int dwCallsSize;
internal int dwCallsOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECALLPARAMS
{
internal int dwTotalSize;
internal int dwBearerMode; // voice
internal int dwMinRate; // (3.1kHz)
internal int dwMaxRate; // (3.1kHz)
internal int dwMediaMode; // interactiveVoice
internal int dwCallParamFlags; // 0
internal int dwAddressMode; // addressID
internal int dwAddressID; // (any available)
internal LINEDIALPARAMS DialParams; // (0, 0, 0, 0)
internal int dwOrigAddressSize; // 0
internal int dwOrigAddressOffset;
internal int dwDisplayableAddressSize; // 0
internal int dwDisplayableAddressOffset;
internal int dwCalledPartySize; // 0
internal int dwCalledPartyOffset;
internal int dwCommentSize; // 0
internal int dwCommentOffset;
internal int dwUserUserInfoSize; // 0
internal int dwUserUserInfoOffset;
internal int dwHighLevelCompSize; // 0
internal int dwHighLevelCompOffset;
internal int dwLowLevelCompSize; // 0
internal int dwLowLevelCompOffset;
internal int dwDevSpecificSize; // 0
internal int dwDevSpecificOffset;
internal int dwPredictiveAutoTransferStates;//TAPI Version 2.0
internal int dwTargetAddressSize; //TAPI Version 2.0
internal int dwTargetAddressOffset; //TAPI Version 2.0
internal int dwSendingFlowspecSize; //TAPI Version 2.0
internal int dwSendingFlowspecOffset; //TAPI Version 2.0
internal int dwReceivingFlowspecSize; //TAPI Version 2.0
internal int dwReceivingFlowspecOffset; //TAPI Version 2.0
internal int dwDeviceClassSize; //TAPI Version 2.0
internal int dwDeviceClassOffset; //TAPI Version 2.0
internal int dwDeviceConfigSize; //TAPI Version 2.0
internal int dwDeviceConfigOffset; //TAPI Version 2.0
internal int dwCallDataSize; //TAPI Version 2.0
internal int dwCallDataOffset; //TAPI Version 2.0
internal int dwNoAnswerTimeout; //TAPI Version 2.0
internal int dwCallingPartyIDSize; //TAPI Version 2.0
internal int dwCallingPartyIDOffset; //TAPI Version 2.0
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECALLSTATUS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwCallState;
internal int dwCallStateMode;
internal int dwCallPrivilege;
internal int dwCallFeatures;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwCallFeatures2; // TAPI v2.0
internal DateTime tStateEntryTime; // TAPI v2.0
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECALLTREATMENTENTRY
{
internal int dwCallTreatmentID;
internal int dwCallTreatmentNameSize;
internal int dwCallTreatmentNameOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECOUNTRYENTRY
{
internal int dwCountryID; // TAPI v1.4
internal int dwCountryCode; // TAPI v1.4
internal int dwNextCountryID; // TAPI v1.4
internal int dwCountryNameSize; // TAPI v1.4
internal int dwCountryNameOffset; // TAPI v1.4
internal int dwSameAreaRuleSize; // TAPI v1.4
internal int dwSameAreaRuleOffset; // TAPI v1.4
internal int dwLongDistanceRuleSize; // TAPI v1.4
internal int dwLongDistanceRuleOffset; // TAPI v1.4
internal int dwInternationalRuleSize; // TAPI v1.4
internal int dwInternationalRuleOffset; // TAPI v1.4
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECOUNTRYLIST
{
internal int dwTotalSize; // TAPI v1.4
internal int dwNeededSize; // TAPI v1.4
internal int dwUsedSize; // TAPI v1.4
internal int dwNumCountries; // TAPI v1.4
internal int dwCountryListSize; // TAPI v1.4
internal int dwCountryListOffset; // TAPI v1.4
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEDEVCAPS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwProviderInfoSize;
internal int dwProviderInfoOffset;
internal int dwSwitchInfoSize;
internal int dwSwitchInfoOffset;
internal int dwPermanentLineID;
internal int dwLineNameSize;
internal int dwLineNameOffset;
internal int dwStringFormat;
internal int dwAddressModes;
internal int dwNumAddresses;
internal int dwBearerModes;
internal int dwMaxRate;
internal int dwMediaModes;
internal int dwGenerateToneModes;
internal int dwGenerateToneMaxNumFreq;
internal int dwGenerateDigitModes;
internal int dwMonitorToneMaxNumFreq;
internal int dwMonitorToneMaxNumEntries;
internal int dwMonitorDigitModes;
internal int dwGatherDigitsMinTimeout;
internal int dwGatherDigitsMaxTimeout;
internal int dwMedCtlDigitMaxListSize;
internal int dwMedCtlMediaMaxListSize;
internal int dwMedCtlToneMaxListSize;
internal int dwMedCtlCallStateMaxListSize;
internal int dwDevCapFlags;
internal int dwMaxNumActiveCalls;
internal int dwAnswerMode;
internal int dwRingModes;
internal int dwLineStates;
internal int dwUUIAcceptSize;
internal int dwUUIAnswerSize;
internal int dwUUIMakeCallSize;
internal int dwUUIDropSize;
internal int dwUUISendUserUserInfoSize;
internal int dwUUICallInfoSize;
internal LINEDIALPARAMS MinDialParams;
internal LINEDIALPARAMS MaxDialParams;
internal LINEDIALPARAMS DefaultDialParams;
internal int dwNumTerminals;
internal int dwTerminalCapsSize;
internal int dwTerminalCapsOffset;
internal int dwTerminalTextEntrySize;
internal int dwTerminalTextSize;
internal int dwTerminalTextOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwLineFeatures;
internal int dwSettableDevStatus;
internal int dwDeviceClassesSize;
internal int dwDeviceClassesOffset;
internal Guid PermanentLineGuid; //TAPI Version 2.2
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEDEVSTATUS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwNumOpens;
internal int dwOpenMediaModes;
internal int dwNumActiveCalls;
internal int dwNumOnHoldCalls;
internal int dwNumOnHoldPendCalls;
internal int dwLineFeatures;
internal int dwNumCallCompletions;
internal int dwRingMode;
internal int dwSignalLevel;
internal int dwBatteryLevel;
internal int dwRoamMode;
internal int dwDevStatusFlags;
internal int dwTerminalModesSize;
internal int dwTerminalModesOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwAvailableMediaModes; // TAPI v2.0
internal int dwAppInfoSize; // TAPI v2.0
internal int dwAppInfoOffset; // TAPI v2.0
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEFORWARD
{
internal int dwForwardMode;
internal int dwCallerAddressSize;
internal int dwCallerAddressOffset;
internal int dwDestCountryCode;
internal int dwDestAddressSize;
internal int dwDestAddressOffset;
internal int dwCallerAddressType;
internal int dwDestAddressType;
};
[StructLayout(LayoutKind.Sequential)]
internal class LINEFORWARDLIST
{
internal int dwTotalSize;
internal int dwNumEntries;
};
[StructLayout(LayoutKind.Sequential)]
internal class LINETRANSLATECAPS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwNumLocations;
internal int dwLocationListSize;
internal int dwLocationListOffset;
internal int dwCurrentLocationID;
internal int dwNumCards;
internal int dwCardListSize;
internal int dwCardListOffset;
internal int dwCurrentPreferredCardID;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINELOCATIONENTRY
{
internal int dwPermanentLocationID;
internal int dwLocationNameSize;
internal int dwLocationNameOffset;
internal int dwCountryCode;
internal int dwCityCodeSize;
internal int dwCityCodeOffset;
internal int dwPreferredCardID;
internal int dwLocalAccessCodeSize; // TAPI v1.4
internal int dwLocalAccessCodeOffset; // TAPI v1.4
internal int dwLongDistanceAccessCodeSize; // TAPI v1.4
internal int dwLongDistanceAccessCodeOffset; // TAPI v1.4
internal int dwTollPrefixListSize; // TAPI v1.4
internal int dwTollPrefixListOffset; // TAPI v1.4
internal int dwCountryID; // TAPI v1.4
internal int dwOptions; // TAPI v1.4
internal int dwCancelCallWaitingSize; // TAPI v1.4
internal int dwCancelCallWaitingOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINECARDENTRY
{
internal int dwPermanentCardID;
internal int dwCardNameSize;
internal int dwCardNameOffset;
internal int dwCardNumberDigits; // TAPI v1.4
internal int dwSameAreaRuleSize; // TAPI v1.4
internal int dwSameAreaRuleOffset; // TAPI v1.4
internal int dwLongDistanceRuleSize; // TAPI v1.4
internal int dwLongDistanceRuleOffset; // TAPI v1.4
internal int dwInternationalRuleSize; // TAPI v1.4
internal int dwInternationalRuleOffset; // TAPI v1.4
internal int dwOptions;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEDIALPARAMS
{
internal int dwDialPause;
internal int dwDialSpeed;
internal int dwDigitDuration;
internal int dwWaitForDialtone;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEEXTENSIONID
{
internal int dwExtensionID0;
internal int dwExtensionID1;
internal int dwExtensionID2;
internal int dwExtensionID3;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEGENERATETONE
{
internal int dwFrequency;
internal int dwCadenceOn;
internal int dwCadenceOff;
internal int dwVolume;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEMESSAGE
{
internal uint hDevice; // TAPI v2.0
internal TapiEvent dwMessageID; // TAPI v2.0
internal IntPtr dwCallbackInstance; // TAPI v2.0
internal IntPtr dwParam1; // TAPI v2.0
internal IntPtr dwParam2; // TAPI v2.0
internal IntPtr dwParam3; // TAPI v2.0
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINEMONITORTONE
{
internal int dwAppSpecific;
internal int dwDuration;
internal int dwFrequency1;
internal int dwFrequency2;
internal int dwFrequency3;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEPROVIDERENTRY
{
internal int dwPermanentProviderID;
internal int dwProviderFilenameSize;
internal int dwProviderFilenameOffset;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINEPROVIDERLIST
{
internal int dwTotalSize; // TAPI v1.4
internal int dwNeededSize; // TAPI v1.4
internal int dwUsedSize; // TAPI v1.4
internal int dwNumProviders; // TAPI v1.4
internal int dwProviderListSize; // TAPI v1.4
internal int dwProviderListOffset; // TAPI v1.4
}
[StructLayout(LayoutKind.Sequential)]
internal struct LINETERMCAPS
{
internal int dwTermDev;
internal int dwTermModes;
internal int dwTermSharing;
}
[StructLayout(LayoutKind.Sequential)]
internal class LINETRANSLATEOUTPUT
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwDialableStringSize;
internal int dwDialableStringOffset;
internal int dwDisplayableStringSize;
internal int dwDisplayableStringOffset;
internal int dwCurrentCountry;
internal int dwDestCountry;
internal int dwTranslateResults;
}
[StructLayout(LayoutKind.Sequential)]
internal class PHONEBUTTONINFO
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwButtonMode;
internal int dwButtonFunction;
internal int dwButtonTextSize;
internal int dwButtonTextOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwButtonState; // TAPI v1.4
}
[StructLayout(LayoutKind.Sequential)]
internal class PHONECAPS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwProviderInfoSize;
internal int dwProviderInfoOffset;
internal int dwPhoneInfoSize;
internal int dwPhoneInfoOffset;
internal int dwPermanentPhoneID;
internal int dwPhoneNameSize;
internal int dwPhoneNameOffset;
internal int dwStringFormat;
internal int dwPhoneStates;
internal int dwHookSwitchDevs;
internal int dwHandsetHookSwitchModes;
internal int dwSpeakerHookSwitchModes;
internal int dwHeadsetHookSwitchModes;
internal int dwVolumeFlags;
internal int dwGainFlags;
internal int dwDisplayNumRows;
internal int dwDisplayNumColumns;
internal int dwNumRingModes;
internal int dwNumButtonLamps;
internal int dwButtonModesSize;
internal int dwButtonModesOffset;
internal int dwButtonFunctionsSize;
internal int dwButtonFunctionsOffset;
internal int dwLampModesSize;
internal int dwLampModesOffset;
internal int dwNumSetData;
internal int dwSetDataSize;
internal int dwSetDataOffset;
internal int dwNumGetData;
internal int dwGetDataSize;
internal int dwGetDataOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwDeviceClassesSize; // TAPI v2.0
internal int dwDeviceClassesOffset; // TAPI v2.0
internal int dwPhoneFeatures; // TAPI v2.0
internal int dwSettableHandsetHookSwitchModes; // TAPI v2.0
internal int dwSettableSpeakerHookSwitchModes; // TAPI v2.0
internal int dwSettableHeadsetHookSwitchModes; // TAPI v2.0
internal int dwMonitoredHandsetHookSwitchModes; // TAPI v2.0
internal int dwMonitoredSpeakerHookSwitchModes; // TAPI v2.0
internal int dwMonitoredHeadsetHookSwitchModes; // TAPI v2.0
internal Guid PermanentPhoneGuid; // TAPI v2.2
}
[StructLayout(LayoutKind.Sequential)]
internal struct PHONEEXTENSIONID
{
internal int dwExtensionID0;
internal int dwExtensionID1;
internal int dwExtensionID2;
internal int dwExtensionID3;
}
[StructLayout(LayoutKind.Sequential)]
internal class PHONESTATUS
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwStatusFlags;
internal int dwNumOwners;
internal int dwNumMonitors;
internal int dwRingMode;
internal int dwRingVolume;
internal int dwHandsetHookSwitchMode;
internal int dwHandsetVolume;
internal int dwHandsetGain;
internal int dwSpeakerHookSwitchMode;
internal int dwSpeakerVolume;
internal int dwSpeakerGain;
internal int dwHeadsetHookSwitchMode;
internal int dwHeadsetVolume;
internal int dwHeadsetGain;
internal int dwDisplaySize;
internal int dwDisplayOffset;
internal int dwLampModesSize;
internal int dwLampModesOffset;
internal int dwOwnerNameSize;
internal int dwOwnerNameOffset;
internal int dwDevSpecificSize;
internal int dwDevSpecificOffset;
internal int dwPhoneFeatures; // TAPI v2.0
}
[StructLayout(LayoutKind.Sequential)]
internal class VARSTRING
{
internal int dwTotalSize;
internal int dwNeededSize;
internal int dwUsedSize;
internal int dwStringFormat;
internal int dwStringSize;
internal int dwStringOffset;
}
}
| 57.318002 | 260 | 0.691588 |
1bd79c8ddf72e57c18370656dd9dac3f1d215751 | 1,306 | cs | C# | Daramee.WICsharp.Shared/Interfaces/IWICPalette.cs | daramkun/WICsharp | a4a95a4dfd53a84f0d30e4ba554a9822710ba52e | [
"MIT"
] | 1 | 2020-05-16T09:04:50.000Z | 2020-05-16T09:04:50.000Z | Daramee.WICsharp.Shared/Interfaces/IWICPalette.cs | daramkun/WICsharp | a4a95a4dfd53a84f0d30e4ba554a9822710ba52e | [
"MIT"
] | null | null | null | Daramee.WICsharp.Shared/Interfaces/IWICPalette.cs | daramkun/WICsharp | a4a95a4dfd53a84f0d30e4ba554a9822710ba52e | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Daramee.WICsharp
{
[ComImport
, Guid ( "00000040-a8f2-4877-ba0a-fd2b6645fb94" )
, InterfaceType ( ComInterfaceType.InterfaceIsIUnknown )]
public interface IWICPalette
{
HRESULT InitializePredefined (
WICBitmapPaletteType ePaletteType,
[In, MarshalAs ( UnmanagedType.Bool )] bool fAddTransparentColor );
HRESULT InitializeCustom (
uint [] pColors,
uint cCount );
HRESULT InitializeFromBitmap (
[In, MarshalAs ( UnmanagedType.Interface )] IWICBitmapSource pISurface,
uint cCount,
[In, MarshalAs ( UnmanagedType.Bool )] bool fAddTransparentColor );
HRESULT InitializeFromPalette (
[In, MarshalAs ( UnmanagedType.Interface )] IWICPalette pIPalette );
HRESULT GetType (
out WICBitmapPaletteType pePaletteType );
HRESULT GetColorCount (
out uint pcCount );
HRESULT GetColors (
uint cCount,
[Out] uint [] pColors,
out uint pcActualColors );
HRESULT IsBlackWhite (
[Out, MarshalAs ( UnmanagedType.Bool )] out bool pfIsBlackWhite );
HRESULT IsGrayscale (
[Out, MarshalAs ( UnmanagedType.Bool )] out bool pfIsGrayscale );
HRESULT HasAlpha (
[Out, MarshalAs ( UnmanagedType.Bool )] out bool pfHasAlpha );
}
}
| 26.12 | 74 | 0.732006 |
1bf07d30828962d09e7282c822421b75856fcbf1 | 2,440 | cs | C# | WPFCommandAggregator/AttachedProperties/Focused.cs | MarcArmbruster/WpfCommandAggregator | c58a2160e5cdbf6a5c581b6b4894e7f9fb18875b | [
"MIT"
] | 1 | 2020-02-20T13:58:48.000Z | 2020-02-20T13:58:48.000Z | WPFCommandAggregator/AttachedProperties/Focused.cs | MarcArmbruster/WpfCommandAggregator | c58a2160e5cdbf6a5c581b6b4894e7f9fb18875b | [
"MIT"
] | null | null | null | WPFCommandAggregator/AttachedProperties/Focused.cs | MarcArmbruster/WpfCommandAggregator | c58a2160e5cdbf6a5c581b6b4894e7f9fb18875b | [
"MIT"
] | 1 | 2021-09-15T15:21:05.000Z | 2021-09-15T15:21:05.000Z | namespace WPFCommandAggregator.AttachedProperties
{
using System.Windows;
using System.Windows.Input;
/// <summary>
/// Attached Property to set the focus to the bound control.
/// </summary>
/// <remarks>
/// <para><b>History</b></para>
/// <list type="table">
/// <item>
/// <term><b>Author:</b></term>
/// <description>Marc Armbruster</description>
/// </item>
/// <item>
/// <term><b>Date:</b></term>
/// <description>Dec/26/2019</description>
/// </item>
/// <item>
/// <term><b>Remarks:</b></term>
/// <description>Initial version.</description>
/// </item>
/// </list>
/// </remarks>
public class Focused
{
/// <summary>
/// Gets the IsFocused value.
/// </summary>
/// <param name="obj">The dependency object.</param>
/// <returns>The IsFocus value of the object..</returns>
public static bool GetFocused(DependencyObject obj)
{
return (bool)obj.GetValue(FocusedProperty);
}
/// <summary>
/// Sets the IsFocused value.
/// </summary>
/// <param name="obj">The dependency object.</param>
/// <param name="value">The value to set.</param>
public static void SetFocused(DependencyObject obj, bool value)
{
obj.SetValue(FocusedProperty, value);
}
/// <summary>
/// Using a DependencyProperty as the backing store for IsFocused.
/// </summary>
public static readonly DependencyProperty FocusedProperty =
DependencyProperty.RegisterAttached(
"Focused",
typeof(bool),
typeof(Focused),
new PropertyMetadata(false, OnFocusedChanged));
/// <summary>
/// Handles the changing of the value.
/// </summary>
/// <param name="sender">The sender object.</param>
/// <param name="eventArgs">The event arguments.</param>
private static void OnFocusedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs eventArgs)
{
var element = sender as UIElement;
if ((bool)eventArgs.NewValue == true)
{
element?.Focus();
}
else
{
Keyboard.ClearFocus();
}
}
}
} | 32.105263 | 115 | 0.530738 |
e4526084daed55d729c7a7bde7ca17534e8c704e | 2,488 | cs | C# | Edison.Mobile/Edison.Mobile.Admin.Client/Edison.Mobile.Admin.Client.Core/Network/DeviceProvisioningRestService.cs | sysgain/ProjectEdison-1 | b8727361295bb60ba760d019e63d9833fb154938 | [
"MIT"
] | 14 | 2018-10-15T10:00:16.000Z | 2021-01-29T02:31:32.000Z | Edison.Mobile/Edison.Mobile.Admin.Client/Edison.Mobile.Admin.Client.Core/Network/DeviceProvisioningRestService.cs | sysgain/ProjectEdison-1 | b8727361295bb60ba760d019e63d9833fb154938 | [
"MIT"
] | null | null | null | Edison.Mobile/Edison.Mobile.Admin.Client/Edison.Mobile.Admin.Client.Core/Network/DeviceProvisioningRestService.cs | sysgain/ProjectEdison-1 | b8727361295bb60ba760d019e63d9833fb154938 | [
"MIT"
] | 11 | 2019-01-12T17:42:55.000Z | 2019-10-01T13:54:35.000Z | using System;
using System.Threading.Tasks;
using Edison.Mobile.Admin.Client.Core.Ioc;
using Edison.Mobile.Admin.Client.Core.Models;
using Edison.Mobile.Common.Auth;
using Edison.Mobile.Common.Logging;
using Edison.Mobile.Common.Network;
using RestSharp;
namespace Edison.Mobile.Admin.Client.Core.Network
{
public class DeviceProvisioningRestService : BaseRestService, IDeviceProvisioningRestService
{
public DeviceProvisioningRestService(AuthService authService, ILogger logger, string baseUrl)
: base(authService, logger, baseUrl)
{
}
public async Task<DeviceCertificateModel> GenerateDeviceCertificate(DeviceCertificateRequestModel deviceCertificateRequestModel)
{
var request = PrepareRequest("/Certificates", Method.POST, deviceCertificateRequestModel);
var result = await client.ExecutePostTaskAsync<DeviceCertificateModel>(request);
if (result.IsSuccessful)
{
return result.Data;
}
logger.Log($"Error generating device certificate. Status code: {result.StatusCode}, Error Message: {result.ErrorMessage}");
return null;
}
public async Task<DeviceSecretKeysModel> GenerateDeviceKeys(Guid deviceId, string ssidName)
{
var requestObject = new
{
DeviceId = deviceId,
SSIDName = ssidName
};
var request = PrepareRequest("Security", Method.POST, requestObject);
var queryResult = await client.ExecutePostTaskAsync<DeviceSecretKeysModel>(request);
if (queryResult.IsSuccessful)
{
return queryResult.Data;
}
logger.Log($"GenerateDeviceKeys: Error while generating or retrieving device keys: {queryResult.StatusCode}");
return null;
}
public async Task<DeviceSecretKeysModel> GetDeviceKeys(Guid deviceId)
{
RestRequest request = PrepareRequest("Security/{deviceId}", Method.GET);
request.AddUrlSegment("deviceId", deviceId);
var queryResult = await client.ExecuteGetTaskAsync<DeviceSecretKeysModel>(request);
if (queryResult.IsSuccessful)
{
return queryResult.Data;
}
logger.Log($"GetDeviceKeys: Error while retrieving device keys: {queryResult.StatusCode}");
return null;
}
}
}
| 36.057971 | 136 | 0.649518 |
e480b9363291b5d649932497e52ebde0ae67454c | 747 | cs | C# | Bogsi.DatingApp/Bogsi.DatingApp.API/Helpers/UserParameters.cs | simonbogaerts/learn_dotnet_angular | be6e5296e0d2602e05c29b063cb82dcc0d596316 | [
"MIT"
] | null | null | null | Bogsi.DatingApp/Bogsi.DatingApp.API/Helpers/UserParameters.cs | simonbogaerts/learn_dotnet_angular | be6e5296e0d2602e05c29b063cb82dcc0d596316 | [
"MIT"
] | 7 | 2021-03-10T06:04:37.000Z | 2022-03-02T07:10:32.000Z | Bogsi.DatingApp/Bogsi.DatingApp.API/Helpers/UserParameters.cs | simonbogaerts/learn_dotnet_angular | be6e5296e0d2602e05c29b063cb82dcc0d596316 | [
"MIT"
] | null | null | null | // ReSharper disable IdentifierTypo
namespace Bogsi.DatingApp.API.Helpers
{
public class UserParameters
{
private const int MaxPageSize = 50;
public int PageNumber { get; set; } = 1;
private int _pageSize = 10;
public int PageSize
{
get => _pageSize;
set => _pageSize = (value > MaxPageSize) ? MaxPageSize: value;
}
public int UserId { get; set; }
public string Gender { get; set; }
public int MinAge { get; set; } = 18;
public int MaxAge { get; set; } = 99;
public string OrderBy { get; set; }
// Like
public bool Likees { get; set; } = false;
public bool Likers { get; set; } = false;
}
} | 24.096774 | 74 | 0.548862 |
f2431a818e904d0b76026f598a30380bd945f16c | 783 | cs | C# | ParsecSharp/Core/Parser/Implementations/Parser.Resume.cs | acple/ParsecSharp | ccf56ba95b13c4286358ca8f447d55eeafdbf312 | [
"MIT"
] | 20 | 2015-11-28T11:54:47.000Z | 2022-03-31T12:50:05.000Z | ParsecSharp/Core/Parser/Implementations/Parser.Resume.cs | acple/ParsecSharp | ccf56ba95b13c4286358ca8f447d55eeafdbf312 | [
"MIT"
] | null | null | null | ParsecSharp/Core/Parser/Implementations/Parser.Resume.cs | acple/ParsecSharp | ccf56ba95b13c4286358ca8f447d55eeafdbf312 | [
"MIT"
] | 1 | 2021-02-06T05:19:13.000Z | 2021-02-06T05:19:13.000Z | using System;
namespace ParsecSharp.Internal.Parsers
{
internal sealed class Resume<TToken, T> : Parser<TToken, T>
{
private readonly Parser<TToken, T> _parser;
private readonly Func<Failure<TToken, T>, Parser<TToken, T>> _resume;
public Resume(Parser<TToken, T> parser, Func<Failure<TToken, T>, Parser<TToken, T>> resume)
{
this._parser = parser;
this._resume = resume;
}
internal sealed override Result<TToken, TResult> Run<TState, TResult>(TState state, Func<Result<TToken, T>, Result<TToken, TResult>> cont)
{
var resume = this._resume;
return this._parser.Run(state, result => result.CaseOf(failure => resume(failure).Run(state, cont), cont));
}
}
}
| 32.625 | 146 | 0.623244 |
25c0b01498bc6310045d7ed48cb41b2afd75b77a | 2,594 | cs | C# | Core/Models/Instruments/InstrumentOptionModel.cs | Indemos/Terminal-V2 | dd195cf886af7f80fb1afa074d4a9f19d139323a | [
"MIT"
] | 7 | 2021-09-23T14:50:04.000Z | 2022-01-25T09:24:24.000Z | Core/Models/Instruments/InstrumentOptionModel.cs | Indemos/Terminal-V2 | dd195cf886af7f80fb1afa074d4a9f19d139323a | [
"MIT"
] | null | null | null | Core/Models/Instruments/InstrumentOptionModel.cs | Indemos/Terminal-V2 | dd195cf886af7f80fb1afa074d4a9f19d139323a | [
"MIT"
] | 1 | 2021-03-30T12:59:18.000Z | 2021-03-30T12:59:18.000Z | using System;
using Core.EnumSpace;
using FluentValidation;
namespace Core.ModelSpace
{
/// <summary>
/// Definition
/// </summary>
public interface IInstrumentOptionModel : IInstrumentModel
{
/// <summary>
/// Contract size
/// </summary>
double? Leverage { get; set; }
/// <summary>
/// Open interest
/// </summary>
double? OpenInterest { get; set; }
/// <summary>
/// Strike price
/// </summary>
double? Strike { get; set; }
/// <summary>
/// The name of the underlying instrument
/// </summary>
string Symbol { get; set; }
/// <summary>
/// CALL or PUT
/// </summary>
OptionSideEnum? Side { get; set; }
/// <summary>
/// Expiration date
/// </summary>
DateTime? ExpirationDate { get; set; }
/// <summary>
/// Reference to the complex data point
/// </summary>
IPointBarModel Bar { get; set; }
}
/// <summary>
/// Implementation
/// </summary>
public class InstrumentOptionModel : InstrumentModel, IInstrumentOptionModel
{
/// <summary>
/// Contract size
/// </summary>
public virtual double? Leverage { get; set; }
/// <summary>
/// Open interest
/// </summary>
public virtual double? OpenInterest { get; set; }
/// <summary>
/// Strike price
/// </summary>
public virtual double? Strike { get; set; }
/// <summary>
/// The name of the underlying instrument
/// </summary>
public virtual string Symbol { get; set; }
/// <summary>
/// CALL or PUT
/// </summary>
public virtual OptionSideEnum? Side { get; set; }
/// <summary>
/// Expiration date
/// </summary>
public virtual DateTime? ExpirationDate { get; set; }
/// <summary>
/// Reference to the complex data point
/// </summary>
public virtual IPointBarModel Bar { get; set; }
/// <summary>
/// Constructor
/// </summary>
public InstrumentOptionModel()
{
Leverage = 100;
Bar = new PointBarModel();
}
}
/// <summary>
/// Validation rules
/// </summary>
public class InstrumentOptionValidation : AbstractValidator<IInstrumentOptionModel>
{
public InstrumentOptionValidation()
{
RuleFor(o => o.Side).NotNull().WithMessage("No side");
RuleFor(o => o.Strike).NotNull().NotEqual(0).WithMessage("No strike");
RuleFor(o => o.ExpirationDate).NotNull().WithMessage("No expiration date");
}
}
}
| 23.369369 | 86 | 0.557826 |
6e37f3d3758881d515dbeb05ae784544d6c3075c | 3,616 | cs | C# | nMQTTTests/MessageComponents/VariableHeader/MqttConnectFlagTests.cs | huguoya/nmqtt | 1b10f0ee7f7b119ed063c8ab9ee997166ad8c412 | [
"MIT"
] | 1 | 2020-12-09T05:46:09.000Z | 2020-12-09T05:46:09.000Z | nMQTTTests/MessageComponents/VariableHeader/MqttConnectFlagTests.cs | huguoya/nmqtt | 1b10f0ee7f7b119ed063c8ab9ee997166ad8c412 | [
"MIT"
] | null | null | null | nMQTTTests/MessageComponents/VariableHeader/MqttConnectFlagTests.cs | huguoya/nmqtt | 1b10f0ee7f7b119ed063c8ab9ee997166ad8c412 | [
"MIT"
] | null | null | null | /*
* nMQTT, a .Net MQTT v3 client implementation.
* http://wiki.github.com/markallanson/nmqtt
*
* Copyright (c) 2009 Mark Allanson (mark@markallanson.net) & Contributors
*
* Licensed under the MIT License. You may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Nmqtt;
using System.IO;
namespace NmqttTests.MessageComponents.VariableHeader
{
public class MqttConnectFlagTests
{
[Fact]
public void MqttConnectFlags_WillQos_AtMostOnce()
{
Assert.Equal<MqttQos>(MqttQos.AtMostOnce, GetConnectFlags(0).WillQos);
}
[Fact]
public void MqttConnectFlags_WillQos_AtLeastOnce()
{
Assert.Equal<MqttQos>(MqttQos.AtLeastOnce, GetConnectFlags(8).WillQos);
}
[Fact]
public void MqttConnectFlags_WillQos_ExactlyOnce()
{
Assert.Equal<MqttQos>(MqttQos.ExactlyOnce, GetConnectFlags(16).WillQos);
}
[Fact]
public void MqttConnectFlags_WillQos_Reserved1()
{
Assert.Equal<MqttQos>(MqttQos.Reserved1, GetConnectFlags(24).WillQos);
}
[Fact]
public void MqttConnectFlags_Reserved1_true()
{
Assert.True(GetConnectFlags(1).Reserved1);
}
[Fact]
public void MqttConnectFlags_Reserved1_false()
{
Assert.False(GetConnectFlags(0).Reserved1);
}
[Fact]
public void MqttConnectFlags_PasswordFlag_true()
{
Assert.True(GetConnectFlags(64).PasswordFlag);
}
[Fact]
public void MqttConnectFlags_PasswordFlag_false()
{
Assert.False(GetConnectFlags(0).PasswordFlag);
}
[Fact]
public void MqttConnectFlags_UsernameFlag_true()
{
Assert.True(GetConnectFlags(128).UsernameFlag);
}
[Fact]
public void MqttConnectFlags_UsernameFlag_false()
{
Assert.False(GetConnectFlags(0).UsernameFlag);
}
[Fact]
public void MqttConnectFlags_CleanStart_true()
{
Assert.True(GetConnectFlags(2).CleanStart);
}
[Fact]
public void MqttConnectFlags_CleanStart_false()
{
Assert.False(GetConnectFlags(1).CleanStart);
}
[Fact]
public void MqttConnectFlags_WillRetain_true()
{
Assert.True(GetConnectFlags(32).WillRetain);
}
[Fact]
public void MqttConnectFlags_WillRetain_false()
{
Assert.False(GetConnectFlags(1).WillRetain);
}
[Fact]
public void MqttConnectFlags_WillFlag_true()
{
Assert.True(GetConnectFlags(4).WillFlag);
}
[Fact]
public void MqttConnectFlags_WillFlag_false()
{
Assert.False(GetConnectFlags(1).WillFlag);
}
/// <summary>
/// Gets the connect flags for a specific byte value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private MqttConnectFlags GetConnectFlags(byte value)
{
using (MemoryStream stream = new MemoryStream())
{
stream.WriteByte(value);
stream.Seek(0, SeekOrigin.Begin);
return new MqttConnectFlags(stream);
}
}
}
}
| 26.202899 | 84 | 0.593197 |
8021952aa76c51648e45076d4a0555637fcfc37a | 357 | cs | C# | src/Ray.Core/Storage/Configuration/IStorageOptions.cs | ElanHasson/Ray | 06a1331aef53f87479bb5281cfa5079f5f20cfd1 | [
"MIT"
] | 3 | 2020-01-27T02:36:56.000Z | 2020-07-26T15:23:29.000Z | src/Ray.Core/Storage/Configuration/IStorageOptions.cs | ElanHasson/Ray | 06a1331aef53f87479bb5281cfa5079f5f20cfd1 | [
"MIT"
] | null | null | null | src/Ray.Core/Storage/Configuration/IStorageOptions.cs | ElanHasson/Ray | 06a1331aef53f87479bb5281cfa5079f5f20cfd1 | [
"MIT"
] | 2 | 2020-01-27T02:36:57.000Z | 2021-06-17T14:36:36.000Z | using System.Threading.Tasks;
namespace Ray.Core.Storage
{
public interface IStorageOptions
{
/// <summary>
/// 是否是单实例
/// </summary>
bool Singleton { get; set; }
/// <summary>
/// 唯一名称,一般可以使用Grain的名称
/// </summary>
string UniqueName { get; set; }
ValueTask Build();
}
}
| 19.833333 | 39 | 0.518207 |
0d15fe3593d14724d6e7703333808b3f3fe0e1ba | 946 | cs | C# | ExtUnit.Tests/TryTests.cs | colethecoder/ExtUnit | ab63cdccf363b026216c9574354202bad805cac5 | [
"MIT"
] | null | null | null | ExtUnit.Tests/TryTests.cs | colethecoder/ExtUnit | ab63cdccf363b026216c9574354202bad805cac5 | [
"MIT"
] | null | null | null | ExtUnit.Tests/TryTests.cs | colethecoder/ExtUnit | ab63cdccf363b026216c9574354202bad805cac5 | [
"MIT"
] | null | null | null | using LanguageExt;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Xunit.Sdk;
namespace ExtUnit.Tests
{
public class TryTests
{
private Try<string> SampleFail() => () =>
throw new NotImplementedException();
private Try<string> SampleSome() => () =>
"1234";
[Fact]
public void Fail_Passes() =>
Assert.Fail(SampleFail());
[Fact]
public void Fail_WithExceptionType_Passes() =>
Assert.Fail<string, NotImplementedException>(SampleFail());
[Fact]
public void Fail_WithIncorrectExceptionType_Fails() =>
Assert.Throws<FailException>(
() => Assert.Fail<string, NullReferenceException>(SampleFail()));
[Fact]
public void Fail_WithValue_Fails() =>
Assert.Throws<FailException>(
() => Assert.Fail(SampleSome()));
}
}
| 25.567568 | 81 | 0.593023 |
427a93da488ab6bd1c44410adea02c26042d2164 | 3,567 | cs | C# | src/Inshapardaz.Database.SqlServer/Repositories/DatabaseFileStorage.cs | inshapardaz/inshapardaz | 98bac0f125cd1b81584402754c818a2213b74386 | [
"Apache-2.0"
] | null | null | null | src/Inshapardaz.Database.SqlServer/Repositories/DatabaseFileStorage.cs | inshapardaz/inshapardaz | 98bac0f125cd1b81584402754c818a2213b74386 | [
"Apache-2.0"
] | null | null | null | src/Inshapardaz.Database.SqlServer/Repositories/DatabaseFileStorage.cs | inshapardaz/inshapardaz | 98bac0f125cd1b81584402754c818a2213b74386 | [
"Apache-2.0"
] | null | null | null | using Dapper;
using Inshapardaz.Domain.Repositories;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Inshapardaz.Database.SqlServer.Repositories
{
public class DatabaseFileStorage : IFileStorage
{
private readonly IProvideConnection _connectionProvider;
public bool SupportsPublicLink => false;
public DatabaseFileStorage(IProvideConnection connectionProvider)
{
_connectionProvider = connectionProvider;
}
public async Task DeleteFile(string filePath, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"Delete From [FileData] Where Path = @Path";
var command = new CommandDefinition(sql, new { Path = filePath }, cancellationToken: cancellationToken);
await connection.ExecuteAsync(command);
}
}
public Task DeleteImage(string filePath, CancellationToken cancellationToken)
{
return DeleteFile(filePath, cancellationToken);
}
public async Task<byte[]> GetFile(string filePath, CancellationToken cancellationToken)
{
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"Select [content]
From [FileData]
Where Path = @Path";
var command = new CommandDefinition(sql, new { Path = filePath }, cancellationToken: cancellationToken);
return await connection.QuerySingleOrDefaultAsync<byte[]>(command);
}
}
public async Task<string> GetTextFile(string filePath, CancellationToken cancellationToken)
{
var content = await GetFile(filePath, cancellationToken);
return System.Text.Encoding.Default.GetString(content);
}
public async Task<string> StoreFile(string name, byte[] content, CancellationToken cancellationToken)
{
var path = $"{Guid.NewGuid():N}/{name}";
using (var connection = _connectionProvider.GetConnection())
{
var sql = @"Insert Into [FileData] (Path, Content)
VALUES (@Path, @Content)"; ;
var command = new CommandDefinition(sql, new { Path = path, Content = content }, cancellationToken: cancellationToken);
await connection.ExecuteAsync(command);
}
return path;
}
public Task<string> StoreImage(string name, byte[] content, string mimeType, CancellationToken cancellationToken)
{
return StoreFile(name, content, cancellationToken);
}
public Task<string> StoreTextFile(string name, string content, CancellationToken cancellationToken)
{
return StoreFile(name, System.Text.Encoding.Default.GetBytes(content), cancellationToken);
}
public async Task TryDeleteFile(string filePath, CancellationToken cancellationToken)
{
try
{
await DeleteFile(filePath, cancellationToken);
}
finally
{
}
}
public Task TryDeleteImage(string filePath, CancellationToken cancellationToken)
{
return DeleteFile(filePath, cancellationToken);
}
public string GetPublicUrl(string filePath)
{
return filePath;
}
}
}
| 35.67 | 135 | 0.610877 |
42ec2b15454af637fbd22670772203846ee0255d | 1,210 | cs | C# | Hinode.Izumi.Services/EmoteService/Commands/DeleteOlderEmotesCommand.cs | envyvox/Hinode.Izumi | fdc5f1bacb9e050d09f9b756ddd81f232bf3d99b | [
"MIT"
] | 1 | 2021-07-27T16:26:01.000Z | 2021-07-27T16:26:01.000Z | Hinode.Izumi.Services/EmoteService/Commands/DeleteOlderEmotesCommand.cs | evkkxo/Hinode.Izumi | fdc5f1bacb9e050d09f9b756ddd81f232bf3d99b | [
"MIT"
] | null | null | null | Hinode.Izumi.Services/EmoteService/Commands/DeleteOlderEmotesCommand.cs | evkkxo/Hinode.Izumi | fdc5f1bacb9e050d09f9b756ddd81f232bf3d99b | [
"MIT"
] | null | null | null | using System;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using Hinode.Izumi.Framework.Database;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using CacheExtensions = Hinode.Izumi.Services.Extensions.CacheExtensions;
namespace Hinode.Izumi.Services.EmoteService.Commands
{
public record DeleteOlderEmotesCommand(DateTimeOffset DateTimeOffset) : IRequest;
public class DeleteOlderEmotesHandler : IRequestHandler<DeleteOlderEmotesCommand>
{
private readonly IConnectionManager _con;
private readonly IMemoryCache _cache;
public DeleteOlderEmotesHandler(IConnectionManager con, IMemoryCache cache)
{
_con = con;
_cache = cache;
}
public async Task<Unit> Handle(DeleteOlderEmotesCommand request, CancellationToken cancellationToken)
{
await _con
.GetConnection()
.ExecuteAsync(@"
delete from emotes
where updated_at < @dateTime",
new {dateTime = request.DateTimeOffset});
_cache.Remove(CacheExtensions.EmotesKey);
return new Unit();
}
}
}
| 30.25 | 109 | 0.666942 |
1176c144ba0293ac87bae6cc482a7720961676e0 | 7,524 | cs | C# | Sds.Osdr.WebApi/DataProviders/OrganizeDataProvider.cs | scidatasoft/osdr-core | cbfd96f6a9dc2900744c18330ac9842475075b7e | [
"MIT"
] | null | null | null | Sds.Osdr.WebApi/DataProviders/OrganizeDataProvider.cs | scidatasoft/osdr-core | cbfd96f6a9dc2900744c18330ac9842475075b7e | [
"MIT"
] | 1 | 2019-11-05T20:02:20.000Z | 2019-11-05T20:02:20.000Z | Sds.Osdr.WebApi/DataProviders/OrganizeDataProvider.cs | ArqiSoft/leanda-core | 4095d3667cdbd728d5cc615ff8cd3aeceaa59843 | [
"MIT"
] | 2 | 2018-12-22T13:48:33.000Z | 2019-02-16T02:17:50.000Z | using MongoDB.Bson;
using MongoDB.Driver;
using Sds.Osdr.Generic.Domain.ValueObjects;
using Sds.Osdr.WebApi.Extensions;
using Sds.Osdr.WebApi.Models;
using Sds.Storage.Blob.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sds.Osdr.WebApi.DataProviders
{
public class OrganizeDataProvider : IOrganizeDataProvider
{
readonly IMongoDatabase _database;
readonly IMongoCollection<BsonDocument> _nodes;
readonly IBlobStorage _blobStorage;
readonly FilterDefinition<BsonDocument> _filterBase = Builders<BsonDocument>.Filter.Ne("IsDeleted", true);
readonly FilterDefinitionBuilder<BsonDocument> _builder = Builders<BsonDocument>.Filter;
//BsonDocument _filter = new BsonDocument("IsDeleted", new BsonDocument("$ne", true));
public OrganizeDataProvider(IMongoDatabase database, IBlobStorage blobStorage)
{
_database = database ?? throw new ArgumentNullException(nameof(database));
_nodes = _database.GetCollection<BsonDocument>("Nodes");
_blobStorage = blobStorage;
}
private IMongoCollection<BsonDocument> GetEntitiesCollection(string entityType)
{
return _database.GetCollection<BsonDocument>(entityType);
}
public IEnumerable<BaseNode> GetBreadcrumbs(Guid itemId)
{
var filter = _filterBase & _builder.Eq("_id", itemId);
var parents = _nodes.Aggregate().Match(filter)
.GraphLookup(_nodes, "ParentId", "_id", "$ParentId", "Parent")
.Unwind("Parent")
.ReplaceRoot<BaseNode>("$Parent")
.ToList();
if (parents.Count() > 0)
{
var result = new List<BaseNode>();
var it = parents.First(p => p.Type == "User");
do
{
result.Add(it);
it = parents.FirstOrDefault(p => p.ParentId == it.Id);
} while (it != null);
return result;
}
else
{
return parents;
}
}
public bool IsItemAccessible(Guid itemId, Guid? userId = null)
{
if (IsItemExistAndHasPermissions(itemId, userId))
return true;
var breadCrumbs = GetBreadcrumbs(itemId);
foreach (var item in breadCrumbs)
if (IsItemExistAndHasPermissions(item.Id, userId))
return true;
return false;
}
private bool IsItemExistAndHasPermissions(Guid itemId, Guid? userId = null)
{
var filter = _filterBase & _builder.Eq("_id", itemId);
var permissions = _nodes.Aggregate().Match(filter)
.Lookup<BsonDocument, BsonDocument>(nameof(AccessPermissions), "_id", "_id", nameof(AccessPermissions))
.Unwind(nameof(AccessPermissions), new AggregateUnwindOptions<BsonDocument> { PreserveNullAndEmptyArrays = true })
.Project("{AccessPermissions:1, OwnedBy:1}")
.FirstOrDefault();
if (permissions != null)
{
if (permissions.Contains("AccessPermissions") && (permissions["AccessPermissions"]["IsPublic"].AsNullableBoolean ?? false))
return true;
if (permissions.Contains("OwnedBy") && (permissions["OwnedBy"].AsGuid == userId))
return true;
if (permissions["_id"].AsGuid == userId)
return true;
return false;
}
else
return false;
}
public PagedList<dynamic> GetSharedNodes(Guid userId, int pageNumber = 1, int pageSize = 20, bool isPublicOnly = false)
{
var filter = _filterBase & _builder.Eq("OwnedBy", userId) & _builder.Or(
_builder.Eq("AccessPermissions.IsPublic", true),
_builder.Not(_builder.Size("AccessPermissions.Users",0)),
_builder.Not(_builder.Size("AccessPermissions.Groups",0))
);
if (isPublicOnly)
filter = filter & _builder.Eq("AccessPermissions.IsPublic", true);
var nodes = _nodes.Aggregate()
.Lookup<BsonDocument, BsonDocument>(nameof(AccessPermissions), "_id", "_id", nameof(AccessPermissions))
.Unwind<dynamic>(nameof(AccessPermissions))
.Match(filter.Render(_nodes.DocumentSerializer, _nodes.Settings.SerializerRegistry));
return PagedList(nodes, pageNumber, pageSize);
}
private PagedList<TProjection> PagedList<TProjection>(IAggregateFluent<TProjection> findFluent, int pageNumber, int pageSize)
{
var count = findFluent.Any() ? findFluent.Group(new BsonDocument
{
{ "_id", "_id" },
{"count", new BsonDocument("$sum", 1)}
})
.FirstAsync().Result["count"].AsInt32 : 0;
var items = findFluent.Skip(pageSize * (pageNumber - 1))
.Limit(pageSize)
.ToList();
return new PagedList<TProjection>(items, count, pageNumber, pageSize);
}
public async Task<IBlob> GetEntityImageAsync(string itemType, Guid itemId, Guid imageId)
{
var filter = _filterBase & _builder.Eq("_id", itemId) & _builder.Eq("Images._id", imageId);
var imageInfo = _database.GetCollection<BsonDocument>(itemType.ToPascalCase()).Aggregate().Match(filter)
.Project("{Images:1}")
.Unwind("Images")
.ReplaceRoot<BsonDocument>("$Images")
.FirstOrDefault();
if (imageInfo != null)
return await _blobStorage.GetFileAsync(imageId, imageInfo["Bucket"].AsString);
else
return null;
}
public async Task<(IBlob blob, string osdrFileName)> GetEntityBlobAsync(string itemType, Guid itemId, Guid blobId)
{
var filter = _filterBase & _builder.Eq("_id", itemId) & _builder.Or(
_builder.Eq("Blob._id", blobId),
_builder.Eq("Pdf.BlobId", blobId)); //TODO: should be refactoring !!!!!
var blobInfo = _database.GetCollection<BsonDocument>(itemType.ToPascalCase()).Aggregate().Match(filter)
.Project("{Blob:1, Name:1}")
.FirstOrDefault();
return blobInfo != null ? (await _blobStorage.GetFileAsync(blobId, blobInfo["Blob"]["Bucket"].AsString), blobInfo["Name"].AsString) : (null, string.Empty);
}
public async Task<object> GetInfoboxMetadataAsync(string entityType, Guid entityId, string infoboxType)
{
var filter = new BsonDocument("InfoBoxType", infoboxType);
if (infoboxType.Equals("fields", StringComparison.InvariantCultureIgnoreCase))
filter.Add("FileId", entityId);
return await _database.GetCollection<dynamic>("Metadata").Find(filter).SingleOrDefaultAsync().ConfigureAwait(false);
}
public async Task<object> GetEntityMetadataAsync(string entityType, Guid entityId)
{
var filter = new BsonDocument("_id", entityId);
return await _database.GetCollection<dynamic>("Metadata").Find(filter).SingleOrDefaultAsync().ConfigureAwait(false);
}
}
}
| 40.021277 | 167 | 0.593966 |
f742739ee242bba86d8fe6fd6c99e8a76d2fa649 | 2,355 | cs | C# | src/BinarySerializer.Ray1/DataTypes/PS1/ALPHA/PS1_FontData.cs | BinarySerializer/BinarySerializer.Ray1 | 27a1eb4a277e5d304ce5fd6ce3b1baf4522c5a4c | [
"MIT"
] | null | null | null | src/BinarySerializer.Ray1/DataTypes/PS1/ALPHA/PS1_FontData.cs | BinarySerializer/BinarySerializer.Ray1 | 27a1eb4a277e5d304ce5fd6ce3b1baf4522c5a4c | [
"MIT"
] | null | null | null | src/BinarySerializer.Ray1/DataTypes/PS1/ALPHA/PS1_FontData.cs | BinarySerializer/BinarySerializer.Ray1 | 27a1eb4a277e5d304ce5fd6ce3b1baf4522c5a4c | [
"MIT"
] | null | null | null | namespace BinarySerializer.Ray1
{
public class PS1_FontData : BinarySerializable
{
public Pointer SpritesPointer { get; set; }
public Pointer ImageBufferPointer { get; set; }
public byte SpritesCount { get; set; }
public SpriteCollection SpriteCollection { get; set; }
public byte[] ImageBuffer { get; set; }
/// <summary>
/// Handles the data serialization
/// </summary>
/// <param name="s">The serializer object</param>
public override void SerializeImpl(SerializerObject s)
{
var settings = s.GetSettings<Ray1Settings>();
SpritesPointer = s.SerializePointer(SpritesPointer, name: nameof(SpritesPointer));
ImageBufferPointer = s.SerializePointer(ImageBufferPointer, allowInvalid: true, name: nameof(ImageBufferPointer));
SpritesCount = s.Serialize<byte>(SpritesCount, name: nameof(SpritesCount));
s.SerializePadding(3);
s.DoAt(SpritesPointer, () => SpriteCollection = s.SerializeObject<SpriteCollection>(SpriteCollection, x => x.Pre_SpritesCount = SpritesCount, name: nameof(SpriteCollection)));
if (settings.EngineVersion == Ray1EngineVersion.PS1_JPDemoVol3)
{
if (ImageBuffer == null && ImageBufferPointer != null && SpriteCollection != null)
{
// Determine length of image buffer
uint length = 0;
foreach (Sprite img in SpriteCollection.Sprites)
{
if (img.ImageType != 2 && img.ImageType != 3)
continue;
uint curLength = img.ImageBufferOffset;
if (img.ImageType == 2)
curLength += (uint)(img.Width / 2) * img.Height;
else if (img.ImageType == 3)
curLength += (uint)img.Width * img.Height;
if (curLength > length)
length = curLength;
}
ImageBuffer = new byte[length];
}
s.DoAt(ImageBufferPointer, () => ImageBuffer = s.SerializeArray<byte>(ImageBuffer, ImageBuffer.Length, name: nameof(ImageBuffer)));
}
}
}
} | 43.611111 | 187 | 0.549894 |
f7d7cbc29cbeeac64997f047d737288c7e71dad2 | 929 | cs | C# | UOP1_Project/Assets/Scripts/Characters/StateMachine/Actions/GroundGravityActionSO.cs | BourdonValentin/open-project-1 | 50afacc1d619bc9e62e67befc7f3223a0e5f0603 | [
"Apache-2.0"
] | 4 | 2021-03-07T08:42:38.000Z | 2022-01-22T16:14:32.000Z | UOP1_Project/Assets/Scripts/Characters/StateMachine/Actions/GroundGravityActionSO.cs | BourdonValentin/open-project-1 | 50afacc1d619bc9e62e67befc7f3223a0e5f0603 | [
"Apache-2.0"
] | null | null | null | UOP1_Project/Assets/Scripts/Characters/StateMachine/Actions/GroundGravityActionSO.cs | BourdonValentin/open-project-1 | 50afacc1d619bc9e62e67befc7f3223a0e5f0603 | [
"Apache-2.0"
] | 1 | 2021-08-09T04:48:29.000Z | 2021-08-09T04:48:29.000Z | using UnityEngine;
using UOP1.StateMachine;
using UOP1.StateMachine.ScriptableObjects;
[CreateAssetMenu(fileName = "GroundGravity", menuName = "State Machines/Actions/Ground Gravity")]
public class GroundGravityActionSO : StateActionSO
{
[Tooltip("Vertical movement pulling down the player to keep it anchored to the ground.")]
[SerializeField] private float _verticalPull = -5f;
protected override StateAction CreateAction() => new GroundGravityAction(_verticalPull);
}
public class GroundGravityAction : StateAction
{
//Component references
private Protagonist _protagonistScript;
private float _verticalPull;
public GroundGravityAction(float slideSpeed)
{
_verticalPull = slideSpeed;
}
public override void Awake(StateMachine stateMachine)
{
_protagonistScript = stateMachine.GetComponent<Protagonist>();
}
public override void OnUpdate()
{
_protagonistScript.movementVector.y = _verticalPull;
}
}
| 25.805556 | 97 | 0.795479 |
9e85b76a84c3fb66f32771ca425789962659dd98 | 2,434 | cs | C# | Assets/Scripts/TeleportMenuPage.cs | ModU-VR-Org/RoleplayU | bfd8463ed914840b25b75b7f4eb2bf60357f4181 | [
"MIT"
] | 30 | 2019-02-25T20:28:36.000Z | 2021-09-22T05:16:20.000Z | Assets/Scripts/TeleportMenuPage.cs | Vytek/RoleplayU | bfd8463ed914840b25b75b7f4eb2bf60357f4181 | [
"MIT"
] | null | null | null | Assets/Scripts/TeleportMenuPage.cs | Vytek/RoleplayU | bfd8463ed914840b25b75b7f4eb2bf60357f4181 | [
"MIT"
] | 3 | 2019-02-26T15:41:10.000Z | 2021-01-30T05:52:00.000Z | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Realtime;
using Photon.Pun;
public class TeleportMenuPage : MenuPageBase
{
public GameObject teleportPlayerButtonsPrefab; // prefab for the menu item that has player name and buttons for DM to select movement options
public List<Transform> teleportPlayerMenuTransforms; //list of transforms attached to menu in correct location for buttons to be
private List<GameObject> teleportMenuButtonPool = new List<GameObject>();
public override void OnEnable()
{
base.OnEnable();
InitializeTeleportMenu();
TeleportToolActivate();
}
public void InitializeTeleportMenu()
{
// Teleport buttons Object Pool
for (int i = 0; i < teleportPlayerMenuTransforms.Count; i++)
{
GameObject teleportPlayerMenuObject = Instantiate(teleportPlayerButtonsPrefab, teleportPlayerMenuTransforms[i].position, transform.rotation);
teleportPlayerMenuObject.transform.SetParent(gameObject.transform);
teleportMenuButtonPool.Add(teleportPlayerMenuObject);
}
}
public void TeleportToolActivate()
{
menuManager.SetScrollButtonsActive(false);
//TODO: CURRENTLY DOES NOT HANDLE MORE THAN 4 PLAYERS, DOES NOT REFRESH (list of players) WITHOUT BACKING OUT OF MENU.
Player[] playerList = PhotonNetwork.PlayerList;
for (int i = 0; i < teleportMenuButtonPool.Count; i++)
{
if (i < playerList.Length)
{
int actorNumber = playerList[i].ActorNumber;
string username = (string)playerList[i].CustomProperties["username"];
teleportMenuButtonPool[i].GetComponent<TeleportMenuButtons>().InitializeTeleportMenuButtons(actorNumber, username);
teleportMenuButtonPool[i].SetActive(true);
}
else
{
teleportMenuButtonPool[i].SetActive(false);
}
}
}
public void UpdateTeleportMenu(int actorId)
{
foreach (var menuItem in teleportMenuButtonPool)
{
if (menuItem.GetComponent<TeleportMenuButtons>().actorId == actorId)
{
menuItem.GetComponent<TeleportMenuButtons>().DeactivateSingleTeleportToggle();
}
}
}
} | 38.634921 | 154 | 0.645029 |
b2338cb0aadc3ec0bed4a007fa0b851e188fc437 | 663 | cs | C# | BTDB/KVDBLayer/Implementation/KeyValueDBOptions.cs | miroslavpokorny/BTDB | 0b1f327f63027e85e008115814ef96b3a8f6cde8 | [
"MIT"
] | null | null | null | BTDB/KVDBLayer/Implementation/KeyValueDBOptions.cs | miroslavpokorny/BTDB | 0b1f327f63027e85e008115814ef96b3a8f6cde8 | [
"MIT"
] | null | null | null | BTDB/KVDBLayer/Implementation/KeyValueDBOptions.cs | miroslavpokorny/BTDB | 0b1f327f63027e85e008115814ef96b3a8f6cde8 | [
"MIT"
] | null | null | null | using BTDB.Allocators;
namespace BTDB.KVDBLayer
{
public class KeyValueDBOptions
{
public IFileCollection? FileCollection;
public ICompressionStrategy? Compression = new SnappyCompressionStrategy();
public uint FileSplitSize = int.MaxValue;
public ICompactorScheduler? CompactorScheduler = KVDBLayer.CompactorScheduler.Instance;
public ulong? OpenUpToCommitUlong;
public ulong? PreserveHistoryUpToCommitUlong;
public ulong? CompactorReadBytesPerSecondLimit;
public ulong? CompactorWriteBytesPerSecondLimit;
public IOffHeapAllocator? Allocator;
public bool ReadOnly;
}
}
| 34.894737 | 95 | 0.737557 |
6c9763fb27922b6e89c14051474bb8fcc736ac58 | 1,110 | cs | C# | src/Demo.Infrastructure/Events/Extensions.cs | nvdvlies/dotnet-api-and-angular-frontend | 78a73954b2a8cd58209fcb13b3e88bd2afaa22dd | [
"MIT"
] | null | null | null | src/Demo.Infrastructure/Events/Extensions.cs | nvdvlies/dotnet-api-and-angular-frontend | 78a73954b2a8cd58209fcb13b3e88bd2afaa22dd | [
"MIT"
] | null | null | null | src/Demo.Infrastructure/Events/Extensions.cs | nvdvlies/dotnet-api-and-angular-frontend | 78a73954b2a8cd58209fcb13b3e88bd2afaa22dd | [
"MIT"
] | null | null | null | using System.Reflection;
using System.Text.Json;
using Demo.Events;
namespace Demo.Infrastructure.Events
{
internal static class Extensions
{
public static RabbitMqEvent ToRabbitMqEvent(this IEvent @event)
{
var assembly = typeof(Event<IEvent, IEventData>).Assembly;
var eventType = assembly.GetType(@event.Type);
var payload = JsonSerializer.Serialize(@event, eventType, new JsonSerializerOptions());
return new RabbitMqEvent { ContentType = @event.Type, Payload = payload };
}
public static IEvent ToEvent(this RabbitMqEvent rabbitMqEvent)
{
var eventType = typeof(Event<IEvent, IEventData>).Assembly.GetType(rabbitMqEvent.ContentType);
var methodName = nameof(Event<IEvent, IEventData>.FromJson);
var method = eventType.GetMethod(methodName,
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
var @event = method.Invoke(null, new object[] { rabbitMqEvent.Payload });
return (IEvent)@event;
}
}
}
| 39.642857 | 106 | 0.66036 |
6726a42677b27bfff128d9be3c0b2a99fb4b7a90 | 69 | cs | C# | SimulatorBox/App.xaml.cs | BWalti/JuniorGamesCore | e651a8ab4aa3ef565028d0190c82cd712bf30e44 | [
"MIT"
] | null | null | null | SimulatorBox/App.xaml.cs | BWalti/JuniorGamesCore | e651a8ab4aa3ef565028d0190c82cd712bf30e44 | [
"MIT"
] | null | null | null | SimulatorBox/App.xaml.cs | BWalti/JuniorGamesCore | e651a8ab4aa3ef565028d0190c82cd712bf30e44 | [
"MIT"
] | null | null | null | namespace SimulatorBox
{
public partial class App
{
}
}
| 9.857143 | 28 | 0.608696 |
67c3916f8c1dabac63b745ae6e387eca1f273e13 | 3,448 | cs | C# | KernX.EventBus.RabbitMQ/RabbitMQEventBus.cs | joffarex/KernX | bb85d6a666d51641ca6ef34f733b989e6ba72e78 | [
"Apache-2.0"
] | null | null | null | KernX.EventBus.RabbitMQ/RabbitMQEventBus.cs | joffarex/KernX | bb85d6a666d51641ca6ef34f733b989e6ba72e78 | [
"Apache-2.0"
] | null | null | null | KernX.EventBus.RabbitMQ/RabbitMQEventBus.cs | joffarex/KernX | bb85d6a666d51641ca6ef34f733b989e6ba72e78 | [
"Apache-2.0"
] | null | null | null | using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace KernX.EventBus.RabbitMQ
{
public sealed class RabbitMQEventBus : IEventBus, IDisposable
{
private readonly IConnection _connection;
private readonly ConnectionFactory _connectionFactory;
private readonly ILogger<RabbitMQEventBus> _logger;
private IModel _consumerChannel;
public RabbitMQEventBus(ILogger<RabbitMQEventBus> logger, RabbitMQSettings settings)
{
_logger = logger;
var connectionString =
$"amqp://{settings.Username}:{settings.Password}@{settings.Host}:{settings.Port}/{settings.VHost}";
_connectionFactory = new ConnectionFactory
{
Uri = new Uri(connectionString),
DispatchConsumersAsync = true
};
_connection = _connectionFactory.CreateConnection();
}
public void Dispose()
{
_connection.Dispose();
}
public Task Publish<T>(string topic, string appId, T @event) where T : IEvent
{
using IModel channel = _connection.CreateModel();
IBasicProperties properties = GetMessageProperties(channel, appId);
byte[] body = Encoding.UTF8.GetBytes(@event.Stringify());
channel.BasicPublish(topic, string.Empty, properties, body);
_logger.LogInformation($"Sent Message: {body}");
return Task.CompletedTask;
}
public Task Subscribe<T>(string queue, Func<EventHeaders, T, Task> callback)
{
_consumerChannel = _connection.CreateModel();
_consumerChannel.BasicQos(0, 1, false);
_consumerChannel.CallbackException += ReceivedCallbackException;
var consumer = new AsyncEventingBasicConsumer(_consumerChannel);
consumer.Received += async (_, eventArgs) => { await ReceivedCallback(eventArgs, callback); };
_consumerChannel.BasicConsume(queue, false, consumer);
_logger.LogInformation("Press [enter] to exit.");
Console.ReadLine();
return Task.CompletedTask;
}
#region Helpers
private static IBasicProperties GetMessageProperties(IModel channel, string appId)
{
IBasicProperties properties = channel.CreateBasicProperties();
properties.Persistent = true;
properties.Headers = EventHeaders.ToDictionary(appId);
return properties;
}
#endregion
#region Callbacks
private void ReceivedCallbackException(object sender, CallbackExceptionEventArgs eventArgs)
{
_logger.LogError(eventArgs.Exception.ToString());
}
private async Task ReceivedCallback<T>(BasicDeliverEventArgs eventArgs, Func<EventHeaders, T, Task> callback)
{
var eventHeaders = EventHeaders.Create(eventArgs.BasicProperties.Headers);
var message = new Message(eventArgs.Body.Span, eventHeaders);
_logger.LogInformation($"[x] {message.ToString()}");
var parsedMessage = await message.ParseMessage<T>();
await callback(eventHeaders, parsedMessage);
_consumerChannel.BasicAck(eventArgs.DeliveryTag, false);
}
#endregion
}
} | 33.803922 | 117 | 0.641241 |
ecede9b3224a3c92f08a02f174c42d54f0d53d02 | 2,014 | cs | C# | LuxWatch/LuxWatch.Data/Migrations/20220313101832_NaskoMigr.cs | PasPac/LuxWatch | a3eed288081184968fc6bd989ea63d05ed5faa83 | [
"MIT"
] | null | null | null | LuxWatch/LuxWatch.Data/Migrations/20220313101832_NaskoMigr.cs | PasPac/LuxWatch | a3eed288081184968fc6bd989ea63d05ed5faa83 | [
"MIT"
] | null | null | null | LuxWatch/LuxWatch.Data/Migrations/20220313101832_NaskoMigr.cs | PasPac/LuxWatch | a3eed288081184968fc6bd989ea63d05ed5faa83 | [
"MIT"
] | null | null | null | using Microsoft.EntityFrameworkCore.Migrations;
namespace LuxWatch.Data.Migrations
{
public partial class NaskoMigr : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Watches_Categorys_CategoryId",
table: "Watches");
migrationBuilder.DropPrimaryKey(
name: "PK_Categorys",
table: "Categorys");
migrationBuilder.RenameTable(
name: "Categorys",
newName: "Categories");
migrationBuilder.AddPrimaryKey(
name: "PK_Categories",
table: "Categories",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Watches_Categories_CategoryId",
table: "Watches",
column: "CategoryId",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Watches_Categories_CategoryId",
table: "Watches");
migrationBuilder.DropPrimaryKey(
name: "PK_Categories",
table: "Categories");
migrationBuilder.RenameTable(
name: "Categories",
newName: "Categorys");
migrationBuilder.AddPrimaryKey(
name: "PK_Categorys",
table: "Categorys",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Watches_Categorys_CategoryId",
table: "Watches",
column: "CategoryId",
principalTable: "Categorys",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
| 31.46875 | 71 | 0.53575 |
a69ab4c7766ea39926ce5b663ab1861f1973ea95 | 1,040 | cs | C# | InitAvatar/InitAvatar.cs | tmutton/InitAvatar | aee2bc3a6b09d31df0ea27aaacdf7d0e736d3d9c | [
"Apache-2.0"
] | null | null | null | InitAvatar/InitAvatar.cs | tmutton/InitAvatar | aee2bc3a6b09d31df0ea27aaacdf7d0e736d3d9c | [
"Apache-2.0"
] | null | null | null | InitAvatar/InitAvatar.cs | tmutton/InitAvatar | aee2bc3a6b09d31df0ea27aaacdf7d0e736d3d9c | [
"Apache-2.0"
] | null | null | null | using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace InitAvatar
{
public class AvatarInitials: IAvatar
{
private AvatarSettings AvatarSettings;
public AvatarInitials(AvatarSettings avatarSettings)
{
this.AvatarSettings = avatarSettings;
}
public Stream Draw(int width, int height)
{
Stream stream = new MemoryStream();
using (var bitmap = new Bitmap(width, height))
{
using (var graphic = Graphics.FromImage(bitmap))
{
var brush = new SolidBrush(this.AvatarSettings.BackgroundColour);
var rect = new Rectangle(0, 0, width, height);
graphic.FillRectangle(brush, rect);
graphic.Save();
stream.Position = 0;
bitmap.Save(stream, ImageFormat.Jpeg);
return stream;
}
}
}
}
}
| 22.12766 | 85 | 0.528846 |
04201c058cba5672abe5b872c87e379e2f91dc0f | 4,465 | cs | C# | Bakery/Program.cs | RyanDanielWalker/Bakery.Solution | 3f8c89357f38b2150ba248c6065beaadeef4b445 | [
"MIT"
] | null | null | null | Bakery/Program.cs | RyanDanielWalker/Bakery.Solution | 3f8c89357f38b2150ba248c6065beaadeef4b445 | [
"MIT"
] | null | null | null | Bakery/Program.cs | RyanDanielWalker/Bakery.Solution | 3f8c89357f38b2150ba248c6065beaadeef4b445 | [
"MIT"
] | null | null | null | using System;
using Bakery.Models;
using System.Collections.Generic;
namespace CounterProgram
{
class Program
{
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Hello! Welcome to Pierre's Bakery.");
Console.WriteLine("Today's menu prices are:");
Console.WriteLine("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Bread - $5.00 per loaf");
Console.WriteLine("Pastry - $2.00 each");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("We are currently running these specials:");
Console.WriteLine("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Bread: Buy 2 loaves, get 1 free!");
Console.WriteLine("Pastries: 3 for $5!");
OrderType();
}
public static void OrderType()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("What would you like to order? [Bread/Pastry]");
Console.ForegroundColor = ConsoleColor.Blue;
string userOrderChoice = Console.ReadLine().ToLower();
if (userOrderChoice == "bread")
{
OrderBread();
}
else if (userOrderChoice == "pastry")
{
OrderPastry();
}
else
{
Console.WriteLine();
Console.WriteLine("Please enter a valid response");
OrderType();
}
}
public static void OrderBread()
{
try
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("How many loaves of bread would you like?");
Console.ForegroundColor = ConsoleColor.Blue;
string loavesOrderedString = Console.ReadLine();
int loavesOrdered = int.Parse(loavesOrderedString);
Bread userBread = new Bread(loavesOrdered);
}
catch (Exception)
{
Console.WriteLine("Please enter a valid number");
OrderBread();
}
DoNextQuestion();
}
public static void DoNextQuestion()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("Would you like to add to your order? [Yes/No]");
Console.ForegroundColor = ConsoleColor.Blue;
string userAddToOrderAnswer = Console.ReadLine().ToLower();
if (userAddToOrderAnswer == "yes")
{
OrderType();
}
else if (userAddToOrderAnswer == "no")
{
CalculateTotal();
}
else
{
Console.WriteLine("Please enter a valid response");
DoNextQuestion();
}
}
public static void OrderPastry()
{
try
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine("How many pastries would you like?");
Console.ForegroundColor = ConsoleColor.Blue;
string pastriesOrderedString = Console.ReadLine();
int pastriesOrdered = int.Parse(pastriesOrderedString);
Pastry userPastry = new Pastry(pastriesOrdered);
}
catch (Exception)
{
Console.WriteLine("Please enter a valid number");
OrderPastry();
}
DoNextQuestion();
}
public static void CalculateTotal()
{
int breadTotal = 0;
int pastryTotal = 0;
int breadDiscount = 0;
int pastryDiscount = 0;
List<Bread> breadTotalList = Bread.GetAll();
List<Pastry> pastryTotalList = Pastry.GetAll();
foreach (Bread element in breadTotalList)
{
element.CalculateBreadDiscount();
breadDiscount += element.GetBreadDiscount();
breadTotal += element.GetBreadTotal();
}
foreach (Pastry element in pastryTotalList)
{
element.CalculatePastryDiscount();
pastryDiscount += element.GetPastryDiscount();
pastryTotal += element.GetPastryTotal();
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine("Your order total is $" + (breadTotal + pastryTotal) + ".00");
Console.WriteLine("You saved $" + (breadDiscount + pastryDiscount) + ".00");
}
}
} | 32.830882 | 87 | 0.60112 |
09fe91e755382f9699b530c810aec79b7e4dc2f2 | 1,593 | cs | C# | test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs | Twtcer/opencvsharp | f786aebdbbbdef0154b04a8cb958e91119736342 | [
"Apache-2.0"
] | null | null | null | test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs | Twtcer/opencvsharp | f786aebdbbbdef0154b04a8cb958e91119736342 | [
"Apache-2.0"
] | null | null | null | test/OpenCvSharp.Tests/face/LBPHFaceRecognizerTest.cs | Twtcer/opencvsharp | f786aebdbbbdef0154b04a8cb958e91119736342 | [
"Apache-2.0"
] | null | null | null | using System;
using OpenCvSharp.Face;
using Xunit;
using Xunit.Abstractions;
namespace OpenCvSharp.Tests.Face
{
// ReSharper disable once InconsistentNaming
public class LBPHFaceRecognizerTest : TestBase
{
private readonly ITestOutputHelper testOutputHelper;
public LBPHFaceRecognizerTest(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
}
[Fact]
public void CreateAndDispose()
{
var recognizer = LBPHFaceRecognizer.Create(1, 8, 8, 8, 123);
recognizer.Dispose();
}
[Fact]
public void TrainAndPredict()
{
using var image = Image("lenna.png");
using var grayImage = image.CvtColor(ColorConversionCodes.BGR2GRAY);
using var model = LBPHFaceRecognizer.Create();
using var cascade = new CascadeClassifier("_data/text/haarcascade_frontalface_default.xml");
var rects = cascade.DetectMultiScale(image);
model.Train(new[] { grayImage }, new[] { 1 });
foreach (Rect rect in rects)
{
using (Mat face = grayImage[rect].Clone())
{
Cv2.Resize(face, face, new Size(256, 256));
model.Predict(face, out int label, out double confidence);
testOutputHelper.WriteLine($"{label} ({confidence})");
Assert.Equal(1, label);
Assert.NotEqual(0, confidence, 9);
}
}
}
}
}
| 28.963636 | 104 | 0.569994 |
ebc93d865219e8d5fce7b6c2f70b279690a39cfb | 858 | cs | C# | Domain/Application/Models/UserAndReceiverModel.cs | kazenetu/IkenBako | 2173d92f10445a324273e8dbad96f07664af68df | [
"MIT"
] | null | null | null | Domain/Application/Models/UserAndReceiverModel.cs | kazenetu/IkenBako | 2173d92f10445a324273e8dbad96f07664af68df | [
"MIT"
] | 51 | 2021-05-21T13:13:48.000Z | 2022-01-14T14:51:49.000Z | Domain/Application/Models/UserAndReceiverModel.cs | kazenetu/IkenBako | 2173d92f10445a324273e8dbad96f07664af68df | [
"MIT"
] | null | null | null | using Domain.Domain.Receivers;
using Domain.Domain.Users;
namespace Domain.Application.Models
{
/// <summary>
/// ユーザーと受信者の集約モデル
/// </summary>
public class UserAndReceiverModel: UserModel
{
/// <summary>
/// 受信者Model
/// </summary>
public ReceiverModel Receiver { get; private set; } = null;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="user">ユーザーエンティティ</param>
/// <param name="receiver">受信者エンティティ</param>
public UserAndReceiverModel(User user,Receiver receiver) : base(user)
{
if(receiver != null)
{
Receiver = new ReceiverModel(receiver);
}
}
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="user">ユーザーエンティティ</param>
public UserAndReceiverModel(User user) : base(user)
{
}
}
}
| 22.578947 | 74 | 0.56993 |
01b8a17a5fe0f7f69f6acb8c90a3189ec4ae3b60 | 6,796 | cs | C# | SpeakAloud/Form1.cs | shisingh/SpeakAloud | c371b36ff39de66fdc6b13b180ce1b15f31c7356 | [
"MIT"
] | null | null | null | SpeakAloud/Form1.cs | shisingh/SpeakAloud | c371b36ff39de66fdc6b13b180ce1b15f31c7356 | [
"MIT"
] | null | null | null | SpeakAloud/Form1.cs | shisingh/SpeakAloud | c371b36ff39de66fdc6b13b180ce1b15f31c7356 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Automation;
using System.Windows.Forms;
namespace GetWindowsText_Winform
{
public partial class Form1 : Form
{
private const int WM_DRAWCLIPBOARD = 0x0308;
private const int WM_CHANGECBCHAIN = 0x030D;
private const int MOD_ALT = 0x1;
private const int MOD_CONTROL = 0x2;
private const int MOD_SHIFT = 0x4;
private const int MOD_WIN = 0x8;
private const int WM_HOTKEY = 0x312;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWnd);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ChangeClipboardChain(
IntPtr hWndRemove, // handle to window to remove
IntPtr hWndNewNext // handle to next window
);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
IntPtr _clipboardViewerNext = IntPtr.Zero;
private bool _getCopyValue = false;
private bool _hotkeyRegistered = false;
Timer _timer = new Timer();
private delegate void UpdateMsgDel(string msg);
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
RegisterClipboardViewer();
_hotkeyRegistered = RegisterHotKey(this.Handle, 1, MOD_CONTROL, (int)Keys.D1);
if (!_hotkeyRegistered)
{
MessageBox.Show("Error registering hotkey");
}
_timer.Tick += _timer_Tick;
_timer.Interval = 2000;
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
//CopyFromActiveProgram();
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_timer.Stop();
UnregisterClipboardViewer();
if (_hotkeyRegistered)
{
UnregisterHotKey(this.Handle, 1);
}
}
public void RegisterClipboardViewer()
{
_clipboardViewerNext = SetClipboardViewer(this.Handle);
}
public void UnregisterClipboardViewer()
{
ChangeClipboardChain(this.Handle, _clipboardViewerNext);
}
private void CopyFromActiveProgram()
{
string selText = null;
if (GetSelectedText(out selText))
{
if (!string.IsNullOrEmpty(selText))
{
string tmpSelText = selText.Trim(new char[] { '\r', '\n', ' ', '\t' });
if (selText.Length > 2)
{
UpdateMessage(selText);
return;
}
}
}
_getCopyValue = true;
SendKeys.SendWait("^c");
}
private void UpdateMessage(string msg)
{
if (this.InvokeRequired)
{
UpdateMsgDel del = new UpdateMsgDel(this.UpdateMessage);
this.Invoke(del, msg);
return;
}
this.textBox1.AppendText(msg + "\r\n");
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_DRAWCLIPBOARD:
if (_getCopyValue && Clipboard.ContainsText())
{
_getCopyValue = false;
this.textBox1.AppendText(Clipboard.GetText());
}
SendMessage(_clipboardViewerNext, m.Msg, m.WParam, m.LParam);
break;
case WM_CHANGECBCHAIN:
if (m.WParam == _clipboardViewerNext)
{
_clipboardViewerNext = m.LParam;
}
else
{
SendMessage(_clipboardViewerNext, m.Msg, m.WParam, m.LParam);
}
break;
case WM_HOTKEY:
CopyFromActiveProgram();
break;
}
base.WndProc(ref m);
}
private void cmdGet_Click(object sender, EventArgs e)
{
CopyFromActiveProgram();
}
private void cmdClear_Click(object sender, EventArgs e)
{
this.textBox1.Clear();
}
private static bool GetSelectedText(out string selText)
{
bool bRet = false;
selText = null;
var element = AutomationElement.FocusedElement;
if (element != null)
{
try
{
object pattern = null;
if (element.TryGetCurrentPattern(TextPattern.Pattern, out pattern))
{
var tp = (TextPattern)pattern;
var sb = new StringBuilder();
foreach (var r in tp.GetSelection())
{
sb.AppendLine(r.GetText(-1));
}
var selectedText = sb.ToString();
selText = selectedText;
//Console.WriteLine("Text={0}", selectedText);
bRet = true;
}
else
{
Console.WriteLine("element.TryGetCurrentPattern failed");
}
}
catch (Exception e)
{
Console.WriteLine("exception = {0}", e.Message);
Console.WriteLine("stack = {0}", e.StackTrace);
}
}
else
{
Console.WriteLine("element is null");
}
return bRet;
}
}
}
| 32.361905 | 98 | 0.475721 |
924c76677371aba4c418b06f359b2774708775dd | 5,934 | cs | C# | languages/csharp/AppEncryption/Crypto/BasicExpiringCryptoPolicy.cs | ravinaik1312/asherah | 143ad91f46b891a5f2fc6a48913bc6a9499ac38b | [
"MIT"
] | 1 | 2020-08-15T09:40:39.000Z | 2020-08-15T09:40:39.000Z | languages/csharp/AppEncryption/Crypto/BasicExpiringCryptoPolicy.cs | thomcost/asherah | 5085159b2aa45cd1436fc91cf498ace3e5440757 | [
"MIT"
] | null | null | null | languages/csharp/AppEncryption/Crypto/BasicExpiringCryptoPolicy.cs | thomcost/asherah | 5085159b2aa45cd1436fc91cf498ace3e5440757 | [
"MIT"
] | null | null | null | using System;
namespace GoDaddy.Asherah.Crypto
{
/// <summary>
/// A Crypto Policy that allows easy customization of the expiration duration and caching TTL,
/// with default values for key strategy, caching, and notification options:
/// <para>
/// - Key Rotation Strategy: Inline<br/>
/// - Caching of System and Intermediate Keys is allowed<br/>
/// - Notifications of reads using expired keys is disabled<br/>
/// </para>
/// All of the default values can be modified using the optional builder methods.
/// </summary>
public class BasicExpiringCryptoPolicy : CryptoPolicy
{
private readonly long keyExpirationMillis;
private readonly long revokeCheckMillis;
// NOTE: Defaults for these are taken from the Builder class, below
private readonly KeyRotationStrategy keyRotationStrategy;
private readonly bool canCacheSystemKeys;
private readonly bool canCacheIntermediateKeys;
private readonly bool notifyExpiredSystemKeyOnRead;
private readonly bool notifyExpiredIntermediateKeyOnRead;
private BasicExpiringCryptoPolicy(Builder builder)
{
keyExpirationMillis = (long)TimeSpan.FromDays(builder.KeyExpirationDays).TotalMilliseconds;
revokeCheckMillis = (long)TimeSpan.FromMinutes(builder.RevokeCheckMinutes).TotalMilliseconds;
keyRotationStrategy = builder.KeyRotationStrategy;
canCacheSystemKeys = builder.CanCacheSystemKeys;
canCacheIntermediateKeys = builder.CanCacheIntermediateKeys;
notifyExpiredSystemKeyOnRead = builder.NotifyExpiredSystemKeyOnRead;
notifyExpiredIntermediateKeyOnRead = builder.NotifyExpiredIntermediateKeyOnRead;
}
public interface IKeyExpirationDaysStep
{
IRevokeCheckMinutesStep WithKeyExpirationDays(int days);
}
public interface IRevokeCheckMinutesStep
{
IBuildStep WithRevokeCheckMinutes(int minutes);
}
public interface IBuildStep
{
IBuildStep WithRotationStrategy(KeyRotationStrategy rotationStrategy);
IBuildStep WithCanCacheSystemKeys(bool cacheSystemKeys);
IBuildStep WithCanCacheIntermediateKeys(bool cacheIntermediateKeys);
IBuildStep WithNotifyExpiredSystemKeyOnRead(bool notify);
IBuildStep WithNotifyExpiredIntermediateKeyOnRead(bool notify);
BasicExpiringCryptoPolicy Build();
}
public static IKeyExpirationDaysStep NewBuilder()
{
return new Builder();
}
public override bool IsKeyExpired(DateTimeOffset keyCreationDate)
{
long currentUnixTimeMillis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
long expiredMillis = keyCreationDate.ToUnixTimeMilliseconds() + keyExpirationMillis;
return currentUnixTimeMillis > expiredMillis;
}
public override long GetRevokeCheckPeriodMillis()
{
return revokeCheckMillis;
}
public override bool CanCacheSystemKeys()
{
return canCacheSystemKeys;
}
public override bool CanCacheIntermediateKeys()
{
return canCacheIntermediateKeys;
}
public override bool NotifyExpiredIntermediateKeyOnRead()
{
return notifyExpiredIntermediateKeyOnRead;
}
public override bool NotifyExpiredSystemKeyOnRead()
{
return notifyExpiredSystemKeyOnRead;
}
public override KeyRotationStrategy GetKeyRotationStrategy()
{
return keyRotationStrategy;
}
private class Builder : IKeyExpirationDaysStep, IRevokeCheckMinutesStep, IBuildStep
{
#pragma warning disable SA1401
internal int KeyExpirationDays;
internal int RevokeCheckMinutes;
// Set some reasonable defaults since these aren't required by the builder steps
internal KeyRotationStrategy KeyRotationStrategy = KeyRotationStrategy.Inline;
internal bool CanCacheSystemKeys = true;
internal bool CanCacheIntermediateKeys = true;
internal bool NotifyExpiredSystemKeyOnRead = false;
internal bool NotifyExpiredIntermediateKeyOnRead = false;
#pragma warning restore SA1401
public IRevokeCheckMinutesStep WithKeyExpirationDays(int days)
{
KeyExpirationDays = days;
return this;
}
public IBuildStep WithRevokeCheckMinutes(int minutes)
{
RevokeCheckMinutes = minutes;
return this;
}
public IBuildStep WithRotationStrategy(KeyRotationStrategy rotationStrategy)
{
KeyRotationStrategy = rotationStrategy;
return this;
}
public IBuildStep WithCanCacheSystemKeys(bool cacheSystemKeys)
{
CanCacheSystemKeys = cacheSystemKeys;
return this;
}
public IBuildStep WithCanCacheIntermediateKeys(bool cacheIntermediateKeys)
{
CanCacheIntermediateKeys = cacheIntermediateKeys;
return this;
}
public IBuildStep WithNotifyExpiredSystemKeyOnRead(bool notify)
{
NotifyExpiredSystemKeyOnRead = notify;
return this;
}
public IBuildStep WithNotifyExpiredIntermediateKeyOnRead(bool notify)
{
NotifyExpiredIntermediateKeyOnRead = notify;
return this;
}
public BasicExpiringCryptoPolicy Build()
{
return new BasicExpiringCryptoPolicy(this);
}
}
}
}
| 35.321429 | 105 | 0.645433 |
9a3e8209b04a5cd3616423927341047f696fe3e9 | 15,449 | cs | C# | C#_Tutorial_by_Derek_Banas/ConsoleApp1/ConsoleApp1/Program.cs | Pikmaniac369/C16302271_-_OOP_Assignment_2 | 8fdca83e16661becab7012292ebcdd4dca544c58 | [
"MIT"
] | 1 | 2020-02-28T14:00:05.000Z | 2020-02-28T14:00:05.000Z | C#_Tutorial_by_Derek_Banas/ConsoleApp1/ConsoleApp1/Program.cs | Pikmaniac369/C16302271_-_OOP_Assignment_2 | 8fdca83e16661becab7012292ebcdd4dca544c58 | [
"MIT"
] | null | null | null | C#_Tutorial_by_Derek_Banas/ConsoleApp1/ConsoleApp1/Program.cs | Pikmaniac369/C16302271_-_OOP_Assignment_2 | 8fdca83e16661becab7012292ebcdd4dca544c58 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Single Line Comment
/*
Multi
Line
Comment
*/
//HELLO WORLD:
//-----------------------------------------------------------------------------
Console.WriteLine("Hello World");
Console.Write("What is your name ");
string name = Console.ReadLine();//Read in input from the command line
Console.WriteLine("Hello " + name);//Say hello to the user
//DATA TYPES
//-----------------------------------------------------------------------------
//Boolean: True or False
bool canVote = true;
//Character: A single 16-bit character
char grade = 'A';
//Integer with a max number of 2,147,483,647
int maxInt = int.MaxValue;
//Long with a max number of 9,223,372,036,854,775,807
long maxLong = long.MaxValue;
//Decimal has a maximum value of 79,228,162,514,264,337,593,543,950,335
//If you need something bigger look up BigInteger
decimal maxDec = decimal.MaxValue;
//A float is a 32 bit number with a maxValue of 3.402823E+38 with 7 decimals of precision
float maxFloat = float.MaxValue;
//A double is a 32 bit number with a maxValue of 1.797693134E+308 with 15 decimals of precision
double maxDouble = double.MaxValue;
Console.WriteLine("Max Int: " + maxInt);
var anotherName = "Tom";
//Will cause an error as var has already been inferred to be a string, not an integer:
//anotherName = 2;
//Display anotherName's type
Console.WriteLine("anotherName is a {0}", anotherName.GetTypeCode());//{0} is replaced with anotherName's type
//MATHEMATICAL OPERATIONS:
//-----------------------------------------------------------------------------
Console.WriteLine("5 + 3 = " + (5 + 3));
Console.WriteLine("5 - 3 = " + (5 - 3));
Console.WriteLine("5 * 3 = " + (5 * 3));
Console.WriteLine("5 / 3 = " + (5 / 3));
Console.WriteLine("5.2 % 3 = " + (5.2 % 3));
int i = 0;
Console.WriteLine("i++ = " + (i++));//Increment i AFTER it is used
Console.WriteLine("++i = " + (++i));//Increment i BEFORE it is used
Console.WriteLine("i-- = " + (i--));//Decrement i AFTER it is used
Console.WriteLine("--i = " + (--i));//Decrement i BEFORE it is used
Console.WriteLine("i += 3: " + (i += 3));// i = i + 3
Console.WriteLine("i -= 2: " + (i -= 2));// i = i - 2
Console.WriteLine("i *= 2: " + (i *= 2));// i = i * 2
Console.WriteLine("i /= 2: " + (i /= 2));// i = i / 2
Console.WriteLine("i %= 2: " + (i %= 2));// i = i % 2
//CASTING:
//-------------------------------------------------------------------------------
double pi = 3.14;
int intPi = (int)pi;
//IN-BUILT MATHS FUNCTIONS:
//---------------------------------------------------------------------------------------
//Acos
//Asin
//Atan
//Atan2
//Cos
//Cosh
//Exp
//Log
//Sin
//Sinh
//Tan
//Tanh
double number1 = 10.5;
double number2 = 15;
Console.WriteLine("Math.Abs(number1): " + (Math.Abs(number1)) );
Console.WriteLine("Math.Ceiling(number1): " + (Math.Ceiling(number1)) );//Round up
Console.WriteLine("Math.Floor(number1): " + (Math.Floor(number1)) );//Round down
Console.WriteLine("Math.Max(number1, number2): " + (Math.Max(number1, number2)) );//The greater of the two
Console.WriteLine("Math.Min(number1, number2): " + (Math.Min(number1, number2)) );//The lesser of the two
Console.WriteLine("Math.Pow(number1, 2): " + (Math.Pow(number1, 2)) );//number1 to the power of 2
Console.WriteLine("Math.Round(number1): " + (Math.Round(number1)) );//Round the number
Console.WriteLine("Math.Sqrt(number1): " + (Math.Sqrt(number1)) );//Find the sqare root
//Generate a random number between 1 and 10
Random rand = new Random();
Console.WriteLine("Random Number between 1 and 10: " + (rand.Next(1, 11)));
//CONDITIONALS:
//------------------------------------------------------------------------------
//Relational Operators: > < <= >= == !=
//Logical Operators: && || ^ !
int age = 17;
if( (age >= 5) && (age <= 7) )
{
Console.WriteLine("Go to elementary school");
}
else if( (age > 7) && (age < 13) )
{
Console.WriteLine("Go to middle school");
}
else
{
Console.WriteLine("Go to high school");
}
if( (age < 14) || (age > 67) )
{
Console.WriteLine("You're not allowed to work. You're either too young or too old!");
}
Console.WriteLine("!true = " + (!true));
bool canDrive = age >= 16 ? true : false;
switch(age)
{
case 0:
Console.WriteLine("Infant");
break;
case 1:
case 2:
Console.WriteLine("Toddler");
//goto Cute;
break;
default:
Console.WriteLine("Child");
break;
}
/*
Cute:
Console.WriteLine("Toddlers are Cute");
*/
//LOOPING:
//----------------------------------------------------------------------------------
int j = 0;
while(j < 10)
{
if(j == 7)
{
j++;
continue;//Skip everything after the if statement and return to beginning of loop
}
if(j == 9)
{
break;//Leave the while loop. No more checking.
}
//If j is an odd number
if( (j % 2) > 0)
{
Console.WriteLine(j);
}
j++;
}
string guess;
do
{
Console.WriteLine("Guess a Number: ");
guess = Console.ReadLine();
}
while(!guess.Equals("15"));
for(int k = 0; k < 10; k++)
{
if((k % 2) > 0)
{
Console.WriteLine(k);
}
}
string randStr = "Here are some random characters";
//For each character in randStr
foreach(char c in randStr)
{
Console.WriteLine(c);
}
//STRINGS:
//---------------------------------------------------------------------------------
//Within a string:
// \' to get '
// \" to get "
// \\ to get \
// \b to go back one space
// \n to get a new line
// \t to get a tab
string sampString = "A bunch of random words";
string sampString2 = "More random words";
Console.WriteLine("Is empty: " + String.IsNullOrEmpty(sampString) );//Is it empty?
Console.WriteLine("Is empty: " + String.IsNullOrWhiteSpace(sampString) );//Is it just whitespace?
Console.WriteLine("String Length: " + sampString.Length);//Length of the string
Console.WriteLine("Index of \'bunch\': " + sampString.IndexOf("bunch") );//Index of 'bunch'
Console.WriteLine("2nd Word: " + sampString.Substring(2, 6) );
Console.WriteLine("Strings Equal: " + sampString.Equals(sampString2) );//Are the strings equal?
Console.WriteLine("Starts with \"A bunch\": " + sampString.StartsWith("A bunch") );
Console.WriteLine("Ends with \"words\": " + sampString.EndsWith("words") );
sampString = sampString.Trim();//Removes excess whitespace from beginning and end
//sampString.TrimEnd() removes excess whitespace from the end
//sampString.TrimStart() removes excess whitespace from the beginning
sampString = sampString.Replace("words", "characters");//Replaces all instances of "words" with "characters"
sampString = sampString.Remove(0, 2);//Removes two characters starting at index 0
string[] names = new string[3] {"Matt", "Joe", "Paul" };//How to create and initialise a string array
Console.WriteLine("Name List: " + String.Join(", ", names) );//Joins the elements of the array together in a single string with ", " between each
string fmtStr = String.Format("{0:c} {1:00.00} {2:#.00} {3:0,0}", 1.56, 15.567, .56, 1000);
Console.WriteLine(fmtStr);
//STRING BUILDER:
//------------------------------------------------------------------------------------
//Can be edited, i.e. can be added to easily
StringBuilder sb = new StringBuilder();
sb.Append("This is the first sentence. ");
sb.AppendFormat("My name is {0} and I live in {1}.", "Adam", "Navan");
//sb.Clear();//Empty the StringBuilder
sb.Replace("a", "e");//Replace every instance of the letter "a" with the letter "e"
sb.Remove(5, 7);// Remove 7 characters, beginning at index 5
Console.WriteLine(sb.ToString());//Needs to be converted to a String to be displayed
//ARRAYS:
//--------------------------------------------------------------------------------------
int[] randNumArray;//Declare an array
int[] randArray = new int[5];//Declare an array and its size
int[] randArray2 = {1, 2, 3, 4, 5};//Declare and initialise an array. Do not put 'new'. Automatically allocates space based on number of elements.
Console.WriteLine("Array Length: " + randArray2.Length);
Console.WriteLine("Item 0: " + randArray2[0]);
for(int l = 0; l < randArray2.Length; l++)
{
Console.WriteLine("Item {0}: {1}", l, randArray2[l]);
}
foreach(int num in randArray2)
{
Console.WriteLine(num);
}
Console.WriteLine("Where is 1: " + Array.IndexOf(randArray2, 1) );//Find the index of 1
string[] names2 = {"Tom", "Paul", "Sally"};
string nameStr = string.Join(", ", names2);
string[] nameArray = nameStr.Split(',');
int[,] multArray = new int[5, 3];//Declare a 2D array
int[,] multArray2 = { {0, 1}, {2, 3}, {4, 5} };//Declare and initialise a 2D array
foreach(int num in multArray2)
{
Console.WriteLine(num);
}
for(int x = 0; x < multArray2.GetLength(0); x++)
{
for(int y = 0; y < multArray2.GetLength(1); y++)
{
Console.WriteLine("{0} | {1} : {2}", x, y, multArray2[x, y] );
}
}
//LISTS:
//---------------------------------------------------------------------------------
//Like an array but can resize itself depending on the number of elements it contains
List<int> numList = new List<int>();//Declaring a List
//Can add values to the List without having to worry about the List's size as it'll change
numList.Add(5);
numList.Add(15);
numList.Add(25);
//Adding an array to a List
int[] randArray3 = {1, 2, 3, 4, 5};//Must be the same data type as the List
numList.AddRange(randArray3);//Use AddRange() for adding arrays instead of just Add()
//Clearing a List
//numList.Clear();
//Copying an array into a List
List<int> numList2 = new List<int>(randArray3);
//Copying a new array into a List
List<int> numList3 = new List<int>(new int[] {1, 2, 3, 4});
numList.Insert(1, 10);//Inserts 10 into index 1 of the List
numList.Remove(5);//Remove 5 from the List. Don't know where it is. Removal by name.
numList.RemoveAt(2);//Remove whatever is located at index 2 of the List
//Use Count to get the length of the List, not Length
for(int m = 0; m < numList.Count; m++)
{
Console.WriteLine(numList[m]);
}
//Find the index of a value
//Returns -1 if it doesn't find anything
Console.WriteLine("4 is in index: " + numList3.IndexOf(4));
//Check to see if the List contains a value
Console.WriteLine("5 in List: " + numList.Contains(5) );
//You can also search for values in a String List
List<string> strList = new List<string>(new string[] {"Tom", "Paul"});
Console.WriteLine("Tom in List: " + strList.Contains("Tom") );
//Ignoring case:
Console.WriteLine("Tom in List: " + strList.Contains("tom", StringComparer.OrdinalIgnoreCase) );
//Sort the List alphabetically or numerically (depends on List type)
strList.Sort();
//EXCEPTION HANDLING:
//--------------------------------------------------------------------------------------
//Divide by 0 exception:
try
{
Console.Write("Divide 10 by ");
int num = int.Parse(Console.ReadLine());//Converts a String into an Integer
Console.WriteLine("10 / {0} = {1}", num, (10 / num));
}
catch (DivideByZeroException ex)
{
//Specifically catches a Divide-By-Zero Exception
Console.WriteLine("Can't divide by zero");
Console.WriteLine(ex.GetType().Name);//Get the name of the exception that was triggered
Console.WriteLine(ex.Message);//Display the exceptions error message
}
catch (Exception ex)
{
//Catches any exception
Console.WriteLine(ex.GetType().Name);//Get the name of the exception that was triggered
Console.WriteLine(ex.Message);//Display the exceptions error message
}
//Stops the command line window from closing immediately
//Equivalent of C's getchar() function
Console.ReadKey();
}
}
}
| 29.939922 | 158 | 0.463007 |
5da04e122aed0f6bf5e6f4e43322069cc2109f1d | 556 | cs | C# | MVCProject/Model/Livro.cs | david-hilles/GitCsharp | b9bec1fa96ea5dc71a25279e9817879eabb468fa | [
"MIT"
] | null | null | null | MVCProject/Model/Livro.cs | david-hilles/GitCsharp | b9bec1fa96ea5dc71a25279e9817879eabb468fa | [
"MIT"
] | null | null | null | MVCProject/Model/Livro.cs | david-hilles/GitCsharp | b9bec1fa96ea5dc71a25279e9817879eabb468fa | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVCProject.Model
{
public class Livro : Informacao
{
public int Id { get; set; }
public int Registro { get; set; }
public string Titulo { get; set; }
public string Isbn { get; set; }
public int Genero { get; set; }
public int Editora { get; set; }
public string Sinopse { get; set; }
public string Observacoes { get; set; }
}
}
| 24.173913 | 48 | 0.589928 |
dec64d0f4ff56226aad95a62f982dcd6fbee753b | 9,454 | cs | C# | common/myoddweb.classifierUnitTest/TestSqlClassify.cs | FFMG/myoddweb.classifier | c8c200bc7168763636e2a485a64ea9e7dbf5d84e | [
"MIT"
] | 12 | 2015-12-27T09:54:17.000Z | 2021-09-07T21:47:42.000Z | common/myoddweb.classifierUnitTest/TestSqlClassify.cs | FFMG/myoddweb.classifier | c8c200bc7168763636e2a485a64ea9e7dbf5d84e | [
"MIT"
] | 10 | 2016-04-05T06:18:54.000Z | 2019-12-10T18:24:58.000Z | common/myoddweb.classifierUnitTest/TestSqlClassify.cs | FFMG/myoddweb.classifier | c8c200bc7168763636e2a485a64ea9e7dbf5d84e | [
"MIT"
] | 2 | 2017-12-28T04:37:04.000Z | 2020-04-21T18:01:21.000Z | using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace myoddweb.classifierUnitTest
{
/// <summary>
/// Summary description for TestSqlClassify
/// </summary>
[TestFixture]
public class TestSqlClassify : TestCommon
{
[OneTimeTearDown]
public void ClassCleanup()
{
ReleaseEngine(true);
}
[TearDown]
public void TestCleanup()
{
ReleaseEngine(false);
}
[Test]
public void TestTrainSimpleText()
{
var categoryName = RandomString(8);
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsTrue(TheEngine.Classify.Train(categoryName, categoryText, uniqueEntryId, 1));
}
[Test]
public void TestUnTrainSimpleText()
{
// this text/category does not exist
// so we cannot un-train anyting.
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsFalse(TheEngine.Classify.UnTrain( uniqueEntryId, categoryText));
}
[Test]
public void TestTrainAndUnTrainSimpleText()
{
var categoryName = RandomString(8);
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsTrue(TheEngine.Classify.Train(categoryName, categoryText, uniqueEntryId, 1));
Assert.IsTrue(TheEngine.Classify.UnTrain( uniqueEntryId, categoryText));
}
[Test]
public void TestGetCategoryName()
{
// the category is created on the fly... #1 is alocated to it.
var categoryName = RandomString(8);
Assert.AreEqual(1, TheEngine.Categories.GetCategory(categoryName));
}
[Test]
public void TestCategoryCannotBeCreatedWithEmptyString()
{
Assert.AreEqual(-1, TheEngine.Categories.GetCategory(""));
Assert.AreEqual(-1, TheEngine.Categories.GetCategory("")); // we ask twice, in case it was inserted.
}
[Test]
public void TestCategoryCannotBeCreatedWithEmptyStringWithSpaces()
{
var random = new Random();
var result = Enumerable.Repeat(" ", random.Next(1, 20)).Aggregate((sum, next) => sum + next);
Assert.AreEqual(-1, TheEngine.Categories.GetCategory(result));
Assert.AreEqual(-1, TheEngine.Categories.GetCategory(result)); // we ask twice, in case it was inserted.
}
[Test]
public void TestCategoryIsCreatedByTrainning()
{
var categoryName = RandomString(8);
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsTrue(TheEngine.Classify.Train(categoryName, categoryText, uniqueEntryId, 1));
// the category should/must exist.
Assert.AreEqual(1, TheEngine.Categories.GetCategory(categoryName));
}
[Test]
public void TestSimpleCategorise()
{
var categoryName = RandomString(8);
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsTrue(TheEngine.Classify.Train(categoryName, categoryText, uniqueEntryId, 1));
// get the category
var categoryId = TheEngine.Categories.GetCategory(categoryName);
// the category should/must exist.
Assert.AreEqual(categoryId, TheEngine.Classify.Categorize(categoryText, 0 ));
}
[Test]
public void TestSimpleCategoriseWithWordCategory()
{
var categoryName = RandomString(8);
var categoryText = RandomStringWithSpaces(8);
var uniqueEntryId = RandomString(100);
Assert.IsTrue(TheEngine.Classify.Train(categoryName, categoryText, uniqueEntryId, 1));
// get the category
var categoryId = TheEngine.Categories.GetCategory(categoryName);
// the category should/must exist.
var wordCategory = new List<Classifier.Interfaces.Helpers.WordCategory>();
var categoryProbabilities = new Dictionary<int, double>();
Assert.AreEqual(categoryId, TheEngine.Classify.Categorize(categoryText, 0, out wordCategory, out categoryProbabilities));
}
[Test]
public void TestGetCategories()
{
// we should have no categories to start with.
var categories = TheEngine.Categories.GetCategories();
Assert.AreEqual( 0, categories.Count);
// çreate 2 categories by getting them.
var categorySpam = TheEngine.Categories.GetCategory( "Spam");
var categoryHam = TheEngine.Categories.GetCategory( "Ham");
var expectedCategories = new Dictionary<int, string>()
{
{categorySpam, "Spam" },
{categoryHam, "Ham" }
};
// now get it again
categories = TheEngine.Categories.GetCategories();
// make sure that it is valid.
CompareCategories(expectedCategories, categories);
// add one more category.
var categoryJam = TheEngine.Categories.GetCategory("Jam");
expectedCategories.Add(categoryJam, "Jam");
// now get it again
categories = TheEngine.Categories.GetCategories();
// make sure that it is valid.
CompareCategories(expectedCategories, categories);
}
private void CompareCategories(Dictionary<int, string> expectedCategories, Dictionary<int, string> categories)
{
// we should have more than one.
Assert.AreEqual(expectedCategories.Count, categories.Count);
if (expectedCategories.Count == categories.Count)
{
foreach (var expectedCategory in expectedCategories)
{
Assert.IsTrue(categories.ContainsKey(expectedCategory.Key));
Assert.AreEqual(expectedCategory.Value, categories[expectedCategory.Key]);
}
}
}
[Test]
public void TestMultipleTrainSimple()
{
// this text/category does not exist
// so we cannot un-train anyting.
var uniqueEntryId1 = RandomString(100 );
var uniqueEntryId2 = RandomString(100);
var uniqueEntryId3 = RandomString(100);
var uniqueEntryId4 = RandomString(100);
var uniqueEntryId5 = RandomString(100);
var categoryText1 = "hello world";
var categoryText2 = "goodbye world";
var categoryText3 = "byebye world";
var categoryText4 = "au revoire world";
var categoryText5 = "is that it world?";
Assert.IsTrue( TheEngine.Classify.Train("spam", categoryText1, uniqueEntryId1, 1)); // world appears once 1/5 = ~20%
Assert.IsTrue( TheEngine.Classify.Train("ham" , categoryText2, uniqueEntryId2, 1)); // world appears twice 4/5 = ~80%
Assert.IsTrue( TheEngine.Classify.Train("ham" , categoryText3, uniqueEntryId3, 1));
Assert.IsTrue( TheEngine.Classify.Train("ham" , categoryText4, uniqueEntryId4, 1));
Assert.IsTrue( TheEngine.Classify.Train("ham" , categoryText5, uniqueEntryId5, 1));
// the word 'world' appears 4x in 'ham'
// so the category must be 'ham'
var thisCategory = TheEngine.Classify.Categorize("world is good", 0 );
Assert.AreEqual(TheEngine.Categories.GetCategory("ham"), thisCategory);
// try and classify #1 again into 'spam'
Assert.IsTrue(TheEngine.Classify.Train("spam", categoryText1, uniqueEntryId1, 1));
// but that should not change anything in the classification
thisCategory = TheEngine.Classify.Categorize("world is good", 0);
Assert.AreEqual(TheEngine.Categories.GetCategory("ham"), thisCategory);
}
[Test]
public void TestThatTheWeightIsUpdated()
{
var categoryName1 = RandomString(8);
var categoryName2 = RandomString(8);
var uniqueEntryId11 = RandomString(100);
var uniqueEntryId12 = RandomString(100);
var uniqueEntryId21 = RandomString(100);
// we add the same word twice to one category
Assert.IsTrue(TheEngine.Classify.Train(categoryName1, "World", uniqueEntryId11, 1));
Assert.IsTrue(TheEngine.Classify.Train(categoryName1, "World", uniqueEntryId12, 1));
// then we add the same one once, to the other category
Assert.IsTrue(TheEngine.Classify.Train(categoryName2, "World", uniqueEntryId21, 1));
// get the category
var categoryId1 = TheEngine.Categories.GetCategory(categoryName1);
var categoryId2 = TheEngine.Categories.GetCategory(categoryName2);
// our category text
const string categoryText = "Hello World";
// so because there are 2 words on one, the current category should be category one.
Assert.AreEqual(categoryId1, TheEngine.Classify.Categorize(categoryText, 0));
// we now want to change the second category entry
// with a bigger weight.
Assert.IsTrue(TheEngine.Classify.Train(categoryName2, "World", uniqueEntryId21, 3));
// so we now have 2xWordx(1xWeight) in category 1
// and 1xWordx(3xWeight) in category 2
// so category 2 should be the one.
Assert.AreEqual(categoryId2, TheEngine.Classify.Categorize(categoryText, 0));
// and if we revet back to 1xWeight then the category should go back to category 1
Assert.IsTrue(TheEngine.Classify.Train(categoryName2, "World", uniqueEntryId21, 1));
Assert.IsTrue(TheEngine.Classify.Train(categoryName1, "World", uniqueEntryId21, 3));
}
[Test]
public void TryAndCategoriseWithMoreThan100Percent()
{
// Cannot be more than 100%
var random = new Random(Guid.NewGuid().GetHashCode());
Assert.Throws<ArgumentException>( () => TheEngine.Classify.Categorize("Some text", (uint)random.Next(101, 200)));
}
}
}
| 35.946768 | 127 | 0.685001 |
26947132f0fbe94b466c065c32b4149d6548860b | 7,232 | cshtml | C# | src/SimpleSSO/Areas/Admin/Views/Ticket/Index.cshtml | stonysong/SimpleSSO | 63a4ea6a21459f55e5573815de529f74f73d3662 | [
"Apache-2.0"
] | 136 | 2016-12-19T09:19:33.000Z | 2021-11-07T20:29:23.000Z | src/SimpleSSO/Areas/Admin/Views/Ticket/Index.cshtml | stonysong/SimpleSSO | 63a4ea6a21459f55e5573815de529f74f73d3662 | [
"Apache-2.0"
] | null | null | null | src/SimpleSSO/Areas/Admin/Views/Ticket/Index.cshtml | stonysong/SimpleSSO | 63a4ea6a21459f55e5573815de529f74f73d3662 | [
"Apache-2.0"
] | 70 | 2016-12-19T06:54:04.000Z | 2021-11-10T09:16:50.000Z |
@{
ViewBag.Title = "Tickets";
}
<div style="width:100%;height:100%">
<div class="panel-body" style="padding-bottom:0px;">
<div class="panel panel-default">
<div class="panel-heading">查询条件</div>
<div class="panel-body">
<form id="formSearch" class="form-horizontal">
<div class="form-group" style="margin-top:15px">
<label class="control-label col-sm-1" for="txt_search_app">App</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="txt_search_app">
</div>
<div class="col-sm-4" style="text-align:left;">
<button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>
</div>
</div>
</form>
</div>
</div>
<div id="toolbar" class="btn-group">
<button id="btn_delete" type="button" class="btn btn-default">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
</button>
</div>
<table id="tb_tickets" style="height:15%"></table>
</div>
</div>
<style>
.form-group {
padding: 3px;
}
.form-group > label {
width: 85px;
text-align: right;
}
.form-group > input {
padding-right: 42.5px;
}
.panel {
margin-bottom: 5px;
}
.panel-body {
padding: 5px;
}
</style>
@section scripts
{
<script type="text/javascript">
var $btnDelete = "#btn_delete",
$btnQuery = "#btn_query",
$tableID = "#tb_tickets",
$queryUrl = "/Ticket/Query",
$deleteUrl = "/Ticket/Delete",
$toolbar = "#toolbar";
$(function () {
//1.初始化Table
var oTable = new TableInit();
oTable.Init();
//2.初始化Button的点击事件
var oButtonInit = new ButtonInit();
oButtonInit.Init();
});
var TableInit = function () {
var oTableInit = new Object();
function isLockedFormatter(value) {
if (value) {
return "<span class='label label-danger'>" + value + "</span>";
}
else {
return "<span class='label label-success'>" + value + "</span>";
}
};
//初始化Table
oTableInit.Init = function () {
$($tableID).bootstrapTable({
url: $queryUrl, //请求后台的URL(*)
method: 'post', //请求方式(*)
toolbar: $toolbar, //工具按钮用哪个容器
striped: true, //是否显示行间隔色
cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
pagination: false, //是否显示分页(*)
sortable: false, //是否启用排序
sortOrder: "asc", //排序方式
queryParams: oTableInit.queryParams,//传递参数(*)
responseHandler: function (res) { return res.Data; },
sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
pageNumber: 10, //初始化加载第一页,默认第一页
pageSize: 10, //每页的记录行数(*)
pageList: [10, 25, 50, 100], //可供选择的每页的行数(*)
strictSearch: true,
showColumns: true, //是否显示所有的列
showRefresh: true, //是否显示刷新按钮
minimumCountColumns: 2, //最少允许的列数
clickToSelect: true, //是否启用点击选中行
height: 400, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
uniqueId: "ID", //每一行的唯一标识,一般为主键列
showToggle: true, //是否显示详细视图和列表视图的切换按钮
cardView: false, //是否显示详细视图
detailView: false, //是否显示父子表
columns: [{
checkbox: true
},
{
title: '应用ID',
field: 'ClientID'
}, {
title: '用户ID',
field: 'UserID'
}, {
title: '用户名称',
field: 'UserName'
},
{
title: '秘钥类型',
field: 'TokenType'
}, {
title: '秘钥',
field: 'Token'
}, {
title: '申请权限',
field: 'RoleScope'
}, {
title: '生成时间(Utc)',
field: 'IssuedUtc'
}, {
title: '过期时间(Utc)',
field: 'ExpiresUtc'
}]
});
};
//得到查询的参数
oTableInit.queryParams = function (params) {
var temp = { //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
Limit: params.limit, //页面大小
Offset: (params.offset), //页码
Name: $("#txt_search_app").val()
};
return temp;
};
return oTableInit;
};
var ButtonInit = function () {
var oInit = new Object();
var isCreate, postdata = {};
oInit.Init = function () {
//删除数据click事件注册
$($btnDelete).click(function () {
var arrselections = $($tableID).bootstrapTable('getSelections');
if (arrselections.length <= 0) {
Ewin.warning('请选择有效数据');
return;
}
Ewin.confirm({ message: "确认要删除选择的数据吗?" }).on(function (e) {
if (!e) {
return;
}
$.ajax({
type: "post",
url: $deleteUrl,
data: { tokens: $.Enumerable.From(arrselections).Select('$.Token').ToArray() },
success: function (data, status) {
if (status == "success") {
Ewin.alertResponseData(data, '删除成功');
$($tableID).bootstrapTable('refresh');
}
},
dataType: "json",
error: function () {
Ewin.error('Error');
},
complete: function () {
}
});
});
});
//条件查询click事件注册
$($btnQuery).click(function () {
$($tableID).bootstrapTable('refresh');
});
};
return oInit;
};
</script>
}
| 34.937198 | 125 | 0.384817 |
a58762a888bb76ce3e83c118a215ac555401f151 | 6,401 | cshtml | C# | Integratieproject 1/cityofideas-website/UI-MVC/Views/Ideation/View.cshtml | jclaessens97/School-Portfolio | 3fe9995d55b8fe26bdcc5ab2e5ac95bef6d563e4 | [
"MIT"
] | null | null | null | Integratieproject 1/cityofideas-website/UI-MVC/Views/Ideation/View.cshtml | jclaessens97/School-Portfolio | 3fe9995d55b8fe26bdcc5ab2e5ac95bef6d563e4 | [
"MIT"
] | 3 | 2021-03-10T04:57:16.000Z | 2021-05-11T12:35:23.000Z | Integratieproject 1/cityofideas-website/UI-MVC/Views/Ideation/View.cshtml | jclaessens97/School-Portfolio | 3fe9995d55b8fe26bdcc5ab2e5ac95bef6d563e4 | [
"MIT"
] | null | null | null | @using COI.BL.Domain.Answer
@using COI.BL.Domain.Foundation
@using COI.BL.Domain.Ideation
@using COI.BL.Domain.User
@using COI.UI_MVC.Extensions
@using COI.UI_MVC.Models
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.Identity.UI.Pages.Internal
@model COI.UI_MVC.Models.IdeationReplyViewModel
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager
@{
ViewBag.Title = "Idee";
Layout = "_Layout";
}
@section Scripts
{
<script type="module" src="~/dist/viewIdeation.entry.js" defer></script>
}
<div class="container">
<div class="ideation-reply-header">
<div class="w-75">
@if (ViewBag.IsAdminIdeation)
{
<a asp-controller="Project" asp-action="Details" asp-route-id="@ViewBag.ProjectId" class="btn-default"><i class="fas fa-backward"></i> naar project</a>
}
else
{
<a asp-controller="Ideation" asp-action="Overview" asp-route-id="@ViewBag.IdeationId" class="btn-default"><i class="fas fa-backward"></i> naar all ideeën</a>
}
<h3 id="ideation-reply-title" class="mb-0 mt-3 h4">@Model.CentralQuestion</h3>
<p id="ideation-reply-creator" class="mb-0"><span class="font-weight-bold">@Model.UserDisplayName</span> (<span class="font-italic" id="date-created">@Model.DateTime.FormatParasableDate()</span>)</p>
<a href="#" class="italic" id="report-button">Dit idee als ongepast melden</a>
</div>
<div class="w-25">
<div class="d-flex justify-content-between">
<p class="h6">
<span class="fas fa-arrow-up mr-2"></span><span id="votes-up">0</span>
</p>
<p class="h6">
<span class="fas fa-arrow-down mr-2"></span><span id="votes-down">0</span>
</p>
</div>
<div id="votes-display" class="progress">
<div id="progress" class="progress-bar">
</div>
</div>
<div id="vote-wrapper">
<button class="btn-default mb-3" id="button-like">Stem voor</button><button class="btn-default mb-3" id="button-dislike">Stem tegen</button>
</div>
</div>
</div>
<input type="hidden" value="@Model.IdeationReplyId" id="ideation-reply-id"/>
<input type="hidden" value="@Model.UserHasVoted" id="ideation-user-voted"/>
<input type="hidden" value="@Model.UpVotes" id="ideation-upvote-count"/>
<input type="hidden" value="@Model.DownVotes" id="ideation-downvote-count"/>
<input type="hidden" value="@ViewBag.IsMod" id="user-is-mod"/>
<input type="hidden" value="@ViewBag.HasReported" id="user-has-reported"/>
<input type="hidden" value="@Model.ReviewedByMod" id="post-reviewed"/>
<input type="hidden" value="@Model.Hidden" id="post-hidden"/>
<h5 class="mb-0 h4">@Model.Title</h5>
<div id="grid" class=" mb-3 mt-3">
@foreach (AnswerViewModel answer in Model.Answers)
{
<div class="ideation-answer grid-item">
<div class="ideation-header">
<p>@answer.QuestionString</p>
</div>
<div class="ideation-body">
@switch (answer.FieldType)
{
case FieldType.OpenText:
<p class="mb-0">@answer.OpenAnswer</p>
break;
case FieldType.DropDown:
case FieldType.SingleChoice:
<p class="mb-0">
<span class="fas fa-check mr-2"></span>@answer.SingleAnswer</p>
break;
case FieldType.MultipleChoice:
foreach (string text in answer.MultipleAnswer)
{
<p class="m-0">
<span class="fas fa-check mr-2"></span>@text</p>
}
break;
case FieldType.Image:
ViewBag.url = @answer.FileAnswer.Url.Contains("http") ? @answer.FileAnswer.Url : $"/uploads/{@answer.FileAnswer.Url}";
<img class="media" src="@ViewBag.url" alt="@answer.FileAnswer.Name"/>
break;
case FieldType.Video:
ViewBag.url = @answer.FileAnswer.Url.Contains("http") ? @answer.FileAnswer.Url : $"/uploads/{@answer.FileAnswer.Url}";
<video class="media" controls>
<source src="@ViewBag.url" type="video/mp4"/>
Your browser does not support the video tag.
</video>
break;
case FieldType.Location:
<img class="media" src="https://maps.googleapis.com/maps/api/staticmap?center=@(answer.LocationAnswer.Latitude),@(answer.LocationAnswer.Longitude)&zoom=@(answer.LocationAnswer.ZoomLevel)&size=600x300&markers=color:red%7C@(answer.LocationAnswer.Latitude),@(answer.LocationAnswer.Longitude)&key=AIzaSyAcjLH-kOiE6TOc84tcRYRewC9bPiRKqvo"/>
break;
}
</div>
</div>
}
</div>
@if (ViewBag.IsMod)
{
<div class="mod-box w-100 p-3 mb-3">
<p class="h4 mb-0">Beheerder acties</p>
@if (Model.IsFlagged)
{
<p class="text-danger mb-0">Deze post is als ongepast gemeld door gebruikers</p>
}
<div id="review-post" class="mt-2 mb-2">
</div>
<h3>Gerapporteerde reacties afhandelen:</h3>
<div id="reported-comment-section">
</div>
</div>
}
<h3>Reacties</h3>
<div id="comment-section">
</div>
@if (SignInManager.IsSignedIn(User))
{
<input type="hidden" id="user-name" value="@UserManager.GetUserAsync(User).Result.UserName"/>
<div id="new-comment" class="mb-3">
</div>
}
else
{
<p class="text-danger">Je moet ingelogd zijn om te kunnen reageren</p>
}
<div id="popup" class="modal">
</div>
</div> | 41.836601 | 363 | 0.529449 |
3fc058118f79c345f04572bd0a91aa35a422ca1a | 6,743 | cs | C# | mcs/class/Mono.CodeContracts/Mono.CodeContracts.Static.Analysis.ExpressionAnalysis/ExpressionDecoder.cs | bbourdon/mono | 1fd191a38b68b1c34af44063d2ecaf4e6e4ba0ae | [
"Apache-2.0"
] | 1 | 2015-11-08T22:16:54.000Z | 2015-11-08T22:16:54.000Z | mcs/class/Mono.CodeContracts/Mono.CodeContracts.Static.Analysis.ExpressionAnalysis/ExpressionDecoder.cs | pcc/mono | c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1 | [
"Apache-2.0"
] | null | null | null | mcs/class/Mono.CodeContracts/Mono.CodeContracts.Static.Analysis.ExpressionAnalysis/ExpressionDecoder.cs | pcc/mono | c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1 | [
"Apache-2.0"
] | null | null | null | //
// ExpressionDecoder.cs
//
// Authors:
// Alexander Chebaturkin (chebaturkin@gmail.com)
//
// Copyright (C) 2011 Alexander Chebaturkin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.CodeContracts.Static.AST;
using Mono.CodeContracts.Static.AST.Visitors;
using Mono.CodeContracts.Static.Analysis.ExpressionAnalysis.Expressions;
using Mono.CodeContracts.Static.Analysis.HeapAnalysis;
using Mono.CodeContracts.Static.ControlFlow;
using Mono.CodeContracts.Static.DataStructures;
using Mono.CodeContracts.Static.Lattices;
using Mono.CodeContracts.Static.Providers;
namespace Mono.CodeContracts.Static.Analysis.ExpressionAnalysis {
class ExpressionDecoder<TSymbolicValue, TContext, TEdgeData> :
IILDecoder<APC, LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue, IExpressionContextProvider<LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue>, TEdgeData>,
IExpressionContextProvider<LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue>,
IExpressionContext<LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue>
where TSymbolicValue : IEquatable<TSymbolicValue>
where TContext : IValueContextProvider<TSymbolicValue>
where TEdgeData : IImmutableMap<TSymbolicValue, LispList<TSymbolicValue>> {
private readonly IILDecoder<APC, TSymbolicValue, TSymbolicValue, IValueContextProvider<TSymbolicValue>, TEdgeData> value_decoder;
private readonly ExpressionAnalysisFacade<TSymbolicValue, TContext, TEdgeData> parent;
private readonly IValueContextProvider<TSymbolicValue> underlying;
public ExpressionDecoder (IILDecoder<APC, TSymbolicValue, TSymbolicValue, IValueContextProvider<TSymbolicValue>, TEdgeData> valueDecoder,
ExpressionAnalysisFacade<TSymbolicValue, TContext, TEdgeData> parent)
{
this.value_decoder = valueDecoder;
this.parent = parent;
this.underlying = valueDecoder.ContextProvider;
}
#region IExpressionContext<LabeledSymbol<APC,SymbolicValue>,SymbolicValue> Members
public LabeledSymbol<APC, TSymbolicValue> Refine (APC pc, TSymbolicValue variable)
{
return new LabeledSymbol<APC, TSymbolicValue> (pc, variable);
}
public TSymbolicValue Unrefine (LabeledSymbol<APC, TSymbolicValue> expression)
{
return expression.Symbol;
}
public Result Decode<Data, Result, Visitor> (LabeledSymbol<APC, TSymbolicValue> expr, Visitor visitor, Data data)
where Visitor : ISymbolicExpressionVisitor<LabeledSymbol<APC, TSymbolicValue>, LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue, Data, Result>
{
ExprDomain<TSymbolicValue> ifFound;
if (!this.parent.PreStateLookup (expr.ReadAt, out ifFound) || ifFound.IsBottom)
return visitor.SymbolicConstant (expr, expr.Symbol, data);
FlatDomain<Expr<TSymbolicValue>> aExpr = ifFound [expr.Symbol];
if (aExpr.IsNormal) {
return aExpr.Concrete.Decode<Data, Result, ExpressionDecoderAdapter<TSymbolicValue, Data, Result, Visitor>>
(expr.ReadAt, expr.Symbol,
new ExpressionDecoderAdapter<TSymbolicValue, Data, Result, Visitor> (visitor), data);
}
TypeNode type;
object constant;
if (this.parent.ValueLayer.ILDecoder.ContextProvider.ValueContext.IsConstant (expr.ReadAt, expr.Symbol, out type, out constant))
return visitor.LoadConst (expr, type, constant, expr.Symbol, data);
return visitor.SymbolicConstant (expr, expr.Symbol, data);
}
public FlatDomain<TypeNode> GetType (LabeledSymbol<APC, TSymbolicValue> expr)
{
return this.underlying.ValueContext.GetType (expr.ReadAt, expr.Symbol);
}
public APC GetPC (LabeledSymbol<APC, TSymbolicValue> pc)
{
return pc.ReadAt;
}
public LabeledSymbol<APC, TSymbolicValue> For (TSymbolicValue variable)
{
return new LabeledSymbol<APC, TSymbolicValue> (MethodContext.CFG.Entry, variable);
}
public bool IsZero (LabeledSymbol<APC, TSymbolicValue> expression)
{
return ValueContext.IsZero (expression.ReadAt, expression.Symbol);
}
#endregion
#region IILDecoder<APC,LabeledSymbol<APC,SymbolicValue>,SymbolicValue,IExpressionContextProvider<LabeledSymbol<APC,SymbolicValue>,SymbolicValue>,EdgeData> Members
public IExpressionContextProvider<LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue> ContextProvider
{
get { return this; }
}
public Result ForwardDecode<Data, Result, Visitor> (APC pc, Visitor visitor, Data state)
where Visitor : IILVisitor<APC, LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue, Data, Result>
{
return this.value_decoder.ForwardDecode<Data, Result, ILDecoderAdapter<TSymbolicValue, Data, Result, Visitor>>
(pc, new ILDecoderAdapter<TSymbolicValue, Data, Result, Visitor> (visitor), state);
}
public bool IsUnreachable (APC pc)
{
return this.parent.IsUnreachable (pc);
}
public TEdgeData EdgeData (APC from, APC to)
{
return this.parent.ValueLayer.ILDecoder.EdgeData (from, to);
}
#endregion
#region Implementation of IMethodContextProvider<Field,Method>
public IMethodContext MethodContext
{
get { return this.underlying.MethodContext; }
}
#endregion
#region Implementation of IStackContextProvider<Field,Method>
public IStackContext StackContext
{
get { return this.underlying.StackContext; }
}
#endregion
#region Implementation of IValueContextProvider<Local,Parameter,Method,Field,Type,SymbolicValue>
public IValueContext<TSymbolicValue> ValueContext
{
get { return this.underlying.ValueContext; }
}
#endregion
#region Implementation of IExpressionContextProvider<Local,Parameter,Method,Field,Type,ExternalExpression<APC,SymbolicValue>,SymbolicValue>
public IExpressionContext<LabeledSymbol<APC, TSymbolicValue>, TSymbolicValue> ExpressionContext
{
get { return this; }
}
#endregion
}
}
| 40.620482 | 164 | 0.776657 |
830c78f0b6df9068452d8437680ed97d7d4e582a | 2,163 | cs | C# | KinectLiveVis_RTX/Plugins/KinectV2/Source/ThirdParty/K4WLib/K4WLib.Build.cs | MariusKM/Integration-of-a-live-camera-feed-in-a-real-time-application-using-RTX | cc5c2fa3319fb93579498dea5cdcf59e3e69abc1 | [
"MIT"
] | null | null | null | KinectLiveVis_RTX/Plugins/KinectV2/Source/ThirdParty/K4WLib/K4WLib.Build.cs | MariusKM/Integration-of-a-live-camera-feed-in-a-real-time-application-using-RTX | cc5c2fa3319fb93579498dea5cdcf59e3e69abc1 | [
"MIT"
] | null | null | null | KinectLiveVis_RTX/Plugins/KinectV2/Source/ThirdParty/K4WLib/K4WLib.Build.cs | MariusKM/Integration-of-a-live-camera-feed-in-a-real-time-application-using-RTX | cc5c2fa3319fb93579498dea5cdcf59e3e69abc1 | [
"MIT"
] | null | null | null | // Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.IO;
public class K4WLib : ModuleRules
{
public K4WLib(ReadOnlyTargetRules Target) : base(Target)
{
Type = ModuleType.External;
string SDKDIR = Utils.ResolveEnvironmentVariable("%KINECTSDK20_DIR%");
SDKDIR = SDKDIR.Replace("\\", "/");
if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32))
{
string BaseDirectory = Path.GetFullPath(Path.Combine(ModuleDirectory, "..", ".."));
string RedistDirectory = Path.Combine(BaseDirectory, "ThirdParty", "Redist");
string ShortPlatform = (Target.Platform == UnrealTargetPlatform.Win64) ? "x64" : "x86";
PublicIncludePaths.Add(SDKDIR + "inc/");
string PlatformPath = (Target.Platform == UnrealTargetPlatform.Win64) ? "x64/" : "x86/";
string LibPath = SDKDIR + "Lib/" + PlatformPath;
PublicLibraryPaths.Add(LibPath);
PublicAdditionalLibraries.AddRange(new string[] { "Kinect20.lib", /*"Kinect20.face.lib" */});
PublicDelayLoadDLLs.AddRange(new string[] { /*"Kinect20.Face.dll",*/ "Kinect20.dll", /*"Microsoft.Kinect.Face.dll", /*vgbtechs/AdaBoostTech.dll", "vgbtechs/RFRProgressTech.dll" */});
/*
RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(RedistDirectory, "Face", ShortPlatform, "Kinect20.Face.dll")));
RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(RedistDirectory, "Face", ShortPlatform, "NuiDataBase")));
RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(RedistDirectory, "Face", ShortPlatform, "Microsoft.Kinect.Face.dll")));
RuntimeDependencies.Add(new RuntimeDependency(Path.Combine(RedistDirectory, "Face", ShortPlatform, "Microsoft.Kinect.Face.xml")));
*/
//PublicDelayLoadDLLs.AddRange(new string[] { "Kinect20.dll", "Kinect20.Face.dll","Microsoft.Kinect.Face.dll", /*vgbtechs/AdaBoostTech.dll", "vgbtechs/RFRProgressTech.dll" */});
}
}
}
| 42.411765 | 195 | 0.655109 |
9497469454acf666bb113a7a49dbe80a173ff55e | 125 | cs | C# | entry-point-processor/EntryPoint.Processor/MessageReceived.cs | afborgesDev/NetCoreIntegrationTestWithCoverage | 74a286d329704ae911b67628b48f63d34695b6c4 | [
"MIT"
] | null | null | null | entry-point-processor/EntryPoint.Processor/MessageReceived.cs | afborgesDev/NetCoreIntegrationTestWithCoverage | 74a286d329704ae911b67628b48f63d34695b6c4 | [
"MIT"
] | null | null | null | entry-point-processor/EntryPoint.Processor/MessageReceived.cs | afborgesDev/NetCoreIntegrationTestWithCoverage | 74a286d329704ae911b67628b48f63d34695b6c4 | [
"MIT"
] | null | null | null | namespace EntryPoint.Processor
{
public class MessageReceived
{
public string? Message { get; set; }
}
} | 17.857143 | 44 | 0.632 |
ab9bc4f9db95cf0cc5c07734a2e1907eb74feb05 | 223 | cs | C# | ConfigSections/SotrageSection.cs | arenchen/Netcorext.Configuration.Abstractions | 7bc186b4f8f8e3d4c588cdb27bea8fda22be7b4e | [
"MIT"
] | null | null | null | ConfigSections/SotrageSection.cs | arenchen/Netcorext.Configuration.Abstractions | 7bc186b4f8f8e3d4c588cdb27bea8fda22be7b4e | [
"MIT"
] | null | null | null | ConfigSections/SotrageSection.cs | arenchen/Netcorext.Configuration.Abstractions | 7bc186b4f8f8e3d4c588cdb27bea8fda22be7b4e | [
"MIT"
] | null | null | null | namespace Netcorext.Configuration.Abstractions.ConfigSections;
public class SotrageSection
{
public Dictionary<string, string> Local { get; set; }
public GoogleCloudStorageSection GoogleCloudStorage { get; set; }
} | 31.857143 | 69 | 0.789238 |
466478493119761fdb22d41e5e9e200d11b7514a | 914 | cs | C# | wallet-service.integration/Data/Contexts/WalletsContext.cs | ihiresolutions/investec-api-wallet-service | aa2f5d4de68def1a0e0c84a0df37626576500971 | [
"MIT"
] | null | null | null | wallet-service.integration/Data/Contexts/WalletsContext.cs | ihiresolutions/investec-api-wallet-service | aa2f5d4de68def1a0e0c84a0df37626576500971 | [
"MIT"
] | null | null | null | wallet-service.integration/Data/Contexts/WalletsContext.cs | ihiresolutions/investec-api-wallet-service | aa2f5d4de68def1a0e0c84a0df37626576500971 | [
"MIT"
] | null | null | null | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using wallet_service.integration.contract.Models;
namespace wallet_service.integration.Data.Contexts
{
public class WalletsContext : DbContext
{
#region Constructors
public WalletsContext(DbContextOptions<WalletsContext> options)
: base(options)
{
}
#endregion
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Wallet>().ToTable("wallets");
modelBuilder.Entity<Transaction>().ToTable("transactions")
.HasOne(p => p.Wallet)
.WithMany(p => p.Transactions);
}
#region Properties
public DbSet<Wallet> Wallets { get; set; }
public DbSet<Transaction> Transactions { get; set; }
#endregion
}
}
| 25.388889 | 74 | 0.63895 |
580c5211bb2e5e21ea015f0f4efcf1f8c505516b | 688 | cs | C# | Havit.GoogleAnalytics/ParameterValueAttribute.cs | havit/HavitFramework | cc23bd0070a4becb2ce990e696022eb62662973a | [
"MIT"
] | 23 | 2019-05-08T07:15:12.000Z | 2022-01-27T06:44:25.000Z | Havit.GoogleAnalytics/ParameterValueAttribute.cs | havit/HavitFramework | cc23bd0070a4becb2ce990e696022eb62662973a | [
"MIT"
] | null | null | null | Havit.GoogleAnalytics/ParameterValueAttribute.cs | havit/HavitFramework | cc23bd0070a4becb2ce990e696022eb62662973a | [
"MIT"
] | 2 | 2021-10-15T06:36:51.000Z | 2022-01-25T22:23:10.000Z | using System;
using System.Collections.Generic;
using System.Text;
namespace Havit.GoogleAnalytics
{
/// <summary>
/// Attribute that defines value for the enum
/// </summary>
public class ParameterValueAttribute : Attribute
{
/// <summary>
/// Value of the enum that is serialized into a query parameter
/// </summary>
public string Value { get; }
/// <summary>
/// Public constructor
/// </summary>
/// <param name="value">Value of the enum that is serialized into a query parameter</param>
public ParameterValueAttribute(string value)
{
Value = value;
}
}
}
| 25.481481 | 99 | 0.593023 |
e600d5da19329d3552b48592495d73d94bc2d34b | 727 | cs | C# | Unremastered Files/ARX8.Core/script/ARX_Script_PositionChildren.cs | VelvetAlabaster/ARX | 0a125e8f6e06f220ea3b1493b6e71cb233046fef | [
"CC0-1.0"
] | null | null | null | Unremastered Files/ARX8.Core/script/ARX_Script_PositionChildren.cs | VelvetAlabaster/ARX | 0a125e8f6e06f220ea3b1493b6e71cb233046fef | [
"CC0-1.0"
] | null | null | null | Unremastered Files/ARX8.Core/script/ARX_Script_PositionChildren.cs | VelvetAlabaster/ARX | 0a125e8f6e06f220ea3b1493b6e71cb233046fef | [
"CC0-1.0"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Positions the children of this object in a line
/// </summary>
[ExecuteInEditMode]
public class ARX_Script_PositionChildren : MonoBehaviour
{
public Vector3 mvec_positionOffset;
public int mn_perRow = 1;
// Update is called once per frame
void Update()
{
for (int i = 0; i < transform.childCount; i++)
{
int nRow = i % mn_perRow;
int nColumn = i / mn_perRow;
int nStack = 0;
transform.GetChild(i).localPosition = new Vector3(mvec_positionOffset.x * nRow, mvec_positionOffset.y * nStack, mvec_positionOffset.z * nColumn);
}
}
}
| 27.961538 | 157 | 0.645117 |
176f8e97dede40e3cd62b42fde60767169162a37 | 630 | cs | C# | src/ClashOfClans.Models/ClanWarMember.cs | tparviainen/clashofclans | e59d87c7e59ca04338a9f8e484943dba453b024b | [
"MIT"
] | 13 | 2020-01-11T09:20:32.000Z | 2022-01-04T03:34:09.000Z | src/ClashOfClans.Models/ClanWarMember.cs | tparviainen/clashofclans | e59d87c7e59ca04338a9f8e484943dba453b024b | [
"MIT"
] | 18 | 2019-07-26T22:34:21.000Z | 2022-01-01T14:13:35.000Z | src/ClashOfClans.Models/ClanWarMember.cs | tparviainen/clashofclans | e59d87c7e59ca04338a9f8e484943dba453b024b | [
"MIT"
] | 2 | 2019-08-03T22:08:27.000Z | 2022-01-04T03:34:30.000Z | namespace ClashOfClans.Models
{
public class ClanWarMember : Identity
{
private int? _townhallLevel;
private int? _mapPosition;
private int? _opponentAttacks;
public int TownhallLevel { get => _townhallLevel ?? default; set => _townhallLevel = value; }
public int MapPosition { get => _mapPosition ?? default; set => _mapPosition = value; }
public ClanWarAttackList? Attacks { get; set; }
public int OpponentAttacks { get => _opponentAttacks ?? default; set => _opponentAttacks = value; }
public ClanWarAttack? BestOpponentAttack { get; set; }
}
}
| 31.5 | 107 | 0.657143 |
1787f959105417b2af4478d55baa3c5effdafca8 | 23,734 | cs | C# | Tests/Linq/Linq/JoinTest.cs | Vclcl/linq2db | b9c2c8f10e3eff9d1e011c82a9c53fab2873ca03 | [
"MIT"
] | null | null | null | Tests/Linq/Linq/JoinTest.cs | Vclcl/linq2db | b9c2c8f10e3eff9d1e011c82a9c53fab2873ca03 | [
"MIT"
] | null | null | null | Tests/Linq/Linq/JoinTest.cs | Vclcl/linq2db | b9c2c8f10e3eff9d1e011c82a9c53fab2873ca03 | [
"MIT"
] | null | null | null | using System;
using System.Linq;
using LinqToDB;
using LinqToDB.Mapping;
using NUnit.Framework;
namespace Tests.Linq
{
using Model;
[TestFixture]
public class JoinTest : TestBase
{
[Test]
public void InnerJoin1([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in db.Person on p1.ID equals p2.ID
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.FirstName });
}
[Test]
public void InnerJoin2([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in db.Person on new { p1.ID, p1.FirstName } equals new { p2.ID, p2.FirstName }
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.FirstName });
}
[Test]
public void InnerJoin3([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in
from p2 in db.Person join p3 in db.Person on new { p2.ID, p2.LastName } equals new { p3.ID, p3.LastName } select new { p2, p3 }
on new { p1.ID, p1.FirstName } equals new { p2.p2.ID, p2.p2.FirstName }
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.p2.FirstName, LastName = p2.p3.LastName });
}
[Test]
public void InnerJoin4([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in db.Person on new { p1.ID, p1.FirstName } equals new { p2.ID, p2.FirstName }
join p3 in db.Person on new { p2.ID, p2.LastName } equals new { p3.ID, p3.LastName }
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.FirstName, LastName = p3.LastName });
}
[Test]
public void InnerJoin5([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in db.Person on new { p1.ID, p1.FirstName } equals new { p2.ID, p2.FirstName }
join p3 in db.Person on new { p1.ID, p2.LastName } equals new { p3.ID, p3.LastName }
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.FirstName, LastName = p3.LastName });
}
[Test]
public void InnerJoin6([DataContexts] string context)
{
using (var db = GetDataContext(context))
TestJohn(
from p1 in db.Person
join p2 in from p3 in db.Person select new { ID = p3.ID + 1, p3.FirstName } on p1.ID equals p2.ID - 1
where p1.ID == 1
select new Person { ID = p1.ID, FirstName = p2.FirstName });
}
[Test]
public void InnerJoin7([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from t in
from ch in Child
join p in Parent on ch.ParentID equals p.ParentID
select ch.ParentID + p.ParentID
where t > 2
select t
,
from t in
from ch in db.Child
join p in db.Parent on ch.ParentID equals p.ParentID
select ch.ParentID + p.ParentID
where t > 2
select t);
}
[Test]
public void InnerJoin8([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from t in
from ch in Child
join p in Parent on ch.ParentID equals p.ParentID
select new { ID = ch.ParentID + p.ParentID }
where t.ID > 2
select t,
from t in
from ch in db.Child
join p in db.Parent on ch.ParentID equals p.ParentID
select new { ID = ch.ParentID + p.ParentID }
where t.ID > 2
select t);
}
[Test]
public void InnerJoin9([DataContexts(ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from g in GrandChild
join p in Parent4 on g.Child.ParentID equals p.ParentID
where g.ParentID < 10 && p.Value1 == TypeValue.Value3
select g,
from g in db.GrandChild
join p in db.Parent4 on g.Child.ParentID equals p.ParentID
where g.ParentID < 10 && p.Value1 == TypeValue.Value3
select g);
}
[Test]
public void InnerJoin10([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join g in GrandChild on p.ParentID equals g.ParentID into q
from q1 in q
select new { p.ParentID, q1.GrandChildID },
from p in db.Parent
join g in db.GrandChild on p.ParentID equals g.ParentID into q
from q1 in q
select new { p.ParentID, q1.GrandChildID });
}
[Test]
public void GroupJoin1([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select p,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select p);
}
[Test]
public void GroupJoin2([DataContexts] string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID into lj
where p.ParentID == 1
select new { p, lj };
var list = q.ToList();
Assert.AreEqual(1, list.Count);
Assert.AreEqual(1, list[0].p.ParentID);
Assert.AreEqual(1, list[0].lj.Count());
var ch = list[0].lj.ToList();
Assert.AreEqual( 1, ch[0].ParentID);
Assert.AreEqual(11, ch[0].ChildID);
}
}
[Test]
public void GroupJoin3([DataContexts] string context)
{
using (var db = GetDataContext(context))
{
var q1 = Parent
.GroupJoin(
Child,
p => p.ParentID,
ch => ch.ParentID,
(p, lj1) => new { p, lj1 = new { lj1 } }
)
.Where (t => t.p.ParentID == 2)
.Select(t => new { t.p, t.lj1 });
var list1 = q1.ToList();
var q2 = db.Parent
.GroupJoin(
db.Child,
p => p.ParentID,
ch => ch.ParentID,
(p, lj1) => new { p, lj1 = new { lj1 } }
)
.Where (t => t.p.ParentID == 2)
.Select(t => new { t.p, t.lj1 });
var list2 = q2.ToList();
Assert.AreEqual(list1.Count, list2.Count);
Assert.AreEqual(list1[0].p.ParentID, list2[0].p.ParentID);
Assert.AreEqual(list1[0].lj1.lj1.Count(), list2[0].lj1.lj1.Count());
}
}
[Test]
public void GroupJoin4([DataContexts] string context)
{
using (var db = GetDataContext(context))
{
var q1 =
from p in Parent
join ch in
from c in Child select new { c.ParentID, c.ChildID }
on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 3
select new { p, lj1 };
var list1 = q1.ToList();
var q2 =
from p in db.Parent
join ch in
from c in db.Child select new { c.ParentID, c.ChildID }
on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 3
select new { p, lj1 };
var list2 = q2.ToList();
Assert.AreEqual(list1.Count, list2.Count);
Assert.AreEqual(list1[0].p.ParentID, list2[0].p.ParentID);
Assert.AreEqual(list1[0].lj1.Count(), list2[0].lj1.Count());
}
}
[Test]
public void GroupJoin5([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.First()
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.First());
}
[Test]
public void GroupJoin51([DataContexts] string context)
{
using (var db = GetDataContext(context))
{
var result =
(
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select new { p1 = lj1, p2 = lj1.First() }
).ToList();
var expected =
(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select new { p1 = lj1, p2 = lj1.First() }
).ToList();
Assert.AreEqual(expected.Count, result.Count);
AreEqual(expected[0].p1, result[0].p1);
}
}
[Test]
public void GroupJoin52([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.First().ParentID
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.First().ParentID);
}
[Test]
public void GroupJoin53([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.Select(_ => _.ParentID).First()
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select lj1.Select(_ => _.ParentID).First());
}
[Test]
public void GroupJoin54([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select new { p1 = lj1.Count(), p2 = lj1.First() }
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
where p.ParentID == 1
select new { p1 = lj1.Count(), p2 = lj1.First() });
}
[Test]
public void GroupJoin6([DataContexts] string context)
{
var n = 1;
using (var db = GetDataContext(context))
{
var q1 =
from p in Parent
join c in Child on p.ParentID + n equals c.ParentID into lj
where p.ParentID == 1
select new { p, lj };
var list1 = q1.ToList();
var ch1 = list1[0].lj.ToList();
var q2 =
from p in db.Parent
join c in db.Child on p.ParentID + n equals c.ParentID into lj
where p.ParentID == 1
select new { p, lj };
var list2 = q2.ToList();
Assert.AreEqual(list1.Count, list2.Count);
Assert.AreEqual(list1[0].p.ParentID, list2[0].p.ParentID);
Assert.AreEqual(list1[0].lj.Count(), list2[0].lj.Count());
var ch2 = list2[0].lj.ToList();
Assert.AreEqual(ch1[0].ParentID, ch2[0].ParentID);
Assert.AreEqual(ch1[0].ChildID, ch2[0].ChildID);
}
}
[Test]
public void GroupJoin7([DataContexts(ProviderName.Firebird)] string context)
{
var n = 1;
using (var db = GetDataContext(context))
{
var q1 =
from p in Parent
join c in Child on new { id = p.ParentID } equals new { id = c.ParentID - n } into j
where p.ParentID == 1
select new { p, j };
var list1 = q1.ToList();
var ch1 = list1[0].j.ToList();
var q2 =
from p in db.Parent
join c in db.Child on new { id = p.ParentID } equals new { id = c.ParentID - n } into j
where p.ParentID == 1
select new { p, j };
var list2 = q2.ToList();
Assert.AreEqual(list1.Count, list2.Count);
Assert.AreEqual(list1[0].p.ParentID, list2[0].p.ParentID);
Assert.AreEqual(list1[0].j.Count(), list2[0].j.Count());
var ch2 = list2[0].j.ToList();
Assert.AreEqual(ch1[0].ParentID, ch2[0].ParentID);
Assert.AreEqual(ch1[0].ChildID, ch2[0].ChildID);
}
}
[Test]
public void GroupJoin8([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join c in Child on p.ParentID equals c.ParentID into g
select new { Child = g.FirstOrDefault() }
,
from p in db.Parent
join c in db.Child on p.ParentID equals c.ParentID into g
select new { Child = g.FirstOrDefault() });
}
[Test]
public void GroupJoin9([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
Parent
.GroupJoin(
Parent,
x => new { Id = x.ParentID },
y => new { Id = y.ParentID },
(xid, yid) => new { xid, yid }
)
.SelectMany(
y => y.yid.DefaultIfEmpty(),
(x1, y) => new { x1.xid, y }
)
.GroupJoin(
Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x2, y) => new { x2.xid, x2.y, h = y }
)
.SelectMany(
a => a.h.DefaultIfEmpty(),
(x3, a) => new { x3.xid, x3.y, a }
)
.GroupJoin(
Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x4, y) => new { x4.xid, x4.y, x4.a, p = y }
)
.SelectMany(
z => z.p.DefaultIfEmpty(),
(x5, z) => new { x5.xid, z, x5.y, x5.a }
)
.GroupJoin(
Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.Value1 ?? 1 },
(x6, y) => new { x6.xid, xy = x6.y, x6.a, x6.z, y }
)
.SelectMany(
z => z.y.DefaultIfEmpty(),
(x7, z) => new { x7.xid, z, x7.xy, x7.a, xz = x7.z }
)
.GroupJoin(
Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x8, y) => new { x8.xid, x8.z, x8.xy, x8.a, x8.xz, y }
)
.SelectMany(
a => a.y.DefaultIfEmpty(),
(x9, a) => new { x9.xid, x9.z, x9.xy, xa = x9.a, x9.xz, a }
),
db.Parent
.GroupJoin(
db.Parent,
x => new { Id = x.ParentID },
y => new { Id = y.ParentID },
(xid, yid) => new { xid, yid }
)
.SelectMany(
y => y.yid.DefaultIfEmpty(),
(x1, y) => new { x1.xid, y }
)
.GroupJoin(
db.Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x2, y) => new { x2.xid, x2.y, h = y }
)
.SelectMany(
a => a.h.DefaultIfEmpty(),
(x3, a) => new { x3.xid, x3.y, a }
)
.GroupJoin(
db.Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x4, y) => new { x4.xid, x4.y, x4.a, p = y }
)
.SelectMany(
z => z.p.DefaultIfEmpty(),
(x5, z) => new { x5.xid, z, x5.y, x5.a }
)
.GroupJoin(
db.Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.Value1 ?? 1 },
(x6, y) => new { x6.xid, xy = x6.y, x6.a, x6.z, y }
)
.SelectMany(
z => z.y.DefaultIfEmpty(),
(x7, z) => new { x7.xid, z, x7.xy, x7.a, xz = x7.z }
)
.GroupJoin(
db.Parent,
x => new { Id = x.xid.ParentID },
y => new { Id = y.ParentID },
(x8, y) => new { x8.xid, x8.z, x8.xy, x8.a, x8.xz, y }
)
.SelectMany(
a => a.y.DefaultIfEmpty(),
(x9, a) => new { x9.xid, x9.z, x9.xy, xa = x9.a, x9.xz, a }
));
}
[Test]
public void LeftJoin1([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
where p.ParentID >= 4
select new { p, ch }
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
where p.ParentID >= 4
select new { p, ch });
}
[Test]
public void LeftJoin2([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in Child on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
select new { p, ch }
,
from p in db.Parent
join ch in db.Child on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
select new { p, ch });
}
[Test]
public void LeftJoin3([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from c in Child select c.Parent,
from c in db.Child select c.Parent);
}
[Test]
public void LeftJoin4([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
Parent
.GroupJoin(Child,
x => new { x.ParentID, x.Value1 },
y => new { y.ParentID, Value1 = (int?)y.ParentID },
(x, y) => new { Parent = x, Child = y })
.SelectMany(
y => y.Child.DefaultIfEmpty(),
(x, y) => new { x.Parent, Child = x.Child.FirstOrDefault() })
.Where(x => x.Parent.ParentID == 1 && x.Parent.Value1 != null)
.OrderBy(x => x.Parent.ParentID)
,
db.Parent
.GroupJoin(db.Child,
x => new { x.ParentID, x.Value1 },
y => new { y.ParentID, Value1 = (int?)y.ParentID },
(x, y) => new { Parent = x, Child = y })
.SelectMany(
y => y.Child.DefaultIfEmpty(),
(x, y) => new { x.Parent, Child = x.Child.FirstOrDefault() })
.Where(x => x.Parent.ParentID == 1 && x.Parent.Value1 != null)
.OrderBy(x => x.Parent.ParentID));
}
[Table("Child")]
public class CountedChild
{
public static int Count;
public CountedChild()
{
Count++;
}
[Column] public int ParentID;
[Column] public int ChildID;
}
[Test]
public void LeftJoin5([DataContexts] string context)
{
using (var db = GetDataContext(context))
{
var q =
from p in db.Parent
join ch in db.GetTable<CountedChild>() on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
where ch == null
select new { p, ch, ch1 = ch };
CountedChild.Count = 0;
var list = q.ToList();
Assert.AreEqual(0, CountedChild.Count);
}
}
[Test]
public void SubQueryJoin([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join ch in
from c in Child
where c.ParentID > 0
select new { c.ParentID, c.ChildID }
on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
select p
,
from p in db.Parent
join ch in
from c in db.Child
where c.ParentID > 0
select new { c.ParentID, c.ChildID }
on p.ParentID equals ch.ParentID into lj1
from ch in lj1.DefaultIfEmpty()
select p);
}
[Test]
public void ReferenceJoin1([DataContexts(ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from c in Child join g in GrandChild on c equals g.Child select new { c.ParentID, g.GrandChildID },
from c in db.Child join g in db.GrandChild on c equals g.Child select new { c.ParentID, g.GrandChildID });
}
[Test]
public void ReferenceJoin2([DataContexts(ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from g in GrandChild
join c in Child on g.Child equals c
select new { c.ParentID, g.GrandChildID },
from g in db.GrandChild
join c in db.Child on g.Child equals c
select new { c.ParentID, g.GrandChildID });
}
[Test]
public void JoinByAnonymousTest([DataContexts(ProviderName.Access)] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join c in Child on new { Parent = p, p.ParentID } equals new { c.Parent, c.ParentID }
select new { p.ParentID, c.ChildID },
from p in db.Parent
join c in db.Child on new { Parent = p, p.ParentID } equals new { c.Parent, c.ParentID }
select new { p.ParentID, c.ChildID });
}
[Test]
public void FourTableJoin([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p in Parent
join c1 in Child on p.ParentID equals c1.ParentID
join c2 in GrandChild on c1.ParentID equals c2.ParentID
join c3 in GrandChild on c2.ParentID equals c3.ParentID
select new { p, c1Key = c1.ChildID, c2Key = c2.GrandChildID, c3Key = c3.GrandChildID }
,
from p in db.Parent
join c1 in db.Child on p.ParentID equals c1.ParentID
join c2 in db.GrandChild on c1.ParentID equals c2.ParentID
join c3 in db.GrandChild on c2.ParentID equals c3.ParentID
select new { p, c1Key = c1.ChildID, c2Key = c2.GrandChildID, c3Key = c3.GrandChildID });
}
[Test]
public void ProjectionTest1([DataContexts] string context)
{
using (var db = GetDataContext(context))
AreEqual(
from p1 in Person
join p2 in Person on p1.ID equals p2.ID
select new { ID1 = new { Value = p1.ID }, FirstName2 = p2.FirstName, } into p1
select p1.ID1.Value
,
from p1 in db.Person
join p2 in db.Person on p1.ID equals p2.ID
select new { ID1 = new { Value = p1.ID }, FirstName2 = p2.FirstName, } into p1
select p1.ID1.Value);
}
[Test]
public void LeftJoinTest([DataContexts] string context)
{
// Reproduces the problem described here: http://rsdn.ru/forum/prj.rfd/4221837.flat.aspx
using (var db = GetDataContext(context))
{
var q =
from p1 in db.Person
join p2 in db.Person on p1.ID equals p2.ID into g
from p2 in g.DefaultIfEmpty() // yes I know the join will always succeed and it'll never be null, but just for test's sake :)
select new { p1, p2 };
var list = q.ToList(); // NotImplementedException? :(
Assert.That(list, Is.Not.Empty);
}
}
[Test]
public void LeftJoinTest2([IncludeDataContexts(ProviderName.SQLite)] string context)
{
// THIS TEST MUST BE RUN IN RELEASE CONFIGURATION (BECAUSE IT PASSES UNDER DEBUG CONFIGURATION)
// Reproduces the problem described here: http://rsdn.ru/forum/prj.rfd/4221837.flat.aspx
using (var db = GetDataContext(context))
{
var q =
from p1 in db.Patient
join p2 in db.Patient on p1.Diagnosis equals p2.Diagnosis into g
from p2 in g.DefaultIfEmpty() // yes I know the join will always succeed and it'll never be null, but just for test's sake :)
join p3 in db.Person on p2.PersonID equals p3.ID
select new { p1, p2, p3 };
var arr = q.ToArray(); // NotImplementedException? :(
Assert.That(arr, Is.Not.Empty);
}
}
[Test]
public void StackOverflow([IncludeDataContexts(ProviderName.SqlServer2008)] string context)
{
using (var db = GetDataContext(context))
{
var q =
from c in db.Child
join p in db.Parent on c.ParentID equals p.ParentID
select new { p, c };
for (var i = 0; i < 100; i++)
{
q =
from c in q
join p in db.Parent on c.p.ParentID equals p.ParentID
select new { p, c.c };
}
var list = q.ToList();
}
}
[Test]
public void ApplyJoin([IncludeDataContexts(ProviderName.SqlServer2008)] string context)
{
using (var db = GetDataContext(context))
{
var q =
from ch in db.Child
from p in new Model.Functions(db).GetParentByID(ch.Parent.ParentID)
select p;
q.ToList();
}
}
}
}
| 29.121472 | 135 | 0.575082 |
4a92a5f738b160ec5e7bb6f383bbf58d9d9f494d | 1,053 | cs | C# | StacksAndQueues/PoisonousPlants/Tester.cs | BoykoNeov/C-Sharp-Advanced---SoftUni | 53c17e6c75df402eb28ff0f3a659be8d73a2d21d | [
"MIT"
] | null | null | null | StacksAndQueues/PoisonousPlants/Tester.cs | BoykoNeov/C-Sharp-Advanced---SoftUni | 53c17e6c75df402eb28ff0f3a659be8d73a2d21d | [
"MIT"
] | null | null | null | StacksAndQueues/PoisonousPlants/Tester.cs | BoykoNeov/C-Sharp-Advanced---SoftUni | 53c17e6c75df402eb28ff0f3a659be8d73a2d21d | [
"MIT"
] | null | null | null | namespace PoisonousPlants
{
using System;
public class Tester
{
public static string TestForDifference()
{
Random rnd = new Random();
int[] testArray = new int[10];
int resultA = -1;
int resultB = -1;
while (resultA == resultB)
{
resultA = PoisonousPlantsStartUp.GetResult(string.Join(" ", testArray), testArray.Length);
resultB = LnkedListSolution.TrivialSolutionUsingLinkedList(string.Join(" ", testArray));
testArray = RandomizeArray(10, rnd, 1, 20);
}
return (string.Join(" ", testArray));
}
private static int[] RandomizeArray (int arraySize, Random randomInstance, int minValue, int maxValue)
{
int[] testArray = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
testArray[i] = randomInstance.Next(minValue, maxValue);
}
return testArray;
}
}
} | 26.325 | 110 | 0.528015 |
99b6cc2550826d69fc1029607ca29c54f2fb7a29 | 696 | cs | C# | src/Scrummy/Domain.Core/Exceptions/EntityValidationException.cs | jan-kelemen/scrummy | 175229d59dad2b0794cf969bfed9d89b93c48666 | [
"MIT"
] | 1 | 2018-08-20T14:34:59.000Z | 2018-08-20T14:34:59.000Z | src/Scrummy/Domain.Core/Exceptions/EntityValidationException.cs | jan-kelemen/scrummy | 175229d59dad2b0794cf969bfed9d89b93c48666 | [
"MIT"
] | 1 | 2018-08-20T18:33:15.000Z | 2018-08-20T18:33:15.000Z | src/Scrummy/Domain.Core/Exceptions/EntityValidationException.cs | jan-kelemen/scrummy | 175229d59dad2b0794cf969bfed9d89b93c48666 | [
"MIT"
] | null | null | null | using System;
using System.Runtime.Serialization;
namespace Scrummy.Domain.Core.Exceptions
{
public class EntityValidationException : EntityException
{
public EntityValidationException()
{
}
public EntityValidationException(string message) : base(message)
{
}
public EntityValidationException(string message, Exception innerException) : base(message, innerException)
{
}
protected EntityValidationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public string ErrorKey { get; set; }
public string ErrorMessage { get; set; }
}
}
| 24 | 115 | 0.655172 |
99d6a1597ae02953096abdd32512e142da81bab8 | 1,138 | cshtml | C# | NexmoDotnetCodeSnippets/Views/Redact/index.cshtml | DavidMelkonyan1997/nexmo-dotnet-code-snippets | d0b4853db7b94c8d5c494383465136a4e0527d20 | [
"MIT"
] | 1 | 2021-04-02T14:17:32.000Z | 2021-04-02T14:17:32.000Z | NexmoDotnetCodeSnippets/Views/Redact/index.cshtml | DavidMelkonyan1997/nexmo-dotnet-code-snippets | d0b4853db7b94c8d5c494383465136a4e0527d20 | [
"MIT"
] | null | null | null | NexmoDotnetCodeSnippets/Views/Redact/index.cshtml | DavidMelkonyan1997/nexmo-dotnet-code-snippets | d0b4853db7b94c8d5c494383465136a4e0527d20 | [
"MIT"
] | null | null | null | <header>
<h1>Code samples for using Nexmo Redact</h1>
</header>
<div style="width:50%; padding-top:10px">
<div class="content">
<div class="title" style="height:20px; background-color:cornflowerblue; text-align:center">
<span style="vertical-align:central; text-align:center">Create an application</span>
</div>
<div style="padding-top:10px">
@using (Html.BeginForm("RedactWithId", "Redact", FormMethod.Post))
{
<input type="text" name="id" id="id" placeholder="id" style="height:30px" />
@Html.DropDownList("product", new SelectList(Enum.GetValues(typeof(RedactModel.RedactProduct))), "Select Product", new { @class = "form-control", @style = "height:30px" })
@Html.DropDownList("type", new SelectList(Enum.GetValues(typeof(RedactModel.RedactType))), "Select Type (sms only)", new { @class = "form-control", @style = "height:30px" })
<input type="submit" value="redact" style="height:30px;" />
}
<h2>@ViewBag.redactResult</h2>
</div>
</div>
</div> | 54.190476 | 205 | 0.595782 |
0729704f638dc1011d12911af0d7e9a41434674f | 1,218 | cs | C# | Assets/Plug Ins/UmbraEvolution/General/CustomAttributes/LessThanInt.cs | snakenjah/MagicPopote | 8429ac81538da037e52d08faa3f2ab6b9ca39be7 | [
"MIT"
] | null | null | null | Assets/Plug Ins/UmbraEvolution/General/CustomAttributes/LessThanInt.cs | snakenjah/MagicPopote | 8429ac81538da037e52d08faa3f2ab6b9ca39be7 | [
"MIT"
] | null | null | null | Assets/Plug Ins/UmbraEvolution/General/CustomAttributes/LessThanInt.cs | snakenjah/MagicPopote | 8429ac81538da037e52d08faa3f2ab6b9ca39be7 | [
"MIT"
] | null | null | null | //Name: Robert MacGillivray
//File: LessThanInt.cs
//Date: Nov.23.2015
//Purpose: To make a class for my LessThanIntInclusive property drawer to be accessed and to store the appropriate less than X integer value
//Last Updated: Dec.01.2015 by Robert MacGillivray
using UnityEngine;
using System.Collections;
namespace UmbraEvolution
{
/// <summary>
/// Accesses the LessThanInclusive property which limits a float or integer in the inspector to any value less or equal to the provided value.
/// </summary>
public class LessThanIntAttribute : PropertyAttribute
{
public int lessThanInteger;
public bool inclusive;
/// <summary>
/// Uses an int for the less than comparison
/// </summary>
/// <param name="lessThanInt">The integer that will be used to limit the value of this variable</param>
/// <param name="inclusive">If true, a less than or equal comparison will be used. If false, a non-inclusive less than comparison will be used.</param>
public LessThanIntAttribute(int lessThanInteger, bool inclusive)
{
this.lessThanInteger = lessThanInteger;
this.inclusive = inclusive;
}
}
}
| 36.909091 | 159 | 0.688834 |
cacbf5d3cfdf40ab355d6811b2d039a97afb6cf9 | 1,736 | cs | C# | Tida.Canvas.Shell/Canvas/StatusBar/InitializeStatusBarEventHandlerForCanvas.cs | JanusTida/Tida.CAD | c81de25141d82346f54e2ff8dc85113bd88d2e95 | [
"MIT"
] | 38 | 2019-04-16T13:37:22.000Z | 2022-01-13T05:26:25.000Z | Tida.Canvas.Shell/Canvas/StatusBar/InitializeStatusBarEventHandlerForCanvas.cs | JanusTida/Tida.CAD | c81de25141d82346f54e2ff8dc85113bd88d2e95 | [
"MIT"
] | 2 | 2020-10-27T20:19:13.000Z | 2021-12-11T18:25:49.000Z | Tida.Canvas.Shell/Canvas/StatusBar/InitializeStatusBarEventHandlerForCanvas.cs | JanusTida/Tida.CAD | c81de25141d82346f54e2ff8dc85113bd88d2e95 | [
"MIT"
] | 17 | 2019-05-23T14:25:12.000Z | 2021-11-25T12:33:51.000Z | using Tida.Canvas.Shell.Contracts.App;
using Tida.Canvas.Shell.Contracts.Canvas;
using Tida.Canvas.Shell.Contracts.Canvas.Events;
using Tida.Canvas.Shell.Contracts.StatusBar;
using Tida.Canvas.Shell.Contracts.StatusBar.Events;
using System.ComponentModel.Composition;
using Tida.Canvas.Shell.Contracts.Common;
namespace Tida.Canvas.Shell.Canvas.StatusBar {
/// <summary>
/// 状态栏初始化时加入画布相关信息及调节选项;
/// </summary>
[Export(typeof(IStatusBarInitializeEventHandler))]
class InitializeStatusBarEventHandlerForCanvas : IStatusBarInitializeEventHandler {
public bool IsEnabled => true;
public int Sort => 4;
public void Handle(IStatusBarService statusBarService) {
if(statusBarService == null) {
return;
}
//画布当前鼠标位置发生变化时,通知状态栏;
CommonEventHelper.GetEvent<CanvasCurrentMousePositionChangedEvent>().Subscribe(CanvasDataContext_CurrentMousePositionChanged);
}
/// <summary>
/// 画布当前鼠标位置发生变化时,通知状态栏;
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CanvasDataContext_CurrentMousePositionChanged(ICanvasDataContext canvasDataContext) {
var currentPosition = CanvasService.CanvasDataContext.CurrentMousePosition;
if(currentPosition == null) {
return;
}
StatusBarService.Report(
LanguageService.TryGetStringWithFormat(
Constants.LanguageFormat_CurrentMousePosition,
currentPosition.X.ToString("F4"),
currentPosition.Y.ToString("F4")
)
);
}
}
}
| 34.72 | 138 | 0.640553 |
88d30d54887e1fc8c974950687599a07c1b819ed | 2,966 | cs | C# | src/STACK/Components/Graphics/SpriteCustomAnimation.cs | advdotnet/AdventuresDotNet | df16f1cc40ebcd0934c92fcd488f6a4a116ea7f5 | [
"MS-PL"
] | 16 | 2017-11-24T23:19:51.000Z | 2022-01-12T23:29:55.000Z | src/STACK/Components/Graphics/SpriteCustomAnimation.cs | advdotnet/AdventuresDotNet | df16f1cc40ebcd0934c92fcd488f6a4a116ea7f5 | [
"MS-PL"
] | null | null | null | src/STACK/Components/Graphics/SpriteCustomAnimation.cs | advdotnet/AdventuresDotNet | df16f1cc40ebcd0934c92fcd488f6a4a116ea7f5 | [
"MS-PL"
] | null | null | null | using STACK.Logging;
using System;
namespace STACK.Components
{
/// <summary>
/// Component for custom sprite animations.
/// </summary>
[Serializable]
public class SpriteCustomAnimation : Component, IPlayAnimation, IUpdate, IInitialize
{
Action<Transform, string, Frames> _GetFramesAction;
string _AnimationName = "";
int Step = 0;
[NonSerialized]
Sprite _Sprite = null;
[NonSerialized]
Transform _Transform = null;
Frames Frames = Frames.Empty;
bool _Playing;
bool _Looped;
bool _Enabled;
float _UpdateOrder;
public Action<Transform, string, Frames> GetFramesAction { get { return _GetFramesAction; } }
public bool Playing { get { return _Playing; } }
public bool Looped { get { return _Looped; } }
public string Animation { get { return _AnimationName; } }
public bool Enabled { get { return _Enabled; } set { _Enabled = value; } }
public float UpdateOrder { get { return _UpdateOrder; } set { _UpdateOrder = value; } }
public SpriteCustomAnimation()
{
Enabled = true;
}
public void Initialize(bool restore)
{
CacheComponents();
}
private void CacheComponents()
{
_Sprite = Get<Sprite>();
_Transform = Get<Transform>();
}
public void StopAnimation()
{
_Playing = false;
Step = 0;
_AnimationName = string.Empty;
_Looped = false;
}
public void Update()
{
if (null == _Sprite || !Playing)
{
return;
}
_Sprite.CurrentFrame = Frames[Step];
Step++;
if (Step >= Frames.Count)
{
if (!Looped)
{
StopAnimation();
}
else
{
Step = 0;
}
}
}
public void PlayAnimation(string animation, bool looped)
{
// avoid memory allocation
Frames.Clear();
GetFramesAction(_Transform, animation, Frames);
if (Frames.Count > 0)
{
_Looped = looped;
_Playing = true;
Step = 0;
_AnimationName = animation;
_Sprite.CurrentFrame = Frames[Step];
}
else
{
Log.WriteLine("Custom animation not found: " + animation, LogLevel.Notice);
}
}
public static SpriteCustomAnimation Create(Entity addTo)
{
return addTo.Add<SpriteCustomAnimation>();
}
public SpriteCustomAnimation SetGetFramesAction(Action<Transform, string, Frames> value) { _GetFramesAction = value; return this; }
}
}
| 27.719626 | 139 | 0.509777 |
1d4b274cb6f1e8df6a1701661355c9db58868bc7 | 9,720 | cs | C# | src/GS.Service.System/AdministratorService.cs | 364988343/Sikiro.RBAC | f698782669b11a2a3088d4c2270a60eee3d16644 | [
"MIT"
] | 67 | 2020-06-09T06:53:57.000Z | 2022-03-17T02:01:15.000Z | src/GS.Service.System/AdministratorService.cs | guoer1228/Sikiro.RBAC | 50d5f903cf24cc37bcbd9d013291e33d29fcc605 | [
"MIT"
] | null | null | null | src/GS.Service.System/AdministratorService.cs | guoer1228/Sikiro.RBAC | 50d5f903cf24cc37bcbd9d013291e33d29fcc605 | [
"MIT"
] | 27 | 2020-06-10T08:29:26.000Z | 2022-03-17T03:20:42.000Z | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Bson;
using Sikiro.Common.Utils;
using Sikiro.Entity.System;
using Sikiro.Nosql.Mongo;
using Sikiro.Service.System.Const;
using Sikiro.Tookits.Base;
using Sikiro.Tookits.Extension;
using Sikiro.Tookits.Interfaces;
namespace Sikiro.Service.System
{
/// <summary>
/// 后台管理员
/// </summary>
public class AdministratorService : IDepend
{
private readonly MongoRepository _mongoRepository;
public AdministratorService(MongoRepository mongoRepository)
{
_mongoRepository = mongoRepository;
}
/// <summary>
/// 手机登录验证
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public ServiceResult LogonCheck(string userName, string password)
{
var user = _mongoRepository.Get<Administrator>(a => a.UserName == userName && a.Status != EAdministratorStatus.Deleted);
if (user == null)
return ServiceResult.IsFailed(AccountConstString.NoUser);
if (user.Status == EAdministratorStatus.Stop)
return ServiceResult.IsFailed("该用户已禁止登陆");
if (user.Status == EAdministratorStatus.NotActive)
return ServiceResult.IsFailed("该用户未激活");
var passwordForMd5 = password.EncodePassword(user.Id.ToString());
if (user.Password != passwordForMd5)
return ServiceResult.IsFailed(AccountConstString.PasswordError);
return ServiceResult.IsSuccess(AccountConstString.ValidSuccess, new AdministratorData
{
UserId = user.Id.ToString(),
UserName = user.UserName,
RealName = user.RealName,
IsSuper = user.IsSuper
});
}
public PageList<Administrator> GetPageList(int pageIndex, int pageSize, Expression<Func<Administrator, bool>> expression)
{
return _mongoRepository.PageList(expression, a => a.Desc(b => b.CreateDateTime), pageIndex, pageSize);
}
public Administrator GetById(string id)
{
return _mongoRepository.Get<Administrator>(a => a.Id == new ObjectId(id));
}
public ServiceResult UpdateStatus(string userId, EAdministratorStatus status)
{
var result = _mongoRepository.Update<Administrator>(a => a.Id == new ObjectId(userId), a => new Administrator
{
Status = status,
UpdateDateTime = DateTime.Now
});
return result > 0 ? ServiceResult.IsSuccess(AccountConstString.OperateSuccess) : ServiceResult.IsFailed(AccountConstString.OperateFailed);
}
public ServiceResult UpdateById(string id, Expression<Func<Administrator, Administrator>> update)
{
return _mongoRepository.Update(a => a.Id == new ObjectId(id), update) > 0 ? ServiceResult.IsSuccess(AccountConstString.OperateSuccess) : ServiceResult.IsFailed(AccountConstString.OperateFailed);
}
public ServiceResult IsExists(string userName, string id)
{
return _mongoRepository.Exists<Administrator>(a => a.Id != new ObjectId(id) && a.UserName == userName) ? ServiceResult.IsFailed("已存在该用户名") : ServiceResult.IsSuccess(AccountConstString.OperateSuccess);
}
public ServiceResult Add(Administrator administrator)
{
var userId = ObjectId.GenerateNewId();
administrator.Id = userId;
administrator.Password = administrator.Password.EncodePassword(userId.ToString());
administrator.CreateDateTime = DateTime.Now;
administrator.UpdateDateTime = DateTime.Now;
var result = _mongoRepository.AddIfNotExist(a => a.UserName == administrator.UserName, administrator);
return result
? ServiceResult.IsSuccess(AccountConstString.OperateSuccess)
: ServiceResult.IsFailed("已存在该用户名");
}
/// <summary>
/// 修改密码
/// </summary>
/// <param name="userId"></param>
/// <param name="oldPassword"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public ServiceResult ChangePassword(ObjectId userId, string oldPassword, string newPassword)
{
var user = _mongoRepository.Get<Administrator>(a => a.Id == userId);
if (user == null)
return ServiceResult.IsFailed(AccountConstString.NoUser);
var oldEncodePassword = EncodePassword(userId.ToString(), oldPassword);
if (user.Password != oldEncodePassword)
return ServiceResult.IsFailed("原密码错误");
var newEncodePassword = EncodePassword(userId.ToString(), newPassword);
_mongoRepository.Update<Administrator>(a => a.Id == userId, a => new Administrator { Password = newEncodePassword });
return ServiceResult.IsSuccess("修改密码完成");
}
/// <summary>
/// 修改密码
/// </summary>
/// <param name="userId"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public ServiceResult ResetPassword(string userId, string newPassword)
{
var newEncodePassword = EncodePassword(userId, newPassword);
_mongoRepository.Update<Administrator>(a => a.Id == userId.ToObjectId(), a => new Administrator { Password = newEncodePassword });
return ServiceResult.IsSuccess("重置密码完成");
}
/// <summary>
/// 密码加密
/// </summary>
/// <param name="userId"></param>
/// <param name="password"></param>
/// <returns></returns>
public string EncodePassword(string userId, string password)
{
return (password.EncodeMd5String() + userId).EncodeMd5String();
}
public List<Administrator> GetListByIds(IEnumerable<ObjectId> ids)
{
if (!ids.Any())
return new List<Administrator>();
return _mongoRepository.ToList<Administrator>(a => ids.Contains(a.Id));
}
public ServiceResult BatchSetStatus(ObjectId[] userIds, EAdministratorStatus status)
{
_mongoRepository.Update<Administrator>(a => userIds.Contains(a.Id), a => new Administrator { Status = status });
return ServiceResult.IsSuccess("设置完成");
}
public Administrator GetByPositionId(ObjectId positionId)
{
return _mongoRepository.Get<Administrator>(a => a.PositionIds.Contains(positionId));
}
public Administrator GetByRoleId(ObjectId roleId)
{
return _mongoRepository.Get<Administrator>(a => a.RoleIds.Contains(roleId));
}
/// <summary>
/// 获取用户已有的权限
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public string[] GetUserCanPassUrl(string userId)
{
var administrator = GetById(userId);
if (administrator == null)
return new string[] { };
return GetAdministratorUrl(administrator);
}
/// <summary>
/// 设置访问权限缓存,并返回功能权限code
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public IEnumerable<int> GetActionCode(string userId)
{
userId.ThrowIfNull();
var admin = _mongoRepository.Get<Administrator>(a => a.Id == userId.ToObjectId());
if (admin == null)
return new List<int>();
var list = admin.IsSuper ? GetSuperMenuAction() : GetAdminMenuAction(admin);
return list.Select(a => a.Code);
}
/// <summary>
/// 获取普通管理员所拥有的权限
/// </summary>
/// <param name="admin"></param>
/// <returns></returns>
private List<MenuAction> GetAdminMenuAction(Administrator admin)
{
var roles = _mongoRepository.ToList<Role>(a => admin.RoleIds.Contains(a.Id));
var menuActionInRoles = roles.SelectMany(a => a.MenuActionIds).Distinct();
var menuActionInUserList = _mongoRepository.ToList<MenuAction>(a => menuActionInRoles.Contains(a.Id));
return menuActionInUserList;
}
/// <summary>
/// 获取超级管理员所拥有的权限
/// </summary>
/// <returns></returns>
private List<MenuAction> GetSuperMenuAction()
{
var menuActionInUserList = _mongoRepository.ToList<MenuAction>(a => true);
return menuActionInUserList.ToList();
}
/// <summary>
/// 获取管理员可访问的路径
/// </summary>
/// <param name="admin"></param>
/// <returns></returns>
private string[] GetAdministratorUrl(Administrator admin)
{
var roles = _mongoRepository.ToList<Role>(a => admin.RoleIds.Contains(a.Id));
var menuInRoles = roles.SelectMany(a => a.MenuId).Distinct();
var menuActionInRoles = roles.SelectMany(a => a.MenuActionIds).Distinct();
var menuInUser = _mongoRepository.ToList<Menu>(a => menuInRoles.Contains(a.Id)).Select(a => (a.Url??"").ToLower().Trim('/'));
var menuActionInUserList = _mongoRepository.ToList<MenuAction>(a => menuActionInRoles.Contains(a.Id));
var menuActionInUser = menuActionInUserList.SelectMany(a => a.Url);
var allUrl = menuInUser.Concat(menuActionInUser);
return allUrl.ToArray();
}
}
}
| 38.267717 | 212 | 0.604424 |
1555e9de2d59136d96eab1bd84006e2ee6f06c95 | 3,942 | cs | C# | SvnCopy/Form1.cs | toolgood/SvnCopy | 1f2d0e9ed04149e9a7bc1bd35893ea9cae0f3595 | [
"MIT"
] | null | null | null | SvnCopy/Form1.cs | toolgood/SvnCopy | 1f2d0e9ed04149e9a7bc1bd35893ea9cae0f3595 | [
"MIT"
] | null | null | null | SvnCopy/Form1.cs | toolgood/SvnCopy | 1f2d0e9ed04149e9a7bc1bd35893ea9cae0f3595 | [
"MIT"
] | null | null | null | using LibSubWCRev;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SvnCopy
{
public partial class Form1 : Form
{
private const string svnCopyFilePath = @"C:\SvnCopySetting.txt";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.Text = Application.StartupPath;
var dict = LoadSetting();
if (dict.ContainsKey(this.textBox1.Text))
{
this.textBox2.Text = dict[this.textBox1.Text];
}
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox2.Text = fbd.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox2.Text == "")
{
MessageBox.Show("请选择目标文件夹。");
return;
}
var srcFolderPath = this.textBox1.Text;
var tarFolderPath = this.textBox2.Text;
SaveSetting();
TryCopyFolder(srcFolderPath, srcFolderPath, tarFolderPath);
this.Close();
}
private Dictionary<string, string> LoadSetting()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (File.Exists(svnCopyFilePath))
{
var texts = File.ReadAllLines(svnCopyFilePath);
foreach (var text in texts)
{
var sp=text.Trim().Split('|');
dict[sp[0]] = sp[1];
}
}
return dict;
}
private void SaveSetting()
{
var srcFolderPath = this.textBox1.Text;
var tarFolderPath = this.textBox2.Text;
var dict = LoadSetting();
dict[srcFolderPath] = tarFolderPath;
StringBuilder sb = new StringBuilder();
foreach (var item in dict)
{
sb.Append(item.Key);
sb.Append("|");
sb.Append(item.Value);
sb.Append("\r\n");
}
File.WriteAllText(svnCopyFilePath, sb.ToString());
}
public void TryCopyFolder(string folderPath, string srcFolderPath, string tarFolderPath)
{
var folders = Directory.GetDirectories(folderPath);
foreach (var folder in folders)
{
TryCopyFolder(folder, srcFolderPath, tarFolderPath);
}
var files = Directory.GetFiles(folderPath);
foreach (var file in files)
{
TryCopy(file, srcFolderPath, tarFolderPath);
}
}
public void TryCopy(string filePath, string srcFolderPath, string tarFolderPath)
{
//if (Path.GetFileName(filePath)=="SvnCopy.exe")
//{
// return;
//}
if (CanCopy(filePath))
{
var tarFilePath = tarFolderPath + filePath.Substring(srcFolderPath.Length);
Directory.CreateDirectory(Path.GetDirectoryName(tarFilePath));
File.Copy(filePath, tarFilePath, true);
}
}
public bool CanCopy(string filePath)
{
SubWCRev sub = new SubWCRev();
sub.GetWCInfo(filePath, true, true);
if (sub.HasUnversioned)
{
return false;
}
return sub.HasModifications;// || sub.HasUnversioned;
}
}
}
| 29.639098 | 96 | 0.525622 |
1db32a1fe8c4503d333d9105866bcbd423447dd4 | 668 | cs | C# | src/Uno.UWP/Generated/3.0.0.0/Windows.Phone.Notification.Management/ReminderState.cs | olirobert/uno | 02c3ffbc0909a71de17a8f0c6268ca6fed7c1b04 | [
"Apache-2.0"
] | 5,973 | 2019-06-27T02:51:02.000Z | 2022-03-31T11:07:25.000Z | src/Uno.UWP/Generated/3.0.0.0/Windows.Phone.Notification.Management/ReminderState.cs | olirobert/uno | 02c3ffbc0909a71de17a8f0c6268ca6fed7c1b04 | [
"Apache-2.0"
] | 6,988 | 2019-06-27T03:34:56.000Z | 2022-03-31T22:01:54.000Z | src/Uno.UWP/Generated/3.0.0.0/Windows.Phone.Notification.Management/ReminderState.cs | olirobert/uno | 02c3ffbc0909a71de17a8f0c6268ca6fed7c1b04 | [
"Apache-2.0"
] | 636 | 2019-06-27T23:31:29.000Z | 2022-03-30T00:50:25.000Z | #pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Phone.Notification.Management
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
public enum ReminderState
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Active = 0,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Snoozed = 1,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Dismissed = 2,
#endif
}
#endif
}
| 33.4 | 99 | 0.708084 |
dfa2e41bbd85a32e8ebc727614e8acfe80bdcc9a | 200 | cs | C# | MyVet.Prism/MyVet.Prism/Views/AgendaPage.xaml.cs | lordimpi/MyVet | 0ba687deb38af52490e833ba8f88d66108ea752d | [
"Apache-2.0"
] | null | null | null | MyVet.Prism/MyVet.Prism/Views/AgendaPage.xaml.cs | lordimpi/MyVet | 0ba687deb38af52490e833ba8f88d66108ea752d | [
"Apache-2.0"
] | null | null | null | MyVet.Prism/MyVet.Prism/Views/AgendaPage.xaml.cs | lordimpi/MyVet | 0ba687deb38af52490e833ba8f88d66108ea752d | [
"Apache-2.0"
] | null | null | null | using Xamarin.Forms;
namespace MyVet.Prism.Views
{
public partial class AgendaPage : ContentPage
{
public AgendaPage()
{
InitializeComponent();
}
}
}
| 15.384615 | 49 | 0.575 |
b7da7337f8db70dff83fc043f852d10bb4e51870 | 1,959 | cs | C# | src/wa.paycheck.infra/Contexts/EmployeeContext.cs | kyogeti/wa-paycheck-api | 9419293bfed37b0cf496cc530c961621c657d762 | [
"MIT"
] | 2 | 2021-04-18T20:10:00.000Z | 2021-04-23T02:12:28.000Z | src/wa.paycheck.infra/Contexts/EmployeeContext.cs | kyogeti/wa-paycheck-api | 9419293bfed37b0cf496cc530c961621c657d762 | [
"MIT"
] | null | null | null | src/wa.paycheck.infra/Contexts/EmployeeContext.cs | kyogeti/wa-paycheck-api | 9419293bfed37b0cf496cc530c961621c657d762 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using wa.paycheck.contracts.Interfaces;
using wa.paycheck.core.Models;
namespace wa.paycheck.infra.Contexts
{
public class EmployeeContext : IEmployeeContext
{
private readonly DefaultContext _context;
public EmployeeContext(DefaultContext context)
{
_context = context;
}
public async Task<List<Employee>> SelectEmployees(List<Guid> ids) => await _context
.Employees
.Where(x => ids.Contains(x.Id))
.ToListAsync();
public async Task<List<Employee>> SelectEmployees() => await _context
.Employees
.ToListAsync();
public async Task<Employee> SelectEmployee(Guid id) => await _context
.Employees
.Where(x => x.Id == id)
.FirstAsync() ?? throw new Exception("No Employee found with such id.");
public async Task<Guid> InsertEmployee(Employee employee)
{
try
{
while (await Exists(employee.Id))
{
employee.Id = new Guid();
}
await _context
.Employees
.AddAsync(employee);
await _context.SaveChangesAsync();
return employee.Id;
}
catch (Exception e)
{
throw e;
//throw new Exception("There was a problem on this database operation. Please, check stack for detailed information.");
}
}
public async Task<bool> Exists(Guid id) => await _context
.Employees
.AnyAsync(x => x.Id == id);
public async Task<bool> CpfExists(string cpf) => await _context
.Employees
.AnyAsync(x => x.Cpf == cpf);
}
} | 27.985714 | 135 | 0.553344 |
03902438fbf34357a95fcb6ad56bcbb31bab9dc2 | 4,186 | cshtml | C# | CRP.Mvc/Views/Account/OpenIdAccount.cshtml | ucdavis/CRP | fdc77fee442e26f6e39dcf0124b6ef4b660d0339 | [
"MIT"
] | null | null | null | CRP.Mvc/Views/Account/OpenIdAccount.cshtml | ucdavis/CRP | fdc77fee442e26f6e39dcf0124b6ef4b660d0339 | [
"MIT"
] | 47 | 2016-11-09T17:28:26.000Z | 2022-01-19T00:09:40.000Z | CRP.Mvc/Views/Account/OpenIdAccount.cshtml | ucdavis/CRP | fdc77fee442e26f6e39dcf0124b6ef4b660d0339 | [
"MIT"
] | null | null | null | @model CRP.Core.Domain.OpenIdUser
@using CRP.Controllers.Helpers
@using CRP.Core.Resources
@using Microsoft.Web.Mvc
@{
ViewBag.Title = "Open ID Account";
}
<h2>OpenIdAccount</h2>
@Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Fields</legend>
<p>
<label for="Email">Email:</label>
@Html.TextBox("Email", Model.Email)
@Html.ValidationMessage("Email", "*")
</p>
<p>
<label for="FirstName">FirstName:</label>
@Html.TextBox("FirstName", Model.FirstName)
@Html.ValidationMessage("FirstName", "*")
</p>
<p>
<label for="LastName">LastName:</label>
@Html.TextBox("LastName", Model.LastName)
@Html.ValidationMessage("LastName", "*")
</p>
<p>
<label for="StreetAddress">StreetAddress:</label>
@Html.TextBox("StreetAddress", Model.StreetAddress)
@Html.ValidationMessage("StreetAddress", "*")
</p>
<p>
<label for="Address2">Address2:</label>
@Html.TextBox("Address2", Model.Address2)
@Html.ValidationMessage("Address2", "*")
</p>
<p>
<label for="City">City:</label>
@Html.TextBox("City", Model.City)
@Html.ValidationMessage("City", "*")
</p>
<p>
<label for="State">State:</label>
@Html.TextBox("State", Model.State)
@Html.ValidationMessage("State", "*")
</p>
<p>
<label for="Zip">Zip:</label>
@Html.TextBox("Zip", Model.Zip)
@Html.ValidationMessage("Zip", "*")
</p>
<p>
<label for="PhoneNumber">PhoneNumber:</label>
@Html.TextBox("PhoneNumber", Model.PhoneNumber)
@Html.ValidationMessage("PhoneNumber", "*")
</p>
<p>
<input type="submit" value="Save"/>
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back Home", "Index", "Home")
</div>
<fieldset>
<legend>Transactions</legend>
<table>
<thead>
<tr>
<th>See Email</th>
<th>Transaction Number</th>
<th>Is Active</th>
<th>Transaction Date</th>
<th>Quantity</th>
<th>SubTotal</th>
<th>Donation</th>
<th>Total</th>
</tr>
</thead>
<tbody>
@foreach (var t in Model.Transactions.Where(t => t.ParentTransaction == null))
{
<tr>
<td>
@using (Html.BeginForm("Lookup", "Transaction", FormMethod.Post))
{
// pull the email
var answer = t.TransactionAnswers.FirstOrDefault(b =>
b.QuestionSet.Name == StaticValues.QuestionSet_ContactInformation
&& b.Question.Name == StaticValues.Question_Email);
@Html.AntiForgeryToken()
@Html.Hidden("orderNumber", t.TransactionNumber)
@Html.Hidden("email", answer != null ? answer.Answer : string.Empty)
@Html.SubmitButton("Submit", "View")
}
</td>
<td>@t.TransactionNumber</td>
<td>@t.IsActive</td>
<td data-sort="@t.TransactionDate.Ticks">@t.TransactionDate.ToString("d")</td>
<td>@t.Quantity</td>
<td>@t.AmountTotal.ToString("C")</td>
<td>@t.DonationTotal.ToString("C")</td>
<td>@t.Total.ToString("C")</td>
</tr>
}
</tbody>
</table>
</fieldset>
| 34.883333 | 102 | 0.454611 |
49ff1da5f1240fd57d453cf747338572dd8f599b | 487 | cs | C# | Function/Utilities/FileHelper.cs | Animundo/ToxicPlants | f9fd4d5644407ee0dac9f7ed6a1c8f29208621f2 | [
"MIT"
] | 1 | 2021-12-20T20:43:02.000Z | 2021-12-20T20:43:02.000Z | Function/Utilities/FileHelper.cs | anniekvandijk/ToxicPlants | 20c346b86fbc3345926b33ea3bfecbef87f11def | [
"MIT"
] | 2 | 2021-12-02T12:13:08.000Z | 2021-12-04T08:53:08.000Z | Function/Utilities/FileHelper.cs | anniekvandijk/ToxicPlants | 20c346b86fbc3345926b33ea3bfecbef87f11def | [
"MIT"
] | null | null | null | using Function.Interfaces;
using System;
using System.IO;
using System.Reflection;
namespace Function.Utilities
{
internal class FileHelper : IFileHelper
{
public string GetToxicPlantAnimalFileLocation(string fileName)
{
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ??
throw new InvalidOperationException("File not found")
, "Data", fileName);
}
}
}
| 27.055556 | 98 | 0.646817 |
c68f5870cba7a946a5b2397a77804a978ce43d18 | 969 | cs | C# | Dumps/PrimitierDumpV1.0.1/Pinwheel/Jupiter/JDisplayName.cs | TotalJTM/PrimitierModdingFramework | c76b4a19074034350e296743e58e7c624ab5cab3 | [
"MIT"
] | 2 | 2022-03-03T02:10:54.000Z | 2022-03-05T20:54:43.000Z | Dumps/PrimitierDumpV1.0.1/Pinwheel/Jupiter/JDisplayName.cs | TotalJTM/PrimitierModdingFramework | c76b4a19074034350e296743e58e7c624ab5cab3 | [
"MIT"
] | null | null | null | Dumps/PrimitierDumpV1.0.1/Pinwheel/Jupiter/JDisplayName.cs | TotalJTM/PrimitierModdingFramework | c76b4a19074034350e296743e58e7c624ab5cab3 | [
"MIT"
] | null | null | null | /*
* Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
// Image 66: Assembly-CSharp.dll - Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 8552-8785
namespace Pinwheel.Jupiter
{
[AttributeUsage] // 0x000000018002A100-0x000000018002A130
public class JDisplayName : Attribute // TypeDefIndex: 8737
{
// Fields
[CompilerGenerated] // 0x0000000180014D50-0x0000000180014D60
private string _DisplayName_k__BackingField; // 0x10
// Properties
public string DisplayName { [CompilerGenerated] /* 0x0000000180014D50-0x0000000180014D60 */ get; [CompilerGenerated] /* 0x0000000180014D50-0x0000000180014D60 */ set; } // 0x0000000180268FC0-0x0000000180268FD0 0x000000018028FF80-0x000000018028FF90
// Constructors
public JDisplayName(string name); // 0x000000018030F700-0x000000018030F730
}
}
| 35.888889 | 248 | 0.78225 |
06e91ae17bbdb56d51f7021f975196df4ace359a | 375 | cs | C# | src/EventCentric/EventCentric.Persistence/IEventStoreDbContext.cs | Narvalex/EventCentric | 1b759bd4f769c96dbf20f910a28b251a25c8f282 | [
"MIT"
] | 21 | 2015-12-29T15:51:05.000Z | 2021-02-09T08:54:00.000Z | src/EventCentric/EventCentric.Persistence/IEventStoreDbContext.cs | Narvalex/EventCentric | 1b759bd4f769c96dbf20f910a28b251a25c8f282 | [
"MIT"
] | 174 | 2015-08-11T15:27:31.000Z | 2016-06-20T12:45:53.000Z | src/EventCentric/EventCentric.Persistence/IEventStoreDbContext.cs | Narvalex/EventCentric | 1b759bd4f769c96dbf20f910a28b251a25c8f282 | [
"MIT"
] | 7 | 2016-05-01T04:25:16.000Z | 2021-06-21T07:48:36.000Z | using System;
using System.Data.Entity;
namespace EventCentric.Persistence
{
public interface IEventStoreDbContext : IDisposable
{
IDbSet<SnapshotEntity> Snapshots { get; }
IDbSet<EventEntity> Events { get; }
IDbSet<SubscriptionEntity> Subscriptions { get; }
IDbSet<InboxEntity> Inbox { get; }
int SaveChanges();
}
}
| 19.736842 | 57 | 0.658667 |
352fb207322834a67ad8e079618bbd1a1ba3bcf2 | 764 | cs | C# | src/Nuclear.Test/Configurations/ClientConfiguration.cs | MikeLimaSierra/Nuclear.Test | 24f6c309e809ff1eac6870f4e0c5828bfe069d9d | [
"MIT"
] | 2 | 2021-01-11T20:08:15.000Z | 2021-01-18T11:12:24.000Z | src/Nuclear.Test/Configurations/ClientConfiguration.cs | MikeLimaSierra/Nuclear.Test | 24f6c309e809ff1eac6870f4e0c5828bfe069d9d | [
"MIT"
] | 30 | 2020-02-23T20:17:25.000Z | 2021-12-11T13:35:03.000Z | src/Nuclear.Test/Configurations/ClientConfiguration.cs | MikeLimaSierra/Nuclear.Test | 24f6c309e809ff1eac6870f4e0c5828bfe069d9d | [
"MIT"
] | null | null | null | using System;
using System.IO;
using Nuclear.Exceptions;
namespace Nuclear.Test.Configurations {
internal abstract class ClientConfiguration : IClientConfiguration {
#region properties
public FileInfo TestAssembly { get; set; }
public Boolean AutoShutdown { get; set; }
public Boolean WriteReport { get; set; }
#endregion
#region ctors
internal ClientConfiguration() { }
internal ClientConfiguration(IClientConfiguration original) {
Throw.If.Object.IsNull(original, nameof(original));
TestAssembly = original.TestAssembly;
AutoShutdown = original.AutoShutdown;
WriteReport = original.WriteReport;
}
#endregion
}
}
| 21.828571 | 72 | 0.647906 |
c6c6b8e554fcf9bb3815dee5b9a8f10fb0daeb8a | 1,680 | cs | C# | WebApi/Validator/StringDateFormatValidator.cs | yunbow/Charp-WebAPI | 969004953633c495a983145e4565cc29d879a415 | [
"MIT"
] | 4 | 2020-04-23T08:28:00.000Z | 2022-01-05T02:57:48.000Z | WebApi/Validator/StringDateFormatValidator.cs | yunbow/CSharp-WebAPI | 969004953633c495a983145e4565cc29d879a415 | [
"MIT"
] | null | null | null | WebApi/Validator/StringDateFormatValidator.cs | yunbow/CSharp-WebAPI | 969004953633c495a983145e4565cc29d879a415 | [
"MIT"
] | null | null | null | using System;
using System.Globalization;
using WebApi.Properties;
namespace WebApi.Validator
{
/// <summary>
/// 文字列日付フォーマットバリデーションの属性
/// </summary>
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
class StringDateFormatAttribute : Attribute
{
private string format;
/// <summary>
/// コンストラクタ
/// </summary>
public StringDateFormatAttribute(string format)
{
this.format = format;
}
/// <summary>
/// フォーマット
/// </summary>
public string Format
{
get
{
return this.format;
}
}
}
/// <summary>
/// 文字列日付フォーマットバリデーション
/// </summary>
class StringDateFormatValidator : AbstractValidator<StringDateFormatAttribute>
{
/// <summary>
/// 本処理を実行する
/// </summary>
/// <returns>実行結果</returns>
public override bool ExecuteCore()
{
object value = this.prop.GetValue(this.srcObj, null);
Type type = this.prop.PropertyType;
if (value != null && type == typeof(string))
{
string strValue = value.ToString();
if (!DateTime.TryParseExact(strValue, this.attr.Format, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateTime))
{
AddException(string.Format(Resources.ErrorValidationStringDateFormat, this.jsonProp.PropertyName, value, this.attr.Format));
return false;
}
}
return true;
}
}
}
| 26.666667 | 144 | 0.541667 |
ccf15d0ecaf816280d907e964132aa4648be2083 | 1,401 | cs | C# | Models/Contact.cs | DeyvidJLira/ecommerce-ASPNetCore | 40beda027da00ed681ad3c42250ea713171bc19c | [
"MIT"
] | null | null | null | Models/Contact.cs | DeyvidJLira/ecommerce-ASPNetCore | 40beda027da00ed681ad3c42250ea713171bc19c | [
"MIT"
] | null | null | null | Models/Contact.cs | DeyvidJLira/ecommerce-ASPNetCore | 40beda027da00ed681ad3c42250ea713171bc19c | [
"MIT"
] | null | null | null | using System.ComponentModel.DataAnnotations;
namespace ecommerce_aspnet.Models {
public class Contact {
public Contact(string name, string email, string message) {
this.Name = name;
this.Email = email;
this.Message = message;
}
[Required(ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E001")]
[MinLength(4, ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E002")]
[MaxLength(30)]
public string Name {get; set;}
[Required(ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E001")]
[EmailAddress(ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E004")]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E001")]
[MinLength(6, ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E002")]
[MaxLength(500, ErrorMessageResourceType = typeof(ecommerce_aspnet.Libraries.Lang.Messages), ErrorMessageResourceName="MSG_E003")]
public string Message { get; set; }
}
} | 56.04 | 138 | 0.729479 |
c185fdf8b57a43616c5312a2e641eee6fc7613ad | 4,057 | cs | C# | Miki/SolutionDilutionForm.cs | glenn216/Miki | bf1c16108b32f2928eeec577a45d74df37bd49c3 | [
"MIT"
] | null | null | null | Miki/SolutionDilutionForm.cs | glenn216/Miki | bf1c16108b32f2928eeec577a45d74df37bd49c3 | [
"MIT"
] | null | null | null | Miki/SolutionDilutionForm.cs | glenn216/Miki | bf1c16108b32f2928eeec577a45d74df37bd49c3 | [
"MIT"
] | 2 | 2022-03-16T23:59:31.000Z | 2022-03-17T00:00:12.000Z | #region MIT License
// Copyright (c) 2022 Glenn Alon
//
// 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 static Miki.Core;
namespace Miki
{
public partial class SolutionDilutionForm : Form
{
public SolutionDilutionForm()
{
InitializeComponent();
}
private void SolutionDilutionForm_Load(object sender, EventArgs e)
{
InitialConcentrationCbox.Text += "M";
InitialVolumeCbox.Text += "mL";
FinalConcentrationCbox.Text += "M";
FinalVolumeCbox.Text += "mL";
}
private void button1_Click(object sender, EventArgs e)
{
string m1_tmp = InitialConcentrationTxt.Text;
string v1_tmp = InitialVolumeTxt.Text;
string m2_tmp = FinalConcentrationTxt.Text;
string v2_tmp = FinalVolumeTxt.Text;
string v1unit = InitialVolumeCbox.Text;
string v2unit = FinalVolumeCbox.Text;
double m1 = ParseDouble(m1_tmp);
double m2 = ParseDouble(m2_tmp);
double v1 = ParseVolume(v1_tmp, v1unit);
double v2 = ParseVolume(v2_tmp, v2unit);
double result;
switch (comboBox1.SelectedItem)
{
case "M1":
result = (m2 * v2) / v1; // (m2 * v2) / v1
ResultsTxt.Text = decimal.Round((decimal)result, 2).ToString("0.00") + " M";
break;
case "M2":
result = (m1 * v1) / v2; // (m1 * v1) / v2
ResultsTxt.Text = decimal.Round((decimal)result, 2).ToString("0.00") + " M";
break;
case "V1":
result = (m2 * v2) / m1; // (m2 * v2) / m1
ResultsTxt.Text = decimal.Round((decimal)result, 2).ToString("0.00") + " mL";
break;
case "V2":
result = (m1 * v1) / m2; // (m1 * v1) / m2
ResultsTxt.Text = decimal.Round((decimal)result, 2).ToString("0.00") + " mL";
break;
default:
MessageBox.Show("Choose a valid unknown.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
comboBox1.Focus();
break;
}
}
private void InitialConcentrationTxt_KeyPress(object sender, KeyPressEventArgs e)
{
ValidateNumber(sender, e, InitialConcentrationTxt);
}
private void InitialVolumeTxt_KeyPress(object sender, KeyPressEventArgs e)
{
ValidateNumber(sender, e, InitialVolumeTxt);
}
private void FinalConcentrationTxt_KeyPress(object sender, KeyPressEventArgs e)
{
ValidateNumber(sender, e, FinalConcentrationTxt);
}
private void FinalVolumeTxt_KeyPress(object sender, KeyPressEventArgs e)
{
ValidateNumber(sender, e, FinalVolumeTxt);
}
}
} | 38.638095 | 118 | 0.594528 |
a122237da2212e8b2de0848e8af88b8274bbfecc | 5,038 | cs | C# | src/Perpetuum.ExportedTypes/BeamType.cs | jeffmaley/PerpetuumServer | ae0fbfc25fc15f27c32293c18a0ecfeb9847d351 | [
"MIT"
] | 46 | 2017-12-16T17:01:18.000Z | 2022-03-14T03:00:31.000Z | src/Perpetuum.ExportedTypes/BeamType.cs | jeffmaley/PerpetuumServer | ae0fbfc25fc15f27c32293c18a0ecfeb9847d351 | [
"MIT"
] | 234 | 2018-01-12T00:13:51.000Z | 2022-03-08T13:41:42.000Z | src/Perpetuum.ExportedTypes/BeamType.cs | jeffmaley/PerpetuumServer | ae0fbfc25fc15f27c32293c18a0ecfeb9847d351 | [
"MIT"
] | 37 | 2018-01-09T23:01:06.000Z | 2022-03-28T14:24:15.000Z | // 0A2C5FFD
// This code was generated by a tool.
// date: 03/05/2017 11:20:35
namespace Perpetuum.ExportedTypes
{
public enum BeamType
{
arbalest_wreck = 41,
argano_wreck = 32,
arkhe_wreck = 31,
armor_repair = 22,
armorpiercing_missile = 72,
armorpiercing_rocket = 68,
artemis_wreck = 43,
artifact_found = 142,
artifact_radar = 141,
attackpoint_damage_enter = 122,
attackpoint_damage_out = 126,
attackpoint_item_enter = 125,
attackpoint_item_out = 127,
attackpoint_presence_enter = 124,
attackpoint_presence_out = 129,
attackpoint_usage_enter = 123,
attackpoint_usage_out = 128,
baphomet_wreck = 40,
blue_10sec = 100,
blue_20sec = 104,
blue_2sec = 92,
blue_5sec = 96,
cameleon_wreck = 38,
castel_wreck = 36,
ceramic_medium_bullet = 77,
ceramic_small_bullet = 73,
chemoactive_medium_laser = 62,
chemoactive_small_laser = 58,
compozite_medium_bullet = 79,
compozite_small_bullet = 75,
cruisemissile_large = 15,
crypto_medium_laser = 108,
crypto_small_laser = 109,
death = 21,
debug_1 = 81,
debug_2 = 82,
debug_3 = 83,
delivery_mission_beam_01 = 143,
delivery_mission_beam_02 = 156,
delivery_mission_beam_03 = 157,
delivery_mission_beam_04 = 158,
deploy_device_01 = 144,
dig = 20,
dock_in = 18,
dock_out = 19,
doublecore_missile = 71,
doublecore_rocket = 67,
flechette_medium_bullet = 113,
flechette_small_bullet = 112,
gargoyle_wreck = 134,
green_10sec = 99,
green_20sec = 103,
green_2sec = 91,
green_5sec = 95,
gropho_wreck = 48,
heatX_missile = 119,
heatX_rocket = 118,
ictus_wreck = 132,
intakt_wreck = 37,
kain_wreck = 44,
laird_wreck = 33,
large_laser = 9,
large_plasma = 6,
large_projectile = 12,
large_railgun = 3,
lithus_wreck = 138,
loot_bolt = 85,
magnedart_medium_rail = 115,
magnedart_small_rail = 114,
medium_e_nezt_beam = 88,
medium_e_transf_beam = 87,
medium_e_vamp_beam = 89,
medium_laser = 8,
medium_plasma = 5,
medium_projectile = 11,
medium_railgun = 2,
mesmer_wreck = 47,
missile_medium = 14,
multifocal_medium_laser = 64,
multifocal_small_laser = 60,
n_refinery_switch_01_beam = 149,
n_refinery_switch_02_beam = 150,
n_refinery_switch_03_beam = 151,
n_refinery_switch_04_beam = 152,
n_refinery_switch_05_beam = 153,
n_refinery_switch_06_beam = 154,
n_refinery_switch_07_beam = 155,
nature_effect = 140,
nitrogen_medium_rail = 53,
nitrogen_small_rail = 49,
npc_egg_beam = 166,
npcteleport = 193,
orange_10sec = 98,
orange_20sec = 102,
orange_2sec = 90,
orange_5sec = 94,
pbs_energy = 177,
pbs_facility = 179,
pbs_repair = 178,
pbs_turret_laser = 174,
pbs_turret_missile = 175,
pbs_turret_neut = 176,
pbs_turret_railgun = 173,
pbs_wreck1 = 180,
pbs_wreck10 = 189,
pbs_wreck11 = 190,
pbs_wreck12 = 191,
pbs_wreck13 = 192,
pbs_wreck2 = 181,
pbs_wreck3 = 182,
pbs_wreck4 = 183,
pbs_wreck5 = 184,
pbs_wreck6 = 185,
pbs_wreck7 = 186,
pbs_wreck8 = 187,
pbs_wreck9 = 188,
pelistal_hq_switch_01 = 145,
pelistal_hq_switch_02 = 146,
pelistal_hq_switch_03 = 147,
pelistal_hq_switch_03_beam_b = 159,
pelistal_hq_switch_03_beam_c = 160,
pelistal_hq_switch_03_beam_d = 161,
phloboitil_medium_rail = 55,
phlobotil_small_rail = 51,
photokinetic_medium_laser = 63,
photokinetic_small_laser = 59,
plant_bomb_explosion = 172,
plant_destroy = 30,
pnc_medium_bullet = 78,
pnc_medium_rail = 54,
pnc_missile = 70,
pnc_rocket = 66,
pnc_small_bullet = 74,
pnc_small_rail = 50,
police_turret_missile = 84,
prometheus_wreck = 34,
red_10sec = 101,
red_20sec = 105,
red_2sec = 93,
red_5sec = 97,
riveler_wreck = 135,
rocket_small = 13,
sap_scanner_beam = 168,
scarab_wreck = 171,
seeddeploy = 139,
sensor_booster = 23,
sequer_wreck = 137,
seth_wreck = 46,
small_driller = 27,
small_energyneutralizer = 26,
small_energytransferer = 25,
small_energyvampire = 24,
small_harvester = 28,
small_laser = 7,
small_plasma = 4,
small_projectile = 10,
small_railgun = 1,
small_remotearmorrepair = 29,
smite_missile = 121,
smite_rocket = 120,
standard_medium_bullet = 80,
standard_medium_laser = 61,
standard_medium_rail = 56,
standard_missile = 69,
standard_rocket = 65,
standard_small_bullet = 76,
standard_small_laser = 57,
standard_small_rail = 52,
symbiont_wreck = 136,
t_depot_switch_beam_01 = 148,
teleport_in = 16,
teleport_out = 17,
teleport_storm = 167,
termis_wreck = 133,
tfj_medium_bullet = 111,
tfj_small_bullet = 110,
thelodica_l_switch_01_a_beam = 162,
thelodica_l_switch_01_b_beam = 163,
thelodica_l_switch_01_c_beam = 164,
thelodica_l_switch_01_d_beam = 165,
timebomb_activation = 169,
timebomb_explosion = 170,
troiar_wreck = 39,
tyrannos_wreck = 45,
udc_medium_rail = 117,
udc_small_rail = 116,
undefined = 0,
vagabond_wreck = 131,
volcano_medium_laser = 107,
volcano_small_laser = 106,
waspish_wreck = 42,
yagel_wreck = 35,
zenith_wreck = 130
}
}
| 24.57561 | 37 | 0.722707 |
d4e3073b2f68410f41c2125f3150362d2a3c5cce | 769 | cs | C# | Day 6/Forms/Results.cs | sabihoshi/cs | c000c957c535d42d34123d8b3797da719d0ceda3 | [
"MIT"
] | null | null | null | Day 6/Forms/Results.cs | sabihoshi/cs | c000c957c535d42d34123d8b3797da719d0ceda3 | [
"MIT"
] | 1 | 2022-02-26T01:23:04.000Z | 2022-02-26T01:23:04.000Z | Day 6/Forms/Results.cs | sabihoshi/cs | c000c957c535d42d34123d8b3797da719d0ceda3 | [
"MIT"
] | null | null | null | using System;
using System.Linq;
using System.Windows.Forms;
namespace Quiz.Forms
{
public partial class Results : Form
{
public Results()
{
InitializeComponent();
}
private void Results_Load(object sender, EventArgs e)
{
Total.Text = Answer.pageMax.ToString();
Score.Text = Answer.Quiz.Questions.Where((q, i) => q.Correct == Answer.answers[i]).Count().ToString();
TimeElapsed.Text = (DateTime.Now - Answer.start).ToString(@"mm\:ss");
}
private void YEHEY_Click(object sender, EventArgs e)
{
Date.Text = DateTime.Now.ToString();
NameOutput.Text = NameInput.Text;
SS.Show();
YEHEY.Hide();
}
private void Restart_Click(object sender, EventArgs e)
{
var newForm = new Answer();
newForm.Show();
Hide();
}
}
} | 21.361111 | 105 | 0.669701 |
1eb472455def256f5c03ea87360d28ede5b09277 | 416 | cs | C# | Team_Project/Assets/Scripts/Stage1/UnderGroundControl.cs | geogao07/Comp-376 | 84bed822d2243c35bde5c3e120e63c35a559988f | [
"MIT"
] | null | null | null | Team_Project/Assets/Scripts/Stage1/UnderGroundControl.cs | geogao07/Comp-376 | 84bed822d2243c35bde5c3e120e63c35a559988f | [
"MIT"
] | null | null | null | Team_Project/Assets/Scripts/Stage1/UnderGroundControl.cs | geogao07/Comp-376 | 84bed822d2243c35bde5c3e120e63c35a559988f | [
"MIT"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnderGroundControl : MonoBehaviour
{
public GameObject leave;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.E))
{
leave.SetActive(true);
}
}
}
| 17.333333 | 52 | 0.605769 |
415ac4d9f0e484c2fa480e74160a34c77f1cd16b | 12,382 | cs | C# | sdk/dotnet/Ec2/VpcIpamPoolCidrAllocation.cs | chivandikwa/pulumi-aws | 19c08bf9dcb90544450ffa4eec7bf6751058fde2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/dotnet/Ec2/VpcIpamPoolCidrAllocation.cs | chivandikwa/pulumi-aws | 19c08bf9dcb90544450ffa4eec7bf6751058fde2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/dotnet/Ec2/VpcIpamPoolCidrAllocation.cs | chivandikwa/pulumi-aws | 19c08bf9dcb90544450ffa4eec7bf6751058fde2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // *** 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.Ec2
{
/// <summary>
/// Allocates (reserves) a CIDR from an IPAM address pool, preventing usage by IPAM. Only works for private IPv4.
///
/// ## Example Usage
///
/// Basic usage:
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var current = Output.Create(Aws.GetRegion.InvokeAsync());
/// var exampleVpcIpam = new Aws.Ec2.VpcIpam("exampleVpcIpam", new Aws.Ec2.VpcIpamArgs
/// {
/// OperatingRegions =
/// {
/// new Aws.Ec2.Inputs.VpcIpamOperatingRegionArgs
/// {
/// RegionName = current.Apply(current => current.Name),
/// },
/// },
/// });
/// var exampleVpcIpamPool = new Aws.Ec2.VpcIpamPool("exampleVpcIpamPool", new Aws.Ec2.VpcIpamPoolArgs
/// {
/// AddressFamily = "ipv4",
/// IpamScopeId = exampleVpcIpam.PrivateDefaultScopeId,
/// Locale = current.Apply(current => current.Name),
/// });
/// var exampleVpcIpamPoolCidr = new Aws.Ec2.VpcIpamPoolCidr("exampleVpcIpamPoolCidr", new Aws.Ec2.VpcIpamPoolCidrArgs
/// {
/// IpamPoolId = exampleVpcIpamPool.Id,
/// Cidr = "172.2.0.0/16",
/// });
/// var exampleVpcIpamPoolCidrAllocation = new Aws.Ec2.VpcIpamPoolCidrAllocation("exampleVpcIpamPoolCidrAllocation", new Aws.Ec2.VpcIpamPoolCidrAllocationArgs
/// {
/// IpamPoolId = exampleVpcIpamPool.Id,
/// Cidr = "172.2.0.0/24",
/// }, new CustomResourceOptions
/// {
/// DependsOn =
/// {
/// exampleVpcIpamPoolCidr,
/// },
/// });
/// }
///
/// }
/// ```
///
/// With the `disallowed_cidrs` attribute:
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var current = Output.Create(Aws.GetRegion.InvokeAsync());
/// var exampleVpcIpam = new Aws.Ec2.VpcIpam("exampleVpcIpam", new Aws.Ec2.VpcIpamArgs
/// {
/// OperatingRegions =
/// {
/// new Aws.Ec2.Inputs.VpcIpamOperatingRegionArgs
/// {
/// RegionName = current.Apply(current => current.Name),
/// },
/// },
/// });
/// var exampleVpcIpamPool = new Aws.Ec2.VpcIpamPool("exampleVpcIpamPool", new Aws.Ec2.VpcIpamPoolArgs
/// {
/// AddressFamily = "ipv4",
/// IpamScopeId = exampleVpcIpam.PrivateDefaultScopeId,
/// Locale = current.Apply(current => current.Name),
/// });
/// var exampleVpcIpamPoolCidr = new Aws.Ec2.VpcIpamPoolCidr("exampleVpcIpamPoolCidr", new Aws.Ec2.VpcIpamPoolCidrArgs
/// {
/// IpamPoolId = exampleVpcIpamPool.Id,
/// Cidr = "172.2.0.0/16",
/// });
/// var exampleVpcIpamPoolCidrAllocation = new Aws.Ec2.VpcIpamPoolCidrAllocation("exampleVpcIpamPoolCidrAllocation", new Aws.Ec2.VpcIpamPoolCidrAllocationArgs
/// {
/// IpamPoolId = exampleVpcIpamPool.Id,
/// NetmaskLength = 28,
/// DisallowedCidrs =
/// {
/// "172.2.0.0/28",
/// },
/// }, new CustomResourceOptions
/// {
/// DependsOn =
/// {
/// exampleVpcIpamPoolCidr,
/// },
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// IPAMs can be imported using the `allocation id`, e.g.
///
/// ```sh
/// $ pulumi import aws:ec2/vpcIpamPoolCidrAllocation:VpcIpamPoolCidrAllocation example
/// ```
/// </summary>
[AwsResourceType("aws:ec2/vpcIpamPoolCidrAllocation:VpcIpamPoolCidrAllocation")]
public partial class VpcIpamPoolCidrAllocation : Pulumi.CustomResource
{
/// <summary>
/// The CIDR you want to assign to the pool.
/// </summary>
[Output("cidr")]
public Output<string> Cidr { get; private set; } = null!;
/// <summary>
/// The description for the allocation.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// Exclude a particular CIDR range from being returned by the pool.
/// </summary>
[Output("disallowedCidrs")]
public Output<ImmutableArray<string>> DisallowedCidrs { get; private set; } = null!;
[Output("ipamPoolAllocationId")]
public Output<string> IpamPoolAllocationId { get; private set; } = null!;
/// <summary>
/// The ID of the pool to which you want to assign a CIDR.
/// </summary>
[Output("ipamPoolId")]
public Output<string> IpamPoolId { get; private set; } = null!;
/// <summary>
/// The netmask length of the CIDR you would like to allocate to the IPAM pool. Valid Values: `0-32`.
/// </summary>
[Output("netmaskLength")]
public Output<int?> NetmaskLength { get; private set; } = null!;
/// <summary>
/// The ID of the resource.
/// </summary>
[Output("resourceId")]
public Output<string> ResourceId { get; private set; } = null!;
/// <summary>
/// The owner of the resource.
/// </summary>
[Output("resourceOwner")]
public Output<string> ResourceOwner { get; private set; } = null!;
/// <summary>
/// The type of the resource.
/// </summary>
[Output("resourceType")]
public Output<string> ResourceType { get; private set; } = null!;
/// <summary>
/// Create a VpcIpamPoolCidrAllocation 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 VpcIpamPoolCidrAllocation(string name, VpcIpamPoolCidrAllocationArgs args, CustomResourceOptions? options = null)
: base("aws:ec2/vpcIpamPoolCidrAllocation:VpcIpamPoolCidrAllocation", name, args ?? new VpcIpamPoolCidrAllocationArgs(), MakeResourceOptions(options, ""))
{
}
private VpcIpamPoolCidrAllocation(string name, Input<string> id, VpcIpamPoolCidrAllocationState? state = null, CustomResourceOptions? options = null)
: base("aws:ec2/vpcIpamPoolCidrAllocation:VpcIpamPoolCidrAllocation", 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 VpcIpamPoolCidrAllocation 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 VpcIpamPoolCidrAllocation Get(string name, Input<string> id, VpcIpamPoolCidrAllocationState? state = null, CustomResourceOptions? options = null)
{
return new VpcIpamPoolCidrAllocation(name, id, state, options);
}
}
public sealed class VpcIpamPoolCidrAllocationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The CIDR you want to assign to the pool.
/// </summary>
[Input("cidr")]
public Input<string>? Cidr { get; set; }
/// <summary>
/// The description for the allocation.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
[Input("disallowedCidrs")]
private InputList<string>? _disallowedCidrs;
/// <summary>
/// Exclude a particular CIDR range from being returned by the pool.
/// </summary>
public InputList<string> DisallowedCidrs
{
get => _disallowedCidrs ?? (_disallowedCidrs = new InputList<string>());
set => _disallowedCidrs = value;
}
/// <summary>
/// The ID of the pool to which you want to assign a CIDR.
/// </summary>
[Input("ipamPoolId", required: true)]
public Input<string> IpamPoolId { get; set; } = null!;
/// <summary>
/// The netmask length of the CIDR you would like to allocate to the IPAM pool. Valid Values: `0-32`.
/// </summary>
[Input("netmaskLength")]
public Input<int>? NetmaskLength { get; set; }
public VpcIpamPoolCidrAllocationArgs()
{
}
}
public sealed class VpcIpamPoolCidrAllocationState : Pulumi.ResourceArgs
{
/// <summary>
/// The CIDR you want to assign to the pool.
/// </summary>
[Input("cidr")]
public Input<string>? Cidr { get; set; }
/// <summary>
/// The description for the allocation.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
[Input("disallowedCidrs")]
private InputList<string>? _disallowedCidrs;
/// <summary>
/// Exclude a particular CIDR range from being returned by the pool.
/// </summary>
public InputList<string> DisallowedCidrs
{
get => _disallowedCidrs ?? (_disallowedCidrs = new InputList<string>());
set => _disallowedCidrs = value;
}
[Input("ipamPoolAllocationId")]
public Input<string>? IpamPoolAllocationId { get; set; }
/// <summary>
/// The ID of the pool to which you want to assign a CIDR.
/// </summary>
[Input("ipamPoolId")]
public Input<string>? IpamPoolId { get; set; }
/// <summary>
/// The netmask length of the CIDR you would like to allocate to the IPAM pool. Valid Values: `0-32`.
/// </summary>
[Input("netmaskLength")]
public Input<int>? NetmaskLength { get; set; }
/// <summary>
/// The ID of the resource.
/// </summary>
[Input("resourceId")]
public Input<string>? ResourceId { get; set; }
/// <summary>
/// The owner of the resource.
/// </summary>
[Input("resourceOwner")]
public Input<string>? ResourceOwner { get; set; }
/// <summary>
/// The type of the resource.
/// </summary>
[Input("resourceType")]
public Input<string>? ResourceType { get; set; }
public VpcIpamPoolCidrAllocationState()
{
}
}
}
| 37.521212 | 170 | 0.548942 |
fc9b9a3ec400d057ae061780d8bfd28fb08a3661 | 2,127 | cs | C# | SP-Shell/Assets/Scripts/Game_System.cs | vpaone59/SeniorProject | 61935893ce0ceb6210a50001b24a5b20394222c4 | [
"BSD-3-Clause"
] | 1 | 2020-02-06T21:27:19.000Z | 2020-02-06T21:27:19.000Z | SP-Shell/Assets/Scripts/Game_System.cs | vpaone59/SeniorProject | 61935893ce0ceb6210a50001b24a5b20394222c4 | [
"BSD-3-Clause"
] | 10 | 2020-03-05T21:18:12.000Z | 2022-02-27T00:31:30.000Z | SP-Shell/Assets/Scripts/Game_System.cs | vpaone59/SeniorProject | 61935893ce0ceb6210a50001b24a5b20394222c4 | [
"BSD-3-Clause"
] | 5 | 2020-02-06T01:12:48.000Z | 2022-02-21T21:35:12.000Z | using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using System.Runtime.InteropServices;
using UnityEngine.Events;
using System;
[System.Serializable]
public class MyStringEvent : UnityEvent<string>
{
}
public class Game_System : MonoBehaviour
{
public GameObject player_container;
public GameObject Text;
public Player[] players;
private UnityEngine.Random rnd = new UnityEngine.Random();
private string assetPath;
private MyStringEvent gameOver = new MyStringEvent();
[DllImport("__Internal")]
private static extern void GameOver(string winner);
// Then create a function that is going to trigger
// the imported function from our JSLib.
// Start is called before the first frame update
void Start()
{
players = player_container.GetComponentsInChildren<Player>();
assetPath = Application.dataPath;
Debug.Log(assetPath);
gameOver.AddListener(UGameOver);
// A correct website page.
//StartCoroutine(GetRequest("http://localhost:3000/"));
}
public void UGameOver(string winner)
{
GameOver(winner);
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
string winner = players[UnityEngine.Random.Range(0, 2)].name;
gameOver.Invoke(winner);
Text.GetComponent<UnityEngine.UI.Text>().text = "Winner = " + winner;
}
}
} | 26.259259 | 91 | 0.623883 |
1f896035845124a82798bf7ed15f87b850188d81 | 3,623 | cs | C# | DryWetMidi.Tests/Interaction/Chords/ChordsManagerTests.cs | zanzo420/drywetmidi | beace77d5ec3cbb57970994d6b3f9814e10c1c17 | [
"MIT"
] | 314 | 2017-05-26T14:35:27.000Z | 2022-03-22T20:32:30.000Z | DryWetMidi.Tests/Interaction/Chords/ChordsManagerTests.cs | jrdndj/drywetmidi | 3ad73e88dacfde2acfcfc4080b4c582835bfc53a | [
"MIT"
] | 137 | 2017-07-27T12:23:34.000Z | 2022-03-31T14:51:23.000Z | DryWetMidi.Tests/Interaction/Chords/ChordsManagerTests.cs | jrdndj/drywetmidi | 3ad73e88dacfde2acfcfc4080b4c582835bfc53a | [
"MIT"
] | 71 | 2017-05-26T18:35:02.000Z | 2022-03-11T17:59:23.000Z | using System.Linq;
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Core;
using Melanchall.DryWetMidi.Interaction;
using Melanchall.DryWetMidi.Tests.Utilities;
using NUnit.Framework;
namespace Melanchall.DryWetMidi.Tests.Interaction
{
[TestFixture]
public sealed class ChordsManagerTests
{
#region Test methods
[Test]
[Description("Check that ChordsCollection is sorted when enumerated.")]
public void Enumeration_Sorted()
{
using (var chordsManager = new TrackChunk().ManageChords())
{
var chords = chordsManager.Chords;
chords.Add(ChordTestUtilities.GetChordByTime(123));
chords.Add(ChordTestUtilities.GetChordByTime(1));
chords.Add(ChordTestUtilities.GetChordByTime(10));
chords.Add(ChordTestUtilities.GetChordByTime(45));
TimedObjectsCollectionTestUtilities.CheckTimedObjectsCollectionTimes(chords, 1, 10, 45, 123);
}
}
[Test]
public void ChordsByNotes_EmptyCollection()
{
var notes = Enumerable.Empty<Note>();
var chords = notes.GetChords();
MidiAsserts.AreEqual(Enumerable.Empty<Chord>(), chords, "Chords are invalid.");
}
[Test]
public void ChordsByNotes_SingleChannel()
{
var notes = new[]
{
new Note((SevenBitNumber)100, 100, 0),
new Note((SevenBitNumber)120, 100, 0),
new Note((SevenBitNumber)100, 100, 10),
new Note((SevenBitNumber)30, 100, 10)
};
var chords = notes.GetChords();
MidiAsserts.AreEqual(
new[]
{
new Chord(
new Note((SevenBitNumber)100, 100, 0),
new Note((SevenBitNumber)120, 100, 0)),
new Chord(
new Note((SevenBitNumber)100, 100, 10),
new Note((SevenBitNumber)30, 100, 10))
},
chords,
"Chords are invalid.");
}
[Test]
public void ChordsByNotes_MultipleChannels()
{
var notes = new[]
{
new Note((SevenBitNumber)1, 100, 0) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)2, 100, 0) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)3, 100, 100) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)4, 100, 100) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)5, 100, 1000),
new Note((SevenBitNumber)6, 100, 1000)
};
var chords = notes.GetChords();
MidiAsserts.AreEqual(
new[]
{
new Chord(
new Note((SevenBitNumber)1, 100, 0) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)2, 100, 0) { Channel = (FourBitNumber)10 }),
new Chord(
new Note((SevenBitNumber)3, 100, 100) { Channel = (FourBitNumber)10 },
new Note((SevenBitNumber)4, 100, 100) { Channel = (FourBitNumber)10 }),
new Chord(
new Note((SevenBitNumber)5, 100, 1000),
new Note((SevenBitNumber)6, 100, 1000))
},
chords,
"Chords are invalid.");
}
#endregion
}
}
| 36.969388 | 109 | 0.516699 |
1ff6f5a90209913ee1fa1b74b8148a84ef655153 | 2,114 | cs | C# | Methods/PriceChangeAlert/PriceChangeAlert.cs | yani-valeva/Programming-Fundamentals | 36ef35d3cb0a16995f6d00623e14c0c68bd6b532 | [
"MIT"
] | null | null | null | Methods/PriceChangeAlert/PriceChangeAlert.cs | yani-valeva/Programming-Fundamentals | 36ef35d3cb0a16995f6d00623e14c0c68bd6b532 | [
"MIT"
] | null | null | null | Methods/PriceChangeAlert/PriceChangeAlert.cs | yani-valeva/Programming-Fundamentals | 36ef35d3cb0a16995f6d00623e14c0c68bd6b532 | [
"MIT"
] | null | null | null | using System;
class PriceChangeAlert
{
public static void Main()
{
int numberOfPrices = int.Parse(Console.ReadLine());
double significanceThreshold = double.Parse(Console.ReadLine());
double lastPrice = double.Parse(Console.ReadLine());
for (int i = 0; i < numberOfPrices - 1; i++)
{
double currentPrice = double.Parse(Console.ReadLine());
double difference = GetPercentageDifference(lastPrice, currentPrice);
bool isSignificantDifference = HasSignificantDifference(difference, significanceThreshold);
string message = GetMessage(currentPrice, lastPrice, difference, isSignificantDifference);
Console.WriteLine(message);
lastPrice = currentPrice;
}
}
public static string GetMessage(double currentPrice, double lastPrice, double difference, bool isSignificantDifference)
{
string result = "";
if (difference == 0)
{
result = string.Format("NO CHANGE: {0}", currentPrice);
}
else if (!isSignificantDifference)
{
result = string.Format("MINOR CHANGE: {0} to {1} ({2:F2}%)", lastPrice, currentPrice, difference * 100);
}
else if (isSignificantDifference && (difference > 0))
{
result = string.Format("PRICE UP: {0} to {1} ({2:F2}%)", lastPrice, currentPrice, difference * 100);
}
else if (isSignificantDifference && (difference < 0))
{
result = string.Format("PRICE DOWN: {0} to {1} ({2:F2}%)", lastPrice, currentPrice, difference * 100);
}
return result;
}
public static bool HasSignificantDifference(double difference, double significanceThreshold)
{
if (Math.Abs(significanceThreshold) <= Math.Abs(difference))
{
return true;
}
return false;
}
public static double GetPercentageDifference(double lastPrice, double currentPrice)
{
double result = (currentPrice - lastPrice) / lastPrice;
return result;
}
}
| 34.096774 | 123 | 0.610218 |
951d06da6a7b7f588b4587ae339f5917a1f092ad | 581 | cs | C# | src/OpenSeaClient/Models/Trait.cs | cristipufu/OpenSeaClient | 4a0becedf1ffb113a5be3f2c947f9d3fa48dcc3f | [
"MIT"
] | 8 | 2022-01-26T06:30:24.000Z | 2022-02-22T16:19:16.000Z | src/OpenSeaClient/Models/Trait.cs | cristipufu/opensea-net | 4a0becedf1ffb113a5be3f2c947f9d3fa48dcc3f | [
"MIT"
] | 2 | 2022-01-26T05:31:28.000Z | 2022-01-27T06:49:51.000Z | src/OpenSeaClient/Models/Trait.cs | cristipufu/opensea-net | 4a0becedf1ffb113a5be3f2c947f9d3fa48dcc3f | [
"MIT"
] | 1 | 2022-01-26T05:19:56.000Z | 2022-01-26T05:19:56.000Z | using Newtonsoft.Json;
namespace OpenSeaClient
{
public class Trait
{
[JsonProperty("trait_type")]
public string? TraitType { get; set; }
[JsonProperty("value")]
public string? Value { get; set; }
[JsonProperty("display_type")]
public string? DisplayType { get; set; }
[JsonProperty("max_value")]
public string? MaxValue { get; set; }
[JsonProperty("trait_count")]
public long? TraitCount { get; set; }
[JsonProperty("order")]
public string? Order { get; set; }
}
}
| 22.346154 | 48 | 0.576592 |
f033592b3eb442d79add44976d3738ba2d56c4d2 | 571 | cs | C# | Lit.Db/Attributes/DbTableAttribute.cs | lisandropodesta/lit.net | 7b5713e4bba79d49c853559adaff3fcb8a0047d1 | [
"MIT"
] | 1 | 2020-04-16T00:36:42.000Z | 2020-04-16T00:36:42.000Z | Lit.Db/Attributes/DbTableAttribute.cs | lisandropodesta/lit.net | 7b5713e4bba79d49c853559adaff3fcb8a0047d1 | [
"MIT"
] | null | null | null | Lit.Db/Attributes/DbTableAttribute.cs | lisandropodesta/lit.net | 7b5713e4bba79d49c853559adaff3fcb8a0047d1 | [
"MIT"
] | null | null | null | using System;
namespace Lit.Db
{
/// <summary>
/// Table attributes definition.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DbTableAttribute : Attribute
{
/// <summary>
/// Name of the table.
/// </summary>
public string TableName => name;
private readonly string name;
#region Constructors
public DbTableAttribute()
{
}
public DbTableAttribute(string name)
{
this.name = name;
}
#endregion
}
}
| 17.84375 | 45 | 0.535902 |
f03d4c457b0df1ddd3bfb3fe275c93860f1c894e | 4,056 | cs | C# | sdk/dotnet/Rds/GetCertificate.cs | alexbowers/pulumi-aws | 7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5 | [
"ECL-2.0",
"Apache-2.0"
] | 260 | 2018-06-18T14:57:00.000Z | 2022-03-29T11:41:03.000Z | sdk/dotnet/Rds/GetCertificate.cs | alexbowers/pulumi-aws | 7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5 | [
"ECL-2.0",
"Apache-2.0"
] | 1,154 | 2018-06-19T20:38:20.000Z | 2022-03-31T19:48:16.000Z | sdk/dotnet/Rds/GetCertificate.cs | alexbowers/pulumi-aws | 7dbdb03b1e4f7c0d51d5b5d17233ff4465c3eff5 | [
"ECL-2.0",
"Apache-2.0"
] | 115 | 2018-06-28T03:20:27.000Z | 2022-03-29T11:41:06.000Z | // *** 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.Rds
{
public static class GetCertificate
{
/// <summary>
/// Information about an RDS Certificate.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var example = Output.Create(Aws.Rds.GetCertificate.InvokeAsync(new Aws.Rds.GetCertificateArgs
/// {
/// LatestValidTill = true,
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetCertificateResult> InvokeAsync(GetCertificateArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetCertificateResult>("aws:rds/getCertificate:getCertificate", args ?? new GetCertificateArgs(), options.WithVersion());
}
public sealed class GetCertificateArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Certificate identifier. For example, `rds-ca-2019`.
/// </summary>
[Input("id")]
public string? Id { get; set; }
/// <summary>
/// When enabled, returns the certificate with the latest `ValidTill`.
/// </summary>
[Input("latestValidTill")]
public bool? LatestValidTill { get; set; }
public GetCertificateArgs()
{
}
}
[OutputType]
public sealed class GetCertificateResult
{
/// <summary>
/// Amazon Resource Name (ARN) of the certificate.
/// </summary>
public readonly string Arn;
/// <summary>
/// Type of certificate. For example, `CA`.
/// </summary>
public readonly string CertificateType;
/// <summary>
/// Boolean whether there is an override for the default certificate identifier.
/// </summary>
public readonly bool CustomerOverride;
/// <summary>
/// If there is an override for the default certificate identifier, when the override expires.
/// </summary>
public readonly string CustomerOverrideValidTill;
public readonly string Id;
public readonly bool? LatestValidTill;
/// <summary>
/// Thumbprint of the certificate.
/// </summary>
public readonly string Thumbprint;
/// <summary>
/// [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) of certificate starting validity date.
/// </summary>
public readonly string ValidFrom;
/// <summary>
/// [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) of certificate ending validity date.
/// </summary>
public readonly string ValidTill;
[OutputConstructor]
private GetCertificateResult(
string arn,
string certificateType,
bool customerOverride,
string customerOverrideValidTill,
string id,
bool? latestValidTill,
string thumbprint,
string validFrom,
string validTill)
{
Arn = arn;
CertificateType = certificateType;
CustomerOverride = customerOverride;
CustomerOverrideValidTill = customerOverrideValidTill;
Id = id;
LatestValidTill = latestValidTill;
Thumbprint = thumbprint;
ValidFrom = validFrom;
ValidTill = validTill;
}
}
}
| 30.961832 | 174 | 0.559911 |
ad6cd93a68c2894e4c5b2b8a3cc7fa61ee1273f3 | 2,140 | cs | C# | VirtualPath.EmbeddedResource.Tests/EmbeddedVirtualPathProviderTests.cs | guillaume86/VirtualPath | 667c793537c2fa258f8b746b99f9c489552638d3 | [
"MIT"
] | 17 | 2015-07-12T15:28:16.000Z | 2020-11-21T14:54:01.000Z | VirtualPath.EmbeddedResource.Tests/EmbeddedVirtualPathProviderTests.cs | ruo2012/VirtualPath | 34ee77a1a9116268231777a6987cdd579236bc7f | [
"MIT"
] | null | null | null | VirtualPath.EmbeddedResource.Tests/EmbeddedVirtualPathProviderTests.cs | ruo2012/VirtualPath | 34ee77a1a9116268231777a6987cdd579236bc7f | [
"MIT"
] | 8 | 2015-07-20T19:09:29.000Z | 2021-04-21T04:24:01.000Z | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using VirtualPath.Tests;
namespace VirtualPath.EmbeddedResource.Tests
{
public class EmbeddedVirtualPathProviderTests
{
[Test]
public void ShouldEnumerateNodes()
{
//foreach (var name in GetResourceNames())
//{
// Console.WriteLine(name);
//}
var provider = new EmbeddedResourceVirtualPathProvider(true, Assembly.GetExecutingAssembly());
var root = provider.RootDirectory;
foreach (var item in root)
{
Console.WriteLine("{0}: {1}", item.Name, item.IsDirectory);
}
var folder = root.GetDirectory("Folder1");
Assert.That(folder, Is.Not.Null);
var file = folder.GetFile("TextFile1.txt");
Assert.That(file, Is.Not.Null);
Console.WriteLine(file.ReadAllText());
}
public static IEnumerable<string> GetResourceNames()
{
var asm = Assembly.GetExecutingAssembly();
var names = asm.GetManifestResourceNames();
var resourceKey = ".resources";
foreach (var resName in names)
{
if (resName.EndsWith(resourceKey))
{
using (var stream = asm.GetManifestResourceStream(resName))
using (var reader = new System.Resources.ResourceReader(stream))
{
foreach (var entry in reader.Cast<DictionaryEntry>())
{
var name = (string)entry.Key;
yield return resName.Substring(0, resName.Length - resourceKey.Length) + "." + name + " = " + entry.Value.GetType();
}
}
}
else
{
yield return resName;
}
}
}
}
} | 32.923077 | 144 | 0.527103 |
e2c84720cf9062f4c51cc770fdd37d505313f2c3 | 1,749 | cs | C# | Code/4cube.UnitTest/GridModelTest.cs | coens97/4cube | 752fe083ae68b454fca77306c004b3303d92a063 | [
"BSD-3-Clause"
] | 2 | 2016-10-24T20:23:08.000Z | 2016-10-24T20:23:08.000Z | Code/4cube.UnitTest/GridModelTest.cs | coens97/4cube | 752fe083ae68b454fca77306c004b3303d92a063 | [
"BSD-3-Clause"
] | null | null | null | Code/4cube.UnitTest/GridModelTest.cs | coens97/4cube | 752fe083ae68b454fca77306c004b3303d92a063 | [
"BSD-3-Clause"
] | null | null | null | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ninject;
using _4cube.Bussiness;
using _4cube.Common;
using _4cube.Common.Components;
using _4cube.Data;
namespace _4cube.UnitTest
{
[TestClass]
public class GridModelTest
{
private GridModel _gridModel;
private IKernel _container;
[TestInitialize]
public void MyTestInitialize()
{
_container = new StandardKernel();
_container.Bind<IGridModel>().To<GridModel>().InTransientScope();
_container.Bind<IGridData>().To<GridData>().InTransientScope();
_gridModel = _container.Get<GridModel>();
}
[TestMethod]
public void TestAddandDeleteComponent()
{
var component = new ComponentEntity { Rotation = Direction.Down, X = 11, Y = 33 };
_gridModel.AddComponent(component);
Assert.AreEqual(_gridModel.Grid.Components.Count, 1);
_gridModel.DeleteComponent(component);
Assert.AreEqual(_gridModel.Grid.Components.Count, 0);
}
[TestMethod]
public void TestRotateComponennt()
{
var component = new ComponentEntity
{
Rotation = Direction.Up
};
var expected = Direction.Right;
Assert.AreEqual(component.Rotation, Direction.Up);
_gridModel.RotateComponent(component);
Assert.AreEqual(component.Rotation, expected);
}
[TestMethod]
public void TestResizeGrid()
{
_gridModel.ResizeGrid(500, 400);
Assert.AreEqual(_gridModel.Grid.Width, 500);
Assert.AreEqual(_gridModel.Grid.Height, 400);
}
}
}
| 27.328125 | 94 | 0.605489 |
e2fa79aabfb6fbb1519de6fb946e4e88e69b3065 | 743 | cs | C# | FelicaData/UiTextCollection.cs | pine613/FelicaDataV2 | c4737d021b7bd7ba8f301198a157214cdacd4d72 | [
"MIT"
] | 1 | 2015-03-27T11:42:59.000Z | 2015-03-27T11:42:59.000Z | FelicaData/UiTextCollection.cs | pine613/FelicaDataV2 | c4737d021b7bd7ba8f301198a157214cdacd4d72 | [
"MIT"
] | null | null | null | FelicaData/UiTextCollection.cs | pine613/FelicaDataV2 | c4737d021b7bd7ba8f301198a157214cdacd4d72 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver.Builders;
using TValue = FelicaData.UiText;
namespace FelicaData
{
public class UiTextCollection : UiValueCollection<UiText, UiTextType, string>
{
public UiTextCollection(
DatabaseManager dbMgr,
CollectionManager colMgr)
: base(dbMgr, colMgr, "UiTexts")
{
}
public string GetText(UiTextType type)
{
return this.GetValue(type, "");
}
public void UpdateText(UiTextType type, string value)
{
this.UpdateValue(type, value);
}
}
}
| 23.21875 | 82 | 0.597577 |
48db21e451b740ebda26f93819ac5b1d068d20f7 | 23,175 | cs | C# | projects/Gibbed.Disrupt.ConvertBinaryObject/Exporting.cs | MasterScott/Gibbed.Disrupt | 8c41fe50fabf2eb5673919ef6b5fff1c09186381 | [
"Zlib"
] | null | null | null | projects/Gibbed.Disrupt.ConvertBinaryObject/Exporting.cs | MasterScott/Gibbed.Disrupt | 8c41fe50fabf2eb5673919ef6b5fff1c09186381 | [
"Zlib"
] | null | null | null | projects/Gibbed.Disrupt.ConvertBinaryObject/Exporting.cs | MasterScott/Gibbed.Disrupt | 8c41fe50fabf2eb5673919ef6b5fff1c09186381 | [
"Zlib"
] | null | null | null | /* Copyright (c) 2020 Rick (rick 'at' gibbed 'dot' us)
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Gibbed.Disrupt.BinaryObjectInfo;
using Gibbed.Disrupt.BinaryObjectInfo.Definitions;
using Gibbed.Disrupt.FileFormats;
namespace Gibbed.Disrupt.ConvertBinaryObject
{
internal static class Exporting
{
public static void Export(
ObjectFileDefinition objectFileDef,
string outputPath,
InfoManager infoManager,
BinaryObjectFile bof)
{
var settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = true,
CheckCharacters = false,
OmitXmlDeclaration = false
};
var objectDef = objectFileDef != null &&
objectFileDef.Object != null &&
objectFileDef.Object.Hash == bof.Root.NameHash
? objectFileDef.Object
: null;
using (var writer = XmlWriter.Create(outputPath, settings))
{
writer.WriteStartDocument();
WriteNode(infoManager, writer, new BinaryObject[0], bof.Root, objectDef, objectFileDef);
writer.WriteEndDocument();
}
}
internal const uint EntityLibrariesHash = 0xBCDD10B4u; // crc32(EntityLibraries)
internal const uint EntityLibraryHash = 0xE0BDB3DBu; // crc32(EntityLibrary)
internal const uint NameHash = 0xFE11D138u; // crc32(Name);
internal const uint EntityLibraryItemHash = 0x256A1FF9u; // unknown source name
internal const uint DisLibItemIdHash = 0x8EDB0295u; // crc32(disLibItemId)
internal const uint EntityHash = 0x0984415Eu; // crc32(Entity)
internal const uint LibHash = 0xA90F3BCC; // crc32(lib)
internal const uint LibItemHash = 0x72DE4948; // unknown source name
internal const uint TextHidNameHash = 0x9D8873F8; // crc32(text_hidName)
internal const uint NomadObjectTemplatesHash = 0x4C4C4CA4; // crc32(NomadObjectTemplates)
internal const uint NomadObjectTemplateHash = 0x142371CF; // unknown source name
internal const uint TemplateHash = 0x6E167DD5; // crc32(Template)
public static void MultiExportEntityLibrary(
ObjectFileDefinition objectFileDef,
string basePath,
string outputPath,
InfoManager infoManager,
BinaryObjectFile bof)
{
var settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = true,
CheckCharacters = false,
OmitXmlDeclaration = false
};
var objectDef = objectFileDef?.Object;
using (var writer = XmlWriter.Create(outputPath, settings))
{
writer.WriteStartDocument();
var root = bof.Root;
{
writer.WriteStartElement("object");
writer.WriteAttributeString("name", "EntityLibraries");
if (objectFileDef != null &&
string.IsNullOrEmpty(objectFileDef.Name) == false)
{
writer.WriteAttributeString("def", objectFileDef.Name);
}
var libraryNames = new Dictionary<string, int>();
Directory.CreateDirectory(basePath);
foreach (var library in root.Children)
{
var chain = new[] { bof.Root, library };
var libraryDef = objectDef?.GetObjectDefinition(library.NameHash, null);
var libraryName = FieldHandling.Deserialize<string>(
null,
FieldType.String,
library.Fields[NameHash]);
var unsanitizedLibraryName = libraryName;
libraryName = libraryName
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
if (libraryNames.ContainsKey(libraryName) == false)
{
libraryNames.Add(libraryName, 1);
}
else
{
libraryName = $"{libraryName} ({++libraryNames[libraryName]})";
}
var libraryPath = Path.Combine(libraryName, "@library.xml");
writer.WriteStartElement("object");
writer.WriteAttributeString("external", libraryPath);
writer.WriteEndElement();
libraryPath = Path.Combine(basePath, libraryPath);
var itemNames = new Dictionary<string, int>();
var libraryParentPath = Path.GetDirectoryName(libraryPath);
if (string.IsNullOrEmpty(libraryParentPath) == false)
{
Directory.CreateDirectory(libraryParentPath);
}
using (var libraryWriter = XmlWriter.Create(libraryPath, settings))
{
libraryWriter.WriteStartDocument();
libraryWriter.WriteStartElement("object");
libraryWriter.WriteAttributeString("name", "EntityLibrary");
libraryWriter.WriteStartElement("field");
libraryWriter.WriteAttributeString("name", "Name");
libraryWriter.WriteAttributeString("type", "String");
libraryWriter.WriteString(unsanitizedLibraryName);
libraryWriter.WriteEndElement();
foreach (var item in library.Children)
{
var itemDef = libraryDef?.GetObjectDefinition(item.NameHash, null);
var itemName = FieldHandling.Deserialize<string>(
null,
FieldType.String,
item.Fields[NameHash]);
itemName = itemName
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
if (itemNames.ContainsKey(itemName) == false)
{
itemNames.Add(itemName, 1);
}
else
{
itemName = $"{itemName} ({++itemNames[itemName]})";
}
var itemPath = itemName + ".xml";
libraryWriter.WriteStartElement("object");
libraryWriter.WriteAttributeString("external", itemPath);
libraryWriter.WriteEndElement();
itemPath = Path.Combine(basePath, libraryName, itemPath);
var itemParentPath = Path.GetDirectoryName(itemPath);
if (string.IsNullOrEmpty(itemParentPath) == false)
{
Directory.CreateDirectory(itemParentPath);
}
using (var itemWriter = XmlWriter.Create(itemPath, settings))
{
itemWriter.WriteStartDocument();
WriteNode(
infoManager,
itemWriter,
chain,
item,
itemDef,
null);
itemWriter.WriteEndDocument();
}
}
libraryWriter.WriteEndDocument();
}
}
writer.WriteEndElement();
}
writer.WriteEndDocument();
}
}
public static bool IsSuitableForEntityLibraryMultiExport(BinaryObjectFile bof)
{
if (bof.Root.Fields.Count != 0 ||
bof.Root.NameHash != EntityLibrariesHash ||
bof.Root.Children.Any(c => c.NameHash != EntityLibraryHash) == true)
{
return false;
}
var nameSeq = new[] { NameHash };
var idAndNameSeq = new[] { DisLibItemIdHash, NameHash };
foreach (var library in bof.Root.Children)
{
if (library.Fields.Keys.SequenceEqual(nameSeq) == false)
{
return false;
}
if (library.Children.Any(sc => sc.NameHash != EntityLibraryItemHash) == true)
{
return false;
}
foreach (var item in library.Children)
{
if (item.Fields.Keys.OrderBy(h => h).SequenceEqual(idAndNameSeq) == false)
{
return false;
}
if (item.Children.Any(sc => sc.NameHash != EntityHash) == true)
{
return false;
}
}
}
return true;
}
public static void MultiExportLibrary(
ObjectFileDefinition objectFileDef,
string basePath,
string outputPath,
InfoManager infoManager,
BinaryObjectFile bof)
{
var settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = true,
CheckCharacters = false,
OmitXmlDeclaration = false
};
var objectDef = objectFileDef?.Object;
using (var writer = XmlWriter.Create(outputPath, settings))
{
writer.WriteStartDocument();
var root = bof.Root;
var chain = new[] { root };
{
writer.WriteStartElement("object");
writer.WriteAttributeString("name", "lib");
if (objectFileDef != null &&
string.IsNullOrEmpty(objectFileDef.Name) == false)
{
writer.WriteAttributeString("def", objectFileDef.Name);
}
Directory.CreateDirectory(basePath);
var itemNames = new Dictionary<string, int>();
foreach (var item in root.Children)
{
var itemDef = objectDef?.GetObjectDefinition(item.NameHash, null);
var itemName = FieldHandling.Deserialize<string>(
null,
FieldType.String,
item.Fields[TextHidNameHash]);
itemName = itemName
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
if (itemNames.ContainsKey(itemName) == false)
{
itemNames.Add(itemName, 1);
}
else
{
itemName = $"{itemName} ({++itemNames[itemName]})";
}
var itemPath = itemName + ".xml";
writer.WriteStartElement("object");
writer.WriteAttributeString("external", itemPath);
writer.WriteEndElement();
itemPath = Path.Combine(basePath, itemPath);
var itemParentPath = Path.GetDirectoryName(itemPath);
if (string.IsNullOrEmpty(itemParentPath) == false)
{
Directory.CreateDirectory(itemParentPath);
}
using (var itemWriter = XmlWriter.Create(itemPath, settings))
{
itemWriter.WriteStartDocument();
WriteNode(
infoManager,
itemWriter,
chain,
item,
itemDef,
null);
itemWriter.WriteEndDocument();
}
}
}
writer.WriteEndDocument();
}
}
public static bool IsSuitableForLibraryMultiExport(BinaryObjectFile bof)
{
return bof.Root.Fields.Count == 0 &&
bof.Root.NameHash == LibHash &&
bof.Root.Children.Any(c => c.NameHash != LibItemHash ||
c.Fields.ContainsKey(TextHidNameHash) == false) == false;
}
public static void MultiExportNomadObjectTemplates(
ObjectFileDefinition objectFileDef,
string basePath,
string outputPath,
InfoManager infoManager,
BinaryObjectFile bof)
{
var settings = new XmlWriterSettings()
{
Encoding = Encoding.UTF8,
Indent = true,
CheckCharacters = false,
OmitXmlDeclaration = false
};
var objectDef = objectFileDef?.Object;
using (var writer = XmlWriter.Create(outputPath, settings))
{
writer.WriteStartDocument();
var root = bof.Root;
var chain = new[] { root };
{
writer.WriteStartElement("object");
writer.WriteAttributeString("name", "NomadObjectTemplates");
if (objectFileDef != null &&
string.IsNullOrEmpty(objectFileDef.Name) == false)
{
writer.WriteAttributeString("def", objectFileDef.Name);
}
Directory.CreateDirectory(basePath);
var itemNames = new Dictionary<string, int>();
foreach (var item in root.Children)
{
var itemDef = objectDef?.GetObjectDefinition(item.NameHash, null);
var itemName = FieldHandling.Deserialize<string>(
null,
FieldType.String,
item.Fields[NameHash]);
itemName = itemName
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
if (itemNames.ContainsKey(itemName) == false)
{
itemNames.Add(itemName, 1);
}
else
{
itemName = $"{itemName} ({++itemNames[itemName]})";
}
var itemPath = itemName + ".xml";
writer.WriteStartElement("object");
writer.WriteAttributeString("external", itemPath);
writer.WriteEndElement();
itemPath = Path.Combine(basePath, itemPath);
var itemParentPath = Path.GetDirectoryName(itemPath);
if (string.IsNullOrEmpty(itemParentPath) == false)
{
Directory.CreateDirectory(itemParentPath);
}
using (var itemWriter = XmlWriter.Create(itemPath, settings))
{
itemWriter.WriteStartDocument();
WriteNode(
infoManager,
itemWriter,
chain,
item,
itemDef,
null);
itemWriter.WriteEndDocument();
}
}
}
writer.WriteEndDocument();
}
}
public static bool IsSuitableForNomadObjectTemplatesMultiExport(BinaryObjectFile bof)
{
if (bof.Root.Fields.Count != 0 ||
bof.Root.NameHash != NomadObjectTemplatesHash ||
bof.Root.Children.Any(c => c.NameHash != NomadObjectTemplateHash) == true)
{
return false;
}
var nameSeq = new[] { NameHash };
foreach (var library in bof.Root.Children)
{
if (library.Fields.Keys.SequenceEqual(nameSeq) == false)
{
return false;
}
if (library.Children.Any(sc => sc.NameHash != TemplateHash) == true)
{
return false;
}
}
return true;
}
private static void WriteNode(
InfoManager infoManager,
XmlWriter writer,
IEnumerable<BinaryObject> parentChain,
BinaryObject node,
ClassDefinition def,
ObjectFileDefinition objectFileDef)
{
var chain = parentChain.Concat(new[] { node });
var originalDef = def;
if (def != null &&
def.ClassFieldHash.HasValue == true)
{
if (node.Fields.ContainsKey(def.ClassFieldHash.Value) == true)
{
var hash = FieldHandling.Deserialize<uint>(
null,
FieldType.UInt32,
node.Fields[def.ClassFieldHash.Value]);
def = infoManager.GetClassDefinition(hash);
}
}
writer.WriteStartElement("object");
if (originalDef != null && originalDef.Name != null && originalDef.Hash == node.NameHash)
{
writer.WriteAttributeString("name", originalDef.Name);
}
else if (def != null && def.Name != null && def.Hash == node.NameHash)
{
writer.WriteAttributeString("name", def.Name);
}
else
{
writer.WriteAttributeString("hash", node.NameHash.ToString("X8"));
}
if (objectFileDef != null &&
string.IsNullOrEmpty(objectFileDef.Name) == false)
{
writer.WriteAttributeString("def", objectFileDef.Name);
}
if (node.Fields != null)
{
foreach (var kv in node.Fields)
{
writer.WriteStartElement("field");
var fieldDef = def?.GetFieldDefinition(kv.Key, chain);
if (fieldDef != null && fieldDef.Name != null && fieldDef.Hash == kv.Key)
{
writer.WriteAttributeString("name", fieldDef.Name);
}
else
{
writer.WriteAttributeString("hash", kv.Key.ToString("X8"));
}
if (fieldDef == null)
{
writer.WriteAttributeString("type", FieldHandling.GetTypeName(FieldType.BinHex));
writer.WriteBinHex(kv.Value, 0, kv.Value.Length);
}
else
{
writer.WriteAttributeString("type", FieldHandling.GetTypeName(fieldDef.Type));
if (fieldDef.ArrayType != FieldType.Invalid)
{
writer.WriteAttributeString("array_type", FieldHandling.GetTypeName(fieldDef.ArrayType));
}
FieldHandling.Export(
fieldDef,
fieldDef.Type,
fieldDef.ArrayType,
kv.Value,
0,
kv.Value.Length,
writer,
out _);
}
writer.WriteEndElement();
}
}
if (def == null || def.DynamicNestedClasses == false)
{
foreach (var childNode in node.Children)
{
var childDef = def?.GetObjectDefinition(childNode.NameHash, chain);
WriteNode(infoManager, writer, chain, childNode, childDef, null);
}
}
else if (def.DynamicNestedClasses == true)
{
foreach (var childNode in node.Children)
{
var childDef = infoManager.GetClassDefinition(childNode.NameHash);
WriteNode(infoManager, writer, chain, childNode, childDef, null);
}
}
writer.WriteEndElement();
}
}
}
| 38.819095 | 117 | 0.45644 |
3e0997300372a2912a75e301d8973df2285adfd1 | 3,179 | cs | C# | Assets/Evereal/VRVideoPlayer/Scripts/UI/ReticleHighlighted.cs | tcdanielh/TutoriVR | 56666bde8dac600e820da2e82adbda5b406af873 | [
"Apache-2.0"
] | 3 | 2021-11-08T04:59:39.000Z | 2022-02-14T06:33:39.000Z | Assets/Evereal/VRVideoPlayer/Scripts/UI/ReticleHighlighted.cs | tcdanielh/TutoriVR | 56666bde8dac600e820da2e82adbda5b406af873 | [
"Apache-2.0"
] | null | null | null | Assets/Evereal/VRVideoPlayer/Scripts/UI/ReticleHighlighted.cs | tcdanielh/TutoriVR | 56666bde8dac600e820da2e82adbda5b406af873 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020-present Evereal. All rights reserved. */
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace Evereal.VRVideoPlayer
{
// This class will invoke an OnClick event for the hotspot button as soon
// after the users gazes over it for a defined period of time
[RequireComponent(typeof(Image))]
public class ReticleHighlighted : MonoBehaviour
{
public static ReticleHighlighted singleton;
// Reference to the image who's fill amount is adjusted to display the bar.
// This will likely be attached to our Camera UI
private Image selectionImage;
// The time we are waiting to complete the gaze interaction
public float waitTime = 2f;
// Used to start and stop the filling coroutine based on input.
private Coroutine selectionFillRoutine;
// Used to allow the coroutine to wait for the bar to fill.
// private bool radialFilled;
// Whether or not the bar is currently useable.
private bool isSelectionRadialActive;
public bool IsSelectionRadialActive
{
get
{
return isSelectionRadialActive;
}
}
public event Action OnClick;
public void ClearOnClickEvents()
{
OnClick = null;
}
public void Hide()
{
selectionImage.gameObject.SetActive(false);
isSelectionRadialActive = false;
// This effectively resets the radial for when it's shown again.
selectionImage.fillAmount = 0f;
}
public void Show()
{
selectionImage.gameObject.SetActive(true);
isSelectionRadialActive = true;
}
public IEnumerator FillSelectionRadial()
{
// At the start of the coroutine, the bar is not filled.
// radialFilled = false;
// Make sure the radial is visible and usable.
Show();
// Create a timer and reset the fill amount.
float timer = 0f;
selectionImage.fillAmount = 0f;
// This loop is executed once per frame until the timer exceeds the duration.
while (timer < waitTime)
{
// The image's fill amount requires a value from 0 to 1 so we normalise the time.
selectionImage.fillAmount = timer / waitTime;
// Increase the timer by the time between frames and wait for the next frame.
timer += Time.deltaTime;
yield return null;
}
// When the loop is finished set the fill amount to be full.
selectionImage.fillAmount = 1f;
// Turn off the radial so it can only be used once.
isSelectionRadialActive = false;
// The radial is now filled so the coroutine waiting for it can continue.
// radialFilled = true;
// call OnClick now that the selection is complete
if (OnClick != null)
OnClick();
// Once it's been used make the radial invisible.
Hide();
}
private void Awake()
{
selectionImage = GetComponent<Image>();
if (singleton != null)
return;
singleton = this;
}
private void Start()
{
// Setup the radial to have no fill at the start and hide if necessary.
selectionImage.fillAmount = 0f;
Hide();
}
}
} | 28.132743 | 89 | 0.658069 |
1a3d38359e54879249f5641fe31ba4b7e68ac2f8 | 2,038 | cs | C# | src/Kos/Controllers/KosThesesDraftsApi.cs | ctu-fee-group/KosApi | cba8bdc393f95a0eae27a09f395549e49c530703 | [
"MIT"
] | null | null | null | src/Kos/Controllers/KosThesesDraftsApi.cs | ctu-fee-group/KosApi | cba8bdc393f95a0eae27a09f395549e49c530703 | [
"MIT"
] | null | null | null | src/Kos/Controllers/KosThesesDraftsApi.cs | ctu-fee-group/KosApi | cba8bdc393f95a0eae27a09f395549e49c530703 | [
"MIT"
] | null | null | null | //
// KosThesesDraftsApi.cs
//
// Copyright (c) Christofel authors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Kos.Abstractions;
using Kos.Data;
using Kos.Extensions;
namespace Kos.Controllers
{
/// <inheritdoc />
public class KosThesesDraftsApi : IKosThesesDraftsApi
{
private readonly IKosAtomApi _atomApi;
/// <summary>
/// Initializes a new instance of the <see cref="KosThesesDraftsApi"/> class.
/// </summary>
/// <param name="atomApi">The atom api.</param>
public KosThesesDraftsApi(IKosAtomApi atomApi)
{
_atomApi = atomApi;
}
/// <inheritdoc />
public Task<IReadOnlyList<ThesisDraft>> GetThesesDrafts
(
string? query = null,
string orderBy = "id",
ushort limit = 10,
int offset = 0,
string? lang = null,
CancellationToken token = default
)
=> _atomApi.LoadFeedContentAsync<ThesisDraft>
("thesesDrafts", query, orderBy, limit, offset, lang, token: token);
/// <inheritdoc />
public Task<ThesisDraft?> GetThesisDraft
(string id, string? lang = null, CancellationToken token = default)
=> _atomApi.LoadEntityContentAsync<ThesisDraft>($"thesesDrafts/{id}", lang, token: token);
/// <inheritdoc />
public Task<IReadOnlyList<Student>> GetThesisDraftApplicants
(
string id,
string? query = null,
string orderBy = "id",
ushort limit = 10,
int offset = 0,
string? lang = null,
CancellationToken token = default
)
=> _atomApi.LoadFeedContentAsync<Student>
($"thesesDrafts/{id}/applicants", query, orderBy, limit, offset, lang, token: token);
}
} | 32.870968 | 103 | 0.596663 |
ae909b013561ac0cbbcb64114cbccf5edbc699a1 | 7,313 | cs | C# | src/contrib/Analyzers/El/GreekAnalyzer.cs | Tasteful/lucene.net | 981e8490140185f3aedad90fd01c9d520cb54e3c | [
"Apache-2.0"
] | null | null | null | src/contrib/Analyzers/El/GreekAnalyzer.cs | Tasteful/lucene.net | 981e8490140185f3aedad90fd01c9d520cb54e3c | [
"Apache-2.0"
] | null | null | null | src/contrib/Analyzers/El/GreekAnalyzer.cs | Tasteful/lucene.net | 981e8490140185f3aedad90fd01c9d520cb54e3c | [
"Apache-2.0"
] | null | null | null | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Lucene.Net.Analysis.Standard;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Analysis.El
{
/**
* {@link Analyzer} for the Greek language.
* <p>
* Supports an external list of stopwords (words
* that will not be indexed at all).
* A default set of stopwords is used unless an alternative list is specified.
* </p>
*
* <p><b>NOTE</b>: This class uses the same {@link Version}
* dependent settings as {@link StandardAnalyzer}.</p>
*/
public sealed class GreekAnalyzer : Analyzer
{
/**
* List of typical Greek stopwords.
*/
private static readonly String[] GREEK_STOP_WORDS = {
"ο", "η", "το", "οι", "τα", "του", "τησ", "των", "τον",
"την", "και",
"κι", "κ", "ειμαι", "εισαι", "ειναι", "ειμαστε", "ειστε"
, "στο", "στον",
"στη", "στην", "μα", "αλλα", "απο", "για", "προσ", "με",
"σε", "ωσ",
"παρα", "αντι", "κατα", "μετα", "θα", "να", "δε", "δεν",
"μη", "μην",
"επι", "ενω", "εαν", "αν", "τοτε", "που", "πωσ", "ποιοσ"
, "ποια", "ποιο",
"ποιοι", "ποιεσ", "ποιων", "ποιουσ", "αυτοσ", "αυτη",
"αυτο", "αυτοι",
"αυτων", "αυτουσ", "αυτεσ", "αυτα", "εκεινοσ", "εκεινη",
"εκεινο",
"εκεινοι", "εκεινεσ", "εκεινα", "εκεινων", "εκεινουσ",
"οπωσ", "ομωσ",
"ισωσ", "οσο", "οτι"
};
/**
* Returns a set of default Greek-stopwords
* @return a set of default Greek-stopwords
*/
public static ISet<string> GetDefaultStopSet()
{
return DefaultSetHolder.DEFAULT_SET;
}
private static class DefaultSetHolder
{
internal static ISet<string> DEFAULT_SET = CharArraySet.UnmodifiableSet(new CharArraySet(GREEK_STOP_WORDS, false));
}
/**
* Contains the stopwords used with the {@link StopFilter}.
*/
private readonly ISet<string> stopSet;
private readonly Version matchVersion;
public GreekAnalyzer(Version matchVersion)
: this(matchVersion, DefaultSetHolder.DEFAULT_SET)
{
}
/**
* Builds an analyzer with the given stop words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public GreekAnalyzer(Version matchVersion, ISet<string> stopwords)
{
stopSet = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stopwords));
this.matchVersion = matchVersion;
}
/**
* Builds an analyzer with the given stop words.
* @param stopwords Array of stopwords to use.
* @deprecated use {@link #GreekAnalyzer(Version, Set)} instead
*/
public GreekAnalyzer(Version matchVersion, params string[] stopwords)
: this(matchVersion, StopFilter.MakeStopSet(stopwords))
{
}
/**
* Builds an analyzer with the given stop words.
* @deprecated use {@link #GreekAnalyzer(Version, Set)} instead
*/
public GreekAnalyzer(Version matchVersion, IDictionary<string, string> stopwords)
: this(matchVersion, stopwords.Keys.ToArray())
{
}
/**
* Creates a {@link TokenStream} which tokenizes all the text in the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link GreekLowerCaseFilter} and {@link StopFilter}
*/
public override TokenStream TokenStream(String fieldName, TextReader reader)
{
TokenStream result = new StandardTokenizer(matchVersion, reader);
result = new GreekLowerCaseFilter(result);
result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
result, stopSet);
return result;
}
private class SavedStreams
{
protected internal Tokenizer source;
protected internal TokenStream result;
};
/**
* Returns a (possibly reused) {@link TokenStream} which tokenizes all the text
* in the provided {@link Reader}.
*
* @return A {@link TokenStream} built from a {@link StandardTokenizer} filtered with
* {@link GreekLowerCaseFilter} and {@link StopFilter}
*/
public override TokenStream ReusableTokenStream(String fieldName, TextReader reader)
{
SavedStreams streams = (SavedStreams)PreviousTokenStream;
if (streams == null)
{
streams = new SavedStreams();
streams.source = new StandardTokenizer(matchVersion, reader);
streams.result = new GreekLowerCaseFilter(streams.source);
streams.result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion),
streams.result, stopSet);
PreviousTokenStream = streams;
}
else
{
streams.source.Reset(reader);
}
return streams.result;
}
}
}
| 41.788571 | 127 | 0.503897 |
8c1352e55a5c88563ee78d8039793734c70bd7de | 10,561 | cs | C# | Garland.Data/Modules/OtherItemSources.cs | ClayLivince/GarlandTools | 7229bf238f727375fb532f4a15b609303c70b64f | [
"MIT"
] | 2 | 2021-12-23T05:38:28.000Z | 2022-01-19T04:52:51.000Z | Garland.Data/Modules/OtherItemSources.cs | ClayLivince/GarlandTools | 7229bf238f727375fb532f4a15b609303c70b64f | [
"MIT"
] | 1 | 2021-11-25T08:13:32.000Z | 2021-11-25T08:13:32.000Z | Garland.Data/Modules/OtherItemSources.cs | ClayLivince/GarlandTools-CN | 7229bf238f727375fb532f4a15b609303c70b64f | [
"MIT"
] | null | null | null | using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Garland.Data.Modules
{
public class OtherItemSources : Module
{
Dictionary<string, dynamic> _venturesByName;
public override string Name => "Other Item Sources";
public override void Start()
{
_venturesByName = _builder.Db.Ventures.Where(v => v.nameEN != null).ToDictionary(v => (string)v.nameEN);
var lines = Utils.Tsv(Path.Combine(Config.SupplementalPath, "FFXIV Data - Items.tsv"));
foreach (var line in lines.Skip(1))
{
var type = line[1];
var args = line.Skip(2).Where(c => c != "").ToArray();
var itemName = line[0];
// Jump over comments
if (itemName.StartsWith("#"))
continue;
try
{
var item = _builder.Db.ItemsByEnName[itemName];
switch (type)
{
case "Desynth":
BuildDesynth(item, args);
break;
case "Reduce":
BuildReduce(item, args);
break;
case "Loot":
BuildLoot(item, args);
break;
case "Venture":
BuildVentures(item, args);
break;
case "Node":
BuildNodes(item, args);
break;
case "FishingSpot":
BuildFishingSpots(item, args);
break;
case "Instance":
BuildInstances(item, args);
break;
case "Voyage":
BuildVoyages(item, args);
break;
case "Gardening":
BuildGardening(item, args);
break;
case "Other":
BuildOther(item, args);
break;
default:
{
var joinedArgs = string.Join(", ", args);
DatabaseBuilder.PrintLine($"Error importing supplemental source '{itemName}' with args '{joinedArgs}': Unsupported type '{type}'");
break;
}
}
}
catch (Exception ex)
{
var joinedArgs = string.Join(", ", args);
DatabaseBuilder.PrintLine($"Error importing supplemental source '{itemName}' with args '{joinedArgs}': {ex.Message}");
//if (System.Diagnostics.Debugger.IsAttached)
//System.Diagnostics.Debugger.Break();
}
}
}
void BuildOther(dynamic item, string[] sources)
{
// For unstructured source strings.
if (item.other != null)
throw new InvalidOperationException("item.other already exists.");
item.other = new JArray(sources);
}
void BuildGardening(dynamic item, string[] sources)
{
foreach (string seedItemName in sources)
{
var seedItem = _builder.Db.ItemsByEnName[seedItemName];
Items.AddGardeningPlant(_builder, seedItem, item);
}
}
void BuildDesynth(dynamic item, string[] sources)
{
if (item.desynthedFrom == null)
item.desynthedFrom = new JArray();
foreach (string itemName in sources)
{
var desynthItem = _builder.Db.ItemsByEnName[itemName];
item.desynthedFrom.Add((int)desynthItem.id);
_builder.Db.AddReference(item, "item", (int)desynthItem.id, false);
if (desynthItem.desynthedTo == null)
desynthItem.desynthedTo = new JArray();
desynthItem.desynthedTo.Add((int)item.id);
_builder.Db.AddReference(desynthItem, "item", (int)item.id, false);
}
}
void BuildReduce(dynamic item, string[] sources)
{
if (item.reducedFrom == null)
item.reducedFrom = new JArray();
foreach (string sourceItemName in sources)
{
if (!_builder.Db.ItemsByEnName.TryGetValue(sourceItemName, out var sourceItem))
{
DatabaseBuilder.PrintLine($"Item name '{sourceItemName}' not found in database. Maybe there is a typo? Or not release in Chinese?");
return;
}
if (sourceItem.reducesTo == null)
sourceItem.reducesTo = new JArray();
sourceItem.reducesTo.Add((int)item.id);
item.reducedFrom.Add((int)sourceItem.id);
_builder.Db.AddReference(sourceItem, "item", (int)item.id, false);
_builder.Db.AddReference(item, "item", (int)sourceItem.id, true);
// Set aetherial reduction info on the gathering node views.
// Bell views
foreach (var nodeView in _builder.Db.NodeViews)
{
foreach (var slot in nodeView.items)
{
if (slot.id == sourceItem.id && slot.reduce == null)
{
slot.reduce = new JObject();
slot.reduce.item = item.chs.name;
slot.reduce.icon = item.icon;
}
}
}
// Database views
foreach (var node in _builder.Db.Nodes)
{
foreach (var slot in node.items)
{
if (slot.id == sourceItem.id && slot.reduceId == null)
{
slot.reduceId = (int)item.id;
_builder.Db.AddReference(node, "item", (int)item.id, false);
}
}
}
}
}
void BuildLoot(dynamic item, string[] sources)
{
if (item.treasure == null)
item.treasure = new JArray();
//var generators = sources.Select(j => _builder.Db.ItemsByName[j]).ToArray();
List<dynamic> generators = new List<dynamic>();
foreach (string source in sources)
{
if (_builder.Db.ItemsByEnName.TryGetValue(source, out var sourceItem))
{
generators.Add(sourceItem);
}
else {
DatabaseBuilder.PrintLine($"Item name '{source}' not found in database. Maybe there is a typo? Or not release in Chinese?");
}
}
foreach (var generator in generators)
{
if (generator.loot == null)
generator.loot = new JArray();
generator.loot.Add((int)item.id);
_builder.Db.AddReference(generator, "item", (int)item.id, false);
item.treasure.Add((int)generator.id);
_builder.Db.AddReference(item, "item", (int)generator.id, true);
}
}
void BuildVentures(dynamic item,string[] sources)
{
if (item.ventures != null)
throw new InvalidOperationException("item.ventures already exists.");
var ventureIds = sources.Select(j => (int)_venturesByName[j].id);
item.ventures = new JArray(ventureIds);
}
void BuildVoyages(dynamic item, string[] sources)
{
if (item.voyages != null)
throw new InvalidOperationException("item.voyages already exists.");
item.voyages = new JArray(sources);
}
void BuildNodes(dynamic item, string[] sources)
{
if (item.nodes == null)
item.nodes = new JArray();
foreach (var id in sources.Select(int.Parse))
{
item.nodes.Add(id);
int itemId = item.id;
var node = _builder.Db.Nodes.First(n => n.id == id);
dynamic w = new JObject();
w.id = itemId;
w.slot = "?"; // Only hidden items here
node.items.Add(w);
_builder.Db.AddReference(node, "item", itemId, false);
_builder.Db.AddReference(item, "node", id, true);
}
}
void BuildFishingSpots(dynamic item, string[] sources)
{
if (item.fishingSpots == null)
item.fishingSpots = new JArray();
foreach (var name in sources)
{
dynamic w = new JObject();
w.id = (int)item.id;
w.lvl = (int)item.ilvl;
var spot = _builder.Db.FishingSpots.First(f => f.name == name);
item.fishingSpots.Add((int)spot.id);
spot.items.Add(w);
_builder.Db.AddReference(spot, "item", (int)item.id, false);
}
}
void BuildInstances(dynamic item, string[] sources)
{
if (item.instances == null)
item.instances = new JArray();
int itemId = item.id;
foreach (var name in sources)
{
var instance = _builder.Db.Instances.First(i => i.en.name.ToString().ToUpper() == name.ToUpper());
int instanceId = instance.id;
if (instance.rewards == null)
instance.rewards = new JArray();
instance.rewards.Add(itemId);
item.instances.Add(instanceId);
_builder.Db.AddReference(instance, "item", itemId, false);
_builder.Db.AddReference(item, "instance", instanceId, true);
}
}
}
} | 35.921769 | 163 | 0.463119 |
0e37eba145671fcac06e1a3edb6c79da2e64ec72 | 379 | cs | C# | Scripts/Mobs/StateMachine/IMobState.cs | zeisthegd/Devour | 22584b4a3c416795e143c91a0d16aefec7d8bf74 | [
"MIT"
] | null | null | null | Scripts/Mobs/StateMachine/IMobState.cs | zeisthegd/Devour | 22584b4a3c416795e143c91a0d16aefec7d8bf74 | [
"MIT"
] | null | null | null | Scripts/Mobs/StateMachine/IMobState.cs | zeisthegd/Devour | 22584b4a3c416795e143c91a0d16aefec7d8bf74 | [
"MIT"
] | null | null | null | using Godot;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MobStateMachine
{
public interface IMobState
{
void PlayAnimation(Mob mob);
void AutoPilot(Mob mob);
void SeeWiz(Mob mob);
void WizOutOfSight(Mob mob);
void RunOutOfHealth(Mob mob);
}
}
| 19.947368 | 37 | 0.680739 |
9c9c087430d26774af2bf91d6be2831664e2c768 | 852 | cs | C# | src/Easy.Web.Serialization.JSONNet/Settings.cs | NimaAra/Easy.Web | a0ecddf2b2b078c57091f932b041248b4ee2de43 | [
"MIT"
] | 8 | 2017-01-07T04:34:10.000Z | 2020-06-13T23:38:52.000Z | src/Easy.Web.Serialization.JSONNet/Settings.cs | NimaAra/Easy.Web | a0ecddf2b2b078c57091f932b041248b4ee2de43 | [
"MIT"
] | null | null | null | src/Easy.Web.Serialization.JSONNet/Settings.cs | NimaAra/Easy.Web | a0ecddf2b2b078c57091f932b041248b4ee2de43 | [
"MIT"
] | null | null | null | namespace Easy.Web.Serialization.JSONNet
{
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
/// <summary>
/// Provides access to the default settings for the serialization.
/// </summary>
public static class Settings
{
/// <summary>
/// Gets the default <see cref="JsonSerializerSettings"/>.
/// </summary>
public static JsonSerializerSettings Default = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateParseHandling = DateParseHandling.DateTime,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.None,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
} | 35.5 | 81 | 0.660798 |
faf0d6dbd6c8b560763150cbf2759ee26c95f1a1 | 3,341 | cs | C# | DdotM.EmailClient.Mailgun/MailgunClient.cs | ddotm/EmailClient | 896be0ff195a2a2a81497b5974071a2fb2403733 | [
"MIT"
] | null | null | null | DdotM.EmailClient.Mailgun/MailgunClient.cs | ddotm/EmailClient | 896be0ff195a2a2a81497b5974071a2fb2403733 | [
"MIT"
] | null | null | null | DdotM.EmailClient.Mailgun/MailgunClient.cs | ddotm/EmailClient | 896be0ff195a2a2a81497b5974071a2fb2403733 | [
"MIT"
] | 1 | 2020-11-04T07:34:30.000Z | 2020-11-04T07:34:30.000Z | using RestSharp;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace DdotM.EmailClient.Mailgun
{
/// <inheritdoc />
public class MailgunClient : IMailgunClient
{
private readonly MailgunClientConfig _mailgunClientConfig;
/// <summary>
/// Constructor. Initializes the instance with the passed in MailgunClientConfig
/// </summary>
/// <param name="mailgunClientConfig">Mailgun client configurations</param>
public MailgunClient(MailgunClientConfig mailgunClientConfig)
{
_mailgunClientConfig = mailgunClientConfig;
}
/// <inheritdoc />
public async Task<MailgunMessage> SendAsync(MailgunMessage msg)
{
// Mailgun API documentation: https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api
var client = new RestClient
{
BaseUrl = new Uri("https://api.mailgun.net/v3")
};
var request = new RestRequest();
request.AddHeader("Authorization", $"Basic {_mailgunClientConfig.ApiKey?.Base64Encode()}");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("domain", _mailgunClientConfig.SendingDomain, ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
// Send a message with custom connection settings
request.AddParameter("o:require-tls", _mailgunClientConfig.RequireTls);
request.AddParameter("o:skip-verification", _mailgunClientConfig.SkipVerification);
request.AddParameter("from", $"{msg.From.Name} <{msg.From.Address}>");
foreach (var toRecipient in msg.ToEmails)
{
request.AddParameter("to", $"{toRecipient.Name} <{toRecipient.Address}>");
}
if (!msg.ToEmails.Any())
{
request.AddParameter("to", $"{msg.From.Name} <{msg.From.Address}>");
}
foreach (var ccRecipient in msg.CcEmails)
{
request.AddParameter("cc", $"{ccRecipient.Name} <{ccRecipient.Address}>");
}
foreach (var bccRecipient in msg.BccEmails)
{
request.AddParameter("bcc", $"{bccRecipient.Name} <{bccRecipient.Address}>");
}
request.AddParameter("subject", msg.Subject);
request.AddParameter("text", msg.TextBody);
request.AddParameter("html", msg.HtmlBody);
// This will disable link rewriting for this message
request.AddParameter("o:tracking", msg.Tracking);
// Set message delivery time - format "Fri, 14 Oct 2011 23:10:10 -0000"
if (msg.DeliveryTime.HasValue)
{
request.AddParameter("o:deliverytime", msg.DeliveryTime.Value.ToString("ddd, dd MMM yyyy HH:mm:ss -0000"));
}
// Add tag(s)
foreach (var tag in msg.Tags)
{
request.AddParameter("o:tag", tag);
}
request.Method = Method.POST;
var response = await client.ExecuteAsync(request);
msg.Response = response;
return msg;
}
}
}
| 37.122222 | 123 | 0.582161 |
164454b8ec99ebf63bbc2abf7c1ae26cc590c4ac | 21,634 | cs | C# | Src/Core/Business/Nz.Core.Business.Impl.Auth/AuthBusiness.cs | paulonz/Nz.Framework | ac938d18569a40fc6a09d47aaa00bdbc5c1c17fb | [
"Apache-2.0"
] | 2 | 2021-02-13T15:35:56.000Z | 2021-02-17T17:44:05.000Z | Src/Core/Business/Nz.Core.Business.Impl.Auth/AuthBusiness.cs | paulonz/Nz.Framework | ac938d18569a40fc6a09d47aaa00bdbc5c1c17fb | [
"Apache-2.0"
] | null | null | null | Src/Core/Business/Nz.Core.Business.Impl.Auth/AuthBusiness.cs | paulonz/Nz.Framework | ac938d18569a40fc6a09d47aaa00bdbc5c1c17fb | [
"Apache-2.0"
] | null | null | null | /*
* Nz.Framework
* Author Paulo Eduardo Nazeazeno
* https://github.com/paulonz/Nz.Framework
*/
namespace Nz.Core.Business.Impl.Auth
{
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Nz.Common.GeneralSettings;
using Nz.Core.Model;
using Nz.Core.Model.Impl.Auth;
using Nz.Libs.EmailSender;
using Nz.Libs.Encryption;
using Nz.Libs.Jwt.Settings;
using Nz.Libs.MessageTemplate;
/// <summary>
/// Classe para autenticação
/// </summary>
public partial class AuthBusiness : IAuthBusiness
{
/// <summary>
/// Criptografia
/// </summary>
private readonly IEncryption _encryption;
/// <summary>
/// Negócios para usuários
/// </summary>
private readonly IUserBusiness _userBusiness;
/// <summary>
/// Configurações gerais
/// </summary>
private readonly IGeneralSettings _general;
/// <summary>
/// Configurações Jwt
/// </summary>
private readonly IJwtSettings _jwt;
/// <summary>
/// Envio de email
/// </summary>
private readonly IEmailSender _emailSender;
/// <summary>
/// Template de mensagens
/// </summary>
private readonly IMessageTemplate _messageTemplate;
/// <summary>
/// Usuário autenticado
/// </summary>
private readonly IAuthUser _authUser;
/// <summary>
/// Logger
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Construtor padrão
/// </summary>
/// <param name="encryption">Objeto de criptografia</param>
/// <param name="userBusiness">Negócios para usuários</param>
/// <param name="general">Configurações gerais</param>
/// <param name="jwt">Configurações JWT</param>
/// <param name="emailSender">Envio de email</param>
/// <param name="messageTemplate">Template para mensagens</param>
/// <param name="authUser">Usuário autenticado</param>
/// <param name="logger">Logger</param>
public AuthBusiness(
IEncryption encryption,
IUserBusiness userBusiness,
IGeneralSettings general,
IJwtSettings jwt,
IEmailSender emailSender,
IMessageTemplate messageTemplate,
IAuthUser authUser,
ILogger<AuthBusiness> logger)
{
_encryption = encryption;
_userBusiness = userBusiness;
_general = general;
_jwt = jwt;
_emailSender = emailSender;
_messageTemplate = messageTemplate;
_authUser = authUser;
_logger = logger;
}
/// <summary>
/// Realiza a autenticação de um usuário
/// </summary>
/// <param name="email">Login de acesso do usuário</param>
/// <param name="password">Senha de acesso do usuário</param>
/// <returns>Array com Token e RefreshToken</returns>
public async Task<User> SignInAsync(
string email,
string password)
{
try
{
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
password = _encryption.Encrypt(password);
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(User.Email)} == \"{email}\" && {nameof(User.Password)} == \"{password}\" && {nameof(User.IsEmailValidated)}",
include: new string[]
{
nameof(User.UserRoles)
}
).ConfigureAwait(false);
return user;
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Atualiza o token de autenticação do usuário
/// </summary>
/// <param name="refreshToken">Dados de autenticação</param>
/// <returns>Tokens de acesso</returns>
public async Task<User> RefreshTokenAsync(
string refreshToken)
{
try
{
if (!string.IsNullOrEmpty(refreshToken))
{
string email = ExtractEmailFromRefreshToken(refreshToken);
if (!string.IsNullOrEmpty(email))
{
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(User.Email)} == \"{email}\"",
include: new string[]
{
nameof(User.UserRoles)
}
).ConfigureAwait(false);
return user;
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Gera o token de autenticação de um usuário
/// </summary>
/// <param name="user">Usuário</param>
/// <returns>Token de autenticação</returns>
public async Task<string> GenerateAuthToken(
User user)
{
try
{
return await Task.Run(() =>
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(GetClaims(user)),
Expires = _general.CurrentDateTime.AddMinutes(_jwt.ExpiresInMinutes),
IssuedAt = _general.CurrentDateTime.AddMinutes(_jwt.ExpiresInMinutes),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(
_general.DefaultEncoding.GetBytes(
_jwt.IssuerSigningKey)),
SecurityAlgorithms.HmacSha256Signature),
Audience = _jwt.ValidAudience,
Issuer = _jwt.ValidIssuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
});
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Gera o token para atualização da sessão do usuário
/// </summary>
/// <param name="user">Usuário</param>
/// <returns>Token de atualização</returns>
public async Task<string> GenerateRefreshToken(
User user)
{
try
{
return await Task.Run(() =>
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new List<Claim>() { new Claim(ClaimTypes.Email, user.Email) }),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(
_general.DefaultEncoding.GetBytes(
_jwt.IssuerSigningKey)),
SecurityAlgorithms.HmacSha256Signature),
Audience = _jwt.ValidAudience,
Issuer = _jwt.ValidIssuer
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
});
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Cadastra um novo usuário
/// </summary>
/// <param name="model">Dados de cadastro</param>
/// <returns>Usuário cadastrado</returns>
public async Task<User> RegisterAsync(
User model)
{
try
{
return await _userBusiness.CreateAsync(model).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Confirmação de registro de um novo usuário
/// </summary>
/// <param name="email">Email da confirmação</param>
/// <param name="confirmationToken">Token da confirmação</param>
/// <returns>Sucesso</returns>
public async Task<User> ConfirmRegisterAsync(
string email,
string confirmationToken)
{
try
{
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(User.Email)} == \"{email}\" && {nameof(user.IsEmailValidated)} == false")
.ConfigureAwait(false);
if (user != null)
{
string registerToken = _encryption.Encrypt(email);
if (confirmationToken.Equals(registerToken, StringComparison.InvariantCultureIgnoreCase))
{
user.IsEmailValidated = true;
user = await _userBusiness.UpdateAsync(user.Id, user);
if (user != null)
{
await SendMailAsync(
MessageTemplateType.EmailConfirmNewUserRegister,
new
{
user.FirstName,
user.Email,
_general.BaseUri
},
user.FirstName,
email).ConfigureAwait(false);
return user;
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Inicio da etapa para recuperação de senha
/// </summary>
/// <param name="email">Email para recuperação de senha</param>
/// <returns>Sucesso</returns>
public async Task<User> ForgotPasswordAsync(
string email)
{
try
{
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(user.Email)} == \"{email}\"")
.ConfigureAwait(false);
if (user != null)
{
user.RecoveryPasswordToken = _encryption.Encrypt($"{user.Email}_{_general.CurrentDateTime}");
user = await _userBusiness.UpdateAsync(user.Id, user).ConfigureAwait(false);
if (user != null)
{
await SendMailAsync(
MessageTemplateType.EmailForgotPassword,
new
{
user.FirstName,
user.RecoveryPasswordToken,
_general.BaseUri
},
user.FirstName,
email).ConfigureAwait(false);
return user;
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Confirmação da recuperação de senha
/// </summary>
/// <param name="email">Email para a confirmação</param>
/// <param name="recoveryPasswordToken">Token para recuperação de senha</param>
/// <param name="newPassword">Nova senha para o usuário</param>
/// <returns>Sucesso</returns>
public async Task<User> ConfirmForgotPasswordAsync(
string email,
string recoveryPasswordToken,
string newPassword)
{
try
{
if (!string.IsNullOrEmpty(email) &&
!string.IsNullOrEmpty(recoveryPasswordToken) &&
!string.IsNullOrEmpty(newPassword))
{
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(User.Email)} == \"{email}\" && {nameof(User.RecoveryPasswordToken)} == \"{recoveryPasswordToken}\"")
.ConfigureAwait(false);
if (user != null)
{
user.Password = _encryption.Encrypt(newPassword);
user.RecoveryPasswordToken = string.Empty;
user = await _userBusiness.UpdateAsync(user.Id, user).ConfigureAwait(false);
if (user != null)
{
await SendMailAsync(
MessageTemplateType.EmailConfirmForgotPassword, new
{
user.FirstName,
user.Email,
_general.BaseUri
},
user.FirstName,
email).ConfigureAwait(false);
return user;
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Alteração de senha de um usuário
/// </summary>
/// <param name="email">Login do usuário</param>
/// <param name="currentPassword">Senha atual</param>
/// <param name="newPassword">Nova senha</param>
/// <returns>Sucesso</returns>
public async Task<User> ChangePasswordAsync(
string email,
string currentPassword,
string newPassword)
{
try
{
if (!string.IsNullOrEmpty(email) &&
!string.IsNullOrEmpty(currentPassword) &&
!string.IsNullOrEmpty(newPassword))
{
if (_authUser.Email == email)
{
currentPassword = _encryption.Encrypt(currentPassword);
User user = await _userBusiness.ReadFirstAsync(
$"{nameof(User.Email)} == \"{email}\" && {nameof(User.Password)} == \"{currentPassword}\"")
.ConfigureAwait(false);
if (user != null)
{
user.Password = _encryption.Encrypt(newPassword);
user = await _userBusiness.UpdateAsync(user.Id, user).ConfigureAwait(false);
if (user != null)
{
await SendMailAsync(
MessageTemplateType.EmailChangePassword,
new
{
user.FirstName,
user.Email
},
user.FirstName,
email).ConfigureAwait(false);
return user;
}
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Lista de regras do usuário
/// </summary>
/// <param name="user">Usuário</param>
/// <returns>Lista de regras</returns>
private IList<Claim> GetClaims(
User user)
{
try
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.MobilePhone, user.Phone),
new Claim(nameof(IAuthUser.IsEmailValidated), user.IsEmailValidated.ToString(System.Globalization.CultureInfo.InvariantCulture))
};
if (user?.UserRoles != null && user.UserRoles.Any(w => !w.ExcludedOn.HasValue))
{
foreach (UserRole item in user.UserRoles.Where(w => !w.ExcludedOn.HasValue))
{
claims.Add(new Claim(ClaimTypes.Role, item.RoleType.ToString()));
}
}
return claims;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Recupera o email do token de refresh
/// </summary>
/// <param name="refreshToken">Token de refresh</param>
/// <returns>Email associado</returns>
private string ExtractEmailFromRefreshToken(
string refreshToken)
{
try
{
JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtSecurityToken = jwtSecurityTokenHandler.ReadJwtToken(refreshToken);
if (jwtSecurityToken != null && jwtSecurityToken.Claims != null && jwtSecurityToken.Claims.Any())
{
if (jwtSecurityToken.Claims.Any(w => w.Type == "email"))
{
return jwtSecurityToken.Claims.First(w => w.Type == "email").Value;
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
return null;
}
/// <summary>
/// Envio de email
/// </summary>
/// <param name="messageTemplateType">Template da mensagem</param>
/// <param name="data">Dados da mensagem</param>
/// <param name="firstName">Primeiro nome do destinatário</param>
/// <param name="toEmail">Email do destinatário</param>
/// <returns></returns>
private async Task SendMailAsync(
MessageTemplateType messageTemplateType,
dynamic data,
string firstName,
string toEmail)
{
string message = _messageTemplate.GetTemplate(
messageTemplateType,
data);
string subject = _messageTemplate.GetSubject(
messageTemplateType,
new
{
FirstName = firstName
});
await _emailSender.SendAsync(
toEmail,
subject,
message).ConfigureAwait(false);
}
/// <summary>
/// Reenvia o código de confirmação
/// </summary>
/// <param name="email">Email do usuário</param>
/// <returns>Sucesso</returns>
public async Task ResendConfirmationCodeAsync(
string email)
{
User user = await _userBusiness.ReadFirstAsync($"{nameof(User.Email)} == {email} AND {nameof(User.IsEmailValidated)} == {false}").ConfigureAwait(false);
if (user != null)
{
await SendMailAsync(
MessageTemplateType.EmailNewUserRegister,
new
{
user.FirstName,
ConfirmationToken = _encryption.Encrypt(user.Email),
_general.BaseUri
},
user.FirstName,
user.Email);
}
}
}
}
| 35.936877 | 164 | 0.455718 |
0902e7f17938e2a9529d1ecd9f6a4a2e17db0de8 | 3,665 | cs | C# | src/Mvc/Mvc.Abstractions/test/Filters/FilterContextTest.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 5,846 | 2015-01-01T04:37:18.000Z | 2022-03-28T15:29:09.000Z | src/Mvc/Mvc.Abstractions/test/Filters/FilterContextTest.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 6,875 | 2015-01-02T17:38:42.000Z | 2018-12-14T00:48:31.000Z | src/Mvc/Mvc.Abstractions/test/Filters/FilterContextTest.cs | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 3,109 | 2015-01-03T01:24:11.000Z | 2022-03-28T12:31:07.000Z | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Routing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Filters
{
public class FilterContextTest
{
[Fact]
public void IsEffectivePolicy_FindsAnotherFilter_ReturnsFalse()
{
// Arrange
var filters = new IFilterMetadata[]
{
Mock.Of<ITestFilterPolicy>(),
Mock.Of<IAnotherTestFilterPolicy>(),
Mock.Of<ITestFilterPolicy>(),
};
var context = new TestFilterContext(filters);
// Act
var result = context.IsEffectivePolicy((ITestFilterPolicy)filters.First());
// Assert
Assert.False(result);
}
[Fact]
public void IsEffectivePolicy_FindsFilterOfInterest_ReturnsTrue()
{
// Arrange
var filters = new IFilterMetadata[]
{
Mock.Of<ITestFilterPolicy>(),
Mock.Of<IAnotherTestFilterPolicy>(),
Mock.Of<ITestFilterPolicy>(),
};
var context = new TestFilterContext(filters);
// Act
var result = context.IsEffectivePolicy((ITestFilterPolicy)filters.Last());
// Assert
Assert.True(result);
}
[Fact]
public void IsEffectivePolicy_NoMatch_ReturnsFalse()
{
// Arrange
var filters = new IFilterMetadata[]
{
Mock.Of<ITestFilterPolicy>(),
Mock.Of<ITestFilterPolicy>(),
};
var context = new TestFilterContext(filters);
// Act
var result = context.IsEffectivePolicy(Mock.Of<IAnotherTestFilterPolicy>());
// Assert
Assert.False(result);
}
[Fact]
public void FindEffectivePolicy_FindsLastFilter_ReturnsIt()
{
// Arrange
var filters = new IFilterMetadata[]
{
Mock.Of<ITestFilterPolicy>(),
Mock.Of<IAnotherTestFilterPolicy>(),
Mock.Of<ITestFilterPolicy>(),
};
var context = new TestFilterContext(filters);
// Act
var result = context.FindEffectivePolicy<ITestFilterPolicy>();
// Assert
Assert.Same(filters.Last(), result);
}
[Fact]
public void FindEffectivePolicy_NoMatch_ReturnsNull()
{
// Arrange
var filters = new IFilterMetadata[]
{
Mock.Of<ITestFilterPolicy>(),
Mock.Of<ITestFilterPolicy>(),
};
var context = new TestFilterContext(filters);
// Act
var result = context.FindEffectivePolicy<IAnotherTestFilterPolicy>();
// Assert
Assert.Null(result);
}
internal class ITestFilterPolicy : IFilterMetadata
{
}
internal class IAnotherTestFilterPolicy : IFilterMetadata
{
}
private class TestFilterContext : FilterContext
{
public TestFilterContext(IList<IFilterMetadata> filters)
: base(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), filters)
{
}
}
}
}
| 27.765152 | 117 | 0.553615 |
449f60dc3873dbbf5b458adfc160ae6b736838e1 | 3,343 | cs | C# | CSharp Advanced Exam Preparation/CSharp_Advanced_Exam_23_June_2019/01.SpaceCrafting/Program.cs | NeSh74/Advanced-Csharp-May-2021 | 015e64f378be3caf4a6f6687a05a0ed15bbcffb0 | [
"MIT"
] | null | null | null | CSharp Advanced Exam Preparation/CSharp_Advanced_Exam_23_June_2019/01.SpaceCrafting/Program.cs | NeSh74/Advanced-Csharp-May-2021 | 015e64f378be3caf4a6f6687a05a0ed15bbcffb0 | [
"MIT"
] | null | null | null | CSharp Advanced Exam Preparation/CSharp_Advanced_Exam_23_June_2019/01.SpaceCrafting/Program.cs | NeSh74/Advanced-Csharp-May-2021 | 015e64f378be3caf4a6f6687a05a0ed15bbcffb0 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _01.SpaceCrafting
{
class Program
{
static void Main(string[] args)
{
var liquidsInput = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
var itemsInput = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int glassCount = 0;
int aluminiumCount = 0;
int lithiumCount = 0;
int carbonCount = 0;
var liquids = new Queue<int>(liquidsInput);
var items = new Stack<int>(itemsInput);
while (liquids.Any() && items.Any())
{
int currentLiquid = liquids.Dequeue();
int currentItem = items.Pop();
if (currentLiquid + currentItem == 25) // Glass
{
glassCount++;
}
else if (currentLiquid + currentItem == 50) // Aluminium
{
aluminiumCount++;
}
else if (currentLiquid + currentItem == 75) // Lithium
{
lithiumCount++;
}
else if (currentLiquid + currentItem == 100) // Carbon fiber
{
carbonCount++;
}
else
{
items.Push(currentItem + 3);
}
}
string result = PrintOutput(
glassCount,
aluminiumCount,
lithiumCount,
carbonCount,
liquids,
items);
Console.WriteLine(result);
}
private static string PrintOutput(int glassCount, int aluminiumCount, int lithiumCount, int carbonCount, Queue<int> liquids, Stack<int> items)
{
var result = new StringBuilder();
if (glassCount > 0
&& aluminiumCount > 0
&& lithiumCount > 0
&& carbonCount > 0)
{
result.AppendLine("Wohoo! You succeeded in building the spaceship!");
}
else
{
result.AppendLine("Ugh, what a pity! You didn't have enough materials to build the spaceship.");
}
if (liquids.Any())
{
result.AppendLine($"Liquids left: {string.Join(", ", liquids)}");
}
else
{
result.AppendLine("Liquids left: none");
}
if (items.Any())
{
result.AppendLine($"Physical items left: {string.Join(", ", items)}");
}
else
{
result.AppendLine("Physical items left: none");
}
result.AppendLine($"Aluminium: {aluminiumCount}");
result.AppendLine($"Carbon fiber: {carbonCount}");
result.AppendLine($"Glass: {glassCount}");
result.AppendLine($"Lithium: {lithiumCount}");
return result.ToString().TrimEnd();
}
}
}
| 30.117117 | 150 | 0.458869 |
78aee3a34aea1747b04ee7822bc08daeaae302bd | 320 | cs | C# | EpisodeDownloader/Program.cs | RobertSmits/EpisodeDownloader | 582970196e837ebaba8224f0eb139591f9fb4fb7 | [
"MIT"
] | null | null | null | EpisodeDownloader/Program.cs | RobertSmits/EpisodeDownloader | 582970196e837ebaba8224f0eb139591f9fb4fb7 | [
"MIT"
] | null | null | null | EpisodeDownloader/Program.cs | RobertSmits/EpisodeDownloader | 582970196e837ebaba8224f0eb139591f9fb4fb7 | [
"MIT"
] | null | null | null | using System.Threading;
using System.Threading.Tasks;
namespace EpisodeDownloader
{
public class Program
{
public static Task Main(string[] args)
{
var downloader = Bootstrapper.BuildEpisodeDownloader();
return downloader.Run(new CancellationToken());
}
}
}
| 21.333333 | 67 | 0.640625 |
742dabfcef8e4ea4a91f4a90fa4df5713224a230 | 567 | cs | C# | AlexaSkillsKit.Lib/Speechlet/AudioPlayerRequest.cs | Apoc70/ExchangeSpeechAssistant | 49ccbcda15764b48c0a685c4b7e299f777462e5c | [
"MIT"
] | null | null | null | AlexaSkillsKit.Lib/Speechlet/AudioPlayerRequest.cs | Apoc70/ExchangeSpeechAssistant | 49ccbcda15764b48c0a685c4b7e299f777462e5c | [
"MIT"
] | null | null | null | AlexaSkillsKit.Lib/Speechlet/AudioPlayerRequest.cs | Apoc70/ExchangeSpeechAssistant | 49ccbcda15764b48c0a685c4b7e299f777462e5c | [
"MIT"
] | null | null | null | // New file created by Tam Huynh (tamhinsf)
// Original AlexaSkillsLib Copyright 2015 Stefan Negritoiu (FreeBusy). See LICENSE file for more information.
using System;
using System.Diagnostics;
using AlexaSkillsKit.Slu;
namespace AlexaSkillsKit.Speechlet
{
public class AudioPlayerRequest : SpeechletRequest
{
public AudioPlayerRequest(string requestId, DateTime timestamp)
: base(requestId, timestamp)
{
}
public virtual Context Context
{
get;
private set;
}
}
} | 22.68 | 110 | 0.656085 |
64fdbcdfba34ef6067587fac54135a50302809da | 5,406 | cs | C# | source/GeoVR.Client/Audio/SelcalInput.cs | sawbe/GeoVR | 7084b9ef48e688cb3db20cd87df4ac0a7f062bb8 | [
"MIT"
] | 14 | 2018-08-12T11:02:59.000Z | 2022-02-23T00:26:30.000Z | source/GeoVR.Client/Audio/SelcalInput.cs | sawbe/GeoVR | 7084b9ef48e688cb3db20cd87df4ac0a7f062bb8 | [
"MIT"
] | 5 | 2021-09-07T13:18:59.000Z | 2022-02-28T11:25:32.000Z | source/GeoVR.Client/Audio/SelcalInput.cs | sawbe/GeoVR | 7084b9ef48e688cb3db20cd87df4ac0a7f062bb8 | [
"MIT"
] | 9 | 2019-10-21T22:16:42.000Z | 2022-03-25T17:22:10.000Z | using Concentus.Enums;
using Concentus.Structs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System.Timers;
namespace GeoVR.Client
{
public class SelcalInput
{
private static Dictionary<char, float> codeLookup = new Dictionary<char, float>
{
{ 'A', 312.6f },
{ 'B', 346.7f },
{ 'C', 384.6f },
{ 'D', 426.6f },
{ 'E', 473.2f },
{ 'F', 524.8f },
{ 'G', 582.1f },
{ 'H', 645.7f },
{ 'J', 716.1f },
{ 'K', 794.3f },
{ 'L', 881.0f },
{ 'M', 977.2f },
{ 'P', 1083.9f },
{ 'Q', 1202.3f },
{ 'R', 1333.5f },
{ 'S', 1479.1f },
};
private static TimeSpan codeDuration = TimeSpan.FromSeconds(1);
private readonly int frameSize = 960;
private OpusEncoder encoder;
private SelcalOpusDataAvailableEventArgs opusDataAvailableArgs;
private SignalGenerator signalGeneratorA;
private SignalGenerator signalGeneratorB;
private MixingSampleProvider signalMixer;
private readonly float[] signalBuffer;
private readonly byte[] encodedSignalBuffer;
private uint audioSequenceCounter;
private string tonesPlaying;
private int toneSent;
private Timer playbackTimer;
public event EventHandler<SelcalOpusDataAvailableEventArgs> OpusDataAvailable;
public event EventHandler Stopped;
public bool Playing { get; private set; }
public long OpusBytesEncoded { get; set; }
public SelcalInput(int sampleRate)
{
encoder = OpusEncoder.Create(sampleRate, 1, OpusApplication.OPUS_APPLICATION_VOIP);
encoder.Bitrate = 16 * 1024;
signalGeneratorA = new SignalGenerator(sampleRate, 1) { Gain = 0.07, Type = SignalGeneratorType.Sin };
signalGeneratorB = new SignalGenerator(sampleRate, 1) { Gain = 0.07, Type = SignalGeneratorType.Sin };
signalMixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, 1)) { ReadFully = false };
signalBuffer = new float[frameSize];
encodedSignalBuffer = new byte[1275];//the maximum encode size
opusDataAvailableArgs = new SelcalOpusDataAvailableEventArgs();
playbackTimer = new Timer(10);
playbackTimer.Elapsed += PlaybackTimer_Elapsed;
}
/// <summary>
/// Starts playback of SELCAL tones
/// </summary>
/// <param name="code">Capitalized SELCAL code without hyphen eg "ABCD"</param>
public void Play(string code)
{
if (Playing)
Stop();
if (code.Length != 4 || code.Any(c=>!codeLookup.ContainsKey(c)))
throw new ArgumentException("Invalid SELCAL tone");
tonesPlaying = code;
AddSignalsToMixer(code.Substring(0, 2));
Playing = true;
playbackTimer.Start();
}
public void Stop()
{
Playing = false;
playbackTimer.Stop();
tonesPlaying = string.Empty;
toneSent = 0;
Stopped?.Invoke(this, new EventArgs());
}
private void PlaybackTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!Playing)
return;
Array.Clear(signalBuffer, 0, signalBuffer.Length);
int read = signalMixer.Read(signalBuffer, 0, frameSize);
if (read == 0)//end of singals reached
{
if(++toneSent >= 2)
{
Stop();
}
else//this can only mean we have the second tone to play
{
AddSignalsToMixer(tonesPlaying.Substring(2, 2));
playbackTimer.Start();
}
}
else //data available
{
int encodedDataLength = encoder.Encode(signalBuffer, 0, frameSize, encodedSignalBuffer, 0, encodedSignalBuffer.Length);
OpusBytesEncoded += encodedDataLength;
byte[] trimmedBuff = new byte[encodedDataLength];
Buffer.BlockCopy(encodedSignalBuffer, 0, trimmedBuff, 0, encodedDataLength);
opusDataAvailableArgs.Audio = trimmedBuff;
opusDataAvailableArgs.SequenceCounter = audioSequenceCounter++;
opusDataAvailableArgs.LastData = read < frameSize;
OpusDataAvailable(this, opusDataAvailableArgs);
playbackTimer.Start();
}
}
private void AddSignalsToMixer(string partTone)
{
signalMixer.RemoveAllMixerInputs();
signalGeneratorA.Frequency = codeLookup[partTone[0]];
signalGeneratorB.Frequency = codeLookup[partTone[1]];
signalMixer.AddMixerInput(signalGeneratorA.Take(codeDuration));
signalMixer.AddMixerInput(signalGeneratorB.Take(codeDuration));
}
public class SelcalOpusDataAvailableEventArgs : OpusDataAvailableEventArgs
{
public bool LastData { get; set; }
}
}
}
| 34.653846 | 135 | 0.574917 |
a4874b2922802c1953f6e170205762d0bb18d541 | 62,625 | cs | C# | src/L3-solution/BoSSS.Solution.EnergyCommon/EnergyUtils.cs | FDYdarmstadt/BoSSS | 974f3eee826424a213e68d8d456d380aeb7cd7e9 | [
"Apache-2.0"
] | 22 | 2017-06-08T05:53:17.000Z | 2021-05-25T13:12:17.000Z | src/L3-solution/BoSSS.Solution.EnergyCommon/EnergyUtils.cs | FDYdarmstadt/BoSSS | 974f3eee826424a213e68d8d456d380aeb7cd7e9 | [
"Apache-2.0"
] | 1 | 2020-07-20T15:32:56.000Z | 2020-07-20T15:34:22.000Z | src/L3-solution/BoSSS.Solution.EnergyCommon/EnergyUtils.cs | FDYdarmstadt/BoSSS | 974f3eee826424a213e68d8d456d380aeb7cd7e9 | [
"Apache-2.0"
] | 12 | 2018-01-05T19:52:35.000Z | 2021-05-07T07:49:27.000Z | /* =======================================================================
Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BoSSS.Foundation;
using ilPSP.LinSolvers;
using ilPSP.Tracing;
using BoSSS.Foundation.XDG;
using BoSSS.Foundation.Quadrature;
using ilPSP;
using ilPSP.Utils;
using System.Diagnostics;
using BoSSS.Foundation.Grid;
using BoSSS.Solution.LevelSetTools;
using System.Collections;
using BoSSS.Platform;
namespace BoSSS.Solution.XNSECommon {
public static class EnergyUtils {
#region global energies (kinetic energy in bulk and surface energy in interface)
/// <summary>
/// Computes the kinetic energy stored in the bulk of a multi-phase flow field.
/// </summary>
/// <param name="Velocity"></param>
/// <param name="rho">Density of the fluids, ordering in the array correlates with species
/// ordering in the level-set tracker, see <see cref="LevelSetTracker.SpeciesIdS"/>.
/// </param>
/// <param name="lsTrk"></param>
/// <param name="momentFittingOrder"></param>
public static double GetKineticEnergy<T>(LevelSetTracker lsTrk, IEnumerable<T> Velocity, double[] rho, int momentFittingOrder, int HistInd = 1)
where T : DGField //
{
using(new FuncTrace()) {
int D = lsTrk.GridDat.SpatialDimension;
if(Velocity.Count() != D) {
throw new ArgumentException();
}
if(lsTrk.SpeciesIdS.Count != rho.Length)
throw new ArgumentException();
//int order = 0;
//if (lsTrk.GetXQuadFactoryHelper(momentFittingVariant).GetCachedVolumeOrders(0).Length > 0) {
// order = lsTrk.GetXQuadFactoryHelper(momentFittingVariant).GetCachedVolumeOrders(0).Max();
//}
//order = Math.Max(order, Velocity.ElementAt(0).Basis.Degree * 2);
var SchemeHelper = lsTrk.GetXDGSpaceMetrics(lsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
//var SchemeHelper = new XQuadSchemeHelper(lsTrk, momentFittingVariant, lsTrk.SpeciesIdS.ToArray());
double kinE = 0.0;
for(int iSpc = 0; iSpc < lsTrk.SpeciesIdS.Count; iSpc++) {
double _rho = rho[iSpc];
SpeciesId spId = lsTrk.SpeciesIdS[iSpc];
var scheme = SchemeHelper.GetVolumeQuadScheme(spId);
for(int d = 0; d < D; d++) {
DGField U = Velocity.ElementAt(d);
if(U is XDGField) {
if(!object.ReferenceEquals((U as XDGField).Basis.Tracker, lsTrk))
throw new ArgumentException();
U = (U as XDGField).GetSpeciesShadowField(spId);
}
kinE += U.L2Error(null, momentFittingOrder, scheme).Pow2() * _rho * 0.5;
}
}
return kinE;
}
}
/// <summary>
/// Computes the energy stored in the fluid interface of a two-phase flow.
/// </summary>
/// <param name="LsTrk"></param>
/// <param name="sigma">Surface tension \f$ \sigma \f$.</param>
/// <param name="momentFittingOrder"></param>
public static double GetSurfaceEnergy(LevelSetTracker LsTrk, double sigma, int momentFittingOrder, int HistInd = 1) {
using(new FuncTrace()) {
if(LsTrk.LevelSets.Count != 1)
throw new NotImplementedException();
double totSurface = 0;
int order = 0;
if(LsTrk.GetCachedOrders().Count > 0) {
order = LsTrk.GetCachedOrders().Max();
} else {
order = 1;
}
//var SchemeHelper = new XQuadSchemeHelper(LsTrk, momentFittingVariant, LsTrk.GetSpeciesId("A"));
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, order, HistInd).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.RegionsHistory[HistInd].GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, order),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
EvalResult.SetAll(1.0);
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for(int i = 0; i < Length; i++)
totSurface += ResultsOfIntegration[i, 0];
}
).Execute();
return totSurface * sigma;
}
}
public static double GetKineticDissipation(LevelSetTracker LsTrk, DGField[] Velocity, double[] mu, int momentFittingOrder, int HistInd = 1) {
using(new FuncTrace()) {
int D = LsTrk.GridDat.SpatialDimension;
if(Velocity.Count() != D) {
throw new ArgumentException();
}
if(LsTrk.SpeciesIdS.Count != mu.Length)
throw new ArgumentException();
double dE = 0.0;
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
for(int iSpc = 0; iSpc < LsTrk.SpeciesIdS.Count; iSpc++) {
SpeciesId spcId = LsTrk.SpeciesIdS[iSpc];
double _mu = mu[iSpc];
var Uspc = Velocity.Select(u => (u as XDGField).GetSpeciesShadowField(spcId)).ToArray();
ScalarFunctionEx changerate_dEspc = GetSpeciesKineticDissipationFunc(Uspc, _mu);
CellQuadratureScheme vqs = SchemeHelper.GetVolumeQuadScheme(spcId);
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
vqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
changerate_dEspc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for(int i = 0; i < Length; i++)
dE += ResultsOfIntegration[i, 0];
}
).Execute();
}
return dE;
}
}
public static double GetInterfaceDilatationalViscosityEnergyCR(LevelSetTracker LsTrk, ConventionalDGField[] uI, double lamI, int momentFittingOrder) {
double dilViscEnergy = 0.0;
ScalarFunctionEx dilViscEnergyFunc = GetInterfaceDivergenceFunc(LsTrk, uI, true);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingOrder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
dilViscEnergyFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for(int i = 0; i < Length; i++)
dilViscEnergy += ResultsOfIntegration[i, 0];
}
).Execute();
return lamI * dilViscEnergy;
}
static ScalarFunctionEx GetInterfaceShearViscosityEnergyCRFunc(LevelSetTracker LsTrk, ConventionalDGField[] uI, bool squared) {
int D = LsTrk.GridDat.SpatialDimension;
return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray GradU_Res = MultidimensionalArray.Create(Len, K, D, D);
for(int i = 0; i < D; i++) {
uI.ElementAt(i).EvaluateGradient(i0, Len, nds, GradU_Res.ExtractSubArrayShallow(-1, -1, i, -1));
}
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(nds, i0, Len);
for(int j = 0; j < Len; j++) {
for(int k = 0; k < K; k++) {
MultidimensionalArray Nsurf = Normals.ExtractSubArrayShallow(j, k, -1);
double[,] Psurf = new double[D, D];
for(int d1 = 0; d1 < D; d1++) {
for(int d2 = 0; d2 < D; d2++) {
if(d2 == d1)
Psurf[d1, d2] = (1 - Nsurf[d1] * Nsurf[d2]);
else
Psurf[d1, d2] = (0 - Nsurf[d1] * Nsurf[d2]);
}
}
double[,] GradUsurf = new double[D, D];
for(int d1 = 0; d1 < D; d1++) {
for(int d2 = 0; d2 < D; d2++) {
for(int dd = 0; dd < D; dd++) {
GradUsurf[d1, d2] += Psurf[d1, dd] * GradU_Res[j, k, dd, d2];
}
}
}
double acc = 0.0;
// GradU
for(int d1 = 0; d1 < D; d1++) {
for(int d2 = 0; d2 < D; d2++) {
for(int dd = 0; dd < D; dd++) {
acc += Psurf[d1, dd] * GradUsurf[dd, d2] * GradUsurf[d1, d2];
}
}
}
// GradU transpose
double[,] Psurf2 = new double[D, D];
for(int d1 = 0; d1 < D; d1++) {
for(int d2 = 0; d2 < D; d2++) {
if(d2 == d1)
Psurf2[d1, d2] = (1 - 2 * Nsurf[d1] * Nsurf[d2]);
else
Psurf2[d1, d2] = (0 - 2 * Nsurf[d1] * Nsurf[d2]);
}
}
for(int d1 = 0; d1 < D; d1++) {
for(int d2 = 0; d2 < D; d2++) {
for(int dd = 0; dd < D; dd++) {
acc -= GradU_Res[j, k, d1, dd] * Psurf2[dd, d2] * GradUsurf[d1, d2];
}
}
}
if(squared) {
result[j, k] = acc.Pow2();
} else {
result[j, k] = acc;
}
}
}
};
}
public static double GetInterfaceShearViscosityEnergyCR(LevelSetTracker LsTrk, ConventionalDGField[] uI, double muI, int momentFittingOrder) {
double shearViscEnergy = 0.0;
ScalarFunctionEx shearViscEnergyFunc = GetInterfaceShearViscosityEnergyCRFunc(LsTrk, uI, false);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingOrder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
shearViscEnergyFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for(int i = 0; i < Length; i++)
shearViscEnergy += ResultsOfIntegration[i, 0];
}
).Execute();
return muI * shearViscEnergy;
}
#endregion
#region local energy fields
static ScalarFunctionEx GetSpeciesKineticDissipationFunc(DGField[] U, double mu) {
int D = U[0].Basis.GridDat.SpatialDimension;
return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray GradU_res = MultidimensionalArray.Create(Len, K, D, D);
for (int i = 0; i < D; i++) {
U[i].EvaluateGradient(i0, Len, nds, GradU_res.ExtractSubArrayShallow(-1, -1, i, -1));
}
MultidimensionalArray U_res = MultidimensionalArray.Create(Len, K, D);
for (int i = 0; i < D; i++) {
U.ElementAt(i).Evaluate(i0, Len, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
}
double acc;
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
acc = 0.0;
for (int d = 0; d < D; d++) {
// viscous term
for (int dd = 0; dd < D; dd++) {
acc -= mu * (GradU_res[j, k, d, dd] * GradU_res[j, k, dd, d] + GradU_res[j, k, dd, d] * GradU_res[j, k, dd, d]);
}
}
result[j, k] = acc;
}
}
};
}
public static void ProjectKineticDissipation(this XDGField proj, LevelSetTracker LsTrk, DGField[] Velocity, double[] mu, int momentFittingOrder, int HistInd = 1) {
using (new FuncTrace()) {
int D = LsTrk.GridDat.SpatialDimension;
if (Velocity.Count() != D) {
throw new ArgumentException();
}
if (LsTrk.SpeciesIdS.Count != mu.Length)
throw new ArgumentException();
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
for (int iSpc = 0; iSpc < LsTrk.SpeciesIdS.Count; iSpc++) {
SpeciesId spcId = LsTrk.SpeciesIdS[iSpc];
double muSpc = mu[iSpc];
var Uspc = Velocity.Select(u => (u as XDGField).GetSpeciesShadowField(spcId)).ToArray();
ScalarFunctionEx spcKinDissip = GetSpeciesKineticDissipationFunc(Uspc, muSpc);
proj.GetSpeciesShadowField(spcId).ProjectField(spcKinDissip);
}
}
}
public static void ProjectKineticEnergy(this XDGField proj, LevelSetTracker LsTrk, XDGField[] Velocity, double[] rho, int momentFittingOrder, int HistInd = 1) {
using (new FuncTrace()) {
int D = LsTrk.GridDat.SpatialDimension;
if (Velocity.Count() != D) {
throw new ArgumentException();
}
if (LsTrk.SpeciesIdS.Count != rho.Length)
throw new ArgumentException();
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
for (int iSpc = 0; iSpc < LsTrk.SpeciesIdS.Count; iSpc++) {
SpeciesId spcId = LsTrk.SpeciesIdS[iSpc];
double _rho = rho[iSpc];
var Uspc = Velocity.Select(u => (u as XDGField).GetSpeciesShadowField(spcId)).ToArray();
//ScalarFunctionEx spcKinDissip = GetSpeciesKineticDissipationFunc(Uspc, _rho);
ScalarFunctionEx spcKinEnergy = delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray U_res = MultidimensionalArray.Create(Len, K, D);
for (int i = 0; i < D; i++) {
Uspc[i].Evaluate(i0, Len, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
}
double acc;
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
acc = 0.0;
for (int d = 0; d < D; d++) {
acc += U_res[j, k, d] * U_res[j, k, d];
}
result[j, k] = _rho * acc / 2.0;
}
}
};
proj.GetSpeciesShadowField(spcId).ProjectField(spcKinEnergy);
}
}
}
static ScalarFunctionEx GetSpeciesPowerOfStressesFunc(DGField P, DGField[] U, DGField[,] GradU, double mu) {
int D = U[0].Basis.GridDat.SpatialDimension;
return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
//MultidimensionalArray P_res = MultidimensionalArray.Create(Len, K);
MultidimensionalArray GradP_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray U_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray GradU_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray GGradU_res = MultidimensionalArray.Create(Len, K, D, D, D);
//P.Evaluate(i0, Len, nds, P_res.ExtractSubArrayShallow(-1, -1));
P.EvaluateGradient(i0, Len, nds, GradP_res.ExtractSubArrayShallow(-1, -1, -1));
for (int i = 0; i < D; i++) {
U.ElementAt(i).Evaluate(i0, Len, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
//U[i].EvaluateGradient(i0, Len, nds, GradU_res.ExtractSubArrayShallow(-1, -1, i, -1));
for (int j = 0; j < D; j++) {
GradU[i, j].Evaluate(i0, Len, nds, GradU_res.ExtractSubArrayShallow(-1, -1, i, j));
GradU[i, j].EvaluateGradient(i0, Len, nds, GGradU_res.ExtractSubArrayShallow(-1, -1, i, j, -1));
}
}
double acc;
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
if (D > 2)
throw new NotImplementedException("TODO");
double[] DivGradUT = new double[D];
double[] LapU = new double[D];
for (int d = 0; d < D; d++) {
DivGradUT[d] += GGradU_res[j, k, 0, d, 0] + GGradU_res[j, k, 1, d, 1];
LapU[d] += GGradU_res[j, k, d, 0, 0] + GGradU_res[j, k, d, 1, 1];
}
acc = 0.0;
for (int d = 0; d < D; d++) {
// gradP * U
acc -= GradP_res[j, k, d] * U_res[j, k, d];
// div(gradU^T)
acc += mu * DivGradUT[d] * U_res[j, k, d];
// lapU
acc += mu * LapU[d] * U_res[j, k, d];
for (int dd = 0; dd < D; dd++) {
// gradU^T:gradU
acc += mu * GradU_res[j, k, dd, d] * GradU_res[j, k, d, dd];
// gradU:gradU
acc += mu * GradU_res[j, k, d, dd] * GradU_res[j, k, d, dd];
}
}
result[j, k] = acc;
}
}
};
}
public static void ProjectPowerOfStresses(this XDGField proj, LevelSetTracker LsTrk, DGField Pressure, DGField[] Velocity, double[] mu, int momentFittingOrder, int HistInd = 1) {
using (new FuncTrace()) {
int D = LsTrk.GridDat.SpatialDimension;
if (Velocity.Count() != D) {
throw new ArgumentException();
}
if (LsTrk.SpeciesIdS.Count != mu.Length)
throw new ArgumentException();
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
for (int iSpc = 0; iSpc < LsTrk.SpeciesIdS.Count; iSpc++) {
SpeciesId spcId = LsTrk.SpeciesIdS[iSpc];
double muSpc = mu[iSpc];
SubGrid sf = LsTrk.Regions.GetSpeciesSubGrid(spcId);
var Pspc = (Pressure as XDGField).GetSpeciesShadowField(spcId);
var Uspc = Velocity.Select(u => (u as XDGField).GetSpeciesShadowField(spcId)).ToArray();
VectorField<DGField> GradVelX = new VectorField<DGField>(D, Velocity[0].Basis, XDGField.Factory);
VectorField<DGField> GradVelY = new VectorField<DGField>(D, Velocity[1].Basis, XDGField.Factory);
for (int d = 0; d < D; d++) {
DGField f_Spc;
f_Spc = ((Velocity[0] as XDGField).GetSpeciesShadowField(spcId));
(GradVelX[d] as XDGField).GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf);
f_Spc = ((Velocity[1] as XDGField).GetSpeciesShadowField(spcId));
(GradVelY[d] as XDGField).GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf);
}
GradVelX.ForEach(F => F.CheckForNanOrInf(true, true, true));
GradVelY.ForEach(F => F.CheckForNanOrInf(true, true, true));
DGField[,] GradU = new DGField[D, D];
GradU[0, 0] = GradVelX[0];
GradU[0, 1] = GradVelX[1];
GradU[1, 0] = GradVelY[0];
GradU[1, 1] = GradVelY[1];
ScalarFunctionEx spcPowStress = GetSpeciesPowerOfStressesFunc(Pspc, Uspc, GradU, muSpc);
proj.GetSpeciesShadowField(spcId).ProjectField(spcPowStress);
}
}
}
//static ScalarFunctionEx GetSpeciesKinEchangerateNSE(DGField[] U, double mu) {
// int D = U[0].Basis.GridDat.SpatialDimension;
// return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
// int K = result.GetLength(1); // No nof Nodes
// MultidimensionalArray U_res = MultidimensionalArray.Create(Len, K, D);
// MultidimensionalArray GradU_res = MultidimensionalArray.Create(Len, K, D, D);
// for (int i = 0; i < D; i++) {
// U.ElementAt(i).Evaluate(i0, Len, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
// U.ElementAt(i).EvaluateGradient(i0, Len, nds, GradU_res.ExtractSubArrayShallow(-1, -1, i, -1));
// }
// double acc;
// for (int j = 0; j < Len; j++) {
// for (int k = 0; k < K; k++) {
// if (D > 2)
// throw new NotImplementedException("TODO");
// acc = 0.0;
// for (int d = 0; d < D; d++) {
// for (int dd = 0; dd < D; dd++) {
// // gradU:gradU
// acc += mu * GradU_res[j, k, d, dd] * GradU_res[j, k, d, dd];
// // gradU^T:gradU
// acc += mu * GradU_res[j, k, dd, d] * GradU_res[j, k, d, dd];
// }
// }
// result[j, k] = -acc;
// }
// }
// };
//}
//public static void ProjectKineticEnergyChangerateNSE(this XDGField proj, LevelSetTracker LsTrk, DGField[] Velocity, double[] mu, int momentFittingOrder, int HistInd = 1) {
// using (new FuncTrace()) {
// int D = LsTrk.GridDat.SpatialDimension;
// if (Velocity.Count() != D) {
// throw new ArgumentException();
// }
// if (LsTrk.SpeciesIdS.Count != mu.Length)
// throw new ArgumentException();
// var SchemeHelper = LsTrk.GetXDGSpaceMetrics(LsTrk.SpeciesIdS.ToArray(), momentFittingOrder, HistInd).XQuadSchemeHelper;
// for (int iSpc = 0; iSpc < LsTrk.SpeciesIdS.Count; iSpc++) {
// SpeciesId spcId = LsTrk.SpeciesIdS[iSpc];
// double muSpc = mu[iSpc];
// SubGrid sf = LsTrk.Regions.GetSpeciesSubGrid(spcId);
// var Uspc = Velocity.Select(u => (u as XDGField).GetSpeciesShadowField(spcId)).ToArray();
// //VectorField<DGField> GradVelX = new VectorField<DGField>(D, Velocity[0].Basis, XDGField.Factory);
// //VectorField<DGField> GradVelY = new VectorField<DGField>(D, Velocity[1].Basis, XDGField.Factory);
// //for (int d = 0; d < D; d++) {
// // DGField f_Spc;
// // f_Spc = ((Velocity[0] as XDGField).GetSpeciesShadowField(spcId));
// // (GradVelX[d] as XDGField).GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf);
// // f_Spc = ((Velocity[1] as XDGField).GetSpeciesShadowField(spcId));
// // (GradVelY[d] as XDGField).GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f_Spc, d, optionalSubGrid: sf);
// //}
// //GradVelX.ForEach(F => F.CheckForNanOrInf(true, true, true));
// //GradVelY.ForEach(F => F.CheckForNanOrInf(true, true, true));
// //DGField[,] GradU = new DGField[D, D];
// //GradU[0, 0] = GradVelX[0];
// //GradU[0, 1] = GradVelX[1];
// //GradU[1, 0] = GradVelY[0];
// //GradU[1, 1] = GradVelY[1];
// ScalarFunctionEx spcPowStress = GetSpeciesKinEchangerateNSE(Uspc, muSpc);
// proj.GetSpeciesShadowField(spcId).ProjectField(spcPowStress);
// }
// }
//}
#endregion
#region energy balance
static ScalarFunctionEx GetFunc_EnergyBalanceAtInterface(XDGField p, VectorField<XDGField> u, VectorField<XDGField> gradUx, VectorField<XDGField> gradUy,
ConventionalDGField[] uI, VectorField<SinglePhaseField> gradUIx, VectorField<SinglePhaseField> gradUIy, SinglePhaseField curv, PhysicalParameters physParam) {
var LsTrk = p.Basis.Tracker;
int D = LsTrk.GridDat.SpatialDimension;
var pA = p.GetSpeciesShadowField("A");
var pB = p.GetSpeciesShadowField("B");
var uA = u.Select(v => v.GetSpeciesShadowField("A")).ToArray();
var uB = u.Select(v => v.GetSpeciesShadowField("B")).ToArray();
var gradUxA = gradUx.Select(v => v.GetSpeciesShadowField("A")).ToArray();
var gradUxB = gradUx.Select(v => v.GetSpeciesShadowField("B")).ToArray();
var gradUyA = gradUy.Select(v => v.GetSpeciesShadowField("A")).ToArray();
var gradUyB = gradUy.Select(v => v.GetSpeciesShadowField("B")).ToArray();
return delegate (int j0, int Len, NodeSet NS, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
int _D = D; // local var may be a bit faster
MultidimensionalArray pARes = MultidimensionalArray.Create(Len, K);
MultidimensionalArray pBRes = MultidimensionalArray.Create(Len, K);
MultidimensionalArray uARes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray uBRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUxARes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUxBRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUyARes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUyBRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray uIRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUIxRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUIyRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray curvRes = MultidimensionalArray.Create(Len, K);
int JE = LsTrk.GridDat.Cells.Count;
BitArray sbArray = new BitArray(JE);
for (int j = j0; j < j0 + Len; j++) {
sbArray[j] = true;
}
CellMask sbmask = new CellMask(LsTrk.GridDat, sbArray);
SubGrid sbgrd = new SubGrid(sbmask);
ClosestPointFinder cp = new ClosestPointFinder(LsTrk, 0, sbgrd, NS.ToEnumerable());
for (int dd = 0; dd < D; dd++) {
pARes.Set(cp.EvaluateAtCp(pA));
pBRes.Set(cp.EvaluateAtCp(pB));
uARes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(uA[dd]));
uBRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(uB[dd]));
gradUxARes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUxA[dd]));
gradUxBRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUxB[dd]));
gradUyARes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUyA[dd]));
gradUyBRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUyB[dd]));
uIRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(uI[dd]));
gradUIxRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUIx[dd]));
gradUIyRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUIy[dd]));
curvRes.Set(cp.EvaluateAtCp(curv));
}
MultidimensionalArray gradUARes = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray gradUBRes = MultidimensionalArray.Create(Len, K, D, D);
gradUARes.ExtractSubArrayShallow(-1, -1, 0, 0).Set(gradUxARes.ExtractSubArrayShallow(-1, -1, 0));
gradUARes.ExtractSubArrayShallow(-1, -1, 0, 1).Set(gradUxARes.ExtractSubArrayShallow(-1, -1, 1));
gradUARes.ExtractSubArrayShallow(-1, -1, 1, 0).Set(gradUyARes.ExtractSubArrayShallow(-1, -1, 0));
gradUARes.ExtractSubArrayShallow(-1, -1, 1, 1).Set(gradUyARes.ExtractSubArrayShallow(-1, -1, 1));
gradUBRes.ExtractSubArrayShallow(-1, -1, 0, 0).Set(gradUxBRes.ExtractSubArrayShallow(-1, -1, 0));
gradUBRes.ExtractSubArrayShallow(-1, -1, 0, 1).Set(gradUxBRes.ExtractSubArrayShallow(-1, -1, 1));
gradUBRes.ExtractSubArrayShallow(-1, -1, 1, 0).Set(gradUyBRes.ExtractSubArrayShallow(-1, -1, 0));
gradUBRes.ExtractSubArrayShallow(-1, -1, 1, 1).Set(gradUyBRes.ExtractSubArrayShallow(-1, -1, 1));
MultidimensionalArray gradUIRes = MultidimensionalArray.Create(Len, K, D, D);
gradUIRes.ExtractSubArrayShallow(-1, -1, 0, 0).Set(gradUIxRes.ExtractSubArrayShallow(-1, -1, 0));
gradUIRes.ExtractSubArrayShallow(-1, -1, 0, 1).Set(gradUIxRes.ExtractSubArrayShallow(-1, -1, 1));
gradUIRes.ExtractSubArrayShallow(-1, -1, 1, 0).Set(gradUIyRes.ExtractSubArrayShallow(-1, -1, 0));
gradUIRes.ExtractSubArrayShallow(-1, -1, 1, 1).Set(gradUIyRes.ExtractSubArrayShallow(-1, -1, 1));
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(NS, j0, Len);
double muA = physParam.mu_A;
double muB = physParam.mu_B;
double sigma = physParam.Sigma;
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
double Ej = 0;
for (int d = 0; d < _D; d++) {
// pressure
Ej -= (pBRes[j, k] * uBRes[j, k, d] - pARes[j, k] * uARes[j, k, d]) * Normals[j, k, d];
for (int dd = 0; dd < _D; dd++) {
// velocity gradients
Ej += (muB * gradUBRes[j, k, d, dd] * uBRes[j, k, dd] - muA * gradUARes[j, k, d, dd] * uARes[j, k, dd]) * Normals[j, k, d];
Ej += (muB * gradUBRes[j, k, dd, d] * uBRes[j, k, dd] - muA * gradUARes[j, k, dd, d] * uARes[j, k, dd]) * Normals[j, k, d];
// surface divergence
if (dd == d) {
Ej += sigma * (1.0 - Normals[j, k, d] * Normals[j, k, dd]) * gradUIRes[j, k, d, dd];
} else {
Ej += sigma * (0.0 - Normals[j, k, d] * Normals[j, k, dd]) * gradUIRes[j, k, d, dd];
}
}
// surface tension
Ej -= sigma * curvRes[j, k] * uIRes[j, k, d] * Normals[j, k, d];
}
result[j, k] = Ej;
}
}
};
}
public static void ProjectEnergyBalanceAtInterface(this SinglePhaseField err, double alpha, XDGField p, VectorField<XDGField> u, ConventionalDGField[] uI, SinglePhaseField curv, PhysicalParameters physParam, CellQuadratureScheme quadScheme = null) {
var LsTrk = u[0].Basis.Tracker;
int D = LsTrk.GridDat.SpatialDimension;
VectorField<XDGField> GuX = new VectorField<XDGField>(D, u[0].Basis, XDGField.Factory);
VectorField<XDGField> GuY = new VectorField<XDGField>(D, u[1].Basis, XDGField.Factory);
foreach (SpeciesId spcId in LsTrk.SpeciesIdS) {
SubGrid sf = LsTrk.Regions.GetSpeciesSubGrid(spcId);
DGField f0_Spc = u[0].GetSpeciesShadowField(spcId);
DGField f1_Spc = u[1].GetSpeciesShadowField(spcId);
for (int dd = 0; dd < D; dd++) {
GuX[dd].GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f0_Spc, dd, optionalSubGrid: sf);
GuY[dd].GetSpeciesShadowField(spcId).DerivativeByFlux(1.0, f1_Spc, dd, optionalSubGrid: sf);
}
}
GuX.ForEach(F => F.CheckForNanOrInf(true, true, true));
GuY.ForEach(F => F.CheckForNanOrInf(true, true, true));
VectorField<SinglePhaseField> GuIx = new VectorField<SinglePhaseField>(D, uI[0].Basis, SinglePhaseField.Factory);
VectorField<SinglePhaseField> GuIy = new VectorField<SinglePhaseField>(D, uI[1].Basis, SinglePhaseField.Factory);
for (int dd = 0; dd < D; dd++) {
GuIx[dd].DerivativeByFlux(1.0, uI[0], dd, optionalSubGrid: LsTrk.Regions.GetCutCellSubGrid());
GuIy[dd].DerivativeByFlux(1.0, uI[1], dd, optionalSubGrid: LsTrk.Regions.GetCutCellSubGrid());
}
GuIx.ForEach(F => F.CheckForNanOrInf(true, true, true));
GuIy.ForEach(F => F.CheckForNanOrInf(true, true, true));
ScalarFunctionEx ErrFunc = GetFunc_EnergyBalanceAtInterface(p, u, GuX, GuY, uI, GuIx, GuIy, curv, physParam);
int order = ((u[0].Basis.Degree - 1) + (p.Basis.Degree) + u[0].Basis.Degree + err.Basis.Degree + 2);
if (quadScheme == null)
quadScheme = (new CellQuadratureScheme(false, LsTrk.Regions.GetCutCellMask())).AddFixedOrderRules(LsTrk.GridDat, order);
err.ProjectField(alpha, ErrFunc,
quadScheme);
}
#endregion
#region interface terms
static ScalarFunctionEx GetFunc_InterfaceDivergence(LevelSetTracker LsTrk, VectorField<SinglePhaseField> gradUIx, VectorField<SinglePhaseField> gradUIy, PhysicalParameters physParam) {
int D = LsTrk.GridDat.SpatialDimension;
return delegate (int j0, int Len, NodeSet NS, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
int _D = D; // local var may be a bit faster
MultidimensionalArray gradUIxRes = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray gradUIyRes = MultidimensionalArray.Create(Len, K, D);
int JE = LsTrk.GridDat.Cells.Count;
BitArray sbArray = new BitArray(JE);
for (int j = j0; j < j0 + Len; j++) {
sbArray[j] = true;
}
CellMask sbmask = new CellMask(LsTrk.GridDat, sbArray);
SubGrid sbgrd = new SubGrid(sbmask);
ClosestPointFinder cp = new ClosestPointFinder(LsTrk, 0, sbgrd, NS.ToEnumerable());
for (int dd = 0; dd < D; dd++) {
gradUIxRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUIx[dd]));
gradUIyRes.ExtractSubArrayShallow(-1, -1, dd).Set(cp.EvaluateAtCp(gradUIy[dd]));
}
MultidimensionalArray gradUIRes = MultidimensionalArray.Create(Len, K, D, D);
gradUIRes.ExtractSubArrayShallow(-1, -1, 0, 0).Set(gradUIxRes.ExtractSubArrayShallow(-1, -1, 0));
gradUIRes.ExtractSubArrayShallow(-1, -1, 0, 1).Set(gradUIxRes.ExtractSubArrayShallow(-1, -1, 1));
gradUIRes.ExtractSubArrayShallow(-1, -1, 1, 0).Set(gradUIyRes.ExtractSubArrayShallow(-1, -1, 0));
gradUIRes.ExtractSubArrayShallow(-1, -1, 1, 1).Set(gradUIyRes.ExtractSubArrayShallow(-1, -1, 1));
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(NS, j0, Len);
double sigma = physParam.Sigma;
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
double divI = 0;
for (int d = 0; d < _D; d++) {
for (int dd = 0; dd < _D; dd++) {
// surface divergence
if (dd == d) {
divI += sigma * (1.0 - Normals[j, k, d] * Normals[j, k, dd]) * gradUIRes[j, k, d, dd];
} else {
divI += sigma * (0.0 - Normals[j, k, d] * Normals[j, k, dd]) * gradUIRes[j, k, d, dd];
}
}
}
result[j, k] = divI;
}
}
};
}
public static void ProjectInterfaceDivergence(this SinglePhaseField divI, double alpha, ConventionalDGField[] uI, LevelSetTracker LsTrk, PhysicalParameters physParam, CellQuadratureScheme quadScheme = null) {
int D = LsTrk.GridDat.SpatialDimension;
VectorField<SinglePhaseField> GuIx = new VectorField<SinglePhaseField>(D, uI[0].Basis, SinglePhaseField.Factory);
VectorField<SinglePhaseField> GuIy = new VectorField<SinglePhaseField>(D, uI[1].Basis, SinglePhaseField.Factory);
for (int dd = 0; dd < D; dd++) {
GuIx[dd].DerivativeByFlux(1.0, uI[0], dd, optionalSubGrid: LsTrk.Regions.GetCutCellSubGrid());
GuIy[dd].DerivativeByFlux(1.0, uI[1], dd, optionalSubGrid: LsTrk.Regions.GetCutCellSubGrid());
}
GuIx.ForEach(F => F.CheckForNanOrInf(true, true, true));
GuIy.ForEach(F => F.CheckForNanOrInf(true, true, true));
ScalarFunctionEx ErrFunc = GetFunc_InterfaceDivergence(LsTrk, GuIx, GuIy, physParam);
int order = ((uI[0].Basis.Degree - 1) + divI.Basis.Degree + 2);
if (quadScheme == null)
quadScheme = (new CellQuadratureScheme(false, LsTrk.Regions.GetCutCellMask())).AddFixedOrderRules(LsTrk.GridDat, order);
divI.ProjectField(alpha, ErrFunc,
quadScheme);
}
#endregion
#region
static ScalarFunctionEx GetEnergyBalanceFunc(XDGField P, VectorField<XDGField> U, ConventionalDGField[] Umean, SinglePhaseField C, double muA, double muB, double sigma, bool squared) {
int D = P.Basis.GridDat.SpatialDimension;
ConventionalDGField pA = P.GetSpeciesShadowField("A");
ConventionalDGField pB = P.GetSpeciesShadowField("B");
var UA = U.Select(u => u.GetSpeciesShadowField("A")).ToArray();
var UB = U.Select(u => u.GetSpeciesShadowField("B")).ToArray();
return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray pA_res = MultidimensionalArray.Create(Len, K);
MultidimensionalArray pB_res = MultidimensionalArray.Create(Len, K);
MultidimensionalArray UA_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray UB_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray GradUA_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray GradUB_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray U_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray GradU_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray Curv_res = MultidimensionalArray.Create(Len, K);
pA.Evaluate(i0, Len, nds, pA_res);
pB.Evaluate(i0, Len, nds, pB_res);
for (int i = 0; i < D; i++) {
UA[i].Evaluate(i0, Len, nds, UA_res.ExtractSubArrayShallow(-1, -1, i));
UB[i].Evaluate(i0, Len, nds, UB_res.ExtractSubArrayShallow(-1, -1, i));
Umean[i].Evaluate(i0, Len, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
UA[i].EvaluateGradient(i0, Len, nds, GradUA_res.ExtractSubArrayShallow(-1, -1, i, -1));
UB[i].EvaluateGradient(i0, Len, nds, GradUB_res.ExtractSubArrayShallow(-1, -1, i, -1));
Umean[i].EvaluateGradient(i0, Len, nds, GradU_res.ExtractSubArrayShallow(-1, -1, i, -1));
}
C.Evaluate(i0, Len, nds, Curv_res);
var Normals = P.Basis.Tracker.DataHistories[0].Current.GetLevelSetNormals(nds, i0, Len);
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
double acc = 0.0;
for (int d = 0; d < D; d++) {
// enrgy jump at interface
acc -= (pB_res[j, k] * UB_res[j, k, d] - pA_res[j, k] * UA_res[j, k, d]) * Normals[j, k, d];
for (int dd = 0; dd < D; dd++) {
acc += (muB * GradUB_res[j, k, d, dd] * UB_res[j, k, dd] - muA * GradUA_res[j, k, d, dd] * UA_res[j, k, dd]) * Normals[j, k, d];
acc += (muB * GradUB_res[j, k, dd, d] * UB_res[j, k, dd] - muA * GradUA_res[j, k, dd, d] * UA_res[j, k, dd]) * Normals[j, k, d]; // Transposed Term
}
// surface energy changerate
//for (int dd = 0; dd < D; dd++) {
// if (dd == d) {
// acc += sigma * (1 - Normals[j, k, d] * Normals[j, k, dd]) * GradU_res[j, k, dd, d];
// } else {
// acc += sigma * (-Normals[j, k, d] * Normals[j, k, dd]) * GradU_res[j, k, dd, d];
// }
//}
// curvature energy
acc -= sigma * Curv_res[j, k] * U_res[j, k, d] * Normals[j, k, d];
}
if (squared) {
result[j, k] = acc.Pow2();
} else {
result[j, k] = acc;
}
}
}
};
}
public static double EnergyBalanceNormAtInterface(XDGField P, VectorField<XDGField> U, ConventionalDGField[] Umean, SinglePhaseField C, double muA, double muB, double sigma, int momentFittingOrder) {
LevelSetTracker LsTrk = P.Basis.Tracker;
double energyBal_Norm = 0.0;
ScalarFunctionEx energyBalFunc = GetEnergyBalanceFunc(P, U, Umean, C, muA, muB, sigma, true);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingOrder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
energyBalFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++)
energyBal_Norm += ResultsOfIntegration[i, 0];
}
).Execute();
return energyBal_Norm.Sqrt();
}
public static void ProjectEnergyBalanceNorm(this SinglePhaseField err, double alpha, XDGField P, VectorField<XDGField> U, ConventionalDGField[] Umean, SinglePhaseField C,
double muA, double muB, double sigma, int momentFittingOrder) {
var LsTrk = U[0].Basis.Tracker;
int D = LsTrk.GridDat.SpatialDimension;
ScalarFunctionEx ErrFunc = GetEnergyBalanceFunc(P, U, Umean, C, muA, muB, sigma, true);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingOrder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
ErrFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++) {
err.SetMeanValue(i0 + i, ResultsOfIntegration[i, 0].Sqrt());
}
}
).Execute();
}
static ScalarFunctionEx GetInterfaceDivergenceFunc(LevelSetTracker LsTrk, ConventionalDGField[] uI, bool squared) {
int D = LsTrk.GridDat.SpatialDimension;
return delegate (int i0, int Len, NodeSet nds, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray GradU_Res = MultidimensionalArray.Create(Len, K, D, D);
for (int i = 0; i < D; i++) {
uI.ElementAt(i).EvaluateGradient(i0, Len, nds, GradU_Res.ExtractSubArrayShallow(-1, -1, i, -1));
}
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(nds, i0, Len);
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
MultidimensionalArray Nsurf = Normals.ExtractSubArrayShallow(j, k, -1);
double[,] Psurf = new double[D, D];
for (int d1 = 0; d1 < D; d1++) {
for (int d2 = 0; d2 < D; d2++) {
if (d2 == d1)
Psurf[d1, d2] = (1 - Nsurf[d1] * Nsurf[d2]);
else
Psurf[d1, d2] = (0 - Nsurf[d1] * Nsurf[d2]);
}
}
double acc = 0.0;
for (int d1 = 0; d1 < D; d1++) {
for (int dd = 0; dd < D; dd++) {
acc += Psurf[d1, dd] * GradU_Res[j, k, dd, d1];
}
}
if (squared) {
result[j, k] = acc.Pow2();
} else {
result[j, k] = acc;
}
}
}
};
}
public static double GetSurfaceChangerate(LevelSetTracker LsTrk, ConventionalDGField[] uI, int momentFittingOrder) {
double SurfChangerate = 0.0;
ScalarFunctionEx surfChangerateFunc = GetInterfaceDivergenceFunc(LsTrk, uI, false);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingOrder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingOrder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
surfChangerateFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++)
SurfChangerate += ResultsOfIntegration[i, 0];
}
).Execute();
return SurfChangerate;
}
public static ScalarFunctionEx GetEnergyJumpFunc(LevelSetTracker LsTrk, VectorField<XDGField> Velocity, XDGField Pressure, double muA, double muB, bool squared) {
var UA = Velocity.Select(u => u.GetSpeciesShadowField("A")).ToArray();
var UB = Velocity.Select(u => u.GetSpeciesShadowField("B")).ToArray();
ConventionalDGField pA = null, pB = null;
bool UsePressure = Pressure != null;
if (UsePressure) {
pA = Pressure.GetSpeciesShadowField("A");
pB = Pressure.GetSpeciesShadowField("B");
}
int D = LsTrk.GridDat.SpatialDimension;
ScalarFunctionEx EnergyJumpFunc = delegate (int j0, int Len, NodeSet Ns, MultidimensionalArray result) {
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray UA_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray UB_res = MultidimensionalArray.Create(Len, K, D);
MultidimensionalArray GradUA_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray GradUB_res = MultidimensionalArray.Create(Len, K, D, D);
MultidimensionalArray pA_res = MultidimensionalArray.Create(Len, K);
MultidimensionalArray pB_res = MultidimensionalArray.Create(Len, K);
for (int i = 0; i < D; i++) {
UA[i].Evaluate(j0, Len, Ns, UA_res.ExtractSubArrayShallow(-1, -1, i));
UB[i].Evaluate(j0, Len, Ns, UB_res.ExtractSubArrayShallow(-1, -1, i));
UA[i].EvaluateGradient(j0, Len, Ns, GradUA_res.ExtractSubArrayShallow(-1, -1, i, -1));
UB[i].EvaluateGradient(j0, Len, Ns, GradUB_res.ExtractSubArrayShallow(-1, -1, i, -1));
}
if (UsePressure) {
pA.Evaluate(j0, Len, Ns, pA_res);
pB.Evaluate(j0, Len, Ns, pB_res);
} else {
pA_res.Clear();
pB_res.Clear();
}
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(Ns, j0, Len);
for (int j = 0; j < Len; j++) {
for (int k = 0; k < K; k++) {
double acc = 0.0;
for (int d = 0; d < D; d++) {
// pressure
if (UsePressure) {
acc += (pB_res[j, k] * UB_res[j, k, d] - pA_res[j, k] * UA_res[j, k, d]) * Normals[j, k, d];
}
// Nabla U + (Nabla U) ^T
for (int dd = 0; dd < D; dd++) {
acc -= (muB * GradUB_res[j, k, d, dd] * UB_res[j, k, dd] - muA * GradUA_res[j, k, d, dd] * UA_res[j, k, dd]) * Normals[j, k, d];
acc -= (muB * GradUB_res[j, k, dd, d] * UB_res[j, k, dd] - muA * GradUA_res[j, k, dd, d] * UA_res[j, k, dd]) * Normals[j, k, d]; // Transposed Term
}
}
if (squared) {
result[j, k] = acc.Pow2();
} else {
result[j, k] = acc;
}
}
}
};
return EnergyJumpFunc;
}
public static double EnergyJumpAtInterface(LevelSetTracker LsTrk, VectorField<XDGField> Velocity, XDGField Pressure, double muA, double muB, bool Norm, int momentFittingorder) {
double EnergyJump = 0.0;
ScalarFunctionEx EnergyJumpFunc = GetEnergyJumpFunc(LsTrk, Velocity, Pressure, muA, muB, Norm);
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingorder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingorder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
EnergyJumpFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++)
EnergyJump += ResultsOfIntegration[i, 0];
}
).Execute();
if (Norm) {
EnergyJump.Sqrt();
}
return EnergyJump;
}
public static double SurfaceEnergyChangerate(LevelSetTracker LsTrk, ConventionalDGField[] uI, double sigma, bool Norm, int momentFittingorder) {
double Changerate_Surface = 0.0;
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingorder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
ScalarFunctionEx SurfaceChangerate = GetInterfaceDivergenceFunc(LsTrk, uI, Norm);
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingorder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
SurfaceChangerate(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++)
Changerate_Surface += ResultsOfIntegration[i, 0];
}
).Execute();
double Changerate_Esurf;
if (Norm) {
Changerate_Esurf = sigma * Changerate_Surface.Sqrt();
} else {
Changerate_Esurf = sigma * Changerate_Surface;
}
return Changerate_Esurf;
}
public static ScalarFunctionEx GetCurvatureEnergyFunc(LevelSetTracker LsTrk, DGField Curvature, double sigma, ConventionalDGField[] uI, bool ExtVel, bool squared) {
int D = LsTrk.GridDat.SpatialDimension;
ScalarFunctionEx CurvatureEnergyFunc = delegate (int i0, int Length, NodeSet nds, MultidimensionalArray result) {
Curvature.Evaluate(i0, Length, nds, result);
int K = result.GetLength(1); // No nof Nodes
MultidimensionalArray U_res = MultidimensionalArray.Create(Length, K, D);
for (int i = 0; i < D; i++) {
uI.ElementAt(i).Evaluate(i0, Length, nds, U_res.ExtractSubArrayShallow(-1, -1, i));
}
var Normals = LsTrk.DataHistories[0].Current.GetLevelSetNormals(nds, i0, Length);
for (int j = 0; j < Length; j++) {
for (int k = 0; k < K; k++) {
double acc = result[j, k];
for (int d = 0; d < D; d++) {
// U * N
if (!ExtVel) {
acc *= U_res[j, k, d] * Normals[j, k, d];
} else {
acc *= U_res[j, k, d];
}
}
if (squared) {
result[j, k] = (sigma * acc).Pow2();
} else {
result[j, k] = sigma * acc;
}
}
}
};
return CurvatureEnergyFunc;
}
public static double CurvatureEnergy(LevelSetTracker LsTrk, SinglePhaseField Curvature, double sigma, ConventionalDGField[] uI, bool ExtVel, bool Norm, int momentFittingorder) {
double EnergyCurv = 0.0;
var SchemeHelper = LsTrk.GetXDGSpaceMetrics(new[] { LsTrk.GetSpeciesId("A") }, momentFittingorder, 1).XQuadSchemeHelper;
CellQuadratureScheme cqs = SchemeHelper.GetLevelSetquadScheme(0, LsTrk.Regions.GetCutCellMask());
ScalarFunctionEx CurvEnergyFunc = GetCurvatureEnergyFunc(LsTrk, Curvature, sigma, uI, ExtVel, Norm);
CellQuadrature.GetQuadrature(new int[] { 1 }, LsTrk.GridDat,
cqs.Compile(LsTrk.GridDat, momentFittingorder),
delegate (int i0, int Length, QuadRule QR, MultidimensionalArray EvalResult) {
CurvEnergyFunc(i0, Length, QR.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0));
},
delegate (int i0, int Length, MultidimensionalArray ResultsOfIntegration) {
for (int i = 0; i < Length; i++)
EnergyCurv += ResultsOfIntegration[i, 0];
}
).Execute();
if (Norm) {
EnergyCurv.Sqrt();
}
return EnergyCurv;
}
#endregion
}
}
| 47.696116 | 258 | 0.504862 |
b42385786e322edf995cf5f9b3470ffbece5a2af | 2,780 | cs | C# | src/Msr.Odr.Admin/Commands/Data/DataInitCommand.cs | Sahaj26/opendatacloud | 6ad959db61b82849391575ae1678c1dcb1fc25c1 | [
"MIT"
] | 6 | 2020-07-21T16:01:03.000Z | 2021-09-20T17:12:32.000Z | src/Msr.Odr.Admin/Commands/Data/DataInitCommand.cs | microsoft/opendatacloud | 6ad959db61b82849391575ae1678c1dcb1fc25c1 | [
"MIT"
] | 2 | 2020-11-12T16:54:32.000Z | 2020-11-12T17:23:48.000Z | src/Msr.Odr.Admin/Commands/Data/DataInitCommand.cs | microsoft/opendatacloud | 6ad959db61b82849391575ae1678c1dcb1fc25c1 | [
"MIT"
] | 4 | 2021-11-10T08:36:05.000Z | 2022-03-24T13:57:03.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading.Tasks;
using McMaster.Extensions.CommandLineUtils;
using Msr.Odr.Admin.Commands.Options;
using Msr.Odr.Admin.Data;
namespace Msr.Odr.Admin.Commands.Dataset
{
public class DataInitCommand
{
public static string AllDataTypes => string.Join(",", new[]
{
DataInitTypes.Domains.ToString(),
DataInitTypes.Licenses.ToString(),
DataInitTypes.FAQs.ToString(),
DataInitTypes.Email.ToString(),
DataInitTypes.ARM.ToString(),
DataInitTypes.DatasetOwners.ToString(),
});
public static void Configure(CommandLineApplication command)
{
command.Description = "Creates initial data for application.";
command.SetDefaultHelp();
var typesOption = command.Option(
"--types | -t <types>", $"The comma-separated list of types to initialize ({AllDataTypes}) or '*' for all.",
CommandOptionType.SingleValue);
command.OnExecute(async () =>
{
var cosmos = new CosmosOptions();
var storage = new StorageOptions();
DataInitTypes selectedTypes = DataInitTypes.None;
string typesText = typesOption.Value();
if(typesText == "*")
{
selectedTypes =
DataInitTypes.Domains |
DataInitTypes.Licenses |
DataInitTypes.FAQs |
DataInitTypes.Email |
DataInitTypes.ARM |
DataInitTypes.DatasetOwners;
}
else if(!string.IsNullOrWhiteSpace(typesText))
{
selectedTypes = typesText
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => Enum.Parse(typeof(DataInitTypes), s.Trim(), true))
.Aggregate(DataInitTypes.None, (selected, v) => selected | (DataInitTypes)v);
}
if (selectedTypes == DataInitTypes.None)
{
throw new ArgumentException("No data types specified.");
}
if (command.HasAllRequiredParameters(new[]
{
cosmos.Endpoint,
cosmos.Database,
storage.Account
}))
{
await new Admin.Data.DataInitTask(cosmos, storage, selectedTypes).ExecuteAsync();
}
return 0;
});
}
}
}
| 35.641026 | 124 | 0.518705 |
e8bd3cfd2af4bde883ad8d30f6c39c2b7345b946 | 134 | cs | C# | templates/alteration/spark/HomeEndpoint.cs | RyanHauert/fubumvc | b59c29dbae9d18fdb74ff3a8f968c052465208d0 | [
"Apache-2.0"
] | 100 | 2015-01-02T19:36:00.000Z | 2021-11-14T12:25:24.000Z | templates/alteration/spark/HomeEndpoint.cs | JohnnyKapps/fubumvc | c803b9398e34c7da4fb2d20963ae571bf15a5ae0 | [
"Apache-2.0"
] | 192 | 2015-01-07T18:10:06.000Z | 2018-06-20T21:58:05.000Z | templates/alteration/spark/HomeEndpoint.cs | JohnnyKapps/fubumvc | c803b9398e34c7da4fb2d20963ae571bf15a5ae0 | [
"Apache-2.0"
] | 43 | 2015-01-05T10:18:47.000Z | 2021-06-10T07:19:32.000Z | namespace %NAMESPACE%
{
public class HomeEndpoint
{
public HomeModel Index(HomeModel model)
{
return model;
}
}
} | 13.4 | 42 | 0.641791 |
b5f384d6605f538c5b834ca3d9a64adb444fc813 | 855 | cs | C# | Semester_Project/MDV/Domain/Trips/TripDto.cs | TRibeiro94/ISEP-ARQSI-2020 | f683e8647a7847c3b6f7c2fac1c573b063e3af2a | [
"MIT"
] | 1 | 2021-11-07T11:10:15.000Z | 2021-11-07T11:10:15.000Z | Semester_Project/MDV/Domain/Trips/TripDto.cs | TRibeiro94/ISEP-ARQSI-2020 | f683e8647a7847c3b6f7c2fac1c573b063e3af2a | [
"MIT"
] | null | null | null | Semester_Project/MDV/Domain/Trips/TripDto.cs | TRibeiro94/ISEP-ARQSI-2020 | f683e8647a7847c3b6f7c2fac1c573b063e3af2a | [
"MIT"
] | 3 | 2021-10-30T11:40:06.000Z | 2021-11-19T20:35:37.000Z | using System.Collections.Generic;
namespace DDDSample1.Domain.Trips{
public class TripDto{
public string Id { get; set; }
public string Key { get; set; }
public string Line { get; set; }
public string Path { get; set; }
public List<int> PassingTimes { get; set; }
public TripDto(string key, string line, string path, List<int> passingTimes){
this.Key = key;
this.Line = line;
this.Path = path;
this.PassingTimes = passingTimes;
}
public TripDto(string id, string key, string line, string path, List<int> passingTimes){
this.Id = id;
this.Key = key;
this.Line = line;
this.Path = path;
this.PassingTimes = passingTimes;
}
}
} | 28.5 | 96 | 0.532164 |
e03b9966f2f145bc4857c8548746dc25e8ddb472 | 3,526 | cs | C# | Blish HUD/GameServices/Input/MouseHook.cs | GregoryComer/Blish-HUD | 255d623c02a76d94246c6d7e1b7671d441550e43 | [
"MIT"
] | null | null | null | Blish HUD/GameServices/Input/MouseHook.cs | GregoryComer/Blish-HUD | 255d623c02a76d94246c6d7e1b7671d441550e43 | [
"MIT"
] | null | null | null | Blish HUD/GameServices/Input/MouseHook.cs | GregoryComer/Blish-HUD | 255d623c02a76d94246c6d7e1b7671d441550e43 | [
"MIT"
] | null | null | null | using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
// ReSharper disable InconsistentNaming
namespace Blish_HUD.Input {
public class MouseHook {
private static readonly Logger Logger = Logger.GetLogger<MouseHook>();
internal struct MSLLHOOKSTRUCT {
public Point pt;
public Int32 mouseData;
public Int32 flags;
public Int32 time;
public IntPtr extra;
public Int32 wheelDelta {
get {
int v = Convert.ToInt32((mouseData & 0xFFFF0000) >> 16);
if (v > SystemInformation.MouseWheelScrollDelta) v -= (ushort.MaxValue + 1);
return v;
}
}
}
private const Int32 WH_MOUSE_LL = 14;
private IntPtr _mouseHook;
private delegate Int32 MouseHookDelegate(Int32 nCode, IntPtr wParam, ref MSLLHOOKSTRUCT lParam);
[MarshalAs(UnmanagedType.FunctionPtr)]
private MouseHookDelegate _mouseProc;
public enum MouseMessages {
WM_MouseMove = 512,
WM_LeftButtonDown = 513,
WM_LeftButtonUp = 514,
WM_LeftDblClick = 515,
WM_RightButtonDown = 516,
WM_RightButtonUp = 517,
WM_RightDblClick = 518,
WM_MiddleButtonDown = 519,
WM_MiddleButtonUp = 520,
WM_MiddleButtonDblClick = 521,
WM_MouseWheel = 522,
}
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookExW(Int32 idHook, MouseHookDelegate HookProc, IntPtr hInstance, Int32 wParam);
[DllImport("user32.dll")]
private static extern Int32 CallNextHookEx(Int32 idHook, Int32 nCode, IntPtr wParam, ref MSLLHOOKSTRUCT lParam);
public MouseHook() => _mouseProc = MouseHookProc;
public bool HookMouse() {
Logger.Debug("Enabling mouse hook.");
if (_mouseHook == IntPtr.Zero) {
_mouseHook = SetWindowsHookExW(WH_MOUSE_LL, _mouseProc, HookExtern.GetModuleHandleW(IntPtr.Zero), 0);
}
return _mouseHook != IntPtr.Zero;
}
public void UnhookMouse() {
Logger.Debug("Disabling the mouse hook.");
if (_mouseHook == IntPtr.Zero) return;
HookExtern.UnhookWindowsHookEx(_mouseHook);
_mouseHook = IntPtr.Zero;
}
private bool _cameraDragging;
private Int32 MouseHookProc(Int32 nCode, IntPtr wParam, ref MSLLHOOKSTRUCT lParam) {
int action = wParam.ToInt32();
if (_cameraDragging && action == 517) { // If the player has been holding WM_RightButtonDown, then we ignore WM_RightButtonUp (they are just releasing the camera)
_cameraDragging = false;
} else if (action > 512 && GameService.Input.HudFocused && action < 523 && !GameService.Input.HookOverride) {
GameService.Input.ClickState = new MouseEvent((MouseMessages)action, lParam);
if (action != 514)
return 1;
} else if (action == 516) { // If WM_RightButtonDown, we ignore it so that we don't accidentally intercept the player moving the camera
_cameraDragging = true;
}
return CallNextHookEx(WH_MOUSE_LL, nCode, wParam, ref lParam);
}
}
}
| 35.616162 | 174 | 0.590471 |
e047803ee3d1e75d97ffde5f06d9c3e2d5059232 | 376 | cs | C# | src/ESFA.DC.ILR.ValidationService.ValidationActor.Interfaces/Models/ValidationActorModel.cs | sampanu/DC-ILR-1819-ValidationService | 0a1ee914911ec30cd524419fa609cc637543be13 | [
"MIT"
] | null | null | null | src/ESFA.DC.ILR.ValidationService.ValidationActor.Interfaces/Models/ValidationActorModel.cs | sampanu/DC-ILR-1819-ValidationService | 0a1ee914911ec30cd524419fa609cc637543be13 | [
"MIT"
] | null | null | null | src/ESFA.DC.ILR.ValidationService.ValidationActor.Interfaces/Models/ValidationActorModel.cs | sampanu/DC-ILR-1819-ValidationService | 0a1ee914911ec30cd524419fa609cc637543be13 | [
"MIT"
] | null | null | null | namespace ESFA.DC.ILR.ValidationService.ValidationActor.Interfaces.Models
{
public class ValidationActorModel
{
public string JobId { get; set; }
public byte[] Message { get; set; }
public byte[] InternalDataCache { get; set; }
public byte[] ExternalDataCache { get; set; }
public byte[] FileDataCache { get; set; }
}
} | 25.066667 | 74 | 0.632979 |
c53948c1645171cba9a5f6de3e4e051ec8f225a4 | 883 | cs | C# | StarwebSharp/Entities/OrderStatusModel.cs | PrimePenguin/PrimePenguin.StarwebSharp | 35cb8c13493ae24052a1c051b70f32acedaebe82 | [
"MIT"
] | 1 | 2019-09-11T12:10:44.000Z | 2019-09-11T12:10:44.000Z | StarwebSharp/Entities/OrderStatusModel.cs | PrimePenguin/PrimePenguin.StarwebSharp | 35cb8c13493ae24052a1c051b70f32acedaebe82 | [
"MIT"
] | 1 | 2019-11-15T15:24:25.000Z | 2019-11-15T20:45:44.000Z | StarwebSharp/Entities/OrderStatusModel.cs | PrimePenguin/PrimePenguin.StarwebSharp | 35cb8c13493ae24052a1c051b70f32acedaebe82 | [
"MIT"
] | 2 | 2019-04-18T21:09:29.000Z | 2019-11-15T20:02:11.000Z | using Newtonsoft.Json;
namespace StarwebSharp.Entities
{
public class OrderStatusModel
{
/// <summary>The id of the order status</summary>
[JsonProperty("statusId")]
public int StatusId { get; set; }
/// <summary>Should an order status update email be sent out when an order gets this status</summary>
[JsonProperty("shouldSendEmail")]
public bool ShouldSendEmail { get; set; }
/// <summary>Standard order statuses has an idCode as well. These are: created, picking, completed, canceled</summary>
[JsonProperty("idCode")]
public string IdCode { get; set; }
[JsonProperty("languages")]
public OrderStatusLanguageModelCollection Languages { get; set; } = new OrderStatusLanguageModelCollection();
[JsonProperty("links")]
public EntityLink[] Links { get; set; }
}
} | 35.32 | 126 | 0.655719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.