content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
/**
* @file ShaderReferenceRenderState.cs
* @author Hongwei Li(taecg@qq.com)
* @created 2018-12-29
* @updated 2021-02-05
*
* @brief SubShader中渲染设置
*/
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace taecg.tools.shaderReference
{
public class ShaderReferenceRenderState : EditorWindow
{
#region 数据成员
private Vector2 scrollPos;
#endregion
public void DrawMainGUI()
{
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
ShaderReferenceUtil.DrawTitle("Cull");
ShaderReferenceUtil.DrawOneContent("Cull Back | Front | Off", "[Enum(UnityEngine.Rendering.CullMode)]\n" +
"背面剔除,默认值为Back。\nBack:表示剔除背面,也就是显示正面,这也是最常用的设置。\nFront:表示剔除前面,只显示背面。\nOff:表示关闭剔除,也就是正反面都渲染。");
ShaderReferenceUtil.DrawTitle("模版测试");
ShaderReferenceUtil.DrawOneContent("Stencil", "模板缓冲区(StencilBuffer)可以为屏幕上的每个像素点保存一个无符号整数值,这个值的具体意义视程序的具体应用而定.在渲染的过程中,可以用这个值与一个预先设定的参考值相比较,根据比较的结果来决定是否更新相应的像素点的颜色值.这个比较的过程被称为模板测试." +
"\n将StencilBuffer的值与ReadMask与运算,然后与Ref值进行Comp比较,结果为true时进行Pass操作,否则进行Fail操作,操作值写入StencilBuffer前先与WriteMask与运算." +
"\n模版缓冲中的默认值为:0" +
"\n公式:(Ref & ReadMask) Comp (StencilBufferValue & ReadMask)\n\n" +
"Stencil\n" +
"{\n" +
"\n Ref [_Stencil]" +
"\n ReadMask [_StencilReadMask]" +
"\n WriteMask [_StencilWriteMask]" +
"\n Comp [_StencilComp] ((UnityEngine.Rendering.CompareFunction))" +
"\n Pass [_StencilOp] (UnityEngine.Rendering.StencilOp)" +
"\n Fail [_Fail]" +
"\n ZFail [_ZFail]" +
"\n}" +
"\nRef:\t设定的参考值,这个值将用来与模板缓冲中的值进行比较.取值范围位为0-255的整数." +
"\nReadMask:\tReadMask的值将和Ref的值以及模板缓冲中的值进行按位与(&)操作,取值范围也是0-255的整数,默认值为255(二进制位11111111),即读取的时候不对Ref的值和模板缓冲中的值产生修改,读取的还是原始值." +
"\nWriteMask:\tWriteMask的值是当写入模板缓冲时进行的按位与操作,取值范围是0-255的整数,默认值也是255,即不做任何修改." +
"\nComp:\t定义Ref与模板缓冲中的值比较的操作函数,默认值为always." +
"\nPass:\t当模板测试(和深度测试)通过时,则根据(stencilOperation值)对模板缓冲值进行处理,默认值为keep." +
"\nFail:\t当模板测试(和深度测试)失败时,则根据(stencilOperation值)对模板缓冲值进行处理,默认值为keep." +
"\nZFail:\t当模板测试通过而深度测试失败时,则根据(stencilOperation值)对模板缓冲值进行处理,默认值为keep.");
ShaderReferenceUtil.DrawOneContent("Comp(比较操作)",
"\nLess:\t相当于“<”操作,即仅当左边<右边,模板测试通过,渲染像素." +
"\nGreater:\t相当于“>”操作,即仅当左边>右边,模板测试通过,渲染像素." +
"\nLequal:\t相当于“<=”操作,即仅当左边<=右边,模板测试通过,渲染像素." +
"\nGequal:\t相当于“>=”操作,即仅当左边>=右边,模板测试通过,渲染像素." +
"\nEqual:\t相当于“=”操作,即仅当左边=右边,模板测试通过,渲染像素." +
"\nNotEqual:\t相当于“!=”操作,即仅当左边!=右边,模板测试通过,渲染像素." +
"\nAlways:\t不管公式两边为何值,模板测试总是通过,渲染像素." +
"\nNever:\t不管公式两边为何值,模板测试总是失败 ,像素被抛弃.");
ShaderReferenceUtil.DrawOneContent("模版缓冲区的更新",
"\nKeep:\t保留当前缓冲中的内容,即stencilBufferValue不变." +
"\nZero:\t将0写入缓冲,即stencilBufferValue值变为0." +
"\nReplace:\t将参考值写入缓冲,即将referenceValue赋值给stencilBufferValue." +
"\nIncrSat:\t将当前模板缓冲值加1,如果stencilBufferValue超过255了,那么保留为255,即不大于255." +
"\nDecrSat:\t将当前模板缓冲值减1,如果stencilBufferValue超过为0,那么保留为0,即不小于0." +
"\nNotEqual:\t相当于“!=”操作,即仅当左边!=右边,模板测试通过,渲染像素." +
"\nInvert:\t将当前模板缓冲值(stencilBufferValue)按位取反." +
"\nIncrWrap:\t当前缓冲的值加1,如果缓冲值超过255了,那么变成0,(然后继续自增)." +
"\nDecrWrap:\t当前缓冲的值减1,如果缓冲值已经为0,那么变成255,(然后继续自减).");
ShaderReferenceUtil.DrawTitle("深度缓冲");
ShaderReferenceUtil.DrawOneContent("ZTest (Less | Greater | LEqual | GEqual | Equal | NotEqual | Never | Always)", "深度测试,拿当前像素的深度值与深度缓冲中的深度值进行比较,默认值为LEqual。" +
"可通过在属性中添加枚举UnityEngine.Rendering.CompareFunction\n" +
"\nDisabled: 禁用,相当于永远通过。" +
"\nNever: 于永远不通过。" +
"\nLess:小于,表示如果当前像素的深度值小于深度缓冲中的深度值,则通过,以下类同。" +
"\nEqual:等于。" +
"\nLEqual:小于等于。" +
"\nGreater:大于。" +
"\nNotEqual:不等于。" +
"\nGequal:大于等于。" +
"\nAlways:永远通过。");
ShaderReferenceUtil.DrawOneContent("ZTest[unity_GUIZTestMode]", "unity_GUIZTestMode用于UI材质中,此值默认为LEqual,仅当UI中Canvas模式为Overlay时,值为Always.");
ShaderReferenceUtil.DrawOneContent("ZWrite On | Off", "深度写入,默认值为On。\nOn:向深度缓冲中写入深度值。\nOff:关闭深度写入。");
ShaderReferenceUtil.DrawOneContent("Offset Factor, Units", "深度偏移,offset = (m * factor) + (r * units),默认值为0,0" +
"\nm:指多边形的深度斜率(在光栅化阶段计算得出)中的最大值,多边形越是与近裁剪面平行,m值就越接近0。" +
"\nr:表示能产生在窗口坐标系的深度值中可分辨的差异的最小值,r是由具体实现OpenGL的平台指定的一个常量。" +
"\n结论:一个大于0的offset会把模型推远,一个小于0的offset会把模型拉近。");
ShaderReferenceUtil.DrawTitle("颜色遮罩");
ShaderReferenceUtil.DrawOneContent("ColorMask RGB | A | 0 | R、G、B、A的任意组合", "颜色遮罩,默认值为:RGBA,表示写入RGBA四个通道。");
ShaderReferenceUtil.DrawTitle("混合");
ShaderReferenceUtil.DrawOneContent("说明", "源颜色*SrcFactor + 目标颜色*DstFactor" +
"\n颜色混合,源颜色与目标颜色以给定的公式进行混合出最终的新颜色。" +
"\n源颜色:当前Shader计算出的颜色。" +
"\n目标颜色:已经存在颜色缓存中的颜色。默认值为Blend Off,即表示关闭混合。" +
"\n在混合时可以针对某个RT做混合,比如Blend 3 One One,就是对RenderTarget3做混合。" +
"\n可在Properties中添加这个实现下拉列表选择:[Enum(UnityEngine.Rendering.BlendMode)]");
ShaderReferenceUtil.DrawOneContent("Blend SrcFactor DstFactor", "SrcFactor为源颜色因子,DstFactor为目标颜色因子,将两者按Op中指定的操作进行混合。");
ShaderReferenceUtil.DrawOneContent("Blend SrcFactor DstFactor, SrcFactorA DstFactorA", "对RGB和A通道分别做混合操作。");
ShaderReferenceUtil.DrawOneContent("BlendOp Op", "混合时的操作运算符,默认值为Add(加法操作)。");
ShaderReferenceUtil.DrawOneContent("BlendOp OpColor, OpAlpha", "对RGB和A通道分别指定混合运算符。");
ShaderReferenceUtil.DrawOneContent("AlphaToMask On | Off", "当值为On时,在使用MSAA时,会根据像素结果将alpha值进行修改多重采样覆盖率,对植被和其他经过alpha测试的着色器非常有用。");
ShaderReferenceUtil.DrawOneContent("Blend factors", "混合因子" +
"\nOne:源或目标的完整值" +
"\nZero:0" +
"\nSrcColor:源的颜色值" +
"\nSrcAlpha:源的Alpha值" +
"\nDstColor:目标的颜色值" +
"\nDstAlpha:目标的Alpha值" +
"\nOneMinusSrcColor:1-源颜色得到的值" +
"\nOneMinusSrcAlpha:1-源Alpha得到的值" +
"\nOneMinusDstColor:1-目标颜色得到的值" +
"\nOneMinusDstAlpha:1-目标Alpha得到的值");
ShaderReferenceUtil.DrawOneContent("Blend Types", "常用的几种混合类型" +
"\nBlend SrcAlpha OneMinusSrcAlpha// Traditional transparency" +
"\nBlend One OneMinusSrcAlpha// Premultiplied transparency" +
"\nBlend One One" +
"\nBlend OneMinusDstColor One // Soft Additive" +
"\nBlend DstColor Zero // Multiplicative" +
"\nBlend DstColor SrcColor // 2x Multiplicative");
ShaderReferenceUtil.DrawOneContent("Blend operations", "混合操作的具体运算符" +
"\nAdd:源+目标" +
"\nSub:源-目标" +
"\nRevSub:目标-源" +
"\nMin:源与目标中最小值" +
"\nMax:源与目标中最大值" +
"\n以下仅用于DX11.1中" +
"\nLogicalClear" +
"\nLogicalSet" +
"\nLogicalCopy" +
"\nLogicalCopyInverted" +
"\nLogicalNoop" +
"\nLogicalInvert" +
"\nLogicalAnd" +
"\nLogicalNand" +
"\nLogicalOr" +
"\nLogicalNor" +
"\nLogicalXor" +
"\nLogicalEquiv" +
"\nLogicalAndReverse" +
"\nLogicalAndInverted" +
"\nLogicalOrReverse" +
"\nLogicalOrInverted");
EditorGUILayout.EndScrollView();
}
}
}
#endif | 54.080537 | 193 | 0.584636 | [
"MIT"
] | KealG/UnityCatLike | Assets/ShaderRefrence/Editor/ShaderReferenceRenderState.cs | 11,390 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
namespace COMTRADEConverter
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Members
private COMTRADEConverterViewModel m_viewModel;
private readonly BackgroundWorker m_worker;
#endregion
#region Constructors
public MainWindow()
{
InitializeComponent();
m_viewModel = new COMTRADEConverterViewModel();
m_viewModel.AddFiles(new string[] { "Drag and drop files here or use the add files button", "Double click on a file to remove it." });
DataContext = m_viewModel;
m_worker = new BackgroundWorker();
m_worker.DoWork += m_workerDoWork;
m_worker.RunWorkerCompleted += m_workerWorkDone;
}
#endregion
#region Methods
private void m_workerDoWork(object sender, DoWorkEventArgs e)
{
m_viewModel.ProcessFiles();
}
private void m_workerWorkDone(object sender, RunWorkerCompletedEventArgs e)
{
//m_viewModel.ProcessFiles();
m_viewModel.Files.Clear();
AddFilesButton.IsEnabled = true;
ClearFileListButton.IsEnabled = true;
ConvertFilesButton.IsEnabled = true;
BrowseButton.IsEnabled = true;
AddFilesMenu.IsEnabled = true;
ClearFilesMenu.IsEnabled = true;
ChangeDestinationMenu.IsEnabled = true;
ConvertFilesMenu.IsEnabled = true;
}
#endregion
#region EventHandlers
private void AddFilesButtonClicked(object sender, RoutedEventArgs e)
{
string filter = "Disturbance Files|*.dat;*.d00;*.rcd;*.rcl;*.pqd;*.eve;*.sel|"
+ "COMTRADE Files|*.dat;*.d00|EMAX Files|*.rcd;*.rcl|PQDIF Files|*.pqd|SEL Files|*.eve;*.sel|All Files|*.*";
OpenFileDialog dialog = new OpenFileDialog() { Multiselect = true, Filter = filter };
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
return;
m_viewModel.AddFiles(dialog.FileNames);
}
private void FileListItemsDropped(object sender, System.Windows.DragEventArgs e)
{
string[] newFiles = (string[])e.Data.GetData(System.Windows.Forms.DataFormats.FileDrop);
m_viewModel.AddFiles(newFiles);
}
private void GoButtonClicked(object sender, RoutedEventArgs e)
{
// Check if export path is legal
if (!Directory.Exists(m_viewModel.ExportPath))
BrowseButtonClicked(sender, e);
//m_viewModel.ProcessFiles();
AddFilesButton.IsEnabled = false;
ClearFileListButton.IsEnabled = false;
ConvertFilesButton.IsEnabled = false;
BrowseButton.IsEnabled = false;
AddFilesMenu.IsEnabled = false;
ClearFilesMenu.IsEnabled = false;
ChangeDestinationMenu.IsEnabled = false;
ConvertFilesMenu.IsEnabled = false;
m_worker.RunWorkerAsync();
}
private void BrowseButtonClicked(object sender, RoutedEventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog() { ShowNewFolderButton = true, Description = "Choose a folder to export files to." };
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
m_viewModel.ExportPath = dialog.SelectedPath;
}
private void ClearFilesButtonClicked(object sender, RoutedEventArgs e)
{
m_viewModel.ClearFileList();
}
private void FileListDoubleClicked(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ListBox fileList = (System.Windows.Controls.ListBox)sender;
if (fileList.SelectedItem != null)
m_viewModel.Files.Remove(fileList.SelectedItem.ToString());
}
private void ErrorsButtonCLicked(object sender, RoutedEventArgs e)
{
ErrorMessagesWindow errorWindow = new ErrorMessagesWindow {DataContext = m_viewModel};
errorWindow.Show();
}
#endregion
}
}
| 34.711111 | 151 | 0.63551 | [
"MIT"
] | GridProtectionAlliance/gsf | Source/Tools/COMTRADEConverter/MainWindow.xaml.cs | 4,688 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace YayoiSDK.APIs.Entities
{
public class Application
{
public Application() { }
}
}
| 13.75 | 33 | 0.745455 | [
"MIT"
] | Asteriskx/Yayoi | YayoiSDK/YayoiSDK/APIs/Entities/Application.cs | 167 | C# |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Changes from the Java version
// Replaced getPolygons with attribute
// Future possibilities
// Replace Add(Polygon) with exposed container?
// Replace entire class with HashSet<Polygon> ?
using System.Collections.Generic;
namespace VelcroPhysics.Tools.Triangulation.Delaunay.Polygon
{
internal class PolygonSet
{
protected List<Polygon> _polygons = new List<Polygon>();
public PolygonSet() { }
public PolygonSet(Polygon poly)
{
_polygons.Add(poly);
}
public IEnumerable<Polygon> Polygons
{
get { return _polygons; }
}
public void Add(Polygon p)
{
_polygons.Add(p);
}
}
} | 37.222222 | 84 | 0.719403 | [
"MIT"
] | Blucky87/VelcroPhysics | VelcroPhysics/Tools/Triangulation/Delaunay/Polygon/PolygonSet.cs | 2,347 | C# |
namespace SimpleBudget.Data
{
public class AccountStore : StoreHelper<Account>
{
internal AccountStore() { }
}
}
| 16.75 | 52 | 0.641791 | [
"Apache-2.0"
] | Aleksey-Terzi/SimpleBudget | Code/SimpleBudget.Data/Entities/Accounts/AccountStore.cs | 136 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CBTTaskFalling : IBehTreeTask
{
[Ordinal(1)] [RED("npc")] public CHandle<CNewNPC> Npc { get; set;}
[Ordinal(2)] [RED("drawableComp")] public CHandle<CDrawableComponent> DrawableComp { get; set;}
[Ordinal(3)] [RED("fakeBroomHidden")] public CBool FakeBroomHidden { get; set;}
[Ordinal(4)] [RED("attachedToGround")] public CBool AttachedToGround { get; set;}
[Ordinal(5)] [RED("broomSpawned")] public CBool BroomSpawned { get; set;}
public CBTTaskFalling(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskFalling(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 33.727273 | 126 | 0.705301 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CBTTaskFalling.cs | 1,081 | C# |
/*$ preserve start $*/
/* ========================================================================================== */
/* FMOD Ex - DSP header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2015. */
/* */
/* Use this header if you are interested in delving deeper into the FMOD software mixing / */
/* DSP engine. In this header you can find parameter structures for FMOD system reigstered */
/* DSP effects and generators. */
/* */
/* ========================================================================================== */
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace FMOD
{
/*$ preserve end $*/
/*
DSP callbacks
*/
public delegate RESULT DSP_CREATECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RELEASECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RESETCALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_READCALLBACK (ref DSP_STATE dsp_state, IntPtr inbuffer, IntPtr outbuffer, uint length, int inchannels, int outchannels);
public delegate RESULT DSP_SETPOSITIONCALLBACK (ref DSP_STATE dsp_state, uint seeklen);
public delegate RESULT DSP_SETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, float val);
public delegate RESULT DSP_GETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, ref float val, StringBuilder valuestr);
public delegate RESULT DSP_DIALOGCALLBACK (ref DSP_STATE dsp_state, IntPtr hwnd, bool show);
/*
[ENUM]
[
[DESCRIPTION]
These definitions can be used for creating FMOD defined special effects or DSP units.
[REMARKS]
To get them to be active, first create the unit, then add it somewhere into the DSP network, either at the front of the network near the soundcard unit to affect the global output (by using System::getDSPHead), or on a single channel (using Channel::getDSPHead).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSPByType
]
*/
public enum DSP_TYPE :int
{
UNKNOWN, /* This unit was created via a non FMOD plugin so has an unknown purpose */
MIXER, /* This unit does nothing but take inputs and mix them together then feed the result to the soundcard unit. */
OSCILLATOR, /* This unit generates sine/square/saw/triangle or noise tones. */
LOWPASS, /* This unit filters sound using a high quality, resonant lowpass filter algorithm but consumes more CPU time. */
ITLOWPASS, /* This unit filters sound using a resonant lowpass filter algorithm that is used in Impulse Tracker, but with limited cutoff range (0 to 8060hz). */
HIGHPASS, /* This unit filters sound using a resonant highpass filter algorithm. */
ECHO, /* This unit produces an echo on the sound and fades out at the desired rate. */
FLANGE, /* This unit produces a flange effect on the sound. */
DISTORTION, /* This unit distorts the sound. */
NORMALIZE, /* This unit normalizes or amplifies the sound to a certain level. */
PARAMEQ, /* This unit attenuates or amplifies a selected frequency range. */
PITCHSHIFT, /* This unit bends the pitch of a sound without changing the speed of playback. */
CHORUS, /* This unit produces a chorus effect on the sound. */
VSTPLUGIN, /* This unit allows the use of Steinberg VST plugins */
WINAMPPLUGIN, /* This unit allows the use of Nullsoft Winamp plugins */
ITECHO, /* This unit produces an echo on the sound and fades out at the desired rate as is used in Impulse Tracker. */
COMPRESSOR, /* This unit implements dynamic compression (linked multichannel, wideband) */
SFXREVERB, /* This unit implements SFX reverb */
LOWPASS_SIMPLE, /* This unit filters sound using a simple lowpass with no resonance, but has flexible cutoff and is fast. */
DELAY, /* This unit produces different delays on individual channels of the sound. */
TREMOLO, /* This unit produces a tremolo / chopper effect on the sound. */
LADSPAPLUGIN, /* This unit allows the use of LADSPA standard plugins. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
The step parameter tells the gui or application that the parameter has a certain granularity.<br>
For example in the example of cutoff frequency with a range from 100.0 to 22050.0 you might only want the selection to be in 10hz increments. For this you would simply use 10.0 as the step value.<br>
For a boolean, you can use min = 0.0, max = 1.0, step = 1.0. This way the only possible values are 0.0 and 1.0.<br>
Some applications may detect min = 0.0, max = 1.0, step = 1.0 and replace a graphical slider bar with a checkbox instead.<br>
A step value of 1.0 would simulate integer values only.<br>
A step value of 0.0 would mean the full floating point range is accessable.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_PARAMETERDESC
{
public float min; /* [in] Minimum value of the parameter (ie 100.0). */
public float max; /* [in] Maximum value of the parameter (ie 22050.0). */
public float defaultval; /* [in] Default value of parameter. */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] name; /* [in] Name of the parameter to be displayed (ie "Cutoff frequency"). */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] label; /* [in] Short string to be put next to value to denote the unit type (ie "hz"). */
public string description; /* [in] Description of the parameter to be displayed as a help item / tooltip for this parameter. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
Strcture to define the parameters for a DSP unit.
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
There are 2 different ways to change a parameter in this architecture.<br>
One is to use DSP::setParameter / DSP::getParameter. This is platform independant and is dynamic, so new unknown plugins can have their parameters enumerated and used.<br>
The other is to use DSP::showConfigDialog. This is platform specific and requires a GUI, and will display a dialog box to configure the plugin.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_DESCRIPTION
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
public char[] name; /* [in] Name of the unit to be displayed in the network. */
public uint version; /* [in] Plugin writer's version number. */
public int channels; /* [in] Number of channels. Use 0 to process whatever number of channels is currently in the network. >0 would be mostly used if the unit is a unit that only generates sound. */
public DSP_CREATECALLBACK create; /* [in] Create callback. This is called when DSP unit is created. Can be null. */
public DSP_RELEASECALLBACK release; /* [in] Release callback. This is called just before the unit is freed so the user can do any cleanup needed for the unit. Can be null. */
public DSP_RESETCALLBACK reset; /* [in] Reset callback. This is called by the user to reset any history buffers that may need resetting for a filter, when it is to be used or re-used for the first time to its initial clean state. Use to avoid clicks or artifacts. */
public DSP_READCALLBACK read; /* [in] Read callback. Processing is done here. Can be null. */
public DSP_SETPOSITIONCALLBACK setposition; /* [in] Setposition callback. This is called if the unit wants to update its position info but not process data. Can be null. */
public int numparameters; /* [in] Number of parameters used in this filter. The user finds this with DSP::getNumParameters */
public DSP_PARAMETERDESC[] paramdesc; /* [in] Variable number of parameter structures. */
public DSP_SETPARAMCALLBACK setparameter; /* [in] This is called when the user calls DSP::setParameter. Can be null. */
public DSP_GETPARAMCALLBACK getparameter; /* [in] This is called when the user calls DSP::getParameter. Can be null. */
public DSP_DIALOGCALLBACK config; /* [in] This is called when the user calls DSP::showConfigDialog. Can be used to display a dialog to configure the filter. Can be null. */
public int configwidth; /* [in] Width of config dialog graphic if there is one. 0 otherwise.*/
public int configheight; /* [in] Height of config dialog graphic if there is one. 0 otherwise.*/
public IntPtr userdata; /* [in] Optional. Specify 0 to ignore. This is user data to be attached to the DSP unit during creation. Access via DSP::getUserData. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
DSP plugin structure that is passed into each callback.
[REMARKS]
Members marked with [in] mean the variable can be written to. The user can set the value.<br>
Members marked with [out] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
FMOD_DSP_DESCRIPTION
]
*/
public struct DSP_STATE
{
public IntPtr instance; /* [out] Handle to the DSP hand the user created. Not to be modified. C++ users cast to FMOD::DSP to use. */
public IntPtr plugindata; /* [in] Plugin writer created data the output author wants to attach to this object. */
public ushort speakermask; /* Specifies which speakers the DSP effect is active on */
};
/*
==============================================================================================================
FMOD built in effect parameters.
Use DSP::setParameter with these enums for the 'index' parameter.
==============================================================================================================
*/
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_OSCILLATOR filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_OSCILLATOR
{
TYPE, /* Waveform type. 0 = sine. 1 = square. 2 = sawup. 3 = sawdown. 4 = triangle. 5 = noise. */
RATE /* Frequency of the sinewave in hz. 1.0 to 22000.0. Default = 220.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_LOWPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_LOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0. */
RESONANCE /* Lowpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITLOWPASS filter.
This is different to the default FMOD_DSP_TYPE_ITLOWPASS filter in that it uses a different quality algorithm and is
the filter used to produce the correct sounding playback in .IT files.<br>
FMOD Ex's .IT playback uses this filter.<br>
[REMARKS]
Note! This filter actually has a limited cutoff frequency below the specified maximum, due to its limited design,
so for a more open range filter use FMOD_DSP_LOWPASS or if you don't mind not having resonance,
FMOD_DSP_LOWPASS_SIMPLE.<br>
The effective maximum cutoff is about 8060hz.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ITLOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0/ */
RESONANCE /* Lowpass resonance Q value. 0.0 to 127.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_HIGHPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_HIGHPASS
{
CUTOFF, /* Highpass cutoff frequency in hz. 10.0 to output 22000.0. Default = 5000.0. */
RESONANCE /* Highpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ECHO filter.
[REMARKS]
Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
'<i>maxchannels</i>' also dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the echo unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel echo, etc.<br>
If the echo effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the echo is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel echo is set to a lower number than the sound's channel count that is coming in, it will not echo the sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ECHO
{
DELAY, /* Echo delay in ms. 10 to 5000. Default = 500. */
DECAYRATIO, /* Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay. Default = 0.5. */
MAXCHANNELS, /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 1.0. */
WETMIX /* Volume of echo signal to pass to output. 0.0 to 1.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_DELAY filter.
[REMARKS]
Note. Every time MaxDelay is changed, the plugin re-allocates the delay buffer. This means the delay will dissapear at that time while it refills its new buffer.<br>
A larger MaxDelay results in larger amounts of memory allocated.<br>
Channel delays above MaxDelay will be clipped to MaxDelay and the delay buffer will not be resized.<br>
<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_DELAY
{
CH0, /* Channel #0 Delay in ms. 0 to 10000. Default = 0. */
CH1, /* Channel #1 Delay in ms. 0 to 10000. Default = 0. */
CH2, /* Channel #2 Delay in ms. 0 to 10000. Default = 0. */
CH3, /* Channel #3 Delay in ms. 0 to 10000. Default = 0. */
CH4, /* Channel #4 Delay in ms. 0 to 10000. Default = 0. */
CH5, /* Channel #5 Delay in ms. 0 to 10000. Default = 0. */
CH6, /* Channel #6 Delay in ms. 0 to 10000. Default = 0. */
CH7, /* Channel #7 Delay in ms. 0 to 10000. Default = 0. */
CH8, /* Channel #8 Delay in ms. 0 to 10000. Default = 0. */
CH9, /* Channel #9 Delay in ms. 0 to 10000. Default = 0. */
CH10, /* Channel #10 Delay in ms. 0 to 10000. Default = 0. */
CH11, /* Channel #11 Delay in ms. 0 to 10000. Default = 0. */
CH12, /* Channel #12 Delay in ms. 0 to 10000. Default = 0. */
CH13, /* Channel #13 Delay in ms. 0 to 10000. Default = 0. */
CH14, /* Channel #14 Delay in ms. 0 to 10000. Default = 0. */
CH15, /* Channel #15 Delay in ms. 0 to 10000. Default = 0. */
MAXDELAY, /* Maximum delay in ms. 0 to 1000. Default = 10. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_FLANGE filter.
[REMARKS]
Flange is an effect where the signal is played twice at the same time, and one copy slides back and forth creating a whooshing or flanging effect.<br>
As there are 2 copies of the same signal, by default each signal is given 50% mix, so that the total is not louder than the original unaffected signal.<br>
<br>
Flange depth is a percentage of a 10ms shift from the original signal. Anything above 10ms is not considered flange because to the ear it begins to 'echo' so 10ms is the highest value possible.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_FLANGE
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.45. */
WETMIX, /* Volume of flange signal to pass to output. 0.0 to 1.0. Default = 0.55. */
DEPTH, /* Flange depth. 0.01 to 1.0. Default = 1.0. */
RATE /* Flange speed in hz. 0.0 to 20.0. Default = 0.1. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_TREMOLO filter.
[REMARKS]
The tremolo effect varies the amplitude of a sound. Depending on the settings, this unit can produce a tremolo, chopper or auto-pan effect.<br>
<br>
The shape of the LFO (low freq. oscillator) can morphed between sine, triangle and sawtooth waves using the FMOD_DSP_TREMOLO_SHAPE and FMOD_DSP_TREMOLO_SKEW parameters.<br>
FMOD_DSP_TREMOLO_DUTY and FMOD_DSP_TREMOLO_SQUARE are useful for a chopper-type effect where the first controls the on-time duration and second controls the flatness of the envelope.<br>
FMOD_DSP_TREMOLO_SPREAD varies the LFO phase between channels to get an auto-pan effect. This works best with a sine shape LFO.<br>
The LFO can be synchronized using the FMOD_DSP_TREMOLO_PHASE parameter which sets its instantaneous phase.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_TREMOLO
{
FREQUENCY, /* LFO frequency in Hz. 0.1 to 20. Default = 4. */
DEPTH, /* Tremolo depth. 0 to 1. Default = 0. */
SHAPE, /* LFO shape morph between triangle and sine. 0 to 1. Default = 0. */
SKEW, /* Time-skewing of LFO cycle. -1 to 1. Default = 0. */
DUTY, /* LFO on-time. 0 to 1. Default = 0.5. */
SQUARE, /* Flatness of the LFO shape. 0 to 1. Default = 0. */
PHASE, /* Instantaneous LFO phase. 0 to 1. Default = 0. */
SPREAD /* Rotation / auto-pan effect. -1 to 1. Default = 0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_DISTORTION filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_DISTORTION
{
LEVEL /* Distortion value. 0.0 to 1.0. Default = 0.5. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_NORMALIZE filter.
[REMARKS]
Normalize amplifies the sound based on the maximum peaks within the signal.<br>
For example if the maximum peaks in the signal were 50% of the bandwidth, it would scale the whole sound by 2.<br>
The lower threshold value makes the normalizer ignores peaks below a certain point, to avoid over-amplification if a loud signal suddenly came in, and also to avoid amplifying to maximum things like background hiss.<br>
<br>
Because FMOD is a realtime audio processor, it doesn't have the luxury of knowing the peak for the whole sound (ie it can't see into the future), so it has to process data as it comes in.<br>
To avoid very sudden changes in volume level based on small samples of new data, fmod fades towards the desired amplification which makes for smooth gain control. The fadetime parameter can control this.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_NORMALIZE
{
FADETIME, /* Time to ramp the silence to full in ms. 0.0 to 20000.0. Default = 5000.0. */
THRESHHOLD, /* Lower volume range threshold to ignore. 0.0 to 1.0. Default = 0.1. Raise higher to stop amplification of very quiet signals. */
MAXAMP /* Maximum amplification allowed. 1.0 to 100000.0. Default = 20.0. 1.0 = no amplifaction, higher values allow more boost. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PARAMEQ filter.
[REMARKS]
Parametric EQ is a bandpass filter that attenuates or amplifies a selected frequency and its neighbouring frequencies.<br>
<br>
To create a multi-band EQ create multiple FMOD_DSP_TYPE_PARAMEQ units and set each unit to different frequencies, for example 1000hz, 2000hz, 4000hz, 8000hz, 16000hz with a range of 1 octave each.<br>
<br>
When a frequency has its gain set to 1.0, the sound will be unaffected and represents the original signal exactly.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PARAMEQ
{
CENTER, /* Frequency center. 20.0 to 22000.0. Default = 8000.0. */
BANDWIDTH, /* Octave range around the center frequency to filter. 0.2 to 5.0. Default = 1.0. */
GAIN /* Frequency Gain. 0.05 to 3.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PITCHSHIFT filter.
[REMARKS]
This pitch shifting unit can be used to change the pitch of a sound without speeding it up or slowing it down.<br>
It can also be used for time stretching or scaling, for example if the pitch was doubled, and the frequency of the sound was halved, the pitch of the sound would sound correct but it would be twice as slow.<br>
<br>
<b>Warning!</b> This filter is very computationally expensive! Similar to a vocoder, it requires several overlapping FFT and IFFT's to produce smooth output, and can require around 440mhz for 1 stereo 48khz signal using the default settings.<br>
Reducing the signal to mono will half the cpu usage, as will the overlap count.<br>
Reducing this will lower audio quality, but what settings to use are largely dependant on the sound being played. A noisy polyphonic signal will need higher overlap and fft size compared to a speaking voice for example.<br>
<br>
This pitch shifter is based on the pitch shifter code at http://www.dspdimension.com, written by Stephan M. Bernsee.<br>
The original code is COPYRIGHT 1999-2003 Stephan M. Bernsee <smb@dspdimension.com>.<br>
<br>
'<i>maxchannels</i>' dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the pitch shift unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel pitch shift, etc.<br>
If the pitch shift effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the pitch shift is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel pitch shift is set to a lower number than the sound's channel count that is coming in, it will not pitch shift the sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PITCHSHIFT
{
PITCH, /* Pitch value. 0.5 to 2.0. Default = 1.0. 0.5 = one octave down, 2.0 = one octave up. 1.0 does not change the pitch. */
FFTSIZE, /* FFT window size. 256, 512, 1024, 2048, 4096. Default = 1024. Increase this to reduce 'smearing'. This effect is a warbling sound similar to when an mp3 is encoded at very low bitrates. */
OVERLAP, /* Window overlap. 1 to 32. Default = 4. Increase this to reduce 'tremolo' effect. Increasing it by a factor of 2 doubles the CPU usage. */
MAXCHANNELS /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_CHORUS filter.
[REMARKS]
Chrous is an effect where the sound is more 'spacious' due to 1 to 3 versions of the sound being played along side the original signal but with the pitch of each copy modulating on a sine wave.<br>
This is a highly configurable chorus unit. It supports 3 taps, small and large delay times and also feedback.<br>
This unit also could be used to do a simple echo, or a flange effect.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_CHORUS
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.5. */
WETMIX1, /* Volume of 1st chorus tap. 0.0 to 1.0. Default = 0.5. */
WETMIX2, /* Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap. 0.0 to 1.0. Default = 0.5. */
WETMIX3, /* Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap. 0.0 to 1.0. Default = 0.5. */
DELAY, /* Chorus delay in ms. 0.1 to 100.0. Default = 40.0 ms. */
RATE, /* Chorus modulation rate in hz. 0.0 to 20.0. Default = 0.8 hz. */
DEPTH, /* Chorus modulation depth. 0.0 to 1.0. Default = 0.03. */
FEEDBACK /* Chorus feedback. Controls how much of the wet signal gets fed back into the chorus buffer. 0.0 to 1.0. Default = 0.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITECHO filter.<br>
This is effectively a software based echo filter that emulates the DirectX DMO echo effect. Impulse tracker files can support this, and FMOD will produce the effect on ANY platform, not just those that support DirectX effects!<br>
[REMARKS]
Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
For stereo signals only! This will not work on mono or multichannel signals. This is fine for .IT format purposes, and also if you use System::addDSP with a standard stereo output.<br>
[PLATFORMS]
Win32, Win64, Linux, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_ITECHO
{
WETDRYMIX, /* Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from 0.0 through 100.0 (all wet). The default value is 50. */
FEEDBACK, /* Percentage of output fed back into input, in the range from 0.0 through 100.0. The default value is 50. */
LEFTDELAY, /* Delay for left channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
RIGHTDELAY, /* Delay for right channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
PANDELAY /* Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as 0.0 (equivalent to FALSE) and 1.0 (equivalent to TRUE). */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_COMPRESSOR unit.<br>
This is a simple linked multichannel software limiter that is uniform across the whole spectrum.<br>
[REMARKS]
The parameters are as follows:
Threshold: [-60dB to 0dB, default 0dB]
Attack Time: [10ms to 200ms, default 50ms]
Release Time: [20ms to 1000ms, default 50ms]
Gain Make Up: [0dB to +30dB, default 0dB]
<br>
The limiter is not guaranteed to catch every peak above the threshold level,
because it cannot apply gain reduction instantaneously - the time delay is
determined by the attack time. However setting the attack time too short will
distort the sound, so it is a compromise. High level peaks can be avoided by
using a short attack time - but not too short, and setting the threshold a few
decibels below the critical level.
<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_COMPRESSOR
{
THRESHOLD, /* Threshold level (dB)in the range from -60 through 0. The default value is 50. */
ATTACK, /* Gain reduction attack time (milliseconds), in the range from 10 through 200. The default value is 50. */
RELEASE, /* Gain reduction release time (milliseconds), in the range from 20 through 1000. The default value is 50. */
GAINMAKEUP /* Make-up gain applied after limiting, in the range from 0.0 through 100.0. The default value is 50. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_SFXREVERB unit.<br>
[REMARKS]
This is a high quality I3DL2 based reverb which improves greatly on FMOD_DSP_REVERB.<br>
On top of the I3DL2 property set, "Dry Level" is also included to allow the dry mix to be changed.<br>
<br>
Currently FMOD_DSP_SFXREVERB_REFLECTIONSLEVEL, FMOD_DSP_SFXREVERB_REFLECTIONSDELAY and FMOD_DSP_SFXREVERB_REVERBDELAY are not enabled but will come in future versions.<br>
<br>
These properties can be set with presets in FMOD_REVERB_PRESETS.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
FMOD_REVERB_PRESETS
]
*/
public enum DSP_SFXREVERB
{
DRYLEVEL, /* Dry Level : Mix level of dry signal in output in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOM, /* Room : Room effect level at low frequencies in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMHF, /* Room HF : Room effect high-frequency level re. low frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMROLLOFFFACTOR, /* Room Rolloff : Like DS3D flRolloffFactor but for room effect. Ranges from 0.0 to 10.0. Default is 10.0 */
DECAYTIME, /* Decay Time : Reverberation decay time at low-frequencies in seconds. Ranges from 0.1 to 20.0. Default is 1.0. */
DECAYHFRATIO, /* Decay HF Ratio : High-frequency to low-frequency decay time ratio. Ranges from 0.1 to 2.0. Default is 0.5. */
REFLECTIONSLEVEL, /* Reflections : Early reflections level relative to room effect in mB. Ranges from -10000.0 to 1000.0. Default is -10000.0. */
REFLECTIONSDELAY, /* Reflect Delay : Delay time of first reflection in seconds. Ranges from 0.0 to 0.3. Default is 0.02. */
REVERBLEVEL, /* Reverb : Late reverberation level relative to room effect in mB. Ranges from -10000.0 to 2000.0. Default is 0.0. */
REVERBDELAY, /* Reverb Delay : Late reverberation delay time relative to first reflection in seconds. Ranges from 0.0 to 0.1. Default is 0.04. */
DIFFUSION, /* Diffusion : Reverberation diffusion (echo density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
DENSITY, /* Density : Reverberation density (modal density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
HFREFERENCE, /* HF Reference : Reference high frequency in Hz. Ranges from 20.0 to 20000.0. Default is 5000.0. */
ROOMLF, /* Room LF : Room effect low-frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
LFREFERENCE /* LF Reference : Reference low-frequency in Hz. Ranges from 20.0 to 1000.0. Default is 250.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_LOWPASS_SIMPLE filter.<br>
This is a very simple low pass filter, based on two single-pole RC time-constant modules.
The emphasis is on speed rather than accuracy, so this should not be used for task requiring critical filtering.<br>
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_LOWPASS_SIMPLE
{
CUTOFF /* Lowpass cutoff frequency in hz. 10.0 to 22000.0. Default = 5000.0 */
}
/*$ preserve start $*/
}
/*$ preserve end $*/
| 52.371622 | 299 | 0.622268 | [
"MIT"
] | Mikxus/SBT | BeatDetector/BeatDetectorC#Version/fmod_dsp.cs | 38,755 | C# |
/*
* 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.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.sgw.Model.V20180511
{
public class UploadGatewayLogResponse : AcsResponse
{
private string requestId;
private bool? success;
private string code;
private string message;
private string taskId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string TaskId
{
get
{
return taskId;
}
set
{
taskId = value;
}
}
}
}
| 17.323232 | 63 | 0.625656 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-sgw/Sgw/Model/V20180511/UploadGatewayLogResponse.cs | 1,715 | C# |
using System;
namespace Niue.Abp.Abp.Domain.Entities.Auditing
{
/// <summary>
/// An entity can implement this interface if <see cref="CreationTime"/> of this entity must be stored.
/// <see cref="CreationTime"/> is automatically set when saving <see cref="Entity"/> to database.
/// </summary>
public interface IHasCreationTime
{
/// <summary>
/// Creation time of this entity.
/// </summary>
DateTime CreationTime { get; set; }
}
} | 30.875 | 107 | 0.625506 | [
"MIT"
] | P79N6A/abp-ant-design-pro-vue | Niue.Abp/Abp/Domain/Entities/Auditing/IHasCreationTime.cs | 494 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support
{
public partial struct EventGridDataFormat :
System.IEquatable<EventGridDataFormat>
{
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Apacheavro = @"APACHEAVRO";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Avro = @"AVRO";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Csv = @"CSV";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Json = @"JSON";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Multijson = @"MULTIJSON";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Orc = @"ORC";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Parquet = @"PARQUET";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Psv = @"PSV";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Raw = @"RAW";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Scsv = @"SCSV";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Singlejson = @"SINGLEJSON";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Sohsv = @"SOHSV";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Tsv = @"TSV";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Tsve = @"TSVE";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat Txt = @"TXT";
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat W3Clogfile = @"W3CLOGFILE";
/// <summary>the value for an instance of the <see cref="EventGridDataFormat" /> Enum.</summary>
private string _value { get; set; }
/// <summary>Conversion from arbitrary object to EventGridDataFormat</summary>
/// <param name="value">the value to convert to an instance of <see cref="EventGridDataFormat" />.</param>
internal static object CreateFrom(object value)
{
return new EventGridDataFormat(System.Convert.ToString(value));
}
/// <summary>Compares values of enum type EventGridDataFormat</summary>
/// <param name="e">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e)
{
return _value.Equals(e._value);
}
/// <summary>Compares values of enum type EventGridDataFormat (override for Object)</summary>
/// <param name="obj">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public override bool Equals(object obj)
{
return obj is EventGridDataFormat && Equals((EventGridDataFormat)obj);
}
/// <summary>Creates an instance of the <see cref="EventGridDataFormat" Enum class./></summary>
/// <param name="underlyingValue">the value to create an instance for.</param>
private EventGridDataFormat(string underlyingValue)
{
this._value = underlyingValue;
}
/// <summary>Returns hashCode for enum EventGridDataFormat</summary>
/// <returns>The hashCode of the value</returns>
public override int GetHashCode()
{
return this._value.GetHashCode();
}
/// <summary>Returns string representation for EventGridDataFormat</summary>
/// <returns>A string for this value.</returns>
public override string ToString()
{
return this._value;
}
/// <summary>Implicit operator to convert string to EventGridDataFormat</summary>
/// <param name="value">the value to convert to an instance of <see cref="EventGridDataFormat" />.</param>
public static implicit operator EventGridDataFormat(string value)
{
return new EventGridDataFormat(value);
}
/// <summary>Implicit operator to convert EventGridDataFormat to string</summary>
/// <param name="e">the value to convert to an instance of <see cref="EventGridDataFormat" />.</param>
public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e)
{
return e._value;
}
/// <summary>Overriding != operator for enum EventGridDataFormat</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are not equal to the same value</returns>
public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e1, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e2)
{
return !e2.Equals(e1);
}
/// <summary>Overriding == operator for enum EventGridDataFormat</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e1, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.EventGridDataFormat e2)
{
return e2.Equals(e1);
}
}
} | 51.224 | 185 | 0.676089 | [
"MIT"
] | Click4PV/azure-powershell | src/Kusto/generated/api/Support/EventGridDataFormat.cs | 6,279 | C# |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;
using System.Data;
namespace imgsample
{
/// <summary>
/// Scales and saves images to db
/// </summary>
public class ImageUtil
{
public ImageUtil()
{
//
// TODO: Add constructor logic here
//
}
private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
System.Drawing.Imaging.ImageCodecInfo[] encoders;
encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
for(j = 0; j < encoders.Length; ++j)
{
if(encoders[j].MimeType == mimeType)
return encoders[j];
} return null;
}
public static System.Drawing.Image GetScaledAndCompressedJpeg(System.IO.Stream stm, int max, long quality)
{
return GetScaledAndCompressedJpeg(System.Drawing.Image.FromStream(stm), max, quality);
}
public static System.Drawing.Image GetScaledAndCompressedJpeg(System.Drawing.Image img, int max, long quality)
{
ImageCodecInfo jpgEncoder = GetEncoderInfo("image/jpeg");
Size s = GetScaledSize(img.Size, max);
Bitmap newBitmap = new Bitmap(s.Width, s.Height);
// Create a Graphics object which is the "workhorse" for the high quality resizing
Graphics grfxThumb = Graphics.FromImage(newBitmap);
// Set the interpolation mode
// Bicubic : Specifies bicubic interpolation
// Bilinear : Specifies bilinear interpolation
// Default : Specifies default mode
// High : Specifies high quality interpolation
// HighQualityBicubic : Specifies high quality bicubic interpolation ****************** THIS IS THE HIGHEST QUALITY
// HighQualityBilinear : Specifies high quality bilinear interpolation
// Invalid : Equivalent to the Invalid element of the QualityMode enumeration
// Low : Specifies low quality interpolation
// NearestNeighbor : Specifies nearest-neighbor interpolation
grfxThumb.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// Draw the original image to the target image
grfxThumb.DrawImage(img, new Rectangle(0, 0, s.Width, s.Height));
// Set the quality (must be a long)
Encoder qualityEncoder = Encoder.Quality;
EncoderParameter ratio = new EncoderParameter(qualityEncoder, (long)quality);
// Add the quality parameter to the list
EncoderParameters codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
// Save to JPG
System.IO.MemoryStream stm = new System.IO.MemoryStream();
newBitmap.Save(stm, jpgEncoder, codecParams);
stm.Seek(0, System.IO.SeekOrigin.Begin);
// Return new bitmap
return new Bitmap(stm);
}
private static Size GetScaledSize(Size orig, int max)
{
Size s = new Size();
if (orig.Height > orig.Width)
{
// Portrait
s.Height = (int)max;
s.Width = (int)((float)orig.Width / ((float)orig.Height / max));
}
else
{
// Landscape
s.Width = (int)max;
s.Height = (int)((float)orig.Height / ((float)orig.Width / max));
}
return s;
}
public static byte[] GetImageBytes(Stream stm)
{
stm.Seek(0, SeekOrigin.Begin); // reset to beginning
byte[] rgOrig = new byte[stm.Length];
stm.Read(rgOrig,0,(int)stm.Length);
return rgOrig;
}
public static byte[] GetScaledImageBytes(Stream stm, int size, long qual)
{
System.IO.Stream streamTemp = new System.IO.MemoryStream();
System.Drawing.Image img = GetScaledAndCompressedJpeg(stm, size, qual);
img.Save(streamTemp, System.Drawing.Imaging.ImageFormat.Jpeg ); // always jpg
byte[] rg = new byte[streamTemp.Length];
streamTemp.Seek(0, SeekOrigin.Begin); // reset to beginning
streamTemp.Read(rg, 0 , (int)streamTemp.Length);
return rg;
}
public static void SaveToRow(imgsample.ImagesDataSet.imageRow row, Stream streamOrig, String nameOrig, String contenttypeOrig)
{
int iThumbSize = System.Convert.ToInt32(ConfigurationSettings.AppSettings["ThumbSize"]);
int iMedSize = System.Convert.ToInt32(ConfigurationSettings.AppSettings["MedSize"]);
long lThumbQuality = (long)System.Convert.ToInt32(ConfigurationSettings.AppSettings["ThumbQuality"]);
long lMedQuality = (long)System.Convert.ToInt32(ConfigurationSettings.AppSettings["MedQuality"]);
System.Drawing.Image imgOrig = null;
System.Drawing.Image imgMed = null;
System.Drawing.Image imgThumb = null;
imgOrig = System.Drawing.Image.FromStream(streamOrig);
streamOrig.Seek(0, SeekOrigin.Begin); // reset to beginning
byte[] rgOrig = new byte[streamOrig.Length];
int n = streamOrig.Read(rgOrig,0,(int)streamOrig.Length);
// create thumb and mid
System.IO.Stream streamTemp = new System.IO.MemoryStream();
imgMed = GetScaledAndCompressedJpeg(imgOrig, iMedSize, lMedQuality);
imgMed.Save(streamTemp, System.Drawing.Imaging.ImageFormat.Jpeg ); // Meds are always png
byte[] rgMed = new byte[streamTemp.Length];
streamTemp.Seek(0, SeekOrigin.Begin); // reset to beginning
streamTemp.Read(rgMed, 0 , (int)streamTemp.Length);
imgThumb = GetScaledAndCompressedJpeg(imgOrig, iThumbSize, lThumbQuality);
streamTemp.Seek(0, SeekOrigin.Begin); // reset to beginning
imgThumb.Save(streamTemp, System.Drawing.Imaging.ImageFormat.Jpeg); // thumbs are always png
byte[] rgThumb = new byte[streamTemp.Length];
streamTemp.Seek(0, SeekOrigin.Begin); // reset to beginning
streamTemp.Read(rgThumb, 0 , (int)streamTemp.Length);
try
{
PropertyItem prop = imgOrig.GetPropertyItem(40091);
EXIFPropertyItem exifProp = new EXIFPropertyItem(prop);
row.img_desc = exifProp.ParsedString;
}
catch {}
try
{
PropertyItem prop = imgOrig.GetPropertyItem((int)KnownEXIFIDCodes.DateTimeOriginal);
EXIFPropertyItem exifProp = new EXIFPropertyItem(prop);
row.img_datepicturetaken = exifProp.ParsedDate;
}
catch {}
string [] parts = nameOrig.Split(new Char[] {'\\'});
string filename = parts[parts.Length-1];
row.img_name = filename;
row.img_full = rgOrig;
row.img_med = rgMed;
row.img_thumb = rgThumb;
row.img_contenttype = contenttypeOrig;
}
}
}
| 35.785311 | 129 | 0.695453 | [
"MIT",
"Unlicense"
] | mdileep/Tigger | Experiments/imgsample/ImageUtil.cs | 6,334 | C# |
using Microsoft.Xna.Framework;
using System;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using tsorcRevamp.Projectiles.Enemy;
namespace tsorcRevamp.NPCs.Bosses {
class TheHunter : ModNPC {
public override void SetStaticDefaults() {
Main.npcFrameCount[npc.type] = 7;
}
public override void SetDefaults() {
npc.aiStyle = -1;
npc.lifeMax = 25000;
npc.damage = 42;
npc.defense = 25;
npc.knockBackResist = 0f;
npc.width = 180;
npc.height = 126;
npc.scale = 1.4f;
npc.value = 200000;
npc.npcSlots = 160;
npc.boss = true;
npc.lavaImmune = true;
npc.noGravity = true;
npc.noTileCollide = true;
npc.HitSound = SoundID.NPCHit1;
npc.DeathSound = SoundID.NPCDeath1;
bossBag = ModContent.ItemType<Items.BossBags.TheHunterBag>();
npc.buffImmune[BuffID.OnFire] = true;
npc.buffImmune[BuffID.Poisoned] = true;
npc.buffImmune[BuffID.Confused] = true;
}
public override void AI() {
npc.netUpdate = true;
npc.ai[2]++;
npc.ai[1]++;
if (npc.ai[0] > 0) npc.ai[0] -= 1.2f;
Vector2 vector8 = new Vector2(npc.position.X + (npc.width * 0.5f), npc.position.Y + (npc.height / 2));
if (npc.target < 0 || npc.target == 255 || Main.player[npc.target].dead || !Main.player[npc.target].active || !Main.player[npc.target].ZoneJungle) {
npc.TargetClosest(true);
}
int dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 18, npc.velocity.X, npc.velocity.Y, 200, default, 0.5f + npc.ai[0] / 75);
Main.dust[dust].noGravity = true;
if (npc.ai[3] == 0) {
npc.alpha = 0;
npc.dontTakeDamage = false;
npc.damage = 73;
if (npc.ai[2] < 600) {
if (Main.player[npc.target].position.X < vector8.X) {
if (npc.velocity.X > -8) { npc.velocity.X -= 0.22f; }
}
if (Main.player[npc.target].position.X > vector8.X) {
if (npc.velocity.X < 8) { npc.velocity.X += 0.22f; }
}
if (Main.player[npc.target].position.Y < vector8.Y + 300) {
if (npc.velocity.Y > 0f) npc.velocity.Y -= 0.8f;
else npc.velocity.Y -= 0.07f;
}
if (Main.player[npc.target].position.Y > vector8.Y + 300) {
if (npc.velocity.Y < 0f) npc.velocity.Y += 0.8f;
else npc.velocity.Y += 0.07f;
}
if (npc.ai[1] >= 0 && npc.ai[2] > 120 && npc.ai[2] < 600) {
float num48 = 22f;
int damage = 38;
int type = ModContent.ProjectileType<MiracleSprouter>();
Main.PlaySound(SoundID.Item, (int)vector8.X, (int)vector8.Y, 17);
float rotation = (float)Math.Atan2(vector8.Y - 80 - (Main.player[npc.target].position.Y + (Main.player[npc.target].height * 0.5f)), vector8.X - (Main.player[npc.target].position.X + (Main.player[npc.target].width * 0.5f)));
int num54 = Projectile.NewProjectile(vector8.X, vector8.Y - 80, (float)((Math.Cos(rotation) * num48) * -1), (float)((Math.Sin(rotation) * num48) * -1), type, damage, 0f, Main.myPlayer);
Main.projectile[num54].timeLeft = 50;
num54 = Projectile.NewProjectile(vector8.X, vector8.Y - 80, (float)((Math.Cos(rotation + 0.4) * num48) * -1), (float)((Math.Sin(rotation + 0.4) * num48) * -1), type, damage, 0f, Main.myPlayer);
Main.projectile[num54].timeLeft = 50;
num54 = Projectile.NewProjectile(vector8.X, vector8.Y - 80, (float)((Math.Cos(rotation - 0.4) * num48) * -1), (float)((Math.Sin(rotation - 0.4) * num48) * -1), type, damage, 0f, Main.myPlayer);
Main.projectile[num54].timeLeft = 50;
npc.ai[1] = -90;
}
npc.netUpdate = true; //new
}
else if (npc.ai[2] >= 600 && npc.ai[2] < 1200) {
npc.velocity.X *= 0.98f;
npc.velocity.Y *= 0.98f;
if ((npc.velocity.X < 2f) && (npc.velocity.X > -2f) && (npc.velocity.Y < 2f) && (npc.velocity.Y > -2f)) {
float rotation = (float)Math.Atan2((vector8.Y) - (Main.player[npc.target].position.Y + (Main.player[npc.target].height * 0.5f)), (vector8.X) - (Main.player[npc.target].position.X + (Main.player[npc.target].width * 0.5f)));
npc.velocity.X = (float)(Math.Cos(rotation) * 25) * -1;
npc.velocity.Y = (float)(Math.Sin(rotation) * 25) * -1;
}
}
else npc.ai[2] = 0;
}
else {
npc.ai[3]++;
npc.alpha = 200;
npc.damage = 100;
npc.dontTakeDamage = true;
if (Main.player[npc.target].position.X < vector8.X) {
if (npc.velocity.X > -6) { npc.velocity.X -= 0.22f; }
}
if (Main.player[npc.target].position.X > vector8.X) {
if (npc.velocity.X < 6) { npc.velocity.X += 0.22f; }
}
if (Main.player[npc.target].position.Y < vector8.Y) {
if (npc.velocity.Y > 0f) npc.velocity.Y -= 0.8f;
else npc.velocity.Y -= 0.07f;
}
if (Main.player[npc.target].position.Y > vector8.Y) {
if (npc.velocity.Y < 0f) npc.velocity.Y += 0.8f;
else npc.velocity.Y += 0.07f;
}
if (npc.ai[3] == 100) {
npc.ai[3] = 1;
npc.life += 50;
if (npc.life > npc.lifeMax) npc.life = npc.lifeMax;
}
if (npc.ai[1] >= 0) {
npc.ai[3] = 0;
for (int num36 = 0; num36 < 40; num36++) {
Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 18, 0, 0, 0, default, 3f);
}
}
}
if (Main.player[npc.target].dead) {
npc.velocity.Y -= 0.04f;
if (npc.timeLeft > 10) {
npc.timeLeft = 0;
return;
}
}
}
public override void FindFrame(int currentFrame) {
int num = 1;
if (!Main.dedServ) {
num = Main.npcTexture[npc.type].Height / Main.npcFrameCount[npc.type];
}
if (npc.velocity.X < 0) {
npc.spriteDirection = -1;
}
else {
npc.spriteDirection = 1;
}
npc.rotation = npc.velocity.X * 0.08f;
npc.frameCounter += 1.0;
if (npc.frameCounter >= 4.0) {
npc.frame.Y = npc.frame.Y + num;
npc.frameCounter = 0.0;
}
if (npc.frame.Y >= num * Main.npcFrameCount[npc.type]) {
npc.frame.Y = 0;
}
if (npc.ai[3] == 0) {
npc.alpha = 0;
}
else {
npc.alpha = 200;
}
}
public override bool StrikeNPC(ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit) {
npc.ai[0] += (float)damage;
if (npc.ai[0] > 800) {
npc.ai[3] = 1;
Color color = new Color();
for (int num36 = 0; num36 < 50; num36++) {
int dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 4, 0, 0, 100, color, 3f);
}
for (int num36 = 0; num36 < 20; num36++) {
int dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 18, 0, 0, 100, color, 3f);
}
npc.ai[1] = -200;
npc.ai[0] = 0;
}
return true;
}
public override void NPCLoot() {
if (Main.expertMode) {
npc.DropBossBags();
}
else {
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.CrestOfEarth>(), 2);
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Accessories.WaterShoes>());
Item.NewItem(npc.getRect(), ItemID.Drax);
}
}
}
}
| 46.561856 | 247 | 0.463744 | [
"MIT"
] | W1K1/tsorcRevamp | NPCs/Bosses/TheHunter.cs | 9,035 | C# |
using System.ComponentModel.DataAnnotations;
using PaderbornUniversity.SILab.Hip.Achievements.Model.Entity;
namespace PaderbornUniversity.SILab.Hip.Achievements.Model.Rest.Achievements
{
public class RouteFinishedAchievementArgs : AchievementArgs
{
[Required]
public int? RouteId { get; set; }
public override Achievement CreateAchievement()
{
return new RouteFinishedAchievement(this);
}
}
}
| 27.058824 | 76 | 0.71087 | [
"Apache-2.0"
] | HiP-App/HiP-Achievements | HIP-Achievements.Model/Rest/Achievements/RouteFinishedAchievementArgs.cs | 462 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the eks-2017-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EKS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.EKS.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListTagsForResource operation
/// </summary>
public class ListTagsForResourceResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListTagsForResourceResponse response = new ListTagsForResourceResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("tags", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
response.Tags = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonEKSException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListTagsForResourceResponseUnmarshaller _instance = new ListTagsForResourceResponseUnmarshaller();
internal static ListTagsForResourceResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListTagsForResourceResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.403509 | 186 | 0.652353 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/EKS/Generated/Model/Internal/MarshallTransformations/ListTagsForResourceResponseUnmarshaller.cs | 4,378 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.CloudMine.Core.Collectors.Context;
using Microsoft.CloudMine.Core.Collectors.Error;
using Microsoft.CloudMine.Core.Collectors.Telemetry;
using Microsoft.CloudMine.Core.Collectors.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.CloudMine.Core.Collectors.IO
{
public abstract class RecordWriterCore<T> : IRecordWriter where T : FunctionContext
{
private readonly string identifier;
private readonly T functionContext;
private readonly ContextWriter<T> contextWriter;
private readonly long recordSizeLimit;
private readonly long fileSizeLimit;
private readonly List<string> outputPaths;
private readonly RecordWriterSource source;
private string outputPathPrefix;
private bool initialized;
private StreamWriter currentWriter;
private string currentOutputSuffix;
private int currentFileIndex;
protected ITelemetryClient TelemetryClient { get; private set; }
protected long SizeInBytes { get; private set; }
public ConcurrentDictionary<string, int> RecordStats { get; }
protected RecordWriterCore(string identifier,
ITelemetryClient telemetryClient,
T functionContext,
ContextWriter<T> contextWriter,
string outputPathPrefix,
long recordSizeLimit,
long fileSizeLimit,
RecordWriterSource source)
{
this.identifier = identifier;
this.TelemetryClient = telemetryClient;
this.functionContext = functionContext;
this.contextWriter = contextWriter;
this.outputPathPrefix = outputPathPrefix;
this.recordSizeLimit = recordSizeLimit;
this.fileSizeLimit = fileSizeLimit;
this.outputPaths = new List<string>();
this.currentFileIndex = 0;
this.source = source;
this.RecordStats = new ConcurrentDictionary<string, int>();
}
protected abstract Task InitializeInternalAsync();
protected abstract Task<StreamWriter> NewStreamWriterAsync(string suffix);
protected abstract Task NotifyCurrentOutputAsync();
public IEnumerable<string> OutputPaths => this.outputPaths;
protected void AddOutputPath(string outputPath)
{
this.outputPaths.Add(outputPath);
}
public void SetOutputPathPrefix(string outputPathPrefix)
{
this.outputPathPrefix = outputPathPrefix;
}
protected string OutputPathPrefix => this.GetOutputPathPrefix(this.functionContext.FunctionStartDate);
protected string GetOutputPathPrefix(DateTime dateTimeUtc)
{
return $"{this.outputPathPrefix}/{dateTimeUtc:yyyy/MM/dd/HH.mm.ss}_{this.identifier}_{this.functionContext.SessionId}";
}
private async Task InitializeAsync(string outputSuffix)
{
if (this.outputPathPrefix == null)
{
string message = "Cannot initialize record writer before the context is set.";
this.TelemetryClient.LogCritical(message);
throw new FatalTerminalException(message);
}
await this.InitializeInternalAsync().ConfigureAwait(false);
this.currentWriter = await this.NewStreamWriterAsync(outputSuffix).ConfigureAwait(false);
this.currentOutputSuffix = outputSuffix;
this.initialized = true;
}
public async Task NewOutputAsync(string outputSuffix, int fileIndex = 0)
{
if (this.initialized)
{
this.currentWriter.Dispose();
await this.NotifyCurrentOutputAsync().ConfigureAwait(false);
string finalSuffix = $"{(string.IsNullOrWhiteSpace(outputSuffix) ? "" : $"_{outputSuffix}")}{(fileIndex == 0 ? "" : $"_{fileIndex}")}";
this.currentWriter = await this.NewStreamWriterAsync(finalSuffix).ConfigureAwait(false);
this.currentOutputSuffix = outputSuffix;
}
else
{
await this.InitializeAsync($"_{outputSuffix}").ConfigureAwait(false);
}
}
public async Task WriteRecordAsync(JObject record, RecordContext recordContext)
{
if (!this.initialized)
{
await this.InitializeAsync(outputSuffix: string.Empty).ConfigureAwait(false);
}
// Augment the metadata to the record only if not done by another record writer.
JToken metadataToken = record.SelectToken("$.Metadata");
if (recordContext.MetadataAugmented)
{
// Confirm (double check) that this is case and fail execution if not.
if (metadataToken == null)
{
Dictionary<string, string> properties = new Dictionary<string, string>()
{
{ "RecordType", recordContext.RecordType },
{ "RecordMetadata", record.SelectToken("$.Metadata").ToString(Formatting.None) },
{ "RecordPrefix", record.ToString(Formatting.None).Substring(0, 1024) },
};
this.TelemetryClient.TrackEvent("RecordWithoutMetadata", properties);
throw new FatalTerminalException("Detected a record without metadata. Investigate 'RecordWithoutMetadata' custom event for details.");
}
}
else
{
this.AugmentRecordMetadata(record, recordContext);
this.AugmentRecord(record);
recordContext.MetadataAugmented = true;
}
// Add WriterSource to Metadata after the other metadata is augmented. This is because this value changes between writers and need to be updated before the record is emitted.
metadataToken = record.SelectToken("$.Metadata");
JObject metadataObject = (JObject)metadataToken;
JToken writerSourceToken = metadataObject.SelectToken("$.WriterSource");
if (writerSourceToken == null)
{
// This is the first time we are adding writer source.
metadataObject.Add("WriterSource", this.source.ToString());
}
else
{
// Override the existing value.
writerSourceToken.Replace(this.source.ToString());
}
string content = record.ToString(Formatting.None);
if (content.Length >= this.recordSizeLimit)
{
Dictionary<string, string> properties = new Dictionary<string, string>()
{
{ "RecordType", recordContext.RecordType },
{ "RecordMetadata", record.SelectToken("$.Metadata").ToString(Formatting.None) },
{ "RecordPrefix", content.Substring(0, 1024) },
};
this.TelemetryClient.TrackEvent("DroppedRecord", properties);
return;
}
this.SizeInBytes = this.currentWriter.BaseStream.Position;
// Check if the current file needs to be rolled over.
if (this.SizeInBytes > this.fileSizeLimit)
{
this.currentFileIndex++;
await this.NewOutputAsync(this.currentOutputSuffix, this.currentFileIndex).ConfigureAwait(false);
}
await this.currentWriter.WriteLineAsync(content).ConfigureAwait(false);
this.RegisterRecord(recordContext.RecordType);
}
private void RegisterRecord(string recordType)
{
if (!this.RecordStats.TryGetValue(recordType, out int recordCount))
{
recordCount = 0;
}
this.RecordStats[recordType] = recordCount + 1;
}
protected virtual void AugmentRecord(JObject record)
{
// Default implementation does not do anything.
}
public async Task FinalizeAsync()
{
if (!this.initialized)
{
return;
}
await this.NotifyCurrentOutputAsync().ConfigureAwait(false);
this.initialized = false;
}
public void Dispose()
{
if (!this.initialized)
{
TelemetryClient.LogWarning("RecordWriter.Dispose was called before RecordWriter was initialized. Ignoring the call.");
return;
}
this.currentWriter.Dispose();
}
private void AugmentRecordMetadata(JObject record, RecordContext recordContext)
{
string serializedRecord = record.ToString(Formatting.None);
JToken metadataToken = record.SelectToken("Metadata");
if (metadataToken == null)
{
metadataToken = new JObject();
record.AddFirst(new JProperty("Metadata", metadataToken));
}
JObject metadata = (JObject)metadataToken;
metadata.Add("FunctionStartDate", this.functionContext.FunctionStartDate);
metadata.Add("RecordType", recordContext.RecordType);
metadata.Add("SessionId", this.functionContext.SessionId);
metadata.Add("CollectorType", this.functionContext.CollectorType.ToString());
metadata.Add("CollectionDate", DateTime.UtcNow);
Dictionary<string, JToken> additionalMetadata = recordContext.AdditionalMetadata;
if (additionalMetadata != null)
{
foreach (KeyValuePair<string, JToken> metadataItem in additionalMetadata)
{
metadata.Add(metadataItem.Key, metadataItem.Value);
}
}
this.contextWriter.AugmentMetadata(metadata, this.functionContext);
metadata.Add("RecordSha", HashUtility.ComputeSha512(serializedRecord));
}
}
public static class RecordWriterExtensions
{
public static string GetOutputPaths(List<IRecordWriter> recordWriters)
{
string result = string.Join(";", recordWriters.Select(recordWriter => string.Join(";", recordWriter.OutputPaths)));
return result;
}
public static string GetOutputPaths(IRecordWriter recordWriter)
{
return GetOutputPaths(new List<IRecordWriter> { recordWriter });
}
}
public enum RecordWriterSource
{
AzureBlob = 0,
AzureDataLake = 1,
}
}
| 38.520833 | 186 | 0.601316 | [
"MIT"
] | dwhathaway/CEDAR.Core.Collector | Core.Collectors/IO/RecordWriterCore.cs | 11,096 | C# |
using System;
using System.Collections.Generic;
using Sfa.Tl.Matching.Data.UnitTests.Repositories.Constants;
namespace Sfa.Tl.Matching.Data.UnitTests.Repositories.EmailTemplate.Builders
{
public class ValidEmailTemplateListBuilder
{
public IList<Domain.Models.EmailTemplate> Build() => new List<Domain.Models.EmailTemplate>
{
new Domain.Models.EmailTemplate
{
Id = 1,
TemplateId = new Guid("1777EF96-70F5-4537-A6B1-41E8A0D8E0EC").ToString(),
TemplateName = "TestTemplate",
CreatedBy = EntityCreationConstants.CreatedByUser,
CreatedOn = EntityCreationConstants.CreatedOn,
ModifiedBy = EntityCreationConstants.ModifiedByUser,
ModifiedOn = EntityCreationConstants.ModifiedOn
},
new Domain.Models.EmailTemplate
{
Id = 2,
TemplateId = new Guid("02D150D6-BD64-4450-A82E-C67DFD5FAC09").ToString(),
TemplateName = "TestTemplate2",
CreatedBy = EntityCreationConstants.CreatedByUser,
CreatedOn = EntityCreationConstants.CreatedOn,
ModifiedBy = EntityCreationConstants.ModifiedByUser,
ModifiedOn = EntityCreationConstants.ModifiedOn
}
};
}
}
| 40.176471 | 98 | 0.622255 | [
"MIT"
] | uk-gov-mirror/SkillsFundingAgency.tl-matching | src/Sfa.Tl.Matching.Data.UnitTests/Repositories/EmailTemplate/Builders/ValidEmailTemplateListBuilder.cs | 1,368 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
#if NETCOREAPP2_0 || NETCOREAPP2_1
using Microsoft.Extensions.DependencyModel;
using System.Linq;
using IOPath = System.IO.Path;
#elif NET461
using System.Reflection;
#else
#error target frameworks need to be updated.
#endif
namespace Microsoft.EntityFrameworkCore.TestUtilities
{
public class BuildReference
{
private BuildReference(IEnumerable<MetadataReference> references, bool copyLocal = false, string path = null)
{
References = references;
CopyLocal = copyLocal;
Path = path;
}
public IEnumerable<MetadataReference> References { get; }
public bool CopyLocal { get; }
public string Path { get; }
public static BuildReference ByName(string name, bool copyLocal = false)
{
#if NET461
var assembly = Assembly.Load(name);
return new BuildReference(
new[] { MetadataReference.CreateFromFile(assembly.Location) },
copyLocal,
new Uri(assembly.CodeBase).LocalPath);
#elif NETCOREAPP2_0 || NETCOREAPP2_1
var references = Enumerable.ToList(
from l in DependencyContext.Default.CompileLibraries
from r in l.ResolveReferencePaths()
where IOPath.GetFileNameWithoutExtension(r) == name
select MetadataReference.CreateFromFile(r));
if (references.Count == 0)
{
throw new InvalidOperationException(
$"Assembly '{name}' not found.");
}
return new BuildReference(
references,
copyLocal);
#else
#error target frameworks need to be updated.
#endif
}
public static BuildReference ByPath(string path)
=> new BuildReference(new[] { MetadataReference.CreateFromFile(path) }, path: path);
}
}
| 32.784615 | 117 | 0.639137 | [
"Apache-2.0"
] | EasonDongH/EntityFrameworkCore | test/EFCore.Design.Tests/TestUtilities/BuildReference.cs | 2,131 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#nullable disable
using System.Text;
namespace Microsoft.DotNet.MSBuildSdkResolver
{
// Note: This is SemVer 2.0.0 https://semver.org/spec/v2.0.0.html
// See the original version of this code here: https://github.com/dotnet/core-setup/blob/master/src/corehost/cli/fxr/fx_ver.cpp
internal sealed class FXVersion
{
public int Major { get; }
public int Minor { get; }
public int Patch { get; }
public string Pre { get; }
public string Build { get; }
public FXVersion(int major, int minor, int patch, string pre = "", string build = "")
{
Major = major;
Minor = minor;
Patch = patch;
Pre = pre;
Build = build;
}
private static string GetId(string ids, int idStart)
{
int next = ids.IndexOf('.', idStart);
return next == -1 ? ids.Substring(idStart) : ids.Substring(idStart, next - idStart);
}
public static int Compare(FXVersion s1, FXVersion s2)
{
// compare(u.v.w-p+b, x.y.z-q+c)
if (s1.Major != s2.Major)
{
return s1.Major > s2.Major ? 1 : -1;
}
if (s1.Minor != s2.Minor)
{
return s1.Minor > s2.Minor ? 1 : -1;
}
if (s1.Patch != s2.Patch)
{
return s1.Patch > s2.Patch ? 1 : -1;
}
if (string.IsNullOrEmpty(s1.Pre) || string.IsNullOrEmpty(s2.Pre))
{
// Empty (release) is higher precedence than prerelease
return string.IsNullOrEmpty(s1.Pre) ? (string.IsNullOrEmpty(s2.Pre) ? 0 : 1) : -1;
}
// Both are non-empty (may be equal)
// First character of pre is '-' when it is not empty
// First idenitifier starts at position 1
int idStart = 1;
for (int i = idStart; true; ++i)
{
// C# strings are not null terminated. Pretend to make code similar to fx_ver.cpp
char s1char = (s1.Pre.Length == i) ? '\0' : s1.Pre[i];
char s2char = (s2.Pre.Length == i) ? '\0' : s2.Pre[i];
if (s1char != s2char)
{
// Found first character with a difference
if (s1char == '\0' && s2char == '.')
{
// identifiers both complete, b has an additional identifier
return -1;
}
if (s2char == '\0' && s1char == '.')
{
// identifiers both complete, a has an additional identifier
return 1;
}
// identifiers must not be empty
string id1 = GetId(s1.Pre, idStart);
string id2 = GetId(s2.Pre, idStart);
int id1num = 0;
bool id1IsNum = int.TryParse(id1, out id1num);
int id2num = 0;
bool id2IsNum = int.TryParse(id2, out id2num);
if (id1IsNum && id2IsNum)
{
// Numeric comparison
return (id1num > id2num) ? 1 : -1;
}
else if (id1IsNum || id2IsNum)
{
// Mixed compare. Spec: Number < Text
return id2IsNum ? 1 : -1;
}
// Ascii compare
// Since we are using only ascii characters, unicode ordinal sort == ascii sort
return (s1char > s2char) ? 1 : -1;
}
else
{
// s1char == s2char
if (s1char == '\0')
{
break;
}
if (s1char == '.')
{
idStart = i + 1;
}
}
}
return 0;
}
private static bool ValidIdentifierCharSet(string id)
{
// ids must be of the set [0-9a-zA-Z-]
// ASCII and Unicode ordering
for (int i = 0; i < id.Length; ++i)
{
if (id[i] >= 'A')
{
if ((id[i] > 'Z' && id[i] < 'a') || id[i] > 'z')
{
return false;
}
}
else
{
if ((id[i] < '0' && id[i] != '-') || id[i] > '9')
{
return false;
}
}
}
return true;
}
private static bool ValidIdentifier(string id, bool buildMeta)
{
if (string.IsNullOrEmpty(id))
{
// Identifier must not be empty
return false;
}
if (!ValidIdentifierCharSet(id))
{
// ids must be of the set [0-9a-zA-Z-]
return false;
}
int ignored;
if (!buildMeta && id[0] == '0' && id.Length > 1 && int.TryParse(id, out ignored))
{
// numeric identifiers must not be padded with 0s
return false;
}
return true;
}
private static bool ValidIdentifiers(string ids)
{
if (string.IsNullOrEmpty(ids))
{
return true;
}
bool prerelease = ids[0] == '-';
bool buildMeta = ids[0] == '+';
if (!(prerelease || buildMeta))
{
// ids must start with '-' or '+' for prerelease & build respectively
return false;
}
int idStart = 1;
int nextId;
while ((nextId = ids.IndexOf('.', idStart)) != -1)
{
if (!ValidIdentifier(ids.Substring(idStart, nextId - idStart), buildMeta))
{
return false;
}
idStart = nextId + 1;
}
if (!ValidIdentifier(ids.Substring(idStart), buildMeta))
{
return false;
}
return true;
}
private static int IndexOfNonNumeric(string s, int startIndex)
{
for (int i = startIndex; i < s.Length; ++i)
{
if ((s[i] < '0') || (s[i] > '9'))
{
return i;
}
}
return -1;
}
public static bool TryParse(string fxVersionString, out FXVersion FXVersion)
{
FXVersion = null;
if (string.IsNullOrEmpty(fxVersionString))
{
return false;
}
int majorSeparator = fxVersionString.IndexOf(".");
if (majorSeparator == -1)
{
return false;
}
int major = 0;
if (!int.TryParse(fxVersionString.Substring(0, majorSeparator), out major))
{
return false;
}
if (majorSeparator > 1 && fxVersionString[0] == '0')
{
// if leading character is 0, and strlen > 1
// then the numeric substring has leading zeroes which is prohibited by the specification.
return false;
}
int minorStart = majorSeparator + 1;
int minorSeparator = fxVersionString.IndexOf(".", minorStart);
if (minorSeparator == -1)
{
return false;
}
int minor = 0;
if (
!int.TryParse(
fxVersionString.Substring(minorStart, minorSeparator - minorStart),
out minor
)
) {
return false;
}
if (minorSeparator - minorStart > 1 && fxVersionString[minorStart] == '0')
{
// if leading character is 0, and strlen > 1
// then the numeric substring has leading zeroes which is prohibited by the specification.
return false;
}
int patch = 0;
int patchStart = minorSeparator + 1;
int patchSeparator = IndexOfNonNumeric(fxVersionString, patchStart);
if (patchSeparator == -1)
{
if (!int.TryParse(fxVersionString.Substring(patchStart), out patch))
{
return false;
}
if (patchStart + 1 < fxVersionString.Length && fxVersionString[patchStart] == '0')
{
// if leading character is 0, and strlen != 1
// then the numeric substring has leading zeroes which is prohibited by the specification.
return false;
}
FXVersion = new FXVersion(major, minor, patch);
return true;
}
if (
!int.TryParse(
fxVersionString.Substring(patchStart, patchSeparator - patchStart),
out patch
)
) {
return false;
}
if (patchSeparator - patchStart > 1 && fxVersionString[patchStart] == '0')
{
return false;
}
int preStart = patchSeparator;
int preSeparator = fxVersionString.IndexOf("+", preStart);
string pre =
(preSeparator == -1)
? fxVersionString.Substring(preStart)
: fxVersionString.Substring(preStart, preSeparator - preStart);
if (!ValidIdentifiers(pre))
{
return false;
}
string build = "";
if (preSeparator != -1)
{
build = fxVersionString.Substring(preSeparator);
if (!ValidIdentifiers(build))
{
return false;
}
}
FXVersion = new FXVersion(major, minor, patch, pre, build);
return true;
}
public override string ToString() =>
(!string.IsNullOrEmpty(Pre), !string.IsNullOrEmpty(Build)) switch
{
(false, false) => $"{Major}.{Minor}.{Patch}",
(true, false) => $"{Major}.{Minor}.{Patch}{Pre}",
(false, true) => $"{Major}.{Minor}.{Patch}{Build}",
(true, true) => $"{Major}.{Minor}.{Patch}{Pre}{Build}",
};
}
}
| 32.652941 | 131 | 0.428842 | [
"MIT"
] | belav/sdk | src/Resolvers/Microsoft.DotNet.MSBuildSdkResolver/FXVersion.cs | 11,102 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class TestMain : MonoBehaviour {
private List<Item> listItem;
private UIWarpContent warpContent;
void Start () {
//测试数据
listItem = new List<Item> ();
for (int i = 0; i < 50; i++) {
listItem.Add (new Item("测试:"+Random.Range(1,1000)));
}
//scrollView 相关所需注意接口
warpContent = gameObject.transform.GetComponentInChildren<UIWarpContent> ();
warpContent.onInitializeItem = onInitializeItem;
//注意:目标init方法必须在warpContent.onInitializeItem之后
warpContent.Init (listItem.Count);
}
private void onInitializeItem(GameObject go,int dataIndex){
// Debug.Log ("go = "+go.name+"_dataIndex = "+dataIndex);
Text text = go.transform.Find ("Text").GetComponent<Text>();
text.text = "i:" + dataIndex+"_N:"+listItem[dataIndex].Name();
//add按钮监听【添加功能】
Button addbutton = go.transform.Find ("Add").GetComponent<Button> ();
addbutton.onClick.RemoveAllListeners ();
addbutton.onClick.AddListener (delegate() {
listItem.Insert(dataIndex+1,new Item("Insert"+Random.Range(1,1000)));
warpContent.AddItem(dataIndex+1);
});
//sub按钮监听【删除功能】
Button subButton = go.transform.Find ("Sub").GetComponent<Button> ();
subButton.onClick.RemoveAllListeners ();
subButton.onClick.AddListener (delegate() {
listItem.RemoveAt(dataIndex);
warpContent.DelItem(dataIndex);
});
}
//测试数据结构
public class Item{
private string name;
public Item(string name){
this.name = name;
}
public string Name(){
return name;
}
public void destroy(){
name = null;
}
}
}
| 24.454545 | 78 | 0.701983 | [
"Apache-2.0"
] | Lenovezhou/Tool | Assets/Scripts/InfinityItem/TestMain.cs | 1,720 | C# |
//-----------------------------------------------------------------------
// <copyright file="AggregateProjectionTransformer.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Tests.Query.OfflineEngine
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.CosmosElements.Numbers;
using Microsoft.Azure.Cosmos.SqlObjects;
using Microsoft.Azure.Cosmos.SqlObjects.Visitors;
using Newtonsoft.Json.Linq;
/// <summary>
/// Transforms a projection with an aggregate to be rewritten with the result.
/// For example if the projection is SELECT SQUARE(AVG(c.age))
/// it might be rewritten as SELECT SQUARE(43)
/// And this is because aggregates need to enter a separate pipeline compared to all other queries.
/// </summary>
internal sealed class AggregateProjectionTransformer
{
private static readonly CosmosNumber Undefined = null;
private readonly AggregateProjectionTransformerVisitor visitor;
public AggregateProjectionTransformer(
IEnumerable<CosmosElement> dataSource)
{
this.visitor = new AggregateProjectionTransformerVisitor(dataSource);
}
public SqlSelectSpec TransformAggregatesInProjection(SqlSelectSpec selectSpec)
{
return selectSpec.Accept(this.visitor);
}
private sealed class AggregateProjectionTransformerVisitor : SqlSelectSpecVisitor<SqlSelectSpec>
{
private readonly AggregateScalarExpressionTransformer scalarExpressionTransformer;
public AggregateProjectionTransformerVisitor(IEnumerable<CosmosElement> dataSource)
{
this.scalarExpressionTransformer = new AggregateScalarExpressionTransformer(dataSource);
}
public override SqlSelectSpec Visit(SqlSelectListSpec selectSpec)
{
List<SqlSelectItem> selectItems = new List<SqlSelectItem>();
foreach (SqlSelectItem selectItem in selectSpec.Items)
{
selectItems.Add(SqlSelectItem.Create(
selectItem.Expression.Accept(this.scalarExpressionTransformer),
selectItem.Alias));
}
return SqlSelectListSpec.Create(selectItems.ToImmutableArray());
}
public override SqlSelectSpec Visit(SqlSelectStarSpec selectSpec)
{
return selectSpec;
}
public override SqlSelectSpec Visit(SqlSelectValueSpec selectSpec)
{
return SqlSelectValueSpec.Create(selectSpec.Expression.Accept(this.scalarExpressionTransformer));
}
private sealed class AggregateScalarExpressionTransformer : SqlScalarExpressionVisitor<SqlScalarExpression>
{
private readonly IEnumerable<CosmosElement> dataSource;
public AggregateScalarExpressionTransformer(IEnumerable<CosmosElement> dataSource)
{
this.dataSource = dataSource;
}
public override SqlScalarExpression Visit(SqlArrayCreateScalarExpression sqlArrayCreateScalarExpression)
{
List<SqlScalarExpression> items = new List<SqlScalarExpression>();
foreach (SqlScalarExpression item in sqlArrayCreateScalarExpression.Items)
{
items.Add(item.Accept(this));
}
return SqlArrayCreateScalarExpression.Create(items.ToImmutableArray());
}
public override SqlScalarExpression Visit(SqlArrayScalarExpression sqlArrayScalarExpression)
{
// No need to worry about aggregates in the subquery (they will recursively get rewritten).
return sqlArrayScalarExpression;
}
public override SqlScalarExpression Visit(SqlBetweenScalarExpression sqlBetweenScalarExpression)
{
return SqlBetweenScalarExpression.Create(
sqlBetweenScalarExpression.Expression.Accept(this),
sqlBetweenScalarExpression.StartInclusive.Accept(this),
sqlBetweenScalarExpression.EndInclusive.Accept(this),
sqlBetweenScalarExpression.Not);
}
public override SqlScalarExpression Visit(SqlBinaryScalarExpression sqlBinaryScalarExpression)
{
return SqlBinaryScalarExpression.Create(
sqlBinaryScalarExpression.OperatorKind,
sqlBinaryScalarExpression.LeftExpression.Accept(this),
sqlBinaryScalarExpression.RightExpression.Accept(this));
}
public override SqlScalarExpression Visit(SqlCoalesceScalarExpression sqlCoalesceScalarExpression)
{
return SqlCoalesceScalarExpression.Create(
sqlCoalesceScalarExpression.Left.Accept(this),
sqlCoalesceScalarExpression.Right.Accept(this));
}
public override SqlScalarExpression Visit(SqlConditionalScalarExpression sqlConditionalScalarExpression)
{
return SqlConditionalScalarExpression.Create(
sqlConditionalScalarExpression.Condition.Accept(this),
sqlConditionalScalarExpression.Consequent.Accept(this),
sqlConditionalScalarExpression.Alternative.Accept(this));
}
public override SqlScalarExpression Visit(SqlExistsScalarExpression sqlExistsScalarExpression)
{
// No need to worry about aggregates within the subquery (they will recursively get rewritten).
return sqlExistsScalarExpression;
}
public override SqlScalarExpression Visit(SqlFunctionCallScalarExpression sqlFunctionCallScalarExpression)
{
SqlScalarExpression rewrittenExpression;
// If the function call is an aggregate just evaluate the aggregate first and return that
if (
!sqlFunctionCallScalarExpression.IsUdf &&
Enum.TryParse(value: sqlFunctionCallScalarExpression.Name.Value, ignoreCase: true, result: out Aggregate aggregate))
{
IReadOnlyList<SqlScalarExpression> arguments = sqlFunctionCallScalarExpression.Arguments;
if (arguments.Count != 1)
{
throw new ArgumentException("Aggregates only accept one argument.");
}
IEnumerable<CosmosElement> results = this.dataSource
.Select((element) => arguments[0].Accept(
ScalarExpressionEvaluator.Singleton,
element));
// If aggregates are pushed to the index, then we only get back defined results
results = results.Where((result) => result != Undefined);
CosmosElement aggregationResult;
switch (aggregate)
{
case Aggregate.Min:
case Aggregate.Max:
if (results.Count() == 0)
{
aggregationResult = Undefined;
}
else if (results.Any(result => !Utils.IsPrimitive(result)))
{
aggregationResult = Undefined;
}
else
{
aggregationResult = results.First();
foreach (CosmosElement result in results)
{
// First compare the types
int comparison = result.CompareTo(aggregationResult);
if (aggregate == Aggregate.Min)
{
if (comparison < 0)
{
aggregationResult = result;
}
}
else if (aggregate == Aggregate.Max)
{
if (comparison > 0)
{
aggregationResult = result;
}
}
else
{
throw new InvalidOperationException("Should not get here");
}
}
}
break;
case Aggregate.Avg:
case Aggregate.Sum:
CosmosNumber sum = CosmosNumber64.Create(0);
double count = 0;
foreach (CosmosElement result in results)
{
if ((result is CosmosNumber resultAsNumber) && (sum != Undefined))
{
sum = CosmosNumber64.Create(Number64.ToDouble(sum.Value) + Number64.ToDouble(resultAsNumber.Value));
count++;
}
else
{
sum = Undefined;
}
}
if (sum != Undefined)
{
if (aggregate == Aggregate.Avg)
{
if (count == 0)
{
aggregationResult = Undefined;
}
else
{
aggregationResult = CosmosNumber64.Create(Number64.ToDouble(sum.Value) / count);
}
}
else
{
aggregationResult = CosmosNumber64.Create(Number64.ToDouble(sum.Value));
}
}
else
{
aggregationResult = Undefined;
}
break;
case Aggregate.Count:
aggregationResult = CosmosNumber64.Create(results.Count());
break;
default:
throw new ArgumentException($"Unknown {nameof(Aggregate)} {aggregate}");
}
if(aggregationResult != Undefined)
{
rewrittenExpression = aggregationResult.Accept(CosmosElementToSqlScalarExpression.Singleton);
}
else
{
rewrittenExpression = SqlLiteralScalarExpression.Create(SqlUndefinedLiteral.Create());
}
}
else
{
// Just a regular function call
rewrittenExpression = SqlFunctionCallScalarExpression.Create(
sqlFunctionCallScalarExpression.Name,
sqlFunctionCallScalarExpression.IsUdf,
sqlFunctionCallScalarExpression.Arguments);
}
return rewrittenExpression;
}
public override SqlScalarExpression Visit(SqlInScalarExpression sqlInScalarExpression)
{
SqlScalarExpression[] items = new SqlScalarExpression[sqlInScalarExpression.Haystack.Length];
for (int i = 0; i < sqlInScalarExpression.Haystack.Length; i++)
{
items[i] = sqlInScalarExpression.Haystack[i].Accept(this);
}
return SqlInScalarExpression.Create(
sqlInScalarExpression.Needle.Accept(this),
sqlInScalarExpression.Not,
items);
}
public override SqlScalarExpression Visit(SqlLikeScalarExpression sqlLikeScalarExpression)
{
return sqlLikeScalarExpression;
}
public override SqlScalarExpression Visit(SqlLiteralScalarExpression sqlLiteralScalarExpression)
{
return sqlLiteralScalarExpression;
}
public override SqlScalarExpression Visit(SqlMemberIndexerScalarExpression sqlMemberIndexerScalarExpression)
{
return SqlMemberIndexerScalarExpression.Create(
sqlMemberIndexerScalarExpression.Member.Accept(this),
sqlMemberIndexerScalarExpression.Indexer.Accept(this));
}
public override SqlScalarExpression Visit(SqlObjectCreateScalarExpression sqlObjectCreateScalarExpression)
{
List<SqlObjectProperty> properties = new List<SqlObjectProperty>();
foreach (SqlObjectProperty property in sqlObjectCreateScalarExpression.Properties)
{
properties.Add(SqlObjectProperty.Create(property.Name, property.Value.Accept(this)));
}
return SqlObjectCreateScalarExpression.Create(properties.ToImmutableArray());
}
public override SqlScalarExpression Visit(SqlParameterRefScalarExpression scalarExpression)
{
return scalarExpression;
}
public override SqlScalarExpression Visit(SqlPropertyRefScalarExpression sqlPropertyRefScalarExpression)
{
return SqlPropertyRefScalarExpression.Create(
sqlPropertyRefScalarExpression.Member?.Accept(this),
sqlPropertyRefScalarExpression.Identifier);
}
public override SqlScalarExpression Visit(SqlSubqueryScalarExpression sqlSubqueryScalarExpression)
{
// No need to worry about the aggregates within the subquery since they get recursively evaluated.
return sqlSubqueryScalarExpression;
}
public override SqlScalarExpression Visit(SqlUnaryScalarExpression sqlUnaryScalarExpression)
{
return SqlUnaryScalarExpression.Create(
sqlUnaryScalarExpression.OperatorKind,
sqlUnaryScalarExpression.Expression.Accept(this));
}
}
}
private sealed class CosmosElementToSqlScalarExpression : ICosmosElementVisitor<SqlScalarExpression>
{
public static readonly CosmosElementToSqlScalarExpression Singleton = new CosmosElementToSqlScalarExpression();
private CosmosElementToSqlScalarExpression()
{
}
public SqlScalarExpression Visit(CosmosArray cosmosArray)
{
List<SqlScalarExpression> items = new List<SqlScalarExpression>();
foreach (CosmosElement arrayItem in cosmosArray)
{
items.Add(arrayItem.Accept(this));
}
return SqlArrayCreateScalarExpression.Create(items.ToImmutableArray());
}
public SqlScalarExpression Visit(CosmosBinary cosmosBinary)
{
throw new NotImplementedException();
}
public SqlScalarExpression Visit(CosmosBoolean cosmosBoolean)
{
SqlBooleanLiteral literal = SqlBooleanLiteral.Create(cosmosBoolean.Value);
return SqlLiteralScalarExpression.Create(literal);
}
public SqlScalarExpression Visit(CosmosGuid cosmosGuid)
{
throw new NotImplementedException();
}
public SqlScalarExpression Visit(CosmosNull cosmosNull)
{
SqlNullLiteral literal = SqlNullLiteral.Singleton;
return SqlLiteralScalarExpression.Create(literal);
}
public SqlScalarExpression Visit(CosmosNumber cosmosNumber)
{
SqlNumberLiteral literal = SqlNumberLiteral.Create(cosmosNumber.Value);
return SqlLiteralScalarExpression.Create(literal);
}
public SqlScalarExpression Visit(CosmosObject cosmosObject)
{
List<SqlObjectProperty> properties = new List<SqlObjectProperty>();
foreach (KeyValuePair<string, CosmosElement> kvp in cosmosObject)
{
SqlPropertyName name = SqlPropertyName.Create(kvp.Key);
CosmosElement value = kvp.Value;
SqlScalarExpression expression = value.Accept(this);
SqlObjectProperty property = SqlObjectProperty.Create(name, expression);
properties.Add(property);
}
return SqlObjectCreateScalarExpression.Create(properties.ToImmutableArray());
}
public SqlScalarExpression Visit(CosmosString cosmosString)
{
SqlStringLiteral literal = SqlStringLiteral.Create(cosmosString.Value);
return SqlLiteralScalarExpression.Create(literal);
}
}
}
}
| 46.586538 | 140 | 0.508101 | [
"MIT"
] | Arithmomaniac/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/Query/OfflineEngine/AggregateProjectionTransformer.cs | 19,382 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCompiler.Tokenizer;
namespace CCompiler.SemanticAnalysis
{
public class Table<T>
{
private Dictionary<string, T> _members;
public Table()
{
_members = new Dictionary<string, T>();
}
public void Push(string id, T member) => _members.Add(id, member);
public bool Exist(string id) => _members.ContainsKey(id);
public T Get(string id) => _members[id];
public override string ToString()
{
var result = new StringBuilder();
foreach (var member in _members)
result.Append($"{member.Value}\n");
return result.Length == 0 ? "{ }" : "{\n" + Utils.AddTab(result.ToString(0, result.Length - 1)) + "}";
}
public Dictionary<string, T> GetData() => _members;
public override bool Equals(object? obj)
{
if (!(obj is Table<T> table)) return false;
var currentMembers = _members.ToList();
var otherMembers = table._members.ToList();
if (currentMembers.Count != otherMembers.Count)
return false;
for (var i = 0; i < currentMembers.Count; i++)
if (currentMembers[i].Value.Equals(otherMembers[i].Value) == false)
return false;
return true;
}
}
} | 31.391304 | 114 | 0.554709 | [
"MIT"
] | ALMikhai/CCompiler | CCompiler/SemanticAnalysis/SymbolTable.cs | 1,446 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Configuration;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.contentitem;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.language;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.DataLayer;
using umbraco.cms.presentation.Trees;
using umbraco.BusinessLogic.Utils;
using umbraco.BusinessLogic.Actions;
using Umbraco.Core.IO;
using Umbraco.Core;
namespace umbraco
{
/// <summary>
/// Handles loading of the xslt files into the application tree
/// </summary>
[Tree(Constants.Applications.Developer, "xslt", "XSLT Files", sortOrder: 5)]
public class loadXslt : FileSystemTree
{
public loadXslt(string application) : base(application) { }
protected override void CreateRootNode(ref XmlTreeNode rootNode)
{
rootNode.NodeType = "init" + TreeAlias;
rootNode.NodeID = "init";
}
/// <summary>
/// Renders the Javascript
/// </summary>
/// <param name="Javascript">The javascript.</param>
public override void RenderJS(ref StringBuilder Javascript)
{
Javascript.Append(
@"
function openXslt(id) {
UmbClientMgr.contentFrame('developer/xslt/editXslt.aspx?file=' + id);
}
");
}
protected override string FilePath
{
get { return SystemDirectories.Xslt + "/"; }
}
protected override string FileSearchPattern
{
get { return "*.xslt"; }
}
protected override void OnRenderFileNode(ref XmlTreeNode xNode)
{
xNode.Action = xNode.Action.Replace("openFile", "openXslt");
xNode.Icon = "icon-code";
xNode.OpenIcon = "icon-code";
}
protected override void OnRenderFolderNode(ref XmlTreeNode xNode)
{
xNode.Menu = new List<IAction>(new IAction[] { ActionDelete.Instance, ContextMenuSeperator.Instance, ActionRefresh.Instance });
xNode.NodeType = "xsltFolder";
}
}
}
| 29.534884 | 140 | 0.658661 | [
"MIT"
] | ConnectionMaster/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadXslt.cs | 2,542 | C# |
using System;
using UnityEditor;
using UnityEngine;
namespace Instech.NodeEditor
{
public class ConnectionLine
{
public NodePort FromPort { get; private set; }
public NodePort ToPort { get; private set; }
private Action<ConnectionLine> _onClickRemoveLine;
public ConnectionLine(NodePort from, NodePort to, Action<ConnectionLine> onClickRemoveLine)
{
FromPort = from;
ToPort = to;
_onClickRemoveLine = onClickRemoveLine;
}
public void Draw()
{
Handles.DrawBezier(
FromPort.Rect.center,
ToPort.Rect.center,
FromPort.Rect.center + Vector2.right * 50f,
ToPort.Rect.center + Vector2.left * 50f,
Color.white,
null,
2f
);
if (Handles.Button((FromPort.Rect.center + ToPort.Rect.center) * 0.5f,
Quaternion.identity, 4, 8, Handles.RectangleHandleCap))
{
_onClickRemoveLine?.Invoke(this);
}
}
}
}
| 27.85 | 99 | 0.547576 | [
"Apache-2.0"
] | inspoy/NodeFlowEditor | Editor/ConnectionLine.cs | 1,114 | C# |
using System;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
namespace Burst.Compiler.IL.Tests
{
internal class ControlFlows
{
[TestCompiler(ExpectCompilerException = true, ExpectedDiagnosticIds = new[] { DiagnosticId.ERR_TryConstructionNotSupported, DiagnosticId.ERR_InstructionLeaveNotSupported })]
public static int TryCatch()
{
try
{
return default(int);
}
catch (InvalidOperationException)
{
return 1;
}
}
[TestCompiler]
public static int For()
{
var counter = 0;
for (var i = 0; i < 10; i++)
counter++;
return counter;
}
[TestCompiler(10)]
public static int ForBreak(int a)
{
int result = 0;
for (int i = 0; i < a; i++)
{
if (i == 5)
{
break;
}
result += 2;
}
return result;
}
[TestCompiler(10, 5)]
public static int ForContinue(int a, int b)
{
int result = 0;
for (int i = 0; i < a; i++)
{
if (i == b)
{
continue;
}
result += i;
}
return result;
}
[TestCompiler]
public static int ForBreak2()
{
int i = 0;
while (true)
{
if (i == 5)
{
break;
}
i++;
}
return i;
}
[TestCompiler(10)]
public static float ForDynamicCondition(ref int b)
{
var counter = 0.0f;
for (var i = 0; i < b; i++)
counter++;
return counter;
}
[TestCompiler(5, 5)]
public static int ForNestedIf(int a, int b)
{
var counter = 0;
for (var i = 0; i < a; i++)
for (var i2 = 0; i != b; i++)
{
counter += i;
counter += i2;
}
return counter;
}
[TestCompiler(5, 5)]
public static int DoWhileNested(int a, int b)
{
var total = 0;
var counter2 = 0;
do
{
var counter1 = 0;
do
{
total++;
counter1++;
} while (counter1 < a);
counter2++;
} while (counter2 < b);
return total;
}
[TestCompiler(5)]
public static int While(int a)
{
var i = 0;
var counter = 0;
while (i < a)
{
i++;
counter += i;
}
return counter;
}
[TestCompiler(5)]
public static int ForForIf(int a)
{
var counter = 0;
for (var i = 0; i != a; i++)
for (var j = 0; j < 4; j++)
if (j > 2)
counter = counter + i;
return counter;
}
[TestCompiler(5)]
public static int ForNestedComplex1(int a)
{
var x = 0;
var y = 0;
for (var i = 0; i < a; i++)
{
y = y + 1;
for (var j = 0; j < 4; j++)
{
if (y > 1)
{
x = x + i;
if (x > 2)
{
for (int k = 0; k < 3; k++)
{
y = y + 1;
if (y > 3)
{
x = x + 1;
}
else if (x > 6)
{
y = 1;
break;
}
}
}
else
{
continue;
}
}
else
{
x--;
}
x++;
}
if (y > 2)
{
x = x + 1;
}
}
return x;
}
[TestCompiler(5)]
public static int ForNestedComplex2(int a)
{
var x = 0;
for (var i = 0; i < a; i++)
{
var insideLoop1 = 0;
for (var j = 0; j < 4; j++)
{
x = x + i;
if (x > 2)
{
insideLoop1++;
for (int k = 0; k < 3; k++)
{
if (insideLoop1 > 3)
{
x = x + 1;
}
else if (x > 6)
{
break;
}
}
}
}
if (insideLoop1 > 2)
{
x = x + 1 + insideLoop1;
}
}
return x;
}
[TestCompiler(5)]
[TestCompiler(-5)]
public static int IfReturn(int a)
{
if (a < 0)
return 55;
return 111;
}
[TestCompiler(5)]
[TestCompiler(-5)]
public static int IfElseReturn(int a)
{
int b = 0;
if (a < 0)
{
b = 1;
}
else
{
b = 2;
}
return b;
}
[TestCompiler(5)]
[TestCompiler(-5)]
public static int IfElseReturnDynamic(int a)
{
int b;
if (a < 0)
{
b = a;
}
else
{
b = a + 1;
}
return b;
}
[TestCompiler(10)]
public static int WhileFunction(int a)
{
while (condition_helper(a))
{
a--;
}
return a;
}
[TestCompiler(10)]
public static int WhileDynamic(ref int a)
{
while (a > 2)
{
a--;
}
return a;
}
[TestCompiler(5, 6, 7)]
[TestCompiler(-5, -6, -7)]
public static int IfDeep(int a, int b, int c)
{
int result = 0;
if (a < 0)
{
if (b > 1)
{
if (c < 2)
{
result = 55;
}
else
{
result = 66;
}
}
else
{
result = 77;
}
}
else
{
if (b < 0)
{
if (c < -2)
{
result = 88;
}
else
{
result = 99;
}
}
else
{
result = 100;
}
}
return result;
}
[TestCompiler(5)]
public static int CallRecursive(int n)
{
return InternalCallRecursive(n);
}
private static int InternalCallRecursive(int n)
{
if (n <= 1)
return 1;
return n * InternalCallRecursive(n - 1);
}
[TestCompiler(3f, 8f)]
[TestCompiler(6f, 8f)]
public static float IfCompareFloat(float a, float b)
{
if (a > 5f)
return 10f;
return b;
}
[TestCompiler(10)]
[TestCompiler(0)]
public static float TernaryCompareFloat(int input)
{
return input > 5 ? 2.5f : 1.2F;
}
[TestCompiler(0)]
[TestCompiler(1)]
public static int TernaryMask(int a)
{
return (a & 1) != 0 ? 5 : 4;
}
[TestCompiler(0)]
[TestCompiler(1)]
public static int IfElseMash(int a)
{
if ((a & 1) != 0)
return 5;
else
return 4;
}
[TestCompiler(0)]
public static int IfCallCondition(int a)
{
if (a > 0 && condition_helper(++a))
{
return a;
}
return -10 + a;
}
[TestCompiler(1)]
[TestCompiler(0)]
[TestCompiler(-1)]
public static int IfIncrementCondition(int a)
{
if (a < 0 || condition_helper(++a))
{
return a;
}
return -10 + a;
}
private static bool condition_helper(int value)
{
return value > 2;
}
[TestCompiler(1, 8)]
public static int IfWhileGotoForward(int a, int b)
{
if (a > 0)
{
while (a < 10)
{
a++;
if (a == b)
{
a--;
goto TestLabel;
}
}
a++;
}
TestLabel:
a--;
return a;
}
[TestCompiler(1, 5)]
public static int IfWhileGotoBackward(int a, int b)
{
RewindLabel:
if (a > 0)
{
while (a < 10)
{
a++;
if (a == b)
{
a++;
goto RewindLabel;
}
}
a++;
}
a--;
return a;
}
[TestCompiler(-1, 0)]
[TestCompiler(0, 0)]
[TestCompiler(0, -1)]
public static int IfAssignCondition(int a, int b)
{
int result = 0;
if (++a > 0 && ++b > 0)
{
result = a + b;
}
else
{
result = a * 10 + b;
}
return result;
}
private static bool ProcessFirstInt(int a, out float b)
{
b = a + 1;
return b < 10;
}
private static bool ProcessNextInt(int a, ref float b)
{
b = a + 2;
return b < 20;
}
[TestCompiler(1, 10)]
public static float ForWhileNestedCall(int a, int b)
{
float value = 0;
for (int i = 0; i < b * 3; i++)
{
var flag = ProcessFirstInt(a, out value);
int num2 = 0;
while (flag && num2 < 2)
{
bool flag2 = i == a;
if (flag2)
{
flag = ProcessNextInt(a + i, ref value);
}
else
{
value++;
flag = ProcessNextInt(a + b + i, ref value);
}
num2++;
}
}
return value;
}
#if BURST_TESTS_ONLY
[TestCompiler(true)]
[TestCompiler(false)]
public static bool CheckDup(bool value)
{
return ILTestsHelper.CheckDupBeforeJump(value);
}
#endif
[TestCompiler(1)]
public static int WhileIfContinue(int a)
{
while (a > 10)
{
if (a < 5)
{
a++;
if (a == 8)
{
continue;
}
}
a++;
}
return a;
}
[TestCompiler(ExpectCompilerException = true, ExpectedDiagnosticIds = new[] { DiagnosticId.ERR_TryConstructionNotSupported, DiagnosticId.ERR_InstructionEndfinallyNotSupported })]
public static int ForEachDispose()
{
var array = new NativeArray<int>();
foreach (var item in array)
{
return item;
}
return 0;
}
[TestCompiler(0)]
[TestCompiler(1)]
[TestCompiler(2)]
[TestCompiler(3)]
[TestCompiler(4)]
public static int SwitchReturn(int a)
{
switch (a)
{
case 1:
return 100;
case 2:
return 200;
case 3:
return 300;
case 10:
return 300;
default:
return 1000;
}
}
[TestCompiler(0)]
[TestCompiler(1)]
[TestCompiler(2)]
[TestCompiler(3)]
[TestCompiler(4)]
public static int SwitchBreak(int a)
{
switch (a)
{
case 1:
return 100;
case 2:
break;
default:
return 1000;
}
return 200;
}
[TestCompiler((byte)0)]
[TestCompiler((byte)1)]
[TestCompiler((byte)2)]
[TestCompiler((byte)3)]
[TestCompiler((byte)4)]
public static int SwitchBreakByte(byte a)
{
switch (a)
{
case 1:
return 100;
case 2:
break;
default:
return 1000;
}
return 200;
}
public static byte GetValueAsByte(int a)
{
return (byte)a;
}
[TestCompiler(0)]
[TestCompiler(1)]
[TestCompiler(2)]
[TestCompiler(3)]
public static byte SwitchByteReturnFromFunction(int a)
{
switch (GetValueAsByte(a))
{
case 0:
return 1;
case 1:
return 2;
case 2:
return 3;
default:
return 0;
}
}
[TestCompiler(long.MaxValue)]
[TestCompiler(long.MinValue)]
[TestCompiler(0)]
public static byte SwitchOnLong(long a)
{
switch (a)
{
case long.MaxValue:
return 1;
case long.MinValue:
return 2;
default:
return 0;
}
}
public static byte TestSwitchByteReturn(NativeArray<byte> _results, int a)
{
if (_results.Length > a)
{
switch (_results[a])
{
case 0:
return 1;
case 1:
return 2;
case 2:
return 3;
default:
return 0;
}
}
return 99;
}
[TestCompiler(EnumSwitch.Case1)]
[TestCompiler(EnumSwitch.Case2)]
[TestCompiler(EnumSwitch.Case3)]
public static int SwitchEnum(EnumSwitch a)
{
switch (a)
{
case EnumSwitch.Case1:
return 100;
case EnumSwitch.Case3:
break;
default:
return 1000;
}
return 200;
}
public enum EnumSwitch
{
Case1,
Case2,
Case3,
}
[TestCompiler(ExpectedException = typeof(InvalidOperationException))]
[MonoOnly(".NET CLR does not support burst.abort correctly")]
public static int ExceptionReachedReturn()
{
throw new InvalidOperationException("This is bad 1");
}
[TestCompiler(ExpectedException = typeof(InvalidOperationException))]
[MonoOnly(".NET CLR does not support burst.abort correctly")]
public static void ExceptionReached()
{
throw new InvalidOperationException("This is bad 2");
}
[TestCompiler(1)]
[TestCompiler(2)]
public static void ExceptionNotReached(int a)
{
if (a > 10)
{
throw new InvalidOperationException("This is bad 2");
}
}
[TestCompiler(1)]
[TestCompiler(2)]
public static void ExceptionMultipleNotReached(int a)
{
if (a > 10)
{
if (a > 15)
{
throw new InvalidOperationException("This is bad 2");
}
else
{
if (a < 8)
{
throw new NotSupportedException();
}
else
{
a = a + 1;
}
}
}
}
[TestCompiler(1)]
[TestCompiler(2)]
public static int ExceptionNotReachedReturn(int a)
{
int b = a;
if (a > 10)
{
b = 5;
throw new InvalidOperationException("This is bad 2");
}
return b;
}
[TestCompiler(13)]
[TestCompiler(1)]
public static int ExceptionMultipleNotReachedReturn(int a)
{
if (a > 10)
{
if (a > 15)
{
throw new InvalidOperationException("This is bad 2");
}
else
{
if (a < 12)
{
throw new NotSupportedException();
}
else
{
a = a + 1;
}
}
}
return a;
}
[TestCompiler]
public static void TestInternalError()
{
var job = new InternalErrorVariableNotFound();
job.Execute();
}
public struct InternalErrorVariableNotFound : IJob
{
public void Execute()
{
CausesError(3);
}
static int CausesError(int x)
{
int y = 0;
while (y != 0 && y != 1)
{
if (x > 0)
x = y++;
}
return y;
}
}
[TestCompiler(true)]
public static int TestPopNonInitialTrailingPush(bool x)
{
return (x ? 1 : -1) * math.min(16, 1);
}
[TestCompiler]
// Check unsigned ternary comparison (Bxx_Un) opcodes
public static ulong TestUnsignedTernary()
{
ulong a = 0;
ulong b = ~0UL;
ulong c = (a < b) ? 1UL : 0;
ulong d = (a <= b) ? 1UL : 0;
ulong e = (a > b) ? 0: 1UL;
ulong f = (a >= b) ? 0: 1UL;
return c + d + e + f;
}
}
}
| 24.432692 | 186 | 0.332546 | [
"Apache-2.0"
] | FynnKaeser/biz.dfch.CS.Unity.Examples | src/biz.dfch.CS.Unity.KartingMicrogame/Library/PackageCache/com.unity.burst@1.2.3/Tests/Runtime/Shared/040-ControlFlows.cs | 20,328 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.ComponentModel;
using Pulumi;
namespace Pulumi.AzureNative.Sql
{
/// <summary>
/// Type of the sever administrator.
/// </summary>
[EnumType]
public readonly struct AdministratorType : IEquatable<AdministratorType>
{
private readonly string _value;
private AdministratorType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static AdministratorType ActiveDirectory { get; } = new AdministratorType("ActiveDirectory");
public static bool operator ==(AdministratorType left, AdministratorType right) => left.Equals(right);
public static bool operator !=(AdministratorType left, AdministratorType right) => !left.Equals(right);
public static explicit operator string(AdministratorType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is AdministratorType other && Equals(other);
public bool Equals(AdministratorType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Gets the auto-execute status (whether to let the system execute the recommendations) of this advisor. Possible values are 'Enabled' and 'Disabled'
/// </summary>
[EnumType]
public readonly struct AutoExecuteStatus : IEquatable<AutoExecuteStatus>
{
private readonly string _value;
private AutoExecuteStatus(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static AutoExecuteStatus Enabled { get; } = new AutoExecuteStatus("Enabled");
public static AutoExecuteStatus Disabled { get; } = new AutoExecuteStatus("Disabled");
public static AutoExecuteStatus Default { get; } = new AutoExecuteStatus("Default");
public static bool operator ==(AutoExecuteStatus left, AutoExecuteStatus right) => left.Equals(right);
public static bool operator !=(AutoExecuteStatus left, AutoExecuteStatus right) => !left.Equals(right);
public static explicit operator string(AutoExecuteStatus value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is AutoExecuteStatus other && Equals(other);
public bool Equals(AutoExecuteStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Specifies the state of the audit. If state is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required.
/// </summary>
[EnumType]
public readonly struct BlobAuditingPolicyState : IEquatable<BlobAuditingPolicyState>
{
private readonly string _value;
private BlobAuditingPolicyState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static BlobAuditingPolicyState Enabled { get; } = new BlobAuditingPolicyState("Enabled");
public static BlobAuditingPolicyState Disabled { get; } = new BlobAuditingPolicyState("Disabled");
public static bool operator ==(BlobAuditingPolicyState left, BlobAuditingPolicyState right) => left.Equals(right);
public static bool operator !=(BlobAuditingPolicyState left, BlobAuditingPolicyState right) => !left.Equals(right);
public static explicit operator string(BlobAuditingPolicyState value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is BlobAuditingPolicyState other && Equals(other);
public bool Equals(BlobAuditingPolicyState other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Collation of the metadata catalog.
/// </summary>
[EnumType]
public readonly struct CatalogCollationType : IEquatable<CatalogCollationType>
{
private readonly string _value;
private CatalogCollationType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static CatalogCollationType DATABASE_DEFAULT { get; } = new CatalogCollationType("DATABASE_DEFAULT");
public static CatalogCollationType SQL_Latin1_General_CP1_CI_AS { get; } = new CatalogCollationType("SQL_Latin1_General_CP1_CI_AS");
public static bool operator ==(CatalogCollationType left, CatalogCollationType right) => left.Equals(right);
public static bool operator !=(CatalogCollationType left, CatalogCollationType right) => !left.Equals(right);
public static explicit operator string(CatalogCollationType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is CatalogCollationType other && Equals(other);
public bool Equals(CatalogCollationType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Specifies the mode of database creation.
///
/// Default: regular database creation.
///
/// Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified as the resource ID of the source database.
///
/// Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId must be specified as the resource ID of the existing primary database.
///
/// PointInTimeRestore: Creates a database by restoring a point in time backup of an existing database. sourceDatabaseId must be specified as the resource ID of the existing database, and restorePointInTime must be specified.
///
/// Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be specified as the recoverable database resource ID to restore.
///
/// Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must be specified. If sourceDatabaseId is the database's original resource ID, then sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored. restorePointInTime may also be specified to restore from an earlier point in time.
///
/// RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point resource ID.
///
/// Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse edition.
/// </summary>
[EnumType]
public readonly struct CreateMode : IEquatable<CreateMode>
{
private readonly string _value;
private CreateMode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static CreateMode Default { get; } = new CreateMode("Default");
public static CreateMode Copy { get; } = new CreateMode("Copy");
public static CreateMode Secondary { get; } = new CreateMode("Secondary");
public static CreateMode PointInTimeRestore { get; } = new CreateMode("PointInTimeRestore");
public static CreateMode Restore { get; } = new CreateMode("Restore");
public static CreateMode Recovery { get; } = new CreateMode("Recovery");
public static CreateMode RestoreExternalBackup { get; } = new CreateMode("RestoreExternalBackup");
public static CreateMode RestoreExternalBackupSecondary { get; } = new CreateMode("RestoreExternalBackupSecondary");
public static CreateMode RestoreLongTermRetentionBackup { get; } = new CreateMode("RestoreLongTermRetentionBackup");
public static CreateMode OnlineSecondary { get; } = new CreateMode("OnlineSecondary");
public static bool operator ==(CreateMode left, CreateMode right) => left.Equals(right);
public static bool operator !=(CreateMode left, CreateMode right) => !left.Equals(right);
public static explicit operator string(CreateMode value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is CreateMode other && Equals(other);
public bool Equals(CreateMode other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The state of the data masking policy.
/// </summary>
[EnumType]
public readonly struct DataMaskingState : IEquatable<DataMaskingState>
{
private readonly string _value;
private DataMaskingState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static DataMaskingState Disabled { get; } = new DataMaskingState("Disabled");
public static DataMaskingState Enabled { get; } = new DataMaskingState("Enabled");
public static bool operator ==(DataMaskingState left, DataMaskingState right) => left.Equals(right);
public static bool operator !=(DataMaskingState left, DataMaskingState right) => !left.Equals(right);
public static explicit operator string(DataMaskingState value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is DataMaskingState other && Equals(other);
public bool Equals(DataMaskingState other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The license type to apply for this database. `LicenseIncluded` if you need a license, or `BasePrice` if you have a license and are eligible for the Azure Hybrid Benefit.
/// </summary>
[EnumType]
public readonly struct DatabaseLicenseType : IEquatable<DatabaseLicenseType>
{
private readonly string _value;
private DatabaseLicenseType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static DatabaseLicenseType LicenseIncluded { get; } = new DatabaseLicenseType("LicenseIncluded");
public static DatabaseLicenseType BasePrice { get; } = new DatabaseLicenseType("BasePrice");
public static bool operator ==(DatabaseLicenseType left, DatabaseLicenseType right) => left.Equals(right);
public static bool operator !=(DatabaseLicenseType left, DatabaseLicenseType right) => !left.Equals(right);
public static explicit operator string(DatabaseLicenseType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is DatabaseLicenseType other && Equals(other);
public bool Equals(DatabaseLicenseType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The state of read-only routing. If enabled, connections that have application intent set to readonly in their connection string may be routed to a readonly secondary replica in the same region.
/// </summary>
[EnumType]
public readonly struct DatabaseReadScale : IEquatable<DatabaseReadScale>
{
private readonly string _value;
private DatabaseReadScale(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static DatabaseReadScale Enabled { get; } = new DatabaseReadScale("Enabled");
public static DatabaseReadScale Disabled { get; } = new DatabaseReadScale("Disabled");
public static bool operator ==(DatabaseReadScale left, DatabaseReadScale right) => left.Equals(right);
public static bool operator !=(DatabaseReadScale left, DatabaseReadScale right) => !left.Equals(right);
public static explicit operator string(DatabaseReadScale value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is DatabaseReadScale other && Equals(other);
public bool Equals(DatabaseReadScale other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The license type to apply for this elastic pool.
/// </summary>
[EnumType]
public readonly struct ElasticPoolLicenseType : IEquatable<ElasticPoolLicenseType>
{
private readonly string _value;
private ElasticPoolLicenseType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ElasticPoolLicenseType LicenseIncluded { get; } = new ElasticPoolLicenseType("LicenseIncluded");
public static ElasticPoolLicenseType BasePrice { get; } = new ElasticPoolLicenseType("BasePrice");
public static bool operator ==(ElasticPoolLicenseType left, ElasticPoolLicenseType right) => left.Equals(right);
public static bool operator !=(ElasticPoolLicenseType left, ElasticPoolLicenseType right) => !left.Equals(right);
public static explicit operator string(ElasticPoolLicenseType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ElasticPoolLicenseType other && Equals(other);
public bool Equals(ElasticPoolLicenseType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The state of the geo backup policy.
/// </summary>
[EnumType]
public readonly struct GeoBackupPolicyState : IEquatable<GeoBackupPolicyState>
{
private readonly string _value;
private GeoBackupPolicyState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static GeoBackupPolicyState Disabled { get; } = new GeoBackupPolicyState("Disabled");
public static GeoBackupPolicyState Enabled { get; } = new GeoBackupPolicyState("Enabled");
public static bool operator ==(GeoBackupPolicyState left, GeoBackupPolicyState right) => left.Equals(right);
public static bool operator !=(GeoBackupPolicyState left, GeoBackupPolicyState right) => !left.Equals(right);
public static explicit operator string(GeoBackupPolicyState value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is GeoBackupPolicyState other && Equals(other);
public bool Equals(GeoBackupPolicyState other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource.
/// </summary>
[EnumType]
public readonly struct IdentityType : IEquatable<IdentityType>
{
private readonly string _value;
private IdentityType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static IdentityType None { get; } = new IdentityType("None");
public static IdentityType SystemAssigned { get; } = new IdentityType("SystemAssigned");
public static IdentityType UserAssigned { get; } = new IdentityType("UserAssigned");
public static IdentityType SystemAssigned_UserAssigned { get; } = new IdentityType("SystemAssigned,UserAssigned");
public static bool operator ==(IdentityType left, IdentityType right) => left.Equals(right);
public static bool operator !=(IdentityType left, IdentityType right) => !left.Equals(right);
public static explicit operator string(IdentityType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is IdentityType other && Equals(other);
public bool Equals(IdentityType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The license type. Possible values are 'LicenseIncluded' (price for SQL license is included) and 'BasePrice' (without SQL license price).
/// </summary>
[EnumType]
public readonly struct InstancePoolLicenseType : IEquatable<InstancePoolLicenseType>
{
private readonly string _value;
private InstancePoolLicenseType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static InstancePoolLicenseType LicenseIncluded { get; } = new InstancePoolLicenseType("LicenseIncluded");
public static InstancePoolLicenseType BasePrice { get; } = new InstancePoolLicenseType("BasePrice");
public static bool operator ==(InstancePoolLicenseType left, InstancePoolLicenseType right) => left.Equals(right);
public static bool operator !=(InstancePoolLicenseType left, InstancePoolLicenseType right) => !left.Equals(right);
public static explicit operator string(InstancePoolLicenseType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is InstancePoolLicenseType other && Equals(other);
public bool Equals(InstancePoolLicenseType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Schedule interval type
/// </summary>
[EnumType]
public readonly struct JobScheduleType : IEquatable<JobScheduleType>
{
private readonly string _value;
private JobScheduleType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobScheduleType Once { get; } = new JobScheduleType("Once");
public static JobScheduleType Recurring { get; } = new JobScheduleType("Recurring");
public static bool operator ==(JobScheduleType left, JobScheduleType right) => left.Equals(right);
public static bool operator !=(JobScheduleType left, JobScheduleType right) => !left.Equals(right);
public static explicit operator string(JobScheduleType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobScheduleType other && Equals(other);
public bool Equals(JobScheduleType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The source of the action to execute.
/// </summary>
[EnumType]
public readonly struct JobStepActionSource : IEquatable<JobStepActionSource>
{
private readonly string _value;
private JobStepActionSource(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobStepActionSource Inline { get; } = new JobStepActionSource("Inline");
public static bool operator ==(JobStepActionSource left, JobStepActionSource right) => left.Equals(right);
public static bool operator !=(JobStepActionSource left, JobStepActionSource right) => !left.Equals(right);
public static explicit operator string(JobStepActionSource value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobStepActionSource other && Equals(other);
public bool Equals(JobStepActionSource other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Type of action being executed by the job step.
/// </summary>
[EnumType]
public readonly struct JobStepActionType : IEquatable<JobStepActionType>
{
private readonly string _value;
private JobStepActionType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobStepActionType TSql { get; } = new JobStepActionType("TSql");
public static bool operator ==(JobStepActionType left, JobStepActionType right) => left.Equals(right);
public static bool operator !=(JobStepActionType left, JobStepActionType right) => !left.Equals(right);
public static explicit operator string(JobStepActionType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobStepActionType other && Equals(other);
public bool Equals(JobStepActionType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The output destination type.
/// </summary>
[EnumType]
public readonly struct JobStepOutputType : IEquatable<JobStepOutputType>
{
private readonly string _value;
private JobStepOutputType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobStepOutputType SqlDatabase { get; } = new JobStepOutputType("SqlDatabase");
public static bool operator ==(JobStepOutputType left, JobStepOutputType right) => left.Equals(right);
public static bool operator !=(JobStepOutputType left, JobStepOutputType right) => !left.Equals(right);
public static explicit operator string(JobStepOutputType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobStepOutputType other && Equals(other);
public bool Equals(JobStepOutputType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Whether the target is included or excluded from the group.
/// </summary>
[EnumType]
public readonly struct JobTargetGroupMembershipType : IEquatable<JobTargetGroupMembershipType>
{
private readonly string _value;
private JobTargetGroupMembershipType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobTargetGroupMembershipType Include { get; } = new JobTargetGroupMembershipType("Include");
public static JobTargetGroupMembershipType Exclude { get; } = new JobTargetGroupMembershipType("Exclude");
public static bool operator ==(JobTargetGroupMembershipType left, JobTargetGroupMembershipType right) => left.Equals(right);
public static bool operator !=(JobTargetGroupMembershipType left, JobTargetGroupMembershipType right) => !left.Equals(right);
public static explicit operator string(JobTargetGroupMembershipType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobTargetGroupMembershipType other && Equals(other);
public bool Equals(JobTargetGroupMembershipType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The target type.
/// </summary>
[EnumType]
public readonly struct JobTargetType : IEquatable<JobTargetType>
{
private readonly string _value;
private JobTargetType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static JobTargetType TargetGroup { get; } = new JobTargetType("TargetGroup");
public static JobTargetType SqlDatabase { get; } = new JobTargetType("SqlDatabase");
public static JobTargetType SqlElasticPool { get; } = new JobTargetType("SqlElasticPool");
public static JobTargetType SqlShardMap { get; } = new JobTargetType("SqlShardMap");
public static JobTargetType SqlServer { get; } = new JobTargetType("SqlServer");
public static bool operator ==(JobTargetType left, JobTargetType right) => left.Equals(right);
public static bool operator !=(JobTargetType left, JobTargetType right) => !left.Equals(right);
public static explicit operator string(JobTargetType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is JobTargetType other && Equals(other);
public bool Equals(JobTargetType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Managed database create mode. PointInTimeRestore: Create a database by restoring a point in time backup of an existing database. SourceDatabaseName, SourceManagedInstanceName and PointInTime must be specified. RestoreExternalBackup: Create a database by restoring from external backup files. Collation, StorageContainerUri and StorageContainerSasToken must be specified. Recovery: Creates a database by restoring a geo-replicated backup. RecoverableDatabaseId must be specified as the recoverable database resource ID to restore. RestoreLongTermRetentionBackup: Create a database by restoring from a long term retention backup (longTermRetentionBackupResourceId required).
/// </summary>
[EnumType]
public readonly struct ManagedDatabaseCreateMode : IEquatable<ManagedDatabaseCreateMode>
{
private readonly string _value;
private ManagedDatabaseCreateMode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ManagedDatabaseCreateMode Default { get; } = new ManagedDatabaseCreateMode("Default");
public static ManagedDatabaseCreateMode RestoreExternalBackup { get; } = new ManagedDatabaseCreateMode("RestoreExternalBackup");
public static ManagedDatabaseCreateMode PointInTimeRestore { get; } = new ManagedDatabaseCreateMode("PointInTimeRestore");
public static ManagedDatabaseCreateMode Recovery { get; } = new ManagedDatabaseCreateMode("Recovery");
public static ManagedDatabaseCreateMode RestoreLongTermRetentionBackup { get; } = new ManagedDatabaseCreateMode("RestoreLongTermRetentionBackup");
public static bool operator ==(ManagedDatabaseCreateMode left, ManagedDatabaseCreateMode right) => left.Equals(right);
public static bool operator !=(ManagedDatabaseCreateMode left, ManagedDatabaseCreateMode right) => !left.Equals(right);
public static explicit operator string(ManagedDatabaseCreateMode value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ManagedDatabaseCreateMode other && Equals(other);
public bool Equals(ManagedDatabaseCreateMode other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Type of the managed instance administrator.
/// </summary>
[EnumType]
public readonly struct ManagedInstanceAdministratorType : IEquatable<ManagedInstanceAdministratorType>
{
private readonly string _value;
private ManagedInstanceAdministratorType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ManagedInstanceAdministratorType ActiveDirectory { get; } = new ManagedInstanceAdministratorType("ActiveDirectory");
public static bool operator ==(ManagedInstanceAdministratorType left, ManagedInstanceAdministratorType right) => left.Equals(right);
public static bool operator !=(ManagedInstanceAdministratorType left, ManagedInstanceAdministratorType right) => !left.Equals(right);
public static explicit operator string(ManagedInstanceAdministratorType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ManagedInstanceAdministratorType other && Equals(other);
public bool Equals(ManagedInstanceAdministratorType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The license type. Possible values are 'LicenseIncluded' (regular price inclusive of a new SQL license) and 'BasePrice' (discounted AHB price for bringing your own SQL licenses).
/// </summary>
[EnumType]
public readonly struct ManagedInstanceLicenseType : IEquatable<ManagedInstanceLicenseType>
{
private readonly string _value;
private ManagedInstanceLicenseType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ManagedInstanceLicenseType LicenseIncluded { get; } = new ManagedInstanceLicenseType("LicenseIncluded");
public static ManagedInstanceLicenseType BasePrice { get; } = new ManagedInstanceLicenseType("BasePrice");
public static bool operator ==(ManagedInstanceLicenseType left, ManagedInstanceLicenseType right) => left.Equals(right);
public static bool operator !=(ManagedInstanceLicenseType left, ManagedInstanceLicenseType right) => !left.Equals(right);
public static explicit operator string(ManagedInstanceLicenseType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ManagedInstanceLicenseType other && Equals(other);
public bool Equals(ManagedInstanceLicenseType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Connection type used for connecting to the instance.
/// </summary>
[EnumType]
public readonly struct ManagedInstanceProxyOverride : IEquatable<ManagedInstanceProxyOverride>
{
private readonly string _value;
private ManagedInstanceProxyOverride(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ManagedInstanceProxyOverride Proxy { get; } = new ManagedInstanceProxyOverride("Proxy");
public static ManagedInstanceProxyOverride Redirect { get; } = new ManagedInstanceProxyOverride("Redirect");
public static ManagedInstanceProxyOverride Default { get; } = new ManagedInstanceProxyOverride("Default");
public static bool operator ==(ManagedInstanceProxyOverride left, ManagedInstanceProxyOverride right) => left.Equals(right);
public static bool operator !=(ManagedInstanceProxyOverride left, ManagedInstanceProxyOverride right) => !left.Equals(right);
public static explicit operator string(ManagedInstanceProxyOverride value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ManagedInstanceProxyOverride other && Equals(other);
public bool Equals(ManagedInstanceProxyOverride other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Specifies the mode of database creation.
///
/// Default: Regular instance creation.
///
/// Restore: Creates an instance by restoring a set of backups to specific point in time. RestorePointInTime and SourceManagedInstanceId must be specified.
/// </summary>
[EnumType]
public readonly struct ManagedServerCreateMode : IEquatable<ManagedServerCreateMode>
{
private readonly string _value;
private ManagedServerCreateMode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ManagedServerCreateMode Default { get; } = new ManagedServerCreateMode("Default");
public static ManagedServerCreateMode PointInTimeRestore { get; } = new ManagedServerCreateMode("PointInTimeRestore");
public static bool operator ==(ManagedServerCreateMode left, ManagedServerCreateMode right) => left.Equals(right);
public static bool operator !=(ManagedServerCreateMode left, ManagedServerCreateMode right) => !left.Equals(right);
public static explicit operator string(ManagedServerCreateMode value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ManagedServerCreateMode other && Equals(other);
public bool Equals(ManagedServerCreateMode other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Principal Type of the sever administrator.
/// </summary>
[EnumType]
public readonly struct PrincipalType : IEquatable<PrincipalType>
{
private readonly string _value;
private PrincipalType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static PrincipalType User { get; } = new PrincipalType("User");
public static PrincipalType Group { get; } = new PrincipalType("Group");
public static PrincipalType Application { get; } = new PrincipalType("Application");
public static bool operator ==(PrincipalType left, PrincipalType right) => left.Equals(right);
public static bool operator !=(PrincipalType left, PrincipalType right) => !left.Equals(right);
public static explicit operator string(PrincipalType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is PrincipalType other && Equals(other);
public bool Equals(PrincipalType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The private link service connection status.
/// </summary>
[EnumType]
public readonly struct PrivateLinkServiceConnectionStateStatus : IEquatable<PrivateLinkServiceConnectionStateStatus>
{
private readonly string _value;
private PrivateLinkServiceConnectionStateStatus(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static PrivateLinkServiceConnectionStateStatus Approved { get; } = new PrivateLinkServiceConnectionStateStatus("Approved");
public static PrivateLinkServiceConnectionStateStatus Pending { get; } = new PrivateLinkServiceConnectionStateStatus("Pending");
public static PrivateLinkServiceConnectionStateStatus Rejected { get; } = new PrivateLinkServiceConnectionStateStatus("Rejected");
public static PrivateLinkServiceConnectionStateStatus Disconnected { get; } = new PrivateLinkServiceConnectionStateStatus("Disconnected");
public static bool operator ==(PrivateLinkServiceConnectionStateStatus left, PrivateLinkServiceConnectionStateStatus right) => left.Equals(right);
public static bool operator !=(PrivateLinkServiceConnectionStateStatus left, PrivateLinkServiceConnectionStateStatus right) => !left.Equals(right);
public static explicit operator string(PrivateLinkServiceConnectionStateStatus value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is PrivateLinkServiceConnectionStateStatus other && Equals(other);
public bool Equals(PrivateLinkServiceConnectionStateStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Failover policy of the read-only endpoint for the failover group.
/// </summary>
[EnumType]
public readonly struct ReadOnlyEndpointFailoverPolicy : IEquatable<ReadOnlyEndpointFailoverPolicy>
{
private readonly string _value;
private ReadOnlyEndpointFailoverPolicy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ReadOnlyEndpointFailoverPolicy Disabled { get; } = new ReadOnlyEndpointFailoverPolicy("Disabled");
public static ReadOnlyEndpointFailoverPolicy Enabled { get; } = new ReadOnlyEndpointFailoverPolicy("Enabled");
public static bool operator ==(ReadOnlyEndpointFailoverPolicy left, ReadOnlyEndpointFailoverPolicy right) => left.Equals(right);
public static bool operator !=(ReadOnlyEndpointFailoverPolicy left, ReadOnlyEndpointFailoverPolicy right) => !left.Equals(right);
public static explicit operator string(ReadOnlyEndpointFailoverPolicy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ReadOnlyEndpointFailoverPolicy other && Equals(other);
public bool Equals(ReadOnlyEndpointFailoverPolicy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Failover policy of the read-write endpoint for the failover group. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required.
/// </summary>
[EnumType]
public readonly struct ReadWriteEndpointFailoverPolicy : IEquatable<ReadWriteEndpointFailoverPolicy>
{
private readonly string _value;
private ReadWriteEndpointFailoverPolicy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ReadWriteEndpointFailoverPolicy Manual { get; } = new ReadWriteEndpointFailoverPolicy("Manual");
public static ReadWriteEndpointFailoverPolicy Automatic { get; } = new ReadWriteEndpointFailoverPolicy("Automatic");
public static bool operator ==(ReadWriteEndpointFailoverPolicy left, ReadWriteEndpointFailoverPolicy right) => left.Equals(right);
public static bool operator !=(ReadWriteEndpointFailoverPolicy left, ReadWriteEndpointFailoverPolicy right) => !left.Equals(right);
public static explicit operator string(ReadWriteEndpointFailoverPolicy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ReadWriteEndpointFailoverPolicy other && Equals(other);
public bool Equals(ReadWriteEndpointFailoverPolicy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The storage account type to be used to store backups for this database.
/// </summary>
[EnumType]
public readonly struct RequestedBackupStorageRedundancy : IEquatable<RequestedBackupStorageRedundancy>
{
private readonly string _value;
private RequestedBackupStorageRedundancy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static RequestedBackupStorageRedundancy Geo { get; } = new RequestedBackupStorageRedundancy("Geo");
public static RequestedBackupStorageRedundancy Local { get; } = new RequestedBackupStorageRedundancy("Local");
public static RequestedBackupStorageRedundancy Zone { get; } = new RequestedBackupStorageRedundancy("Zone");
public static bool operator ==(RequestedBackupStorageRedundancy left, RequestedBackupStorageRedundancy right) => left.Equals(right);
public static bool operator !=(RequestedBackupStorageRedundancy left, RequestedBackupStorageRedundancy right) => !left.Equals(right);
public static explicit operator string(RequestedBackupStorageRedundancy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is RequestedBackupStorageRedundancy other && Equals(other);
public bool Equals(RequestedBackupStorageRedundancy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The name of the sample schema to apply when creating this database.
/// </summary>
[EnumType]
public readonly struct SampleName : IEquatable<SampleName>
{
private readonly string _value;
private SampleName(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SampleName AdventureWorksLT { get; } = new SampleName("AdventureWorksLT");
public static SampleName WideWorldImportersStd { get; } = new SampleName("WideWorldImportersStd");
public static SampleName WideWorldImportersFull { get; } = new SampleName("WideWorldImportersFull");
public static bool operator ==(SampleName left, SampleName right) => left.Equals(right);
public static bool operator !=(SampleName left, SampleName right) => !left.Equals(right);
public static explicit operator string(SampleName value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SampleName other && Equals(other);
public bool Equals(SampleName other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The secondary type of the database if it is a secondary. Valid values are Geo and Named.
/// </summary>
[EnumType]
public readonly struct SecondaryType : IEquatable<SecondaryType>
{
private readonly string _value;
private SecondaryType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SecondaryType Geo { get; } = new SecondaryType("Geo");
public static SecondaryType Named { get; } = new SecondaryType("Named");
public static bool operator ==(SecondaryType left, SecondaryType right) => left.Equals(right);
public static bool operator !=(SecondaryType left, SecondaryType right) => !left.Equals(right);
public static explicit operator string(SecondaryType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SecondaryType other && Equals(other);
public bool Equals(SecondaryType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Specifies the state of the policy, whether it is enabled or disabled or a policy has not been applied yet on the specific database.
/// </summary>
[EnumType]
public readonly struct SecurityAlertsPolicyState : IEquatable<SecurityAlertsPolicyState>
{
private readonly string _value;
private SecurityAlertsPolicyState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SecurityAlertsPolicyState Enabled { get; } = new SecurityAlertsPolicyState("Enabled");
public static SecurityAlertsPolicyState Disabled { get; } = new SecurityAlertsPolicyState("Disabled");
public static bool operator ==(SecurityAlertsPolicyState left, SecurityAlertsPolicyState right) => left.Equals(right);
public static bool operator !=(SecurityAlertsPolicyState left, SecurityAlertsPolicyState right) => !left.Equals(right);
public static explicit operator string(SecurityAlertsPolicyState value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SecurityAlertsPolicyState other && Equals(other);
public bool Equals(SecurityAlertsPolicyState other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
[EnumType]
public readonly struct SensitivityLabelRank : IEquatable<SensitivityLabelRank>
{
private readonly string _value;
private SensitivityLabelRank(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SensitivityLabelRank None { get; } = new SensitivityLabelRank("None");
public static SensitivityLabelRank Low { get; } = new SensitivityLabelRank("Low");
public static SensitivityLabelRank Medium { get; } = new SensitivityLabelRank("Medium");
public static SensitivityLabelRank High { get; } = new SensitivityLabelRank("High");
public static SensitivityLabelRank Critical { get; } = new SensitivityLabelRank("Critical");
public static bool operator ==(SensitivityLabelRank left, SensitivityLabelRank right) => left.Equals(right);
public static bool operator !=(SensitivityLabelRank left, SensitivityLabelRank right) => !left.Equals(right);
public static explicit operator string(SensitivityLabelRank value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SensitivityLabelRank other && Equals(other);
public bool Equals(SensitivityLabelRank other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The server key type like 'ServiceManaged', 'AzureKeyVault'.
/// </summary>
[EnumType]
public readonly struct ServerKeyType : IEquatable<ServerKeyType>
{
private readonly string _value;
private ServerKeyType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ServerKeyType ServiceManaged { get; } = new ServerKeyType("ServiceManaged");
public static ServerKeyType AzureKeyVault { get; } = new ServerKeyType("AzureKeyVault");
public static bool operator ==(ServerKeyType left, ServerKeyType right) => left.Equals(right);
public static bool operator !=(ServerKeyType left, ServerKeyType right) => !left.Equals(right);
public static explicit operator string(ServerKeyType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ServerKeyType other && Equals(other);
public bool Equals(ServerKeyType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Whether or not public endpoint access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'
/// </summary>
[EnumType]
public readonly struct ServerPublicNetworkAccess : IEquatable<ServerPublicNetworkAccess>
{
private readonly string _value;
private ServerPublicNetworkAccess(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ServerPublicNetworkAccess Enabled { get; } = new ServerPublicNetworkAccess("Enabled");
public static ServerPublicNetworkAccess Disabled { get; } = new ServerPublicNetworkAccess("Disabled");
public static bool operator ==(ServerPublicNetworkAccess left, ServerPublicNetworkAccess right) => left.Equals(right);
public static bool operator !=(ServerPublicNetworkAccess left, ServerPublicNetworkAccess right) => !left.Equals(right);
public static explicit operator string(ServerPublicNetworkAccess value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ServerPublicNetworkAccess other && Equals(other);
public bool Equals(ServerPublicNetworkAccess other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The storage account type used to store backups for this instance. The options are LRS (LocallyRedundantStorage), ZRS (ZoneRedundantStorage) and GRS (GeoRedundantStorage)
/// </summary>
[EnumType]
public readonly struct StorageAccountType : IEquatable<StorageAccountType>
{
private readonly string _value;
private StorageAccountType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static StorageAccountType GRS { get; } = new StorageAccountType("GRS");
public static StorageAccountType LRS { get; } = new StorageAccountType("LRS");
public static StorageAccountType ZRS { get; } = new StorageAccountType("ZRS");
public static bool operator ==(StorageAccountType left, StorageAccountType right) => left.Equals(right);
public static bool operator !=(StorageAccountType left, StorageAccountType right) => !left.Equals(right);
public static explicit operator string(StorageAccountType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is StorageAccountType other && Equals(other);
public bool Equals(StorageAccountType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Conflict resolution policy of the sync group.
/// </summary>
[EnumType]
public readonly struct SyncConflictResolutionPolicy : IEquatable<SyncConflictResolutionPolicy>
{
private readonly string _value;
private SyncConflictResolutionPolicy(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SyncConflictResolutionPolicy HubWin { get; } = new SyncConflictResolutionPolicy("HubWin");
public static SyncConflictResolutionPolicy MemberWin { get; } = new SyncConflictResolutionPolicy("MemberWin");
public static bool operator ==(SyncConflictResolutionPolicy left, SyncConflictResolutionPolicy right) => left.Equals(right);
public static bool operator !=(SyncConflictResolutionPolicy left, SyncConflictResolutionPolicy right) => !left.Equals(right);
public static explicit operator string(SyncConflictResolutionPolicy value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SyncConflictResolutionPolicy other && Equals(other);
public bool Equals(SyncConflictResolutionPolicy other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Sync direction of the sync member.
/// </summary>
[EnumType]
public readonly struct SyncDirection : IEquatable<SyncDirection>
{
private readonly string _value;
private SyncDirection(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SyncDirection Bidirectional { get; } = new SyncDirection("Bidirectional");
public static SyncDirection OneWayMemberToHub { get; } = new SyncDirection("OneWayMemberToHub");
public static SyncDirection OneWayHubToMember { get; } = new SyncDirection("OneWayHubToMember");
public static bool operator ==(SyncDirection left, SyncDirection right) => left.Equals(right);
public static bool operator !=(SyncDirection left, SyncDirection right) => !left.Equals(right);
public static explicit operator string(SyncDirection value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SyncDirection other && Equals(other);
public bool Equals(SyncDirection other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// Database type of the sync member.
/// </summary>
[EnumType]
public readonly struct SyncMemberDbType : IEquatable<SyncMemberDbType>
{
private readonly string _value;
private SyncMemberDbType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SyncMemberDbType AzureSqlDatabase { get; } = new SyncMemberDbType("AzureSqlDatabase");
public static SyncMemberDbType SqlServerDatabase { get; } = new SyncMemberDbType("SqlServerDatabase");
public static bool operator ==(SyncMemberDbType left, SyncMemberDbType right) => left.Equals(right);
public static bool operator !=(SyncMemberDbType left, SyncMemberDbType right) => !left.Equals(right);
public static explicit operator string(SyncMemberDbType value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SyncMemberDbType other && Equals(other);
public bool Equals(SyncMemberDbType other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The status of the database transparent data encryption.
/// </summary>
[EnumType]
public readonly struct TransparentDataEncryptionStatus : IEquatable<TransparentDataEncryptionStatus>
{
private readonly string _value;
private TransparentDataEncryptionStatus(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static TransparentDataEncryptionStatus Enabled { get; } = new TransparentDataEncryptionStatus("Enabled");
public static TransparentDataEncryptionStatus Disabled { get; } = new TransparentDataEncryptionStatus("Disabled");
public static bool operator ==(TransparentDataEncryptionStatus left, TransparentDataEncryptionStatus right) => left.Equals(right);
public static bool operator !=(TransparentDataEncryptionStatus left, TransparentDataEncryptionStatus right) => !left.Equals(right);
public static explicit operator string(TransparentDataEncryptionStatus value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is TransparentDataEncryptionStatus other && Equals(other);
public bool Equals(TransparentDataEncryptionStatus other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
}
| 48.446386 | 680 | 0.708693 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Sql/Enums.cs | 60,994 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Build.Framework;
using Microsoft.DotNet.Build.Tasks.Feed.Model;
using Microsoft.DotNet.Maestro.Client;
using Microsoft.DotNet.Maestro.Client.Models;
using Microsoft.DotNet.VersionTools.BuildManifest.Model;
using Microsoft.DotNet.VersionTools.Util;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.DotNet.Build.Tasks.Feed.GeneralUtils;
using MsBuildUtils = Microsoft.Build.Utilities;
namespace Microsoft.DotNet.Build.Tasks.Feed
{
/// <summary>
/// The intended use of this task is to push artifacts described in
/// a build manifest to a static package feed.
/// </summary>
public abstract class PublishArtifactsInManifestBase : Microsoft.Build.Utilities.Task
{
/// <summary>
/// Full path to the folder containing blob assets.
/// </summary>
public string BlobAssetsBasePath { get; set; }
/// <summary>
/// Full path to the folder containing package assets.
/// </summary>
public string PackageAssetsBasePath { get; set; }
/// <summary>
/// ID of the build (in BAR/Maestro) that produced the artifacts being published.
/// This might change in the future as we'll probably fetch this ID from the manifest itself.
/// </summary>
public int BARBuildId { get; set; }
/// <summary>
/// Access point to the Maestro API to be used for accessing BAR.
/// </summary>
public string MaestroApiEndpoint { get; set; }
/// <summary>
/// Authentication token to be used when interacting with Maestro API.
/// </summary>
public string BuildAssetRegistryToken { get; set; }
/// <summary>
/// Directory where "nuget.exe" is installed. This will be used to publish packages.
/// </summary>
[Required]
public string NugetPath { get; set; }
/// <summary>
/// Maximum number of parallel uploads for the upload tasks
/// </summary>
public int MaxClients { get; set; } = 16;
/// <summary>
/// Whether this build is internal or not. If true, extra checks are done to avoid accidental
/// publishing of assets to public feeds or storage accounts.
/// </summary>
public bool InternalBuild { get; set; } = false;
/// <summary>
/// If true, safety checks only print messages and do not error
/// - Internal asset to public feed
/// - Stable packages to non-isolated feeds
/// </summary>
public bool SkipSafetyChecks { get; set; } = false;
/// <summary>
/// Which build model (i.e., parsed build manifest) the publishing task will operate on.
/// This is set by the main publishing task before dispatching the execution to one of
/// the version specific publishing task.
/// </summary>
public BuildModel BuildModel { get; set; }
public string AkaMSClientId { get; set; }
public string AkaMSClientSecret { get; set; }
public string AkaMSTenant { get; set; }
public string AkaMsOwners { get; set; }
public string AkaMSCreatedBy { get; set; }
public string AkaMSGroupOwner { get; set; }
public readonly Dictionary<TargetFeedContentType, HashSet<TargetFeedConfig>> FeedConfigs =
new Dictionary<TargetFeedContentType, HashSet<TargetFeedConfig>>();
private readonly Dictionary<TargetFeedContentType, HashSet<PackageArtifactModel>> PackagesByCategory =
new Dictionary<TargetFeedContentType, HashSet<PackageArtifactModel>>();
private readonly Dictionary<TargetFeedContentType, HashSet<BlobArtifactModel>> BlobsByCategory =
new Dictionary<TargetFeedContentType, HashSet<BlobArtifactModel>>();
private readonly ConcurrentDictionary<(int AssetId, string AssetLocation, AddAssetLocationToAssetAssetLocationType LocationType), ValueTuple> NewAssetLocations =
new ConcurrentDictionary<(int AssetId, string AssetLocation, AddAssetLocationToAssetAssetLocationType LocationType), ValueTuple>();
// Matches versions such as 1.0.0.1234
private static readonly string FourPartVersionPattern = @"\d+\.\d+\.\d+\.\d+";
private static Regex FourPartVersionRegex = new Regex(FourPartVersionPattern);
protected LatestLinksManager LinkManager { get; set; } = null;
/// <summary>
/// For functions where retry is possible, max number of retries to perform
/// </summary>
public int MaxRetryCount { get; set; } = 5;
/// <summary>
/// For functions where retry is possible, base value for waiting between retries (may be multiplied in 2nd-Nth retry)
/// </summary>
public int RetryDelayMilliseconds { get; set; } = 5000;
public override bool Execute()
{
return ExecuteAsync().GetAwaiter().GetResult();
}
public abstract Task<bool> ExecuteAsync();
/// <summary>
/// Lookup an asset in the build asset dictionary by name and version
/// </summary>
/// <param name="name">Name of asset</param>
/// <param name="version">Version of asset</param>
/// <returns>Asset if one with the name and version exists, null otherwise</returns>
private Asset LookupAsset(string name, string version, Dictionary<string, HashSet<Asset>> buildAssets)
{
if (!buildAssets.TryGetValue(name, out HashSet<Asset> assetsWithName))
{
return null;
}
return assetsWithName.FirstOrDefault(asset => asset.Version == version);
}
/// <summary>
/// Lookup an asset in the build asset dictionary by name only.
/// This is for blob lookup purposes.
/// </summary>
/// <param name="name">Name of asset</param>
/// <returns>
/// Asset if one with the name exists and is the only asset with the name.
/// Throws if there is more than one asset with that name.
/// </returns>
private Asset LookupAsset(string name, Dictionary<string, HashSet<Asset>> buildAssets)
{
if (!buildAssets.TryGetValue(name, out HashSet<Asset> assetsWithName))
{
return null;
}
return assetsWithName.Single();
}
/// <summary>
/// Build up a map of asset name -> asset list so that we can avoid n^2 lookups when processing assets.
/// We use name only because blobs are only looked up by id (version is not recorded in the manifest).
/// This could mean that there might be multiple versions of the same asset in the build.
/// </summary>
/// <param name="buildInformation">Build information</param>
/// <returns>Map of asset name -> list of assets with that name.</returns>
protected Dictionary<string, HashSet<Asset>> CreateBuildAssetDictionary(Maestro.Client.Models.Build buildInformation)
{
Dictionary<string, HashSet<Asset>> buildAssets = new Dictionary<string, HashSet<Asset>>();
foreach (var asset in buildInformation.Assets)
{
if (buildAssets.TryGetValue(asset.Name, out HashSet<Asset> assetsWithName))
{
assetsWithName.Add(asset);
}
else
{
buildAssets.Add(asset.Name, new HashSet<Asset>(new AssetComparer()) { asset });
}
}
return buildAssets;
}
/// <summary>
/// Records the association of Asset -> AssetLocation to be persisted later in BAR.
/// </summary>
/// <param name="assetId">Id of the asset (i.e., name of the package) whose the location should be updated.</param>
/// <param name="assetVersion">Version of the asset whose the location should be updated.</param>
/// <param name="buildAssets">List of BAR Assets for the build that's being modified.</param>
/// <param name="feedConfig">Configuration of where the asset was published.</param>
/// <param name="assetLocationType">Type of feed location that is being added.</param>
/// <returns>True if that asset didn't have the informed location recorded already.</returns>
private bool TryAddAssetLocation(string assetId, string assetVersion, Dictionary<string, HashSet<Asset>> buildAssets, TargetFeedConfig feedConfig, AddAssetLocationToAssetAssetLocationType assetLocationType)
{
Asset assetRecord = string.IsNullOrEmpty(assetVersion) ?
LookupAsset(assetId, buildAssets) :
LookupAsset(assetId, assetVersion, buildAssets);
if (assetRecord == null)
{
string versionMsg = string.IsNullOrEmpty(assetVersion) ? string.Empty : $"and version {assetVersion}";
Log.LogError($"Asset with Id {assetId} {versionMsg} isn't registered on the BAR Build with ID {BARBuildId}");
return false;
}
return NewAssetLocations.TryAdd((assetRecord.Id, feedConfig.TargetURL, assetLocationType), ValueTuple.Create());
}
/// <summary>
/// Persist in BAR all pending associations of Asset -> AssetLocation stored in `NewAssetLocations`.
/// </summary>
/// <param name="client">Maestro++ API client</param>
protected Task PersistPendingAssetLocationAsync(IMaestroApi client)
{
var updates = NewAssetLocations.Keys.Select(nal => new AssetAndLocation(nal.AssetId, (LocationType)nal.LocationType)
{
Location = nal.AssetLocation
}).ToImmutableList();
return client.Assets.BulkAddLocationsAsync(updates);
}
/// <summary>
/// Protect against accidental publishing of internal assets to non-internal feeds.
/// </summary>
/// <returns></returns>
protected void CheckForInternalBuildsOnPublicFeeds(TargetFeedConfig feedConfig)
{
// If separated out for clarity.
if (!SkipSafetyChecks)
{
if (InternalBuild && !feedConfig.Internal)
{
Log.LogError($"Use of non-internal feed '{feedConfig.TargetURL}' is invalid for an internal build. This can be overridden with '{nameof(SkipSafetyChecks)}= true'");
}
}
}
/// <summary>
/// Run a check to verify that stable assets are not published to
/// locations they should not be published.
///
/// This is only done for packages since feeds are
/// immutable.
/// </summary>
public void CheckForStableAssetsInNonIsolatedFeeds()
{
if ((!string.IsNullOrEmpty(BuildModel.Identity.IsReleaseOnlyPackageVersion) && bool.Parse(BuildModel.Identity.IsReleaseOnlyPackageVersion))
|| SkipSafetyChecks)
{
return;
}
foreach (var packagesPerCategory in PackagesByCategory)
{
var category = packagesPerCategory.Key;
var packages = packagesPerCategory.Value;
if (FeedConfigs.TryGetValue(category, out HashSet<TargetFeedConfig> feedConfigsForCategory))
{
foreach (var feedConfig in feedConfigsForCategory)
{
// Look at the version numbers. If any of the packages here are stable and about to be published to a
// non-isolated feed, then issue an error. Isolated feeds may recieve all packages.
if (feedConfig.Isolated)
{
continue;
}
HashSet<PackageArtifactModel> filteredPackages = FilterPackages(packages, feedConfig);
foreach (var package in filteredPackages)
{
// Special case. Four part versions should publish to non-isolated feeds
if (FourPartVersionRegex.IsMatch(package.Version))
{
continue;
}
if (!NuGetVersion.TryParse(package.Version, out NuGetVersion version))
{
Log.LogError($"Package '{package.Id}' has invalid version '{package.Version}'");
}
// We want to avoid pushing non-final bits with final version numbers to feeds that are in general
// use by the public. This is for technical (can't overwrite the original packages) reasons as well as
// to avoid confusion. Because .NET core generally brands its "final" bits without prerelease version
// suffixes (e.g. 3.0.0-preview1), test to see whether a prerelease suffix exists.
else if (!version.IsPrerelease)
{
Log.LogError($"Package '{package.Id}' has stable version '{package.Version}' but is targeted at a non-isolated feed '{feedConfig.TargetURL}'");
}
}
}
}
}
}
/// <summary>
/// Handle package publishing for all the feed configs.
/// </summary>
/// <param name="client">Maestro API client</param>
/// <param name="buildAssets">Assets information about build being published.</param>
/// <returns>Task</returns>
protected async Task HandlePackagePublishingAsync(Dictionary<string, HashSet<Asset>> buildAssets)
{
List<Task> publishTasks = new List<Task>();
// Just log a empty line for better visualization of the logs
Log.LogMessage(MessageImportance.High, "\nBegin publishing of packages: ");
foreach (var packagesPerCategory in PackagesByCategory)
{
var category = packagesPerCategory.Key;
var packages = packagesPerCategory.Value;
if (FeedConfigs.TryGetValue(category, out HashSet<TargetFeedConfig> feedConfigsForCategory))
{
foreach (var feedConfig in feedConfigsForCategory)
{
HashSet<PackageArtifactModel> filteredPackages = FilterPackages(packages, feedConfig);
foreach (var package in filteredPackages)
{
string isolatedString = feedConfig.Isolated ? "Isolated" : "Non-Isolated";
string internalString = feedConfig.Internal ? $", Internal" : ", Public";
string shippingString = package.NonShipping ? "NonShipping" : "Shipping";
Log.LogMessage(MessageImportance.High, $"Package {package.Id}@{package.Version} ({shippingString}) should go to {feedConfig.TargetURL} ({isolatedString}{internalString})");
}
switch (feedConfig.Type)
{
case FeedType.AzDoNugetFeed:
publishTasks.Add(PublishPackagesToAzDoNugetFeedAsync(filteredPackages, buildAssets, feedConfig));
break;
case FeedType.AzureStorageFeed:
publishTasks.Add(PublishPackagesToAzureStorageNugetFeedAsync(filteredPackages, buildAssets, feedConfig));
break;
default:
Log.LogError($"Unknown target feed type for category '{category}': '{feedConfig.Type}'.");
break;
}
}
}
else
{
Log.LogError($"No target feed configuration found for artifact category: '{category}'.");
}
}
await Task.WhenAll(publishTasks);
}
private HashSet<PackageArtifactModel> FilterPackages(HashSet<PackageArtifactModel> packages, TargetFeedConfig feedConfig)
{
return feedConfig.AssetSelection switch
{
AssetSelection.All => packages,
AssetSelection.NonShippingOnly => packages.Where(p => p.NonShipping).ToHashSet(),
AssetSelection.ShippingOnly => packages.Where(p => !p.NonShipping).ToHashSet(),
// Throw NIE here instead of logging an error because error would have already been logged in the
// parser for the user.
_ => throw new NotImplementedException($"Unknown asset selection type '{feedConfig.AssetSelection}'")
};
}
protected async Task HandleBlobPublishingAsync(Dictionary<string, HashSet<Asset>> buildAssets)
{
List<Task> publishTasks = new List<Task>();
// Just log a empty line for better visualization of the logs
Log.LogMessage(MessageImportance.High, "\nPublishing blobs: ");
foreach (var blobsPerCategory in BlobsByCategory)
{
var category = blobsPerCategory.Key;
var blobs = blobsPerCategory.Value;
if (FeedConfigs.TryGetValue(category, out HashSet<TargetFeedConfig> feedConfigsForCategory))
{
foreach (var feedConfig in feedConfigsForCategory)
{
HashSet<BlobArtifactModel> filteredBlobs = FilterBlobs(blobs, feedConfig);
foreach (var blob in filteredBlobs)
{
string isolatedString = feedConfig.Isolated ? "Isolated" : "Non-Isolated";
string internalString = feedConfig.Internal ? $", Internal" : ", Public";
string shippingString = blob.NonShipping ? "NonShipping" : "Shipping";
Log.LogMessage(MessageImportance.High, $"Blob {blob.Id} ({shippingString}) should go to {feedConfig.TargetURL} ({isolatedString}{internalString})");
}
switch (feedConfig.Type)
{
case FeedType.AzDoNugetFeed:
publishTasks.Add(PublishBlobsToAzDoNugetFeedAsync(filteredBlobs, buildAssets, feedConfig));
break;
case FeedType.AzureStorageFeed:
publishTasks.Add(PublishBlobsToAzureStorageNugetFeedAsync(filteredBlobs, buildAssets, feedConfig));
break;
default:
Log.LogError($"Unknown target feed type for category '{category}': '{feedConfig.Type}'.");
break;
}
}
}
else
{
Log.LogError($"No target feed configuration found for artifact category: '{category}'.");
}
}
await Task.WhenAll(publishTasks);
}
/// <summary>
/// Filter the blobs by the feed config information
/// </summary>
/// <param name="blobs"></param>
/// <param name="feedConfig"></param>
/// <returns></returns>
private HashSet<BlobArtifactModel> FilterBlobs(HashSet<BlobArtifactModel> blobs, TargetFeedConfig feedConfig)
{
return feedConfig.AssetSelection switch
{
AssetSelection.All => blobs,
AssetSelection.NonShippingOnly => blobs.Where(p => p.NonShipping).ToHashSet(),
AssetSelection.ShippingOnly => blobs.Where(p => !p.NonShipping).ToHashSet(),
// Throw NYI here instead of logging an error because error would have already been logged in the
// parser for the user.
_ => throw new NotImplementedException("Unknown asset selection type '{feedConfig.AssetSelection}'")
};
}
/// <summary>
/// Split the artifacts into categories.
///
/// Categories are either specified explicitly when publishing (with the asset attribute "Category", separated by ';'),
/// or they are inferred based on the extension of the asset.
/// </summary>
/// <param name="buildModel"></param>
public void SplitArtifactsInCategories(BuildModel buildModel)
{
foreach (var packageAsset in buildModel.Artifacts.Packages)
{
string categories = string.Empty;
if (!packageAsset.Attributes.TryGetValue("Category", out categories))
{
// Package artifacts don't have extensions. They are always nupkgs.
// Set the category explicitly to "PACKAGE"
categories = GeneralUtils.PackagesCategory;
}
foreach (var category in categories.Split(';'))
{
if (!Enum.TryParse(category, ignoreCase: true, out TargetFeedContentType categoryKey))
{
Log.LogError($"Invalid target feed config category '{category}'.");
}
if (PackagesByCategory.ContainsKey(categoryKey))
{
PackagesByCategory[categoryKey].Add(packageAsset);
}
else
{
PackagesByCategory[categoryKey] = new HashSet<PackageArtifactModel>() { packageAsset };
}
}
}
foreach (var blobAsset in buildModel.Artifacts.Blobs)
{
string categories = string.Empty;
if (!blobAsset.Attributes.TryGetValue("Category", out categories))
{
categories = GeneralUtils.InferCategory(blobAsset.Id, Log);
}
foreach (var category in categories.Split(';'))
{
if (!Enum.TryParse(category, ignoreCase: true, out TargetFeedContentType categoryKey))
{
Log.LogError($"Invalid target feed config category '{category}'.");
}
if (BlobsByCategory.ContainsKey(categoryKey))
{
BlobsByCategory[categoryKey].Add(blobAsset);
}
else
{
BlobsByCategory[categoryKey] = new HashSet<BlobArtifactModel>() { blobAsset };
}
}
}
}
private async Task PublishPackagesToAzDoNugetFeedAsync(
HashSet<PackageArtifactModel> packagesToPublish,
Dictionary<string, HashSet<Asset>> buildAssets,
TargetFeedConfig feedConfig)
{
await PushNugetPackagesAsync(packagesToPublish, feedConfig, maxClients: MaxClients,
async (feed, httpClient, package, feedAccount, feedVisibility, feedName) =>
{
string localPackagePath = Path.Combine(PackageAssetsBasePath, $"{package.Id}.{package.Version}.nupkg");
if (!File.Exists(localPackagePath))
{
Log.LogError($"Could not locate '{package.Id}.{package.Version}' at '{localPackagePath}'");
return;
}
TryAddAssetLocation(package.Id, package.Version, buildAssets, feedConfig, AddAssetLocationToAssetAssetLocationType.NugetFeed);
await PushNugetPackageAsync(feed, httpClient, localPackagePath, package.Id, package.Version, feedAccount, feedVisibility, feedName);
});
}
/// <summary>
/// Push nuget packages to the azure devops feed.
/// </summary>
/// <param name="packagesToPublish">List of packages to publish</param>
/// <param name="feedConfig">Information about feed to publish to</param>
public async Task PushNugetPackagesAsync<T>(HashSet<T> packagesToPublish, TargetFeedConfig feedConfig, int maxClients,
Func<TargetFeedConfig, HttpClient, T, string, string, string, Task> packagePublishAction)
{
if (!packagesToPublish.Any())
{
return;
}
var parsedUri = Regex.Match(feedConfig.TargetURL, PublishingConstants.AzDoNuGetFeedPattern);
if (!parsedUri.Success)
{
Log.LogError($"Azure DevOps NuGetFeed was not in the expected format '{PublishingConstants.AzDoNuGetFeedPattern}'");
return;
}
string feedAccount = parsedUri.Groups["account"].Value;
string feedVisibility = parsedUri.Groups["visibility"].Value;
string feedName = parsedUri.Groups["feed"].Value;
using (var clientThrottle = new SemaphoreSlim(maxClients, maxClients))
{
using (HttpClient httpClient = new HttpClient(new HttpClientHandler { CheckCertificateRevocationList = true }))
{
httpClient.Timeout = TimeSpan.FromSeconds(180);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", feedConfig.Token))));
await Task.WhenAll(packagesToPublish.Select(async packageToPublish =>
{
try
{
// Wait to avoid starting too many processes.
await clientThrottle.WaitAsync();
await packagePublishAction(feedConfig, httpClient, packageToPublish, feedAccount, feedVisibility, feedName);
}
finally
{
clientThrottle.Release();
}
}));
}
}
}
/// <summary>
/// Push a single package to an Azure DevOps nuget feed.
/// </summary>
/// <param name="feedConfig">Infos about the target feed</param>
/// <param name="packageToPublish">Package to push</param>
/// <returns>Task</returns>
/// <remarks>
/// This method attempts to take the most efficient path to push the package.
///
/// There are four cases:
/// - Package does not exist on the target feed, and is pushed normally
/// - Package exists with bitwise-identical contents
/// - Package exists with non-matching contents
/// - Azure DevOps is having some issue meaning we didn't succeed to publish at first.
///
/// The second case is by far the most common. So, we first attempt to push the
/// package normally using nuget.exe. If this fails, this could mean any number of
/// things (like failed auth). But in normal circumstances, this might mean the
/// package already exists. This either means that we are attempting to push the
/// same package, or attemtping to push a different package with the same id and
/// version. The second case is an error, as Azure DevOps feeds are immutable,
/// the former is simply a case where we should continue onward.
///
/// To handle the third case we rely on the call to compare file contents
/// `CompareLocalPackageToFeedPackage` to return PackageFeedStatus.DoesNotExist,
/// meaning that it got a 404 when looking up the file in the feed - to trigger
/// a retry on the publish operation. This was implemented this way because we
/// didn't want to rely on parsing the output of the push operation - which does
/// a call to `nuget.exe` behind the scenes.
/// </remarks>
public async Task PushNugetPackageAsync(
TargetFeedConfig feedConfig,
HttpClient client,
string localPackageLocation,
string id,
string version,
string feedAccount,
string feedVisibility,
string feedName,
Func<string, string, HttpClient, MsBuildUtils.TaskLoggingHelper, Task<PackageFeedStatus>> CompareLocalPackageToFeedPackageCallBack = null,
Func<string, string, Task<ProcessExecutionResult>> RunProcessAndGetOutputsCallBack = null
)
{
// Using these callbacks we can mock up functionality when testing.
CompareLocalPackageToFeedPackageCallBack ??= GeneralUtils.CompareLocalPackageToFeedPackage;
RunProcessAndGetOutputsCallBack ??= GeneralUtils.RunProcessAndGetOutputsAsync;
ProcessExecutionResult nugetResult = null;
var packageStatus = GeneralUtils.PackageFeedStatus.Unknown;
try
{
Log.LogMessage(MessageImportance.Normal, $"Pushing local package {localPackageLocation} to target feed {feedConfig.TargetURL}");
int attemptIndex = 0;
do
{
attemptIndex++;
// The feed key when pushing to AzDo feeds is "AzureDevOps" (works with the credential helper).
nugetResult = await RunProcessAndGetOutputsCallBack(NugetPath, $"push \"{localPackageLocation}\" -Source \"{feedConfig.TargetURL}\" -NonInteractive -ApiKey AzureDevOps -Verbosity quiet");
if (nugetResult.ExitCode == 0)
{
// We have just pushed this package so we know it exists and is identical to our local copy
packageStatus = GeneralUtils.PackageFeedStatus.ExistsAndIdenticalToLocal;
break;
}
Log.LogMessage(MessageImportance.Low, $"Attempt # {attemptIndex} failed to push {localPackageLocation}, attempting to determine whether the package already existed on the feed with the same content. Nuget exit code = {nugetResult.ExitCode}");
string packageContentUrl = $"https://pkgs.dev.azure.com/{feedAccount}/{feedVisibility}_apis/packaging/feeds/{feedName}/nuget/packages/{id}/versions/{version}/content";
packageStatus = await CompareLocalPackageToFeedPackageCallBack(localPackageLocation, packageContentUrl, client, Log);
switch (packageStatus)
{
case GeneralUtils.PackageFeedStatus.ExistsAndIdenticalToLocal:
{
Log.LogMessage(MessageImportance.Normal, $"Package '{localPackageLocation}' already exists on '{feedConfig.TargetURL}' but has the same content; skipping push");
break;
}
case GeneralUtils.PackageFeedStatus.ExistsAndDifferent:
{
Log.LogError($"Package '{localPackageLocation}' already exists on '{feedConfig.TargetURL}' with different content.");
break;
}
default:
{
// For either case (unknown exception or 404, we will retry the push and check again. Linearly increase back-off time on each retry.
Log.LogMessage(MessageImportance.Low, $"Hit error checking package status after failed push: '{packageStatus}'. Will retry after {RetryDelayMilliseconds * attemptIndex} ms.");
await Task.Delay(RetryDelayMilliseconds * attemptIndex).ConfigureAwait(false);
break;
}
}
}
while (packageStatus != GeneralUtils.PackageFeedStatus.ExistsAndIdenticalToLocal && // Success
packageStatus != GeneralUtils.PackageFeedStatus.ExistsAndDifferent && // Give up: Non-retriable error
attemptIndex <= MaxRetryCount); // Give up: Too many retries
if (packageStatus != GeneralUtils.PackageFeedStatus.ExistsAndIdenticalToLocal)
{
Log.LogError($"Failed to publish package '{id}@{version}' to '{feedConfig.TargetURL}' after {MaxRetryCount} attempts. (Final status: {packageStatus})");
}
else
{
Log.LogMessage(MessageImportance.High, $"Succeeded publishing package '{localPackageLocation}' to feed {feedConfig.TargetURL}");
}
}
catch (Exception e)
{
Log.LogError($"Unexpected exception pushing package '{id}@{version}': {e.Message}");
}
if (packageStatus != GeneralUtils.PackageFeedStatus.ExistsAndIdenticalToLocal && nugetResult?.ExitCode != 0)
{
Log.LogError($"Output from nuget.exe: {Environment.NewLine}StdOut:{Environment.NewLine}{nugetResult.StandardOut}{Environment.NewLine}StdErr:{Environment.NewLine}{nugetResult.StandardError}");
}
}
private async Task PublishBlobsToAzDoNugetFeedAsync(
HashSet<BlobArtifactModel> blobsToPublish,
Dictionary<string, HashSet<Asset>> buildAssets,
TargetFeedConfig feedConfig)
{
HashSet<BlobArtifactModel> packagesToPublish = new HashSet<BlobArtifactModel>();
foreach (var blob in blobsToPublish)
{
// Applies to symbol packages and core-sdk's VS feed packages
if (blob.Id.EndsWith(GeneralUtils.PackageSuffix, StringComparison.OrdinalIgnoreCase))
{
packagesToPublish.Add(blob);
}
else
{
Log.LogWarning($"AzDO feed publishing not available for blobs. Blob '{blob.Id}' was not published.");
}
}
await PushNugetPackagesAsync<BlobArtifactModel>(packagesToPublish, feedConfig, maxClients: MaxClients,
async (feed, httpClient, blob, feedAccount, feedVisibility, feedName) =>
{
if (TryAddAssetLocation(blob.Id, assetVersion: null, buildAssets, feedConfig, AddAssetLocationToAssetAssetLocationType.Container))
{
// Determine the local path to the blob
string fileName = Path.GetFileName(blob.Id);
string localBlobPath = Path.Combine(BlobAssetsBasePath, fileName);
if (!File.Exists(localBlobPath))
{
Log.LogError($"Could not locate '{blob.Id} at '{localBlobPath}'");
return;
}
string id;
string version;
// Determine package ID and version by asking the nuget libraries
using (var packageReader = new NuGet.Packaging.PackageArchiveReader(localBlobPath))
{
PackageIdentity packageIdentity = packageReader.GetIdentity();
id = packageIdentity.Id;
version = packageIdentity.Version.ToString();
}
await PushNugetPackageAsync(feed, httpClient, localBlobPath, id, version, feedAccount, feedVisibility, feedName);
}
});
}
private async Task PublishPackagesToAzureStorageNugetFeedAsync(
HashSet<PackageArtifactModel> packagesToPublish,
Dictionary<string, HashSet<Asset>> buildAssets,
TargetFeedConfig feedConfig)
{
var packages = packagesToPublish.Select(p =>
{
var localPackagePath = Path.Combine(PackageAssetsBasePath, $"{p.Id}.{p.Version}.nupkg");
if (!File.Exists(localPackagePath))
{
Log.LogError($"Could not locate '{p.Id}.{p.Version}' at '{localPackagePath}'");
}
return localPackagePath;
});
if (Log.HasLoggedErrors)
{
return;
}
var blobFeedAction = CreateBlobFeedAction(feedConfig);
var pushOptions = new PushOptions
{
AllowOverwrite = feedConfig.AllowOverwrite,
PassIfExistingItemIdentical = true
};
packagesToPublish
.ToList()
.ForEach(package => TryAddAssetLocation(package.Id, package.Version, buildAssets, feedConfig, AddAssetLocationToAssetAssetLocationType.NugetFeed));
await blobFeedAction.PushToFeedAsync(packages, pushOptions);
}
private async Task PublishBlobsToAzureStorageNugetFeedAsync(
HashSet<BlobArtifactModel> blobsToPublish,
Dictionary<string, HashSet<Asset>> buildAssets,
TargetFeedConfig feedConfig)
{
var blobs = blobsToPublish
.Select(blob =>
{
var fileName = Path.GetFileName(blob.Id);
var localBlobPath = Path.Combine(BlobAssetsBasePath, fileName);
if (!File.Exists(localBlobPath))
{
Log.LogError($"Could not locate '{blob.Id} at '{localBlobPath}'");
}
return new Microsoft.Build.Utilities.TaskItem(localBlobPath, new Dictionary<string, string>
{
{"RelativeBlobPath", blob.Id}
});
})
.ToArray();
if (Log.HasLoggedErrors)
{
return;
}
var blobFeedAction = CreateBlobFeedAction(feedConfig);
var pushOptions = new PushOptions
{
AllowOverwrite = feedConfig.AllowOverwrite,
PassIfExistingItemIdentical = true
};
blobsToPublish
.ToList()
.ForEach(blob => TryAddAssetLocation(blob.Id, assetVersion: null, buildAssets, feedConfig, AddAssetLocationToAssetAssetLocationType.Container));
await blobFeedAction.PublishToFlatContainerAsync(blobs, maxClients: MaxClients, pushOptions);
if (LinkManager == null)
{
LinkManager = new LatestLinksManager(AkaMSClientId, AkaMSClientSecret, AkaMSTenant, AkaMSGroupOwner, AkaMSCreatedBy, AkaMsOwners, Log);
}
// The latest links should be updated only after the publishing is complete, to avoid
// dead links in the interim.
await LinkManager.CreateOrUpdateLatestLinksAsync(blobsToPublish, feedConfig, PublishingConstants.ExpectedFeedUrlSuffix.Length);
}
private BlobFeedAction CreateBlobFeedAction(TargetFeedConfig feedConfig)
{
var proxyBackedFeedMatch = Regex.Match(feedConfig.TargetURL, PublishingConstants.AzureStorageProxyFeedPattern);
var proxyBackedStaticFeedMatch = Regex.Match(feedConfig.TargetURL, PublishingConstants.AzureStorageProxyFeedStaticPattern);
var azureStorageStaticBlobFeedMatch = Regex.Match(feedConfig.TargetURL, PublishingConstants.AzureStorageStaticBlobFeedPattern);
if (proxyBackedFeedMatch.Success || proxyBackedStaticFeedMatch.Success)
{
var regexMatch = (proxyBackedFeedMatch.Success) ? proxyBackedFeedMatch : proxyBackedStaticFeedMatch;
var containerName = regexMatch.Groups["container"].Value;
var baseFeedName = regexMatch.Groups["baseFeedName"].Value;
var feedURL = regexMatch.Groups["feedURL"].Value;
var storageAccountName = "dotnetfeed";
// Initialize the feed using sleet
SleetSource sleetSource = new SleetSource()
{
Name = baseFeedName,
Type = "azure",
BaseUri = feedURL,
AccountName = storageAccountName,
Container = containerName,
FeedSubPath = baseFeedName,
ConnectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={feedConfig.Token};EndpointSuffix=core.windows.net"
};
return new BlobFeedAction(sleetSource, feedConfig.Token, Log);
}
else if (azureStorageStaticBlobFeedMatch.Success)
{
return new BlobFeedAction(feedConfig.TargetURL, feedConfig.Token, Log);
}
else
{
Log.LogError($"Could not parse Azure feed URL: '{feedConfig.TargetURL}'");
return null;
}
}
protected bool AnyMissingRequiredProperty()
{
foreach (PropertyInfo prop in this.GetType().GetProperties())
{
RequiredAttribute attribute =
(RequiredAttribute)Attribute.GetCustomAttribute(prop, typeof(RequiredAttribute));
if (attribute != null)
{
string value = prop.GetValue(this, null)?.ToString();
if (string.IsNullOrEmpty(value))
{
Log.LogError($"The property {prop.Name} is required but doesn't have a value set.");
}
}
}
AnyMissingRequiredBaseProperties();
return Log.HasLoggedErrors;
}
protected bool AnyMissingRequiredBaseProperties()
{
if (string.IsNullOrEmpty(BlobAssetsBasePath))
{
Log.LogError($"The property {nameof(BlobAssetsBasePath)} is required but doesn't have a value set.");
}
if (string.IsNullOrEmpty(PackageAssetsBasePath))
{
Log.LogError($"The property {nameof(PackageAssetsBasePath)} is required but doesn't have a value set.");
}
if (BARBuildId == 0)
{
Log.LogError($"The property {nameof(BARBuildId)} is required but doesn't have a value set.");
}
if (string.IsNullOrEmpty(MaestroApiEndpoint))
{
Log.LogError($"The property {nameof(MaestroApiEndpoint)} is required but doesn't have a value set.");
}
if (string.IsNullOrEmpty(BuildAssetRegistryToken))
{
Log.LogError($"The property {nameof(BuildAssetRegistryToken)} is required but doesn't have a value set.");
}
return Log.HasLoggedErrors;
}
}
}
| 47.689581 | 262 | 0.57186 | [
"MIT"
] | AdamYoblick/arcade | src/Microsoft.DotNet.Build.Tasks.Feed/src/PublishArtifactsInManifestBase.cs | 44,399 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MvcClient.Models;
using Newtonsoft.Json.Linq;
namespace MvcClient.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
}
public async Task<IActionResult> CallApi()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var content = await client.GetStringAsync("https://localhost:6001/api/chat");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 30.419355 | 112 | 0.668081 | [
"MIT"
] | dnonn/PersonalWebsite | src/Web/MvcClient/Controllers/HomeController.cs | 1,888 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace RapidGUI
{
public static partial class TypeUtility
{
static readonly string ListInterfaceStr = "IList`1";
public static Type GetListInterface(Type type) => type.GetInterface(ListInterfaceStr);
public static bool IsList(Type type) => GetListInterface(type) != null;
static Dictionary<Type, bool> multiLineTable = new Dictionary<Type, bool>();
public static bool IsMultiLine(Type type)
{
bool ret;
if (!multiLineTable.TryGetValue(type, out ret))
{
var infoList = GetMemberInfoList(type);
ret = infoList.Any(info => info.range != null);
if (!ret)
{
var elemtTypes = infoList.Select(info => info.MemberType);
ret = elemtTypes.Any(t => IsRecursive(t) || IsList(t))
|| (elemtTypes.Count() > 4);
}
multiLineTable[type] = ret;
}
return ret;
}
static Dictionary<Type, bool> isRecursiveTable = new Dictionary<Type, bool>();
public static bool IsRecursive(Type type)
{
if (!isRecursiveTable.TryGetValue(type, out var ret))
{
ret = GetMemberInfoList(type).Any();
isRecursiveTable[type] = ret;
}
return ret;
}
}
} | 29.76 | 94 | 0.540995 | [
"MIT"
] | Craxy/Parkitect-HideScenery | src/HideScenery/RapidGui/Component/Utilities/TypeUtility.cs | 1,490 | C# |
#pragma warning disable 618
using System.Collections.Generic;
namespace OpenRasta.OperationModel.Interceptors
{
public interface IOperationInterceptorProvider
{
IEnumerable<IOperationInterceptor> GetInterceptors(IOperation operation);
}
}
#pragma warning restore 618 | 24.083333 | 78 | 0.792388 | [
"MIT"
] | openrasta/openrasta-core | src/OpenRasta/OperationModel/Interceptors/IOperationInterceptorProvider.cs | 289 | C# |
using System;
namespace CarRentalSystem.Controllers
{
using System.Web.Mvc;
using CarRentalSystem.Models.Cars;
using Microsoft.AspNet.Identity;
using CarRentalSystem.Data;
using System.Net;
using System.Linq;
using CarRentalSystem.Models.Renting;
public class CarsController : Controller
{
public ActionResult All(int page = 1, string user = null, string search = null)
{
var db = new CarsDbContext();
var pageSize = 5;
var carsQuery = db.Cars.AsQueryable();
if (search != null)
{
carsQuery = carsQuery
.Where(c => c.Make.ToLower().Contains(search.ToLower()) ||
c.Model.ToLower().Contains(search.ToLower()) ||
c.Year.ToString().Contains(search) ||
c.Color.ToLower().Contains(search.ToLower()));
}
if (user != null && user != string.Empty)
{
carsQuery = carsQuery
.Where(c => c.Owner.Email == user);
}
var cars = carsQuery
.OrderByDescending(c => c.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(c => new CarListingModel()
{
Make = c.Make,
Model = c.Model,
Year = c.Year,
ImageUrl = c.ImageUrl,
Id = c.Id,
PricePerDay = c.PricePerDay,
IsRented = c.IsRented,
})
.ToList();
ViewBag.CurrentPage = page;
return View(cars);
}
[Authorize]
[HttpGet]
public ActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult Create(CreateCarModel carModel)
{
if (this.ModelState.IsValid)
{
var ownerId = this.User.Identity.GetUserId();
var car = new Car
{
Make = carModel.Make,
Model = carModel.Model,
Color = carModel.Color,
Engine = carModel.Engine,
EngineType = carModel.EngineType,
ImageUrl = carModel.ImageUrl,
Power = carModel.Power,
PricePerDay = carModel.PricePerDay,
Year = carModel.Year,
OwnerId = ownerId,
};
var db = new CarsDbContext();
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Details", new {id = car.Id});
}
return View(carModel);
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var db = new CarsDbContext();
var car = db.Cars
.Where(c => c.Id == id)
.Select(c => new CarDetailsModel()
{
Id = c.Id,
Make = c.Make,
Model = c.Model,
EngineType = c.EngineType,
ImageUrl = c.ImageUrl,
Year = c.Year,
Color = c.Color,
Power = c.Power,
PricePerDay = c.PricePerDay,
Engine = c.Engine,
IsRented = c.IsRented,
TotalRents = c.Rentings.Count,
ContactInformation = c.Owner.Email,
})
.FirstOrDefault();
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[Authorize]
[HttpGet]
public ActionResult Rent(RentCarModel rentCarModel)
{
if (rentCarModel.Days < 1 || rentCarModel.Days > 10)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var db = new CarsDbContext();
var car = db.Cars
.Where(c => c.Id == rentCarModel.CarId)
.Select(c => new
{
c.IsRented,
FullName = c.Make + " " + c.Model + " (" + c.Year + ")",
c.PricePerDay,
c.ImageUrl
})
.FirstOrDefault();
if (car == null || car.IsRented)
{
return HttpNotFound();
}
rentCarModel.CarImageUrl = car.ImageUrl;
rentCarModel.CarName = car.FullName;
rentCarModel.PricePerDay = car.PricePerDay;
rentCarModel.TotalPrice = car.PricePerDay * rentCarModel.Days;
return View(rentCarModel);
}
[Authorize]
[HttpPost]
public ActionResult Rent(int carId, int days)
{
var db = new CarsDbContext();
var car = db.Cars
.Where(c => c.Id == carId)
.FirstOrDefault();
var userId = this.User.Identity.GetUserId();
if (car == null || car.IsRented || car.OwnerId == userId)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var renting = new Renting
{
CarId = carId,
Days = days,
RentedOn = DateTime.Now,
UserId = userId,
TotalPrice = days * car.PricePerDay
};
car.IsRented = true;
db.Rentings.Add(renting);
db.SaveChanges();
return RedirectToAction("Details", new {id = car.Id});
}
}
} | 29.194175 | 87 | 0.439142 | [
"MIT"
] | pirocorp/Software-Technologies | 22. C# Blog Basic Functionality/CarRentalSystem/CarRentalSystem/Controllers/CarsController.cs | 6,016 | C# |
////////////////////////////////////////////////
// © https://github.com/badhitman
////////////////////////////////////////////////
using System;
using System.Linq;
using ab.Model;
using Android.Content;
using Android.Views;
using AndroidX.RecyclerView.Widget;
using Java.Lang;
using Microsoft.EntityFrameworkCore;
namespace ab.Services
{
public class ScriptsListAdapter : RecyclerView.Adapter
{
public static readonly string TAG = "● scripts-list-adapter";
public event EventHandler<int> ItemClick;
Context mContext;
public override int ItemCount { get { lock (DatabaseContext.DbLocker) { using (DatabaseContext db = new DatabaseContext()) { return db.Scripts.Count(); } } } }
public ScriptsListAdapter(Context _mContext)
{
mContext = _mContext;
}
void OnClick(int scriptId)
{
if (ItemClick != null)
ItemClick(this, scriptId);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
ScriptListItemViewHolder scriptListItemViewHolder = holder as ScriptListItemViewHolder;
lock (DatabaseContext.DbLocker)
{
using (DatabaseContext db = new DatabaseContext())
{
ScriptModel script = db.Scripts.Skip(position).Include(x => x.TriggerPort).ThenInclude(x => x.Hardware).FirstOrDefault();
scriptListItemViewHolder.ScriptId = script.Id;
//
scriptListItemViewHolder.Name.Text = script.Name;
if (script.TriggerPort != null)
{
scriptListItemViewHolder.Name.Text += $" (tg: {script.TriggerPort.Hardware.Name} > {script.TriggerPort} > {(script.TriggerPortState == true ? "ON" : (script.TriggerPortState == false ? "OFF" : "Switch"))})";
}
}
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
// Inflate the CardView for the photo:
View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.scripts_list_item, parent, false);
// Create a ViewHolder to hold view references inside the CardView:
ScriptListItemViewHolder scriptListItemViewHolder = new ScriptListItemViewHolder(itemView, OnClick);
return scriptListItemViewHolder;
}
}
} | 38.830769 | 231 | 0.596672 | [
"MIT"
] | badhitman/Xamarin-ab-log-app | server configurator/Services/scripts/ScriptsListAdapter.cs | 2,529 | C# |
#pragma checksum "..\..\CustomWindow.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "E5C175F50F409B940A03B127E73573FD2FCA32CFAA1C475CDE16C2E8C412FF68"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using HardwareMonitor;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Whush.Demo.Styles.VS2012 {
/// <summary>
/// VS2012WindowStyle
/// </summary>
public partial class VS2012WindowStyle : System.Windows.ResourceDictionary, System.Windows.Markup.IComponentConnector, System.Windows.Markup.IStyleConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/HardwareMonitor;component/customwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\CustomWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
void System.Windows.Markup.IStyleConnector.Connect(int connectionId, object target) {
System.Windows.EventSetter eventSetter;
switch (connectionId)
{
case 1:
eventSetter = new System.Windows.EventSetter();
eventSetter.Event = System.Windows.FrameworkElement.LoadedEvent;
#line 54 "..\..\CustomWindow.xaml"
eventSetter.Handler = new System.Windows.RoutedEventHandler(this.WindowLoaded);
#line default
#line hidden
((System.Windows.Style)(target)).Setters.Add(eventSetter);
break;
case 2:
#line 100 "..\..\CustomWindow.xaml"
((System.Windows.Controls.Image)(target)).MouseUp += new System.Windows.Input.MouseButtonEventHandler(this.IconMouseUp);
#line default
#line hidden
#line 101 "..\..\CustomWindow.xaml"
((System.Windows.Controls.Image)(target)).MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(this.IconMouseLeftButtonDown);
#line default
#line hidden
break;
case 3:
#line 122 "..\..\CustomWindow.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MinButtonClick);
#line default
#line hidden
break;
case 4:
#line 142 "..\..\CustomWindow.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.MaxButtonClick);
#line default
#line hidden
break;
case 5:
#line 163 "..\..\CustomWindow.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.CloseButtonClick);
#line default
#line hidden
break;
}
}
}
}
| 42.463768 | 162 | 0.639078 | [
"MIT"
] | JettFlat/WPF-hardware-monitor | HardwareMonitor/obj/Debug/CustomWindow.g.cs | 5,862 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the frauddetector-2019-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.FraudDetector.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.FraudDetector.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteBatchPredictionJob Request Marshaller
/// </summary>
public class DeleteBatchPredictionJobRequestMarshaller : IMarshaller<IRequest, DeleteBatchPredictionJobRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DeleteBatchPredictionJobRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteBatchPredictionJobRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.FraudDetector");
string target = "AWSHawksNestServiceFacade.DeleteBatchPredictionJob";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-11-15";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetJobId())
{
context.Writer.WritePropertyName("jobId");
context.Writer.Write(publicRequest.JobId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DeleteBatchPredictionJobRequestMarshaller _instance = new DeleteBatchPredictionJobRequestMarshaller();
internal static DeleteBatchPredictionJobRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteBatchPredictionJobRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.165049 | 163 | 0.644027 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/FraudDetector/Generated/Model/Internal/MarshallTransformations/DeleteBatchPredictionJobRequestMarshaller.cs | 3,725 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ItemConnection : MonoBehaviour {
protected bool removed;
protected abstract ItemConnector Connector { get; set; }
public void Remove() {
if (removed) {
Logger.Print("Re-Removing item conn");
return;
}
Logger.PrintVariables("Removing item conn", name);
removed = true;
OnRemoveConnection();
Destroy(this);
Connector.OnReleaseItem();
}
protected virtual void OnRemoveConnection() { }
protected virtual void Start() {
//NullCheck.Check(Connector);
}
protected virtual void Update() {
}
#region Static methods
public static ChildConnection AddChildConnection(ItemConnector connector, Transform target, Interactable addTo) {
return ChildConnection.Configuration(connector, target, addTo);
}
public static LuerlockItemConnection AddLuerlockItemConnection(ItemConnector connector, Transform target, Interactable addTo) {
return LuerlockItemConnection.Configuration(connector, target, addTo);
}
public static LuerlockLooseItemConnection AddLuerlockLooseItemConnection(ItemConnector connector, Transform target, Interactable addTo) {
return LuerlockLooseItemConnection.Configuration(connector, target, addTo);
}
public static JointConnection AddJointConnection(ItemConnector connector, Transform target, Interactable addTo) {
return JointConnection.Configuration(connector, target, addTo);
}
#endregion
}
| 32.918367 | 141 | 0.719157 | [
"MIT"
] | ohtuprojekti-farmasia/farmasia-vr | Assets/Scripts/Objects/Connections/ItemConnection.cs | 1,615 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace HandTracingUI.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HandTracingUI.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 33.861111 | 179 | 0.575472 | [
"Apache-2.0"
] | AniChikage/HandTrackingUI | HandTracingUI/Properties/Resources.Designer.cs | 2,768 | C# |
using Abp.Runtime.Validation;
using HC.WeChat.Dto;
using HC.WeChat.WeChatGroups;
namespace HC.WeChat.WeChatGroups.Dtos
{
public class GetWeChatGroupsInput : PagedAndSortedInputDto, IShouldNormalize
{
////BCC/ BEGIN CUSTOM CODE SECTION
////ECC/ END CUSTOM CODE SECTION
/// <summary>
/// 模糊搜索使用的关键字
/// </summary>
public string Filter { get; set; }
/// <summary>
/// 组名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 正常化排序使用
/// </summary>
public void Normalize()
{
if (string.IsNullOrEmpty(Sorting))
{
Sorting = "Id";
}
}
}
}
| 21.794118 | 80 | 0.511471 | [
"MIT"
] | DonaldTdz/GAWeChat | aspnet-core/src/HC.WeChat.Application/WeChatGroups/Dtos/GetWeChatGroupsInput.cs | 781 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.Common.Utility;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Microsoft.Practices.EnterpriseLibrary.PolicyInjection
{
/// <summary>
/// A non-static facade class that provides the main entry point into the
/// Policy Injection Application Block. Methods on this class
/// create intercepted objects, or wrap existing instances with
/// interceptors.
/// </summary>
/// <remarks>
/// <para>
/// This facade can be initialized with either an <see cref="IServiceLocator"/> or an
/// <see cref="IConfigurationSource"/>. In the latter case, a new container will be created and it will be disposed
/// when the policy injector is disposed.
/// </para>
/// </remarks>
public class PolicyInjector : IDisposable
{
private IUnityContainer container;
private readonly bool ownsContainer;
private InstanceInterceptionPolicySettingInjectionMember instanceInterceptionPolicySettingInjectionMember;
/// <summary>
/// Initializes a new instance of the <see cref="PolicyInjector"/> class with the specified configuration source.
/// </summary>
/// <param name="configurationSource">The configuration source from which to retrieve configuration information.</param>
/// <exception cref="ArgumentNullException"><paramref name="configurationSource"/> is <see langword="null"/>.</exception>
public PolicyInjector(IConfigurationSource configurationSource)
{
if (configurationSource == null)
{
throw new ArgumentNullException("configurationSource");
}
this.ownsContainer = true;
Initialize(CreateContainer(configurationSource));
}
/// <summary>
/// Initializes a new instance of the <see cref="PolicyInjector"/> class with the specified service locator.
/// </summary>
/// <param name="serviceLocator">The service locator from which an <see cref="IUnityContainer"/> can be resolved
/// to perform interception.</param>
/// <exception cref="ArgumentNullException"><paramref name="serviceLocator"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">An <see cref="IUnityContainer"/> cannot be resolved from the
/// <paramref name="serviceLocator"/>, or the resolved container does not have the <see cref="Interception"/>
/// extension.</exception>
public PolicyInjector(IServiceLocator serviceLocator)
{
if (serviceLocator == null)
{
throw new ArgumentNullException("serviceLocator");
}
Initialize(GetUnityContainer(serviceLocator));
}
/// <summary>
/// Initializes a new instance of the <see cref="PolicyInjector"/> class with the specified container.
/// </summary>
/// <param name="container">The container to perform interception.</param>
/// <exception cref="ArgumentNullException"><paramref name="container"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">The container does not have the <see cref="Interception"/>
/// extension.</exception>
public PolicyInjector(IUnityContainer container)
{
Guard.ArgumentNotNull(container, "container");
Initialize(container);
}
private void Initialize(IUnityContainer container)
{
if (container.Configure<Interception>() == null)
{
throw new ArgumentException("Container does not have the interception extension", "container");
}
if (container.Configure<TransientPolicyBuildUpExtension>() == null)
{
throw new ArgumentException("Container does not have the transient buildup extension", "container");
}
this.container = container;
this.instanceInterceptionPolicySettingInjectionMember =
new InstanceInterceptionPolicySettingInjectionMember(new TransparentProxyInterceptor());
}
/// <summary>
/// Creates a proxy for the given object that adds interception policies.
/// </summary>
/// <remarks>
/// Despite the name of the <typeparamref name="TInterface"/> parameter, this
/// may be any type that the instance is assignable to, including both interfaces
/// that it implements and the concrete type of the object.
/// </remarks>
/// <typeparam name="TInterface">Type of the proxy to return.</typeparam>
/// <param name="instance">Instance object to wrap.</param>
/// <returns>The proxy for the instance, or the raw object if no policies apply.</returns>
public TInterface Wrap<TInterface>(object instance)
{
return (TInterface)Wrap(typeof(TInterface), instance);
}
/// <summary>
/// Creates a proxy for the given object that adds interception policies.
/// </summary>
/// <param name="typeToReturn">Type of the proxy to return.</param>
/// <param name="instance">Instance object to wrap.</param>
/// <returns>The proxy for the instance, or the raw object if no policies apply.</returns>
public object Wrap(Type typeToReturn, object instance)
{
Guard.ArgumentNotNull(typeToReturn, "typeToReturn");
Guard.ArgumentNotNull(instance, "instance");
Microsoft.Practices.Unity.Utility.Guard.InstanceIsAssignable(typeToReturn, instance, "instance");
if (this.container == null)
{
throw new ObjectDisposedException("policyInjector");
}
return this.container.Configure<TransientPolicyBuildUpExtension>()
.BuildUp(
typeToReturn,
instance,
null,
this.instanceInterceptionPolicySettingInjectionMember);
}
/// <summary>
/// Creates a new object of type <typeparamref name="TObject"/> and
/// adds interception as needed to match the policies specified for the injector.
/// </summary>
/// <typeparam name="TObject">Type of object to create.</typeparam>
/// <param name="args">Arguments to pass to the <typeparamref name="TObject"/> constructor.</param>
/// <returns>The intercepted object (or possibly a raw instance if no policies apply).</returns>
public TObject Create<TObject>(params object[] args)
{
return (TObject)Create(typeof(TObject), args);
}
/// <summary>
/// Creates a new object of type <typeparamref name="TObject"/> and
/// adds interception as needed to match the policies specified for the injector.
/// </summary>
/// <typeparam name="TObject">Concrete object type to create.</typeparam>
/// <typeparam name="TInterface">Type of reference to return. Must be an interface the object implements.</typeparam>
/// <param name="args">Arguments to pass to the <typeparamref name="TObject"/> constructor.</param>
/// <returns>The intercepted object (or possibly a raw instance if no policies apply).</returns>
public TInterface Create<TObject, TInterface>(params object[] args)
where TObject : TInterface
{
return (TInterface)Create(typeof(TObject), typeof(TInterface), args);
}
/// <summary>
/// Creates a new object of type <paramref name="typeToCreate"/> and
/// adds interception as needed to match the policies specified for the injector.
/// </summary>
/// <param name="typeToCreate">Type of object to create.</param>
/// <param name="args">Arguments to pass to the <paramref name="typeToCreate"/> constructor.</param>
/// <returns>The intercepted object (or possibly a raw instance if no policies apply).</returns>
public object Create(Type typeToCreate, params object[] args)
{
return Create(typeToCreate, typeToCreate, args);
}
/// <summary>
/// Creates a new object of type <paramref name="typeToCreate"/> and
/// adds interception as needed to match the policies specified for the injector.
/// </summary>
/// <param name="typeToCreate">Concrete object type to create.</param>
/// <param name="typeToReturn">Type of reference to return. Must be an interface the object implements.</param>
/// <param name="args">Arguments to pass to the <paramref name="typeToCreate"/> constructor.</param>
/// <returns>The intercepted object (or possibly a raw instance if no policies apply).</returns>
public object Create(Type typeToCreate, Type typeToReturn, params object[] args)
{
Guard.ArgumentNotNull(typeToCreate, "typeToCreate");
object instance = Activator.CreateInstance(typeToCreate, args);
return Wrap(typeToReturn, instance);
}
/// <summary>
/// Dispose this policy injector.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose this policy injector.
/// </summary>
/// <param name="disposing"><see langword="true"/> if being called from the IDisposable.Dispose method,
/// <see langword="false"/> if being called from a finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.container != null)
{
var containerForDisposal = this.container;
this.container = null;
if (this.ownsContainer)
{
containerForDisposal.Dispose();
}
}
}
}
private static IUnityContainer CreateContainer(IConfigurationSource configurationSource)
{
var container = new UnityContainer();
container
.AddNewExtension<Interception>()
.AddNewExtension<TransientPolicyBuildUpExtension>();
var settings = configurationSource.GetSection(PolicyInjectionSettings.SectionName) as PolicyInjectionSettings;
if (settings != null)
{
settings.ConfigureContainer(container);
}
return container;
}
private static IUnityContainer GetUnityContainer(IServiceLocator serviceLocator)
{
try
{
return serviceLocator.GetInstance<IUnityContainer>();
}
catch (ActivationException e)
{
throw new InvalidOperationException("Cannot resolve container", e);
}
}
}
}
| 45.370079 | 129 | 0.626605 | [
"Apache-2.0"
] | Microsoft/policy-injection-application-block | source/Src/PolicyInjection/PolicyInjector.cs | 11,526 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GK {
public class BreakableSurface : MonoBehaviour {
public MeshFilter Filter { get; private set; }
public MeshRenderer Renderer { get; private set; }
public MeshCollider Collider { get; private set; }
public Rigidbody Rigidbody { get; private set; }
public List<Vector2> Polygon;
public float Thickness = 1.0f;
public float MinBreakArea = 0.01f;
public float MinImpactToBreak = 50.0f;
float _Area = -1.0f;
public float Area {
get {
if (_Area < 0.0f) {
_Area = Geom.Area(Polygon);
}
return _Area;
}
}
void Start() {
Reload();
}
public void Reload() {
var pos = transform.position;
if (Filter == null) Filter = GetComponent<MeshFilter>();
if (Renderer == null) Renderer = GetComponent<MeshRenderer>();
if (Collider == null) Collider = GetComponent<MeshCollider>();
if (Rigidbody == null) Rigidbody = GetComponent<Rigidbody>();
if (Polygon.Count == 0) {
// Assume it's a cube with localScale dimensions
var scale = 0.5f * transform.localScale;
Polygon.Add(new Vector2(-scale.x, -scale.y));
Polygon.Add(new Vector2(scale.x, -scale.y));
Polygon.Add(new Vector2(scale.x, scale.y));
Polygon.Add(new Vector2(-scale.x, scale.y));
Thickness = 2.0f * scale.z;
transform.localScale = Vector3.one;
}
var mesh = MeshFromPolygon(Polygon, Thickness);
Filter.sharedMesh = mesh;
Collider.sharedMesh = mesh;
}
void FixedUpdate() {
var pos = transform.position;
if (pos.magnitude > 1000.0f) {
DestroyImmediate(gameObject);
}
}
void OnCollisionEnter(Collision coll) {
if (coll.impactForceSum.magnitude > MinImpactToBreak) {
var pnt = coll.contacts[0].point;
Break((Vector2)transform.InverseTransformPoint(pnt));
}
}
static float NormalizedRandom(float mean, float stddev) {
var u1 = UnityEngine.Random.value;
var u2 = UnityEngine.Random.value;
var randStdNormal = Mathf.Sqrt(-2.0f * Mathf.Log(u1)) *
Mathf.Sin(2.0f * Mathf.PI * u2);
return mean + stddev * randStdNormal;
}
public void Break(Vector2 position) {
var area = Area;
if (area > MinBreakArea) {
var calc = new VoronoiCalculator();
var clip = new VoronoiClipper();
var sites = new Vector2[10];
for (int i = 0; i < sites.Length; i++) {
var dist = Mathf.Abs(NormalizedRandom(0.0f, 1.0f/2.0f));
var angle = 2.0f * Mathf.PI * Random.value;
sites[i] = position + new Vector2(
dist * Mathf.Cos(angle),
dist * Mathf.Sin(angle));
}
var diagram = calc.CalculateDiagram(sites);
var clipped = new List<Vector2>();
for (int i = 0; i < sites.Length; i++) {
clip.ClipSite(diagram, Polygon, i, ref clipped);
if (clipped.Count > 0) {
var newGo = Instantiate(gameObject, transform.parent);
newGo.transform.localPosition = transform.localPosition;
newGo.transform.localRotation = transform.localRotation;
var bs = newGo.GetComponent<BreakableSurface>();
bs.Thickness = Thickness;
bs.Polygon.Clear();
bs.Polygon.AddRange(clipped);
var childArea = bs.Area;
var rb = bs.GetComponent<Rigidbody>();
rb.mass = Rigidbody.mass * (childArea / area);
}
}
gameObject.active = false;
Destroy(gameObject);
}
}
static Mesh MeshFromPolygon(List<Vector2> polygon, float thickness) {
var count = polygon.Count;
// TODO: cache these things to avoid garbage
var verts = new Vector3[6 * count];
var norms = new Vector3[6 * count];
var tris = new int[3 * (4 * count - 4)];
// TODO: add UVs
var vi = 0;
var ni = 0;
var ti = 0;
var ext = 0.5f * thickness;
// Top
for (int i = 0; i < count; i++) {
verts[vi++] = new Vector3(polygon[i].x, polygon[i].y, ext);
norms[ni++] = Vector3.forward;
}
// Bottom
for (int i = 0; i < count; i++) {
verts[vi++] = new Vector3(polygon[i].x, polygon[i].y, -ext);
norms[ni++] = Vector3.back;
}
// Sides
for (int i = 0; i < count; i++) {
var iNext = i == count - 1 ? 0 : i + 1;
verts[vi++] = new Vector3(polygon[i].x, polygon[i].y, ext);
verts[vi++] = new Vector3(polygon[i].x, polygon[i].y, -ext);
verts[vi++] = new Vector3(polygon[iNext].x, polygon[iNext].y, -ext);
verts[vi++] = new Vector3(polygon[iNext].x, polygon[iNext].y, ext);
var norm = Vector3.Cross(polygon[iNext] - polygon[i], Vector3.forward).normalized;
norms[ni++] = norm;
norms[ni++] = norm;
norms[ni++] = norm;
norms[ni++] = norm;
}
for (int vert = 2; vert < count; vert++) {
tris[ti++] = 0;
tris[ti++] = vert - 1;
tris[ti++] = vert;
}
for (int vert = 2; vert < count; vert++) {
tris[ti++] = count;
tris[ti++] = count + vert;
tris[ti++] = count + vert - 1;
}
for (int vert = 0; vert < count; vert++) {
var si = 2*count + 4*vert;
tris[ti++] = si;
tris[ti++] = si + 1;
tris[ti++] = si + 2;
tris[ti++] = si;
tris[ti++] = si + 2;
tris[ti++] = si + 3;
}
Debug.Assert(ti == tris.Length);
Debug.Assert(vi == verts.Length);
var mesh = new Mesh();
mesh.vertices = verts;
mesh.triangles = tris;
mesh.normals = norms;
return mesh;
}
}
}
| 24.394495 | 86 | 0.605679 | [
"MIT"
] | phamngocanit82/PNA-Unity3D | ShootPanel/Assets/Scripts/BreakableSurface.cs | 5,320 | C# |
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using MyInvest.Infrastructure.Crosscutting.AspNetIdentity.Context;
namespace MyInvest.Infrastructure.Crosscutting.AspNetIdentity.Configuration
{
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
}
| 33.391304 | 129 | 0.755208 | [
"MIT"
] | jonas1307/MyInvest | src/MyInvest.Infrastructure.Crosscutting.AspNetIdentity/Configuration/ApplicationRoleManager.cs | 770 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Export.Database.DbProviders.Algo
File: BaseDbProvider.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Export.Database.DbProviders
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Linq;
using Ecng.Common;
using Ecng.Data;
abstract class BaseDbProvider : Disposable
{
public static BaseDbProvider Create(DatabaseConnectionPair connection)
{
if (connection == null)
throw new ArgumentNullException(nameof(connection));
if (connection.Provider is SqlServerDatabaseProvider)
return new MSSQLDbProvider(connection);
else
return new SQLiteDbProvider(connection);
}
protected BaseDbProvider(DatabaseConnectionPair connection)
{
if (connection == null)
throw new ArgumentNullException(nameof(connection));
Database = new Database("Export", connection.ConnectionString) { Provider = connection.Provider };
}
protected override void DisposeManaged()
{
Database.Dispose();
base.DisposeManaged();
}
/// <summary>
/// To check uniqueness of data in the database. It effects performance.
/// </summary>
public bool CheckUnique { get; set; }
public Database Database { get; }
public abstract void InsertBatch(Table table, IEnumerable<IDictionary<string, object>> parameters);
public void CreateIfNotExists(Table table)
{
using (var connection = Database.CreateConnection())
{
using (var command = CreateCommand(connection, CreateIsTableExistsString(table), null))
{
var result = command.ExecuteScalar();
if (result != null)
{
if (result is string value)
{
if (!value.IsEmpty())
return;
}
if (result is int i)
{
if (i != 0)
return;
}
return;
}
}
using (var command = CreateCommand(connection, CreateCreateTableString(table), null))
command.ExecuteNonQuery();
}
}
protected IDbCommand CreateCommand(DbConnection connection, string sqlString, IDictionary<string, object> parameters)
{
var command = Database.Provider.CreateCommand(sqlString, CommandType.Text);
command.Connection = connection;
if (parameters != null)
{
foreach (var par in parameters)
{
var dbParam = Database.Provider.Factory.CreateParameter();
if (dbParam == null)
throw new InvalidOperationException();
dbParam.Direction = ParameterDirection.Input;
dbParam.ParameterName = par.Key;
dbParam.Value = par.Value ?? DBNull.Value;
dbParam.IsNullable = true;
command.Parameters.Add(dbParam);
}
}
return command;
}
protected virtual string CreateIsTableExistsString(Table table)
{
if (table == null)
throw new ArgumentNullException(nameof(table));
return $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{table.Name}'";
}
private string CreateCreateTableString(Table table)
{
if (table == null)
throw new ArgumentNullException(nameof(table));
var tableName = table.Name;
var sb = new StringBuilder();
sb.Append("CREATE TABLE [");
sb.Append(tableName);
sb.Append("] (");
var hasColumns = false;
foreach (var column in table.Columns)
{
hasColumns = true;
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
var type = column.DbType;
var isNullable = false;
if (type.IsGenericType && type.IsNullable())
{
isNullable = true;
type = type.GetUnderlyingType();
}
else if (type == typeof(string))
isNullable = true;
sb.Append(" ");
sb.Append(GetDbType(type, column.ValueRestriction));
if (!isNullable)
sb.Append(" NOT NULL");
sb.Append(", ");
}
var primaryKeyString = CreatePrimaryKeyString(table, table.Columns.Where(c => c.IsPrimaryKey));
if (!primaryKeyString.IsEmpty())
sb.AppendFormat(" {0}", primaryKeyString);
else if (hasColumns)
sb.Remove(sb.Length - ", ".Length, ", ".Length);
sb.Append(")");
return sb.ToString();
}
protected abstract string CreatePrimaryKeyString(Table table, IEnumerable<ColumnDescription> columns);
protected virtual string GetDbType(Type type, object restriction)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type == typeof(string))
{
if (restriction is StringRestriction srest)
{
if (srest.IsFixedSize)
return $"nchar({srest.MaxLength})";
else if (srest.MaxLength > 0)
return "nvarchar({0})".Put(srest.MaxLength == int.MaxValue ? "max" : srest.MaxLength.To<string>());
}
else
return "nvarchar(max)";
}
if (type == typeof(long))
return "bigint";
if (type == typeof(int))
return "integer";
if (type == typeof(decimal))
{
return restriction is DecimalRestriction drest
? $"decimal({drest.Precision},{drest.Scale})"
: "decimal";
}
if (type == typeof(Enum))
return "integer";
if (type == typeof(double))
return "float";
if (type == typeof(float))
return "float";
throw new NotSupportedException($"{type.Name} is not supported by {nameof(BaseDbProvider)}.");
}
}
} | 25.955157 | 119 | 0.653594 | [
"Apache-2.0"
] | Pvredev/StockSharp | Algo/Export/Database/DbProviders/BaseDbProvider.cs | 5,788 | C# |
using eLib.Database.Interfaces;
using eStationCore.IManagers;
namespace eStationCore.Store.SqlLite
{
public class EstationSqlLite : IEstation
{
private string _path;
public EstationSqlLite(string path)
{
this._path = path;
}
public ISalesManager Sales { get; }
public IOilManager Oils { get; }
public ICiternesManager Citernes { get; }
public IFuelManager Fuels { get; }
public IPompesManager Pompes { get; }
public ICustomersManager Customers { get; }
public IHrManager HumanResource { get; }
public ISecurityManager Authentication { get; }
public IEconomatManager Economat { get; }
public IDocumentsManager Documents { get; }
public IMetaManager Meta { get; }
}
}
| 29.071429 | 55 | 0.640049 | [
"MIT"
] | HalidCisse/eStation | EStationCore/Store/SqlLite/EstationSqlLite.cs | 816 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace HamburgerSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
| 26.580645 | 106 | 0.725728 | [
"MIT"
] | CNinnovation/BastaMainz2016 | UWP/AdaptiveLayouts/HamburgerSample/MainPage.xaml.cs | 826 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Android.Content;
using Android.Content.PM;
using Mindscape.Raygun4Net.Builders;
using Mindscape.Raygun4Net.Messages;
namespace Mindscape.Raygun4Net
{
public class RaygunMessageBuilder : IRaygunMessageBuilder
{
public static RaygunMessageBuilder New
{
get
{
return new RaygunMessageBuilder();
}
}
private readonly RaygunMessage _raygunMessage;
private RaygunMessageBuilder()
{
_raygunMessage = new RaygunMessage();
}
public RaygunMessage Build()
{
return _raygunMessage;
}
public IRaygunMessageBuilder SetMachineName(string machineName)
{
_raygunMessage.Details.MachineName = machineName;
return this;
}
public IRaygunMessageBuilder SetEnvironmentDetails()
{
_raygunMessage.Details.Environment = RaygunEnvironmentMessageBuilder.Build();
return this;
}
public IRaygunMessageBuilder SetExceptionDetails(Exception exception)
{
if (exception != null)
{
_raygunMessage.Details.Error = RaygunErrorMessageBuilder.Build(exception);
}
return this;
}
public IRaygunMessageBuilder SetClientDetails()
{
_raygunMessage.Details.Client = new RaygunClientMessage();
return this;
}
public IRaygunMessageBuilder SetUserCustomData(IDictionary userCustomData)
{
_raygunMessage.Details.UserCustomData = userCustomData;
return this;
}
public IRaygunMessageBuilder SetTags(IList<string> tags)
{
_raygunMessage.Details.Tags = tags;
return this;
}
public IRaygunMessageBuilder SetUser(RaygunIdentifierMessage user)
{
_raygunMessage.Details.User = user;
return this;
}
public IRaygunMessageBuilder SetVersion(string version)
{
if (String.IsNullOrWhiteSpace(version))
{
try
{
Context context = RaygunClient.Context;
PackageManager manager = context.PackageManager;
PackageInfo info = manager.GetPackageInfo(context.PackageName, 0);
version = info.VersionCode + " / " + info.VersionName;
}
catch (Exception ex)
{
RaygunLogger.Debug(string.Format("Error retrieving package version {0}", ex.Message));
}
}
if (String.IsNullOrWhiteSpace(version))
{
version = "Not supplied";
}
_raygunMessage.Details.Version = version;
return this;
}
public IRaygunMessageBuilder SetTimeStamp(DateTime? currentTime)
{
if (currentTime != null)
{
_raygunMessage.OccurredOn = currentTime.Value;
}
return this;
}
}
} | 23.871795 | 96 | 0.668099 | [
"MIT"
] | Havunen/raygun4net | Mindscape.Raygun4Net.Xamarin.Android/RaygunMessageBuilder.cs | 2,793 | C# |
/*
Original author: Dieter Vandroemme, dev at Sizing Servers Lab (https://www.sizingservers.be) @ University College of West-Flanders, Department GKG
Written in 2015
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.Collections.Generic;
namespace SizingServers.Util {
/// <summary>
/// <para>This class contains extra functionality upon FindAndReplace for searching a given text. For instance: A find next is implemented in it.</para>
/// <para>It caches the found entries in the text (rows, columns, starts, match lengths) and invalidate it's cache when needed. For instance: A new find pattern is given.</para>
/// <para>This also means that, unlike FindAndReplace, the functionality in this class is not thread safe.</para>
/// </summary>
public class FindAndReplaceHelperObject {
private List<int> _rows, _columns, _starts, _matchLengths;
private string _find, _inText;
private bool _wholeWords, _matchCase;
private int _findIndex;
/// <summary>
/// Find the next occurance of a given find pattern. When one of the given arguments is different then the last time this function was called, the find cache is invalidated.
/// </summary>
/// <param name="find">You can use *, +, - "" like before in Google. Multiline find patterns are not supported.</param>
/// <param name="inText"></param>
/// <param name="row">The row where a match is found.</param>
/// <param name="column">The column where a match is found.</param>
/// <param name="start">The start index of a find, for making text selections easier.</param>
/// <param name="matchLength">The length of the match</param>
/// <param name="wholeWords"></param>
/// <param name="matchCase"></param>
public void FindNext(string find, string inText, out int row, out int column, out int start, out int matchLength, bool wholeWords = false, bool matchCase = false) {
row = column = start = matchLength = -1;
if (_find != find || _inText != inText || _wholeWords != wholeWords || _matchCase != matchCase) {
FindAndReplace.Find(find, inText, out _rows, out _columns, out _starts, out _matchLengths, wholeWords, matchCase);
_findIndex = 0;
_find = find;
_inText = inText;
_wholeWords = wholeWords;
_matchCase = matchCase;
}
if (_rows.Count != 0) {
row = _rows[_findIndex];
column = _columns[_findIndex];
start = _starts[_findIndex];
matchLength = _matchLengths[_findIndex];
++_findIndex;
if (_findIndex == _rows.Count) _findIndex = 0;
}
}
/// <summary>
/// Find all occurances of a given find pattern. When one of the given arguments is different then the last time this function was called, the find cache is invalidated.
/// </summary>
/// <param name="find">You can use *, +, - "" like before in Google. Multiline find patterns are not supported.</param>
/// <param name="inText"></param>
/// <param name="rows">The rows where a match is found.</param>
/// <param name="columns">The columns where a match is found.</param>
/// <param name="starts">The start index of each find, for making text selections easier.</param>
/// <param name="matchLengths">The lengths of the match</param>
/// <param name="wholeWords"></param>
/// <param name="matchCase"></param>
public void FindAll(string find, string inText, out List<int> rows, out List<int> columns, out List<int> starts, out List<int> matchLengths, bool wholeWords = false, bool matchCase = false) {
if (_find != find || _inText != inText || _wholeWords != wholeWords || _matchCase != matchCase) {
FindAndReplace.Find(find, inText, out _rows, out _columns, out _starts, out _matchLengths, wholeWords, matchCase);
_find = find;
_inText = inText;
_wholeWords = wholeWords;
_matchCase = matchCase;
}
_findIndex = 0;
rows = _rows;
columns = _columns;
starts = _starts;
matchLengths = _matchLengths;
}
/// <summary>
/// Always call FindNext(...) or FindAll(...) first.
/// </summary>
/// <param name="with"></param>
/// <param name="all">True for replacing all occurances.</param>
/// <returns></returns>
public string Replace(string with, bool all) {
if (_findIndex == -1) return _inText;
string inText;
if (all) {
inText = FindAndReplace.Replace(_rows, _columns, _matchLengths, _inText, with);
} else {
int row = _rows[_findIndex];
int column = _columns[_findIndex];
int start = _starts[_findIndex];
int matchLength = _matchLengths[_findIndex];
inText = FindAndReplace.Replace(row, column, matchLength, _inText, with);
}
List<int> r, c, s, m;
FindAll(_find, inText, out r, out c, out s, out m, _wholeWords, _matchCase);
return _inText;
}
}
}
| 57.504425 | 461 | 0.618806 | [
"MIT"
] | sizingservers/sizingservers.util | SizingServers.Util/FindAndReplaceHelperObject.cs | 6,500 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NuGet;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Packaging.Signing;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.DependencyResolver;
using NuGet.Versioning;
using NuGet.Repositories;
using Sprache;
using Versatile;
using System.Text.RegularExpressions;
namespace DevAudit.AuditLibrary
{
public class NetCorePackageSource : PackageSource, IDeveloperPackageSource
{
#region Constructors
public NetCorePackageSource(Dictionary<string, object> package_source_options,
EventHandler<EnvironmentEventArgs> message_handler = null) : base(package_source_options, message_handler)
{}
#endregion
#region Overriden members
public override string PackageManagerId { get { return "nuget"; } }
public override string PackageManagerLabel { get { return ".NET Core"; } }
public override string DefaultPackageManagerConfigurationFile { get { return string.Empty; } }
public override IEnumerable<Package> GetPackages(params string[] o)
{
AuditFileInfo config_file = this.AuditEnvironment.ConstructFile(this.PackageManagerConfigurationFile);
List<Package> packages = new List<Package>();
var isSnlSolution = config_file.Name.EndsWith(".sln");
var isCsProj = config_file.Name.EndsWith(".csproj");
var isBuildTargets = config_file.Name.EndsWith(".Build.targets");
var isDepsJson = config_file.Name.EndsWith(".deps.json");
if(isSnlSolution)
{
var Content = File.ReadAllText(this.PackageManagerConfigurationFile);
Regex projReg = new Regex("Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\"", RegexOptions.Compiled);
var matches = projReg.Matches(Content).Cast<Match>();
var Projects = matches.Select(x => x.Groups[2].Value).ToList();
for (int i = 0; i < Projects.Count; ++i)
{
if (!Path.IsPathRooted(Projects[i]))
Projects[i] = Path.Combine(Path.GetDirectoryName(this.PackageManagerConfigurationFile),
Projects[i]);
Projects[i] = Path.GetFullPath(Projects[i]);
}
foreach(var project in Projects)
{
var tmpProject = GetPackagesFromProjectFile(project, true);
if(tmpProject.Count != 0)
{
this.AuditEnvironment.Info($"Found {tmpProject.Count} packages in {project}");
foreach(var tmpPacket in tmpProject)
{
if(!packages.Contains(tmpPacket))
packages.Add(tmpPacket);
}
}
}
return packages;
}
if (isCsProj || isBuildTargets)
{
return GetPackagesFromProjectFile(this.PackageManagerConfigurationFile, isCsProj);
}
if (isDepsJson)
{
try
{
this.AuditEnvironment.Info("Reading packages from .NET Core dependencies manifest..");
JObject json = (JObject)JToken.Parse(config_file.ReadAsText());
JObject libraries = (JObject)json["libraries"];
if (libraries != null)
{
foreach (JProperty p in libraries.Properties())
{
string[] name = p.Name.Split('/');
packages.Add(new Package("nuget", name[0], name[1]));
}
}
return packages;
}
catch (Exception e)
{
this.AuditEnvironment.Error(e, "Error reading .NET Core dependencies manifest {0}.", config_file.FullName);
return packages;
}
}
this.AuditEnvironment.Error("Unknown .NET Core project file type: {0}.", config_file.FullName);
return packages;
}
private List<Package> GetPackagesFromProjectFile(string filename, bool isCsProj)
{
List<Package> packages = new List<Package>();
AuditFileInfo config_file = this.AuditEnvironment.ConstructFile(filename);
var fileType = isCsProj ? ".csproj" : "build targets";
this.AuditEnvironment.Info($"Reading packages from .NET Core C# {fileType} file.");
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
string xml = config_file.ReadAsText();
if (xml.StartsWith(_byteOrderMarkUtf8, StringComparison.Ordinal))
{
var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length;
xml = xml.Remove(0, lastIndexOfUtf8);
}
XElement root = XElement.Parse(xml);
var package = isCsProj ? "Include" : "Update";
if (root.Name.LocalName == "Project")
{
packages =
root
.Descendants()
.Where(x => x.Name.LocalName == "PackageReference" && x.Attribute(package) != null && x.Attribute("Version") != null)
.SelectMany(r => GetDeveloperPackages(r.Attribute(package).Value, r.Attribute("Version").Value))
.ToList();
IEnumerable<string> skipped_packages =
root
.Descendants()
.Where(x => x.Name.LocalName == "PackageReference" && x.Attribute(package) != null && x.Attribute("Version") == null)
.Select(r => r.Attribute(package).Value);
if (skipped_packages.Count() > 0)
{
this.AuditEnvironment.Warning("{0} package(s) do not have a version specified and will not be audited: {1}.", skipped_packages.Count(),
skipped_packages.Aggregate((s1, s2) => s1 + "," + s2));
}
var helper = new NuGetApiHelper(this.AuditEnvironment, config_file.DirectoryName);
var nuGetFrameworks = helper.GetFrameworks(root);
if (!nuGetFrameworks.Any())
{
AuditEnvironment.Warning("Scanning from project file found 0 packages, checking for packages.config file. ");
nuGetFrameworks = helper.GetFrameworks();
}
if (!nuGetFrameworks.Any())
{
AuditEnvironment.Warning("Scanning NuGet transitive dependencies failed because no target framework is found in {0}...", config_file.Name);
}
foreach (var framework in nuGetFrameworks)
{
AuditEnvironment.Info("Scanning NuGet transitive dependencies for {0}...", framework.GetFrameworkString());
var deps = helper.GetPackageDependencies(packages, framework);
Task.WaitAll(deps);
packages = helper.AddPackageDependencies(deps.Result, packages);
}
return packages;
}
else
{
this.AuditEnvironment.Error("{0} is not a .NET Core format .csproj file.", config_file.FullName);
return packages;
}
}
public override bool IsVulnerabilityVersionInPackageVersionRange(string vulnerability_version, string package_version)
{
string message = "";
bool r = NuGetv2.RangeIntersect(vulnerability_version, package_version, out message);
if (!r && !string.IsNullOrEmpty(message))
{
throw new Exception(message);
}
else return r;
}
#endregion
#region Properties
public string DefaultPackageSourceLockFile {get; } = "";
public string PackageSourceLockFile {get; set;}
#endregion
#region Methods
public bool PackageVersionIsRange(string version)
{
var lcs = Versatile.SemanticVersion.Grammar.Range.Parse(version);
if (lcs.Count > 1)
{
return true;
}
else if (lcs.Count == 1)
{
var cs = lcs.Single();
if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal)
{
return false;
}
else
{
return true;
}
}
else throw new ArgumentException($"Failed to parser {version} as a version.");
}
public List<string> GetMinimumPackageVersions(string version)
{
if (version.StartsWith("["))
version = version.Remove(0, 1);
if (version.EndsWith("]"))
version = version.Remove(version.Length -1, 1);
var lcs = Versatile.SemanticVersion.Grammar.Range.Parse(version);
List<string> minVersions = new List<string>();
foreach(ComparatorSet<Versatile.SemanticVersion> cs in lcs)
{
if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal)
{
minVersions.Add(cs.Single().Version.ToNormalizedString());
}
else
{
var gt = cs.Where(c => c.Operator == ExpressionType.GreaterThan || c.Operator == ExpressionType.GreaterThanOrEqual).Single();
if (gt.Operator == ExpressionType.GreaterThan)
{
var v = gt.Version;
minVersions.Add((v++).ToNormalizedString());
this.AuditEnvironment.Info("Using {0} package version {1} which satisfies range {2}.",
this.PackageManagerLabel, (v++).ToNormalizedString(), version);
}
else
{
minVersions.Add(gt.Version.ToNormalizedString());
this.AuditEnvironment.Info("Using {0} package version {1} which satisfies range {2}.",
this.PackageManagerLabel, gt.Version.ToNormalizedString(), version);
}
}
}
return minVersions;
}
public List<Package> GetDeveloperPackages(string name, string version, string vendor = null, string group = null,
string architecture=null)
{
return GetMinimumPackageVersions(version).Select(v => new Package(PackageManagerId, name, v, vendor, group,
architecture)).ToList();
}
public async Task GetDeps(XElement project, List<Package> packages)
{
IEnumerable<NuGetFramework> frameworks =
project.Descendants()
.Where(x => x.Name.LocalName == "TargetFramework" || x.Name.LocalName == "TargetFrameworks")
.SingleOrDefault()
.Value.Split(';')
.Select(f => NuGetFramework.ParseFolder(f));
AuditEnvironment.Info("{0}", frameworks.First().Framework);
var nugetPackages = packages.Select(p => new PackageIdentity(p.Name, NuGetVersion.Parse(p.Version)));
var settings = Settings.LoadDefaultSettings(root: null);
var sourceRepositoryProvider = new SourceRepositoryProvider(settings, Repository.Provider.GetCoreV3());
var logger = NullLogger.Instance;
using (var cacheContext = new SourceCacheContext())
{
foreach (var np in nugetPackages)
{
foreach (var sourceRepository in sourceRepositoryProvider.GetRepositories())
{
var dependencyInfoResource = await sourceRepository.GetResourceAsync<DependencyInfoResource>();
var dependencyInfo = await dependencyInfoResource.ResolvePackage(
np, frameworks.First(), cacheContext, logger, CancellationToken.None);
if (dependencyInfo != null)
{
AuditEnvironment.Info("Dependency info: {0}.", dependencyInfo);
}
}
}
}
}
#endregion
}
}
| 40.429467 | 159 | 0.550283 | [
"BSD-3-Clause"
] | gmeks/DevAudit | DevAudit.AuditLibrary/PackageSources/NetCorePackageSource.cs | 12,897 | C# |
using System.Linq;
using SkiaSharp;
using GTTG.Core.Drawing.Canvases;
using GTTG.Core.Strategies.Implementations;
using GTTG.Core.Strategies.Interfaces;
using GTTG.Model.Model.Infrastructure;
using GTTG.Model.Strategies.Types;
using GTTG.Model.ViewModel.Infrastructure.Stations;
using GTTG.Model.ViewModel.Infrastructure.Tracks;
namespace GTTG.Traffic.ViewModel {
public class TutorialStationView : StrategyStationView<TutorialTrackView> {
public TutorialStationView(Station station,
ITrackViewFactory<TutorialTrackView> trackViewFactory,
ISegmentRegistry<SegmentType<Track>, MeasureableSegment> segmentRegistry)
: base(station, segmentRegistry, trackViewFactory) {
HasClipEnabled = true; // apply clip, because DrawColor would otherwise cover whole canvas
foreach (var track in TrackViews.Select(t => t.Track)) {
TrackSegments.Resolve(new SegmentType<Track>(track, SegmentPlacement.Lower)).HeightMeasureHelpers += MeasureSegmentHeight;
TrackSegments.Resolve(new SegmentType<Track>(track, SegmentPlacement.Upper)).HeightMeasureHelpers += MeasureSegmentHeight;
}
}
protected override void OnDraw(DrawingCanvas drawingCanvas) {
drawingCanvas.Canvas.DrawColor(SKColors.WhiteSmoke);
foreach (var trackView in TrackViews) {
drawingCanvas.Draw(trackView);
}
}
private static float MeasureSegmentHeight() => 15;
}
}
| 37.585366 | 138 | 0.706035 | [
"MIT"
] | Sykoj/GTTG | tutorials/traffic/GTTG.Traffic/ViewModel/TutorialStationView.cs | 1,543 | C# |
namespace Nancy.Core.Scanning
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class TypeCatalog : ITypeCatalog
{
private readonly Lazy<IReadOnlyCollection<Assembly>> assemblies;
public TypeCatalog(IAssemblyCatalog assemblyCatalog)
{
Check.NotNull(assemblyCatalog, nameof(assemblyCatalog));
this.assemblies = new Lazy<IReadOnlyCollection<Assembly>>(() => assemblyCatalog.GetAssemblies().ToArray());
}
public IEnumerable<Type> GetTypesAssignableTo(Type targetType, ScanningStrategy strategy)
{
Check.NotNull(targetType, nameof(targetType));
Check.NotNull(strategy, nameof(strategy));
var targetTypeInfo = targetType.GetTypeInfo();
return this.GetTypesAssignableToInternal(targetTypeInfo, strategy);
}
private IEnumerable<Type> GetTypesAssignableToInternal(TypeInfo typeInfo, ScanningStrategy strategy)
{
foreach (var assembly in this.assemblies.Value)
{
if (assembly.IsDynamic)
{
continue;
}
if (!strategy.Invoke(assembly))
{
continue;
}
foreach (var exportedType in assembly.ExportedTypes)
{
var exportedTypeInfo = exportedType.GetTypeInfo();
if (exportedTypeInfo.IsAbstract)
{
continue;
}
if (exportedTypeInfo.IsAssignableTo(typeInfo))
{
yield return exportedType;
}
}
}
}
}
}
| 29.983607 | 119 | 0.543466 | [
"Apache-2.0"
] | khellang/nancy-bootstrapper-prototype | src/Nancy.Core/Scanning/TypeCatalog.cs | 1,829 | C# |
using System;
using System.Collections.Generic;
using Abp.Authorization.Users;
using Abp.Extensions;
namespace library.Authorization.Users
{
public class User : AbpUser<User>
{
public const string DefaultPassword = "123qwe";
public static string CreateRandomPassword()
{
return Guid.NewGuid().ToString("N").Truncate(16);
}
public static User CreateTenantAdminUser(int tenantId, string emailAddress)
{
var user = new User
{
TenantId = tenantId,
UserName = AdminUserName,
Name = AdminUserName,
Surname = AdminUserName,
EmailAddress = emailAddress,
Roles = new List<UserRole>()
};
user.SetNormalizedNames();
return user;
}
}
}
| 24.742857 | 83 | 0.561201 | [
"MIT"
] | janjan111921/abpsampleLibrary | src/library.Core/Authorization/Users/User.cs | 868 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace W01T03_Layouts.Layouts
{
public class AbsoluteOrnek : ContentPage
{
public AbsoluteOrnek()
{
AbsoluteLayout al = new AbsoluteLayout();
BoxView blue = new BoxView();
blue.BackgroundColor = Color.Blue;
al.Children.Add(blue);
BoxView red = new BoxView();
red.BackgroundColor = Color.Red;
red.Opacity = 0.75;
al.Children.Add(red, new Rectangle(20,20,40,40));
Content = al;
}
}
} | 21.433333 | 61 | 0.581649 | [
"MIT"
] | coshkun/Xamarin | lectures-ms/W01T03.Layouts/W01T03_Layouts/W01T03_Layouts/Layouts/AbsoluteOrnek.cs | 645 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using BenchmarkDotNet.Attributes;
using MicroBenchmarks;
namespace System.Collections
{
[BenchmarkCategory(Categories.CoreFX, Categories.Collections, Categories.NonGenericCollections)]
public class CtorDefaultSizeNonGeneric
{
[Benchmark]
public ArrayList ArrayList() => new ArrayList();
[Benchmark]
public Hashtable Hashtable() => new Hashtable();
[Benchmark]
public Queue Queue() => new Queue();
[Benchmark]
public Stack Stack() => new Stack();
[Benchmark]
public SortedList SortedList() => new SortedList();
}
} | 29.25 | 100 | 0.680098 | [
"MIT"
] | AndyAyersMS/performance | src/benchmarks/micro/corefx/System.Collections/Create/CtorDefaultSizeNonGeneric.cs | 821 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using ICSharpCode.AvalonEdit.Utils;
#if NREFACTORY
using ICSharpCode.NRefactory.Editor;
#endif
namespace ICSharpCode.AvalonEdit.Document {
/// <summary>
/// Interface to allow TextSegments to access the TextSegmentCollection - we cannot use a direct reference
/// because TextSegmentCollection is generic.
/// </summary>
interface ISegmentTree {
void Add(TextSegment s);
void Remove(TextSegment s);
void UpdateAugmentedData(TextSegment s);
}
/// <summary>
/// <para>
/// A collection of text segments that supports efficient lookup of segments
/// intersecting with another segment.
/// </para>
/// </summary>
/// <remarks><inheritdoc cref="TextSegment"/></remarks>
/// <see cref="TextSegment"/>
public sealed class TextSegmentCollection<T> : ICollection<T>, ISegmentTree, IWeakEventListener where T : TextSegment {
// Implementation: this is basically a mixture of an augmented interval tree
// and the TextAnchorTree.
// WARNING: you need to understand interval trees (the version with the augmented 'high'/'max' field)
// and how the TextAnchorTree works before you have any chance of understanding this code.
// This means that every node holds two "segments":
// one like the segments in the text anchor tree to support efficient offset changes
// and another that is the interval as seen by the user
// So basically, the tree contains a list of contiguous node segments of the first kind,
// with interval segments starting at the end of every node segment.
// Performance:
// Add is O(lg n)
// Remove is O(lg n)
// DocumentChanged is O(m * lg n), with m the number of segments that intersect with the changed document section
// FindFirstSegmentWithStartAfter is O(m + lg n) with m being the number of segments at the same offset as the result segment
// FindIntersectingSegments is O(m + lg n) with m being the number of intersecting segments.
int count;
TextSegment root;
bool isConnectedToDocument;
#region Constructor
/// <summary>
/// Creates a new TextSegmentCollection that needs manual calls to <see cref="UpdateOffsets(DocumentChangeEventArgs)"/>.
/// </summary>
public TextSegmentCollection() {
}
/// <summary>
/// Creates a new TextSegmentCollection that updates the offsets automatically.
/// </summary>
/// <param name="textDocument">The document to which the text segments
/// that will be added to the tree belong. When the document changes, the
/// position of the text segments will be updated accordingly.</param>
public TextSegmentCollection(TextDocument textDocument) {
if (textDocument == null)
throw new ArgumentNullException("textDocument");
textDocument.VerifyAccess();
isConnectedToDocument = true;
TextDocumentWeakEventManager.Changed.AddListener(textDocument, this);
}
#endregion
#region OnDocumentChanged / UpdateOffsets
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) {
if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
OnDocumentChanged((DocumentChangeEventArgs) e);
return true;
}
return false;
}
/// <summary>
/// Updates the start and end offsets of all segments stored in this collection.
/// </summary>
/// <param name="e">DocumentChangeEventArgs instance describing the change to the document.</param>
public void UpdateOffsets(DocumentChangeEventArgs e) {
if (e == null)
throw new ArgumentNullException("e");
if (isConnectedToDocument)
throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
OnDocumentChanged(e);
CheckProperties();
}
void OnDocumentChanged(DocumentChangeEventArgs e) {
OffsetChangeMap map = e.OffsetChangeMapOrNull;
if (map != null) {
foreach (OffsetChangeMapEntry entry in map) {
UpdateOffsetsInternal(entry);
}
}
else {
UpdateOffsetsInternal(e.CreateSingleChangeMapEntry());
}
}
/// <summary>
/// Updates the start and end offsets of all segments stored in this collection.
/// </summary>
/// <param name="change">OffsetChangeMapEntry instance describing the change to the document.</param>
public void UpdateOffsets(OffsetChangeMapEntry change) {
if (isConnectedToDocument)
throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
UpdateOffsetsInternal(change);
CheckProperties();
}
#endregion
#region UpdateOffsets (implementation)
void UpdateOffsetsInternal(OffsetChangeMapEntry change) {
// Special case pure insertions, because they don't always cause a text segment to increase in size when the replaced region
// is inside a segment (when offset is at start or end of a text semgent).
if (change.RemovalLength == 0) {
InsertText(change.Offset, change.InsertionLength);
}
else {
ReplaceText(change);
}
}
void InsertText(int offset, int length) {
if (length == 0)
return;
// enlarge segments that contain offset (excluding those that have offset as endpoint)
foreach (TextSegment segment in FindSegmentsContaining(offset)) {
if (segment.StartOffset < offset && offset < segment.EndOffset) {
segment.Length += length;
}
}
// move start offsets of all segments >= offset
TextSegment node = FindFirstSegmentWithStartAfter(offset);
if (node != null) {
node.nodeLength += length;
UpdateAugmentedData(node);
}
}
void ReplaceText(OffsetChangeMapEntry change) {
Debug.Assert(change.RemovalLength > 0);
int offset = change.Offset;
foreach (TextSegment segment in FindOverlappingSegments(offset, change.RemovalLength)) {
if (segment.StartOffset <= offset) {
if (segment.EndOffset >= offset + change.RemovalLength) {
// Replacement inside segment: adjust segment length
segment.Length += change.InsertionLength - change.RemovalLength;
}
else {
// Replacement starting inside segment and ending after segment end: set segment end to removal position
//segment.EndOffset = offset;
segment.Length = offset - segment.StartOffset;
}
}
else {
// Replacement starting in front of text segment and running into segment.
// Keep segment.EndOffset constant and move segment.StartOffset to the end of the replacement
int remainingLength = segment.EndOffset - (offset + change.RemovalLength);
RemoveSegment(segment);
segment.StartOffset = offset + change.RemovalLength;
segment.Length = Math.Max(0, remainingLength);
AddSegment(segment);
}
}
// move start offsets of all segments > offset
TextSegment node = FindFirstSegmentWithStartAfter(offset + 1);
if (node != null) {
Debug.Assert(node.nodeLength >= change.RemovalLength);
node.nodeLength += change.InsertionLength - change.RemovalLength;
UpdateAugmentedData(node);
}
}
#endregion
#region Add
/// <summary>
/// Adds the specified segment to the tree. This will cause the segment to update when the
/// document changes.
/// </summary>
public void Add(T item) {
if (item == null)
throw new ArgumentNullException("item");
if (item.ownerTree != null)
throw new ArgumentException("The segment is already added to a SegmentCollection.");
AddSegment(item);
}
void ISegmentTree.Add(TextSegment s) {
AddSegment(s);
}
void AddSegment(TextSegment node) {
int insertionOffset = node.StartOffset;
node.distanceToMaxEnd = node.segmentLength;
if (root == null) {
root = node;
node.totalNodeLength = node.nodeLength;
}
else if (insertionOffset >= root.totalNodeLength) {
// append segment at end of tree
node.nodeLength = node.totalNodeLength = insertionOffset - root.totalNodeLength;
InsertAsRight(root.RightMost, node);
}
else {
// insert in middle of tree
TextSegment n = FindNode(ref insertionOffset);
Debug.Assert(insertionOffset < n.nodeLength);
// split node segment 'n' at offset
node.totalNodeLength = node.nodeLength = insertionOffset;
n.nodeLength -= insertionOffset;
InsertBefore(n, node);
}
node.ownerTree = this;
count++;
CheckProperties();
}
void InsertBefore(TextSegment node, TextSegment newNode) {
if (node.left == null) {
InsertAsLeft(node, newNode);
}
else {
InsertAsRight(node.left.RightMost, newNode);
}
}
#endregion
#region GetNextSegment / GetPreviousSegment
/// <summary>
/// Gets the next segment after the specified segment.
/// Segments are sorted by their start offset.
/// Returns null if segment is the last segment.
/// </summary>
public T GetNextSegment(T segment) {
if (!Contains(segment))
throw new ArgumentException("segment is not inside the segment tree");
return (T) segment.Successor;
}
/// <summary>
/// Gets the previous segment before the specified segment.
/// Segments are sorted by their start offset.
/// Returns null if segment is the first segment.
/// </summary>
public T GetPreviousSegment(T segment) {
if (!Contains(segment))
throw new ArgumentException("segment is not inside the segment tree");
return (T) segment.Predecessor;
}
#endregion
#region FirstSegment/LastSegment
/// <summary>
/// Returns the first segment in the collection or null, if the collection is empty.
/// </summary>
public T FirstSegment {
get {
return root == null ? null : (T) root.LeftMost;
}
}
/// <summary>
/// Returns the last segment in the collection or null, if the collection is empty.
/// </summary>
public T LastSegment {
get {
return root == null ? null : (T) root.RightMost;
}
}
#endregion
#region FindFirstSegmentWithStartAfter
/// <summary>
/// Gets the first segment with a start offset greater or equal to <paramref name="startOffset"/>.
/// Returns null if no such segment is found.
/// </summary>
public T FindFirstSegmentWithStartAfter(int startOffset) {
if (root == null)
return null;
if (startOffset <= 0)
return (T) root.LeftMost;
TextSegment s = FindNode(ref startOffset);
// startOffset means that the previous segment is starting at the offset we were looking for
while (startOffset == 0) {
TextSegment p = (s == null) ? root.RightMost : s.Predecessor;
// There must always be a predecessor: if we were looking for the first node, we would have already
// returned it as root.LeftMost above.
Debug.Assert(p != null);
startOffset += p.nodeLength;
s = p;
}
return (T) s;
}
/// <summary>
/// Finds the node at the specified offset.
/// After the method has run, offset is relative to the beginning of the returned node.
/// </summary>
TextSegment FindNode(ref int offset) {
TextSegment n = root;
while (true) {
if (n.left != null) {
if (offset < n.left.totalNodeLength) {
n = n.left; // descend into left subtree
continue;
}
else {
offset -= n.left.totalNodeLength; // skip left subtree
}
}
if (offset < n.nodeLength) {
return n; // found correct node
}
else {
offset -= n.nodeLength; // skip this node
}
if (n.right != null) {
n = n.right; // descend into right subtree
}
else {
// didn't find any node containing the offset
return null;
}
}
}
#endregion
#region FindOverlappingSegments
/// <summary>
/// Finds all segments that contain the given offset.
/// (StartOffset <= offset <= EndOffset)
/// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
/// </summary>
/// <returns>Returns a new collection containing the results of the query.
/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
public ReadOnlyCollection<T> FindSegmentsContaining(int offset) {
return FindOverlappingSegments(offset, 0);
}
/// <summary>
/// Finds all segments that overlap with the given segment (including touching segments).
/// </summary>
/// <returns>Returns a new collection containing the results of the query.
/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
public ReadOnlyCollection<T> FindOverlappingSegments(ISegment segment) {
if (segment == null)
throw new ArgumentNullException("segment");
return FindOverlappingSegments(segment.Offset, segment.Length);
}
/// <summary>
/// Finds all segments that overlap with the given segment (including touching segments).
/// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
/// </summary>
/// <returns>Returns a new collection containing the results of the query.
/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
public ReadOnlyCollection<T> FindOverlappingSegments(int offset, int length) {
ThrowUtil.CheckNotNegative(length, "length");
List<T> results = new List<T>();
if (root != null) {
FindOverlappingSegments(results, root, offset, offset + length);
}
return results.AsReadOnly();
}
void FindOverlappingSegments(List<T> results, TextSegment node, int low, int high) {
// low and high are relative to node.LeftMost startpos (not node.LeftMost.Offset)
if (high < 0) {
// node is irrelevant for search because all intervals in node are after high
return;
}
// find values relative to node.Offset
int nodeLow = low - node.nodeLength;
int nodeHigh = high - node.nodeLength;
if (node.left != null) {
nodeLow -= node.left.totalNodeLength;
nodeHigh -= node.left.totalNodeLength;
}
if (node.distanceToMaxEnd < nodeLow) {
// node is irrelevant for search because all intervals in node are before low
return;
}
if (node.left != null)
FindOverlappingSegments(results, node.left, low, high);
if (nodeHigh < 0) {
// node and everything in node.right is before low
return;
}
if (nodeLow <= node.segmentLength) {
results.Add((T) node);
}
if (node.right != null)
FindOverlappingSegments(results, node.right, nodeLow, nodeHigh);
}
#endregion
#region UpdateAugmentedData
void UpdateAugmentedData(TextSegment node) {
int totalLength = node.nodeLength;
int distanceToMaxEnd = node.segmentLength;
if (node.left != null) {
totalLength += node.left.totalNodeLength;
int leftDTME = node.left.distanceToMaxEnd;
// dtme is relative, so convert it to the coordinates of node:
if (node.left.right != null)
leftDTME -= node.left.right.totalNodeLength;
leftDTME -= node.nodeLength;
if (leftDTME > distanceToMaxEnd)
distanceToMaxEnd = leftDTME;
}
if (node.right != null) {
totalLength += node.right.totalNodeLength;
int rightDTME = node.right.distanceToMaxEnd;
// dtme is relative, so convert it to the coordinates of node:
rightDTME += node.right.nodeLength;
if (node.right.left != null)
rightDTME += node.right.left.totalNodeLength;
if (rightDTME > distanceToMaxEnd)
distanceToMaxEnd = rightDTME;
}
if (node.totalNodeLength != totalLength
|| node.distanceToMaxEnd != distanceToMaxEnd) {
node.totalNodeLength = totalLength;
node.distanceToMaxEnd = distanceToMaxEnd;
if (node.parent != null)
UpdateAugmentedData(node.parent);
}
}
void ISegmentTree.UpdateAugmentedData(TextSegment node) {
UpdateAugmentedData(node);
}
#endregion
#region Remove
/// <summary>
/// Removes the specified segment from the tree. This will cause the segment to not update
/// anymore when the document changes.
/// </summary>
public bool Remove(T item) {
if (!Contains(item))
return false;
RemoveSegment(item);
return true;
}
void ISegmentTree.Remove(TextSegment s) {
RemoveSegment(s);
}
void RemoveSegment(TextSegment s) {
int oldOffset = s.StartOffset;
TextSegment successor = s.Successor;
if (successor != null)
successor.nodeLength += s.nodeLength;
RemoveNode(s);
if (successor != null)
UpdateAugmentedData(successor);
Disconnect(s, oldOffset);
CheckProperties();
}
void Disconnect(TextSegment s, int offset) {
s.left = s.right = s.parent = null;
s.ownerTree = null;
s.nodeLength = offset;
count--;
}
/// <summary>
/// Removes all segments from the tree.
/// </summary>
public void Clear() {
T[] segments = this.ToArray();
root = null;
int offset = 0;
foreach (TextSegment s in segments) {
offset += s.nodeLength;
Disconnect(s, offset);
}
CheckProperties();
}
#endregion
#region CheckProperties
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties() {
#if DEBUG
if (root != null) {
CheckProperties(root);
// check red-black property:
int blackCount = -1;
CheckNodeProperties(root, null, RED, 0, ref blackCount);
}
int expectedCount = 0;
// we cannot trust LINQ not to call ICollection.Count, so we need this loop
// to count the elements in the tree
using (IEnumerator<T> en = GetEnumerator()) {
while (en.MoveNext()) expectedCount++;
}
Debug.Assert(count == expectedCount);
#endif
}
#if DEBUG
void CheckProperties(TextSegment node) {
int totalLength = node.nodeLength;
int distanceToMaxEnd = node.segmentLength;
if (node.left != null) {
CheckProperties(node.left);
totalLength += node.left.totalNodeLength;
distanceToMaxEnd = Math.Max(distanceToMaxEnd,
node.left.distanceToMaxEnd + node.left.StartOffset - node.StartOffset);
}
if (node.right != null) {
CheckProperties(node.right);
totalLength += node.right.totalNodeLength;
distanceToMaxEnd = Math.Max(distanceToMaxEnd,
node.right.distanceToMaxEnd + node.right.StartOffset - node.StartOffset);
}
Debug.Assert(node.totalNodeLength == totalLength);
Debug.Assert(node.distanceToMaxEnd == distanceToMaxEnd);
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
void CheckNodeProperties(TextSegment node, TextSegment parentNode, bool parentColor, int blackCount, ref int expectedBlackCount) {
if (node == null) return;
Debug.Assert(node.parent == parentNode);
if (parentColor == RED) {
Debug.Assert(node.color == BLACK);
}
if (node.color == BLACK) {
blackCount++;
}
if (node.left == null && node.right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
}
static void AppendTreeToString(TextSegment node, StringBuilder b, int indent) {
if (node.color == RED)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString() + node.ToDebugString());
indent += 2;
if (node.left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.left, b, indent);
}
if (node.right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.right, b, indent);
}
}
#endif
internal string GetTreeAsString() {
#if DEBUG
StringBuilder b = new StringBuilder();
if (root != null)
AppendTreeToString(root, b, 0);
return b.ToString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Red/Black Tree
internal const bool RED = true;
internal const bool BLACK = false;
void InsertAsLeft(TextSegment parentNode, TextSegment newNode) {
Debug.Assert(parentNode.left == null);
parentNode.left = newNode;
newNode.parent = parentNode;
newNode.color = RED;
UpdateAugmentedData(parentNode);
FixTreeOnInsert(newNode);
}
void InsertAsRight(TextSegment parentNode, TextSegment newNode) {
Debug.Assert(parentNode.right == null);
parentNode.right = newNode;
newNode.parent = parentNode;
newNode.color = RED;
UpdateAugmentedData(parentNode);
FixTreeOnInsert(newNode);
}
void FixTreeOnInsert(TextSegment node) {
Debug.Assert(node != null);
Debug.Assert(node.color == RED);
Debug.Assert(node.left == null || node.left.color == BLACK);
Debug.Assert(node.right == null || node.right.color == BLACK);
TextSegment parentNode = node.parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.color = BLACK;
return;
}
if (parentNode.color == BLACK) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
TextSegment grandparentNode = parentNode.parent;
TextSegment uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.color == RED) {
parentNode.color = BLACK;
uncleNode.color = BLACK;
grandparentNode.color = RED;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.right && parentNode == grandparentNode.left) {
RotateLeft(parentNode);
node = node.left;
}
else if (node == parentNode.left && parentNode == grandparentNode.right) {
RotateRight(parentNode);
node = node.right;
}
// because node might have changed, reassign variables:
parentNode = node.parent;
grandparentNode = parentNode.parent;
// Now recolor a bit:
parentNode.color = BLACK;
grandparentNode.color = RED;
// Second rotation:
if (node == parentNode.left && parentNode == grandparentNode.left) {
RotateRight(grandparentNode);
}
else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
RotateLeft(grandparentNode);
}
}
void RemoveNode(TextSegment removedNode) {
if (removedNode.left != null && removedNode.right != null) {
// replace removedNode with it's in-order successor
TextSegment leftMost = removedNode.right.LeftMost;
RemoveNode(leftMost); // remove leftMost from its current location
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.left = removedNode.left;
if (leftMost.left != null) leftMost.left.parent = leftMost;
leftMost.right = removedNode.right;
if (leftMost.right != null) leftMost.right.parent = leftMost;
leftMost.color = removedNode.color;
UpdateAugmentedData(leftMost);
if (leftMost.parent != null) UpdateAugmentedData(leftMost.parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
TextSegment parentNode = removedNode.parent;
TextSegment childNode = removedNode.left ?? removedNode.right;
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAugmentedData(parentNode);
if (removedNode.color == BLACK) {
if (childNode != null && childNode.color == RED) {
childNode.color = BLACK;
}
else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
void FixTreeOnDelete(TextSegment node, TextSegment parentNode) {
Debug.Assert(node == null || node.parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
TextSegment sibling = Sibling(node, parentNode);
if (sibling.color == RED) {
parentNode.color = RED;
sibling.color = BLACK;
if (node == parentNode.left) {
RotateLeft(parentNode);
}
else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.color == BLACK
&& sibling.color == BLACK
&& GetColor(sibling.left) == BLACK
&& GetColor(sibling.right) == BLACK) {
sibling.color = RED;
FixTreeOnDelete(parentNode, parentNode.parent);
return;
}
if (parentNode.color == RED
&& sibling.color == BLACK
&& GetColor(sibling.left) == BLACK
&& GetColor(sibling.right) == BLACK) {
sibling.color = RED;
parentNode.color = BLACK;
return;
}
if (node == parentNode.left &&
sibling.color == BLACK &&
GetColor(sibling.left) == RED &&
GetColor(sibling.right) == BLACK) {
sibling.color = RED;
sibling.left.color = BLACK;
RotateRight(sibling);
}
else if (node == parentNode.right &&
sibling.color == BLACK &&
GetColor(sibling.right) == RED &&
GetColor(sibling.left) == BLACK) {
sibling.color = RED;
sibling.right.color = BLACK;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.color = parentNode.color;
parentNode.color = BLACK;
if (node == parentNode.left) {
if (sibling.right != null) {
Debug.Assert(sibling.right.color == RED);
sibling.right.color = BLACK;
}
RotateLeft(parentNode);
}
else {
if (sibling.left != null) {
Debug.Assert(sibling.left.color == RED);
sibling.left.color = BLACK;
}
RotateRight(parentNode);
}
}
void ReplaceNode(TextSegment replacedNode, TextSegment newNode) {
if (replacedNode.parent == null) {
Debug.Assert(replacedNode == root);
root = newNode;
}
else {
if (replacedNode.parent.left == replacedNode)
replacedNode.parent.left = newNode;
else
replacedNode.parent.right = newNode;
}
if (newNode != null) {
newNode.parent = replacedNode.parent;
}
replacedNode.parent = null;
}
void RotateLeft(TextSegment p) {
// let q be p's right child
TextSegment q = p.right;
Debug.Assert(q != null);
Debug.Assert(q.parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.right = q.left;
if (p.right != null) p.right.parent = p;
// set q's left child to be p
q.left = p;
p.parent = q;
UpdateAugmentedData(p);
UpdateAugmentedData(q);
}
void RotateRight(TextSegment p) {
// let q be p's left child
TextSegment q = p.left;
Debug.Assert(q != null);
Debug.Assert(q.parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.left = q.right;
if (p.left != null) p.left.parent = p;
// set q's right child to be p
q.right = p;
p.parent = q;
UpdateAugmentedData(p);
UpdateAugmentedData(q);
}
static TextSegment Sibling(TextSegment node) {
if (node == node.parent.left)
return node.parent.right;
else
return node.parent.left;
}
static TextSegment Sibling(TextSegment node, TextSegment parentNode) {
Debug.Assert(node == null || node.parent == parentNode);
if (node == parentNode.left)
return parentNode.right;
else
return parentNode.left;
}
static bool GetColor(TextSegment node) {
return node != null ? node.color : BLACK;
}
#endregion
#region ICollection<T> implementation
/// <summary>
/// Gets the number of segments in the tree.
/// </summary>
public int Count {
get { return count; }
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}
/// <summary>
/// Gets whether this tree contains the specified item.
/// </summary>
public bool Contains(T item) {
return item != null && item.ownerTree == this;
}
/// <summary>
/// Copies all segments in this SegmentTree to the specified array.
/// </summary>
public void CopyTo(T[] array, int arrayIndex) {
if (array == null)
throw new ArgumentNullException("array");
if (array.Length < this.Count)
throw new ArgumentException("The array is too small", "array");
if (arrayIndex < 0 || arrayIndex + count > array.Length)
throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Value must be between 0 and " + (array.Length - count));
foreach (T s in this) {
array[arrayIndex++] = s;
}
}
/// <summary>
/// Gets an enumerator to enumerate the segments.
/// </summary>
public IEnumerator<T> GetEnumerator() {
if (root != null) {
TextSegment current = root.LeftMost;
while (current != null) {
yield return (T) current;
// TODO: check if collection was modified during enumeration
current = current.Successor;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return this.GetEnumerator();
}
#endregion
}
}
| 32.176842 | 141 | 0.686928 | [
"MIT"
] | trigger-death/ZeldaOracle | EditorLibraries/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs | 30,570 | C# |
//[?] 정적(Static, Shared) 멤버와 인스턴스(Instance) 멤버
using System;
namespace StaticAndInstance
{
//[1] 클래스 생성
class SharedAndInstance
{
//[1][1] static(shared) 멤버
public static void StaticMember() => Console.WriteLine("[1] Static Member");
//[1][2] instance 멤버
public void InstanceMember() => Console.WriteLine("[2] Instance Member");
}
class StaticAndInstance
{
static void Main()
{
//[2] 클래스 사용
//[2][1] 정적 멤버 사용
SharedAndInstance.StaticMember(); // 정적 멤버 => 클래스.멤버 형태
//[2][2] 인스턴스 멤버 사용
SharedAndInstance obj = new SharedAndInstance();
obj.InstanceMember(); // 인스턴스 멤버 => 개체.멤버 형태
}
}
}
| 24.9 | 84 | 0.542169 | [
"MIT"
] | VisualAcademy/DotNet | DotNet/DotNet/32_Object/05_StaticAndInstance/StaticAndInstance.cs | 873 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
namespace WpfApp1.NetCore
{
public class ListItem
{
public string Title { get; set; }
public int ItemHeight { get; } = 22;
public ListItem()
{
}
public ListItem(string title)
{
Title = title;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
: Window
{
private struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
private struct RECT
{
public int Left, Top, Right, Bottom;
}
private const int _abmGetTaskbarPos = 5;
private ObservableCollection<ListItem> _items { get; set; }
private readonly Thickness _backButtonMargin;
private readonly Thickness _addButtonMargin;
[DllImport("shell32.dll")]
private static extern IntPtr SHAppBarMessage(int msg, ref APPBARDATA data);
private int GetTaskBarHeight()
{
var data = new APPBARDATA();
data.cbSize = Marshal.SizeOf(data);
var ptr = SHAppBarMessage(_abmGetTaskbarPos, ref data);
Marshal.FreeHGlobal(ptr);
return data.rc.Bottom - data.rc.Top; // height
//return data.rc.Right - data.rc.Right; // width
}
public MainWindow()
{
DataContext = this;
InitializeComponent();
_items = new ObservableCollection<ListItem>
{
new ListItem("Item 1") ,
new ListItem("Item 2")
};
listBox.ItemsSource = _items;
_backButtonMargin = BtnBack.Margin;
_addButtonMargin = BtnAdd.Margin;
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
var screenHeight = SystemParameters.FullPrimaryScreenHeight;
var height = double.IsNaN(Height)
? ActualHeight
: Height;
var itemHeight = 22;
var listBoxTotalHeight = _items.Count * itemHeight;
var otherHeightAndMargin = BtnBack.Height
+ _backButtonMargin.Top
+ _backButtonMargin.Bottom
+ BtnAdd.Height
+ _addButtonMargin.Top
+ _addButtonMargin.Bottom;
var taskbarHeight = GetTaskBarHeight();
Top = screenHeight - listBoxTotalHeight - otherHeightAndMargin + 10;
Left = SystemParameters.FullPrimaryScreenWidth - Width;
listBox.MaxHeight = screenHeight - taskbarHeight;
MaxHeight = SystemParameters.WorkArea.Height;
_items.CollectionChanged += Items_CollectionChanged;
}
private void Items_CollectionChanged(
object sender,
NotifyCollectionChangedEventArgs e
)
{
//var itemHeight = 22;
//var listBoxTotalHeight = _items.Count * itemHeight;
//var taskbarHeight = GetTaskBarHeight();
//var screenHeight = SystemParameters.FullPrimaryScreenHeight;
//var otherHeightAndMargin = BtnBack.Height
// + _backButtonMargin.Top
// + _backButtonMargin.Bottom
// + BtnAdd.Height
// + _addButtonMargin.Top
// + _addButtonMargin.Bottom;
//var actualHeight = listBoxTotalHeight + otherHeightAndMargin;
//if (Top + actualHeight > screenHeight - taskbarHeight)
//{
// Top = screenHeight - actualHeight - taskbarHeight;
// if (Top + ActualHeight > screenHeight - taskbarHeight)
// Top = screenHeight - ActualHeight - taskbarHeight;
// if (actualHeight > screenHeight)
// {
// var height = screenHeight - taskbarHeight;
// listBox.Height = height;
// //Top = screenHeight - actualHeight - taskbarHeight - 12;
// }
// if (Top < 0)
// Top = 0;
//}
}
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
var itemsToAdd = 10;
var count = _items.Count;
for (var i = count; i < count + itemsToAdd; i++)
{
_items.Add(new ListItem($"Item {i + 1}"));
}
var taskbarHeight = GetTaskBarHeight();
var screenHeight = SystemParameters.FullPrimaryScreenHeight;
var buttonHeights = BtnBack.Height + BtnAdd.Height;
var buttonMargins = _backButtonMargin.Top
+ _backButtonMargin.Bottom
+ _addButtonMargin.Top
+ _addButtonMargin.Bottom;
Top = screenHeight - ActualHeight - 3;
if (itemsToAdd > 1)
if (Top + ActualHeight + buttonHeights + buttonMargins > screenHeight - taskbarHeight)
Top = screenHeight
- ActualHeight
- (taskbarHeight * (itemsToAdd - 1))
+ ((itemsToAdd - 2 <= 0 ? 0 : itemsToAdd - 2) * 3);
if (ActualHeight > screenHeight)
{
var height = screenHeight - taskbarHeight - 15;
listBox.MaxHeight = height;
}
if (Top < 0)
Top = 0;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_items.CollectionChanged -= Items_CollectionChanged;
}
}
}
| 27.872093 | 90 | 0.682103 | [
"MIT"
] | rafsanulhasan/AutoHeightAndCornerRadiusWPF | WpfApp1.NetCore/MainWindow.xaml.cs | 4,796 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Execution;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
using StreamJsonRpc;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Microsoft.VisualStudio.LanguageServices.Remote
{
internal class JsonRpcSession : RemoteHostClient.Session
{
private static int s_sessionId = 1;
// current session id
private readonly int _currentSessionId;
// communication channel related to service information
private readonly ServiceJsonRpcClient _serviceClient;
// communication channel related to snapshot information
private readonly SnapshotJsonRpcClient _snapshotClientOpt;
// close connection when cancellation has raised
private readonly CancellationTokenRegistration _cancellationRegistration;
public static async Task<JsonRpcSession> CreateAsync(
Optional<Func<CancellationToken, Task<PinnedRemotableDataScope>>> getSnapshotAsync,
object callbackTarget,
Stream serviceStream,
Stream snapshotStreamOpt,
CancellationToken cancellationToken)
{
var snapshot = getSnapshotAsync.Value == null ? null : await getSnapshotAsync.Value(cancellationToken).ConfigureAwait(false);
JsonRpcSession session;
try
{
session = new JsonRpcSession(snapshot, callbackTarget, serviceStream, snapshotStreamOpt, cancellationToken);
}
catch
{
snapshot?.Dispose();
throw;
}
try
{
await session.InitializeAsync().ConfigureAwait(false);
}
catch when (!cancellationToken.IsCancellationRequested)
{
// The session disposes of itself when cancellation is requested.
session.Dispose();
throw;
}
return session;
}
private JsonRpcSession(
PinnedRemotableDataScope snapshot,
object callbackTarget,
Stream serviceStream,
Stream snapshotStreamOpt,
CancellationToken cancellationToken) :
base(snapshot, cancellationToken)
{
Contract.Requires((snapshot == null) == (snapshotStreamOpt == null));
// get session id
_currentSessionId = Interlocked.Increment(ref s_sessionId);
_serviceClient = new ServiceJsonRpcClient(serviceStream, callbackTarget, cancellationToken);
_snapshotClientOpt = snapshot == null ? null : new SnapshotJsonRpcClient(this, snapshotStreamOpt, cancellationToken);
// dispose session when cancellation has raised
_cancellationRegistration = CancellationToken.Register(Dispose);
}
private async Task InitializeAsync()
{
// All roslyn remote service must based on ServiceHubServiceBase which implements Initialize method
// This will set this session's solution and whether that solution is for primary branch or not
var primaryBranch = PinnedScopeOpt?.ForPrimaryBranch ?? false;
var solutionChecksum = PinnedScopeOpt?.SolutionChecksum;
if (_snapshotClientOpt != null)
{
await _snapshotClientOpt.InvokeAsync(WellKnownServiceHubServices.ServiceHubServiceBase_Initialize, _currentSessionId, primaryBranch, solutionChecksum).ConfigureAwait(false);
}
await _serviceClient.InvokeAsync(WellKnownServiceHubServices.ServiceHubServiceBase_Initialize, _currentSessionId, primaryBranch, solutionChecksum).ConfigureAwait(false);
}
public override Task InvokeAsync(string targetName, params object[] arguments)
{
return _serviceClient.InvokeAsync(targetName, arguments);
}
public override Task<T> InvokeAsync<T>(string targetName, params object[] arguments)
{
return _serviceClient.InvokeAsync<T>(targetName, arguments);
}
public override Task InvokeAsync(string targetName, IEnumerable<object> arguments, Func<Stream, CancellationToken, Task> funcWithDirectStreamAsync)
{
return _serviceClient.InvokeAsync(targetName, arguments, funcWithDirectStreamAsync);
}
public override Task<T> InvokeAsync<T>(string targetName, IEnumerable<object> arguments, Func<Stream, CancellationToken, Task<T>> funcWithDirectStreamAsync)
{
return _serviceClient.InvokeAsync<T>(targetName, arguments, funcWithDirectStreamAsync);
}
protected override void OnDisposed()
{
// dispose cancellation registration
_cancellationRegistration.Dispose();
// dispose service and snapshot channels
_serviceClient.Dispose();
_snapshotClientOpt?.Dispose();
}
/// <summary>
/// Communication channel between VS feature and roslyn service in remote host.
///
/// this is the channel consumer of remote host client will playing with
/// </summary>
private class ServiceJsonRpcClient : JsonRpcClient
{
private readonly object _callbackTarget;
public ServiceJsonRpcClient(Stream stream, object callbackTarget, CancellationToken cancellationToken)
: base(stream, callbackTarget, useThisAsCallback: false, cancellationToken: cancellationToken)
{
// this one doesn't need cancellation token since it has nothing to cancel
_callbackTarget = callbackTarget;
StartListening();
}
}
/// <summary>
/// Communication channel between remote host client and remote host.
///
/// this is framework's back channel to talk to remote host
///
/// for example, this will be used to deliver missing assets in remote host.
///
/// each remote host client will have its own back channel so that it can work isolated
/// with other clients.
/// </summary>
private class SnapshotJsonRpcClient : JsonRpcClient
{
private readonly JsonRpcSession _owner;
private readonly CancellationTokenSource _source;
public SnapshotJsonRpcClient(JsonRpcSession owner, Stream stream, CancellationToken cancellationToken)
: base(stream, callbackTarget: null, useThisAsCallback: true, cancellationToken: cancellationToken)
{
Contract.ThrowIfNull(owner.PinnedScopeOpt);
_owner = owner;
_source = new CancellationTokenSource();
StartListening();
}
private PinnedRemotableDataScope PinnedScope => _owner.PinnedScopeOpt;
/// <summary>
/// this is callback from remote host side to get asset associated with checksum from VS.
/// </summary>
public async Task RequestAssetAsync(int sessionId, Checksum[] checksums, string streamName)
{
try
{
Contract.ThrowIfFalse(_owner._currentSessionId == sessionId);
using (Logger.LogBlock(FunctionId.JsonRpcSession_RequestAssetAsync, streamName, _source.Token))
using (var stream = await DirectStream.GetAsync(streamName, _source.Token).ConfigureAwait(false))
{
using (var writer = new ObjectWriter(stream))
{
writer.WriteInt32(sessionId);
await WriteAssetAsync(writer, checksums).ConfigureAwait(false);
}
await stream.FlushAsync(_source.Token).ConfigureAwait(false);
}
}
catch (IOException)
{
// remote host side is cancelled (client stream connection is closed)
// can happen if pinned solution scope is disposed
}
catch (OperationCanceledException)
{
// rpc connection is closed.
// can happen if pinned solution scope is disposed
}
}
private async Task WriteAssetAsync(ObjectWriter writer, Checksum[] checksums)
{
// special case
if (checksums.Length == 0)
{
await WriteNoAssetAsync(writer).ConfigureAwait(false);
return;
}
if (checksums.Length == 1)
{
await WriteOneAssetAsync(writer, checksums[0]).ConfigureAwait(false);
return;
}
await WriteMultipleAssetsAsync(writer, checksums).ConfigureAwait(false);
}
private Task WriteNoAssetAsync(ObjectWriter writer)
{
writer.WriteInt32(0);
return SpecializedTasks.EmptyTask;
}
private async Task WriteOneAssetAsync(ObjectWriter writer, Checksum checksum)
{
var remotableData = PinnedScope.GetRemotableData(checksum, _source.Token) ?? RemotableData.Null;
writer.WriteInt32(1);
checksum.WriteTo(writer);
writer.WriteInt32((int)remotableData.Kind);
await remotableData.WriteObjectToAsync(writer, _source.Token).ConfigureAwait(false);
}
private async Task WriteMultipleAssetsAsync(ObjectWriter writer, Checksum[] checksums)
{
var remotableDataMap = PinnedScope.GetRemotableData(checksums, _source.Token);
writer.WriteInt32(remotableDataMap.Count);
foreach (var kv in remotableDataMap)
{
var checksum = kv.Key;
var remotableData = kv.Value;
checksum.WriteTo(writer);
writer.WriteInt32((int)remotableData.Kind);
await remotableData.WriteObjectToAsync(writer, _source.Token).ConfigureAwait(false);
}
}
protected override void OnDisconnected(object sender, JsonRpcDisconnectedEventArgs e)
{
_source.Cancel();
}
}
}
} | 40.02952 | 189 | 0.611173 | [
"Apache-2.0"
] | amcasey/roslyn | src/VisualStudio/Core/Next/Remote/JsonRpcSession.cs | 10,850 | C# |
using UnityEngine;
public static class JuceCoreUnityComponentExtensions
{
public static void DestroyGameObject(this Component component)
{
if (component == null)
{
return;
}
MonoBehaviour.Destroy(component.gameObject);
}
public static T InstantiateGameObjectAndGetComponent<T>(this T component, Transform parent = null) where T : Component
{
GameObject instance = MonoBehaviour.Instantiate(component.gameObject, parent);
return instance.GetComponent<T>();
}
}
| 24.954545 | 122 | 0.677596 | [
"MIT"
] | Juce-Assets/Juce-CoreUnity | Runtime/Extensions/JuceCoreUnityComponentExtensions.cs | 551 | C# |
// Copyright 2018 Ionx Solutions (https://www.ionxsolutions.com)
// Ionx Solutions licenses this file to you under the Apache License,
// Version 2.0. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
using System;
using Serilog.Events;
using Serilog.Formatting.Display;
namespace Serilog.Sinks.Syslog
{
/// <inheritdoc />
/// <summary>
/// Formats messages for use with the Linux libc syslog() function. Note that syslog() is only
/// used to write the 'body' of the message - it takes care of the priority, timestamp etc by
/// itself, so this formatter is rather simple
/// </summary>
public class LocalFormatter : SyslogFormatterBase
{
/// <summary>
/// Initialize a new instance of <see cref="LocalFormatter"/> class allowing you to specify values for
/// the facility, application name and template formatter.
/// </summary>
/// <param name="facility"><inheritdoc cref="Facility" path="/summary"/></param>
/// <param name="templateFormatter"><inheritdoc cref="SyslogFormatterBase.templateFormatter" path="/summary"/></param>
/// <param name="severityMapping"><inheritdoc cref="SyslogLoggerConfigurationExtensions.LocalSyslog" path="/param[@name='severityMapping']"/></param>
public LocalFormatter(Facility facility = Facility.Local0,
MessageTemplateTextFormatter templateFormatter = null,
Func<LogEventLevel, Severity> severityMapping = null)
: base(facility, templateFormatter, severityMapping: severityMapping) { }
public override string FormatMessage(LogEvent logEvent)
=> RenderMessage(logEvent);
}
}
| 48.361111 | 158 | 0.677771 | [
"Apache-2.0"
] | IonxSolutions/serilog-sinks-syslog | src/Serilog.Sinks.Syslog/Sinks/Formatters/LocalFormatter.cs | 1,741 | C# |
using Assets.Common.StandardAssets.CrossPlatformInput.Scripts;
using Assets.Common.StandardAssets.Utility;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Assets.Common.StandardAssets.Characters.FirstPersonCharacter.Scripts
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
[AddComponentMenu("Scripts/Standard Assets/Characters/First Person/First Person Controller")]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update() {
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump) {
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) {
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) {
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate() {
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(
transform.position,
m_CharacterController.radius,
Vector3.down,
out hitInfo,
m_CharacterController.height / 2f,
Physics.AllLayers,
QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x * speed;
m_MoveDir.z = desiredMove.z * speed;
if (m_CharacterController.isGrounded) {
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump) {
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
} else {
m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio() {
if (!m_CharacterController.isGrounded) {
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed) {
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1) {
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) {
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit) {
Rigidbody body = hit.collider.attachedRigidbody;
// dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below) {
return;
}
if (body == null || body.isKinematic) {
return;
}
body.AddForceAtPosition(m_CharacterController.velocity * 0.1f, hit.point, ForceMode.Impulse);
}
}
}
| 37.515625 | 133 | 0.601833 | [
"MIT"
] | Chapmania/unity-ui-examples | Assets/Common/StandardAssets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs | 9,604 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage
{
public abstract class VirtualDocumentBase<T> : VirtualDocument where T : VirtualDocumentSnapshot
{
private T _currentSnapshot;
private long? _hostDocumentSyncVersion;
protected VirtualDocumentBase(Uri uri, ITextBuffer textBuffer)
{
if (uri is null)
{
throw new ArgumentNullException(nameof(uri));
}
if (textBuffer is null)
{
throw new ArgumentNullException(nameof(textBuffer));
}
Uri = uri;
TextBuffer = textBuffer;
_currentSnapshot = GetUpdatedSnapshot();
}
public override Uri Uri { get; }
public override ITextBuffer TextBuffer { get; }
public override long? HostDocumentSyncVersion => _hostDocumentSyncVersion;
public override VirtualDocumentSnapshot CurrentSnapshot => _currentSnapshot;
public override VirtualDocumentSnapshot Update(IReadOnlyList<ITextChange> changes, long hostDocumentVersion)
{
if (changes is null)
{
throw new ArgumentNullException(nameof(changes));
}
_hostDocumentSyncVersion = hostDocumentVersion;
TextBuffer.SetHostDocumentSyncVersion(_hostDocumentSyncVersion.Value);
if (changes.Count == 0)
{
// Even though nothing changed here, we want the synchronizer to be aware of the host document version change.
// So, let's make an empty edit to invoke the text buffer Changed events.
TextBuffer.MakeEmptyEdit();
_currentSnapshot = GetUpdatedSnapshot();
return _currentSnapshot;
}
using var edit = TextBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, InviolableEditTag.Instance);
for (var i = 0; i < changes.Count; i++)
{
var change = changes[i];
edit.Replace(change.OldSpan.Start, change.OldSpan.Length, change.NewText);
}
edit.Apply();
_currentSnapshot = GetUpdatedSnapshot();
return _currentSnapshot;
}
protected abstract T GetUpdatedSnapshot();
public override void Dispose()
{
TextBuffer.ChangeContentType(InertContentType.Instance, null);
if (TextBuffer.Properties != null && TextBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDocument))
{
TextBuffer.Properties.RemoveProperty(typeof(ITextDocument));
try
{
textDocument.Dispose();
}
catch
{
// Eat the exception for now while we are investigating an issue.
// There is System.OperationCanceledException: 'Project unload has already occurred or begun.'
// that gets thrown if Razor file is open when you are shutting down VS at
// Microsoft.VisualStudio.ProjectSystem.ProjectAsynchronousTasksServiceBase.RegisterAsyncTask(Microsoft.VisualStudio.Threading.JoinableTask, Microsoft.VisualStudio.ProjectSystem.ProjectCriticalOperation, bool)
// Microsoft.VisualStudio.ProjectSystem.VS.Implementation.CodeGenerators.GeneratorScheduler.ScheduleFileGeneration(Microsoft.VisualStudio.ProjectSystem.VS.Implementation.CodeGenerators.IGeneratorSchedulerRequest)
// Microsoft.VisualStudio.ProjectSystem.VS.Implementation.CodeGenerators.SingleFileGeneratorsService.ScheduleRefreshGeneratedFile(string)
// Microsoft.VisualStudio.ProjectSystem.VS.Implementation.CodeGenerators.SingleFileGeneratorsService.TextDocumentFactoryService_TextDocumentDisposed(object, Microsoft.VisualStudio.Text.TextDocumentEventArgs)
// Microsoft.VisualStudio.Text.Implementation.TextDocumentFactoryService.RaiseTextDocumentDisposed(Microsoft.VisualStudio.Text.ITextDocument)
// Microsoft.VisualStudio.Text.Implementation.TextDocument.Dispose()
// Microsoft.VisualStudio.LanguageServer.ContainedLanguage.VirtualDocumentBase<T>.Dispose() in VirtualDocumentBase
}
}
}
}
}
| 44.875 | 232 | 0.655239 | [
"Apache-2.0"
] | Youssef1313/aspnetcore-tooling | src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/VirtualDocumentBase.cs | 4,669 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProAppDistanceAndDirectionModule.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Esri")]
[assembly: AssemblyProduct("ProAppDistanceAndDirectionModule.Tests")]
[assembly: AssemblyCopyright("Copyright © Esri 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("560a68c8-c80b-4c84-9c3e-1ccd8addca76")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.378378 | 84 | 0.75429 | [
"Apache-2.0"
] | ArcGIS/distance-direction-addin-dotnet | source/addins/ProAppDistanceAndDirectionModule.Tests/Properties/AssemblyInfo.cs | 1,460 | C# |
#region Copyright & License
/*
Copyright (c) 2022, Integrated Solutions, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Integrated Solutions, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISI.Extensions.MessageBus
{
public abstract partial class AbstractMessageBus
{
public virtual async Task<TResponse> PublishAsync<TRequest, TResponse>(TRequest request, TimeSpan? timeout = null, TimeSpan? timeToLive = null, System.Threading.CancellationToken cancellationToken = default)
where TRequest : class
where TResponse : class
{
return await PublishAsync<TRequest, TResponse>((string)null, request, timeout, timeToLive, cancellationToken);
}
public abstract Task<TResponse> PublishAsync<TRequest, TResponse>(string queueName, TRequest request, TimeSpan? timeout = null, TimeSpan? timeToLive = null, System.Threading.CancellationToken cancellationToken = default)
where TRequest : class
where TResponse : class;
public virtual async Task<TResponse> PublishAsync<TRequest, TResponse>(Type requestType, TRequest request, TimeSpan? timeout = null, TimeSpan? timeToLive = null, System.Threading.CancellationToken cancellationToken = default)
where TRequest : class
where TResponse : class
{
return await PublishAsync<TRequest, TResponse>((string)null, requestType, request, timeout, timeToLive, cancellationToken);
}
public abstract Task<TResponse> PublishAsync<TRequest, TResponse>(string queueName, Type requestType, TRequest request, TimeSpan? timeout = null, TimeSpan? timeToLive = null, System.Threading.CancellationToken cancellationToken = default)
where TRequest : class
where TResponse : class;
}
} | 65.645833 | 754 | 0.796255 | [
"BSD-3-Clause"
] | ISI-Extensions/ISI.Extensions | src/ISI.Extensions/MessageBus/AbstractMessageBus/Publish_TRequest_TResponse.cs | 3,151 | C# |
// ---------------------------------------------------------------------------------------------------------------------
// <copyright file="NumberExtensions.cs" company="Justin Rockwood">
// Copyright (c) Justin Rockwood. All Rights Reserved. Licensed under the Apache License, Version 2.0. See
// LICENSE.txt in the project root for license information.
// </copyright>
// ---------------------------------------------------------------------------------------------------------------------
namespace RayTracerChallenge.Library
{
using System;
/// <summary>
/// Contains extension methods for numbers.
/// </summary>
public static class NumberExtensions
{
public const double Epsilon = 0.00001;
public static bool IsApproximatelyEqual(this double number, double other)
{
return Math.Abs(number - other) < Epsilon;
}
public static double RoundToEpsilon(this double number)
{
return Math.Round(number, digits: 5);
}
}
}
| 34.566667 | 121 | 0.497589 | [
"Apache-2.0"
] | jrockwood/RayTracerChallenge | CSharp/RayTracerChallenge.Library/NumberExtensions.cs | 1,039 | C# |
namespace EA.Prsd.Core.Tests.Mvc
{
using System.Collections;
using System.Collections.Generic;
using System.Web;
internal class FakeHttpContext : HttpContextBase
{
private Dictionary<object, object> _items = new Dictionary<object, object>();
public override IDictionary Items { get { return _items; } }
}
}
| 26.846154 | 85 | 0.687679 | [
"Unlicense"
] | DEFRA/prsd-iws | src/EA.Prsd.Core.Tests/Mvc/FakeHttpContext.cs | 351 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using KModkit;
using rnd = UnityEngine.Random;
class SequenceCut : Puzzle
{
int[] symbolToRow = { 29, 20, 30, 17, 4, 23, 25, 18, 16, 1, 15, 13, 3, 24, 2, 8, 7, 26, 14, 19, 11, 27, 21, 5, 28, 22, 10, 6, 0, 9, 12 };
int[][] sequences = new int[][] {
new int[] { ComponentInfo.ORANGE, ComponentInfo.YELLOW, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.BLUE },
new int[] { ComponentInfo.PURPLE, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.YELLOW, ComponentInfo.BLUE },
new int[] { ComponentInfo.PURPLE, ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.YELLOW, ComponentInfo.WHITE, ComponentInfo.BLUE, ComponentInfo.RED },
new int[] { ComponentInfo.YELLOW, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.BLUE, ComponentInfo.WHITE, ComponentInfo.PURPLE },
new int[] { ComponentInfo.YELLOW, ComponentInfo.WHITE, ComponentInfo.GREEN, ComponentInfo.RED, ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.BLUE },
new int[] { ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.BLUE, ComponentInfo.YELLOW },
new int[] { ComponentInfo.PURPLE, ComponentInfo.ORANGE, ComponentInfo.BLUE, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.RED },
new int[] { ComponentInfo.GREEN, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.YELLOW, ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.PURPLE },
new int[] { ComponentInfo.ORANGE, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.BLUE, ComponentInfo.GREEN },
new int[] { ComponentInfo.YELLOW, ComponentInfo.PURPLE, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.ORANGE },
new int[] { ComponentInfo.ORANGE, ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.GREEN, ComponentInfo.WHITE },
new int[] { ComponentInfo.ORANGE, ComponentInfo.WHITE, ComponentInfo.GREEN, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.YELLOW, ComponentInfo.BLUE },
new int[] { ComponentInfo.PURPLE, ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.WHITE, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.ORANGE },
new int[] { ComponentInfo.WHITE, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.YELLOW, ComponentInfo.GREEN },
new int[] { ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.GREEN },
new int[] { ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.BLUE },
new int[] { ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.PURPLE, ComponentInfo.RED, ComponentInfo.BLUE },
new int[] { ComponentInfo.BLUE, ComponentInfo.GREEN, ComponentInfo.RED, ComponentInfo.YELLOW, ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.PURPLE },
new int[] { ComponentInfo.GREEN, ComponentInfo.PURPLE, ComponentInfo.ORANGE, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.YELLOW, ComponentInfo.WHITE },
new int[] { ComponentInfo.PURPLE, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.WHITE, ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.YELLOW },
new int[] { ComponentInfo.RED, ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.GREEN, ComponentInfo.BLUE, ComponentInfo.YELLOW, ComponentInfo.PURPLE },
new int[] { ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.PURPLE, ComponentInfo.ORANGE },
new int[] { ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.GREEN, ComponentInfo.BLUE, ComponentInfo.RED },
new int[] { ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.ORANGE, ComponentInfo.RED, ComponentInfo.PURPLE },
new int[] { ComponentInfo.PURPLE, ComponentInfo.ORANGE, ComponentInfo.GREEN, ComponentInfo.WHITE, ComponentInfo.RED, ComponentInfo.BLUE, ComponentInfo.YELLOW },
new int[] { ComponentInfo.RED, ComponentInfo.WHITE, ComponentInfo.GREEN, ComponentInfo.PURPLE, ComponentInfo.ORANGE, ComponentInfo.BLUE, ComponentInfo.YELLOW },
new int[] { ComponentInfo.YELLOW, ComponentInfo.ORANGE, ComponentInfo.RED, ComponentInfo.PURPLE, ComponentInfo.BLUE, ComponentInfo.WHITE, ComponentInfo.GREEN },
new int[] { ComponentInfo.PURPLE, ComponentInfo.RED, ComponentInfo.WHITE, ComponentInfo.YELLOW, ComponentInfo.ORANGE, ComponentInfo.BLUE, ComponentInfo.GREEN },
new int[] { ComponentInfo.PURPLE, ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.ORANGE, ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.WHITE },
new int[] { ComponentInfo.WHITE, ComponentInfo.RED, ComponentInfo.ORANGE, ComponentInfo.GREEN, ComponentInfo.YELLOW, ComponentInfo.BLUE, ComponentInfo.PURPLE },
new int[] { ComponentInfo.RED, ComponentInfo.GREEN, ComponentInfo.BLUE, ComponentInfo.YELLOW, ComponentInfo.ORANGE, ComponentInfo.PURPLE, ComponentInfo.WHITE },
};
int row;
int[] seq;
List<int>[] cutGroups = new List<int>[7];
List<int> used;
List<int> cut;
public SequenceCut(Modkit module, int moduleId, ComponentInfo info) : base(module, moduleId, info)
{
Debug.LogFormat("[The Modkit #{0}] Solving Sequence Cut. Symbols present are: {1}. Alphanumeric keys present are: {2}.", moduleId, info.GetSymbols(), info.alphabet.Join(", "));
row = info.symbols.Select(x => symbolToRow[x]).Min();
seq = sequences[row];
Debug.LogFormat("[The Modkit #{0}] Base sequence {1} - [ {2} ].", moduleId, row + 1, seq.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));
CalcKeysSwitches();
Debug.LogFormat("[The Modkit #{0}] Final sequence is [ {1} ].", moduleId, seq.Select(x => ComponentInfo.COLORNAMES[x]).Join(", "));
CalcWireCuts();
}
public override void OnWireCut(int wire)
{
if(module.IsAnimating())
return;
module.GetComponent<KMAudio>().PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.WireSnip, module.transform);
module.CutWire(wire);
if(module.IsSolved())
return;
if(!module.CheckValidComponents())
{
Debug.LogFormat("[The Modkit #{0}] Strike! Cut wire {1} when component selection was [ {2} ] instead of [ {3} ].", moduleId, wire + 1, module.GetOnComponents(), module.GetTargetComponents());
module.CauseStrike();
module.RegenWires();
return;
}
module.StartSolve();
List<int> group = null;
int acc = 0;
for(int i = 0; i < cutGroups.Length; i++)
{
acc += cutGroups[i].Count();
if(acc > cut.Count())
{
group = cutGroups[i];
break;
}
}
if(group.Contains(wire))
{
Debug.LogFormat("[The Modkit #{0}] Correctly cut wire {1}.", moduleId, wire + 1);
cut.Add(wire);
if(cut.Count() == 5)
{
Debug.LogFormat("[The Modkit #{0}] Module solved.", moduleId);
module.Solve();
}
}
else
{
Debug.LogFormat("[The Modkit #{0}] Strike! Incorrectly cut wire {1}.", moduleId, wire + 1);
module.CauseStrike();
module.RegenWires();
CalcWireCuts();
}
}
void CalcKeysSwitches()
{
for(int i = 0; i < info.alphabet.Length; i++)
{
int pos1;
int pos2;
if(module.bomb.GetSerialNumber().IndexOf(info.alphabet[i][0]) != -1)
pos1 = module.bomb.GetSerialNumber().IndexOf(info.alphabet[i][0]);
else
pos1 = (info.alphabet[i][0] - 'A' + 1) % 7;
if((info.alphabet[i][1] - '0') >= 1 && (info.alphabet[i][1] - '0') <= 7)
pos2 = (info.alphabet[i][1] - '0') - 1;
else if ((info.alphabet[i][1] - '0') == 0)
pos2 = module.bomb.GetSerialNumber().IndexOf(module.bomb.GetSerialNumberNumbers().ToArray()[0].ToString()[0]);
else
pos2 = 6;
Debug.LogFormat("[The Modkit #{0}] Alphanumeric key {1} switches positions {2} and {3}.", moduleId, i + 1, pos1 + 1, pos2 + 1);
int temp = seq[pos1];
seq[pos1] = seq[pos2];
seq[pos2] = temp;
}
}
void CalcWireCuts()
{
Debug.LogFormat("[The Modkit #{0}] Wires present: {1}.", moduleId, info.GetWireNames());
used = new List<int>();
cut = new List<int>();
for(int i = 0; i < cutGroups.Length; i++)
{
cutGroups[i] = new List<int>();
for(int j = 0; j < info.wires.Length; j++)
{
int color1 = info.wires[j] / 10;
int color2 = info.wires[j] % 10;
if((color1 == seq[i] || color2 == seq[i]) && !used.Contains(j))
{
used.Add(j);
cutGroups[i].Add(j);
}
}
}
Debug.LogFormat("[The Modkit #{0}] Wires cut groups: {1}.", moduleId, cutGroups.Where(x => x.Count() != 0).Select(x => "[" + x.Select(y => y + 1).Join(", ") + "]").Join(""));
}
} | 58.656805 | 197 | 0.65167 | [
"MIT"
] | rocket0634/ktane-modkit | Assets/Scripts The Modkit/SequenceCut.cs | 9,913 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CSpawnTreeInitializerToggleMonsterDefaultIdleBehaviors : ISpawnTreeInitializerToggleBehavior
{
public CSpawnTreeInitializerToggleMonsterDefaultIdleBehaviors(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CSpawnTreeInitializerToggleMonsterDefaultIdleBehaviors(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 35.73913 | 166 | 0.782238 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CSpawnTreeInitializerToggleMonsterDefaultIdleBehaviors.cs | 800 | C# |
using AutoMapper;
using sXb_service.Helpers;
using sXb_service.Models;
using sXb_service.Repos.Interfaces;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace sXb_service.Services
{
public class BookApi : IBookApi
{
private string key;
private HttpClient bookApi;
private IMapper _mapper;
public BookApi(IHttpClientFactory clientFactory, BookApiConfig bookApiConfig, IMapper mapper)
{
bookApi = clientFactory.CreateClient("findBook");
key = bookApiConfig.Apikey;
_mapper = mapper;
}
public async Task<Paging<BookApiResult>> FindBook(string term, int page)
{
List<BookApiResult> results = new List<BookApiResult>();
var index = (page - 1) * 10;
try
{
var response = await bookApi.GetAsync($"volumes?q={term}&startIndex={index}&key={key}");
response.EnsureSuccessStatusCode();
var bookInfo = await response.Content.ReadAsAsync<BookSearchResults>();
foreach (var book in bookInfo.Items)
{
var newBook = _mapper.Map<BookApiResult>(book.VolumeInfo);
if(newBook.ISBN10 != null)
{
results.Add(newBook);
}
}
return Paging<BookApiResult>.ApplyPaging(bookInfo.TotalItems, results, page);
}
catch
{
return Paging<BookApiResult>.ApplyPaging(0, results, page);
}
}
}
}
public class BookSearchResults
{
public int TotalItems { get; set; }
public Items[] Items { get; set; }
}
public class Items
{
public VolumeInfo VolumeInfo { get; set; }
}
public class VolumeInfo
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string[] Authors { get; set; }
public string Publisher { get; set; }
public string Description { get; set; }
public IndustryIdentifiers[] IndustryIdentifiers { get; set; }
public ImageLinks ImageLinks { get; set; }
}
public class IndustryIdentifiers
{
public string Type { get; set; }
public string Identifier { get; set; }
}
public class ImageLinks
{
public string SmallThumbnail { get; set; }
public string Thumbnail { get; set; }
}
| 28.337209 | 104 | 0.597866 | [
"MIT"
] | studentsXbooks/studentsXbooks-app | backend/sXb-service/Services/BookApi.cs | 2,439 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
namespace cfg.l10n
{
public partial class TbL10NDemo
{
private readonly Dictionary<int, l10n.L10NDemo> _dataMap;
private readonly List<l10n.L10NDemo> _dataList;
public TbL10NDemo(ByteBuf _buf)
{
_dataMap = new Dictionary<int, l10n.L10NDemo>();
_dataList = new List<l10n.L10NDemo>();
for(int n = _buf.ReadSize() ; n > 0 ; --n)
{
l10n.L10NDemo _v;
_v = l10n.L10NDemo.DeserializeL10NDemo(_buf);
_dataList.Add(_v);
_dataMap.Add(_v.Id, _v);
}
PostInit();
}
public Dictionary<int, l10n.L10NDemo> DataMap => _dataMap;
public List<l10n.L10NDemo> DataList => _dataList;
public l10n.L10NDemo GetOrDefault(int key) => _dataMap.TryGetValue(key, out var v) ? v : null;
public l10n.L10NDemo Get(int key) => _dataMap[key];
public l10n.L10NDemo this[int key] => _dataMap[key];
public void Resolve(Dictionary<string, object> _tables)
{
foreach(var v in _dataList)
{
v.Resolve(_tables);
}
PostResolve();
}
public void TranslateText(System.Func<string, string, string> translator)
{
foreach(var v in _dataList)
{
v.TranslateText(translator);
}
}
partial void PostInit();
partial void PostResolve();
}
} | 28.645161 | 98 | 0.558559 | [
"MIT"
] | HFX-93/luban_examples | Projects/Csharp_DotNet5_bin/Gen/l10n/TbL10NDemo.cs | 1,776 | C# |
/*
* The MIT License
*
* Copyright 2019 Palmtree Software.
*
* 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.
*/
namespace Palmtree.Math.Test.Plugin.Sint
{
class ComponentTestPlugin_Subtruct_UX_UI
: ComponentTestPluginBase_2_1
{
public ComponentTestPlugin_Subtruct_UX_UI()
: base("sint", "subtruct_ux_ui", "test_data_subtruct_ux_ui.xml")
{
}
protected override IDataItem TestFunc(IDataItem p1, IDataItem p2)
{
var u = p1.ToUBigInt().Value;
var v = p2.ToUInt32().Value;
var w = u.Subtruct(v);
return (new BigIntDataItem(w));
}
public override int Order => 101;
}
}
/*
* END OF FILE
*/ | 34.431373 | 80 | 0.697608 | [
"MIT"
] | rougemeilland/Palmtree.Math | Palmtree.Math.Test/Plugin/Sint/ComponentTestPlugin_Subtruct_UX_UI.cs | 1,758 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Win.Rentas
{
public partial class FormComida : Form
{
public FormComida()
{
InitializeComponent();
}
}
}
| 19 | 43 | 0.654135 | [
"MIT"
] | AdrianPin/Ventas | Ventas1/SistemaRentas/Rentas/Win.Rentas/FormComida.cs | 401 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Server.MasterData.DTO.Data.CrossService;
namespace Server.Util
{
public static class TimeSpanExtensions
{
/// <summary>
/// Multiplies a timespan by an integer value
/// </summary>
public static long DividedBy(this TimeSpan dividend, TimeSpan divisor)
{
return dividend.Ticks / divisor.Ticks;
}
public static TimeSpan ToTimeSpan(this RequiredAttentiveness attentiveness)
{
switch (attentiveness)
{
case RequiredAttentiveness.Constantly:
return TimeSpan.FromSeconds(1);
case RequiredAttentiveness.Minutely:
return TimeSpan.FromMinutes(1);
case RequiredAttentiveness.Hourly:
return TimeSpan.FromHours(1);
case RequiredAttentiveness.Daily:
return TimeSpan.FromDays(1);
case RequiredAttentiveness.Weekly:
return TimeSpan.FromDays(7);
default:
return TimeSpan.FromHours(1);
}
}
}
} | 31.25641 | 83 | 0.576702 | [
"MIT"
] | ViolaCrellin/NopePets | Server/Util/TimeSpanExtensions.cs | 1,221 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_Activities_Controls_UI_Activity_Details {
/// <summary>
/// headDetail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.FormEngine.Web.UI.FormCategoryHeading headDetail;
/// <summary>
/// pnlDetails control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlDetails;
}
| 31.75 | 81 | 0.549213 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/Activities/Controls/UI/Activity/Details.ascx.designer.cs | 1,018 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using OrbitalShell.Lib;
using OrbitalShell.Component.CommandLine.CommandModel;
using OrbitalShell.Component.CommandLine.Parsing;
using OrbitalShell.Component.CommandLine.Processor;
using System.Reflection;
using System.Collections.ObjectModel;
using OrbitalShell.Component.Shell.Variable;
using System.Text;
namespace OrbitalShell.Component.Shell.Module
{
/// <summary>
/// module command manager
/// </summary>
public class ModuleCommandManager : IModuleCommandManager
{
#region attributes
public IEnumerable<string> CommandDeclaringShortTypesNames => AllCommands.Select(x => x.DeclaringTypeShortName).Distinct();
public IEnumerable<string> CommandDeclaringTypesNames => AllCommands.Select(x => x.DeclaringTypeFullName).Distinct();
public IEnumerable<string> CommandDeclaringTypesAssemblyQualifiedNames => AllCommands.Select(x => x.DecralingTypeAssemblyQualifiedName).Distinct();
readonly Dictionary<string, List<CommandSpecification>> _commands = new Dictionary<string, List<CommandSpecification>>();
public IReadOnlyDictionary<string, List<CommandSpecification>> Commands => new ReadOnlyDictionary<string, List<CommandSpecification>>(_commands);
public List<CommandSpecification> AllCommands
{
get
{
var coms = new List<CommandSpecification>();
foreach (var kvp in _commands)
foreach (var com in kvp.Value)
coms.Add(com);
coms.Sort(new Comparison<CommandSpecification>((x, y) => x.Name.CompareTo(y.Name)));
return coms;
}
}
readonly IModuleSet _modules;
readonly ISyntaxAnalyser _syntaxAnalyzer;
#endregion
public ModuleCommandManager(
ISyntaxAnalyser syntaxAnalyser,
IModuleSet modules
)
{
_syntaxAnalyzer = syntaxAnalyser;
_modules = modules;
}
public bool UnregisterCommand(CommandSpecification comSpec)
{
if (_commands.TryGetValue(comSpec.Name, out var cmdLst))
{
var r = cmdLst.Remove(comSpec);
if (r)
_syntaxAnalyzer.Remove(comSpec);
if (cmdLst.Count == 0)
_commands.Remove(comSpec.Name);
return r;
}
return false;
}
public ModuleSpecification
UnregisterModuleCommands(
CommandEvaluationContext context,
string modulePackageId)
{
modulePackageId = modulePackageId?.ToLower();
var moduleSpecification = _modules.Values.Where(x => x.Key.ToLower() == modulePackageId).FirstOrDefault();
if (moduleSpecification != null)
{
foreach (var com in AllCommands)
if (com.MethodInfo.DeclaringType.Assembly == moduleSpecification.Assembly)
UnregisterCommand(com);
return moduleSpecification;
}
else
{
context.Errorln($"commands module '{modulePackageId}' not registered");
return ModuleSpecification.ModuleSpecificationNotDefined;
}
}
int _RegisterModuleCommands(CommandEvaluationContext context, Type type)
{
if (type.GetInterface(typeof(ICommandsDeclaringType).FullName) != null)
return RegisterCommandClass(context, type, false);
return 0;
}
public void RegisterCommandClass<T>(CommandEvaluationContext context) => RegisterCommandClass(context, typeof(T), true);
public int RegisterCommandClass(CommandEvaluationContext context, Type type) => RegisterCommandClass(context, type, true);
public string CheckAndNormalizeCommandNamespace(string[] segments)
{
for (int i = 0; i < segments.Length; i++)
{
var s = segments[i];
if (string.IsNullOrWhiteSpace(s)) throw new Exception("invalid namespace segment: '{s}'");
segments[i] = s.ToLower();
}
return string.Join(CommandLineSyntax.CommandNamespaceSeparator, segments);
}
/// <summary>
/// normalize a command name according to naming conventions
/// </summary>
/// <param name="s">command name to be normalized</param>
/// <returns>normalized command name</returns>
public string CheckAndNormalizeCommandName(string s)
{
if (string.IsNullOrWhiteSpace(s)) throw new Exception("command name can't be empty");
var sb = new StringBuilder();
var t = s.ToCharArray();
for (int i = 0; i < t.Length; i++)
{
var c = t[i];
if (char.IsUpper(c) && (i == t.Length - 1 || !char.IsUpper(t[i + 1])))
{
sb.Append(CommandLineSyntax.CommandNamespaceSeparator);
sb.Append(char.ToLower(c));
}
else
sb.Append(c);
}
var r = sb.ToString();
if (r.StartsWith(CommandLineSyntax.CommandNamespaceSeparator))
r = r.Length > 1 ? r.Substring(1) : "";
return r;
}
public int RegisterCommandClass(
CommandEvaluationContext context,
Type type,
bool registerAsModule
)
{
if (type.GetInterface(typeof(ICommandsDeclaringType).FullName) == null)
throw new Exception($"the type '{type.FullName}' must implements interface '{typeof(ICommandsDeclaringType).FullName}' to be registered as a command class");
var dtNamespaceAttr = type.GetCustomAttribute<CommandsNamespaceAttribute>();
var dtNamespace = (dtNamespaceAttr == null) ? "" : CheckAndNormalizeCommandNamespace(dtNamespaceAttr.Segments);
var comsCount = 0;
object instance = Activator.CreateInstance(type, new object[] { });
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (registerAsModule && _modules.ContainsKey(type.FullName))
{
context.Errorln($"a module with same name than the commands declaring type '{type.FullName}' is already registered");
return 0;
}
foreach (var method in methods)
{
var cmd = method.GetCustomAttribute<CommandAttribute>();
if (cmd != null)
{
if (!method.ReturnType.HasInterface(typeof(ICommandResult)))
{
context.Errorln($"class={type.FullName} method={method.Name} wrong return type. should be of type '{typeof(ICommandResult).FullName}', but is of type: {method.ReturnType.FullName}");
}
else
{
// ⏺ build the command specification from the method meta-data
var cmdNamespaceAttr = method.GetCustomAttribute<CommandNamespaceAttribute>();
var cmdNamespace = cmdNamespaceAttr == null ? dtNamespace : CheckAndNormalizeCommandNamespace(cmdNamespaceAttr.Segments);
var cmdAliasesAttrLst = method.GetCustomAttributes<CommandAliasAttribute>();
var cmdAliases = cmdAliasesAttrLst?.Select(x => (x.AliasName, x.AliasText)).ToList();
if (cmdAliases.Count == 0) cmdAliases = null; // convention
#region init from method parameters attributes
var paramspecs = new List<CommandParameterSpecification>();
bool syntaxError = false;
var pindex = 0;
foreach (var parameter in method.GetParameters())
{
if (pindex == 0)
{
// manadatory: param 0 is CommandEvaluationContext
if (parameter.ParameterType != typeof(CommandEvaluationContext))
{
context.Errorln($"class={type.FullName} method={method.Name} parameter 0 ('{parameter.Name}') should be of type '{typeof(CommandEvaluationContext).FullName}', but is of type: {parameter.ParameterType.FullName}");
syntaxError = true;
break;
}
}
else
{
CommandParameterSpecification pspec = null;
object defval = null;
if (!parameter.HasDefaultValue && parameter.ParameterType.IsValueType)
defval = Activator.CreateInstance(parameter.ParameterType);
// param
var paramAttr = parameter.GetCustomAttribute<ParameterAttribute>();
if (paramAttr != null)
{
// TODO: validate command specification (eg. indexs validity)
pspec = new CommandParameterSpecification(
parameter.Name,
paramAttr.Description,
paramAttr.IsOptional,
paramAttr.Index,
null,
null,
true,
parameter.HasDefaultValue,
paramAttr.HasDefaultValue ?
paramAttr.DefaultValue
: ((parameter.HasDefaultValue) ? parameter.DefaultValue : defval),
parameter);
}
// option
var optAttr = parameter.GetCustomAttribute<OptionAttribute>();
if (optAttr != null)
{
var reqParamAttr = parameter.GetCustomAttribute<OptionRequireParameterAttribute>();
try
{
pspec = new CommandParameterSpecification(
parameter.Name,
optAttr.Description,
optAttr.IsOptional,
-1,
optAttr.OptionName /*?? parameter.Name*/,
optAttr.OptionLongName,
optAttr.HasValue,
parameter.HasDefaultValue,
optAttr.HasDefaultValue ?
optAttr.DefaultValue
: ((parameter.HasDefaultValue) ? parameter.DefaultValue : defval),
parameter,
reqParamAttr?.RequiredParameterName);
}
catch (Exception ex)
{
context.Errorln(ex.Message);
}
}
if (pspec == null)
{
syntaxError = true;
context.Errorln($"invalid parameter: class={type.FullName} method={method.Name} name={parameter.Name}");
}
else
paramspecs.Add(pspec);
}
pindex++;
}
#endregion
if (!syntaxError)
{
var cmdNameAttr = method.GetCustomAttribute<CommandNameAttribute>();
var cmdName = CheckAndNormalizeCommandName(
(cmdNameAttr != null && cmdNameAttr.Name != null) ?
cmdNameAttr.Name
: (cmd.Name ?? method.Name));
bool registered = true;
CommandSpecification cmdspec = null;
try
{
cmdspec = new CommandSpecification(
cmdNamespace,
cmdName,
cmd.Description,
cmd.LongDescription,
cmd.Documentation,
method,
instance,
cmdAliases,
paramspecs);
}
catch (Exception ex)
{
context.Errorln($"error in command '{cmdName}' specification: {ex.Message}");
}
if (cmdspec != null)
{
if (_commands.TryGetValue(cmdspec.Name, out var cmdlst))
{
if (cmdlst.Select(x => x.MethodInfo.DeclaringType == type).Any())
{
context.Errorln($"command already registered: '{cmdspec.Name}' in type '{cmdspec.DeclaringTypeFullName}'");
registered = false;
}
else
{
cmdlst.Add(cmdspec);
}
}
else
_commands.Add(cmdspec.Name, new List<CommandSpecification> { cmdspec });
if (registered)
{
_syntaxAnalyzer.Add(cmdspec);
comsCount++;
// register command Aliases
if (cmdspec.Aliases != null)
foreach (var alias in cmdspec.Aliases)
context.CommandLineProcessor.CommandsAlias.AddOrReplaceAlias(
context,
alias.name,
alias.text
);
}
}
}
}
}
}
if (registerAsModule)
{
if (comsCount == 0)
context.Errorln($"no commands found in type '{type.FullName}'");
else
{
var descAttr = type.GetCustomAttribute<CommandsAttribute>();
var description = descAttr != null ? descAttr.Description : "";
_modules.Add(
type.FullName, // key not from assembly but from type
new ModuleSpecification(
type.FullName,
ModuleUtil.DeclaringTypeShortName(type),
description,
type.Assembly,
new ModuleInfo(
1,
comsCount
),
type
));
}
}
return comsCount;
}
public CommandSpecification GetCommandSpecification(MethodInfo commandMethodInfo)
=> AllCommands.Where(x => x.MethodInfo == commandMethodInfo).FirstOrDefault();
}
} | 46.884932 | 248 | 0.449132 | [
"MIT"
] | OrbitalShell/Orbital-Shell | OrbitalShell-Kernel/Component/Shell/Module/ModuleCommandManager.cs | 17,115 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Cognitive.CustomVision.Training.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class ImageCreateSummary
{
/// <summary>
/// Initializes a new instance of the ImageCreateSummary class.
/// </summary>
public ImageCreateSummary()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ImageCreateSummary class.
/// </summary>
public ImageCreateSummary(bool isBatchSuccessful = default(bool), IList<ImageCreateResult> images = default(IList<ImageCreateResult>))
{
IsBatchSuccessful = isBatchSuccessful;
Images = images;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "IsBatchSuccessful")]
public bool IsBatchSuccessful { get; private set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Images")]
public IList<ImageCreateResult> Images { get; private set; }
}
}
| 30.509091 | 142 | 0.631108 | [
"MIT"
] | Bhaskers-Blu-Org2/Cognitive-CustomVision-Windows | ClientLibrary/Microsoft.Cognitive.CustomVision.Training/Generated/Models/ImageCreateSummary.cs | 1,678 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("4.ParallelFramework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("4.ParallelFramework")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("95bc7c5a-3389-4426-a75f-e49bfd90ceeb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.746279 | [
"MIT"
] | RePierre/dot-net-async | 4.ParallelFramework/Properties/AssemblyInfo.cs | 1,414 | C# |
using System;
using System.Windows.Forms;
/* Chanmongler -- chanstyle imageboard downloader and searcher
* Copyright (C) 2008,2009 Praetox (http://praetox.com/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chanmongler {
public partial class frmNews : Form {
public frmNews() {
InitializeComponent();
}
string DownloadError;
private void frmNews_Load(object sender, EventArgs e) {
DownloadError = txtNews.Text;
txtNews.Text = "Downloading news...";
this.Show(); Application.DoEvents();
try {
txtNews.Text = new System.Net.WebClient().DownloadString(
frmMain.PrgDomain + "Chanmongler_news.php");
txtNews.SelectionStart = 0;
txtNews.SelectionLength = 0;
}
catch {
txtNews.Text = DownloadError;
txtNews.SelectionStart = 0;
txtNews.SelectionLength = 0;
}
}
}
}
| 36.148936 | 74 | 0.609182 | [
"Unlicense"
] | Praetox/Chan | Chanmongler_final/Backup/Chanmongler/frmNews.cs | 1,701 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class ShowOnlineHelpRequest
{
public static readonly
RequestType<string, object> Type =
RequestType<string, object>.Create("powerShell/showOnlineHelp");
}
}
| 30 | 101 | 0.733333 | [
"MIT"
] | stefb965/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/ShowOnlineHelpRequest.cs | 512 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fragmentctrl : MonoBehaviour{
public Vector3 jumpForce;
public float destroyDelay;
private Rigidbody2D rb;
// Use this for initialization
void Start (){
rb = GetComponent<Rigidbody2D>();
rb.AddForce(jumpForce);
Destroy(gameObject,destroyDelay);
}
}
| 17.238095 | 42 | 0.756906 | [
"MIT"
] | smishadhin/Unity-Game-Projects-PublivRepo | Cats on the woods - 2d platformer/Assets/Scripts/Fragmentctrl.cs | 364 | C# |
/*******************************************************************************
* Copyright (c) 2013 IBM Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Steve Pitschke - initial API and implementation
*******************************************************************************/
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Xml.Linq;
using log4net;
using Microsoft.Test.CommandLineParsing;
using OSLC4Net.Client.Exceptions;
using OSLC4Net.Client.Oslc;
using OSLC4Net.Client.Oslc.Jazz;
using OSLC4Net.Client.Oslc.Resources;
using OSLC4Net.Core.Model;
using System.Net.Security;
namespace OSLC4Net.Client.Samples
{
/// <summary>
/// Samples of logging in to Rational Requirements Composer and running OSLC operations
///
///
/// - run an OLSC Requirement query and retrieve OSLC Requirements and de-serialize them as .NET objects
/// - TODO: Add more requirement sample scenarios
/// </summary>
class RRCOAuthSample
{
private static ILog logger = LogManager.GetLogger(typeof(RRCFormSample));
// Following is a workaround for primaryText issue in DNG ( it is PrimaryText instead of primaryText
private static readonly QName PROPERTY_PRIMARY_TEXT_WORKAROUND = new QName(RmConstants.JAZZ_RM_NAMESPACE, "PrimaryText");
/// <summary>
/// Login to the RRC server and perform some OSLC actions
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
CommandLineDictionary cmd = CommandLineDictionary.FromArguments(args);
if (!ValidateOptions(cmd)) {
logger.Error("Syntax: /url=https://<server>:port/<context>/ /user=<user> /password=<password> /project=\"<project_area>\"");
logger.Error("Example: /url=https://exmple.com:9443/rm /user=ADMIN /password=ADMIN /project=\"JKE Banking (Requirements Management)\"");
return;
}
String webContextUrl = cmd["url"];
String user = cmd["user"];
String passwd = cmd["password"];
String projectArea = cmd["project"];
try {
//STEP 0: Need to accept all SSL certificates for DotNet Open Auth to be able to do it's OAuth token generation UNLESS
//the SSL certificate from CLM is a from a trusted certificate authority.
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OslcClient.AcceptAllServerCertificates);
//STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl,OSLCConstants.OSLC_RM_V2);
//STEP 2: Create a new OSLC OAuth capable client, the parameter of following call should be provided
//This is a bit of a hack for readability. It is assuming RRC is at context /rm. Could use a regex or UriBuilder instead.
String authUrl = webContextUrl.Replace("/rm", "/jts"); // XXX - should be ReplaceFirst(), if it existed
JazzOAuthClient client = helper.InitOAuthClient("123456789", "secret", user, passwd, authUrl);
//STEP 3: Get the URL of the OSLC ChangeManagement catalog
String catalogUrl = helper.GetCatalogUrl();
//STEP 4: Find the OSLC Service Provider for the project area we want to work with
String serviceProviderUrl = client.LookupServiceProviderUrl(catalogUrl, projectArea);
//STEP 5: Get the Query Capabilities URL so that we can run some OSLC queries
String queryCapability = client.LookupQueryCapability(serviceProviderUrl,
OSLCConstants.OSLC_RM_V2,
OSLCConstants.RM_REQUIREMENT_TYPE);
//STEP 6: Create base requirements
//Get the Creation Factory URL for change requests so that we can create one
Requirement requirement = new Requirement();
String requirementFactory = client.LookupCreationFactory(
serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
requirement.GetRdfTypes()[0].ToString());
//Get Feature Requirement Type URL
ResourceShape featureInstanceShape = RmUtil.LookupRequirementsInstanceShapes(
serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
requirement.GetRdfTypes()[0].ToString(), client, "Feature");
Uri rootFolder = null;
//Get Collection Type URL
RequirementCollection collection = new RequirementCollection();
ResourceShape collectionInstanceShape = RmUtil.LookupRequirementsInstanceShapes(
serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
collection.GetRdfTypes()[0].ToString(), client, "Personal Collection");
String req01URL=null;
String req02URL=null;
String req03URL=null;
String req04URL=null;
String reqcoll01URL=null;
String primaryText = null;
if (( featureInstanceShape != null ) && (requirementFactory != null ) ){
// Create REQ01
requirement.SetInstanceShape(featureInstanceShape.GetAbout());
requirement.SetTitle("Req01");
// Decorate the PrimaryText
primaryText = "My Primary Text";
XElement obj = RmUtil.ConvertStringToHTML(primaryText);
requirement.GetExtendedProperties().Add(RmConstants.PROPERTY_PRIMARY_TEXT, obj);
requirement.SetDescription("Created By OSLC4Net");
requirement.AddImplementedBy(new Link(new Uri("http://google.com"), "Link in REQ01"));
//Create the change request
HttpResponseMessage creationResponse = client.CreateResource(
requirementFactory, requirement,
OslcMediaType.APPLICATION_RDF_XML,
OslcMediaType.APPLICATION_RDF_XML);
req01URL = creationResponse.Headers.Location.ToString();
creationResponse.ConsumeContent();
// Create REQ02
requirement = new Requirement();
requirement.SetInstanceShape(featureInstanceShape.GetAbout());
requirement.SetTitle("Req02");
requirement.SetDescription("Created By OSLC4Net");
requirement.AddValidatedBy(new Link(new Uri("http://bancomer.com"), "Link in REQ02"));
//Create the change request
creationResponse = client.CreateResource(
requirementFactory, requirement,
OslcMediaType.APPLICATION_RDF_XML,
OslcMediaType.APPLICATION_RDF_XML);
req02URL = creationResponse.Headers.Location.ToString();
creationResponse.ConsumeContent();
// Create REQ03
requirement = new Requirement();
requirement.SetInstanceShape(featureInstanceShape.GetAbout());
requirement.SetTitle("Req03");
requirement.SetDescription("Created By OSLC4Net");
requirement.AddValidatedBy(new Link(new Uri("http://outlook.com"), "Link in REQ03"));
//Create the change request
creationResponse = client.CreateResource(
requirementFactory, requirement,
OslcMediaType.APPLICATION_RDF_XML,
OslcMediaType.APPLICATION_RDF_XML);
req03URL = creationResponse.Headers.Location.ToString();
creationResponse.ConsumeContent();
// Create REQ04
requirement = new Requirement();
requirement.SetInstanceShape(featureInstanceShape.GetAbout());
requirement.SetTitle("Req04");
requirement.SetDescription("Created By OSLC4Net");
//Create the Requirement
creationResponse = client.CreateResource(
requirementFactory, requirement,
OslcMediaType.APPLICATION_RDF_XML,
OslcMediaType.APPLICATION_RDF_XML);
req04URL = creationResponse.Headers.Location.ToString();
creationResponse.ConsumeContent();
// Now create a collection
// Create REQ04
collection = new RequirementCollection();
collection.AddUses(new Uri(req03URL));
collection.AddUses(new Uri(req04URL));
collection.SetInstanceShape(collectionInstanceShape.GetAbout());
collection.SetTitle("Collection01");
collection.SetDescription("Created By OSLC4Net");
//Create the change request
creationResponse = client.CreateResource(
requirementFactory, collection,
OslcMediaType.APPLICATION_RDF_XML,
OslcMediaType.APPLICATION_RDF_XML);
reqcoll01URL = creationResponse.Headers.Location.ToString();
creationResponse.ConsumeContent();
}
// Check that everything was properly created
if ( req01URL == null ||
req02URL == null ||
req03URL == null ||
req04URL == null ||
reqcoll01URL == null ) {
throw new Exception("Failed to create an artifact");
}
// GET the root folder based on First requirement created
HttpResponseMessage getResponse = client.GetResource(req01URL,OslcMediaType.APPLICATION_RDF_XML);
requirement = getResponse.Content.ReadAsAsync<Requirement>(client.GetFormatters()).Result;
String etag1 = getResponse.Headers.ETag.ToString();
// May not be needed getResponse.ConsumeContent();
//Save the Uri of the root folder in order to used it easily
rootFolder = (Uri) requirement.GetExtendedProperties()[RmConstants.PROPERTY_PARENT_FOLDER];
String changedPrimaryText = (String ) requirement.GetExtendedProperties()[RmConstants.PROPERTY_PRIMARY_TEXT];
if ( changedPrimaryText == null ){
// Check with the workaround
changedPrimaryText = (String ) requirement.GetExtendedProperties()[PROPERTY_PRIMARY_TEXT_WORKAROUND];
}
if ( ( changedPrimaryText != null) && (! changedPrimaryText.Contains(primaryText)) ) {
logger.Error("Error getting primary Text");
}
//QUERIES
// SCENARIO 01 Do a query for type= Requirements
OslcQueryParameters queryParams = new OslcQueryParameters();
queryParams.SetPrefix("rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
queryParams.SetWhere("rdf:type=<http://open-services.net/ns/rm#Requirement>");
OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
OslcQueryResult result = query.Submit();
bool processAsDotNetObjects = false;
int resultsSize = result.GetMembersUrls().Length;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 01 = " + resultsSize + "\n");
// SCENARIO 02 Do a query for type= Requirements and for it folder container = rootFolder
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("nav=<http://com.ibm.rdm/navigation#>,rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
queryParams.SetWhere("rdf:type=<http://open-services.net/ns/rm#Requirement> and nav:parent=<" + rootFolder + ">");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
processAsDotNetObjects = false;
resultsSize = result.GetMembersUrls().Length;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 02 = " + resultsSize + "\n");
// SCENARIO 03 Do a query for title
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("dcterms=<http://purl.org/dc/terms/>");
queryParams.SetWhere("dcterms:title=\"Req04\"");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 03 = " + resultsSize + "\n");
// SCENARIO 04 Do a query for the link that is implemented
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
queryParams.SetWhere("oslc_rm:implementedBy=<http://google.com>");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 04 = " + resultsSize + "\n");
// SCENARIO 05 Do a query for the links that is validated
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
queryParams.SetWhere("oslc_rm:validatedBy in [<http://bancomer.com>,<http://outlook.com>]");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 05 = " + resultsSize + "\n");
// SCENARIO 06 Do a query for it container folder and for the link that is implemented
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("nav=<http://com.ibm.rdm/navigation#>,oslc_rm=<http://open-services.net/ns/rm#>");
queryParams.SetWhere("nav:parent=<"+rootFolder+"> and oslc_rm:validatedBy=<http://bancomer.com>");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 06 = " + resultsSize + "\n");
// GET resources from req03 in order edit its values
getResponse = client.GetResource(req03URL,OslcMediaType.APPLICATION_RDF_XML);
requirement = getResponse.Content.ReadAsAsync<Requirement>(client.GetFormatters()).Result;
// Get the eTAG, we need it to update
String etag = getResponse.Headers.ETag.ToString();
getResponse.ConsumeContent();
requirement.SetTitle("My new Title");
requirement.AddImplementedBy(new Link(new Uri("http://google.com"), "Link created by an Eclipse Lyo user"));
// Update the requirement with the proper etag
HttpResponseMessage updateResponse = client.UpdateResource(req03URL,
requirement, OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);
updateResponse.ConsumeContent();
/*Do a query in order to see if the requirement have changed*/
// SCENARIO 07 Do a query for the new title just changed
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("dcterms=<http://purl.org/dc/terms/>");
queryParams.SetWhere("dcterms:title=\"My new Title\"");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 07 = " + resultsSize + "\n");
// SCENARIO 08 Do a query for implementedBy links
queryParams = new OslcQueryParameters();
queryParams.SetPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
queryParams.SetWhere("oslc_rm:implementedBy=<http://google.com>");
query = new OslcQuery(client, queryCapability, 10, queryParams);
result = query.Submit();
resultsSize = result.GetMembersUrls().Length;
processAsDotNetObjects = false;
ProcessPagedQueryResults(result,client, processAsDotNetObjects);
Console.WriteLine("\n------------------------------\n");
Console.WriteLine("Number of Results for SCENARIO 08 = " + resultsSize + "\n");
} catch (RootServicesException re) {
logger.Error("Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
} catch (Exception e) {
logger.Error(e.Message,e);
}
}
private static void ProcessPagedQueryResults(OslcQueryResult result, OslcClient client, bool asDotNetObjects) {
int page = 1;
//For now, just show first 5 pages
do {
Console.WriteLine("\nPage " + page + ":\n");
ProcessCurrentPage(result,client,asDotNetObjects);
if (result.MoveNext() && page < 5) {
result = result.Current;
page++;
} else {
break;
}
} while(true);
}
private static void ProcessCurrentPage(OslcQueryResult result, OslcClient client, bool asDotNetObjects) {
foreach (String resultsUrl in result.GetMembersUrls()) {
Console.WriteLine(resultsUrl);
HttpResponseMessage response = null;
try {
//Get a single artifact by its URL
response = client.GetResource(resultsUrl, OSLCConstants.CT_RDF);
if (response != null) {
//De-serialize it as a .NET object
if (asDotNetObjects) {
//Requirement req = response.getEntity(Requirement.class);
//printRequirementInfo(req); //print a few attributes
} else {
//Just print the raw RDF/XML (or process the XML as desired)
processRawResponse(response);
}
}
} catch (Exception e) {
logger.Error("Unable to process artfiact at url: " + resultsUrl, e);
}
}
}
private static void processRawResponse(HttpResponseMessage response)
{
Stream inStream = response.Content.ReadAsStreamAsync().Result;
StreamReader streamReader = new StreamReader(new BufferedStream(inStream), System.Text.Encoding.UTF8);
String line = null;
while ((line = streamReader.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.WriteLine();
response.ConsumeContent();
}
private static bool ValidateOptions(CommandLineDictionary cmd) {
bool isValid = true;
if (! (cmd.ContainsKey("url") &&
cmd.ContainsKey("user") &&
cmd.ContainsKey("password") &&
cmd.ContainsKey("project") &&
cmd.Count == 4))
{
isValid = false;
}
return isValid;
}
}
}
| 44.896471 | 154 | 0.670877 | [
"EPL-1.0"
] | OSLC/oslc4net | OSLC4Net_SDK/OSLC4Net.Client.Samples/RRCOAuthSample.cs | 19,083 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace VBSAdmin.Models.AccountViewModels
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
}
| 22.1875 | 52 | 0.698592 | [
"MIT"
] | nwbible/vbsadmin | VBSAdmin/src/VBSAdmin/Models/AccountViewModels/ExternalLoginConfirmationViewModel.cs | 357 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query
{
public class RelationalSqlTranslatingExpressionVisitor : ExpressionVisitor
{
private const string RuntimeParameterPrefix = QueryCompilationContext.QueryParameterPrefix + "entity_equality_";
private static readonly MethodInfo _parameterValueExtractor =
typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterValueExtractor));
private static readonly MethodInfo _parameterListValueExtractor =
typeof(RelationalSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ParameterListValueExtractor));
private readonly QueryCompilationContext _queryCompilationContext;
private readonly IModel _model;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly QueryableMethodTranslatingExpressionVisitor _queryableMethodTranslatingExpressionVisitor;
private readonly SqlTypeMappingVerifyingExpressionVisitor _sqlTypeMappingVerifyingExpressionVisitor;
public RelationalSqlTranslatingExpressionVisitor(
[NotNull] RelationalSqlTranslatingExpressionVisitorDependencies dependencies,
[NotNull] QueryCompilationContext queryCompilationContext,
[NotNull] QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor)
{
Check.NotNull(dependencies, nameof(dependencies));
Check.NotNull(queryCompilationContext, nameof(queryCompilationContext));
Check.NotNull(queryableMethodTranslatingExpressionVisitor, nameof(queryableMethodTranslatingExpressionVisitor));
Dependencies = dependencies;
_sqlExpressionFactory = dependencies.SqlExpressionFactory;
_queryCompilationContext = queryCompilationContext;
_model = queryCompilationContext.Model;
_queryableMethodTranslatingExpressionVisitor = queryableMethodTranslatingExpressionVisitor;
_sqlTypeMappingVerifyingExpressionVisitor = new SqlTypeMappingVerifyingExpressionVisitor();
}
protected virtual RelationalSqlTranslatingExpressionVisitorDependencies Dependencies { get; }
public virtual SqlExpression Translate([NotNull] Expression expression)
{
Check.NotNull(expression, nameof(expression));
var result = Visit(expression);
if (result is SqlExpression translation)
{
if (translation is SqlUnaryExpression sqlUnaryExpression
&& sqlUnaryExpression.OperatorType == ExpressionType.Convert
&& sqlUnaryExpression.Type == typeof(object))
{
translation = sqlUnaryExpression.Operand;
}
translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(translation);
if (translation.TypeMapping == null)
{
// The return type is not-mappable hence return null
return null;
}
_sqlTypeMappingVerifyingExpressionVisitor.Visit(translation);
return translation;
}
return null;
}
public virtual SqlExpression TranslateAverage([NotNull] Expression expression)
{
Check.NotNull(expression, nameof(expression));
if (!(expression is SqlExpression sqlExpression))
{
sqlExpression = Translate(expression);
}
if (sqlExpression == null)
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(expression.Print()));
}
var inputType = sqlExpression.Type.UnwrapNullableType();
if (inputType == typeof(int)
|| inputType == typeof(long))
{
sqlExpression = _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(sqlExpression, typeof(double)));
}
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
sqlExpression.Type,
sqlExpression.TypeMapping)
: (SqlExpression)_sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping);
}
public virtual SqlExpression TranslateCount([CanBeNull] Expression expression = null)
{
if (expression != null)
{
// TODO: Translate Count with predicate for GroupBy
return null;
}
return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { _sqlExpressionFactory.Fragment("*") },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(int)));
}
public virtual SqlExpression TranslateLongCount([CanBeNull] Expression expression = null)
{
if (expression != null)
{
// TODO: Translate Count with predicate for GroupBy
return null;
}
return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { _sqlExpressionFactory.Fragment("*") },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(long)));
}
public virtual SqlExpression TranslateMax([NotNull] Expression expression)
{
Check.NotNull(expression, nameof(expression));
if (!(expression is SqlExpression sqlExpression))
{
sqlExpression = Translate(expression);
}
return sqlExpression != null
? _sqlExpressionFactory.Function(
"MAX",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
}
public virtual SqlExpression TranslateMin([NotNull] Expression expression)
{
Check.NotNull(expression, nameof(expression));
if (!(expression is SqlExpression sqlExpression))
{
sqlExpression = Translate(expression);
}
return sqlExpression != null
? _sqlExpressionFactory.Function(
"MIN",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
}
public virtual SqlExpression TranslateSum([NotNull] Expression expression)
{
Check.NotNull(expression, nameof(expression));
if (!(expression is SqlExpression sqlExpression))
{
sqlExpression = Translate(expression);
}
if (sqlExpression == null)
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(expression.Print()));
}
var inputType = sqlExpression.Type.UnwrapNullableType();
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
inputType,
sqlExpression.TypeMapping)
: (SqlExpression)_sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
inputType,
sqlExpression.TypeMapping);
}
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
Check.NotNull(binaryExpression, nameof(binaryExpression));
if (binaryExpression.Left.Type == typeof(AnonymousObject)
&& binaryExpression.NodeType == ExpressionType.Equal)
{
return Visit(ConvertAnonymousObjectEqualityComparison(binaryExpression));
}
var left = TryRemoveImplicitConvert(binaryExpression.Left);
var right = TryRemoveImplicitConvert(binaryExpression.Right);
var visitedLeft = Visit(left);
var visitedRight = Visit(right);
if ((binaryExpression.NodeType == ExpressionType.Equal
|| binaryExpression.NodeType == ExpressionType.NotEqual)
// Visited expression could be null, We need to pass MemberInitExpression
&& TryRewriteEntityEquality(binaryExpression.NodeType, visitedLeft ?? left, visitedRight ?? right, out var result))
{
return result;
}
var uncheckedNodeTypeVariant = binaryExpression.NodeType switch
{
ExpressionType.AddChecked => ExpressionType.Add,
ExpressionType.SubtractChecked => ExpressionType.Subtract,
ExpressionType.MultiplyChecked => ExpressionType.Multiply,
_ => binaryExpression.NodeType
};
return TranslationFailed(binaryExpression.Left, visitedLeft, out var sqlLeft)
|| TranslationFailed(binaryExpression.Right, visitedRight, out var sqlRight)
? null
: uncheckedNodeTypeVariant == ExpressionType.Coalesce
? _sqlExpressionFactory.Coalesce(sqlLeft, sqlRight)
: (Expression)_sqlExpressionFactory.MakeBinary(
uncheckedNodeTypeVariant,
sqlLeft,
sqlRight,
null);
}
protected override Expression VisitConditional(ConditionalExpression conditionalExpression)
{
Check.NotNull(conditionalExpression, nameof(conditionalExpression));
var test = Visit(conditionalExpression.Test);
var ifTrue = Visit(conditionalExpression.IfTrue);
var ifFalse = Visit(conditionalExpression.IfFalse);
return TranslationFailed(conditionalExpression.Test, test, out var sqlTest)
|| TranslationFailed(conditionalExpression.IfTrue, ifTrue, out var sqlIfTrue)
|| TranslationFailed(conditionalExpression.IfFalse, ifFalse, out var sqlIfFalse)
? null
: _sqlExpressionFactory.Case(new[] { new CaseWhenClause(sqlTest, sqlIfTrue) }, sqlIfFalse);
}
protected override Expression VisitConstant(ConstantExpression constantExpression)
=> new SqlConstantExpression(Check.NotNull(constantExpression, nameof(constantExpression)), null);
protected override Expression VisitExtension(Expression extensionExpression)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
switch (extensionExpression)
{
case EntityProjectionExpression _:
case EntityReferenceExpression _:
case SqlExpression _:
return extensionExpression;
case EntityShaperExpression entityShaperExpression:
return new EntityReferenceExpression(entityShaperExpression);
case ProjectionBindingExpression projectionBindingExpression:
return projectionBindingExpression.ProjectionMember != null
? ((SelectExpression)projectionBindingExpression.QueryExpression)
.GetMappedProjection(projectionBindingExpression.ProjectionMember)
: null;
default:
return null;
}
}
protected override Expression VisitInvocation(InvocationExpression invocationExpression) => null;
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression) => null;
protected override Expression VisitListInit(ListInitExpression listInitExpression) => null;
protected override Expression VisitMember(MemberExpression memberExpression)
{
Check.NotNull(memberExpression, nameof(memberExpression));
var innerExpression = Visit(memberExpression.Expression);
return TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member))
?? (TranslationFailed(memberExpression.Expression, Visit(memberExpression.Expression), out var sqlInnerExpression)
? null
: Dependencies.MemberTranslatorProvider.Translate(sqlInnerExpression, memberExpression.Member, memberExpression.Type));
}
protected override Expression VisitMemberInit(MemberInitExpression memberInitExpression)
=> GetConstantOrNull(Check.NotNull(memberInitExpression, nameof(memberInitExpression)));
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Check.NotNull(methodCallExpression, nameof(methodCallExpression));
// EF.Property case
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var propertyName))
{
return TryBindMember(Visit(source), MemberIdentity.Create(propertyName))
?? throw new InvalidOperationException(CoreStrings.QueryUnableToTranslateEFProperty(methodCallExpression.Print()));
}
// EF Indexer property
if (methodCallExpression.TryGetIndexerArguments(_model, out source, out propertyName))
{
return TryBindMember(Visit(source), MemberIdentity.Create(propertyName));
}
// GroupBy Aggregate case
if (methodCallExpression.Object == null
&& methodCallExpression.Method.DeclaringType == typeof(Enumerable)
&& methodCallExpression.Arguments.Count > 0
&& methodCallExpression.Arguments[0] is GroupByShaperExpression groupByShaperExpression)
{
var translatedAggregate = methodCallExpression.Method.Name switch
{
nameof(Enumerable.Average) => TranslateAverage(GetSelectorOnGrouping(methodCallExpression, groupByShaperExpression)),
nameof(Enumerable.Count) => TranslateCount(GetPredicateOnGrouping(methodCallExpression, groupByShaperExpression)),
nameof(Enumerable.LongCount) => TranslateLongCount(GetPredicateOnGrouping(methodCallExpression, groupByShaperExpression)),
nameof(Enumerable.Max) => TranslateMax(GetSelectorOnGrouping(methodCallExpression, groupByShaperExpression)),
nameof(Enumerable.Min) => TranslateMin(GetSelectorOnGrouping(methodCallExpression, groupByShaperExpression)),
nameof(Enumerable.Sum) => TranslateSum(GetSelectorOnGrouping(methodCallExpression, groupByShaperExpression)),
_ => null
};
if (translatedAggregate == null)
{
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
return translatedAggregate;
}
// Subquery case
var subqueryTranslation = _queryableMethodTranslatingExpressionVisitor.TranslateSubquery(methodCallExpression);
if (subqueryTranslation != null)
{
static bool IsAggregateResultWithCustomShaper(MethodInfo method)
{
if (method.IsGenericMethod)
{
method = method.GetGenericMethodDefinition();
}
return QueryableMethods.IsAverageWithoutSelector(method)
|| QueryableMethods.IsAverageWithSelector(method)
|| method == QueryableMethods.MaxWithoutSelector
|| method == QueryableMethods.MaxWithSelector
|| method == QueryableMethods.MinWithoutSelector
|| method == QueryableMethods.MinWithSelector
|| QueryableMethods.IsSumWithoutSelector(method)
|| QueryableMethods.IsSumWithSelector(method);
}
if (subqueryTranslation.ResultCardinality == ResultCardinality.Enumerable)
{
return null;
}
if (subqueryTranslation.ShaperExpression is EntityShaperExpression entityShaperExpression)
{
return new EntityReferenceExpression(subqueryTranslation);
}
if (!(subqueryTranslation.ShaperExpression is ProjectionBindingExpression
|| IsAggregateResultWithCustomShaper(methodCallExpression.Method)))
{
return null;
}
var subquery = (SelectExpression)subqueryTranslation.QueryExpression;
subquery.ApplyProjection();
#pragma warning disable IDE0046 // Convert to conditional expression
if (subquery.Tables.Count == 0
#pragma warning restore IDE0046 // Convert to conditional expression
&& methodCallExpression.Method.IsGenericMethod
&& methodCallExpression.Method.GetGenericMethodDefinition() is MethodInfo genericMethod
&& (genericMethod == QueryableMethods.AnyWithoutPredicate
|| genericMethod == QueryableMethods.AnyWithPredicate
|| genericMethod == QueryableMethods.All
|| genericMethod == QueryableMethods.Contains))
{
return subquery.Projection[0].Expression;
}
return new ScalarSubqueryExpression(subquery);
}
SqlExpression sqlObject = null;
SqlExpression[] arguments;
var method = methodCallExpression.Method;
if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object != null
&& methodCallExpression.Arguments.Count == 1)
{
var left = Visit(methodCallExpression.Object);
var right = Visit(methodCallExpression.Arguments[0]);
if (TryRewriteEntityEquality(ExpressionType.Equal,
left ?? methodCallExpression.Object,
right ?? methodCallExpression.Arguments[0],
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
sqlObject = leftSql;
arguments = new SqlExpression[1] { rightSql };
}
else
{
return null;
}
}
else if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object == null
&& methodCallExpression.Arguments.Count == 2)
{
var left = Visit(methodCallExpression.Arguments[0]);
var right = Visit(methodCallExpression.Arguments[1]);
if (TryRewriteEntityEquality(ExpressionType.Equal,
left ?? methodCallExpression.Arguments[0],
right ?? methodCallExpression.Arguments[1],
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
arguments = new SqlExpression[2] { leftSql, rightSql };
}
else
{
return null;
}
}
else if (method.IsGenericMethod
&& method.GetGenericMethodDefinition().Equals(EnumerableMethods.Contains))
{
var enumerable = Visit(methodCallExpression.Arguments[0]);
var item = Visit(methodCallExpression.Arguments[1]);
if (TryRewriteContainsEntity(enumerable, item ?? methodCallExpression.Arguments[1], out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
arguments = new SqlExpression[2] { sqlEnumerable, sqlItem };
}
else
{
return null;
}
}
else if (methodCallExpression.Arguments.Count == 1
&& method.IsContainsMethod())
{
var enumerable = Visit(methodCallExpression.Object);
var item = Visit(methodCallExpression.Arguments[0]);
if (TryRewriteContainsEntity(enumerable, item ?? methodCallExpression.Arguments[0], out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
sqlObject = sqlEnumerable;
arguments = new SqlExpression[1] { sqlItem };
}
else
{
return null;
}
}
else
{
if (TranslationFailed(methodCallExpression.Object, Visit(methodCallExpression.Object), out sqlObject))
{
return null;
}
arguments = new SqlExpression[methodCallExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
var argument = methodCallExpression.Arguments[i];
if (TranslationFailed(argument, Visit(argument), out var sqlArgument))
{
return null;
}
arguments[i] = sqlArgument;
}
}
return Dependencies.MethodCallTranslatorProvider.Translate(_model, sqlObject, methodCallExpression.Method, arguments);
}
protected override Expression VisitNew(NewExpression newExpression)
=> GetConstantOrNull(Check.NotNull(newExpression, nameof(newExpression)));
protected override Expression VisitNewArray(NewArrayExpression newArrayExpression) => null;
protected override Expression VisitParameter(ParameterExpression parameterExpression)
=> new SqlParameterExpression(Check.NotNull(parameterExpression, nameof(parameterExpression)), null);
protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExpression)
{
Check.NotNull(typeBinaryExpression, nameof(typeBinaryExpression));
var innerExpression = Visit(typeBinaryExpression.Expression);
if (typeBinaryExpression.NodeType == ExpressionType.TypeIs
&& innerExpression is EntityReferenceExpression entityReferenceExpression)
{
var entityType = entityReferenceExpression.EntityType;
if (entityType.GetAllBaseTypesInclusive().Any(et => et.ClrType == typeBinaryExpression.TypeOperand))
{
return _sqlExpressionFactory.Constant(true);
}
var derivedType = entityType.GetDerivedTypes().SingleOrDefault(et => et.ClrType == typeBinaryExpression.TypeOperand);
if (derivedType != null)
{
var concreteEntityTypes = derivedType.GetConcreteDerivedTypesInclusive().ToList();
var discriminatorColumn = BindProperty(entityReferenceExpression, entityType.GetDiscriminatorProperty());
return concreteEntityTypes.Count == 1
? _sqlExpressionFactory.Equal(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue()))
: (Expression)_sqlExpressionFactory.In(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()),
negated: false);
}
return _sqlExpressionFactory.Constant(false);
}
return null;
}
protected override Expression VisitUnary(UnaryExpression unaryExpression)
{
Check.NotNull(unaryExpression, nameof(unaryExpression));
var operand = Visit(unaryExpression.Operand);
if (operand is EntityReferenceExpression entityReferenceExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked
|| unaryExpression.NodeType == ExpressionType.TypeAs))
{
return entityReferenceExpression.Convert(unaryExpression.Type);
}
if (TranslationFailed(unaryExpression.Operand, operand, out var sqlOperand))
{
return null;
}
switch (unaryExpression.NodeType)
{
case ExpressionType.Not:
return _sqlExpressionFactory.Not(sqlOperand);
case ExpressionType.Negate:
return _sqlExpressionFactory.Negate(sqlOperand);
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.TypeAs:
// Object convert needs to be converted to explicit cast when mismatching types
if (operand.Type.IsInterface
&& unaryExpression.Type.GetInterfaces().Any(e => e == operand.Type)
|| unaryExpression.Type.UnwrapNullableType() == operand.Type.UnwrapNullableType()
|| unaryExpression.Type.UnwrapNullableType() == typeof(Enum))
{
return sqlOperand;
}
// Introduce explicit cast only if the target type is mapped else we need to client eval
if (unaryExpression.Type == typeof(object)
|| _sqlExpressionFactory.FindMapping(unaryExpression.Type) != null)
{
sqlOperand = _sqlExpressionFactory.ApplyDefaultTypeMapping(sqlOperand);
return _sqlExpressionFactory.Convert(sqlOperand, unaryExpression.Type);
}
break;
case ExpressionType.Quote:
return operand;
}
return null;
}
private Expression TryBindMember(Expression source, MemberIdentity member)
{
if (!(source is EntityReferenceExpression entityReferenceExpression))
{
return null;
}
var entityType = entityReferenceExpression.EntityType;
var property = member.MemberInfo != null
? entityType.FindProperty(member.MemberInfo)
: entityType.FindProperty(member.Name);
return property != null ? BindProperty(entityReferenceExpression, property) : null;
}
private SqlExpression BindProperty(EntityReferenceExpression entityReferenceExpression, IProperty property)
{
if (entityReferenceExpression.ParameterEntity != null)
{
return ((EntityProjectionExpression)Visit(entityReferenceExpression.ParameterEntity.ValueBufferExpression)).BindProperty(property);
}
if (entityReferenceExpression.SubqueryEntity != null)
{
var entityShaper = (EntityShaperExpression)entityReferenceExpression.SubqueryEntity.ShaperExpression;
var innerProjection = ((EntityProjectionExpression)Visit(entityShaper.ValueBufferExpression)).BindProperty(property);
var subSelectExpression = (SelectExpression)entityReferenceExpression.SubqueryEntity.QueryExpression;
subSelectExpression.AddToProjection(innerProjection);
return new ScalarSubqueryExpression(subSelectExpression);
}
return null;
}
private static Expression GetSelectorOnGrouping(
MethodCallExpression methodCallExpression, GroupByShaperExpression groupByShaperExpression)
{
if (methodCallExpression.Arguments.Count == 1)
{
return groupByShaperExpression.ElementSelector;
}
if (methodCallExpression.Arguments.Count == 2)
{
var selectorLambda = methodCallExpression.Arguments[1].UnwrapLambdaFromQuote();
return ReplacingExpressionVisitor.Replace(
selectorLambda.Parameters[0],
groupByShaperExpression.ElementSelector,
selectorLambda.Body);
}
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
private static Expression GetPredicateOnGrouping(
MethodCallExpression methodCallExpression, GroupByShaperExpression groupByShaperExpression)
{
if (methodCallExpression.Arguments.Count == 1)
{
return null;
}
if (methodCallExpression.Arguments.Count == 2)
{
var selectorLambda = methodCallExpression.Arguments[1].UnwrapLambdaFromQuote();
return ReplacingExpressionVisitor.Replace(
selectorLambda.Parameters[0],
groupByShaperExpression.ElementSelector,
selectorLambda.Body);
}
throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
}
private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression)
{
if (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked)
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = unaryExpression.Type.UnwrapNullableType();
if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}
}
return expression;
}
private static Expression ConvertAnonymousObjectEqualityComparison(BinaryExpression binaryExpression)
{
var leftExpressions = ((NewArrayExpression)((NewExpression)binaryExpression.Left).Arguments[0]).Expressions;
var rightExpressions = ((NewArrayExpression)((NewExpression)binaryExpression.Right).Arguments[0]).Expressions;
return leftExpressions.Zip(
rightExpressions,
(l, r) =>
{
l = RemoveObjectConvert(l);
r = RemoveObjectConvert(r);
if (l.Type.IsNullableType())
{
r = r.Type.IsNullableType() ? r : Expression.Convert(r, l.Type);
}
else if (r.Type.IsNullableType())
{
l = l.Type.IsNullableType() ? l : Expression.Convert(l, r.Type);
}
return Expression.Equal(l, r);
})
.Aggregate((a, b) => Expression.AndAlso(a, b));
static Expression RemoveObjectConvert(Expression expression)
=> expression is UnaryExpression unaryExpression
&& expression.Type == typeof(object)
&& expression.NodeType == ExpressionType.Convert
? unaryExpression.Operand
: expression;
}
private static SqlConstantExpression GetConstantOrNull(Expression expression)
=> CanEvaluate(expression)
? new SqlConstantExpression(
Expression.Constant(
Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile().Invoke(),
expression.Type),
null)
: null;
private bool TryRewriteContainsEntity(Expression source, Expression item, out Expression result)
{
result = null;
if (!(item is EntityReferenceExpression itemEntityReference))
{
return false;
}
var entityType = itemEntityReference.EntityType;
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(entityType.DisplayName()));
}
if (primaryKeyProperties.Count > 1)
{
throw new InvalidOperationException(
CoreStrings.EntityEqualityContainsWithCompositeKeyNotSupported(entityType.DisplayName()));
}
var property = primaryKeyProperties[0];
Expression rewrittenSource;
switch (source)
{
case SqlConstantExpression sqlConstantExpression:
var values = (IEnumerable)sqlConstantExpression.Value;
var propertyValueList = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.ClrType.MakeNullable()));
var propertyGetter = property.GetGetter();
foreach (var value in values)
{
propertyValueList.Add(propertyGetter.GetClrValue(value));
}
rewrittenSource = Expression.Constant(propertyValueList);
break;
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterListValueExtractor.MakeGenericMethod(entityType.ClrType, property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter
);
var newParameterName =
$"{RuntimeParameterPrefix}" +
$"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}";
rewrittenSource = _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
break;
default:
return false;
}
result = Visit(Expression.Call(
EnumerableMethods.Contains.MakeGenericMethod(property.ClrType.MakeNullable()),
rewrittenSource,
CreatePropertyAccessExpression(item, property)));
return true;
}
private bool TryRewriteEntityEquality(ExpressionType nodeType, Expression left, Expression right, out Expression result)
{
var leftEntityReference = left as EntityReferenceExpression;
var rightEntityReference = right as EntityReferenceExpression;
if (leftEntityReference == null
&& rightEntityReference == null)
{
result = null;
return false;
}
if (IsNullSqlConstantExpression(left)
|| IsNullSqlConstantExpression(right))
{
var nonNullEntityReference = IsNullSqlConstantExpression(left) ? rightEntityReference : leftEntityReference;
var entityType1 = nonNullEntityReference.EntityType;
var primaryKeyProperties1 = entityType1.FindPrimaryKey()?.Properties;
if (primaryKeyProperties1 == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(entityType1.DisplayName()));
}
result = Visit(primaryKeyProperties1.Select(p =>
Expression.MakeBinary(
nodeType,
CreatePropertyAccessExpression(nonNullEntityReference, p),
Expression.Constant(null, p.ClrType.MakeNullable())))
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r)));
return true;
}
var leftEntityType = leftEntityReference?.EntityType;
var rightEntityType = rightEntityReference?.EntityType;
var entityType = leftEntityType ?? rightEntityType;
Debug.Assert(entityType != null, "At least either side should be entityReference so entityType should be non-null.");
if (leftEntityType != null
&& rightEntityType != null
&& leftEntityType.GetRootType() != rightEntityType.GetRootType())
{
result = _sqlExpressionFactory.Constant(false);
return true;
}
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(entityType.DisplayName()));
}
if (primaryKeyProperties.Count > 1
&& (leftEntityReference?.SubqueryEntity != null
|| rightEntityReference?.SubqueryEntity != null))
{
throw new InvalidOperationException(
CoreStrings.EntityEqualitySubqueryWithCompositeKeyNotSupported(entityType.DisplayName()));
}
result = Visit(primaryKeyProperties.Select(p =>
Expression.MakeBinary(
nodeType,
CreatePropertyAccessExpression(left, p),
CreatePropertyAccessExpression(right, p)))
.Aggregate((l, r) => Expression.AndAlso(l, r)));
return true;
}
private Expression CreatePropertyAccessExpression(Expression target, IProperty property)
{
switch (target)
{
case SqlConstantExpression sqlConstantExpression:
return Expression.Constant(
property.GetGetter().GetClrValue(sqlConstantExpression.Value), property.ClrType.MakeNullable());
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterValueExtractor.MakeGenericMethod(property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter);
var newParameterName =
$"{RuntimeParameterPrefix}" +
$"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}";
return _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
case MemberInitExpression memberInitExpression
when memberInitExpression.Bindings.SingleOrDefault(
mb => mb.Member.Name == property.Name) is MemberAssignment memberAssignment:
return memberAssignment.Expression;
default:
return target.CreateEFPropertyExpression(property);
}
}
private static T ParameterValueExtractor<T>(QueryContext context, string baseParameterName, IProperty property)
{
var baseParameter = context.ParameterValues[baseParameterName];
return baseParameter == null ? (T)(object)null : (T)property.GetGetter().GetClrValue(baseParameter);
}
private static List<TProperty> ParameterListValueExtractor<TEntity, TProperty>(
QueryContext context, string baseParameterName, IProperty property)
{
if (!(context.ParameterValues[baseParameterName] is IEnumerable<TEntity> baseListParameter))
{
return null;
}
var getter = property.GetGetter();
return baseListParameter.Select(e => e != null ? (TProperty)getter.GetClrValue(e) : (TProperty)(object)null).ToList();
}
private static bool CanEvaluate(Expression expression)
{
#pragma warning disable IDE0066 // Convert switch statement to expression
switch (expression)
#pragma warning restore IDE0066 // Convert switch statement to expression
{
case ConstantExpression constantExpression:
return true;
case NewExpression newExpression:
return newExpression.Arguments.All(e => CanEvaluate(e));
case MemberInitExpression memberInitExpression:
return CanEvaluate(memberInitExpression.NewExpression)
&& memberInitExpression.Bindings.All(
mb => mb is MemberAssignment memberAssignment && CanEvaluate(memberAssignment.Expression));
default:
return false;
}
}
private static bool IsNullSqlConstantExpression(Expression expression)
=> expression is SqlConstantExpression sqlConstant && sqlConstant.Value == null;
[DebuggerStepThrough]
private static bool TranslationFailed(Expression original, Expression translation, out SqlExpression castTranslation)
{
if (original != null
&& !(translation is SqlExpression))
{
castTranslation = null;
return true;
}
castTranslation = translation as SqlExpression;
return false;
}
private sealed class EntityReferenceExpression : Expression
{
public EntityReferenceExpression(EntityShaperExpression parameter)
{
ParameterEntity = parameter;
EntityType = parameter.EntityType;
}
public EntityReferenceExpression(ShapedQueryExpression subquery)
{
SubqueryEntity = subquery;
EntityType = ((EntityShaperExpression)subquery.ShaperExpression).EntityType;
}
private EntityReferenceExpression(EntityReferenceExpression entityReferenceExpression, IEntityType entityType)
{
ParameterEntity = entityReferenceExpression.ParameterEntity;
SubqueryEntity = entityReferenceExpression.SubqueryEntity;
EntityType = entityType;
}
public EntityShaperExpression ParameterEntity { get; }
public ShapedQueryExpression SubqueryEntity { get; }
public IEntityType EntityType { get; }
public override Type Type => EntityType.ClrType;
public override ExpressionType NodeType => ExpressionType.Extension;
public Expression Convert(Type type)
{
if (type == typeof(object) // Ignore object conversion
|| type.IsAssignableFrom(Type)) // Ignore casting to base type/interface
{
return this;
}
var derivedEntityType = EntityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type);
return derivedEntityType == null ? null : new EntityReferenceExpression(this, derivedEntityType);
}
}
private sealed class SqlTypeMappingVerifyingExpressionVisitor : ExpressionVisitor
{
protected override Expression VisitExtension(Expression extensionExpression)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
if (extensionExpression is SqlExpression sqlExpression
&& !(extensionExpression is SqlFragmentExpression)
&& !(extensionExpression is SqlFunctionExpression sqlFunctionExpression
&& sqlFunctionExpression.Type.IsQueryableType()))
{
if (sqlExpression.TypeMapping == null)
{
throw new InvalidOperationException(CoreStrings.NullTypeMappingInSqlTree);
}
}
return base.VisitExtension(extensionExpression);
}
}
}
}
| 44.175725 | 147 | 0.586385 | [
"Apache-2.0"
] | Sohra/efcore | src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs | 48,770 | C# |
using System;
using NUnit.Framework;
namespace WebGL.UnitTests
{
[TestFixture]
public class BadArgumentsTest : BaseTest
{
private class ValueThrows
{
public readonly dynamic Value;
public readonly bool Throws;
public ValueThrows(dynamic value, bool throws)
{
Value = value;
Throws = throws;
}
}
[Test(Description = "Tests calling WebGL APIs with wrong argument types")]
public void ShouldDoMagic()
{
var context = WebGLTestUtils.create3DContext(Canvas);
var program = WebGLTestUtils.loadStandardProgram(context);
var shader = WebGLTestUtils.loadStandardVertexShader(context);
Action<WebGLRenderingContext, uint, Action> shouldGenerateGLError = WebGLTestUtils.shouldGenerateGLError;
Assert.That(program != null, "Program Compiled");
Assert.That(shader != null, "Shader Compiled");
var loc = context.getUniformLocation(program, "u_modelViewProjMatrix");
Assert.That(loc != null, "getUniformLocation succeeded");
var arguments = new[]
{
new ValueThrows("foo", true),
new ValueThrows(0, true),
new ValueThrows(null, false)
};
Action<string> shouldBeEmptyString = (command) => Assert.That(command, Is.EqualTo(string.Empty));
for (var i = 0; i < arguments.Length; ++i)
{
Action<Func<object>, Func<object>> func;
Action<Func<object>, Func<object>> func2;
Action<Func<object>, Func<object>> func3;
if (arguments[i].Throws)
{
func = WebGLTestUtils.shouldThrow;
func2 = WebGLTestUtils.shouldThrow;
func3 = WebGLTestUtils.shouldThrow;
}
else
{
func = WebGLTestUtils.shouldBeUndefined;
func2 = WebGLTestUtils.shouldBeNull;
func3 = WebGLTestUtils.shouldBeEmptyString;
}
var argument = arguments[i].Value;
func(() => context.compileShader(argument), null);
func(() => context.linkProgram(argument), null);
func(() => context.attachShader(program, argument), null);
func(() => context.attachShader(argument, shader), null);
func(() => context.detachShader(program, argument), null);
func(() => context.detachShader(argument, shader), null);
func(() => context.useProgram(argument), null);
func(() => context.shaderSource(argument, "foo"), null);
func(() => context.bindAttribLocation(argument, 0, "foo"), null);
func(() => context.bindBuffer(context.ARRAY_BUFFER, argument), null);
func(() => context.bindFramebuffer(context.FRAMEBUFFER, argument), null);
func(() => context.bindRenderbuffer(context.RENDERBUFFER, argument), null);
func(() => context.bindTexture(context.TEXTURE_2D, argument), null);
func(() => context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, argument), null);
func(() => context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, argument, 0), null);
func(() => context.uniform2fv(argument, new Float32Array(new[] {0.0f, 0.0f})), null);
func(() => context.uniform2iv(argument, new Int32Array(new[] {0, 0})), null);
func(() => context.uniformMatrix2fv(argument, false, new Float32Array(new[] {0.0f, 0.0f, 0.0f, 0.0f})), null);
func2(() => context.getProgramParameter(argument, 0), null);
func2(() => context.getShaderParameter(argument, 0), null);
func2(() => context.getUniform(argument, loc), null);
func2(() => context.getUniform(program, argument), null);
func2(() => context.getUniformLocation(argument, "u_modelViewProjMatrix"), null);
func3(() => context.getProgramInfoLog(argument), null);
func3(() => context.getShaderInfoLog(argument), null);
func3(() => context.getShaderSource(argument), null);
}
}
}
} | 48.797872 | 145 | 0.555483 | [
"Apache-2.0"
] | jdarc/webgl.net | WebGL.UnitTests/conformance/v100/BadArgumentsTest.cs | 4,589 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vortex_Backup : Skill
{
[SerializeField]
private GameObject VortexZone;
//[SerializeField]
//private GameObject VortexZoneT;
//private GameObject Vortex_Temp;
[SerializeField]
private Transform SpawnPoint;
protected override void Effect()
{
GameObject Vortex = Instantiate(VortexZone, SpawnPoint.position, Player.transform.localRotation);
Vortex.GetComponent<VortexZone>().SetPlayer(Player);
}
public override void Play()
{
//Destroy(Vortex_Temp);
Avaliable = false;
HUD.WaitCD();
Effect();
}
public override void CountCD()
{
StartCoroutine("Count_CD");
}
IEnumerator Count_CD()
{
float ReturnTime = Time.time + CD;
float currentTime = 0;
while (ReturnTime >= Time.time)
{
currentTime = ReturnTime - Time.time;
HUD.setCD(currentTime, CD);
yield return new WaitForSeconds(Time.deltaTime);
}
HUD.setCD(0);
Avaliable = true;
yield return null;
}
public void Teste()
{
Vector3 Pos = Player.transform.position;
Pos.y += 3;
//Vortex_Temp = Instantiate(VortexZoneT, Pos, Quaternion.identity);
}
public override void Brinks()
{
return;
//Teste();
}
}
| 21.863636 | 105 | 0.602911 | [
"Apache-2.0"
] | bruno-pLima/PandoraPlayers | Players/Angie/Skills/Vortex_Backup.cs | 1,445 | C# |
namespace SpeedyCdn.Enums
{
//
public enum CacheElementType
{
Image,
Static
}
public enum Gravity
{
None,
NorthWest,
North,
NorthEast,
West,
Center,
East,
SouthWest,
South,
SouthEast
}
public enum BorderPlacement
{
Extend,
Overlay
}
}
| 12.612903 | 32 | 0.457801 | [
"Apache-2.0"
] | brianmed/SpeedyCdn | Enums.cs | 391 | C# |
#pragma warning disable IDE1006 // Naming Styles
using MonoMod.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace MonoMod.RuntimeDetour.Platforms {
#if !MONOMOD_INTERNAL
public
#endif
unsafe class DetourNativeMonoPlatform : IDetourNativePlatform {
private readonly IDetourNativePlatform Inner;
private readonly long _Pagesize;
public DetourNativeMonoPlatform(IDetourNativePlatform inner, string libmono) {
Inner = inner;
Dictionary<string, List<DynDllMapping>> mappings = new Dictionary<string, List<DynDllMapping>>();
if (!string.IsNullOrEmpty(libmono))
mappings.Add("mono", new List<DynDllMapping>() { libmono });
DynDll.ResolveDynDllImports(this, mappings);
_Pagesize = mono_pagesize();
}
private unsafe void SetMemPerms(IntPtr start, ulong len, MmapProts prot) {
long pagesize = _Pagesize;
long startPage = ((long) start) & ~(pagesize - 1);
long endPage = ((long) start + (long) len + pagesize - 1) & ~(pagesize - 1);
if (mono_mprotect((IntPtr) startPage, (IntPtr) (endPage - startPage), (int) prot) != 0) {
int error = Marshal.GetLastWin32Error();
if (error == 0) {
// This can happen on some Android devices.
// Let's hope for the best.
} else {
throw new Win32Exception();
}
}
}
public void MakeWritable(IntPtr src, uint size) {
// RWX because old versions of mono always use RWX.
SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
}
public void MakeExecutable(IntPtr src, uint size) {
// RWX because old versions of mono always use RWX.
SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
}
public void FlushICache(IntPtr src, uint size) {
// mono_arch_flush_icache isn't reliably exported.
Inner.FlushICache(src, size);
}
public NativeDetourData Create(IntPtr from, IntPtr to, byte? type) {
return Inner.Create(from, to, type);
}
public void Free(NativeDetourData detour) {
Inner.Free(detour);
}
public void Apply(NativeDetourData detour) {
Inner.Apply(detour);
}
public void Copy(IntPtr src, IntPtr dst, byte type) {
Inner.Copy(src, dst, type);
}
public IntPtr MemAlloc(uint size) {
return Inner.MemAlloc(size);
}
public void MemFree(IntPtr ptr) {
Inner.MemFree(ptr);
}
#pragma warning disable IDE0044 // Add readonly modifier
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value null
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int d_mono_pagesize();
[DynDllImport("mono")]
private d_mono_pagesize mono_pagesize;
[UnmanagedFunctionPointer(CallingConvention.Cdecl, SetLastError = true)]
private delegate int d_mono_mprotect(IntPtr addr, IntPtr length, int flags);
[DynDllImport("mono")]
private d_mono_mprotect mono_mprotect;
#pragma warning restore IDE0044 // Add readonly modifier
#pragma warning restore CS0649 // Field is never assigned to, and will always have its default value null
[Flags]
private enum MmapProts : int {
PROT_READ = 0x1,
PROT_WRITE = 0x2,
PROT_EXEC = 0x4,
PROT_NONE = 0x0,
PROT_GROWSDOWN = 0x01000000,
PROT_GROWSUP = 0x02000000,
}
}
}
| 34.75 | 109 | 0.616136 | [
"MIT"
] | abrenneke/MonoMod.Common | RuntimeDetour/Platforms/Native/DetourNativeMonoPlatform.cs | 3,894 | C# |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.core
{
/// <summary>
/// <para>Defines the callback for the single selection manager.</para>
/// </summary>
public interface ISingleSelectionProvider
{
#region Methods
/// <summary>
/// <para>Returns the elements which are part of the selection.</para>
/// </summary>
/// <returns>The widgets for the selection.</returns>
qx.ui.core.Widget GetItems();
/// <summary>
/// <para>Returns whether the given item is selectable.</para>
/// </summary>
/// <param name="item">The item to be checked</param>
/// <returns>Whether the given item is selectable</returns>
bool IsItemSelectable(qx.ui.core.Widget item);
#endregion Methods
}
} | 26.677419 | 72 | 0.694075 | [
"MIT"
] | SharpKit/SharpKit-SDK | Defs/Qooxdoo/ui/core/ISingleSelectionProvider.cs | 827 | C# |
using System;
namespace Panosen.Time
{
/// <summary>
/// 时间转换器
/// </summary>
public static class TimeConvert
{
/// <summary>
/// 基准时间
/// </summary>
public static readonly DateTime TimeBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// 转换为秒需要用到的
/// </summary>
private const int SecondBase = 10000_000;
/// <summary>
/// 转换为毫秒需要用到的
/// </summary>
private const int MillsSecondBase = 10000;
/// <summary>
/// 将秒数转换为时间
/// </summary>
/// <param name="ticks">从1970年1月1日00:00:00至起用时间的秒数</param>
/// <returns>转换后的时间</returns>
public static DateTimeOffset FromTicks(long ticks)
{
return new DateTime(TimeBase.Ticks + ticks * SecondBase, DateTimeKind.Utc).ToLocalTime();
}
/// <summary>
/// 将时间转换为秒数
/// </summary>
/// <param name="time">需要转换的时间</param>
/// <returns>从1970年1月1日00:00:00至起用时间的秒数</returns>
public static long ToTicks(DateTimeOffset time)
{
return (time.ToUniversalTime() - TimeBase).Ticks / SecondBase;
}
/// <summary>
/// 将毫秒数转换为时间
/// </summary>
/// <param name="millsTicks">从1970年1月1日00:00:00至起用时间的毫秒数</param>
/// <returns>转换后的时间</returns>
public static DateTimeOffset FromMilliTicks(long millsTicks)
{
return new DateTime(TimeBase.Ticks + millsTicks * MillsSecondBase, DateTimeKind.Utc).ToLocalTime();
}
/// <summary>
/// 将时间转换为毫秒数
/// </summary>
/// <param name="time">需要转换的时间</param>
/// <returns>从1970年1月1日00:00:00至起用时间的毫秒数</returns>
public static long ToMilliTicks(DateTimeOffset time)
{
return (time.ToUniversalTime() - TimeBase).Ticks / MillsSecondBase;
}
}
}
| 28.925373 | 111 | 0.552116 | [
"MIT"
] | panosen/panosen-time | Panosen.Time/TimeConvert.cs | 2,216 | C# |
using Abp.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace TalentMatrix.Org
{
public class Student: Entity<int>
{
public string Name { get; set; }
/// <summary>
/// 学生所在的学校
/// </summary>
public School School { get; set; }
}
}
| 19.176471 | 42 | 0.59816 | [
"MIT"
] | benjamin0809/abp-marvelous | aspnet-core/src/TalentMatrix.Core/Org/Student.cs | 342 | C# |
namespace Krillin.App.Models
{
using System.Xml.Serialization;
[XmlRoot(ElementName = "guid")]
public class Guid
{
[XmlAttribute(AttributeName = "isPermaLink")]
public string IsPermaLink { get; set; }
[XmlText]
public string Text { get; set; }
}
}
| 22.5 | 54 | 0.580952 | [
"Apache-2.0"
] | marcoablanco/GS.Reader.Rss | Krillin/Krillin.App/Krillin.App/Krillin.App/Models/Guid.cs | 317 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshBuilder {
private List<Vector3> m_Vertices = new List<Vector3>();
public List<Vector3> Vertices { get { return m_Vertices; }}
private List<Vector3> m_Normals = new List<Vector3>();
public List<Vector3> Normals { get { return m_Normals; }}
private List<Vector2> m_UVs = new List<Vector2>();
public List<Vector2> UVs { get { return m_UVs; }}
private List<Vector4> m_Tangents = new List<Vector4>();
public List<Vector4> Tangents { get { return m_Tangents; }}
private List<int> m_Indices = new List<int>();
public int[] GetTriangles()
{
return m_Indices.ToArray();
}
public void ReplaceTriangleIndex(int tindex, int indexValue)
{
m_Indices[tindex] = indexValue;
}
public void ClearTriangles()
{
m_Indices.Clear();
}
public void AddTriangle(int index0, int index1, int index2)
{
m_Indices.Add (index0);
m_Indices.Add (index1);
m_Indices.Add (index2);
}
public Mesh CreateMesh()
{
Mesh mesh = new Mesh ();
mesh.vertices = m_Vertices.ToArray ();
mesh.triangles = m_Indices.ToArray ();
// Normals sao opcionais
if (m_Normals.Count == m_Vertices.Count) {
mesh.normals = m_Normals.ToArray();
}
// UVs sao opcionais
if (m_UVs.Count == m_Vertices.Count) {
mesh.uv = m_UVs.ToArray();
}
// Tangents sao opcionais
if (m_Tangents.Count == m_Vertices.Count) {
mesh.tangents = m_Tangents.ToArray();
}
mesh.RecalculateBounds ();
return mesh;
}
}
| 21.338028 | 61 | 0.693069 | [
"MIT"
] | adrianogil/VR360QualityTool | unity/VR360QualityTool/Assets/Scripts/MeshBuilder.cs | 1,517 | C# |
using System.Collections.Generic;
namespace RecipeBox.Models
{
public class Recipe
{
public Recipe()
{
this.JoinEntities = new HashSet<RecipeTag>();
}
public int RecipeId { get; set; }
public string Name { get; set; }
public string Ingredients { get; set; }
public string Instructions { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ICollection<RecipeTag> JoinEntities { get; set; }
}
} | 25.888889 | 68 | 0.665236 | [
"MIT"
] | Patrick-Dolan/recipe-box | RecipeBox/Models/Recipe.cs | 466 | C# |
/*
* Copyright © 2018 Federation of State Medical Boards
* All Rights Reserved
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FluentAssertions;
using P3Net.Kraken.Data.Sql;
using P3Net.Kraken.UnitTesting;
namespace Tests.P3Net.Kraken.Data.Sql
{
[TestClass]
public class SqlConnectionManagerTests : UnitTest
{
#region Ctor
[TestMethod]
public void Ctor_Default ()
{
var target = new SqlConnectionManager();
target.ConnectionString.Should().BeEmpty();
}
#pragma warning disable 618
[TestMethod]
public void Ctor_WithConnectionStringWorks ()
{
var expectedString = "Server=server1;Database=DB1";
var target = new SqlConnectionManager(expectedString);
target.ConnectionString.Should().Be(expectedString);
}
[TestMethod]
public void Ctor_WithConnectionStringNullFails ()
{
Action a = () => new SqlConnectionManager(null);
a.Should().Throw<ArgumentNullException>();
}
[TestMethod]
public void Ctor_WithConnectionStringEmptyFails ()
{
Action a = () => new SqlConnectionManager("");
a.Should().Throw<ArgumentException>();
}
#pragma warning disable 618
#endregion
#region FormatParameterName
[TestMethod]
public void FormatParameterName_NotAlreadyFormatted ()
{
var name = "FirstName";
var expected = $"@{name}";
var target = new TestSqlConnectionManager();
var actual = target.GetParameterName(name);
actual.Should().Be(expected);
}
[TestMethod]
public void FormatParameterName_AlreadyFormatted ()
{
var name = "@FirstName";
var expected = name;
var target = new TestSqlConnectionManager();
var actual = target.GetParameterName(name);
actual.Should().Be(expected);
}
#endregion
#region Private Members
private sealed class TestSqlConnectionManager : SqlConnectionManager
{
public TestSqlConnectionManager () : base(@"Server=localhost;Database=Master")
{ }
public string GetParameterName ( string originalName ) => FormatParameterName(originalName);
}
#endregion
}
}
| 25.329897 | 104 | 0.602768 | [
"MIT"
] | CoolDadTx/Kraken | Tests/Tests.P3Net.Kraken.Data/Sql/SqlConnectionManagerTests.cs | 2,460 | C# |
using HarmonyLib;
using Psychology;
using UnityEngine;
using Verse;
namespace Gradual_Romance.Harmony
{
[HarmonyPatch(typeof(Pawn_SexualityTracker))]
[HarmonyPatch("AdjustedSexDrive", MethodType.Getter)]
public class AdjustedSexDrive_GRPatch
{
[HarmonyPostfix]
public static void GRXenoSexDrive(ref float __result, ref Pawn_SexualityTracker __instance, ref Pawn ___pawn)
{
var curve = GradualRomanceMod.GetSexDriveCurveFor(___pawn);
if (curve == null)
{
return;
}
__result = curve.Evaluate(___pawn.ageTracker.AgeBiologicalYearsFloat) *
Mathf.InverseLerp(0f, 0.5f, __instance.sexDrive);
__result = ___pawn.def.GetModExtension<XenoRomanceExtension>().canGoIntoHeat == false
? Mathf.Clamp01(__result)
: Mathf.Min(__result, 0f);
}
}
}
/*
*
*
* if(PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Realistic)
{
return Mathf.Clamp((int)Rand.GaussianAsymmetric(0f, 1f, 3.13f), 0, 6);
}
else if (PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Invisible)
{
return Mathf.Clamp((int)Rand.GaussianAsymmetric(3.5f, 1.7f, 1.7f), 0, 6);
}
else if (PsychologyBase.KinseyFormula() == PsychologyBase.KinseyMode.Gaypocalypse)
{
return Mathf.Clamp((int)Rand.GaussianAsymmetric(7f, 3.13f, 1f), 0, 6);
}
*
*
* public float AdjustedSexDrive
{
get
{
float ageFactor = 1f;
if (pawn.gender == Gender.Male) {
ageFactor = MaleSexDriveCurve.Evaluate(pawn.ageTracker.AgeBiologicalYears);
}
else if (pawn.gender == Gender.Female)
{
ageFactor = FemaleSexDriveCurve.Evaluate(pawn.ageTracker.AgeBiologicalYears);
}
return Mathf.Clamp01(ageFactor * Mathf.InverseLerp(0f, 0.5f, this.sexDrive));
}
}
*
*
*/ | 34.076923 | 117 | 0.555756 | [
"MIT"
] | emipa606/GradualRomance | Source/Gradual Romance/AdjustedSexDrive_GRPatch.cs | 2,217 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace EcCoach.Web.Migrations
{
public partial class AdminFieldToUser : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsAdmin",
table: "AspNetUsers",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsAdmin",
table: "AspNetUsers");
}
}
}
| 26.541667 | 71 | 0.574568 | [
"MIT"
] | FernandaCalzado/BecomingDotNetDevUASD | EventsCoach/EcCoach.Web/Migrations/20210207050120_AdminFieldToUser.cs | 639 | C# |
using Util.Helpers;
using Util.Ui.Builders;
using Util.Ui.Configs;
namespace Util.Ui.Material.Tabs.Builders {
/// <summary>
/// Material链接选项卡生成器
/// </summary>
public class TabLinkBuilder : TagBuilder {
/// <summary>
/// 初始化链接选项卡生成器
/// </summary>
public TabLinkBuilder() : base( "a" ) {
AddAttribute( "mat-tab-link" ).AddAttribute( "routerLinkActive" );
}
/// <summary>
/// 配置路由链接
/// </summary>
/// <param name="config">配置</param>
public void ConfigRouterLink( IConfig config ) {
var id = config.GetValue( UiConst.Id );
if( string.IsNullOrWhiteSpace( id ) )
id = $"{Id.Guid()}";
id = $"m_{id}";
AddAttribute( $"#{id}", "routerLinkActive" );
AddAttribute( "[active]", $"{id}.isActive" );
}
}
} | 29.766667 | 78 | 0.517357 | [
"MIT"
] | 12321/Util | src/Util.Ui.Angular.Material/Material/Tabs/Builders/TabLinkBuilder.cs | 949 | C# |
using System;
namespace Pushpay.DynamoDbProvisioner
{
[AttributeUsage(AttributeTargets.Property)]
public class DynamoDBTimeToLiveAttribute : Attribute { }
}
| 20.125 | 57 | 0.813665 | [
"MIT"
] | hzawawi/dynamodb-provisioner | Pushpay.DynamoDbProvisioner/DynamoDBTimeToLiveAttribute.cs | 163 | C# |
#if PLY_GAME
using plyBloxKit;
namespace Devdog.InventoryPro.Integration.plyGame.plyBlox
{
[plyBlock("Inventory Pro", "Items", "Open/Close treasure chest", BlockType.Action, Description = "Open or close a treasure chest.")]
public class OpenCloseTreasureChest : plyBlock
{
[plyBlockField("Treasure chest", ShowName = true, ShowValue = true, DefaultObject = typeof(LootableObject), EmptyValueName = "-error-", SubName = "Treasure chest", Description = "The chest you wish to open / close")]
public LootableObject chest;
[plyBlockField("Chest action", ShowName = true, ShowValue = true, DefaultObject = typeof(Bool_Value), SubName = "Action", Description = "Open or close the chest?")]
public Bool_Value action;
public override void Created()
{
blockIsValid = chest != null;
}
public override BlockReturn Run(BlockReturn param)
{
if (action.value)
chest.trigger.Use();
else
chest.trigger.UnUse();
return BlockReturn.OK;
}
}
}
#endif | 33.757576 | 224 | 0.63465 | [
"MIT"
] | PotentialGames/Cal-tEspa-l | BRGAME/Assets/Devdog/InventoryPro/Scripts/Integration/plyGame/plyBlox/OpenCloseTreasureChest.cs | 1,116 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wave : MonoBehaviour {
[SerializeField]
private Player player;
[SerializeField]
private WaveComponent[] waveComponents;
[SerializeField] private string waveText;
private float timeElapsed = 0f;
private Enemy[] spawnedEnemies;
private bool isWaveDone = false;
public bool IsWaveDone { get { return this.isWaveDone;}}
public string WaveText { get { return this.waveText; } }
// Use this for initialization
void Start () {
this.spawnedEnemies = new Enemy[this.waveComponents.Length];
}
// Update is called once per frame
void Update () {
if (isWaveDone) { return; }
if(waveComponents != null)
{
this.timeElapsed += Time.deltaTime;
TrySpawnWaveComponents();
}else
{
CheckIfWaveEnded();
}
}
private void CheckIfWaveEnded()
{
bool allDestroyed = true;
foreach (Enemy enemy in spawnedEnemies)
{
if(enemy != null)
{
allDestroyed = false;
}
}
if (allDestroyed)
{
isWaveDone = true;
}
}
private void TrySpawnWaveComponents()
{
bool thingsLeftToSpawn = false;
for (int i = 0; i < waveComponents.Length; i++)
{
WaveComponent waveComponent = waveComponents[i];
if (waveComponent != null)
{
thingsLeftToSpawn = true;
if (timeElapsed > waveComponent.DelaySeconds)
{
spawnedEnemies[i] = waveComponent.SpawnEnemy(player);
waveComponents[i] = null;
}
}
}
if (!thingsLeftToSpawn)
{
waveComponents = null;
}
}
}
| 24.050633 | 73 | 0.548947 | [
"MIT"
] | lukehb/ld37 | Assets/Scripts/Wave.cs | 1,902 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace mainForm
{
using System;
using System.Collections.Generic;
public partial class EmployeeCategory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public EmployeeCategory()
{
this.Employees = new HashSet<Employee>();
}
public string EmployeeCat { get; set; }
public string JobTitle { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employee> Employees { get; set; }
}
}
| 36.5 | 128 | 0.582648 | [
"Unlicense"
] | brlala/Library-Management-System | mainForm/EmployeeCategory.cs | 1,095 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
namespace FinalInferno{
public class TriggerSceneChange : Triggerable
{
//TO DO: Usar a struct SceneWarp aqui e atualizar o script de editor para refletir isso
[SerializeField] private string sceneName = "Battle";
[SerializeField] private Vector2 positionOnLoad = new Vector2(0,0);
[SerializeField] private bool isCutscene = false;
[SerializeField] private List<DialogueEntry> dialogues = new List<DialogueEntry>();
[SerializeField] private FinalInferno.UI.FSM.ButtonClickDecision decision;
protected override void TriggerAction(Fog.Dialogue.Agent agent){
if(sceneName != null && sceneName != ""){
CharacterOW.PartyCanMove = false;
Fog.Dialogue.Dialogue selectedDialogue = null;
if(isCutscene){
foreach(DialogueEntry entry in dialogues){
//Debug.Log("Checking dialogue: " + entry.dialogue + " with quest " + entry.quest + " and event " + entry.eventFlag);
if(entry.quest.GetFlag(entry.eventFlag)){
selectedDialogue = entry.dialogue;
}else{
//Debug.Log("Event " + entry.eventFlag + " deu false");
break;
}
}
}
//Debug.Log("Loading scene: " + sceneName + "; dialogue = " + selectedDialogue);
FinalInferno.UI.ChangeSceneUI.sceneName = sceneName;
FinalInferno.UI.ChangeSceneUI.positionOnLoad = positionOnLoad;
FinalInferno.UI.ChangeSceneUI.isCutscene = isCutscene;
FinalInferno.UI.ChangeSceneUI.selectedDialogue = selectedDialogue;
decision.Click();
}
}
}
#if UNITY_EDITOR
// PropertyDrawer necessario para exibir e editar QuestEvent no editor da unity
[CustomEditor(typeof(TriggerSceneChange))]
public class TriggerSceneChangeEditor : Editor{
SerializedProperty sceneName;
Object sceneObj;
public void OnEnable(){
sceneName = serializedObject.FindProperty("sceneName");
//Debug.Log("Procurando " + sceneName.stringValue + "...");
string[] objectsFound = AssetDatabase.FindAssets(sceneName.stringValue + " t:sceneAsset", new[] {"Assets/Scenes"});
if(sceneName.stringValue != "" && objectsFound != null && objectsFound.Length > 0 && objectsFound[0] != null && objectsFound[0] != ""){
sceneObj = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(objectsFound[0]), typeof(Object));
}else{
//Debug.Log("Não achou");
sceneObj = null;
}
}
public override void OnInspectorGUI(){
serializedObject.Update();
sceneObj = EditorGUILayout.ObjectField(sceneObj, typeof(SceneAsset), false);
if(sceneObj != null)
sceneName.stringValue = sceneObj.name;
else
sceneName.stringValue = "";
if(sceneObj != null){
SerializedProperty positionOnLoad = serializedObject.FindProperty("positionOnLoad");
SerializedProperty isCutscene = serializedObject.FindProperty("isCutscene");
SerializedProperty decision = serializedObject.FindProperty("decision");
EditorGUILayout.PropertyField(positionOnLoad);
EditorGUILayout.PropertyField(isCutscene);
EditorGUILayout.PropertyField(decision);
if(isCutscene.boolValue){
SerializedProperty dialogues = serializedObject.FindProperty("dialogues");
EditorGUILayout.PropertyField(dialogues, includeChildren:true);
}
}
serializedObject.ApplyModifiedProperties();
}
}
#endif
}
| 46.033708 | 147 | 0.600683 | [
"MIT"
] | FellowshipOfTheGame/FinalInferno | Assets/Scripts/Overworld/TriggerSceneChange.cs | 4,100 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Anonymous_Vox
{
class Program
{
static void Main(string[] args)
{
string pattern = @"([a-zA-Z]+)(.+)\1";
string text = Console.ReadLine();
string[] values = Console.ReadLine().Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries);
var result = new StringBuilder();
int counter = 0;
int index = 0;
string lastAdded = String.Empty;
int lastLength = 0;
while (counter < values.Length && index < text.Length)
{
Match match = Regex.Match(text.Substring(index), pattern);
if (!match.Success)
{
break;
}
result.Append(text.Substring(index, match.Groups[2].Index));
result.Append(values[counter]);
result.Append(match.Groups[1].Value);
lastAdded = match.Groups[1].Value;
lastLength = match.Groups[1].Length;
index += match.Groups[1].Index - index;
index += match.Groups[1].Value.Length * 2 + match.Groups[2].Length;
counter++;
}
int indexLast = text.LastIndexOf(lastAdded);
string remaining = text.Substring(indexLast + lastLength);
result.Append(remaining);
Console.WriteLine(result);
}
}
} | 36.348837 | 119 | 0.53039 | [
"MIT"
] | KristiyanSevov/SoftUni-Programming-Fundamentals | Exam 05.11.2017/Anonymous Vox/Anonymous Vox.cs | 1,565 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан по шаблону.
//
// Изменения, вносимые в этот файл вручную, могут привести к непредвиденной работе приложения.
// Изменения, вносимые в этот файл вручную, будут перезаписаны при повторном создании кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ServiceStation.Model
{
using System;
using System.Collections.Generic;
public partial class ContactPersonModel
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ContactPersonModel()
{
this.PowerOfAttorney = new HashSet<PowerOfAttorneyModel>();
}
public System.Guid ID { get; set; }
public string FFP { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Additionally { get; set; }
public System.Guid ID_сontractor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PowerOfAttorneyModel> PowerOfAttorney { get; set; }
public virtual ContractorModel Contractor { get; set; }
}
}
| 40.194444 | 128 | 0.601935 | [
"MIT"
] | Scronullik/ServiceStation | ServiceStation/ServiceStation/Model/ContactPersonModel.cs | 1,621 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.