content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PropertyDependencyFramework;
namespace WPFSample.DemonstrationShowcases
{
class SimplePropertyDependencyOldSqlVM : BindableExt
{
private int _d1;
public int D1
{
get { return _d1; }
set
{
_d1 = value;
NotifyPropertyChanged(() => D1);
RecalculateEverything();
}
}
private int _d2;
public int D2
{
get { return _d2; }
set
{
_d2 = value;
NotifyPropertyChanged(() => D2);
RecalculateEverything();
}
}
private int _d3;
public int D3
{
get { return _d3; }
set
{
_d3 = value;
NotifyPropertyChanged(() => D3);
RecalculateEverything();
}
}
private int _d4;
public int D4
{
get { return _d4; }
set
{
_d4 = value;
NotifyPropertyChanged(() => D4);
RecalculateEverything();
}
}
private int _d5;
public int D5
{
get { return _d5; }
set
{
_d5 = value;
NotifyPropertyChanged(() => D5);
RecalculateEverything();
}
}
private int _c1;
public int C1
{
get { return _c1; }
set { _c1 = value; NotifyPropertyChanged(() => C1); }
}
private int _c2;
public int C2
{
get { return _c2; }
set { _c2 = value; NotifyPropertyChanged(() => C2); }
}
private int _c3;
public int C3
{
get { return _c3; }
set { _c3 = value; NotifyPropertyChanged(() => C3); }
}
private int _b1;
public int B1
{
get { return _b1; }
set { _b1 = value; NotifyPropertyChanged(() => B1); }
}
private int _b2;
public int B2
{
get { return _b2; }
set { _b2 = value; NotifyPropertyChanged(() => B2); }
}
private int _a1;
public int A1
{
get { return _a1; }
set { _a1 = value; NotifyPropertyChanged(() => A1); }
}
void RecalculateEverything()
{
C1 = D1 + D2;
C2 = 3*D3;
C3 = D4 + D5;
B1 = 2*C1 - C2;
B2 = C3 - C2;
A1 = B1 + B2;
}
public override string ToString()
{
return "Simple Property Dependency OLD SQL Demonstration";
}
}
}
| 16.046154 | 61 | 0.588686 | [
"MIT"
] | interknowlogy/pdfx | Samples/WPFSample/WPFSample/DemonstrationShowcases/SimplePropertyDependencyOldSqlVM.cs | 2,088 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BeeHive.DataStructures;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;
namespace ConveyorBelt.Tooling
{
public static class IBlobExtensions
{
public static IEnumerable<DynamicTableEntity> FromIisLogsToEntities(this IBlob blob)
{
var reader = new StreamReader(blob.Body);
string line = null;
string[] fields = null;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("#Fields: "))
fields = BuildFields(line);
if (line.StartsWith("#"))
continue;
var idSegments = blob.Id.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
var entries = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var datetime = string.Join(" ", entries.Take(2));
var rest = entries.Skip(2).ToArray();
var entity = new DynamicTableEntity();
entity.Timestamp = DateTimeOffset.Parse(datetime);
entity.PartitionKey = string.Join("_", idSegments.Take(idSegments.Length-1));
entity.RowKey = string.Format("{0}_{1:yyyyMMddHHmmss}_{2}",
Path.GetFileNameWithoutExtension(idSegments.Last()),
entity.Timestamp,
Guid.NewGuid().ToString("N"));
if (fields.Length != rest.Length)
throw new InvalidOperationException("fields not equal");
for (int i = 0; i < fields.Length; i++)
{
string name = fields[i];
string value = rest[i];
if (Regex.IsMatch(value, @"^[1-9]\d*$")) // numeric
entity.Properties.Add(name, new EntityProperty(Convert.ToInt64(value)));
else
entity.Properties.Add(name, new EntityProperty(value));
}
yield return entity;
}
}
private static string[] BuildFields(string line)
{
line = line.Replace("#Fields: ", "");
if (!line.StartsWith("date time "))
throw new InvalidDataException("Does not contain date time as the first fields.");
line = line.Replace("date time ", "");
line = line.Replace(")", "");
line = line.Replace("(", "_");
return line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| 37.04 | 99 | 0.542477 | [
"MIT"
] | nojlkobhuk/conveyorbelt | src/ConveyorBelt.Tooling/IBlobExtensions.cs | 2,780 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LinkedDataBrowser.Models.Extensions
{
public static class ListExtension
{
/// <summary>
/// Get shorter list, keep only selected subset of elements
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="count">Maximum count of the elements to keep</param>
/// <param name="n">Order of the subset to keep in the list</param>
/// <param name="indexOfSubset"> Index in the original array where the subset starts</param>
/// <returns></returns>
public static List<T> GetNthSubset<T>(this List<T> originalList, int count, int n, out int indexOfSubset)
{
indexOfSubset = -1;
if (n < 1) throw new ArgumentException("Order of subset must be at least 1 ");
if (count < 0) throw new ArgumentException("Cannot select negative number of elements ");
else if (count == 0) return new List<T>();
if (originalList.Count == 0) return null;
int startIndex = (n - 1) * count;
if (startIndex >= originalList.Count)
return null;
indexOfSubset = startIndex;
int tillEnd = originalList.Count - startIndex;
int newCount = (tillEnd < count) ? tillEnd : count;
return originalList.GetRange(startIndex, newCount);
}
}
}
| 40.513514 | 113 | 0.611074 | [
"MIT"
] | EvkaS/GofriBrowser | LinkedDataBrowser/Models/Extensions/ListExtension.cs | 1,501 | C# |
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2016 Dominik Reichl <dominik.reichl@t-online.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
namespace KeePass.UI
{
public sealed class DynamicMenuEventArgs : EventArgs
{
private string m_strItemName = string.Empty;
private object m_objTag = null;
public string ItemName
{
get { return m_strItemName; }
}
public object Tag
{
get { return m_objTag; }
}
public DynamicMenuEventArgs(string strItemName, object objTag)
{
Debug.Assert(strItemName != null);
if(strItemName == null) throw new ArgumentNullException("strItemName");
m_strItemName = strItemName;
m_objTag = objTag;
}
}
public sealed class DynamicMenu
{
private ToolStripItemCollection m_tsicHost;
private List<ToolStripItem> m_vMenuItems = new List<ToolStripItem>();
public event EventHandler<DynamicMenuEventArgs> MenuClick;
// Constructor required by plugins
public DynamicMenu(ToolStripDropDownItem tsmiHost)
{
Debug.Assert(tsmiHost != null);
if(tsmiHost == null) throw new ArgumentNullException("tsmiHost");
m_tsicHost = tsmiHost.DropDownItems;
}
public DynamicMenu(ToolStripItemCollection tsicHost)
{
Debug.Assert(tsicHost != null);
if(tsicHost == null) throw new ArgumentNullException("tsicHost");
m_tsicHost = tsicHost;
}
~DynamicMenu()
{
Clear();
}
public void Clear()
{
for(int i = 0; i < m_vMenuItems.Count; ++i)
{
ToolStripItem tsi = m_vMenuItems[m_vMenuItems.Count - i - 1];
if(tsi is ToolStripMenuItem)
tsi.Click -= this.OnMenuClick;
m_tsicHost.Remove(tsi);
}
m_vMenuItems.Clear();
}
public ToolStripMenuItem AddItem(string strItemText, Image imgSmallIcon)
{
return AddItem(strItemText, imgSmallIcon, null);
}
public ToolStripMenuItem AddItem(string strItemText, Image imgSmallIcon,
object objTag)
{
Debug.Assert(strItemText != null);
if(strItemText == null) throw new ArgumentNullException("strItemText");
ToolStripMenuItem tsmi = new ToolStripMenuItem(strItemText);
tsmi.Click += this.OnMenuClick;
tsmi.Tag = objTag;
if(imgSmallIcon != null) tsmi.Image = imgSmallIcon;
m_tsicHost.Add(tsmi);
m_vMenuItems.Add(tsmi);
return tsmi;
}
public void AddSeparator()
{
ToolStripSeparator sep = new ToolStripSeparator();
m_tsicHost.Add(sep);
m_vMenuItems.Add(sep);
}
private void OnMenuClick(object sender, EventArgs e)
{
ToolStripItem tsi = (sender as ToolStripItem);
Debug.Assert(tsi != null); if(tsi == null) return;
string strText = tsi.Text;
Debug.Assert(strText != null); if(strText == null) return;
DynamicMenuEventArgs args = new DynamicMenuEventArgs(strText, tsi.Tag);
if(this.MenuClick != null) this.MenuClick(sender, args);
}
}
}
| 25.892857 | 76 | 0.724966 | [
"BSD-3-Clause"
] | FDlucifer/KeeThief | KeePass-2.34-Source-Patched/KeePass/UI/DynamicMenu.cs | 3,625 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1_TwoSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("1_TwoSum")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4e931a02-aca7-4cc5-a39d-c7b681fd709e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.405405 | 84 | 0.746387 | [
"MIT"
] | Gemnnn/LeetCode | 1_TwoSum/1_TwoSum/Properties/AssemblyInfo.cs | 1,387 | C# |
using Integrator.Models.ViewModels.CurriculumVitaes;
using Integrator.Models.ViewModels.Users;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Integrator.Factories.CurriculumVitae
{
public partial interface ICurriculumVitaeViewModelFactory
{
CurriculumVitaeViewModel PerpareCurriculumVitaeViewModel(CurriculumVitaeViewModel model, Boolean DisplayFullCurriculumVitae);
EditUserCurriculumViteaWorkExperienceViewModel prepareEditCurriuclumVitaeWorkExperiences();
EditUserCurriculumViteaWorkExperienceViewModel prepareEditSingleCurriuclumVitaeWorkExperiences(int UserJobID);
//EditUserCurriculumViteaWorkExperienceViewModel
EditUserQualificationViewModel prepareEditCurriuclumVitaeQualifications();
EditUserInterestViewModel prepareEditCurriculumVitaeInterests();
EditUserLanguageViewModel PrepareEditCurriculumVitaeLanguages();
EditUserAwardViewModel PrepareEditCurriculumVitaeAwards();
EditUserPictureViewModel PrepareEditCurriculumViteaPictures();
// EditUserCurriculumVitaePictureViewModel
}
}
| 35.030303 | 133 | 0.82699 | [
"Apache-2.0"
] | Speedie007/Intergrator | Integrator.Web/Integrator.Factories/CurriculumVitae/ICurriculumVitaeViewModelFactory.cs | 1,158 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lakeformation-2017-03-31.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.LakeFormation
{
/// <summary>
/// Configuration for accessing Amazon LakeFormation service
/// </summary>
public partial class AmazonLakeFormationConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.7.0.17");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonLakeFormationConfig()
{
this.AuthenticationServiceName = "lakeformation";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "lakeformation";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2017-03-31";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.4125 | 111 | 0.592522 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/LakeFormation/Generated/AmazonLakeFormationConfig.cs | 2,113 | C# |
using System;
// ReSharper disable InconsistentNaming
namespace NetworkSkins
{
public static class BuildingAiRenderMeshesPatch
{
public static bool Prefix(BuildingAI __instance, RenderManager.CameraInfo cameraInfo, ushort buildingID, ref Building data, int layerMask, ref RenderManager.Instance instance)
{
__instance.m_info.m_rendered = true;
if (__instance.m_info.m_mesh != null)
{
BuildingAI.RenderMesh(cameraInfo, buildingID, ref data, __instance.m_info, ref instance);
}
if (__instance.m_info.m_subMeshes != null)
{
for (int i = 0; i < __instance.m_info.m_subMeshes.Length; i++)
{
BuildingInfo.MeshInfo meshInfo = __instance.m_info.m_subMeshes[i];
if (((meshInfo.m_flagsRequired | meshInfo.m_flagsForbidden) & data.m_flags) == meshInfo.m_flagsRequired)
{
BuildingInfoSub buildingInfoSub = meshInfo.m_subInfo as BuildingInfoSub;
buildingInfoSub.m_rendered = true;
if (buildingInfoSub.m_subMeshes != null && buildingInfoSub.m_subMeshes.Length != 0)
{
for (int j = 0; j < buildingInfoSub.m_subMeshes.Length; j++)
{
BuildingInfo.MeshInfo meshInfo2 = buildingInfoSub.m_subMeshes[j];
if (((meshInfo2.m_flagsRequired | meshInfo2.m_flagsForbidden) & data.m_flags) == meshInfo2.m_flagsRequired)
{
BuildingInfoSub buildingInfoSub2 = meshInfo2.m_subInfo as BuildingInfoSub;
buildingInfoSub2.m_rendered = true;
BuildingAI.RenderMesh(cameraInfo, __instance.m_info, buildingInfoSub2, meshInfo.m_matrix, ref instance);
}
}
}
else
{
BuildingAI.RenderMesh(cameraInfo, __instance.m_info, buildingInfoSub, meshInfo.m_matrix, ref instance);
}
}
}
}
return false;
}
}
}
| 48.428571 | 183 | 0.521281 | [
"MIT"
] | simog6/NetworkSkins2 | NetworkSkins/BuildingAiRenderMeshesPatch.cs | 2,375 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using LogCast.Engine;
using NUnit.Framework;
namespace LogCast.NLog.Test.LogCastTarget.given_nlog_configuration.and_context_id_enabled
{
public class when_logging_two_times : Context
{
private LogCastDocument _lastLog;
private const string SecondTestMessage = "Another data";
public override void Act()
{
Logger.Warn(TestMessage);
Logger.Error(SecondTestMessage);
Complete();
_lastLog = ClientMock.LastLog;
}
[Test]
public void then_higher_log_severity_is_picked_out_of_merge()
{
_lastLog.GetProperty<string>(Property.LogLevel)
.Should().Be("Error",
"Merge should have replaced accumulated value of the second log call with higher severity");
}
[Test]
public void then_durations_total_is_populated()
{
ClientMock.LastLog
.GetProperty<int>(Property.Durations.Name, Property.Durations.Total)
.Should().BeGreaterOrEqualTo(0);
}
[Test]
public void then_durations_is_populated()
{
_lastLog.GetProperty<IEnumerable<int>>(Property.Durations.Name, Property.DefaultChildName)
.Count().Should().Be(3);
}
[Test]
public void then_total_is_greater_or_equal_to_durations()
{
var durations = _lastLog.GetProperty<IEnumerable<int>>(Property.Durations.Name, Property.DefaultChildName);
var total = _lastLog.GetProperty<int>(Property.Durations.Name, Property.Durations.Total);
total.Should().BeGreaterOrEqualTo(durations.Sum());
}
[Test]
public void then_details_are_concatenated_from_2_messages()
{
_lastLog.GetProperty<string>(Property.Details).Should().NotBeNullOrEmpty();
}
[Test]
public void then_durations_are_populated()
{
_lastLog.GetProperty<IEnumerable<int>>(Property.Durations.Name, Property.DefaultChildName)
.Count().Should().Be(3);
}
}
} | 32.955224 | 119 | 0.629076 | [
"MIT"
] | kbabiy/LogCast | LogCast.NLog.Test/LogCastTarget/given_nlog_configuration/and_context_id_enabled/when_logging_two_times.cs | 2,210 | C# |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace WinGridProxy
{
class ListViewNoFlicker : ListView
{
public ListViewNoFlicker()
{
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}
public class ListViewItemComparer : IComparer<object>
{
// Initialize the variables to default
public int column = 0;
public bool bAscending = true;
// Using the Compare function of IComparer
public int Compare(object x, object y)
{
// Cast the objects to ListViewItems
ListViewItem lvi1 = (ListViewItem)x;
ListViewItem lvi2 = (ListViewItem)y;
// If the column is the string columns
if (column != 2)
{
string lvi1String = lvi1.SubItems[column].ToString();
string lvi2String = lvi2.SubItems[column].ToString();
// Return the normal Compare
if (bAscending)
return String.Compare(lvi1String, lvi2String);
// Return the negated Compare
return -String.Compare(lvi1String, lvi2String);
}
// The column is the Age column
int lvi1Int = ParseListItemString(lvi1.SubItems[column].ToString());
int lvi2Int = ParseListItemString(lvi2.SubItems[column].ToString());
// Return the normal compare.. if x < y then return -1
if (bAscending)
{
if (lvi1Int < lvi2Int)
return -1;
else if (lvi1Int == lvi2Int)
return 0;
return 1;
}
// Return the opposites for descending
if (lvi1Int > lvi2Int)
return -1;
else if (lvi1Int == lvi2Int)
return 0;
return 1;
}
private int ParseListItemString(string x)
{
//ListViewItems are returned like this: "ListViewSubItem: {19}"
int counter = 0;
for (int i = x.Length - 1; i >= 0; i--, counter++)
{
if (x[i] == '{')
break;
}
return Int32.Parse(x.Substring(x.Length - counter, counter - 1));
}
}
}
| 34.880952 | 107 | 0.588168 | [
"BSD-3-Clause"
] | BigManzai/libopenmetaverse | Programs/WinGridProxy/ListViewNoFlicker.cs | 4,397 | C# |
namespace XTB.CustomApiManager.Forms
{
partial class NewResponsePropertyForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewResponsePropertyForm));
this.panel2 = new System.Windows.Forms.Panel();
this.lblCustomizable = new System.Windows.Forms.Label();
this.chkIsCustomizable = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.cdsCustomApiName = new xrmtb.XrmToolBox.Controls.Controls.CDSDataTextBox();
this.label17 = new System.Windows.Forms.Label();
this.pictureBox13 = new System.Windows.Forms.PictureBox();
this.lblTitle = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOk = new System.Windows.Forms.Button();
this.pictureBox4 = new System.Windows.Forms.PictureBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.cboEntities = new xrmtb.XrmToolBox.Controls.EntitiesDropdownControl();
this.label11 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.txtDisplayName = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.cboType = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.txtUniqueName = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtDescription = new System.Windows.Forms.TextBox();
this.ttInfo = new System.Windows.Forms.ToolTip(this.components);
this.label12 = new System.Windows.Forms.Label();
this.cdsCboSolutions = new xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox13)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
this.SuspendLayout();
//
// panel2
//
this.panel2.Controls.Add(this.label12);
this.panel2.Controls.Add(this.cdsCboSolutions);
this.panel2.Controls.Add(this.lblCustomizable);
this.panel2.Controls.Add(this.chkIsCustomizable);
this.panel2.Controls.Add(this.label2);
this.panel2.Controls.Add(this.cdsCustomApiName);
this.panel2.Controls.Add(this.label17);
this.panel2.Controls.Add(this.pictureBox13);
this.panel2.Controls.Add(this.lblTitle);
this.panel2.Controls.Add(this.btnCancel);
this.panel2.Controls.Add(this.btnOk);
this.panel2.Controls.Add(this.pictureBox4);
this.panel2.Controls.Add(this.pictureBox1);
this.panel2.Controls.Add(this.pictureBox3);
this.panel2.Controls.Add(this.cboEntities);
this.panel2.Controls.Add(this.label11);
this.panel2.Controls.Add(this.label10);
this.panel2.Controls.Add(this.txtDisplayName);
this.panel2.Controls.Add(this.label9);
this.panel2.Controls.Add(this.cboType);
this.panel2.Controls.Add(this.label6);
this.panel2.Controls.Add(this.txtUniqueName);
this.panel2.Controls.Add(this.label4);
this.panel2.Controls.Add(this.txtName);
this.panel2.Controls.Add(this.label3);
this.panel2.Controls.Add(this.txtDescription);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(525, 353);
this.panel2.TabIndex = 5;
//
// lblCustomizable
//
this.lblCustomizable.AutoSize = true;
this.lblCustomizable.Location = new System.Drawing.Point(26, 274);
this.lblCustomizable.Name = "lblCustomizable";
this.lblCustomizable.Size = new System.Drawing.Size(77, 13);
this.lblCustomizable.TabIndex = 106;
this.lblCustomizable.Text = "IsCustomizable";
this.ttInfo.SetToolTip(this.lblCustomizable, "Controls whether the Custom API Response Property can be customized or deleted wh" +
"en deployed as managed.");
//
// chkIsCustomizable
//
this.chkIsCustomizable.AutoSize = true;
this.chkIsCustomizable.Location = new System.Drawing.Point(106, 274);
this.chkIsCustomizable.Name = "chkIsCustomizable";
this.chkIsCustomizable.Size = new System.Drawing.Size(15, 14);
this.chkIsCustomizable.TabIndex = 105;
this.chkIsCustomizable.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(27, 46);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(72, 13);
this.label2.TabIndex = 78;
this.label2.Text = "Custom API";
//
// cdsCustomApiName
//
this.cdsCustomApiName.BackColor = System.Drawing.SystemColors.Window;
this.cdsCustomApiName.DisplayFormat = "{{name}} ({{uniquename}})";
this.cdsCustomApiName.Entity = null;
this.cdsCustomApiName.EntityReference = null;
this.cdsCustomApiName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cdsCustomApiName.Id = new System.Guid("00000000-0000-0000-0000-000000000000");
this.cdsCustomApiName.Location = new System.Drawing.Point(106, 43);
this.cdsCustomApiName.LogicalName = "customapi";
this.cdsCustomApiName.Name = "cdsCustomApiName";
this.cdsCustomApiName.OrganizationService = null;
this.cdsCustomApiName.Size = new System.Drawing.Size(317, 20);
this.cdsCustomApiName.TabIndex = 77;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label17.Location = new System.Drawing.Point(303, 16);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(213, 13);
this.label17.TabIndex = 75;
this.label17.Text = "Fields that cannot be modified after creation";
//
// pictureBox13
//
this.pictureBox13.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox13.Image")));
this.pictureBox13.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox13.InitialImage")));
this.pictureBox13.Location = new System.Drawing.Point(286, 13);
this.pictureBox13.Name = "pictureBox13";
this.pictureBox13.Size = new System.Drawing.Size(20, 19);
this.pictureBox13.TabIndex = 74;
this.pictureBox13.TabStop = false;
//
// lblTitle
//
this.lblTitle.AutoSize = true;
this.lblTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTitle.Location = new System.Drawing.Point(19, 11);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(260, 20);
this.lblTitle.TabIndex = 73;
this.lblTitle.Text = "Create New Response Property";
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Image = ((System.Drawing.Image)(resources.GetObject("btnCancel.Image")));
this.btnCancel.Location = new System.Drawing.Point(390, 309);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(78, 32);
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Cancel";
this.btnCancel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnCancel.UseVisualStyleBackColor = true;
//
// btnOk
//
this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOk.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnOk.Image = ((System.Drawing.Image)(resources.GetObject("btnOk.Image")));
this.btnOk.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnOk.Location = new System.Drawing.Point(306, 309);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(78, 32);
this.btnOk.TabIndex = 72;
this.btnOk.Text = "Create";
this.btnOk.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// pictureBox4
//
this.pictureBox4.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox4.Image")));
this.pictureBox4.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox4.InitialImage")));
this.pictureBox4.Location = new System.Drawing.Point(337, 237);
this.pictureBox4.Name = "pictureBox4";
this.pictureBox4.Size = new System.Drawing.Size(20, 19);
this.pictureBox4.TabIndex = 67;
this.pictureBox4.TabStop = false;
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.InitialImage")));
this.pictureBox1.Location = new System.Drawing.Point(317, 211);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(20, 19);
this.pictureBox1.TabIndex = 65;
this.pictureBox1.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox3.Image")));
this.pictureBox3.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox3.InitialImage")));
this.pictureBox3.Location = new System.Drawing.Point(422, 74);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(20, 19);
this.pictureBox3.TabIndex = 64;
this.pictureBox3.TabStop = false;
//
// cboEntities
//
this.cboEntities.AutoLoadData = false;
this.cboEntities.LanguageCode = 1033;
this.cboEntities.Location = new System.Drawing.Point(127, 233);
this.cboEntities.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.cboEntities.Name = "cboEntities";
this.cboEntities.Service = null;
this.cboEntities.Size = new System.Drawing.Size(215, 25);
this.cboEntities.SolutionFilter = null;
this.cboEntities.TabIndex = 63;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(26, 241);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(101, 13);
this.label11.TabIndex = 54;
this.label11.Text = "Logical Entity Name";
this.ttInfo.SetToolTip(this.label11, "The logical name of the entity bound to the custom API response property .\r\nCanno" +
"t be changed after it is saved.");
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(26, 130);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(72, 13);
this.label10.TabIndex = 52;
this.label10.Text = "Display Name";
this.ttInfo.SetToolTip(this.label10, "Localized display name for custom API response property instances. \r\nFor use when" +
" the message parameter is exposed to be called in an app.");
//
// txtDisplayName
//
this.txtDisplayName.Location = new System.Drawing.Point(104, 127);
this.txtDisplayName.Name = "txtDisplayName";
this.txtDisplayName.Size = new System.Drawing.Size(319, 20);
this.txtDisplayName.TabIndex = 51;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(26, 211);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(31, 13);
this.label9.TabIndex = 50;
this.label9.Text = "Type";
this.ttInfo.SetToolTip(this.label9, resources.GetString("label9.ToolTip"));
//
// cboType
//
this.cboType.FormattingEnabled = true;
this.cboType.Location = new System.Drawing.Point(104, 209);
this.cboType.Name = "cboType";
this.cboType.Size = new System.Drawing.Size(211, 21);
this.cboType.TabIndex = 48;
this.cboType.SelectedIndexChanged += new System.EventHandler(this.cboType_SelectedIndexChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(26, 78);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(72, 13);
this.label6.TabIndex = 46;
this.label6.Text = "Unique Name";
this.ttInfo.SetToolTip(this.label6, "Unique name for the custom API response property. \r\nThis will be the name of the " +
"parameter when you call the Custom API.\r\nCannot be changed after it is saved.");
//
// txtUniqueName
//
this.txtUniqueName.Location = new System.Drawing.Point(104, 74);
this.txtUniqueName.Name = "txtUniqueName";
this.txtUniqueName.Size = new System.Drawing.Size(319, 20);
this.txtUniqueName.TabIndex = 45;
this.txtUniqueName.Leave += new System.EventHandler(this.txtUniqueName_Leave);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(26, 104);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 13);
this.label4.TabIndex = 41;
this.label4.Text = "Name";
this.ttInfo.SetToolTip(this.label4, resources.GetString("label4.ToolTip"));
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(104, 101);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(319, 20);
this.txtName.TabIndex = 40;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(26, 156);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 39;
this.label3.Text = "Description";
this.ttInfo.SetToolTip(this.label3, "Localized description for custom API response property instances. \r\nFor use when " +
"the message parameter is exposed to be called in an app. \r\nFor example, as a Too" +
"lTip.");
//
// txtDescription
//
this.txtDescription.Location = new System.Drawing.Point(104, 153);
this.txtDescription.Multiline = true;
this.txtDescription.Name = "txtDescription";
this.txtDescription.Size = new System.Drawing.Size(319, 49);
this.txtDescription.TabIndex = 38;
//
// ttInfo
//
this.ttInfo.AutoPopDelay = 10000;
this.ttInfo.InitialDelay = 500;
this.ttInfo.ReshowDelay = 100;
this.ttInfo.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
this.ttInfo.ToolTipTitle = "Attribute Info";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(27, 304);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(182, 13);
this.label12.TabIndex = 108;
this.label12.Text = "Add to unmanaged solution (optional)";
this.ttInfo.SetToolTip(this.label12, "Controls whether the Custom API can be customized or deleted when deployed as man" +
"aged.");
//
// cdsCboSolutions
//
this.cdsCboSolutions.DisplayFormat = "{{friendlyname}} ({{P.customizationprefix}})";
this.cdsCboSolutions.FormattingEnabled = true;
this.cdsCboSolutions.Location = new System.Drawing.Point(30, 320);
this.cdsCboSolutions.Name = "cdsCboSolutions";
this.cdsCboSolutions.OrganizationService = null;
this.cdsCboSolutions.Size = new System.Drawing.Size(252, 21);
this.cdsCboSolutions.TabIndex = 107;
this.cdsCboSolutions.SelectedIndexChanged += new System.EventHandler(this.cdsCboSolutions_SelectedIndexChanged);
this.cdsCboSolutions.TextUpdate += new System.EventHandler(this.cdsCboSolutions_TextUpdate);
//
// NewResponsePropertyForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Window;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(525, 356);
this.Controls.Add(this.panel2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "NewResponsePropertyForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Custom Api Manager";
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox13)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox txtDisplayName;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox cboType;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txtUniqueName;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtDescription;
private xrmtb.XrmToolBox.Controls.EntitiesDropdownControl cboEntities;
private System.Windows.Forms.PictureBox pictureBox4;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Label lblTitle;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.PictureBox pictureBox13;
private xrmtb.XrmToolBox.Controls.Controls.CDSDataTextBox cdsCustomApiName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ToolTip ttInfo;
private System.Windows.Forms.Label lblCustomizable;
private System.Windows.Forms.CheckBox chkIsCustomizable;
private System.Windows.Forms.Label label12;
private xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox cdsCboSolutions;
}
} | 53.788636 | 234 | 0.614315 | [
"MIT"
] | drivardxrm/XTB.CustomApiManager | XTB.CustomApiManager/Forms/NewResponsePropertyForm.designer.cs | 23,669 | C# |
namespace Desktop_View
{
partial class TNovaNota
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtNota = new System.Windows.Forms.TextBox();
this.btnAdicionar = new MaterialSkin.Controls.MaterialFlatButton();
this.btnCancelar = new MaterialSkin.Controls.MaterialFlatButton();
this.SuspendLayout();
//
// txtNota
//
this.txtNota.Location = new System.Drawing.Point(13, 78);
this.txtNota.Multiline = true;
this.txtNota.Name = "txtNota";
this.txtNota.Size = new System.Drawing.Size(775, 316);
this.txtNota.TabIndex = 0;
this.txtNota.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// btnAdicionar
//
this.btnAdicionar.AutoSize = true;
this.btnAdicionar.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnAdicionar.Depth = 0;
this.btnAdicionar.Location = new System.Drawing.Point(359, 403);
this.btnAdicionar.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
this.btnAdicionar.MouseState = MaterialSkin.MouseState.HOVER;
this.btnAdicionar.Name = "btnAdicionar";
this.btnAdicionar.Primary = false;
this.btnAdicionar.Size = new System.Drawing.Size(84, 36);
this.btnAdicionar.TabIndex = 1;
this.btnAdicionar.Text = "Adicionar";
this.btnAdicionar.UseVisualStyleBackColor = true;
//
// btnCancelar
//
this.btnCancelar.AutoSize = true;
this.btnCancelar.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnCancelar.BackColor = System.Drawing.Color.Red;
this.btnCancelar.Depth = 0;
this.btnCancelar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCancelar.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.btnCancelar.Location = new System.Drawing.Point(13, 403);
this.btnCancelar.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6);
this.btnCancelar.MouseState = MaterialSkin.MouseState.HOVER;
this.btnCancelar.Name = "btnCancelar";
this.btnCancelar.Primary = false;
this.btnCancelar.Size = new System.Drawing.Size(82, 36);
this.btnCancelar.TabIndex = 2;
this.btnCancelar.Text = "Cancelar";
this.btnCancelar.UseVisualStyleBackColor = false;
//
// TNovaNota
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.btnCancelar);
this.Controls.Add(this.btnAdicionar);
this.Controls.Add(this.txtNota);
this.Name = "TNovaNota";
this.Text = "Nova Nota";
this.Load += new System.EventHandler(this.TNovaNota_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtNota;
private MaterialSkin.Controls.MaterialFlatButton btnAdicionar;
private MaterialSkin.Controls.MaterialFlatButton btnCancelar;
}
} | 42.73 | 107 | 0.597707 | [
"MIT"
] | Mogueno/Atena-Desk-and-Mobile | desk/Desktop_View/TNovaNota.Designer.cs | 4,275 | C# |
using AutoFixture;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoFixtureDemo.Tests
{
public class GuidEnumDemos
{
[Test]
public void Guid()
{
var fixture = new Fixture();
var sut =
new EmailMessage(
fixture.Create<string>(),
fixture.Create<string>(),
fixture.Create<bool>(),
fixture.Create<string>())
{
Id = fixture.Create<Guid>()
};
Assert.Pass();
}
}
}
| 22.354839 | 47 | 0.497835 | [
"MIT"
] | mirusser/Learning-dontNet | src/Testing/AutoFixture/AutoFixtureDemo.Tests/GuidEnumDemos.cs | 695 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the route53-recovery-readiness-2019-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Route53RecoveryReadiness.Model
{
/// <summary>
/// Container for the parameters to the GetReadinessCheckResourceStatus operation.
/// Gets individual readiness status for a readiness check. To see the overall readiness
/// status for a recovery group, that considers the readiness status for all the readiness
/// checks in the recovery group, use GetRecoveryGroupReadinessSummary.
/// </summary>
public partial class GetReadinessCheckResourceStatusRequest : AmazonRoute53RecoveryReadinessRequest
{
private int? _maxResults;
private string _nextToken;
private string _readinessCheckName;
private string _resourceIdentifier;
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The number of objects that you want to return with this call.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1000)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token that identifies which batch of results you want to see.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ReadinessCheckName.
/// <para>
/// Name of a readiness check.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ReadinessCheckName
{
get { return this._readinessCheckName; }
set { this._readinessCheckName = value; }
}
// Check to see if ReadinessCheckName property is set
internal bool IsSetReadinessCheckName()
{
return this._readinessCheckName != null;
}
/// <summary>
/// Gets and sets the property ResourceIdentifier.
/// <para>
/// The resource identifier, which is the Amazon Resource Name (ARN) or the identifier
/// generated for the resource by Application Recovery Controller (for example, for a
/// DNS target resource).
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ResourceIdentifier
{
get { return this._resourceIdentifier; }
set { this._resourceIdentifier = value; }
}
// Check to see if ResourceIdentifier property is set
internal bool IsSetResourceIdentifier()
{
return this._resourceIdentifier != null;
}
}
} | 33.016393 | 124 | 0.623138 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Route53RecoveryReadiness/Generated/Model/GetReadinessCheckResourceStatusRequest.cs | 4,028 | C# |
#region Using
using JetBrains.Annotations;
#endregion
namespace Utils.StructParsers
{
[PublicAPI]
public sealed class LongParser : IStructParser<long>
{
long IStructParser<long>.ParseOrDefault(string value, long @default)
=> ParseOrDefault(value, @default);
long? IStructParser<long>.Parse(string value)
=> Parse(value);
public static long? Parse(string value)
=> long.TryParse(value, out var result) ? result : (long?)null;
public static long ParseOrDefault(string value, long @default = default)
=> Parse(value) ?? @default;
}
}
| 25.36 | 80 | 0.640379 | [
"MIT"
] | azoh19/Utils.Common | Utils.StructParsers/LongParser.cs | 636 | C# |
namespace Dear.MediaControl {
public interface IMedia {
void VolumeUp();
void VolumeDown();
void VolumeMute();
}
} | 21 | 30 | 0.585034 | [
"MIT"
] | MrWindows/MrWindows | MrWindows/MediaControl/IMedia.cs | 149 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Screens;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays;
using osu.Game.Overlays.Mods;
using osu.Game.Overlays.Toolbar;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.Menu;
using osu.Game.Screens.OnlinePlay.Lounge;
using osu.Game.Screens.Play;
using osu.Game.Screens.Ranking;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Options;
using osu.Game.Tests.Beatmaps.IO;
using osuTK;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneScreenNavigation : OsuGameTestScene
{
private const float click_padding = 25;
private Vector2 backButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, Game.LayoutRectangle.Bottom - click_padding));
private Vector2 optionsButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, click_padding));
[Test]
public void TestExitSongSelectWithEscape()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show());
AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible);
pushEscape();
AddAssert("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden);
exitViaEscapeAndConfirm();
}
/// <summary>
/// This tests that the F1 key will open the mod select overlay, and not be handled / blocked by the music controller (which has the same default binding
/// but should be handled *after* song select).
/// </summary>
[Test]
public void TestOpenModSelectOverlayUsingAction()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddStep("Show mods overlay", () => InputManager.Key(Key.F1));
AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible);
}
[Test]
public void TestRetryCountIncrements()
{
Player player = null;
PushAndConfirm(() => new TestPlaySongSelect());
AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait());
AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault);
AddStep("press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () =>
{
// dismiss any notifications that may appear (ie. muted notification).
clickMouseInCentre();
return (player = Game.ScreenStack.CurrentScreen as Player) != null;
});
AddAssert("retry count is 0", () => player.RestartCount == 0);
AddStep("attempt to retry", () => player.ChildrenOfType<HotkeyRetryOverlay>().First().Action());
AddUntilStep("wait for old player gone", () => Game.ScreenStack.CurrentScreen != player);
AddUntilStep("get new player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null);
AddAssert("retry count is 1", () => player.RestartCount == 1);
}
[Test]
public void TestRetryFromResults()
{
Player player = null;
ResultsScreen results = null;
IWorkingBeatmap beatmap() => Game.Beatmap.Value;
PushAndConfirm(() => new TestPlaySongSelect());
AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait());
AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault);
AddStep("set mods", () => Game.SelectedMods.Value = new Mod[] { new OsuModNoFail(), new OsuModDoubleTime { SpeedChange = { Value = 2 } } });
AddStep("press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () =>
{
// dismiss any notifications that may appear (ie. muted notification).
clickMouseInCentre();
return (player = Game.ScreenStack.CurrentScreen as Player) != null;
});
AddUntilStep("wait for track playing", () => beatmap().Track.IsRunning);
AddStep("seek to near end", () => player.ChildrenOfType<GameplayClockContainer>().First().Seek(beatmap().Beatmap.HitObjects[^1].StartTime - 1000));
AddUntilStep("wait for pass", () => (results = Game.ScreenStack.CurrentScreen as ResultsScreen) != null && results.IsLoaded);
AddStep("attempt to retry", () => results.ChildrenOfType<HotkeyRetryOverlay>().First().Action());
AddUntilStep("wait for player", () => Game.ScreenStack.CurrentScreen != player && Game.ScreenStack.CurrentScreen is Player);
}
[TestCase(true)]
[TestCase(false)]
public void TestSongContinuesAfterExitPlayer(bool withUserPause)
{
Player player = null;
IWorkingBeatmap beatmap() => Game.Beatmap.Value;
PushAndConfirm(() => new TestPlaySongSelect());
AddStep("import beatmap", () => ImportBeatmapTest.LoadOszIntoOsu(Game, virtualTrack: true).Wait());
AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault);
if (withUserPause)
AddStep("pause", () => Game.Dependencies.Get<MusicController>().Stop(true));
AddStep("press enter", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () =>
{
// dismiss any notifications that may appear (ie. muted notification).
clickMouseInCentre();
return (player = Game.ScreenStack.CurrentScreen as Player) != null;
});
AddUntilStep("wait for fail", () => player.HasFailed);
AddUntilStep("wait for track stop", () => !Game.MusicController.IsPlaying);
AddAssert("Ensure time before preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime);
pushEscape();
AddUntilStep("wait for track playing", () => Game.MusicController.IsPlaying);
AddAssert("Ensure time wasn't reset to preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime);
}
[Test]
public void TestMenuMakesMusic()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddUntilStep("wait for no track", () => Game.MusicController.CurrentTrack.IsDummyDevice);
AddStep("return to menu", () => songSelect.Exit());
AddUntilStep("wait for track", () => !Game.MusicController.CurrentTrack.IsDummyDevice && Game.MusicController.IsPlaying);
}
[Test]
public void TestPushSongSelectAndPressBackButtonImmediately()
{
AddStep("push song select", () => Game.ScreenStack.Push(new TestPlaySongSelect()));
AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action());
AddWaitStep("wait two frames", 2);
}
[Test]
public void TestExitSongSelectWithClick()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show());
AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible);
AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition));
// BackButton handles hover using its child button, so this checks whether or not any of BackButton's children are hovered.
AddUntilStep("Back button is hovered", () => Game.ChildrenOfType<BackButton>().First().Children.Any(c => c.IsHovered));
AddStep("Click back button", () => InputManager.Click(MouseButton.Left));
AddUntilStep("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden);
exitViaBackButtonAndConfirm();
}
[Test]
public void TestExitMultiWithEscape()
{
PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists());
exitViaEscapeAndConfirm();
}
[Test]
public void TestExitMultiWithBackButton()
{
PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists());
exitViaBackButtonAndConfirm();
}
[Test]
public void TestOpenOptionsAndExitWithEscape()
{
AddUntilStep("Wait for options to load", () => Game.Settings.IsLoaded);
AddStep("Enter menu", () => InputManager.Key(Key.Enter));
AddStep("Move mouse to options overlay", () => InputManager.MoveMouseTo(optionsButtonPosition));
AddStep("Click options overlay", () => InputManager.Click(MouseButton.Left));
AddAssert("Options overlay was opened", () => Game.Settings.State.Value == Visibility.Visible);
AddStep("Hide options overlay using escape", () => InputManager.Key(Key.Escape));
AddAssert("Options overlay was closed", () => Game.Settings.State.Value == Visibility.Hidden);
}
[Test]
public void TestWaitForNextTrackInMenu()
{
bool trackCompleted = false;
AddUntilStep("Wait for music controller", () => Game.MusicController.IsLoaded);
AddStep("Seek close to end", () =>
{
Game.MusicController.SeekTo(Game.MusicController.CurrentTrack.Length - 1000);
Game.MusicController.CurrentTrack.Completed += () => trackCompleted = true;
});
AddUntilStep("Track was completed", () => trackCompleted);
AddUntilStep("Track was restarted", () => Game.MusicController.IsPlaying);
}
[Test]
public void TestModSelectInput()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show());
AddStep("Change ruleset to osu!taiko", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.Key(Key.Number2);
InputManager.ReleaseKey(Key.ControlLeft);
});
AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.OnlineID == 1);
AddAssert("Mods overlay still visible", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible);
}
[Test]
public void TestBeatmapOptionsInput()
{
TestPlaySongSelect songSelect = null;
PushAndConfirm(() => songSelect = new TestPlaySongSelect());
AddStep("Show options overlay", () => songSelect.BeatmapOptionsOverlay.Show());
AddStep("Change ruleset to osu!taiko", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.Key(Key.Number2);
InputManager.ReleaseKey(Key.ControlLeft);
});
AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.OnlineID == 1);
AddAssert("Options overlay still visible", () => songSelect.BeatmapOptionsOverlay.State.Value == Visibility.Visible);
}
[Test]
public void TestSettingsViaHotkeyFromMainMenu()
{
AddAssert("toolbar not displayed", () => Game.Toolbar.State.Value == Visibility.Hidden);
AddStep("press settings hotkey", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.Key(Key.O);
InputManager.ReleaseKey(Key.ControlLeft);
});
AddUntilStep("settings displayed", () => Game.Settings.State.Value == Visibility.Visible);
}
[Test]
public void TestToolbarHiddenByUser()
{
AddStep("Enter menu", () => InputManager.Key(Key.Enter));
AddUntilStep("Wait for toolbar to load", () => Game.Toolbar.IsLoaded);
AddStep("Hide toolbar", () =>
{
InputManager.PressKey(Key.ControlLeft);
InputManager.Key(Key.T);
InputManager.ReleaseKey(Key.ControlLeft);
});
pushEscape();
AddStep("Enter menu", () => InputManager.Key(Key.Enter));
AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden);
AddStep("Enter song select", () =>
{
InputManager.Key(Key.Enter);
InputManager.Key(Key.Enter);
});
AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden);
}
[Test]
public void TestPushMatchSubScreenAndPressBackButtonImmediately()
{
TestMultiplayerScreenStack multiplayerScreenStack = null;
PushAndConfirm(() => multiplayerScreenStack = new TestMultiplayerScreenStack());
AddUntilStep("wait for lounge", () => multiplayerScreenStack.ChildrenOfType<LoungeSubScreen>().SingleOrDefault()?.IsLoaded == true);
AddStep("open room", () => multiplayerScreenStack.ChildrenOfType<LoungeSubScreen>().Single().Open());
AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action());
AddWaitStep("wait two frames", 2);
}
[Test]
public void TestOverlayClosing()
{
// use now playing overlay for "overlay -> background" drag case
// since most overlays use a scroll container that absorbs on mouse down
NowPlayingOverlay nowPlayingOverlay = null;
AddUntilStep("Wait for now playing load", () => (nowPlayingOverlay = Game.ChildrenOfType<NowPlayingOverlay>().FirstOrDefault()) != null);
AddStep("enter menu", () => InputManager.Key(Key.Enter));
AddUntilStep("toolbar displayed", () => Game.Toolbar.State.Value == Visibility.Visible);
AddStep("open now playing", () => InputManager.Key(Key.F6));
AddUntilStep("now playing is visible", () => nowPlayingOverlay.State.Value == Visibility.Visible);
// drag tests
// background -> toolbar
AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight));
AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left));
AddStep("move cursor to toolbar", () => InputManager.MoveMouseTo(Game.Toolbar.ScreenSpaceDrawQuad.Centre));
AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden);
AddStep("press now playing hotkey", () => InputManager.Key(Key.F6));
// toolbar -> background
AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left));
AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight));
AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible);
// background -> overlay
AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left));
AddStep("move cursor to now playing overlay", () => InputManager.MoveMouseTo(nowPlayingOverlay.ScreenSpaceDrawQuad.Centre));
AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible);
// overlay -> background
AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left));
AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight));
AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible);
// background -> background
AddStep("press left mouse button", () => InputManager.PressButton(MouseButton.Left));
AddStep("move cursor to left", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomLeft));
AddStep("release left mouse button", () => InputManager.ReleaseButton(MouseButton.Left));
AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden);
AddStep("press now playing hotkey", () => InputManager.Key(Key.F6));
// click tests
// toolbar
AddStep("move cursor to toolbar", () => InputManager.MoveMouseTo(Game.Toolbar.ScreenSpaceDrawQuad.Centre));
AddStep("click left mouse button", () => InputManager.Click(MouseButton.Left));
AddAssert("now playing is still visible", () => nowPlayingOverlay.State.Value == Visibility.Visible);
// background
AddStep("move cursor to background", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.BottomRight));
AddStep("click left mouse button", () => InputManager.Click(MouseButton.Left));
AddAssert("now playing is hidden", () => nowPlayingOverlay.State.Value == Visibility.Hidden);
}
[Test]
public void TestExitGameFromSongSelect()
{
PushAndConfirm(() => new TestPlaySongSelect());
exitViaEscapeAndConfirm();
pushEscape(); // returns to osu! logo
AddStep("Hold escape", () => InputManager.PressKey(Key.Escape));
AddUntilStep("Wait for intro", () => Game.ScreenStack.CurrentScreen is IntroScreen);
AddStep("Release escape", () => InputManager.ReleaseKey(Key.Escape));
AddUntilStep("Wait for game exit", () => Game.ScreenStack.CurrentScreen == null);
AddStep("test dispose doesn't crash", () => Game.Dispose());
}
private void clickMouseInCentre()
{
InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
}
private void pushEscape() =>
AddStep("Press escape", () => InputManager.Key(Key.Escape));
private void exitViaEscapeAndConfirm()
{
pushEscape();
ConfirmAtMainMenu();
}
private void exitViaBackButtonAndConfirm()
{
AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition));
AddStep("Click back button", () => InputManager.Click(MouseButton.Left));
ConfirmAtMainMenu();
}
public class TestPlaySongSelect : PlaySongSelect
{
public ModSelectOverlay ModSelectOverlay => ModSelect;
public BeatmapOptionsOverlay BeatmapOptionsOverlay => BeatmapOptions;
protected override bool DisplayStableImportPrompt => false;
}
}
}
| 45.320879 | 162 | 0.604723 | [
"MIT"
] | powenn/osu | osu.Game.Tests/Visual/Navigation/TestSceneScreenNavigation.cs | 20,167 | C# |
// This file is part of VaultLib.Core by heyitsleo.
//
// Created: 10/31/2019 @ 4:59 PM.
using CoreLibraries.IO;
namespace VaultLib.Core.Pack
{
/// <summary>
/// Provides options for vault pack loading
/// </summary>
public class PackLoadingOptions
{
public PackLoadingOptions(ByteOrder byteOrder = ByteOrder.Little)
{
ByteOrder = byteOrder;
}
public ByteOrder ByteOrder { get; }
}
} | 21.904762 | 73 | 0.615217 | [
"MIT"
] | BreakinBenny/VaultLib | VaultLib.Core/Pack/PackLoadingOptions.cs | 462 | C# |
/* Copyright 2010-present MongoDB 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using Xunit;
namespace MongoDB.Bson.Tests
{
public class RawBsonDocumentTests
{
[Fact]
public void TestClone()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
using (var clone = (IDisposable)rawBsonDocument.Clone())
{
Assert.Equal(rawBsonDocument, clone);
}
}
[Fact]
public void TestContains()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
Assert.Equal(true, rawBsonDocument.Contains("x"));
Assert.Equal(false, rawBsonDocument.Contains("z"));
}
}
[Fact]
public void TestContainsValue()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
Assert.Equal(true, rawBsonDocument.ContainsValue(1));
Assert.Equal(false, rawBsonDocument.ContainsValue(3));
}
}
[Fact]
public void TestDeepClone()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
using (var clone = (IDisposable)rawBsonDocument.DeepClone())
{
Assert.Equal(rawBsonDocument, clone);
}
}
[Fact]
public void TestElementCount()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var count = rawBsonDocument.ElementCount;
Assert.Equal(2, count);
}
}
[Fact]
public void TestElements()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var elements = rawBsonDocument.Elements.ToArray();
Assert.Equal(2, elements.Length);
Assert.Equal("x", elements[0].Name);
Assert.Equal(1, elements[0].Value.AsInt32);
Assert.Equal("y", elements[1].Name);
Assert.Equal(2, elements[1].Value.AsInt32);
}
}
[Fact]
public void TestGetElementByIndex()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var elements = new[] { rawBsonDocument.GetElement(0), rawBsonDocument.GetElement(1) };
Assert.Equal("x", elements[0].Name);
Assert.Equal(1, elements[0].Value.AsInt32);
Assert.Equal("y", elements[1].Name);
Assert.Equal(2, elements[1].Value.AsInt32);
Assert.Throws<ArgumentOutOfRangeException>(() => { rawBsonDocument.GetElement(2); });
}
}
[Fact]
public void TestGetElementByName()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var elements = new[] { rawBsonDocument.GetElement("x"), rawBsonDocument.GetElement("y") };
Assert.Equal("x", elements[0].Name);
Assert.Equal(1, elements[0].Value.AsInt32);
Assert.Equal("y", elements[1].Name);
Assert.Equal(2, elements[1].Value.AsInt32);
Assert.Throws<KeyNotFoundException>(() => { rawBsonDocument.GetElement("z"); });
}
}
[Fact]
public void TestGetHashcode()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
Assert.Equal(bsonDocument.GetHashCode(), rawBsonDocument.GetHashCode());
}
}
[Fact]
public void TestGetValueByIndex()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var values = new[] { rawBsonDocument.GetValue(0), rawBsonDocument.GetValue(1) };
Assert.Equal(1, values[0].AsInt32);
Assert.Equal(2, values[1].AsInt32);
Assert.Throws<ArgumentOutOfRangeException>(() => { rawBsonDocument.GetValue(2); });
}
}
[Fact]
public void TestGetValueByName()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var values = new[] { rawBsonDocument.GetValue("x"), rawBsonDocument.GetValue("y") };
Assert.Equal(1, values[0].AsInt32);
Assert.Equal(2, values[1].AsInt32);
Assert.Throws<KeyNotFoundException>(() => { rawBsonDocument.GetValue("z"); });
}
}
[Fact]
public void TestGetValueByNameWithDefaultValue()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
Assert.Equal(1, rawBsonDocument.GetValue("x", 3).AsInt32);
Assert.Equal(3, rawBsonDocument.GetValue("z", 3).AsInt32);
}
}
[Fact]
public void TestNames()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var names = rawBsonDocument.Names.ToArray();
Assert.Equal(2, names.Length);
Assert.Equal("x", names[0]);
Assert.Equal("y", names[1]);
}
}
[Fact]
public void TestNestedRawBsonArray()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "a", new BsonArray { 1, 2 } } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var nestedRawBsonArray = rawBsonDocument["a"].AsBsonArray;
var nestedValues = nestedRawBsonArray.Values.ToArray();
Assert.Equal(1, rawBsonDocument["x"].AsInt32);
Assert.Equal(2, nestedValues.Length);
Assert.Equal(1, nestedValues[0].AsInt32);
Assert.Equal(2, nestedValues[1].AsInt32);
}
}
[Fact]
public void TestNestedRawBsonDocument()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "d", new BsonDocument { { "x", 1 }, { "y", 2 } } } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var nestedRawBsonDocument = rawBsonDocument["d"].AsBsonDocument;
var nestedElements = nestedRawBsonDocument.Elements.ToArray();
Assert.Equal(1, rawBsonDocument["x"].AsInt32);
Assert.Equal(2, nestedElements.Length);
Assert.Equal("x", nestedElements[0].Name);
Assert.Equal(1, nestedElements[0].Value.AsInt32);
Assert.Equal("y", nestedElements[1].Name);
Assert.Equal(2, nestedElements[1].Value.AsInt32);
}
}
[Fact]
public void TestRawValues()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
#pragma warning disable 618
var rawValues = rawBsonDocument.RawValues.ToArray();
#pragma warning restore
Assert.Equal(2, rawValues.Length);
Assert.Equal(1, rawValues[0]);
Assert.Equal(2, rawValues[1]);
}
}
[Fact]
public void TestValues()
{
var bsonDocument = new BsonDocument { { "x", 1 }, { "y", 2 } };
var bson = bsonDocument.ToBson();
using (var rawBsonDocument = BsonSerializer.Deserialize<RawBsonDocument>(bson))
{
var rawValues = rawBsonDocument.Values.ToArray();
Assert.Equal(2, rawValues.Length);
Assert.Equal(1, rawValues[0].AsInt32);
Assert.Equal(2, rawValues[1].AsInt32);
}
}
}
}
| 39.182156 | 117 | 0.54611 | [
"Apache-2.0"
] | 591094733/mongo-csharp-driver | tests/MongoDB.Bson.Tests/ObjectModel/RawBsonDocumentTests.cs | 10,542 | C# |
using System;
using System.Threading;
namespace Trees
{
class Program
{
static void Main(string[] args)
{
Debug.Init();
var printer = new Printer();
var world = new World(Console.WindowWidth, Console.WindowHeight);
while (true)
{
world.Run();
printer.PrintWorld(world);
// printer.PrintTreeIds(world);
Thread.Sleep(1000);
}
}
}
}
| 21.913043 | 77 | 0.478175 | [
"MIT"
] | XDA-7/trees | Program.cs | 506 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Dynamic.Utils;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace System.Linq.Expressions.Interpreter
{
internal abstract partial class CallInstruction : Instruction
{
/// <summary>
/// The number of arguments including "this" for instance methods.
/// </summary>
public abstract int ArgumentCount { get; }
#region Construction
public override string InstructionName => "Call";
#if FEATURE_DLG_INVOKE
private static readonly CacheDict<MethodInfo, CallInstruction> s_cache = new CacheDict<MethodInfo, CallInstruction>(256);
#endif
public static CallInstruction Create(MethodInfo info)
{
return Create(info, info.GetParametersCached());
}
/// <summary>
/// Creates a new ReflectedCaller which can be used to quickly invoke the provided MethodInfo.
/// </summary>
public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters)
{
int argumentCount = parameters.Length;
if (!info.IsStatic)
{
argumentCount++;
}
// A workaround for CLR behavior (Unable to create delegates for Array.Get/Set):
// T[]::Address - not supported by ETs due to T& return value
if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set"))
{
return GetArrayAccessor(info, argumentCount);
}
#if !FEATURE_DLG_INVOKE
return new MethodInfoCallInstruction(info, argumentCount);
#else
if (!info.IsStatic && info.DeclaringType!.IsValueType)
{
return new MethodInfoCallInstruction(info, argumentCount);
}
if (argumentCount >= MaxHelpers)
{
// no delegate for this size, fall back to reflection invoke
return new MethodInfoCallInstruction(info, argumentCount);
}
foreach (ParameterInfo pi in parameters)
{
if (pi.ParameterType.IsByRef)
{
// we don't support ref args via generics.
return new MethodInfoCallInstruction(info, argumentCount);
}
}
// see if we've created one w/ a delegate
CallInstruction? res;
if (ShouldCache(info))
{
if (s_cache.TryGetValue(info, out res))
{
return res;
}
}
// create it
try
{
#if FEATURE_FAST_CREATE
if (argumentCount < MaxArgs)
{
res = FastCreate(info, parameters);
}
else
#endif
{
res = SlowCreate(info, parameters);
}
}
catch (TargetInvocationException tie)
{
if (!(tie.InnerException is NotSupportedException))
{
throw;
}
res = new MethodInfoCallInstruction(info, argumentCount);
}
catch (NotSupportedException)
{
// if Delegate.CreateDelegate can't handle the method fall back to
// the slow reflection version. For example this can happen w/
// a generic method defined on an interface and implemented on a class or
// a virtual generic method.
res = new MethodInfoCallInstruction(info, argumentCount);
}
// cache it for future users if it's a reasonable method to cache
if (ShouldCache(info))
{
s_cache[info] = res;
}
return res;
#endif
}
private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount)
{
Type arrayType = info.DeclaringType!;
bool isGetter = info.Name == "Get";
MethodInfo? alternativeMethod = null;
switch (arrayType.GetArrayRank())
{
case 1:
alternativeMethod = isGetter ?
arrayType.GetMethod("GetValue", new[] { typeof(int) }) :
typeof(CallInstruction).GetMethod(nameof(ArrayItemSetter1));
break;
case 2:
alternativeMethod = isGetter ?
arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int) }) :
typeof(CallInstruction).GetMethod(nameof(ArrayItemSetter2));
break;
case 3:
alternativeMethod = isGetter ?
arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int), typeof(int) }) :
typeof(CallInstruction).GetMethod(nameof(ArrayItemSetter3));
break;
}
if ((object?)alternativeMethod == null)
{
return new MethodInfoCallInstruction(info, argumentCount);
}
return Create(alternativeMethod);
}
public static void ArrayItemSetter1(Array array, int index0, object value)
{
array.SetValue(value, index0);
}
public static void ArrayItemSetter2(Array array, int index0, int index1, object value)
{
array.SetValue(value, index0, index1);
}
public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value)
{
array.SetValue(value, index0, index1, index2);
}
#if FEATURE_DLG_INVOKE
private static bool ShouldCache(MethodInfo info)
{
return true;
}
#endif
#if FEATURE_FAST_CREATE
/// <summary>
/// Gets the next type or null if no more types are available.
/// </summary>
private static Type? TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index)
{
if (!target.IsStatic)
{
index--;
if (index < 0)
{
return target.DeclaringType;
}
}
if (index < pi.Length)
{
// next in signature
return pi[index].ParameterType;
}
if (target.ReturnType == typeof(void) || index > pi.Length)
{
// no more parameters
return null;
}
// last parameter on Invoke is return type
return target.ReturnType;
}
private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi)
{
return pi.Length != index || (pi.Length == index && !target.IsStatic);
}
#endif
#if FEATURE_DLG_INVOKE
/// <summary>
/// Uses reflection to create new instance of the appropriate ReflectedCaller
/// </summary>
private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis)
{
List<Type> types = new List<Type>();
if (!info.IsStatic) types.Add(info.DeclaringType!);
foreach (ParameterInfo pi in pis)
{
types.Add(pi.ParameterType);
}
if (info.ReturnType != typeof(void))
{
types.Add(info.ReturnType);
}
Type[] arrTypes = types.ToArray();
try
{
return (CallInstruction)Activator.CreateInstance(GetHelperType(info, arrTypes), info)!;
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UnwrapAndRethrow(e);
throw ContractUtils.Unreachable;
}
}
#endif
#endregion
#region Instruction
public override int ConsumedStack => ArgumentCount;
#endregion
/// <summary>
/// If the target of invocation happens to be a delegate
/// over enclosed instance lightLambda, return that instance.
/// We can interpret LightLambdas directly.
/// </summary>
protected static bool TryGetLightLambdaTarget(object? instance, [NotNullWhen(true)] out LightLambda? lightLambda)
{
var del = instance as Delegate;
if ((object?)del != null)
{
var thunk = del.Target as Func<object[], object>;
if ((object?)thunk != null)
{
lightLambda = thunk.Target as LightLambda;
if (lightLambda != null)
{
return true;
}
}
}
lightLambda = null;
return false;
}
protected object? InterpretLambdaInvoke(LightLambda targetLambda, object?[] args)
{
if (ProducedStack > 0)
{
return targetLambda.Run(args);
}
else
{
return targetLambda.RunVoid(args);
}
}
}
internal class MethodInfoCallInstruction : CallInstruction
{
protected readonly MethodInfo _target;
protected readonly int _argumentCount;
public override int ArgumentCount => _argumentCount;
internal MethodInfoCallInstruction(MethodInfo target, int argumentCount)
{
_target = target;
_argumentCount = argumentCount;
}
public override int ProducedStack => _target.ReturnType == typeof(void) ? 0 : 1;
public override int Run(InterpretedFrame frame)
{
int first = frame.StackIndex - _argumentCount;
object? ret;
if (_target.IsStatic)
{
object?[] args = GetArgs(frame, first, 0);
try
{
ret = _target.Invoke(null, args);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UnwrapAndRethrow(e);
throw ContractUtils.Unreachable;
}
}
else
{
object? instance = frame.Data[first];
NullCheck(instance);
object?[] args = GetArgs(frame, first, 1);
if (TryGetLightLambdaTarget(instance, out LightLambda? targetLambda))
{
// no need to Invoke, just interpret the lambda body
ret = InterpretLambdaInvoke(targetLambda, args);
}
else
{
try
{
ret = _target.Invoke(instance, args);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UnwrapAndRethrow(e);
throw ContractUtils.Unreachable;
}
}
}
if (_target.ReturnType != typeof(void))
{
frame.Data[first] = ret;
frame.StackIndex = first + 1;
}
else
{
frame.StackIndex = first;
}
return 1;
}
protected object?[] GetArgs(InterpretedFrame frame, int first, int skip)
{
int count = _argumentCount - skip;
if (count > 0)
{
var args = new object?[count];
for (int i = 0; i < args.Length; i++)
{
args[i] = frame.Data[first + i + skip];
}
return args;
}
else
{
return Array.Empty<object>();
}
}
public override string ToString() => "Call(" + _target + ")";
}
internal class ByRefMethodInfoCallInstruction : MethodInfoCallInstruction
{
private readonly ByRefUpdater[] _byrefArgs;
internal ByRefMethodInfoCallInstruction(MethodInfo target, int argumentCount, ByRefUpdater[] byrefArgs)
: base(target, argumentCount)
{
_byrefArgs = byrefArgs;
}
public override int ProducedStack => _target.ReturnType == typeof(void) ? 0 : 1;
public sealed override int Run(InterpretedFrame frame)
{
int first = frame.StackIndex - _argumentCount;
object?[]? args = null;
object? instance = null;
try
{
object? ret;
if (_target.IsStatic)
{
args = GetArgs(frame, first, 0);
try
{
ret = _target.Invoke(null, args);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UnwrapAndRethrow(e);
throw ContractUtils.Unreachable;
}
}
else
{
instance = frame.Data[first];
NullCheck(instance);
args = GetArgs(frame, first, 1);
if (TryGetLightLambdaTarget(instance, out LightLambda? targetLambda))
{
// no need to Invoke, just interpret the lambda body
ret = InterpretLambdaInvoke(targetLambda, args);
}
else
{
try
{
ret = _target.Invoke(instance, args);
}
catch (TargetInvocationException e)
{
ExceptionHelpers.UnwrapAndRethrow(e);
throw ContractUtils.Unreachable;
}
}
}
if (_target.ReturnType != typeof(void))
{
frame.Data[first] = ret;
frame.StackIndex = first + 1;
}
else
{
frame.StackIndex = first;
}
}
finally
{
if (args != null)
{
foreach (ByRefUpdater arg in _byrefArgs)
{
// -1: instance param, just copy back the exact instance invoked with, which
// gets passed by reference from reflection for value types.
arg.Update(frame, arg.ArgumentIndex == -1 ? instance : args[arg.ArgumentIndex]);
}
}
}
return 1;
}
}
}
| 32.322176 | 129 | 0.489579 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs | 15,450 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Hubble.Core.Service;
namespace Hubble.Core.StoredProcedure
{
class SP_AddSchema : StoredProcedure, IStoredProc, IHelper
{
#region IStoredProc Members
override public string Name
{
get
{
return "SP_AddSchema";
}
}
public void Run()
{
Global.UserRightProvider.CanDo(Right.RightItem.ManageDB);
if (Parameters.Count != 1)
{
throw new ArgumentException("Parameter 1 is Schema xml string. ");
}
string xmlStr = Parameters[0];
TaskManage.Schema schema = TaskManage.Schema.ConvertFromString(xmlStr);
ScheduleTaskMgr.ScheduleMgr.Add(schema);
OutputMessage(string.Format("Add schema successul, SchemaId={0}.", schema.SchemaId));
}
#endregion
#region IHelper Members
public string Help
{
get
{
return "Add a schema. Parameter 1 is schema xml string.";
}
}
#endregion
}
}
| 29.271429 | 98 | 0.612494 | [
"Apache-2.0"
] | aoaob/HubbleDotNet | C#/src/Hubble.Data/Hubble.Core/StoredProcedure/SP_AddSchema.cs | 2,051 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the greengrass-2017-06-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Greengrass.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Greengrass.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListFunctionDefinitions operation
/// </summary>
public class ListFunctionDefinitionsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListFunctionDefinitionsResponse response = new ListFunctionDefinitionsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Definitions", targetDepth))
{
var unmarshaller = new ListUnmarshaller<DefinitionInformation, DefinitionInformationUnmarshaller>(DefinitionInformationUnmarshaller.Instance);
response.Definitions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
}
return new AmazonGreengrassException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListFunctionDefinitionsResponseUnmarshaller _instance = new ListFunctionDefinitionsResponseUnmarshaller();
internal static ListFunctionDefinitionsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListFunctionDefinitionsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.758929 | 193 | 0.655711 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Greengrass/Generated/Model/Internal/MarshallTransformations/ListFunctionDefinitionsResponseUnmarshaller.cs | 4,229 | C# |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
namespace Butterfly.Db {
public enum TableIndexType {
Primary,
Unique,
Other
}
/// <summary>
/// Defines an index for a <see cref="Table"/>
/// </summary>
public class TableIndex {
public TableIndex(TableIndexType indexType, string[] fieldNames) {
this.IndexType = indexType;
this.FieldNames = fieldNames;
}
public TableIndexType IndexType {
get;
protected set;
}
public string[] FieldNames {
get;
protected set;
}
}
}
| 23.617647 | 74 | 0.56538 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | firesharkstudios/butterfly-db | Butterfly.Db/TableIndex.cs | 805 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Linq;
namespace Microsoft.CodeAnalysis.Interactive
{
internal readonly struct RemoteExecutionResult
{
internal sealed class Data
{
public bool Success;
public string[] SourcePaths = null!;
public string[] ReferencePaths = null!;
public string WorkingDirectory = null!;
public RemoteInitializationResult.Data? InitializationResult;
public RemoteExecutionResult Deserialize()
=> new RemoteExecutionResult(
Success,
SourcePaths.ToImmutableArray(),
ReferencePaths.ToImmutableArray(),
WorkingDirectory,
InitializationResult?.Deserialize());
}
public readonly bool Success;
/// <summary>
/// New value of source search paths after execution.
/// </summary>
public readonly ImmutableArray<string> SourcePaths;
/// <summary>
/// New value of reference search paths after execution.
/// </summary>
public readonly ImmutableArray<string> ReferencePaths;
/// <summary>
/// New value of working directory in the remote process after execution.
/// </summary>
public readonly string WorkingDirectory;
public readonly RemoteInitializationResult? InitializationResult;
public RemoteExecutionResult(
bool success,
ImmutableArray<string> sourcePaths,
ImmutableArray<string> referencePaths,
string workingDirectory,
RemoteInitializationResult? initializationResult)
{
Success = success;
SourcePaths = sourcePaths;
ReferencePaths = referencePaths;
WorkingDirectory = workingDirectory;
InitializationResult = initializationResult;
}
public Data Serialize()
=> new Data()
{
Success = Success,
SourcePaths = SourcePaths.ToArray(),
ReferencePaths = ReferencePaths.ToArray(),
WorkingDirectory = WorkingDirectory,
InitializationResult = InitializationResult?.Serialize(),
};
}
}
| 33.592105 | 81 | 0.611046 | [
"MIT"
] | 06needhamt/roslyn | src/Interactive/Host/Interactive/Core/RemoteExecutionResult.cs | 2,555 | C# |
namespace FlowDesign.Model.Components.SystemEnvironment
{
/// <summary>
/// Komponente für einen Actor.
/// </summary>
/// <seealso cref="FlowDesign.Model.Components.SystemEnvironment.SystemEnvironmentComponent" />
public class ActorComponent : SystemEnvironmentComponent
{
/// <summary>
/// Konstruktor.
/// </summary>
public ActorComponent()
{
this.SystemEnvType = SystemEnvComponentType.Actors;
}
}
}
| 27.388889 | 99 | 0.624746 | [
"MIT"
] | FlowDesign-HS-Esslingen/FlowDesignModelingTool | Source/FlowDesign.Model/Components/SystemEnvironment/ActorComponent.cs | 496 | C# |
using System;
using System.Linq;
using LinqToDB;
using LinqToDB.Mapping;
using NUnit.Framework;
namespace Tests.UserTests
{
using Model;
[TestFixture]
public class Issue307Tests : TestBase
{
[Table(Name = "Person")]
public class Entity307
{
private Entity307()
{
}
[Column("PersonID"), Identity, PrimaryKey]
public int ID { get; set; }
[Column]
public Gender Gender { get; set; }
[Column]
public String FirstName { get; private set; }
[Column]
public String MiddleName { get; set; }
[Column]
public String LastName { get; set; }
public void SetFirstName(string firstName)
{
FirstName = firstName;
}
public static Entity307 Create()
{
return new Entity307();
}
}
[Test]
public void Issue307Test([DataSources] string context)
{
using (var db = GetDataContext(context))
using (new DeletePerson(db))
{
var obj = Entity307.Create();
obj.SetFirstName("FirstName307");
obj.LastName = "LastName307";
var id1 = Convert.ToInt32(db.InsertWithIdentity(obj));
var obj2 = db.GetTable<Entity307>().First(_ => _.ID == id1);
Assert.IsNull(obj2.MiddleName);
Assert.AreEqual(obj.FirstName, obj2.FirstName);
}
}
}
}
| 17.942029 | 64 | 0.653473 | [
"MIT"
] | FrancisChung/linq2db | Tests/Linq/UserTests/Issue307Tests.cs | 1,240 | C# |
namespace MouseKeyboardActivityMonitor.WinApi
{
internal static class Messages
{
//values from Winuser.h in Microsoft SDK.
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
public const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
public const int WM_LBUTTONDOWN = 0x201;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
public const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
public const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
public const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
public const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
public const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
public const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
public const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
public const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
public const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// The WM_XBUTTONDOWN message is posted when the user presses the first or second X mouse
/// button.
/// </summary>
public const int WM_XBUTTONDOWN = 0x20B;
/// <summary>
/// The WM_XBUTTONUP message is posted when the user releases the first or second X mouse
/// button.
/// </summary>
public const int WM_XBUTTONUP = 0x20C;
/// <summary>
/// The WM_XBUTTONDBLCLK message is posted when the user double-clicks the first or second
/// X mouse button.
/// </summary>
/// <remarks>Only windows that have the CS_DBLCLKS style can receive WM_XBUTTONDBLCLK messages.</remarks>
public const int WM_XBUTTONDBLCLK = 0x20D;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a non-system
/// key is pressed. A non-system key is a key that is pressed when the ALT key is not pressed.
/// </summary>
public const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a non-system
/// key is released. A non-system key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
public const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
public const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
public const int WM_SYSKEYUP = 0x105;
}
}
| 42.77193 | 113 | 0.628384 | [
"MIT"
] | Behzadkhosravifar/BlackANT | Black ANT/MouseKeyboardActivityMonitor/WinApi/Messages.cs | 4,878 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace QuickTrack.Controllers
{
public class DispatchController : Controller
{
//
// GET: /Dispatch/
public ActionResult DispatchManagement()
{
return View ();
}
public ActionResult DispatchSchedule()
{
return View();
}
public ActionResult DispatchMonitoring()
{
return View ();
}
public ActionResult DispatchJobOrderTrans()
{
return View();
}
}
}
| 16.117647 | 48 | 0.640511 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/test/csharp/497c70dedc81708ad63d00dc4783a8f00b8958c5DispatchController.cs | 550 | C# |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using CsvHelper;
using Newtonsoft.Json;
using NLog;
using RestSharp;
namespace hubspot2s3
{
class Program
{
private static readonly NLog.Logger s_logger = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
var _config = new NLog.Config.LoggingConfiguration();
var _logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var _logconsole = new NLog.Targets.ConsoleTarget("logconsole");
_config.AddRule(LogLevel.Info, LogLevel.Fatal, _logconsole);
_config.AddRule(LogLevel.Debug, LogLevel.Fatal, _logfile);
NLog.LogManager.Configuration = _config;
Config.FromEnv();
Secrets.FromEnv();
Context.FromEnv();
Console.WriteLine($"This run is in mode: {Context.GetValue("run_mode")}");
HubSpot _hubSpot = new HubSpot(Secrets.GetValue("hubspot_basic_api_key"),
Secrets.GetValue("hubspot_oauth_access_token"));
S3 _s3File = new S3(Secrets.GetValue("aws_access_key_id"), Secrets.GetValue("aws_secret_access_key"),
Config.GetValue("s3_bucket_name"), Config.GetValue("s3_file_name"), Config.GetValue("s3_region_name"));
using (var _csv = new CsvReader(new StreamReader(_s3File.S3InputStream), CultureInfo.InvariantCulture))
{
_csv.Read();
_csv.ReadHeader();
while (_csv.Read())
{
if (bool.Parse(Config.GetValue("make_contact")))
{
var _dataRecord = Enumerable.ToList(_csv.GetRecord<dynamic>());
s_logger.Info($"Creating Contact: {string.Join(",", _dataRecord)}");
IRestResponse _resp = _hubSpot.Create("contacts", HubSpotContactFromRow(_csv));
s_logger.Info(_resp.StatusCode.ToString());
}
if (bool.Parse(Config.GetValue("make_company")))
{
var _dataRecord = Enumerable.ToList(_csv.GetRecord<dynamic>());
s_logger.Info($"Creating Company: {string.Join(",", _dataRecord)}");
IRestResponse _resp = _hubSpot.Create("companies", HubSpotCompanyFromRow(_csv));
s_logger.Info(_resp.StatusCode.ToString());
}
}
}
}
public static string HubSpotContactFromRow(CsvReader Record)
{
var _contact = new
{
properties = new[]
{
new { property = "email", value = Record.GetField<string>("email") },
new { property = "firstname", value = Record.GetField<string>("first_name") },
new { property = "lastname", value = Record.GetField<string>("last_name") },
new { property = "company", value = Record.GetField<string>("company") },
new { property = "city", value = Record.GetField<string>("city") },
new { property = "state", value = Record.GetField<string>("state") },
new { property = "country", value = Record.GetField<string>("country") },
new { property = "zip", value = Record.GetField<string>("zip") }
}
};
return JsonConvert.SerializeObject(_contact);
}
public static string HubSpotCompanyFromRow(CsvReader Record)
{
var _company = new
{
properties = new[]
{
new { name = "name", value = Record.GetField<string>("company") },
new { name = "description", value = Record.GetField<string>("desc") }
}
};
return JsonConvert.SerializeObject(_company);
}
}
} | 42.694737 | 123 | 0.542899 | [
"MIT"
] | EAHYoder/hubspot_to_s3 | csharp/hubspot2s3/Main.cs | 4,058 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ks.h(373,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct __struct_ks_176__union_0__struct_1
{
public IntPtr Semaphore;
public uint Reserved;
public int Adjustment;
}
}
| 24.466667 | 82 | 0.711172 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/__struct_ks_176__union_0__struct_1.cs | 369 | C# |
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using NewRelic.Agent.IntegrationTestHelpers;
using NewRelic.Agent.IntegrationTests.Shared;
using Xunit;
using Xunit.Abstractions;
namespace NewRelic.Agent.UnboundedIntegrationTests.MongoDB
{
abstract public class MongoDB2_6_DatabaseTests<T> : NewRelicIntegrationTest<T>
where T : RemoteServiceFixtures.MongoDB2_6ApplicationFixture
{
private readonly RemoteServiceFixtures.MongoDB2_6ApplicationFixture _fixture;
public MongoDB2_6_DatabaseTests(T fixture, ITestOutputHelper output) : base(fixture)
{
_fixture = fixture;
_fixture.TestLogger = output;
_fixture.Actions
(
exerciseApplication: () =>
{
_fixture.CreateCollection();
_fixture.CreateCollectionAsync();
_fixture.DropCollection();
_fixture.DropCollectionAsync();
_fixture.ListCollections();
_fixture.ListCollectionsAsync();
_fixture.RenameCollection();
_fixture.RenameCollectionAsync();
_fixture.RunCommand();
_fixture.RunCommandAsync();
}
);
_fixture.Initialize();
}
[Fact]
public void CheckForDatastoreInstanceMetrics()
{
var serverHost = CommonUtils.NormalizeHostname(MongoDbConfiguration.MongoDb26Server);
var m = _fixture.AgentLog.GetMetricByName($"Datastore/instance/MongoDB/{serverHost}/{MongoDbConfiguration.MongoDb26Port}");
Assert.NotNull(m);
}
[Fact]
public void CreateCollection()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/statement/MongoDB/createTestCollection/CreateCollection");
Assert.NotNull(m);
}
[Fact]
public void CreateCollectionAsync()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/statement/MongoDB/createTestCollectionAsync/CreateCollectionAsync");
Assert.NotNull(m);
}
[Fact]
public void DropCollection()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/statement/MongoDB/dropTestCollection/DropCollection");
Assert.NotNull(m);
}
[Fact]
public void DropCollectionAsync()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/statement/MongoDB/dropTestCollectionAsync/DropCollectionAsync");
Assert.NotNull(m);
}
[Fact]
public void ListCollections()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/ListCollections");
Assert.NotNull(m);
}
[Fact]
public void ListCollectionsAsync()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/ListCollectionsAsync");
Assert.NotNull(m);
}
[Fact]
public void RenameCollection()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/RenameCollection");
Assert.NotNull(m);
}
[Fact]
public void RenameCollectionAsync()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/RenameCollectionAsync");
Assert.NotNull(m);
}
[Fact]
public void RunCommand()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/RunCommand");
Assert.NotNull(m);
}
[Fact]
public void RunCommandAsync()
{
var m = _fixture.AgentLog.GetMetricByName("Datastore/operation/MongoDB/RunCommandAsync");
Assert.NotNull(m);
}
}
[NetFrameworkTest]
public class MongoDB2_6_FrameworkDatabaseTests : MongoDB2_6_DatabaseTests<RemoteServiceFixtures.MongoDB2_6FrameworkApplicationFixture>
{
public MongoDB2_6_FrameworkDatabaseTests(RemoteServiceFixtures.MongoDB2_6FrameworkApplicationFixture fixture, ITestOutputHelper output) : base(fixture, output)
{
}
}
[NetCoreTest]
public class MongoDB2_6_CoreDatabaseTests : MongoDB2_6_DatabaseTests<RemoteServiceFixtures.MongoDB2_6CoreApplicationFixture>
{
public MongoDB2_6_CoreDatabaseTests(RemoteServiceFixtures.MongoDB2_6CoreApplicationFixture fixture, ITestOutputHelper output) : base(fixture, output)
{
}
}
}
| 31.917808 | 167 | 0.627897 | [
"Apache-2.0"
] | SergeyKanzhelev/newrelic-dotnet-agent | tests/Agent/IntegrationTests/UnboundedIntegrationTests/MongoDB/MongoDB2_6_DatabaseTests.cs | 4,660 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using FluentAssertions;
using Nest;
using Tests.Core.Extensions;
namespace Tests.ClientConcepts.HighLevel.Inference.Equality
{
public class TaskIdEqualityTests
{
[U] public void Eq()
{
TaskId types = "node:1337";
TaskId[] equal = { "node:1337" };
foreach (var t in equal)
{
(t == types).ShouldBeTrue(t);
t.Should().Be(types);
}
}
[U] public void NotEq()
{
TaskId types = "node:1337";
TaskId[] notEqual = { "node:1338", " node:1337", "node:1337 ", "node:133", "node2:1337" };
foreach (var t in notEqual)
{
(t != types).ShouldBeTrue(t);
t.Should().NotBe(types);
}
}
[U] public void Null()
{
TaskId value = "node:1339";
(value == null).Should().BeFalse();
(null == value).Should().BeFalse();
}
}
}
| 23.454545 | 96 | 0.645349 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Tests/ClientConcepts/HighLevel/Inference/Equality/TaskIdEqualityTests.cs | 1,032 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Ambeth.TestUtil")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Ambeth.TestUtil")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7063b175-9c5d-4bbd-a26c-1ccdaa13bbae")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.405405 | 84 | 0.748065 | [
"Apache-2.0"
] | Dennis-Koch/ambeth | ambeth/Ambeth.TestUtil/Properties/AssemblyInfo.cs | 1,424 | C# |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
#if EF5
using System.Data.Objects;
#elif EF6
using System.Data.Entity.Core.Objects;
#elif EFCORE
using System.Linq;
#endif
namespace Z.EntityFramework.Plus
{
/// <summary>Class for query future value.</summary>
/// <typeparam name="T">The type of elements of the query.</typeparam>
#if QUERY_INCLUDEOPTIMIZED
internal class QueryFutureEnumerable<T> : BaseQueryFuture, IEnumerable<T>
#else
public class QueryFutureEnumerable<T> : BaseQueryFuture, IEnumerable<T>
#endif
{
/// <summary>The result of the query future.</summary>
private IEnumerable<T> _result;
/// <summary>Constructor.</summary>
/// <param name="ownerBatch">The batch that owns this item.</param>
/// <param name="query">
/// The query to defer the execution and to add in the batch of future
/// queries.
/// </param>
#if EF5 || EF6
public QueryFutureEnumerable(QueryFutureBatch ownerBatch, ObjectQuery<T> query)
#elif EFCORE
public QueryFutureEnumerable(QueryFutureBatch ownerBatch, IQueryable query)
#endif
{
OwnerBatch = ownerBatch;
Query = query;
}
/// <summary>Gets the enumerator of the query future.</summary>
/// <returns>The enumerator of the query future.</returns>
public IEnumerator<T> GetEnumerator()
{
if (!HasValue)
{
OwnerBatch.ExecuteQueries();
}
if (_result == null)
{
return new List<T>().GetEnumerator();
}
return _result.GetEnumerator();
}
/// <summary>Gets the enumerator of the query future.</summary>
/// <returns>The enumerator of the query future.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#if NET45
public async Task<List<T>> ToListAsync()
{
if (!HasValue)
{
await OwnerBatch.ExecuteQueriesAsync().ConfigureAwait(false);
}
if (_result == null)
{
return new List<T>();
}
using (var enumerator = _result.GetEnumerator())
{
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
return list;
}
}
public async Task<T[]> ToArrayAsync()
{
if (!HasValue)
{
await OwnerBatch.ExecuteQueriesAsync().ConfigureAwait(false);
}
if (_result == null)
{
return new T[0];
}
using (var enumerator = _result.GetEnumerator())
{
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
return list.ToArray();
}
}
public async Task<T> FirstOrDefaultAsync()
{
if (!HasValue)
{
await OwnerBatch.ExecuteQueriesAsync().ConfigureAwait(false);
}
if (_result == null)
{
return default(T);
}
using (var enumerator = _result.GetEnumerator())
{
enumerator.MoveNext();
return enumerator.Current;
}
}
#endif
/// <summary>Sets the result of the query deferred.</summary>
/// <param name="reader">The reader returned from the query execution.</param>
public override void SetResult(DbDataReader reader)
{
if (reader.GetType().FullName.Contains("Oracle"))
{
var reader2 = new QueryFutureOracleDbReader(reader);
reader = reader2;
}
var enumerator = GetQueryEnumerator<T>(reader);
SetResult(enumerator);
}
public void SetResult(IEnumerator<T> enumerator)
{
// Enumerate on all items
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
_result = list;
HasValue = true;
}
#if EFCORE
public override void ExecuteInMemory()
{
HasValue = true;
_result = ((IQueryable<T>) Query).ToList();
}
#endif
public override void GetResultDirectly()
{
var query = ((IQueryable<T>)Query);
GetResultDirectly(query);
}
internal void GetResultDirectly(IQueryable<T> query)
{
using (var enumerator = query.GetEnumerator())
{
SetResult(enumerator);
}
}
}
} | 29.041026 | 191 | 0.541762 | [
"MIT"
] | Dramikon/EntityFramework-Plus | src/shared/Z.EF.Plus.QueryFuture.Shared/QueryFutureEnumerable.cs | 5,666 | C# |
using System.Text;
using Konsole.Internal;
namespace Konsole.Forms
{
public class BoxWriter : IBoxWriter
{
private readonly IBoxStyle _lines;
private readonly int _width; // total width of the dialog, including lines
private readonly int _captionWidth; // width of the widest caption
private readonly int _textWidth; // space left over to display value text, taking into account space needed for seperator ' : '
private string _padding; // number of characters to pad with, normally 1.
private readonly int _insideWidth; // total width of the inside of the dialog, normally totalwidth -2
public BoxWriter(IBoxStyle lines, int width, int captionWidth, int padding)
{
_lines = lines;
_captionWidth = captionWidth;
_padding = new string(' ', padding);
_insideWidth = width - 2;
// textwidth = insideWidth - 3 (' : ') - captionWidth
_textWidth = _insideWidth - (captionWidth + 3);
_width = width;
}
public string Header(string title)
{
var sb = new StringBuilder();
// left line, 1 + title+ 1, right right
int linelen = (((_insideWidth ) - title.Length)/2) - 1;
var leftline = string.Format("{0}{1}",_lines.TL, new string(_lines.T,linelen));
var rightline = string.Format("{0}{1}", new string(_lines.T, linelen), _lines.TR);
string spacer = new string(' ', _insideWidth - (leftline.Length + title.Length + rightline.Length))+" ";
var topline = string.Format("{0}{1} {2}{3}{4}", _padding, leftline, title, spacer, rightline);
return topline;
}
public string Footer
{
get
{
return string.Format("{0}{1}{2}{3}", _padding, _lines.BL, new string(_lines.T, _insideWidth), _lines.BR);
}
}
public string Line
{
get
{
return string.Format("{0}{1}{2}{3}", _padding, _lines.LJ, new string(_lines.T, _insideWidth), _lines.RJ);
}
}
public string Write(string text)
{
// if text overflows, add in ellispses
string writeText = (text.Length > _insideWidth)
? text.Substring(0, _insideWidth - 3) + "..."
: text.FixLeft(_insideWidth);
return string.Format("{0}{1}{2}{3}", _padding, _lines.L, writeText, _lines.R);
}
}
} | 42.111111 | 144 | 0.543159 | [
"Apache-2.0"
] | johnmbaughman/konsole | Konsole/Forms/BoxWriter.cs | 2,653 | C# |
// Licensed under the Apache License, Version 2.0 (the "License").
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DevDecoder.HIDDevices;
using DevDecoder.HIDDevices.Controllers;
using DevDecoder.HIDDevices.Usages;
using DynamicData;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace HIDDevices.Sample.Samples
{
public class DependencyInjectionSample : Sample
{
/// <inheritdoc />
public override string Description =>
"Demonstrates configuration of controllers in a dependency injection scenario.";
/// <inheritdoc />
public override async Task ExecuteAsync(CancellationToken token = default)
{
// Create an example service provider (this may be done by your framework code already)
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// NOTE: ServiceProvider should be disposed asynchronously by most frameworks, however many examples don't show this,
// Devices also supports asynchronous disposal, and so should be disposed automatically by the service provider
// when it is disposed. If you create a Devices object yourself, also use await using to ensure correct disposal.
await using var serviceProvider = serviceCollection.BuildServiceProvider();
// Get the logger
var logger = serviceProvider.GetService<ILogger<DependencyInjectionSample>>();
// Grab the controllers service
var controllers = serviceProvider.GetService<Devices>()!;
// Subscribe to changes in controllers
using var subscription1 = controllers
.ControlUsagesAll(GenericDesktopPage.X, ButtonPage.Button9)
//.Connect()
.Subscribe(changeSet =>
{
var logBuilder = new StringBuilder();
logBuilder.AppendLine("Devices updated:");
var first = true;
foreach (var change in changeSet)
{
if (first)
{
first = false;
}
else
{
logBuilder.AppendLine(null);
}
var device = change.Current;
logBuilder.Append(" The ")
.Append(device)
.Append(" Device was ");
switch (change.Reason)
{
case ChangeReason.Add:
logBuilder.AppendLine("added.");
break;
case ChangeReason.Update:
logBuilder.AppendLine("updated.");
break;
case ChangeReason.Remove:
// Warning, the controller will be in the process of being disposed, so you should not access it's methods
// (ToString() is safe though, and is all that is being accessed above).
logBuilder.AppendLine("removed.");
break;
}
logBuilder.Append(" DevicePath: ")
.AppendLine(device.DevicePath)
.Append(" Usages: ")
.AppendLine(string.Join(", ", device.Usages))
.Append(" Controls: ")
.AppendLine(string.Join(", ", device.Keys));
}
logger.LogInformation(logBuilder.ToString());
});
// Subscribe to all button control changes
var batch = 0;
using var subscription2 = controllers
// Watch for control changes only
.ControlChanges()
.Subscribe(changes =>
{
// Log the changes and look for a press of Button 1 on any controller.
var logBuilder = new StringBuilder();
logBuilder.Append("Batch ").Append(++batch).AppendLine(":");
foreach (var group in changes.GroupBy(c => c.Control.Device))
{
logBuilder.Append(" ").Append(group.Key).AppendLine(":");
foreach (var change in group)
{
logBuilder
.Append(" ")
.Append(change.Control.Name)
.Append(": ")
.Append(change.PreviousValue.ToString("F3"))
.Append(" -> ")
.Append(change.Value.ToString("F3"))
.Append(" (")
.Append(change.Elapsed.TotalMilliseconds.ToString("0.###"))
.AppendLine("ms)");
}
}
logger.LogInformation(logBuilder.ToString());
});
// Subscribe to just button 1 change events, and trigger a task completion source when any are pressed.
var button0PressedTcs = new TaskCompletionSource<bool>();
using var subscription3 = controllers
// Watch for button one changes only
.ControlChanges(c => c.ButtonNumber == 0)
//&& !c.Device.Usages.Contains(65538u))
.Subscribe(changes =>
{
if (changes.Any(c => c.Value > 0.5))
{
button0PressedTcs.TrySetResult(true);
}
});
// Subscribe to a specific controller type
var gamepadBatch = 0;
using var gamepadSubscription = controllers
.Controllers<Gamepad>()
.Do(gamepad =>
{
var logBuilder = new StringBuilder();
logBuilder.Append(gamepad.Name)
.AppendLine(" found! Following controls were mapped:");
foreach (var (control, infos) in gamepad.Mapping)
{
logBuilder.Append(" ")
.Append(control.Name)
.Append(" => ")
.AppendLine(string.Join(", ", infos.Select(info => info.PropertyName)));
}
logger.LogInformation(logBuilder.ToString());
// Connect the gamepad, so we can start listening for changes.
gamepad.Connect();
})
.SelectMany(gamepad => gamepad.Changes)
.Subscribe(changes =>
{
var logBuilder = new StringBuilder();
logBuilder.Append("Gamepad Batch ").Append(++gamepadBatch).AppendLine(":");
foreach (var change in changes)
{
var valueStr = change.Value switch
{
bool b => b ? "Pressed" : "Not Pressed",
double d => d.ToString("F3"),
null => "<null>",
_ => change.Value.ToString()
};
logBuilder.Append(" ")
.Append(change.PropertyName)
.Append(": ")
.Append(valueStr)
.Append(" (")
.AppendFormat("{0:F3}", change.Elapsed.TotalMilliseconds)
.AppendLine("ms)");
}
logger.LogInformation(logBuilder.ToString());
});
logger.LogInformation("Press Button 1 on any device to exit!");
// Wait on signal that Button 1 has been pressed
await button0PressedTcs.Task.ConfigureAwait(false);
logger.LogInformation("Finished");
}
private static void ConfigureServices(IServiceCollection services) =>
// Configure logging and add the Devices service as a singleton.
services
.AddLogging(configure => configure.AddConsole())
.AddSingleton<Devices>();
}
}
| 43.778325 | 138 | 0.473613 | [
"Apache-2.0"
] | DevDecoder/HIDControllers | HIDDevices.Sample/Samples/DependencyInjectionSample.cs | 8,889 | C# |
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Sce.Atf.Controls.PropertyEditing
{
/// <summary>
/// UITypeEditor to handle dynamic flag "enumerations"</summary>
public class FlagsUITypeEditor : UITypeEditor, IAnnotatedParams
{
/// <summary>
/// Default constructor</summary>
public FlagsUITypeEditor()
{
}
/// <summary>
/// Constructor with flag names</summary>
/// <param name="names">Array of flag definitions, such as "FlagA=2", or just the name, as in "FlagA"</param>
/// <remarks>Flag values default to successive powers of 2, starting with 1</remarks>
public FlagsUITypeEditor(string[] names)
{
DefineFlags(names);
}
/// <summary>
/// Constructor with flag names and values</summary>
/// <param name="names">Array of flag names, such as "FlagNameA". Specifying the value in the string
/// (as in "FlagNameA=2") is not allowed.</param>
/// <param name="values">Flag values array</param>
public FlagsUITypeEditor(string[] names, int[] values)
{
DefineFlags(names, values);
}
/// <summary>
/// Defines the flag names and values</summary>
/// <param name="definitions">Flag definitions array</param>
/// <remarks>Flag values default to successive powers of 2, starting with 1. Flag names
/// with the format "FlagName=X" are parsed so that FlagName gets the value X, where X is
/// an int.</remarks>
public void DefineFlags(string[] definitions)
{
EnumUtil.ParseFlagDefinitions(definitions, out m_names, out m_displayNames, out m_values);
}
/// <summary>
/// Defines the flag names and values</summary>
/// <param name="names">Flag names array</param>
/// <param name="values">Flag values array</param>
public void DefineFlags(string[] names, int[] values)
{
if (names == null || values == null || names.Length != values.Length)
throw new ArgumentException("names and/or values null, or of unequal length");
m_names = names;
m_displayNames = names;
m_values = values;
}
/// <summary>
/// Gets the editor style used by the System.Drawing.Design.UITypeEditor.EditValue(
/// System.IServiceProvider,System.Object) method</summary>
/// <param name="context">An System.ComponentModel.ITypeDescriptorContext that can be used to gain
/// additional context information</param>
/// <returns>A System.Drawing.Design.UITypeEditorEditStyle value that indicates the style
/// of editor used by the System.Drawing.Design.UITypeEditor.EditValue(System.IServiceProvider,System.Object)
/// method. If the System.Drawing.Design.UITypeEditor does not support this method,
/// System.Drawing.Design.UITypeEditor.GetEditStyle() returns System.Drawing.Design.UITypeEditorEditStyle.None.</returns>
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
/// <summary>
/// Edits the specified object's value using the editor style indicated by the
/// System.Drawing.Design.UITypeEditor.GetEditStyle() method</summary>
/// <param name="context">An System.ComponentModel.ITypeDescriptorContext that can be used to gain
/// additional context information</param>
/// <param name="provider">An System.IServiceProvider that this editor can use to obtain services</param>
/// <param name="value">The object to edit</param>
/// <returns>The new value of the object. If the value of the object has not changed, this should
/// return the same object it was passed.</returns>
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
m_editorService =
provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
if (m_editorService != null)
{
CheckedListBox checkedListBox = new CheckedListBox();
checkedListBox.CheckOnClick = true;
foreach (string displayName in m_displayNames)
checkedListBox.Items.Add(displayName);
// size control so all strings are completely visible
using (System.Drawing.Graphics g = checkedListBox.CreateGraphics())
{
float width = 0f;
foreach (string displayName in m_displayNames)
{
float w = g.MeasureString(displayName, checkedListBox.Font).Width;
width = Math.Max(width, w);
}
float height = m_displayNames.Length * checkedListBox.ItemHeight;
int scrollBarThickness = SystemInformation.VerticalScrollBarWidth;
if (height > checkedListBox.Height - 4) // vertical scrollbar?
width += SystemInformation.VerticalScrollBarWidth;
if (width > checkedListBox.Width)
checkedListBox.Width = (int)width + 31; // magic number from Windows.Forms dll
}
if (value is string)
FillCheckedListBoxFromString(value, checkedListBox);
else if (value is int)
FillCheckedListBoxFromInt(value, checkedListBox);
// otherwise, ignore value
m_editorService.DropDownControl(checkedListBox);
object newValue;
if (value is string)
newValue = ExtractStringFromCheckedListBox(checkedListBox);
else
newValue = ExtractIntFromCheckedListBox(checkedListBox);
// be careful to return the same object if the value didn't change
if (!newValue.Equals(value))
value = newValue;
}
return value;
}
#region IAnnotatedParams Members
/// <summary>
/// Initializes the control</summary>
/// <param name="parameters">Editor parameters</param>
public void Initialize(string[] parameters)
{
DefineFlags(parameters);
}
#endregion
private object ExtractIntFromCheckedListBox(CheckedListBox checkedListBox)
{
CheckedListBox.CheckedIndexCollection indices = checkedListBox.CheckedIndices;
int intValue = 0;
foreach (int index in indices)
intValue |= m_values[index];
return intValue;
}
private object ExtractStringFromCheckedListBox(CheckedListBox checkedListBox)
{
CheckedListBox.CheckedIndexCollection indices = checkedListBox.CheckedIndices;
StringBuilder sb = new StringBuilder();
foreach (int index in indices)
{
sb.Append(m_names[index]);
sb.Append("|");
}
if (sb.Length > 0)
sb.Length--; // trim last "|"
else
sb.Append(NoFlags);
return sb.ToString();
}
private void FillCheckedListBoxFromInt(object value, CheckedListBox listBox)
{
int flags = (int)value;
for (int i = 0; i < m_values.Length; ++i)
{
bool isChecked = (flags & m_values[i]) == m_values[i];
listBox.SetItemChecked(i, isChecked);
}
}
private void FillCheckedListBoxFromString(object obj, CheckedListBox listBox)
{
string value = obj.ToString();
if (value == NoFlags)
return;
char[] delimiters = new[] { '|', ';', ',', ':' };
string[] flags = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
foreach (string flag in flags)
{
for (int i = 0; i < m_names.Length; i++)
{
if (flag == m_names[i])
{
listBox.SetItemChecked(i, true);
break;
}
}
}
}
private string[] m_names;
private string[] m_displayNames;
private int[] m_values;
private IWindowsFormsEditorService m_editorService;
private static readonly string NoFlags = "(none)".Localize("No flags");
}
}
| 41.224215 | 134 | 0.570434 | [
"Apache-2.0"
] | RedpointGames/Protogame.LevelEditor | ATF/Framework/Atf.Gui.WinForms/Controls/PropertyEditing/FlagsUITypeEditor.cs | 8,974 | C# |
#if !NOFILEIO
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBitcoin.BitcoinCore
{
[Obsolete]
public class DataDirectory
{
private readonly string _Folder;
public string Folder
{
get
{
return _Folder;
}
}
private readonly Network _Network;
public Network Network
{
get
{
return _Network;
}
}
public DataDirectory(string dataFolder, Network network)
{
EnsureExist(dataFolder);
this._Folder = dataFolder;
this._Network = network;
}
private void EnsureExist(string folder)
{
if(!Directory.Exists(folder))
Directory.CreateDirectory(folder);
}
}
}
#endif | 17.066667 | 59 | 0.66276 | [
"MIT"
] | ChekaZ/NBitcoin | NBitcoin/BitcoinCore/DataDirectory.cs | 770 | C# |
using HotelManagementApp.Models;
using HotelManagementApp.Models.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HotelManagementApp.Services
{
public class ApartTypeService
{
private readonly ApplicationDbContext _db;
private readonly ILogger _logger;
public ApartTypeService(ApplicationDbContext db, ILogger<ApartTypeService> logger)
{
this._db = db;
this._logger = logger;
}
public async Task<List<ApartTypeModel>> GetAllTypes()
{
return await _db.ApartTypes.ToListAsync();
}
}
} | 23.884615 | 84 | 0.78905 | [
"Unlicense"
] | Dasik/HotelManagementApp | HotelManagementApp/Services/ApartTypeService.cs | 623 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public float health=20f;
public void Damage(float amount)
{
health-=amount;
if(health==0)
{
destroy();
}
}
void destroy()
{
Destroy(gameObject);
}
}
| 15.391304 | 36 | 0.564972 | [
"MIT"
] | ayush4602/Calico-Ghost-Town | Assets/Scripts/Health.cs | 354 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using FluentValidation;
using MediatR;
using WeatherForecast.Application.Interfaces;
namespace WeatherForecast.Application.Commands.SubmitWeatherForecast
{
public class SubmitWeatherForecastCommand : IRequest<bool>
{
/// <summary>
/// The local date time of the forecast
/// </summary>
public DateTime LocalDateTime { get; set; }
/// <summary>
/// The forecast summary
/// </summary>
public string Summary { get; set; }
/// <summary>
/// The temperature in Celsius
/// </summary>
public int TemperatureC { get; set; }
public class Validator : AbstractValidator<SubmitWeatherForecastCommand>
{
public Validator()
{
RuleFor(x => x.LocalDateTime)
.NotNull()
.GreaterThanOrEqualTo(DateTime.Today);
RuleFor(x => x.Summary)
.NotEmpty()
.MaximumLength(50);
RuleFor(x => x.TemperatureC)
.NotNull();
}
}
public class Handler : IRequestHandler<SubmitWeatherForecastCommand, bool>
{
private readonly IMapper _mapper;
private readonly IWeatherForecastApiClient _weatherForecastApiClient;
public Handler(IMapper mapper, IWeatherForecastApiClient weatherForecastApiClient)
{
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_weatherForecastApiClient = weatherForecastApiClient ?? throw new ArgumentNullException(nameof(weatherForecastApiClient));
}
/// <inheritdoc />
public async Task<bool> Handle(SubmitWeatherForecastCommand request, CancellationToken cancellationToken)
{
var forecastToSubmit = _mapper.Map<ForecastDto>(request);
var result = await _weatherForecastApiClient.SubmitForecastAsync(forecastToSubmit, cancellationToken);
return result;
}
}
}
}
| 34.661538 | 139 | 0.58411 | [
"MIT"
] | draekien/Draekien.CleanVerticalSlice.Template | Features/WeatherForecast/Src/WeatherForecast.Application/Commands/SubmitWeatherForecast/SubmitWeatherForecastCommand.cs | 2,255 | C# |
#region Using Statements
using System;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;
#endregion
namespace Delight
{
/// <summary>
/// Interface for ensuring initialize method is called once on object construction.
/// </summary>
public interface IInitialize
{
void AfterInitialize();
}
}
| 19.944444 | 88 | 0.707521 | [
"MIT"
] | MUDV587/Delight | UnityProject/Delight/Assets/Delight/Source/IInitialize.cs | 361 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("82665e88-abbe-4468-9b30-769913b45f23")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер построения
// Редакция
//
// Можно задать все значения или принять номер построения и номер редакции по умолчанию,
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.378378 | 100 | 0.745649 | [
"MIT"
] | Panda-Lewandowski/DataBase | Tickets DB/10/10/ConsoleApplication1/ConsoleApplication1/Properties/AssemblyInfo.cs | 2,066 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace StarkPlatform.Compiler.Operations
{
/// <summary>
/// Represents a reference to a method other than as the target of an invocation.
/// <para>
/// Current usage:
/// (1) C# method reference expression.
/// (2) VB method reference expression.
/// </para>
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
public interface IMethodReferenceOperation : IMemberReferenceOperation
{
/// <summary>
/// Referenced method.
/// </summary>
IMethodSymbol Method { get; }
/// <summary>
/// Indicates whether the reference uses virtual semantics.
/// </summary>
bool IsVirtual { get; }
}
}
| 32.193548 | 161 | 0.623246 | [
"BSD-2-Clause",
"MIT"
] | encrypt0r/stark | src/compiler/StarkPlatform.Compiler/Operations/IMethodReferenceOperation.cs | 1,000 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using EntityWorker.Core.InterFace;
using EntityWorker.Core.Object.Library;
using EntityWorker.Core.Interface;
using EntityWorker.Core.Object.Library.DbWrapper;
using FastDeepCloner;
namespace EntityWorker.Core.Helper
{
/// <summary>
/// UseFull Methods
/// </summary>
public static class MethodHelper
{
///// <summary>
///// Get All types that containe Property with PrimaryKey Attribute
///// </summary>
///// <param name="assembly"></param>
///// <returns></returns>
public static List<Type> GetDbEntitys(Assembly assembly) => assembly?.DefinedTypes.Where(type => type.GetPrimaryKey() != null).Cast<Type>().ToList();
/// <summary>
/// Convert Value from Type to Type
/// when fail a default value will be loaded.
/// can handle all known types like datetime, time span, string, long etc
/// ex
/// "1115rd" to int? will return null
/// "152" to int? 152
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
///
public static T ConvertValue<T>(this object value) => (T)ConvertValue(value, typeof(T));
/// <summary>
/// Convert Value from Type to Type
/// when fail a default value will be loaded.
/// can handle all known types like datetime, time span, string, long etc
/// ex
/// "1115rd" to int? will return null
/// "152" to int? 152
/// </summary>
/// <param name="value"></param>
/// <param name="toType"></param>
/// <returns></returns>
public static object ConvertValue(this object value, Type toType)
{
var data = new LightDataTable();
data.AddColumn("value", toType, value);
data.AddRow(new object[1] { value });
return data.Rows.First().TryValueAndConvert(toType, "value", true);
}
/// <summary>
/// Convert String ToBase64String
/// </summary>
/// <param name="stringToEncode"></param>
/// <returns></returns>
public static string EncodeStringToBase64(string stringToEncode)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToEncode));
}
/// <summary>
/// Convert Base64String To String
/// </summary>
/// <param name="stringToDecode"></param>
/// <returns></returns>
public static string DecodeStringFromBase64(string stringToDecode)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(stringToDecode));
}
private static Regex stringExp = new Regex(@"String\[.*?\]|String\[.?\]");
private static Regex dateExp = new Regex(@"Date\[.*?\]|Date\[.?\]");
private static Regex guidExp = new Regex(@"Guid\[.*?\]|Guid\[.?\]");
private static Regex decimalExp = new Regex(@"Decimal\[.*?\]|Decimal\[.?\]");
internal static ISqlCommand ProcessSql(this IRepository repository, TransactionSqlConnection connection, IDbTransaction tran, string sql)
{
var i = 1;
var dicCols = new SafeValueType<string, Tuple<object, SqlDbType>>();
MatchCollection matches = null;
while ((matches = stringExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"String\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
var v = str.ConvertValue<string>();
if (string.Equals(v, "null", StringComparison.OrdinalIgnoreCase))
v = null;
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(v, SqlDbType.NVarChar));
i++;
}
while ((matches = dateExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Date\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<DateTime?>(), SqlDbType.DateTime));
i++;
}
while ((matches = guidExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Guid\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<Guid?>(), SqlDbType.UniqueIdentifier));
i++;
}
while ((matches = decimalExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Decimal\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<decimal?>(), SqlDbType.Decimal));
i++;
}
sql = sql.CleanValidSqlName(repository.DataBaseTypes);
DbCommand cmd = null;
try
{
switch (repository.DataBaseTypes)
{
case DataBaseTypes.Mssql:
cmd = tran != null ?
"System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
case DataBaseTypes.PostgreSql:
cmd = tran != null ?
"Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
case DataBaseTypes.Sqllight:
cmd = tran != null ?
"System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
}
}
catch (Exception e)
{
switch (repository.DataBaseTypes)
{
case DataBaseTypes.Mssql:
throw new EntityException($"Please make sure that nuget 'System.Data.SqlClient' is installed \n orginal exception: \n {e.Message}");
case DataBaseTypes.PostgreSql:
throw new EntityException($"Please make sure that nuget 'Npgsql' is installed \n orginal exception: \n {e.Message}");
case DataBaseTypes.Sqllight:
throw new EntityException($"Please make sure that nuget 'System.Data.SQLite' is installed \n orginal exception: \n {e.Message}");
}
}
var dbCommandExtended = new DbCommandExtended(cmd, repository);
foreach (var dic in dicCols)
{
dbCommandExtended.AddInnerParameter(dic.Key, dic.Value.Item1);
}
return dbCommandExtended;
}
}
}
| 43.91623 | 184 | 0.54733 | [
"MIT"
] | AlenToma/EntityWorker.Core | Source/EntityWorker.Core/Helper/MethodHelper.cs | 8,390 | C# |
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
namespace NotaFiscalNet.Core.Transmissao
{
/// <summary>
/// Representa o Retorno da Consulta de Recibo de Entrega de Lote de Notas Fiscais Eletrônicas.
/// </summary>
public sealed class RetornoConsultaRecibo
{
public RetornoConsultaRecibo(string xmlRetornoConsultaRecibo)
{
this.Xml = xmlRetornoConsultaRecibo;
using (StringReader reader = new StringReader(xmlRetornoConsultaRecibo))
{
XPathDocument xdoc = new XPathDocument(reader);
XPathNavigator navigator = xdoc.CreateNavigator();
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
ns.AddNamespace("nfe", Constants.NamespacePortalFiscalNFe);
XPathNavigator rootNode = navigator.SelectSingleNode("/nfe:retConsReciNFe", ns);
// versão do leiaute de retorno
this.VersaoLeiaute = rootNode.SelectSingleNode("@versao", ns).Value;
// tpAmb
this.Ambiente = (TipoAmbiente)rootNode.SelectSingleNode("nfe:tpAmb", ns).ValueAsInt;
// verAplic
this.VersaoAplicacao = rootNode.SelectSingleNode("nfe:verAplic", ns).Value;
// nRec
this.NumeroRecibo = rootNode.SelectSingleNode("nfe:nRec", ns).ValueAsLong;
// cStat
this.Status = rootNode.SelectSingleNode("nfe:cStat", ns).Value;
// xMotivo
this.Motivo = rootNode.SelectSingleNode("nfe:xMotivo", ns).Value;
// cUF
this.UFIBGE = (UfIBGE)rootNode.SelectSingleNode("nfe:cUF", ns).ValueAsInt;
this.Protocolos = new ProtocoloStatusProcessamentoCollection();
// protNFe
XPathNodeIterator protNFeIterator = rootNode.Select("nfe:protNFe", ns);
if (protNFeIterator != null)
{
foreach (XPathNavigator nav in protNFeIterator)
{
ProtocoloStatusProcessamento protocolo = new ProtocoloStatusProcessamento(nav, ns);
this.Protocolos.Add(protocolo);
}
}
}
}
/// <summary>
/// Retorna ou define o xml no qual a instância representa.
/// </summary>
private string Xml { get; set; }
/// <summary>
/// Retorna o valor indicando o tipo de ambiente que o retorno se refere.
/// </summary>
public TipoAmbiente Ambiente { get; private set; }
/// <summary>
/// Retorna a versão do leiaute de retorno do recibo.
/// </summary>
public string VersaoLeiaute { get; private set; }
/// <summary>
/// Retorna a versão da aplicação que processa o lote.
/// </summary>
public string VersaoAplicacao { get; private set; }
/// <summary>
/// Retorna o código do status de envio do lote.
/// </summary>
public string Status { get; private set; }
/// <summary>
/// Retorna a descrição referente ao código do status de envio do lote.
/// </summary>
public string Motivo { get; private set; }
/// <summary>
/// Retorna a código da UF IBGE onde o lote foi entregue.
/// </summary>
public UfIBGE UFIBGE { get; private set; }
/// <summary>
/// Retorna o número do recibo consultado.
/// </summary>
public long NumeroRecibo { get; private set; }
/// <summary>
/// Retorna a lista de Protocolos referente as Notas Fiscais Eletrônicas contidas no lote.
/// </summary>
public ProtocoloStatusProcessamentoCollection Protocolos { get; private set; }
/// <summary>
/// Salva o recibo de entrega do Lote de Notas Fiscais Eletrônicas em um arquivo xml.
/// </summary>
/// <remarks>O arquivo terá o seguinte nome: [NúmeroRecibo]-rec.xml.</remarks>
/// <param name="caminho">Caminho onde o arquivo será salvo.</param>
public void SalvarXml(string caminho)
{
//string path = Path.Combine(caminho, this.NumeroRecibo.ToString() + "-rec.xml");
// TODO: Terminar
throw new NotImplementedException();
}
}
} | 36.418033 | 107 | 0.577538 | [
"MIT"
] | NotaFiscalNet/NotaFiscalNet | src/NotaFiscalNet.Core/Transmissao/RetornoConsultaRecibo.cs | 4,463 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Assignment01.Account {
public partial class Manage {
/// <summary>
/// successMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder successMessage;
/// <summary>
/// ChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink ChangePassword;
/// <summary>
/// CreatePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink CreatePassword;
/// <summary>
/// PhoneNumber control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label PhoneNumber;
}
}
| 33.942308 | 84 | 0.52238 | [
"MIT"
] | luizerico/Comp229-2016-Assignment-01 | Assignment01/Assignment01/Account/Manage.aspx.designer.cs | 1,767 | C# |
using Com.Danliris.Service.Packing.Inventory.Data.Models.Master;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.IdentityProvider;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Com.Moonlay.Models;
namespace Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.Master
{
public class WeftTypeRepository : IWeftTypeRepository
{
private const string UserAgent = "Repository";
private readonly PackingInventoryDbContext _dbContext;
private readonly IIdentityProvider _identityProvider;
private readonly DbSet<WeftTypeModel> _dbSet;
public WeftTypeRepository(PackingInventoryDbContext dbContext, IServiceProvider serviceProvider)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<WeftTypeModel>();
_identityProvider = serviceProvider.GetService<IIdentityProvider>();
}
public Task<int> DeleteAsync(int id)
{
var model = _dbSet.FirstOrDefault(s => s.Id == id);
model.FlagForDelete(_identityProvider.Username, UserAgent);
_dbSet.Update(model);
return _dbContext.SaveChangesAsync();
}
public int GetCodeByType(string type)
{
var data = _dbSet.FirstOrDefault(s => s.Type == type);
if (data == null)
{
return 0;
}
else
{
return Convert.ToInt32(data.Code);
}
}
public IQueryable<WeftTypeModel> GetDbSet()
{
return _dbSet;
}
public Task<int> InsertAsync(WeftTypeModel model)
{
model.FlagForCreate(_identityProvider.Username, UserAgent);
_dbSet.Add(model);
return _dbContext.SaveChangesAsync();
}
public Task<int> MultipleInsertAsync(IEnumerable<WeftTypeModel> models)
{
foreach(var model in models)
{
model.FlagForCreate(_identityProvider.Username, UserAgent);
_dbSet.Add(model);
}
return _dbContext.SaveChangesAsync();
}
public IQueryable<WeftTypeModel> ReadAll()
{
return _dbSet.AsNoTracking();
}
public Task<WeftTypeModel> ReadByIdAsync(int id)
{
return _dbSet.FirstOrDefaultAsync(s => s.Id == id);
}
public Task<int> UpdateAsync(int id, WeftTypeModel model)
{
var modelToUpdate = _dbSet.FirstOrDefault(s => s.Id == id);
modelToUpdate.SetType(model.Type, _identityProvider.Username, UserAgent);
modelToUpdate.SetCode(model.Code, _identityProvider.Username, UserAgent);
return _dbContext.SaveChangesAsync();
}
}
}
| 31.210526 | 104 | 0.624283 | [
"MIT"
] | AndreaZain/com-danliris-service-packing-inventory | src/Com.Danliris.Service.Packing.Inventory.Infrastructure/Repositories/Master/WeftTypeRepository.cs | 2,967 | C# |
// this code is borrowed from RxOfficial(rx.codeplex.com) and modified
#if (NET_4_6)
using System;
using System.Threading.Tasks;
using System.Threading;
namespace UniRx
{
/// <summary>
/// Provides a set of static methods for converting tasks to observable sequences.
/// </summary>
public static class TaskObservableExtensions
{
/// <summary>
/// Returns an observable sequence that signals when the task completes.
/// </summary>
/// <param name="task">Task to convert to an observable sequence.</param>
/// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
/// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
/// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
public static IObservable<Unit> ToObservable(this Task task)
{
if (task == null)
throw new ArgumentNullException("task");
return ToObservableImpl(task, null);
}
/// <summary>
/// Returns an observable sequence that signals when the task completes.
/// </summary>
/// <param name="task">Task to convert to an observable sequence.</param>
/// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
/// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
/// <exception cref="ArgumentNullException"><paramref name="task"/> is null or <paramref name="scheduler"/> is null.</exception>
/// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
public static IObservable<Unit> ToObservable(this Task task, IScheduler scheduler)
{
if (task == null)
throw new ArgumentNullException("task");
if (scheduler == null)
throw new ArgumentNullException("scheduler");
return ToObservableImpl(task, scheduler);
}
private static IObservable<Unit> ToObservableImpl(Task task, IScheduler scheduler)
{
var res = default(IObservable<Unit>);
if (task.IsCompleted)
{
scheduler = scheduler ?? Scheduler.Immediate;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
res = Observable.Return<Unit>(Unit.Default, scheduler);
break;
case TaskStatus.Faulted:
res = Observable.Throw<Unit>(task.Exception.InnerException, scheduler);
break;
case TaskStatus.Canceled:
res = Observable.Throw<Unit>(new TaskCanceledException(task), scheduler);
break;
}
}
else
{
//
// Separate method to avoid closure in synchronous completion case.
//
res = ToObservableSlow(task, scheduler);
}
return res;
}
private static IObservable<Unit> ToObservableSlow(Task task, IScheduler scheduler)
{
var subject = new AsyncSubject<Unit>();
var options = GetTaskContinuationOptions(scheduler);
task.ContinueWith(t => ToObservableDone(task, subject), options);
return ToObservableResult(subject, scheduler);
}
private static void ToObservableDone(Task task, IObserver<Unit> subject)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
subject.OnNext(Unit.Default);
subject.OnCompleted();
break;
case TaskStatus.Faulted:
subject.OnError(task.Exception.InnerException);
break;
case TaskStatus.Canceled:
subject.OnError(new TaskCanceledException(task));
break;
}
}
/// <summary>
/// Returns an observable sequence that propagates the result of the task.
/// </summary>
/// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
/// <param name="task">Task to convert to an observable sequence.</param>
/// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
/// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
/// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task)
{
if (task == null)
throw new ArgumentNullException("task");
return ToObservableImpl(task, null);
}
/// <summary>
/// Returns an observable sequence that propagates the result of the task.
/// </summary>
/// <typeparam name="TResult">The type of the result produced by the task.</typeparam>
/// <param name="task">Task to convert to an observable sequence.</param>
/// <param name="scheduler">Scheduler on which to notify observers about completion, cancellation or failure.</param>
/// <returns>An observable sequence that produces the task's result, or propagates the exception produced by the task.</returns>
/// <exception cref="ArgumentNullException"><paramref name="task"/> is null or <paramref name="scheduler"/> is null.</exception>
/// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync{TResult}(Func{CancellationToken, Task{TResult}})"/> instead.</remarks>
public static IObservable<TResult> ToObservable<TResult>(this Task<TResult> task, IScheduler scheduler)
{
if (task == null)
throw new ArgumentNullException("task");
if (scheduler == null)
throw new ArgumentNullException("scheduler");
return ToObservableImpl(task, scheduler);
}
private static IObservable<TResult> ToObservableImpl<TResult>(Task<TResult> task, IScheduler scheduler)
{
var res = default(IObservable<TResult>);
if (task.IsCompleted)
{
scheduler = scheduler ?? Scheduler.Immediate;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
res = Observable.Return<TResult>(task.Result, scheduler);
break;
case TaskStatus.Faulted:
res = Observable.Throw<TResult>(task.Exception.InnerException, scheduler);
break;
case TaskStatus.Canceled:
res = Observable.Throw<TResult>(new TaskCanceledException(task), scheduler);
break;
}
}
else
{
//
// Separate method to avoid closure in synchronous completion case.
//
res = ToObservableSlow(task, scheduler);
}
return res;
}
private static IObservable<TResult> ToObservableSlow<TResult>(Task<TResult> task, IScheduler scheduler)
{
var subject = new AsyncSubject<TResult>();
var options = GetTaskContinuationOptions(scheduler);
task.ContinueWith(t => ToObservableDone(task, subject), options);
return ToObservableResult(subject, scheduler);
}
private static void ToObservableDone<TResult>(Task<TResult> task, IObserver<TResult> subject)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
subject.OnNext(task.Result);
subject.OnCompleted();
break;
case TaskStatus.Faulted:
subject.OnError(task.Exception.InnerException);
break;
case TaskStatus.Canceled:
subject.OnError(new TaskCanceledException(task));
break;
}
}
private static TaskContinuationOptions GetTaskContinuationOptions(IScheduler scheduler)
{
var options = TaskContinuationOptions.None;
if (scheduler != null)
{
//
// We explicitly don't special-case the immediate scheduler here. If the user asks for a
// synchronous completion, we'll try our best. However, there's no guarantee due to the
// internal stack probing in the TPL, which may cause asynchronous completion on a thread
// pool thread in order to avoid stack overflows. Therefore we can only attempt to be more
// efficient in the case where the user specified a scheduler, hence we know that the
// continuation will trigger a scheduling operation. In case of the immediate scheduler,
// it really becomes "immediate scheduling" wherever the TPL decided to run the continuation,
// i.e. not necessarily where the task was completed from.
//
options |= TaskContinuationOptions.ExecuteSynchronously;
}
return options;
}
private static IObservable<TResult> ToObservableResult<TResult>(AsyncSubject<TResult> subject, IScheduler scheduler)
{
if (scheduler != null)
{
return subject.ObserveOn(scheduler);
}
else
{
return subject.AsObservable();
}
}
/// <summary>
/// Returns a task that will receive the last value or the exception produced by the observable sequence.
/// </summary>
/// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
/// <param name="observable">Observable sequence to convert to a task.</param>
/// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable)
{
if (observable == null)
throw new ArgumentNullException("observable");
return observable.ToTask(new CancellationToken(), null);
}
/// <summary>
/// Returns a task that will receive the last value or the exception produced by the observable sequence.
/// </summary>
/// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
/// <param name="observable">Observable sequence to convert to a task.</param>
/// <param name="state">The state to use as the underlying task's AsyncState.</param>
/// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, object state)
{
if (observable == null)
throw new ArgumentNullException("observable");
return observable.ToTask(new CancellationToken(), state);
}
/// <summary>
/// Returns a task that will receive the last value or the exception produced by the observable sequence.
/// </summary>
/// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
/// <param name="observable">Observable sequence to convert to a task.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
/// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken)
{
if (observable == null)
throw new ArgumentNullException("observable");
return observable.ToTask(cancellationToken, null);
}
/// <summary>
/// Returns a task that will receive the last value or the exception produced by the observable sequence.
/// </summary>
/// <typeparam name="TResult">The type of the elements in the source sequence.</typeparam>
/// <param name="observable">Observable sequence to convert to a task.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task, causing unsubscription from the observable sequence.</param>
/// <param name="state">The state to use as the underlying task's AsyncState.</param>
/// <returns>A task that will receive the last element or the exception produced by the observable sequence.</returns>
/// <exception cref="ArgumentNullException"><paramref name="observable"/> is null.</exception>
public static Task<TResult> ToTask<TResult>(this IObservable<TResult> observable, CancellationToken cancellationToken, object state)
{
if (observable == null)
throw new ArgumentNullException("observable");
var hasValue = false;
var lastValue = default(TResult);
var tcs = new TaskCompletionSource<TResult>(state);
var disposable = new SingleAssignmentDisposable();
var ctr = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
ctr = cancellationToken.Register(() =>
{
disposable.Dispose();
tcs.TrySetCanceled(cancellationToken);
});
}
var taskCompletionObserver = Observer.Create<TResult>(
value =>
{
hasValue = true;
lastValue = value;
},
ex =>
{
tcs.TrySetException(ex);
ctr.Dispose(); // no null-check needed (struct)
disposable.Dispose();
},
() =>
{
if (hasValue)
tcs.TrySetResult(lastValue);
else
tcs.TrySetException(new InvalidOperationException("Strings_Linq.NO_ELEMENTS"));
ctr.Dispose(); // no null-check needed (struct)
disposable.Dispose();
}
);
//
// Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
// will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
// spot, which may throw an exception. (Similar to TFS 487142)
//
try
{
//
// [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
//
// Notice we could use a safe subscription to route errors through OnError, but we still need the
// exception handling logic here for the reason explained above. We cannot afford to throw here
// and as a result never set the TaskCompletionSource, so we tunnel everything through here.
//
disposable.Disposable = observable.Subscribe/*Unsafe*/(taskCompletionObserver);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
}
}
#endif
| 45.915761 | 190 | 0.590874 | [
"MIT"
] | Acidburn0zzz/UniRx | Assets/Plugins/UniRx/Scripts/Tasks/TaskObservableExtensions.cs | 16,899 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// The Electric Potential of a system known to use Alternating Current.
/// </summary>
public partial struct ElectricPotentialAc : IQuantity<ElectricPotentialAcUnit>, IEquatable<ElectricPotentialAc>, IComparable, IComparable<ElectricPotentialAc>, IConvertible, IFormattable
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly ElectricPotentialAcUnit? _unit;
static ElectricPotentialAc()
{
BaseDimensions = BaseDimensions.Dimensionless;
Info = new QuantityInfo<ElectricPotentialAcUnit>(QuantityType.ElectricPotentialAc,
new UnitInfo<ElectricPotentialAcUnit>[] {
new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.KilovoltAc, BaseUnits.Undefined),
new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MegavoltAc, BaseUnits.Undefined),
new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MicrovoltAc, BaseUnits.Undefined),
new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.MillivoltAc, BaseUnits.Undefined),
new UnitInfo<ElectricPotentialAcUnit>(ElectricPotentialAcUnit.VoltAc, BaseUnits.Undefined),
},
BaseUnit, Zero, BaseDimensions);
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unit">The unit representation to contruct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public ElectricPotentialAc(double numericValue, ElectricPotentialAcUnit unit)
{
if(unit == ElectricPotentialAcUnit.Undefined)
throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = unit;
}
/// <summary>
/// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>.
/// If multiple compatible units were found, the first match is used.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unitSystem">The unit system to create the quantity with.</param>
/// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception>
/// <exception cref="ArgumentException">No unit was found for the given <see cref="UnitSystem"/>.</exception>
public ElectricPotentialAc(double numericValue, UnitSystem unitSystem)
{
if(unitSystem == null) throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
}
#region Static Properties
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
public static QuantityInfo<ElectricPotentialAcUnit> Info { get; }
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions { get; }
/// <summary>
/// The base unit of ElectricPotentialAc, which is VoltAc. All conversions go via this value.
/// </summary>
public static ElectricPotentialAcUnit BaseUnit { get; } = ElectricPotentialAcUnit.VoltAc;
/// <summary>
/// Represents the largest possible value of ElectricPotentialAc
/// </summary>
public static ElectricPotentialAc MaxValue { get; } = new ElectricPotentialAc(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of ElectricPotentialAc
/// </summary>
public static ElectricPotentialAc MinValue { get; } = new ElectricPotentialAc(double.MinValue, BaseUnit);
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public static QuantityType QuantityType { get; } = QuantityType.ElectricPotentialAc;
/// <summary>
/// All units of measurement for the ElectricPotentialAc quantity.
/// </summary>
public static ElectricPotentialAcUnit[] Units { get; } = Enum.GetValues(typeof(ElectricPotentialAcUnit)).Cast<ElectricPotentialAcUnit>().Except(new ElectricPotentialAcUnit[]{ ElectricPotentialAcUnit.Undefined }).ToArray();
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit VoltAc.
/// </summary>
public static ElectricPotentialAc Zero { get; } = new ElectricPotentialAc(0, BaseUnit);
#endregion
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public ElectricPotentialAcUnit Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<ElectricPotentialAcUnit> QuantityInfo => Info;
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public QuantityType Type => ElectricPotentialAc.QuantityType;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => ElectricPotentialAc.BaseDimensions;
#endregion
#region Conversion Properties
/// <summary>
/// Get ElectricPotentialAc in KilovoltsAc.
/// </summary>
public double KilovoltsAc => As(ElectricPotentialAcUnit.KilovoltAc);
/// <summary>
/// Get ElectricPotentialAc in MegavoltsAc.
/// </summary>
public double MegavoltsAc => As(ElectricPotentialAcUnit.MegavoltAc);
/// <summary>
/// Get ElectricPotentialAc in MicrovoltsAc.
/// </summary>
public double MicrovoltsAc => As(ElectricPotentialAcUnit.MicrovoltAc);
/// <summary>
/// Get ElectricPotentialAc in MillivoltsAc.
/// </summary>
public double MillivoltsAc => As(ElectricPotentialAcUnit.MillivoltAc);
/// <summary>
/// Get ElectricPotentialAc in VoltsAc.
/// </summary>
public double VoltsAc => As(ElectricPotentialAcUnit.VoltAc);
#endregion
#region Static Methods
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation(ElectricPotentialAcUnit unit)
{
return GetAbbreviation(unit, null);
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
/// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static string GetAbbreviation(ElectricPotentialAcUnit unit, [CanBeNull] IFormatProvider provider)
{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}
#endregion
#region Static Factory Methods
/// <summary>
/// Get ElectricPotentialAc from KilovoltsAc.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricPotentialAc FromKilovoltsAc(QuantityValue kilovoltsac)
{
double value = (double) kilovoltsac;
return new ElectricPotentialAc(value, ElectricPotentialAcUnit.KilovoltAc);
}
/// <summary>
/// Get ElectricPotentialAc from MegavoltsAc.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricPotentialAc FromMegavoltsAc(QuantityValue megavoltsac)
{
double value = (double) megavoltsac;
return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MegavoltAc);
}
/// <summary>
/// Get ElectricPotentialAc from MicrovoltsAc.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricPotentialAc FromMicrovoltsAc(QuantityValue microvoltsac)
{
double value = (double) microvoltsac;
return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MicrovoltAc);
}
/// <summary>
/// Get ElectricPotentialAc from MillivoltsAc.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricPotentialAc FromMillivoltsAc(QuantityValue millivoltsac)
{
double value = (double) millivoltsac;
return new ElectricPotentialAc(value, ElectricPotentialAcUnit.MillivoltAc);
}
/// <summary>
/// Get ElectricPotentialAc from VoltsAc.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static ElectricPotentialAc FromVoltsAc(QuantityValue voltsac)
{
double value = (double) voltsac;
return new ElectricPotentialAc(value, ElectricPotentialAcUnit.VoltAc);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="ElectricPotentialAcUnit" /> to <see cref="ElectricPotentialAc" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>ElectricPotentialAc unit value.</returns>
public static ElectricPotentialAc From(QuantityValue value, ElectricPotentialAcUnit fromUnit)
{
return new ElectricPotentialAc((double)value, fromUnit);
}
#endregion
#region Static Parse Methods
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static ElectricPotentialAc Parse(string str)
{
return Parse(str, null);
}
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static ElectricPotentialAc Parse(string str, [CanBeNull] IFormatProvider provider)
{
return QuantityParser.Default.Parse<ElectricPotentialAc, ElectricPotentialAcUnit>(
str,
provider,
From);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse([CanBeNull] string str, out ElectricPotentialAc result)
{
return TryParse(str, null, out result);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out ElectricPotentialAc result)
{
return QuantityParser.Default.TryParse<ElectricPotentialAc, ElectricPotentialAcUnit>(
str,
provider,
From,
out result);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static ElectricPotentialAcUnit ParseUnit(string str)
{
return ParseUnit(str, null);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static ElectricPotentialAcUnit ParseUnit(string str, IFormatProvider provider = null)
{
return UnitParser.Default.Parse<ElectricPotentialAcUnit>(str, provider);
}
/// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ElectricPotentialAcUnit)"/>
public static bool TryParseUnit(string str, out ElectricPotentialAcUnit unit)
{
return TryParseUnit(str, null, out unit);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="unit">The parsed unit if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.TryParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParseUnit(string str, IFormatProvider provider, out ElectricPotentialAcUnit unit)
{
return UnitParser.Default.TryParse<ElectricPotentialAcUnit>(str, provider, out unit);
}
#endregion
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static ElectricPotentialAc operator -(ElectricPotentialAc right)
{
return new ElectricPotentialAc(-right.Value, right.Unit);
}
/// <summary>Get <see cref="ElectricPotentialAc"/> from adding two <see cref="ElectricPotentialAc"/>.</summary>
public static ElectricPotentialAc operator +(ElectricPotentialAc left, ElectricPotentialAc right)
{
return new ElectricPotentialAc(left.Value + right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="ElectricPotentialAc"/> from subtracting two <see cref="ElectricPotentialAc"/>.</summary>
public static ElectricPotentialAc operator -(ElectricPotentialAc left, ElectricPotentialAc right)
{
return new ElectricPotentialAc(left.Value - right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="ElectricPotentialAc"/> from multiplying value and <see cref="ElectricPotentialAc"/>.</summary>
public static ElectricPotentialAc operator *(double left, ElectricPotentialAc right)
{
return new ElectricPotentialAc(left * right.Value, right.Unit);
}
/// <summary>Get <see cref="ElectricPotentialAc"/> from multiplying value and <see cref="ElectricPotentialAc"/>.</summary>
public static ElectricPotentialAc operator *(ElectricPotentialAc left, double right)
{
return new ElectricPotentialAc(left.Value * right, left.Unit);
}
/// <summary>Get <see cref="ElectricPotentialAc"/> from dividing <see cref="ElectricPotentialAc"/> by value.</summary>
public static ElectricPotentialAc operator /(ElectricPotentialAc left, double right)
{
return new ElectricPotentialAc(left.Value / right, left.Unit);
}
/// <summary>Get ratio value from dividing <see cref="ElectricPotentialAc"/> by <see cref="ElectricPotentialAc"/>.</summary>
public static double operator /(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.VoltsAc / right.VoltsAc;
}
#endregion
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.Value <= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.Value >= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if less than.</summary>
public static bool operator <(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.Value < right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than.</summary>
public static bool operator >(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.Value > right.GetValueAs(left.Unit);
}
/// <summary>Returns true if exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator ==(ElectricPotentialAc left, ElectricPotentialAc right)
{
return left.Equals(right);
}
/// <summary>Returns true if not exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator !=(ElectricPotentialAc left, ElectricPotentialAc right)
{
return !(left == right);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if(obj is null) throw new ArgumentNullException(nameof(obj));
if(!(obj is ElectricPotentialAc objElectricPotentialAc)) throw new ArgumentException("Expected type ElectricPotentialAc.", nameof(obj));
return CompareTo(objElectricPotentialAc);
}
/// <inheritdoc />
public int CompareTo(ElectricPotentialAc other)
{
return _value.CompareTo(other.GetValueAs(this.Unit));
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public override bool Equals(object obj)
{
if(obj is null || !(obj is ElectricPotentialAc objElectricPotentialAc))
return false;
return Equals(objElectricPotentialAc);
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(ElectricPotentialAc, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public bool Equals(ElectricPotentialAc other)
{
return _value.Equals(other.GetValueAs(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another ElectricPotentialAc within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </para>
/// </summary>
/// <param name="other">The other quantity to compare to.</param>
/// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name="comparisonType">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
public bool Equals(ElectricPotentialAc other, double tolerance, ComparisonType comparisonType)
{
if(tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0.");
double thisValue = (double)this.Value;
double otherValueInThisUnits = other.As(this.Unit);
return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current ElectricPotentialAc.</returns>
public override int GetHashCode()
{
return new { QuantityType, Value, Unit }.GetHashCode();
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(ElectricPotentialAcUnit unit)
{
if(Unit == unit)
return Convert.ToDouble(Value);
var converted = GetValueAs(unit);
return Convert.ToDouble(converted);
}
/// <inheritdoc cref="IQuantity.As(UnitSystem)"/>
public double As(UnitSystem unitSystem)
{
if(unitSystem == null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if(firstUnitInfo == null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
return As(firstUnitInfo.Value);
}
/// <inheritdoc />
double IQuantity.As(Enum unit)
{
if(!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit));
return As(unitAsElectricPotentialAcUnit);
}
/// <summary>
/// Converts this ElectricPotentialAc to another ElectricPotentialAc with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A ElectricPotentialAc with the specified unit.</returns>
public ElectricPotentialAc ToUnit(ElectricPotentialAcUnit unit)
{
var convertedValue = GetValueAs(unit);
return new ElectricPotentialAc(convertedValue, unit);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit)
{
if(!(unit is ElectricPotentialAcUnit unitAsElectricPotentialAcUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialAcUnit)} is supported.", nameof(unit));
return ToUnit(unitAsElectricPotentialAcUnit);
}
/// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/>
public ElectricPotentialAc ToUnit(UnitSystem unitSystem)
{
if(unitSystem == null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if(firstUnitInfo == null)
throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem));
return ToUnit(firstUnitInfo.Value);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
/// <inheritdoc />
IQuantity<ElectricPotentialAcUnit> IQuantity<ElectricPotentialAcUnit>.ToUnit(ElectricPotentialAcUnit unit) => ToUnit(unit);
/// <inheritdoc />
IQuantity<ElectricPotentialAcUnit> IQuantity<ElectricPotentialAcUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem);
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double GetValueInBaseUnit()
{
switch(Unit)
{
case ElectricPotentialAcUnit.KilovoltAc: return (_value) * 1e3d;
case ElectricPotentialAcUnit.MegavoltAc: return (_value) * 1e6d;
case ElectricPotentialAcUnit.MicrovoltAc: return (_value) * 1e-6d;
case ElectricPotentialAcUnit.MillivoltAc: return (_value) * 1e-3d;
case ElectricPotentialAcUnit.VoltAc: return _value;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
internal ElectricPotentialAc ToBaseUnit()
{
var baseUnitValue = GetValueInBaseUnit();
return new ElectricPotentialAc(baseUnitValue, BaseUnit);
}
private double GetValueAs(ElectricPotentialAcUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = GetValueInBaseUnit();
switch(unit)
{
case ElectricPotentialAcUnit.KilovoltAc: return (baseUnitValue) / 1e3d;
case ElectricPotentialAcUnit.MegavoltAc: return (baseUnitValue) / 1e6d;
case ElectricPotentialAcUnit.MicrovoltAc: return (baseUnitValue) / 1e-6d;
case ElectricPotentialAcUnit.MillivoltAc: return (baseUnitValue) / 1e-3d;
case ElectricPotentialAcUnit.VoltAc: return baseUnitValue;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
#region ToString Methods
/// <summary>
/// Gets the default string representation of value and unit.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString()
{
return ToString("g");
}
/// <summary>
/// Gets the default string representation of value and unit using the given format provider.
/// </summary>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public string ToString([CanBeNull] IFormatProvider provider)
{
return ToString("g", provider);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")]
public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix)
{
var value = Convert.ToDouble(Value);
var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);
return ToString(provider, format);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param>
/// <param name="args">Arguments for string format. Value and unit are implictly included as arguments 0 and 1.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")]
public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args)
{
if (format == null) throw new ArgumentNullException(nameof(format));
if (args == null) throw new ArgumentNullException(nameof(args));
provider = provider ?? CultureInfo.CurrentUICulture;
var value = Convert.ToDouble(Value);
var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args);
return string.Format(provider, format, formatArgs);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />.
/// </summary>
/// <param name="format">The format string.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentUICulture);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="formatProvider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return QuantityFormatter.Format<ElectricPotentialAcUnit>(this, format, formatProvider);
}
#endregion
#region IConvertible Methods
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to bool is not supported.");
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to char is not supported.");
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to DateTime is not supported.");
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString("g", provider);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if(conversionType == typeof(ElectricPotentialAc))
return this;
else if(conversionType == typeof(ElectricPotentialAcUnit))
return Unit;
else if(conversionType == typeof(QuantityType))
return ElectricPotentialAc.QuantityType;
else if(conversionType == typeof(BaseDimensions))
return ElectricPotentialAc.BaseDimensions;
else
throw new InvalidCastException($"Converting {typeof(ElectricPotentialAc)} to {conversionType} is not supported.");
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
#endregion
}
}
| 44.993471 | 230 | 0.622313 | [
"MIT-feh"
] | ebfortin/UnitsNet | UnitsNet/GeneratedCode/Quantities/ElectricPotentialAc.g.cs | 41,351 | C# |
using System;
using System.Windows.Forms;
namespace SyncMonitorBrightness
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.85 | 65 | 0.578947 | [
"MIT"
] | diaconesq/SyncMonitorBrightness | Program.cs | 439 | C# |
//-----------------------------------------------------------------------------
// FILE: Service.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Neon.Common;
using Neon.Service;
using IdentityServer4;
using IdentityServer4.Stores;
using IdentityServer4.Models;
using IdentityServer4.Services;
namespace NeonIdentityService
{
/// <summary>
/// Implements the <c>neon-identity-service</c>, a Secure Token Server (STS) based on
/// <b>IdentityServer4</b>.
/// </summary>
public partial class Service : NeonService
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="name">The service name.</param>
/// <param name="serviceMap">Optionally specifies the service map.</param>
public Service(string name, ServiceMap serviceMap = null)
: base(name, serviceMap: serviceMap)
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <inheritdoc/>
protected async override Task<int> OnRunAsync()
{
// Read and verify the environment variables.
var connectionString = GetEnvironmentVariable("CONNECTION_STRING");
if (string.IsNullOrWhiteSpace(connectionString))
{
Log.LogError("[CONNECTION_STRING] environment variable is blank or missing.");
}
// Indicate that the service is ready.
await SetRunningAsync();
// Wait for the process terminator to signal that the service is stopping.
await Terminator.StopEvent.WaitAsync();
Terminator.ReadyToExit();
return 0;
}
}
}
| 30.975 | 94 | 0.625504 | [
"Apache-2.0"
] | nforgeio/neonKUBE | Services/neon-identity-service/Service.cs | 2,480 | C# |
using System;
using System.Runtime.InteropServices;
using System.Security;
using Tynted.SFML.System;
namespace Tynted.SFML.Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Base class for textured shapes with outline
/// </summary>
////////////////////////////////////////////////////////////
public abstract class Shape : Transformable, Drawable
{
////////////////////////////////////////////////////////////
/// <summary>
/// Source texture of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Texture Texture
{
get { return myTexture; }
set { myTexture = value; sfShape_setTexture(CPointer, value != null ? value.CPointer : IntPtr.Zero, false); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Sub-rectangle of the texture that the shape will display
/// </summary>
////////////////////////////////////////////////////////////
public IntRect TextureRect
{
get { return sfShape_getTextureRect(CPointer); }
set { sfShape_setTextureRect(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Fill color of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Color FillColor
{
get { return sfShape_getFillColor(CPointer); }
set { sfShape_setFillColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Outline color of the shape
/// </summary>
////////////////////////////////////////////////////////////
public Color OutlineColor
{
get { return sfShape_getOutlineColor(CPointer); }
set { sfShape_setOutlineColor(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Thickness of the shape's outline
/// </summary>
////////////////////////////////////////////////////////////
public float OutlineThickness
{
get { return sfShape_getOutlineThickness(CPointer); }
set { sfShape_setOutlineThickness(CPointer, value); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the total number of points of the shape
/// </summary>
/// <returns>The total point count</returns>
////////////////////////////////////////////////////////////
public abstract uint GetPointCount();
////////////////////////////////////////////////////////////
/// <summary>
/// Get the position of a point
///
/// The returned point is in local coordinates, that is,
/// the shape's transforms (position, rotation, scale) are
/// not taken into account.
/// The result is undefined if index is out of the valid range.
/// </summary>
/// <param name="index">Index of the point to get, in range [0 .. PointCount - 1]</param>
/// <returns>index-th point of the shape</returns>
////////////////////////////////////////////////////////////
public abstract Vector2f GetPoint(uint index);
////////////////////////////////////////////////////////////
/// <summary>
/// Get the local bounding rectangle of the entity.
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
/// </summary>
/// <returns>Local bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetLocalBounds()
{
return sfShape_getLocalBounds(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the global bounding rectangle of the entity.
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
/// </summary>
/// <returns>Global bounding rectangle of the entity</returns>
////////////////////////////////////////////////////////////
public FloatRect GetGlobalBounds()
{
// we don't use the native getGlobalBounds function,
// because we override the object's transform
return Transform.TransformRect(GetLocalBounds());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw the shape to a render target
/// </summary>
/// <param name="target">Render target to draw to</param>
/// <param name="states">Current render states</param>
////////////////////////////////////////////////////////////
public void Draw(RenderTarget target, RenderStates states)
{
states.Transform *= Transform;
RenderStates.MarshalData marshaledStates = states.Marshal();
if (target is RenderWindow)
{
sfRenderWindow_drawShape(( (RenderWindow)target ).CPointer, CPointer, ref marshaledStates);
}
else if (target is RenderTexture)
{
sfRenderTexture_drawShape(( (RenderTexture)target ).CPointer, CPointer, ref marshaledStates);
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Default constructor
/// </summary>
////////////////////////////////////////////////////////////
protected Shape() :
base(IntPtr.Zero)
{
myGetPointCountCallback = new GetPointCountCallbackType(InternalGetPointCount);
myGetPointCallback = new GetPointCallbackType(InternalGetPoint);
CPointer = sfShape_create(myGetPointCountCallback, myGetPointCallback, IntPtr.Zero);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Construct the shape from another shape
/// </summary>
/// <param name="copy">Shape to copy</param>
////////////////////////////////////////////////////////////
public Shape(Shape copy) :
base(IntPtr.Zero)
{
myGetPointCountCallback = new GetPointCountCallbackType(InternalGetPointCount);
myGetPointCallback = new GetPointCallbackType(InternalGetPoint);
CPointer = sfShape_create(myGetPointCountCallback, myGetPointCallback, IntPtr.Zero);
Origin = copy.Origin;
Position = copy.Position;
Rotation = copy.Rotation;
Scale = copy.Scale;
Texture = copy.Texture;
TextureRect = copy.TextureRect;
FillColor = copy.FillColor;
OutlineColor = copy.OutlineColor;
OutlineThickness = copy.OutlineThickness;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Recompute the internal geometry of the shape.
///
/// This function must be called by the derived class everytime
/// the shape's points change (ie. the result of either
/// PointCount or GetPoint is different).
/// </summary>
////////////////////////////////////////////////////////////
protected void Update()
{
sfShape_update(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfShape_destroy(CPointer);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Callback passed to the C API
/// </summary>
////////////////////////////////////////////////////////////
private uint InternalGetPointCount(IntPtr userData)
{
return GetPointCount();
}
////////////////////////////////////////////////////////////
/// <summary>
/// Callback passed to the C API
/// </summary>
////////////////////////////////////////////////////////////
private Vector2f InternalGetPoint(uint index, IntPtr userData)
{
return GetPoint(index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint GetPointCountCallbackType(IntPtr UserData);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate Vector2f GetPointCallbackType(uint index, IntPtr UserData);
private readonly GetPointCountCallbackType myGetPointCountCallback;
private readonly GetPointCallbackType myGetPointCallback;
private Texture myTexture = null;
#region Imports
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShape_create(GetPointCountCallbackType getPointCount, GetPointCallbackType getPoint, IntPtr userData);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfShape_copy(IntPtr Shape);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_destroy(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setTexture(IntPtr CPointer, IntPtr Texture, bool AdjustToNewSize);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setTextureRect(IntPtr CPointer, IntRect Rect);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntRect sfShape_getTextureRect(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setFillColor(IntPtr CPointer, Color Color);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Color sfShape_getFillColor(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setOutlineColor(IntPtr CPointer, Color Color);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern Color sfShape_getOutlineColor(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_setOutlineThickness(IntPtr CPointer, float Thickness);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfShape_getOutlineThickness(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern FloatRect sfShape_getLocalBounds(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfShape_update(IntPtr CPointer);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_drawShape(IntPtr CPointer, IntPtr Shape, ref RenderStates.MarshalData states);
[DllImport(CSFML.graphics, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderTexture_drawShape(IntPtr CPointer, IntPtr Shape, ref RenderStates.MarshalData states);
#endregion
}
}
| 44.169492 | 133 | 0.531005 | [
"Apache-2.0"
] | NocturnalWisp/Tynted-Engine | TyntedEngine/SFML/SFML.Graphics/Shape.cs | 13,030 | C# |
// Copyright (c) 2015 SharpYaml - Alexandre Mutel
//
// 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.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// 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;
namespace SharpYaml.Serialization
{
/// <summary>
/// Defines the method needed to be able to visit Yaml elements.
/// </summary>
public interface IYamlVisitor
{
/// <summary>
/// Visits a <see cref="YamlStream"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="YamlStream"/> that is being visited.
/// </param>
void Visit(YamlStream stream);
/// <summary>
/// Visits a <see cref="YamlDocument"/>.
/// </summary>
/// <param name="document">
/// The <see cref="YamlDocument"/> that is being visited.
/// </param>
void Visit(YamlDocument document);
/// <summary>
/// Visits a <see cref="YamlScalarNode"/>.
/// </summary>
/// <param name="scalar">
/// The <see cref="YamlScalarNode"/> that is being visited.
/// </param>
void Visit(YamlScalarNode scalar);
/// <summary>
/// Visits a <see cref="YamlSequenceNode"/>.
/// </summary>
/// <param name="sequence">
/// The <see cref="YamlSequenceNode"/> that is being visited.
/// </param>
void Visit(YamlSequenceNode sequence);
/// <summary>
/// Visits a <see cref="YamlMappingNode"/>.
/// </summary>
/// <param name="mapping">
/// The <see cref="YamlMappingNode"/> that is being visited.
/// </param>
void Visit(YamlMappingNode mapping);
}
} | 43.884211 | 83 | 0.628208 | [
"MIT"
] | Schnutzel/SharpYaml | SharpYaml/Serialization/IYamlVisitor.cs | 4,169 | C# |
// -------------------------------------------------------
// Created by Andrew Witte.
// -------------------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
/// <summary>
/// Main Reign delegate class.
/// </summary>
public class ReignServices : MonoBehaviour
{
/// <summary>
/// Current instance of the ReignServices object.
/// </summary>
public static ReignServices Singleton {get; private set;}
private bool canDestroy;
public delegate void FrameDoneCallbackMethod();
private static FrameDoneCallbackMethod frameDoneCallback;
private static bool requestingFrame;
public delegate void CaptureScreenShotCallbackMethod(byte[] data);
private static CaptureScreenShotCallbackMethod captureScreenShotCallback;
private static int lastScreenWidth, lastScreenHeight;
public delegate void ScreenSizeChangedCallbackMethod(int oldWidth, int oldHeight, int newWidth, int newHeight);
public static event ScreenSizeChangedCallbackMethod ScreenSizeChangedCallback;
/// <summary>
/// Sevice delegate method.
/// </summary>
public delegate void ServiceMethod();
private static event ServiceMethod updateService, onguiService, destroyService;
private static List<ServiceMethod>[] invokeOnUnityThreadCallbacks;
private static int invokeSwap;
/// <summary>
/// Used to add service callbacks.
/// </summary>
/// <param name="update">Update callback.</param>
/// <param name="onGUI">OnGUI callback.</param>
/// <param name="destroy">OnDestroy callback.</param>
public static void AddService(ServiceMethod update, ServiceMethod onGUI, ServiceMethod destroy)
{
if (update != null)
{
updateService -= update;
updateService += update;
}
if (onGUI != null)
{
onguiService -= onGUI;
onguiService += onGUI;
}
if (destroy != null)
{
destroyService -= destroy;
destroyService += destroy;
}
}
/// <summary>
/// Used to remove service callbacks.
/// </summary>
/// <param name="update">Update callback.</param>
/// <param name="onGUI">OnGUI callback.</param>
/// <param name="destroy">OnDestroy callback.</param>
public static void RemoveService(ServiceMethod update, ServiceMethod onGUI, ServiceMethod destroy)
{
if (update != null) updateService -= update;
if (onGUI != null) onguiService -= onGUI;
if (destroy != null) destroyService -= destroy;
}
public static void InvokeOnUnityThread(ServiceMethod callback)
{
lock (Singleton)
{
invokeOnUnityThreadCallbacks[invokeSwap].Add(callback);
}
}
public static void RequestEndOfFrame(FrameDoneCallbackMethod frameDoneCallback)
{
if (ReignServices.frameDoneCallback != null)
{
Debug.LogError("You must wait until RequestEndOfFrame has finished!");
return;
}
ReignServices.frameDoneCallback = frameDoneCallback;
requestingFrame = true;
}
public static void CaptureScreenShot(CaptureScreenShotCallbackMethod captureScreenShotCallback)
{
if (ReignServices.captureScreenShotCallback != null)
{
Debug.LogError("You must wait until CaptureScreenShot has finished!");
return;
}
ReignServices.captureScreenShotCallback = captureScreenShotCallback;
RequestEndOfFrame(captureScreenShotEndOfFrame);
}
private static void captureScreenShotEndOfFrame()
{
var width = Screen.width;
var height = Screen.height;
var texture = new Texture2D(width, height, TextureFormat.RGB24, false);
texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
texture.Apply();
var data = texture.EncodeToPNG();
GameObject.Destroy(texture);
if (captureScreenShotCallback != null) captureScreenShotCallback(data);
captureScreenShotCallback = null;
}
static ReignServices()
{
#if DISABLE_REIGN
Debug.LogWarning("NOTE: Reign is disabled for this platform. Check Player Settings for 'DISABLE_REIGN'");
#endif
lastScreenWidth = Screen.width;
lastScreenHeight = Screen.height;
invokeOnUnityThreadCallbacks = new List<ServiceMethod>[2];
invokeOnUnityThreadCallbacks[0] = new List<ServiceMethod>();
invokeOnUnityThreadCallbacks[1] = new List<ServiceMethod>();
}
/// <summary>
/// Used to check if the ReignServices obj exists in the scene.
/// </summary>
public static void CheckStatus()
{
if (Singleton == null) Debug.LogError("ReignServices Prefab or Script does NOT exist in your scene!");
}
void Awake()
{
if (Singleton != null)
{
canDestroy = false;
Destroy(gameObject);
return;
}
canDestroy = true;
Singleton = this;
DontDestroyOnLoad(gameObject);
}
void OnDestroy()
{
if (!canDestroy) return;
PlayerPrefs.Save ();
if (destroyService != null) destroyService();
Singleton = null;
updateService = null;
onguiService = null;
destroyService = null;
}
void Update()
{
// invoke update server delegates
if (updateService != null) updateService();
// if end of frame wait requested
if (requestingFrame)
{
requestingFrame = false;
StartCoroutine(frameSync());
}
// screen size changed callback helper
int newScreenWidth = Screen.width;
int newScreenHeight = Screen.height;
if (newScreenWidth != lastScreenWidth || newScreenHeight != lastScreenHeight)
{
if (ScreenSizeChangedCallback != null) ScreenSizeChangedCallback(lastScreenWidth, lastScreenHeight, newScreenWidth, newScreenHeight);
}
lastScreenWidth = Screen.width;
lastScreenHeight = Screen.height;
// unity thread delegates
if (invokeOnUnityThreadCallbacks != null && invokeOnUnityThreadCallbacks[invokeSwap].Count != 0)
{
invokeSwap = 1 - invokeSwap;
foreach (var callback in invokeOnUnityThreadCallbacks[1 - invokeSwap])
{
callback();
}
invokeOnUnityThreadCallbacks[1 - invokeSwap].Clear();
}
}
private IEnumerator frameSync()
{
yield return new WaitForEndOfFrame();
if (frameDoneCallback != null) frameDoneCallback();
frameDoneCallback = null;
}
void OnGUI()
{
if (onguiService != null) onguiService();
}
}
| 26.895928 | 136 | 0.718371 | [
"MIT"
] | U3DC/Snaker | Assets/Plugins/Reign/Services/ReignServices.cs | 5,944 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WGui.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.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;
}
}
}
}
| 34.16129 | 151 | 0.578848 | [
"MIT"
] | kaseat/BridgeDataAnalysis | WGui/Properties/Settings.Designer.cs | 1,061 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using static Euler.Extension;
using static Euler.Sequence;
using Euler81;
using Euler;
namespace Euler82
{
public class Program
{
public static IEnumerable<SearchState> NeighborFunc(SearchState s, int numCols, int numRows, Func<SearchState, long> heuristicFunc, long[,] minPathLengths)
{
if(s.currentLocation.col < numCols - 1) {
var newLocation = (col: s.currentLocation.col+1, row: s.currentLocation.row);
var newState = new SearchState
{
matrix = s.matrix,
currentLocation = newLocation,
locationsInPath = new HashSet<(int col, int row)>(s.locationsInPath.Append(newLocation)),
pathSum = s.pathSum + s.matrix[newLocation.col, newLocation.row]
};
newState.heuristicValue = heuristicFunc(newState);
if (newState.pathSum < minPathLengths[newState.currentLocation.col, newState.currentLocation.row])
{
minPathLengths[newState.currentLocation.col, newState.currentLocation.row] = newState.pathSum;
yield return newState;
}
}
if(s.currentLocation.row < numRows - 1) {
var newLocation = (col: s.currentLocation.col, row: s.currentLocation.row + 1);
var newState = new SearchState
{
matrix = s.matrix,
currentLocation = newLocation,
locationsInPath = new HashSet<(int col, int row)>(s.locationsInPath.Append(newLocation)),
pathSum = s.pathSum + s.matrix[newLocation.col, newLocation.row]
};
newState.heuristicValue = heuristicFunc(newState);
if (newState.pathSum < minPathLengths[newState.currentLocation.col, newState.currentLocation.row])
{
minPathLengths[newState.currentLocation.col, newState.currentLocation.row] = newState.pathSum;
yield return newState;
}
}
if(s.currentLocation.row > 0) {
var newLocation = (col: s.currentLocation.col, row: s.currentLocation.row - 1);
var newState = new SearchState
{
matrix = s.matrix,
currentLocation = newLocation,
locationsInPath = new HashSet<(int col, int row)>(s.locationsInPath.Append(newLocation)),
pathSum = s.pathSum + s.matrix[newLocation.col, newLocation.row]
};
newState.heuristicValue = heuristicFunc(newState);
if (newState.pathSum < minPathLengths[newState.currentLocation.col, newState.currentLocation.row])
{
minPathLengths[newState.currentLocation.col, newState.currentLocation.row] = newState.pathSum;
yield return newState;
}
}
}
static void Main(string[] args)
{
var profiler = new Euler.Profiler();
AStarWithMinPathLengthCheck(Euler81.Program.FullMatrix, profiler).ConsoleWriteLine();
profiler.Print();
}
public static long AStarWithMinPathLengthCheck(Matrix matrix)
{
return AStarWithMinPathLengthCheck(matrix, IProfiler.Default);
}
public static long AStarWithMinPathLengthCheck(Matrix matrix, IProfiler profiler = null)
{
if (profiler == null) profiler = IProfiler.Default;
var minPathLengths = new long[matrix.NumCols, matrix.NumRows];
for (int col = 0; col < matrix.NumCols; ++col)
{
for (int row = 0; row < matrix.NumRows; ++row)
{
minPathLengths[col, row] = long.MaxValue;
}
}
//Func<SearchState, long> heuristicFunc = s => s.pathSum + diagonalMinSums[s.currentLocation.col + s.currentLocation.row+1];
Func<SearchState, long> heuristicFunc = s => s.pathSum; // assume all values are minimum value
Func<SearchState, IEnumerable<SearchState>> neighborFunc = s => NeighborFunc(s, matrix.NumCols, matrix.NumRows, heuristicFunc, minPathLengths);
Func<SearchState, bool> goalFunc = s => s.currentLocation.col == matrix.NumCols - 1;
Euler.MinHeap<SearchState> searchFrontier = new Euler.MinHeap<SearchState>();
for (int i = 0; i < matrix.NumRows; ++i)
{
var startState = new SearchState
{
matrix = matrix,
currentLocation = (col: 0, row: i),
locationsInPath = new HashSet<(int col, int row)>((col: 0, row: i).Yield()),
pathSum = matrix[0, i]
};
startState.heuristicValue = heuristicFunc(startState);
searchFrontier.Add(startState);
}
int numInspected = 0;
while (searchFrontier.Count > 0)
{
SearchState next;
using (profiler.Time("Pop search state"))
{
next = searchFrontier.Pop();
}
++numInspected;
if (numInspected % 1 == 0)
{
// TODO: progress reporting
//Console.WriteLine($"{numInspected}/{numInspected+searchFrontier.Count}: {next.currentLocation}, {next.locationsInPath.Count}, {next.pathSum}, {next.heuristicValue}");
}
if (goalFunc(next))
{
// TODO: Progress reporting
//Console.WriteLine($"Goal reached. Path sum: {next.pathSum}");
return next.pathSum;
}
else
{
using (profiler.Time("Get neighbors and add to heap"))
searchFrontier.AddRange(neighborFunc(next));
}
}
throw new Exception("Goal state not reached!");
}
public static IEnumerable<EulerProblemInstance<long>> ProblemInstances
{
get
{
var factory = EulerProblemInstance<long>.InstanceFactoryWithCustomParameterRepresentation<Matrix>(typeof(Euler82.Program), 82);
yield return factory(nameof(AStarWithMinPathLengthCheck), Euler81.Program.FullMatrix, "full matrix", 260324L).Canonical();
yield return factory(nameof(AStarWithMinPathLengthCheck), Euler81.Program.ExampleMatrix, "example matrix", 994L).Mini();
}
}
}
}
| 41.533333 | 188 | 0.552751 | [
"Unlicense"
] | sjohna/euler-dotnetcore | Euler082/Program.cs | 6,855 | C# |
using EPiServer.Commerce.Order;
using EPiServer.Core;
using EPiServer.Reference.Commerce.Site.Features.Cart.Services;
using EPiServer.Reference.Commerce.Site.Features.Checkout.Pages;
using EPiServer.Reference.Commerce.Site.Features.Checkout.Services;
using EPiServer.Reference.Commerce.Site.Features.Checkout.ViewModelFactories;
using EPiServer.Reference.Commerce.Site.Features.Checkout.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Market.Services;
using EPiServer.Reference.Commerce.Site.Features.Recommendations.Services;
using EPiServer.Reference.Commerce.Site.Features.Shared.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Attributes;
using EPiServer.Web.Mvc;
using EPiServer.Web.Mvc.Html;
using EPiServer.Web.Routing;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace EPiServer.Reference.Commerce.Site.Features.Checkout.Controllers
{
public class CheckoutController : PageController<CheckoutPage>
{
private readonly ICurrencyService _currencyService;
private readonly ControllerExceptionHandler _controllerExceptionHandler;
private readonly CheckoutViewModelFactory _checkoutViewModelFactory;
private readonly OrderSummaryViewModelFactory _orderSummaryViewModelFactory;
private readonly IOrderRepository _orderRepository;
private readonly ICartService _cartService;
private readonly IRecommendationService _recommendationService;
private readonly OrderValidationService _orderValidationService;
private ICart _cart;
private readonly CheckoutService _checkoutService;
public CheckoutController(
ICurrencyService currencyService,
ControllerExceptionHandler controllerExceptionHandler,
IOrderRepository orderRepository,
CheckoutViewModelFactory checkoutViewModelFactory,
ICartService cartService,
OrderSummaryViewModelFactory orderSummaryViewModelFactory,
IRecommendationService recommendationService,
CheckoutService checkoutService,
OrderValidationService orderValidationService)
{
_currencyService = currencyService;
_controllerExceptionHandler = controllerExceptionHandler;
_orderRepository = orderRepository;
_checkoutViewModelFactory = checkoutViewModelFactory;
_cartService = cartService;
_orderSummaryViewModelFactory = orderSummaryViewModelFactory;
_recommendationService = recommendationService;
_checkoutService = checkoutService;
_orderValidationService = orderValidationService;
}
[HttpGet]
[OutputCache(Duration = 0, NoStore = true)]
public async Task<ActionResult> Index(CheckoutPage currentPage)
{
if (CartIsNullOrEmpty())
{
return View("EmptyCart");
}
var viewModel = CreateCheckoutViewModel(currentPage);
Cart.Currency = _currencyService.GetCurrentCurrency();
_checkoutService.UpdateShippingAddresses(Cart, viewModel);
_checkoutService.UpdateShippingMethods(Cart, viewModel.Shipments);
_cartService.ApplyDiscounts(Cart);
_orderRepository.Save(Cart);
await _recommendationService.TrackCheckoutAsync(HttpContext);
_checkoutService.ProcessPaymentCancel(viewModel, TempData, ControllerContext);
return View(viewModel.ViewName, viewModel);
}
[HttpGet]
public ActionResult SingleShipment(CheckoutPage currentPage)
{
if (!CartIsNullOrEmpty())
{
_cartService.MergeShipments(Cart);
_orderRepository.Save(Cart);
}
return RedirectToAction("Index", new { node = currentPage.ContentLink });
}
[HttpPost]
[AllowDBWrite]
public ActionResult ChangeAddress(UpdateAddressViewModel addressViewModel)
{
ModelState.Clear();
var viewModel = CreateCheckoutViewModel(addressViewModel.CurrentPage);
_checkoutService.CheckoutAddressHandling.ChangeAddress(viewModel, addressViewModel);
_checkoutService.UpdateShippingAddresses(Cart, viewModel);
_orderRepository.Save(Cart);
var addressViewName = addressViewModel.ShippingAddressIndex > -1 ? "SingleShippingAddress" : "BillingAddress";
return PartialView(addressViewName, viewModel);
}
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult OrderSummary()
{
var viewModel = _orderSummaryViewModelFactory.CreateOrderSummaryViewModel(Cart);
return PartialView(viewModel);
}
[HttpPost]
[AllowDBWrite]
public ActionResult AddCouponCode(CheckoutPage currentPage, string couponCode)
{
if (_cartService.AddCouponCode(Cart, couponCode))
{
_orderRepository.Save(Cart);
}
var viewModel = CreateCheckoutViewModel(currentPage);
return View(viewModel.ViewName, viewModel);
}
[HttpPost]
[AllowDBWrite]
public ActionResult RemoveCouponCode(CheckoutPage currentPage, string couponCode)
{
_cartService.RemoveCouponCode(Cart, couponCode);
_orderRepository.Save(Cart);
var viewModel = CreateCheckoutViewModel(currentPage);
return View(viewModel.ViewName, viewModel);
}
[HttpPost]
[AllowDBWrite]
public ActionResult Purchase(CheckoutViewModel viewModel, IPaymentMethod paymentMethod)
{
if (CartIsNullOrEmpty())
{
return Redirect(Url.ContentUrl(ContentReference.StartPage));
}
viewModel.Payment = paymentMethod;
viewModel.IsAuthenticated = User.Identity.IsAuthenticated;
_checkoutService.CheckoutAddressHandling.UpdateUserAddresses(viewModel);
if (!_checkoutService.ValidateOrder(ModelState, viewModel, _orderValidationService.ValidateOrder(Cart)))
{
return View(viewModel);
}
if (!paymentMethod.ValidateData())
{
return View(viewModel);
}
_checkoutService.UpdateShippingAddresses(Cart, viewModel);
_checkoutService.CreateAndAddPaymentToCart(Cart, viewModel);
var purchaseOrder = _checkoutService.PlaceOrder(Cart, ModelState, viewModel);
if (!string.IsNullOrEmpty(viewModel.RedirectUrl))
{
return Redirect(viewModel.RedirectUrl);
}
if (purchaseOrder == null)
{
return View(viewModel);
}
var confirmationSentSuccessfully = _checkoutService.SendConfirmation(viewModel, purchaseOrder);
return Redirect(_checkoutService.BuildRedirectionUrl(viewModel, purchaseOrder, confirmationSentSuccessfully));
}
public ActionResult OnPurchaseException(ExceptionContext filterContext)
{
var currentPage = filterContext.RequestContext.GetRoutedData<CheckoutPage>();
if (currentPage == null)
{
return new EmptyResult();
}
var viewModel = CreateCheckoutViewModel(currentPage);
ModelState.AddModelError("Purchase", filterContext.Exception.Message);
return View(viewModel.ViewName, viewModel);
}
protected override void OnException(ExceptionContext filterContext)
{
_controllerExceptionHandler.HandleRequestValidationException(filterContext, "purchase", OnPurchaseException);
}
private ViewResult View(CheckoutViewModel checkoutViewModel)
{
return View(checkoutViewModel.ViewName, CreateCheckoutViewModel(checkoutViewModel.CurrentPage, checkoutViewModel.Payment));
}
private CheckoutViewModel CreateCheckoutViewModel(CheckoutPage currentPage, IPaymentMethod paymentMethod = null)
{
return _checkoutViewModelFactory.CreateCheckoutViewModel(Cart, currentPage, paymentMethod);
}
private ICart Cart => _cart ?? (_cart = _cartService.LoadCart(_cartService.DefaultCartName));
private bool CartIsNullOrEmpty()
{
return Cart == null || !Cart.GetAllLineItems().Any();
}
}
}
| 38.855856 | 135 | 0.675052 | [
"Apache-2.0"
] | Cauldrath/Quicksilver | Sources/EPiServer.Reference.Commerce.Site/Features/Checkout/Controllers/CheckoutController.cs | 8,628 | C# |
using System.Text;
using Microsoft.OpenApi.Models;
namespace openapi_to_terraform.Generator.azurerm.v2_45_1.GeneratorModels
{
public class TerraformApimProductApi
{
public static string GenerateBlock(OpenApiDocument document, string revision)
{
StringBuilder sb = new StringBuilder();
string resourceName = document.Info.Title.ToLower().Replace(" ", "") + $"_rev{revision}";
sb.AppendLine($"resource \"azurerm_api_management_product_api\" \"{resourceName}productapi\" {{");
sb.AppendLine($"\tapi_name\t=\tazurerm_api_management_api.{resourceName}.name");
sb.AppendLine($"\tproduct_id\t=\t{{api_management_product_id}}");
sb.AppendLine($"\tapi_management_name\t=\t{{api_management_service_name}}");
sb.AppendLine($"\tresource_group_name\t=\t{{api_management_resource_group_name}}");
sb.AppendLine("}");
return sb.ToString();
}
}
} | 44.318182 | 110 | 0.667692 | [
"MIT"
] | awaldow/openapi-to-terraform | openapi-to-terraform.Generator/azurerm/v2_45_1/GeneratorModels/TerraformApiProductApi.cs | 975 | C# |
using System;
using System.Collections.Generic;
namespace OpcPublisher
{
using Opc.Ua;
using OpcPublisher.Crypto;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using static OpcPublisher.OpcSession;
/// <summary>
/// Class to manage OPC sessions.
/// </summary>
public interface IOpcSession : IDisposable
{
/// <summary>
/// The endpoint to connect to for the session.
/// </summary>
string EndpointUrl { get; set; }
/// <summary>
/// The encrypted credential for authentication against the OPC UA Server. This is only used, when <see cref="OpcAuthenticationMode"/> is set to "UsernamePassword".
/// </summary>
EncryptedNetworkCredential EncryptedAuthCredential { get; set; }
/// <summary>
/// The authentication mode to use for authentication against the OPC UA Server.
/// </summary>
OpcAuthenticationMode OpcAuthenticationMode { get; set; }
/// <summary>
/// The OPC UA stack session object of the session.
/// </summary>
IOpcUaSession OpcUaClientSession { get; set; }
/// <summary>
/// The state of the session.
/// </summary>
SessionState State { get; set; }
/// <summary>
/// The subscriptions on this session.
/// </summary>
List<IOpcSubscription> OpcSubscriptions { get; }
/// <summary>
/// Counts session connection attempts which were unsuccessful.
/// </summary>
uint UnsuccessfulConnectionCount { get; set; }
/// <summary>
/// Counts missed keep alives.
/// </summary>
uint MissedKeepAlives { get; set; }
/// <summary>
/// The default publishing interval to use on this session.
/// </summary>
int PublishingInterval { get; set; }
/// <summary>
/// The OPC UA timeout setting to use for the OPC UA session.
/// </summary>
uint SessionTimeout { get; }
/// <summary>
/// Flag to control if a secure or unsecure OPC UA transport should be used for the session.
/// </summary>
bool UseSecurity { get; set; }
/// <summary>
/// Signals to run the connect and monitor task.
/// </summary>
AutoResetEvent ConnectAndMonitorSession { get; set; }
/// <summary>
/// Number of subscirptoins on this session.
/// </summary>
/// <returns></returns>
int GetNumberOfOpcSubscriptions();
/// <summary>
/// Number of configured monitored items on this session.
/// </summary>
/// <returns></returns>
int GetNumberOfOpcMonitoredItemsConfigured();
/// <summary>
/// Number of actually monitored items on this sessions.
/// </summary>
/// <returns></returns>
int GetNumberOfOpcMonitoredItemsMonitored();
/// <summary>
/// Number of monitored items to be removed from this session.
/// </summary>
/// <returns></returns>
int GetNumberOfOpcMonitoredItemsToRemove();
/// <summary>
/// This task is started when a session is configured and is running till session shutdown and ensures:
/// - disconnected sessions are reconnected.
/// - monitored nodes are no longer monitored if requested to do so.
/// - monitoring for a node starts if it is required.
/// - unused subscriptions (without any nodes to monitor) are removed.
/// - sessions with out subscriptions are removed.
/// </summary>
Task ConnectAndMonitorAsync();
/// <summary>
/// Connects the session if it is disconnected.
/// </summary>
Task ConnectSessionAsync(CancellationToken ct);
/// <summary>
/// Monitoring for a node starts if it is required.
/// </summary>
Task MonitorNodesAsync(CancellationToken ct);
/// <summary>
/// Checks if there are monitored nodes tagged to stop monitoring.
/// </summary>
Task StopMonitoringNodesAsync(CancellationToken ct);
/// <summary>
/// Checks if there are subscriptions without any monitored items and remove them.
/// </summary>
Task RemoveUnusedSubscriptionsAsync(CancellationToken ct);
/// <summary>
/// Checks if there are session without any subscriptions and remove them.
/// </summary>
Task RemoveUnusedSessionsAsync(CancellationToken ct);
/// <summary>
/// Disconnects a session and removes all subscriptions on it and marks all nodes on those subscriptions
/// as unmonitored.
/// </summary>
Task DisconnectAsync();
/// <summary>
/// Returns the namespace index for a namespace URI.
/// </summary>
int GetNamespaceIndexUnlocked(string namespaceUri);
/// <summary>
/// Adds a node to be monitored. If there is no subscription with the requested publishing interval,
/// one is created.
/// </summary>
Task<HttpStatusCode> AddNodeForMonitoringAsync(NodeId nodeId, ExpandedNodeId expandedNodeId,
int? opcPublishingInterval, int? opcSamplingInterval, string displayName,
int? heartbeatInterval, bool? skipFirst, CancellationToken ct);
/// <summary>
/// Tags a monitored node to stop monitoring and remove it.
/// </summary>
Task<HttpStatusCode> RequestMonitorItemRemovalAsync(NodeId nodeId, ExpandedNodeId expandedNodeId, CancellationToken ct, bool takeLock = true);
/// <summary>
/// Checks if the node specified by either the given NodeId or ExpandedNodeId on the given endpoint is published in the session.
/// </summary>
bool IsNodePublishedInSession(NodeId nodeId, ExpandedNodeId expandedNodeId);
/// <summary>
/// Shutdown the current session if it is connected.
/// </summary>
Task ShutdownAsync();
/// <summary>
/// Take the session semaphore.
/// </summary>
Task<bool> LockSessionAsync();
/// <summary>
/// Release the session semaphore.
/// </summary>
void ReleaseSession();
Task Reconnect();
}
}
| 34.717391 | 172 | 0.601284 | [
"MIT"
] | 4or5trees/iot-edge-opc-publisher | opcpublisher/IOpcSession.cs | 6,390 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Ch01_01EmptyProject.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.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;
}
}
}
}
| 39.777778 | 151 | 0.58473 | [
"MIT"
] | AndreGuimRua/Direct3D-Rendering-Cookbook | Ch01_01EmptyProject/Properties/Settings.Designer.cs | 1,076 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MASA.PM.Service.Admin.Infrastructure.Entities
{
[Table("EnvironmentClusterProjects")]
[Index(nameof(EnvironmentClusterId), Name = "IX_EnvironmentClusterId")]
public class EnvironmentClusterProject : Entity<int>
{
[Comment("Environment cluster Id")]
[Range(1, int.MaxValue, ErrorMessage = "Environment cluster is required")]
public int EnvironmentClusterId { get; set; }
[Comment("System Id")]
[Range(1, int.MaxValue, ErrorMessage = "Project is required")]
public int ProjectId { get; set; }
}
}
| 31.454545 | 82 | 0.696532 | [
"Apache-2.0"
] | masastack/MASA.PM | src/Services/MASA.PM.Service.Admin/Infrastructure/Entities/EnvironmentClusterProject.cs | 694 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Elastic.Apm.Api;
using Elastic.Apm.Config;
using Elastic.Apm.Logging;
namespace Elastic.Apm.Helpers
{
internal static class StacktraceHelper
{
private const string DefaultAsyncMethodName = "MoveNext";
/// <summary>
/// Turns a System.Diagnostic.StackFrame[] into a <see cref="CapturedStackFrame" /> list which can be reported to the APM
/// Server
/// </summary>
/// <param name="frames">The stack frames to rewrite into APM stack traces</param>
/// <param name="logger">The logger to emit exceptions on should one occur</param>
/// <param name="dbgCapturingFor">Just for logging.</param>
/// <param name="configurationReader">
/// Config reader - this controls the collection of stack traces (e.g. limit on frames,
/// etc)
/// </param>
/// <returns>A prepared List that can be passed to the APM server</returns>
internal static List<CapturedStackFrame> GenerateApmStackTrace(StackFrame[] frames, IApmLogger logger,
IConfigurationReader configurationReader, string dbgCapturingFor
)
{
var stackTraceLimit = configurationReader.StackTraceLimit;
if (stackTraceLimit == 0)
return null;
if (stackTraceLimit > 0)
// new StackTrace(skipFrames: n) skips frames from the top of the stack (currently executing method is top)
// the StackTraceLimit feature takes the top n frames, so unfortunately we currently capture the whole stack trace and just take
// the top `configurationReader.StackTraceLimit` frames. - This could be optimized.
frames = frames.Take(stackTraceLimit).ToArray();
var retVal = new List<CapturedStackFrame>(frames.Length);
logger.Trace()?.Log("transform stack frames");
try
{
foreach (var frame in frames)
{
var fileName = frame?.GetMethod()
?.DeclaringType?.FullName; //see: https://github.com/elastic/apm-agent-dotnet/pull/240#discussion_r289619196
var functionName = GetRealMethodName(frame?.GetMethod());
logger.Trace()?.Log("{MethodName}, {lineNo}", functionName, frame?.GetFileLineNumber());
retVal.Add(new CapturedStackFrame
{
Function = functionName ?? "N/A",
FileName = string.IsNullOrWhiteSpace(fileName) ? "N/A" : fileName,
Module = frame?.GetMethod()?.ReflectedType?.Assembly.FullName,
LineNo = frame?.GetFileLineNumber() ?? 0,
AbsPath = frame?.GetFileName() // optional property
});
}
}
catch (Exception e)
{
logger?.Warning()?.LogException(e, "Failed capturing stacktrace for {ApmContext}", dbgCapturingFor);
}
return retVal;
}
/// <summary>
/// Turns an <see cref="Exception" /> into a <see cref="CapturedStackFrame" /> list which can be reported to the APM
/// Server
/// </summary>
/// <param name="exception">The exception to rewrite into APM stack traces</param>
/// <param name="logger">The logger to emit exceptions on should one occur</param>
/// <param name="dbgCapturingFor">Just for logging.</param>
/// <param name="configurationReader">
/// Config reader - this controls the collection of stack traces (e.g. limit on frames,
/// etc)
/// </param>
/// <returns>A prepared List that can be passed to the APM server</returns>
internal static List<CapturedStackFrame> GenerateApmStackTrace(Exception exception, IApmLogger logger, string dbgCapturingFor,
IConfigurationReader configurationReader
)
{
var stackTraceLimit = configurationReader.StackTraceLimit;
if (stackTraceLimit == 0)
return null;
try
{
try
{
return GenerateApmStackTrace(
new EnhancedStackTrace(exception).GetFrames(), logger, configurationReader, dbgCapturingFor);
}
catch (Exception e)
{
logger?.Debug()?
.LogException(e, "Failed generating stack trace with EnhancedStackTrace - using fallback without demystification");
// Fallback, see https://github.com/elastic/apm-agent-dotnet/issues/957
// This callstack won't be demystified, but at least it'll be captured.
return GenerateApmStackTrace(
new StackTrace(exception, true).GetFrames(), logger, configurationReader, dbgCapturingFor);
}
}
catch (Exception e)
{
logger?.Warning()?.Log("Failed extracting stack trace from exception for {ApmContext}."
+ " Exception for failure to extract: {ExceptionForFailureToExtract}."
+ " Exception to extract from: {ExceptionToExtractFrom}.",
dbgCapturingFor, e, exception);
}
return null;
}
/// <summary>
/// Finds real method name even for Async methods, full description of the issue is available here
/// https://stackoverflow.com/a/28633192
/// </summary>
/// <param name="inputMethod">Method to discover</param>
/// <returns>A real method name (even for async methods)</returns>
private static string GetRealMethodName(MethodBase inputMethod)
{
if (inputMethod == null)
return null;
if (inputMethod.Name != DefaultAsyncMethodName)
return inputMethod.Name;
var declaredType = inputMethod.DeclaringType;
if (declaredType == null)
return DefaultAsyncMethodName;
if (declaredType.GetInterfaces().All(i => i != typeof(IAsyncStateMachine)))
return DefaultAsyncMethodName;
var generatedType = inputMethod.DeclaringType;
var originalType = generatedType?.DeclaringType;
if (originalType == null)
return DefaultAsyncMethodName;
var foundMethod = originalType.GetMethods(BindingFlags.Instance | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly)
.FirstOrDefault(m => m.GetCustomAttribute<AsyncStateMachineAttribute>()?.StateMachineType == generatedType);
return foundMethod?.Name ?? DefaultAsyncMethodName;
}
}
}
| 35.047904 | 132 | 0.712284 | [
"MIT"
] | arleyscastro/lumini-hire-test | src/Elastic.Apm/Helpers/StacktraceHelper.cs | 5,853 | C# |
namespace ConfigApp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ApplyButton = new System.Windows.Forms.Button();
this.Tabs = new System.Windows.Forms.TabControl();
this.LeftSettings = new System.Windows.Forms.TabPage();
this.yawrightLtext = new System.Windows.Forms.TextBox();
this.yawleftLtext = new System.Windows.Forms.TextBox();
this.rollrightLtext = new System.Windows.Forms.TextBox();
this.rollleftLtext = new System.Windows.Forms.TextBox();
this.pitchdownLtext = new System.Windows.Forms.TextBox();
this.pitchupLtext = new System.Windows.Forms.TextBox();
this.touch4Ltext = new System.Windows.Forms.TextBox();
this.touch3Ltext = new System.Windows.Forms.TextBox();
this.touch2Ltext = new System.Windows.Forms.TextBox();
this.touch1Ltext = new System.Windows.Forms.TextBox();
this.flex4Ltext = new System.Windows.Forms.TextBox();
this.flex3Ltext = new System.Windows.Forms.TextBox();
this.flex2Ltext = new System.Windows.Forms.TextBox();
this.flex1Ltext = new System.Windows.Forms.TextBox();
this.yawrightlabelL = new System.Windows.Forms.Label();
this.yawleftlabelL = new System.Windows.Forms.Label();
this.rolllrightlabelL = new System.Windows.Forms.Label();
this.rollleftlabelL = new System.Windows.Forms.Label();
this.pitchdownlabelL = new System.Windows.Forms.Label();
this.pitchuplabelL = new System.Windows.Forms.Label();
this.touch4labelL = new System.Windows.Forms.Label();
this.touch3labelL = new System.Windows.Forms.Label();
this.touch2labelL = new System.Windows.Forms.Label();
this.touch1labelL = new System.Windows.Forms.Label();
this.flex4labelL = new System.Windows.Forms.Label();
this.flex3labelL = new System.Windows.Forms.Label();
this.flex2labelL = new System.Windows.Forms.Label();
this.flex1LabelL = new System.Windows.Forms.Label();
this.LeftMappingHeader = new System.Windows.Forms.Label();
this.LeftGestureHeader = new System.Windows.Forms.LinkLabel();
this.RightSettings = new System.Windows.Forms.TabPage();
this.yawrightRtext = new System.Windows.Forms.TextBox();
this.yawleftRtext = new System.Windows.Forms.TextBox();
this.rollrightRtext = new System.Windows.Forms.TextBox();
this.rollleftRtext = new System.Windows.Forms.TextBox();
this.pitchdownRtext = new System.Windows.Forms.TextBox();
this.pitchupRtext = new System.Windows.Forms.TextBox();
this.touch4Rtext = new System.Windows.Forms.TextBox();
this.touch3Rtext = new System.Windows.Forms.TextBox();
this.touch2Rtext = new System.Windows.Forms.TextBox();
this.touch1Rtext = new System.Windows.Forms.TextBox();
this.flex4Rtext = new System.Windows.Forms.TextBox();
this.flex3Rtext = new System.Windows.Forms.TextBox();
this.flex2Rtext = new System.Windows.Forms.TextBox();
this.flex1Rtext = new System.Windows.Forms.TextBox();
this.rawrightlabelR = new System.Windows.Forms.Label();
this.yawleftlabelR = new System.Windows.Forms.Label();
this.rollrightlabelR = new System.Windows.Forms.Label();
this.rollleftlabelR = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.pitchuplabelR = new System.Windows.Forms.Label();
this.touch4labelR = new System.Windows.Forms.Label();
this.touch3labelR = new System.Windows.Forms.Label();
this.touch2labelR = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.flex4labelR = new System.Windows.Forms.Label();
this.flex3labelR = new System.Windows.Forms.Label();
this.flex2labelR = new System.Windows.Forms.Label();
this.flex1labelR = new System.Windows.Forms.Label();
this.RightMappingHeader = new System.Windows.Forms.Label();
this.RightGestureHeading = new System.Windows.Forms.LinkLabel();
this.comPortLabel = new System.Windows.Forms.Label();
this.comPortDropDown = new System.Windows.Forms.ComboBox();
this.Tabs.SuspendLayout();
this.LeftSettings.SuspendLayout();
this.RightSettings.SuspendLayout();
this.SuspendLayout();
//
// ApplyButton
//
this.ApplyButton.Location = new System.Drawing.Point(155, 579);
this.ApplyButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.ApplyButton.Name = "ApplyButton";
this.ApplyButton.Size = new System.Drawing.Size(100, 28);
this.ApplyButton.TabIndex = 2;
this.ApplyButton.Text = "Apply";
this.ApplyButton.UseVisualStyleBackColor = true;
//
// Tabs
//
this.Tabs.Controls.Add(this.LeftSettings);
this.Tabs.Controls.Add(this.RightSettings);
this.Tabs.Location = new System.Drawing.Point(16, 38);
this.Tabs.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Tabs.Multiline = true;
this.Tabs.Name = "Tabs";
this.Tabs.SelectedIndex = 0;
this.Tabs.Size = new System.Drawing.Size(375, 533);
this.Tabs.TabIndex = 6;
//
// LeftSettings
//
this.LeftSettings.BackColor = System.Drawing.SystemColors.ControlLight;
this.LeftSettings.Controls.Add(this.yawrightLtext);
this.LeftSettings.Controls.Add(this.yawleftLtext);
this.LeftSettings.Controls.Add(this.rollrightLtext);
this.LeftSettings.Controls.Add(this.rollleftLtext);
this.LeftSettings.Controls.Add(this.pitchdownLtext);
this.LeftSettings.Controls.Add(this.pitchupLtext);
this.LeftSettings.Controls.Add(this.touch4Ltext);
this.LeftSettings.Controls.Add(this.touch3Ltext);
this.LeftSettings.Controls.Add(this.touch2Ltext);
this.LeftSettings.Controls.Add(this.touch1Ltext);
this.LeftSettings.Controls.Add(this.flex4Ltext);
this.LeftSettings.Controls.Add(this.flex3Ltext);
this.LeftSettings.Controls.Add(this.flex2Ltext);
this.LeftSettings.Controls.Add(this.flex1Ltext);
this.LeftSettings.Controls.Add(this.yawrightlabelL);
this.LeftSettings.Controls.Add(this.yawleftlabelL);
this.LeftSettings.Controls.Add(this.rolllrightlabelL);
this.LeftSettings.Controls.Add(this.rollleftlabelL);
this.LeftSettings.Controls.Add(this.pitchdownlabelL);
this.LeftSettings.Controls.Add(this.pitchuplabelL);
this.LeftSettings.Controls.Add(this.touch4labelL);
this.LeftSettings.Controls.Add(this.touch3labelL);
this.LeftSettings.Controls.Add(this.touch2labelL);
this.LeftSettings.Controls.Add(this.touch1labelL);
this.LeftSettings.Controls.Add(this.flex4labelL);
this.LeftSettings.Controls.Add(this.flex3labelL);
this.LeftSettings.Controls.Add(this.flex2labelL);
this.LeftSettings.Controls.Add(this.flex1LabelL);
this.LeftSettings.Controls.Add(this.LeftMappingHeader);
this.LeftSettings.Controls.Add(this.LeftGestureHeader);
this.LeftSettings.Location = new System.Drawing.Point(4, 25);
this.LeftSettings.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.LeftSettings.Name = "LeftSettings";
this.LeftSettings.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.LeftSettings.Size = new System.Drawing.Size(367, 504);
this.LeftSettings.TabIndex = 0;
this.LeftSettings.Text = "Left Glove";
this.LeftSettings.Click += new System.EventHandler(this.tabPage1_Click_1);
//
// yawrightLtext
//
this.yawrightLtext.Location = new System.Drawing.Point(175, 459);
this.yawrightLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.yawrightLtext.Name = "yawrightLtext";
this.yawrightLtext.Size = new System.Drawing.Size(180, 22);
this.yawrightLtext.TabIndex = 39;
//
// yawleftLtext
//
this.yawleftLtext.Location = new System.Drawing.Point(175, 426);
this.yawleftLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.yawleftLtext.Name = "yawleftLtext";
this.yawleftLtext.Size = new System.Drawing.Size(180, 22);
this.yawleftLtext.TabIndex = 38;
//
// rollrightLtext
//
this.rollrightLtext.Location = new System.Drawing.Point(175, 393);
this.rollrightLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.rollrightLtext.Name = "rollrightLtext";
this.rollrightLtext.Size = new System.Drawing.Size(180, 22);
this.rollrightLtext.TabIndex = 37;
//
// rollleftLtext
//
this.rollleftLtext.Location = new System.Drawing.Point(175, 359);
this.rollleftLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.rollleftLtext.Name = "rollleftLtext";
this.rollleftLtext.Size = new System.Drawing.Size(180, 22);
this.rollleftLtext.TabIndex = 36;
//
// pitchdownLtext
//
this.pitchdownLtext.Location = new System.Drawing.Point(175, 326);
this.pitchdownLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.pitchdownLtext.Name = "pitchdownLtext";
this.pitchdownLtext.Size = new System.Drawing.Size(180, 22);
this.pitchdownLtext.TabIndex = 35;
//
// pitchupLtext
//
this.pitchupLtext.Location = new System.Drawing.Point(175, 293);
this.pitchupLtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.pitchupLtext.Name = "pitchupLtext";
this.pitchupLtext.Size = new System.Drawing.Size(180, 22);
this.pitchupLtext.TabIndex = 34;
//
// touch4Ltext
//
this.touch4Ltext.Location = new System.Drawing.Point(175, 260);
this.touch4Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch4Ltext.Name = "touch4Ltext";
this.touch4Ltext.Size = new System.Drawing.Size(180, 22);
this.touch4Ltext.TabIndex = 33;
//
// touch3Ltext
//
this.touch3Ltext.Location = new System.Drawing.Point(175, 226);
this.touch3Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch3Ltext.Name = "touch3Ltext";
this.touch3Ltext.Size = new System.Drawing.Size(180, 22);
this.touch3Ltext.TabIndex = 32;
//
// touch2Ltext
//
this.touch2Ltext.Location = new System.Drawing.Point(175, 193);
this.touch2Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch2Ltext.Name = "touch2Ltext";
this.touch2Ltext.Size = new System.Drawing.Size(180, 22);
this.touch2Ltext.TabIndex = 31;
//
// touch1Ltext
//
this.touch1Ltext.Location = new System.Drawing.Point(175, 160);
this.touch1Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch1Ltext.Name = "touch1Ltext";
this.touch1Ltext.Size = new System.Drawing.Size(180, 22);
this.touch1Ltext.TabIndex = 30;
//
// flex4Ltext
//
this.flex4Ltext.Location = new System.Drawing.Point(175, 127);
this.flex4Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex4Ltext.Name = "flex4Ltext";
this.flex4Ltext.Size = new System.Drawing.Size(180, 22);
this.flex4Ltext.TabIndex = 29;
//
// flex3Ltext
//
this.flex3Ltext.Location = new System.Drawing.Point(175, 94);
this.flex3Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex3Ltext.Name = "flex3Ltext";
this.flex3Ltext.Size = new System.Drawing.Size(180, 22);
this.flex3Ltext.TabIndex = 28;
//
// flex2Ltext
//
this.flex2Ltext.Location = new System.Drawing.Point(175, 60);
this.flex2Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex2Ltext.Name = "flex2Ltext";
this.flex2Ltext.Size = new System.Drawing.Size(180, 22);
this.flex2Ltext.TabIndex = 27;
//
// flex1Ltext
//
this.flex1Ltext.Location = new System.Drawing.Point(175, 27);
this.flex1Ltext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex1Ltext.Name = "flex1Ltext";
this.flex1Ltext.Size = new System.Drawing.Size(180, 22);
this.flex1Ltext.TabIndex = 26;
this.flex1Ltext.TextChanged += new System.EventHandler(this.flex1Ltext_TextChanged);
//
// yawrightlabelL
//
this.yawrightlabelL.AutoSize = true;
this.yawrightlabelL.Location = new System.Drawing.Point(8, 463);
this.yawrightlabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.yawrightlabelL.Name = "yawrightlabelL";
this.yawrightlabelL.Size = new System.Drawing.Size(82, 17);
this.yawrightlabelL.TabIndex = 24;
this.yawrightlabelL.Text = "YAWRIGHT";
//
// yawleftlabelL
//
this.yawleftlabelL.AutoSize = true;
this.yawleftlabelL.Location = new System.Drawing.Point(8, 430);
this.yawleftlabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.yawleftlabelL.Name = "yawleftlabelL";
this.yawleftlabelL.Size = new System.Drawing.Size(73, 17);
this.yawleftlabelL.TabIndex = 23;
this.yawleftlabelL.Text = "YAWLEFT";
//
// rolllrightlabelL
//
this.rolllrightlabelL.AutoSize = true;
this.rolllrightlabelL.Location = new System.Drawing.Point(8, 396);
this.rolllrightlabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rolllrightlabelL.Name = "rolllrightlabelL";
this.rolllrightlabelL.Size = new System.Drawing.Size(88, 17);
this.rolllrightlabelL.TabIndex = 22;
this.rolllrightlabelL.Text = "ROLLRIGHT";
//
// rollleftlabelL
//
this.rollleftlabelL.AutoSize = true;
this.rollleftlabelL.Location = new System.Drawing.Point(8, 363);
this.rollleftlabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rollleftlabelL.Name = "rollleftlabelL";
this.rollleftlabelL.Size = new System.Drawing.Size(79, 17);
this.rollleftlabelL.TabIndex = 21;
this.rollleftlabelL.Text = "ROLLLEFT";
//
// pitchdownlabelL
//
this.pitchdownlabelL.AutoSize = true;
this.pitchdownlabelL.Location = new System.Drawing.Point(8, 330);
this.pitchdownlabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.pitchdownlabelL.Name = "pitchdownlabelL";
this.pitchdownlabelL.Size = new System.Drawing.Size(92, 17);
this.pitchdownlabelL.TabIndex = 20;
this.pitchdownlabelL.Text = "PITCHDOWN";
//
// pitchuplabelL
//
this.pitchuplabelL.AutoSize = true;
this.pitchuplabelL.Location = new System.Drawing.Point(8, 297);
this.pitchuplabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.pitchuplabelL.Name = "pitchuplabelL";
this.pitchuplabelL.Size = new System.Drawing.Size(67, 17);
this.pitchuplabelL.TabIndex = 19;
this.pitchuplabelL.Text = "PITCHUP";
//
// touch4labelL
//
this.touch4labelL.AutoSize = true;
this.touch4labelL.Location = new System.Drawing.Point(8, 263);
this.touch4labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch4labelL.Name = "touch4labelL";
this.touch4labelL.Size = new System.Drawing.Size(65, 17);
this.touch4labelL.TabIndex = 18;
this.touch4labelL.Text = "TOUCH4";
//
// touch3labelL
//
this.touch3labelL.AutoSize = true;
this.touch3labelL.Location = new System.Drawing.Point(8, 230);
this.touch3labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch3labelL.Name = "touch3labelL";
this.touch3labelL.Size = new System.Drawing.Size(65, 17);
this.touch3labelL.TabIndex = 17;
this.touch3labelL.Text = "TOUCH3";
//
// touch2labelL
//
this.touch2labelL.AutoSize = true;
this.touch2labelL.Location = new System.Drawing.Point(8, 197);
this.touch2labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch2labelL.Name = "touch2labelL";
this.touch2labelL.Size = new System.Drawing.Size(65, 17);
this.touch2labelL.TabIndex = 16;
this.touch2labelL.Text = "TOUCH2";
//
// touch1labelL
//
this.touch1labelL.AutoSize = true;
this.touch1labelL.Location = new System.Drawing.Point(8, 164);
this.touch1labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch1labelL.Name = "touch1labelL";
this.touch1labelL.Size = new System.Drawing.Size(65, 17);
this.touch1labelL.TabIndex = 15;
this.touch1labelL.Text = "TOUCH1";
//
// flex4labelL
//
this.flex4labelL.AutoSize = true;
this.flex4labelL.Location = new System.Drawing.Point(8, 130);
this.flex4labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex4labelL.Name = "flex4labelL";
this.flex4labelL.Size = new System.Drawing.Size(50, 17);
this.flex4labelL.TabIndex = 14;
this.flex4labelL.Text = "FLEX4";
//
// flex3labelL
//
this.flex3labelL.AutoSize = true;
this.flex3labelL.Location = new System.Drawing.Point(8, 97);
this.flex3labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex3labelL.Name = "flex3labelL";
this.flex3labelL.Size = new System.Drawing.Size(50, 17);
this.flex3labelL.TabIndex = 13;
this.flex3labelL.Text = "FLEX3";
//
// flex2labelL
//
this.flex2labelL.AutoSize = true;
this.flex2labelL.Location = new System.Drawing.Point(8, 64);
this.flex2labelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex2labelL.Name = "flex2labelL";
this.flex2labelL.Size = new System.Drawing.Size(50, 17);
this.flex2labelL.TabIndex = 12;
this.flex2labelL.Text = "FLEX2";
//
// flex1LabelL
//
this.flex1LabelL.AutoSize = true;
this.flex1LabelL.Location = new System.Drawing.Point(8, 31);
this.flex1LabelL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex1LabelL.Name = "flex1LabelL";
this.flex1LabelL.Size = new System.Drawing.Size(50, 17);
this.flex1LabelL.TabIndex = 11;
this.flex1LabelL.Text = "FLEX1";
this.flex1LabelL.Click += new System.EventHandler(this.label2_Click);
//
// LeftMappingHeader
//
this.LeftMappingHeader.AutoSize = true;
this.LeftMappingHeader.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LeftMappingHeader.Location = new System.Drawing.Point(171, 4);
this.LeftMappingHeader.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.LeftMappingHeader.Name = "LeftMappingHeader";
this.LeftMappingHeader.Size = new System.Drawing.Size(162, 19);
this.LeftMappingHeader.TabIndex = 1;
this.LeftMappingHeader.Text = "Keyboard Mapping:";
//
// LeftGestureHeader
//
this.LeftGestureHeader.AutoSize = true;
this.LeftGestureHeader.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LeftGestureHeader.LinkColor = System.Drawing.Color.Black;
this.LeftGestureHeader.Location = new System.Drawing.Point(8, 4);
this.LeftGestureHeader.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.LeftGestureHeader.Name = "LeftGestureHeader";
this.LeftGestureHeader.Size = new System.Drawing.Size(78, 19);
this.LeftGestureHeader.TabIndex = 0;
this.LeftGestureHeader.TabStop = true;
this.LeftGestureHeader.Text = "Gesture:";
//
// RightSettings
//
this.RightSettings.BackColor = System.Drawing.SystemColors.ControlLight;
this.RightSettings.Controls.Add(this.yawrightRtext);
this.RightSettings.Controls.Add(this.yawleftRtext);
this.RightSettings.Controls.Add(this.rollrightRtext);
this.RightSettings.Controls.Add(this.rollleftRtext);
this.RightSettings.Controls.Add(this.pitchdownRtext);
this.RightSettings.Controls.Add(this.pitchupRtext);
this.RightSettings.Controls.Add(this.touch4Rtext);
this.RightSettings.Controls.Add(this.touch3Rtext);
this.RightSettings.Controls.Add(this.touch2Rtext);
this.RightSettings.Controls.Add(this.touch1Rtext);
this.RightSettings.Controls.Add(this.flex4Rtext);
this.RightSettings.Controls.Add(this.flex3Rtext);
this.RightSettings.Controls.Add(this.flex2Rtext);
this.RightSettings.Controls.Add(this.flex1Rtext);
this.RightSettings.Controls.Add(this.rawrightlabelR);
this.RightSettings.Controls.Add(this.yawleftlabelR);
this.RightSettings.Controls.Add(this.rollrightlabelR);
this.RightSettings.Controls.Add(this.rollleftlabelR);
this.RightSettings.Controls.Add(this.label2);
this.RightSettings.Controls.Add(this.label1);
this.RightSettings.Controls.Add(this.pitchuplabelR);
this.RightSettings.Controls.Add(this.touch4labelR);
this.RightSettings.Controls.Add(this.touch3labelR);
this.RightSettings.Controls.Add(this.touch2labelR);
this.RightSettings.Controls.Add(this.label14);
this.RightSettings.Controls.Add(this.flex4labelR);
this.RightSettings.Controls.Add(this.flex3labelR);
this.RightSettings.Controls.Add(this.flex2labelR);
this.RightSettings.Controls.Add(this.flex1labelR);
this.RightSettings.Controls.Add(this.RightMappingHeader);
this.RightSettings.Controls.Add(this.RightGestureHeading);
this.RightSettings.Location = new System.Drawing.Point(4, 25);
this.RightSettings.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.RightSettings.Name = "RightSettings";
this.RightSettings.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.RightSettings.Size = new System.Drawing.Size(367, 504);
this.RightSettings.TabIndex = 1;
this.RightSettings.Text = "Right Glove";
this.RightSettings.Click += new System.EventHandler(this.tabPage2_Click);
//
// yawrightRtext
//
this.yawrightRtext.Location = new System.Drawing.Point(175, 459);
this.yawrightRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.yawrightRtext.Name = "yawrightRtext";
this.yawrightRtext.Size = new System.Drawing.Size(180, 22);
this.yawrightRtext.TabIndex = 40;
//
// yawleftRtext
//
this.yawleftRtext.Location = new System.Drawing.Point(175, 426);
this.yawleftRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.yawleftRtext.Name = "yawleftRtext";
this.yawleftRtext.Size = new System.Drawing.Size(180, 22);
this.yawleftRtext.TabIndex = 39;
//
// rollrightRtext
//
this.rollrightRtext.Location = new System.Drawing.Point(175, 393);
this.rollrightRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.rollrightRtext.Name = "rollrightRtext";
this.rollrightRtext.Size = new System.Drawing.Size(180, 22);
this.rollrightRtext.TabIndex = 38;
//
// rollleftRtext
//
this.rollleftRtext.Location = new System.Drawing.Point(175, 359);
this.rollleftRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.rollleftRtext.Name = "rollleftRtext";
this.rollleftRtext.Size = new System.Drawing.Size(180, 22);
this.rollleftRtext.TabIndex = 37;
//
// pitchdownRtext
//
this.pitchdownRtext.Location = new System.Drawing.Point(175, 326);
this.pitchdownRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.pitchdownRtext.Name = "pitchdownRtext";
this.pitchdownRtext.Size = new System.Drawing.Size(180, 22);
this.pitchdownRtext.TabIndex = 36;
//
// pitchupRtext
//
this.pitchupRtext.Location = new System.Drawing.Point(175, 293);
this.pitchupRtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.pitchupRtext.Name = "pitchupRtext";
this.pitchupRtext.Size = new System.Drawing.Size(180, 22);
this.pitchupRtext.TabIndex = 35;
//
// touch4Rtext
//
this.touch4Rtext.Location = new System.Drawing.Point(175, 260);
this.touch4Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch4Rtext.Name = "touch4Rtext";
this.touch4Rtext.Size = new System.Drawing.Size(180, 22);
this.touch4Rtext.TabIndex = 34;
//
// touch3Rtext
//
this.touch3Rtext.Location = new System.Drawing.Point(175, 226);
this.touch3Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch3Rtext.Name = "touch3Rtext";
this.touch3Rtext.Size = new System.Drawing.Size(180, 22);
this.touch3Rtext.TabIndex = 33;
//
// touch2Rtext
//
this.touch2Rtext.Location = new System.Drawing.Point(175, 193);
this.touch2Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch2Rtext.Name = "touch2Rtext";
this.touch2Rtext.Size = new System.Drawing.Size(180, 22);
this.touch2Rtext.TabIndex = 32;
//
// touch1Rtext
//
this.touch1Rtext.Location = new System.Drawing.Point(175, 160);
this.touch1Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.touch1Rtext.Name = "touch1Rtext";
this.touch1Rtext.Size = new System.Drawing.Size(180, 22);
this.touch1Rtext.TabIndex = 31;
//
// flex4Rtext
//
this.flex4Rtext.Location = new System.Drawing.Point(175, 127);
this.flex4Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex4Rtext.Name = "flex4Rtext";
this.flex4Rtext.Size = new System.Drawing.Size(180, 22);
this.flex4Rtext.TabIndex = 30;
//
// flex3Rtext
//
this.flex3Rtext.Location = new System.Drawing.Point(175, 94);
this.flex3Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex3Rtext.Name = "flex3Rtext";
this.flex3Rtext.Size = new System.Drawing.Size(180, 22);
this.flex3Rtext.TabIndex = 29;
//
// flex2Rtext
//
this.flex2Rtext.Location = new System.Drawing.Point(175, 60);
this.flex2Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex2Rtext.Name = "flex2Rtext";
this.flex2Rtext.Size = new System.Drawing.Size(180, 22);
this.flex2Rtext.TabIndex = 28;
//
// flex1Rtext
//
this.flex1Rtext.Location = new System.Drawing.Point(175, 27);
this.flex1Rtext.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.flex1Rtext.Name = "flex1Rtext";
this.flex1Rtext.Size = new System.Drawing.Size(180, 22);
this.flex1Rtext.TabIndex = 27;
this.flex1Rtext.TextChanged += new System.EventHandler(this.flex1Rtext_TextChanged);
//
// rawrightlabelR
//
this.rawrightlabelR.AutoSize = true;
this.rawrightlabelR.Location = new System.Drawing.Point(8, 463);
this.rawrightlabelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rawrightlabelR.Name = "rawrightlabelR";
this.rawrightlabelR.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.rawrightlabelR.Size = new System.Drawing.Size(82, 17);
this.rawrightlabelR.TabIndex = 25;
this.rawrightlabelR.Text = "YAWRIGHT";
//
// yawleftlabelR
//
this.yawleftlabelR.AutoSize = true;
this.yawleftlabelR.Location = new System.Drawing.Point(8, 430);
this.yawleftlabelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.yawleftlabelR.Name = "yawleftlabelR";
this.yawleftlabelR.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.yawleftlabelR.Size = new System.Drawing.Size(73, 17);
this.yawleftlabelR.TabIndex = 24;
this.yawleftlabelR.Text = "YAWLEFT";
//
// rollrightlabelR
//
this.rollrightlabelR.AutoSize = true;
this.rollrightlabelR.Location = new System.Drawing.Point(8, 396);
this.rollrightlabelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rollrightlabelR.Name = "rollrightlabelR";
this.rollrightlabelR.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.rollrightlabelR.Size = new System.Drawing.Size(88, 17);
this.rollrightlabelR.TabIndex = 23;
this.rollrightlabelR.Text = "ROLLRIGHT";
//
// rollleftlabelR
//
this.rollleftlabelR.AutoSize = true;
this.rollleftlabelR.Location = new System.Drawing.Point(8, 363);
this.rollleftlabelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rollleftlabelR.Name = "rollleftlabelR";
this.rollleftlabelR.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.rollleftlabelR.Size = new System.Drawing.Size(79, 17);
this.rollleftlabelR.TabIndex = 22;
this.rollleftlabelR.Text = "ROLLLEFT";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(8, 330);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.label2.Size = new System.Drawing.Size(92, 17);
this.label2.TabIndex = 21;
this.label2.Text = "PITCHDOWN";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 334);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.label1.Size = new System.Drawing.Size(0, 17);
this.label1.TabIndex = 20;
this.label1.Click += new System.EventHandler(this.label1_Click_1);
//
// pitchuplabelR
//
this.pitchuplabelR.AutoSize = true;
this.pitchuplabelR.Location = new System.Drawing.Point(8, 297);
this.pitchuplabelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.pitchuplabelR.Name = "pitchuplabelR";
this.pitchuplabelR.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.pitchuplabelR.Size = new System.Drawing.Size(67, 17);
this.pitchuplabelR.TabIndex = 19;
this.pitchuplabelR.Text = "PITCHUP";
//
// touch4labelR
//
this.touch4labelR.AutoSize = true;
this.touch4labelR.Location = new System.Drawing.Point(8, 263);
this.touch4labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch4labelR.Name = "touch4labelR";
this.touch4labelR.Size = new System.Drawing.Size(65, 17);
this.touch4labelR.TabIndex = 18;
this.touch4labelR.Text = "TOUCH4";
//
// touch3labelR
//
this.touch3labelR.AutoSize = true;
this.touch3labelR.Location = new System.Drawing.Point(8, 230);
this.touch3labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch3labelR.Name = "touch3labelR";
this.touch3labelR.Size = new System.Drawing.Size(65, 17);
this.touch3labelR.TabIndex = 17;
this.touch3labelR.Text = "TOUCH3";
//
// touch2labelR
//
this.touch2labelR.AutoSize = true;
this.touch2labelR.Location = new System.Drawing.Point(8, 197);
this.touch2labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.touch2labelR.Name = "touch2labelR";
this.touch2labelR.Size = new System.Drawing.Size(65, 17);
this.touch2labelR.TabIndex = 16;
this.touch2labelR.Text = "TOUCH2";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(8, 164);
this.label14.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(65, 17);
this.label14.TabIndex = 15;
this.label14.Text = "TOUCH1";
//
// flex4labelR
//
this.flex4labelR.AutoSize = true;
this.flex4labelR.Location = new System.Drawing.Point(8, 130);
this.flex4labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex4labelR.Name = "flex4labelR";
this.flex4labelR.Size = new System.Drawing.Size(50, 17);
this.flex4labelR.TabIndex = 14;
this.flex4labelR.Text = "FLEX4";
//
// flex3labelR
//
this.flex3labelR.AutoSize = true;
this.flex3labelR.Location = new System.Drawing.Point(8, 97);
this.flex3labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex3labelR.Name = "flex3labelR";
this.flex3labelR.Size = new System.Drawing.Size(50, 17);
this.flex3labelR.TabIndex = 13;
this.flex3labelR.Text = "FLEX3";
//
// flex2labelR
//
this.flex2labelR.AutoSize = true;
this.flex2labelR.Location = new System.Drawing.Point(8, 64);
this.flex2labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex2labelR.Name = "flex2labelR";
this.flex2labelR.Size = new System.Drawing.Size(50, 17);
this.flex2labelR.TabIndex = 12;
this.flex2labelR.Text = "FLEX2";
//
// flex1labelR
//
this.flex1labelR.AutoSize = true;
this.flex1labelR.Location = new System.Drawing.Point(8, 31);
this.flex1labelR.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.flex1labelR.Name = "flex1labelR";
this.flex1labelR.Size = new System.Drawing.Size(50, 17);
this.flex1labelR.TabIndex = 11;
this.flex1labelR.Text = "FLEX1";
this.flex1labelR.Click += new System.EventHandler(this.label1_Click);
//
// RightMappingHeader
//
this.RightMappingHeader.AutoSize = true;
this.RightMappingHeader.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.RightMappingHeader.Location = new System.Drawing.Point(171, 4);
this.RightMappingHeader.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.RightMappingHeader.Name = "RightMappingHeader";
this.RightMappingHeader.Size = new System.Drawing.Size(162, 19);
this.RightMappingHeader.TabIndex = 1;
this.RightMappingHeader.Text = "Keyboard Mapping:";
//
// RightGestureHeading
//
this.RightGestureHeading.AutoSize = true;
this.RightGestureHeading.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.RightGestureHeading.LinkColor = System.Drawing.Color.Black;
this.RightGestureHeading.Location = new System.Drawing.Point(8, 4);
this.RightGestureHeading.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.RightGestureHeading.Name = "RightGestureHeading";
this.RightGestureHeading.Size = new System.Drawing.Size(78, 19);
this.RightGestureHeading.TabIndex = 0;
this.RightGestureHeading.TabStop = true;
this.RightGestureHeading.Text = "Gesture:";
//
// comPortLabel
//
this.comPortLabel.AutoSize = true;
this.comPortLabel.Location = new System.Drawing.Point(12, 9);
this.comPortLabel.Name = "comPortLabel";
this.comPortLabel.Size = new System.Drawing.Size(70, 17);
this.comPortLabel.TabIndex = 7;
this.comPortLabel.Text = "Com Port:";
//
// comPortDropDown
//
this.comPortDropDown.FormattingEnabled = true;
this.comPortDropDown.Location = new System.Drawing.Point(88, 6);
this.comPortDropDown.Name = "comPortDropDown";
this.comPortDropDown.Size = new System.Drawing.Size(121, 24);
this.comPortDropDown.TabIndex = 8;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.ClientSize = new System.Drawing.Size(407, 613);
this.Controls.Add(this.comPortDropDown);
this.Controls.Add(this.comPortLabel);
this.Controls.Add(this.Tabs);
this.Controls.Add(this.ApplyButton);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "Form1";
this.Text = "Glove Configuration";
this.Load += new System.EventHandler(this.Form1_Load);
this.Tabs.ResumeLayout(false);
this.LeftSettings.ResumeLayout(false);
this.LeftSettings.PerformLayout();
this.RightSettings.ResumeLayout(false);
this.RightSettings.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button ApplyButton;
private System.Windows.Forms.TabControl Tabs;
private System.Windows.Forms.TabPage LeftSettings;
private System.Windows.Forms.TabPage RightSettings;
private System.Windows.Forms.Label LeftMappingHeader;
private System.Windows.Forms.LinkLabel LeftGestureHeader;
private System.Windows.Forms.Label RightMappingHeader;
private System.Windows.Forms.LinkLabel RightGestureHeading;
private System.Windows.Forms.Label pitchuplabelL;
private System.Windows.Forms.Label touch4labelL;
private System.Windows.Forms.Label touch3labelL;
private System.Windows.Forms.Label touch2labelL;
private System.Windows.Forms.Label touch1labelL;
private System.Windows.Forms.Label flex4labelL;
private System.Windows.Forms.Label flex3labelL;
private System.Windows.Forms.Label flex2labelL;
private System.Windows.Forms.Label pitchuplabelR;
private System.Windows.Forms.Label touch4labelR;
private System.Windows.Forms.Label touch3labelR;
private System.Windows.Forms.Label touch2labelR;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label flex4labelR;
private System.Windows.Forms.Label flex3labelR;
private System.Windows.Forms.Label flex2labelR;
private System.Windows.Forms.Label flex1labelR;
private System.Windows.Forms.Label flex1LabelL;
private System.Windows.Forms.Label pitchdownlabelL;
private System.Windows.Forms.TextBox yawrightLtext;
private System.Windows.Forms.TextBox yawleftLtext;
private System.Windows.Forms.TextBox rollrightLtext;
private System.Windows.Forms.TextBox rollleftLtext;
private System.Windows.Forms.TextBox pitchdownLtext;
private System.Windows.Forms.TextBox pitchupLtext;
private System.Windows.Forms.TextBox touch4Ltext;
private System.Windows.Forms.TextBox touch3Ltext;
private System.Windows.Forms.TextBox touch2Ltext;
private System.Windows.Forms.TextBox touch1Ltext;
private System.Windows.Forms.TextBox flex4Ltext;
private System.Windows.Forms.TextBox flex3Ltext;
private System.Windows.Forms.TextBox flex2Ltext;
private System.Windows.Forms.TextBox flex1Ltext;
private System.Windows.Forms.Label yawrightlabelL;
private System.Windows.Forms.Label yawleftlabelL;
private System.Windows.Forms.Label rolllrightlabelL;
private System.Windows.Forms.Label rollleftlabelL;
private System.Windows.Forms.Label yawleftlabelR;
private System.Windows.Forms.Label rollrightlabelR;
private System.Windows.Forms.Label rollleftlabelR;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label rawrightlabelR;
private System.Windows.Forms.TextBox yawrightRtext;
private System.Windows.Forms.TextBox yawleftRtext;
private System.Windows.Forms.TextBox rollrightRtext;
private System.Windows.Forms.TextBox rollleftRtext;
private System.Windows.Forms.TextBox pitchdownRtext;
private System.Windows.Forms.TextBox pitchupRtext;
private System.Windows.Forms.TextBox touch4Rtext;
private System.Windows.Forms.TextBox touch3Rtext;
private System.Windows.Forms.TextBox touch2Rtext;
private System.Windows.Forms.TextBox touch1Rtext;
private System.Windows.Forms.TextBox flex4Rtext;
private System.Windows.Forms.TextBox flex3Rtext;
private System.Windows.Forms.TextBox flex2Rtext;
private System.Windows.Forms.TextBox flex1Rtext;
private System.Windows.Forms.Label comPortLabel;
private System.Windows.Forms.ComboBox comPortDropDown;
}
}
| 52.959777 | 162 | 0.592734 | [
"Apache-2.0"
] | apadin1/Team-GLOVE | ConfigApp/ConfigApp/Form1.Designer.cs | 47,401 | C# |
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Vostok.ServiceDiscovery.Abstractions
{
/// <summary>
/// Represents information about an instance of application registered in service discovery system.
/// </summary>
[PublicAPI]
public interface IReplicaInfo
{
/// <summary>
/// Application environment.
/// </summary>
[NotNull]
string Environment { get; }
/// <summary>
/// Application name.
/// </summary>
[NotNull]
string Application { get; }
/// <summary>
/// Application replica id.
/// </summary>
[NotNull]
string Replica { get; }
/// <summary>
/// Application properties.
/// </summary>
[NotNull]
IReadOnlyDictionary<string, string> Properties { get; }
}
} | 25.416667 | 104 | 0.537705 | [
"MIT"
] | borovskyav/servicediscovery.abstractions | Vostok.ServiceDiscovery.Abstractions/IReplicaInfo.cs | 917 | C# |
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Transports
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Context;
using Events;
using GreenPipes;
using Pipeline;
/// <summary>
/// A receive endpoint is called by the receive transport to push messages to consumers.
/// The receive endpoint is where the initial deserialization occurs, as well as any additional
/// filters on the receive context.
/// </summary>
public class ReceiveEndpoint :
IReceiveEndpointControl
{
readonly IReceiveTransport _receiveTransport;
ConnectHandle _handle;
readonly ReceiveEndpointContext _context;
public ReceiveEndpoint(IReceiveTransport receiveTransport, ReceiveEndpointContext context)
{
_context = context;
_receiveTransport = receiveTransport;
_handle = receiveTransport.ConnectReceiveTransportObserver(new Observer(this, context.EndpointObservers));
}
ReceiveEndpointContext IReceiveEndpoint.Context => _context;
ReceiveEndpointHandle IReceiveEndpointControl.Start()
{
var transportHandle = _receiveTransport.Start();
return new Handle(transportHandle);
}
void IProbeSite.Probe(ProbeContext context)
{
_receiveTransport.Probe(context);
_context.ReceivePipe.Probe(context);
}
ConnectHandle IReceiveObserverConnector.ConnectReceiveObserver(IReceiveObserver observer)
{
return _receiveTransport.ConnectReceiveObserver(observer);
}
ConnectHandle IReceiveEndpointObserverConnector.ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return _context.ConnectReceiveEndpointObserver(observer);
}
ConnectHandle IConsumeObserverConnector.ConnectConsumeObserver(IConsumeObserver observer)
{
return _context.ReceivePipe.ConnectConsumeObserver(observer);
}
ConnectHandle IConsumeMessageObserverConnector.ConnectConsumeMessageObserver<T>(IConsumeMessageObserver<T> observer)
{
return _context.ReceivePipe.ConnectConsumeMessageObserver(observer);
}
ConnectHandle IConsumePipeConnector.ConnectConsumePipe<T>(IPipe<ConsumeContext<T>> pipe)
{
return _context.ReceivePipe.ConnectConsumePipe(pipe);
}
ConnectHandle IRequestPipeConnector.ConnectRequestPipe<T>(Guid requestId, IPipe<ConsumeContext<T>> pipe)
{
return _context.ReceivePipe.ConnectRequestPipe(requestId, pipe);
}
ConnectHandle IPublishObserverConnector.ConnectPublishObserver(IPublishObserver observer)
{
return _receiveTransport.ConnectPublishObserver(observer);
}
ConnectHandle ISendObserverConnector.ConnectSendObserver(ISendObserver observer)
{
return _receiveTransport.ConnectSendObserver(observer);
}
public Task<ISendEndpoint> GetSendEndpoint(Uri address)
{
return _context.SendEndpointProvider.GetSendEndpoint(address);
}
public IPublishEndpoint CreatePublishEndpoint(Uri sourceAddress, ConsumeContext context = null)
{
return _context.PublishEndpointProvider.CreatePublishEndpoint(sourceAddress, context);
}
public Task<ISendEndpoint> GetPublishSendEndpoint<T>(T message)
where T : class
{
return _context.PublishEndpointProvider.GetPublishSendEndpoint(message);
}
class Observer :
IReceiveTransportObserver
{
readonly ReceiveEndpoint _endpoint;
readonly IReceiveEndpointObserver _observer;
public Observer(ReceiveEndpoint endpoint, IReceiveEndpointObserver observer)
{
_endpoint = endpoint;
_observer = observer;
}
public Task Ready(ReceiveTransportReady ready)
{
return _observer.Ready(new ReceiveEndpointReadyEvent(ready.InputAddress, _endpoint));
}
public Task Completed(ReceiveTransportCompleted completed)
{
return _observer.Completed(new ReceiveEndpointCompletedEvent(completed, _endpoint));
}
public Task Faulted(ReceiveTransportFaulted faulted)
{
return _observer.Faulted(new ReceiveEndpointFaultedEvent(faulted, _endpoint));
}
}
class Handle :
ReceiveEndpointHandle
{
readonly ReceiveTransportHandle _transportHandle;
public Handle(ReceiveTransportHandle transportHandle)
{
_transportHandle = transportHandle;
}
Task ReceiveEndpointHandle.Stop(CancellationToken cancellationToken)
{
return _transportHandle.Stop(cancellationToken);
}
}
}
} | 36.04321 | 125 | 0.652166 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit/Transports/ReceiveEndpoint.cs | 5,839 | C# |
/**
* ---------------------------------------------------------
*
* vkWinPlayer - минималистичный плеер для VK.COM
* @Author GROM - <botx68@gmail.com>
* @WebSite: https://retro3f.github.io/ | https://github.com/retro3f
* @About: Программа для прослушивания музыки с сайта vk.com
* @Date: 10.08.2016
* @Programming language: C#
*
*----------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Threading;
//CustomLib
using WMPLib; // WMP
using Newtonsoft.Json;// JSON
using Newtonsoft.Json.Linq; // JSON
using MetroFramework.Forms;
using MetroFramework;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace vkWinPlayer
{
public partial class Form1 : MetroForm
{
IniLib ini = new IniLib(Application.StartupPath + "\\vkWinPlayerSettings.ini");
public Form1()
{
InitializeComponent();
this.MouseWheel += new MouseEventHandler(changeInVolume_MouseWheel);
}
string apiServerVK = "https://api.vk.com/method/";
string apiVersion = "5.56";
public string accessToken;
public string userUid;
public string lastFmAccessToken;
// Глобальные переменные функции - (getUserInfo)
string getUserUid;
string getFirstName;
string getLastName;
string getPhotoProfile;
// Старт плеера.
WindowsMediaPlayer WMPs = new WMPLib.WindowsMediaPlayer(); //создаётся плеер
private void Form1_Load(object sender, EventArgs e)
{
getIniAccessTokenAndUid();
if (accessToken == "")
{
MetroMessageBox.Show(this, "Ключ доступа(access_token) не найден!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
else if (userUid == "")
{
MetroMessageBox.Show(this, "Идентификатор(UID) пользователя не найден!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
else
{
if (lastFmAccessToken == "")
{
MetroMessageBox.Show(this, "Ключ доступа LAST.FM(access_token) не найден!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
string allAudioFiles = Convert.ToString(getAudioCount(userUid));
audioGet(userUid, allAudioFiles);
getUserInfo(userUid, "photo_50");
textCountAudio.Text = String.Format("У вас {0} аудиозаписей", allAudioFiles);
textProfileName.Text = String.Format("Вы вошли как: {0} {1}", getFirstName, getLastName);
imgProfile.ImageLocation = getPhotoProfile; // подгружаем аватарку профиля.
pictureGetArtist.ImageLocation = getArtistPicture("");
try
{
// Задаем стандартную громкость(10%)
string getIniVolume = ini.IniRead("PlayerSettings", "Volume");
Regex Regular = new Regex(@"^[0-9 ]+$");
if (Regular.IsMatch(getIniVolume))
{
if (getIniVolume == "")
{
WMPs.settings.volume = changeInVolume.Value; // если не получили сохранненую громкость, то задаем дефолтную.
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value);
}
else
{
WMPs.settings.volume = changeInVolume.Value = Convert.ToInt32(getIniVolume); // если получили ранее сохраненную громкость, то ставим ее.
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = Convert.ToInt32(getIniVolume));
}
}
else
{
WMPs.settings.volume = changeInVolume.Value; // если не получили сохранненую громкость или что то пошло не так, то задаем дефолтную.
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value);
}
}
catch (System.OverflowException)
{
WMPs.settings.volume = changeInVolume.Value; // если не получили сохранненую громкость или что то пошло не так, то задаем дефолтную.
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value);
}
//чекбокс автовоспроизведения
string getIniAutoPlayStatus = ini.IniRead("PlayerSettings", "AutoPlayStatus");
if (getIniAutoPlayStatus == "True")
{
autoPlayMusic.Checked = true;
}
else
{
autoPlayMusic.Checked = false;
}
string getIniCheckMutes = ini.IniRead("PlayerSettings", "MuteStatus");
if (getIniCheckMutes == "True")
{
checkMute.Checked = true;
}
else
{
checkMute.Checked = false;
}
string getIniAudioRepeat = ini.IniRead("PlayerSettings", "AudioRepeat");
if (getIniAudioRepeat == "True")
{
audioRepeat.Checked = true;
}
else
{
audioRepeat.Checked = false;
}
}
}
public void getIniAccessTokenAndUid()
{
accessToken = ini.IniRead("UserInfo", "access_token");
userUid = ini.IniRead("UserInfo", "uid");
lastFmAccessToken = ini.IniRead("UserInfo", "lastfm_access_token");
}
// Функция получает более детальные данные о пользователе
public void getUserInfo(string uid, string fields)
{
string inq = apiServerVK + "users.get?user_ids=" + uid + "&access_token=" + accessToken + "&fields=" + fields + "&v=" + apiVersion;
string inetGetCall = inetGet(inq);
var json = JObject.Parse(inetGetCall);
var reg_response = json["response"] as JContainer;
var valid_json = reg_response[0] as JObject;
dynamic GetUserInfo = JsonConvert.DeserializeObject<dynamic>(valid_json.ToString());
getUserUid = GetUserInfo.id; // UID
getFirstName = GetUserInfo.first_name; // first_name
getLastName = GetUserInfo.last_name; // last_name
getPhotoProfile = GetUserInfo.photo_50; // photo_50
}
// Функция для получения картинки артиста с Last.Fm
public string getArtistPicture(string nameArtist)
{
string lastFmAccessToken = ini.IniRead("UserInfo", "lastfm_access_token");
string error_img_link_no_album = "https://pp.vk.me/c630827/v630827017/43eff/Af5KwCw1bP4.jpg";
if (lastFmAccessToken == "")
{
return error_img_link_no_album;
}
else
{
try
{
string lastFmGetLink = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + nameArtist + "&api_key=" + lastFmAccessToken + "&format=json";
string lastFmResp = inetGet(lastFmGetLink);
if (lastFmResp == "")
{
return error_img_link_no_album;
}
else
{
var json = JObject.Parse(lastFmResp);
var reg_response = json["artist"]["image"] as JContainer;
var valid_json = reg_response[1] as JObject;
string reg_response2 = valid_json["#text"].ToString();
if (reg_response2 == "")
{
return error_img_link_no_album;
}
else
{
return reg_response2;
}
}
}
catch (System.NullReferenceException)
{
return error_img_link_no_album;
}
}
}
// Функция получает количество аудизаписей у данного пользователя.
public int getAudioCount(string uid)
{
try
{
if (uid == "")
{
return 0; // если не был передан uid.
}
else
{
string getAudioCounts = apiServerVK + "audio.getCount?owner_id=" + uid + "&access_token=" + accessToken + "&v=" + apiVersion;
string audioCountJson = inetGet(getAudioCounts);
dynamic ac = JsonConvert.DeserializeObject<dynamic>(audioCountJson);
return ac.response; // результат.
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
return 0;
}
}
public List<Audio> audioList = null;
public class Audio
{
public int id { get; set; }
public int owner_id { get; set; }
public string artist { get; set; }
public string title { get; set; }
public int duration { get; set; }
public string url { get; set; }
public string lyrics_id { get; set; }
public int genre_id { get; set; }
}
public void audioGet(string owner_id, string count)
{
try
{
string q = apiServerVK + "audio.get?owner_id=" + owner_id + "&count=" + count + "&access_token=" + accessToken + "&v=" + apiVersion;
string res = inetGet(q);
if (res == "")
{
MetroMessageBox.Show(this, "Неудалось синхронизироватся с API.VK.COM", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
else
{
JToken token = JToken.Parse(res);
audioList = Enumerable.Skip(token["response"]["items"].Children(), 1).Select(c => c.ToObject<Audio>()).ToList();
//string[] arr1 = new string[] { };
this.Invoke((MethodInvoker)delegate
{
for (int i = 0; i < audioList.Count(); i++)
{
listBox1.Items.Add(audioList[i].artist + " - " + audioList[i].title);
}
});
}
}
catch (System.NullReferenceException)
{
MetroMessageBox.Show(this, "Исключение: System.NullReferenceException| Функции(audioGet) не удалось получить список аудифайлов с сервера. ", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
}
public string inetGet(string str)
{
try
{
var webRequest = WebRequest.Create(str);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
return reader.ReadToEnd();
}
}
catch (System.Net.WebException)
{
return "";
}
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
WMPs.URL = audioList[listBox1.SelectedIndex].url;
if (audioList[listBox1.SelectedIndex].url == "")
{
timerOneUpdateTrackBarAndPosition.Enabled = false;
}
else
{
WMPs.controls.play();
ini.IniWrite("PlayerSettings", "AudioRepeatPos", Convert.ToString(listBox1.SelectedIndex));
string sListBox = listBox1.SelectedItem.ToString();
string[] splitslistBox = sListBox.Split('-');
splitslistBox[0] = splitslistBox[0].Replace(@" ", @"");
pictureGetArtist.ImageLocation = getArtistPicture(splitslistBox[0]);
Thread.Sleep(1000);
timerOneUpdateTrackBarAndPosition.Enabled = true;
//timerTwoMusicSwitch.Enabled = true;
}
}
public void timerOneUpdateTrackBarAndPosition_Tick(object sender, EventArgs e)
{
try
{
audioTrackBar.Maximum = Convert.ToInt32(WMPs.currentMedia.duration);
audioTrackBar.Value = Convert.ToInt32(WMPs.controls.currentPosition);
currentPositionAudio.Text = WMPs.controls.currentPositionString; // начало трека
durationAudio.Text = WMPs.currentMedia.durationString; // Конец трека
audioNameRealTimes.Text = WMPs.status.ToString();
}
catch (System.ArgumentOutOfRangeException)
{
}
}
private void audioTrackBar_Scroll(object sender, ScrollEventArgs e)
{
double time = WMPs.controls.currentPosition = audioTrackBar.Value;
}
public void changeInVolume_Scroll(object sender, ScrollEventArgs e)
{
ini.IniWrite("PlayerSettings", "Volume", Convert.ToString(changeInVolume.Value));
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value);
WMPs.settings.volume = changeInVolume.Value;
}
private void ButtonPlayAudio_Click(object sender, EventArgs e)
{
WMPs.controls.play();
//timerTwoMusicSwitch.Enabled = true;
}
private void ButtonPauseAudio_Click(object sender, EventArgs e)
{
WMPs.controls.pause();
}
private void ButtonStopAudio_Click(object sender, EventArgs e)
{
WMPs.controls.stop();
timerTwoMusicSwitch.Enabled = false;
}
public void timerTwoMusicSwitch_Tick(object sender, EventArgs e)
{
if (currentPositionAudio.Text == "00:00" && durationAudio.Text == "00:00")
{
}
else
{
if (autoPlayMusic.Checked == true) // Если чекбокс активный, то делаем автовоспроизведение.
{
if (audioNameRealTimes.Text == "Остановлено") // дикий костыль, а по другому я хз:)
{
try
{
listBox1.SelectedIndex += 1; // Если предыдущий трек завершился мы воспролизводим новый.
}
catch
{
listBox1.SelectedIndex = 0; // если плейлист закончился, то начинаем с нуля.
}
}
}
}
}
// тут и так все понятно.
private void textProfileName_Click(object sender, EventArgs e)
{
string profileLinks = "https://vk.com/id" + getUserUid;
Process.Start(profileLinks);
}
private void autoPlayMusic_CheckedChanged(object sender, EventArgs e)
{
string checkAutoPlayStatus = ini.IniRead("PlayerSettings", "AutoPlayStatus");
if (autoPlayMusic.Checked == true)
{
if (autoPlayMusic.Checked) audioRepeat.Checked = false;
if (checkAutoPlayStatus == "True")
{
timerTwoMusicSwitch.Enabled = true;
}
else
{
ini.IniWrite("PlayerSettings", "AutoPlayStatus", Convert.ToString(timerTwoMusicSwitch.Enabled = true));
}
}
else
{
timerTwoMusicSwitch.Enabled = false;
ini.IniWrite("PlayerSettings", "AutoPlayStatus", Convert.ToString(timerTwoMusicSwitch.Enabled = false));
}
}
private void checkMute_CheckedChanged(object sender, EventArgs e)
{
string getIniVolumes = ini.IniRead("PlayerSettings", "Volume");
string checkMuteStatus = ini.IniRead("PlayerSettings", "MuteStatus");
if (checkMute.Checked == true)
{
if (checkMuteStatus == "True")
{
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = 0);
WMPs.settings.volume = changeInVolume.Value = 0;
}
else
{
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = 0);
WMPs.settings.volume = changeInVolume.Value = 0;
ini.IniWrite("PlayerSettings", "MuteStatus", Convert.ToString(checkMute.Checked));
}
}
else
{
ini.IniWrite("PlayerSettings", "MuteStatus", Convert.ToString(checkMute.Checked));
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = Convert.ToInt32(getIniVolumes));
WMPs.settings.volume = changeInVolume.Value = Convert.ToInt32(getIniVolumes);
}
}
public void changeInVolume_MouseWheel(object sender, MouseEventArgs e)
{
((HandledMouseEventArgs)e).Handled = true;//disable default mouse wheel
if (e.Delta > 0)
{
if (changeInVolume.Value < changeInVolume.Maximum)
{
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = changeInVolume.Value++);
WMPs.settings.volume = changeInVolume.Value = changeInVolume.Value++;
}
}
else
{
if (changeInVolume.Value > changeInVolume.Minimum)
{
VolumeText.Text = string.Format("Громкость: {0}", changeInVolume.Value = changeInVolume.Value--);
WMPs.settings.volume = changeInVolume.Value = changeInVolume.Value--;
}
}
}
// очередной костыль :)
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
private void audioRepeat_CheckedChanged(object sender, EventArgs e)
{
string checkAudioRepeatStatus = ini.IniRead("PlayerSettings", "AudioRepeat");
if (audioRepeat.Checked == true)
{
if (audioRepeat.Checked) autoPlayMusic.Checked = false;
if (checkAudioRepeatStatus == "True")
{
timerAudioRepeat.Enabled = true;
}
else
{
ini.IniWrite("PlayerSettings", "AudioRepeat", Convert.ToString(timerAudioRepeat.Enabled = true));
}
}
else
{
timerAudioRepeat.Enabled = false;
ini.IniWrite("PlayerSettings", "AudioRepeat", Convert.ToString(timerAudioRepeat.Enabled = false));
}
}
public void BtnDownloadAudioFile_Click(object sender, EventArgs e)
{
try
{
string getPathAudioFile = ini.IniRead("PlayerSettings", "AudioDownloadPath");
if (getPathAudioFile == "")
{
MetroMessageBox.Show(this, "В открывшемся окне выберите папку куда сохранить ваши аудиофайлы и нажмите кнопку: 'ок'.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
FolderBrowserDialog fbdPath = new FolderBrowserDialog();
if (fbdPath.ShowDialog() == DialogResult.OK)
{
ini.IniWrite("PlayerSettings", "AudioDownloadPath", fbdPath.SelectedPath);
}
}
else
{
WebClient webClient = new WebClient();
string LinkAudioFile = audioList[listBox1.SelectedIndex].url;
string nameArtistOrTitle = audioList[listBox1.SelectedIndex].artist + " - " + audioList[listBox1.SelectedIndex].title;
LinkAudioFile = LinkAudioFile.Substring(0, LinkAudioFile.LastIndexOf('?'));
if (LinkAudioFile == "" && nameArtistOrTitle == "")
{
MetroMessageBox.Show(this, "Неудалось получить имя аудиофайла или ссылку с сервера...", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
webClient.DownloadFileAsync(new Uri(LinkAudioFile), getPathAudioFile + "/" + nameArtistOrTitle + ".mp3");
MetroMessageBox.Show(this, "Вы успешно скачали: " + nameArtistOrTitle, "", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
}
catch (System.ArgumentOutOfRangeException)
{
// если item не выбран, а кнопка скачать была нажата.
MetroMessageBox.Show(this, "Пожалуйста выберите аудиофайл для скачивания.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timerAudioRepeat_Tick(object sender, EventArgs e)
{
//MessageBox.Show();
if (currentPositionAudio.Text == "00:00" && durationAudio.Text == "00:00")
{
}
else
{
if (audioRepeat.Checked == true) // Если чекбокс активный, то делаем автовоспроизведение.
{
if (audioNameRealTimes.Text == "Остановлено")
{
try
{
string getIniPosAudioRepeat = ini.IniRead("PlayerSettings", "AudioRepeatPos");
listBox1.SelectedIndex = Convert.ToInt32(getIniPosAudioRepeat); // Если трек завершился мы воспроизводим его заново.
WMPs.controls.play();
}
catch
{
//!
}
}
}
}
}
}
} | 38.283113 | 205 | 0.512304 | [
"MIT"
] | retro3f/vkWinPlayer | vkWinPlayer/Form1.cs | 24,518 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v5/enums/conversion_action_category.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V5.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v5/enums/conversion_action_category.proto</summary>
public static partial class ConversionActionCategoryReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v5/enums/conversion_action_category.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConversionActionCategoryReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj5nb29nbGUvYWRzL2dvb2dsZWFkcy92NS9lbnVtcy9jb252ZXJzaW9uX2Fj",
"dGlvbl9jYXRlZ29yeS5wcm90bxIdZ29vZ2xlLmFkcy5nb29nbGVhZHMudjUu",
"ZW51bXMaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8irQMKHENvbnZl",
"cnNpb25BY3Rpb25DYXRlZ29yeUVudW0ijAMKGENvbnZlcnNpb25BY3Rpb25D",
"YXRlZ29yeRIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05PV04QARILCgdERUZB",
"VUxUEAISDQoJUEFHRV9WSUVXEAMSDAoIUFVSQ0hBU0UQBBIKCgZTSUdOVVAQ",
"BRIICgRMRUFEEAYSDAoIRE9XTkxPQUQQBxIPCgtBRERfVE9fQ0FSVBAIEhIK",
"DkJFR0lOX0NIRUNLT1VUEAkSEgoOU1VCU0NSSUJFX1BBSUQQChITCg9QSE9O",
"RV9DQUxMX0xFQUQQCxIRCg1JTVBPUlRFRF9MRUFEEAwSFAoQU1VCTUlUX0xF",
"QURfRk9STRANEhQKEEJPT0tfQVBQT0lOVE1FTlQQDhIRCg1SRVFVRVNUX1FV",
"T1RFEA8SEgoOR0VUX0RJUkVDVElPTlMQEBISCg5PVVRCT1VORF9DTElDSxAR",
"EgsKB0NPTlRBQ1QQEhIOCgpFTkdBR0VNRU5UEBMSDwoLU1RPUkVfVklTSVQQ",
"FBIOCgpTVE9SRV9TQUxFEBVC8gEKIWNvbS5nb29nbGUuYWRzLmdvb2dsZWFk",
"cy52NS5lbnVtc0IdQ29udmVyc2lvbkFjdGlvbkNhdGVnb3J5UHJvdG9QAVpC",
"Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29v",
"Z2xlYWRzL3Y1L2VudW1zO2VudW1zogIDR0FBqgIdR29vZ2xlLkFkcy5Hb29n",
"bGVBZHMuVjUuRW51bXPKAh1Hb29nbGVcQWRzXEdvb2dsZUFkc1xWNVxFbnVt",
"c+oCIUdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlY1OjpFbnVtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Enums.ConversionActionCategoryEnum), global::Google.Ads.GoogleAds.V5.Enums.ConversionActionCategoryEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V5.Enums.ConversionActionCategoryEnum.Types.ConversionActionCategory) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing the category of conversions that are associated
/// with a ConversionAction.
/// </summary>
public sealed partial class ConversionActionCategoryEnum : pb::IMessage<ConversionActionCategoryEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ConversionActionCategoryEnum> _parser = new pb::MessageParser<ConversionActionCategoryEnum>(() => new ConversionActionCategoryEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ConversionActionCategoryEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V5.Enums.ConversionActionCategoryReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCategoryEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCategoryEnum(ConversionActionCategoryEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ConversionActionCategoryEnum Clone() {
return new ConversionActionCategoryEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ConversionActionCategoryEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ConversionActionCategoryEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ConversionActionCategoryEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the ConversionActionCategoryEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The category of conversions that are associated with a ConversionAction.
/// </summary>
public enum ConversionActionCategory {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Default category.
/// </summary>
[pbr::OriginalName("DEFAULT")] Default = 2,
/// <summary>
/// User visiting a page.
/// </summary>
[pbr::OriginalName("PAGE_VIEW")] PageView = 3,
/// <summary>
/// Purchase, sales, or "order placed" event.
/// </summary>
[pbr::OriginalName("PURCHASE")] Purchase = 4,
/// <summary>
/// Signup user action.
/// </summary>
[pbr::OriginalName("SIGNUP")] Signup = 5,
/// <summary>
/// Lead-generating action.
/// </summary>
[pbr::OriginalName("LEAD")] Lead = 6,
/// <summary>
/// Software download action (as for an app).
/// </summary>
[pbr::OriginalName("DOWNLOAD")] Download = 7,
/// <summary>
/// The addition of items to a shopping cart or bag on an advertiser site.
/// </summary>
[pbr::OriginalName("ADD_TO_CART")] AddToCart = 8,
/// <summary>
/// When someone enters the checkout flow on an advertiser site.
/// </summary>
[pbr::OriginalName("BEGIN_CHECKOUT")] BeginCheckout = 9,
/// <summary>
/// The start of a paid subscription for a product or service.
/// </summary>
[pbr::OriginalName("SUBSCRIBE_PAID")] SubscribePaid = 10,
/// <summary>
/// A call to indicate interest in an advertiser's offering.
/// </summary>
[pbr::OriginalName("PHONE_CALL_LEAD")] PhoneCallLead = 11,
/// <summary>
/// A lead conversion imported from an external source into Google Ads.
/// </summary>
[pbr::OriginalName("IMPORTED_LEAD")] ImportedLead = 12,
/// <summary>
/// A submission of a form on an advertiser site indicating business
/// interest.
/// </summary>
[pbr::OriginalName("SUBMIT_LEAD_FORM")] SubmitLeadForm = 13,
/// <summary>
/// A booking of an appointment with an advertiser's business.
/// </summary>
[pbr::OriginalName("BOOK_APPOINTMENT")] BookAppointment = 14,
/// <summary>
/// A quote or price estimate request.
/// </summary>
[pbr::OriginalName("REQUEST_QUOTE")] RequestQuote = 15,
/// <summary>
/// A search for an advertiser's business location with intention to visit.
/// </summary>
[pbr::OriginalName("GET_DIRECTIONS")] GetDirections = 16,
/// <summary>
/// A click to an advertiser's partner's site.
/// </summary>
[pbr::OriginalName("OUTBOUND_CLICK")] OutboundClick = 17,
/// <summary>
/// A call, SMS, email, chat or other type of contact to an advertiser.
/// </summary>
[pbr::OriginalName("CONTACT")] Contact = 18,
/// <summary>
/// A website engagement event such as long site time or a Google Analytics
/// (GA) Smart Goal. Intended to be used for GA, Firebase, GA Gold goal
/// imports.
/// </summary>
[pbr::OriginalName("ENGAGEMENT")] Engagement = 19,
/// <summary>
/// A visit to a physical store location.
/// </summary>
[pbr::OriginalName("STORE_VISIT")] StoreVisit = 20,
/// <summary>
/// A sale occurring in a physical store.
/// </summary>
[pbr::OriginalName("STORE_SALE")] StoreSale = 21,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 39.523026 | 332 | 0.668997 | [
"Apache-2.0"
] | GraphikaPS/google-ads-dotnet | src/V5/Types/ConversionActionCategory.cs | 12,015 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallController : MonoBehaviour {
private Vector3 startPos;
private Quaternion startRot;
private Rigidbody rb;
private Color defultColor;
public bool isLegal = false;
public List<GameObject> starsList;
public LevelConfig levelConfig;
public Color illegalColor = Color.red;
public bool isGrabbing = false;
public bool isInPlatform = false;
public void ResetGame()
{
transform.position = startPos;
transform.rotation = startRot;
rb.velocity = new Vector3(0,0,0);
isGrabbing = false;
ResetStars();
levelConfig.ResetScore();
}
void ResetStars()
{
foreach (GameObject star in starsList)
{
StarController starController = star.GetComponent<StarController>();
starController.Reset();
}
}
void Awake()
{
startPos = transform.position;
startRot = transform.rotation;
rb = GetComponent<Rigidbody>();
defultColor = GetComponent<Renderer>().material.GetColor("_Color");
}
// Use this for initialization
void Start () {
}
void OnCollisionEnter(Collision other)
{
// reset ball and stars
if (other.gameObject.CompareTag("Ground"))
{
ResetGame();
}
}
public void SetLegal()
{
isLegal = true;
GetComponent<Renderer>().material.SetColor("_Color", defultColor);
//Debug.Log("set ball to legal");
//Debug.Log("Ball Color: " + GetComponent<Renderer>().material.GetColor("_Color").ToString());
}
public void SetIllegal()
{
isLegal = false;
GetComponent<Renderer>().material.SetColor("_Color", illegalColor);
//Debug.Log("set ball to illegal");
//Debug.Log("Ball Color: " + GetComponent<Renderer>().material.GetColor("_Color").ToString());
}
// Update is called once per frame
void Update () {
}
}
| 21.595238 | 96 | 0.695149 | [
"MIT"
] | molock/RubeGoldbergGame | Assets/Scripts/BallController.cs | 1,816 | C# |
using System;
using UnityEngine;
namespace multiVar{
public class Gradiente : _MetodoMultVar
{
protected override double[] Algoritmo()
{
double[] res = new double[varNum];
return res;
}
}
} | 17.928571 | 47 | 0.569721 | [
"Apache-2.0"
] | Avatark0/PO2-2021 | PO2 - Projeto 2/Assets/_Scripts/Metodos_Multi/Metodos/Gradiente.cs | 251 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using PhraseQuery = Lucene.Net.Search.PhraseQuery;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestAddIndexesNoOptimize:LuceneTestCase
{
[Test]
public virtual void TestSimpleCase()
{
// main directory
Directory dir = new RAMDirectory();
// two auxiliary directories
Directory aux = new RAMDirectory();
Directory aux2 = new RAMDirectory();
IndexWriter writer = null;
writer = NewWriter(dir, true);
// add 100 documents
AddDocs(writer, 100);
Assert.AreEqual(100, writer.MaxDoc());
writer.Close();
writer = NewWriter(aux, true);
writer.UseCompoundFile = false; // use one without a compound file
// add 40 documents in separate files
AddDocs(writer, 40);
Assert.AreEqual(40, writer.MaxDoc());
writer.Close();
writer = NewWriter(aux2, true);
// add 40 documents in compound files
AddDocs2(writer, 50);
Assert.AreEqual(50, writer.MaxDoc());
writer.Close();
// test doc count before segments are merged
writer = NewWriter(dir, false);
Assert.AreEqual(100, writer.MaxDoc());
writer.AddIndexesNoOptimize(new Directory[]{aux, aux2});
Assert.AreEqual(190, writer.MaxDoc());
writer.Close();
// make sure the old index is correct
VerifyNumDocs(aux, 40);
// make sure the new index is correct
VerifyNumDocs(dir, 190);
// now add another set in.
Directory aux3 = new RAMDirectory();
writer = NewWriter(aux3, true);
// add 40 documents
AddDocs(writer, 40);
Assert.AreEqual(40, writer.MaxDoc());
writer.Close();
// test doc count before segments are merged/index is optimized
writer = NewWriter(dir, false);
Assert.AreEqual(190, writer.MaxDoc());
writer.AddIndexesNoOptimize(new Directory[]{aux3});
Assert.AreEqual(230, writer.MaxDoc());
writer.Close();
// make sure the new index is correct
VerifyNumDocs(dir, 230);
VerifyTermDocs(dir, new Term("content", "aaa"), 180);
VerifyTermDocs(dir, new Term("content", "bbb"), 50);
// now optimize it.
writer = NewWriter(dir, false);
writer.Optimize();
writer.Close();
// make sure the new index is correct
VerifyNumDocs(dir, 230);
VerifyTermDocs(dir, new Term("content", "aaa"), 180);
VerifyTermDocs(dir, new Term("content", "bbb"), 50);
// now add a single document
Directory aux4 = new RAMDirectory();
writer = NewWriter(aux4, true);
AddDocs2(writer, 1);
writer.Close();
writer = NewWriter(dir, false);
Assert.AreEqual(230, writer.MaxDoc());
writer.AddIndexesNoOptimize(new Directory[]{aux4});
Assert.AreEqual(231, writer.MaxDoc());
writer.Close();
VerifyNumDocs(dir, 231);
VerifyTermDocs(dir, new Term("content", "bbb"), 51);
}
[Test]
public virtual void TestWithPendingDeletes()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
writer.AddIndexesNoOptimize(new Directory[]{aux});
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++)
{
Document doc = new Document();
doc.Add(new Field("id", "" + (i % 10), Field.Store.NO, Field.Index.NOT_ANALYZED));
doc.Add(new Field("content", "bbb " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.UpdateDocument(new Term("id", "" + (i % 10)), doc);
}
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.Add(new Term("content", "bbb"));
q.Add(new Term("content", "14"));
writer.DeleteDocuments(q);
writer.Optimize();
writer.Commit();
VerifyNumDocs(dir, 1039);
VerifyTermDocs(dir, new Term("content", "aaa"), 1030);
VerifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.Close();
dir.Close();
aux.Close();
}
[Test]
public virtual void TestWithPendingDeletes2()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++)
{
Document doc = new Document();
doc.Add(new Field("id", "" + (i % 10), Field.Store.NO, Field.Index.NOT_ANALYZED));
doc.Add(new Field("content", "bbb " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.UpdateDocument(new Term("id", "" + (i % 10)), doc);
}
writer.AddIndexesNoOptimize(new Directory[]{aux});
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.Add(new Term("content", "bbb"));
q.Add(new Term("content", "14"));
writer.DeleteDocuments(q);
writer.Optimize();
writer.Commit();
VerifyNumDocs(dir, 1039);
VerifyTermDocs(dir, new Term("content", "aaa"), 1030);
VerifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.Close();
dir.Close();
aux.Close();
}
[Test]
public virtual void TestWithPendingDeletes3()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++)
{
Document doc = new Document();
doc.Add(new Field("id", "" + (i % 10), Field.Store.NO, Field.Index.NOT_ANALYZED));
doc.Add(new Field("content", "bbb " + i, Field.Store.NO, Field.Index.ANALYZED));
writer.UpdateDocument(new Term("id", "" + (i % 10)), doc);
}
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.Add(new Term("content", "bbb"));
q.Add(new Term("content", "14"));
writer.DeleteDocuments(q);
writer.AddIndexesNoOptimize(new Directory[]{aux});
writer.Optimize();
writer.Commit();
VerifyNumDocs(dir, 1039);
VerifyTermDocs(dir, new Term("content", "aaa"), 1030);
VerifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.Close();
dir.Close();
aux.Close();
}
// case 0: add self or exceed maxMergeDocs, expect exception
[Test]
public virtual void TestAddSelf()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
IndexWriter writer = null;
writer = NewWriter(dir, true);
// add 100 documents
AddDocs(writer, 100);
Assert.AreEqual(100, writer.MaxDoc());
writer.Close();
writer = NewWriter(aux, true);
writer.UseCompoundFile = false; // use one without a compound file
writer.SetMaxBufferedDocs(1000);
// add 140 documents in separate files
AddDocs(writer, 40);
writer.Close();
writer = NewWriter(aux, true);
writer.UseCompoundFile = false; // use one without a compound file
writer.SetMaxBufferedDocs(1000);
AddDocs(writer, 100);
writer.Close();
writer = NewWriter(dir, false);
try
{
// cannot add self
writer.AddIndexesNoOptimize(new Directory[]{aux, dir});
Assert.IsTrue(false);
}
catch (System.ArgumentException)
{
Assert.AreEqual(100, writer.MaxDoc());
}
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 100);
}
// in all the remaining tests, make the doc count of the oldest segment
// in dir large so that it is never merged in addIndexesNoOptimize()
// case 1: no tail segments
[Test]
public virtual void TestNoTailSegments()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
writer.SetMaxBufferedDocs(10);
writer.MergeFactor = 4;
AddDocs(writer, 10);
writer.AddIndexesNoOptimize(new Directory[]{aux});
Assert.AreEqual(1040, writer.MaxDoc());
Assert.AreEqual(2, writer.GetSegmentCount());
Assert.AreEqual(1000, writer.GetDocCount(0));
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 1040);
}
// case 2: tail segments, invariants hold, no copy
[Test]
public virtual void TestNoCopySegments()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
writer.SetMaxBufferedDocs(9);
writer.MergeFactor = 4;
AddDocs(writer, 2);
writer.AddIndexesNoOptimize(new Directory[]{aux});
Assert.AreEqual(1032, writer.MaxDoc());
Assert.AreEqual(2, writer.GetSegmentCount());
Assert.AreEqual(1000, writer.GetDocCount(0));
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 1032);
}
// case 3: tail segments, invariants hold, copy, invariants hold
[Test]
public virtual void TestNoMergeAfterCopy()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(dir, false);
writer.SetMaxBufferedDocs(10);
writer.MergeFactor = 4;
writer.AddIndexesNoOptimize(new Directory[]{aux, new RAMDirectory(aux)});
Assert.AreEqual(1060, writer.MaxDoc());
Assert.AreEqual(1000, writer.GetDocCount(0));
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 1060);
}
// case 4: tail segments, invariants hold, copy, invariants not hold
[Test]
public virtual void TestMergeAfterCopy()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
SetUpDirs(dir, aux);
IndexReader reader = IndexReader.Open(aux, false);
for (int i = 0; i < 20; i++)
{
reader.DeleteDocument(i);
}
Assert.AreEqual(10, reader.NumDocs());
reader.Close();
IndexWriter writer = NewWriter(dir, false);
writer.SetMaxBufferedDocs(4);
writer.MergeFactor = 4;
writer.AddIndexesNoOptimize(new Directory[]{aux, new RAMDirectory(aux)});
Assert.AreEqual(1020, writer.MaxDoc());
Assert.AreEqual(1000, writer.GetDocCount(0));
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 1020);
}
// case 5: tail segments, invariants not hold
[Test]
public virtual void TestMoreMerges()
{
// main directory
Directory dir = new RAMDirectory();
// auxiliary directory
Directory aux = new RAMDirectory();
Directory aux2 = new RAMDirectory();
SetUpDirs(dir, aux);
IndexWriter writer = NewWriter(aux2, true);
writer.SetMaxBufferedDocs(100);
writer.MergeFactor = 10;
writer.AddIndexesNoOptimize(new Directory[]{aux});
Assert.AreEqual(30, writer.MaxDoc());
Assert.AreEqual(3, writer.GetSegmentCount());
writer.Close();
IndexReader reader = IndexReader.Open(aux, false);
for (int i = 0; i < 27; i++)
{
reader.DeleteDocument(i);
}
Assert.AreEqual(3, reader.NumDocs());
reader.Close();
reader = IndexReader.Open(aux2, false);
for (int i = 0; i < 8; i++)
{
reader.DeleteDocument(i);
}
Assert.AreEqual(22, reader.NumDocs());
reader.Close();
writer = NewWriter(dir, false);
writer.SetMaxBufferedDocs(6);
writer.MergeFactor = 4;
writer.AddIndexesNoOptimize(new Directory[]{aux, aux2});
Assert.AreEqual(1025, writer.MaxDoc());
Assert.AreEqual(1000, writer.GetDocCount(0));
writer.Close();
// make sure the index is correct
VerifyNumDocs(dir, 1025);
}
private IndexWriter NewWriter(Directory dir, bool create)
{
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), create, IndexWriter.MaxFieldLength.UNLIMITED);
writer.SetMergePolicy(new LogDocMergePolicy(writer));
return writer;
}
private void AddDocs(IndexWriter writer, int numDocs)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(new Field("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
writer.AddDocument(doc);
}
}
private void AddDocs2(IndexWriter writer, int numDocs)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(new Field("content", "bbb", Field.Store.NO, Field.Index.ANALYZED));
writer.AddDocument(doc);
}
}
private void VerifyNumDocs(Directory dir, int numDocs)
{
IndexReader reader = IndexReader.Open(dir, true);
Assert.AreEqual(numDocs, reader.MaxDoc);
Assert.AreEqual(numDocs, reader.NumDocs());
reader.Close();
}
private void VerifyTermDocs(Directory dir, Term term, int numDocs)
{
IndexReader reader = IndexReader.Open(dir, true);
TermDocs termDocs = reader.TermDocs(term);
int count = 0;
while (termDocs.Next())
count++;
Assert.AreEqual(numDocs, count);
reader.Close();
}
private void SetUpDirs(Directory dir, Directory aux)
{
IndexWriter writer = null;
writer = NewWriter(dir, true);
writer.SetMaxBufferedDocs(1000);
// add 1000 documents in 1 segment
AddDocs(writer, 1000);
Assert.AreEqual(1000, writer.MaxDoc());
Assert.AreEqual(1, writer.GetSegmentCount());
writer.Close();
writer = NewWriter(aux, true);
writer.UseCompoundFile = false; // use one without a compound file
writer.SetMaxBufferedDocs(100);
writer.MergeFactor = 10;
// add 30 documents in 3 segments
for (int i = 0; i < 3; i++)
{
AddDocs(writer, 10);
writer.Close();
writer = NewWriter(aux, false);
writer.UseCompoundFile = false; // use one without a compound file
writer.SetMaxBufferedDocs(100);
writer.MergeFactor = 10;
}
Assert.AreEqual(30, writer.MaxDoc());
Assert.AreEqual(3, writer.GetSegmentCount());
writer.Close();
}
// LUCENE-1270
[Test]
public virtual void TestHangOnClose()
{
Directory dir = new MockRAMDirectory();
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetMergePolicy(new LogByteSizeMergePolicy(writer));
writer.SetMaxBufferedDocs(5);
writer.UseCompoundFile = false;
writer.MergeFactor = 100;
Document doc = new Document();
doc.Add(new Field("content", "aaa bbb ccc ddd eee fff ggg hhh iii", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
for (int i = 0; i < 60; i++)
writer.AddDocument(doc);
writer.SetMaxBufferedDocs(200);
Document doc2 = new Document();
doc2.Add(new Field("content", "aaa bbb ccc ddd eee fff ggg hhh iii", Field.Store.YES, Field.Index.NO));
doc2.Add(new Field("content", "aaa bbb ccc ddd eee fff ggg hhh iii", Field.Store.YES, Field.Index.NO));
doc2.Add(new Field("content", "aaa bbb ccc ddd eee fff ggg hhh iii", Field.Store.YES, Field.Index.NO));
doc2.Add(new Field("content", "aaa bbb ccc ddd eee fff ggg hhh iii", Field.Store.YES, Field.Index.NO));
for (int i = 0; i < 10; i++)
writer.AddDocument(doc2);
writer.Close();
Directory dir2 = new MockRAMDirectory();
writer = new IndexWriter(dir2, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
LogByteSizeMergePolicy lmp = new LogByteSizeMergePolicy(writer);
lmp.MinMergeMB = 0.0001;
writer.SetMergePolicy(lmp);
writer.MergeFactor = 4;
writer.UseCompoundFile = false;
writer.SetMergeScheduler(new SerialMergeScheduler());
writer.AddIndexesNoOptimize(new Directory[]{dir});
writer.Close();
dir.Close();
dir2.Close();
}
// LUCENE-1642: make sure CFS of destination indexwriter
// is respected when copying tail segments
[Test]
public virtual void TestTargetCFS()
{
Directory dir = new RAMDirectory();
IndexWriter writer = NewWriter(dir, true);
writer.UseCompoundFile = false;
AddDocs(writer, 1);
writer.Close();
Directory other = new RAMDirectory();
writer = NewWriter(other, true);
writer.UseCompoundFile = true;
writer.AddIndexesNoOptimize(new Directory[]{dir});
Assert.IsTrue(writer.NewestSegment().GetUseCompoundFile());
writer.Close();
}
}
} | 37.726813 | 161 | 0.523735 | [
"Apache-2.0"
] | ClearCanvas/lucene.net | test/core/Index/TestAddIndexesNoOptimize.cs | 22,372 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iotanalytics-2017-11-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTAnalytics.Model
{
/// <summary>
/// The destination to which dataset contents are delivered.
/// </summary>
public partial class DatasetContentDeliveryDestination
{
private IotEventsDestinationConfiguration _iotEventsDestinationConfiguration;
private S3DestinationConfiguration _s3DestinationConfiguration;
/// <summary>
/// Gets and sets the property IotEventsDestinationConfiguration.
/// <para>
/// Configuration information for delivery of dataset contents to IoT Events.
/// </para>
/// </summary>
public IotEventsDestinationConfiguration IotEventsDestinationConfiguration
{
get { return this._iotEventsDestinationConfiguration; }
set { this._iotEventsDestinationConfiguration = value; }
}
// Check to see if IotEventsDestinationConfiguration property is set
internal bool IsSetIotEventsDestinationConfiguration()
{
return this._iotEventsDestinationConfiguration != null;
}
/// <summary>
/// Gets and sets the property S3DestinationConfiguration.
/// <para>
/// Configuration information for delivery of dataset contents to Amazon S3.
/// </para>
/// </summary>
public S3DestinationConfiguration S3DestinationConfiguration
{
get { return this._s3DestinationConfiguration; }
set { this._s3DestinationConfiguration = value; }
}
// Check to see if S3DestinationConfiguration property is set
internal bool IsSetS3DestinationConfiguration()
{
return this._s3DestinationConfiguration != null;
}
}
} | 34.605263 | 110 | 0.686312 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoTAnalytics/Generated/Model/DatasetContentDeliveryDestination.cs | 2,630 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using StarkPlatform.Compiler.CodeFixes;
using StarkPlatform.Compiler.Stark.Syntax;
using StarkPlatform.Compiler.Editing;
using StarkPlatform.Compiler.RemoveUnusedParametersAndValues;
namespace StarkPlatform.Compiler.Stark.RemoveUnusedParametersAndValues
{
[ExportCodeFixProvider(LanguageNames.Stark, Name = PredefinedCodeFixProviderNames.RemoveUnusedValues), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)]
internal class CSharpRemoveUnusedValuesCodeFixProvider :
AbstractRemoveUnusedValuesCodeFixProvider<ExpressionSyntax, StatementSyntax, BlockSyntax,
ExpressionStatementSyntax, LocalDeclarationStatementSyntax, VariableDeclarationSyntax,
ForStatementSyntax, SwitchSectionSyntax, SwitchLabelSyntax, CatchClauseSyntax, CatchClauseSyntax>
{
protected override BlockSyntax WrapWithBlockIfNecessary(IEnumerable<StatementSyntax> statements)
=> SyntaxFactory.Block(statements);
protected override SyntaxToken GetForEachStatementIdentifier(ForStatementSyntax node)
=> node.Variable.GetFirstToken();
protected override SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, SyntaxToken newName)
{
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
var identifierName = (IdentifierNameSyntax)node;
return identifierName.WithIdentifier(newName.WithTriviaFrom(identifierName.Identifier));
case SyntaxKind.VariableDeclaration:
var variableDeclarator = (VariableDeclarationSyntax)node;
return variableDeclarator.WithIdentifier(newName.WithTriviaFrom(variableDeclarator.Identifier));
case SyntaxKind.SingleVariableDesignation:
return newName.ValueText == AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName
? SyntaxFactory.DiscardDesignation().WithTriviaFrom(node)
: (SyntaxNode)SyntaxFactory.SingleVariableDesignation(newName).WithTriviaFrom(node);
case SyntaxKind.CatchDeclaration:
var catchDeclaration = (CatchDeclarationSyntax)node;
return catchDeclaration.WithIdentifier(newName.WithTriviaFrom(catchDeclaration.Identifier));
default:
Debug.Fail($"Unexpected node kind for local/parameter declaration or reference: '{node.Kind()}'");
return null;
}
}
protected override void InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(SwitchSectionSyntax switchCaseBlock, SyntaxEditor editor, LocalDeclarationStatementSyntax declarationStatement)
{
var firstStatement = switchCaseBlock.Statements.FirstOrDefault();
if (firstStatement != null)
{
editor.InsertBefore(firstStatement, declarationStatement);
}
else
{
// Switch section without any statements is an error case.
// Insert before containing switch statement.
editor.InsertBefore(switchCaseBlock.Parent, declarationStatement);
}
}
}
}
| 51.246377 | 207 | 0.704468 | [
"BSD-2-Clause",
"MIT"
] | encrypt0r/stark | src/compiler/StarkPlatform.Compiler.Stark.Features/RemoveUnusedParametersAndValues/CSharpRemoveUnusedValuesCodeFixProvider.cs | 3,538 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Runtime.InteropServices;
using System.Xml;
namespace LibPostalNet
{
public unsafe class AddressExpansionResponse : IDisposable
{
private IntPtr _Instance;
private IntPtr _InputString;
private ulong _NumExpansions;
public string[] Expansions { get; private set; }
internal AddressExpansionResponse(string input, AddressExpansionOptions options)
{
if (ReferenceEquals(options, null)) throw new NullReferenceException();
_InputString = MarshalUTF8.StringToPtr(input);
var native = LibPostal.UnsafeNativeMethods.ExpandAddress(_InputString, options._Native, ref _NumExpansions);
if (native == IntPtr.Zero || native.ToPointer() == null)
return;
_Instance = native;
Expansions = new string[_NumExpansions];
for (int x = 0; x < (int)_NumExpansions; x++)
{
int offset = x * Marshal.SizeOf(typeof(IntPtr));
Expansions[x] = MarshalUTF8.PtrToString(Marshal.ReadIntPtr(native, offset));
}
}
~AddressExpansionResponse() { Dispose(false); }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_Instance != IntPtr.Zero)
{
LibPostal.UnsafeNativeMethods.ExpansionArrayDestroy(_Instance, _NumExpansions);
_Instance = IntPtr.Zero;
}
if (_InputString != IntPtr.Zero)
{
Marshal.FreeHGlobal(_InputString);
_InputString = IntPtr.Zero;
}
}
public string ToJSON()
{
var json = new JArray();
foreach (var expansion in Expansions)
{
json.Add(new JValue(expansion));
}
return json.ToString(Newtonsoft.Json.Formatting.None);
}
public string ToXML()
{
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", string.Empty, string.Empty));
var address = doc.CreateElement("address");
foreach (var expansion in Expansions)
{
var elem = doc.CreateElement("expansion");
elem.AppendChild(doc.CreateTextNode(expansion));
address.AppendChild(elem);
}
doc.AppendChild(address);
return doc.OuterXml;
}
}
}
| 34.329114 | 121 | 0.550516 | [
"MIT"
] | AeroXuk/LibPostalNet | LibPostalNet/AddressExpansionResponse.cs | 2,714 | C# |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using OpenTK;
using osu.Framework.Graphics.Primitives;
using System.Diagnostics;
namespace osu.Framework.Graphics.Colour
{
/// <summary>
/// ColourInfo contains information about the colours of all 4 vertices of a quad.
/// These colours are always stored in linear space.
/// </summary>
public struct ColourInfo : IEquatable<ColourInfo>
{
public SRGBColour TopLeft;
public SRGBColour BottomLeft;
public SRGBColour TopRight;
public SRGBColour BottomRight;
public bool HasSingleColour;
/// <summary>
/// Creates a ColourInfo with a single linear colour assigned to all vertices.
/// </summary>
/// <param name="colour">The single linear colour to be assigned to all vertices.</param>
/// <returns>The created ColourInfo.</returns>
public static ColourInfo SingleColour(SRGBColour colour)
{
ColourInfo result = new ColourInfo();
result.TopLeft = result.BottomLeft = result.TopRight = result.BottomRight = colour;
result.HasSingleColour = true;
return result;
}
/// <summary>
/// Creates a ColourInfo with a horizontal gradient.
/// </summary>
/// <param name="c1">The left colour of the gradient.</param>
/// <param name="c2">The right colour of the gradient.</param>
/// <returns>The created ColourInfo.</returns>
public static ColourInfo GradientHorizontal(SRGBColour c1, SRGBColour c2)
{
ColourInfo result = new ColourInfo();
result.TopLeft = result.BottomLeft = c1;
result.TopRight = result.BottomRight = c2;
result.HasSingleColour = false;
return result;
}
/// <summary>
/// Creates a ColourInfo with a horizontal gradient.
/// </summary>
/// <param name="c1">The top colour of the gradient.</param>
/// <param name="c2">The bottom colour of the gradient.</param>
/// <returns>The created ColourInfo.</returns>
public static ColourInfo GradientVertical(SRGBColour c1, SRGBColour c2)
{
ColourInfo result = new ColourInfo();
result.TopLeft = result.TopRight = c1;
result.BottomLeft = result.BottomRight = c2;
result.HasSingleColour = false;
return result;
}
public SRGBColour Colour
{
get
{
Debug.Assert(HasSingleColour, "Attempted to read single colour from multi-colour ColourInfo.");
return TopLeft;
}
set
{
TopLeft = BottomLeft = TopRight = BottomRight = value;
HasSingleColour = true;
}
}
public SRGBColour Interpolate(Vector2 interp) => SRGBColour.FromVector(
(1 - interp.Y) * ((1 - interp.X) * TopLeft.ToVector() + interp.X * TopRight.ToVector()) +
interp.Y * ((1 - interp.X) * BottomLeft.ToVector() + interp.X * BottomRight.ToVector()));
public void ApplyChild(ColourInfo childColour)
{
Debug.Assert(HasSingleColour);
if (childColour.HasSingleColour)
Colour *= childColour.Colour;
else
{
HasSingleColour = false;
BottomLeft = childColour.BottomLeft * TopLeft;
TopRight = childColour.TopRight * TopLeft;
BottomRight = childColour.BottomRight * TopLeft;
// Need to assign TopLeft last to keep correctness.
TopLeft = childColour.TopLeft * TopLeft;
}
}
public void ApplyChild(ColourInfo childColour, Quad interp)
{
Debug.Assert(!HasSingleColour);
SRGBColour newTopLeft = Interpolate(interp.TopLeft) * childColour.TopLeft;
SRGBColour newTopRight = Interpolate(interp.TopRight) * childColour.TopRight;
SRGBColour newBottomLeft = Interpolate(interp.BottomLeft) * childColour.BottomLeft;
SRGBColour newBottomRight = Interpolate(interp.BottomRight) * childColour.BottomRight;
TopLeft = newTopLeft;
TopRight = newTopRight;
BottomLeft = newBottomLeft;
BottomRight = newBottomRight;
}
/// <summary>
/// Created a new ColourInfo with the alpha value of the colours of all vertices
/// multiplied by a given alpha parameter.
/// </summary>
/// <param name="alpha">The alpha parameter to multiply the alpha values of all vertices with.</param>
/// <returns>The new ColourInfo.</returns>
public ColourInfo MultiplyAlpha(float alpha)
{
if (alpha == 1.0)
return this;
ColourInfo result = this;
result.TopLeft.MultiplyAlpha(alpha);
if (HasSingleColour)
{
result.BottomLeft = result.TopRight = result.BottomRight = result.TopLeft;
}
else
{
result.BottomLeft.MultiplyAlpha(alpha);
result.TopRight.MultiplyAlpha(alpha);
result.BottomRight.MultiplyAlpha(alpha);
}
return result;
}
public bool Equals(ColourInfo other)
{
if (!HasSingleColour)
{
if (other.HasSingleColour)
return false;
return
HasSingleColour == other.HasSingleColour &&
TopLeft.Equals(other.TopLeft) &&
TopRight.Equals(other.TopRight) &&
BottomLeft.Equals(other.BottomLeft) &&
BottomRight.Equals(other.BottomRight);
}
return other.HasSingleColour && TopLeft.Equals(other.TopLeft);
}
public bool Equals(SRGBColour other)
{
return HasSingleColour && TopLeft.Equals(other);
}
/// <summary>
/// The average colour of all corners.
/// </summary>
public SRGBColour AverageColour
{
get
{
if (HasSingleColour)
return TopLeft;
return SRGBColour.FromVector(
(TopLeft.ToVector() + TopRight.ToVector() + BottomLeft.ToVector() + BottomRight.ToVector()) / 4);
}
}
/// <summary>
/// The maximum alpha value of all four corners.
/// </summary>
public float MaxAlpha
{
get
{
float max = TopLeft.Linear.A;
if (TopRight.Linear.A < max) max = TopRight.Linear.A;
if (BottomLeft.Linear.A < max) max = BottomLeft.Linear.A;
if (BottomRight.Linear.A < max) max = BottomRight.Linear.A;
return max;
}
}
}
}
| 36.74 | 118 | 0.548449 | [
"MIT"
] | jorolf/osu-framework | osu.Framework/Graphics/Colour/ColourInfo.cs | 7,350 | C# |
namespace SAModel.SAEditorCommon.DataTypes
{
public interface IScaleable
{
Vertex GetScale();
void SetScale(Vertex scale);
}
}
| 15 | 43 | 0.748148 | [
"MIT",
"BSD-3-Clause"
] | X-Hax/sa_tools | Libraries/SAEditorCommon/DataTypes/IScaleable.cs | 137 | C# |
using Microsoft.EntityFrameworkCore;
using Senai.Gufos.WebApi.Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Senai.Gufos.WebApi.Repositories
{
public class EventoRepository
{
public List<Eventos> Listar()
{
using (GufosContext ctx = new GufosContext())
{
return ctx.Eventos.Include(x => x.IdCategoriaNavigation).ToList();
}
}
public void Cadastrar(Eventos eventos)
{
using (GufosContext ctx = new GufosContext())
{
ctx.Eventos.Add(eventos);
ctx.SaveChanges();
}
}
}
}
| 24 | 82 | 0.579167 | [
"MIT"
] | jv-soncini/Exercicios-API | Gufos/Senai.Gufos.WebApi/Senai.Gufos.WebApi/Repositories/EventoRepository.cs | 722 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Html;
using System.Xml;
using System.Html.Services;
using System.Html.Media.Graphics;
namespace wwtlib
{
//[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Method)]
//public class LayerProperty : System.Attribute
//{
// public LayerProperty()
// {
// }
//}
public enum AltUnits { Meters=1, Feet=2, Inches=3, Miles=4, Kilometers=5, AstronomicalUnits=6, LightYears=7, Parsecs=8, MegaParsecs=9, Custom=10 , KiloParsecs=11};
public enum FadeType { FadeIn=1, FadeOut=2, Both=3, None=4 };
public abstract class Layer
{
public virtual LayerUI GetPrimaryUI()
{
return null;
}
public Guid ID = Guid.NewGuid();
public bool LoadedFromTour = false;
public TourDocument tourDocument = null;
public string GetFileStreamUrl(string filename)
{
if (tourDocument != null)
{
return tourDocument.GetFileStream(filename);
}
return null;
}
protected float opacity = 1.0f;
public virtual float Opacity
{
get
{
return opacity;
}
set
{
if (opacity != value)
{
version++;
opacity = value;
}
}
}
public bool opened = false;
public virtual bool Opened
{
get
{
return opened;
}
set
{
if (opened != value)
{
version++;
opened = value;
}
}
}
private Date startTime = Date.Parse("01/01/1900");
public Date StartTime
{
get { return startTime; }
set
{
if (startTime != value)
{
version++;
startTime = value;
}
}
}
private Date endTime = Date.Parse("01/01/2100");
public Date EndTime
{
get { return endTime; }
set
{
if (endTime != value)
{
version++;
endTime = value;
}
}
}
private double fadeSpan = 0;
public double FadeSpan
{
get { return fadeSpan; }
set
{
version++;
fadeSpan = value;
}
}
private FadeType fadeType = FadeType.None;
public FadeType FadeType
{
get { return fadeType; }
set {
if (fadeType != value)
{
Version++;
fadeType = value;
}
}
}
protected int version = 0;
public int Version
{
get { return version; }
set { version = value; }
}
public virtual Place FindClosest(Coordinates target, float distance, Place closestPlace, bool astronomical)
{
return closestPlace;
}
public virtual bool HoverCheckScreenSpace(Vector2d cursor)
{
return false;
}
public virtual bool ClickCheckScreenSpace(Vector2d cursor)
{
return false;
}
public virtual bool Draw(RenderContext renderContext, float opacity, bool flat)
{
return true;
}
public virtual bool PreDraw(RenderContext renderContext, float opacity)
{
return true;
}
public virtual bool UpadteData(object data, bool purgeOld, bool purgeAll, bool hasHeader)
{
return true;
}
public virtual bool CanCopyToClipboard()
{
return false;
}
public virtual void CopyToClipboard()
{
return;
}
public virtual double[] GetParams()
{
double[] paramList = new double[5];
paramList[0] = color.R / 255;
paramList[1] = color.G / 255;
paramList[2] = color.B / 255;
paramList[3] = color.A / 255;
paramList[4] = opacity;
return paramList;
}
public virtual void SetParams(double[] paramList)
{
if (paramList.Length == 5)
{
opacity = (float)paramList[4];
color = Color.FromArgb((byte)(paramList[3] * 255), (byte)(paramList[0] * 255), (byte)(paramList[1] * 255), (byte)(paramList[2] * 255));
}
}
public virtual string[] GetParamNames()
{
return new string[] { "Color.Red", "Color.Green", "Color.Blue", "Color.Alpha", "Opacity" };
}
public virtual object GetEditUI()
{
return this as IUiController;
}
public virtual void CleanUp()
{
}
private string name;
public virtual string Name
{
get { return name; }
set
{
if (name != value)
{
version++;
name = value;
}
}
}
public override string ToString()
{
return name;
}
protected string referenceFrame;
public string ReferenceFrame
{
get { return referenceFrame; }
set { referenceFrame = value; }
}
//public bool SetProp(string name, string value)
//{
// Type thisType = this.GetType();
// PropertyInfo pi = thisType.GetProperty(name);
// bool safeToSet = false;
// Type layerPropType = typeof(LayerProperty);
// object[] attributes = pi.GetCustomAttributes(false);
// foreach (object var in attributes)
// {
// if (var.GetType() == layerPropType)
// {
// safeToSet = true;
// break;
// }
// }
// if (safeToSet)
// {
// //Convert.ChangeType(
// if (pi.PropertyType.BaseType == typeof(Enum))
// {
// pi.SetValue(this, Enum.Parse(pi.PropertyType, value, true), null);
// }
// else if (pi.PropertyType == typeof(TimeSpan))
// {
// pi.SetValue(this, TimeSpan.Parse(value), null);
// }
// else if (pi.PropertyType == typeof(Vector3d))
// {
// pi.SetValue(this, Vector3d.Parse(value), null);
// }
// else
// {
// // todo fix this
// // pi.SetValue(this, Convert.ChangeType(value, pi.PropertyType), null);
// }
// }
// return safeToSet;
//}
//public bool SetProps(string xml)
//{
// XDocument doc = XDocument.Parse(xml);
// XElement root = doc.Element("LayerApi");
// XElement LayerNode = root.Element("Layer");
// foreach (XAttribute attrib in LayerNode.Attributes())
// {
// if (attrib.Name == "Class")
// {
// continue;
// }
// if (!SetProp(attrib.Name.ToString(), attrib.Value))
// {
// return false;
// }
// }
// return true;
//}
//public string GetProp(string name)
//{
// Type thisType = this.GetType();
// PropertyInfo pi = thisType.GetProperty(name);
// bool safeToGet = false;
// Type layerPropType = typeof(LayerProperty);
// object[] attributes = pi.GetCustomAttributes(false);
// foreach (object var in attributes)
// {
// if (var.GetType() == layerPropType)
// {
// safeToGet = true;
// break;
// }
// }
// if (safeToGet)
// {
// return pi.GetValue(this, null).ToString();
// }
// return null;
//}
public string GetProps()
{
//MemoryStream ms = new MemoryStream();
//using (XmlTextWriter xmlWriter = new XmlTextWriter(ms, System.Text.Encoding.UTF8))
//{
// xmlWriter.Formatting = Formatting.Indented;
// xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
// xmlWriter.WriteStartElement("LayerApi");
// xmlWriter.WriteElementString("Status", "Success");
// xmlWriter.WriteStartElement("Layer");
// xmlWriter.WriteAttributeString("Class", this.GetType().ToString().Replace("TerraViewer.",""));
// Type thisType = this.GetType();
// PropertyInfo[] properties = thisType.GetProperties();
// Type layerPropType = typeof(LayerProperty);
// foreach (PropertyInfo pi in properties)
// {
// bool safeToGet = false;
// object[] attributes = pi.GetCustomAttributes(false);
// foreach (object var in attributes)
// {
// if (var.GetType() == layerPropType)
// {
// safeToGet = true;
// break;
// }
// }
// if (safeToGet)
// {
// xmlWriter.WriteAttributeString(pi.Name, pi.GetValue(this, null).ToString());
// }
// }
// xmlWriter.WriteEndElement();
// xmlWriter.WriteFullEndElement();
// xmlWriter.Close();
//}
//byte[] data = ms.GetBuffer();
//return Encoding.UTF8.GetString(data);
return "";
}
protected Color color = Colors.White;
public virtual Color Color
{
get { return color; }
set
{
if (color != value)
{
color = value;
version++;
CleanUp();
//todo should this invalidate and cleanup
}
}
}
public virtual void ColorChanged()
{
CleanUp();
}
public virtual string ColorValue
{
get
{
return Color.ToString();
}
set
{
Color = Color.FromName(value);
}
}
// private bool enabled = true;
public bool Enabled = true;
//{
// get { return enabled; }
// set
// {
// if (enabled != value)
// {
// version++;
// enabled = value;
// }
// //todo notify of change
// }
//}
protected bool astronomical = false;
public bool Astronomical
{
get { return astronomical; }
set
{
if (astronomical != value)
{
version++;
astronomical = value;
}
}
}
//
//public virtual string[] Header
//{
// get
// {
// return null;
// }
//}
/* Save Load support
*
*/
public virtual string GetTypeName()
{
return "TerraViewer.Layer";
}
public virtual void SaveToXml(XmlTextWriter xmlWriter)
{
//todo write
xmlWriter.WriteStartElement("Layer");
xmlWriter.WriteAttributeString("Id", ID.ToString());
xmlWriter.WriteAttributeString("Type", GetTypeName());
xmlWriter.WriteAttributeString("Name", Name);
xmlWriter.WriteAttributeString("ReferenceFrame", referenceFrame);
xmlWriter.WriteAttributeString("Color", color.Save());
xmlWriter.WriteAttributeString("Opacity", opacity.ToString());
xmlWriter.WriteAttributeString("StartTime", Util.XMLDate(StartTime));
xmlWriter.WriteAttributeString("EndTime", Util.XMLDate(EndTime));
xmlWriter.WriteAttributeString("FadeSpan", FadeSpan.ToString());
xmlWriter.WriteAttributeString("FadeType", FadeType.ToString());
WriteLayerProperties(xmlWriter);
xmlWriter.WriteEndElement();
}
public virtual void WriteLayerProperties(XmlTextWriter xmlWriter)
{
return;
}
public virtual void InitializeFromXml(XmlNode node)
{
}
public static Layer FromXml(XmlNode layerNode, bool someFlag)
{
string layerClassName = layerNode.Attributes.GetNamedItem("Type").Value.ToString();
string overLayType = layerClassName.Replace("TerraViewer.","");
if (overLayType == null)
{
return null;
}
Layer newLayer = null;
switch (overLayType)
{
case "SpreadSheetLayer":
newLayer = new SpreadSheetLayer();
break;
case "GreatCirlceRouteLayer":
newLayer = new GreatCirlceRouteLayer();
break;
case "GridLayer":
newLayer = new GridLayer();
break;
case "ImageSetLayer":
newLayer = new ImageSetLayer();
break;
case "Object3dLayer":
newLayer = new Object3dLayer();
break;
case "OrbitLayer":
newLayer = new OrbitLayer();
break;
default:
return null;
}
//Force inheritance.
// TODO: Understand why this breaks in SS .8
//Script.Literal("for(var method in this){\n /*if (({}).toString.call(this[method]).match(/\\s([a-zA-Z]+)/)[1].toLowerCase() == 'function'){\n*/ newLayer[method] = this[method];/*\n}*/\n}");
newLayer.InitFromXml(layerNode);
return newLayer;
}
public virtual void InitFromXml(XmlNode node)
{
ID = Guid.FromString(node.Attributes.GetNamedItem("Id").Value);
Name = node.Attributes.GetNamedItem("Name").Value;
referenceFrame = node.Attributes.GetNamedItem("ReferenceFrame").Value;
color = Color.Load(node.Attributes.GetNamedItem("Color").Value);
opacity = Single.Parse(node.Attributes.GetNamedItem("Opacity").Value);
if (node.Attributes.GetNamedItem("StartTime") != null)
{
StartTime = new Date(node.Attributes.GetNamedItem("StartTime").Value);
}
if (node.Attributes.GetNamedItem("EndTime") != null)
{
EndTime = new Date(node.Attributes.GetNamedItem("EndTime").Value);
}
if (node.Attributes.GetNamedItem("FadeSpan") != null)
{
FadeSpan = Util.ParseTimeSpan((node.Attributes.GetNamedItem("FadeSpan").Value));
}
if (node.Attributes.GetNamedItem("FadeType") != null)
{
switch (node.Attributes.GetNamedItem("FadeType").Value)
{
case "In":
FadeType = FadeType.FadeIn;
break;
case "Out":
FadeType = FadeType.FadeOut;
break;
case "Both":
FadeType = FadeType.Both;
break;
case "None":
FadeType = FadeType.None;
break;
default:
break;
}
}
InitializeFromXml(node);
}
public virtual void LoadData(TourDocument doc, string filename)
{
return;
}
public virtual void AddFilesToCabinet(FileCabinet fc)
{
return;
}
public void GetStringFromGzipBlob(System.Html.Data.Files.Blob blob, GzipStringReady dataReady)
{
FileReader reader = new FileReader();
reader.OnLoadEnd = delegate (System.Html.Data.Files.FileProgressEvent e)
{
string result = (string)Script.Literal("pako.inflate(e.target.result, { to: 'string' })");
dataReady(result);
};
reader. ReadAsArrayBuffer(blob);
}
}
public delegate void GzipStringReady(string data);
class LayerCollection : Layer
{
public override bool Draw(RenderContext renderContext, float opacity, bool flat)
{
return base.Draw(renderContext, opacity, false);
}
}
//public class MarkerPlot
//{
// public Texture Texture;
// public VertexBuffer VertexBuffer = null;
// public int PointCount = 0;
// public MarkerPlot()
// {
// }
// public MarkerPlot(Texture texture, VertexBuffer vertexBuffer, int pointCount)
// {
// Texture = texture;
// VertexBuffer = vertexBuffer;
// PointCount = pointCount;
// }
//}
public class DomainValue
{
public DomainValue(string text, int markerIndex)
{
Text = text;
MarkerIndex = markerIndex;
}
public string Text;
public int MarkerIndex = 4;
public object CustomMarker = null;
}
}
| 27.275 | 202 | 0.459481 | [
"MIT"
] | astrofrog/wwt-web-client | HTML5SDK/wwtlib/Layers/Layer.cs | 18,549 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetPad.Compilation;
using NetPad.Packages;
using NetPad.Scripts;
namespace NetPad.Runtimes;
public class DefaultExternalProcessScriptRuntimeFactory : IScriptRuntimeFactory
{
private readonly IServiceProvider _serviceProvider;
public DefaultExternalProcessScriptRuntimeFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Task<IScriptRuntime> CreateScriptRuntimeAsync(Script script)
{
var runtime = new ExternalProcessScriptRuntime(
script,
_serviceProvider.CreateScope(),
_serviceProvider.GetRequiredService<ICodeParser>(),
_serviceProvider.GetRequiredService<ICodeCompiler>(),
_serviceProvider.GetRequiredService<IPackageProvider>(),
_serviceProvider.GetRequiredService<ILogger<ExternalProcessScriptRuntime>>()
);
return Task.FromResult<IScriptRuntime>(runtime);
}
}
| 32.21875 | 88 | 0.749758 | [
"MIT"
] | tareqimbasher/NetPad | src/Infrastructure/ScriptRuntimes/NetPad.ExternalProcessScriptRuntime/DefaultExternalProcessScriptRuntimeFactory.cs | 1,031 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace System.Runtime.Analyzers
{
/// <summary>
/// CA2215: Dispose Methods Should Call Base Class Dispose
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public class CSharpDisposeMethodsShouldCallBaseClassDisposeFixer : DisposeMethodsShouldCallBaseClassDisposeFixer
{
}
} | 38.05 | 160 | 0.713535 | [
"Apache-2.0"
] | amcasey/roslyn-analyzers | src/System.Runtime.Analyzers/CSharp/CSharpDisposeMethodsShouldCallBaseClassDispose.Fixer.cs | 761 | C# |
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Juno.Sdk.Webhooks.Queries
{
public class GetWebhookSecretRequest : IRequest<string>
{
public Dictionary<string, List<string>> Parameters { get; set; }
}
}
| 22.941176 | 72 | 0.758974 | [
"MIT"
] | marivaaldo/juno-sdk-net | src/Juno.Sdk/Webhooks/Queries/GetWebhookSecretRequest.cs | 392 | C# |
// <copyright file="TestMetricProcessor.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using OpenTelemetry.Metrics.Aggregators;
using OpenTelemetry.Metrics.Export;
namespace OpenTelemetry.Metrics.Test
{
internal class TestMetricProcessor : MetricProcessor
{
public List<Tuple<string, LabelSet, long>> counters = new List<Tuple<string, LabelSet, long>>();
public List<Tuple<string, LabelSet, Tuple<long, DateTime>>> gauges = new List<Tuple<string, LabelSet, Tuple<long, DateTime>>>();
public List<Tuple<string, LabelSet, List<long>>> measures = new List<Tuple<string, LabelSet, List<long>>>();
public override void ProcessCounter(string meterName, string metricName, LabelSet labelSet, CounterSumAggregator<long> sumAggregator)
{
counters.Add(new Tuple<string, LabelSet, long>(metricName, labelSet, sumAggregator.ValueFromLastCheckpoint()));
}
public override void ProcessCounter(string meterName, string metricName, LabelSet labelSet, CounterSumAggregator<double> sumAggregator)
{
}
public override void ProcessGauge(string meterName, string metricName, LabelSet labelSet, GaugeAggregator<long> gaugeAggregator)
{
gauges.Add(new Tuple<string, LabelSet, Tuple<long, DateTime>>(metricName, labelSet, gaugeAggregator.ValueFromLastCheckpoint()));
}
public override void ProcessGauge(string meterName, string metricName, LabelSet labelSet, GaugeAggregator<double> gaugeAggregator)
{
}
public override void ProcessMeasure(string meterName, string metricName, LabelSet labelSet, MeasureExactAggregator<long> measureAggregator)
{
measures.Add(new Tuple<string, LabelSet, List<long>>(metricName, labelSet, measureAggregator.ValueFromLastCheckpoint()));
}
public override void ProcessMeasure(string meterName, string metricName, LabelSet labelSet, MeasureExactAggregator<double> measureAggregator)
{
}
}
}
| 46.103448 | 149 | 0.728871 | [
"Apache-2.0"
] | FrancisChung/opentelemetry-dotnet | test/OpenTelemetry.Tests/Impl/Metrics/TestMetricProcessor.cs | 2,676 | C# |
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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 GoogleCloudExtension.Utils;
using GoogleCloudExtension.Utils.Async;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GoogleCloudExtensionUnitTests.Utils
{
[TestClass]
public class ProtectedAsyncCommandTests : ExtensionTestBase
{
[TestMethod]
public void TestConstrutor_DefaultsCanExecuteCommandToTrue()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.CompletedTask);
Assert.IsTrue(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestConstrutor_OverridesDefaultCanExecuteCommandWithParameter()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.CompletedTask, false);
Assert.IsFalse(objectUnderTest.CanExecuteCommand);
}
[TestMethod]
public void TestConstrutor_InitalizesLatestExecutionWithCompletedTask()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.CompletedTask);
Assert.IsTrue(objectUnderTest.LatestExecution.IsCompleted);
}
[TestMethod]
public void TestExecute_InvokesProvidedAction()
{
var tcs = new TaskCompletionSource<object>();
var actionMock = new Mock<Func<Task>>();
actionMock.Setup(f => f()).Returns(tcs.Task);
var objectUnderTest = new ProtectedAsyncCommand(actionMock.Object);
objectUnderTest.Execute(null);
actionMock.Verify(f => f(), Times.Once);
}
[TestMethod]
public void TestExecute_DoesNotThrowWhenActionErrors()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.FromException(new Exception()));
objectUnderTest.Execute(null);
}
[TestMethod]
public void TestExecute_UpdatesLatestExecution()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.CompletedTask);
AsyncProperty originalExecution = objectUnderTest.LatestExecution;
objectUnderTest.Execute(null);
Assert.AreNotEqual(originalExecution, objectUnderTest.LatestExecution);
}
[TestMethod]
public void TestLatestExecution_TracksActionTask()
{
var tcs = new TaskCompletionSource<object>();
var objectUnderTest = new ProtectedAsyncCommand(() => tcs.Task);
objectUnderTest.Execute(null);
Assert.AreEqual(tcs.Task, objectUnderTest.LatestExecution.ActualTask);
}
[TestMethod]
public void TestLatestExecution_NotifiesOnChange()
{
var objectUnderTest = new ProtectedAsyncCommand(() => Task.CompletedTask);
var changedProperties = new List<string>();
objectUnderTest.PropertyChanged += (sender, args) => changedProperties.Add(args.PropertyName);
objectUnderTest.Execute(null);
CollectionAssert.AreEqual(new[] { nameof(objectUnderTest.LatestExecution) }, changedProperties);
}
}
}
| 34.805556 | 108 | 0.672519 | [
"Apache-2.0"
] | GoogleCloudPlatform/google-cloud-visualstudio | GoogleCloudExtension/GoogleCloudExtensionUnitTests/Utils/ProtectedAsyncCommandTests.cs | 3,761 | C# |
using System;
namespace AvP.Joy.Sequences
{
public sealed class WrappedSequence<T> : ISequence<T>
{
private readonly ISequence<T> source;
private readonly Func<ISequence<T>, ISequence<T>> tailWrapper;
public WrappedSequence(ISequence<T> source, Func<ISequence<T>, ISequence<T>> tailWrapper)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (tailWrapper == null) throw new ArgumentNullException(nameof(tailWrapper));
var sourceAs = source as WrappedSequence<T>;
if (sourceAs != null)
{
this.source = sourceAs.source;
this.tailWrapper = tail => tailWrapper(sourceAs.tailWrapper(tail));
}
else
{
this.source = source;
this.tailWrapper = tailWrapper;
}
}
public bool Any { get { return source.Any; } }
public T Head { get { return source.Head; } }
public ISequence<T> GetTail() { return tailWrapper(source.GetTail()); }
}
} | 34.28125 | 97 | 0.577028 | [
"Apache-2.0"
] | av-pinzur/JoySharp | Joy/Sequences/WrappedSequence.cs | 1,099 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using books_api.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace books_api.Controllers
{
[Authorize]
[Route("[controller]")]
[ApiController]
public class OrdersController : ControllerBase
{
private readonly OrdersStore store;
public OrdersController(OrdersStore store)
{
this.store = store;
}
[HttpGet]
[Route("")]
public IActionResult GetOrders()
{
return Ok(store.Orders);
}
}
}
| 21.09375 | 50 | 0.648889 | [
"MIT"
] | johnsilver94/bookstore-app | bookstore-back/books-api/Controllers/OrdersController.cs | 677 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Sprache;
namespace DockerComposeBuild
{
internal class Project
{
public Project(Guid guid, string name, string projectFile, Guid buildConfiguration)
{
Guid = guid;
Name = name ?? throw new ArgumentNullException(nameof(name));
ProjectFile = projectFile ?? throw new ArgumentNullException(nameof(projectFile));
BuildConfiguration = buildConfiguration;
}
public Guid Guid { get; set; }
public string Name { get; set; }
public string ProjectFile { get; set; }
public Guid BuildConfiguration { get; set; }
public override string ToString()
{
return $"{nameof(Guid)}: {Guid}, {nameof(Name)}: {Name}, {nameof(ProjectFile)}: {ProjectFile}, {nameof(BuildConfiguration)}: {BuildConfiguration}";
}
}
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: DockerComposeBuild <target> <destination>");
return;
}
var target = args[0];
var destination = args[1];
// Read target
var targetFile = File.ReadAllText(target);
var targetFileMultiline = File.ReadLines(target).ToArray();
// Parse all projects
var projects = ReadProjects(targetFile);
// Find docker compose
var dockerComposeProjects =
projects.Where(e => e.Name == "docker-compose" && e.ProjectFile.EndsWith(".dcproj")).ToList();
// Check if docker compose does not exists
if (!dockerComposeProjects.Any())
{
Console.WriteLine("Aborting: No docker compose project found");
return;
}
// Check if contain more than one compose file
if (dockerComposeProjects.Count > 1)
{
Console.WriteLine("Aborting: Multiple docker compose files found");
return;
}
// Get docker compose
var dockerCompose = dockerComposeProjects.First();
// Update docker compose
var destinationFileMultiline = new List<string>();
for (int i = 0; i < targetFileMultiline.Length; i++)
{
if (targetFileMultiline[i].Contains(dockerCompose.Name, StringComparison.OrdinalIgnoreCase) &&
targetFileMultiline[i].Contains(dockerCompose.ProjectFile, StringComparison.OrdinalIgnoreCase) &&
targetFileMultiline[i].Contains(dockerCompose.Guid.ToString(), StringComparison.OrdinalIgnoreCase) &&
targetFileMultiline[i].Contains(dockerCompose.ProjectFile.ToString(), StringComparison.OrdinalIgnoreCase))
{
i += 1;
continue;
}
if (targetFileMultiline[i].Contains(dockerCompose.BuildConfiguration.ToString(),
StringComparison.OrdinalIgnoreCase))
{
continue;
}
destinationFileMultiline.Add(targetFileMultiline[i]);
}
// Write output
File.WriteAllLines(destination, destinationFileMultiline);
}
private static IEnumerable<Project> ReadProjects(string slnFile)
{
// Setup parsers
Parser<Guid> guidParser =
from open in Parse.String("\"{")
from guid in Parse.LetterOrDigit.Or(e => Parse.Char('-').Invoke(e)).Many()
from close in Parse.String("}\"")
select Guid.Parse(string.Join("", guid));
Parser<string> nameParser =
from open in Parse.Char('\"')
from name in Parse.CharExcept('\"').Many()
from close in Parse.Char('\"')
select string.Join("", name);
Parser<Project> projectParser =
from beginProject in Parse.String("(")
from guid in guidParser.Token()
from endProject in Parse.String(")")
from whiteSpace in Parse.WhiteSpace.Many()
from equal in Parse.Char('=')
from whitespace2 in Parse.WhiteSpace.Many()
from name in nameParser.Token()
from whitespace3 in Parse.WhiteSpace.Many()
from comma1 in Parse.Char(',')
from whitespace4 in Parse.WhiteSpace.Many()
from projectFile in nameParser.Token()
from whitespace5 in Parse.WhiteSpace.Many()
from comma2 in Parse.Char(',')
from whitespace6 in Parse.WhiteSpace.Many()
from buildConfiguration in guidParser.Token()
from whitespace7 in Parse.WhiteSpace.Many()
select new Project(guid, name, projectFile, buildConfiguration);
var slnParser =
from whitespace1 in Parse.WhiteSpace.Or(Parse.AnyChar.Except(Parse.String("Project"))).Many()
from parsedProjects in Parse.Many(
// from ignored in Parse.Until((Parse.WhiteSpace.Or(Parse.AnyChar)).Many(), Parse.String("Project"))
from _1 in Parse.WhiteSpace.Many()
from beginProject in Parse.String("Project")
from project in projectParser.Token()
from endProject in Parse.String("EndProject")
from _2 in Parse.WhiteSpace.Many()
select project
)
from whitespace2 in (Parse.WhiteSpace.Or(Parse.AnyChar)).Many()
select parsedProjects;
return slnParser.Parse(slnFile);
}
}
}
| 39.013072 | 159 | 0.55671 | [
"MIT"
] | sahb1239/SAHB.Build.DockerComposeRemoval | src/DockerComposeBuild/Program.cs | 5,971 | C# |
namespace CloudPharmacy.Common.CommonResponse
{
public class OperationResponse
{
protected bool _forcedFailedResponse;
public bool CompletedWithSuccess => OperationError == null && !_forcedFailedResponse;
public OperationError OperationError { get; set; }
public OperationResponse SetAsFailureResponse(OperationError operationError)
{
OperationError = operationError;
_forcedFailedResponse = true;
return this;
}
}
public class OperationResponse<T> : OperationResponse
{
public OperationResponse() { }
public OperationResponse(T result)
{
Result = result;
}
public T Result { get; set; }
public new OperationResponse<T> SetAsFailureResponse(OperationError operationError)
{
base.SetAsFailureResponse(operationError);
return this;
}
}
}
| 27.911765 | 93 | 0.632244 | [
"MIT"
] | Daniel-Krzyczkowski/Cloud-Pharmacy-On-Azure | src/backend-apis/CloudPharmacy.Common/CommonResponse/OperationResponse.cs | 951 | C# |
#region License
// Copyright (c) .NET Foundation and contributors.
//
// 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.
//
// The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
#endregion
namespace FastEndpoints.Validation.Internal
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Represents a chain of properties
/// </summary>
public class PropertyChain
{
private readonly List<string> _memberNames = new List<string>(2);
/// <summary>
/// Creates a new PropertyChain.
/// </summary>
public PropertyChain()
{
}
/// <summary>
/// Creates a new PropertyChain based on another.
/// </summary>
public PropertyChain(PropertyChain parent)
{
if (parent != null
&& parent._memberNames.Count > 0)
{
_memberNames.AddRange(parent._memberNames);
}
}
/// <summary>
/// Creates a new PropertyChain
/// </summary>
/// <param name="memberNames"></param>
public PropertyChain(IEnumerable<string> memberNames)
{
_memberNames.AddRange(memberNames);
}
/// <summary>
/// Creates a PropertyChain from a lambda expression
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static PropertyChain FromExpression(LambdaExpression expression)
{
var memberNames = new Stack<string>();
var getMemberExp = new Func<Expression, MemberExpression>(toUnwrap =>
{
if (toUnwrap is UnaryExpression)
{
return ((UnaryExpression)toUnwrap).Operand as MemberExpression;
}
return toUnwrap as MemberExpression;
});
var memberExp = getMemberExp(expression.Body);
while (memberExp != null)
{
memberNames.Push(memberExp.Member.Name);
memberExp = getMemberExp(memberExp.Expression);
}
return new PropertyChain(memberNames);
}
/// <summary>
/// Adds a MemberInfo instance to the chain
/// </summary>
/// <param name="member">Member to add</param>
public void Add(MemberInfo member)
{
if (member != null)
_memberNames.Add(member.Name);
}
/// <summary>
/// Adds a property name to the chain
/// </summary>
/// <param name="propertyName">Name of the property to add</param>
public void Add(string propertyName)
{
if (!string.IsNullOrEmpty(propertyName))
_memberNames.Add(propertyName);
}
/// <summary>
/// Adds an indexer to the property chain. For example, if the following chain has been constructed:
/// Parent.Child
/// then calling AddIndexer(0) would convert this to:
/// Parent.Child[0]
/// </summary>
/// <param name="indexer"></param>
/// <param name="surroundWithBrackets">Whether square brackets should be applied before and after the indexer. Default true.</param>
public void AddIndexer(object indexer, bool surroundWithBrackets = true)
{
if (_memberNames.Count == 0)
{
throw new InvalidOperationException("Could not apply an Indexer because the property chain is empty.");
}
string last = _memberNames[_memberNames.Count - 1];
last += surroundWithBrackets ? "[" + indexer + "]" : indexer;
_memberNames[_memberNames.Count - 1] = last;
}
/// <summary>
/// Creates a string representation of a property chain.
/// </summary>
public override string ToString()
{
// Performance: Calling string.Join causes much overhead when it's not needed.
switch (_memberNames.Count)
{
case 0:
return string.Empty;
case 1:
return _memberNames[0];
default:
return string.Join(ValidatorOptions.Global.PropertyChainSeparator, _memberNames);
}
}
/// <summary>
/// Checks if the current chain is the child of another chain.
/// For example, if chain1 were for "Parent.Child" and chain2 were for "Parent.Child.GrandChild" then
/// chain2.IsChildChainOf(chain1) would be true.
/// </summary>
/// <param name="parentChain">The parent chain to compare</param>
/// <returns>True if the current chain is the child of the other chain, otherwise false</returns>
public bool IsChildChainOf(PropertyChain parentChain)
{
return ToString().StartsWith(parentChain.ToString());
}
/// <summary>
/// Builds a property path.
/// </summary>
public string BuildPropertyName(string propertyName)
{
if (_memberNames.Count == 0)
{
return propertyName;
}
var chain = new PropertyChain(this);
chain.Add(propertyName);
return chain.ToString();
}
/// <summary>
/// Number of member names in the chain
/// </summary>
public int Count => _memberNames.Count;
}
}
| 33.675824 | 140 | 0.57285 | [
"MIT"
] | stefandevo/FastEndpoints | Src/Validation/Internal/PropertyChain.cs | 6,129 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4963
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DeskConnectActiveListener.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.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;
}
}
}
}
| 34.774194 | 150 | 0.586271 | [
"MIT"
] | aronsajan/Desk-Connect | src/DeskConnectActiveListener/Properties/Settings.Designer.cs | 1,080 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ProviderHub
{
/// <summary>
/// API Version: 2020-11-20.
/// </summary>
[AzureNativeResourceType("azure-native:providerhub:ResourceTypeRegistration")]
public partial class ResourceTypeRegistration : Pulumi.CustomResource
{
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
[Output("properties")]
public Output<Outputs.ResourceTypeRegistrationResponseProperties> Properties { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a ResourceTypeRegistration resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ResourceTypeRegistration(string name, ResourceTypeRegistrationArgs args, CustomResourceOptions? options = null)
: base("azure-native:providerhub:ResourceTypeRegistration", name, args ?? new ResourceTypeRegistrationArgs(), MakeResourceOptions(options, ""))
{
}
private ResourceTypeRegistration(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:providerhub:ResourceTypeRegistration", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:providerhub:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-native:providerhub/v20201120:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-nextgen:providerhub/v20201120:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-native:providerhub/v20210501preview:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-nextgen:providerhub/v20210501preview:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-native:providerhub/v20210601preview:ResourceTypeRegistration"},
new Pulumi.Alias { Type = "azure-nextgen:providerhub/v20210601preview:ResourceTypeRegistration"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ResourceTypeRegistration resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ResourceTypeRegistration Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ResourceTypeRegistration(name, id, options);
}
}
public sealed class ResourceTypeRegistrationArgs : Pulumi.ResourceArgs
{
[Input("properties")]
public Input<Inputs.ResourceTypeRegistrationPropertiesArgs>? Properties { get; set; }
/// <summary>
/// The name of the resource provider hosted within ProviderHub.
/// </summary>
[Input("providerNamespace", required: true)]
public Input<string> ProviderNamespace { get; set; } = null!;
/// <summary>
/// The resource type.
/// </summary>
[Input("resourceType")]
public Input<string>? ResourceType { get; set; }
public ResourceTypeRegistrationArgs()
{
}
}
}
| 45.305556 | 155 | 0.638872 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ProviderHub/ResourceTypeRegistration.cs | 4,893 | C# |
/*
Copyright 2007-2017 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the MIT License. You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at https://opensource.org/licenses/MIT.
*/
using NGenerics.DataStructures.Mathematical;
using NUnit.Framework;
namespace NGenerics.Tests.DataStructures.Mathematical.Vector3DTests
{
[TestFixture]
public class IncrementOperator
{
[Test]
public void Simple()
{
var vector3D = new Vector3D(4, 7, 8);
vector3D++;
Assert.AreEqual(5, vector3D.X);
Assert.AreEqual(8, vector3D.Y);
Assert.AreEqual(9, vector3D.Z);
}
}
} | 26.666667 | 88 | 0.65875 | [
"MIT"
] | ngenerics/ngenerics | src/NGenerics.Tests/DataStructures/Mathematical/Vector3DTests/IncrementOperator.cs | 800 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Harry.Validation
{
public enum Level
{
None,
Low,
Medium,
High,
Extreme
}
}
| 12.9375 | 33 | 0.570048 | [
"MIT"
] | harry-wangx/Harry.Validation | Harry.Validation.Abstractions/Level.cs | 209 | C# |
using System;
using System.Collections.Generic;
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Validation;
using System.Linq;
using System.Runtime.Serialization;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 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 HOLDER 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.
*/
//
// Generated on Tue, Sep 22, 2015 20:02+1000 for FHIR v1.0.1
//
namespace Hl7.Fhir.Model
{
/// <summary>
/// A digital Signature - XML DigSig, JWT, Graphical image of signature, etc.
/// </summary>
[FhirType("Signature")]
[DataContract]
public partial class Signature : Hl7.Fhir.Model.Element, System.ComponentModel.INotifyPropertyChanged
{
[NotMapped]
public override string TypeName { get { return "Signature"; } }
/// <summary>
/// Indication of the reason the entity signed the object(s)
/// </summary>
[FhirElement("type", InSummary=true, Order=30)]
[Cardinality(Min=1,Max=-1)]
[DataMember]
public List<Hl7.Fhir.Model.Coding> Type
{
get { if(_Type==null) _Type = new List<Hl7.Fhir.Model.Coding>(); return _Type; }
set { _Type = value; OnPropertyChanged("Type"); }
}
private List<Hl7.Fhir.Model.Coding> _Type;
/// <summary>
/// When the signature was created
/// </summary>
[FhirElement("when", InSummary=true, Order=40)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.Instant WhenElement
{
get { return _WhenElement; }
set { _WhenElement = value; OnPropertyChanged("WhenElement"); }
}
private Hl7.Fhir.Model.Instant _WhenElement;
/// <summary>
/// When the signature was created
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public DateTimeOffset? When
{
get { return WhenElement != null ? WhenElement.Value : null; }
set
{
if(value == null)
WhenElement = null;
else
WhenElement = new Hl7.Fhir.Model.Instant(value);
OnPropertyChanged("When");
}
}
/// <summary>
/// Who signed the signature
/// </summary>
[FhirElement("who", InSummary=true, Order=50, Choice=ChoiceType.DatatypeChoice)]
[AllowedTypes(typeof(Hl7.Fhir.Model.FhirUri),typeof(Hl7.Fhir.Model.ResourceReference))]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.Element Who
{
get { return _Who; }
set { _Who = value; OnPropertyChanged("Who"); }
}
private Hl7.Fhir.Model.Element _Who;
/// <summary>
/// The technical format of the signature
/// </summary>
[FhirElement("contentType", InSummary=true, Order=60)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.Code ContentTypeElement
{
get { return _ContentTypeElement; }
set { _ContentTypeElement = value; OnPropertyChanged("ContentTypeElement"); }
}
private Hl7.Fhir.Model.Code _ContentTypeElement;
/// <summary>
/// The technical format of the signature
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public string ContentType
{
get { return ContentTypeElement != null ? ContentTypeElement.Value : null; }
set
{
if(value == null)
ContentTypeElement = null;
else
ContentTypeElement = new Hl7.Fhir.Model.Code(value);
OnPropertyChanged("ContentType");
}
}
/// <summary>
/// The actual signature content (XML DigSig. JWT, picture, etc.)
/// </summary>
[FhirElement("blob", InSummary=true, Order=70)]
[Cardinality(Min=1,Max=1)]
[DataMember]
public Hl7.Fhir.Model.Base64Binary BlobElement
{
get { return _BlobElement; }
set { _BlobElement = value; OnPropertyChanged("BlobElement"); }
}
private Hl7.Fhir.Model.Base64Binary _BlobElement;
/// <summary>
/// The actual signature content (XML DigSig. JWT, picture, etc.)
/// </summary>
/// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks>
[NotMapped]
[IgnoreDataMemberAttribute]
public byte[] Blob
{
get { return BlobElement != null ? BlobElement.Value : null; }
set
{
if(value == null)
BlobElement = null;
else
BlobElement = new Hl7.Fhir.Model.Base64Binary(value);
OnPropertyChanged("Blob");
}
}
public override IDeepCopyable CopyTo(IDeepCopyable other)
{
var dest = other as Signature;
if (dest != null)
{
base.CopyTo(dest);
if(Type != null) dest.Type = new List<Hl7.Fhir.Model.Coding>(Type.DeepCopy());
if(WhenElement != null) dest.WhenElement = (Hl7.Fhir.Model.Instant)WhenElement.DeepCopy();
if(Who != null) dest.Who = (Hl7.Fhir.Model.Element)Who.DeepCopy();
if(ContentTypeElement != null) dest.ContentTypeElement = (Hl7.Fhir.Model.Code)ContentTypeElement.DeepCopy();
if(BlobElement != null) dest.BlobElement = (Hl7.Fhir.Model.Base64Binary)BlobElement.DeepCopy();
return dest;
}
else
throw new ArgumentException("Can only copy to an object of the same type", "other");
}
public override IDeepCopyable DeepCopy()
{
return CopyTo(new Signature());
}
public override bool Matches(IDeepComparable other)
{
var otherT = other as Signature;
if(otherT == null) return false;
if(!base.Matches(otherT)) return false;
if( !DeepComparable.Matches(Type, otherT.Type)) return false;
if( !DeepComparable.Matches(WhenElement, otherT.WhenElement)) return false;
if( !DeepComparable.Matches(Who, otherT.Who)) return false;
if( !DeepComparable.Matches(ContentTypeElement, otherT.ContentTypeElement)) return false;
if( !DeepComparable.Matches(BlobElement, otherT.BlobElement)) return false;
return true;
}
public override bool IsExactly(IDeepComparable other)
{
var otherT = other as Signature;
if(otherT == null) return false;
if(!base.IsExactly(otherT)) return false;
if( !DeepComparable.IsExactly(Type, otherT.Type)) return false;
if( !DeepComparable.IsExactly(WhenElement, otherT.WhenElement)) return false;
if( !DeepComparable.IsExactly(Who, otherT.Who)) return false;
if( !DeepComparable.IsExactly(ContentTypeElement, otherT.ContentTypeElement)) return false;
if( !DeepComparable.IsExactly(BlobElement, otherT.BlobElement)) return false;
return true;
}
}
}
| 38.540084 | 124 | 0.593716 | [
"BSD-3-Clause"
] | ssharunas/fhir-net-api | src/Hl7.Fhir.Core/Model/Generated/Signature.cs | 9,136 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RawNotification.DataAccess.DAImplements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RawNotification.DataAccess.DAImplements.Tests
{
[TestClass()]
public class ReceiverDATests
{
[TestMethod()]
public void GetReceiverByIdTest()
{
using (RawNotificationDB db = new RawNotificationDB())
{
var reveiver = db.ReceiverDA.GetReceiverById(9999);
}
}
}
} | 25.521739 | 67 | 0.67121 | [
"Apache-2.0"
] | lekhasy/RawNotification | Implementation/RN_Enhance/RawNotification/RawNotification.DataAccess.Test/DAImplements/ReceiverDATests.cs | 589 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Rigidbody))]
public class RigidBodyFPSController : PortalTraveller
{
[Tooltip("How fast the player moves.")]
public float MovementSpeed = 7.0f;
[Tooltip("Units per second acceleration")]
public float AccelRate = 20.0f;
[Tooltip("Units per second deceleration")]
public float DecelRate = 20.0f;
[Tooltip("Acceleration the player has in mid-air")]
public float AirborneAccel = 2.0f;
[Tooltip("The velocity applied to the player when the jump button is pressed")]
public float JumpSpeed = 5.0f;
[Tooltip("Extra units added to the player's fudge height... if you're rocketting off ramps or feeling too loosely attached to the ground, increase this. If you're being yanked down to stuff too far beneath you, lower this.")]
public float FudgeExtra = 0.5f; // extra height, can't modify this during runtime
[Tooltip("Maximum slope the player can walk up")]
public float MaximumSlope = 45.0f;
[Tooltip("Camera Sensitivity")]
public float Sensitivity = 8;
[Tooltip("Lowest and highest angle for the camera")]
public Vector2 pitchMinMax = new Vector2(-40, 85);
private bool grounded = false;
// temp vars
private float inputX;
private float inputY;
private Vector3 movement;
private float acceleration; // or deceleration
// keep track of falling
private bool falling;
private float fallSpeed;
// jump state var:
// 0 = hit ground since last jump, can jump if grounded = true
// 1 = jump button pressed, try to jump during fixedupdate
// 2 = jump force applied, waiting to leave the ground
// 3 = jump was successful, haven't hit the ground yet (this state is to ignore fudging)
private byte doJump;
private Vector3 groundNormal; // average normal of the ground i'm standing on
private bool touchingDynamic; // if we're touching a dynamic object, don't prevent idle sliding
private bool groundedLastFrame; // was i grounded last frame? used for fudging
private List<GameObject> collisions; // the objects i'm colliding with
private Dictionary<int, ContactPoint[]> contactPoints; // all of the collision contact points
// temporary calculations
private float halfPlayerHeight;
private float fudgeCheck;
private float bottomCapsuleSphereOrigin; // transform.position.y - this variable = the y coord for the origin of the capsule's bottom sphere
private float capsuleRadius;
private Rigidbody rigidbody;
private Camera cam;
void Awake()
{
movement = Vector3.zero;
grounded = false;
groundNormal = Vector3.zero;
touchingDynamic = false;
groundedLastFrame = false;
collisions = new List<GameObject>();
contactPoints = new Dictionary<int, ContactPoint[]>();
// do our calculations so we don't have to do them every frame
CapsuleCollider capsule = (CapsuleCollider) GetComponent<Collider>();
halfPlayerHeight = capsule.height * 0.5f;
fudgeCheck = halfPlayerHeight + FudgeExtra;
bottomCapsuleSphereOrigin = halfPlayerHeight - capsule.radius;
capsuleRadius = capsule.radius;
PhysicMaterial controllerMat = new PhysicMaterial();
controllerMat.bounciness = 0.0f;
controllerMat.dynamicFriction = 0.0f;
controllerMat.staticFriction = 0.0f;
controllerMat.bounceCombine = PhysicMaterialCombine.Minimum;
controllerMat.frictionCombine = PhysicMaterialCombine.Minimum;
capsule.material = controllerMat;
// just in case this wasn't set in the inspector
rigidbody = GetComponent<Rigidbody>();
rigidbody.freezeRotation = true;
// get the Camera
cam = Camera.main;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void FixedUpdate()
{
// check if we're grounded
RaycastHit hit;
grounded = false;
groundNormal = Vector3.zero;
foreach (ContactPoint[] contacts in contactPoints.Values)
for (int i = 0; i < contacts.Length; i++)
if (contacts[i].point.y <= rigidbody.position.y - bottomCapsuleSphereOrigin && Physics.Raycast(contacts[i].point + Vector3.up, Vector3.down, out hit, 1.1f, ~0) && Vector3.Angle(hit.normal, Vector3.up) <= MaximumSlope)
{
grounded = true;
groundNormal += hit.normal;
}
if (grounded)
{
// average the summed normals
groundNormal.Normalize();
if (doJump == 3)
doJump = 0;
}
else if (doJump == 2)
doJump = 3;
// get player input
inputX = Input.GetAxis("Horizontal");
inputY = Input.GetAxis("Vertical");
// limit the length to 1.0f
float length = Mathf.Sqrt(inputX * inputX + inputY * inputY);
if (length > 1.0f)
{
inputX /= length;
inputY /= length;
}
if (grounded && doJump != 3)
{
if (falling)
{
// we just landed from a fall
falling = false;
this.DoFallDamage(Mathf.Abs(fallSpeed));
}
// align our movement vectors with the ground normal (ground normal = up)
Vector3 newForward = transform.forward;
Vector3.OrthoNormalize(ref groundNormal, ref newForward);
Vector3 targetSpeed = Vector3.Cross(groundNormal, newForward) * inputX * MovementSpeed + newForward * inputY * MovementSpeed;
length = targetSpeed.magnitude;
float difference = length - rigidbody.velocity.magnitude;
// avoid divide by zero
if (Mathf.Approximately(difference, 0.0f))
movement = Vector3.zero;
else
{
// determine if we should accelerate or decelerate
if (difference > 0.0f)
acceleration = Mathf.Min(AccelRate * Time.deltaTime, difference);
else
acceleration = Mathf.Max(-DecelRate * Time.deltaTime, difference);
// normalize the difference vector and store it in movement
difference = 1.0f / difference;
movement = new Vector3((targetSpeed.x - rigidbody.velocity.x) * difference * acceleration, (targetSpeed.y - rigidbody.velocity.y) * difference * acceleration, (targetSpeed.z - rigidbody.velocity.z) * difference * acceleration);
}
if (doJump == 1)
{
// jump button was pressed, do jump
movement.y = JumpSpeed - rigidbody.velocity.y;
doJump = 2;
}
else if (!touchingDynamic && Mathf.Approximately(inputX + inputY, 0.0f) && doJump < 2)
// prevent sliding by countering gravity... this may be dangerous
movement.y -= Physics.gravity.y * Time.deltaTime;
rigidbody.AddForce(new Vector3(movement.x, movement.y, movement.z), ForceMode.VelocityChange);
groundedLastFrame = true;
}
else
{
// not grounded, so check if we need to fudge and do air accel
// fudging
if (groundedLastFrame && doJump != 3 && !falling)
{
// see if there's a surface we can stand on beneath us within fudgeCheck range
if (Physics.Raycast(transform.position, Vector3.down, out hit, fudgeCheck + (rigidbody.velocity.magnitude * Time.deltaTime), ~0) && Vector3.Angle(hit.normal, Vector3.up) <= MaximumSlope)
{
groundedLastFrame = true;
// catches jump attempts that would have been missed if we weren't fudging
if (doJump == 1)
{
movement.y += JumpSpeed;
doJump = 2;
return;
}
// we can't go straight down, so do another raycast for the exact distance towards the surface
// i tried doing exsec and excsc to avoid doing another raycast, but my math sucks and it failed horribly
// if anyone else knows a reasonable way to implement a simple trig function to bypass this raycast, please contribute to the thead!
if (Physics.Raycast(new Vector3(transform.position.x, transform.position.y - bottomCapsuleSphereOrigin, transform.position.z), -hit.normal, out hit, hit.distance, ~0))
{
rigidbody.AddForce(hit.normal * -hit.distance, ForceMode.VelocityChange);
return; // skip air accel because we should be grounded
}
}
}
// if we're here, we're not fudging so we're defintiely airborne
// thus, if falling isn't set, set it
if (!falling)
falling = true;
fallSpeed = rigidbody.velocity.y;
// air accel
if (!Mathf.Approximately(inputX + inputY, 0.0f))
{
// note, this will probably malfunction if you set the air accel too high... this code should be rewritten if you intend to do so
// get direction vector
movement = transform.TransformDirection(new Vector3(inputX * AirborneAccel * Time.deltaTime, 0.0f, inputY * AirborneAccel * Time.deltaTime));
// add up our accel to the current velocity to check if it's too fast
float a = movement.x + rigidbody.velocity.x;
float b = movement.z + rigidbody.velocity.z;
// check if our new velocity will be too fast
length = Mathf.Sqrt(a * a + b * b);
if (length > 0.0f)
{
if (length > MovementSpeed)
{
// normalize the new movement vector
length = 1.0f / Mathf.Sqrt(movement.x * movement.x + movement.z * movement.z);
movement.x *= length;
movement.z *= length;
// normalize our current velocity (before accel)
length = 1.0f / Mathf.Sqrt(rigidbody.velocity.x * rigidbody.velocity.x + rigidbody.velocity.z * rigidbody.velocity.z);
Vector3 rigidbodyDirection = new Vector3(rigidbody.velocity.x * length, 0.0f, rigidbody.velocity.z * length);
// dot product of accel unit vector and velocity unit vector, clamped above 0 and inverted (1-x)
length = (1.0f - Mathf.Max(movement.x * rigidbodyDirection.x + movement.z * rigidbodyDirection.z, 0.0f)) * AirborneAccel * Time.deltaTime;
movement.x *= length;
movement.z *= length;
}
// and finally, add our force
rigidbody.AddForce(new Vector3(movement.x, 0.0f, movement.z), ForceMode.VelocityChange);
}
}
groundedLastFrame = false;
}
// camera control
float mX = Input.GetAxisRaw("Mouse X");
float mY = Input.GetAxisRaw("Mouse Y");
// Verrrrrry gross hack to stop camera swinging down at start
float mMag = Mathf.Sqrt(mX * mX + mY * mY);
if (mMag > 5)
{
mX = 0;
mY = 0;
}
float yaw = rigidbody.transform.eulerAngles.y + mX * Sensitivity;
float pitch = cam.transform.eulerAngles.x - mY * Sensitivity;
if (pitch > 180)
{
pitch -= 360;
}
pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);
cam.transform.eulerAngles = new Vector3(pitch, cam.transform.eulerAngles.y, cam.transform.eulerAngles.z);
rigidbody.transform.eulerAngles = new Vector3(rigidbody.transform.eulerAngles.x, yaw, rigidbody.transform.eulerAngles.z);
}
void Update()
{
// check for input here
if (groundedLastFrame && Input.GetButtonDown("Jump"))
doJump = 1;
}
void DoFallDamage(float fallSpeed) // fallSpeed will be positive
{
// do your fall logic here using fallSpeed to determine how hard we hit the ground
//Debug.Log("Hit the ground at " + fallSpeed.ToString() + " units per second");
}
void OnCollisionEnter(Collision collision)
{
// keep track of collision objects and contact points
collisions.Add(collision.gameObject);
contactPoints.Add(collision.gameObject.GetInstanceID(), collision.contacts);
// check if this object is dynamic
if (!collision.gameObject.isStatic)
touchingDynamic = true;
// reset the jump state if able
if (doJump == 3)
doJump = 0;
}
void OnCollisionStay(Collision collision)
{
// update contact points
contactPoints[collision.gameObject.GetInstanceID()] = collision.contacts;
}
void OnCollisionExit(Collision collision)
{
touchingDynamic = false;
// remove this collision and its associated contact points from the list
// don't break from the list once we find it because we might somehow have duplicate entries, and we need to recheck groundedOnDynamic anyways
for (int i = 0; i < collisions.Count; i++)
{
if (collisions[i] == collision.gameObject)
collisions.RemoveAt(i--);
else if (!collisions[i].isStatic)
touchingDynamic = true;
}
contactPoints.Remove(collision.gameObject.GetInstanceID());
}
public bool Grounded
{
get
{
return grounded;
}
}
public bool Falling
{
get
{
return falling;
}
}
public float FallSpeed
{
get
{
return fallSpeed;
}
}
public Vector3 GroundNormal
{
get
{
return groundNormal;
}
}
public override void Teleport(Transform fromPortal, Transform toPortal, Vector3 pos, Quaternion rot)
{
transform.position = pos;
Vector3 eulerRot = rot.eulerAngles;
rigidbody.transform.eulerAngles = new Vector3(rigidbody.transform.eulerAngles.x, eulerRot.y, rigidbody.transform.eulerAngles.z);
rigidbody.velocity = toPortal.TransformVector(fromPortal.InverseTransformVector(rigidbody.velocity));
rigidbody.angularVelocity = toPortal.TransformVector(fromPortal.InverseTransformVector(rigidbody.angularVelocity));
//Physics.SyncTransforms();
}
} | 38.491003 | 243 | 0.595672 | [
"MIT"
] | 20ChaituR/portal2 | Assets/Scripts/Demo/RigidBodyFPSController.cs | 14,975 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace MyAlbum.Core.Models
{
public class User
{
public string Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Comment> Comments { get; set; }
public ICollection<Photo> Photos { get; set; }
public ICollection<Album> Albums { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public User()
{
Comments = new Collection<Comment>();
Photos = new Collection<Photo>();
Albums = new Collection<Album>();
}
}
} | 26.333333 | 58 | 0.592405 | [
"MIT"
] | NhatTanVu/myalbum | src/WebSPA/Core/Models/User.cs | 790 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;
namespace Millistream.Streaming.DataTypes.UnitTests
{
[TestClass]
public class InsRefTests
{
[TestMethod]
public void TryParseInsRefTest()
{
Assert.IsTrue(InsRef.TryParse("1", out InsRef insRef));
Assert.AreEqual(1ul, insRef);
Assert.IsTrue(InsRef.TryParse("1".GetBytes(), out insRef));
Assert.AreEqual(1ul, insRef);
Assert.IsTrue(InsRef.TryParse("0", out insRef));
Assert.AreEqual(0ul, insRef);
Assert.IsTrue(InsRef.TryParse("0".GetBytes(), out insRef));
Assert.AreEqual(0ul, insRef);
Assert.IsTrue(InsRef.TryParse(ulong.MaxValue.ToString(), out insRef));
Assert.AreEqual(ulong.MaxValue, insRef);
Assert.IsTrue(InsRef.TryParse(ulong.MaxValue.ToString().GetBytes(), out insRef));
Assert.AreEqual(ulong.MaxValue, insRef);
Assert.IsFalse(InsRef.TryParse("-1", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("-1".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse(".", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse(".".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("abc", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("abc".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("1.1", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("1.1".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsTrue(InsRef.TryParse("10 ", out insRef));
Assert.AreEqual(10ul, insRef);
Assert.IsTrue(InsRef.TryParse("10 ".GetBytes(), out insRef));
Assert.AreEqual(10ul, insRef);
Assert.IsFalse(InsRef.TryParse("0 1", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("0 1".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse(".1", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse(".1".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsTrue(InsRef.TryParse(" 5", out insRef));
Assert.AreEqual(5ul, insRef);
Assert.IsTrue(InsRef.TryParse(" 5".GetBytes(), out insRef));
Assert.AreEqual(5ul, insRef);
Assert.IsFalse(InsRef.TryParse("184467440737095516150", out insRef));
Assert.AreEqual(default, insRef);
Assert.IsFalse(InsRef.TryParse("184467440737095516150".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
Assert.IsTrue(InsRef.TryParse("00000000000000000000000184467440".GetBytes(), out insRef));
Assert.AreEqual(184467440ul, insRef);
Assert.IsFalse(InsRef.TryParse("00000000000000000000000184467440737095516150".GetBytes(), out insRef));
Assert.AreEqual(default, insRef);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ParseInsRefWithInvalidCharsTest() => InsRef.Parse("1.3");
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ParseInsRefWithInvalidBytesTest() => InsRef.Parse("-1".GetBytes());
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CompareInsRefToObjectOfAnotherTypeTest() => new InsRef(1).CompareTo(1ul);
[TestMethod]
public void CompareInsRefsTest()
{
InsRef insRef = new InsRef(10);
Assert.AreEqual(1, insRef.CompareTo(null));
Assert.AreEqual(0, insRef.CompareTo(InsRef.Parse("10".GetBytes())));
Assert.AreEqual(-1, insRef.CompareTo(new InsRef(11)));
Assert.AreEqual(1, insRef.CompareTo(new InsRef(9)));
Assert.IsTrue(new InsRef(1).Equals(new InsRef(1)));
Assert.IsTrue(new InsRef(1) == new InsRef(1));
Assert.IsFalse(new InsRef(1).Equals(new InsRef(2)));
Assert.IsFalse(new InsRef(1) == new InsRef(2));
Assert.IsTrue(new InsRef(1) != new InsRef(2));
Assert.IsTrue(new InsRef(10) == 10ul);
Assert.IsTrue(20ul == InsRef.Parse("20".GetBytes()));
Assert.IsFalse(new InsRef(100).Equals(100ul));
Assert.IsFalse(new InsRef(100).Equals(100));
Assert.AreEqual(new InsRef(50).GetHashCode(), InsRef.Parse("50".GetBytes()).GetHashCode());
Assert.AreNotEqual(InsRef.Parse("1".GetBytes()).GetHashCode(), new InsRef(2).GetHashCode());
Assert.IsTrue(new InsRef(1) > new InsRef(0));
Assert.IsTrue(new InsRef(5) < 6ul);
Assert.IsTrue(new InsRef(6) <= 6ul);
Assert.IsTrue(new InsRef(6) >= new InsRef(4));
Assert.IsTrue(new InsRef(6) >= new InsRef(6));
Assert.IsFalse(new InsRef(6) >= new InsRef(7));
Assert.IsFalse(new InsRef(10) > new InsRef(11));
Assert.IsTrue(new InsRef(10) > 9ul);
}
[TestMethod]
public void InsRefToStringTest()
{
InsRef insref = new InsRef(100);
Assert.AreEqual(insref.ToString(), 100ul.ToString());
Assert.AreEqual(insref.ToString("D2", CultureInfo.InvariantCulture), 100ul.ToString("D2", CultureInfo.InvariantCulture));
CultureInfo cultureInfo = new CultureInfo("sv");
Assert.AreEqual(insref.ToString("N0", cultureInfo), 100ul.ToString("N0", cultureInfo));
}
[TestMethod]
public void InsRefToUInt64Test()
{
InsRef insref = new InsRef(100);
ulong ul = insref;
Assert.AreEqual(100ul, ul);
ul = new InsRef(1000);
Assert.AreEqual(1000ul, ul);
}
}
} | 47.801527 | 133 | 0.607314 | [
"MIT"
] | mgnsm/Millistream.NET | Tests/Millistream.Streaming.DataTypes.UnitTests/InsRefTests.cs | 6,264 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// ExtInfos Data Structure.
/// </summary>
[Serializable]
public class ExtInfos : AopObject
{
/// <summary>
/// 唤起鉴权的页面类型;DETAIL表示商详页
/// </summary>
[XmlElement("req_from_page")]
public string ReqFromPage { get; set; }
}
}
| 20 | 47 | 0.578947 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Domain/ExtInfos.cs | 410 | C# |
using System.Linq;
using Elastic.Xunit.XunitPlumbing;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
using Xunit;
using static Tests.Framework.Promisify;
namespace Tests.Analysis
{
[SkipVersion("<5.2.0", "Normalizers are a new 5.2.0 feature")]
public class AnalysisWithNormalizerCrudTests : AnalysisCrudTests
{
public AnalysisWithNormalizerCrudTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override CreateIndexRequest CreateInitializer(string indexName) => new CreateIndexRequest(indexName)
{
Settings = new IndexSettings
{
Analysis = new Nest.Analysis
{
Analyzers = Analyzers.AnalyzerUsageTests.InitializerExample.Analysis.Analyzers,
CharFilters = CharFilters.CharFilterUsageTests.InitializerExample.Analysis.CharFilters,
Tokenizers = Tokenizers.TokenizerUsageTests.InitializerExample.Analysis.Tokenizers,
TokenFilters = TokenFilters.TokenFilterUsageTests.InitializerExample.Analysis.TokenFilters,
Normalizers = Normalizers.NormalizerUsageTests.InitializerExample.Analysis.Normalizers,
}
}
};
protected override ICreateIndexRequest CreateFluent(string indexName, CreateIndexDescriptor c) =>
c.Settings(s => s
.Analysis(a => a
.Analyzers(t => Promise(Analyzers.AnalyzerUsageTests.FluentExample(s).Value.Analysis.Analyzers))
.CharFilters(t => Promise(CharFilters.CharFilterUsageTests.FluentExample(s).Value.Analysis.CharFilters))
.Tokenizers(t => Promise(Tokenizers.TokenizerUsageTests.FluentExample(s).Value.Analysis.Tokenizers))
.TokenFilters(t => Promise(TokenFilters.TokenFilterUsageTests.FluentExample(s).Value.Analysis.TokenFilters))
.Normalizers(t => Promise(Normalizers.NormalizerUsageTests.FluentExample(s).Value.Analysis.Normalizers))
)
);
}
}
| 41.304348 | 113 | 0.789474 | [
"Apache-2.0"
] | Tchami/elasticsearch-net | src/Tests/Analysis/Normalizers/AnalysisWithNormalizerCrudTests.cs | 1,902 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.