source
stringclasses 1
value | id
stringlengths 40
40
| language
stringclasses 2
values | date
stringclasses 1
value | author
stringclasses 1
value | url
stringclasses 1
value | title
stringclasses 1
value | extra
stringlengths 528
1.53k
| quality_signals
stringlengths 139
178
| text
stringlengths 6
1.05M
|
---|---|---|---|---|---|---|---|---|---|
TheStack | bdb0a3a16ada26fb7e82362601a08f6352c24589 | C#code:C# | {"size": 30745, "ext": "cs", "max_stars_repo_path": "Source/DotSpatial.Symbology.Forms/FeatureCategoryControl.Designer.cs", "max_stars_repo_name": "CGX-GROUP/DotSpatial", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/DotSpatial.Symbology.Forms/FeatureCategoryControl.Designer.cs", "max_issues_repo_name": "CGX-GROUP/DotSpatial", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/DotSpatial.Symbology.Forms/FeatureCategoryControl.Designer.cs", "max_forks_repo_name": "CGX-GROUP/DotSpatial", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 52.1101694915, "max_line_length": 180, "alphanum_fraction": 0.6187672792} | using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
partial class FeatureCategoryControl
{
private IContainer components = null;
/// <summary>
/// Handles disposing unmanaged memory
/// </summary>
/// <param name="disposing">The disposed item</param>
protected override void Dispose(bool disposing)
{
breakSliderGraph1.Dispose();
if (components != null && disposing)
{
foreach (var id in components.Components.OfType<IDisposable>())
{
id.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FeatureCategoryControl));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this._cmbField = new System.Windows.Forms.ComboBox();
this._lblFieldName = new System.Windows.Forms.Label();
this.ttHelp = new System.Windows.Forms.ToolTip(this.components);
this.btnRamp = new System.Windows.Forms.Button();
this.cmdRefresh = new System.Windows.Forms.Button();
this.btnExclude = new System.Windows.Forms.Button();
this.radUniqueValues = new System.Windows.Forms.RadioButton();
this.radQuantities = new System.Windows.Forms.RadioButton();
this.btnAdd = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnUp = new System.Windows.Forms.Button();
this.btnDown = new System.Windows.Forms.Button();
this.cmbNormField = new System.Windows.Forms.ComboBox();
this.nudSigFig = new System.Windows.Forms.NumericUpDown();
this.cmbIntervalSnapping = new System.Windows.Forms.ComboBox();
this.dgvStatistics = new System.Windows.Forms.DataGridView();
this.Stat = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Value = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.tabScheme = new System.Windows.Forms.TabControl();
this.tabStatistics = new System.Windows.Forms.TabPage();
this.label3 = new System.Windows.Forms.Label();
this.lblSigFig = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.cmbInterval = new System.Windows.Forms.ComboBox();
this.nudCategoryCount = new System.Windows.Forms.NumericUpDown();
this.lblBreaks = new System.Windows.Forms.Label();
this.tabGraph = new System.Windows.Forms.TabPage();
this.lblColumns = new System.Windows.Forms.Label();
this.nudColumns = new System.Windows.Forms.NumericUpDown();
this.chkLog = new System.Windows.Forms.CheckBox();
this.chkShowStd = new System.Windows.Forms.CheckBox();
this.chkShowMean = new System.Windows.Forms.CheckBox();
this.breakSliderGraph1 = new DotSpatial.Symbology.Forms.BreakSliderGraph();
this.chkUseGradients = new System.Windows.Forms.CheckBox();
this.dgvCategories = new System.Windows.Forms.DataGridView();
this.colSymbol = new System.Windows.Forms.DataGridViewImageColumn();
this.colValues = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colLegendText = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colCount = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.radCustom = new System.Windows.Forms.RadioButton();
this.angGradientAngle = new DotSpatial.Symbology.Forms.AngleControl();
this.featureSizeRangeControl1 = new DotSpatial.Symbology.Forms.FeatureSizeRangeControl();
this.tccColorRange = new DotSpatial.Symbology.Forms.TabColorControl();
this.dataGridViewImageColumn1 = new System.Windows.Forms.DataGridViewImageColumn();
((System.ComponentModel.ISupportInitialize)(this.nudSigFig)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgvStatistics)).BeginInit();
this.tabScheme.SuspendLayout();
this.tabStatistics.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudCategoryCount)).BeginInit();
this.tabGraph.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudColumns)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgvCategories)).BeginInit();
this.SuspendLayout();
//
// _cmbField
//
this._cmbField.FormattingEnabled = true;
resources.ApplyResources(this._cmbField, "_cmbField");
this._cmbField.Name = "_cmbField";
this._cmbField.SelectedIndexChanged += new System.EventHandler(this.CmbFieldSelectedIndexChanged);
//
// _lblFieldName
//
resources.ApplyResources(this._lblFieldName, "_lblFieldName");
this._lblFieldName.Name = "_lblFieldName";
//
// btnRamp
//
resources.ApplyResources(this.btnRamp, "btnRamp");
this.btnRamp.Name = "btnRamp";
this.ttHelp.SetToolTip(this.btnRamp, resources.GetString("btnRamp.ToolTip"));
this.btnRamp.UseVisualStyleBackColor = true;
this.btnRamp.Click += new System.EventHandler(this.BtnRampClick);
//
// cmdRefresh
//
resources.ApplyResources(this.cmdRefresh, "cmdRefresh");
this.cmdRefresh.Name = "cmdRefresh";
this.ttHelp.SetToolTip(this.cmdRefresh, resources.GetString("cmdRefresh.ToolTip"));
this.cmdRefresh.UseVisualStyleBackColor = true;
this.cmdRefresh.Click += new System.EventHandler(this.CmdRefreshClick);
//
// btnExclude
//
resources.ApplyResources(this.btnExclude, "btnExclude");
this.btnExclude.Name = "btnExclude";
this.ttHelp.SetToolTip(this.btnExclude, resources.GetString("btnExclude.ToolTip"));
this.btnExclude.UseVisualStyleBackColor = true;
this.btnExclude.Click += new System.EventHandler(this.BtnExcludeClick);
//
// radUniqueValues
//
resources.ApplyResources(this.radUniqueValues, "radUniqueValues");
this.radUniqueValues.Checked = true;
this.radUniqueValues.Name = "radUniqueValues";
this.radUniqueValues.TabStop = true;
this.ttHelp.SetToolTip(this.radUniqueValues, resources.GetString("radUniqueValues.ToolTip"));
this.radUniqueValues.UseVisualStyleBackColor = true;
this.radUniqueValues.CheckedChanged += new System.EventHandler(this.RadUniqueValuesCheckedChanged);
//
// radQuantities
//
resources.ApplyResources(this.radQuantities, "radQuantities");
this.radQuantities.Name = "radQuantities";
this.ttHelp.SetToolTip(this.radQuantities, resources.GetString("radQuantities.ToolTip"));
this.radQuantities.UseVisualStyleBackColor = true;
this.radQuantities.CheckedChanged += new System.EventHandler(this.RadQuantitiesCheckedChanged);
//
// btnAdd
//
this.btnAdd.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.add;
resources.ApplyResources(this.btnAdd, "btnAdd");
this.btnAdd.Name = "btnAdd";
this.ttHelp.SetToolTip(this.btnAdd, resources.GetString("btnAdd.ToolTip"));
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.BtnAddClick);
//
// btnDelete
//
this.btnDelete.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.delete;
resources.ApplyResources(this.btnDelete, "btnDelete");
this.btnDelete.Name = "btnDelete";
this.ttHelp.SetToolTip(this.btnDelete, resources.GetString("btnDelete.ToolTip"));
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.BtnDeleteClick);
//
// btnUp
//
this.btnUp.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.up;
resources.ApplyResources(this.btnUp, "btnUp");
this.btnUp.Name = "btnUp";
this.ttHelp.SetToolTip(this.btnUp, resources.GetString("btnUp.ToolTip"));
this.btnUp.UseVisualStyleBackColor = true;
this.btnUp.Click += new System.EventHandler(this.BtnUpClick);
//
// btnDown
//
this.btnDown.BackColor = System.Drawing.SystemColors.Control;
this.btnDown.Image = global::DotSpatial.Symbology.Forms.SymbologyFormsImages.down;
resources.ApplyResources(this.btnDown, "btnDown");
this.btnDown.Name = "btnDown";
this.ttHelp.SetToolTip(this.btnDown, resources.GetString("btnDown.ToolTip"));
this.btnDown.UseVisualStyleBackColor = false;
this.btnDown.Click += new System.EventHandler(this.BtnDownClick);
//
// cmbNormField
//
this.cmbNormField.FormattingEnabled = true;
resources.ApplyResources(this.cmbNormField, "cmbNormField");
this.cmbNormField.Name = "cmbNormField";
this.ttHelp.SetToolTip(this.cmbNormField, resources.GetString("cmbNormField.ToolTip"));
this.cmbNormField.SelectedIndexChanged += new System.EventHandler(this.CmbNormFieldSelectedIndexChanged);
//
// nudSigFig
//
resources.ApplyResources(this.nudSigFig, "nudSigFig");
this.nudSigFig.Maximum = new decimal(new int[] {
16,
0,
0,
0});
this.nudSigFig.Name = "nudSigFig";
this.ttHelp.SetToolTip(this.nudSigFig, resources.GetString("nudSigFig.ToolTip"));
this.nudSigFig.ValueChanged += new System.EventHandler(this.NudSigFigValueChanged);
//
// cmbIntervalSnapping
//
this.cmbIntervalSnapping.FormattingEnabled = true;
resources.ApplyResources(this.cmbIntervalSnapping, "cmbIntervalSnapping");
this.cmbIntervalSnapping.Name = "cmbIntervalSnapping";
this.ttHelp.SetToolTip(this.cmbIntervalSnapping, resources.GetString("cmbIntervalSnapping.ToolTip"));
this.cmbIntervalSnapping.SelectedIndexChanged += new System.EventHandler(this.CmbIntervalSnappingSelectedIndexChanged);
//
// dgvStatistics
//
this.dgvStatistics.AllowUserToAddRows = false;
this.dgvStatistics.AllowUserToDeleteRows = false;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.AntiqueWhite;
this.dgvStatistics.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.dgvStatistics.BackgroundColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvStatistics.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.dgvStatistics.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvStatistics.ColumnHeadersVisible = false;
this.dgvStatistics.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Stat,
this.Value});
resources.ApplyResources(this.dgvStatistics, "dgvStatistics");
this.dgvStatistics.Name = "dgvStatistics";
this.dgvStatistics.RowHeadersVisible = false;
this.dgvStatistics.ShowCellErrors = false;
this.ttHelp.SetToolTip(this.dgvStatistics, resources.GetString("dgvStatistics.ToolTip"));
//
// Stat
//
resources.ApplyResources(this.Stat, "Stat");
this.Stat.Name = "Stat";
//
// Value
//
this.Value.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.Value, "Value");
this.Value.Name = "Value";
//
// tabScheme
//
this.tabScheme.Controls.Add(this.tabStatistics);
this.tabScheme.Controls.Add(this.tabGraph);
resources.ApplyResources(this.tabScheme, "tabScheme");
this.tabScheme.Name = "tabScheme";
this.tabScheme.SelectedIndex = 0;
//
// tabStatistics
//
this.tabStatistics.Controls.Add(this.label3);
this.tabStatistics.Controls.Add(this.cmbNormField);
this.tabStatistics.Controls.Add(this.btnExclude);
this.tabStatistics.Controls.Add(this.nudSigFig);
this.tabStatistics.Controls.Add(this.lblSigFig);
this.tabStatistics.Controls.Add(this.label1);
this.tabStatistics.Controls.Add(this.cmbIntervalSnapping);
this.tabStatistics.Controls.Add(this.dgvStatistics);
this.tabStatistics.Controls.Add(this.label2);
this.tabStatistics.Controls.Add(this.cmbInterval);
this.tabStatistics.Controls.Add(this.nudCategoryCount);
this.tabStatistics.Controls.Add(this.lblBreaks);
resources.ApplyResources(this.tabStatistics, "tabStatistics");
this.tabStatistics.Name = "tabStatistics";
this.tabStatistics.UseVisualStyleBackColor = true;
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// lblSigFig
//
resources.ApplyResources(this.lblSigFig, "lblSigFig");
this.lblSigFig.Name = "lblSigFig";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// cmbInterval
//
this.cmbInterval.FormattingEnabled = true;
resources.ApplyResources(this.cmbInterval, "cmbInterval");
this.cmbInterval.Name = "cmbInterval";
this.cmbInterval.SelectedIndexChanged += new System.EventHandler(this.CmbIntervalSelectedIndexChanged);
//
// nudCategoryCount
//
resources.ApplyResources(this.nudCategoryCount, "nudCategoryCount");
this.nudCategoryCount.Name = "nudCategoryCount";
this.nudCategoryCount.Value = new decimal(new int[] {
5,
0,
0,
0});
this.nudCategoryCount.ValueChanged += new System.EventHandler(this.NudCategoryCountValueChanged);
//
// lblBreaks
//
resources.ApplyResources(this.lblBreaks, "lblBreaks");
this.lblBreaks.Name = "lblBreaks";
//
// tabGraph
//
this.tabGraph.Controls.Add(this.lblColumns);
this.tabGraph.Controls.Add(this.nudColumns);
this.tabGraph.Controls.Add(this.chkLog);
this.tabGraph.Controls.Add(this.chkShowStd);
this.tabGraph.Controls.Add(this.chkShowMean);
this.tabGraph.Controls.Add(this.breakSliderGraph1);
resources.ApplyResources(this.tabGraph, "tabGraph");
this.tabGraph.Name = "tabGraph";
this.tabGraph.UseVisualStyleBackColor = true;
//
// lblColumns
//
resources.ApplyResources(this.lblColumns, "lblColumns");
this.lblColumns.Name = "lblColumns";
//
// nudColumns
//
this.nudColumns.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.nudColumns, "nudColumns");
this.nudColumns.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.nudColumns.Minimum = new decimal(new int[] {
10,
0,
0,
0});
this.nudColumns.Name = "nudColumns";
this.nudColumns.Value = new decimal(new int[] {
40,
0,
0,
0});
this.nudColumns.ValueChanged += new System.EventHandler(this.NudColumnsValueChanged);
//
// chkLog
//
resources.ApplyResources(this.chkLog, "chkLog");
this.chkLog.Name = "chkLog";
this.chkLog.UseVisualStyleBackColor = true;
this.chkLog.CheckedChanged += new System.EventHandler(this.ChkLogCheckedChanged);
//
// chkShowStd
//
resources.ApplyResources(this.chkShowStd, "chkShowStd");
this.chkShowStd.Name = "chkShowStd";
this.chkShowStd.UseVisualStyleBackColor = true;
this.chkShowStd.CheckedChanged += new System.EventHandler(this.ChkShowStdCheckedChanged);
//
// chkShowMean
//
resources.ApplyResources(this.chkShowMean, "chkShowMean");
this.chkShowMean.Name = "chkShowMean";
this.chkShowMean.UseVisualStyleBackColor = true;
this.chkShowMean.CheckedChanged += new System.EventHandler(this.ChkShowMeanCheckedChanged);
//
// breakSliderGraph1
//
this.breakSliderGraph1.AttributeSource = null;
this.breakSliderGraph1.BackColor = System.Drawing.Color.White;
this.breakSliderGraph1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.breakSliderGraph1.BreakColor = System.Drawing.Color.Blue;
this.breakSliderGraph1.BreakSelectedColor = System.Drawing.Color.Red;
this.breakSliderGraph1.FontColor = System.Drawing.Color.Black;
this.breakSliderGraph1.IntervalMethod = DotSpatial.Symbology.IntervalMethod.EqualInterval;
resources.ApplyResources(this.breakSliderGraph1, "breakSliderGraph1");
this.breakSliderGraph1.LogY = false;
this.breakSliderGraph1.MaximumSampleSize = 10000;
this.breakSliderGraph1.MinHeight = 20;
this.breakSliderGraph1.Name = "breakSliderGraph1";
this.breakSliderGraph1.NumColumns = 40;
this.breakSliderGraph1.RasterLayer = null;
this.breakSliderGraph1.Scheme = null;
this.breakSliderGraph1.ShowMean = false;
this.breakSliderGraph1.ShowStandardDeviation = false;
this.breakSliderGraph1.Title = "Statistical Breaks:";
this.breakSliderGraph1.TitleColor = System.Drawing.Color.Black;
this.breakSliderGraph1.TitleFont = new System.Drawing.Font("Arial", 20F, System.Drawing.FontStyle.Bold);
this.breakSliderGraph1.SliderMoved += new System.EventHandler<DotSpatial.Symbology.Forms.BreakSliderEventArgs>(this.BreakSliderGraph1SliderMoved);
//
// chkUseGradients
//
resources.ApplyResources(this.chkUseGradients, "chkUseGradients");
this.chkUseGradients.Name = "chkUseGradients";
this.chkUseGradients.UseVisualStyleBackColor = true;
this.chkUseGradients.CheckedChanged += new System.EventHandler(this.ChkUseGradientsCheckedChanged);
//
// dgvCategories
//
this.dgvCategories.AllowUserToAddRows = false;
this.dgvCategories.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvCategories.BackgroundColor = System.Drawing.SystemColors.Window;
this.dgvCategories.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvCategories.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colSymbol,
this.colValues,
this.colLegendText,
this.colCount});
resources.ApplyResources(this.dgvCategories, "dgvCategories");
this.dgvCategories.MultiSelect = false;
this.dgvCategories.Name = "dgvCategories";
this.dgvCategories.RowHeadersVisible = false;
this.dgvCategories.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvCategories.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvCategoriesCellContentClick);
//
// colSymbol
//
this.colSymbol.FillWeight = 49.97129F;
resources.ApplyResources(this.colSymbol, "colSymbol");
this.colSymbol.Name = "colSymbol";
this.colSymbol.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// colValues
//
this.colValues.FillWeight = 142.132F;
resources.ApplyResources(this.colValues, "colValues");
this.colValues.Name = "colValues";
this.colValues.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// colLegendText
//
this.colLegendText.FillWeight = 157.008F;
resources.ApplyResources(this.colLegendText, "colLegendText");
this.colLegendText.Name = "colLegendText";
//
// colCount
//
this.colCount.FillWeight = 50.88878F;
resources.ApplyResources(this.colCount, "colCount");
this.colCount.Name = "colCount";
this.colCount.ReadOnly = true;
this.colCount.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// radCustom
//
resources.ApplyResources(this.radCustom, "radCustom");
this.radCustom.Name = "radCustom";
this.radCustom.TabStop = true;
this.radCustom.UseVisualStyleBackColor = true;
this.radCustom.CheckedChanged += new System.EventHandler(this.RadCustomCheckedChanged);
//
// angGradientAngle
//
this.angGradientAngle.Angle = 0;
this.angGradientAngle.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.angGradientAngle, "angGradientAngle");
this.angGradientAngle.Clockwise = false;
this.angGradientAngle.KnobColor = System.Drawing.Color.Green;
this.angGradientAngle.Name = "angGradientAngle";
this.angGradientAngle.StartAngle = 0;
this.angGradientAngle.AngleChanged += new System.EventHandler(this.AngGradientAngleAngleChanged);
//
// featureSizeRangeControl1
//
resources.ApplyResources(this.featureSizeRangeControl1, "featureSizeRangeControl1");
this.featureSizeRangeControl1.Name = "featureSizeRangeControl1";
this.featureSizeRangeControl1.Scheme = null;
this.featureSizeRangeControl1.SizeRange = null;
this.featureSizeRangeControl1.SizeRangeChanged += new System.EventHandler<DotSpatial.Symbology.Forms.SizeRangeEventArgs>(this.PointSizeRangeControl1SizeRangeChanged);
//
// tccColorRange
//
this.tccColorRange.EndColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.tccColorRange.HueShift = 0;
resources.ApplyResources(this.tccColorRange, "tccColorRange");
this.tccColorRange.Name = "tccColorRange";
this.tccColorRange.StartColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.tccColorRange.UseRangeChecked = true;
this.tccColorRange.ColorChanged += new System.EventHandler<DotSpatial.Symbology.Forms.ColorRangeEventArgs>(this.TccColorRangeColorChanged);
//
// dataGridViewImageColumn1
//
this.dataGridViewImageColumn1.FillWeight = 76.14214F;
resources.ApplyResources(this.dataGridViewImageColumn1, "dataGridViewImageColumn1");
this.dataGridViewImageColumn1.Name = "dataGridViewImageColumn1";
this.dataGridViewImageColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewImageColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
// FeatureCategoryControl
//
this.Controls.Add(this.chkUseGradients);
this.Controls.Add(this.angGradientAngle);
this.Controls.Add(this.featureSizeRangeControl1);
this.Controls.Add(this.tccColorRange);
this.Controls.Add(this.tabScheme);
this.Controls.Add(this.dgvCategories);
this.Controls.Add(this.radCustom);
this.Controls.Add(this.btnDown);
this.Controls.Add(this.btnUp);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.radQuantities);
this.Controls.Add(this.radUniqueValues);
this.Controls.Add(this.btnRamp);
this.Controls.Add(this.cmdRefresh);
this.Controls.Add(this._lblFieldName);
this.Controls.Add(this._cmbField);
this.Name = "FeatureCategoryControl";
resources.ApplyResources(this, "$this");
((System.ComponentModel.ISupportInitialize)(this.nudSigFig)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgvStatistics)).EndInit();
this.tabScheme.ResumeLayout(false);
this.tabStatistics.ResumeLayout(false);
this.tabStatistics.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudCategoryCount)).EndInit();
this.tabGraph.ResumeLayout(false);
this.tabGraph.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudColumns)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgvCategories)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private AngleControl angGradientAngle;
private BreakSliderGraph breakSliderGraph1;
private Button btnAdd;
private Button btnDelete;
private Button btnDown;
private Button btnExclude;
private Button btnRamp;
private Button btnUp;
private CheckBox chkLog;
private CheckBox chkShowMean;
private CheckBox chkShowStd;
private CheckBox chkUseGradients;
private ComboBox cmbInterval;
private ComboBox cmbIntervalSnapping;
private ComboBox cmbNormField;
private Button cmdRefresh;
private DataGridViewTextBoxColumn colCount;
private DataGridViewTextBoxColumn colLegendText;
private DataGridViewImageColumn colSymbol;
private DataGridViewTextBoxColumn colValues;
private DataGridViewImageColumn dataGridViewImageColumn1;
private DataGridView dgvCategories;
private DataGridView dgvStatistics;
private FeatureSizeRangeControl featureSizeRangeControl1;
private Label label1;
private Label label2;
private Label label3;
private Label lblBreaks;
private Label lblColumns;
private Label lblSigFig;
private Label _lblFieldName;
private NumericUpDown nudCategoryCount;
private NumericUpDown nudColumns;
private NumericUpDown nudSigFig;
private RadioButton radCustom;
private RadioButton radQuantities;
private RadioButton radUniqueValues;
private TabPage tabGraph;
private TabControl tabScheme;
private TabPage tabStatistics;
private TabColorControl tccColorRange;
private ToolTip ttHelp;
private ProgressCancelDialog _cancelDialog;
private Timer _cleanupTimer;
private ComboBox _cmbField;
private DataGridViewTextBoxColumn Stat;
private DataGridViewTextBoxColumn Value;
}
}
|
||||
TheStack | bdb1398cfe9857852b80cf6a27d57e3eaeede696 | C#code:C# | {"size": 615, "ext": "cshtml", "max_stars_repo_path": "Factory/Views/Shared/Header.cshtml", "max_stars_repo_name": "aGhouzlane/Factory.Solution", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Factory/Views/Shared/Header.cshtml", "max_issues_repo_name": "aGhouzlane/Factory.Solution", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Factory/Views/Shared/Header.cshtml", "max_forks_repo_name": "aGhouzlane/Factory.Solution", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.2857142857, "max_line_length": 85, "alphanum_fraction": 0.6292682927} | <div style=" position:fixed;
top:0px;
left:0px;
width:100%;
color:rgb(146, 232, 253);
background:#333;
padding-left: 25px;
padding-top: 20px;
padding-bottom: 20px;">
<div style="display: inline-block; padding-right: 20px;">
<img width="50px;" height="50px;" src="~/img/factory.png" alt="bread-img">
</div>
<div style="display: inline-block;">
<h4><b>Dr. Sillystringz's Factory</b></h4>
</div>
<div style="display: inline-block;">
<div style="width: 5px; height: 5px; border-radius: 50%; background-color:blue;">
</div>
</div>
</div>
<div style="margin-top: 100px;"></div> |
||||
TheStack | bdb173864dd67e4f35be18d9069da5202583f0d8 | C#code:C# | {"size": 474, "ext": "cs", "max_stars_repo_path": "Assets/LeanTween/Examples/Archived/TestingRigidbodyCS.cs", "max_stars_repo_name": "nikinov/Extra_credits_game_jam_6", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/LeanTween/Examples/Archived/TestingRigidbodyCS.cs", "max_issues_repo_name": "nikinov/Extra_credits_game_jam_6", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/LeanTween/Examples/Archived/TestingRigidbodyCS.cs", "max_forks_repo_name": "nikinov/Extra_credits_game_jam_6", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.6086956522, "max_line_length": 94, "alphanum_fraction": 0.6983122363} | using UnityEngine;
namespace LeanTween.Examples.Archived
{
public class TestingRigidbodyCS : MonoBehaviour {
private GameObject ball1;
// Use this for initialization
void Start () {
ball1 = GameObject.Find("Sphere1");
Framework.LeanTween.rotateAround( ball1, Vector3.forward, -90f, 1.0f);
Framework.LeanTween.move( ball1, new Vector3(2f,0f,7f), 1.0f).setDelay(1.0f).setRepeat(-1);
}
// Update is called once per frame
void Update () {
}
}
}
|
||||
TheStack | bdb420c3dd4f4f31ec16bbf32c4ec91531e1e56c | C#code:C# | {"size": 331, "ext": "cs", "max_stars_repo_path": "XorPay.Web/index.aspx.designer.cs", "max_stars_repo_name": "HeavenJoe/xorpay_net", "max_stars_repo_stars_event_min_datetime": "2019-09-01T00:46:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T16:00:47.000Z", "max_issues_repo_path": "XorPay.Web/index.aspx.designer.cs", "max_issues_repo_name": "xorpay/xorpay_net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "XorPay.Web/index.aspx.designer.cs", "max_forks_repo_name": "xorpay/xorpay_net", "max_forks_repo_forks_event_min_datetime": "2019-09-04T06:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T20:28:11.000Z"} | {"max_stars_count": 11.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 20.6875, "max_line_length": 81, "alphanum_fraction": 0.2719033233} | //------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace XorPay.Web {
public partial class index {
}
}
|
||||
TheStack | bdb50d5e957a6d79cf2c942c8d4b5feeaba52450 | C#code:C# | {"size": 2727, "ext": "cs", "max_stars_repo_path": "Assets/Plugins/backtrace-unity-1.1.5/src/Interfaces/IBacktraceDatabaseContext.cs", "max_stars_repo_name": "konraddysput/RedRunner", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Plugins/backtrace-unity-1.1.5/src/Interfaces/IBacktraceDatabaseContext.cs", "max_issues_repo_name": "konraddysput/RedRunner", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Plugins/backtrace-unity-1.1.5/src/Interfaces/IBacktraceDatabaseContext.cs", "max_forks_repo_name": "konraddysput/RedRunner", "max_forks_repo_forks_event_min_datetime": "2020-03-23T18:07:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T18:07:04.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 29.967032967, "max_line_length": 103, "alphanum_fraction": 0.5753575358} | using Backtrace.Unity.Model;
using Backtrace.Unity.Model.Database;
using System;
using System.Collections.Generic;
namespace Backtrace.Unity.Interfaces
{
internal interface IBacktraceDatabaseContext : IDisposable
{
/// <summary>
/// Add new record to Database
/// </summary>
/// <param name="backtraceData">Diagnostic data</param>
BacktraceDatabaseRecord Add(BacktraceData backtraceData);
/// <summary>
/// Add new data to database
/// </summary>
/// <param name="backtraceDatabaseRecord">Database record</param>
BacktraceDatabaseRecord Add(BacktraceDatabaseRecord backtraceDatabaseRecord);
/// <summary>
/// Get first record or null
/// </summary>
/// <returns>First existing record in database store</returns>
BacktraceDatabaseRecord FirstOrDefault();
/// <summary>
/// Get last record or null
/// </summary>
/// <returns>Last existing record in database store</returns>
BacktraceDatabaseRecord LastOrDefault();
/// <summary>
/// Get all records stored in Database
/// </summary>
IEnumerable<BacktraceDatabaseRecord> Get();
/// <summary>
/// Delete database record by using BacktraceDatabaseRecord
/// </summary>
/// <param name="record">Database record</param>
void Delete(BacktraceDatabaseRecord record);
/// <summary>
/// Check if any similar record exists
/// </summary>
/// <param name="n">Compared record</param>
bool Any(BacktraceDatabaseRecord n);
/// <summary>
/// Check if any similar record exists
/// </summary>
bool Any();
/// <summary>
/// Get total count of records
/// </summary>
/// <returns>Total number of records</returns>
int Count();
/// <summary>
/// Clear database
/// </summary>
void Clear();
/// <summary>
/// Increment record time for all records
/// </summary>
void IncrementBatchRetry();
/// <summary>
/// Get database size
/// </summary>
/// <returns>Database size</returns>
long GetSize();
/// <summary>
/// Get total number of records stored in database
/// </summary>
/// <returns>Total number of records</returns>
int GetTotalNumberOfRecords();
/// <summary>
/// Remove last record in database.
/// </summary>
/// <returns>If algorithm can remove last record, method return true. Otherwise false</returns>
bool RemoveLastRecord();
}
}
|
||||
TheStack | bdb566ad7a6f5e5649467862502a9985e485daea | C#code:C# | {"size": 770, "ext": "cs", "max_stars_repo_path": "code/Server/Common/Blobs/ContainerDescriptor.cs", "max_stars_repo_name": "Thorcik1704/EmbeddedSocial-Service", "max_stars_repo_stars_event_min_datetime": "2020-05-09T09:32:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:23:07.000Z", "max_issues_repo_path": "code/Server/Common/Blobs/ContainerDescriptor.cs", "max_issues_repo_name": "Thorcik1704/EmbeddedSocial-Service", "max_issues_repo_issues_event_min_datetime": "2020-06-04T09:17:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T17:33:39.000Z", "max_forks_repo_path": "code/Server/Common/Blobs/ContainerDescriptor.cs", "max_forks_repo_name": "Thorcik1704/EmbeddedSocial-Service", "max_forks_repo_forks_event_min_datetime": "2020-02-01T23:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T08:29:59.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 1.0, "max_forks_count": 9.0, "avg_line_length": 27.5, "max_line_length": 78, "alphanum_fraction": 0.6038961039} | // <copyright file="ContainerDescriptor.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace SocialPlus.Server.Blobs
{
/// <summary>
/// Container descriptor class
/// </summary>
public class ContainerDescriptor
{
/// <summary>
/// Gets or sets container name
/// </summary>
public string ContainerName { get; set; }
/// <summary>
/// Gets or sets Azure storage instance type
/// </summary>
public AzureStorageInstanceType AzureStorageInstanceType { get; set; }
/// <summary>
/// Gets or sets Azure CDN instance type
/// </summary>
public AzureCdnInstanceType AzureCdnInstanceType { get; set; }
}
}
|
||||
TheStack | bdb91962b7db3037869e9ff71cf479e28d08c1fc | C#code:C# | {"size": 1771, "ext": "cs", "max_stars_repo_path": "Source/Wpf/Prism.Unity.Wpf.Tests/UnityContainerExtensionFixture.cs", "max_stars_repo_name": "hronlukas/Prism", "max_stars_repo_stars_event_min_datetime": "2020-04-03T16:09:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T21:55:50.000Z", "max_issues_repo_path": "Source/Wpf/Prism.Unity.Wpf.Tests/UnityContainerExtensionFixture.cs", "max_issues_repo_name": "hronlukas/Prism", "max_issues_repo_issues_event_min_datetime": "2018-09-28T02:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-02T14:02:02.000Z", "max_forks_repo_path": "Source/Wpf/Prism.Unity.Wpf.Tests/UnityContainerExtensionFixture.cs", "max_forks_repo_name": "hronlukas/Prism", "max_forks_repo_forks_event_min_datetime": "2019-02-07T11:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-16T00:34:11.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 8.0, "max_forks_count": 8.0, "avg_line_length": 29.5166666667, "max_line_length": 82, "alphanum_fraction": 0.6261998871} |
using System.Collections.Generic;
using Unity;
using Xunit;
using Prism.IocContainer.Wpf.Tests.Support.Mocks;
namespace Prism.Unity.Wpf.Tests
{
public class UnityContainerExtensionFixture
{
[Fact]
public void ExtensionReturnsTrueIfThereIsAPolicyForType()
{
UnityContainer container = new UnityContainer();
container.RegisterType<object, string>();
Assert.True(container.IsTypeRegistered(typeof(object)));
Assert.False(container.IsTypeRegistered(typeof(int)));
container.RegisterType<IList<int>, List<int>>();
Assert.True(container.IsTypeRegistered(typeof(IList<int>)));
Assert.False(container.IsTypeRegistered(typeof(IList<string>)));
container.RegisterType(typeof(IDictionary<,>), typeof(Dictionary<,>));
Assert.True(container.IsTypeRegistered(typeof(IDictionary<,>)));
}
[Fact]
public void TryResolveShouldResolveTheElementIfElementExist()
{
var container = new UnityContainer();
container.RegisterType<IService, MockService>();
object dependantA = container.TryResolve<IService>();
Assert.NotNull(dependantA);
}
[Fact]
public void TryResolveShouldReturnNullIfElementNotExist()
{
var container = new UnityContainer();
object dependantA = container.TryResolve<IDependantA>();
Assert.Null(dependantA);
}
[Fact]
public void TryResolveWorksWithValueTypes()
{
var container = new UnityContainer();
int valueType = container.TryResolve<int>();
Assert.Equal(default(int), valueType);
}
}
} |
||||
TheStack | bdb9b2fcdddd340b7347462779faa4791f42357f | C#code:C# | {"size": 615, "ext": "cs", "max_stars_repo_path": "Source/Katas/FourInARow/Kodefoxx.Katas.FourInARow/Players/Player.cs", "max_stars_repo_name": "KodeFoxx-Projects/Katas", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Katas/FourInARow/Kodefoxx.Katas.FourInARow/Players/Player.cs", "max_issues_repo_name": "KodeFoxx-Projects/Katas", "max_issues_repo_issues_event_min_datetime": "2018-04-04T06:55:48.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-04T08:46:07.000Z", "max_forks_repo_path": "Source/Katas/FourInARow/Kodefoxx.Katas.FourInARow/Players/Player.cs", "max_forks_repo_name": "KodeFoxx-Projects/Katas", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 5.0, "max_forks_count": null, "avg_line_length": 22.7777777778, "max_line_length": 57, "alphanum_fraction": 0.5024390244} | using Kodefoxx.Katas.FourInARow.Board;
namespace Kodefoxx.Katas.FourInARow.Players
{
public sealed class Player
{
/// <summary>
/// Creates a new <see cref="Player"/>.
/// </summary>
internal Player(string name, BoardSlotValue type)
{
Name = name;
Type = type;
}
/// <summary>
/// Gets the name of the player.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the type of the player.
/// </summary>
public BoardSlotValue Type { get; }
}
}
|
||||
TheStack | bdba818f2551b61bb066a1ead3fbf3587cb76993 | C#code:C# | {"size": 7571, "ext": "cs", "max_stars_repo_path": "TramsDataApi/Migrations/TramsDb/20211206174953_AddAndAmendApplyingSchoolTables.cs", "max_stars_repo_name": "DFE-Digital/trams-data-api", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TramsDataApi/Migrations/TramsDb/20211206174953_AddAndAmendApplyingSchoolTables.cs", "max_issues_repo_name": "DFE-Digital/trams-data-api", "max_issues_repo_issues_event_min_datetime": "2021-04-30T11:15:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T12:49:12.000Z", "max_forks_repo_path": "TramsDataApi/Migrations/TramsDb/20211206174953_AddAndAmendApplyingSchoolTables.cs", "max_forks_repo_name": "DFE-Digital/trams-data-api", "max_forks_repo_forks_event_min_datetime": "2021-04-10T21:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T09:18:12.000Z"} | {"max_stars_count": null, "max_issues_count": 8.0, "max_forks_count": 2.0, "avg_line_length": 37.6666666667, "max_line_length": 91, "alphanum_fraction": 0.5303130366} | using Microsoft.EntityFrameworkCore.Migrations;
namespace TramsDataApi.Migrations.TramsDb
{
public partial class AddAndAmendApplyingSchoolTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_A2BApplyingSchool",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropColumn(
name: "ApplyingSchoolsId",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.AddColumn<string>(
name: "ApplyingSchoolId",
schema: "sdd",
table: "A2BApplyingSchool",
nullable: false,
defaultValue: "");
migrationBuilder.AddPrimaryKey(
name: "PK_A2BApplyingSchool",
schema: "sdd",
table: "A2BApplyingSchool",
column: "ApplyingSchoolId");
migrationBuilder.CreateTable(
name: "A2BSelectOption",
schema: "sdd",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_A2BSelectOption", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_A2BApplyingSchool_SchoolDeclarationBodyAgree",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolDeclarationBodyAgree");
migrationBuilder.CreateIndex(
name: "IX_A2BApplyingSchool_SchoolDeclarationTeacherChair",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolDeclarationTeacherChair");
migrationBuilder.CreateIndex(
name: "IX_A2BApplyingSchool_SchoolLeaseExists",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolLeaseExists");
migrationBuilder.CreateIndex(
name: "IX_A2BApplyingSchool_SchoolLoanExists",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolLoanExists");
migrationBuilder.AddForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolDeclarationBodyAgree",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolDeclarationBodyAgree",
principalSchema: "sdd",
principalTable: "A2BSelectOption",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolDeclarationTeacherChair",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolDeclarationTeacherChair",
principalSchema: "sdd",
principalTable: "A2BSelectOption",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolLeaseExists",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolLeaseExists",
principalSchema: "sdd",
principalTable: "A2BSelectOption",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolLoanExists",
schema: "sdd",
table: "A2BApplyingSchool",
column: "SchoolLoanExists",
principalSchema: "sdd",
principalTable: "A2BSelectOption",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.InsertData(
schema: "sdd",
table: "A2BSelectOption",
columns: new[] {"Id", "Name"},
values: new object[] {907660000, "Yes"});
migrationBuilder.InsertData(
schema: "sdd",
table: "A2BSelectOption",
columns: new[] {"Id", "Name"},
values: new object[] {907660001, "No"});
migrationBuilder.InsertData(
schema: "sdd",
table: "A2BSelectOption",
columns: new[] {"Id", "Name"},
values: new object[] {907660002, "Unknown"});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolDeclarationBodyAgree",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolDeclarationTeacherChair",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolLeaseExists",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropForeignKey(
name: "FK_A2BApplyingSchool_A2BSelectOption_SchoolLoanExists",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropTable(
name: "A2BSelectOption",
schema: "sdd");
migrationBuilder.DropPrimaryKey(
name: "PK_A2BApplyingSchool",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropIndex(
name: "IX_A2BApplyingSchool_SchoolDeclarationBodyAgree",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropIndex(
name: "IX_A2BApplyingSchool_SchoolDeclarationTeacherChair",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropIndex(
name: "IX_A2BApplyingSchool_SchoolLeaseExists",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropIndex(
name: "IX_A2BApplyingSchool_SchoolLoanExists",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.DropColumn(
name: "ApplyingSchoolId",
schema: "sdd",
table: "A2BApplyingSchool");
migrationBuilder.AddColumn<string>(
name: "ApplyingSchoolsId",
schema: "sdd",
table: "A2BApplyingSchool",
type: "nvarchar(450)",
nullable: false,
defaultValue: "");
migrationBuilder.AddPrimaryKey(
name: "PK_A2BApplyingSchool",
schema: "sdd",
table: "A2BApplyingSchool",
column: "ApplyingSchoolsId");
}
}
}
|
||||
TheStack | bdbb15b5f920b342d9ccc96ab2a1d3b214d249e4 | C#code:C# | {"size": 4674, "ext": "cs", "max_stars_repo_path": "Tests/CSF.ORM.Tests/Entities/EntityDataTests.cs", "max_stars_repo_name": "csf-dev/CSF.ORM", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/CSF.ORM.Tests/Entities/EntityDataTests.cs", "max_issues_repo_name": "csf-dev/CSF.ORM", "max_issues_repo_issues_event_min_datetime": "2020-02-09T14:51:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T08:56:38.000Z", "max_forks_repo_path": "Tests/CSF.ORM.Tests/Entities/EntityDataTests.cs", "max_forks_repo_name": "csf-dev/CSF.ORM", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 50.0, "max_forks_count": null, "avg_line_length": 40.6434782609, "max_line_length": 152, "alphanum_fraction": 0.6521181001} | //
// EntityDataTests.cs
//
// Author:
// Craig Fowler <[email protected]>
//
// Copyright (c) 2020 Craig Fowler
//
// 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.Threading;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using CSF.Entities;
using CSF.ORM.Stubs;
using Moq;
using NUnit.Framework;
namespace CSF.ORM.Entities
{
[TestFixture, Parallelizable]
public class EntityDataTests
{
[Test, AutoMoqData]
public void Add_adds_entity_using_identity_if_not_null([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister)
.Setup(x => x.Add(entity, It.IsAny<object>()))
.Returns((Car e, object obj) => obj);
entity.Identity = 5;
sut.Add(entity);
Mock.Get(persister).Verify(x => x.Add(entity, 5L), Times.Once);
}
[Test, AutoMoqData]
public void Add_adds_entity_without_identity_if_it_is_null([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister)
.Setup(x => x.Add(entity, It.IsAny<object>()))
.Returns((Car e, object obj) => obj);
entity.Identity = 0;
sut.Add(entity);
Mock.Get(persister).Verify(x => x.Add(entity, null), Times.Once);
}
[Test, AutoMoqData]
public void Add_returns_result_from_persister_add([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister).Setup(x => x.Add(entity, null)).Returns(5);
Mock.Get(persister).Setup(x => x.Add(entity, It.IsAny<object>())).Returns(5);
var result = sut.Add(entity);
Assert.That(result, Is.EqualTo(new IdentityFactory().Create(typeof(Car), 5L)));
}
[Test, AutoMoqData]
public async Task AddAsync_adds_entity_using_identity_if_not_null([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister)
.Setup(x => x.AddAsync(entity, It.IsAny<object>(), It.IsAny<CancellationToken>()))
.Returns((Car e, object obj, CancellationToken t) => Task.FromResult(obj));
entity.Identity = 5;
await sut.AddAsync(entity);
Mock.Get(persister).Verify(x => x.AddAsync(entity, 5L, It.IsAny<CancellationToken>()), Times.Once);
}
[Test, AutoMoqData]
public async Task AddAsync_adds_entity_without_identity_if_it_is_null([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister)
.Setup(x => x.AddAsync(entity, It.IsAny<object>(), It.IsAny<CancellationToken>()))
.Returns((Car e, object obj, CancellationToken t) => Task.FromResult(obj));
entity.Identity = 0;
await sut.AddAsync(entity);
Mock.Get(persister).Verify(x => x.AddAsync(entity, null, It.IsAny<CancellationToken>()), Times.Once);
}
[Test, AutoMoqData]
public async Task AddAsync_returns_result_from_persister_add([Frozen] IPersister persister, EntityData sut, Car entity)
{
Mock.Get(persister).Setup(x => x.AddAsync(entity, null, It.IsAny<CancellationToken>())).Returns(Task.FromResult((object) 5L));
Mock.Get(persister).Setup(x => x.AddAsync(entity, It.IsAny<object>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult((object) 5L));
var result = await sut.AddAsync(entity);
Assert.That(result, Is.EqualTo(new IdentityFactory().Create(typeof(Car), 5L)));
}
}
}
|
||||
TheStack | bdbbbb2de660b51fa85e7a165eccf91d829f9ef3 | C#code:C# | {"size": 13101, "ext": "cs", "max_stars_repo_path": "iothub/service/src/Common/Data/AmqpErrorMapper.cs", "max_stars_repo_name": "prmathur-microsoft/azure-iot-sdk-csharp", "max_stars_repo_stars_event_min_datetime": "2017-08-28T08:04:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T21:12:50.000Z", "max_issues_repo_path": "iothub/service/src/Common/Data/AmqpErrorMapper.cs", "max_issues_repo_name": "prmathur-microsoft/azure-iot-sdk-csharp", "max_issues_repo_issues_event_min_datetime": "2019-10-22T00:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T00:06:14.000Z", "max_forks_repo_path": "iothub/service/src/Common/Data/AmqpErrorMapper.cs", "max_forks_repo_name": "prmathur-microsoft/azure-iot-sdk-csharp", "max_forks_repo_forks_event_min_datetime": "2015-11-08T09:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:53:53.000Z"} | {"max_stars_count": 4.0, "max_issues_count": 2.0, "max_forks_count": 5.0, "avg_line_length": 40.940625, "max_line_length": 182, "alphanum_fraction": 0.598580261} | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Common.Exceptions
{
using System;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.Devices.Common;
using Microsoft.Azure.Devices.Common.Client;
static class AmqpErrorMapper
{
const int MaxSizeInInfoMap = 32 * 1024;
public static Tuple<string, string, string> GenerateError(Exception ex)
{
if (ex is DeviceNotFoundException)
{
var deviceNotFoundException = (DeviceNotFoundException)ex;
return Tuple.Create(AmqpErrorCode.NotFound.ToString(), deviceNotFoundException.Message, deviceNotFoundException.TrackingId);
}
if (ex is DeviceAlreadyExistsException)
{
var deviceAlreadyExistsException = (DeviceAlreadyExistsException)ex;
return Tuple.Create(IotHubAmqpErrorCode.DeviceAlreadyExists.ToString(), deviceAlreadyExistsException.Message, deviceAlreadyExistsException.TrackingId);
}
if (ex is IotHubThrottledException)
{
var deviceContainerThrottledException = (IotHubThrottledException)ex;
return Tuple.Create(IotHubAmqpErrorCode.DeviceContainerThrottled.ToString(), deviceContainerThrottledException.Message, deviceContainerThrottledException.TrackingId);
}
if (ex is QuotaExceededException)
{
var quotaExceededException = (QuotaExceededException)ex;
return Tuple.Create(IotHubAmqpErrorCode.QuotaExceeded.ToString(), quotaExceededException.Message, quotaExceededException.TrackingId);
}
if (ex is DeviceMessageLockLostException)
{
var messageLockLostException = (DeviceMessageLockLostException)ex;
return Tuple.Create(IotHubAmqpErrorCode.MessageLockLostError.ToString(), messageLockLostException.Message, messageLockLostException.TrackingId);
}
if (ex is MessageTooLargeException)
{
var deviceMessageTooLargeException = (MessageTooLargeException)ex;
return Tuple.Create(AmqpErrorCode.MessageSizeExceeded.ToString(), deviceMessageTooLargeException.Message, deviceMessageTooLargeException.TrackingId);
}
if (ex is DeviceMaximumQueueDepthExceededException)
{
var queueDepthExceededException = (DeviceMaximumQueueDepthExceededException)ex;
return Tuple.Create(AmqpErrorCode.ResourceLimitExceeded.ToString(), queueDepthExceededException.Message, queueDepthExceededException.TrackingId);
}
if (ex is PreconditionFailedException)
{
var preconditionFailedException = (PreconditionFailedException)ex;
return Tuple.Create(IotHubAmqpErrorCode.PreconditionFailed.ToString(), preconditionFailedException.Message, preconditionFailedException.TrackingId);
}
if (ex is IotHubSuspendedException)
{
var iotHubSuspendedException = (IotHubSuspendedException)ex;
return Tuple.Create(IotHubAmqpErrorCode.IotHubSuspended.ToString(), iotHubSuspendedException.Message, iotHubSuspendedException.TrackingId);
}
return Tuple.Create(AmqpErrorCode.InternalError.ToString(), ex.ToStringSlim(), (string)null);
}
public static AmqpException ToAmqpException(Exception exception, string gatewayId)
{
return ToAmqpException(exception, gatewayId, false);
}
public static AmqpException ToAmqpException(Exception exception, string gatewayId, bool includeStackTrace)
{
Error amqpError = ToAmqpError(exception, includeStackTrace);
return new AmqpException(amqpError);
}
public static Error ToAmqpError(Exception exception, string gatewayId)
{
return ToAmqpError(exception, false);
}
public static Error ToAmqpError(Exception exception, bool includeStackTrace)
{
if (exception == null)
{
throw new ArgumentNullException("exception");
}
Error error = new Error();
error.Description = exception.Message;
if (exception is AmqpException)
{
AmqpException amqpException = (AmqpException)exception;
error.Condition = amqpException.Error.Condition;
error.Info = amqpException.Error.Info;
}
else if (exception is UnauthorizedAccessException || exception is UnauthorizedException)
{
error.Condition = AmqpErrorCode.UnauthorizedAccess;
}
else if (exception is NotSupportedException)
{
error.Condition = AmqpErrorCode.NotImplemented;
}
else if (exception is DeviceNotFoundException)
{
error.Condition = AmqpErrorCode.NotFound;
}
else if (exception is IotHubNotFoundException)
{
error.Condition = IotHubAmqpErrorCode.IotHubNotFoundError;
}
else if (exception is DeviceMessageLockLostException)
{
error.Condition = IotHubAmqpErrorCode.MessageLockLostError;
}
else if (exception is MessageTooLargeException)
{
error.Condition = AmqpErrorCode.MessageSizeExceeded;
}
else if (exception is DeviceMaximumQueueDepthExceededException)
{
error.Condition = AmqpErrorCode.ResourceLimitExceeded;
}
else if (exception is TimeoutException)
{
error.Condition = IotHubAmqpErrorCode.TimeoutError;
}
else if (exception is InvalidOperationException)
{
error.Condition = AmqpErrorCode.NotAllowed;
}
else if (exception is ArgumentOutOfRangeException)
{
error.Condition = IotHubAmqpErrorCode.ArgumentOutOfRangeError;
}
else if (exception is ArgumentException)
{
error.Condition = IotHubAmqpErrorCode.ArgumentError;
}
else if (exception is PreconditionFailedException)
{
error.Condition = IotHubAmqpErrorCode.PreconditionFailed;
}
else if (exception is IotHubSuspendedException)
{
error.Condition = IotHubAmqpErrorCode.IotHubSuspended;
}
else if (exception is QuotaExceededException)
{
error.Condition = IotHubAmqpErrorCode.QuotaExceeded;
}
else if (exception is TimeoutException)
{
error.Condition = IotHubAmqpErrorCode.TimeoutError;
}
else
{
error.Condition = AmqpErrorCode.InternalError;
error.Description = error.Description;
}
// we will always need this to add trackingId
if (error.Info == null)
{
error.Info = new Fields();
}
string stackTrace;
if (includeStackTrace && !string.IsNullOrEmpty(stackTrace = exception.StackTrace))
{
if (stackTrace.Length > MaxSizeInInfoMap)
{
stackTrace = stackTrace.Substring(0, MaxSizeInInfoMap);
}
// error.Info came from AmqpExcpetion then it contains StackTraceName already.
string dummy;
if (!error.Info.TryGetValue(IotHubAmqpProperty.StackTraceName, out dummy))
{
error.Info.Add(IotHubAmqpProperty.StackTraceName, stackTrace);
}
}
string trackingId;
error.Info.TryGetValue(IotHubAmqpProperty.TrackingId, out trackingId);
trackingId = TrackingHelper.CheckAndAddGatewayIdToTrackingId(trackingId);
error.Info[IotHubAmqpProperty.TrackingId] = trackingId;
return error;
}
public static Exception GetExceptionFromOutcome(Outcome outcome)
{
Exception retException = null;
if (outcome == null)
{
retException = new IotHubException("Unknown error.");
return retException;
}
if (outcome.DescriptorCode == Rejected.Code)
{
var rejected = (Rejected)outcome;
retException = AmqpErrorMapper.ToIotHubClientContract(rejected.Error);
}
else if (outcome.DescriptorCode == Released.Code)
{
retException = new OperationCanceledException("AMQP link released.");
}
else
{
retException = new IotHubException("Unknown error.");
}
return retException;
}
public static Exception ToIotHubClientContract(Error error)
{
Exception retException;
if (error == null)
{
retException = new IotHubException("Unknown error.");
return retException;
}
string message = error.Description;
string trackingId = null;
if (error.Info != null && error.Info.TryGetValue(IotHubAmqpProperty.TrackingId, out trackingId))
{
message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId);
}
if (error.Condition.Equals(IotHubAmqpErrorCode.TimeoutError))
{
retException = new TimeoutException(message);
}
else if (error.Condition.Equals(AmqpErrorCode.NotFound))
{
retException = new DeviceNotFoundException(message, innerException: null);
}
else if (error.Condition.Equals(AmqpErrorCode.NotImplemented))
{
retException = new NotSupportedException(message);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.MessageLockLostError))
{
retException = new DeviceMessageLockLostException(message);
}
else if (error.Condition.Equals(AmqpErrorCode.NotAllowed))
{
retException = new InvalidOperationException(message);
}
else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess))
{
retException = new UnauthorizedException(message);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.ArgumentError))
{
retException = new ArgumentException(message);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.ArgumentOutOfRangeError))
{
retException = new ArgumentOutOfRangeException(message);
}
else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded))
{
retException = new MessageTooLargeException(message);
}
else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded))
{
retException = new DeviceMaximumQueueDepthExceededException(message);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.DeviceAlreadyExists))
{
retException = new DeviceAlreadyExistsException(message, (Exception)null);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.DeviceContainerThrottled))
{
retException = new IotHubThrottledException(message, (Exception)null);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.QuotaExceeded))
{
retException = new QuotaExceededException(message, (Exception)null);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.PreconditionFailed))
{
retException = new PreconditionFailedException(message, (Exception)null);
}
else if (error.Condition.Equals(IotHubAmqpErrorCode.IotHubSuspended))
{
retException = new IotHubSuspendedException(message);
}
else
{
retException = new IotHubException(message);
}
if (trackingId != null && retException is IotHubException)
{
IotHubException iotHubException = (IotHubException)retException;
iotHubException.TrackingId = trackingId;
}
return retException;
}
}
}
|
||||
TheStack | bdbd1a988c255ee159becadd1d9b7655d52d3aa4 | C#code:C# | {"size": 428, "ext": "cs", "max_stars_repo_path": "Snouthill/Net/Packets/Messenger/InitMessengerRequest.cs", "max_stars_repo_name": "branw/Snouthill", "max_stars_repo_stars_event_min_datetime": "2019-06-01T08:20:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-01T08:20:56.000Z", "max_issues_repo_path": "Snouthill/Net/Packets/Messenger/InitMessengerRequest.cs", "max_issues_repo_name": "branw/Snouthill", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Snouthill/Net/Packets/Messenger/InitMessengerRequest.cs", "max_forks_repo_name": "branw/Snouthill", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.75, "max_line_length": 95, "alphanum_fraction": 0.7336448598} | using Snouthill.Game;
namespace Snouthill.Net.Packets.Messenger;
[RequestOpcode(12)]
public record InitMessengerRequest : IRequest;
public class InitMessengerRequestHandler : IRequestHandler<InitMessengerRequest>
{
public void Handle(InitMessengerRequest request, Player player)
{
player.Send(new InitMessengerResponse("Hello", 10, 5, 8, new List<string> {"a", "b"}));
//TODO handle requests
}
} |
||||
TheStack | bdbdc06f473e8ee059864f5bdec75d607ae769e8 | C#code:C# | {"size": 2348, "ext": "cs", "max_stars_repo_path": "src/Osc/QueryDsl/FullText/Intervals/IntervalsAnyOf.cs", "max_stars_repo_name": "MaxKsyunz/opensearch-net", "max_stars_repo_stars_event_min_datetime": "2022-02-17T22:22:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T22:22:15.000Z", "max_issues_repo_path": "src/Osc/QueryDsl/FullText/Intervals/IntervalsAnyOf.cs", "max_issues_repo_name": "MaxKsyunz/opensearch-net", "max_issues_repo_issues_event_min_datetime": "2022-02-10T21:17:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:57:33.000Z", "max_forks_repo_path": "src/Osc/QueryDsl/FullText/Intervals/IntervalsAnyOf.cs", "max_forks_repo_name": "MaxKsyunz/opensearch-net", "max_forks_repo_forks_event_min_datetime": "2022-03-24T20:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:06:04.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 5.0, "max_forks_count": 1.0, "avg_line_length": 35.5757575758, "max_line_length": 124, "alphanum_fraction": 0.7555366269} | /* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Osc
{
/// <summary>
/// A rule that emits intervals produced by any of its sub-rules.
/// </summary>
[ReadAs(typeof(IntervalsAnyOf))]
public interface IIntervalsAnyOf : IIntervals
{
/// <summary>
/// An array of rules to match.
/// </summary>
[DataMember(Name = "intervals")]
IEnumerable<IntervalsContainer> Intervals { get; set; }
}
/// <inheritdoc cref="IIntervalsAnyOf" />
public class IntervalsAnyOf : IntervalsBase, IIntervalsAnyOf
{
/// <inheritdoc />
public IEnumerable<IntervalsContainer> Intervals { get; set; }
internal override void WrapInContainer(IIntervalsContainer container) => container.AnyOf = this;
}
/// <inheritdoc cref="IIntervalsAnyOf" />
public class IntervalsAnyOfDescriptor : IntervalsDescriptorBase<IntervalsAnyOfDescriptor, IIntervalsAnyOf>, IIntervalsAnyOf
{
IEnumerable<IntervalsContainer> IIntervalsAnyOf.Intervals { get; set; }
/// <inheritdoc cref="IIntervalsAnyOf.Intervals" />
public IntervalsAnyOfDescriptor Intervals(Func<IntervalsListDescriptor, IPromise<List<IntervalsContainer>>> selector) =>
Assign(selector, (a, v) => a.Intervals = v.InvokeOrDefault(new IntervalsListDescriptor())?.Value);
}
}
|
||||
TheStack | bdbf19e68e30b96c76a34e4e4033f4bbc0bf387c | C#code:C# | {"size": 511, "ext": "cs", "max_stars_repo_path": "src/Umbraco.Web/Models/ContentEditing/MemberPropertyTypeDisplay.cs", "max_stars_repo_name": "tompipe/Umbraco-CMS", "max_stars_repo_stars_event_min_datetime": "2019-02-11T03:56:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-11T03:56:45.000Z", "max_issues_repo_path": "src/Umbraco.Web/Models/ContentEditing/MemberPropertyTypeDisplay.cs", "max_issues_repo_name": "tompipe/Umbraco-CMS", "max_issues_repo_issues_event_min_datetime": "2021-05-11T23:01:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T09:57:32.000Z", "max_forks_repo_path": "src/Umbraco.Web/Models/ContentEditing/MemberPropertyTypeDisplay.cs", "max_forks_repo_name": "tompipe/Umbraco-CMS", "max_forks_repo_forks_event_min_datetime": "2018-10-09T05:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-09T05:06:00.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 4.0, "max_forks_count": 1.0, "avg_line_length": 28.3888888889, "max_line_length": 64, "alphanum_fraction": 0.6790606654} | using System.Runtime.Serialization;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "propertyType")]
public class MemberPropertyTypeDisplay : PropertyTypeDisplay
{
[DataMember(Name = "showOnMemberProfile")]
public bool MemberCanViewProperty { get; set; }
[DataMember(Name = "memberCanEdit")]
public bool MemberCanEditProperty { get; set; }
[DataMember(Name = "isSensitiveData")]
public bool IsSensitiveData { get; set; }
}
}
|
||||
TheStack | bdbf8c11b9ab927d4ba95e0a609b7c36010c47f7 | C#code:C# | {"size": 214, "ext": "cs", "max_stars_repo_path": "Alsolos.Commons.Wpf/Behaviors/MultiSelectBehavior/IListItemConverter.cs", "max_stars_repo_name": "heinersuter/Alsolos.Commons.Wpf", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Alsolos.Commons.Wpf/Behaviors/MultiSelectBehavior/IListItemConverter.cs", "max_issues_repo_name": "heinersuter/Alsolos.Commons.Wpf", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Alsolos.Commons.Wpf/Behaviors/MultiSelectBehavior/IListItemConverter.cs", "max_forks_repo_name": "heinersuter/Alsolos.Commons.Wpf", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.7777777778, "max_line_length": 59, "alphanum_fraction": 0.7336448598} | namespace Alsolos.Commons.Wpf.Behaviors.MultiselectBehavior
{
public interface IListItemConverter
{
object Convert(object masterListItem);
object ConvertBack(object targetListItem);
}
} |
||||
TheStack | bdc171765cf31afb86d1f73752be788c1c04fd5b | C#code:C# | {"size": 2549, "ext": "cs", "max_stars_repo_path": "src/JwtAuthDemo/Controllers/AuthController.cs", "max_stars_repo_name": "mirusser/Learning-dontNet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/JwtAuthDemo/Controllers/AuthController.cs", "max_issues_repo_name": "mirusser/Learning-dontNet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/JwtAuthDemo/Controllers/AuthController.cs", "max_forks_repo_name": "mirusser/Learning-dontNet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.4459459459, "max_line_length": 130, "alphanum_fraction": 0.6422126324} | using JwtAuthDemo.Models;
using JwtAuthDemo.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace JwtAuthDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly IUserService _userService;
public AuthController(IConfiguration configuration, IUserService userService)
{
_configuration = configuration;
_userService = userService;
}
[AllowAnonymous]
[HttpPost(nameof(Auth))]
public IActionResult Auth([FromBody] LoginModel data)
{
bool isValid = _userService.IsValidUserInformation(data);
if (isValid)
{
var tokenString = GenerateJwtToken(data.UserName);
return Ok(new { Token = tokenString, Message = "Success" });
}
return BadRequest("Please pass the valid Username and Password");
}
[Authorize(AuthenticationSchemes = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)]
[HttpGet(nameof(GetResult))]
public IActionResult GetResult()
{
return Ok("API Validated");
}
/// <summary>
/// Generate JWT Token after successful login.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
private string GenerateJwtToken(string userName)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Jwt:key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("id", userName) }),
Expires = DateTime.UtcNow.AddHours(1),
Issuer = _configuration["Jwt:Issuer"],
Audience = _configuration["Jwt:Audience"],
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
|
||||
TheStack | bdc1fb083c3b0c3dccf579df058f8b88d8d377a7 | C#code:C# | {"size": 561, "ext": "cs", "max_stars_repo_path": "High-Quality_Code/07_Using_Control_Structures/1_TaskOne_Chef.cs", "max_stars_repo_name": "razsilev/TelerikAcademy_Homework", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "High-Quality_Code/07_Using_Control_Structures/1_TaskOne_Chef.cs", "max_issues_repo_name": "razsilev/TelerikAcademy_Homework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "High-Quality_Code/07_Using_Control_Structures/1_TaskOne_Chef.cs", "max_forks_repo_name": "razsilev/TelerikAcademy_Homework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 14.3846153846, "max_line_length": 39, "alphanum_fraction": 0.6363636364} | public class Chef
{
public void Cook()
{
Bowl bowl = GetBowl();
// processing carrot
Carrot carrot = GetCarrot();
var peeledCarrot = Peel(carrot);
var cuttedCarrot = Cut(peeledCarrot);
bowl.Add(cuttedCarrot);
// processing potato
Potato potato = GetPotato();
var peeledPotato = Peel(potato);
var cuttedPotato = Cut(peeledPotato);
bowl.Add(cuttedPotato);
}
private Bowl GetBowl()
{
//...
}
private Potato GetPotato()
{
//...
}
private Carrot GetCarrot()
{
//...
}
private void Cut(Vegetable potato)
{
//...
}
} |
||||
TheStack | bdc3cd4c49d7eef029496ee725c405a85f8bc052 | C#code:C# | {"size": 1767, "ext": "cs", "max_stars_repo_path": "osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs", "max_stars_repo_name": "Malox10/osu", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs", "max_issues_repo_name": "Malox10/osu", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "osu.Game/Graphics/UserInterface/DimmedLoadingLayer.cs", "max_forks_repo_name": "Malox10/osu", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.9491525424, "max_line_length": 111, "alphanum_fraction": 0.5647990945} | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
// blocking scroll can cause weird behaviour when this layer is used within a ScrollContainer.
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
|
||||
TheStack | bdc727e75085fd4283dad881c43672107668c2aa | C#code:C# | {"size": 1466, "ext": "cs", "max_stars_repo_path": "test/AspNetCoreModules.Tests/SampleModule.cs", "max_stars_repo_name": "awesome-inc/AspNetCoreModules", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/AspNetCoreModules.Tests/SampleModule.cs", "max_issues_repo_name": "awesome-inc/AspNetCoreModules", "max_issues_repo_issues_event_min_datetime": "2022-02-25T21:54:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T21:54:32.000Z", "max_forks_repo_path": "test/AspNetCoreModules.Tests/SampleModule.cs", "max_forks_repo_name": "awesome-inc/AspNetCoreModules", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 26.1785714286, "max_line_length": 84, "alphanum_fraction": 0.6712141883} | using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AspNetCoreModules.Tests;
public class SampleModule : AspNetCoreModule
{
private readonly ILogger<SampleModule> _logger;
private readonly SampleSettings _settings;
public SampleModule(SampleSettings settings, ILogger<SampleModule> logger)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public override void ConfigureServices(IServiceCollection services)
{
if (!_settings.Enabled)
{
return;
}
_logger.LogInformation("Configure sample services...");
// TODO
base.ConfigureServices(services);
}
protected override void Load(ContainerBuilder builder)
{
if (!_settings.Enabled)
{
return;
}
_logger.LogInformation("Configure sample...");
base.Load(builder);
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (!_settings.Enabled)
{
return;
}
_logger.LogInformation($"Configure sample app ({env.EnvironmentName})...");
base.Configure(app, env);
}
}
|
||||
TheStack | bdc9280f18d9e1aef35f1634e28f26ee51a46dd0 | C#code:C# | {"size": 1211, "ext": "cs", "max_stars_repo_path": "src/ZLogger.Unity/Assets/Scripts/ZString/Number/FloatEx.cs", "max_stars_repo_name": "sucrose0413/ZLogger", "max_stars_repo_stars_event_min_datetime": "2018-04-03T03:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:40:02.000Z", "max_issues_repo_path": "src/ZLogger.Unity/Assets/Scripts/ZString/Number/FloatEx.cs", "max_issues_repo_name": "sucrose0413/ZLogger", "max_issues_repo_issues_event_min_datetime": "2020-02-04T05:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T00:02:26.000Z", "max_forks_repo_path": "src/ZLogger.Unity/Assets/Scripts/ZString/Number/FloatEx.cs", "max_forks_repo_name": "sucrose0413/ZLogger", "max_forks_repo_forks_event_min_datetime": "2018-04-16T09:27:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T15:21:16.000Z"} | {"max_stars_count": 1835.0, "max_issues_count": 63.0, "max_forks_count": 396.0, "avg_line_length": 27.5227272727, "max_line_length": 68, "alphanum_fraction": 0.6292320396} | using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace System
{
internal static class FloatEx
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsFinite(double d)
{
long bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegative(double d)
{
return BitConverter.DoubleToInt64Bits(d) < 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFinite(float f)
{
int bits = SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) < 0x7F800000;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegative(float f)
{
return SingleToInt32Bits(f) < 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}
}
}
|
||||
TheStack | bdc970ffb9fac900ee0a9b7641c30066b6c7bc91 | C#code:C# | {"size": 593, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/SoundManager.cs", "max_stars_repo_name": "pemoeda08/wave", "max_stars_repo_stars_event_min_datetime": "2019-10-30T14:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:48:44.000Z", "max_issues_repo_path": "Assets/Scripts/SoundManager.cs", "max_issues_repo_name": "Unity3D-Projects/wave", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/SoundManager.cs", "max_forks_repo_name": "Unity3D-Projects/wave", "max_forks_repo_forks_event_min_datetime": "2019-10-30T14:32:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T19:28:17.000Z"} | {"max_stars_count": 27.0, "max_issues_count": null, "max_forks_count": 7.0, "avg_line_length": 19.7666666667, "max_line_length": 47, "alphanum_fraction": 0.5952782462} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : MonoBehaviour
{
public AudioSource efxSource;
public AudioSource musicSource;
public static SoundManager instance = null;
void Awake()
{
if(instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
public void PlaySingle(AudioClip clip)
{
efxSource.clip = clip;
efxSource.Play();
}
}
|
||||
TheStack | bdcc8f54587dc1fc74d625ab2f109f8f4b159427 | C#code:C# | {"size": 3053, "ext": "cs", "max_stars_repo_path": "project/OsEngine/Entity/Portfolio.cs", "max_stars_repo_name": "dakinshin/OsEngine", "max_stars_repo_stars_event_min_datetime": "2017-03-08T08:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T04:55:11.000Z", "max_issues_repo_path": "project/OsEngine/Entity/Portfolio.cs", "max_issues_repo_name": "madfishman333/OsEngine", "max_issues_repo_issues_event_min_datetime": "2017-06-01T11:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T13:47:17.000Z", "max_forks_repo_path": "project/OsEngine/Entity/Portfolio.cs", "max_forks_repo_name": "madfishman333/OsEngine", "max_forks_repo_forks_event_min_datetime": "2017-03-03T12:20:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:08:43.000Z"} | {"max_stars_count": 362.0, "max_issues_count": 44.0, "max_forks_count": 325.0, "avg_line_length": 30.53, "max_line_length": 112, "alphanum_fraction": 0.5623976417} | /*
* Your rights to use code governed by this license http://o-s-a.net/doc/license_simple_engine.pdf
* Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf
*/
using System.Collections.Generic;
namespace OsEngine.Entity
{
/// <summary>
/// portfolio (account) in the trading system and positions opened on this account
/// портфель (счёт) в торговой системе и позиции открытые по этому счёту
/// </summary>
public class Portfolio
{
/// <summary>
/// Account number
/// номер счёта
/// </summary>
public string Number;
/// <summary>
/// deposit at the beginning of the session
/// депозит на счёте на начало сессии
/// </summary>
public decimal ValueBegin;
/// <summary>
/// deposit amount now
/// размер депозита сейчас
/// </summary>
public decimal ValueCurrent;
/// <summary>
/// blocked part of the deposit. And positions and bids
/// блокированная часть депозита. И позициями и заявками
/// </summary>
public decimal ValueBlocked;
/// <summary>
/// session profit
/// профит за сессию
/// </summary>
public decimal Profit;
// then goes the storage of open positions in the system by portfolio
// далее идёт хранилище открытых позиций в системе по портфелю
private List<PositionOnBoard> _positionOnBoard;
/// <summary>
/// take positions on the portfolio in the trading system
/// взять позиции по портфелю в торговой системе
/// </summary>
public List<PositionOnBoard> GetPositionOnBoard()
{
return _positionOnBoard;
}
/// <summary>
/// update the position of the instrument in the trading system
/// обновить позицию по инструменту в торговой системе
/// </summary>
public void SetNewPosition(PositionOnBoard position)
{
if (_positionOnBoard != null && _positionOnBoard.Count != 0)
{
for (int i = 0; i < _positionOnBoard.Count; i ++)
{
if (_positionOnBoard[i].SecurityNameCode == position.SecurityNameCode)
{
_positionOnBoard[i].ValueCurrent = position.ValueCurrent;
_positionOnBoard[i].ValueBlocked = position.ValueBlocked;
return;
}
}
}
if (_positionOnBoard == null)
{
_positionOnBoard = new List<PositionOnBoard>();
}
_positionOnBoard.Add(position);
}
/// <summary>
/// clear all positions on the exchange
/// очистить все позиции на бирже
/// </summary>
public void ClearPositionOnBoard()
{
_positionOnBoard = new List<PositionOnBoard>();
}
}
}
|
||||
TheStack | bdccbafde3281a805109df58c29b385943beba02 | C#code:C# | {"size": 2428, "ext": "cs", "max_stars_repo_path": "Assets/_Project/Misadventure/Items/TileEffectComponent.cs", "max_stars_repo_name": "EuleMitKeule/misadventure", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/_Project/Misadventure/Items/TileEffectComponent.cs", "max_issues_repo_name": "EuleMitKeule/misadventure", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/_Project/Misadventure/Items/TileEffectComponent.cs", "max_forks_repo_name": "EuleMitKeule/misadventure", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.9473684211, "max_line_length": 108, "alphanum_fraction": 0.6021416804} | using System.Collections;
using System.Collections.Generic;
using Misadventure.Level;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace Misadventure.Items
{
public class TileEffectComponent : MonoBehaviour
{
[SerializeField] float tileDuration;
[SerializeField] [MinMaxSlider(0, "tileDuration")] Vector2 tileDurationOffset;
[SerializeField] public List<ConsumableItemData> itemEffects;
Tilemap Tilemap { get; set; }
void Awake()
{
Tilemap = GetComponent<Tilemap>();
GameComponent.LevelLoaded += OnLevelLoaded;
GameComponent.LevelUnloaded += OnLevelUnloaded;
}
private void OnLevelUnloaded(object sender, LevelEventArgs e)
{
// Tilemap.tilemapTileChanged -= OnTileChanged;
GameComponent.LevelLoaded -= OnLevelLoaded;
GameComponent.LevelUnloaded -= OnLevelUnloaded;
}
private void OnLevelLoaded(object sender, LevelEventArgs e)
{
if (e.IsMenu) return;
// Tilemap.tilemapTileChanged += OnTileChanged;
}
// void OnTileChanged(Tilemap tilemap, Tilemap.SyncTile[] tiles)
// {
// if (Tilemap != tilemap) return;
// foreach (var tile in tiles)
// {
// StartCoroutine(DestroyTile(tile.position));
// }
// }
public void SetTile(Vector3Int position, TileBase tile)
{
Tilemap.SetTile(position, tile);
StartCoroutine(DestroyTile(position));
}
IEnumerator DestroyTile(Vector3Int pos)
{
var durationOffset = UnityEngine.Random.Range(tileDurationOffset.x, tileDurationOffset.y);
var duration = tileDuration + (UnityEngine.Random.Range(0, 1) < 0.5f ? 1 : -1) * durationOffset;
yield return new WaitForSeconds(duration);
Tilemap.SetTile(pos, null);
}
void OnTriggerEnter2D(Collider2D other)
{
if (!other.gameObject.layer.IsPlayer()) return;
var itemPickupComponent = other.GetComponent<ItemPickupComponent>();
if (!itemPickupComponent) return;
foreach (var itemEffect in itemEffects)
{
itemPickupComponent.ConsumeItem(itemEffect);
}
}
}
} |
||||
TheStack | bdcd10332f104dfe0094ae4956d86e98574d91f4 | C#code:C# | {"size": 1995, "ext": "cs", "max_stars_repo_path": "Mefistofeles.Repositories/DTO/Match.cs", "max_stars_repo_name": "jslonim/SeleniumBettingBot", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mefistofeles.Repositories/DTO/Match.cs", "max_issues_repo_name": "jslonim/SeleniumBettingBot", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mefistofeles.Repositories/DTO/Match.cs", "max_forks_repo_name": "jslonim/SeleniumBettingBot", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.3287671233, "max_line_length": 165, "alphanum_fraction": 0.5172932331} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repositories.DTO
{
public class Match
{
public Int64 Id { get; set; }
public Team Local { get; set; }
public Team Road { get; set; }
public DateTime MatchDttm { get; set; }
public double TieOdds {get;set;}
public string Pick { get; set; }
public string Expert { get; set; }
public string Sport { get; set; }
public string Result { get; set; }
public bool AfterTime { get; set; }
public Match()
{
}
public Match(Team local, Team road, DateTime matchDttm, double tieOdds = 0)
{
Id = Id;
Local = local;
Road = road;
MatchDttm = matchDttm;
TieOdds = tieOdds;
}
public Match(Int64 id, Team local, Team road, DateTime matchDttm, double tieOdds = 0)
{
Id = Id;
Local = local;
Road = road;
MatchDttm = matchDttm;
TieOdds = tieOdds;
}
public Match(Int64 id, Team local, Team road, DateTime matchDttm, string pick, string expert, string sport, double tieOdds = 0)
{
Id = Id;
Local = local;
Road = road;
MatchDttm = matchDttm;
TieOdds = tieOdds;
Pick = pick;
Expert = expert;
Sport = sport;
}
public Match(Int64 id, Team local, Team road, DateTime matchDttm, string pick, string expert, string sport, string result,bool afterTime, double tieOdds = 0)
{
Id = Id;
Local = local;
Road = road;
MatchDttm = matchDttm;
TieOdds = tieOdds;
Pick = pick;
Expert = expert;
Sport = sport;
Result = result;
AfterTime = afterTime;
}
}
}
|
||||
TheStack | bdcd31ec3f4b7e82318c67a73dea81c07e1ebd46 | C#code:C# | {"size": 1058, "ext": "cs", "max_stars_repo_path": "edrawings-api/eDrawingsWinFormsHost/eDrawingsWinFormsHost/EDrawingsHost.cs", "max_stars_repo_name": "codestackdev/swex-examples", "max_stars_repo_stars_event_min_datetime": "2019-08-14T08:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T13:38:48.000Z", "max_issues_repo_path": "edrawings-api/eDrawingsWinFormsHost/eDrawingsWinFormsHost/EDrawingsHost.cs", "max_issues_repo_name": "codestackdev/swex-examples", "max_issues_repo_issues_event_min_datetime": "2020-05-08T10:12:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T06:52:40.000Z", "max_forks_repo_path": "edrawings-api/eDrawingsWinFormsHost/eDrawingsWinFormsHost/EDrawingsHost.cs", "max_forks_repo_name": "codestackdev/swex-examples", "max_forks_repo_forks_event_min_datetime": "2019-08-12T07:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T23:45:34.000Z"} | {"max_stars_count": 17.0, "max_issues_count": 2.0, "max_forks_count": 38.0, "avg_line_length": 27.8421052632, "max_line_length": 91, "alphanum_fraction": 0.6124763705} | //**********************
//Hosting eDrawings control in Windows Forms
//Copyright(C) 2019 www.codestack.net
//License: https://github.com/codestack-net-dev/solidworks-api-examples/blob/master/LICENSE
//Product URL: https://www.codestack.net/edrawings-api/gettings-started/winforms/
//**********************
using eDrawings.Interop.EModelViewControl;
using System;
using System.Windows.Forms;
namespace CodeStack.Examples.eDrawingsApi
{
public class EDrawingsHost : AxHost
{
public event Action<EModelViewControl> ControlLoaded;
private bool m_IsLoaded;
public EDrawingsHost() : base("22945A69-1191-4DCF-9E6F-409BDE94D101")
{
m_IsLoaded = false;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
if (!m_IsLoaded)
{
m_IsLoaded = true;
var ctrl = this.GetOcx() as EModelViewControl;
ControlLoaded?.Invoke(this.GetOcx() as EModelViewControl);
}
}
}
}
|
||||
TheStack | bdcd9a72ad9f3215770d7cdef5f7cbac5d6db5fa | C#code:C# | {"size": 412, "ext": "cs", "max_stars_repo_path": "Assets/DrawSceneLine.cs", "max_stars_repo_name": "kokaterimon/Juego-de-Plataformas-", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/DrawSceneLine.cs", "max_issues_repo_name": "kokaterimon/Juego-de-Plataformas-", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/DrawSceneLine.cs", "max_forks_repo_name": "kokaterimon/Juego-de-Plataformas-", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.6842105263, "max_line_length": 47, "alphanum_fraction": 0.7233009709} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawSceneLine : MonoBehaviour {
public Transform from;
public Transform to;
void OnDrawGizmosSelected(){
if (from != null && to != null){
Gizmos.color = Color.cyan;
Gizmos.DrawLine(from.position, to.position);
Gizmos.DrawSphere(from.position, 0.15f);
Gizmos.DrawSphere(to.position, 0.15f);
}
}
}
|
||||
TheStack | bdcf4f83b9a086789d67b1f398d3353d5c038345 | C#code:C# | {"size": 968, "ext": "cs", "max_stars_repo_path": "KNetFramework/Network/Packets/PacketLogItem.cs", "max_stars_repo_name": "Kahath/KNet", "max_stars_repo_stars_event_min_datetime": "2017-10-13T11:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-15T16:37:32.000Z", "max_issues_repo_path": "KNetFramework/Network/Packets/PacketLogItem.cs", "max_issues_repo_name": "Kahath/Framework", "max_issues_repo_issues_event_min_datetime": "2018-01-31T22:15:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-31T22:24:59.000Z", "max_forks_repo_path": "KNetFramework/Network/Packets/PacketLogItem.cs", "max_forks_repo_name": "Kahath/KNet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": 4.0, "max_forks_count": null, "avg_line_length": 16.406779661, "max_line_length": 98, "alphanum_fraction": 0.7179752066} | /*
* Copyright © Kahath 2015
* Licensed under MIT license.
*/
using KNetFramework.Enums;
using KNetFramework.Network.Session;
namespace KNetFramework.Network.Packets
{
internal class PacketLogItem
{
#region Fields
private Client _client;
private PacketHeader _packetHeader;
private byte[] _packetMessage;
private PacketLogTypes _packetLogType;
#endregion
#region Properties
internal Client Client
{
get { return _client; }
}
internal PacketHeader PacketHeader
{
get { return _packetHeader; }
}
internal byte[] PacketMessage
{
get { return _packetMessage; }
}
internal PacketLogTypes PacketLogType
{
get { return _packetLogType; }
}
#endregion
#region Constructors
public PacketLogItem(Client client, PacketHeader header, byte[] message, PacketLogTypes logtype)
{
_client = client;
_packetHeader = header;
_packetMessage = message;
_packetLogType = logtype;
}
#endregion
}
}
|
||||
TheStack | bdd0f12124b9a42cad27f305c6db5c456dae6860 | C#code:C# | {"size": 1545, "ext": "cshtml", "max_stars_repo_path": "GaragemGestao/GaragemGestao/Views/Repairs/AddVehicle.cshtml", "max_stars_repo_name": "Andresp2018/GaragemGestao", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GaragemGestao/GaragemGestao/Views/Repairs/AddVehicle.cshtml", "max_issues_repo_name": "Andresp2018/GaragemGestao", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GaragemGestao/GaragemGestao/Views/Repairs/AddVehicle.cshtml", "max_forks_repo_name": "Andresp2018/GaragemGestao", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.5869565217, "max_line_length": 101, "alphanum_fraction": 0.5540453074} | @model GaragemGestao.Models.AddVehicleViewModel
@{
ViewData["Title"] = "AddVehicle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add Vehicle</h2>
<h4>To Order</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="AddVehicle">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="VehicleId" class="control-label"></label>
<select asp-for="VehicleId" asp-items="Model.Vehicles" class="form-control"></select>
<span asp-validation-for="VehicleId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Quantity" class="control-label"></label>
<input asp-for="Quantity" class="form-control" />
<span asp-validation-for="Quantity" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Issue" class="control-label"></label>
<input asp-for="Issue" class="form-control" />
<span asp-validation-for="Issue" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
<a asp-action="Index" class="btn btn-success">Back to List</a>
</div>
</form>
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
|
||||
TheStack | bdd143f5b409c96bc048e32cc81c42b6918691d7 | C#code:C# | {"size": 2456, "ext": "cs", "max_stars_repo_path": "WyvernFramework/Demos/ImageEffects/ClearEffect.cs", "max_stars_repo_name": "DarkKitsune/WyvernFramework", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WyvernFramework/Demos/ImageEffects/ClearEffect.cs", "max_issues_repo_name": "DarkKitsune/WyvernFramework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WyvernFramework/Demos/ImageEffects/ClearEffect.cs", "max_forks_repo_name": "DarkKitsune/WyvernFramework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.3157894737, "max_line_length": 99, "alphanum_fraction": 0.5052931596} | using VulkanCore;
using WyvernFramework;
using System.IO;
using System.Collections.Generic;
namespace Demos.GraphicalEffect
{
public class ClearEffect : ImageEffect
{
private ClearColorValue _clearColor = new ClearColorValue(1f, 1f, 1f, 1f);
/// <summary>
/// Color to clear with
/// </summary>
public ClearColorValue ClearColor
{
get { return _clearColor; }
set
{
_clearColor = value;
Refresh();
}
}
public ClearEffect(Graphics graphics, RenderPassObject renderPass)
: base(
nameof(TriangleTestEffect), graphics,
ImageLayout.TransferDstOptimal, Accesses.TransferWrite, PipelineStages.Transfer
)
{
}
public override void OnStart()
{
}
protected override void OnRecordCommandBuffer(VKImage image, CommandBuffer buffer)
{
// Begin recording
buffer.Begin(new CommandBufferBeginInfo());
// Write commands
buffer.CmdPipelineBarrier(
srcStageMask: InitialStage,
dstStageMask: PipelineStages.Transfer,
imageMemoryBarriers: new ImageMemoryBarrier[]
{
new ImageMemoryBarrier(
image: image.Image,
subresourceRange: image.SubresourceRange,
srcAccessMask: InitialAccess,
dstAccessMask: Accesses.TransferWrite,
oldLayout: InitialLayout,
newLayout: ImageLayout.TransferDstOptimal
)
}
);
buffer.CmdClearColorImage(
image.Image,
ImageLayout.TransferDstOptimal,
ClearColor,
image.SubresourceRange
);
// Finish recording
buffer.End();
}
public override void OnDraw(Semaphore start, VKImage image)
{
// Submit the command buffer
Graphics.TransferQueueFamily.First.Submit(
start, PipelineStages.Transfer, GetCommandBuffer(image), FinishedSemaphore
);
}
}
}
|
||||
TheStack | bdd389d18360a015e6ff53fa0b5b89e16def0932 | C#code:C# | {"size": 15860, "ext": "cs", "max_stars_repo_path": "src/Boleto.Net/Banco/Banco_Semear.cs", "max_stars_repo_name": "adrbarros/boletonet", "max_stars_repo_stars_event_min_datetime": "2015-01-22T11:32:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T18:59:48.000Z", "max_issues_repo_path": "src/Boleto.Net/Banco/Banco_Semear.cs", "max_issues_repo_name": "adrbarros/boletonet", "max_issues_repo_issues_event_min_datetime": "2015-01-22T21:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T17:08:30.000Z", "max_forks_repo_path": "src/Boleto.Net/Banco/Banco_Semear.cs", "max_forks_repo_name": "adrbarros/boletonet", "max_forks_repo_forks_event_min_datetime": "2015-01-20T21:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T18:13:24.000Z"} | {"max_stars_count": 474.0, "max_issues_count": 645.0, "max_forks_count": 551.0, "avg_line_length": 45.5747126437, "max_line_length": 229, "alphanum_fraction": 0.5698612863} | using BoletoNet.Util;
using System;
using System.Web.UI;
[assembly: WebResource("BoletoNet.Imagens.743.jpg", "image/jpeg")]
namespace BoletoNet
{
/// <author>
/// Eduardo Frare
/// Stiven
/// </author>
internal class Banco_Semear : AbstractBanco, IBanco
{
private string _dacNossoNumero = string.Empty;
private int _dacBoleto = 0;
/// <summary>
/// Classe responsavel em criar os campos do Banco Banco_Semear.
/// </summary>
internal Banco_Semear()
{
this.Codigo = 743;
this.Digito = "9";
this.Nome = "Semear";
}
/// <summary>
/// Calcula o digito do Nosso Numero
/// </summary>
public string CalcularDigitoNossoNumero(Boleto boleto)
{
return Mod11Semear(boleto.NossoNumero, 9);
}
#region IBanco Members
/// <summary>
/// A linha digitável será composta por cinco campos:
/// 1º campo
/// composto pelo código de Banco, código da moeda, as cinco primeiras posições do campo
/// livre e o dígito verificador deste campo;
/// 2º campo
/// composto pelas posições 6ª a 15ª do campo livre e o dígito verificador deste campo;
/// 3º campo
/// composto pelas posições 16ª a 25ª do campo livre e o dígito verificador deste campo;
/// 4º campo
/// composto pelo dígito verificador do código de barras, ou seja, a 5ª posição do código de
/// barras;
/// 5º campo
/// Composto pelo fator de vencimento com 4(quatro) caracteres e o valor do documento com 10(dez) caracteres, sem separadores e sem edição.
/// </summary>
public override void FormataLinhaDigitavel(Boleto boleto)
{
var campoLivre = FormataCampoLivre(boleto);
#region Campo 1
string Grupo1 = string.Empty;
string banco = Codigo.ToString();
int moeda = boleto.Moeda;
string primeiras5PosicoesCampoLivre = campoLivre.Substring(0, 5);
int digitoVerificadorCampo1 = Mod10(banco + moeda + primeiras5PosicoesCampoLivre);
Grupo1 = string.Format("{0}{1}{2}.{3}{4} ", banco, moeda, campoLivre.Substring(0, 1), campoLivre.Substring(1, 4), digitoVerificadorCampo1);
#endregion Campo 1
#region Campo 2
string Grupo2 = campoLivre.Substring(5, 10);
int D2 = Mod10(Grupo2);
Grupo2 = string.Format("{0}.{1}{2} ", Grupo2.Substring(0, 5), Grupo2.Substring(5, 5), D2);
#endregion Campo 2
#region Campo 3
string Grupo3 = campoLivre.Substring(15, 9) + boleto.Cedente.ContaBancaria.DigitoConta;
int D3 = Mod10(Grupo3);
Grupo3 = string.Format("{0}.{1}{2} ", Grupo3.Substring(0, 5), Grupo3.Substring(5, 5), D3);
#endregion Campo 3
#region Campo 4
string Grupo4 = string.Empty;
Grupo4 = string.Format("{0} ", boleto.CodigoBarra.DigitoVerificador);
#endregion Campo 4
#region Campo 5
string Grupo5 = string.Empty;
string fatorVencimento = FatorVencimento(boleto).ToString();
string valorFormatado = boleto.ValorCodBarra.ToString("N2").Replace(",", "").Replace(".", "");
valorFormatado = Utils.FormatCode(valorFormatado, 10);
Grupo5 = string.Format("{0}{1}", fatorVencimento, valorFormatado);
#endregion Campo 5
boleto.CodigoBarra.LinhaDigitavel = Grupo1 + Grupo2 + Grupo3 + Grupo4 + Grupo5;
}
/// <summary>
///
/// *******
///
/// O código de barra para cobrança contém 44 posições dispostas da seguinte forma:
/// 01 a 03 - 3 - Identificação do Banco
/// 04 a 04 - 1 - Código da Moeda
/// 05 a 05 – 1 - Dígito verificador do Código de Barras
/// 06 a 09 - 4 - Fator de vencimento
/// 10 a 19 - 10 - Valor
/// 20 a 43 – 24 - Campo Livre
/// 44 a 44 - 1 - Digito 0
/// *******
/// </summary>
///
public override void FormataCodigoBarra(Boleto boleto)
{
var valorBoleto = boleto.ValorCodBarra.ToString("N2").Replace(",", "").Replace(".", "");
valorBoleto = Utils.FormatCode(valorBoleto, 10);
if (boleto.Carteira == "02") // Com registro
{
boleto.CodigoBarra.Codigo = string.Format("{0}{1}{2}{3}{4}0", Codigo.ToString(), boleto.Moeda,
FatorVencimento(boleto), valorBoleto, FormataCampoLivre(boleto));
}
else
{
throw new NotImplementedException("Carteira ainda não implementada.");
}
_dacBoleto = Mod11(boleto.CodigoBarra.Codigo, 9);
boleto.CodigoBarra.Codigo = Strings.Left(boleto.CodigoBarra.Codigo, 4) + _dacBoleto + Strings.Right(boleto.CodigoBarra.Codigo, 39);
}
///<summary>
/// Campo Livre
/// 20 a 23 - 4 - Agência Cedente (Sem o digito verificador,completar com zeros a esquerda quandonecessário)
/// 24 a 25 - 2 - Carteira
/// 26 a 36 - 11 - Número do Nosso Número(Sem o digito verificador)
/// 37 a 43 - 7 - Conta do Cedente (Sem o digito verificador,completar com zeros a esquerda quando necessário)
/// 44 a 44 - 1 - Zero
///</summary>
public string FormataCampoLivre(Boleto boleto)
{
var agencia = boleto.Cedente.ContaBancaria.Agencia.PadLeft(4, '0');
var carteira = boleto.Carteira;
var nossoNumero = boleto.NossoNumero.Split('-')[0];
var conta = boleto.Cedente.ContaBancaria.Conta.PadLeft(7, '0');
string FormataCampoLivre = string.Format("{0}{1}{2}{3}", agencia, carteira, nossoNumero, conta);
return FormataCampoLivre;
}
public override void FormataNumeroDocumento(Boleto boleto)
{
throw new NotImplementedException("Função ainda não implementada.");
}
public override void FormataNossoNumero(Boleto boleto)
{
boleto.DigitoNossoNumero = Mod11Semear(boleto.NossoNumero, 9);
boleto.NossoNumero = string.Format("{0}-{1}", boleto.NossoNumero, boleto.DigitoNossoNumero);
}
public override string GerarHeaderRemessa(string numeroConvenio, Cedente cedente, TipoArquivo tipoArquivo, int numeroArquivoRemessa, Boleto boletos)
{
throw new NotImplementedException("Função não implementada.");
}
public override void ValidaBoleto(Boleto boleto)
{
if (boleto.Carteira != "02" && boleto.Carteira != "03" && boleto.Carteira != "06" && boleto.Carteira != "09" && boleto.Carteira != "16" && boleto.Carteira != "19" && boleto.Carteira != "25" && boleto.Carteira != "26")
throw new NotImplementedException("Carteira não implementada. Carteiras implementadas 02, 03, 06, 09, 16, 19, 25, 26.");
//O valor é obrigatório para a carteira 03
if (boleto.Carteira == "03")
{
if (boleto.ValorBoleto == 0)
throw new NotImplementedException("Para a carteira 03, o valor do boleto não pode ser igual a zero");
}
//O valor é obrigatório para a carteira 09
if (boleto.Carteira == "09")
{
if (boleto.ValorBoleto == 0)
throw new NotImplementedException("Para a carteira 09, o valor do boleto não pode ser igual a zero");
}
//else if (boleto.Carteira == "06")
//{
// boleto.ValorBoleto = 0;
//}
//Verifica se o nosso número é válido
if (boleto.NossoNumero.Length > 11)
{
boleto.NossoNumero = boleto.NossoNumero.Substring(0, 11);
}
else if (boleto.NossoNumero.Length < 11)
boleto.NossoNumero = Utils.FormatCode(boleto.NossoNumero, 11);
//Verificar se a Agencia esta correta
if (boleto.Cedente.ContaBancaria.Agencia.Length > 4)
throw new NotImplementedException("A quantidade de dígitos da Agência " + boleto.Cedente.ContaBancaria.Agencia + ", são de 4 números.");
else if (boleto.Cedente.ContaBancaria.Agencia.Length < 4)
boleto.Cedente.ContaBancaria.Agencia = Utils.FormatCode(boleto.Cedente.ContaBancaria.Agencia, 4);
//Verificar se a Conta esta correta
if (boleto.Cedente.ContaBancaria.Conta.Length > 7)
throw new NotImplementedException("A quantidade de dígitos da Conta " + boleto.Cedente.ContaBancaria.Conta + ", são de 07 números.");
else if (boleto.Cedente.ContaBancaria.Conta.Length < 7)
boleto.Cedente.ContaBancaria.Conta = Utils.FormatCode(boleto.Cedente.ContaBancaria.Conta, 7);
//Verifica se data do processamento é valida
//if (boleto.DataProcessamento.ToString("dd/MM/yyyy") == "01/01/0001")
if (boleto.DataProcessamento == DateTime.MinValue) // diegomodolo ([email protected])
boleto.DataProcessamento = DateTime.Now;
//Verifica se data do documento é valida
//if (boleto.DataDocumento.ToString("dd/MM/yyyy") == "01/01/0001")
if (boleto.DataDocumento == DateTime.MinValue) // diegomodolo ([email protected])
boleto.DataDocumento = DateTime.Now;
boleto.QuantidadeMoeda = 0;
// Atribui o nome do banco ao local de pagamento
if (string.IsNullOrEmpty(boleto.LocalPagamento))
boleto.LocalPagamento = "PAGÁVEL PREFERENCIALMENTE NAS AGÊNCIAS DO BRADESCO";
else if (boleto.LocalPagamento == "Até o vencimento, preferencialmente no ")
boleto.LocalPagamento += Nome;
// Calcula o DAC do Nosso Número
_dacNossoNumero = CalcularDigitoNossoNumero(boleto);
boleto.DigitoNossoNumero = _dacNossoNumero;
FormataCodigoBarra(boleto);
FormataLinhaDigitavel(boleto);
FormataNossoNumero(boleto);
}
#endregion IBanco Members
private string Mod11Semear(string seq, int b)
{
int s = 0, p = 2;
for (int i = seq.Length; i > 0; i--)
{
s = s + (Convert.ToInt32(seq.Mid(i, 1)) * p);
if (p == b)
p = 2;
else
p = p + 1;
}
int r = (s % 11);
if (r == 0)
return "0";
else if (r == 1)
return "P";
else
return (11 - r).ToString();
}
public string GerarRegistroDetalhe9(Boleto boleto, int numeroRegistro)
{
string _detalhe = "";
_detalhe += "2"; // 001 a 001 Tipo Registro
_detalhe += new string(' ', 320); // 002 a 321 Mensagens 1,2,3,4
if (boleto.DataOutrosDescontos == DateTime.MinValue) // 322 a 327 Data limite para concessão de Desconto 2
{
_detalhe += "000000"; //Caso nao tenha data de vencimento
}
else
{
_detalhe += boleto.DataOutrosDescontos.ToString("ddMMyy");
}
// 328 a 340 Valor do Desconto 2
_detalhe += Utils.FitStringLength(boleto.OutrosDescontos.ToString("0.00").Replace(",", ""), 13, 13, '0', 0, true, true, true);
_detalhe += "000000"; // 341 a 346 ata limite para concessão de Desconto 3
// 347 a 359 Valor do Desconto 3
_detalhe += Utils.FitStringLength("", 13, 13, '0', 0, true, true, true);
_detalhe += new string(' ', 7); // 360 a 366 Filler
_detalhe += Utils.FitStringLength(boleto.Carteira, 3, 3, '0', 0, true, true, true); // 367 a 369 Nº da Carteira
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.Agencia, 5, 5, '0', 0, true, true, true); // 370 a 374 N da agencia(5)
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.Conta, 7, 7, '0', 0, true, true, true); // 375 a 381 Conta Corrente(7)
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.DigitoConta, 1, 1, '0', 0, true, true, true);// 382 a 382 D da conta(1)
_detalhe += Utils.FitStringLength(boleto.NossoNumero, 11, 11, '0', 0, true, true, true); // 383 a 393 Nosso Número (11)
// Força o NossoNumero a ter 11 dígitos. Alterado por Luiz Ponce 07/07/2012
_detalhe += Mod11Semear(boleto.Carteira + Utils.FitStringLength(boleto.NossoNumero, 11, 11, '0', 0, true, true, true), 7); // 394 a 394 Digito de Auto Conferencia do Nosso Número (01)
//Desconto Bonificação por dia (10, N)
_detalhe += Utils.FitStringLength(numeroRegistro.ToString(), 6, 6, '0', 0, true, true, true); // 395 a 400
//Retorno
return Utils.SubstituiCaracteresEspeciais(_detalhe);
}
public string GerarRegistroDetalhe2(Boleto boleto, int numeroRegistro)
{
string _detalhe = "";
_detalhe += "9"; // 001 a 001 Tipo Registro
_detalhe += new string(' ', 320); // 002 a 321 Mensagens 1,2,3,4
if (boleto.DataOutrosDescontos == DateTime.MinValue) // 322 a 327 Data limite para concessão de Desconto 2
{
_detalhe += "000000"; //Caso nao tenha data de vencimento
}
else
{
_detalhe += boleto.DataOutrosDescontos.ToString("ddMMyy");
}
// 328 a 340 Valor do Desconto 2
_detalhe += Utils.FitStringLength(boleto.OutrosDescontos.ToString("0.00").Replace(",", ""), 13, 13, '0', 0, true, true, true);
_detalhe += "000000"; // 341 a 346 ata limite para concessão de Desconto 3
// 347 a 359 Valor do Desconto 3
_detalhe += Utils.FitStringLength("", 13, 13, '0', 0, true, true, true);
_detalhe += new string(' ', 7); // 360 a 366 Filler
_detalhe += Utils.FitStringLength(boleto.Carteira, 3, 3, '0', 0, true, true, true); // 367 a 369 Nº da Carteira
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.Agencia, 5, 5, '0', 0, true, true, true); // 370 a 374 N da agencia(5)
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.Conta, 7, 7, '0', 0, true, true, true); // 375 a 381 Conta Corrente(7)
_detalhe += Utils.FitStringLength(boleto.Cedente.ContaBancaria.DigitoConta, 1, 1, '0', 0, true, true, true);// 382 a 382 D da conta(1)
_detalhe += Utils.FitStringLength(boleto.NossoNumero, 11, 11, ' ', 0, true, true, true); // 383 a 393 Nosso Número (11)
// Força o NossoNumero a ter 11 dígitos. Alterado por Luiz Ponce 07/07/2012
_detalhe += Mod11Semear(boleto.Carteira + Utils.FitStringLength(boleto.NossoNumero, 11, 11, '0', 0, true, true, true), 7); // 394 a 394 Digito de Auto Conferencia do Nosso Número (01)
//Desconto Bonificação por dia (10, N)
_detalhe += Utils.FitStringLength(numeroRegistro.ToString(), 6, 6, '0', 0, true, true, true); // 395 a 400
//Retorno
return Utils.SubstituiCaracteresEspeciais(_detalhe);
}
}
} |
||||
TheStack | bdd6fb8d34c42f382d845f86d8bba3e32ca8692a | C#code:C# | {"size": 222, "ext": "cs", "max_stars_repo_path": "TMDB.Core/API/V3/Models/Networks/AlternativeNetworkNamesRequest.cs", "max_stars_repo_name": "JeremiSharkboy/TMDb.Client", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TMDB.Core/API/V3/Models/Networks/AlternativeNetworkNamesRequest.cs", "max_issues_repo_name": "JeremiSharkboy/TMDb.Client", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TMDB.Core/API/V3/Models/Networks/AlternativeNetworkNamesRequest.cs", "max_forks_repo_name": "JeremiSharkboy/TMDb.Client", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.6666666667, "max_line_length": 69, "alphanum_fraction": 0.7522522523} | using TMDB.Core.Attributes;
namespace TMDB.Core.Api.V3.Models.Networks
{
[ApiGetEndpoint("/network/{network_id}/alternative_names")]
public class AlternativeNetworkNamesRequest : NetworksBaseRequest
{
}
} |
||||
TheStack | bdd7a0b4b6a38af54cde53c8da9ef01b2a16a8fb | C#code:C# | {"size": 16144, "ext": "cs", "max_stars_repo_path": "WWCP_OCPPv2.0/DataTypes/Complex/MessageContent.cs", "max_stars_repo_name": "OpenChargingCloud/WWCP_", "max_stars_repo_stars_event_min_datetime": "2017-01-19T03:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T03:28:54.000Z", "max_issues_repo_path": "WWCP_OCPPv2.0/DataTypes/Complex/MessageContent.cs", "max_issues_repo_name": "OpenChargingCloud/WWCP_", "max_issues_repo_issues_event_min_datetime": "2017-07-07T15:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T09:47:21.000Z", "max_forks_repo_path": "WWCP_OCPPv2.0/DataTypes/Complex/MessageContent.cs", "max_forks_repo_name": "OpenChargingCloud/WWCP_", "max_forks_repo_forks_event_min_datetime": "2017-01-19T03:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T22:48:27.000Z"} | {"max_stars_count": 21.0, "max_issues_count": 5.0, "max_forks_count": 18.0, "avg_line_length": 34.05907173, "max_line_length": 225, "alphanum_fraction": 0.5102205154} | /*
* Copyright (c) 2014-2021 GraphDefined GmbH
* This file is part of WWCP OCPP <https://github.com/OpenChargingCloud/WWCP_OCPP>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Usings
using System;
using Newtonsoft.Json.Linq;
using org.GraphDefined.Vanaheimr.Illias;
using org.GraphDefined.Vanaheimr.Hermod.JSON;
#endregion
namespace cloud.charging.open.protocols.OCPPv2_0
{
/// <summary>
/// A message to be displayed at a charging station.
/// </summary>
public class MessageContent
{
#region Properties
/// <summary>
/// The message content. 512
/// </summary>
public String Content { get; }
/// <summary>
/// The message language identifier, as defined in rfc5646.
/// </summary>
public Language_Id Language { get; }
/// <summary>
/// The message format.
/// </summary>
public MessageFormats Format { get; }
/// <summary>
/// An optional custom data object to allow to store any kind of customer specific data.
/// </summary>
public CustomData CustomData { get; }
#endregion
#region Constructor(s)
/// <summary>
/// Create a new message to be displayed at a charging station.
/// </summary>
/// <param name="Content">The message content.</param>
/// <param name="Language">The message language identifier, as defined in rfc5646.</param>
/// <param name="Format">The message format.</param>
/// <param name="CustomData">An optional custom data object to allow to store any kind of customer specific data.</param>
public MessageContent(String Content,
Language_Id Language,
MessageFormats Format,
CustomData CustomData = null)
{
this.Content = Content?.Trim();
this.Language = Language;
this.Format = Format;
this.CustomData = CustomData;
if (this.Content.IsNullOrEmpty())
throw new ArgumentNullException(nameof(Content), "The given message content must not be null or empty!");
}
#endregion
#region Documentation
// {
// "$schema": "http://json-schema.org/draft-06/schema#",
// "$id": "urn:OCPP:Cp:2:2020:3:MessageContentType",
// "comment": "OCPP 2.0.1 FINAL",
// "description": "Message_ Content\r\nurn:x-enexis:ecdm:uid:2:234490\r\nContains message details, for a message to be displayed on a Charging Station.\r\n\r\n",
// "javaType": "MessageContent",
// "type": "object",
// "additionalProperties": false,
// "properties": {
// "customData": {
// "$ref": "#/definitions/CustomDataType"
// },
// "format": {
// "$ref": "#/definitions/MessageFormatEnumType"
// },
// "language": {
// "description": "Message_ Content. Language. Language_ Code\r\nurn:x-enexis:ecdm:uid:1:570849\r\nMessage language identifier. Contains a language code as defined in <<ref-RFC5646,[RFC5646]>>.\r\n",
// "type": "string",
// "maxLength": 8
// },
// "content": {
// "description": "Message_ Content. Content. Message\r\nurn:x-enexis:ecdm:uid:1:570852\r\nMessage contents.\r\n\r\n",
// "type": "string",
// "maxLength": 512
// }
// },
// "required": [
// "format",
// "content"
// ]
// }
#endregion
#region (static) Parse (MessageContentJSON, OnException = null)
/// <summary>
/// Parse the given JSON representation of a message content.
/// </summary>
/// <param name="MessageContentJSON">The JSON to be parsed.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static MessageContent Parse(JObject MessageContentJSON,
OnExceptionDelegate OnException = null)
{
if (TryParse(MessageContentJSON,
out MessageContent modem,
OnException))
{
return modem;
}
return default;
}
#endregion
#region (static) Parse (MessageContentText, OnException = null)
/// <summary>
/// Parse the given text representation of a message content.
/// </summary>
/// <param name="MessageContentText">The text to be parsed.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static MessageContent Parse(String MessageContentText,
OnExceptionDelegate OnException = null)
{
if (TryParse(MessageContentText,
out MessageContent modem,
OnException))
{
return modem;
}
return default;
}
#endregion
#region (static) TryParse(MessageContentJSON, out MessageContent, OnException = null)
/// <summary>
/// Try to parse the given JSON representation of a message content.
/// </summary>
/// <param name="MessageContentJSON">The JSON to be parsed.</param>
/// <param name="MessageContent">The parsed connector type.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static Boolean TryParse(JObject MessageContentJSON,
out MessageContent MessageContent,
OnExceptionDelegate OnException = null)
{
try
{
MessageContent = default;
#region Content
if (!MessageContentJSON.ParseMandatoryText("content",
"message content",
out String Content,
out String ErrorResponse))
{
return false;
}
#endregion
#region Language
if (!MessageContentJSON.MapMandatory("language",
"message language",
Language_Id.Parse,
out Language_Id Language,
out ErrorResponse))
{
return false;
}
#endregion
#region Format
if (!MessageContentJSON.MapMandatory("format",
"message format",
MessageFormatsExtentions.Parse,
out MessageFormats Format,
out ErrorResponse))
{
return false;
}
#endregion
#region CustomData
if (MessageContentJSON.ParseOptionalJSON("customData",
"custom data",
OCPPv2_0.CustomData.TryParse,
out CustomData CustomData,
out ErrorResponse))
{
if (ErrorResponse != null)
return false;
}
#endregion
MessageContent = new MessageContent(Content.Trim(),
Language,
Format,
CustomData);
return true;
}
catch (Exception e)
{
OnException?.Invoke(DateTime.UtcNow, MessageContentJSON, e);
MessageContent = default;
return false;
}
}
#endregion
#region (static) TryParse(MessageContentText, out MessageContent, OnException = null)
/// <summary>
/// Try to parse the given text representation of a message content.
/// </summary>
/// <param name="MessageContentText">The text to be parsed.</param>
/// <param name="MessageContent">The parsed connector type.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static Boolean TryParse(String MessageContentText,
out MessageContent MessageContent,
OnExceptionDelegate OnException = null)
{
try
{
MessageContentText = MessageContentText?.Trim();
if (MessageContentText.IsNotNullOrEmpty() &&
TryParse(JObject.Parse(MessageContentText),
out MessageContent,
OnException))
{
return true;
}
}
catch (Exception e)
{
OnException?.Invoke(DateTime.UtcNow, MessageContentText, e);
}
MessageContent = default;
return false;
}
#endregion
#region ToJSON(CustomMessageContentResponseSerializer = null, CustomCustomDataResponseSerializer = null)
/// <summary>
/// Return a JSON representation of this object.
/// </summary>
/// <param name="CustomMessageContentResponseSerializer">A delegate to serialize custom MessageContent objects.</param>
/// <param name="CustomCustomDataResponseSerializer">A delegate to serialize CustomData objects.</param>
public JObject ToJSON(CustomJObjectSerializerDelegate<MessageContent> CustomMessageContentResponseSerializer = null,
CustomJObjectSerializerDelegate<CustomData> CustomCustomDataResponseSerializer = null)
{
var JSON = JSONObject.Create(
new JProperty("content", Content),
new JProperty("language", Language.ToString()),
new JProperty("format", Format. AsText()),
CustomData != null
? new JProperty("customData", CustomData.ToJSON(CustomCustomDataResponseSerializer))
: null
);
return CustomMessageContentResponseSerializer != null
? CustomMessageContentResponseSerializer(this, JSON)
: JSON;
}
#endregion
#region Operator overloading
#region Operator == (MessageContent1, MessageContent2)
/// <summary>
/// Compares two instances of this object.
/// </summary>
/// <param name="MessageContent1">An id tag info.</param>
/// <param name="MessageContent2">Another id tag info.</param>
/// <returns>true|false</returns>
public static Boolean operator == (MessageContent MessageContent1, MessageContent MessageContent2)
{
// If both are null, or both are same instance, return true.
if (ReferenceEquals(MessageContent1, MessageContent2))
return true;
// If one is null, but not both, return false.
if (MessageContent1 is null || MessageContent2 is null)
return false;
if (MessageContent1 is null)
throw new ArgumentNullException(nameof(MessageContent1), "The given id tag info must not be null!");
return MessageContent1.Equals(MessageContent2);
}
#endregion
#region Operator != (MessageContent1, MessageContent2)
/// <summary>
/// Compares two instances of this object.
/// </summary>
/// <param name="MessageContent1">An id tag info.</param>
/// <param name="MessageContent2">Another id tag info.</param>
/// <returns>true|false</returns>
public static Boolean operator != (MessageContent MessageContent1, MessageContent MessageContent2)
=> !(MessageContent1 == MessageContent2);
#endregion
#endregion
#region IEquatable<MessageContent> Members
#region Equals(Object)
/// <summary>
/// Compares two instances of this object.
/// </summary>
/// <param name="Object">An object to compare with.</param>
/// <returns>true|false</returns>
public override Boolean Equals(Object Object)
{
if (Object is null)
return false;
if (!(Object is MessageContent MessageContent))
return false;
return Equals(MessageContent);
}
#endregion
#region Equals(MessageContent)
/// <summary>
/// Compares two id tag infos for equality.
/// </summary>
/// <param name="MessageContent">An id tag info to compare with.</param>
/// <returns>True if both match; False otherwise.</returns>
public Boolean Equals(MessageContent MessageContent)
{
if (MessageContent is null)
return false;
return String.Equals(Content, MessageContent.Content, StringComparison.OrdinalIgnoreCase) &&
Language.Equals(MessageContent.Language) &&
Format. Equals(MessageContent.Format) &&
((CustomData == null && MessageContent.CustomData == null) ||
(CustomData != null && MessageContent.CustomData != null && CustomData.Equals(MessageContent.CustomData)));
}
#endregion
#endregion
#region (override) GetHashCode()
/// <summary>
/// Return the HashCode of this object.
/// </summary>
/// <returns>The HashCode of this object.</returns>
public override Int32 GetHashCode()
{
unchecked
{
return Content. GetHashCode() * 7 ^
Language.GetHashCode() * 5 ^
Format. GetHashCode() * 3 ^
(CustomData != null
? CustomData.GetHashCode()
: 0);
}
}
#endregion
#region (override) ToString()
/// <summary>
/// Return a text representation of this object.
/// </summary>
public override String ToString()
=> String.Concat(Content, " (", Language, ", ", Format, ")");
#endregion
}
}
|
||||
TheStack | bdd9f7f62237e1c180d66c2f22375cc01e2cb1fa | C#code:C# | {"size": 1296, "ext": "cs", "max_stars_repo_path": "src/Armory/Formats/WarMaterialDeliveryCertificateFormats/Domain/WarMaterialDeliveryCertificateFormatExplosive.cs", "max_stars_repo_name": "cantte/Armory.Api", "max_stars_repo_stars_event_min_datetime": "2021-06-10T19:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T16:50:12.000Z", "max_issues_repo_path": "src/Armory/Formats/WarMaterialDeliveryCertificateFormats/Domain/WarMaterialDeliveryCertificateFormatExplosive.cs", "max_issues_repo_name": "cantte/Armory.Api", "max_issues_repo_issues_event_min_datetime": "2021-07-30T19:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T05:10:15.000Z", "max_forks_repo_path": "src/Armory/Formats/WarMaterialDeliveryCertificateFormats/Domain/WarMaterialDeliveryCertificateFormatExplosive.cs", "max_forks_repo_name": "cantte/Armory.Api", "max_forks_repo_forks_event_min_datetime": "2021-08-04T23:56:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T23:56:15.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 67.0, "max_forks_count": 1.0, "avg_line_length": 35.027027027, "max_line_length": 119, "alphanum_fraction": 0.712191358} | using System.ComponentModel.DataAnnotations.Schema;
using Armory.Armament.Explosives.Domain;
namespace Armory.Formats.WarMaterialDeliveryCertificateFormats.Domain
{
public class WarMaterialDeliveryCertificateFormatExplosive
{
public WarMaterialDeliveryCertificateFormatExplosive(WarMaterialDeliveryCertificateFormat format,
string explosiveSerial, int quantity)
{
Format = format;
ExplosiveSerial = explosiveSerial;
Quantity = quantity;
}
private WarMaterialDeliveryCertificateFormatExplosive()
{
}
public int WarMaterialDeliveryCertificateFormatId { get; set; }
[ForeignKey("WarMaterialDeliveryCertificateFormatId")]
public WarMaterialDeliveryCertificateFormat Format { get; set; }
public string ExplosiveSerial { get; set; }
[ForeignKey("ExplosiveSerial")] public Explosive Explosive { get; set; }
public int Quantity { get; set; }
public static WarMaterialDeliveryCertificateFormatExplosive Create(WarMaterialDeliveryCertificateFormat format,
string explosiveSerial, int quantity)
{
return new WarMaterialDeliveryCertificateFormatExplosive(format, explosiveSerial, quantity);
}
}
}
|
||||
TheStack | bddb1e3330c8fd0c54a0f903bb4ddd767fe32ec1 | C#code:C# | {"size": 1105, "ext": "cs", "max_stars_repo_path": "src/RpcNep17Tracker/Nep17Transfer.cs", "max_stars_repo_name": "chenzhitong/neo-modules", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RpcNep17Tracker/Nep17Transfer.cs", "max_issues_repo_name": "chenzhitong/neo-modules", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RpcNep17Tracker/Nep17Transfer.cs", "max_forks_repo_name": "chenzhitong/neo-modules", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.6944444444, "max_line_length": 114, "alphanum_fraction": 0.6190045249} | using Neo.IO;
using System.IO;
using System.Numerics;
namespace Neo.Plugins
{
public class Nep17Transfer : ISerializable
{
public UInt160 UserScriptHash;
public uint BlockIndex;
public UInt256 TxHash;
public BigDecimal Amount;
int ISerializable.Size => 20 + sizeof(uint) + 32 + Amount.Value.ToByteArray().GetVarSize() + sizeof(byte);
void ISerializable.Serialize(BinaryWriter writer)
{
writer.Write(UserScriptHash);
writer.Write(BlockIndex);
writer.Write(TxHash);
writer.WriteVarBytes(Amount.Value.ToByteArray());
writer.Write(Amount.Decimals);
}
void ISerializable.Deserialize(BinaryReader reader)
{
UserScriptHash = reader.ReadSerializable<UInt160>();
BlockIndex = reader.ReadUInt32();
TxHash = reader.ReadSerializable<UInt256>();
var value = new BigInteger(reader.ReadVarBytes(512));
var decimals = reader.ReadByte();
Amount = new BigDecimal(value, decimals);
}
}
}
|
||||
TheStack | bddbc185956a32f90ebf59c0a0d1a5404d90bfd7 | C#code:C# | {"size": 1532, "ext": "cs", "max_stars_repo_path": "src/Service.BalanceHistory.Domain.Models/WalletBalanceUpdateOperation.cs", "max_stars_repo_name": "MyJetWallet/Service.BalanceHistory", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Service.BalanceHistory.Domain.Models/WalletBalanceUpdateOperation.cs", "max_issues_repo_name": "MyJetWallet/Service.BalanceHistory", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Service.BalanceHistory.Domain.Models/WalletBalanceUpdateOperation.cs", "max_forks_repo_name": "MyJetWallet/Service.BalanceHistory", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.9166666667, "max_line_length": 95, "alphanum_fraction": 0.6063968668} | using System;
using System.Runtime.Serialization;
namespace Service.BalanceHistory.Domain.Models
{
[DataContract]
public class WalletBalanceUpdateOperation
{
public WalletBalanceUpdateOperation(WalletBalanceUpdateOperation update)
{
Id = update.Id;
Symbol = update.Symbol;
Timestamp = update.Timestamp;
SequenceId = update.SequenceId;
EventType = update.EventType;
OperationId = update.OperationId;
TxId = update.TxId;
OppositeSymbol = update.OppositeSymbol;
OppositeAmount = update.OppositeAmount;
}
public WalletBalanceUpdateOperation()
{
}
[DataMember(Order = 1)] public long Id { get; set; }
[DataMember(Order = 2)] public string Symbol { get; set; }
[DataMember(Order = 3)] public DateTime Timestamp { get; set; }
[DataMember(Order = 4)] public double Amount { get; set; }
[DataMember(Order = 5)] public long SequenceId { get; set; }
[DataMember(Order = 6)] public WalletBalanceUpdateOperationType EventType { get; set; }
[DataMember(Order = 7)] public string OperationId { get; set; }
//Cash In/Out fields
[DataMember(Order = 8)] public string TxId { get; set; }
//Swap/trade fields
[DataMember(Order = 9)] public string OppositeSymbol { get; set; }
[DataMember(Order = 10)] public double OppositeAmount { get; set; }
}
} |
||||
TheStack | bdde866e4bd00090b9bce4876dd759b539fef8ba | C#code:C# | {"size": 210, "ext": "cs", "max_stars_repo_path": "Open-Lab-03.07/Divider.cs", "max_stars_repo_name": "Misko183/Open-Lab-03.07", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Open-Lab-03.07/Divider.cs", "max_issues_repo_name": "Misko183/Open-Lab-03.07", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Open-Lab-03.07/Divider.cs", "max_forks_repo_name": "Misko183/Open-Lab-03.07", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.5, "max_line_length": 64, "alphanum_fraction": 0.5619047619} | using System;
namespace Open_Lab_03._07
{
public class Divider
{
public bool EqualSlices(int total, int people, int each)
{
return people * each <= total;
}
}
} |
||||
TheStack | bde0c7dd1ff60b080d53fb3c63ad3d7064764903 | C#code:C# | {"size": 187, "ext": "cs", "max_stars_repo_path": "PCMarket/PCMarket.Common/Strings.cs", "max_stars_repo_name": "kraskoo/PCMarket", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PCMarket/PCMarket.Common/Strings.cs", "max_issues_repo_name": "kraskoo/PCMarket", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCMarket/PCMarket.Common/Strings.cs", "max_forks_repo_name": "kraskoo/PCMarket", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.7142857143, "max_line_length": 119, "alphanum_fraction": 0.4385026738} | namespace PCMarket.Common
{
public class Strings
{
public const string UriPattern = @"([\!\@\$\%\^\&\*\(\)\\\/\-\#\.\:\w]+)(\/?|\\?[\w\d\-]+?\.[jpegpntif]{3,4})";
}
} |
||||
TheStack | bde0d5b0d736ebab0f0ec4cda515e2f06f1f6e2c | C#code:C# | {"size": 8359, "ext": "cs", "max_stars_repo_path": "Source/MethodCallReturn.cs", "max_stars_repo_name": "niubi007/Moq", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/MethodCallReturn.cs", "max_issues_repo_name": "niubi007/Moq", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/MethodCallReturn.cs", "max_forks_repo_name": "niubi007/Moq", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.0743494424, "max_line_length": 153, "alphanum_fraction": 0.7315468357} | //Copyright (c) 2007. Clarius Consulting, Manas Technology Solutions, InSTEDD
//https://github.com/moq/moq4
//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 Clarius Consulting, Manas Technology Solutions or InSTEDD 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.
//[This is the BSD license, see
// http://www.opensource.org/licenses/bsd-license.php]
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Moq.Language;
using Moq.Language.Flow;
using Moq.Properties;
namespace Moq
{
internal sealed partial class MethodCallReturn<TMock, TResult> : MethodCall, ISetup<TMock, TResult>, ISetupGetter<TMock, TResult>, IReturnsResult<TMock>
where TMock : class
{
// This enum exists for reasons of optimizing memory usage.
// Previously this class had two `bool` fields, `hasReturnValue` and `callBase`.
// Using an enum allows us to combine them into a single field.
private enum ReturnValueKind : byte
{
None = 0,
Explicit,
CallBase,
}
private Delegate valueDel;
private Action<object[]> afterReturnCallback;
private ReturnValueKind returnValueKind;
public MethodCallReturn(Mock mock, Condition condition, LambdaExpression originalExpression, MethodInfo method, IReadOnlyList<Expression> arguments)
: base(mock, condition, originalExpression, method, arguments)
{
}
public bool ProvidesReturnValue() => this.returnValueKind != ReturnValueKind.None;
public IVerifies Raises(Action<TMock> eventExpression, EventArgs args)
{
return this.Raises(eventExpression, () => args);
}
public IVerifies Raises(Action<TMock> eventExpression, Func<EventArgs> func)
{
return this.RaisesImpl(eventExpression, func);
}
public IVerifies Raises(Action<TMock> eventExpression, params object[] args)
{
return this.RaisesImpl(eventExpression, args);
}
public IReturnsResult<TMock> Returns(Delegate valueFunction)
{
// If `TResult` is `Delegate`, that is someone is setting up the return value of a method
// that returns a `Delegate`, then we have arrived here because C# picked the wrong overload:
// We don't want to invoke the passed delegate to get a return value; the passed delegate
// already is the return value.
if (typeof(TResult) == typeof(Delegate))
{
return this.Returns(() => (TResult)(object)valueFunction);
}
if (valueFunction != null && valueFunction.GetMethodInfo().ReturnType == typeof(void))
{
throw new ArgumentException(Resources.InvalidReturnsCallbackNotADelegateWithReturnType, nameof(valueFunction));
}
SetReturnDelegate(valueFunction);
return this;
}
public IReturnsResult<TMock> Returns(Func<TResult> valueExpression)
{
SetReturnDelegate(valueExpression);
return this;
}
public IReturnsResult<TMock> Returns(TResult value)
{
Returns(() => value);
return this;
}
public IReturnsResult<TMock> CallBase()
{
this.returnValueKind = ReturnValueKind.CallBase;
return this;
}
IReturnsThrows<TMock, TResult> ICallback<TMock, TResult>.Callback(Delegate callback)
{
base.Callback(callback);
return this;
}
IReturnsThrowsGetter<TMock, TResult> ICallbackGetter<TMock, TResult>.Callback(Action callback)
{
base.Callback(callback);
return this;
}
public new IReturnsThrows<TMock, TResult> Callback(Action callback)
{
base.Callback(callback);
return this;
}
private void SetReturnDelegate(Delegate value)
{
if (value == null)
{
// A `null` reference (instead of a valid delegate) is interpreted as the actual return value.
// This is necessary because the compiler might have picked the unexpected overload for calls like `Returns(null)`,
// or the user might have picked an overload like `Returns<T>(null)`,
// and instead of in `Returns(TResult)`, we ended up in `Returns(Delegate)` or `Returns(Func)`,
// which likely isn't what the user intended.
// So here we do what we would've done in `Returns(TResult)`:
this.valueDel = (Func<TResult>)(() => default(TResult));
}
else
{
ValidateReturnDelegate(value);
this.valueDel = value;
}
this.returnValueKind = ReturnValueKind.Explicit;
}
private void ValidateReturnDelegate(Delegate callback)
{
var callbackMethod = callback.GetMethodInfo();
ValidateNumberOfCallbackParameters(callbackMethod);
ValidateCallbackReturnType(callbackMethod);
}
private void ValidateNumberOfCallbackParameters(MethodInfo callbackMethod)
{
var numberOfActualParameters = callbackMethod.GetParameters().Length;
if (callbackMethod.IsExtensionMethod())
{
numberOfActualParameters--;
}
if (numberOfActualParameters > 0)
{
var numberOfExpectedParameters = this.Method.GetParameters().Length;
if (numberOfActualParameters != numberOfExpectedParameters)
{
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
Resources.InvalidCallbackParameterCountMismatch,
numberOfExpectedParameters,
numberOfActualParameters));
}
}
}
private void ValidateCallbackReturnType(MethodInfo callbackMethod)
{
var expectedReturnType = this.Method.ReturnType;
var actualReturnType = callbackMethod.ReturnType;
if (!expectedReturnType.IsAssignableFrom(actualReturnType))
{
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
Resources.InvalidCallbackReturnTypeMismatch,
expectedReturnType,
actualReturnType));
}
}
protected override void SetCallbackWithoutArguments(Action callback)
{
if (this.ProvidesReturnValue())
{
this.afterReturnCallback = delegate { callback(); };
}
else
{
base.SetCallbackWithoutArguments(callback);
}
}
protected override void SetCallbackWithArguments(Delegate callback)
{
if (this.ProvidesReturnValue())
{
this.afterReturnCallback = delegate(object[] args) { callback.InvokePreserveStack(args); };
}
else
{
base.SetCallbackWithArguments(callback);
}
}
public override void Execute(Invocation invocation)
{
base.Execute(invocation);
if (this.returnValueKind == ReturnValueKind.CallBase)
{
invocation.ReturnBase();
}
else if (this.valueDel != null)
{
invocation.Return(this.valueDel.HasCompatibleParameterList(new ParameterInfo[0])
? valueDel.InvokePreserveStack() //we need this, for the user to be able to use parameterless methods
: valueDel.InvokePreserveStack(invocation.Arguments)); //will throw if parameters mismatch
}
else if (this.Mock.Behavior == MockBehavior.Strict)
{
throw MockException.ReturnValueRequired(invocation);
}
else
{
invocation.Return(default(TResult));
}
this.afterReturnCallback?.Invoke(invocation.Arguments);
}
}
}
|
||||
TheStack | bde0f6ec50122e34fec8c9b05910350976cee0f7 | C#code:C# | {"size": 534, "ext": "cs", "max_stars_repo_path": "DiLite/Registrations/TypeRegistration.cs", "max_stars_repo_name": "balazs-kis/dilite", "max_stars_repo_stars_event_min_datetime": "2020-03-02T10:37:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-20T12:11:58.000Z", "max_issues_repo_path": "DiLite/Registrations/TypeRegistration.cs", "max_issues_repo_name": "balazs-kis/dilite", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DiLite/Registrations/TypeRegistration.cs", "max_forks_repo_name": "balazs-kis/dilite", "max_forks_repo_forks_event_min_datetime": "2021-04-24T09:30:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-24T09:30:16.000Z"} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 25.4285714286, "max_line_length": 114, "alphanum_fraction": 0.6086142322} | using System;
using System.Collections.Generic;
namespace DiLite.Registrations
{
internal class TypeRegistration : Registration
{
public TypeRegistration(
Type registeredType,
IEnumerable<Type> aliases,
bool isSingleInstance)
: base(
registeredType,
aliases,
isSingleInstance)
{
}
public override RegisteredEntity RegisteredEntity => new RegisteredType(RegisteredType, IsSingleInstance);
}
} |
||||
TheStack | bde55fc97f80dcaaf169fa81acbf9d570ba1709f | C#code:C# | {"size": 2482, "ext": "cs", "max_stars_repo_path": "Sources/Core/Implementations/BaseBlockStore.cs", "max_stars_repo_name": "terwoord/overdrive", "max_stars_repo_stars_event_min_datetime": "2015-11-29T11:20:41.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-29T11:20:41.000Z", "max_issues_repo_path": "Sources/Core/Implementations/BaseBlockStore.cs", "max_issues_repo_name": "terwoord/overdrive", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Core/Implementations/BaseBlockStore.cs", "max_forks_repo_name": "terwoord/overdrive", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.82, "max_line_length": 131, "alphanum_fraction": 0.5048348106} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace TerWoord.OverDriveStorage.Implementations
{
public abstract class BaseBlockStore : IBlockStore
{
private bool _disposed = false;
protected bool IsDisposed
{
get
{
return _disposed;
}
}
protected virtual void DoDispose()
{
}
protected void CheckDisposed()
{
if (IsDisposed)
{
throw new ObjectDisposedException("DeduplicatingBlockStore");
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
GC.SuppressFinalize(this);
_disposed = true;
DoDispose();
}
public abstract void Store(ulong index, ArraySegment<byte> buffer);
public virtual void Store(ulong[] indices, ArraySegment<byte> buffer)
{
CheckDisposed();
if (buffer.Count != (indices.Length * BlockSize))
{
throw new Exception("Buffer size not correct!");
}
for (int i = 0; i < indices.Length; i++)
{
Store(indices[i], new ArraySegment<byte>(buffer.Array, (int)(buffer.Offset + (i * BlockSize)), (int)BlockSize));
}
}
public abstract void Retrieve(ulong index, ArraySegment<byte> buffer);
public virtual void Retrieve(ulong[] indices, ArraySegment<byte> buffer)
{
CheckDisposed();
if (buffer.Count != (indices.Length * BlockSize))
{
throw new Exception("Buffer size not correct!");
}
for (int i = 0; i < indices.Length; i++)
{
Retrieve(indices[i], new ArraySegment<byte>(buffer.Array, (int)(buffer.Offset + (i * BlockSize)), (int)BlockSize));
}
}
public abstract uint BlockSize
{
get;
}
public abstract ulong BlockCount
{
get;
}
public abstract void DumpCacheInfo(StreamWriter output, string linePrefix);
public virtual void PreloadCaches()
{
}
public virtual string Id
{
get;
set;
}
public virtual void Flush()
{
}
}
} |
||||
TheStack | bde648e0cbc38f30757d97aaacf2dfc20899b60d | C#code:C# | {"size": 1114, "ext": "cs", "max_stars_repo_path": "DeployTrackerMVC2/Controllers/PageControllers.cs", "max_stars_repo_name": "GoProduction/DeployTrackerMVC", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DeployTrackerMVC2/Controllers/PageControllers.cs", "max_issues_repo_name": "GoProduction/DeployTrackerMVC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeployTrackerMVC2/Controllers/PageControllers.cs", "max_forks_repo_name": "GoProduction/DeployTrackerMVC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.4230769231, "max_line_length": 99, "alphanum_fraction": 0.5565529623} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DeployTrackerMVC2.Controllers
{
//Make sure all page controllers are added to the RouteConfig file as well. No route, no clout.
public class DeveloperController : Controller
{
// GET: Developer
public ActionResult Index()
{
return View();
}
}
public class QAController : Controller
{
// GET: Developer
public ActionResult Index()
{
return View();
}
}
public class NewDeployController : Controller
{
// GET: NewDeploy
public ActionResult Index()
{
return View();
}
}
public class ChangeLogsController : Controller
{
//GET: ChangeLogs
public ActionResult Index()
{
return View();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
} |
||||
TheStack | bde8d23c65419b3d301ea3d832237f2385f80e98 | C#code:C# | {"size": 395, "ext": "cs", "max_stars_repo_path": "Neo4jClient.DataAnnotations/Cypher/IAnnotated.cs", "max_stars_repo_name": "Arsslensoft/Neo4jClient.DataAnnotations", "max_stars_repo_stars_event_min_datetime": "2017-08-08T03:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T10:30:58.000Z", "max_issues_repo_path": "Neo4jClient.DataAnnotations/Cypher/IAnnotated.cs", "max_issues_repo_name": "Arsslensoft/Neo4jClient.DataAnnotations", "max_issues_repo_issues_event_min_datetime": "2019-04-23T15:56:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T21:18:27.000Z", "max_forks_repo_path": "Neo4jClient.DataAnnotations/Cypher/IAnnotated.cs", "max_forks_repo_name": "Arsslensoft/Neo4jClient.DataAnnotations", "max_forks_repo_forks_event_min_datetime": "2019-05-25T13:04:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T11:24:07.000Z"} | {"max_stars_count": 12.0, "max_issues_count": 9.0, "max_forks_count": 2.0, "avg_line_length": 28.2142857143, "max_line_length": 58, "alphanum_fraction": 0.746835443} | using System.ComponentModel;
using Neo4jClient.Cypher;
namespace Neo4jClient.DataAnnotations.Cypher
{
public interface IAnnotated : IHaveAnnotationsContext
{
[EditorBrowsable(EditorBrowsableState.Never)]
ref ICypherFluentQuery CypherQuery { get; }
[EditorBrowsable(EditorBrowsableState.Never)]
string Build(ref ICypherFluentQuery currentQuery);
}
} |
||||
TheStack | bdeacf7a73e9a68b324400c112145f295a496d08 | C#code:C# | {"size": 1934, "ext": "cs", "max_stars_repo_path": "ApiConsole/Program.cs", "max_stars_repo_name": "maxcutler/wp-api-csharp", "max_stars_repo_stars_event_min_datetime": "2015-04-19T00:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-19T02:13:50.000Z", "max_issues_repo_path": "ApiConsole/Program.cs", "max_issues_repo_name": "maxcutler/wp-api-csharp", "max_issues_repo_issues_event_min_datetime": "2015-04-06T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-06T14:39:14.000Z", "max_forks_repo_path": "ApiConsole/Program.cs", "max_forks_repo_name": "maxcutler/wp-api-csharp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 28.4411764706, "max_line_length": 104, "alphanum_fraction": 0.7197518097} | using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PortableWordPressApi;
using PortableWordPressApi.Resources;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
Console.WriteLine();
var indexResponse = await httpClient.GetAsync(api.ApiRootUri);
var index = JsonConvert.DeserializeObject<ApiIndex>(await indexResponse.Content.ReadAsStringAsync());
Console.WriteLine("Supported routes:");
foreach (var route in index.Routes)
{
Console.WriteLine("\t" + route.Key);
}
Console.WriteLine();
var postsResponse = await httpClient.GetAsync(api.ApiRootUri + "posts");
var postsResponseContent = await postsResponse.Content.ReadAsStringAsync();
var posts = JsonConvert.DeserializeObject<List<Post>>(postsResponseContent);
Console.WriteLine("Recent posts:");
foreach (var post in posts)
{
Console.WriteLine("\t{0}", post.Title);
}
Console.WriteLine();
var mediaResponse = await httpClient.GetAsync(api.ApiRootUri + "media");
var mediaResponseContent = await mediaResponse.Content.ReadAsStringAsync();
var media = JsonConvert.DeserializeObject<List<Media>>(mediaResponseContent);
Console.WriteLine("Recent media:");
foreach (var medium in media)
{
Console.WriteLine("\t{0}", medium.Source);
}
Console.WriteLine();
}
}
}
|
||||
TheStack | bdebafc05c0a9b5a55d1bfaf5ea35dba39520b1c | C#code:C# | {"size": 798, "ext": "cs", "max_stars_repo_path": "Assets/CameraStuff/Zoom/Ready.cs", "max_stars_repo_name": "draculeq/MineralTycoon", "max_stars_repo_stars_event_min_datetime": "2017-06-19T14:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-19T14:57:16.000Z", "max_issues_repo_path": "Assets/CameraStuff/Zoom/Ready.cs", "max_issues_repo_name": "draculeq/MineralTycoon", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/CameraStuff/Zoom/Ready.cs", "max_forks_repo_name": "draculeq/MineralTycoon", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.6, "max_line_length": 132, "alphanum_fraction": 0.5601503759} | using UnityEngine;
namespace Assets.CameraStuff.Zoom
{
public class Ready : ZoomState
{
public override ZoomState Init(ZoomStateMachine stateMachine)
{
base.Init(stateMachine);
return this;
}
public override ZoomState Tick()
{
if (Mathf.Abs(Input.GetAxis("Zoom")) > 0)
return _stateMachine.Get<Scrolling>().Init(_stateMachine);
if (Input.touchCount == 2 && (Input.touches[0].phase == TouchPhase.Began || Input.touches[1].phase == TouchPhase.Began))
return _stateMachine.Get<Pinching>().Init(_stateMachine);
return this;
}
private static bool Zooming()
{
var value = false;
return value;
}
}
}
|
||||
TheStack | bdec20a2287a4b700911d833acad42b50f8b2d3f | C#code:C# | {"size": 722, "ext": "cs", "max_stars_repo_path": "DhcpServer.Test/SpanExtensionsTest.cs", "max_stars_repo_name": "bobbymcr/DhcpServer", "max_stars_repo_stars_event_min_datetime": "2020-01-23T22:37:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T05:08:23.000Z", "max_issues_repo_path": "DhcpServer.Test/SpanExtensionsTest.cs", "max_issues_repo_name": "bobbymcr/DhcpServer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DhcpServer.Test/SpanExtensionsTest.cs", "max_forks_repo_name": "bobbymcr/DhcpServer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 10.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.7407407407, "max_line_length": 87, "alphanum_fraction": 0.6066481994} | // <copyright file="SpanExtensionsTest.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
namespace DhcpServer.Test
{
using System;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class SpanExtensionsTest
{
[TestMethod]
public void CopyUInt32()
{
byte[] raw = new byte[] { 0xFC, 0x22, 0x33, 0x44, 0x00, 0xFF, 0x78, 0x00 };
Span<byte> buffer = new Span<byte>(raw);
0U.CopyTo(buffer.Slice(0));
0xABCDEF11.CopyTo(buffer.Slice(4));
raw.Should().ContainInOrder(0, 0, 0, 0, 0xAB, 0xCD, 0xEF, 0x11);
}
}
}
|
||||
TheStack | bdece63f8d7144582a13bc083a6c3cf64b1700ca | C#code:C# | {"size": 2390, "ext": "cs", "max_stars_repo_path": "Source/Walmart.Sdk.Marketplace/V2/Payload/Item/MPItemView.cs", "max_stars_repo_name": "GaryWayneSmith/partnerapi_sdk_dotnet", "max_stars_repo_stars_event_min_datetime": "2018-07-09T22:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T03:50:01.000Z", "max_issues_repo_path": "Source/Walmart.Sdk.Marketplace/V2/Payload/Item/MPItemView.cs", "max_issues_repo_name": "GaryWayneSmith/partnerapi_sdk_dotnet", "max_issues_repo_issues_event_min_datetime": "2018-06-04T22:15:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-14T15:09:36.000Z", "max_forks_repo_path": "Source/Walmart.Sdk.Marketplace/V2/Payload/Item/MPItemView.cs", "max_forks_repo_name": "GaryWayneSmith/partnerapi_sdk_dotnet", "max_forks_repo_forks_event_min_datetime": "2018-06-08T02:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T03:12:45.000Z"} | {"max_stars_count": 17.0, "max_issues_count": 17.0, "max_forks_count": 16.0, "avg_line_length": 34.1428571429, "max_line_length": 83, "alphanum_fraction": 0.5765690377} | /*
Copyright (c) 2018-present, Walmart Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code++. Version 4.4.0.7
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Walmart.Sdk.Marketplace.V2.Payload.Item
{
using System;
using System.Xml.Serialization;
using System.Xml;
using Walmart.Sdk.Base.Primitive;
/// <summary>
/// MPItemView
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.4.0.7")]
[Serializable]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(Namespace="http://walmart.com/")]
[XmlRootAttribute(Namespace="http://walmart.com/", IsNullable=false)]
public class MPItemView : BasePayload
{
[XmlElement("mart")]
public Mart Mart { get; set; }
[XmlElement("sku")]
public string Sku { get; set; }
[XmlElement("wpid")]
public string Wpid { get; set; }
[XmlElement("upc")]
public string Upc { get; set; }
[XmlElement("gtin")]
public string Gtin { get; set; }
[XmlElement("productName")]
public string ProductName { get; set; }
[XmlElement("shelf")]
public string Shelf { get; set; }
[XmlElement("productType")]
public string ProductType { get; set; }
[XmlElement("price")]
public Money Price { get; set; }
[XmlElement("publishedStatus")]
public ItemPublishStatus PublishedStatus { get; set; }
/// <summary>
/// MPItemView class constructor
/// </summary>
public MPItemView()
{
Price = new Money();
}
}
}
|
||||
TheStack | bded3b1ed9a0f2275a018e3f7bf78a35fe2a3a97 | C#code:C# | {"size": 328, "ext": "cs", "max_stars_repo_path": "plbEdit/Controls/PLBControlBox.cs", "max_stars_repo_name": "EddyK28/plbEdit", "max_stars_repo_stars_event_min_datetime": "2019-09-17T01:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-17T01:43:49.000Z", "max_issues_repo_path": "plbEdit/Controls/PLBControlBox.cs", "max_issues_repo_name": "EddyK28/plbEdit", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plbEdit/Controls/PLBControlBox.cs", "max_forks_repo_name": "EddyK28/plbEdit", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.8181818182, "max_line_length": 163, "alphanum_fraction": 0.6798780488} |
namespace plbEdit.Controls
{
public class PLBControlBox : System.Windows.Forms.TextBox
{
static System.Drawing.Font fnt = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
public PLBControlBox() : base() { Font = fnt; }
}
}
|
||||
TheStack | bded5da76c5b988a1f9ca8af6e7b30aea47f3221 | C#code:C# | {"size": 2796, "ext": "cs", "max_stars_repo_path": "Assets/Plugins/RuntimeTransformGizmo/Objects/Commands/SelectCommand.cs", "max_stars_repo_name": "MonarchSolutions/Ballance", "max_stars_repo_stars_event_min_datetime": "2016-10-24T15:12:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T12:32:05.000Z", "max_issues_repo_path": "Assets/Plugins/RuntimeTransformGizmo/Objects/Commands/SelectCommand.cs", "max_issues_repo_name": "MonarchSolutions/Ballance", "max_issues_repo_issues_event_min_datetime": "2018-07-14T05:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T12:26:17.000Z", "max_forks_repo_path": "Assets/Plugins/RuntimeTransformGizmo/Objects/Commands/SelectCommand.cs", "max_forks_repo_name": "MonarchSolutions/Ballance", "max_forks_repo_forks_event_min_datetime": "2016-12-08T08:45:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T16:01:54.000Z"} | {"max_stars_count": 500.0, "max_issues_count": 24.0, "max_forks_count": 82.0, "avg_line_length": 24.5263157895, "max_line_length": 142, "alphanum_fraction": 0.7349785408} | using System;
using CommandUndoRedo;
using UnityEngine;
using System.Collections.Generic;
namespace RuntimeGizmos
{
public abstract class SelectCommand : ICommand
{
protected Transform target;
protected TransformGizmo transformGizmo;
public SelectCommand(TransformGizmo transformGizmo, Transform target)
{
this.transformGizmo = transformGizmo;
this.target = target;
}
public abstract void Execute();
public abstract void UnExecute();
}
public class AddTargetCommand : SelectCommand
{
List<Transform> targetRoots = new List<Transform>();
public AddTargetCommand(TransformGizmo transformGizmo, Transform target, List<Transform> targetRoots) : base(transformGizmo, target)
{
//Since we might have had a child selected and then selected the parent, the child would have been removed from the selected,
//so we store all the targetRoots before we add so that if we undo we can properly have the children selected again.
this.targetRoots.AddRange(targetRoots);
}
public override void Execute()
{
transformGizmo.AddTarget(target, false);
}
public override void UnExecute()
{
transformGizmo.RemoveTarget(target, false);
for(int i = 0; i < targetRoots.Count; i++)
{
transformGizmo.AddTarget(targetRoots[i], false);
}
}
}
public class RemoveTargetCommand : SelectCommand
{
public RemoveTargetCommand(TransformGizmo transformGizmo, Transform target) : base(transformGizmo, target) {}
public override void Execute()
{
transformGizmo.RemoveTarget(target, false);
}
public override void UnExecute()
{
transformGizmo.AddTarget(target, false);
}
}
public class ClearTargetsCommand : SelectCommand
{
List<Transform> targetRoots = new List<Transform>();
public ClearTargetsCommand(TransformGizmo transformGizmo, List<Transform> targetRoots) : base(transformGizmo, null)
{
this.targetRoots.AddRange(targetRoots);
}
public override void Execute()
{
transformGizmo.ClearTargets(false);
}
public override void UnExecute()
{
for(int i = 0; i < targetRoots.Count; i++)
{
transformGizmo.AddTarget(targetRoots[i], false);
}
}
}
public class ClearAndAddTargetCommand : SelectCommand
{
List<Transform> targetRoots = new List<Transform>();
public ClearAndAddTargetCommand(TransformGizmo transformGizmo, Transform target, List<Transform> targetRoots) : base(transformGizmo, target)
{
this.targetRoots.AddRange(targetRoots);
}
public override void Execute()
{
transformGizmo.ClearTargets(false);
transformGizmo.AddTarget(target, false);
}
public override void UnExecute()
{
transformGizmo.RemoveTarget(target, false);
for(int i = 0; i < targetRoots.Count; i++)
{
transformGizmo.AddTarget(targetRoots[i], false);
}
}
}
}
|
||||
TheStack | bdef12977371275a52210b72b02bff22b0a78e38 | C#code:C# | {"size": 253, "ext": "cshtml", "max_stars_repo_path": "src/AdminLte.TagHelpers.Demo/Pages/Shared/Components/SidebarBrand/Default.cshtml", "max_stars_repo_name": "osucubs/admin-lte-dotnet", "max_stars_repo_stars_event_min_datetime": "2020-01-27T08:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:45:03.000Z", "max_issues_repo_path": "src/AdminLte.TagHelpers.Demo/Pages/Shared/Components/SidebarBrand/Default.cshtml", "max_issues_repo_name": "osucubs/admin-lte-dotnet", "max_issues_repo_issues_event_min_datetime": "2020-02-28T05:42:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-29T17:36:18.000Z", "max_forks_repo_path": "src/AdminLte.TagHelpers.Demo/Pages/Shared/Components/SidebarBrand/Default.cshtml", "max_forks_repo_name": "osucubs/admin-lte-dotnet", "max_forks_repo_forks_event_min_datetime": "2020-02-28T03:27:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T15:03:26.000Z"} | {"max_stars_count": 75.0, "max_issues_count": 3.0, "max_forks_count": 24.0, "avg_line_length": 50.6, "max_line_length": 119, "alphanum_fraction": 0.6600790514} | <a href="~/" class="brand-link">
<img src="~/lib/admin-lte/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3"
style="opacity: .8">
<span class="brand-text font-weight-light">AdminLTE 3</span>
</a> |
||||
TheStack | bdefc27ca55fd9bcbb2dc3480d26833a37d75a91 | C#code:C# | {"size": 216, "ext": "cs", "max_stars_repo_path": "api/AltV.Net.NetworkingEntity/Elements/Factories/INetworkingClientFactory.cs", "max_stars_repo_name": "je-schindler/coreclr-module", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "api/AltV.Net.NetworkingEntity/Elements/Factories/INetworkingClientFactory.cs", "max_issues_repo_name": "je-schindler/coreclr-module", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "api/AltV.Net.NetworkingEntity/Elements/Factories/INetworkingClientFactory.cs", "max_forks_repo_name": "je-schindler/coreclr-module", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.0, "max_line_length": 54, "alphanum_fraction": 0.7685185185} | using AltV.Net.NetworkingEntity.Elements.Entities;
namespace AltV.Net.NetworkingEntity.Elements.Factories
{
public interface INetworkingClientFactory
{
INetworkingClient Create(string token);
}
} |
||||
TheStack | bdf1a130172a1096e1a810f48f47bd3a5d520f42 | C#code:C# | {"size": 289, "ext": "cs", "max_stars_repo_path": "NBi.Xml/Items/QueryScalarXml.cs", "max_stars_repo_name": "TheAutomatingMrLynch/NBi", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NBi.Xml/Items/QueryScalarXml.cs", "max_issues_repo_name": "TheAutomatingMrLynch/NBi", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NBi.Xml/Items/QueryScalarXml.cs", "max_forks_repo_name": "TheAutomatingMrLynch/NBi", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 18.0625, "max_line_length": 42, "alphanum_fraction": 0.7612456747} | using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using NBi.Core;
using NBi.Xml.SerializationOption;
namespace NBi.Xml.Items
{
public class QueryScalarXml : QueryXml
{
}
} |
||||
TheStack | bdf2f6dcfc2b4bbc244ab84b65bb0a538f4c8dce | C#code:C# | {"size": 1021, "ext": "cs", "max_stars_repo_path": "HtmlMinify/HtmlMinifyExample/HtmlMinifyAttribute.cs", "max_stars_repo_name": "BenjaminAbt/samples.ASPNETMVC", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HtmlMinify/HtmlMinifyExample/HtmlMinifyAttribute.cs", "max_issues_repo_name": "BenjaminAbt/samples.ASPNETMVC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HtmlMinify/HtmlMinifyExample/HtmlMinifyAttribute.cs", "max_forks_repo_name": "BenjaminAbt/samples.ASPNETMVC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.0333333333, "max_line_length": 177, "alphanum_fraction": 0.6591576885} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace HtmlMinifyExample
{
public class HtmlMinifyAttribute : ActionFilterAttribute
{
/// <summary>
/// Implement attribute behavior
/// </summary>
public override void OnActionExecuted( ActionExecutedContext filterContext )
{
if ( IsSupportedContentType( filterContext ) )
{
filterContext.HttpContext.Response.Filter = new HtmlMinifyStream( filterContext.HttpContext.Response.Filter );
}
}
/// <summary>
/// Returns troe if filter is not null and content type is html.
/// </summary>
private Boolean IsSupportedContentType( ActionExecutedContext filterContext )
{
return filterContext.HttpContext.Response.Filter != null && filterContext.HttpContext.Response.ContentType.Equals( "text/html", StringComparison.OrdinalIgnoreCase );
}
}
} |
||||
TheStack | bdf34eb5570f098fc44d136fc7fdf735fb692bf1 | C#code:C# | {"size": 252, "ext": "cs", "max_stars_repo_path": "src/SimpleS3.Core.Abstracts/Authentication/ISignatureBuilder.cs", "max_stars_repo_name": "Genbox/SimpleS3-Ext", "max_stars_repo_stars_event_min_datetime": "2019-10-07T07:14:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:20:26.000Z", "max_issues_repo_path": "src/SimpleS3.Core.Abstracts/Authentication/ISignatureBuilder.cs", "max_issues_repo_name": "Genbox/SimpleS3-Ext", "max_issues_repo_issues_event_min_datetime": "2019-10-08T12:42:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T22:39:40.000Z", "max_forks_repo_path": "src/SimpleS3.Core.Abstracts/Authentication/ISignatureBuilder.cs", "max_forks_repo_name": "Genbox/SimpleS3-Ext", "max_forks_repo_forks_event_min_datetime": "2019-10-06T21:48:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T03:46:23.000Z"} | {"max_stars_count": 22.0, "max_issues_count": 35.0, "max_forks_count": 5.0, "avg_line_length": 28.0, "max_line_length": 86, "alphanum_fraction": 0.7341269841} | using Genbox.SimpleS3.Core.Abstracts.Request;
namespace Genbox.SimpleS3.Core.Abstracts.Authentication
{
public interface ISignatureBuilder
{
byte[] CreateSignature(IRequest request, bool enablePayloadSignature = true);
}
} |
||||
TheStack | bdf4edb5d65f6a4e2a74d21a93cf2ed046d69a26 | C#code:C# | {"size": 727, "ext": "cs", "max_stars_repo_path": "WpfPlotDigitizer/ViewModels/MainWindowVM.cs", "max_stars_repo_name": "alex1392/WpfPlotDigitizer", "max_stars_repo_stars_event_min_datetime": "2019-02-16T08:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T03:36:11.000Z", "max_issues_repo_path": "WpfPlotDigitizer/ViewModels/MainWindowVM.cs", "max_issues_repo_name": "alex1392/WpfPlotDigitizer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WpfPlotDigitizer/ViewModels/MainWindowVM.cs", "max_forks_repo_name": "alex1392/WpfPlotDigitizer", "max_forks_repo_forks_event_min_datetime": "2022-01-08T06:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T06:28:29.000Z"} | {"max_stars_count": 9.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 24.2333333333, "max_line_length": 76, "alphanum_fraction": 0.7331499312} | using CycWpfLibrary;
using CycWpfLibrary.Resource;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using static WpfPlotDigitizer.DI;
using MahApps.Metro;
using CycWpfLibrary.CustomControls;
namespace WpfPlotDigitizer
{
public class MainWindowVM : ViewModelBase
{
public PageManagerBase PageManager => pageManager;
/// <summary>
/// For initializing
/// </summary>
public ApplicationManager ApplicationManager { get; set; } = appManager;
/// <summary>
/// For initializing
/// </summary>
public MessageManager MessageManager { get; set; } = messageManager;
}
}
|
||||
TheStack | bdf649f5847ad25c71ca95918d0aeae751518558 | C#code:C# | {"size": 2629, "ext": "cs", "max_stars_repo_path": "Zapp/Config/FuseConfig.cs", "max_stars_repo_name": "omniaretail/zapp", "max_stars_repo_stars_event_min_datetime": "2017-02-01T09:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:43:22.000Z", "max_issues_repo_path": "Zapp/Config/FuseConfig.cs", "max_issues_repo_name": "omniaretail/zapp", "max_issues_repo_issues_event_min_datetime": "2017-01-31T08:42:42.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-17T14:42:16.000Z", "max_forks_repo_path": "Zapp/Config/FuseConfig.cs", "max_forks_repo_name": "omniaretail/zapp", "max_forks_repo_forks_event_min_datetime": "2017-09-19T07:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-24T04:20:07.000Z"} | {"max_stars_count": 5.0, "max_issues_count": 7.0, "max_forks_count": 2.0, "avg_line_length": 36.5138888889, "max_line_length": 107, "alphanum_fraction": 0.6162038798} | using Newtonsoft.Json;
using System.Collections.Generic;
namespace Zapp.Config
{
/// <summary>
/// Represents a class used for configurating the fusions.
/// </summary>
public class FuseConfig
{
/// <summary>
/// Represents the root folder for the fusion packs.
/// </summary>
[JsonProperty("rootDir")]
public string RootDirectory { get; set; } = "{zappDir}/fuse/";
/// <summary>
/// Represents the pattern for packing entries.
/// </summary>
[JsonProperty("entryPattern")]
public string EntryPattern { get; set; } = "*.{dll,exe}";
/// <summary>
/// Represents the pattern for extracting fusions.
/// </summary>
[JsonProperty("fusionDirPattern")]
public string FusionDirectoryPattern { get; set; } = "{fusionId}_{epoch}/";
/// <summary>
/// Represents a collection of configuration for fusions.
/// </summary>
[JsonProperty("fusions")]
public List<FusePackConfig> Fusions { get; set; } = new List<FusePackConfig>();
/// <summary>
/// Represents a security configuration for loading unknown assemblies.
/// </summary>
[JsonProperty("isLoadFromRemoteSourcesEnabled")]
public bool IsLoadFromRemoteSourcesEnabled { get; set; } = false;
/// <summary>
/// Represents a configuration to enable per-process garbage collection threads.
/// </summary>
[JsonProperty("isGcServerEnabled")]
public bool IsGcServerEnabled { get; set; } = false;
/// <summary>
/// Represents a configuration to enable concurrent garbage collection.
/// </summary>
[JsonProperty("isGcConcurrentEnabled")]
public bool IsGcConcurrentEnabled { get; set; } = true;
/// <summary>
/// Represents a configuration to enable garbage collection for very large objects.
/// </summary>
[JsonProperty("isGcVeryLargeObjectsAllowed")]
public bool IsGcVeryLargeObjectsAllowed { get; set; } = false;
/// <summary>
/// Represents a setting that indicates if zapp should ignore an initial schedule failure.
/// </summary>
[JsonProperty("ignoreInitialScheduleFailure")]
public bool IgnoreInitialScheduleFailure = true;
/// <summary>
/// Represents a setting that indicates if zapp is allowed to proceed for fusions without patients.
/// </summary>
[JsonProperty("allowFusionsWithoutPatients")]
public bool AllowFusionsWithoutPatients = false;
}
}
|
||||
TheStack | bdf6bb642b8b7f72462c7f37c226ba8f3445e0c2 | C#code:C# | {"size": 3812, "ext": "cshtml", "max_stars_repo_path": "src/Modules/Laser.Orchard.GDPR/Views/DefinitionTemplates/MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel.cshtml", "max_stars_repo_name": "INVA-Spa/Laser.Orchard.Platform", "max_stars_repo_stars_event_min_datetime": "2018-11-22T18:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T18:44:03.000Z", "max_issues_repo_path": "src/Modules/Laser.Orchard.GDPR/Views/DefinitionTemplates/MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel.cshtml", "max_issues_repo_name": "mkbiltek2019/Laser.Orchard.Platform", "max_issues_repo_issues_event_min_datetime": "2019-11-04T16:08:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T07:10:38.000Z", "max_forks_repo_path": "src/Modules/Laser.Orchard.GDPR/Views/DefinitionTemplates/MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel.cshtml", "max_forks_repo_name": "mkbiltek2019/Laser.Orchard.Platform", "max_forks_repo_forks_event_min_datetime": "2019-04-26T18:10:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T17:28:38.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 15.0, "max_forks_count": 5.0, "avg_line_length": 48.8717948718, "max_line_length": 194, "alphanum_fraction": 0.6177859391} | @model Laser.Orchard.GDPR.ViewModels.MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel
@{
var anonymizationId = Model.AnonymizationDivId + "_MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel";
var erasureId = Model.ErasureDivId + "_MediaLibraryPickerFieldGDPRPartFieldSettingsViewModel";
}
<fieldset>
<div id="@anonymizationId">
<div>
@Html.CheckBoxFor(m => m.AttemptToAnonymizeItems)
<label for="@Html.FieldIdFor(m => m.AttemptToAnonymizeItems)" class="forcheckbox">
@T("We will attempt to anonymize items selected in the field.")
</label>
<span class="hint">
@T("Setting this flag casues Anonymization to propagate to all items selected in the field. CAREFUL: the process is not guaranteed to prevent recursions.")
</span>
</div>
<div>
@Html.CheckBoxFor(m => m.DetachGDPRItemsOnAnonymize)
<label for="@Html.FieldIdFor(m => m.DetachGDPRItemsOnAnonymize)" class="forcheckbox">
@T("Detach items with personal identifiable information after anonymization.")
</label>
<span class="hint">
@T("If this flag is set, after anonymizing the ContentItem for the MediaLibraryPickerField and eventually its selected items, we will unselect those items that have a GDPRPart.")
</span>
</div>
<div>
@Html.CheckBoxFor(m => m.DetachAllItemsOnAnonymize)
<label for="@Html.FieldIdFor(m => m.DetachAllItemsOnAnonymize)" class="forcheckbox">
@T("Detach all items after anonymization.")
</label>
<span class="hint">
@T("If this flag is set, after anonymizing the ContentItem for the MediaLibraryPickerField and eventually its selected items, we will unselect all items.")
</span>
</div>
</div>
<div id="@erasureId">
<div>
@Html.CheckBoxFor(m => m.AttemptToEraseItems)
<label for="@Html.FieldIdFor(m => m.AttemptToEraseItems)" class="forcheckbox">
@T("We will attempt to erase items selected in the field.")
</label>
<span class="hint">
@T("Setting this flag casues Erasure to propagate to all items selected in the field. CAREFUL: the process is not guaranteed to prevent recursions.")
</span>
</div>
<div>
@Html.CheckBoxFor(m => m.DetachGDPRItemsOnErase)
<label for="@Html.FieldIdFor(m => m.DetachGDPRItemsOnErase)" class="forcheckbox">
@T("Detach items with personal identifiable information after erasure.")
</label>
<span class="hint">
@T("If this flag is set, after erasing the ContentItem for the MediaLibraryPickerField and eventually its selected items, we will unselect those items that have a GDPRPart.")
</span>
</div>
<div>
@Html.CheckBoxFor(m => m.DetachAllItemsOnErase)
<label for="@Html.FieldIdFor(m => m.DetachAllItemsOnErase)" class="forcheckbox">
@T("Detach all items after erasure.")
</label>
<span class="hint">
@T("If this flag is set, after erasing the ContentItem for the MediaLibraryPickerField and eventually its selected items, we will unselect all items.")
</span>
</div>
</div>
</fieldset>
@using (Script.Foot()) {
<script>
document
.getElementById('@Model.AnonymizationDivId')
.appendChild(document.getElementById('@anonymizationId'));
document
.getElementById('@Model.ErasureDivId')
.appendChild(document.getElementById('@erasureId'));
</script>
} |
||||
TheStack | bdf6c2e4c563903577966e382596f5576dc0d6b9 | C#code:C# | {"size": 9905, "ext": "cs", "max_stars_repo_path": "sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/ComputeTextureBase.cs", "max_stars_repo_name": "nesrak1/xenko", "max_stars_repo_stars_event_min_datetime": "2019-11-16T16:47:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:09:03.000Z", "max_issues_repo_path": "sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/ComputeTextureBase.cs", "max_issues_repo_name": "kbb-uran/xenko", "max_issues_repo_issues_event_min_datetime": "2019-10-23T16:15:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T01:28:42.000Z", "max_forks_repo_path": "sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/ComputeTextureBase.cs", "max_forks_repo_name": "kbb-uran/xenko", "max_forks_repo_forks_event_min_datetime": "2019-12-08T16:57:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T02:04:49.000Z"} | {"max_stars_count": 34.0, "max_issues_count": 14.0, "max_forks_count": 19.0, "avg_line_length": 38.2432432432, "max_line_length": 197, "alphanum_fraction": 0.5765774861} | // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System.ComponentModel;
using Xenko.Core;
using Xenko.Core.Annotations;
using Xenko.Core.Mathematics;
using Xenko.Graphics;
using Xenko.Shaders;
namespace Xenko.Rendering.Materials.ComputeColors
{
/// <summary>
/// Base class for texture nodes
/// </summary>
[DataContract(Inherited = true)]
[Display("Texture")]
public abstract class ComputeTextureBase : ComputeKeyedBase
{
/// <summary>
/// Initializes a new instance of the <see cref="ComputeTextureColor" /> class.
/// </summary>
/// <param name="texture">The texture.</param>
/// <param name="texcoordIndex">Index of the texcoord.</param>
/// <param name="scale">The scale.</param>
/// <param name="offset">The offset.</param>
protected ComputeTextureBase(Texture texture, TextureCoordinate texcoordIndex, Vector2 scale, Vector2 offset)
{
Enabled = true;
Texture = texture;
TexcoordIndex = texcoordIndex;
Sampler = new ComputeColorParameterSampler();
Scale = scale;
Offset = offset;
Key = null;
}
/// <summary>
/// Gets or sets the enable state of the texture.
/// </summary>
/// <userdoc>If unchecked, ignore the texture value and use the fallback value instead</userdoc>
[DefaultValue(true)]
public bool Enabled { get; set; }
/// <summary>
/// The texture Reference.
/// </summary>
/// <userdoc>
/// The reference to the texture asset
/// </userdoc>
[DataMember(10)]
[DefaultValue(null)]
[Display("Texture")]
[InlineProperty]
public Texture Texture { get; set; }
/// <summary>
/// The texture coordinate used to sample the texture.
/// </summary>
/// <userdoc>
/// The coordinates used to sample the texture
/// </userdoc>
[DataMember(30)]
[DefaultValue(TextureCoordinate.Texcoord0)]
public TextureCoordinate TexcoordIndex { get; set; }
/// <summary>
/// The sampler of the texture.
/// </summary>
/// <userdoc>
/// The texture sampler
/// </userdoc>
[DataMemberIgnore]
private ComputeColorParameterSampler Sampler { get; set; }
/// <summary>
/// The texture filtering mode.
/// </summary>
/// <userdoc>
/// The texture filtering method
/// </userdoc>
[DataMember(41)]
[DefaultValue(TextureFilter.Linear)]
public TextureFilter Filtering
{
get
{
return Sampler.Filtering;
}
set
{
Sampler.Filtering = value;
}
}
/// <summary>
/// The texture address mode.
/// </summary>
/// <userdoc>
/// How to wrap the texture along the U (horizontal) axis
/// </userdoc>
[DataMember(42)]
[DefaultValue(TextureAddressMode.Wrap)]
[Display("Address mode U")]
public TextureAddressMode AddressModeU
{
get
{
return Sampler.AddressModeU;
}
set
{
Sampler.AddressModeU = value;
}
}
/// <summary>
/// The texture address mode.
/// </summary>
/// <userdoc>
/// How to wrap the texture along the V (vertical) axis
/// </userdoc>
[DataMember(43)]
[DefaultValue(TextureAddressMode.Wrap)]
[Display("Address mode V")]
public TextureAddressMode AddressModeV
{
get
{
return Sampler.AddressModeV;
}
set
{
Sampler.AddressModeV = value;
}
}
/// <summary>
/// The scale of the texture coordinates.
/// </summary>
/// <userdoc>
/// The scale to apply to the texture coordinates. Values lower than 1 zoom the texture in; values greater than 1 tile it.
/// </userdoc>
[DataMember(50)]
public Vector2 Scale { get; set; }
/// <summary>
/// The offset in the texture coordinates.
/// </summary>
/// <userdoc>
/// The offset to apply to the model's texture coordinates
/// </userdoc>
[DataMember(60)]
public Vector2 Offset { get; set; }
/// <summary>
/// Uses random texture coordinates.
/// </summary>
/// <userdoc>
/// Sample the input texture with random texture coordinates. This reduces tiling effects produced by high UV scales, but is costly.
/// </userdoc>
[DataMember(70)]
[DefaultValue(false)]
[Display("Use random texture coordinates")]
public bool UseRandomTextureCoordinates { get; set; }
/// <inheritdoc/>
public override string ToString()
{
return "Texture";
}
protected abstract string GetTextureChannelAsString();
public abstract ShaderSource GenerateShaderFromFallbackValue(ShaderGeneratorContext context, MaterialComputeColorKeys baseKeys);
public override ShaderSource GenerateShaderSource(ShaderGeneratorContext context, MaterialComputeColorKeys baseKeys)
{
if (!Enabled || Texture == null) // generate shader from default value when the texture is null or disabled
{
var fallbackValue = GenerateShaderFromFallbackValue(context, baseKeys);
if (fallbackValue != null)
return fallbackValue;
}
// generate shader from the texture
// TODO: Use a generated UsedTexcoordIndex when backing textures
var usedTexcoord = "TEXCOORD" + MaterialUtility.GetTextureIndex(TexcoordIndex);
var textureKey = context.GetTextureKey(this, baseKeys);
var samplerKey = context.GetSamplerKey(Sampler);
UsedKey = textureKey;
var scale = Scale;
var scaleFactor = context.CurrentOverrides.UVScale;
if (scaleFactor != Vector2.One)
{
scale *= scaleFactor;
}
var channelStr = GetTextureChannelAsString();
// "TTEXTURE", "TStream"
ShaderClassSource shaderSource;
// TODO: Workaround bad to have to copy all the new ShaderClassSource(). Check how to improve this
if (context.OptimizeMaterials)
{
var scaleStr = MaterialUtility.GetAsShaderString(scale);
var offsetStr = MaterialUtility.GetAsShaderString(Offset);
// If materials are optimized, we precompute best shader combination (note: will generate shader permutations!)
if (context.IsNotPixelStage)
{
if (Offset != Vector2.Zero)
shaderSource = new ShaderClassSource("ComputeColorTextureLodScaledOffsetSampler", textureKey, usedTexcoord, samplerKey, channelStr, scaleStr, offsetStr, 0.0f);
else if (scale != Vector2.One)
shaderSource = new ShaderClassSource("ComputeColorTextureLodScaledSampler", textureKey, usedTexcoord, samplerKey, channelStr, scaleStr, 0.0f);
else
shaderSource = new ShaderClassSource("ComputeColorTextureLodSampler", textureKey, usedTexcoord, samplerKey, channelStr, 0.0f);
}
else
{
if (Offset != Vector2.Zero)
shaderSource = new ShaderClassSource("ComputeColorTextureScaledOffsetSampler", textureKey, usedTexcoord, samplerKey, channelStr, scaleStr, offsetStr);
else if (scale != Vector2.One)
shaderSource = new ShaderClassSource("ComputeColorTextureScaledSampler", textureKey, usedTexcoord, samplerKey, channelStr, scaleStr);
else
shaderSource = new ShaderClassSource("ComputeColorTextureSampler", textureKey, usedTexcoord, samplerKey, channelStr);
}
}
else
{
// Try to avoid shader permutations, by putting UV scaling/offset in shader parameters
var textureScale = (ValueParameterKey<Vector2>)context.GetParameterKey(MaterialKeys.TextureScale);
var textureOffset = (ValueParameterKey<Vector2>)context.GetParameterKey(MaterialKeys.TextureOffset);
context.Parameters.Set(textureScale, scale);
context.Parameters.Set(textureOffset, Offset);
if (context.IsNotPixelStage)
{
shaderSource = new ShaderClassSource("ComputeColorTextureLodScaledOffsetDynamicSampler", textureKey, usedTexcoord, samplerKey, channelStr, textureScale, textureOffset, 0.0f);
}
else
{
if (UseRandomTextureCoordinates)
shaderSource = new ShaderClassSource("ComputeColorTextureScaledOffsetDynamicSamplerRandomUV", textureKey, usedTexcoord, samplerKey, channelStr, textureScale, textureOffset);
else
shaderSource = new ShaderClassSource("ComputeColorTextureScaledOffsetDynamicSampler", textureKey, usedTexcoord, samplerKey, channelStr, textureScale, textureOffset);
}
}
return shaderSource;
}
}
}
|
||||
TheStack | bdf71286eb23ee513911440ab05cd53347381ff0 | C#code:C# | {"size": 759, "ext": "cs", "max_stars_repo_path": "NetSiteUtilities/AopApi/Domain/AlipayItemOperationContext.cs", "max_stars_repo_name": "erikzhouxin/CSharpSolution", "max_stars_repo_stars_event_min_datetime": "2019-10-07T05:51:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-07T05:51:25.000Z", "max_issues_repo_path": "NetSiteUtilities/AopApi/Domain/AlipayItemOperationContext.cs", "max_issues_repo_name": "erikzhouxin/CSharpSolution", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetSiteUtilities/AopApi/Domain/AlipayItemOperationContext.cs", "max_forks_repo_name": "erikzhouxin/CSharpSolution", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.4838709677, "max_line_length": 55, "alphanum_fraction": 0.5718050066} | using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayItemOperationContext Data Structure.
/// </summary>
[Serializable]
public class AlipayItemOperationContext : AopObject
{
/// <summary>
/// 商品创建者,商户授权模式此值不需要填写。
/// </summary>
[XmlElement("creator")]
public string Creator { get; set; }
/// <summary>
/// 操作角色类型,授权授权模式下此值不需要填写。
/// </summary>
[XmlElement("op_role")]
public string OpRole { get; set; }
/// <summary>
/// 商户ID,如果商户传入此值,将以此商户ID作为业务主体,商户授权模式此值不需要填写。
/// </summary>
[XmlElement("partner_id")]
public string PartnerId { get; set; }
}
}
|
||||
TheStack | bdf7edd10f047ed5f52e6fee11e15a67f1d693ca | C#code:C# | {"size": 827, "ext": "cs", "max_stars_repo_path": "Daniel15.BusinessLayer/Services/CodeRepositories/RepositoryInfo.cs", "max_stars_repo_name": "niranjan2m/test", "max_stars_repo_stars_event_min_datetime": "2015-05-20T07:31:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T15:15:42.000Z", "max_issues_repo_path": "Daniel15.BusinessLayer/Services/CodeRepositories/RepositoryInfo.cs", "max_issues_repo_name": "niranjan2m/test", "max_issues_repo_issues_event_min_datetime": "2015-03-09T06:10:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T09:54:37.000Z", "max_forks_repo_path": "Daniel15.BusinessLayer/Services/CodeRepositories/RepositoryInfo.cs", "max_forks_repo_name": "niranjan2m/test", "max_forks_repo_forks_event_min_datetime": "2015-02-06T08:26:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:54:34.000Z"} | {"max_stars_count": 25.0, "max_issues_count": 24.0, "max_forks_count": 24.0, "avg_line_length": 22.3513513514, "max_line_length": 66, "alphanum_fraction": 0.6348246675} | using System;
namespace Daniel15.BusinessLayer.Services.CodeRepositories
{
// TODO: Move to DTO assembly
/// <summary>
/// Represents information on a code repository
/// </summary>
public class RepositoryInfo
{
/// <summary>
/// Number of forks the repository has.
/// </summary>
public int? Forks { get; set; }
/// <summary>
/// Number of "watchers" (users watching it) the repository has.
/// </summary>
public int? Watchers { get; set; }
/// <summary>
/// Number of bugs or issues the repository has.
/// </summary>
public int? OpenIssues { get; set; }
/// <summary>
/// Date the repository was created
/// </summary>
public DateTime? Created { get; set; }
/// <summary>
/// Date the repository was last updated
/// </summary>
public DateTime? Updated { get; set; }
}
}
|
||||
TheStack | bdf9189fc7c6c3dc97e7f9373fd844829af6449a | C#code:C# | {"size": 3759, "ext": "cs", "max_stars_repo_path": "Util/WellKnownPeer/Properties/Settings.Designer.cs", "max_stars_repo_name": "ekzyis/CrypTool-2", "max_stars_repo_stars_event_min_datetime": "2021-09-29T14:50:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:01:21.000Z", "max_issues_repo_path": "Util/WellKnownPeer/Properties/Settings.Designer.cs", "max_issues_repo_name": "ekzyis/CrypTool-2", "max_issues_repo_issues_event_min_datetime": "2021-12-24T22:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-25T10:03:13.000Z", "max_forks_repo_path": "Util/WellKnownPeer/Properties/Settings.Designer.cs", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_forks_event_min_datetime": "2021-10-17T19:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T02:57:57.000Z"} | {"max_stars_count": 12.0, "max_issues_count": 15.0, "max_forks_count": 10.0, "avg_line_length": 37.9696969697, "max_line_length": 151, "alphanum_fraction": 0.5661080074} | //------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WellKnownPeer.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("RootCertificate.crt")]
public string RootCertificate {
get {
return ((string)(this["RootCertificate"]));
}
set {
this["RootCertificate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("anonymous.p12")]
public string OwnKey {
get {
return ((string)(this["OwnKey"]));
}
set {
this["OwnKey"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("anonymous")]
public string OwnPassword {
get {
return ((string)(this["OwnPassword"]));
}
set {
this["OwnPassword"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string WellKnownPeers {
get {
return ((string)(this["WellKnownPeers"]));
}
set {
this["WellKnownPeers"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("kopal;niko")]
public string Administrators {
get {
return ((string)(this["Administrators"]));
}
set {
this["Administrators"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string BannedCertificates {
get {
return ((string)(this["BannedCertificates"]));
}
set {
this["BannedCertificates"] = value;
}
}
}
}
|
||||
TheStack | bdfa9f0a49dab8c7ca1e9612aaf312778adff775 | C#code:C# | {"size": 393, "ext": "cs", "max_stars_repo_path": "ElasticSearch7Template.Utility/ApiLogModel/WebApiExceptionLogModel.cs", "max_stars_repo_name": "xubb1988/ElasticSearch7Template", "max_stars_repo_stars_event_min_datetime": "2020-01-14T09:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T18:31:18.000Z", "max_issues_repo_path": "ElasticSearch7Template.Utility/ApiLogModel/WebApiExceptionLogModel.cs", "max_issues_repo_name": "xubb1988/ElasticSearch7Template", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ElasticSearch7Template.Utility/ApiLogModel/WebApiExceptionLogModel.cs", "max_forks_repo_name": "xubb1988/ElasticSearch7Template", "max_forks_repo_forks_event_min_datetime": "2020-01-14T06:47:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-14T06:47:11.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 20.6842105263, "max_line_length": 56, "alphanum_fraction": 0.5216284987} | namespace ElasticSearch7Template.Utility
{
/// <summary>
/// webapi异常日志类
/// </summary>
public class WebApiExceptionLogModel: WebApiLogModel
{
/// <summary>
/// 异常信息
/// </summary>
public string ExceptionMessage { get; set; }
/// <summary>
/// 状态码
/// </summary>
public int StatusCode { get; set; }
}
}
|
||||
TheStack | bdfac2d93970a56e672d3e6dcb0461e61bcdd6a3 | C#code:C# | {"size": 69063, "ext": "cs", "max_stars_repo_path": "sourceCode/dotNet4.6/ndp/cdf/src/NetFx20/system.transactions/System/Transactions/Oletx/OleTxTransaction.cs", "max_stars_repo_name": "csoap/csoap.github.io", "max_stars_repo_stars_event_min_datetime": "2017-03-03T02:13:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T09:59:56.000Z", "max_issues_repo_path": "sourceCode/dotNet4.6/ndp/cdf/src/NetFx20/system.transactions/System/Transactions/Oletx/OleTxTransaction.cs", "max_issues_repo_name": "295007712/295007712.github.io", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sourceCode/dotNet4.6/ndp/cdf/src/NetFx20/system.transactions/System/Transactions/Oletx/OleTxTransaction.cs", "max_forks_repo_name": "295007712/295007712.github.io", "max_forks_repo_forks_event_min_datetime": "2016-11-15T05:20:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T16:32:11.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 41.5291641612, "max_line_length": 198, "alphanum_fraction": 0.5336721544} | //-----------------------------------------------------------------------------
// <copyright file="OletxTransaction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
using System.Transactions.Diagnostics;
namespace System.Transactions.Oletx
{
/// <summary>
/// A Transaction object represents a single transaction. It is created by TransactionManager
/// objects through CreateTransaction or through deserialization. Alternatively, the static Create
/// methodis provided, which creates a "default" TransactionManager and requests that it create
/// a new transaction with default values. A transaction can only be committed by
/// the client application that created the transaction. If a client application wishes to allow
/// access to the transaction by multiple threads, but wants to prevent those other threads from
/// committing the transaction, the application can make a "clone" of the transaction. Transaction
/// clones have the same capabilities as the original transaction, except for the ability to commit
/// the transaction.
/// </summary>
[Serializable]
internal class OletxTransaction : ISerializable, IObjectReference
{
// We have a strong reference on realOletxTransaction which does the real work
internal RealOletxTransaction realOletxTransaction = null;
// String that is used as a name for the propagationToken
// while serializing and deserializing this object
protected const string propagationTokenString = "OletxTransactionPropagationToken";
// When an OletxTransaction is being created via deserialization, this member is
// filled with the propagation token from the serialization info. Later, when
// GetRealObject is called, this array is used to decide whether or not a new
// transation needs to be created and if so, to create the transaction.
private byte[] propagationTokenForDeserialize = null;
protected int disposed = 0;
// In GetRealObject, we ask LTM if it has a promoted transaction with the same ID. If it does,
// we need to remember that transaction because GetRealObject is called twice during
// deserialization. In this case, GetRealObject returns the LTM transaction, not this OletxTransaction.
// The OletxTransaction will get GC'd because there will be no references to it.
internal Transaction savedLtmPromotedTransaction = null;
private TransactionTraceIdentifier traceIdentifier = TransactionTraceIdentifier.Empty;
// Property
internal RealOletxTransaction RealTransaction
{
get
{
return this.realOletxTransaction;
}
}
internal Guid Identifier
{
get
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.get_Identifier"
);
}
Guid returnValue = this.realOletxTransaction.Identifier;
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.get_Identifier"
);
}
return returnValue;
}
}
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (this.realOletxTransaction != null && this.realOletxTransaction.InternalTransaction != null)
{
returnValue = this.realOletxTransaction.InternalTransaction.DistributedTxId;
}
return returnValue;
}
}
internal System.Transactions.TransactionStatus Status
{
get
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.get_Status"
);
}
TransactionStatus returnValue = this.realOletxTransaction.Status;
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.get_Status"
);
}
return returnValue;
}
}
internal Exception InnerException
{
get
{
return this.realOletxTransaction.innerException;
}
}
internal OletxTransaction(RealOletxTransaction realOletxTransaction)
{
this.realOletxTransaction = realOletxTransaction;
// Tell the realOletxTransaction that we are here.
this.realOletxTransaction.OletxTransactionCreated();
}
protected OletxTransaction(SerializationInfo serializationInfo, StreamingContext context)
{
if (serializationInfo == null)
{
throw new ArgumentNullException( "serializationInfo");
}
// Simply store the propagation token from the serialization info. GetRealObject will
// decide whether or not we will use it.
propagationTokenForDeserialize = (byte[])serializationInfo.GetValue(propagationTokenString, typeof(byte[]));
if ( propagationTokenForDeserialize.Length < 24 )
{
throw new ArgumentException( SR.GetString( SR.InvalidArgument ), "serializationInfo" );
}
}
public object GetRealObject(
StreamingContext context
)
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"IObjectReference.GetRealObject"
);
}
if ( null == propagationTokenForDeserialize )
{
if ( DiagnosticTrace.Critical )
{
InternalErrorTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
SR.GetString( SR.UnableToDeserializeTransaction )
);
}
throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.UnableToDeserializeTransactionInternalError ), null );
}
// This may be a second call. If so, just return.
if ( null != this.savedLtmPromotedTransaction )
{
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"IObjectReference.GetRealObject"
);
}
return this.savedLtmPromotedTransaction;
}
Transaction returnValue = TransactionInterop.GetTransactionFromTransmitterPropagationToken( propagationTokenForDeserialize );
Debug.Assert( null != returnValue, "OletxTransaction.GetRealObject - GetTxFromPropToken returned null" );
this.savedLtmPromotedTransaction = returnValue;
if ( DiagnosticTrace.Verbose )
{
TransactionDeserializedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
returnValue.internalTransaction.PromotedTransaction.TransactionTraceId
);
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"IObjectReference.GetRealObject"
);
}
return returnValue;
}
/// <summary>
/// Implementation of IDisposable.Dispose. Releases managed, and unmanaged resources
/// associated with the Transaction object.
/// </summary>
internal void Dispose()
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"IDisposable.Dispose"
);
}
int localDisposed = Interlocked.CompareExchange( ref this.disposed, 1, 0 );
if ( 0 == localDisposed )
{
this.realOletxTransaction.OletxTransactionDisposed();
}
GC.SuppressFinalize (this);
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"IDisposable.Dispose"
);
}
}
// Specific System.Transactions implementation
/// <summary>
/// Initiates commit processing of the transaction. The caller must have created the transaction
/// as a new transaction through TransactionManager.CreateTransaction or Transaction.Create.
///
/// If the transaction is already aborted due to some other participant making a Rollback call,
/// the transaction timeout period expiring, or some sort of network failure, an exception will
/// be raised.
/// </summary>
/// <summary>
/// Initiates rollback processing of the transaction. This method can be called on any instance
/// of a Transaction class, regardless of how the Transaction was obtained. It is possible for this
/// method to be called "too late", after the outcome of the transaction has already been determined.
/// In this case, an exception is raised.
internal void Rollback()
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.Rollback"
);
}
if ( DiagnosticTrace.Warning )
{
TransactionRollbackCalledTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
this.TransactionTraceId
);
}
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
this.realOletxTransaction.Rollback();
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.Rollback"
);
}
}
internal IPromotedEnlistment EnlistVolatile(
ISinglePhaseNotificationInternal singlePhaseNotification,
EnlistmentOptions enlistmentOptions
)
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistVolatile( ISinglePhaseNotificationInternal )"
);
}
Debug.Assert( null != singlePhaseNotification, "Argument is null" );
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
if ( this.realOletxTransaction == null || this.realOletxTransaction.TooLateForEnlistments )
{
throw TransactionException.Create(SR.GetString(SR.TraceSourceOletx),
SR.GetString(SR.TooLate), null, this.DistributedTxId);
}
IPromotedEnlistment enlistment = realOletxTransaction.EnlistVolatile(
singlePhaseNotification,
enlistmentOptions,
this
);
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistVolatile( ISinglePhaseNotificationInternal )"
);
}
return enlistment;
}
internal IPromotedEnlistment EnlistVolatile(
IEnlistmentNotificationInternal enlistmentNotification,
EnlistmentOptions enlistmentOptions
)
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistVolatile( IEnlistmentNotificationInternal )"
);
}
Debug.Assert( null != enlistmentNotification, "Argument is null" );
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
if ( this.realOletxTransaction == null || this.realOletxTransaction.TooLateForEnlistments )
{
throw TransactionException.Create(SR.GetString(SR.TraceSourceOletx),
SR.GetString(SR.TooLate), null, this.DistributedTxId);
}
IPromotedEnlistment enlistment = realOletxTransaction.EnlistVolatile(
enlistmentNotification,
enlistmentOptions,
this
);
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistVolatile( IEnlistmentNotificationInternal )"
);
}
return enlistment;
}
internal IPromotedEnlistment EnlistDurable(
Guid resourceManagerIdentifier,
ISinglePhaseNotificationInternal singlePhaseNotification,
bool canDoSinglePhase,
EnlistmentOptions enlistmentOptions
)
{
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistDurable( ISinglePhaseNotificationInternal )"
);
}
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
if ( this.realOletxTransaction == null || this.realOletxTransaction.TooLateForEnlistments )
{
throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ),
SR.GetString( SR.TooLate ), null, this.DistributedTxId);
}
// get the Oletx TM from the real class
OletxTransactionManager oletxTM = realOletxTransaction.OletxTransactionManagerInstance;
// get the resource manager from the Oletx TM
OletxResourceManager rm = oletxTM.FindOrRegisterResourceManager(resourceManagerIdentifier);
// ask the rm to do the durable enlistment
OletxEnlistment enlistment = rm.EnlistDurable(
this,
canDoSinglePhase,
singlePhaseNotification,
enlistmentOptions
);
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.EnlistDurable( ISinglePhaseNotificationInternal )"
);
}
return enlistment;
}
internal OletxDependentTransaction DependentClone(
bool delayCommit
)
{
OletxDependentTransaction dependentClone = null;
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.DependentClone"
);
}
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
if (TransactionStatus.Aborted == Status)
{
throw TransactionAbortedException.Create(SR.GetString(SR.TraceSourceOletx), SR.GetString(SR.TransactionAborted), realOletxTransaction.innerException, this.DistributedTxId);
}
if (TransactionStatus.InDoubt == Status)
{
throw TransactionInDoubtException.Create(SR.GetString(SR.TraceSourceOletx), SR.GetString(SR.TransactionIndoubt), realOletxTransaction.innerException, this.DistributedTxId);
}
if (TransactionStatus.Active != Status)
{
throw TransactionException.Create(SR.GetString(SR.TraceSourceOletx), SR.GetString(SR.TransactionAlreadyOver), null, this.DistributedTxId);
}
dependentClone = new OletxDependentTransaction( realOletxTransaction, delayCommit );
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.DependentClone"
);
}
return dependentClone;
}
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if ( TransactionTraceIdentifier.Empty == this.traceIdentifier )
{
lock ( this.realOletxTransaction )
{
if ( TransactionTraceIdentifier.Empty == this.traceIdentifier )
{
try
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier( this.realOletxTransaction.Identifier.ToString(), 0 );
Thread.MemoryBarrier();
this.traceIdentifier = temp;
}
catch ( TransactionException ex )
{
// realOletxTransaction.Identifier throws a TransactionException if it can't determine the guid of the
// transaction because the transaction was already committed or aborted before the RealOletxTransaction was
// created. If that happens, we don't want to throw just because we are trying to trace. So just use
// the TransactionTraceIdentifier.Empty.
if ( DiagnosticTrace.Verbose )
{
ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
ex );
}
}
}
}
}
return this.traceIdentifier;
}
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public void GetObjectData(SerializationInfo serializationInfo, StreamingContext context)
{
if (serializationInfo == null)
{
throw new ArgumentNullException( "serializationInfo");
}
byte[] propagationToken = null;
if ( DiagnosticTrace.Verbose )
{
MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.GetObjectData"
);
}
Debug.Assert( ( 0 == this.disposed ), "OletxTransction object is disposed" );
propagationToken = TransactionInterop.GetTransmitterPropagationToken( this );
serializationInfo.SetType( typeof( OletxTransaction ) );
serializationInfo.AddValue(propagationTokenString, propagationToken);
if ( DiagnosticTrace.Information )
{
TransactionSerializedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
this.TransactionTraceId
);
}
if ( DiagnosticTrace.Verbose )
{
MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
"OletxTransaction.GetObjectData"
);
}
}
virtual public System.Transactions.IsolationLevel IsolationLevel
{
get { return ( this.realOletxTransaction.TransactionIsolationLevel ); }
}
}
// Internal class used by OletxTransaction class which is public
internal class RealOletxTransaction
{
// Transaction manager
private OletxTransactionManager oletxTransactionManager;
private ITransactionShim transactionShim;
// guid related to transaction
private System.Guid txGuid;
// Isolation level of the transaction
private IsolationLevel isolationLevel;
// Record the exception that caused the transaction to abort.
internal Exception innerException;
// Store status
private TransactionStatus status;
// This is the count of undisposed OletxTransaction objects that reference
// this RealOletxTransaction. This is incremented when an OletxTransaction is created
// and decremented when OletxTransactionDisposed is
// called. When it is decremented to zero, the transactionShim
// field is "released", thus releasing the unmanged proxy interface
// pointer.
private int undisposedOletxTransactionCount;
// The list of containers for phase0 volatile enlistment multiplexing so we only enlist with the proxy once per wave.
// The last one on the list is the "current" one.
internal ArrayList phase0EnlistVolatilementContainerList;
// The container for phase1 volatile enlistment multiplexing so we only enlist with the proxy once.
internal OletxPhase1VolatileEnlistmentContainer phase1EnlistVolatilementContainer;
// Used to get outcomes of transactions with a voter.
private OutcomeEnlistment outcomeEnlistment = null;
// This is a count of volatile and Phase0 durable enlistments on this transaction that have not yet voted.
// This is incremented when an enlistment is made and decremented when the
// enlistment votes. It is checked in Rollback. If the count is greater than 0,
// then the doomed field is set to true and the Rollback is allowed. If the count
// is zero in Rollback, the rollback is rejected with a "too late" exception.
// All checking and modification of this field needs to be done under a lock( this ).
private int undecidedEnlistmentCount = 0;
// If true, indicates that the transaction should NOT commit. This is set to
// true if Rollback is called when there are outstanding enlistments. This is
// checked when enlistments vote Prepared. If true, then the enlistment's vote
// is turned into a ForceRollback. All checking and modification of this field
// needs to be done under a lock (this).
private bool doomed = false;
// This property is used to allocate enlistment identifiers for enlistment trace identifiers.
// It is only incremented when a new enlistment is created for this instance of RealOletxTransaction.
// Enlistments on all clones of this Real transaction use this value.
internal int enlistmentCount = 0;
private DateTime creationTime;
private DateTime lastStateChangeTime;
private TransactionTraceIdentifier traceIdentifier = TransactionTraceIdentifier.Empty;
// This field is set directly from the OletxCommittableTransaction constructor. It will be null
// for non-root RealOletxTransactions.
internal OletxCommittableTransaction committableTransaction;
// This is an internal OletxTransaction. It is created as part of the RealOletxTransaction constructor.
// It is used by the DependentCloneEnlistments when creating their volatile enlistments.
internal OletxTransaction internalClone;
// This is set initialized to false. It is set to true when the OletxPhase1VolatileContainer gets a VoteRequest or
// when any OletxEnlistment attached to this transaction gets a PrepareRequest. At that point, it is too late for any
// more enlistments.
private bool tooLateForEnlistments;
// This is the InternalTransaction that instigated creation of this RealOletxTransaction. When we get the outcome
// of the transaction, we use this to notify the InternalTransaction of the outcome. We do this to avoid the LTM
// always creating a volatile enlistment just to get the outcome.
private InternalTransaction internalTransaction;
internal InternalTransaction InternalTransaction
{
get
{
return this.internalTransaction;
}
set
{
this.internalTransaction = value;
}
}
internal OletxTransactionManager OletxTransactionManagerInstance
{
get
{
return oletxTransactionManager;
}
}
internal Guid Identifier
{
get
{
// The txGuid will be empty if the oletx transaction was already committed or aborted when we
// tried to create the RealOletxTransaction. We still allow creation of the RealOletxTransaction
// for COM+ interop purposes, but we can't get the guid or the status of the transaction.
if ( txGuid.Equals( Guid.Empty ) )
{
throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString ( SR.CannotGetTransactionIdentifier ), null );
}
return this.txGuid;
}
}
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (this.InternalTransaction != null)
{
returnValue = this.InternalTransaction.DistributedTxId;
}
return returnValue;
}
}
internal IsolationLevel TransactionIsolationLevel
{
get
{
return this.isolationLevel;
}
}
internal TransactionStatus Status
{
get
{
return this.status;
}
}
internal System.Guid TxGuid
{
get
{
return this.txGuid;
}
}
internal void IncrementUndecidedEnlistments()
{
// Avoid taking a lock on the transaction here. Decrement
// will be called by a thread owning a lock on enlistment
// containers. When creating new enlistments the transaction
// will attempt to get a lock on the container when it
// already holds a lock on the transaction. This can result
// in a deadlock.
Interlocked.Increment(ref this.undecidedEnlistmentCount);
}
internal void DecrementUndecidedEnlistments()
{
// Avoid taking a lock on the transaction here. Decrement
// will be called by a thread owning a lock on enlistment
// containers. When creating new enlistments the transaction
// will attempt to get a lock on the container when it
// already holds a lock on the transaction. This can result
// in a deadlock.
Interlocked.Decrement(ref this.undecidedEnlistmentCount);
}
internal int UndecidedEnlistments
{
get
{
return this.undecidedEnlistmentCount;
}
}
internal bool Doomed
{
get
{
return this.doomed;
}
}
internal ITransactionShim TransactionShim
{
get
{
ITransactionShim shim = this.transactionShim;
if ( null == shim )
{
throw TransactionInDoubtException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString(SR.TransactionIndoubt), null, this.DistributedTxId );
}
return shim;
}
}
// Common constructor used by all types of constructors
// Create a clean and fresh transaction.
internal RealOletxTransaction(OletxTransactionManager transactionManager,
ITransactionShim transactionShim,
OutcomeEnlistment outcomeEnlistment,
Guid identifier,
OletxTransactionIsolationLevel oletxIsoLevel,
bool isRoot )
{
bool successful = false;
try
{
// initialize the member fields
this.oletxTransactionManager = transactionManager;
this.transactionShim = transactionShim;
this.outcomeEnlistment = outcomeEnlistment;
this.txGuid = identifier;
this.isolationLevel = OletxTransactionManager.ConvertIsolationLevelFromProxyValue( oletxIsoLevel );
this.status = TransactionStatus.Active;
this.undisposedOletxTransactionCount = 0;
this.phase0EnlistVolatilementContainerList = null;
this.phase1EnlistVolatilementContainer = null;
this.tooLateForEnlistments = false;
this.internalTransaction = null;
this.creationTime = DateTime.UtcNow;
this.lastStateChangeTime = this.creationTime;
// Connect this object with the OutcomeEnlistment.
this.internalClone = new OletxTransaction( this );
// We have have been created without an outcome enlistment if it was too late to create
// a clone from the ITransactionNative that we were created from.
if ( null != this.outcomeEnlistment )
{
this.outcomeEnlistment.SetRealTransaction( this );
}
else
{
this.status = TransactionStatus.InDoubt;
}
if ( DiagnosticTrace.HaveListeners )
{
DiagnosticTrace.TraceTransfer(this.txGuid);
}
successful = true;
}
finally
{
if (!successful)
{
if (this.outcomeEnlistment != null)
{
this.outcomeEnlistment.UnregisterOutcomeCallback();
this.outcomeEnlistment = null;
}
}
}
}
internal bool TooLateForEnlistments
{
get
{
return this.tooLateForEnlistments;
}
set
{
this.tooLateForEnlistments = value;
}
}
internal OletxVolatileEnlistmentContainer AddDependentClone( bool delayCommit )
{
IPhase0EnlistmentShim phase0Shim = null;
IVoterBallotShim voterShim = null;
bool needVoterEnlistment = false;
bool needPhase0Enlistment = false;
OletxVolatileEnlistmentContainer returnValue = null;
OletxPhase0VolatileEnlistmentContainer localPhase0VolatileContainer = null;
OletxPhase1VolatileEnlistmentContainer localPhase1VolatileContainer = null;
bool enlistmentSucceeded = false;
bool phase0ContainerLockAcquired = false;
IntPtr phase0Handle = IntPtr.Zero;
// Yes, we are talking to the proxy while holding the lock on the RealOletxTransaction.
// If we don't then things get real sticky with other threads allocating containers.
// We only do this the first time we get a depenent clone of a given type (delay vs. non-delay).
// After that, we don't create a new container, except for Phase0 if we need to create one
// for a second wave.
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock ( this )
{
if ( delayCommit )
{
if ( null == this.phase0EnlistVolatilementContainerList )
{
// Not using a MemoryBarrier because all access to this member variable is under a lock of the
// object.
this.phase0EnlistVolatilementContainerList = new ArrayList(1);
}
// We may have failed the proxy enlistment for the first container, but we would have
// allocated the list. That is why we have this check here.
if ( 0 == this.phase0EnlistVolatilementContainerList.Count )
{
localPhase0VolatileContainer = new OletxPhase0VolatileEnlistmentContainer( this );
needPhase0Enlistment = true;
}
else
{
localPhase0VolatileContainer = this.phase0EnlistVolatilementContainerList[this.phase0EnlistVolatilementContainerList.Count - 1] as OletxPhase0VolatileEnlistmentContainer;
if (localPhase0VolatileContainer != null)
{
//CSDMain 91509 - We now synchronize this call with the shim notification trying to call Phase0Request on this container
TakeContainerLock(localPhase0VolatileContainer, ref phase0ContainerLockAcquired);
}
if ( ! localPhase0VolatileContainer.NewEnlistmentsAllowed )
{
//It is OK to release the lock at this time because we are creating a new container that has not yet
//been enlisted with DTC. So there is no ---- to worry about
ReleaseContainerLock(localPhase0VolatileContainer, ref phase0ContainerLockAcquired);
localPhase0VolatileContainer = new OletxPhase0VolatileEnlistmentContainer( this );
needPhase0Enlistment = true;
}
else
{
needPhase0Enlistment = false;
}
}
if ( needPhase0Enlistment )
{
// We need to create a VoterNotifyShim if native threads are not allowed to enter managed code.
phase0Handle = HandleTable.AllocHandle( localPhase0VolatileContainer );
}
}
else // ! delayCommit
{
if ( null == this.phase1EnlistVolatilementContainer )
{
localPhase1VolatileContainer = new OletxPhase1VolatileEnlistmentContainer( this );
needVoterEnlistment = true;
// We need to create a VoterNotifyShim.
localPhase1VolatileContainer.voterHandle =
HandleTable.AllocHandle( localPhase1VolatileContainer );
}
else
{
needVoterEnlistment = false;
localPhase1VolatileContainer = this.phase1EnlistVolatilementContainer;
}
}
try
{
//At this point, we definitely need the lock on the phase0 container so that it doesnt ---- with shim notifications from unmanaged code
//corrupting state while we are in the middle of an AddDependentClone processing
if (localPhase0VolatileContainer != null)
{
TakeContainerLock(localPhase0VolatileContainer, ref phase0ContainerLockAcquired);
}
// If enlistDuringPrepareRequired is true, we need to ask the proxy to create a Phase0 enlistment.
if ( needPhase0Enlistment )
{
// We need to use shims if native threads are not allowed to enter managed code.
this.transactionShim.Phase0Enlist(
phase0Handle,
out phase0Shim );
localPhase0VolatileContainer.Phase0EnlistmentShim = phase0Shim;
}
if ( needVoterEnlistment )
{
// We need to use shims if native threads are not allowed to enter managed code.
OletxTransactionManagerInstance.dtcTransactionManagerLock.AcquireReaderLock( -1 );
try
{
this.transactionShim.CreateVoter(
localPhase1VolatileContainer.voterHandle,
out voterShim );
enlistmentSucceeded = true;
}
finally
{
OletxTransactionManagerInstance.dtcTransactionManagerLock.ReleaseReaderLock();
}
localPhase1VolatileContainer.VoterBallotShim = voterShim;
}
if ( delayCommit )
{
// if we needed a Phase0 enlistment, we need to add the container to the
// list.
if ( needPhase0Enlistment )
{
this.phase0EnlistVolatilementContainerList.Add( localPhase0VolatileContainer );
}
localPhase0VolatileContainer.AddDependentClone();
returnValue = localPhase0VolatileContainer;
}
else
{
// If we needed a voter enlistment, we need to save the container as THE
// phase1 container for this transaction.
if ( needVoterEnlistment )
{
Debug.Assert( ( null == this.phase1EnlistVolatilementContainer ),
"RealOletxTransaction.AddDependentClone - phase1VolContainer not null when expected" );
this.phase1EnlistVolatilementContainer = localPhase1VolatileContainer;
}
localPhase1VolatileContainer.AddDependentClone();
returnValue = localPhase1VolatileContainer;
}
}
catch (COMException comException)
{
OletxTransactionManager.ProxyException( comException );
throw;
}
}
}
finally
{
//First release the lock on the phase 0 container if it was acquired. Any work on localPhase0VolatileContainer
//that needs its state to be consistent while processing should do so before this statement is executed.
if (localPhase0VolatileContainer != null)
{
ReleaseContainerLock(localPhase0VolatileContainer, ref phase0ContainerLockAcquired);
}
if ( phase0Handle != IntPtr.Zero && localPhase0VolatileContainer.Phase0EnlistmentShim == null )
{
HandleTable.FreeHandle( phase0Handle );
}
if ( !enlistmentSucceeded &&
null != localPhase1VolatileContainer &&
localPhase1VolatileContainer.voterHandle != IntPtr.Zero &&
needVoterEnlistment )
{
HandleTable.FreeHandle( localPhase1VolatileContainer.voterHandle );
}
}
return returnValue;
}
void ReleaseContainerLock(OletxPhase0VolatileEnlistmentContainer localPhase0VolatileContainer, ref bool phase0ContainerLockAcquired)
{
if (phase0ContainerLockAcquired)
{
Monitor.Exit(localPhase0VolatileContainer);
phase0ContainerLockAcquired = false;
}
}
void TakeContainerLock(OletxPhase0VolatileEnlistmentContainer localPhase0VolatileContainer, ref bool phase0ContainerLockAcquired)
{
if (!phase0ContainerLockAcquired)
{
#pragma warning disable 0618
//@
Monitor.Enter(localPhase0VolatileContainer);
#pragma warning restore 0618
phase0ContainerLockAcquired = true;
}
}
internal IPromotedEnlistment CommonEnlistVolatile(
IEnlistmentNotificationInternal enlistmentNotification,
EnlistmentOptions enlistmentOptions,
OletxTransaction oletxTransaction
)
{
OletxVolatileEnlistment enlistment = null;
bool needVoterEnlistment = false;
bool needPhase0Enlistment = false;
OletxPhase0VolatileEnlistmentContainer localPhase0VolatileContainer = null;
OletxPhase1VolatileEnlistmentContainer localPhase1VolatileContainer = null;
IntPtr phase0Handle = IntPtr.Zero;
IVoterBallotShim voterShim = null;
IPhase0EnlistmentShim phase0Shim = null;
bool enlistmentSucceeded = false;
// Yes, we are talking to the proxy while holding the lock on the RealOletxTransaction.
// If we don't then things get real sticky with other threads allocating containers.
// We only do this the first time we get a depenent clone of a given type (delay vs. non-delay).
// After that, we don't create a new container, except for Phase0 if we need to create one
// for a second wave.
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock ( this )
{
enlistment = new OletxVolatileEnlistment(
enlistmentNotification,
enlistmentOptions,
oletxTransaction
);
if ( (enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0 )
{
if ( null == this.phase0EnlistVolatilementContainerList )
{
// Not using a MemoryBarrier because all access to this member variable is done when holding
// a lock on the object.
this.phase0EnlistVolatilementContainerList = new ArrayList(1);
}
// We may have failed the proxy enlistment for the first container, but we would have
// allocated the list. That is why we have this check here.
if ( 0 == this.phase0EnlistVolatilementContainerList.Count )
{
localPhase0VolatileContainer = new OletxPhase0VolatileEnlistmentContainer( this );
needPhase0Enlistment = true;
}
else
{
localPhase0VolatileContainer = this.phase0EnlistVolatilementContainerList[this.phase0EnlistVolatilementContainerList.Count - 1] as OletxPhase0VolatileEnlistmentContainer;
if ( ! localPhase0VolatileContainer.NewEnlistmentsAllowed )
{
localPhase0VolatileContainer = new OletxPhase0VolatileEnlistmentContainer( this );
needPhase0Enlistment = true;
}
else
{
needPhase0Enlistment = false;
}
}
if ( needPhase0Enlistment )
{
// We need to create a VoterNotifyShim if native threads are not allowed to enter managed code.
phase0Handle = HandleTable.AllocHandle( localPhase0VolatileContainer );
}
}
else // not EDPR = TRUE - may need a voter...
{
if ( null == this.phase1EnlistVolatilementContainer )
{
needVoterEnlistment = true;
localPhase1VolatileContainer = new OletxPhase1VolatileEnlistmentContainer( this );
// We need to create a VoterNotifyShim.
localPhase1VolatileContainer.voterHandle =
HandleTable.AllocHandle( localPhase1VolatileContainer );
}
else
{
needVoterEnlistment = false;
localPhase1VolatileContainer = this.phase1EnlistVolatilementContainer;
}
}
try
{
// If enlistDuringPrepareRequired is true, we need to ask the proxy to create a Phase0 enlistment.
if ( needPhase0Enlistment )
{
lock ( localPhase0VolatileContainer )
{
transactionShim.Phase0Enlist(
phase0Handle,
out phase0Shim );
localPhase0VolatileContainer.Phase0EnlistmentShim = phase0Shim;
}
}
if ( needVoterEnlistment )
{
this.transactionShim.CreateVoter(
localPhase1VolatileContainer.voterHandle,
out voterShim );
enlistmentSucceeded = true;
localPhase1VolatileContainer.VoterBallotShim = voterShim;
}
if ( (enlistmentOptions & EnlistmentOptions.EnlistDuringPrepareRequired) != 0 )
{
localPhase0VolatileContainer.AddEnlistment(
enlistment
);
if ( needPhase0Enlistment )
{
this.phase0EnlistVolatilementContainerList.Add( localPhase0VolatileContainer );
}
}
else
{
localPhase1VolatileContainer.AddEnlistment(
enlistment
);
if ( needVoterEnlistment )
{
Debug.Assert( ( null == this.phase1EnlistVolatilementContainer ),
"RealOletxTransaction.CommonEnlistVolatile - phase1VolContainer not null when expected." );
this.phase1EnlistVolatilementContainer = localPhase1VolatileContainer;
}
}
}
catch (COMException comException)
{
OletxTransactionManager.ProxyException( comException );
throw;
}
}
}
finally
{
if ( phase0Handle != IntPtr.Zero && localPhase0VolatileContainer.Phase0EnlistmentShim == null )
{
HandleTable.FreeHandle( phase0Handle );
}
if ( !enlistmentSucceeded &&
null != localPhase1VolatileContainer &&
localPhase1VolatileContainer.voterHandle != IntPtr.Zero &&
needVoterEnlistment )
{
HandleTable.FreeHandle( localPhase1VolatileContainer.voterHandle );
}
}
return enlistment;
}
internal IPromotedEnlistment EnlistVolatile(
ISinglePhaseNotificationInternal enlistmentNotification,
EnlistmentOptions enlistmentOptions,
OletxTransaction oletxTransaction
)
{
IPromotedEnlistment enlistment = CommonEnlistVolatile(
enlistmentNotification,
enlistmentOptions,
oletxTransaction
);
return enlistment;
}
internal IPromotedEnlistment EnlistVolatile(
IEnlistmentNotificationInternal enlistmentNotification,
EnlistmentOptions enlistmentOptions,
OletxTransaction oletxTransaction
)
{
IPromotedEnlistment enlistment = CommonEnlistVolatile(
enlistmentNotification,
enlistmentOptions,
oletxTransaction
);
return enlistment;
}
internal void Commit()
{
try
{
this.transactionShim.Commit();
}
catch (COMException comException)
{
if ( ( NativeMethods.XACT_E_ABORTED == comException.ErrorCode ) ||
( NativeMethods.XACT_E_INDOUBT == comException.ErrorCode )
)
{
Interlocked.CompareExchange<Exception>( ref this.innerException, comException, null );
if ( DiagnosticTrace.Verbose )
{
ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
comException );
}
}
else if ( NativeMethods.XACT_E_ALREADYINPROGRESS == comException.ErrorCode )
{
throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ), SR.GetString( SR.TransactionAlreadyOver ), comException );
}
else
{
OletxTransactionManager.ProxyException( comException );
throw;
}
}
}
internal void Rollback()
{
System.Guid tempGuid = Guid.Empty;
lock (this)
{
// if status is not active and not aborted, then throw an exception
if (TransactionStatus.Aborted != status &&
TransactionStatus.Active != status)
{
throw TransactionException.Create(
SR.GetString( SR.TraceSourceOletx ),
SR.GetString( SR.TransactionAlreadyOver ),
null,
this.DistributedTxId
);
}
// If the transaciton is already aborted, we can get out now. Calling Rollback on an already aborted transaction
// is legal.
if ( TransactionStatus.Aborted == status )
{
return;
}
// If there are still undecided enlistments, we can doom the transaction.
// We can safely make this check because we ALWAYS have a Phase1 Volatile enlistment to
// get the outcome. If we didn't have that enlistment, we would not be able to do this
// because not all instances of RealOletxTransaction would have enlistments.
if ( 0 < this.undecidedEnlistmentCount )
{
this.doomed = true;
}
else if ( this.tooLateForEnlistments )
{
// It's too late for rollback to be called here.
throw TransactionException.Create(
SR.GetString( SR.TraceSourceOletx ),
SR.GetString( SR.TransactionAlreadyOver ),
null,
this.DistributedTxId
);
}
// Tell the volatile enlistment containers to vote no now if they have outstanding
// notifications.
if ( null != this.phase0EnlistVolatilementContainerList )
{
foreach ( OletxPhase0VolatileEnlistmentContainer phase0VolatileContainer in this.phase0EnlistVolatilementContainerList )
{
phase0VolatileContainer.RollbackFromTransaction();
}
}
if ( null != this.phase1EnlistVolatilementContainer )
{
this.phase1EnlistVolatilementContainer.RollbackFromTransaction();
}
}
try
{
this.transactionShim.Abort();
}
catch (COMException comException)
{
// If the ErrorCode is XACT_E_ALREADYINPROGRESS and the transaciton is already doomed, we must be
// the root transaction and we have already called Commit - ignore the exception. The
// Rollback is allowed and one of the enlistments that hasn't voted yet will make sure it is
// aborted.
if ( NativeMethods.XACT_E_ALREADYINPROGRESS == comException.ErrorCode )
{
if ( this.doomed )
{
if ( DiagnosticTrace.Verbose )
{
ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
comException );
}
}
else
{
throw TransactionException.Create( SR.GetString( SR.TraceSourceOletx ),
SR.GetString( SR.TransactionAlreadyOver ),
comException,
this.DistributedTxId
);
}
}
else
{
// Otherwise, throw the exception out to the app.
OletxTransactionManager.ProxyException( comException );
throw;
}
}
}
internal void OletxTransactionCreated()
{
Interlocked.Increment( ref this.undisposedOletxTransactionCount );
}
internal void OletxTransactionDisposed()
{
int localCount = Interlocked.Decrement( ref this.undisposedOletxTransactionCount );
Debug.Assert( 0 <= localCount, "RealOletxTransction.undisposedOletxTransationCount < 0" );
}
internal void FireOutcome(TransactionStatus statusArg)
{
lock ( this )
{
if (statusArg == TransactionStatus.Committed)
{
if ( DiagnosticTrace.Verbose )
{
TransactionCommittedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
this.TransactionTraceId
);
}
status = TransactionStatus.Committed;
}
else if (statusArg == TransactionStatus.Aborted)
{
if ( DiagnosticTrace.Warning )
{
TransactionAbortedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
this.TransactionTraceId
);
}
status = TransactionStatus.Aborted;
}
else
{
if ( DiagnosticTrace.Warning )
{
TransactionInDoubtTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ),
this.TransactionTraceId
);
}
status = TransactionStatus.InDoubt;
}
}
// Let the InternalTransaciton know about the outcome.
if ( null != this.InternalTransaction )
{
InternalTransaction.DistributedTransactionOutcome( this.InternalTransaction, status );
}
}
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if ( TransactionTraceIdentifier.Empty == this.traceIdentifier )
{
lock ( this )
{
if ( TransactionTraceIdentifier.Empty == this.traceIdentifier )
{
if ( Guid.Empty != this.txGuid )
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier( this.txGuid.ToString(), 0 );
Thread.MemoryBarrier();
this.traceIdentifier = temp;
}
else
{
// We don't have a txGuid if we couldn't determine the guid of the
// transaction because the transaction was already committed or aborted before the RealOletxTransaction was
// created. If that happens, we don't want to throw just because we are trying to trace. So just use the
// TransactionTraceIdentifier.Empty.
}
}
}
}
return this.traceIdentifier;
}
}
internal void TMDown()
{
lock ( this )
{
// Tell the volatile enlistment containers that the TM went down.
if ( null != this.phase0EnlistVolatilementContainerList )
{
foreach ( OletxPhase0VolatileEnlistmentContainer phase0VolatileContainer in this.phase0EnlistVolatilementContainerList )
{
phase0VolatileContainer.TMDown();
}
}
}
// Tell the outcome enlistment the TM went down. We are doing this outside the lock
// because this may end up making calls out to user code through enlistments.
outcomeEnlistment.TMDown();
}
}
internal sealed class OutcomeEnlistment
{
private WeakReference weakRealTransaction;
private System.Guid txGuid;
private bool haveIssuedOutcome;
private TransactionStatus savedStatus;
internal Guid TransactionIdentifier
{
get
{
return txGuid;
}
}
internal OutcomeEnlistment()
{
this.haveIssuedOutcome = false;
this.savedStatus = TransactionStatus.InDoubt;
}
internal void SetRealTransaction( RealOletxTransaction realTx )
{
bool localHaveIssuedOutcome = false;
TransactionStatus localStatus = TransactionStatus.InDoubt;
lock ( this )
{
localHaveIssuedOutcome = this.haveIssuedOutcome;
localStatus = this.savedStatus;
// We want to do this while holding the lock.
if ( ! localHaveIssuedOutcome )
{
// We don't use MemoryBarrier here because all access to these member variables is done while holding
// a lock on the object.
// We are going to use a weak reference so the transaction object can get garbage
// collected before we receive the outcome.
this.weakRealTransaction = new WeakReference(realTx);
// Save the transaction guid so that the transaction can be removed from the
// TransactionTable
this.txGuid = realTx.TxGuid;
}
}
// We want to do this outside the lock because we are potentially calling out to user code.
if ( localHaveIssuedOutcome )
{
realTx.FireOutcome( localStatus );
// We may be getting this notification while there are still volatile prepare notifications outstanding. Tell the
// container to drive the aborted notification in that case.
if ( ( ( TransactionStatus.Aborted == localStatus ) || ( TransactionStatus.InDoubt == localStatus ) ) &&
( null != realTx.phase1EnlistVolatilementContainer ) )
{
realTx.phase1EnlistVolatilementContainer.OutcomeFromTransaction( localStatus );
}
}
}
internal void UnregisterOutcomeCallback()
{
this.weakRealTransaction = null;
}
private void InvokeOutcomeFunction(TransactionStatus status)
{
WeakReference localTxWeakRef = null;
// In the face of TMDown notifications, we may have already issued
// the outcome of the transaction.
lock ( this )
{
if ( this.haveIssuedOutcome )
{
return;
}
this.haveIssuedOutcome = true;
this.savedStatus = status;
localTxWeakRef = this.weakRealTransaction;
}
// It is possible for the weakRealTransaction member to be null if some exception was thrown
// during the RealOletxTransaction constructor after the OutcomeEnlistment object was created.
// In the finally block of the constructor, it calls UnregisterOutcomeCallback, which will
// null out weakRealTransaction. If this is the case, there is nothing to do.
if ( null != localTxWeakRef )
{
RealOletxTransaction realOletxTransaction = localTxWeakRef.Target as RealOletxTransaction;
if (null != realOletxTransaction)
{
realOletxTransaction.FireOutcome(status);
// The container list won't be changing on us now because the transaction status has changed such that
// new enlistments will not be created.
// Tell the Phase0Volatile containers, if any, about the outcome of the transaction.
// I am not protecting the access to phase0EnlistVolatilementContainerList with a lock on "this"
// because it is too late for these to be allocated anyway.
if ( null != realOletxTransaction.phase0EnlistVolatilementContainerList )
{
foreach ( OletxPhase0VolatileEnlistmentContainer phase0VolatileContainer in realOletxTransaction.phase0EnlistVolatilementContainerList )
{
phase0VolatileContainer.OutcomeFromTransaction( status );
}
}
// We may be getting this notification while there are still volatile prepare notifications outstanding. Tell the
// container to drive the aborted notification in that case.
if ( ( ( TransactionStatus.Aborted == status ) || ( TransactionStatus.InDoubt == status ) ) &&
( null != realOletxTransaction.phase1EnlistVolatilementContainer ) )
{
realOletxTransaction.phase1EnlistVolatilementContainer.OutcomeFromTransaction( status );
}
}
localTxWeakRef.Target = null;
}
}
//
// We need to figure out if the transaction is InDoubt as a result of TMDown. This
// can happen for a number of reasons. For instance we have responded prepared
// to all of our enlistments or we have no enlistments.
//
internal bool TransactionIsInDoubt(RealOletxTransaction realTx)
{
if ( null != realTx.committableTransaction &&
!realTx.committableTransaction.CommitCalled )
{
// If this is a committable transaction and commit has not been called
// then we know the outcome.
return false;
}
return realTx.UndecidedEnlistments == 0;
}
internal void TMDown()
{
// Assume that we don't know because that is the safest answer.
bool transactionIsInDoubt = true;
RealOletxTransaction realOletxTransaction = null;
lock ( this )
{
if ( null != this.weakRealTransaction )
{
realOletxTransaction = this.weakRealTransaction.Target as RealOletxTransaction;
}
}
if (null != realOletxTransaction)
{
lock ( realOletxTransaction )
{
transactionIsInDoubt = TransactionIsInDoubt(realOletxTransaction);
}
}
// If we have already voted, then we can't tell what the outcome
// is. We do this outside the lock because it may end up invoking user
// code when it calls into the enlistments later on the stack.
if ( transactionIsInDoubt )
{
this.InDoubt();
}
// We have not yet voted, so just say it aborted.
else
{
this.Aborted();
}
}
#region ITransactionOutcome Members
public void Committed()
{
InvokeOutcomeFunction(TransactionStatus.Committed);
return;
}
public void Aborted()
{
InvokeOutcomeFunction(TransactionStatus.Aborted);
return;
}
public void InDoubt()
{
InvokeOutcomeFunction(TransactionStatus.InDoubt);
return;
}
#endregion
}
}
|
||||
TheStack | bdfb4d92e232fec8e401aff95167faebb8225ba9 | C#code:C# | {"size": 2633, "ext": "cs", "max_stars_repo_path": "src/Lucene.Net.Facet/Taxonomy/WriterCache/NameHashIntCacheLRU.cs", "max_stars_repo_name": "eladmarg/lucene.net", "max_stars_repo_stars_event_min_datetime": "2021-04-08T00:57:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T08:03:04.000Z", "max_issues_repo_path": "src/Lucene.Net.Facet/Taxonomy/WriterCache/NameHashIntCacheLRU.cs", "max_issues_repo_name": "Magicianred/lucenenet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Lucene.Net.Facet/Taxonomy/WriterCache/NameHashIntCacheLRU.cs", "max_forks_repo_name": "Magicianred/lucenenet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.8939393939, "max_line_length": 122, "alphanum_fraction": 0.6498290923} | namespace Lucene.Net.Facet.Taxonomy.WriterCache
{
/*
* 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.
*/
/// <summary>
/// An an LRU cache of mapping from name to int.
/// Used to cache Ordinals of category paths.
/// It uses as key, hash of the path instead of the path.
/// This way the cache takes less RAM, but correctness depends on
/// assuming no collisions.
/// <para/>
/// NOTE: this was NameHashIntCacheLRU in Lucene
/// <para/>
/// @lucene.experimental
/// </summary>
public class NameHashInt32CacheLru : IInternalNameInt32CacheLru // LUCENENET specific - added interface
{
private readonly IInternalNameInt32CacheLru cache;
internal NameHashInt32CacheLru(int limit)
{
this.cache = new NameCacheLru<long>(
limit,
(name) => name.Int64HashCode(),
(name, prefixLength) => name.Subpath(prefixLength).Int64HashCode());
}
/// <inheritdoc/>
public int Count => cache.Count;
/// <inheritdoc/>
public int Limit => cache.Limit;
/// <inheritdoc/>
string IInternalNameInt32CacheLru.Stats => cache.Stats;
/// <inheritdoc/>
void IInternalNameInt32CacheLru.Clear() => cache.Clear();
/// <inheritdoc/>
bool IInternalNameInt32CacheLru.MakeRoomLRU() => cache.MakeRoomLRU();
/// <inheritdoc/>
bool IInternalNameInt32CacheLru.Put(FacetLabel name, int val) => cache.Put(name, val);
/// <inheritdoc/>
bool IInternalNameInt32CacheLru.Put(FacetLabel name, int prefixLen, int val) => cache.Put(name, prefixLen, val);
/// <inheritdoc/>
bool IInternalNameInt32CacheLru.TryGetValue(FacetLabel name, out int value) => cache.TryGetValue(name, out value);
}
} |
||||
TheStack | bdfcaa6c6227357a17b9698d3c0377523449484f | C#code:C# | {"size": 8710, "ext": "cs", "max_stars_repo_path": "TestSuites/RDP/Client/src/TestSuite/RDPEUSB/S2_CancelRequest.cs", "max_stars_repo_name": "microsoft/WindowsProtocolTestSuites", "max_stars_repo_stars_event_min_datetime": "2019-05-14T09:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T19:45:34.000Z", "max_issues_repo_path": "TestSuites/RDP/Client/src/TestSuite/RDPEUSB/S2_CancelRequest.cs", "max_issues_repo_name": "QPC-database/WindowsProtocolTestSuites", "max_issues_repo_issues_event_min_datetime": "2019-05-24T12:34:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T06:46:35.000Z", "max_forks_repo_path": "TestSuites/RDP/Client/src/TestSuite/RDPEUSB/S2_CancelRequest.cs", "max_forks_repo_name": "QPC-database/WindowsProtocolTestSuites", "max_forks_repo_forks_event_min_datetime": "2019-05-15T02:05:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T00:52:11.000Z"} | {"max_stars_count": 332.0, "max_issues_count": 85.0, "max_forks_count": 106.0, "avg_line_length": 47.5956284153, "max_line_length": 149, "alphanum_fraction": 0.6461538462} | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeusb;
namespace Microsoft.Protocols.TestSuites.Rdpeusb
{
public partial class RdpeusbTestSutie
{
[TestMethod]
[Priority(0)]
[TestCategory("RDP7.1")]
[TestCategory("RDPEUSB")]
[TestCategory("Interactive")]
[TestCategory("DeviceNeeded")]
[TestCategory("BasicFeature")]
[Description("Verify behaviors of canceling an IO control request.")]
public void BVT_EUSB_CancelRequest_IoControl()
{
LogComment("BVT_EUSB_CancelRequest_IoControl");
LogComment("1. Creates the control virtual channel, exchanges capabilities then notifies that the channel is created.");
context.ControlChannel = CreateVirtualChannel();
LogComment("2. Receives an add virtual channel request.");
rdpeusbAdapter.ExpectAddVirtualChannel(context.ControlChannel);
LogComment("3. Creates a new virtual channel for the device.");
DynamicVirtualChannel channel = CreateVirtualChannel();
LogComment("4. Receives an add device request.");
EusbDeviceContext device = rdpeusbAdapter.ExpectAddDevice(channel);
LogComment("5. Register a callback to provide the Request Completion Interface to the client.");
uint interfaceId = IdGenerator.NewId();
rdpeusbAdapter.RegisterCallback(device, 1, interfaceId);
// TODO: Needs a long processing IO request so that the request cannot be completed before cancel is
// received.
LogComment("6. Sends an IO request.");
uint requestId = IdGenerator.NewId();
const uint outputSize = 256;
rdpeusbAdapter.IoControl(device, UsbIoControlCode.IOCTL_INTERNAL_USB_GET_HUB_NAME, null, outputSize, requestId);
LogComment("7. Sends a cancel request with the request ID specified in the IO request.");
rdpeusbAdapter.CancelRequest(device, requestId);
LogComment("8. Expects not to receive a completion message.");
EusbPdu pdu = rdpeusbAdapter.ExpectCompletion(device.VirtualChannel);
if (null != pdu)
{
Site.Log.Add(
LogEntryKind.Debug,
"The Completion message is received. Callback interface ID: {0}, Completion Interface ID: {1}",
interfaceId,
pdu.InterfaceId
);
}
LogComment("9. Sends retract device request and the channel for the device is expected to be closed.");
rdpeusbAdapter.RetractDevice(device, USB_RETRACT_REASON.UsbRetractReason_BlockedByPolicy);
}
[TestMethod]
[Priority(0)]
[TestCategory("RDP7.1")]
[TestCategory("RDPEUSB")]
[TestCategory("Interactive")]
[TestCategory("DeviceNeeded")]
[TestCategory("BasicFeature")]
[Description("Verify behaviors of canceling an internal IO control request.")]
public void BVT_EUSB_CancelRequest_InternalIoControl()
{
LogComment("BVT_EUSB_CancelRequest_InternalIoControl");
LogComment("1. Creates the control virtual channel, exchanges capabilities then notifies that the channel is created.");
context.ControlChannel = CreateVirtualChannel();
LogComment("2. Receives an add virtual channel request.");
rdpeusbAdapter.ExpectAddVirtualChannel(context.ControlChannel);
LogComment("3. Creates a new virtual channel for the device.");
DynamicVirtualChannel channel = CreateVirtualChannel();
LogComment("4. Receives an add device request.");
EusbDeviceContext device = rdpeusbAdapter.ExpectAddDevice(channel);
LogComment("5. Register a callback to provide the Request Completion Interface to the client.");
uint interfaceId = IdGenerator.NewId();
rdpeusbAdapter.RegisterCallback(device, 1, interfaceId);
// TODO: Needs a long processing internal IO request so that the request cannot be completed before cancel is
// received.
LogComment("6. Sends an internal IO request.");
uint requestId = IdGenerator.NewId();
const uint outputSize = 4;
rdpeusbAdapter.InternalIoControl(device, UsbInternalIoControlCode.IOCTL_TSUSBGD_IOCTL_USBDI_QUERY_BUS_TIME, null, outputSize, requestId);
LogComment("7. Sends a cancel request with the request ID specified in the IO request.");
rdpeusbAdapter.CancelRequest(device, requestId);
LogComment("8. Expects not to receive a completion message.");
EusbPdu pdu = rdpeusbAdapter.ExpectCompletion(device.VirtualChannel);
if (null != pdu)
{
Site.Log.Add(
LogEntryKind.Debug,
"The Completion message is received. Callback interface ID: {0}, Completion Interface ID: {1}",
interfaceId,
pdu.InterfaceId
);
}
LogComment("9. Sends retract device request and the channel for the device is expected to be closed.");
rdpeusbAdapter.RetractDevice(device, USB_RETRACT_REASON.UsbRetractReason_BlockedByPolicy);
}
[TestMethod]
[Priority(0)]
[TestCategory("RDP7.1")]
[TestCategory("RDPEUSB")]
[TestCategory("Interactive")]
[TestCategory("DeviceNeeded")]
[TestCategory("BasicFeature")]
[Description("Verify behaviors of canceling a transfer in request.")]
public void BVT_EUSB_CancelRequest_TransferInRequest()
{
LogComment("BVT_EUSB_CancelRequest_TransferInRequest");
LogComment("1. Creates the control virtual channel, exchanges capabilities then notifies that the channel is created.");
context.ControlChannel = CreateVirtualChannel();
LogComment("2. Receives an add virtual channel request.");
rdpeusbAdapter.ExpectAddVirtualChannel(context.ControlChannel);
LogComment("3. Creates a new virtual channel for the device.");
DynamicVirtualChannel channel = CreateVirtualChannel();
LogComment("4. Receives an add device request.");
EusbDeviceContext device = rdpeusbAdapter.ExpectAddDevice(channel);
LogComment("5. Register a callback to provide the Request Completion Interface to the client.");
uint interfaceId = IdGenerator.NewId();
rdpeusbAdapter.RegisterCallback(device, 1, interfaceId);
// TODO: Needs a long processing transfer in request so that the request cannot be completed before cancel is
// received.
LogComment("6. Sends TS_URB_CONTROL_DESCRIPTOR_REQUEST within a transfer in request.");
uint requestId = IdGenerator.NewId();
TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new UrbBuilder(
URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE,
requestId,
0).BuildDeviceDescriptorRequest();
rdpeusbAdapter.TransferInRequest(device, des, USB_DEVICE_DESCRIPTOR.DefaultSize);
LogComment("7. Sends a cancel request with the request ID specified in the transfer in request.");
rdpeusbAdapter.CancelRequest(device, requestId);
LogComment("8. Expects not to receive a completion message.");
EusbPdu pdu = rdpeusbAdapter.ExpectCompletion(device.VirtualChannel);
if (null != pdu)
{
Site.Log.Add(
LogEntryKind.Debug,
"The Completion message is received. Callback interface ID: {0}, Completion Interface ID: {1}",
interfaceId,
pdu.InterfaceId
);
}
LogComment("9. Sends retract device request and the channel for the device is expected to be closed.");
rdpeusbAdapter.RetractDevice(device, USB_RETRACT_REASON.UsbRetractReason_BlockedByPolicy);
}
}
}
|
||||
TheStack | bdfcdb5a796a073f661fadfd8095ebbda5edd2b7 | C#code:C# | {"size": 101, "ext": "cs", "max_stars_repo_path": "src/Stripe.Client.Sdk/Models/Arguments/DiscountCreateArguments.cs", "max_stars_repo_name": "johnallers/Stripe.Client", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Stripe.Client.Sdk/Models/Arguments/DiscountCreateArguments.cs", "max_issues_repo_name": "johnallers/Stripe.Client", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Stripe.Client.Sdk/Models/Arguments/DiscountCreateArguments.cs", "max_forks_repo_name": "johnallers/Stripe.Client", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.8333333333, "max_line_length": 44, "alphanum_fraction": 0.7227722772} | namespace Stripe.Client.Sdk.Models.Arguments
{
public class DiscountCreateArguments
{
}
} |
||||
TheStack | da0247c2e853188a174bed7e1c6521a80c767851 | C#code:C# | {"size": 1042, "ext": "cs", "max_stars_repo_path": "CP.Data/Repositories/CourseRepository.cs", "max_stars_repo_name": "AnilAwadh/nTierMVC", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CP.Data/Repositories/CourseRepository.cs", "max_issues_repo_name": "AnilAwadh/nTierMVC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CP.Data/Repositories/CourseRepository.cs", "max_forks_repo_name": "AnilAwadh/nTierMVC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.4146341463, "max_line_length": 78, "alphanum_fraction": 0.5700575816} | using CP.Domain.Entities;
using CP.Domain.Interfaces.Repositories;
using CP.Data.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace CP.Data.Repositories
{
public class CourseRepository : RepositoryBase<Course>, ICourseRepository
{
public CourseRepository(CPContext dbContext)
: base(dbContext)
{
}
public IEnumerable<Course> GetGrid()
{
return DbSet
.Include("CourseType")
.AsNoTracking()
.ToList();
}
public Course GetByIdWithDependencies(Guid cursoId)
{
return DbSet
.Include("CourseType")
.FirstOrDefault(x => x.CourseId == cursoId);
}
public Course GetByName(string description)
{
return Find(x => x.Name == description).FirstOrDefault();
}
}
}
|
||||
TheStack | da0293ef25cf3348df443b418343aa3f39f1f440 | C#code:C# | {"size": 246, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/DisableGmeobject.cs", "max_stars_repo_name": "Quooler/Pungu-2D", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/DisableGmeobject.cs", "max_issues_repo_name": "Quooler/Pungu-2D", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/DisableGmeobject.cs", "max_forks_repo_name": "Quooler/Pungu-2D", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.4, "max_line_length": 45, "alphanum_fraction": 0.6991869919} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisableGmeobject : MonoBehaviour
{
[SerializeField]
GameObject other;
public void Disable()
{
other.SetActive(false);
}
}
|
||||
TheStack | da047e1cb2430421d855ca5ac92c0d5677986711 | C#code:C# | {"size": 2129, "ext": "cs", "max_stars_repo_path": "src/FubuTransportation.Testing/Monitoring/PermanentTaskController/when_checking_status.cs", "max_stars_repo_name": "RyanHauert/FubuTransportation", "max_stars_repo_stars_event_min_datetime": "2017-04-11T23:34:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-26T06:43:05.000Z", "max_issues_repo_path": "src/FubuTransportation.Testing/Monitoring/PermanentTaskController/when_checking_status.cs", "max_issues_repo_name": "RyanHauert/FubuTransportation", "max_issues_repo_issues_event_min_datetime": "2015-02-09T19:05:29.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-11T15:02:52.000Z", "max_forks_repo_path": "src/FubuTransportation.Testing/Monitoring/PermanentTaskController/when_checking_status.cs", "max_forks_repo_name": "RyanHauert/FubuTransportation", "max_forks_repo_forks_event_min_datetime": "2015-03-13T20:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2015-05-18T16:18:12.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 4.0, "max_forks_count": 3.0, "avg_line_length": 32.2575757576, "max_line_length": 90, "alphanum_fraction": 0.6115547205} | using System;
using FubuCore;
using FubuTestingSupport;
using FubuTransportation.Monitoring;
using NUnit.Framework;
namespace FubuTransportation.Testing.Monitoring.PermanentTaskController
{
[TestFixture]
public class when_checking_status : PersistentTaskControllerContext
{
protected override void theContextIs()
{
Task("running://1").IsFullyFunctionalAndActive();
Task("stopped://1").IsActive = false;
Task("error://1").IsActiveButNotFunctional(new DivideByZeroException());
Task("timeout://1").IsFullyFunctionalAndActive();
Task("timeout://1").Timesout = true;
settings.TakeOwnershipMessageTimeout = 45.Seconds();
settings.TaskAvailabilityCheckTimeout = 45.Seconds();
}
private HealthStatus findStatus(string uriString)
{
var uri = uriString.ToUri();
var task = theController.CheckStatus(uri);
task.Wait();
return task.Result;
}
[Test]
public void check_the_status_of_a_task_that_times_out_in_its_availibility_check()
{
settings.TakeOwnershipMessageTimeout = 2.Seconds();
settings.TaskAvailabilityCheckTimeout = 2.Seconds();
findStatus("timeout://1").ShouldEqual(HealthStatus.Timedout);
}
[Test]
public void check_the_status_of_an_unknown_task()
{
findStatus("unknown://1").ShouldEqual(HealthStatus.Unknown);
}
[Test]
public void check_the_status_of_an_active_and_functional_task()
{
findStatus("running://1").ShouldEqual(HealthStatus.Active);
}
[Test]
public void check_the_status_of_an_inactive_task()
{
findStatus("stopped://1").ShouldEqual(HealthStatus.Inactive);
}
[Test]
public void check_the_status_of_an_active_task_that_has_errored_out()
{
findStatus("error://1").ShouldEqual(HealthStatus.Error);
}
}
} |
||||
TheStack | da052280dca046c1cd1523bd2c36a86e97a6a346 | C#code:C# | {"size": 1890, "ext": "cs", "max_stars_repo_path": "soft.Hati.ErrorListSearchOn/soft.Hati.ErrorListSearchOn/Services/Search/SearchEngine.cs", "max_stars_repo_name": "Hatisoft/ErrorListSearchOn", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soft.Hati.ErrorListSearchOn/soft.Hati.ErrorListSearchOn/Services/Search/SearchEngine.cs", "max_issues_repo_name": "Hatisoft/ErrorListSearchOn", "max_issues_repo_issues_event_min_datetime": "2018-07-06T06:05:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-09T00:50:42.000Z", "max_forks_repo_path": "soft.Hati.ErrorListSearchOn/soft.Hati.ErrorListSearchOn/Services/Search/SearchEngine.cs", "max_forks_repo_name": "Hatisoft/ErrorListSearchOn", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 2.0, "max_forks_count": null, "avg_line_length": 33.1578947368, "max_line_length": 141, "alphanum_fraction": 0.5957671958} | using System;
using System.Diagnostics;
using System.Linq;
namespace soft.Hati.ErrorListSearchOn.Services.Search
{
public interface SearchEngine
{
void Search(string query);
string GenerateQuery(string info);
}
public abstract class SearchBase : SearchEngine
{
protected abstract string Url { get; }
public void Search(string query)
{
query = query.Replace(' ', '+');
var notExpectedChars = query.ToList().Where(character => (character != '+' && !char.IsLetterOrDigit(character)));
notExpectedChars.ToList().ForEach(character => query = query.Replace(string.Format("{0}", character), Uri.HexEscape(character)));
try
{
Process.Start(string.Format("{0}{1}", Url, query));
}
catch { }
}
public string GenerateQuery(string info)
{
info = info.Replace(' ', '+');
var notExpectedChars = info.ToList().Where(character => (character != '+' && !char.IsLetterOrDigit(character)));
notExpectedChars.ToList().ForEach(character => info = info.Replace(string.Format("{0}", character), Uri.HexEscape(character)));
return string.Format("{0}{1}", Url, info);
}
}
public class GoogleSearch : SearchBase
{
protected override string Url { get { return @"http://www.google.com/search?q="; } }
}
public class BingSearch : SearchBase
{
protected override string Url { get { return @"http://www.bing.com/search?q="; } }
}
public class StackOverflowSearch : SearchBase
{
protected override string Url { get { return @"http://stackoverflow.com/search?q="; } }
}
public class DuckDuckGo : SearchBase
{
protected override string Url { get { return @"https://duckduckgo.com/?q="; } }
}
} |
||||
TheStack | da064c424340689209d525fed05f0424f5b9eaf0 | C#code:C# | {"size": 15588, "ext": "cs", "max_stars_repo_path": "src/Dfc.DiscoverSkillsAndCareers.UnitTests/FunctionTests/PostAnswerHttpTriggerTests.cs", "max_stars_repo_name": "Muthuramana/dfc-discoverskillsandcareers", "max_stars_repo_stars_event_min_datetime": "2019-08-14T13:32:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T09:31:39.000Z", "max_issues_repo_path": "src/Dfc.DiscoverSkillsAndCareers.UnitTests/FunctionTests/PostAnswerHttpTriggerTests.cs", "max_issues_repo_name": "Muthuramana/dfc-discoverskillsandcareers", "max_issues_repo_issues_event_min_datetime": "2019-01-29T14:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-22T14:07:32.000Z", "max_forks_repo_path": "src/Dfc.DiscoverSkillsAndCareers.UnitTests/FunctionTests/PostAnswerHttpTriggerTests.cs", "max_forks_repo_name": "Muthuramana/dfc-discoverskillsandcareers", "max_forks_repo_forks_event_min_datetime": "2019-06-21T10:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T08:36:16.000Z"} | {"max_stars_count": 6.0, "max_issues_count": 28.0, "max_forks_count": 2.0, "avg_line_length": 41.679144385, "max_line_length": 115, "alphanum_fraction": 0.5485629972} | using Dfc.DiscoverSkillsAndCareers.AssessmentFunctionApp.Models;
using Dfc.DiscoverSkillsAndCareers.AssessmentFunctionApp.Services;
using Dfc.DiscoverSkillsAndCareers.Repositories;
using DFC.HTTP.Standard;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Dfc.DiscoverSkillsAndCareers.AssessmentFunctionApp.AssessmentApi;
using Dfc.DiscoverSkillsAndCareers.Models;
using NSubstitute.ExceptionExtensions;
using Xunit;
namespace Dfc.UnitTests.FunctionTests
{
public class PostAnswerHttpTriggerTests : IDisposable
{
public PostAnswerHttpTriggerTests()
{
_request = new DefaultHttpRequest(new DefaultHttpContext());
_log = Substitute.For<ILogger>();
_httpRequestHelper = Substitute.For<IHttpRequestHelper>();
_httpResponseMessageHelper = Substitute.For<IHttpResponseMessageHelper>();
_userSessionRepository = Substitute.For<IUserSessionRepository>();
_questionRepository = Substitute.For<IQuestionRepository>();
_assessmentCalculationService = Substitute.For<IAssessmentCalculationService>();
_filterAssessmentCalculationService = Substitute.For<IFilterAssessmentCalculationService>();
}
public void Dispose()
{
_httpRequestHelper = null;
_httpResponseMessageHelper = null;
_userSessionRepository = null;
_userSessionRepository = null;
}
private HttpRequest _request;
private ILogger _log;
private IHttpRequestHelper _httpRequestHelper;
private IHttpResponseMessageHelper _httpResponseMessageHelper;
private IUserSessionRepository _userSessionRepository;
private IQuestionRepository _questionRepository;
private IAssessmentCalculationService _assessmentCalculationService;
private IFilterAssessmentCalculationService _filterAssessmentCalculationService;
private async Task<HttpResponseMessage> RunFunction(string sessionId)
{
return await PostAnswerHttpTrigger.Run(
_request,
sessionId,
_log,
_httpRequestHelper,
_httpResponseMessageHelper,
_userSessionRepository,
_questionRepository,
_assessmentCalculationService,
_filterAssessmentCalculationService
).ConfigureAwait(false);
}
[Fact]
public async Task PostAnswerHttpTrigger_WithInvalidAnswerValue_ShouldReturnBadRequest()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "1",
SelectedOption = "invalid-answer"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
var result = await RunFunction("session1");
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
}
[Fact]
public async Task PostAnswerHttpTrigger_WithInvalidSessionId_ShouldReturnNoContent()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "1",
SelectedOption = "Agree"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
var result = await RunFunction("invalid-session-id");
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
}
[Fact]
public async Task PostAnswerHttpTrigger_WithMissingSessionId_ShouldReturnBadRequest()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var result = await RunFunction(null);
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.BadRequest, result.StatusCode);
}
[Fact]
public async Task PostAnswerHttpTrigger_UnableToFindQuestion_ShouldReturnNoContent()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "1",
SelectedOption = "Agree"
};
_questionRepository.GetQuestion("1").Returns(Task.FromResult<Question>(null));
_userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(new UserSession
{
AssessmentState = new AssessmentState("QS-1", 5)
}));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
var result = await RunFunction("session1");
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);
}
[Fact]
public async Task PostAnswerHttpTrigger_Returns_500OnException()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "1",
SelectedOption = "Agree"
};
_userSessionRepository.GetUserSession("session1").Throws(new Exception());
var result = await RunFunction("session1");
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode);
}
[Fact]
public async Task PostAnswerHttpTrigger_WithValidAnswerValue_ShouldHaveIsSuccessInModel()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "1",
SelectedOption = "Agree"
};
_questionRepository.GetQuestion("1").Returns(Task.FromResult(new Question {QuestionId = "1"}));
_userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(new UserSession
{
AssessmentState = new AssessmentState("QS-1", 5)
}));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
var result = await RunFunction("session1");
var content = await result.Content.ReadAsAsync<PostAnswerResponse>();
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.True(content.IsSuccess);
}
[Fact]
public async Task PostAnswerHttpTrigger_WithValidAnswerValue_ShouldReturnNextQuestionEvenIfComplete()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "short-1-1",
SelectedOption = "Agree"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
_questionRepository.GetQuestion("short-1-1").Returns(Task.FromResult(new Question
{
QuestionId = "short-1-1",
IsFilterQuestion = false,
Order = 1,
Texts = new []
{
new QuestionText { LanguageCode = "en", Text = "q1" },
}
}));
var session = new UserSession
{
AssessmentType = "short",
AssessmentState = new AssessmentState("QS-1", 2)
{
RecordedAnswers = new[]
{
new Answer
{
QuestionId = "1", QuestionNumber = 1, QuestionSetVersion = "QS-1",
SelectedOption = AnswerOption.Agree
},
}
}
};
_userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(session));
var result = await RunFunction("session1");
var content = await result.Content.ReadAsAsync<PostAnswerResponse>();
Assert.IsType<HttpResponseMessage>(result);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.True(content.IsSuccess);
Assert.Equal(2,content.NextQuestionNumber);
}
[Fact]
public async Task PostAnswerHttpTrigger_WhenAssessmentComplete_ShouldCallAssementCalculationService()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "short-1-1",
SelectedOption = "Agree"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
_questionRepository.GetQuestion("short-1-1").Returns(Task.FromResult(new Question
{
QuestionId = "short-1-1",
IsFilterQuestion = false,
Order = 1,
Texts = new []
{
new QuestionText { LanguageCode = "en", Text = "q1" },
}
}));
var session = new UserSession
{
AssessmentType = "short",
AssessmentState = new AssessmentState("QS-1", 1)
{
CurrentQuestion = 1
}
};
_userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(session));
var result = await RunFunction("session1");
await _assessmentCalculationService.ReceivedWithAnyArgs(1)
.CalculateAssessment(Arg.Any<UserSession>(), Arg.Any<ILogger>());
}
[Fact]
public async Task PostAnswerHttpTrigger_WhenFilterAssessmentComplete_ShouldCallAssementCalculationService()
{
_httpResponseMessageHelper = new HttpResponseMessageHelper();
var postAnswerRequest = new PostAnswerRequest()
{
QuestionId = "AC-1",
SelectedOption = "Agree"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(postAnswerRequest);
_request.Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
_questionRepository.GetQuestion("AC-1").Returns(Task.FromResult(new Question
{
QuestionId = "AC-1",
IsFilterQuestion = true,
Order = 1,
TraitCode = "A",
Texts = new []
{
new QuestionText { LanguageCode = "en", Text = "q1" },
}
}));
var session = new UserSession
{
AssessmentType = "filtered",
AssessmentState = new AssessmentState("QS-1", 1)
{
RecordedAnswers = new []
{
new Answer { QuestionNumber = 1, SelectedOption = AnswerOption.Agree, TraitCode = "A"}
},
CurrentQuestion = 1
},
FilteredAssessmentState = new FilteredAssessmentState
{
CurrentFilterAssessmentCode = "AC",
JobCategoryStates = new List<JobCategoryState>
{
new JobCategoryState("AC", "Animal Care", "QS-1", new []
{
new JobCategorySkill { QuestionId = "AC-1", QuestionNumber = 1, Skill = "A"},
})
}
}
};
_userSessionRepository.GetUserSession("session1").Returns(Task.FromResult(session));
var result = await RunFunction("session1");
await _filterAssessmentCalculationService.ReceivedWithAnyArgs(1)
.CalculateAssessment(Arg.Any<UserSession>(), Arg.Any<ILogger>());
}
}
}
// FilteredAssessmentState = new FilteredAssessmentState
// {
// CurrentFilterAssessmentCode = "filtered-social-care-1",
// CompleteDt = new DateTime(2019,1,1),
// JobCategoryStates = new List<JobCategoryState> {
// new JobCategoryState
// {
// JobCategoryCode = "filtered-social-care-1",
// CurrentQuestion = 1,
// JobCategoryName = "socail-care",
// QuestionSetVersion = "filtered-social-care-1",
// Skills = new []
// {
// new JobCategorySkill { Skill = "Initative" },
// new JobCategorySkill { Skill = "Self control" }
// }
// }
// },
// RecordedAnswers = new []
// {
// new Answer {
// AnsweredDt = new DateTime(2019,1,1),
// QuestionSetVersion = "filtered-social-care-1",
// IsNegative = false,
// QuestionId = "filtered-social-care-1-1",
// QuestionNumber = 1,
// QuestionText = "Question 1",
// SelectedOption = AnswerOption.Yes
// },
// new Answer {
// AnsweredDt = new DateTime(2019,1,1),
// QuestionSetVersion = "filtered-social-care-1",
// IsNegative = false,
// QuestionId = "filtered-social-care-1-2",
// QuestionNumber = 2,
// QuestionText = "Question 2",
// SelectedOption = AnswerOption.No
// }
// }
// }
|
||||
TheStack | da06e5f4d68871917230c542ea8d354a8b68b656 | C#code:C# | {"size": 1045, "ext": "cs", "max_stars_repo_path": "samples/AspNetSimple/Controllers/WebApiController.cs", "max_stars_repo_name": "MABrunner/R4MVC", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "samples/AspNetSimple/Controllers/WebApiController.cs", "max_issues_repo_name": "MABrunner/R4MVC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/AspNetSimple/Controllers/WebApiController.cs", "max_forks_repo_name": "MABrunner/R4MVC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.4347826087, "max_line_length": 125, "alphanum_fraction": 0.7559808612} | using System;
using System.Threading.Tasks;
using AspNetSimple.Models;
using Microsoft.AspNetCore.Mvc;
namespace AspNetSimple.Controllers
{
public partial class WebApiController : ControllerBase
{
public virtual Product ApiCall() => throw new NotImplementedException();
public virtual Product ApiCallWithParams(int id) => throw new NotImplementedException();
public virtual Task<Product> TaskApiCall() => throw new NotImplementedException();
public virtual Task<Product> TaskApiCallWithParams(int id) => throw new NotImplementedException();
public virtual ActionResult<Product> ApiCallTyped() => throw new NotImplementedException();
public virtual ActionResult<Product> ApiCallTypedWithParams(int id) => throw new NotImplementedException();
public virtual Task<ActionResult<Product>> TaskApiCallTyped() => throw new NotImplementedException();
public virtual Task<ActionResult<Product>> TaskApiCallTypedWithParams(int id) => throw new NotImplementedException();
}
}
|
||||
TheStack | da070dfe648c82c52352a5dba8572549511184ef | C#code:C# | {"size": 1354, "ext": "cs", "max_stars_repo_path": "BroadworksConnector/Ocip/Models/SystemXsiPolicyProfileDeleteRequest.cs", "max_stars_repo_name": "Rogn/broadworks-connector-net", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BroadworksConnector/Ocip/Models/SystemXsiPolicyProfileDeleteRequest.cs", "max_issues_repo_name": "Rogn/broadworks-connector-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BroadworksConnector/Ocip/Models/SystemXsiPolicyProfileDeleteRequest.cs", "max_forks_repo_name": "Rogn/broadworks-connector-net", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.0243902439, "max_line_length": 131, "alphanum_fraction": 0.6735598227} | using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Delete an entry from system Xsi application Id list.
/// The response is either a SuccessResponse or an ErrorResponse.
/// <see cref="SuccessResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:19455""}]")]
public class SystemXsiPolicyProfileDeleteRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private BroadWorksConnector.Ocip.Models.XsiPolicyProfileKey _xsiPolicyProfile;
[XmlElement(ElementName = "xsiPolicyProfile", IsNullable = false, Namespace = "")]
[Group(@"7f663d5135470c33ca64b0eed3c3aa0c:19455")]
public BroadWorksConnector.Ocip.Models.XsiPolicyProfileKey XsiPolicyProfile
{
get => _xsiPolicyProfile;
set
{
XsiPolicyProfileSpecified = true;
_xsiPolicyProfile = value;
}
}
[XmlIgnore]
protected bool XsiPolicyProfileSpecified { get; set; }
}
}
|
||||
TheStack | da07cf6d00f6fb9b1e1d72b83a689eed64761db2 | C#code:C# | {"size": 1692, "ext": "cs", "max_stars_repo_path": "src/Razor/Microsoft.NET.Sdk.Razor/src/BlazorWriteSatelliteAssemblyFile.cs", "max_stars_repo_name": "nintroz/aspnetcore", "max_stars_repo_stars_event_min_datetime": "2020-09-30T11:41:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T07:44:14.000Z", "max_issues_repo_path": "src/Razor/Microsoft.NET.Sdk.Razor/src/BlazorWriteSatelliteAssemblyFile.cs", "max_issues_repo_name": "nintroz/aspnetcore", "max_issues_repo_issues_event_min_datetime": "2020-07-21T18:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-21T18:02:07.000Z", "max_forks_repo_path": "src/Razor/Microsoft.NET.Sdk.Razor/src/BlazorWriteSatelliteAssemblyFile.cs", "max_forks_repo_name": "nintroz/aspnetcore", "max_forks_repo_forks_event_min_datetime": "2021-09-16T15:49:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T15:49:25.000Z"} | {"max_stars_count": 5.0, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 31.3333333333, "max_line_length": 111, "alphanum_fraction": 0.6004728132} | // 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.IO;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.AspNetCore.Razor.Tasks
{
public class BlazorWriteSatelliteAssemblyFile : Task
{
[Required]
public ITaskItem[] SatelliteAssembly { get; set; }
[Required]
public ITaskItem WriteFile { get; set; }
public override bool Execute()
{
using var fileStream = File.Create(WriteFile.ItemSpec);
WriteSatelliteAssemblyFile(fileStream);
return true;
}
internal void WriteSatelliteAssemblyFile(Stream stream)
{
var root = new XElement("SatelliteAssembly");
foreach (var item in SatelliteAssembly)
{
// <Assembly Name="..." Culture="..." DestinationSubDirectory="..." />
root.Add(new XElement("Assembly",
new XAttribute("Name", item.ItemSpec),
new XAttribute("Culture", item.GetMetadata("Culture")),
new XAttribute("DestinationSubDirectory", item.GetMetadata("DestinationSubDirectory"))));
}
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using var writer = XmlWriter.Create(stream, xmlWriterSettings);
var xDocument = new XDocument(root);
xDocument.Save(writer);
}
}
}
|
||||
TheStack | da08c5c0c1789573895e6f7b39e826310f6a6f34 | C#code:C# | {"size": 841, "ext": "cs", "max_stars_repo_path": "src/CoreWCF.Primitives/tests/Helpers/MockReplySessionChannel.cs", "max_stars_repo_name": "bstordrup/CoreWCF", "max_stars_repo_stars_event_min_datetime": "2019-06-07T17:27:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:13:56.000Z", "max_issues_repo_path": "src/CoreWCF.Primitives/tests/Helpers/MockReplySessionChannel.cs", "max_issues_repo_name": "bstordrup/CoreWCF", "max_issues_repo_issues_event_min_datetime": "2019-06-07T19:02:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:29:50.000Z", "max_forks_repo_path": "src/CoreWCF.Primitives/tests/Helpers/MockReplySessionChannel.cs", "max_forks_repo_name": "bstordrup/CoreWCF", "max_forks_repo_forks_event_min_datetime": "2019-06-07T18:11:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:35:25.000Z"} | {"max_stars_count": 1110.0, "max_issues_count": 403.0, "max_forks_count": 204.0, "avg_line_length": 27.1290322581, "max_line_length": 96, "alphanum_fraction": 0.6599286564} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Text;
using CoreWCF.Channels;
namespace Helpers
{
internal class MockReplySessionChannel : MockReplyChannel, IReplySessionChannel
{
public MockReplySessionChannel(IServiceProvider serviceProvider) : base(serviceProvider)
{
Session = new MockReplySessionChannelSession(Guid.NewGuid().ToString());
}
public IInputSession Session { get; }
private class MockReplySessionChannelSession : IInputSession
{
public MockReplySessionChannelSession(string id)
{
Id = id;
}
public string Id { get; }
}
}
}
|
||||
TheStack | da0a440f1d60b5137b16c8988f7c0629155edc47 | C#code:C# | {"size": 613, "ext": "cs", "max_stars_repo_path": "Sharpotify7/Sparpotify7.Library/Crypto/RandomBytes.cs", "max_stars_repo_name": "fernandoescolar/sharpotify7", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sharpotify7/Sparpotify7.Library/Crypto/RandomBytes.cs", "max_issues_repo_name": "fernandoescolar/sharpotify7", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sharpotify7/Sparpotify7.Library/Crypto/RandomBytes.cs", "max_forks_repo_name": "fernandoescolar/sharpotify7", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.5769230769, "max_line_length": 61, "alphanum_fraction": 0.5693311582} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sharpotify.Crypto
{
internal static class RandomBytes
{
private static Random _rnd = new Random();
public static void GetRandomBytes(ref byte[] buffer)
{
_rnd.NextBytes(buffer);
}
public static byte[] GetRandomBytes(int length)
{
/* Create a buffer of the specified length. */
byte[] buffer = new byte[length];
GetRandomBytes(ref buffer);
return buffer;
}
}
}
|
||||
TheStack | da0b251aa5f9bd274468532d080bf8ae9b5d8c7d | C#code:C# | {"size": 548, "ext": "cs", "max_stars_repo_path": "src/Mages.Core/Runtime/Types/MagesString.cs", "max_stars_repo_name": "FlorianRappl/Mages", "max_stars_repo_stars_event_min_datetime": "2016-04-29T13:57:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T19:39:41.000Z", "max_issues_repo_path": "src/Mages.Core/Runtime/Types/MagesString.cs", "max_issues_repo_name": "FlorianRappl/Mages", "max_issues_repo_issues_event_min_datetime": "2016-04-29T14:08:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T17:49:49.000Z", "max_forks_repo_path": "src/Mages.Core/Runtime/Types/MagesString.cs", "max_forks_repo_name": "FlorianRappl/Mages", "max_forks_repo_forks_event_min_datetime": "2016-06-29T01:15:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T00:13:04.000Z"} | {"max_stars_count": 115.0, "max_issues_count": 107.0, "max_forks_count": 16.0, "avg_line_length": 24.9090909091, "max_line_length": 96, "alphanum_fraction": 0.5675182482} | namespace Mages.Core.Runtime.Types
{
using Mages.Core.Runtime.Functions;
using System;
using System.Collections.Generic;
static class MagesString
{
private static readonly Function Create = new Function(args =>
{
return Curry.MinOne(Create, args) ??
Stringify.This(args[0]);
});
public static readonly IDictionary<String, Object> Type = new Dictionary<String, Object>
{
{ "name", "String" },
{ "create", Create },
};
}
}
|
||||
TheStack | da0b2a88f8c305f897cefb838fe42f0b9b04784f | C#code:C# | {"size": 11851, "ext": "cs", "max_stars_repo_path": "Lucene.Net 2.4.0/Search/FieldCache.cs", "max_stars_repo_name": "restran/lucene-file-finder", "max_stars_repo_stars_event_min_datetime": "2015-05-31T09:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T07:01:23.000Z", "max_issues_repo_path": "Lucene.Net 2.4.0/Search/FieldCache.cs", "max_issues_repo_name": "restran/lucene-file-finder", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lucene.Net 2.4.0/Search/FieldCache.cs", "max_forks_repo_name": "restran/lucene-file-finder", "max_forks_repo_forks_event_min_datetime": "2015-08-22T02:21:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T03:31:43.000Z"} | {"max_stars_count": 6.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 42.7833935018, "max_line_length": 101, "alphanum_fraction": 0.6830647203} | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
namespace Lucene.Net.Search
{
/// <summary> Expert: Maintains caches of term values.
/// </summary>
/// <since>lucene 1.4</since>
/// <version>$Id:$</version>
/// <summary>Expert: Stores term text values and document ordering data. </summary>
public class StringIndex
{
/// <summary>All the term values, in natural order. </summary>
public System.String[] Lookup;
/// <summary>For each document, an index into the lookup array. </summary>
public int[] Order;
/// <summary>Creates one of these objects </summary>
public StringIndex(int[] values, System.String[] lookup)
{
this.Order = values;
this.Lookup = lookup;
}
}
public struct FieldCache_Fields{
/// <summary>Indicator for StringIndex values in the cache. </summary>
// NOTE: the value assigned to this constant must not be
// the same as any of those in SortField!!
public readonly static int STRING_INDEX = - 1;
/// <summary>Expert: The cache used internally by sorting and range query classes. </summary>
public readonly static FieldCache DEFAULT;
static FieldCache_Fields()
{
DEFAULT = new FieldCacheImpl();
}
}
public interface FieldCache
{
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as a single byte and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the single byte values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
byte[] GetBytes(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as bytes and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the bytes.
/// </param>
/// <param name="parser"> Computes byte for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
byte[] GetBytes(IndexReader reader, System.String field, ByteParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as shorts and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the shorts.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
short[] GetShorts(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as shorts and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the shorts.
/// </param>
/// <param name="parser"> Computes short for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
short[] GetShorts(IndexReader reader, System.String field, ShortParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as integers and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the integers.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
int[] GetInts(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as integers and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the integers.
/// </param>
/// <param name="parser"> Computes integer for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
int[] GetInts(IndexReader reader, System.String field, IntParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found, reads the terms in <code>field</code> as floats and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the floats.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
float[] GetFloats(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found, reads the terms in <code>field</code> as floats and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the floats.
/// </param>
/// <param name="parser"> Computes float for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
float[] GetFloats(IndexReader reader, System.String field, FloatParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found, reads the term values in <code>field</code> and returns an array
/// of size <code>reader.maxDoc()</code> containing the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the strings.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
System.String[] GetStrings(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found reads the term values in <code>field</code> and returns
/// an array of them in natural order, along with an array telling
/// which element in the term array each document uses.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the strings.
/// </param>
/// <returns> Array of terms and index into the array for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
StringIndex GetStringIndex(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found reads <code>field</code> to see if it contains integers, floats
/// or strings, and then calls one of the other methods in this class to get the
/// values. For string values, a StringIndex is returned. After
/// calling this method, there is an entry in the cache for both
/// type <code>AUTO</code> and the actual found type.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the values.
/// </param>
/// <returns> int[], float[] or StringIndex.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
object GetAuto(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found reads the terms out of <code>field</code> and calls the given SortComparator
/// to get the sort values. A hit in the cache will happen if <code>reader</code>,
/// <code>field</code>, and <code>comparator</code> are the same (using <code>equals()</code>)
/// as a previous call to this method.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the values.
/// </param>
/// <param name="comparator">Used to convert terms into something to sort by.
/// </param>
/// <returns> Array of sort objects, one for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
System.IComparable[] GetCustom(IndexReader reader, System.String field, SortComparator comparator);
}
/// <summary>Interface to parse bytes from document fields.</summary>
/// <seealso cref="FieldCache.GetBytes(IndexReader, String, FieldCache.ByteParser)">
/// </seealso>
public interface ByteParser
{
/// <summary>Return a single Byte representation of this field's value. </summary>
byte ParseByte(System.String string_Renamed);
}
/// <summary>Interface to parse shorts from document fields.</summary>
/// <seealso cref="FieldCache.GetShorts(IndexReader, String, FieldCache.ShortParser)">
/// </seealso>
public interface ShortParser
{
/// <summary>Return a short representation of this field's value. </summary>
short ParseShort(System.String string_Renamed);
}
/// <summary>Interface to parse ints from document fields.</summary>
/// <seealso cref="FieldCache.GetInts(IndexReader, String, FieldCache.IntParser)">
/// </seealso>
public interface IntParser
{
/// <summary>Return an integer representation of this field's value. </summary>
int ParseInt(System.String string_Renamed);
}
/// <summary>Interface to parse floats from document fields.</summary>
/// <seealso cref="FieldCache.GetFloats(IndexReader, String, FieldCache.FloatParser)">
/// </seealso>
public interface FloatParser
{
/// <summary>Return an float representation of this field's value. </summary>
float ParseFloat(System.String string_Renamed);
}
} |
||||
TheStack | da0d4a8d3c83bb1602cc8d70b8e2a5944b447ad9 | C#code:C# | {"size": 697, "ext": "cs", "max_stars_repo_path": "src/test/UnitTests/ConfigTest.cs", "max_stars_repo_name": "0xF6/hmac.app", "max_stars_repo_stars_event_min_datetime": "2021-02-26T15:46:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T20:48:21.000Z", "max_issues_repo_path": "src/test/UnitTests/ConfigTest.cs", "max_issues_repo_name": "0xF6/hmac.app", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/UnitTests/ConfigTest.cs", "max_forks_repo_name": "0xF6/hmac.app", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.8928571429, "max_line_length": 70, "alphanum_fraction": 0.56241033} | namespace UnitTests
{
using hmac.Core;
using NUnit.Framework;
public class Tests
{
[Test]
public void Test1()
{
var config = new Config
{
Adapter = AdapterType.SHA256,
IgnoreNullValue = true,
OutputType = OutputType.Hex
};
var value = ConfigMapper.MapToString(config);
var resultConfig = ConfigMapper.FromString(value);
Assert.AreEqual(AdapterType.SHA256, resultConfig.Adapter);
Assert.AreEqual(OutputType.Hex, resultConfig.OutputType);
Assert.AreEqual(true, resultConfig.IgnoreNullValue);
}
}
} |
||||
TheStack | da0db5bfb33cf2de7dd6f29d728a77fbaa84ea16 | C#code:C# | {"size": 646, "ext": "cs", "max_stars_repo_path": "Kooboo.CMS/Kooboo/Job/IJob.cs", "max_stars_repo_name": "syberside/CMS", "max_stars_repo_stars_event_min_datetime": "2015-01-02T08:42:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T14:01:59.000Z", "max_issues_repo_path": "Kooboo.CMS/Kooboo/Job/IJob.cs", "max_issues_repo_name": "syberside/CMS", "max_issues_repo_issues_event_min_datetime": "2015-01-13T13:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T23:33:52.000Z", "max_forks_repo_path": "Kooboo.CMS/Kooboo/Job/IJob.cs", "max_forks_repo_name": "syberside/CMS", "max_forks_repo_forks_event_min_datetime": "2015-01-03T15:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T01:52:47.000Z"} | {"max_stars_count": 288.0, "max_issues_count": 45.0, "max_forks_count": 171.0, "avg_line_length": 21.5333333333, "max_line_length": 72, "alphanum_fraction": 0.5588235294} | #region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
namespace Kooboo.Job
{
/// <summary>
///
/// </summary>
public interface IJob
{
/// <summary>
/// Executes the specified execution state.
/// </summary>
/// <param name="executionState">State of the execution.</param>
void Execute(object executionState);
/// <summary>
/// Errors the specified e.
/// </summary>
/// <param name="e">The e.</param>
void Error(Exception e);
}
}
|
||||
TheStack | da0ecd1106e5ec538f46588e41fdb3c3741dc6c0 | C#code:C# | {"size": 619, "ext": "cs", "max_stars_repo_path": "src/ZKWeb.Plugins/Common.Base/src/UIComponents/Forms/Attributes/FileUploaderAsUrlFieldAttribute.cs", "max_stars_repo_name": "zkweb-framework/ZKWeb.Plugins", "max_stars_repo_stars_event_min_datetime": "2016-05-17T11:42:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T10:32:51.000Z", "max_issues_repo_path": "src/ZKWeb.Plugins/Common.Base/src/UIComponents/Forms/Attributes/FileUploaderAsUrlFieldAttribute.cs", "max_issues_repo_name": "303248153/ZKWeb.Plugins", "max_issues_repo_issues_event_min_datetime": "2016-06-06T10:02:49.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-26T05:45:45.000Z", "max_forks_repo_path": "src/ZKWeb.Plugins/Common.Base/src/UIComponents/Forms/Attributes/FileUploaderAsUrlFieldAttribute.cs", "max_forks_repo_name": "zkweb-framework/ZKWeb.Plugins", "max_forks_repo_forks_event_min_datetime": "2016-07-08T09:02:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T07:55:22.000Z"} | {"max_stars_count": 52.0, "max_issues_count": 2.0, "max_forks_count": 30.0, "avg_line_length": 29.4761904762, "max_line_length": 102, "alphanum_fraction": 0.6768982229} | namespace ZKWeb.Plugins.Common.Base.src.UIComponents.Forms.Attributes {
/// <summary>
/// 文件上传, 以url的形式自动保存
/// </summary>
public class FileUploaderAsUrlFieldAttribute : FileUploaderFieldAttribute {
/// <summary>
/// 上传目录
/// </summary>
public string UploadDirectory { get; set; }
/// <summary>
/// 初始化
/// </summary>
public FileUploaderAsUrlFieldAttribute(
string name, string extensions = null, int maxContentsLength = 0, string uploadDirectory = null) :
base(name, extensions, maxContentsLength) {
UploadDirectory = uploadDirectory ?? "common.base.files";
}
}
}
|
||||
TheStack | da0f00c0ffbb275e3650b9d2a929d60d49f0b9c5 | C#code:C# | {"size": 628, "ext": "cs", "max_stars_repo_path": "KBL.Framework/KBL.Framework.BAL.Interfaces/Services/IBaseCrudServices.cs", "max_stars_repo_name": "petrekov/KBL.Framework", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KBL.Framework/KBL.Framework.BAL.Interfaces/Services/IBaseCrudServices.cs", "max_issues_repo_name": "petrekov/KBL.Framework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KBL.Framework/KBL.Framework.BAL.Interfaces/Services/IBaseCrudServices.cs", "max_forks_repo_name": "petrekov/KBL.Framework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.0526315789, "max_line_length": 102, "alphanum_fraction": 0.6926751592} | using KBL.Framework.BAL.Interfaces.Entities;
using System.Collections.Generic;
namespace KBL.Framework.BAL.Interfaces.Services
{
public interface IBaseCrudServices<DetailDto, GridDto> where DetailDto : IDto where GridDto : IDto
{
long Create(DetailDto dto);
bool Update(DetailDto dto);
bool Delete(DetailDto dto);
bool UnDelete(DetailDto dto);
long Create(DetailDto dto, string createdBy);
bool Update(DetailDto dto, string modifiedBy);
bool Delete(DetailDto dto, string deletedBy);
DetailDto Get(long id);
IEnumerable<GridDto> GetAll();
}
}
|
||||
TheStack | da0f5ced2ebf0205b22e4365ee248517e7462528 | C#code:C# | {"size": 1870, "ext": "cs", "max_stars_repo_path": "src/Murtain.Extensions.Gemini/BuilderExtensions/GeminiApplicationServiceCollectionExtensions.cs", "max_stars_repo_name": "Murtain/Murtain.X_DVA", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Murtain.Extensions.Gemini/BuilderExtensions/GeminiApplicationServiceCollectionExtensions.cs", "max_issues_repo_name": "Murtain/Murtain.X_DVA", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Murtain.Extensions.Gemini/BuilderExtensions/GeminiApplicationServiceCollectionExtensions.cs", "max_forks_repo_name": "Murtain/Murtain.X_DVA", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.9583333333, "max_line_length": 173, "alphanum_fraction": 0.7556149733} | using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Murtain.Extensions.Gemini.Builder;
using Murtain.Extensions.Dependency.Configuration;
using Murtain.Extensions.Settings.Configuration;
using Microsoft.Extensions.Configuration;
using Murtain.Extensions.AutoMapper.Configuration;
namespace Microsoft.Extensions.DependencyInjection
{
public static class GeminiApplicationServiceCollectionExtensions
{
public static IGeminiApplicationServiceCollection AddDependency(this IGeminiApplicationServiceCollection builder, Action<IDependencyScanConfiguration> option = null)
{
builder.Services.AddDependency(option);
return builder;
}
public static IGeminiApplicationServiceCollection AddLoggerInterception(this IGeminiApplicationServiceCollection builder)
{
builder.Services.AddLoggerInterception();
return builder;
}
public static IGeminiApplicationServiceCollection AddSettingsManager(this IGeminiApplicationServiceCollection builder, Action<ISettingsConfiguration> option = null)
{
builder.Services.AddSettingsManager(option);
return builder;
}
public static IGeminiApplicationServiceCollection AddServiceDiscovery(this IGeminiApplicationServiceCollection builder, IConfiguration serviceOptionsConfiguration)
{
builder.Services.AddServiceDiscovery(serviceOptionsConfiguration);
return builder;
}
public static IGeminiApplicationServiceCollection AddAutoMapper(this IGeminiApplicationServiceCollection builder, Action<IAutoMapperConfiguration> option = null)
{
builder.Services.AddAutoMapper(option);
return builder;
}
}
}
|
||||
TheStack | da11772e08c336e0115771c281969367448c4849 | C#code:C# | {"size": 629, "ext": "cs", "max_stars_repo_path": "src/In.ProjectEKA.HipService/User/AuthOnConfirmResponse.cs", "max_stars_repo_name": "thanakritTW/hip-service", "max_stars_repo_stars_event_min_datetime": "2019-12-10T09:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T10:41:54.000Z", "max_issues_repo_path": "src/In.ProjectEKA.HipService/User/AuthOnConfirmResponse.cs", "max_issues_repo_name": "thanakritTW/hip-service", "max_issues_repo_issues_event_min_datetime": "2019-12-30T12:59:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-06T09:40:26.000Z", "max_forks_repo_path": "src/In.ProjectEKA.HipService/User/AuthOnConfirmResponse.cs", "max_forks_repo_name": "thanakritTW/hip-service", "max_forks_repo_forks_event_min_datetime": "2020-06-26T06:56:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T12:53:18.000Z"} | {"max_stars_count": 12.0, "max_issues_count": 180.0, "max_forks_count": 10.0, "avg_line_length": 27.347826087, "max_line_length": 116, "alphanum_fraction": 0.586645469} | namespace In.ProjectEKA.HipService.User
{
using System;
using HipLibrary.Patient.Model;
public class AuthOnConfirmResponse
{
public AuthOnConfirmResponse(Guid requestId, DateTime timestamp, AuthOnConfirm auth, Error error, Resp resp)
{
RequestId = requestId;
Timestamp = timestamp;
Auth = auth;
Error = error;
Resp = resp;
}
public Guid RequestId { get; }
public DateTime Timestamp { get; }
public AuthOnConfirm Auth { get; }
public Error Error { get; }
public Resp Resp { get; }
}
} |
||||
TheStack | da119d75e31e8ae9fc87fb0ef42b898292c28d6b | C#code:C# | {"size": 4902, "ext": "cs", "max_stars_repo_path": "Website/DesktopModules/Hotcakes/Core/Models/ProductImage.cs", "max_stars_repo_name": "puresystems/hotcakes-commerce-core", "max_stars_repo_stars_event_min_datetime": "2018-09-20T19:53:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T00:14:02.000Z", "max_issues_repo_path": "Website/DesktopModules/Hotcakes/Core/Models/ProductImage.cs", "max_issues_repo_name": "puresystems/hotcakes-commerce-core", "max_issues_repo_issues_event_min_datetime": "2018-09-18T17:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T09:47:29.000Z", "max_forks_repo_path": "Website/DesktopModules/Hotcakes/Core/Models/ProductImage.cs", "max_forks_repo_name": "puresystems/hotcakes-commerce-core", "max_forks_repo_forks_event_min_datetime": "2018-09-20T19:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T06:11:46.000Z"} | {"max_stars_count": 29.0, "max_issues_count": 177.0, "max_forks_count": 37.0, "avg_line_length": 43.3805309735, "max_line_length": 120, "alphanum_fraction": 0.6483068135} | #region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using Hotcakes.Commerce;
using Hotcakes.Commerce.Catalog;
using Hotcakes.Commerce.Storage;
namespace Hotcakes.Modules.Core.Models
{
/// <summary>
/// Product images information.
/// This can be used to show the multiple images of the products on product detail page.
/// </summary>
[Serializable]
public class ProductImageUrls
{
/// <summary>
/// Original image url without resize.
/// </summary>
public string OriginalUrl { get; set; }
/// <summary>
/// Medium size image url which generated from original image
/// </summary>
public string MediumlUrl { get; set; }
/// <summary>
/// Small size image url which is generated from original image
/// </summary>
public string SmallUrl { get; set; }
/// <summary>
/// Very small size image url which is generated from original image.
/// This is shown as small icons and hover on it show the bigger image.
/// </summary>
public string TinyUrl { get; set; }
/// <summary>
/// Alter text for image if image not available.
/// </summary>
public string MediumlAltText { get; set; }
/// <summary>
/// Alternate text for the image if image not available
/// </summary>
public string SmallAltText { get; set; }
/// <summary>
/// Load the Image information for the product
/// </summary>
/// <param name="hccApp">An instance of the Hotcakes Application context.</param>
/// <param name="product">Product for which its required to have the image details.</param>
public void LoadProductImageUrls(HotcakesApplication hccApp, Product product)
{
OriginalUrl = DiskStorage.ProductImageUrlOriginal(hccApp, product.Bvin, product.ImageFileSmall,
hccApp.IsCurrentRequestSecure());
MediumlUrl = DiskStorage.ProductImageUrlMedium(hccApp, product.Bvin, product.ImageFileMedium,
hccApp.IsCurrentRequestSecure());
SmallUrl = DiskStorage.ProductImageUrlSmall(hccApp, product.Bvin, product.ImageFileSmall,
hccApp.IsCurrentRequestSecure());
MediumlAltText = product.ImageFileMediumAlternateText;
SmallAltText = product.ImageFileSmallAlternateText;
TinyUrl = SmallUrl;
if (string.IsNullOrWhiteSpace(MediumlAltText))
{
MediumlAltText = SmallAltText;
}
}
/// <summary>
/// Load additional image information for the given product
/// </summary>
/// <param name="hccApp">An instance of the Hotcakes Application context.</param>
/// <param name="img">Product for which its required to have the image details.</param>
public void LoadAlternateImageUrls(HotcakesApplication hccApp, ProductImage img)
{
MediumlUrl = DiskStorage.ProductAdditionalImageUrlMedium(hccApp, img.ProductId, img.Bvin, img.FileName,
false);
OriginalUrl = DiskStorage.ProductAdditionalImageUrlOriginal(hccApp, img.ProductId, img.Bvin, img.FileName,
false);
SmallUrl = DiskStorage.ProductAdditionalImageUrlSmall(hccApp, img.ProductId, img.Bvin, img.FileName, false);
TinyUrl = DiskStorage.ProductAdditionalImageUrlTiny(hccApp, img.ProductId, img.Bvin, img.FileName, false);
MediumlAltText = img.AlternateText;
SmallAltText = img.AlternateText;
}
}
} |
||||
TheStack | da122b828e1b319b5794e52ed962476ada35ddb5 | C#code:C# | {"size": 177, "ext": "cs", "max_stars_repo_path": "MiniFSWatcher/Events/RenameOrMoveEvent.cs", "max_stars_repo_name": "BurcinSayin/MiniFSWatcher", "max_stars_repo_stars_event_min_datetime": "2016-07-14T10:01:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T09:40:50.000Z", "max_issues_repo_path": "MiniFSWatcher/Events/RenameOrMoveEvent.cs", "max_issues_repo_name": "BurcinSayin/MiniFSWatcher", "max_issues_repo_issues_event_min_datetime": "2016-09-22T22:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T08:42:03.000Z", "max_forks_repo_path": "MiniFSWatcher/Events/RenameOrMoveEvent.cs", "max_forks_repo_name": "BurcinSayin/MiniFSWatcher", "max_forks_repo_forks_event_min_datetime": "2016-09-22T21:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T23:47:36.000Z"} | {"max_stars_count": 50.0, "max_issues_count": 11.0, "max_forks_count": 24.0, "avg_line_length": 22.125, "max_line_length": 57, "alphanum_fraction": 0.6779661017} | namespace CenterDevice.MiniFSWatcher.Events
{
public class RenameOrMoveEvent: FileSystemEvent
{
public string OldFilename { get; internal set; }
}
}
|
||||
TheStack | da122f04fa27aaac77859f88bffb1d0786c9061b | C#code:C# | {"size": 2070, "ext": "cshtml", "max_stars_repo_path": "src/StockportWebapp/Views/stockportgov/Shared/_LayoutPrint.cshtml", "max_stars_repo_name": "smbc-digital/iag-webapp", "max_stars_repo_stars_event_min_datetime": "2016-11-20T18:22:26.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-26T09:02:34.000Z", "max_issues_repo_path": "src/StockportWebapp/Views/stockportgov/Shared/_LayoutPrint.cshtml", "max_issues_repo_name": "smbc-digital/iag-webapp", "max_issues_repo_issues_event_min_datetime": "2016-11-21T16:54:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T19:59:44.000Z", "max_forks_repo_path": "src/StockportWebapp/Views/stockportgov/Shared/_LayoutPrint.cshtml", "max_forks_repo_name": "smbc-digital/iag-webapp", "max_forks_repo_forks_event_min_datetime": "2017-03-13T20:36:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T14:05:22.000Z"} | {"max_stars_count": 5.0, "max_issues_count": 8.0, "max_forks_count": 2.0, "avg_line_length": 71.3793103448, "max_line_length": 366, "alphanum_fraction": 0.7487922705} |
<!DOCTYPE html>
<html lang="en-GB" class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=12.0, minimum-scale=1" />
<title>Stockport Council</title>
<link href="~/assets/stylesheets/cludo-search-default.css" rel="stylesheet" />
<link rel="stylesheet" href="/assets/stylesheets/vendor/unsemantic-grid-responsive-tablet-min.css" />
<link rel="stylesheet" href="/assets/stylesheets/styleguide-sg.min.css" />
<link rel="stylesheet" href="~/assets/stylesheets/site-sg.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" integrity="sha256-AIodEDkC8V/bHBkfyxzolUMw57jeQ9CauwhVW6YJ9CA= sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1 sha512-4uGZHpbDliNxiAv/QzZNo/yb2FtAX+qiDb7ypBWiEdJQX8Pugp8M6il5SRkN8jQrDLWsh3rrPDSXRf3DwFYM6g==" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI= sha384-mXQoED/lFIuocc//nss8aJOIrz7X7XruhR6bO+sGceiSyMELoVdZkN7F0oYwcFH+ sha512-QAV866KcCo2YSgj8D7BW+Zn3Fe5wVKTWwzKtWy8mkW+tePcJL7JYilvdfrBFQcdz4ODD48GpIPnhTp9UDI37uw==" crossorigin="anonymous"></script>
</head>
<body class="container-layout-free print">
<main>
@RenderBody()
</main>
<script src="~/assets/javascript/vendor/modernizr.min.js"></script>
<script src="~/assets/javascript/vendor/jquery.validate.min.js"></script>
<script src="~/assets/javascript/vendor/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="~/assets/stylesheets/vendor/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
<script src="/assets/javascript/vendor/slick.min.js"></script>
<script type="text/javascript" src="//customer.cludo.com/scripts/bundles/search-script.min.js"></script>
<script src="/assets/javascript/stockportgov.min.js"></script>
</body>
</html> |
||||
TheStack | da12debf2b2c08136ba2901c3e9db6f1d2a6779d | C#code:C# | {"size": 13316, "ext": "cs", "max_stars_repo_path": "tools/ModuleCore/src/TestProperties.cs", "max_stars_repo_name": "DJackman123/Extensions", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/ModuleCore/src/TestProperties.cs", "max_issues_repo_name": "DJackman123/Extensions", "max_issues_repo_issues_event_min_datetime": "2019-08-02T15:57:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-02T15:57:32.000Z", "max_forks_repo_path": "tools/ModuleCore/src/TestProperties.cs", "max_forks_repo_name": "aayc/Extensions", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 27.6265560166, "max_line_length": 126, "alphanum_fraction": 0.4471312707} | //---------------------------------------------------------------------
// <copyright file="TestProperties.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System;
using System.Collections; //IEnumerator
using System.Collections.Generic; //List<T>
using System.Security.Permissions;
using System.Security;
namespace Microsoft.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// TestInput
//
////////////////////////////////////////////////////////////////
public class TestInput
{
//Data
static TestProps _properties;
static String _initstring;
static String _commandline;
//Constructor
static public TestProps Properties
{
get
{
//Delegate for now...
if(_properties == null)
TestInput.Properties = new TestProps(new TestProperties());
return _properties;
}
[EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
[SecuritySafeCritical]
set
{
//TODO: This code should eventually be in ltm and then we simply only use it's collection
//_properties = value;
//For now, we do our own logic
//Clear between each run
_properties = new TestProps(new TestProperties());
//InitString keywords
String initstring = value["Alias/InitString"];
if(initstring != null)
{
_properties["Alias/InitString"] = initstring;
//Keywords
Hashtable keywords = KeywordParser.ParseKeywords(initstring);
foreach(String key in keywords.Keys)
_properties["Alias/InitString/" + key] = keywords[key] as String;
}
//CommandLine
String commandline = value["CommandLine"] ?? Environment.CommandLine;
if(commandline != null)
{
_properties["CommandLine"] = commandline;
//Options
KeywordParser.Tokens tokens = new KeywordParser.Tokens();
tokens.Equal = " ";
tokens.Seperator = "/";
Hashtable options = KeywordParser.ParseKeywords(commandline, tokens);
foreach (String key in options.Keys)
_properties["CommandLine/" + key] = options[key] as String;
}
}
}
static internal void Dispose()
{
//Reset the info.
//Since this is a static class, (to make it simplier to access from anywhere in your code)
//we need to reset this info everytime a test is run - so if you don't select an alias
//the next time it doesn't use the previous alias setting - ie: ProviderInfo doesn't
//get called when no alias is selected...
_properties = null;
_initstring = null;
_commandline = null;
}
static public string InitString
{
get
{
//Useful typed getter
if(_initstring == null)
_initstring = TestInput.Properties["Alias/InitString"];
return _initstring;
}
}
static public string CommandLine
{
get
{
//Useful typed getter
if (_commandline == null)
_commandline = TestInput.Properties["CommandLine"];
return _commandline;
}
}
static public String Filter
{
get
{
if(TestInput.Properties != null)
return TestInput.Properties["CommandLine/Filter"];
return null;
}
}
static public String MaxPriority
{
get
{
if(TestInput.Properties != null)
return TestInput.Properties["CommandLine/MaxPriority"];
return null;
}
}
}
////////////////////////////////////////////////////////////////
// TestProps
//
////////////////////////////////////////////////////////////////
public class TestProps : ITestProperties, IEnumerable, IEnumerator
{
//Data
protected ITestProperties _internal;
protected int _enum = -1;
//Constructor
public TestProps(ITestProperties properties)
{
_internal = properties;
}
//Accessors
public virtual ITestProperties Internal
{
get { return _internal; }
}
public virtual int Count
{
get
{
if(_internal != null)
return _internal.Count;
return 0;
}
}
public virtual TestProp this[int index]
{
get
{
ITestProperty property = _internal.GetItem(index);
if(property != null)
return new TestProp(property);
return null;
}
}
public virtual String this[String name]
{
get
{
ITestProperty property = _internal.Get(name);
if(property != null)
return StringEx.ToString(property.Value);
return null;
}
set
{
this.Add(name).Value = value;
}
}
public virtual TestProp Get(String name)
{
ITestProperty property = _internal.Get(name);
if(property != null)
return new TestProp(property);
return null;
}
public virtual TestProp Add(String name)
{
return new TestProp(_internal.Add(name));
}
public virtual void Remove(String name)
{
_internal.Remove(name);
}
public virtual IEnumerator GetEnumerator()
{
return this;
}
public virtual bool MoveNext()
{
if(_enum+1 >= this.Count)
return false;
_enum++;
return true;
}
public virtual Object Current
{
get { return this[_enum]; }
}
public virtual void Reset()
{
_enum = -1;
}
public virtual void Clear()
{
if(_internal != null)
_internal.Clear();
}
ITestProperty ITestProperties.Add(String name)
{
return _internal.Add(name);
}
ITestProperty ITestProperties.Get(String name)
{
return _internal.Get(name);
}
ITestProperty ITestProperties.GetItem(int index)
{
return _internal.GetItem(index);
}
}
////////////////////////////////////////////////////////////////
// TestProp
//
////////////////////////////////////////////////////////////////
public class TestProp : ITestProperty, IEnumerable
{
//Data
protected ITestProperty _internal;
//Constructor
public TestProp(ITestProperty property)
{
_internal = property;
}
//Accessors
public virtual ITestProperty Internal
{
get { return _internal; }
}
public virtual String Name
{
get { return _internal.Name; }
}
public virtual String Desc
{
get { return _internal.Desc; }
}
public virtual TestPropertyFlags Flags
{
get { return _internal.Flags; }
set { _internal.Flags = value; }
}
public virtual Object Value
{
get { return _internal.Value; }
set { _internal.set_Value(ref value); }
}
public virtual TestProps Children
{
get { return new TestProps(_internal.Children); }
}
public virtual IEnumerator GetEnumerator()
{
return this.Children;
}
void ITestProperty.set_Value(ref object value)
{
_internal.set_Value(ref value);
}
ITestProperties ITestProperty.Children
{
get { return _internal.Children; }
}
ITestProperties ITestProperty.Metadata
{
get { return _internal.Metadata; }
}
}
////////////////////////////////////////////////////////////////
// TestProperty
//
////////////////////////////////////////////////////////////////
[Serializable]
public class TestProperty : ITestProperty
{
//Data
protected String _name = null;
protected String _desc = null;
protected Object _value = null;
protected TestPropertyFlags _flags = 0;
protected TestProperties _metadata = null;
protected TestProperties _children = null;
//Constructor
public TestProperty(String name, Object value)
{
_name = name;
_value = value;
}
//Accessors
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Desc
{
get { return _desc; }
set { _desc = value; }
}
public TestPropertyFlags Flags
{
get { return _flags; }
set { _flags = value; }
}
public object Value
{
get { return _value; }
set { _value = value; }
}
public void set_Value(ref object value)
{
_value = value;
}
public ITestProperties Metadata
{
get { return _metadata; }
}
public ITestProperties Children
{
get { return _children; }
}
}
////////////////////////////////////////////////////////////////
// TestProperties
//
////////////////////////////////////////////////////////////////
[Serializable]
public class TestProperties : ITestProperties, IEnumerable
{
//Data
protected List<TestProperty> _list = null;
//Constructor
public TestProperties()
{
_list = new List<TestProperty>();
}
//Methods
public virtual int Count
{
get { return _list.Count; }
}
public virtual TestProperty this[int index]
{
get { return _list[index]; }
}
public virtual Object this[String name]
{
get
{
ITestProperty property = this.Get(name);
if(property != null)
return property.Value;
return null;
}
set { this.Add(name).Value = value; }
}
public virtual int IndexOf(string name)
{
int count = _list.Count;
for(int i=0; i<count; i++)
{
if(String.Compare(_list[i].Name, name, true/*ignorecase*/)==0)
return i;
}
return -1;
}
public virtual IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
ITestProperty ITestProperties.GetItem(int index)
{
return this[index];
}
public virtual ITestProperty Get(String name)
{
int index = this.IndexOf(name);
if(index >= 0)
return _list[index];
return null;
}
ITestProperty ITestProperties.Add(String name)
{
return (TestProperty)Add(name);
}
public virtual TestProperty Add(String name)
{
//Exists
int index = this.IndexOf(name);
if(index >= 0)
return _list[index];
//Otherwise add
TestProperty property = new TestProperty(name, null);
_list.Add(property);
return property;
}
public virtual void Remove(String name)
{
int index = this.IndexOf(name);
if(index >= 0)
_list.RemoveAt(index);
}
public virtual void Clear()
{
_list.Clear();
}
}
}
|
||||
TheStack | da12f9d4d7e983512ccddd1f6573bd72136be88e | C#code:C# | {"size": 701, "ext": "cs", "max_stars_repo_path": "TeensyCNCManager.Core/ViewModelBase.cs", "max_stars_repo_name": "IlyaChernov/Teensy_CNC_Manager", "max_stars_repo_stars_event_min_datetime": "2019-07-10T19:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T08:29:53.000Z", "max_issues_repo_path": "TeensyCNCManager.Core/ViewModelBase.cs", "max_issues_repo_name": "IlyaChernov/Teensy_CNC_Manager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TeensyCNCManager.Core/ViewModelBase.cs", "max_forks_repo_name": "IlyaChernov/Teensy_CNC_Manager", "max_forks_repo_forks_event_min_datetime": "2018-11-05T13:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-25T07:27:32.000Z"} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 26.9615384615, "max_line_length": 90, "alphanum_fraction": 0.6504992867} | namespace TeensyCNCManager.Core
{
using System.ComponentModel;
using System.Runtime.CompilerServices;
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void OnPropertyChangedAuto([CallerMemberName]string propertyName = null)
{
OnPropertyChanged(propertyName);
}
}
}
|
||||
TheStack | da1320922417f842f6503f0309cf56fb6d102091 | C#code:C# | {"size": 862, "ext": "cs", "max_stars_repo_path": "Nats/src/Vls.Abp.Nats/Utf8JsonNatsSerializer.cs", "max_stars_repo_name": "vicecop/Vlc.Abp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Nats/src/Vls.Abp.Nats/Utf8JsonNatsSerializer.cs", "max_issues_repo_name": "vicecop/Vlc.Abp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nats/src/Vls.Abp.Nats/Utf8JsonNatsSerializer.cs", "max_forks_repo_name": "vicecop/Vlc.Abp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.1212121212, "max_line_length": 85, "alphanum_fraction": 0.650812065} | using System;
using System.Text;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Json;
namespace Vls.Abp.Nats
{
public class Utf8JsonNatsSerializer : INatsSerializer, ITransientDependency
{
private readonly IJsonSerializer _jsonSerializer;
public Utf8JsonNatsSerializer(IJsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public byte[] Serialize(object obj)
{
return Encoding.UTF8.GetBytes(_jsonSerializer.Serialize(obj));
}
public object Deserialize(byte[] value, Type type)
{
return _jsonSerializer.Deserialize(type, Encoding.UTF8.GetString(value));
}
public T Deserialize<T>(byte[] value)
{
return _jsonSerializer.Deserialize<T>(Encoding.UTF8.GetString(value));
}
}
}
|
||||
TheStack | da139acfae6424b91f806ce7aea8c6c72e6c9124 | C#code:C# | {"size": 4676, "ext": "cs", "max_stars_repo_path": "Bookify/Bookify.App/Bookify.App.Core/Initialization/Bootstrapper.cs", "max_stars_repo_name": "Falgantil/Bookify", "max_stars_repo_stars_event_min_datetime": "2017-01-23T14:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-23T14:42:03.000Z", "max_issues_repo_path": "Bookify/Bookify.App/Bookify.App.Core/Initialization/Bootstrapper.cs", "max_issues_repo_name": "RiBoysen/Bookify", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bookify/Bookify.App/Bookify.App.Core/Initialization/Bootstrapper.cs", "max_forks_repo_name": "RiBoysen/Bookify", "max_forks_repo_forks_event_min_datetime": "2019-09-13T09:09:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-13T09:09:52.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 43.2962962963, "max_line_length": 150, "alphanum_fraction": 0.6505560308} | using System;
using System.Linq;
using Acr.UserDialogs;
using Bookify.App.Core.Interfaces;
using Bookify.App.Core.Interfaces.Initialization;
using Bookify.App.Core.Interfaces.Services;
using Bookify.App.Core.Services;
using Bookify.App.Sdk;
using Bookify.App.Sdk.Implementations;
using Bookify.App.Sdk.Interfaces;
using Ninject;
using Ninject.Parameters;
using PCLStorage;
namespace Bookify.App.Core.Initialization
{
/// <summary>
/// The shared Bootstrapper. Requires a <see cref="IPlatformInitializer"/> that will handle all platform-specific initialization.
/// </summary>
public sealed class Bootstrapper
{
/// <summary>
/// The platform initializer
/// </summary>
private readonly IPlatformInitializer platformInitializer;
/// <summary>
/// The DI kernel
/// </summary>
private IKernel kernel;
/// <summary>
/// Initializes a new instance of the <see cref="Bootstrapper"/> class.
/// </summary>
/// <param name="platformInitializer">The platform initializer.</param>
private Bootstrapper(IPlatformInitializer platformInitializer)
{
this.platformInitializer = platformInitializer;
}
/// <summary>
/// Creates an instance of <see cref="Bootstrapper" /> that automatically initializes the Bootstrapper and <see cref="platformInitializer" />.
/// </summary>
/// <param name="platformInitializer">The platform initializer.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">Thrown if <see cref="platformInitializer"/> is null.</exception>
public static Bootstrapper Initialize(IPlatformInitializer platformInitializer)
{
if (platformInitializer == null)
{
throw new ArgumentNullException(nameof(platformInitializer));
}
var bootstrapper = new Bootstrapper(platformInitializer);
bootstrapper.Initialize();
return bootstrapper;
}
/// <summary>
/// Resolves an instance of type <see cref="T"/> from the DI kernel, using any provided parameters.
/// </summary>
/// <typeparam name="T">Any type that requires constructor parameters to be resolved using types from the registered kernel.</typeparam>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
public T Resolve<T>(params Parameter[] parameters)
{
var args = parameters.Select(p => (IParameter)new ConstructorArgument(p.ParamName, p.Value));
return this.kernel.Get<T>(args.ToArray());
}
/// <summary>
/// Initializes this instance, as well as the registered PlatformInitializer.
/// </summary>
private void Initialize()
{
this.kernel = new StandardKernel();
ApiConfig.Website = "https://bookifyapi.azurewebsites.net/";
this.platformInitializer.BeforeInit(this.kernel);
// Create all platform independent bindings here
this.kernel.Bind<IUserDialogs>().ToMethod(c => UserDialogs.Instance);
this.kernel.Bind<IFileSystem>().ToMethod(c => FileSystem.Current);
this.kernel.Bind<IDelayService>().To<DelayService>().InSingletonScope();
this.kernel.Bind<ICachingRegionFactory>().To<CachingRegionFactory>().InSingletonScope();
this.kernel.Bind<IAuthenticationApi>().To<AuthenticationApi>().InSingletonScope();
this.kernel.Bind<IBooksApi>().To<BooksApi>().InSingletonScope();
this.kernel.Bind<IGenresApi>().To<GenresApi>().InSingletonScope();
this.kernel.Bind<IPersonApi>().To<PersonApi>().InSingletonScope();
this.kernel.Bind<IFeedbackApi>().To<FeedbackApi>().InSingletonScope();
this.kernel.Bind<IFilesApi>().To<FilesApi>().InSingletonScope();
this.kernel.Bind<IAuthenticationService>().To<AuthenticationService>().InSingletonScope();
this.kernel.Bind<IPersonService>().To<PersonService>().InSingletonScope();
this.kernel.Bind<IShoppingCartService>().To<ShoppingCartService>().InSingletonScope();
this.kernel.Bind<IBooksService>().To<BooksService>().InSingletonScope();
this.kernel.Bind<IFeedbackService>().To<FeedbackService>().InSingletonScope();
this.kernel.Bind<IGenreService>().To<GenreService>().InSingletonScope();
this.kernel.Bind<IConfig>().To<Config>().InSingletonScope();
this.platformInitializer.AfterInit(this.kernel);
}
}
}
|
||||
TheStack | da14e289337e0e7b74eb8d2a1114e49677afb08a | C#code:C# | {"size": 711, "ext": "cs", "max_stars_repo_path": "src/HBaseNet/Metadata/Annotations/HBasePropertyAttribute.cs", "max_stars_repo_name": "hsxian/HBaseNet", "max_stars_repo_stars_event_min_datetime": "2020-08-02T11:40:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T05:23:35.000Z", "max_issues_repo_path": "src/HBaseNet/Metadata/Annotations/HBasePropertyAttribute.cs", "max_issues_repo_name": "hsxian/HBaseNet", "max_issues_repo_issues_event_min_datetime": "2021-06-24T09:18:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T08:35:10.000Z", "max_forks_repo_path": "src/HBaseNet/Metadata/Annotations/HBasePropertyAttribute.cs", "max_forks_repo_name": "hsxian/HBaseNet", "max_forks_repo_forks_event_min_datetime": "2020-08-04T01:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-06T01:47:40.000Z"} | {"max_stars_count": 35.0, "max_issues_count": 3.0, "max_forks_count": 2.0, "avg_line_length": 35.55, "max_line_length": 144, "alphanum_fraction": 0.6511954993} | using System;
using HBaseNet.Const;
using HBaseNet.Utility;
namespace HBaseNet.Metadata.Annotations
{
public class HBasePropertyAttribute : Attribute
{
public bool IsIgnore { get; set; }
public byte[] Family { get; set; }
public byte[] Qualifier { get; set; }
public HBasePropertyAttribute(byte[] family, byte[] qualifier)
{
Family = family ?? ConstByte.DefaultFamily;
Qualifier = qualifier;
}
public HBasePropertyAttribute(byte[] qualifier) : this(null, qualifier) { }
public HBasePropertyAttribute(string family = null, string qualifier = null) : this(family?.ToUtf8Bytes(), qualifier?.ToUtf8Bytes()) { }
}
} |
||||
TheStack | da174741c33b7e3b11f946e32e8741a3654ec13e | C#code:C# | {"size": 1894, "ext": "cs", "max_stars_repo_path": "src/TooMany.WebServer/Startup.cs", "max_stars_repo_name": "MiloszKrajewski/TooMany", "max_stars_repo_stars_event_min_datetime": "2020-12-17T21:52:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T10:37:07.000Z", "max_issues_repo_path": "src/TooMany.WebServer/Startup.cs", "max_issues_repo_name": "MiloszKrajewski/TooMany", "max_issues_repo_issues_event_min_datetime": "2020-12-17T23:12:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T13:50:25.000Z", "max_forks_repo_path": "src/TooMany.WebServer/Startup.cs", "max_forks_repo_name": "MiloszKrajewski/TooMany", "max_forks_repo_forks_event_min_datetime": "2021-05-28T21:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T21:12:13.000Z"} | {"max_stars_count": 5.0, "max_issues_count": 29.0, "max_forks_count": 1.0, "avg_line_length": 29.1384615385, "max_line_length": 100, "alphanum_fraction": 0.7597676874} | using System;
using System.Linq;
using K4os.Json.KnownTypes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace TooMany.WebServer
{
public class Startup
{
public Startup(IConfiguration configuration) { Configuration = configuration; }
private IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddNewtonsoftJson(
o => UpdateSerializationSettings(o.SerializerSettings));
services
.AddSignalR()
.AddNewtonsoftJsonProtocol(
o => UpdateSerializationSettings(o.PayloadSerializerSettings));
}
private static void UpdateSerializationSettings(JsonSerializerSettings settings)
{
settings.SerializationBinder = KnownTypesSerializationBinder.Default;
settings.NullValueHandling = NullValueHandling.Ignore;
settings.TypeNameHandling = TypeNameHandling.Auto;
settings.Formatting = Formatting.None;
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseStaticFiles();
app.UseCors(ConfigureCors);
app.UseEndpoints(
endpoints => {
endpoints.MapControllers();
endpoints.MapHub<MonitorHub>("/monitor");
});
}
private void ConfigureCors(CorsPolicyBuilder policy)
{
var origins = Configuration.GetSection("Host:Server:Cors").Get<string[]>();
policy
.WithOrigins(origins)
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
}
}
}
|
||||
TheStack | da180ec35cb1245ab23962fa0d12873e5d930a6e | C#code:C# | {"size": 1041, "ext": "cs", "max_stars_repo_path": "src/OptsLib.Avalonia/Editors/EnumOptionEditor.axaml.cs", "max_stars_repo_name": "piksel/OptsLib", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OptsLib.Avalonia/Editors/EnumOptionEditor.axaml.cs", "max_issues_repo_name": "piksel/OptsLib", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OptsLib.Avalonia/Editors/EnumOptionEditor.axaml.cs", "max_forks_repo_name": "piksel/OptsLib", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.3902439024, "max_line_length": 78, "alphanum_fraction": 0.5360230548} | using System;
using System.Diagnostics;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using static Avalonia.Controls.Design;
namespace OptsLib.Avalonia.Editors
{
public class EnumOptionEditor : OptionEditor
{
public static DirectProperty<EnumOptionEditor, Enum?> ValueProperty =
AvaloniaProperty.RegisterDirect<EnumOptionEditor, Enum?>(
nameof(Value), e => e.Value, (e, v) => e.Value = v);
Enum? _value;
public Enum? Value
{
get => _value;
set
{
Debug.WriteLine($"EnumValue => {value}");
SetAndRaise(ValueProperty, ref _value, value);
}
}
public EnumOptionEditor()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
// if (!IsDesignMode)
// {
// DataContext = this;
// }
}
}
} |
||||
TheStack | da1b4e90ea731a47fbd191a88001df858b9a7cc3 | C#code:C# | {"size": 331, "ext": "cs", "max_stars_repo_path": "src/Tinja.Abstractions/Injection/Graphs/IGraphSiteBuilder.cs", "max_stars_repo_name": "zuvys/Tinja", "max_stars_repo_stars_event_min_datetime": "2018-04-02T09:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T03:18:38.000Z", "max_issues_repo_path": "src/Tinja.Abstractions/Injection/Graphs/IGraphSiteBuilder.cs", "max_issues_repo_name": "zuvys/Tinja", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tinja.Abstractions/Injection/Graphs/IGraphSiteBuilder.cs", "max_forks_repo_name": "zuvys/Tinja", "max_forks_repo_forks_event_min_datetime": "2019-05-07T03:32:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T10:51:56.000Z"} | {"max_stars_count": 18.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 23.6428571429, "max_line_length": 72, "alphanum_fraction": 0.6888217523} | using System;
using Tinja.Abstractions.Injection.Graphs.Sites;
namespace Tinja.Abstractions.Injection.Graphs
{
/// <summary>
/// an interface for build <see cref="GraphSite"/>
/// </summary>
public interface IGraphSiteBuilder
{
GraphSite Build(Type serviceType, string tag, bool tagOptional);
}
}
|
||||
TheStack | da1b98f83f7e5dfff74a0e95968861edb3f873b1 | C#code:C# | {"size": 656, "ext": "cs", "max_stars_repo_path": "DasContract.Editor.Web/Components/Common/TabButton.razor.cs", "max_stars_repo_name": "drozdik-m/DasContract", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DasContract.Editor.Web/Components/Common/TabButton.razor.cs", "max_issues_repo_name": "drozdik-m/DasContract", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DasContract.Editor.Web/Components/Common/TabButton.razor.cs", "max_forks_repo_name": "drozdik-m/DasContract", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.2962962963, "max_line_length": 66, "alphanum_fraction": 0.6798780488} | using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DasContract.Editor.Web.Components.Common
{
public partial class TabButton: ComponentBase
{
[Parameter]
public bool Active { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> OnClick { get; set; }
protected async void OnClickHandler(MouseEventArgs args)
{
await OnClick.InvokeAsync(args);
}
}
}
|
||||
TheStack | da1bc230e49c7a1dbd32a1cbd2a9f154e7bd0530 | C#code:C# | {"size": 2080, "ext": "cshtml", "max_stars_repo_path": "Form.Examples/Views/Examples/_ExampleTwoForm.cshtml", "max_stars_repo_name": "matteoinno/Form.Examples", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Form.Examples/Views/Examples/_ExampleTwoForm.cshtml", "max_issues_repo_name": "matteoinno/Form.Examples", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Form.Examples/Views/Examples/_ExampleTwoForm.cshtml", "max_forks_repo_name": "matteoinno/Form.Examples", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 49.5238095238, "max_line_length": 115, "alphanum_fraction": 0.5625} | @model Form.Examples.Models.ExampleTwoViewModel
@{
Layout = null;
}
<!--IMPORTANT: add an id to the form. It is necessary to serialize the form in the javascript.-->
@using (Html.BeginForm("ExampleTwo", "Examples", FormMethod.Post, new { id = "insert-dialog-form" }))
{
<div class="form-horizontal">
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Company, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Company, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })
</div>
</div>
</div>
} |
||||
TheStack | da1c60be30c1bec4bf58d9799404bfcb4e38a4ad | C#code:C# | {"size": 238, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/2.Attribute/6.Conditionals/DisableInPrefabsAttributeExample.cs", "max_stars_repo_name": "RootGame/Odin-Inspector-Chinese-Tutorial", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/2.Attribute/6.Conditionals/DisableInPrefabsAttributeExample.cs", "max_issues_repo_name": "RootGame/Odin-Inspector-Chinese-Tutorial", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/2.Attribute/6.Conditionals/DisableInPrefabsAttributeExample.cs", "max_forks_repo_name": "RootGame/Odin-Inspector-Chinese-Tutorial", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 18.3076923077, "max_line_length": 61, "alphanum_fraction": 0.8151260504} | #region
using Sirenix.OdinInspector;
using UnityEngine;
#endregion
public class DisableInPrefabsAttributeExample : MonoBehaviour
{
[DisableInPrefabs]//只要是预制体,就隐藏此属性,不管是否在asset还是hierarchy
public GameObject DisabledInPrefabs;
}
|
||||
TheStack | da1d4257b93ca705c29c7c8ebc4ab2d3e5771372 | C#code:C# | {"size": 1090, "ext": "cs", "max_stars_repo_path": "src/FluentHub.Octokit/Models/User.cs", "max_stars_repo_name": "fluenthub-community/FluentHub", "max_stars_repo_stars_event_min_datetime": "2022-03-03T11:43:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:27:39.000Z", "max_issues_repo_path": "src/FluentHub.Octokit/Models/User.cs", "max_issues_repo_name": "fluenthub-community/FluentHub", "max_issues_repo_issues_event_min_datetime": "2022-03-05T05:57:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:43:22.000Z", "max_forks_repo_path": "src/FluentHub.Octokit/Models/User.cs", "max_forks_repo_name": "onein528/FluentHub", "max_forks_repo_forks_event_min_datetime": "2022-03-11T13:16:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:33.000Z"} | {"max_stars_count": 26.0, "max_issues_count": 35.0, "max_forks_count": 4.0, "avg_line_length": 33.0303030303, "max_line_length": 58, "alphanum_fraction": 0.6220183486} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FluentHub.Octokit.Models
{
public class User
{
public string AvatarUrl { get; set; }
public string Bio { get; set; }
public string Company { get; set; }
public string Email { get; set; }
public bool IsCampusExpert { get; set; }
public bool IsBountyHunter { get; set; }
public bool IsDeveloperProgramMember { get; set; }
public bool IsEmployee { get; set; }
public bool IsGitHubStar { get; set; }
public bool IsViewer { get; set; }
public string Location { get; set; }
public string Login { get; set; }
public string Name { get; set; }
public string TwitterUsername { get; set; }
public bool ViewerIsFollowing { get; set; }
public string WebsiteUrl { get; set; }
public bool IsOrganization { get; set; }
public int FollowersTotalCount { get; set; }
public int FollowingTotalCount { get; set; }
}
}
|
||||
TheStack | da2033f3ed4d5a90798b75cf0731dae95901fa10 | C#code:C# | {"size": 6236, "ext": "cs", "max_stars_repo_path": "UIPeriodicTable/CSharp/Resources/Components/code_table.cs", "max_stars_repo_name": "AtomicGameEngine/AtomicPrototypes", "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T14:50:10.000Z", "max_issues_repo_path": "UIPeriodicTable/CSharp/Resources/Components/code_table.cs", "max_issues_repo_name": "AtomicGameEngine/AtomicPrototypes", "max_issues_repo_issues_event_min_datetime": "2015-03-25T14:28:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-04T14:25:18.000Z", "max_forks_repo_path": "UIPeriodicTable/CSharp/Resources/Components/code_table.cs", "max_forks_repo_name": "AtomicGameEngine/AtomicPrototypes", "max_forks_repo_forks_event_min_datetime": "2015-04-06T18:55:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-25T01:18:46.000Z"} | {"max_stars_count": 122.0, "max_issues_count": 85.0, "max_forks_count": 75.0, "avg_line_length": 35.4318181818, "max_line_length": 100, "alphanum_fraction": 0.4538165491} | // handle the periodic table jumps
using System;
using AtomicEngine;
public class code_table : CSComponent {
public void Setup( UILayout mylayout )
{
UILayout pgtable = (UILayout) mylayout.GetWidget("pagetable");
var dest = new AtomicEngine.Vector<AtomicEngine.UIWidget>();
pgtable.SearchWidgetClass( "TBButton", dest );
for (var ii = 0; ii < dest.Size; ii++) { // set bulk event handlers on all buttons -- boom!
dest[ii].SubscribeToEvent<WidgetEvent> (dest [ii], HandleTableEvent);
}
}
// handle table clicks
private static void HandleTableEvent ( WidgetEvent ev )
{
UIWidget widget = (UIWidget)ev.Target;
if ( widget.Equals(null)) return;
if ( ev.Type == UI_EVENT_TYPE.UI_EVENT_TYPE_CLICK) {
UITabContainer maintb = (UITabContainer)widget.FindWidget("maintabs");
UITabContainer acttb = (UITabContainer)widget.FindWidget("primarytabs");
UITabContainer semitb = (UITabContainer)widget.FindWidget("moretabs");
UITabContainer viewtb = (UITabContainer)widget.FindWidget("supporttabs");
UITabContainer supporttb = (UITabContainer)widget.FindWidget("atomictabs");
if (widget.GetId() == "A1" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(0);
}
if (widget.GetId() == "A2" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(1);
}
if (widget.GetId() == "A3" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(2);
}
if (widget.GetId() == "A4" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(3);
}
if (widget.GetId() == "A5" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(4);
}
if (widget.GetId() == "A6" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(5);
}
if (widget.GetId() == "A7" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(6);
}
if (widget.GetId() == "A8" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(7);
}
if (widget.GetId() == "A9" ) {
maintb.SetCurrentPage(1);
acttb.SetCurrentPage(8);
}
if (widget.GetId() == "B1" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(0);
}
if (widget.GetId() == "B2" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(1);
}
if (widget.GetId() == "B3" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(2);
}
if (widget.GetId() == "B4" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(3);
}
if (widget.GetId() == "B5" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(4);
}
if (widget.GetId() == "B6" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(5);
}
if (widget.GetId() == "B7" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(6);
}
if (widget.GetId() == "B8" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(7);
}
if (widget.GetId() == "B9" ) {
maintb.SetCurrentPage(2);
semitb.SetCurrentPage(8);
}
if (widget.GetId() == "C1" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(0);
}
if (widget.GetId() == "C2" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(1);
}
if (widget.GetId() == "C3" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(2);
}
if (widget.GetId() == "C4" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(3);
}
if (widget.GetId() == "C5" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(4);
}
if (widget.GetId() == "C6" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(5);
}
if (widget.GetId() == "C7" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(6);
}
if (widget.GetId() == "C8" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(7);
}
if (widget.GetId() == "C9" ) {
maintb.SetCurrentPage(3);
viewtb.SetCurrentPage(8);
}
if (widget.GetId() == "D2" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(0);
}
if (widget.GetId() == "D3" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(1);
}
if (widget.GetId() == "D4" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(2);
}
if (widget.GetId() == "D5" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(3);
}
if (widget.GetId() == "D6" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(4);
}
if (widget.GetId() == "D7" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(5);
}
if (widget.GetId() == "D8" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(6);
}
if (widget.GetId() == "D9" ) {
maintb.SetCurrentPage(4);
supporttb.SetCurrentPage(7);
}
}
}
}
|
||||
TheStack | da209cb03ed9a03391e8073446f8311dc68aa1a3 | C#code:C# | {"size": 35262, "ext": "cs", "max_stars_repo_path": "Cores.NET/Cores.Basic/Common/Base/Kernel.cs", "max_stars_repo_name": "tyama0x7f/IPA-DN-Cores", "max_stars_repo_stars_event_min_datetime": "2020-04-21T12:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T11:19:51.000Z", "max_issues_repo_path": "Cores.NET/Cores.Basic/Common/Base/Kernel.cs", "max_issues_repo_name": "tyama0x7f/IPA-DN-Cores", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cores.NET/Cores.Basic/Common/Base/Kernel.cs", "max_forks_repo_name": "tyama0x7f/IPA-DN-Cores", "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:45:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T11:29:29.000Z"} | {"max_stars_count": 7.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 34.2017458778, "max_line_length": 183, "alphanum_fraction": 0.5203051443} | // IPA Cores.NET
//
// Copyright (c) 2018- IPA CyberLab.
// Copyright (c) 2003-2018 Daiyuu Nobori.
// Copyright (c) 2013-2018 SoftEther VPN Project, University of Tsukuba, Japan.
// All Rights Reserved.
//
// License: The Apache License, Version 2.0
// https://www.apache.org/licenses/LICENSE-2.0
//
// THIS 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.
//
// THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
// JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
// DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
// JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
// AGAINST US (IPA CYBERLAB, DAIYUU NOBORI, SOFTETHER VPN PROJECT OR OTHER
// SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
// OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
// AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
// CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
// JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
// ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
// PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
// LAW OR COURT RULE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using IPA.Cores.Basic;
using IPA.Cores.Basic.Legacy;
using IPA.Cores.Helper.Basic;
using static IPA.Cores.Globals.Basic;
namespace IPA.Cores.Basic
{
public static class Kernel
{
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);
public static PlatformID GetOsPlatform()
{
return Environment.OSVersion.Platform;
}
public static bool InternalCheckIsWow64()
{
if (GetOsPlatform() == PlatformID.Win32NT)
{
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool retVal;
if (!IsWow64Process(p.Handle, out retVal))
{
return false;
}
return retVal;
}
}
else
{
return false;
}
}
return false;
}
// スリープ
public static void SleepThread(int millisec)
{
ThreadObj.Sleep(millisec);
}
public static void SleepThreadInfinite() => SleepThread(Timeout.Infinite);
// デバッグのため停止
public static void SuspendForDebug()
{
Dbg.WriteLine("SuspendForDebug() called.");
SleepThread(ThreadObj.Infinite);
}
// 環境変数文字列の取得
public static string GetEnvStr(string name)
=> Environment.GetEnvironmentVariable(name)._NonNull();
// 現在のプロセスを強制終了する
static public void SelfKill(string msg = "")
{
if (msg._IsFilled()) msg._Print();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
// プログラムを起動する
public static Process Run(string exeName, string args)
{
Process p = new Process();
p.StartInfo.FileName = IO.InnerFilePath(exeName);
p.StartInfo.Arguments = args;
p.Start();
return p;
}
// OS の再起動
static Once RebootOnceFlag;
public static void RebootOperatingSystemForcefullyDangerous()
{
if (Env.IsLinux)
{
if (RebootOnceFlag.IsFirstCall())
{
// sync, sync, sync
for (int i = 0; i < 3; i++)
{
UnixTryRunSystemProgram(EnsureInternal.Yes, Consts.LinuxCommands.Sync, "", CoresConfig.Timeouts.RebootDangerous_Sync_Timeout);
}
Sleep(300);
// reboot
for (int i = 0; i < 3; i++)
{
UnixTryRunSystemProgram(EnsureInternal.Yes, Consts.LinuxCommands.Reboot, "--reboot --force", CoresConfig.Timeouts.RebootDangerous_Reboot_Timeout);
}
Sleep(300);
// reboot with BIOS (最後の手段)
Lfs.WriteStringToFile(@"/proc/sys/kernel/sysrq", "1");
Sleep(300);
Lfs.WriteStringToFile(@"/proc/sysrq-trigger", "b");
}
else
{
throw new CoresException("Already rebooting");
}
}
else
{
throw new NotImplementedException();
}
}
public static bool UnixTryRunSystemProgram(EnsureInternal yes, string commandName, string args, int timeout = Timeout.Infinite)
{
string[] dirs = { "/sbin/", "/bin/", "/usr/bin/", "/usr/local/bin/", "/usr/local/sbin/", "/usr/local/bin/" };
foreach (string dir in dirs)
{
if (UnixTryRunProgramInternal(yes, Path.Combine(dir, commandName), args, timeout))
{
return true;
}
}
return false;
}
public static bool UnixTryRunProgramInternal(EnsureInternal yes, string exe, string args, int timeout = Timeout.Infinite)
{
if (exe._IsEmpty()) throw new ArgumentNullException(nameof(exe));
args = args._NonNull();
try
{
ProcessStartInfo info = new ProcessStartInfo()
{
FileName = exe,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false,
CreateNoWindow = true,
WorkingDirectory = Env.AppRootDir,
};
using (Process p = Process.Start(info)!)
{
return p.WaitForExit(timeout);
}
}
catch (Exception ex)
{
ex._Debug();
}
return false;
}
}
// 子プロセスの実行パラメータのフラグ
[Flags]
public enum ExecFlags
{
None = 0,
KillProcessGroup = 1, // Kill する場合はプロセスグループを Kill する
EasyInputOutputMode = 2, // 標準出力およびエラー出力の結果を簡易的に受信し、標準入力の結果を簡易的に送信する (結果を確認しながらの対話はできない)
EasyPrintRealtimeStdOut = 4, // stdout データをリアルタイムで表示する
EasyPrintRealtimeStdErr = 8, // stderr データをリアルタイムで表示する
UnixAutoFullPath = 16, // UNIX 用コマンドで自動フルパス解決をする
Default = KillProcessGroup | ExecFlags.EasyInputOutputMode | UnixAutoFullPath,
}
// 簡易実行
public static class EasyExec
{
public static async Task<EasyExecResult> ExecBashAsync(string command, string? currentDirectory = null,
ExecFlags flags = ExecFlags.Default | ExecFlags.EasyInputOutputMode,
int easyOutputMaxSize = Consts.Numbers.DefaultLargeBufferSize, string? easyInputStr = null, int? timeout = null,
CancellationToken cancel = default, bool debug = false, bool throwOnErrorExitCode = true,
string printTag = "")
{
if (timeout <= 0) timeout = Timeout.Infinite;
List<string> args = new List<string>();
args.Add("-c");
args.Add(command);
ExecOptions opt = new ExecOptions(Lfs.UnixGetFullPathFromCommandName(Consts.LinuxCommands.Bash), args, currentDirectory, flags, easyOutputMaxSize, easyInputStr, printTag);
if (debug)
{
Dbg.WriteLine($"ExecBashAsync: --- Starting bash command \"{command}\" ---");
}
EasyExecResult result;
try
{
using ExecInstance exec = new ExecInstance(opt);
try
{
await exec.WaitForExitAsync(timeout._NormalizeTimeout(CoresConfig.Timeouts.DefaultEasyExecTimeout), cancel);
}
finally
{
await exec.CancelAsync();
}
result = new EasyExecResult(exec);
}
catch (Exception ex)
{
Dbg.WriteLine($"Error on bash process \"{command}\". Exception: {ex.Message}");
throw;
}
if (debug)
{
Dbg.WriteLine($"ExecAsync: The result of bash \"{command}\": " + result.ToString(Str.GetCrlfStr(), false));
}
if (throwOnErrorExitCode)
{
result.ThrowExceptionIfError();
}
return result;
}
public static async Task<EasyExecResult> ExecAsync(string cmdName, string? arguments = null, string? currentDirectory = null,
ExecFlags flags = ExecFlags.Default | ExecFlags.EasyInputOutputMode,
int easyOutputMaxSize = Consts.Numbers.DefaultLargeBufferSize, string? easyInputStr = null, int? timeout = null,
CancellationToken cancel = default, bool debug = false, bool throwOnErrorExitCode = true, string printTag = "")
{
if (timeout <= 0) timeout = Timeout.Infinite;
ExecOptions opt = new ExecOptions(cmdName, arguments, currentDirectory, flags, easyOutputMaxSize, easyInputStr, printTag);
if (debug)
{
Dbg.WriteLine($"ExecAsync: --- Starting process \"{cmdName}{(arguments._IsFilled() ? " " : "")}{arguments}\" ---");
}
EasyExecResult result;
try
{
using ExecInstance exec = new ExecInstance(opt);
try
{
await exec.WaitForExitAsync(timeout._NormalizeTimeout(CoresConfig.Timeouts.DefaultEasyExecTimeout), cancel);
}
finally
{
await exec.CancelAsync();
}
result = new EasyExecResult(exec);
}
catch (Exception ex)
{
Dbg.WriteLine($"Error on starting process \"{cmdName}{(arguments._IsFilled() ? " " : "")}{arguments}\". Exception: {ex.Message}");
throw;
}
if (debug)
{
Dbg.WriteLine($"ExecAsync: The result of process \"{cmdName}{(arguments._IsFilled() ? " " : "")}{arguments}\": " + result.ToString(Str.GetCrlfStr(), false));
}
if (throwOnErrorExitCode)
{
result.ThrowExceptionIfError();
}
return result;
}
}
public class CoresEasyExecException : CoresException
{
public CoresEasyExecException(EasyExecResult result)
: base(result.ToString())
{
}
}
// 簡易実行の結果
public class EasyExecResult
{
public int ExitCode => Instance.ExitCode;
public bool IsOk => (ExitCode == 0);
public int ProcessId => Instance.ProcessId;
public string OutputStr { get; }
public string ErrorStr { get; }
ReadOnlyMemory<byte> OutputData => Instance.EasyOutputData;
ReadOnlyMemory<byte> ErrorData => Instance.EasyErrorData;
public string OutputAndErrorStr { get; }
public string ErrorAndOutputStr { get; }
public long TookTime => Instance.TookTime;
public bool IsTimeouted => Instance.IsTimeouted;
public ExecInstance Instance { get; }
public EasyExecResult(ExecInstance exec)
{
this.Instance = exec;
this.OutputStr = exec.EasyOutputStr._NonNull()._NormalizeCrlf(true);
this.ErrorStr = exec.EasyErrorStr._NonNull()._NormalizeCrlf(true);
this.OutputAndErrorStr = this.OutputStr + this.ErrorStr;
this.ErrorAndOutputStr = this.ErrorStr + this.OutputStr;
}
public Exception? GetExceptionIfError()
{
if (this.IsOk) return null;
return new CoresEasyExecException(this);
}
public void ThrowExceptionIfError()
{
Exception? ex = GetExceptionIfError();
if (ex != null) throw ex;
}
public override string ToString()
=> ToString(", ", true);
public string ToString(string separator, bool oneLine)
{
List<string> w = new List<string>();
string argsStr;
if (Instance.Options.ArgumentsList != null)
{
argsStr = Instance.Options.ArgumentsList._Combine(" ");
}
else
{
argsStr = Instance.Options.Arguments;
}
w.Add($"Command: \"{Instance.Options.FileName}{(argsStr._IsFilled() ? " " : "")}{argsStr}\"");
if (Instance.ExitCode == 0)
{
w.Add($"Result: OK (Exit code = 0)");
}
else
{
if (this.IsTimeouted == false)
{
w.Add($"Result: Error (Exit code = {ExitCode})");
}
else
{
w.Add($"Result: Timeout Error");
}
}
w.Add($"Took time: {TookTime._ToString3()}");
w.Add($"Process Id: {ProcessId}");
string errorStr = oneLine ? this.ErrorStr._OneLine(" / ") : this.ErrorStr;
string outputStr = oneLine ? this.OutputStr._OneLine(" / ") : this.OutputStr;
if (this.ErrorStr._IsFilled()) w.Add($"ErrorStr: \"{errorStr.Trim()}\"");
if (this.OutputStr._IsFilled()) w.Add($"OutputStr: \"{outputStr.Trim()}\"");
return w._Combine(separator);
}
}
// 子プロセスの実行パラメータ
public class ExecOptions
{
public string CommandName { get; }
public string FileName { get; }
public string Arguments { get; }
public IEnumerable<string>? ArgumentsList { get; }
public string CurrentDirectory { get; }
public ExecFlags Flags { get; }
public int EasyOutputMaxSize { get; }
public string? EasyInputStr { get; }
public string PrintTag { get; }
public ExecOptions(string commandName, string? arguments = null, string? currentDirectory = null, ExecFlags flags = ExecFlags.Default,
int easyOutputMaxSize = Consts.Numbers.DefaultLargeBufferSize, string? easyInputStr = null, string printTag = "")
{
this.CommandName = commandName._NullCheck();
if (Env.IsUnix == false || flags.Bit(ExecFlags.UnixAutoFullPath) == false)
{
this.FileName = this.CommandName._NullCheck();
}
else
{
try
{
this.FileName = Lfs.UnixGetFullPathFromCommandName(this.CommandName._NullCheck());
}
catch
{
this.FileName = this.CommandName._NullCheck();
}
}
this.Arguments = arguments._NonNull();
this.ArgumentsList = null;
this.CurrentDirectory = currentDirectory._NonNull();
this.Flags = flags;
this.EasyOutputMaxSize = easyOutputMaxSize._Max(1);
this.EasyInputStr = easyInputStr._NullIfZeroLen();
this.PrintTag = printTag;
}
public ExecOptions(string commandName, IEnumerable<string> argumentsList, string? currentDirectory = null, ExecFlags flags = ExecFlags.Default,
int easyOutputMaxSize = Consts.Numbers.DefaultLargeBufferSize, string? easyInputStr = null, string printTag = "")
{
this.CommandName = commandName._NullCheck();
if (Env.IsUnix == false || flags.Bit(ExecFlags.UnixAutoFullPath) == false)
{
this.FileName = this.CommandName._NullCheck();
}
else
{
try
{
this.FileName = Lfs.UnixGetFullPathFromCommandName(this.CommandName._NullCheck());
}
catch
{
this.FileName = this.CommandName._NullCheck();
}
}
this.Arguments = "";
this.ArgumentsList = argumentsList;
this.CurrentDirectory = currentDirectory._NonNull();
this.Flags = flags;
this.EasyOutputMaxSize = easyOutputMaxSize._Max(1);
this.EasyInputStr = easyInputStr._NullIfZeroLen();
this.PrintTag = printTag;
}
}
// 実行中および実行後の子プロセスのインスタンス
public class ExecInstance : AsyncServiceWithMainLoop
{
public ExecOptions Options { get; }
public AsyncManualResetEvent ExitEvent { get; } = new AsyncManualResetEvent();
public Encoding InputEncoding { get; }
public Encoding OutputEncoding { get; }
public Encoding ErrorEncoding { get; }
PipePoint StandardPipePoint_MySide;
PipePointStreamWrapper StandardPipeWrapper;
PipePoint _InputOutputPipePoint;
PipePoint ErrorPipePoint_MySide;
PipePointStreamWrapper ErrorPipeWrapper;
PipePoint _ErrorPipePoint;
volatile bool EasyOutputAndErrorDataCompleted = false;
Memory<byte> _EasyOutputData;
Memory<byte> _EasyErrorData;
public PipePoint InputOutputPipePoint
{
get
{
if (this.Options.Flags.Bit(ExecFlags.EasyInputOutputMode)) throw new NotSupportedException();
return _InputOutputPipePoint;
}
}
public PipePoint ErrorPipePoint
{
get
{
if (this.Options.Flags.Bit(ExecFlags.EasyInputOutputMode)) throw new NotSupportedException();
return _ErrorPipePoint;
}
}
public ReadOnlyMemory<byte> EasyOutputData
{
get
{
if (this.Options.Flags.Bit(ExecFlags.EasyInputOutputMode) == false) throw new NotSupportedException();
if (EasyOutputAndErrorDataCompleted == false) throw new CoresException("The result string is not received yet.");
return _EasyOutputData;
}
}
public ReadOnlyMemory<byte> EasyErrorData
{
get
{
if (this.Options.Flags.Bit(ExecFlags.EasyInputOutputMode) == false) throw new NotSupportedException();
if (EasyOutputAndErrorDataCompleted == false) throw new CoresException("The result string is not received yet.");
return _EasyErrorData;
}
}
string? _EasyOutputStr = null;
public string EasyOutputStr
{
get
{
if (_EasyOutputStr == null)
{
_EasyOutputStr = EasyOutputData._GetString(this.OutputEncoding);
}
return _EasyOutputStr;
}
}
string? _EasyErrorStr = null;
public string EasyErrorStr
{
get
{
if (_EasyErrorStr == null)
{
_EasyErrorStr = EasyErrorData._GetString(this.ErrorEncoding);
}
return _EasyErrorStr;
}
}
int? _ExitCode = null;
public int ExitCode
{
get
{
return _ExitCode ?? throw new CoresException("Process is still running.");
}
}
public int ProcessId { get; private set; }
readonly Process Proc;
readonly Task? EasyInputTask = null;
readonly Task<Memory<byte>>? EasyOutputTask = null;
readonly Task<Memory<byte>>? EasyErrorTask = null;
readonly NetAppStub? EasyInputOutputStub = null;
readonly PipeStream? EasyInputOutputStream = null;
readonly NetAppStub? EasyErrorStub = null;
readonly PipeStream? EasyErrorStream = null;
public long StartTick { get; }
public long EndTick { get; private set; }
public bool IsTimeouted
{
get
{
if (_ExitCode == null) return false;
if ((_ExitCode ?? 0) == 0) return false;
return _TimeoutedFlag;
}
}
bool _TimeoutedFlag = false;
public long TookTime
{
get
{
if (StartTick == 0 || EndTick == 0) return 0;
return EndTick - StartTick;
}
}
public ExecInstance(ExecOptions options)
{
try
{
this.InputEncoding = Console.OutputEncoding;
this.OutputEncoding = this.ErrorEncoding = Console.InputEncoding;
this.Options = options._NullCheck();
ProcessStartInfo info = new ProcessStartInfo()
{
FileName = options.FileName,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true,
WorkingDirectory = options.CurrentDirectory._NullIfEmpty()!,
};
if (options.ArgumentsList != null)
{
options.ArgumentsList._DoForEach(a => info.ArgumentList.Add(a._NonNull()));
}
else
{
info.Arguments = options.Arguments._NullIfZeroLen()!;
}
StartTick = Time.HighResTick64;
Proc = Process.Start(info)!;
Proc._FixProcessObjectHandleLeak(); // メモリリーク解消
this.ProcessId = Proc.Id;
// 標準入出力を接続する
this.StandardPipePoint_MySide = PipePoint.NewDuplexPipeAndGetOneSide(PipePointSide.A_LowerSide);
this._InputOutputPipePoint = this.StandardPipePoint_MySide.CounterPart._NullCheck();
this.StandardPipeWrapper = new PipePointStreamWrapper(StandardPipePoint_MySide, Proc.StandardOutput.BaseStream, Proc.StandardInput.BaseStream);
// 標準エラー出力を接続する
this.ErrorPipePoint_MySide = PipePoint.NewDuplexPipeAndGetOneSide(PipePointSide.A_LowerSide);
this._ErrorPipePoint = this.ErrorPipePoint_MySide.CounterPart._NullCheck();
this.ErrorPipeWrapper = new PipePointStreamWrapper(ErrorPipePoint_MySide, Proc.StandardError.BaseStream, Stream.Null);
if (options.Flags.Bit(ExecFlags.EasyInputOutputMode))
{
this.EasyInputOutputStub = this._InputOutputPipePoint.GetNetAppProtocolStub(noCheckDisconnected: true);
this.EasyInputOutputStream = this.EasyInputOutputStub.GetStream();
this.EasyErrorStub = this._ErrorPipePoint.GetNetAppProtocolStub(noCheckDisconnected: true);
this.EasyErrorStream = this.EasyErrorStub.GetStream();
if (options.EasyInputStr != null)
{
// 標準入力の注入タスク
this.EasyInputTask = this.EasyInputOutputStream.SendAsync(this.Options.EasyInputStr!._GetBytes(this.InputEncoding), this.GrandCancel)._LeakCheck();
}
// 標準出力の読み出しタスク
this.EasyOutputTask = this.EasyInputOutputStream._ReadWithMaxBufferSizeAsync(this.Options.EasyOutputMaxSize, this.GrandCancel,
async (data, cancel) => await EasyPrintRealTimeRecvDataCallbackAsync(data, false, cancel))._LeakCheck();
// 標準エラー出力の読み出しタスク
this.EasyErrorTask = this.EasyErrorStream._ReadWithMaxBufferSizeAsync(this.Options.EasyOutputMaxSize, this.GrandCancel,
async (data, cancel) => await EasyPrintRealTimeRecvDataCallbackAsync(data, true, cancel))._LeakCheck();
}
this.StartMainLoop(MainLoopAsync);
}
catch
{
this._DisposeSafe();
throw;
}
}
PipeStreamPairWithSubTask? EasyRealTimeStdOut = null;
PipeStreamPairWithSubTask? EasyRealTimeStdErr = null;
// リアルタイムでデータが届いたときに呼ばれるコールバック関数
Task EasyPrintRealTimeRecvDataCallbackAsync(ReadOnlyMemory<byte> data, bool stderr, CancellationToken cancel)
{
PipeStreamPairWithSubTask? pair = null;
if (stderr == false)
{
if (this.Options.Flags.Bit(ExecFlags.EasyPrintRealtimeStdOut))
{
pair = (this.EasyRealTimeStdErr ??= new PipeStreamPairWithSubTask(EasyPrintRealTimeRecvDataPrintCallbackAsync));
}
}
else
{
if (this.Options.Flags.Bit(ExecFlags.EasyPrintRealtimeStdErr))
{
pair = (this.EasyRealTimeStdOut ??= new PipeStreamPairWithSubTask(EasyPrintRealTimeRecvDataPrintCallbackAsync));
}
}
if (pair != null)
{
if (pair.StreamA.IsReadyToSend())
{
pair.StreamA.FastSendNonBlock(data._CloneMemory(), true);
}
}
return TaskCompleted;
}
readonly AsyncLock WriteLineLocker = new AsyncLock();
async Task EasyPrintRealTimeRecvDataPrintCallbackAsync(PipeStream st)
{
var r = new BinaryLineReader(st);
while (true)
{
List<Tuple<Memory<byte>, bool>>? lines = await r.ReadLinesWithTimeoutAsync(1000);
if (lines == null)
{
break;
}
foreach (var line in lines)
{
string tagStr = "";
if (this.Options.PrintTag._IsFilled()) tagStr = $"{this.Options.PrintTag}: ";
string str = tagStr + line.Item1._GetString(this.OutputEncoding);
if (line.Item2 == false)
{
str += " [...!!pending!!...]";
}
using (await WriteLineLocker.LockWithAwait())
{
Con.WriteLine(str);
}
}
}
}
async Task MainLoopAsync(CancellationToken cancel)
{
await Task.Yield();
try
{
// 終了するまで待機する (Cancel された場合は Kill されるので以下の待機は自動的に解除される)
Proc.WaitForExit();
if (this.EndTick == 0) this.EndTick = Time.HighResTick64;
}
catch (Exception ex)
{
if (this.EndTick == 0) this.EndTick = Time.HighResTick64;
ex._Debug();
throw;
}
finally
{
if (this.EndTick == 0) this.EndTick = Time.HighResTick64;
// 終了した or 待機に失敗した
// 戻り値をセットする
try
{
_ExitCode = Proc.ExitCode;
}
catch
{
_ExitCode = -1;
}
if (this.EasyInputTask != null)
{
await this.EasyInputTask._TryAwait();
}
try
{
if (this.EasyOutputTask != null)
{
this._EasyOutputData = await this.EasyOutputTask;
}
if (this.EasyErrorTask != null)
{
this._EasyErrorData = await this.EasyErrorTask;
}
}
catch (Exception ex)
{
ex._Debug();
}
EasyOutputAndErrorDataCompleted = true;
Interlocked.MemoryBarrier();
// 完了フラグを立てる
ExitEvent.Set(true);
}
}
// 終了まで待機する
public async Task<int> WaitForExitAsync(int timeout = Timeout.Infinite, CancellationToken cancel = default)
{
await ExitEvent.WaitAsync(timeout, cancel);
return this._ExitCode ?? -1;
}
public int WaitForExit(int timeout = Timeout.Infinite, CancellationToken cancel = default)
=> WaitForExitAsync(timeout, cancel)._GetResult();
protected override async Task CancelImplAsync(Exception? ex)
{
try
{
if (Proc != null)
{
if (Proc.HasExited == false)
{
try
{
#if !NETSTANDARD
Proc.Kill(Options.Flags.Bit(ExecFlags.KillProcessGroup));
#else
Proc.Kill();
#endif
_TimeoutedFlag = true;
}
catch
{
}
}
}
}
finally
{
await base.CancelImplAsync(ex);
}
}
protected override async Task CleanupImplAsync(Exception? ex)
{
try
{
await this.EasyInputOutputStub._DisposeSafeAsync();
await this.EasyInputOutputStream._DisposeSafeAsync();
await this.EasyErrorStub._DisposeSafeAsync();
await this.EasyErrorStream._DisposeSafeAsync();
await this.StandardPipeWrapper._DisposeSafeAsync();
await this.ErrorPipeWrapper._DisposeSafeAsync();
await this.StandardPipePoint_MySide._DisposeSafeAsync();
await this.ErrorPipePoint_MySide._DisposeSafeAsync();
await this.EasyRealTimeStdOut._DisposeSafeAsync();
await this.EasyRealTimeStdErr._DisposeSafeAsync();
}
finally
{
await base.CleanupImplAsync(ex);
}
}
}
namespace Legacy
{
// 子プロセスの起動・制御用クラス
public class ChildProcess
{
string stdout = "", stderr = "";
int exitcode = -1;
int timeout;
Event? timeout_thread_event = null;
Process proc;
bool finished = false;
bool killed = false;
void timeout_thread(object? param)
{
this.timeout_thread_event!.Wait(this.timeout);
if (finished == false)
{
try
{
proc.Kill();
killed = true;
}
catch
{
}
}
}
public string StdOut => stdout;
public string StdErr => stderr;
public int ExitCode => exitcode;
public bool TimeoutKilled => killed;
public bool IsOk => exitcode == 0;
public bool IsError => !IsOk;
public ChildProcess(string exe, string args = "", string input = "", bool throwExceptionOnExitError = false, int timeout = ThreadObj.Infinite)
{
this.timeout = timeout;
Str.NormalizeString(ref args);
ProcessStartInfo info = new ProcessStartInfo()
{
FileName = IO.InnerFilePath(exe),
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = !Str.IsEmptyStr(input),
};
ThreadObj? t = null;
using (Process p = Process.Start(info)!)
{
this.proc = p;
if (timeout != ThreadObj.Infinite)
{
timeout_thread_event = new Event();
t = new ThreadObj(timeout_thread);
}
if (Str.IsEmptyStr(input) == false)
{
p.StandardInput.Write(input);
p.StandardInput.Flush();
p.StandardInput.Close();
}
stdout = p.StandardOutput.ReadToEnd();
stderr = p.StandardError.ReadToEnd();
p.WaitForExit();
finished = true;
if (timeout_thread_event != null)
{
timeout_thread_event.Set();
}
if (t != null) t.WaitForEnd();
if (killed)
{
if (Str.IsEmptyStr(stderr))
{
stderr = $"Process run timeout ({timeout._ToString3()} msecs).";
}
}
exitcode = p.ExitCode;
if (throwExceptionOnExitError)
{
if (exitcode != 0)
{
throw new ApplicationException($"ChildProcess: '{exe}': exitcode = {exitcode}, errorstr = {stderr._OneLine()}");
}
}
}
}
}
}
}
|
Subsets and Splits