content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// File: ConcurrentList.cs
// Copyright (c) 2018-2019 Maksym Shnurenok
// License: MIT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Marketplace.Core.DataTypes.Collections
{
/// <summary>
/// The concurrent list.
/// Credits go to Ronnie Overby (original version is taken from from https://gist.github.com/ronnieoverby/11c8b6b067872db719d7)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="System.Collections.Generic.IList{T}" />
/// <seealso cref="System.IDisposable" />
internal class ConcurrentList<T> : IList<T>, IDisposable
{
#region Fields
/// <summary>
/// The lock
/// </summary>
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
/// <summary>
/// The count
/// </summary>
private int _count = 0;
/// <summary>
/// The array
/// </summary>
private T[] _arr;
#endregion
#region Properties
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
public int Count
{
get
{
_lock.EnterReadLock();
try
{
return _count;
}
finally
{
_lock.ExitReadLock();
}
}
}
/// <summary>
/// Gets the length of the internal array.
/// </summary>
/// <value>
/// The length of the internal array.
/// </value>
public int InternalArrayLength
{
get
{
_lock.EnterReadLock();
try
{
return _arr.Length;
}
finally
{
_lock.ExitReadLock();
}
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentList{T}"/> class.
/// </summary>
/// <param name="initialCapacity">The initial capacity.</param>
public ConcurrentList(int initialCapacity)
{
_arr = new T[initialCapacity];
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentList{T}"/> class.
/// </summary>
public ConcurrentList() : this(4)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentList{T}"/> class.
/// </summary>
/// <param name="items">The items.</param>
public ConcurrentList(IEnumerable<T> items)
{
_arr = items.ToArray();
_count = _arr.Length;
}
#endregion
#region Public methods
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
public void Add(T item)
{
_lock.EnterWriteLock();
try
{
var newCount = _count + 1;
EnsureCapacity(newCount);
_arr[_count] = item;
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name="items">The items.</param>
/// <exception cref="ArgumentNullException">items</exception>
public void AddRange(IEnumerable<T> items)
{
if (items == null)
throw new ArgumentNullException("items");
_lock.EnterWriteLock();
try
{
var arr = items as T[] ?? items.ToArray();
var newCount = _count + arr.Length;
EnsureCapacity(newCount);
Array.Copy(arr, 0, _arr, _count, arr.Length);
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <returns>
/// true if <paramref name="item">item</paramref> was successfully removed from the <see cref="System.Collections.Generic.ICollection`1"></see>; otherwise, false. This method also returns false if <paramref name="item">item</paramref> is not found in the original <see cref="System.Collections.Generic.ICollection`1"></see>.
/// </returns>
public bool Remove(T item)
{
_lock.EnterUpgradeableReadLock();
try
{
var i = IndexOfInternal(item);
if (i == -1)
return false;
_lock.EnterWriteLock();
try
{
RemoveAtInternal(i);
return true;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
_lock.EnterReadLock();
try
{
for (int i = 0; i < _count; i++)
// deadlocking potential mitigated by lock recursion enforcement
yield return _arr[i];
}
finally
{
_lock.ExitReadLock();
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"></see>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"></see>.</param>
/// <returns>
/// The index of <paramref name="item">item</paramref> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return IndexOfInternal(item);
}
finally
{
_lock.ExitReadLock();
}
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"></see> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which item should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"></see>.</param>
/// <exception cref="ArgumentOutOfRangeException">index</exception>
public void Insert(int index, T item)
{
_lock.EnterUpgradeableReadLock();
try
{
if (index > _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
var newCount = _count + 1;
EnsureCapacity(newCount);
// shift everything right by one, starting at index
Array.Copy(_arr, index, _arr, index + 1, _count - index);
// insert
_arr[index] = item;
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"></see> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">index</exception>
public void RemoveAt(int index)
{
_lock.EnterUpgradeableReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
RemoveAtInternal(index);
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
/// </summary>
public void Clear()
{
_lock.EnterWriteLock();
try
{
Array.Clear(_arr, 0, _count);
_count = 0;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
/// <returns>
/// true if <paramref name="item">item</paramref> is found in the <see cref="System.Collections.Generic.ICollection`1"></see>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return IndexOfInternal(item) != -1;
}
finally
{
_lock.ExitReadLock();
}
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
/// <exception cref="ArgumentException">Destination array was not long enough.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
if (_count > array.Length - arrayIndex)
throw new ArgumentException("Destination array was not long enough.");
Array.Copy(_arr, 0, array, arrayIndex, _count);
}
finally
{
_lock.ExitReadLock();
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Gets or sets the <see cref="T"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="T"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException">
/// index
/// or
/// index
/// </exception>
public T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
return _arr[index];
}
finally
{
_lock.ExitReadLock();
}
}
set
{
_lock.EnterUpgradeableReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
_arr[index] = value;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
}
/// <summary>
/// Executes the action thread-safely.
/// </summary>
/// <param name="action">The action.</param>
public void DoSync(Action<ConcurrentList<T>> action)
{
GetSync(l =>
{
action(l);
return 0;
});
}
/// <summary>
/// Executes the function thread-safely.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="func">The function.</param>
/// <returns></returns>
public TResult GetSync<TResult>(Func<ConcurrentList<T>, TResult> func)
{
_lock.EnterWriteLock();
try
{
return func(this);
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_lock.Dispose();
}
#endregion
#region Private methods
/// <summary>
/// Ensures the capacity.
/// </summary>
/// <param name="capacity">The capacity.</param>
private void EnsureCapacity(int capacity)
{
if (_arr.Length >= capacity)
return;
int doubled;
checked
{
try
{
doubled = _arr.Length * 2;
}
catch (OverflowException)
{
doubled = int.MaxValue;
}
}
var newLength = Math.Max(doubled, capacity);
Array.Resize(ref _arr, newLength);
}
/// <summary>
/// Index of the internal item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
private int IndexOfInternal(T item)
{
return Array.FindIndex(_arr, 0, _count, x => x.Equals(item));
}
/// <summary>
/// Removes the internal item at index.
/// </summary>
/// <param name="index">The index.</param>
private void RemoveAtInternal(int index)
{
Array.Copy(_arr, index + 1, _arr, index, _count - index - 1);
_count--;
// release last element
Array.Clear(_arr, _count, 1);
}
#endregion
}
}
| 30.647495 | 332 | 0.473031 | [
"MIT"
] | MaxCrank/marketplace | src/Core/DataTypes/Collections/ConcurrentList.cs | 16,521 | C# |
using System;
using System.Collections.Generic;
using NodeCanvas.Framework.Internal;
using ParadoxNotion.Design;
using ParadoxNotion.Serialization;
using UnityEngine;
using System.Linq;
namespace NodeCanvas.Framework
{
/// A Blackboard component to hold variables
[ParadoxNotion.Design.SpoofAOT]
public class Blackboard : MonoBehaviour, ISerializationCallbackReceiver, IBlackboard
{
///Remark: We serialize the whole blackboard as normal which is the previous behaviour.
///To support prefab overrides we now also serialize each variable individually.
///Each serialized variable has it's own list of references since it can be an object with multiple
///UnityObject fields, or simply a list of UnityObjects.
///We keep both old and new serializations. If something goes wrong or needs change with the new one,
///there is still the old one to fallback to.
[SerializeField] private string _serializedBlackboard;
[SerializeField] private List<UnityEngine.Object> _objectReferences;
[SerializeField] private SerializationPair[] _serializedVariables;
[NonSerialized] private BlackboardSource _blackboard = new BlackboardSource();
[NonSerialized] private bool haltForUndo = false;
[NonSerialized] private string _identifier;
///----------------------------------------------------------------------------------------------
void ISerializationCallbackReceiver.OnBeforeSerialize() { SelfSerialize(); }
void ISerializationCallbackReceiver.OnAfterDeserialize() { SelfDeserialize(); }
///----------------------------------------------------------------------------------------------
///Self Serialize blackboard
public void SelfSerialize() {
if ( haltForUndo /*|| ParadoxNotion.Services.Threader.applicationIsPlaying || Application.isPlaying*/ ) {
return;
}
var newReferences = new List<UnityEngine.Object>();
var newSerialization = JSONSerializer.Serialize(typeof(BlackboardSource), _blackboard, newReferences);
if ( newSerialization != _serializedBlackboard || !newReferences.SequenceEqual(_objectReferences) || ( _serializedVariables == null || _serializedVariables.Length != _blackboard.variables.Count ) ) {
haltForUndo = true;
UndoUtility.RecordObjectComplete(this, UndoUtility.GetLastOperationNameOr("Blackboard Change"));
haltForUndo = false;
_serializedVariables = new SerializationPair[_blackboard.variables.Count];
for ( var i = 0; i < _blackboard.variables.Count; i++ ) {
var serializedVariable = new SerializationPair();
serializedVariable._json = JSONSerializer.Serialize(typeof(Variable), _blackboard.variables.ElementAt(i).Value, serializedVariable._references);
_serializedVariables[i] = serializedVariable;
}
_serializedBlackboard = newSerialization;
_objectReferences = newReferences;
}
}
///Self Deserialize blackboard
public void SelfDeserialize() {
_blackboard = new BlackboardSource();
if ( !string.IsNullOrEmpty(_serializedBlackboard) /*&& ( _serializedVariables == null || _serializedVariables.Length == 0 )*/ ) {
JSONSerializer.TryDeserializeOverwrite<BlackboardSource>(_blackboard, _serializedBlackboard, _objectReferences);
}
//this is to handle prefab overrides
if ( _serializedVariables != null && _serializedVariables.Length > 0 ) {
_blackboard.variables.Clear();
for ( var i = 0; i < _serializedVariables.Length; i++ ) {
var variable = JSONSerializer.Deserialize<Variable>(_serializedVariables[i]._json, _serializedVariables[i]._references);
_blackboard.variables[variable.name] = variable;
}
}
}
///Serialize the blackboard to json with optional list to store object references within.
///Use this in runtime for blackboard save/load
public string Serialize(List<UnityEngine.Object> references, bool pretyJson = false) {
return JSONSerializer.Serialize(typeof(BlackboardSource), _blackboard, references, pretyJson);
}
///Deserialize the blackboard from json with optional list of object references to read serializedreferences from.
///We deserialize ON TOP of existing variables so that external references to them stay intact.
///Use this in runtime for blackboard save/load
public bool Deserialize(string json, List<UnityEngine.Object> references, bool removeMissingVariables = true) {
var deserializedBB = JSONSerializer.Deserialize<BlackboardSource>(json, references);
if ( deserializedBB == null ) { return false; }
this.OverwriteFrom(deserializedBB, removeMissingVariables);
this.InitializePropertiesBinding(( (IBlackboard)this ).propertiesBindTarget, true);
return true;
}
///----------------------------------------------------------------------------------------------
public event System.Action<Variable> onVariableAdded;
public event System.Action<Variable> onVariableRemoved;
string IBlackboard.identifier => _identifier;
Dictionary<string, Variable> IBlackboard.variables { get { return _blackboard.variables; } set { _blackboard.variables = value; } }
Component IBlackboard.propertiesBindTarget => this;
UnityEngine.Object IBlackboard.unityContextObject => this;
IBlackboard IBlackboard.parent => null;
string IBlackboard.independantVariablesFieldName => nameof(_serializedVariables);
void IBlackboard.TryInvokeOnVariableAdded(Variable variable) { if ( onVariableAdded != null ) onVariableAdded(variable); }
void IBlackboard.TryInvokeOnVariableRemoved(Variable variable) { if ( onVariableRemoved != null ) onVariableRemoved(variable); }
///----------------------------------------------------------------------------------------------
//...
virtual protected void Awake() {
_identifier = gameObject.name;
this.InitializePropertiesBinding(( (IBlackboard)this ).propertiesBindTarget, false);
}
///----------------------------------------------------------------------------------------------
//These exist here only for backward compatibility in case ppl used these methods in any reflection
///Add a new variable of name and type
public Variable AddVariable(string name, System.Type type) {
return IBlackboardExtensions.AddVariable(this, name, type);
}
///Add a new variable of name and value
public Variable AddVariable(string name, object value) {
return IBlackboardExtensions.AddVariable(this, name, value);
}
///Delete the variable with specified name
public Variable RemoveVariable(string name) {
return IBlackboardExtensions.RemoveVariable(this, name);
}
///Get a Variable of name and optionaly type
public Variable GetVariable(string name, System.Type ofType = null) {
return IBlackboardExtensions.GetVariable(this, name, ofType);
}
///Get a Variable of ID and optionaly type
public Variable GetVariableByID(string ID) {
return IBlackboardExtensions.GetVariableByID(this, ID);
}
//Generic version of get variable
public Variable<T> GetVariable<T>(string name) {
return IBlackboardExtensions.GetVariable<T>(this, name);
}
///Get the variable value of name
public T GetVariableValue<T>(string name) {
return IBlackboardExtensions.GetVariableValue<T>(this, name);
}
///Set the variable value of name
public Variable SetVariableValue(string name, object value) {
return IBlackboardExtensions.SetVariableValue(this, name, value);
}
[System.Obsolete("Use GetVariableValue")]
public T GetValue<T>(string name) { return GetVariableValue<T>(name); }
[System.Obsolete("Use SetVariableValue")]
public Variable SetValue(string name, object value) { return SetVariableValue(name, value); }
///----------------------------------------------------------------------------------------------
[ContextMenu("Show Json")]
void ShowJson() { JSONSerializer.ShowData(_serializedBlackboard, this.name); }
///----------------------------------------------------------------------------------------------
///Saves the Blackboard in PlayerPrefs with saveKey being it's name. You can use this for a Save system
public string Save() { return Save(this.name); }
///Saves the Blackboard in PlayerPrefs in the provided saveKey. You can use this for a Save system
public string Save(string saveKey) {
var json = Serialize(null);
PlayerPrefs.SetString(saveKey, json);
return json;
}
///Loads back the Blackboard from PlayerPrefs saveKey same as it's name. You can use this for a Save system
public bool Load() { return Load(this.name); }
///Loads back the Blackboard from PlayerPrefs of the provided saveKey. You can use this for a Save system
public bool Load(string saveKey) {
var json = PlayerPrefs.GetString(saveKey);
if ( string.IsNullOrEmpty(json) ) {
Debug.Log("No data to load blackboard variables from key " + saveKey);
return false;
}
return Deserialize(json, null, true);
}
///----------------------------------------------------------------------------------------------
virtual protected void OnValidate() { _identifier = gameObject.name; }
public override string ToString() { return _identifier; }
}
} | 49.721951 | 211 | 0.613951 | [
"MIT"
] | BlestxVentures/oculus-experiments | Assets/External/ParadoxNotion/CanvasCore/Framework/Runtime/Variables/Blackboard.cs | 10,195 | C# |
/*
* FactSet Symbology API
*
* The FactSet Symbology API provides symbol resolution services, allowing clients to translate market identifiers into various symbology types. various market symbology types such as, FactSet Permanent Identifiers, CUSIP, ISIN, SEDOL, Tickers, and Bloomberg FIGIs. Factset's Symbology API sits at the center of its hub-and-spoke data model, enabling you to quickly harmonize the expanding catalog of Content APIs. Translate market IDs into CUSIP, SEDOL, ISIN, Tickers as a point in time or for the entire history of the requested id allowing Data Management workflows to normalize ids over time. Additionally, the Symbology API provides translation of market ids into Bloomberg FIGI.
*
* The version of the OpenAPI document: 2.0.0
* Contact: api@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace FactSet.SDK.Symbology.Model
{
/// <summary>
/// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification
/// </summary>
public abstract partial class AbstractOpenAPISchema
{
/// <summary>
/// Custom JSON serializer
/// </summary>
static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
MissingMemberHandling = MissingMemberHandling.Error,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Custom JSON serializer for objects with additional properties
/// </summary>
static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings
{
// OpenAPI generated types generally hide default constructors.
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
OverrideSpecifiedNames = false
}
}
};
/// <summary>
/// Gets or Sets the actual instance
/// </summary>
public abstract Object ActualInstance { get; set; }
/// <summary>
/// Gets or Sets IsNullable to indicate whether the instance is nullable
/// </summary>
public bool IsNullable { get; protected set; }
/// <summary>
/// Gets or Sets the schema type, which can be either `oneOf` or `anyOf`
/// </summary>
public string SchemaType { get; protected set; }
/// <summary>
/// Converts the instance into JSON string.
/// </summary>
public abstract string ToJson();
}
}
| 41.461538 | 690 | 0.656153 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/Symbology/v1/src/FactSet.SDK.Symbology/Model/AbstractOpenAPISchema.cs | 3,234 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Reset_Lever : MonoBehaviour
{
public GameObject door_01;
public GameObject door_02;
public GameObject door_03;
public GameObject lever_01;
public GameObject lever_02;
public GameObject lever_03;
private GameObject player;
[SerializeField]
int activationDistance;
//public bool isActive;
private float distanceToPlayer;
[SerializeField]
Sprite open, closed;
SpriteRenderer renderer;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
renderer = GetComponent<SpriteRenderer>();
renderer.sprite = closed;
}
// Update is called once per frame
void Update()
{
distanceToPlayer = Vector2.Distance(player.transform.position, gameObject.transform.position);
if (distanceToPlayer < activationDistance)
{
if (Input.GetKeyDown("e"))
{
door_01.transform.GetComponent<Door>().ResetPosition();
door_02.transform.GetComponent<Door>().ResetPosition();
door_03.transform.GetComponent<Door>().ResetPosition();
lever_01.transform.GetComponent<Lever>().ResetState();
lever_02.transform.GetComponent<Lever>().ResetState();
lever_03.transform.GetComponent<Lever>().ResetState();
renderer.sprite = open;
}
else
{
renderer.sprite = closed;
}
}
}
}
| 28.482143 | 102 | 0.617555 | [
"MIT"
] | allenbateman/Game-Jam-CITM-2022 | Game Jam CITM 2022/Assets/Scripts/Reset_Lever.cs | 1,595 | C# |
//
// Copyright 2013, Leanplum, Inc.
//
// 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.
namespace LeanplumSDK
{
/// <summary>
/// Leanplum constants.
/// </summary>
public class SharedConstants
{
public const string SDK_VERSION = "2.2.0";
public class Kinds
{
public const string INT = "integer";
public const string FLOAT = "float";
public const string STRING = "string";
public const string BOOLEAN = "bool";
public const string FILE = "file";
public const string DICTIONARY = "group";
public const string ARRAY = "list";
}
}
}
| 32.536585 | 68 | 0.711394 | [
"Apache-2.0"
] | kurtdekker/Leanplum-Unity-SDK | LeanplumSample/Assets/LeanplumSDK/SharedConstants.cs | 1,334 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Dfc.ProviderPortal.Lars.Functions.ImportCsv
{
public class LarsCosmosDbCollectionSettings
{
public string EndpointUri { get; set; }
public string PrimaryKey { get; set; }
public string DatabaseId { get; set; }
public CollectionSettings CollectionSettings { get; set; }
}
}
| 26.4 | 66 | 0.699495 | [
"MIT"
] | SkillsFundingAgency/dfc-providerportal-lars | src/Dfc.ProviderPortal.Lars.Functions/ImportCsv/LarsCosmosDbCollectionSettings.cs | 398 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using FluentAssertions;
using Microsoft.DotNet.BuildServer;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
using Microsoft.Extensions.EnvironmentAbstractions;
using Moq;
using NuGet.Frameworks;
using Xunit;
using LocalizableStrings = Microsoft.DotNet.BuildServer.LocalizableStrings;
namespace Microsoft.DotNet.Tests.BuildServerTests
{
public class VBCSCompilerServerTests
{
[Fact]
public void GivenAZeroExitShutdownDoesNotThrow()
{
var server = new VBCSCompilerServer(CreateCommandFactoryMock().Object);
server.Shutdown();
}
[Fact]
public void GivenANonZeroExitCodeShutdownThrows()
{
const string ErrorMessage = "failed!";
var server = new VBCSCompilerServer(CreateCommandFactoryMock(exitCode: 1, stdErr: ErrorMessage).Object);
Action a = () => server.Shutdown();
a.ShouldThrow<BuildServerException>().WithMessage(
string.Format(
LocalizableStrings.ShutdownCommandFailed,
ErrorMessage));
}
private Mock<ICommandFactory> CreateCommandFactoryMock(int exitCode = 0, string stdErr = "")
{
var commandMock = new Mock<ICommand>(MockBehavior.Strict);
commandMock.Setup(c => c.CaptureStdOut()).Returns(commandMock.Object);
commandMock.Setup(c => c.CaptureStdErr()).Returns(commandMock.Object);
commandMock.Setup(c => c.Execute()).Returns(new CommandResult(null, exitCode, "", stdErr));
var commandFactoryMock = new Mock<ICommandFactory>(MockBehavior.Strict);
commandFactoryMock
.Setup(
f => f.Create(
"exec",
new string[] { VBCSCompilerServer.VBCSCompilerPath, "-shutdown" },
It.IsAny<NuGetFramework>(),
Constants.DefaultConfiguration))
.Returns(commandMock.Object);
return commandFactoryMock;
}
}
}
| 36.140625 | 116 | 0.638565 | [
"MIT"
] | APiZFiBlockChain4/cli | test/dotnet.Tests/BuildServerTests/VBCSCompilerServerTests.cs | 2,313 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Routing.Template;
namespace Microsoft.AspNetCore.Routing
{
public static class InlineRouteParameterParser
{
public static TemplatePart ParseRouteParameter(string routeParameter)
{
if (routeParameter == null)
{
throw new ArgumentNullException(nameof(routeParameter));
}
if (routeParameter.Length == 0)
{
return TemplatePart.CreateParameter(
name: string.Empty,
isCatchAll: false,
isOptional: false,
defaultValue: null,
inlineConstraints: null);
}
var startIndex = 0;
var endIndex = routeParameter.Length - 1;
var isCatchAll = false;
var isOptional = false;
if (routeParameter[0] == '*')
{
isCatchAll = true;
startIndex++;
}
if (routeParameter[endIndex] == '?')
{
isOptional = true;
endIndex--;
}
var currentIndex = startIndex;
// Parse parameter name
var parameterName = string.Empty;
while (currentIndex <= endIndex)
{
var currentChar = routeParameter[currentIndex];
if ((currentChar == ':' || currentChar == '=') && startIndex != currentIndex)
{
// Parameter names are allowed to start with delimiters used to denote constraints or default values.
// i.e. "=foo" or ":bar" would be treated as parameter names rather than default value or constraint
// specifications.
parameterName = routeParameter.Substring(startIndex, currentIndex - startIndex);
// Roll the index back and move to the constraint parsing stage.
currentIndex--;
break;
}
else if (currentIndex == endIndex)
{
parameterName = routeParameter.Substring(startIndex, currentIndex - startIndex + 1);
}
currentIndex++;
}
var parseResults = ParseConstraints(routeParameter, currentIndex, endIndex);
currentIndex = parseResults.CurrentIndex;
string? defaultValue = null;
if (currentIndex <= endIndex &&
routeParameter[currentIndex] == '=')
{
defaultValue = routeParameter.Substring(currentIndex + 1, endIndex - currentIndex);
}
return TemplatePart.CreateParameter(parameterName,
isCatchAll,
isOptional,
defaultValue,
parseResults.Constraints);
}
private static ConstraintParseResults ParseConstraints(
string routeParameter,
int currentIndex,
int endIndex)
{
var inlineConstraints = new List<InlineConstraint>();
var state = ParseState.Start;
var startIndex = currentIndex;
do
{
var currentChar = currentIndex > endIndex ? null : (char?)routeParameter[currentIndex];
switch (state)
{
case ParseState.Start:
switch (currentChar)
{
case null:
state = ParseState.End;
break;
case ':':
state = ParseState.ParsingName;
startIndex = currentIndex + 1;
break;
case '(':
state = ParseState.InsideParenthesis;
break;
case '=':
state = ParseState.End;
currentIndex--;
break;
}
break;
case ParseState.InsideParenthesis:
switch (currentChar)
{
case null:
state = ParseState.End;
var constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex);
inlineConstraints.Add(new InlineConstraint(constraintText));
break;
case ')':
// Only consume a ')' token if
// (a) it is the last token
// (b) the next character is the start of the new constraint ':'
// (c) the next character is the start of the default value.
var nextChar = currentIndex + 1 > endIndex ? null : (char?)routeParameter[currentIndex + 1];
switch (nextChar)
{
case null:
state = ParseState.End;
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex + 1);
inlineConstraints.Add(new InlineConstraint(constraintText));
break;
case ':':
state = ParseState.Start;
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex + 1);
inlineConstraints.Add(new InlineConstraint(constraintText));
startIndex = currentIndex + 1;
break;
case '=':
state = ParseState.End;
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex + 1);
inlineConstraints.Add(new InlineConstraint(constraintText));
break;
}
break;
case ':':
case '=':
// In the original implementation, the Regex would've backtracked if it encountered an
// unbalanced opening bracket followed by (not necessarily immediatiely) a delimiter.
// Simply verifying that the parantheses will eventually be closed should suffice to
// determine if the terminator needs to be consumed as part of the current constraint
// specification.
var indexOfClosingParantheses = routeParameter.IndexOf(')', currentIndex + 1);
if (indexOfClosingParantheses == -1)
{
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex);
inlineConstraints.Add(new InlineConstraint(constraintText));
if (currentChar == ':')
{
state = ParseState.ParsingName;
startIndex = currentIndex + 1;
}
else
{
state = ParseState.End;
currentIndex--;
}
}
else
{
currentIndex = indexOfClosingParantheses;
}
break;
}
break;
case ParseState.ParsingName:
switch (currentChar)
{
case null:
state = ParseState.End;
var constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex);
inlineConstraints.Add(new InlineConstraint(constraintText));
break;
case ':':
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex);
inlineConstraints.Add(new InlineConstraint(constraintText));
startIndex = currentIndex + 1;
break;
case '(':
state = ParseState.InsideParenthesis;
break;
case '=':
state = ParseState.End;
constraintText = routeParameter.Substring(startIndex, currentIndex - startIndex);
inlineConstraints.Add(new InlineConstraint(constraintText));
currentIndex--;
break;
}
break;
}
currentIndex++;
} while (state != ParseState.End);
return new ConstraintParseResults(currentIndex, inlineConstraints);
}
private enum ParseState
{
Start,
ParsingName,
InsideParenthesis,
End
}
private readonly struct ConstraintParseResults
{
public readonly int CurrentIndex;
public readonly IEnumerable<InlineConstraint> Constraints;
public ConstraintParseResults(int currentIndex, IEnumerable<InlineConstraint> constraints)
{
CurrentIndex = currentIndex;
Constraints = constraints;
}
}
}
}
| 44.455285 | 125 | 0.42575 | [
"Apache-2.0"
] | 4samitim/aspnetcore | src/Http/Routing/src/InlineRouteParameterParser.cs | 10,936 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 1.0.9-262
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// Describes the configuration of a device connector. Configuration properties may be changed by a Intersight user or by a device administrator using the connector's API exposed through the platforms management interface
/// </summary>
[DataContract]
public partial class AssetDeviceConfiguration : IEquatable<AssetDeviceConfiguration>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="AssetDeviceConfiguration" /> class.
/// </summary>
/// <param name="Ancestors">Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. .</param>
/// <param name="Moid">A unique identifier of this Managed Object instance. .</param>
/// <param name="Owners">An array of owners which represent effective ownership of this object. .</param>
/// <param name="Parent">The direct ancestor of this managed object in the containment hierarchy. .</param>
/// <param name="Tags">An array of tags, which allow to add key, value meta-data to managed objects. .</param>
/// <param name="VersionContext">The versioning info for this managed object .</param>
/// <param name="Device">Device.</param>
/// <param name="LocalConfigurationLocked">Specifies whether configuration through the platforms local management interface has been disabled, with only configuration through the Intersight service enabled .</param>
/// <param name="LogLevel">The log level of the device connector service. .</param>
public AssetDeviceConfiguration(List<MoBaseMoRef> Ancestors = default(List<MoBaseMoRef>), string Moid = default(string), List<string> Owners = default(List<string>), MoBaseMoRef Parent = default(MoBaseMoRef), List<MoTag> Tags = default(List<MoTag>), MoVersionContext VersionContext = default(MoVersionContext), AssetDeviceRegistrationRef Device = default(AssetDeviceRegistrationRef), bool? LocalConfigurationLocked = default(bool?), string LogLevel = default(string))
{
this.Ancestors = Ancestors;
this.Moid = Moid;
this.Owners = Owners;
this.Parent = Parent;
this.Tags = Tags;
this.VersionContext = VersionContext;
this.Device = Device;
this.LocalConfigurationLocked = LocalConfigurationLocked;
this.LogLevel = LogLevel;
}
/// <summary>
/// The Account ID for this managed object.
/// </summary>
/// <value>The Account ID for this managed object. </value>
[DataMember(Name="AccountMoid", EmitDefaultValue=false)]
public string AccountMoid { get; private set; }
/// <summary>
/// Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy.
/// </summary>
/// <value>Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. </value>
[DataMember(Name="Ancestors", EmitDefaultValue=false)]
public List<MoBaseMoRef> Ancestors { get; set; }
/// <summary>
/// The time when this managed object was created.
/// </summary>
/// <value>The time when this managed object was created. </value>
[DataMember(Name="CreateTime", EmitDefaultValue=false)]
public DateTime? CreateTime { get; private set; }
/// <summary>
/// The time when this managed object was last modified.
/// </summary>
/// <value>The time when this managed object was last modified. </value>
[DataMember(Name="ModTime", EmitDefaultValue=false)]
public DateTime? ModTime { get; private set; }
/// <summary>
/// A unique identifier of this Managed Object instance.
/// </summary>
/// <value>A unique identifier of this Managed Object instance. </value>
[DataMember(Name="Moid", EmitDefaultValue=false)]
public string Moid { get; set; }
/// <summary>
/// The fully-qualified type of this managed object, e.g. the class name.
/// </summary>
/// <value>The fully-qualified type of this managed object, e.g. the class name. </value>
[DataMember(Name="ObjectType", EmitDefaultValue=false)]
public string ObjectType { get; private set; }
/// <summary>
/// An array of owners which represent effective ownership of this object.
/// </summary>
/// <value>An array of owners which represent effective ownership of this object. </value>
[DataMember(Name="Owners", EmitDefaultValue=false)]
public List<string> Owners { get; set; }
/// <summary>
/// The direct ancestor of this managed object in the containment hierarchy.
/// </summary>
/// <value>The direct ancestor of this managed object in the containment hierarchy. </value>
[DataMember(Name="Parent", EmitDefaultValue=false)]
public MoBaseMoRef Parent { get; set; }
/// <summary>
/// An array of tags, which allow to add key, value meta-data to managed objects.
/// </summary>
/// <value>An array of tags, which allow to add key, value meta-data to managed objects. </value>
[DataMember(Name="Tags", EmitDefaultValue=false)]
public List<MoTag> Tags { get; set; }
/// <summary>
/// The versioning info for this managed object
/// </summary>
/// <value>The versioning info for this managed object </value>
[DataMember(Name="VersionContext", EmitDefaultValue=false)]
public MoVersionContext VersionContext { get; set; }
/// <summary>
/// Gets or Sets Device
/// </summary>
[DataMember(Name="Device", EmitDefaultValue=false)]
public AssetDeviceRegistrationRef Device { get; set; }
/// <summary>
/// Specifies whether configuration through the platforms local management interface has been disabled, with only configuration through the Intersight service enabled
/// </summary>
/// <value>Specifies whether configuration through the platforms local management interface has been disabled, with only configuration through the Intersight service enabled </value>
[DataMember(Name="LocalConfigurationLocked", EmitDefaultValue=false)]
public bool? LocalConfigurationLocked { get; set; }
/// <summary>
/// The log level of the device connector service.
/// </summary>
/// <value>The log level of the device connector service. </value>
[DataMember(Name="LogLevel", EmitDefaultValue=false)]
public string LogLevel { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AssetDeviceConfiguration {\n");
sb.Append(" AccountMoid: ").Append(AccountMoid).Append("\n");
sb.Append(" Ancestors: ").Append(Ancestors).Append("\n");
sb.Append(" CreateTime: ").Append(CreateTime).Append("\n");
sb.Append(" ModTime: ").Append(ModTime).Append("\n");
sb.Append(" Moid: ").Append(Moid).Append("\n");
sb.Append(" ObjectType: ").Append(ObjectType).Append("\n");
sb.Append(" Owners: ").Append(Owners).Append("\n");
sb.Append(" Parent: ").Append(Parent).Append("\n");
sb.Append(" Tags: ").Append(Tags).Append("\n");
sb.Append(" VersionContext: ").Append(VersionContext).Append("\n");
sb.Append(" Device: ").Append(Device).Append("\n");
sb.Append(" LocalConfigurationLocked: ").Append(LocalConfigurationLocked).Append("\n");
sb.Append(" LogLevel: ").Append(LogLevel).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AssetDeviceConfiguration);
}
/// <summary>
/// Returns true if AssetDeviceConfiguration instances are equal
/// </summary>
/// <param name="other">Instance of AssetDeviceConfiguration to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AssetDeviceConfiguration other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AccountMoid == other.AccountMoid ||
this.AccountMoid != null &&
this.AccountMoid.Equals(other.AccountMoid)
) &&
(
this.Ancestors == other.Ancestors ||
this.Ancestors != null &&
this.Ancestors.SequenceEqual(other.Ancestors)
) &&
(
this.CreateTime == other.CreateTime ||
this.CreateTime != null &&
this.CreateTime.Equals(other.CreateTime)
) &&
(
this.ModTime == other.ModTime ||
this.ModTime != null &&
this.ModTime.Equals(other.ModTime)
) &&
(
this.Moid == other.Moid ||
this.Moid != null &&
this.Moid.Equals(other.Moid)
) &&
(
this.ObjectType == other.ObjectType ||
this.ObjectType != null &&
this.ObjectType.Equals(other.ObjectType)
) &&
(
this.Owners == other.Owners ||
this.Owners != null &&
this.Owners.SequenceEqual(other.Owners)
) &&
(
this.Parent == other.Parent ||
this.Parent != null &&
this.Parent.Equals(other.Parent)
) &&
(
this.Tags == other.Tags ||
this.Tags != null &&
this.Tags.SequenceEqual(other.Tags)
) &&
(
this.VersionContext == other.VersionContext ||
this.VersionContext != null &&
this.VersionContext.Equals(other.VersionContext)
) &&
(
this.Device == other.Device ||
this.Device != null &&
this.Device.Equals(other.Device)
) &&
(
this.LocalConfigurationLocked == other.LocalConfigurationLocked ||
this.LocalConfigurationLocked != null &&
this.LocalConfigurationLocked.Equals(other.LocalConfigurationLocked)
) &&
(
this.LogLevel == other.LogLevel ||
this.LogLevel != null &&
this.LogLevel.Equals(other.LogLevel)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AccountMoid != null)
hash = hash * 59 + this.AccountMoid.GetHashCode();
if (this.Ancestors != null)
hash = hash * 59 + this.Ancestors.GetHashCode();
if (this.CreateTime != null)
hash = hash * 59 + this.CreateTime.GetHashCode();
if (this.ModTime != null)
hash = hash * 59 + this.ModTime.GetHashCode();
if (this.Moid != null)
hash = hash * 59 + this.Moid.GetHashCode();
if (this.ObjectType != null)
hash = hash * 59 + this.ObjectType.GetHashCode();
if (this.Owners != null)
hash = hash * 59 + this.Owners.GetHashCode();
if (this.Parent != null)
hash = hash * 59 + this.Parent.GetHashCode();
if (this.Tags != null)
hash = hash * 59 + this.Tags.GetHashCode();
if (this.VersionContext != null)
hash = hash * 59 + this.VersionContext.GetHashCode();
if (this.Device != null)
hash = hash * 59 + this.Device.GetHashCode();
if (this.LocalConfigurationLocked != null)
hash = hash * 59 + this.LocalConfigurationLocked.GetHashCode();
if (this.LogLevel != null)
hash = hash * 59 + this.LogLevel.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 45.926154 | 475 | 0.568069 | [
"Apache-2.0"
] | ategaw-cisco/intersight-powershell | csharp/swaggerClient/src/intersight/Model/AssetDeviceConfiguration.cs | 14,926 | C# |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace ICSharpCode.ILSpy.Controls
{
/// <summary>
/// Allows to automatically sort a grid view.
/// </summary>
public class SortableGridViewColumn : GridViewColumn
{
// This class was copied from ICSharpCode.Core.Presentation.
static readonly ComponentResourceKey headerTemplateKey = new ComponentResourceKey(typeof(SortableGridViewColumn), "ColumnHeaderTemplate");
public SortableGridViewColumn()
{
this.SetValueToExtension(HeaderTemplateProperty, new DynamicResourceExtension(headerTemplateKey));
}
string sortBy;
public string SortBy {
get { return sortBy; }
set {
if (sortBy != value) {
sortBy = value;
OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("SortBy"));
}
}
}
#region SortDirection property
public static readonly DependencyProperty SortDirectionProperty =
DependencyProperty.RegisterAttached("SortDirection", typeof(ColumnSortDirection), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(ColumnSortDirection.None, OnSortDirectionChanged));
public ColumnSortDirection SortDirection {
get { return (ColumnSortDirection)GetValue(SortDirectionProperty); }
set { SetValue(SortDirectionProperty, value); }
}
public static ColumnSortDirection GetSortDirection(ListView listView)
{
return (ColumnSortDirection)listView.GetValue(SortDirectionProperty);
}
public static void SetSortDirection(ListView listView, ColumnSortDirection value)
{
listView.SetValue(SortDirectionProperty, value);
}
static void OnSortDirectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null) {
SortableGridViewColumn col = GetCurrentSortColumn(grid);
if (col != null)
col.SortDirection = (ColumnSortDirection)args.NewValue;
Sort(grid);
}
}
#endregion
#region CurrentSortColumn property
public static readonly DependencyProperty CurrentSortColumnProperty =
DependencyProperty.RegisterAttached("CurrentSortColumn", typeof(SortableGridViewColumn), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(OnCurrentSortColumnChanged));
public static SortableGridViewColumn GetCurrentSortColumn(ListView listView)
{
return (SortableGridViewColumn)listView.GetValue(CurrentSortColumnProperty);
}
public static void SetCurrentSortColumn(ListView listView, SortableGridViewColumn value)
{
listView.SetValue(CurrentSortColumnProperty, value);
}
static void OnCurrentSortColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null) {
SortableGridViewColumn oldColumn = (SortableGridViewColumn)args.OldValue;
if (oldColumn != null)
oldColumn.SortDirection = ColumnSortDirection.None;
SortableGridViewColumn newColumn = (SortableGridViewColumn)args.NewValue;
if (newColumn != null) {
newColumn.SortDirection = GetSortDirection(grid);
}
Sort(grid);
}
}
#endregion
#region SortMode property
public static readonly DependencyProperty SortModeProperty =
DependencyProperty.RegisterAttached("SortMode", typeof(ListViewSortMode), typeof(SortableGridViewColumn),
new FrameworkPropertyMetadata(ListViewSortMode.None, OnSortModeChanged));
public static ListViewSortMode GetSortMode(ListView listView)
{
return (ListViewSortMode)listView.GetValue(SortModeProperty);
}
public static void SetSortMode(ListView listView, ListViewSortMode value)
{
listView.SetValue(SortModeProperty, value);
}
static void OnSortModeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
ListView grid = sender as ListView;
if (grid != null) {
if ((ListViewSortMode)args.NewValue != ListViewSortMode.None)
grid.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickHandler));
else
grid.RemoveHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickHandler));
}
}
static void GridViewColumnHeaderClickHandler(object sender, RoutedEventArgs e)
{
ListView grid = sender as ListView;
GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
if (grid != null && headerClicked != null && headerClicked.Role != GridViewColumnHeaderRole.Padding) {
if (headerClicked.Column == GetCurrentSortColumn(grid)) {
if (GetSortDirection(grid) == ColumnSortDirection.Ascending)
SetSortDirection(grid, ColumnSortDirection.Descending);
else
SetSortDirection(grid, ColumnSortDirection.Ascending);
} else {
SetSortDirection(grid, ColumnSortDirection.Ascending);
SetCurrentSortColumn(grid, headerClicked.Column as SortableGridViewColumn);
}
}
}
#endregion
static void Sort(ListView grid)
{
ColumnSortDirection currentDirection = GetSortDirection(grid);
SortableGridViewColumn column = GetCurrentSortColumn(grid);
if (column != null && GetSortMode(grid) == ListViewSortMode.Automatic && currentDirection != ColumnSortDirection.None) {
ICollectionView dataView = CollectionViewSource.GetDefaultView(grid.ItemsSource);
string sortBy = column.SortBy;
if (sortBy == null) {
Binding binding = column.DisplayMemberBinding as Binding;
if (binding != null && binding.Path != null) {
sortBy = binding.Path.Path;
}
}
dataView.SortDescriptions.Clear();
if (sortBy != null) {
ListSortDirection direction;
if (currentDirection == ColumnSortDirection.Descending)
direction = ListSortDirection.Descending;
else
direction = ListSortDirection.Ascending;
dataView.SortDescriptions.Add(new SortDescription(sortBy, direction));
}
dataView.Refresh();
}
}
}
public enum ColumnSortDirection
{
None,
Ascending,
Descending
}
public enum ListViewSortMode
{
/// <summary>
/// Disable automatic sorting when sortable columns are clicked.
/// </summary>
None,
/// <summary>
/// Fully automatic sorting.
/// </summary>
Automatic,
/// <summary>
/// Automatically update SortDirection and CurrentSortColumn properties,
/// but do not actually sort the data.
/// </summary>
HalfAutomatic
}
sealed class ColumnSortDirectionToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Equals(value, parameter) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| 36.030973 | 140 | 0.746285 | [
"MIT"
] | arturek/ILSpy | ILSpy/Controls/SortableGridViewColumn.cs | 8,145 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Net;
using System.Net.Mime;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Microsoft.Web.Mvc.Properties;
namespace Microsoft.Web.Mvc.Resources
{
/// <summary>
/// An ActionResult that can render a SyndicationFeed to the Atom 1.0 feed format
/// </summary>
public class AtomFeedActionResult : ActionResult
{
private ContentType contentType;
private SyndicationFeed feed;
/// <summary>
/// The content type defaults to application/atom+xml
/// </summary>
/// <param name="feed"></param>
public AtomFeedActionResult(SyndicationFeed feed)
: this(feed, new ContentType("application/atom+xml")) { }
public AtomFeedActionResult(SyndicationFeed feed, ContentType contentType)
{
if (feed == null)
{
throw new ArgumentNullException("feed");
}
if (contentType == null)
{
throw new ArgumentNullException("contentType");
}
this.feed = feed;
this.contentType = contentType;
}
public ContentType ContentType
{
get { return this.contentType; }
}
public SyndicationFeed Feed
{
get { return this.feed; }
}
public override void ExecuteResult(ControllerContext context)
{
Encoding encoding = Encoding.UTF8;
if (!String.IsNullOrEmpty(this.ContentType.CharSet))
{
try
{
encoding = Encoding.GetEncoding(this.ContentType.CharSet);
}
catch (ArgumentException)
{
throw new HttpException(
(int)HttpStatusCode.NotAcceptable,
String.Format(
CultureInfo.CurrentCulture,
MvcResources.Resources_UnsupportedFormat,
this.ContentType
)
);
}
}
XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };
this.ContentType.CharSet = settings.Encoding.HeaderName;
context.HttpContext.Response.ContentType = this.ContentType.ToString();
using (
XmlWriter writer = XmlWriter.Create(
context.HttpContext.Response.OutputStream,
settings
)
)
{
this.Feed.GetAtom10Formatter().WriteTo(writer);
writer.Flush();
}
}
}
}
| 32.053763 | 111 | 0.546125 | [
"Apache-2.0"
] | belav/AspNetWebStack | src/Microsoft.Web.Mvc/Resources/AtomFeedActionResult.cs | 2,983 | C# |
// ***********************************************************************
// Assembly : XLabs.Sample
// Author : XLabs Team
// Created : 12-27-2015
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="ExtendedPickerPage.xaml.cs" company="XLabs Team">
// Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
// This project is licensed under the Apache 2.0 license
// https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
// XLabs is a open source project that aims to provide a powerfull and cross
// platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//
using System.Collections.ObjectModel;
using System.Windows.Input;
using Xamarin.Forms;
using XLabs.Forms.Controls;
namespace XLabs.Sample.Pages.Controls
{
public partial class ExtendedPickerPage : ContentPage
{
public class DataClass
{
public string FirstName{get;set;}
public string LastName{get;set;}
}
public ExtendedPickerPage ()
{
InitializeComponent ();
BindingContext = this;
myPicker = new ExtendedPicker (){DisplayProperty = "FirstName"};
myPicker.SetBinding(ExtendedPicker.ItemsSourceProperty,new Binding("MyDataList",BindingMode.TwoWay));
myPicker.SetBinding(ExtendedPicker.SelectedItemProperty,new Binding("TheChosenOne",BindingMode.TwoWay));
myStackLayout.Children.Add (new Label{ Text = "Code Created:" });
myStackLayout.Children.Add (myPicker);
TheChosenOne = new DataClass(){ FirstName = "Jet", LastName = "Li" };
MyDataList = new ObservableCollection<object> () {
new DataClass(){FirstName="Jack",LastName="Doe"},
TheChosenOne,
new DataClass(){FirstName="Matt",LastName="Bar"},
new DataClass(){FirstName="Mic",LastName="Jaggery"},
new DataClass(){FirstName="Michael",LastName="Jackon"}
};
}
public ICommand DoIt{ get; set; }
private object chosenOne;
public object TheChosenOne{
get{
return chosenOne;
}
set{
chosenOne = value;
OnPropertyChanged ("TheChosenOne");
}
}
ObservableCollection<object> dataList;
public ObservableCollection<object> MyDataList {
get{ return dataList; }
set{
dataList = value;
OnPropertyChanged ("MyDataList");
}
}
}
}
| 29.795181 | 107 | 0.626769 | [
"Apache-2.0"
] | jdluzen/Xamarin-Forms-Labs | Samples/XLabs.Sample/Pages/Controls/ExtendedPickerPage.xaml.cs | 2,475 | C# |
using System;
namespace SecurityDriven.Inferno.Extensions
{
/// <remarks>Not a constant-time implementation (memory lookups).</remarks>
public class Base32Config
{
const int BASE = 32;
internal char[] Base32table;
internal long[] ReverseMap;
int? hashcode;
public Base32Config(char[] alphabet = null)
{
if (alphabet == null)
{
this.Base32table = Default.Base32table;
this.ReverseMap = Default.ReverseMap;
return;
}
if (alphabet.Length != BASE)
throw new ArgumentOutOfRangeException(nameof(alphabet), $"'{nameof(alphabet)}' array must have exactly {BASE.ToString()} characters.");
this.Base32table = alphabet;
char ch;
this.ReverseMap = new long[byte.MaxValue];
for (int i = 0; i < Base32table.Length; ++i)
{
ch = Base32table[i];
this.ReverseMap[char.ToUpperInvariant(ch)] = i;
this.ReverseMap[char.ToLowerInvariant(ch)] = i;
}
}//ctor
public override int GetHashCode()
{
if (this.hashcode == null)
this.hashcode = new string(this.Base32table).GetHashCode();
return this.hashcode.GetValueOrDefault();
}
public override bool Equals(object obj)
{
var rhs = obj as Base32Config;
if (rhs == null)
return false;
if (this.GetHashCode() != rhs.GetHashCode())
return false;
for (int i = 0; i < BASE; ++i)
{
if (this.Base32table[i] != rhs.Base32table[i])
return false;
}
return true;
}
public static readonly Base32Config Default = new Base32Config("123456789ABCDEFGHJKMNPQRSTUVWXYZ".ToCharArray());
public static readonly Base32Config Rfc = new Base32Config("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".ToCharArray());
}//class Base32Config
}//ns | 25.830769 | 139 | 0.68374 | [
"MIT"
] | voronytskyi/SecurityDriven.Inferno | Extensions/Base32Config.cs | 1,681 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CCC.Model.V20170705
{
public class ListUnreachableContactsResponse : AcsResponse
{
private string requestId;
private bool? success;
private string code;
private string message;
private int? httpStatusCode;
private ListUnreachableContacts_UnreachableContacts unreachableContacts;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public int? HttpStatusCode
{
get
{
return httpStatusCode;
}
set
{
httpStatusCode = value;
}
}
public ListUnreachableContacts_UnreachableContacts UnreachableContacts
{
get
{
return unreachableContacts;
}
set
{
unreachableContacts = value;
}
}
public class ListUnreachableContacts_UnreachableContacts
{
private int? totalCount;
private int? pageNumber;
private int? pageSize;
private List<ListUnreachableContacts_UnreachableContact> list;
public int? TotalCount
{
get
{
return totalCount;
}
set
{
totalCount = value;
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
}
}
public List<ListUnreachableContacts_UnreachableContact> List
{
get
{
return list;
}
set
{
list = value;
}
}
public class ListUnreachableContacts_UnreachableContact
{
private int? totalAttempts;
private List<ListUnreachableContacts_Contact> contacts;
public int? TotalAttempts
{
get
{
return totalAttempts;
}
set
{
totalAttempts = value;
}
}
public List<ListUnreachableContacts_Contact> Contacts
{
get
{
return contacts;
}
set
{
contacts = value;
}
}
public class ListUnreachableContacts_Contact
{
private string contactId;
private string contactName;
private string role;
private string phoneNumber;
private string state;
private string referenceId;
public string ContactId
{
get
{
return contactId;
}
set
{
contactId = value;
}
}
public string ContactName
{
get
{
return contactName;
}
set
{
contactName = value;
}
}
public string Role
{
get
{
return role;
}
set
{
role = value;
}
}
public string PhoneNumber
{
get
{
return phoneNumber;
}
set
{
phoneNumber = value;
}
}
public string State
{
get
{
return state;
}
set
{
state = value;
}
}
public string ReferenceId
{
get
{
return referenceId;
}
set
{
referenceId = value;
}
}
}
}
}
}
}
| 15.549488 | 75 | 0.544557 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Model/V20170705/ListUnreachableContactsResponse.cs | 4,556 | C# |
namespace WinFormsIoc.Services
{
public class EmailsService : IEmailsService
{
public void SendEmail(string from, string to, string title, string message)
{
//todo: ...
}
}
} | 22.3 | 83 | 0.587444 | [
"Apache-2.0"
] | VahidN/Dependency-Injection-Samples | DI11_WinFormsIoc/WinFormsIoc.Services/EmailsService.cs | 225 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Infrastructure.Design
{
using System.Configuration;
using System.IO;
using Xunit;
public class AppConfigReaderTests
{
[Fact]
public void Ctor_validates_parameter()
{
var ex = Assert.Throws<ArgumentNullException>(() => new AppConfigReader(null));
Assert.Equal("configuration", ex.ParamName);
}
[Fact]
public void GetProviderServices_returns_provider_when_exists()
{
var reader = new AppConfigReader(
CreateConfig("<provider invariantName='My.Invariant1' type='MyProvider1'/>"));
var provider = reader.GetProviderServices("My.Invariant1");
Assert.Equal("MyProvider1", provider);
}
[Fact]
public void GetProviderServices_returns_null_when_not_exists()
{
var reader = new AppConfigReader(
CreateConfig("<provider invariantName='My.Invariant1' type='MyProvider1'/>"));
var provider = reader.GetProviderServices("My.Invariant2");
Assert.Null(provider);
}
private static Configuration CreateConfig(string providers)
{
var file = Path.GetTempFileName();
File.WriteAllText(
file,
@"<?xml version='1.0' encoding='utf-8'?>
<configuration>
<configSections>
<section name='entityFramework' type='System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework' />
</configSections>
<entityFramework>
<providers>
" + providers + @"
</providers>
</entityFramework>
</configuration>");
return ConfigurationManager.OpenMappedExeConfiguration(
new ExeConfigurationFileMap { ExeConfigFilename = file },
ConfigurationUserLevel.None);
}
}
}
| 33.765625 | 140 | 0.584452 | [
"Apache-2.0"
] | Cireson/EntityFramework6 | test/EntityFramework/UnitTests/Infrastructure/Design/AppConfigReaderTests.cs | 2,163 | C# |
// Copyright (c) Approxoft. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using SvgBlazor.Docs.Interfaces;
namespace SvgBlazor.Docs.Examples
{
public class FillRuleNonZeroExample : IExampleCode
{
public void Example(SvgComponent svg)
{
/* #example-code-start */
var shape1 = new SvgPath
{
Path = "M 20 180 H 180 L 100 20 Z M 80 148 H 120 L 100 108 Z",
Fill = new SvgFill { Rule = FillRule.NonZero },
Stroke = new SvgStroke { Color = "grey" },
};
var shape2 = new SvgPath
{
Path = "M 220 180 H 380 L 300 20 z M 320 147 H 280 L 300 108 Z",
Fill = new SvgFill { Rule = FillRule.NonZero },
Stroke = new SvgStroke { Color = "grey" },
};
/* #example-code-end */
svg.Add(shape1);
svg.Add(shape2);
}
}
} | 31.84375 | 91 | 0.526006 | [
"MIT"
] | Approxoft/SvgBlazor | src/SvgBlazor.Docs/Pages/Attributes/Fill/Examples/FillRuleNonZeroExample.cs | 1,021 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Habrador_Computational_Geometry;
public class CutMeshWithPlaneController : MonoBehaviour
{
public Transform cutPlaneTrans;
//Place all new meshes below this go, so we can cut them again
public Transform meshesToCutParentTrans;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CutMesh();
}
}
private void CutMesh()
{
List<Transform> transformsToCut = GetChildTransformsWithMeshAttached(meshesToCutParentTrans);
//Plane3 cutPlane = new Plane3(cutPlaneTrans.position.ToMyVector3(), cutPlaneTrans.up.ToMyVector3());
OrientedPlane3 cutPlane = new OrientedPlane3(cutPlaneTrans);
foreach (Transform childTransToCut in transformsToCut)
{
//Only cut active gameobjects
if (!childTransToCut.gameObject.activeInHierarchy)
{
continue;
}
//Cut the mesh
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
//Should return null (if we couldn't cut the mesh because the mesh didn't intersect with the plane)
List<Mesh> cutMeshes = CutMeshWithPlane.CutMesh(childTransToCut, cutPlane);
timer.Stop();
Debug.Log($"It took {timer.ElapsedMilliseconds / 1000f} seconds to cut the mesh");
if (cutMeshes == null)
{
Debug.Log("This mesh couldn't be cut");
continue;
}
Debug.Log($"Number of new meshes after cut: {cutMeshes.Count}");
//Make sure the new object has the correct transform because it might have been a child to other gameobjects when we found it
//and these old parent objects might have had some scale, etc
//This might change in the future but then we would have to locate the correct parent-child, which might be messy?
Transform oldChildParent = childTransToCut.parent;
//The transform will now be in global space
childTransToCut.parent = null;
//Create new game objects with the new meshes
foreach (Mesh newMesh in cutMeshes)
{
GameObject newObj = Instantiate(childTransToCut.gameObject);
newObj.transform.parent = meshesToCutParentTrans;
newObj.GetComponent<MeshFilter>().mesh = newMesh;
}
//Hide the original one
childTransToCut.gameObject.SetActive(false);
//And make sure the original one has the previous parent
childTransToCut.parent = oldChildParent;
}
}
public List<Transform> GetChildTransformsWithMeshAttached(Transform parentTrans)
{
if (parentTrans == null)
{
Debug.Log("No parent so cant get children");
return null;
}
//Is not including the parent
int children = parentTrans.childCount;
List<Transform> childrenTransforms = new List<Transform>();
for (int i = 0; i < children; i++)
{
Transform thisChild = parentTrans.GetChild(i);
//Make sure we add the transform to which a mesh filter is attached
if (thisChild.GetComponent<MeshFilter>() == null)
{
//We can't use this directly because we might in the future need the parent to a child with a mesh because it might have some important scripts attached to it
//And the parent is always thisChild
MeshFilter[] meshFiltersInChildren = thisChild.GetComponentsInChildren<MeshFilter>(includeInactive: false);
if (meshFiltersInChildren.Length == 0)
{
Debug.Log("This child has no mesh attached to it");
continue;
}
foreach (MeshFilter mf in meshFiltersInChildren)
{
childrenTransforms.Add(mf.transform);
}
}
else
{
childrenTransforms.Add(thisChild);
}
}
return childrenTransforms;
}
}
| 29.972414 | 174 | 0.59434 | [
"MIT"
] | Habrador/Computational-geometry | Assets/Test scenes/8. Deform mesh/Cut mesh with plane/CutMeshWithPlaneController.cs | 4,346 | C# |
using System;
namespace Katsudon.Builder.Variables
{
[PrimitiveConverter]
public class BoolConstConverter : IPrimitiveConverter
{
public int order => 80;
public IVariable TryConvert(IUdonProgramBlock block, in IVariable variable, TypeCode fromPrimitive, TypeCode toPrimitive, Type toType)
{
if(toType != typeof(bool) || !(variable is IConstVariable constVariable))
{
return null;
}
if(fromPrimitive == TypeCode.Object)
{
return block.machine.GetConstVariable(constVariable.value != null);
}
if(fromPrimitive == TypeCode.Char)
{
return block.machine.GetConstVariable(Convert.ToChar(constVariable.value) != '\0');
}
return block.machine.GetConstVariable(Convert.ToBoolean(constVariable.value));
}
public static void Register(PrimitiveConvertersList container, IModulesContainer modules)
{
container.AddConverter(new BoolConstConverter());
}
}
} | 28.40625 | 136 | 0.742574 | [
"Apache-2.0"
] | Xytabich/Katsudon | Assets/Katsudon/Builder/Numeric/BoolConstConverter.cs | 911 | C# |
using System.Collections.Generic;
namespace SixtenLabs.Spawn.Vulkan.Spec
{
public class VkFeatureRequire
{
public string Comment { get; set; }
public IList<VkFeatureRequireType> Types { get; set; }
public IList<VkFeatureRequireEnum> Enums { get; set; }
public IList<VkFeatureRequireCommand> Commands { get; set; }
}
}
| 20.875 | 62 | 0.739521 | [
"Unlicense"
] | SixtenLabs/SpawnOfVulkan | src/SixtenLabs.Spawn.Vulkan/Spec/VkFeatureRequire.cs | 336 | C# |
namespace TransactionProject.EndToEnd.Tests.Infrastructure
{
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using Shouldly;
/// <summary>
/// Shouldly assertions, but hooked into Selenium's WebDriverWait mechanism
/// </summary>
public class WaitAndAssert
{
public static IWebDriver WebDriver;
private static readonly TimeSpan s_DefaultTimeout = TimeSpan.FromSeconds(10);
//public static void Collection<T>(Func<IEnumerable<T>> actualValues, params Action<T>[] elementInspectors)
// => WaitAssertCore(() => Assert.Collection(actualValues(), elementInspectors));
public static void False(Func<bool> aActual)
=> WaitAssertCore(() => aActual().ShouldBeFalse());
public static void Single<T>(Func<IEnumerable<T>> aActualValues)
=> WaitAssertCore(() => aActualValues().ShouldHaveSingleItem());
public static void True(Func<bool> aActual)
=> WaitAssertCore(() => aActual().ShouldBeTrue());
public static void WaitAndAssertContains(string aExpectedSubstring, Func<string> aActualString)
=> WaitAssertCore(() => aActualString().ShouldContain(aExpectedSubstring));
public static void WaitAndAssertEmpty<T>(Func<IEnumerable<T>> aActualValues)
=> WaitAssertCore(() => aActualValues().ShouldBeEmpty());
public static void WaitAndAssertEqual<T>(T aExpected, Func<T> aActual)
=> WaitAssertCore(() => aActual().ShouldBe(aExpected));
public static void WaitAndAssertNotEmpty<T>(Func<IEnumerable<T>> aActualValues)
=> WaitAssertCore(() => aActualValues().ShouldNotBeEmpty());
private static void WaitAssertCore(Action aAssertion, TimeSpan aTimeout = default)
{
if (aTimeout == default)
{
aTimeout = s_DefaultTimeout;
}
try
{
new WebDriverWait(WebDriver, aTimeout).Until(aWebDriver =>
{
try
{
aAssertion();
return true;
}
catch
{
return false;
}
});
}
catch (WebDriverTimeoutException)
{
// Instead of reporting it as a timeout, report the exception
aAssertion();
}
}
}
} | 32.271429 | 111 | 0.651616 | [
"Unlicense"
] | stefanbemelmans/HercHomeTransactionModule | Tests/EndToEnd.Selenium.Tests/Infrastructure/WaitAndAssert.cs | 2,259 | C# |
// StorePartialConsumableOperation
using ClubPenguin.Net.Client;
using ClubPenguin.Net.Client.Mappers;
using ClubPenguin.Net.Domain;
using ClubPenguin.Net.Offline;
using hg.ApiWebKit.core.attributes;
using hg.ApiWebKit.mappers;
[HttpPOST]
[HttpAccept("application/json")]
[HttpContentType("application/json")]
[HttpBasicAuthorization("cp-api-username", "cp-api-password")]
[HttpPath("cp-api-base-uri", "/consumable/v1/partial")]
public class StorePartialConsumableOperation : CPAPIHttpOperation
{
[HttpRequestJsonBody]
public SignedResponse<UsedConsumable> Partial;
[HttpResponseJsonBody]
public SignedResponse<ClubPenguin.Net.Domain.ConsumableInventory> SignedConsumableInventory;
public StorePartialConsumableOperation(SignedResponse<UsedConsumable> partial)
{
Partial = partial;
}
protected override void PerformOfflineAction(OfflineDatabase offlineDatabase, IOfflineDefinitionLoader offlineDefinitions)
{
ClubPenguin.Net.Offline.ConsumableInventory value = offlineDatabase.Read<ClubPenguin.Net.Offline.ConsumableInventory>();
if (!value.Inventory.ContainsKey(Partial.Data.type))
{
value.Inventory[Partial.Data.type] = new InventoryItemStock();
}
value.Inventory[Partial.Data.type].partialCount = Partial.Data.partialCount;
offlineDatabase.Write(value);
SignedConsumableInventory = new SignedResponse<ClubPenguin.Net.Domain.ConsumableInventory>
{
Data = new ClubPenguin.Net.Domain.ConsumableInventory
{
inventoryMap = value.Inventory
}
};
}
protected override void SetOfflineData(OfflineDatabase offlineDatabase, IOfflineDefinitionLoader offlineDefinitions)
{
ClubPenguin.Net.Offline.ConsumableInventory value = offlineDatabase.Read<ClubPenguin.Net.Offline.ConsumableInventory>();
value.Inventory = SignedConsumableInventory.Data.inventoryMap;
offlineDatabase.Write(value);
}
}
| 35.403846 | 123 | 0.811515 | [
"MIT"
] | smdx24/CPI-Source-Code | ClubPenguin.Net.Client/StorePartialConsumableOperation.cs | 1,841 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public GameObject gameOverScreen;
private void Start()
{
gameOverScreen.SetActive(false);
PlayerController.OnPlayerBeatLevel += NextScene;
Guard.OnGuardHasSpottedPlayer += GameOver;
}
private void OnDestroy()
{
PlayerController.OnPlayerBeatLevel -= NextScene;
Guard.OnGuardHasSpottedPlayer -= GameOver;
}
public void NextScene()
{
Debug.Log("Load next scene");
if (SceneManager.GetActiveScene().buildIndex+1 < SceneManager.sceneCountInBuildSettings)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
else
{
SceneManager.LoadScene(0);
}
}
public void RestartScene()
{
Debug.Log("Restart Scene");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void Quit()
{
Application.Quit();
}
public void GameOver()
{
gameOverScreen.SetActive(true);
}
}
| 24.183673 | 96 | 0.637975 | [
"MIT"
] | Christakou/Guarded | Assets/Scripts/SceneLoader.cs | 1,187 | C# |
namespace CommonUtility.Security
{
public enum CryptoServiceProviderType
{
MD5,
SHA1,
SHA256,
SHA384,
SHA512,
HMACMD5,
HMACSHA1,
HMACSHA256,
HMACSHA384,
HMACSHA512
}
} | 15.352941 | 41 | 0.517241 | [
"MIT"
] | 3gbywork/CommonUtility | CommonUtility/Security/CryptoServiceProviderType.cs | 263 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BulkCalculationState")]
[assembly: AssemblyDescription("Bulk State Updater for Dynamic Calculations")]
[assembly: AssemblyCompany("Grid Protection Alliance")]
[assembly: AssemblyProduct("Grid Solutions Framework")]
[assembly: AssemblyCopyright("Copyright © GPA, 2021. All Rights Reserved.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug Build")]
#else
[assembly: AssemblyConfiguration("Release Build")]
#endif
// 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("a4228442-039f-4dc0-8e9c-410a09f12c91")]
// 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("2.3.504.0")]
[assembly: AssemblyVersion("2.3.504.0")]
[assembly: AssemblyFileVersion("2.3.504.0")]
| 38.333333 | 84 | 0.757191 | [
"MIT"
] | SRM256/gsf | Source/Tools/BulkCalculationState/Properties/AssemblyInfo.cs | 1,498 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace ePlatform.Api.Core.QueryBuilder
{
// İtemleri filtrelemek için üretilmesi gereken class
/// <summary>
/// Adds generic Model for search.
/// </summary>
public class QueryFilterBuilder<T> where T : new()
{
public List<QueryFilter> Filters { get; private set; } = new List<QueryFilter>();
PagingModel model = new PagingModel() { PageIndex = 1, PageSize = 50 };
/// <summary>
/// Adds three parameters and returns the result.
/// </summary>
/// <returns>
/// The result of QueryFilterBuilder to Build()
/// </returns>
/// <example>
/// <code>
/// var queryFilter = new QueryFilterBuilder<OutboxInvoiceGetModel>()
/// .QueryFor(q => q.ExecutionDate, Operator.LessThan, new DateTime())
/// .QueryFor(q => q.InvoiceNumber, Operator.Equal, "EPK2019000001731")
/// .QueryFor(q => q.Status, Operator.Equal, InvoiceStatus.Error)
/// .Buil();
/// </code>
/// </example>
public QueryFilterBuilder<T> QueryFor<TProperty>(Expression<Func<T, TProperty>> expression, Operator @operator, object value)
{
MemberExpression memeberExpression = expression.Body as MemberExpression;
object convertedObj = value;
if (typeof(TProperty) == typeof(DateTime))
{
if (value.GetType() == typeof(DateTime) ||
value.GetType() == typeof(Nullable<DateTime>))
{
convertedObj = Convert.ToDateTime(value).ToString("dd.MM.yyyy");
}
else
throw new Exception(memeberExpression.Member.Name + " value should be DateTime class");
}
Filters.Add(new QueryFilter(memeberExpression.Member.Name, @operator, convertedObj));
return this;
}
public QueryFilterBuilder<T> PageIndex(int index = 1)
{
if (index == 0)
throw new Exception("PageIndex can not be zero");
this.model.PageIndex = index;
return this;
}
public QueryFilterBuilder<T> PageSize(int size = 50)
{
if (size == 0)
throw new Exception("PageSize can not be zero");
this.model.PageSize = size;
return this;
}
public QueryFilterBuilder<T> IsDesc(bool isDesc)
{
this.model.IsDesc = isDesc;
return this;
}
public PagingModel Build()
{
model.QueryFilter = JsonConvert.SerializeObject(Filters);
return model;
}
}
}
| 34.691358 | 133 | 0.565836 | [
"MIT"
] | Quaqmre/eplatform-api-dotnet-client | src/ePlatform.Api.Core/QueryBuilder/QueryFilterBuilder.cs | 2,815 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AdaptiveHR.Model
{
public class EmailModel
{
public string Email { get; set; }
public string From { get; set; }
public string Recipients { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
| 22.647059 | 46 | 0.636364 | [
"MIT"
] | AllenFreecs/AdaptiveHR | AdaptiveHR/Model/EmailModel.cs | 387 | C# |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class Gift : Resource
{
public Gift() { }
public Gift(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public Gift(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public Gift(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static CreateRequest Create()
{
string url = ApiUtil.BuildUrl("gifts");
return new CreateRequest(url, HttpMethod.POST);
}
public static CreateForItemsRequest CreateForItems()
{
string url = ApiUtil.BuildUrl("gifts", "create_for_items");
return new CreateForItemsRequest(url, HttpMethod.POST);
}
public static EntityRequest<Type> Retrieve(string id)
{
string url = ApiUtil.BuildUrl("gifts", CheckNull(id));
return new EntityRequest<Type>(url, HttpMethod.GET);
}
public static GiftListRequest List()
{
string url = ApiUtil.BuildUrl("gifts");
return new GiftListRequest(url);
}
public static EntityRequest<Type> Claim(string id)
{
string url = ApiUtil.BuildUrl("gifts", CheckNull(id), "claim");
return new EntityRequest<Type>(url, HttpMethod.POST);
}
public static EntityRequest<Type> Cancel(string id)
{
string url = ApiUtil.BuildUrl("gifts", CheckNull(id), "cancel");
return new EntityRequest<Type>(url, HttpMethod.POST);
}
public static UpdateGiftRequest UpdateGift(string id)
{
string url = ApiUtil.BuildUrl("gifts", CheckNull(id), "update_gift");
return new UpdateGiftRequest(url, HttpMethod.POST);
}
#endregion
#region Properties
public string Id
{
get { return GetValue<string>("id", true); }
}
public StatusEnum Status
{
get { return GetEnum<StatusEnum>("status", true); }
}
public DateTime? ScheduledAt
{
get { return GetDateTime("scheduled_at", false); }
}
public bool AutoClaim
{
get { return GetValue<bool>("auto_claim", true); }
}
public bool NoExpiry
{
get { return GetValue<bool>("no_expiry", true); }
}
public DateTime? ClaimExpiryDate
{
get { return GetDateTime("claim_expiry_date", false); }
}
public long? ResourceVersion
{
get { return GetValue<long?>("resource_version", false); }
}
public DateTime? UpdatedAt
{
get { return GetDateTime("updated_at", false); }
}
public GiftGifter Gifter
{
get { return GetSubResource<GiftGifter>("gifter"); }
}
public GiftGiftReceiver GiftReceiver
{
get { return GetSubResource<GiftGiftReceiver>("gift_receiver"); }
}
public List<GiftGiftTimeline> GiftTimelines
{
get { return GetResourceList<GiftGiftTimeline>("gift_timelines"); }
}
#endregion
#region Requests
public class CreateRequest : EntityRequest<CreateRequest>
{
public CreateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CreateRequest ScheduledAt(long scheduledAt)
{
m_params.AddOpt("scheduled_at", scheduledAt);
return this;
}
public CreateRequest AutoClaim(bool autoClaim)
{
m_params.AddOpt("auto_claim", autoClaim);
return this;
}
public CreateRequest NoExpiry(bool noExpiry)
{
m_params.AddOpt("no_expiry", noExpiry);
return this;
}
public CreateRequest ClaimExpiryDate(long claimExpiryDate)
{
m_params.AddOpt("claim_expiry_date", claimExpiryDate);
return this;
}
public CreateRequest CouponIds(List<string> couponIds)
{
m_params.AddOpt("coupon_ids", couponIds);
return this;
}
public CreateRequest GifterCustomerId(string gifterCustomerId)
{
m_params.Add("gifter[customer_id]", gifterCustomerId);
return this;
}
public CreateRequest GifterSignature(string gifterSignature)
{
m_params.Add("gifter[signature]", gifterSignature);
return this;
}
public CreateRequest GifterNote(string gifterNote)
{
m_params.AddOpt("gifter[note]", gifterNote);
return this;
}
public CreateRequest GifterPaymentSrcId(string gifterPaymentSrcId)
{
m_params.AddOpt("gifter[payment_src_id]", gifterPaymentSrcId);
return this;
}
public CreateRequest GiftReceiverCustomerId(string giftReceiverCustomerId)
{
m_params.Add("gift_receiver[customer_id]", giftReceiverCustomerId);
return this;
}
public CreateRequest GiftReceiverFirstName(string giftReceiverFirstName)
{
m_params.Add("gift_receiver[first_name]", giftReceiverFirstName);
return this;
}
public CreateRequest GiftReceiverLastName(string giftReceiverLastName)
{
m_params.Add("gift_receiver[last_name]", giftReceiverLastName);
return this;
}
public CreateRequest GiftReceiverEmail(string giftReceiverEmail)
{
m_params.Add("gift_receiver[email]", giftReceiverEmail);
return this;
}
public CreateRequest PaymentIntentId(string paymentIntentId)
{
m_params.AddOpt("payment_intent[id]", paymentIntentId);
return this;
}
public CreateRequest PaymentIntentGatewayAccountId(string paymentIntentGatewayAccountId)
{
m_params.AddOpt("payment_intent[gateway_account_id]", paymentIntentGatewayAccountId);
return this;
}
public CreateRequest PaymentIntentGwToken(string paymentIntentGwToken)
{
m_params.AddOpt("payment_intent[gw_token]", paymentIntentGwToken);
return this;
}
public CreateRequest PaymentIntentReferenceId(string paymentIntentReferenceId)
{
m_params.AddOpt("payment_intent[reference_id]", paymentIntentReferenceId);
return this;
}
[Obsolete]
public CreateRequest PaymentIntentGwPaymentMethodId(string paymentIntentGwPaymentMethodId)
{
m_params.AddOpt("payment_intent[gw_payment_method_id]", paymentIntentGwPaymentMethodId);
return this;
}
public CreateRequest PaymentIntentAdditionalInfo(JToken paymentIntentAdditionalInfo)
{
m_params.AddOpt("payment_intent[additional_info]", paymentIntentAdditionalInfo);
return this;
}
public CreateRequest ShippingAddressFirstName(string shippingAddressFirstName)
{
m_params.AddOpt("shipping_address[first_name]", shippingAddressFirstName);
return this;
}
public CreateRequest ShippingAddressLastName(string shippingAddressLastName)
{
m_params.AddOpt("shipping_address[last_name]", shippingAddressLastName);
return this;
}
public CreateRequest ShippingAddressEmail(string shippingAddressEmail)
{
m_params.AddOpt("shipping_address[email]", shippingAddressEmail);
return this;
}
public CreateRequest ShippingAddressCompany(string shippingAddressCompany)
{
m_params.AddOpt("shipping_address[company]", shippingAddressCompany);
return this;
}
public CreateRequest ShippingAddressPhone(string shippingAddressPhone)
{
m_params.AddOpt("shipping_address[phone]", shippingAddressPhone);
return this;
}
public CreateRequest ShippingAddressLine1(string shippingAddressLine1)
{
m_params.AddOpt("shipping_address[line1]", shippingAddressLine1);
return this;
}
public CreateRequest ShippingAddressLine2(string shippingAddressLine2)
{
m_params.AddOpt("shipping_address[line2]", shippingAddressLine2);
return this;
}
public CreateRequest ShippingAddressLine3(string shippingAddressLine3)
{
m_params.AddOpt("shipping_address[line3]", shippingAddressLine3);
return this;
}
public CreateRequest ShippingAddressCity(string shippingAddressCity)
{
m_params.AddOpt("shipping_address[city]", shippingAddressCity);
return this;
}
public CreateRequest ShippingAddressStateCode(string shippingAddressStateCode)
{
m_params.AddOpt("shipping_address[state_code]", shippingAddressStateCode);
return this;
}
public CreateRequest ShippingAddressState(string shippingAddressState)
{
m_params.AddOpt("shipping_address[state]", shippingAddressState);
return this;
}
public CreateRequest ShippingAddressZip(string shippingAddressZip)
{
m_params.AddOpt("shipping_address[zip]", shippingAddressZip);
return this;
}
public CreateRequest ShippingAddressCountry(string shippingAddressCountry)
{
m_params.AddOpt("shipping_address[country]", shippingAddressCountry);
return this;
}
public CreateRequest ShippingAddressValidationStatus(ChargeBee.Models.Enums.ValidationStatusEnum shippingAddressValidationStatus)
{
m_params.AddOpt("shipping_address[validation_status]", shippingAddressValidationStatus);
return this;
}
public CreateRequest SubscriptionPlanId(string subscriptionPlanId)
{
m_params.Add("subscription[plan_id]", subscriptionPlanId);
return this;
}
public CreateRequest SubscriptionPlanQuantity(int subscriptionPlanQuantity)
{
m_params.AddOpt("subscription[plan_quantity]", subscriptionPlanQuantity);
return this;
}
public CreateRequest SubscriptionPlanQuantityInDecimal(string subscriptionPlanQuantityInDecimal)
{
m_params.AddOpt("subscription[plan_quantity_in_decimal]", subscriptionPlanQuantityInDecimal);
return this;
}
public CreateRequest AddonId(int index, string addonId)
{
m_params.AddOpt("addons[id][" + index + "]", addonId);
return this;
}
public CreateRequest AddonQuantity(int index, int addonQuantity)
{
m_params.AddOpt("addons[quantity][" + index + "]", addonQuantity);
return this;
}
public CreateRequest AddonQuantityInDecimal(int index, string addonQuantityInDecimal)
{
m_params.AddOpt("addons[quantity_in_decimal][" + index + "]", addonQuantityInDecimal);
return this;
}
}
public class CreateForItemsRequest : EntityRequest<CreateForItemsRequest>
{
public CreateForItemsRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CreateForItemsRequest ScheduledAt(long scheduledAt)
{
m_params.AddOpt("scheduled_at", scheduledAt);
return this;
}
public CreateForItemsRequest AutoClaim(bool autoClaim)
{
m_params.AddOpt("auto_claim", autoClaim);
return this;
}
public CreateForItemsRequest NoExpiry(bool noExpiry)
{
m_params.AddOpt("no_expiry", noExpiry);
return this;
}
public CreateForItemsRequest ClaimExpiryDate(long claimExpiryDate)
{
m_params.AddOpt("claim_expiry_date", claimExpiryDate);
return this;
}
public CreateForItemsRequest CouponIds(List<string> couponIds)
{
m_params.AddOpt("coupon_ids", couponIds);
return this;
}
public CreateForItemsRequest GifterCustomerId(string gifterCustomerId)
{
m_params.Add("gifter[customer_id]", gifterCustomerId);
return this;
}
public CreateForItemsRequest GifterSignature(string gifterSignature)
{
m_params.Add("gifter[signature]", gifterSignature);
return this;
}
public CreateForItemsRequest GifterNote(string gifterNote)
{
m_params.AddOpt("gifter[note]", gifterNote);
return this;
}
public CreateForItemsRequest GifterPaymentSrcId(string gifterPaymentSrcId)
{
m_params.AddOpt("gifter[payment_src_id]", gifterPaymentSrcId);
return this;
}
public CreateForItemsRequest GiftReceiverCustomerId(string giftReceiverCustomerId)
{
m_params.Add("gift_receiver[customer_id]", giftReceiverCustomerId);
return this;
}
public CreateForItemsRequest GiftReceiverFirstName(string giftReceiverFirstName)
{
m_params.Add("gift_receiver[first_name]", giftReceiverFirstName);
return this;
}
public CreateForItemsRequest GiftReceiverLastName(string giftReceiverLastName)
{
m_params.Add("gift_receiver[last_name]", giftReceiverLastName);
return this;
}
public CreateForItemsRequest GiftReceiverEmail(string giftReceiverEmail)
{
m_params.Add("gift_receiver[email]", giftReceiverEmail);
return this;
}
public CreateForItemsRequest PaymentIntentId(string paymentIntentId)
{
m_params.AddOpt("payment_intent[id]", paymentIntentId);
return this;
}
public CreateForItemsRequest PaymentIntentGatewayAccountId(string paymentIntentGatewayAccountId)
{
m_params.AddOpt("payment_intent[gateway_account_id]", paymentIntentGatewayAccountId);
return this;
}
public CreateForItemsRequest PaymentIntentGwToken(string paymentIntentGwToken)
{
m_params.AddOpt("payment_intent[gw_token]", paymentIntentGwToken);
return this;
}
public CreateForItemsRequest PaymentIntentReferenceId(string paymentIntentReferenceId)
{
m_params.AddOpt("payment_intent[reference_id]", paymentIntentReferenceId);
return this;
}
[Obsolete]
public CreateForItemsRequest PaymentIntentGwPaymentMethodId(string paymentIntentGwPaymentMethodId)
{
m_params.AddOpt("payment_intent[gw_payment_method_id]", paymentIntentGwPaymentMethodId);
return this;
}
public CreateForItemsRequest PaymentIntentAdditionalInfo(JToken paymentIntentAdditionalInfo)
{
m_params.AddOpt("payment_intent[additional_info]", paymentIntentAdditionalInfo);
return this;
}
public CreateForItemsRequest ShippingAddressFirstName(string shippingAddressFirstName)
{
m_params.AddOpt("shipping_address[first_name]", shippingAddressFirstName);
return this;
}
public CreateForItemsRequest ShippingAddressLastName(string shippingAddressLastName)
{
m_params.AddOpt("shipping_address[last_name]", shippingAddressLastName);
return this;
}
public CreateForItemsRequest ShippingAddressEmail(string shippingAddressEmail)
{
m_params.AddOpt("shipping_address[email]", shippingAddressEmail);
return this;
}
public CreateForItemsRequest ShippingAddressCompany(string shippingAddressCompany)
{
m_params.AddOpt("shipping_address[company]", shippingAddressCompany);
return this;
}
public CreateForItemsRequest ShippingAddressPhone(string shippingAddressPhone)
{
m_params.AddOpt("shipping_address[phone]", shippingAddressPhone);
return this;
}
public CreateForItemsRequest ShippingAddressLine1(string shippingAddressLine1)
{
m_params.AddOpt("shipping_address[line1]", shippingAddressLine1);
return this;
}
public CreateForItemsRequest ShippingAddressLine2(string shippingAddressLine2)
{
m_params.AddOpt("shipping_address[line2]", shippingAddressLine2);
return this;
}
public CreateForItemsRequest ShippingAddressLine3(string shippingAddressLine3)
{
m_params.AddOpt("shipping_address[line3]", shippingAddressLine3);
return this;
}
public CreateForItemsRequest ShippingAddressCity(string shippingAddressCity)
{
m_params.AddOpt("shipping_address[city]", shippingAddressCity);
return this;
}
public CreateForItemsRequest ShippingAddressStateCode(string shippingAddressStateCode)
{
m_params.AddOpt("shipping_address[state_code]", shippingAddressStateCode);
return this;
}
public CreateForItemsRequest ShippingAddressState(string shippingAddressState)
{
m_params.AddOpt("shipping_address[state]", shippingAddressState);
return this;
}
public CreateForItemsRequest ShippingAddressZip(string shippingAddressZip)
{
m_params.AddOpt("shipping_address[zip]", shippingAddressZip);
return this;
}
public CreateForItemsRequest ShippingAddressCountry(string shippingAddressCountry)
{
m_params.AddOpt("shipping_address[country]", shippingAddressCountry);
return this;
}
public CreateForItemsRequest ShippingAddressValidationStatus(ChargeBee.Models.Enums.ValidationStatusEnum shippingAddressValidationStatus)
{
m_params.AddOpt("shipping_address[validation_status]", shippingAddressValidationStatus);
return this;
}
public CreateForItemsRequest SubscriptionItemItemPriceId(int index, string subscriptionItemItemPriceId)
{
m_params.AddOpt("subscription_items[item_price_id][" + index + "]", subscriptionItemItemPriceId);
return this;
}
public CreateForItemsRequest SubscriptionItemQuantity(int index, int subscriptionItemQuantity)
{
m_params.AddOpt("subscription_items[quantity][" + index + "]", subscriptionItemQuantity);
return this;
}
}
public class GiftListRequest : ListRequestBase<GiftListRequest>
{
public GiftListRequest(string url)
: base(url)
{
}
public EnumFilter<Gift.StatusEnum, GiftListRequest> Status()
{
return new EnumFilter<Gift.StatusEnum, GiftListRequest>("status", this);
}
public StringFilter<GiftListRequest> GiftReceiverEmail()
{
return new StringFilter<GiftListRequest>("gift_receiver[email]", this);
}
public StringFilter<GiftListRequest> GifterCustomerId()
{
return new StringFilter<GiftListRequest>("gifter[customer_id]", this);
}
public StringFilter<GiftListRequest> GiftReceiverCustomerId()
{
return new StringFilter<GiftListRequest>("gift_receiver[customer_id]", this);
}
}
public class UpdateGiftRequest : EntityRequest<UpdateGiftRequest>
{
public UpdateGiftRequest(string url, HttpMethod method)
: base(url, method)
{
}
public UpdateGiftRequest ScheduledAt(long scheduledAt)
{
m_params.Add("scheduled_at", scheduledAt);
return this;
}
public UpdateGiftRequest Comment(string comment)
{
m_params.AddOpt("comment", comment);
return this;
}
}
#endregion
public enum StatusEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "scheduled")]
Scheduled,
[EnumMember(Value = "unclaimed")]
Unclaimed,
[EnumMember(Value = "claimed")]
Claimed,
[EnumMember(Value = "cancelled")]
Cancelled,
[EnumMember(Value = "expired")]
Expired,
}
#region Subclasses
public class GiftGifter : Resource
{
public string CustomerId() {
return GetValue<string>("customer_id", true);
}
public string InvoiceId() {
return GetValue<string>("invoice_id", false);
}
public string Signature() {
return GetValue<string>("signature", false);
}
public string Note() {
return GetValue<string>("note", false);
}
}
public class GiftGiftReceiver : Resource
{
public string CustomerId() {
return GetValue<string>("customer_id", true);
}
public string SubscriptionId() {
return GetValue<string>("subscription_id", true);
}
public string FirstName() {
return GetValue<string>("first_name", false);
}
public string LastName() {
return GetValue<string>("last_name", false);
}
public string Email() {
return GetValue<string>("email", false);
}
}
public class GiftGiftTimeline : Resource
{
public StatusEnum Status() {
return GetEnum<StatusEnum>("status", true);
}
public DateTime? OccurredAt() {
return GetDateTime("occurred_at", false);
}
}
#endregion
}
}
| 38.723602 | 150 | 0.569172 | [
"MIT"
] | cdekkerpossibilit/chargebee-dotnet | ChargeBee/Models/Gift.cs | 24,938 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// CreateQueueRequest
/// </summary>
[DataContract]
public partial class CreateQueueRequest : IEquatable<CreateQueueRequest>
{
/// <summary>
/// The skill evaluation method to use when routing conversations.
/// </summary>
/// <value>The skill evaluation method to use when routing conversations.</value>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum SkillEvaluationMethodEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum None for "NONE"
/// </summary>
[EnumMember(Value = "NONE")]
None,
/// <summary>
/// Enum Best for "BEST"
/// </summary>
[EnumMember(Value = "BEST")]
Best,
/// <summary>
/// Enum All for "ALL"
/// </summary>
[EnumMember(Value = "ALL")]
All
}
/// <summary>
/// The skill evaluation method to use when routing conversations.
/// </summary>
/// <value>The skill evaluation method to use when routing conversations.</value>
[DataMember(Name="skillEvaluationMethod", EmitDefaultValue=false)]
public SkillEvaluationMethodEnum? SkillEvaluationMethod { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CreateQueueRequest" /> class.
/// </summary>
[JsonConstructorAttribute]
protected CreateQueueRequest() { }
/// <summary>
/// Initializes a new instance of the <see cref="CreateQueueRequest" /> class.
/// </summary>
/// <param name="Name">The queue name (required).</param>
/// <param name="Division">The division to which this entity belongs..</param>
/// <param name="Description">The queue description..</param>
/// <param name="DateCreated">The date the queue was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="DateModified">The date of the last modification to the queue. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
/// <param name="ModifiedBy">The ID of the user that last modified the queue..</param>
/// <param name="CreatedBy">The ID of the user that created the queue..</param>
/// <param name="MediaSettings">The media settings for the queue. Valid key values: CALL, CALLBACK, CHAT, EMAIL, MESSAGE, SOCIAL_EXPRESSION, VIDEO_COMM.</param>
/// <param name="RoutingRules">The routing rules for the queue, used for routing to known or preferred agents..</param>
/// <param name="Bullseye">The bulls-eye settings for the queue..</param>
/// <param name="AcwSettings">The ACW settings for the queue..</param>
/// <param name="SkillEvaluationMethod">The skill evaluation method to use when routing conversations..</param>
/// <param name="QueueFlow">The in-queue flow to use for call conversations waiting in queue..</param>
/// <param name="EmailInQueueFlow">The in-queue flow to use for email conversations waiting in queue..</param>
/// <param name="MessageInQueueFlow">The in-queue flow to use for message conversations waiting in queue..</param>
/// <param name="WhisperPrompt">The prompt used for whisper on the queue, if configured..</param>
/// <param name="OnHoldPrompt">The audio to be played when calls on this queue are on hold. If not configured, the default on-hold music will play..</param>
/// <param name="AutoAnswerOnly">Specifies whether the configured whisper should play for all ACD calls, or only for those which are auto-answered..</param>
/// <param name="EnableTranscription">Indicates whether voice transcription is enabled for this queue..</param>
/// <param name="EnableManualAssignment">Indicates whether manual assignment is enabled for this queue..</param>
/// <param name="CallingPartyName">The name to use for caller identification for outbound calls from this queue..</param>
/// <param name="CallingPartyNumber">The phone number to use for caller identification for outbound calls from this queue..</param>
/// <param name="DefaultScripts">The default script Ids for the communication types..</param>
/// <param name="OutboundMessagingAddresses">The messaging addresses for the queue..</param>
/// <param name="OutboundEmailAddress">OutboundEmailAddress.</param>
/// <param name="SourceQueueId">The id of an existing queue to copy the settings from when creating a new queue..</param>
public CreateQueueRequest(string Name = null, WritableDivision Division = null, string Description = null, DateTime? DateCreated = null, DateTime? DateModified = null, string ModifiedBy = null, string CreatedBy = null, Dictionary<string, MediaSetting> MediaSettings = null, List<RoutingRule> RoutingRules = null, Bullseye Bullseye = null, AcwSettings AcwSettings = null, SkillEvaluationMethodEnum? SkillEvaluationMethod = null, DomainEntityRef QueueFlow = null, DomainEntityRef EmailInQueueFlow = null, DomainEntityRef MessageInQueueFlow = null, DomainEntityRef WhisperPrompt = null, DomainEntityRef OnHoldPrompt = null, bool? AutoAnswerOnly = null, bool? EnableTranscription = null, bool? EnableManualAssignment = null, string CallingPartyName = null, string CallingPartyNumber = null, Dictionary<string, Script> DefaultScripts = null, QueueMessagingAddresses OutboundMessagingAddresses = null, QueueEmailAddress OutboundEmailAddress = null, string SourceQueueId = null)
{
this.Name = Name;
this.Division = Division;
this.Description = Description;
this.DateCreated = DateCreated;
this.DateModified = DateModified;
this.ModifiedBy = ModifiedBy;
this.CreatedBy = CreatedBy;
this.MediaSettings = MediaSettings;
this.RoutingRules = RoutingRules;
this.Bullseye = Bullseye;
this.AcwSettings = AcwSettings;
this.SkillEvaluationMethod = SkillEvaluationMethod;
this.QueueFlow = QueueFlow;
this.EmailInQueueFlow = EmailInQueueFlow;
this.MessageInQueueFlow = MessageInQueueFlow;
this.WhisperPrompt = WhisperPrompt;
this.OnHoldPrompt = OnHoldPrompt;
this.AutoAnswerOnly = AutoAnswerOnly;
this.EnableTranscription = EnableTranscription;
this.EnableManualAssignment = EnableManualAssignment;
this.CallingPartyName = CallingPartyName;
this.CallingPartyNumber = CallingPartyNumber;
this.DefaultScripts = DefaultScripts;
this.OutboundMessagingAddresses = OutboundMessagingAddresses;
this.OutboundEmailAddress = OutboundEmailAddress;
this.SourceQueueId = SourceQueueId;
}
/// <summary>
/// The globally unique identifier for the object.
/// </summary>
/// <value>The globally unique identifier for the object.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; private set; }
/// <summary>
/// The queue name
/// </summary>
/// <value>The queue name</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The division to which this entity belongs.
/// </summary>
/// <value>The division to which this entity belongs.</value>
[DataMember(Name="division", EmitDefaultValue=false)]
public WritableDivision Division { get; set; }
/// <summary>
/// The queue description.
/// </summary>
/// <value>The queue description.</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// The date the queue was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>The date the queue was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateCreated", EmitDefaultValue=false)]
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date of the last modification to the queue. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>The date of the last modification to the queue. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="dateModified", EmitDefaultValue=false)]
public DateTime? DateModified { get; set; }
/// <summary>
/// The ID of the user that last modified the queue.
/// </summary>
/// <value>The ID of the user that last modified the queue.</value>
[DataMember(Name="modifiedBy", EmitDefaultValue=false)]
public string ModifiedBy { get; set; }
/// <summary>
/// The ID of the user that created the queue.
/// </summary>
/// <value>The ID of the user that created the queue.</value>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public string CreatedBy { get; set; }
/// <summary>
/// The total number of members in the queue.
/// </summary>
/// <value>The total number of members in the queue.</value>
[DataMember(Name="memberCount", EmitDefaultValue=false)]
public int? MemberCount { get; private set; }
/// <summary>
/// The number of user members (i.e., non-group members) in the queue.
/// </summary>
/// <value>The number of user members (i.e., non-group members) in the queue.</value>
[DataMember(Name="userMemberCount", EmitDefaultValue=false)]
public int? UserMemberCount { get; private set; }
/// <summary>
/// The number of joined members in the queue.
/// </summary>
/// <value>The number of joined members in the queue.</value>
[DataMember(Name="joinedMemberCount", EmitDefaultValue=false)]
public int? JoinedMemberCount { get; private set; }
/// <summary>
/// The media settings for the queue. Valid key values: CALL, CALLBACK, CHAT, EMAIL, MESSAGE, SOCIAL_EXPRESSION, VIDEO_COMM
/// </summary>
/// <value>The media settings for the queue. Valid key values: CALL, CALLBACK, CHAT, EMAIL, MESSAGE, SOCIAL_EXPRESSION, VIDEO_COMM</value>
[DataMember(Name="mediaSettings", EmitDefaultValue=false)]
public Dictionary<string, MediaSetting> MediaSettings { get; set; }
/// <summary>
/// The routing rules for the queue, used for routing to known or preferred agents.
/// </summary>
/// <value>The routing rules for the queue, used for routing to known or preferred agents.</value>
[DataMember(Name="routingRules", EmitDefaultValue=false)]
public List<RoutingRule> RoutingRules { get; set; }
/// <summary>
/// The bulls-eye settings for the queue.
/// </summary>
/// <value>The bulls-eye settings for the queue.</value>
[DataMember(Name="bullseye", EmitDefaultValue=false)]
public Bullseye Bullseye { get; set; }
/// <summary>
/// The ACW settings for the queue.
/// </summary>
/// <value>The ACW settings for the queue.</value>
[DataMember(Name="acwSettings", EmitDefaultValue=false)]
public AcwSettings AcwSettings { get; set; }
/// <summary>
/// The in-queue flow to use for call conversations waiting in queue.
/// </summary>
/// <value>The in-queue flow to use for call conversations waiting in queue.</value>
[DataMember(Name="queueFlow", EmitDefaultValue=false)]
public DomainEntityRef QueueFlow { get; set; }
/// <summary>
/// The in-queue flow to use for email conversations waiting in queue.
/// </summary>
/// <value>The in-queue flow to use for email conversations waiting in queue.</value>
[DataMember(Name="emailInQueueFlow", EmitDefaultValue=false)]
public DomainEntityRef EmailInQueueFlow { get; set; }
/// <summary>
/// The in-queue flow to use for message conversations waiting in queue.
/// </summary>
/// <value>The in-queue flow to use for message conversations waiting in queue.</value>
[DataMember(Name="messageInQueueFlow", EmitDefaultValue=false)]
public DomainEntityRef MessageInQueueFlow { get; set; }
/// <summary>
/// The prompt used for whisper on the queue, if configured.
/// </summary>
/// <value>The prompt used for whisper on the queue, if configured.</value>
[DataMember(Name="whisperPrompt", EmitDefaultValue=false)]
public DomainEntityRef WhisperPrompt { get; set; }
/// <summary>
/// The audio to be played when calls on this queue are on hold. If not configured, the default on-hold music will play.
/// </summary>
/// <value>The audio to be played when calls on this queue are on hold. If not configured, the default on-hold music will play.</value>
[DataMember(Name="onHoldPrompt", EmitDefaultValue=false)]
public DomainEntityRef OnHoldPrompt { get; set; }
/// <summary>
/// Specifies whether the configured whisper should play for all ACD calls, or only for those which are auto-answered.
/// </summary>
/// <value>Specifies whether the configured whisper should play for all ACD calls, or only for those which are auto-answered.</value>
[DataMember(Name="autoAnswerOnly", EmitDefaultValue=false)]
public bool? AutoAnswerOnly { get; set; }
/// <summary>
/// Indicates whether voice transcription is enabled for this queue.
/// </summary>
/// <value>Indicates whether voice transcription is enabled for this queue.</value>
[DataMember(Name="enableTranscription", EmitDefaultValue=false)]
public bool? EnableTranscription { get; set; }
/// <summary>
/// Indicates whether manual assignment is enabled for this queue.
/// </summary>
/// <value>Indicates whether manual assignment is enabled for this queue.</value>
[DataMember(Name="enableManualAssignment", EmitDefaultValue=false)]
public bool? EnableManualAssignment { get; set; }
/// <summary>
/// The name to use for caller identification for outbound calls from this queue.
/// </summary>
/// <value>The name to use for caller identification for outbound calls from this queue.</value>
[DataMember(Name="callingPartyName", EmitDefaultValue=false)]
public string CallingPartyName { get; set; }
/// <summary>
/// The phone number to use for caller identification for outbound calls from this queue.
/// </summary>
/// <value>The phone number to use for caller identification for outbound calls from this queue.</value>
[DataMember(Name="callingPartyNumber", EmitDefaultValue=false)]
public string CallingPartyNumber { get; set; }
/// <summary>
/// The default script Ids for the communication types.
/// </summary>
/// <value>The default script Ids for the communication types.</value>
[DataMember(Name="defaultScripts", EmitDefaultValue=false)]
public Dictionary<string, Script> DefaultScripts { get; set; }
/// <summary>
/// The messaging addresses for the queue.
/// </summary>
/// <value>The messaging addresses for the queue.</value>
[DataMember(Name="outboundMessagingAddresses", EmitDefaultValue=false)]
public QueueMessagingAddresses OutboundMessagingAddresses { get; set; }
/// <summary>
/// Gets or Sets OutboundEmailAddress
/// </summary>
[DataMember(Name="outboundEmailAddress", EmitDefaultValue=false)]
public QueueEmailAddress OutboundEmailAddress { get; set; }
/// <summary>
/// The id of an existing queue to copy the settings from when creating a new queue.
/// </summary>
/// <value>The id of an existing queue to copy the settings from when creating a new queue.</value>
[DataMember(Name="sourceQueueId", EmitDefaultValue=false)]
public string SourceQueueId { get; set; }
/// <summary>
/// The URI for this object
/// </summary>
/// <value>The URI for this object</value>
[DataMember(Name="selfUri", EmitDefaultValue=false)]
public string SelfUri { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CreateQueueRequest {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Division: ").Append(Division).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" DateCreated: ").Append(DateCreated).Append("\n");
sb.Append(" DateModified: ").Append(DateModified).Append("\n");
sb.Append(" ModifiedBy: ").Append(ModifiedBy).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" MemberCount: ").Append(MemberCount).Append("\n");
sb.Append(" UserMemberCount: ").Append(UserMemberCount).Append("\n");
sb.Append(" JoinedMemberCount: ").Append(JoinedMemberCount).Append("\n");
sb.Append(" MediaSettings: ").Append(MediaSettings).Append("\n");
sb.Append(" RoutingRules: ").Append(RoutingRules).Append("\n");
sb.Append(" Bullseye: ").Append(Bullseye).Append("\n");
sb.Append(" AcwSettings: ").Append(AcwSettings).Append("\n");
sb.Append(" SkillEvaluationMethod: ").Append(SkillEvaluationMethod).Append("\n");
sb.Append(" QueueFlow: ").Append(QueueFlow).Append("\n");
sb.Append(" EmailInQueueFlow: ").Append(EmailInQueueFlow).Append("\n");
sb.Append(" MessageInQueueFlow: ").Append(MessageInQueueFlow).Append("\n");
sb.Append(" WhisperPrompt: ").Append(WhisperPrompt).Append("\n");
sb.Append(" OnHoldPrompt: ").Append(OnHoldPrompt).Append("\n");
sb.Append(" AutoAnswerOnly: ").Append(AutoAnswerOnly).Append("\n");
sb.Append(" EnableTranscription: ").Append(EnableTranscription).Append("\n");
sb.Append(" EnableManualAssignment: ").Append(EnableManualAssignment).Append("\n");
sb.Append(" CallingPartyName: ").Append(CallingPartyName).Append("\n");
sb.Append(" CallingPartyNumber: ").Append(CallingPartyNumber).Append("\n");
sb.Append(" DefaultScripts: ").Append(DefaultScripts).Append("\n");
sb.Append(" OutboundMessagingAddresses: ").Append(OutboundMessagingAddresses).Append("\n");
sb.Append(" OutboundEmailAddress: ").Append(OutboundEmailAddress).Append("\n");
sb.Append(" SourceQueueId: ").Append(SourceQueueId).Append("\n");
sb.Append(" SelfUri: ").Append(SelfUri).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as CreateQueueRequest);
}
/// <summary>
/// Returns true if CreateQueueRequest instances are equal
/// </summary>
/// <param name="other">Instance of CreateQueueRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CreateQueueRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Division == other.Division ||
this.Division != null &&
this.Division.Equals(other.Division)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.DateCreated == other.DateCreated ||
this.DateCreated != null &&
this.DateCreated.Equals(other.DateCreated)
) &&
(
this.DateModified == other.DateModified ||
this.DateModified != null &&
this.DateModified.Equals(other.DateModified)
) &&
(
this.ModifiedBy == other.ModifiedBy ||
this.ModifiedBy != null &&
this.ModifiedBy.Equals(other.ModifiedBy)
) &&
(
this.CreatedBy == other.CreatedBy ||
this.CreatedBy != null &&
this.CreatedBy.Equals(other.CreatedBy)
) &&
(
this.MemberCount == other.MemberCount ||
this.MemberCount != null &&
this.MemberCount.Equals(other.MemberCount)
) &&
(
this.UserMemberCount == other.UserMemberCount ||
this.UserMemberCount != null &&
this.UserMemberCount.Equals(other.UserMemberCount)
) &&
(
this.JoinedMemberCount == other.JoinedMemberCount ||
this.JoinedMemberCount != null &&
this.JoinedMemberCount.Equals(other.JoinedMemberCount)
) &&
(
this.MediaSettings == other.MediaSettings ||
this.MediaSettings != null &&
this.MediaSettings.SequenceEqual(other.MediaSettings)
) &&
(
this.RoutingRules == other.RoutingRules ||
this.RoutingRules != null &&
this.RoutingRules.SequenceEqual(other.RoutingRules)
) &&
(
this.Bullseye == other.Bullseye ||
this.Bullseye != null &&
this.Bullseye.Equals(other.Bullseye)
) &&
(
this.AcwSettings == other.AcwSettings ||
this.AcwSettings != null &&
this.AcwSettings.Equals(other.AcwSettings)
) &&
(
this.SkillEvaluationMethod == other.SkillEvaluationMethod ||
this.SkillEvaluationMethod != null &&
this.SkillEvaluationMethod.Equals(other.SkillEvaluationMethod)
) &&
(
this.QueueFlow == other.QueueFlow ||
this.QueueFlow != null &&
this.QueueFlow.Equals(other.QueueFlow)
) &&
(
this.EmailInQueueFlow == other.EmailInQueueFlow ||
this.EmailInQueueFlow != null &&
this.EmailInQueueFlow.Equals(other.EmailInQueueFlow)
) &&
(
this.MessageInQueueFlow == other.MessageInQueueFlow ||
this.MessageInQueueFlow != null &&
this.MessageInQueueFlow.Equals(other.MessageInQueueFlow)
) &&
(
this.WhisperPrompt == other.WhisperPrompt ||
this.WhisperPrompt != null &&
this.WhisperPrompt.Equals(other.WhisperPrompt)
) &&
(
this.OnHoldPrompt == other.OnHoldPrompt ||
this.OnHoldPrompt != null &&
this.OnHoldPrompt.Equals(other.OnHoldPrompt)
) &&
(
this.AutoAnswerOnly == other.AutoAnswerOnly ||
this.AutoAnswerOnly != null &&
this.AutoAnswerOnly.Equals(other.AutoAnswerOnly)
) &&
(
this.EnableTranscription == other.EnableTranscription ||
this.EnableTranscription != null &&
this.EnableTranscription.Equals(other.EnableTranscription)
) &&
(
this.EnableManualAssignment == other.EnableManualAssignment ||
this.EnableManualAssignment != null &&
this.EnableManualAssignment.Equals(other.EnableManualAssignment)
) &&
(
this.CallingPartyName == other.CallingPartyName ||
this.CallingPartyName != null &&
this.CallingPartyName.Equals(other.CallingPartyName)
) &&
(
this.CallingPartyNumber == other.CallingPartyNumber ||
this.CallingPartyNumber != null &&
this.CallingPartyNumber.Equals(other.CallingPartyNumber)
) &&
(
this.DefaultScripts == other.DefaultScripts ||
this.DefaultScripts != null &&
this.DefaultScripts.SequenceEqual(other.DefaultScripts)
) &&
(
this.OutboundMessagingAddresses == other.OutboundMessagingAddresses ||
this.OutboundMessagingAddresses != null &&
this.OutboundMessagingAddresses.Equals(other.OutboundMessagingAddresses)
) &&
(
this.OutboundEmailAddress == other.OutboundEmailAddress ||
this.OutboundEmailAddress != null &&
this.OutboundEmailAddress.Equals(other.OutboundEmailAddress)
) &&
(
this.SourceQueueId == other.SourceQueueId ||
this.SourceQueueId != null &&
this.SourceQueueId.Equals(other.SourceQueueId)
) &&
(
this.SelfUri == other.SelfUri ||
this.SelfUri != null &&
this.SelfUri.Equals(other.SelfUri)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Division != null)
hash = hash * 59 + this.Division.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.DateCreated != null)
hash = hash * 59 + this.DateCreated.GetHashCode();
if (this.DateModified != null)
hash = hash * 59 + this.DateModified.GetHashCode();
if (this.ModifiedBy != null)
hash = hash * 59 + this.ModifiedBy.GetHashCode();
if (this.CreatedBy != null)
hash = hash * 59 + this.CreatedBy.GetHashCode();
if (this.MemberCount != null)
hash = hash * 59 + this.MemberCount.GetHashCode();
if (this.UserMemberCount != null)
hash = hash * 59 + this.UserMemberCount.GetHashCode();
if (this.JoinedMemberCount != null)
hash = hash * 59 + this.JoinedMemberCount.GetHashCode();
if (this.MediaSettings != null)
hash = hash * 59 + this.MediaSettings.GetHashCode();
if (this.RoutingRules != null)
hash = hash * 59 + this.RoutingRules.GetHashCode();
if (this.Bullseye != null)
hash = hash * 59 + this.Bullseye.GetHashCode();
if (this.AcwSettings != null)
hash = hash * 59 + this.AcwSettings.GetHashCode();
if (this.SkillEvaluationMethod != null)
hash = hash * 59 + this.SkillEvaluationMethod.GetHashCode();
if (this.QueueFlow != null)
hash = hash * 59 + this.QueueFlow.GetHashCode();
if (this.EmailInQueueFlow != null)
hash = hash * 59 + this.EmailInQueueFlow.GetHashCode();
if (this.MessageInQueueFlow != null)
hash = hash * 59 + this.MessageInQueueFlow.GetHashCode();
if (this.WhisperPrompt != null)
hash = hash * 59 + this.WhisperPrompt.GetHashCode();
if (this.OnHoldPrompt != null)
hash = hash * 59 + this.OnHoldPrompt.GetHashCode();
if (this.AutoAnswerOnly != null)
hash = hash * 59 + this.AutoAnswerOnly.GetHashCode();
if (this.EnableTranscription != null)
hash = hash * 59 + this.EnableTranscription.GetHashCode();
if (this.EnableManualAssignment != null)
hash = hash * 59 + this.EnableManualAssignment.GetHashCode();
if (this.CallingPartyName != null)
hash = hash * 59 + this.CallingPartyName.GetHashCode();
if (this.CallingPartyNumber != null)
hash = hash * 59 + this.CallingPartyNumber.GetHashCode();
if (this.DefaultScripts != null)
hash = hash * 59 + this.DefaultScripts.GetHashCode();
if (this.OutboundMessagingAddresses != null)
hash = hash * 59 + this.OutboundMessagingAddresses.GetHashCode();
if (this.OutboundEmailAddress != null)
hash = hash * 59 + this.OutboundEmailAddress.GetHashCode();
if (this.SourceQueueId != null)
hash = hash * 59 + this.SourceQueueId.GetHashCode();
if (this.SelfUri != null)
hash = hash * 59 + this.SelfUri.GetHashCode();
return hash;
}
}
}
}
| 39.616998 | 979 | 0.529992 | [
"MIT"
] | MyPureCloud/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/CreateQueueRequest.cs | 35,893 | C# |
// T4 code generation is enabled for model 'Z:\Projects\ntieref\samples\NTierDemo\NTierDemo\Server\NTierDemo.Server.Domain.Edmx\NTierDemoModel.edmx'.
// To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
// property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
// is open in the designer.
// If no context and entity classes have been generated, it may be because you created an empty model but
// have not yet chosen which version of Entity Framework to use. To generate a context class and entity
// classes for your model, open the model in the designer, right-click on the designer surface, and
// select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
// Item...'. | 80.8 | 151 | 0.77104 | [
"ECL-2.0",
"Apache-2.0"
] | 6bee/ntieref | samples/NTierDemo/NTierDemo/Server/NTierDemo.Server.Domain.Edmx/NTierDemoModel.Designer.cs | 810 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.AzureStack.Management.Network.Admin
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
/// <summary>
/// Network Admin Client
/// </summary>
public partial interface INetworkAdminClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every
/// service call.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Client API Version.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated
/// and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IResourceProviderStateOperations.
/// </summary>
IResourceProviderStateOperations ResourceProviderState { get; }
/// <summary>
/// Gets the ILoadBalancersOperations.
/// </summary>
ILoadBalancersOperations LoadBalancers { get; }
/// <summary>
/// Gets the IPublicIPAddressesOperations.
/// </summary>
IPublicIPAddressesOperations PublicIPAddresses { get; }
/// <summary>
/// Gets the IQuotasOperations.
/// </summary>
IQuotasOperations Quotas { get; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
IVirtualNetworksOperations VirtualNetworks { get; }
}
}
| 30.54 | 79 | 0.599542 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/azurestack/Microsoft.AzureStack.Management.Network.Admin/src/Generated/INetworkAdminClient.cs | 3,054 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xamarin.Forms;
namespace Horus.Forms.Converters
{
public class TitleLabelConverter :IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Color.FromHex("#FFFFFF") : Color.FromHex("#1A1A1A");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 25.125 | 103 | 0.679934 | [
"MIT"
] | mtotaro/HorusChallenge | Horus/Converters/TitleLabelConverter.cs | 605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using SPA.DocumentManager.UnitGroups;
namespace SPA.DocumentManager.UnitGroups.DomainServices
{
/// <summary>
/// UnitGroup领域层的业务管理
/// </summary>
public class UnitGroupManager :DocumentManagerDomainServiceBase, IUnitGroupManager
{
private readonly IRepository<UnitGroup, int> _unitgroupRepository;
/// <summary>
/// UnitGroup的构造方法
/// </summary>
public UnitGroupManager(IRepository<UnitGroup, int> unitgroupRepository)
{
_unitgroupRepository = unitgroupRepository;
}
/// <summary>
/// 初始化
/// </summary>
public void InitUnitGroup()
{
throw new NotImplementedException();
}
//TODO:编写领域业务代码
//// custom codes
//// custom codes end
}
}
| 20.477273 | 86 | 0.655938 | [
"MIT"
] | lzhm216/dmproject | aspnet-core/src/SPA.DocumentManager.Core/UnitGroups/DomainServices/UnitGroupManager.cs | 949 | C# |
using System;
using Xunit;
namespace Shopping.Test
{
public class UnitTest1
{
[Fact]
public void Test1()
{
Assert.True(true);
}
}
}
| 12.6 | 30 | 0.502646 | [
"MIT"
] | insightapac/pocketpantry-microservices | src/Shopping.Test/UnitTest1.cs | 189 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.ComponentModel;
using Pulumi;
namespace Pulumi.AzureNative.DBforPostgreSQL.V20210601
{
/// <summary>
/// The mode to create a new PostgreSQL server.
/// </summary>
[EnumType]
public readonly struct CreateMode : IEquatable<CreateMode>
{
private readonly string _value;
private CreateMode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static CreateMode Default { get; } = new CreateMode("Default");
public static CreateMode Create { get; } = new CreateMode("Create");
public static CreateMode Update { get; } = new CreateMode("Update");
public static CreateMode PointInTimeRestore { get; } = new CreateMode("PointInTimeRestore");
public static bool operator ==(CreateMode left, CreateMode right) => left.Equals(right);
public static bool operator !=(CreateMode left, CreateMode right) => !left.Equals(right);
public static explicit operator string(CreateMode value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is CreateMode other && Equals(other);
public bool Equals(CreateMode other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// A value indicating whether Geo-Redundant backup is enabled on the server.
/// </summary>
[EnumType]
public readonly struct GeoRedundantBackupEnum : IEquatable<GeoRedundantBackupEnum>
{
private readonly string _value;
private GeoRedundantBackupEnum(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static GeoRedundantBackupEnum Enabled { get; } = new GeoRedundantBackupEnum("Enabled");
public static GeoRedundantBackupEnum Disabled { get; } = new GeoRedundantBackupEnum("Disabled");
public static bool operator ==(GeoRedundantBackupEnum left, GeoRedundantBackupEnum right) => left.Equals(right);
public static bool operator !=(GeoRedundantBackupEnum left, GeoRedundantBackupEnum right) => !left.Equals(right);
public static explicit operator string(GeoRedundantBackupEnum value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is GeoRedundantBackupEnum other && Equals(other);
public bool Equals(GeoRedundantBackupEnum other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The HA mode for the server.
/// </summary>
[EnumType]
public readonly struct HighAvailabilityMode : IEquatable<HighAvailabilityMode>
{
private readonly string _value;
private HighAvailabilityMode(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static HighAvailabilityMode Disabled { get; } = new HighAvailabilityMode("Disabled");
public static HighAvailabilityMode ZoneRedundant { get; } = new HighAvailabilityMode("ZoneRedundant");
public static bool operator ==(HighAvailabilityMode left, HighAvailabilityMode right) => left.Equals(right);
public static bool operator !=(HighAvailabilityMode left, HighAvailabilityMode right) => !left.Equals(right);
public static explicit operator string(HighAvailabilityMode value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is HighAvailabilityMode other && Equals(other);
public bool Equals(HighAvailabilityMode other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// PostgreSQL Server version.
/// </summary>
[EnumType]
public readonly struct ServerVersion : IEquatable<ServerVersion>
{
private readonly string _value;
private ServerVersion(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static ServerVersion ServerVersion_13 { get; } = new ServerVersion("13");
public static ServerVersion ServerVersion_12 { get; } = new ServerVersion("12");
public static ServerVersion ServerVersion_11 { get; } = new ServerVersion("11");
public static bool operator ==(ServerVersion left, ServerVersion right) => left.Equals(right);
public static bool operator !=(ServerVersion left, ServerVersion right) => !left.Equals(right);
public static explicit operator string(ServerVersion value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is ServerVersion other && Equals(other);
public bool Equals(ServerVersion other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
/// <summary>
/// The tier of the particular SKU, e.g. Burstable.
/// </summary>
[EnumType]
public readonly struct SkuTier : IEquatable<SkuTier>
{
private readonly string _value;
private SkuTier(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
public static SkuTier Burstable { get; } = new SkuTier("Burstable");
public static SkuTier GeneralPurpose { get; } = new SkuTier("GeneralPurpose");
public static SkuTier MemoryOptimized { get; } = new SkuTier("MemoryOptimized");
public static bool operator ==(SkuTier left, SkuTier right) => left.Equals(right);
public static bool operator !=(SkuTier left, SkuTier right) => !left.Equals(right);
public static explicit operator string(SkuTier value) => value._value;
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => obj is SkuTier other && Equals(other);
public bool Equals(SkuTier other) => string.Equals(_value, other._value, StringComparison.Ordinal);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
public override string ToString() => _value;
}
}
| 42.467456 | 122 | 0.682597 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DBforPostgreSQL/V20210601/Enums.cs | 7,177 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Topology;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;
namespace TTC2017.SmartGrids.CIM.IEC61970.StateVariables
{
/// <summary>
/// The public interface for SvPowerFlow
/// </summary>
[DefaultImplementationTypeAttribute(typeof(SvPowerFlow))]
[XmlDefaultImplementationTypeAttribute(typeof(SvPowerFlow))]
public interface ISvPowerFlow : IModelElement, IStateVariable
{
/// <summary>
/// The p property
/// </summary>
float P
{
get;
set;
}
/// <summary>
/// The q property
/// </summary>
float Q
{
get;
set;
}
/// <summary>
/// The Terminal property
/// </summary>
ITerminal Terminal
{
get;
set;
}
/// <summary>
/// Gets fired before the P property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> PChanging;
/// <summary>
/// Gets fired when the P property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> PChanged;
/// <summary>
/// Gets fired before the Q property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> QChanging;
/// <summary>
/// Gets fired when the Q property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> QChanged;
/// <summary>
/// Gets fired before the Terminal property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TerminalChanging;
/// <summary>
/// Gets fired when the Terminal property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> TerminalChanged;
}
}
| 28.942857 | 96 | 0.589997 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61970/StateVariables/ISvPowerFlow.cs | 3,041 | 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("ServerSideFinalProject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServerSideFinalProject")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("92c5ed20-c6bc-4eaa-bb98-d2a522ddd82c")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.111111 | 84 | 0.755102 | [
"MIT"
] | Turgibot/ServerSideFinalProject | ServerSideFinalProject/ServerSideFinalProject/Properties/AssemblyInfo.cs | 1,375 | C# |
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* 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 FluentAssertions;
using IdentityServer3.Core;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Validation;
using Microsoft.Owin;
using System.IO;
using System.Text;
using Xunit;
namespace IdentityServer3.Tests.Validation.Secrets
{
public class FormPostCredentialExtraction
{
const string Category = "Secrets - Form Post Secret Parsing";
IdentityServerOptions _options;
PostBodySecretParser _parser;
public FormPostCredentialExtraction()
{
_options = new IdentityServerOptions();
_parser = new PostBodySecretParser(_options);
}
[Fact]
public async void EmptyOwinEnvironment()
{
var context = new OwinContext();
context.Request.Body = new MemoryStream();
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
[Fact]
public async void Valid_PostBody()
{
var context = new OwinContext();
var body = "client_id=client&client_secret=secret";
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Type.Should().Be(Constants.ParsedSecretTypes.SharedSecret);
secret.Id.Should().Be("client");
secret.Credential.Should().Be("secret");
}
[Fact]
public async void ClientId_Too_Long()
{
var context = new OwinContext();
var longClientId = "x".Repeat(_options.InputLengthRestrictions.ClientId + 1);
var body = string.Format("client_id={0}&client_secret=secret", longClientId);
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
[Fact]
public async void ClientSecret_Too_Long()
{
var context = new OwinContext();
var longClientSecret = "x".Repeat(_options.InputLengthRestrictions.ClientSecret + 1);
var body = string.Format("client_id=client&client_secret={0}", longClientSecret);
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
[Fact]
public async void Missing_ClientId()
{
var context = new OwinContext();
var body = "client_secret=secret";
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
[Fact]
public async void Missing_ClientSecret()
{
var context = new OwinContext();
var body = "client_id=client";
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
[Fact]
public async void Malformed_PostBody()
{
var context = new OwinContext();
var body = "malformed";
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));
var secret = await _parser.ParseAsync(context.Environment);
secret.Should().BeNull();
}
}
} | 30.251799 | 97 | 0.6283 | [
"Apache-2.0"
] | AppliedSystems/IdentityServer3 | source/Tests/UnitTests/Validation/Secrets/FormPostCredentialParsing.cs | 4,207 | C# |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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.
namespace SolidCP.LocalizationToolkit {
partial class Resources
{
}
}
| 47.888889 | 83 | 0.741879 | [
"BSD-3-Clause"
] | Alirexaa/SolidCP | SolidCP/Sources/Tools/SolidCP.LocalizationToolkit/Resources.cs | 1,726 | C# |
// Copyright (C) Sina Iravanian, Julian Verdurmen, axuno gGmbH and other contributors.
// Licensed under the MIT license.
using System;
using System.Globalization;
using System.Xml;
namespace YAXLib.Exceptions
{
/// <summary>
/// Raised when the element value corresponding to some property is not present in the given XML file, when
/// deserializing.
/// This exception is raised during deserialization.
/// </summary>
[Obsolete("unused - will be removed in Yax 3")]
public class YAXElementValueAlreadyExistsException : YAXDeserializationException
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="YAXAttributeMissingException" /> class.
/// </summary>
/// <param name="elementName">Name of the element.</param>
public YAXElementValueAlreadyExistsException(string elementName) :
this(elementName, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YAXAttributeMissingException" /> class.
/// </summary>
/// <param name="elementName">Name of the element.</param>
/// <param name="lineInfo">IXmlLineInfo derived object, e.g. XElement, XAttribute containing line info</param>
public YAXElementValueAlreadyExistsException(string elementName, IXmlLineInfo lineInfo) :
base(lineInfo)
{
ElementName = elementName;
}
#endregion
#region Properties
/// <summary>
/// Gets the name of the attribute.
/// </summary>
/// <value>The name of the attribute.</value>
public string ElementName { get; }
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <value></value>
/// <returns>
/// The error message that explains the reason for the exception, or an empty string("").
/// </returns>
public override string Message => string.Format(CultureInfo.CurrentCulture,
"Element with the given name already has value: '{0}'.{1}", ElementName, LineInfoMessage);
#endregion
}
} | 36.016129 | 118 | 0.618003 | [
"MIT"
] | OrbintSoft/YAXLib | YAXLib/Exceptions/YAXElementValueAlreadyExistsException.cs | 2,235 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MixedRealityExtension.API;
using MixedRealityExtension.App;
using MixedRealityExtension.Core.Types;
using MixedRealityExtension.Util.GodotHelper;
using System;
using Godot;
using GodotCollisionShape = Godot.CollisionShape;
namespace MixedRealityExtension.Core
{
/// <summary>
/// Abstract class that represents the collider geometry.
/// </summary>
public abstract class ColliderGeometry
{
/// <summary>
/// The shape of the collider. <see cref="ColliderType"/>
/// </summary>
public abstract ColliderType Shape { get; }
internal abstract void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider);
}
/// <summary>
/// Class that represents the sphere geometry for a sphere collider.
/// </summary>
public class SphereColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Sphere;
/// <summary>
/// The center of the sphere collider geometry.
/// </summary>
public MWVector3 Center { get; set; }
/// <summary>
/// The radius of the sphere collider geometry.
/// </summary>
public float? Radius { get; set; }
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
if (collider.Shape is SphereShape sphereCollider)
{
if (Center != null)
{
Vector3 newCenter;
newCenter.x = Center.X;
newCenter.y = Center.Y;
newCenter.z = Center.Z;
collider.Transform = new Transform(Basis.Identity, newCenter);
}
if (Radius != null)
{
sphereCollider.Radius = Radius.Value;
}
}
}
}
/// <summary>
/// Class that represents the box geometry of a box collider.
/// </summary>
public class BoxColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Box;
/// <summary>
/// The size of the box collider geometry.
/// </summary>
public MWVector3 Size { get; set; }
/// <summary>
/// The center of the box collider geometry.
/// </summary>
public MWVector3 Center { get; set; }
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
if (collider.Shape is BoxShape boxShape)
{
if (Center != null)
{
Vector3 newCenter;
newCenter.x = Center.X;
newCenter.y = Center.Y;
newCenter.z = Center.Z;
collider.Transform = new Transform(Basis.Identity, newCenter);
}
if (Size != null)
{
Vector3 newSize;
newSize.x = Size.X;
newSize.y = Size.Y;
newSize.z = Size.Z;
boxShape.Extents = newSize;
}
}
}
}
/// <summary>
/// Class that represents the mesh geometry of a mesh collider.
/// </summary>
public class MeshColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Mesh;
/// <summary>
/// The asset ID of the collider's mesh
/// </summary>
public Guid MeshId { get; set; }
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
if (collider.Shape is ConcavePolygonShape concavePolygonShape)
{
Patch(app, concavePolygonShape);
}
}
private void Patch(MixedRealityExtensionApp app, ConcavePolygonShape concavePolygonShape)
{
var tempId = MeshId;
app.AssetManager.OnSet(MeshId, asset =>
{
if (MeshId != tempId) return;
concavePolygonShape.Data = (Vector3[])(asset.Asset as Mesh).SurfaceGetArrays(0)[0];
});
}
}
/// <summary>
/// Class that describes a cylinder-shaped collision volume
/// </summary>
public class CylinderColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Cylinder;
/// <summary>
/// The centerpoint of the collider in local space
/// </summary>
public MWVector3 Center { get; set; }
/// <summary>
/// The rotation of the collider in local space
/// </summary>
public Quat Rotation { get; set; }
/// <summary>
/// The bounding box of the cylinder.
/// </summary>
public MWVector3 Dimensions { get; set; }
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
if (collider.Shape is CylinderShape cylinderShape)
{
Vector3 newCenter = Vector3.Zero;
Basis basis = Basis.Identity;
if (Center != null)
{
newCenter.x = Center.X;
newCenter.y = Center.Y;
newCenter.z = Center.Z;
}
if (Dimensions != null)
{
float radius;
float height;
if (Mathf.IsEqualApprox(Dimensions.X, Dimensions.Y))
{
height = Dimensions.Z;
radius = Dimensions.X / 2;
}
else if (Mathf.IsEqualApprox(Dimensions.X, Dimensions.Z))
{
height = Dimensions.Y;
radius = Dimensions.X / 2;
}
else
{
height = Dimensions.X;
radius = Dimensions.Y / 2;
}
cylinderShape.Radius = radius;
cylinderShape.Height = height;
if (Dimensions.X == height)
{
basis = basis.Rotated(Vector3.Forward, Mathf.Pi / 2);
}
else if (Dimensions.Z == height)
{
basis = basis.Rotated(Vector3.Right, Mathf.Pi / 2);
}
}
collider.Transform = new Transform(basis, newCenter);
}
}
}
/// <summary>
/// Class that describes a capsule-shaped collision volume
/// </summary>
public class CapsuleColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Capsule;
/// <summary>
/// The centerpoint of the collider in local space
/// </summary>
public MWVector3 Center { get; set; }
/// <summary>
/// The dimensions of the collider, with the largest component of the vector being the
/// primary axis and height of the capsule, and the second largest the radius.
/// </summary>
public MWVector3 Size { get; set; }
/// <summary>
/// The primary axis of the capsule (x = 0, y = 1, z = 2)
/// </summary>
public int? Direction
{
get => Size?.LargestComponentIndex();
}
/// <summary>
/// The height of the capsule along its primary axis, including end caps
/// </summary>
public float? Height
{
get => Size?.LargestComponentValue() - 2 * Radius;
}
/// <summary>
/// The radius of the capsule
/// </summary>
public float? Radius
{
get => Size != null ? Size.SmallestComponentValue() / 2 : (float?) null;
}
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
if (collider.Shape is CapsuleShape capsuleShape)
{
Vector3 newCenter = Vector3.Zero;
Basis basis = Basis.Identity;
if (Center != null)
{
newCenter.x = Center.X;
newCenter.y = Center.Y;
newCenter.z = Center.Z;
}
if (Size != null)
{
capsuleShape.Radius = Radius.Value;
capsuleShape.Height = Height.Value;
// default capsule Shape is Z-aligned; rotate if necessary
if (Size.LargestComponentIndex() == 0)
{
basis = basis.Rotated(Vector3.Up, Mathf.Pi / 2);
}
else if (Size.LargestComponentIndex() == 1)
{
basis = basis.Rotated(Vector3.Right, Mathf.Pi / 2);
}
}
collider.Transform = new Transform(basis, newCenter);
}
}
}
/// <summary>
/// Class that represents geometry automatically generated alongside a mesh.
/// </summary>
public class AutoColliderGeometry : ColliderGeometry
{
/// <inheritdoc />
public override ColliderType Shape => ColliderType.Auto;
internal override void Patch(MixedRealityExtensionApp app, GodotCollisionShape collider)
{
// We do not accept patching for auto colliders from the app.
}
}
}
| 25.229508 | 91 | 0.65809 | [
"MIT"
] | dasg34/mixed-reality-extension-godot | MREGodotRuntimeLib/Core/ColliderGeometry.cs | 7,697 | C# |
using Microsoft.Xna.Framework.Audio;
using Terraria.ModLoader;
using Terraria;
using System;
namespace BahiaMod.Sounds.Item
{
class AtabaqueKick : ModSound
{
public override SoundEffectInstance PlaySound(ref SoundEffectInstance soundInstance, float volume, float pan, SoundType type)
{
soundInstance = sound.CreateInstance();
soundInstance.Volume = volume * .7f;
soundInstance.Pan = pan;
soundInstance.Pitch = 0f;
return soundInstance;
}
}
} | 28.368421 | 133 | 0.658627 | [
"MIT"
] | lluckymou/BahiaMod | Sounds/Item/AtabaqueKick.cs | 541 | C# |
#pragma checksum "..\..\settings.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "54C2E3416C56C22A068C6E060A106095A01C54BC35EF557BAEFAB27323A9864F"
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using ModernNotyfi;
using ModernWpf;
using ModernWpf.Controls;
using ModernWpf.Controls.Primitives;
using ModernWpf.DesignTime;
using ModernWpf.Markup;
using ModernWpf.Media.Animation;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace ModernNotyfi {
/// <summary>
/// settings
/// </summary>
public partial class settings : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 1 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal ModernNotyfi.settings Settings;
#line default
#line hidden
#line 13 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Media.SolidColorBrush Window_Back;
#line default
#line hidden
#line 23 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal ModernWpf.Controls.NavigationView NavView;
#line default
#line hidden
#line 47 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button close;
#line default
#line hidden
#line 48 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Save_Settings;
#line default
#line hidden
#line 49 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label Titles;
#line default
#line hidden
#line 50 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Image Sett_img;
#line default
#line hidden
#line 51 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TabControl Settings_Tab;
#line default
#line hidden
#line 56 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Main;
#line default
#line hidden
#line 59 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label mainsett_text;
#line default
#line hidden
#line 62 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_7;
#line default
#line hidden
#line 63 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Keyboard;
#line default
#line hidden
#line 66 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label widgettmaintext;
#line default
#line hidden
#line 69 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Personalization;
#line default
#line hidden
#line 72 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label perssetttext;
#line default
#line hidden
#line 75 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Info;
#line default
#line hidden
#line 78 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label aboutstext;
#line default
#line hidden
#line 81 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Update;
#line default
#line hidden
#line 84 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label updatemainsett;
#line default
#line hidden
#line 87 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_8;
#line default
#line hidden
#line 93 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label NameProfile;
#line default
#line hidden
#line 96 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Media.ImageBrush AccauntImg;
#line default
#line hidden
#line 99 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label localacc;
#line default
#line hidden
#line 109 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_1;
#line default
#line hidden
#line 128 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label thametext;
#line default
#line hidden
#line 129 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox theme_combo;
#line default
#line hidden
#line 135 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label funnanduse;
#line default
#line hidden
#line 153 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid Click_Shitdown_Check;
#line default
#line hidden
#line 154 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label texts65464;
#line default
#line hidden
#line 156 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.CheckBox Exit_Setting;
#line default
#line hidden
#line 168 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label textstyleshutdown;
#line default
#line hidden
#line 169 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox Style_Shutdown;
#line default
#line hidden
#line 175 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label subbone;
#line default
#line hidden
#line 183 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid Click_Shitdown_Check1;
#line default
#line hidden
#line 184 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text3243;
#line default
#line hidden
#line 186 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.CheckBox Chek_Start_Notify;
#line default
#line hidden
#line 197 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text0213023;
#line default
#line hidden
#line 198 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox pos_combo;
#line default
#line hidden
#line 213 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox Language_combo1;
#line default
#line hidden
#line 225 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_2;
#line default
#line hidden
#line 226 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Start;
#line default
#line hidden
#line 229 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label twxtwidgwtwidgwtmenu;
#line default
#line hidden
#line 239 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_3;
#line default
#line hidden
#line 260 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label pparone;
#line default
#line hidden
#line 261 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider Opacity_Panel_Settings;
#line default
#line hidden
#line 272 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label pcolortext;
#line default
#line hidden
#line 273 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBox Color_Border;
#line default
#line hidden
#line 274 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Color;
#line default
#line hidden
#line 284 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Border Border_Preview;
#line default
#line hidden
#line 290 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label infotextpreview;
#line default
#line hidden
#line 293 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label otherptext;
#line default
#line hidden
#line 312 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label texte65930;
#line default
#line hidden
#line 313 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Go_Tab_2;
#line default
#line hidden
#line 325 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label pradiusboprder;
#line default
#line hidden
#line 326 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider CRadius_Panel_Settings;
#line default
#line hidden
#line 337 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text23r923ri;
#line default
#line hidden
#line 338 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.CheckBox Chek_Allow_Window;
#line default
#line hidden
#line 342 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_3_Copy1;
#line default
#line hidden
#line 366 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Tab_Update;
#line default
#line hidden
#line 367 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Open_Site;
#line default
#line hidden
#line 368 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label version;
#line default
#line hidden
#line 369 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label Devetxt;
#line default
#line hidden
#line 370 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_6;
#line default
#line hidden
#line 371 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label textaboutproduct;
#line default
#line hidden
#line 372 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_5;
#line default
#line hidden
#line 373 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button text_5_dadsc;
#line default
#line hidden
#line 374 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label text_5_Copy;
#line default
#line hidden
#line 375 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button text_5_dvdsacv;
#line default
#line hidden
#line 385 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label InfoUpdate;
#line default
#line hidden
#line 386 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Image Update_img;
#line default
#line hidden
#line 387 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Check_Update;
#line default
#line hidden
#line 388 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label LastChekUpdate;
#line default
#line hidden
#line 392 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label SysInfoHeader;
#line default
#line hidden
#line 414 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label inforelithe;
#line default
#line hidden
#line 415 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label WindowsVersion;
#line default
#line hidden
#line 416 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label Version;
#line default
#line hidden
#line 417 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label Memory;
#line default
#line hidden
#line 418 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label EctInfoSys;
#line default
#line hidden
#line 427 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBox color_piker;
#line default
#line hidden
#line 428 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Color_Save;
#line default
#line hidden
#line 429 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Site_color;
#line default
#line hidden
#line 434 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider Red;
#line default
#line hidden
#line 435 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider Green;
#line default
#line hidden
#line 436 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Slider Blue;
#line default
#line hidden
#line 437 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label redtext;
#line default
#line hidden
#line 438 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label greentext;
#line default
#line hidden
#line 439 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label bluetext;
#line default
#line hidden
#line 446 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label REDtext;
#line default
#line hidden
#line 448 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label GREENtext;
#line default
#line hidden
#line 450 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Label BLUEtext;
#line default
#line hidden
#line 454 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Border Material_Border;
#line default
#line hidden
#line 478 "..\..\settings.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Back;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/ModernNotify;component/settings.xaml", System.UriKind.Relative);
#line 1 "..\..\settings.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.Settings = ((ModernNotyfi.settings)(target));
#line 11 "..\..\settings.xaml"
this.Settings.Loaded += new System.Windows.RoutedEventHandler(this.Settings_Loaded);
#line default
#line hidden
return;
case 2:
this.Window_Back = ((System.Windows.Media.SolidColorBrush)(target));
return;
case 3:
this.NavView = ((ModernWpf.Controls.NavigationView)(target));
#line 29 "..\..\settings.xaml"
this.NavView.ItemInvoked += new ModernWpf.TypedEventHandler<ModernWpf.Controls.NavigationView, ModernWpf.Controls.NavigationViewItemInvokedEventArgs>(this.NavView_ItemInvoked);
#line default
#line hidden
return;
case 4:
this.close = ((System.Windows.Controls.Button)(target));
#line 47 "..\..\settings.xaml"
this.close.Click += new System.Windows.RoutedEventHandler(this.Close);
#line default
#line hidden
return;
case 5:
this.Save_Settings = ((System.Windows.Controls.Button)(target));
#line 48 "..\..\settings.xaml"
this.Save_Settings.Click += new System.Windows.RoutedEventHandler(this.Save_Settings_Click);
#line default
#line hidden
return;
case 6:
this.Titles = ((System.Windows.Controls.Label)(target));
return;
case 7:
this.Sett_img = ((System.Windows.Controls.Image)(target));
return;
case 8:
this.Settings_Tab = ((System.Windows.Controls.TabControl)(target));
return;
case 9:
this.Open_Main = ((System.Windows.Controls.Button)(target));
#line 56 "..\..\settings.xaml"
this.Open_Main.Click += new System.Windows.RoutedEventHandler(this.Open_Main_Click);
#line default
#line hidden
return;
case 10:
this.mainsett_text = ((System.Windows.Controls.Label)(target));
return;
case 11:
this.text_7 = ((System.Windows.Controls.Label)(target));
return;
case 12:
this.Open_Keyboard = ((System.Windows.Controls.Button)(target));
#line 63 "..\..\settings.xaml"
this.Open_Keyboard.Click += new System.Windows.RoutedEventHandler(this.Open_Keyboard_Click);
#line default
#line hidden
return;
case 13:
this.widgettmaintext = ((System.Windows.Controls.Label)(target));
return;
case 14:
this.Open_Personalization = ((System.Windows.Controls.Button)(target));
#line 69 "..\..\settings.xaml"
this.Open_Personalization.Click += new System.Windows.RoutedEventHandler(this.Open_Personalization_Click);
#line default
#line hidden
return;
case 15:
this.perssetttext = ((System.Windows.Controls.Label)(target));
return;
case 16:
this.Open_Info = ((System.Windows.Controls.Button)(target));
#line 75 "..\..\settings.xaml"
this.Open_Info.Click += new System.Windows.RoutedEventHandler(this.Open_Info_Click);
#line default
#line hidden
return;
case 17:
this.aboutstext = ((System.Windows.Controls.Label)(target));
return;
case 18:
this.Open_Update = ((System.Windows.Controls.Button)(target));
#line 81 "..\..\settings.xaml"
this.Open_Update.Click += new System.Windows.RoutedEventHandler(this.Open_Update_Click);
#line default
#line hidden
return;
case 19:
this.updatemainsett = ((System.Windows.Controls.Label)(target));
return;
case 20:
this.text_8 = ((System.Windows.Controls.Label)(target));
return;
case 21:
this.NameProfile = ((System.Windows.Controls.Label)(target));
return;
case 22:
this.AccauntImg = ((System.Windows.Media.ImageBrush)(target));
return;
case 23:
this.localacc = ((System.Windows.Controls.Label)(target));
return;
case 24:
this.text_1 = ((System.Windows.Controls.Label)(target));
return;
case 25:
this.thametext = ((System.Windows.Controls.Label)(target));
return;
case 26:
this.theme_combo = ((System.Windows.Controls.ComboBox)(target));
#line 129 "..\..\settings.xaml"
this.theme_combo.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.theme_combo_SelectionChanged);
#line default
#line hidden
return;
case 27:
this.funnanduse = ((System.Windows.Controls.Label)(target));
return;
case 28:
this.Click_Shitdown_Check = ((System.Windows.Controls.Grid)(target));
return;
case 29:
this.texts65464 = ((System.Windows.Controls.Label)(target));
return;
case 30:
this.Exit_Setting = ((System.Windows.Controls.CheckBox)(target));
return;
case 31:
this.textstyleshutdown = ((System.Windows.Controls.Label)(target));
return;
case 32:
this.Style_Shutdown = ((System.Windows.Controls.ComboBox)(target));
#line 169 "..\..\settings.xaml"
this.Style_Shutdown.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.theme_combo_SelectionChanged);
#line default
#line hidden
return;
case 33:
this.subbone = ((System.Windows.Controls.Label)(target));
return;
case 34:
this.Click_Shitdown_Check1 = ((System.Windows.Controls.Grid)(target));
return;
case 35:
this.text3243 = ((System.Windows.Controls.Label)(target));
return;
case 36:
this.Chek_Start_Notify = ((System.Windows.Controls.CheckBox)(target));
return;
case 37:
this.text0213023 = ((System.Windows.Controls.Label)(target));
return;
case 38:
this.pos_combo = ((System.Windows.Controls.ComboBox)(target));
return;
case 39:
this.Language_combo1 = ((System.Windows.Controls.ComboBox)(target));
#line 213 "..\..\settings.xaml"
this.Language_combo1.DataContextChanged += new System.Windows.DependencyPropertyChangedEventHandler(this.Select_Language);
#line default
#line hidden
return;
case 40:
this.text_2 = ((System.Windows.Controls.Label)(target));
return;
case 41:
this.Open_Start = ((System.Windows.Controls.Button)(target));
return;
case 42:
this.twxtwidgwtwidgwtmenu = ((System.Windows.Controls.Label)(target));
return;
case 43:
this.text_3 = ((System.Windows.Controls.Label)(target));
return;
case 44:
this.pparone = ((System.Windows.Controls.Label)(target));
return;
case 45:
this.Opacity_Panel_Settings = ((System.Windows.Controls.Slider)(target));
#line 261 "..\..\settings.xaml"
this.Opacity_Panel_Settings.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(this.ValueUpdate);
#line default
#line hidden
return;
case 46:
this.pcolortext = ((System.Windows.Controls.Label)(target));
return;
case 47:
this.Color_Border = ((System.Windows.Controls.TextBox)(target));
#line 273 "..\..\settings.xaml"
this.Color_Border.TextChanged += new System.Windows.Controls.TextChangedEventHandler(this.Color_Border_TextChanged);
#line default
#line hidden
return;
case 48:
this.Open_Color = ((System.Windows.Controls.Button)(target));
#line 274 "..\..\settings.xaml"
this.Open_Color.Click += new System.Windows.RoutedEventHandler(this.Open_Color_Click);
#line default
#line hidden
return;
case 49:
this.Border_Preview = ((System.Windows.Controls.Border)(target));
return;
case 50:
this.infotextpreview = ((System.Windows.Controls.Label)(target));
return;
case 51:
this.otherptext = ((System.Windows.Controls.Label)(target));
return;
case 52:
this.texte65930 = ((System.Windows.Controls.Label)(target));
return;
case 53:
this.Go_Tab_2 = ((System.Windows.Controls.Button)(target));
#line 313 "..\..\settings.xaml"
this.Go_Tab_2.Click += new System.Windows.RoutedEventHandler(this.Go_Tab_1_Click);
#line default
#line hidden
return;
case 54:
this.pradiusboprder = ((System.Windows.Controls.Label)(target));
return;
case 55:
this.CRadius_Panel_Settings = ((System.Windows.Controls.Slider)(target));
#line 326 "..\..\settings.xaml"
this.CRadius_Panel_Settings.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(this.CRadius_Panel_Settings_Value);
#line default
#line hidden
return;
case 56:
this.text23r923ri = ((System.Windows.Controls.Label)(target));
return;
case 57:
this.Chek_Allow_Window = ((System.Windows.Controls.CheckBox)(target));
return;
case 58:
this.text_3_Copy1 = ((System.Windows.Controls.Label)(target));
return;
case 59:
this.Open_Tab_Update = ((System.Windows.Controls.Button)(target));
#line 366 "..\..\settings.xaml"
this.Open_Tab_Update.Click += new System.Windows.RoutedEventHandler(this.Open_Tab_Update_Click);
#line default
#line hidden
return;
case 60:
this.Open_Site = ((System.Windows.Controls.Button)(target));
#line 367 "..\..\settings.xaml"
this.Open_Site.Click += new System.Windows.RoutedEventHandler(this.Open_Site_Progect);
#line default
#line hidden
return;
case 61:
this.version = ((System.Windows.Controls.Label)(target));
return;
case 62:
this.Devetxt = ((System.Windows.Controls.Label)(target));
return;
case 63:
this.text_6 = ((System.Windows.Controls.Label)(target));
return;
case 64:
this.textaboutproduct = ((System.Windows.Controls.Label)(target));
return;
case 65:
this.text_5 = ((System.Windows.Controls.Label)(target));
return;
case 66:
this.text_5_dadsc = ((System.Windows.Controls.Button)(target));
#line 373 "..\..\settings.xaml"
this.text_5_dadsc.Click += new System.Windows.RoutedEventHandler(this.Open_Sourse);
#line default
#line hidden
return;
case 67:
this.text_5_Copy = ((System.Windows.Controls.Label)(target));
return;
case 68:
this.text_5_dvdsacv = ((System.Windows.Controls.Button)(target));
#line 375 "..\..\settings.xaml"
this.text_5_dvdsacv.Click += new System.Windows.RoutedEventHandler(this.Open_Sourse_Code);
#line default
#line hidden
return;
case 69:
this.InfoUpdate = ((System.Windows.Controls.Label)(target));
return;
case 70:
this.Update_img = ((System.Windows.Controls.Image)(target));
return;
case 71:
this.Check_Update = ((System.Windows.Controls.Button)(target));
#line 387 "..\..\settings.xaml"
this.Check_Update.Click += new System.Windows.RoutedEventHandler(this.Check_Update_Click);
#line default
#line hidden
return;
case 72:
this.LastChekUpdate = ((System.Windows.Controls.Label)(target));
return;
case 73:
this.SysInfoHeader = ((System.Windows.Controls.Label)(target));
return;
case 74:
this.inforelithe = ((System.Windows.Controls.Label)(target));
return;
case 75:
this.WindowsVersion = ((System.Windows.Controls.Label)(target));
return;
case 76:
this.Version = ((System.Windows.Controls.Label)(target));
return;
case 77:
this.Memory = ((System.Windows.Controls.Label)(target));
return;
case 78:
this.EctInfoSys = ((System.Windows.Controls.Label)(target));
return;
case 79:
this.color_piker = ((System.Windows.Controls.TextBox)(target));
return;
case 80:
this.Color_Save = ((System.Windows.Controls.Button)(target));
#line 428 "..\..\settings.xaml"
this.Color_Save.Click += new System.Windows.RoutedEventHandler(this.Color_Save_Click);
#line default
#line hidden
return;
case 81:
this.Site_color = ((System.Windows.Controls.Button)(target));
#line 429 "..\..\settings.xaml"
this.Site_color.Click += new System.Windows.RoutedEventHandler(this.Site_color_Click);
#line default
#line hidden
return;
case 82:
this.Red = ((System.Windows.Controls.Slider)(target));
#line 434 "..\..\settings.xaml"
this.Red.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(this.RGBtoHESH);
#line default
#line hidden
return;
case 83:
this.Green = ((System.Windows.Controls.Slider)(target));
#line 435 "..\..\settings.xaml"
this.Green.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(this.RGBtoHESH);
#line default
#line hidden
return;
case 84:
this.Blue = ((System.Windows.Controls.Slider)(target));
#line 436 "..\..\settings.xaml"
this.Blue.ValueChanged += new System.Windows.RoutedPropertyChangedEventHandler<double>(this.RGBtoHESH);
#line default
#line hidden
return;
case 85:
this.redtext = ((System.Windows.Controls.Label)(target));
return;
case 86:
this.greentext = ((System.Windows.Controls.Label)(target));
return;
case 87:
this.bluetext = ((System.Windows.Controls.Label)(target));
return;
case 88:
this.REDtext = ((System.Windows.Controls.Label)(target));
return;
case 89:
this.GREENtext = ((System.Windows.Controls.Label)(target));
return;
case 90:
this.BLUEtext = ((System.Windows.Controls.Label)(target));
return;
case 91:
this.Material_Border = ((System.Windows.Controls.Border)(target));
return;
case 92:
this.Back = ((System.Windows.Controls.Button)(target));
#line 478 "..\..\settings.xaml"
this.Back.Click += new System.Windows.RoutedEventHandler(this.Backs);
#line default
#line hidden
return;
}
this._contentLoaded = true;
}
}
}
| 37.704348 | 188 | 0.596717 | [
"MIT"
] | Stamir36/ModernNotyfi | ModernNotyfi/obj/Release/settings.g.cs | 47,832 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using log4net;
using MFilesAPI;
using AecCloud.WebAPI.Models;
namespace AecCloud.MfilesClientCore
{
/// <summary>
/// MFiles 库相关
/// </summary>
public static class MFilesVault
{
private static readonly List<string> VaultGuids = new List<string>();
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static VaultConnection InitialVaultConnection(UserDto user, VaultDto vault)
{
var app = new MFilesClientApplication();
var conns = app.GetVaultConnectionsWithGUID(vault.Guid);
//var count = conns.Count;
var removeConns = new List<VaultConnection>();
VaultConnection connection = null;
foreach (VaultConnection vc in conns)
{
if (vc.NetworkAddress != vault.Server.Ip
|| vc.Name != vault.Name
|| vc.Endpoint != vault.Server.Port)
{
removeConns.Add(vc);
}
else
{
connection = vc;
}
}
if (removeConns.Count > 0)
{
foreach (var vc in removeConns)
{
app.RemoveVaultConnection(vc.Name, vc.UserSpecific);
}
}
if (connection == null)
{
connection = new VaultConnection
{
AuthType = MFAuthType.MFAuthTypeSpecificWindowsUser,
AutoLogin = false,
NetworkAddress = vault.Server.Ip,
Endpoint = vault.Server.Port,
Name = vault.Name,
ServerVaultName = vault.Name,
ServerVaultGUID = vault.Guid,
UserName = user.UserName,
Password = user.Password,
Domain = user.Domain,
UserSpecific = true,
ProtocolSequence = "ncacn_ip_tcp"
};
app.AddVaultConnection(connection);
}
//var now = DateTime.Now;
Vault mfVault = null;
if (connection.IsLoggedIn())
{
var v = connection.BindToVault(IntPtr.Zero, true, true);
if (v != null)
{
var accountName = v.SessionInfo.AccountName;
var index = accountName.IndexOf('\\');
var userName = accountName.Substring(index + 1);
if (StringComparer.OrdinalIgnoreCase.Equals(userName, user.UserName))
{
mfVault = v;
}
else
{
v.LogOutWithDialogs(IntPtr.Zero);
}
}
}
return connection;
}
private static bool Need2Remove(VaultDto vault, VaultConnection vc, string vaultName)
{
vaultName = vaultName ?? vault.Name;
if (vc.Name == vaultName)
{
if (vc.NetworkAddress != vault.Server.Ip) return true;
if (vc.Endpoint != vault.Server.Port) return true;
if (vc.ServerVaultGUID != vault.Guid) return true;
}
if (vc.ServerVaultGUID != vault.Guid) return false;
if (vc.Name != vaultName) return true;
if (vc.NetworkAddress != vault.Server.Ip) return true;
if (vc.Endpoint != vault.Server.Port) return true;
return false;
}
public static Vault GetUserVault(UserDto user, VaultDto vault, bool forceLogout)
{
// (string.Format(" in GetUserVault(),userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
return GetUserVault(user, vault, forceLogout, null);
}
/// <summary>
///
/// </summary>
/// <param name="user"></param>
/// <param name="vault"></param>
/// <param name="forceLogout">是否强制退出</param>
/// <param name="vaultName">库名称</param>
/// <returns></returns>
public static Vault GetUserVault(UserDto user, VaultDto vault, bool forceLogout, string vaultName)
{
log.Info(" GetUserVault username="+user.FullName+",vault="+vault.Name);
if (VaultGuids.Contains(vault.Guid))
{
return GetVault(user, vault.Guid);
}
vaultName = vaultName ?? vault.Name;
var app = new MFilesClientApplication();
var removeConns = new List<VaultConnection>();
try
{
var sameVC = app.GetVaultConnection(vault.Name);
var needR = Need2Remove(vault, sameVC, vaultName);
if (needR) removeConns.Add(sameVC);
}
catch (Exception ex)
{
log.Info(string.Format("GetUserVault error:{0},{1}",vaultName,ex.Message));
}
var conns = app.GetVaultConnectionsWithGUID(vault.Guid);
VaultConnection connection = null;
foreach (VaultConnection vc in conns)
{
var needR = Need2Remove(vault, vc, vaultName);
if (needR) removeConns.Add(vc);
else connection = vc;
}
if (removeConns.Count > 0)
{
foreach (var vc in removeConns)
{
app.RemoveVaultConnection(vc.Name, vc.UserSpecific);
}
}
if (connection == null)
{
connection = new VaultConnection
{
AuthType = MFAuthType.MFAuthTypeSpecificWindowsUser,
AutoLogin = false,
NetworkAddress = vault.Server.Ip,
Endpoint = vault.Server.Port,
Name = vaultName,
ServerVaultName = vault.Name,
ServerVaultGUID = vault.Guid,
UserName = user.UserName,
Password = user.Password,
Domain = user.Domain,
UserSpecific = true,
ProtocolSequence = "ncacn_ip_tcp"
};
if (String.IsNullOrEmpty(user.Domain))
{
connection.AuthType = MFAuthType.MFAuthTypeSpecificMFilesUser;
}
app.AddVaultConnection(connection);
}
//var now = DateTime.Now;
Vault mfVault = null;
if (connection.IsLoggedIn())
{
var v = connection.BindToVault(IntPtr.Zero, true, true);
if (v != null)
{
if (forceLogout)
{
try
{
v.LogOutWithDialogs(IntPtr.Zero);
}
catch
{
log.Info("Remote Loggin time11111: " + DateTime.Now);
}
}
else
{
var accountName = v.SessionInfo.AccountName;
var index = accountName.IndexOf('\\');
var userName = accountName.Substring(index + 1);
if (StringComparer.OrdinalIgnoreCase.Equals(userName, user.UserName))
{
mfVault = v;
}
else
{
try
{
v.LogOutWithDialogs(IntPtr.Zero);
}
catch
{
log.Info("Remote Loggin time 22222: " + DateTime.Now);
}
}
}
}
}
log.Info("Remote Loggin time: " + DateTime.Now );
try
{
//now = DateTime.Now;
var has = false;
log.Info(string.Format(" in getuservault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
if (forceLogout)
{
mfVault = LoginVault(connection, user.UserName, user.Password, user.Domain);
has = true;
}
if (mfVault == null || !has)
{
mfVault = LoginVault(connection, user.UserName, user.Password, user.Domain);
}
log.Info("Loggin time: " + DateTime.Now );
}
catch
{
log.Info("Remote Loggin time: 33333" + DateTime.Now);
}
VaultGuids.Add(vault.Guid);
return mfVault;
}
/// <summary>
/// 设置客户端MFiles连接
/// </summary>
/// <param name="user"></param>
/// <param name="vault"></param>
public static Vault GetUserVault1(UserDto user, VaultDto vault)
{
if (VaultGuids.Contains(vault.Guid))
{
return GetVault(user, vault.Guid);
}
var server = vault.Server;
var conn = new VaultConnection();
var domain = user.Domain;
conn.AuthType = MFAuthType.MFAuthTypeSpecificWindowsUser;
conn.AutoLogin = false;
conn.NetworkAddress = server.Ip;// "192.168.2.129";
conn.Endpoint = server.Port;// "2266";
conn.Name = vault.Name;//"我的云盘";
conn.ServerVaultName = vault.Name;// "示例库";
conn.ServerVaultGUID = vault.Guid;// "{08ED46E7-C0FF-4D16-BA38-5043144CCD15}";
conn.UserName = user.UserName;// "qiuge";
conn.Password = user.Password;// "sd2350139";
conn.Domain = domain;// "simuladesign";
conn.UserSpecific = true;
conn.ProtocolSequence = "ncacn_ip_tcp";
var app = new MFilesClientApplication();
var conns = app.GetVaultConnections();
var connsSameName = new VaultConnections();
foreach (VaultConnection co in conns)
{
var coGUID = co.ServerVaultGUID;
if (coGUID == conn.ServerVaultGUID) // && co.Name == conn.Name
{
connsSameName.Add(-1, co);
}
}
if (connsSameName.Count > 0)
{
foreach (VaultConnection co in connsSameName)
{
app.RemoveVaultConnection(co.Name, co.UserSpecific);
}
}
app.AddVaultConnection(conn);
Vault mfVault = null;
try
{
// Writelog(string.Format(" in getuservault1,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, domain));
mfVault = LoginVault(conn, user.UserName, user.Password, domain);
}
catch
{
}
VaultGuids.Add(vault.Guid);
return mfVault;
}
public static Vault LoginVault(VaultConnection vc, UserDto user)
{
// Writelog(string.Format(" in loginvault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
return LoginVault(vc, user.UserName, user.Password, user.Domain);
}
private static Vault LoginVault(VaultConnection vc, string userName, string pwd, string domain)
{
// Writelog(string.Format(" userName={0}, pwd={1}, domai={2}", userName, pwd, domain));
if (!String.IsNullOrEmpty(domain))
{
return vc.LogInAsUser(MFAuthType.MFAuthTypeSpecificWindowsUser, userName, pwd, domain);
}
else
{
return vc.LogInAsUser(MFAuthType.MFAuthTypeSpecificMFilesUser, userName, pwd, "");
}
}
/// <summary>
/// 连接MFiles库
/// </summary>
/// <returns>MFiles 对象Vault</returns>
public static Vault GetVault(UserDto user, string vaultGuid, bool login=true)
{
//string vaultName = "设计云";
Vault vault = null;
var clientApp = new MFilesClientApplication();
VaultConnections conns = clientApp.GetVaultConnections();
string domain = user.Domain;
// Writelog(string.Format(" in GetVault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
foreach (VaultConnection vConn in conns)
{
if (vConn.GetGUID() == vaultGuid)
{
var loggedIn = vConn.IsLoggedIn();
if (!loggedIn && !login) return null;
if (vConn.IsLoggedIn())
{
vault = vConn.BindToVault(IntPtr.Zero, true, true);
string account = (domain == "" ? user.UserName : domain + "\\" + user.UserName);
if (vault.SessionInfo.AccountName != account)
{
vault.LogOutWithDialogs(IntPtr.Zero);
vault = LoginVault(vConn, user.UserName, user.Password, domain);
}
}
else
{
vault = LoginVault(vConn, user.UserName, user.Password, domain);
}
break;
}
}
return vault;
}
public static void LogoutVault(string vaultGuid)
{
var app = new MFilesClientApplication();
var vcs = app.GetVaultConnectionsWithGUID(vaultGuid);
foreach (VaultConnection vc in vcs)
{
if (vc.IsLoggedIn())
{
var v = vc.BindToVault(IntPtr.Zero, true, true);
try
{
v.LogOutWithDialogs(IntPtr.Zero);
}
catch
{
}
}
}
}
/// <summary>
/// 对"参数oVault是否有效"进行核实,若登出,则重连
/// </summary>
/// <param name="oVault">MFilesAPI.Vault</param>
/// <param name="user"></param>
/// <param name="vaultGuid">客户端库GUID</param>
public static Vault Connect2Vault(Vault oVault, UserDto user, string vaultGuid)
{
// Writelog(string.Format(" in Connect2Vault,userName={0}, pwd={1}, domai={2}", user.UserName, user.Password, user.Domain));
Vault vault = oVault;
if (!oVault.LoggedIn)
{
var clientApp = new MFilesClientApplication();
VaultConnections conns = clientApp.GetVaultConnections();
foreach (VaultConnection vConn in conns)
{
if (vConn.GetGUID() == vaultGuid)
{
vault = LoginVault(vConn, user.UserName, user.Password, user.Domain);
break;
}
}
}
return vault;
}
//添加基本搜索条件,类别、未删除
public static void AddSearchBaseCondition(SearchConditions oSearchConditions, int classId)
{
var oSearchCondition1 = new SearchCondition();
oSearchCondition1.ConditionType = MFConditionType.MFConditionTypeEqual;
oSearchCondition1.Expression.DataPropertyValuePropertyDef = (int)MFBuiltInPropertyDef.MFBuiltInPropertyDefClass;
oSearchCondition1.TypedValue.SetValue(MFDataType.MFDatatypeLookup, classId);
oSearchConditions.Add(-1, oSearchCondition1);
var oSearchCondition2 = new SearchCondition();
oSearchCondition2.ConditionType = MFConditionType.MFConditionTypeEqual;
oSearchCondition2.Expression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
oSearchCondition2.TypedValue.SetValue(MFDataType.MFDatatypeBoolean, false);
oSearchConditions.Add(-1, oSearchCondition2);
}
//public static async Task<string> SearchView(Vault vault, string search)
//{
// var viewName = "搜索:" + search + " - "+DateTime.Now.ToString("yyyyMMddHHmmss");
// var oViewNew = new View { Name = viewName };
// var oSc = new SearchCriteria
// {
// FullTextSearchString = search,
// FullTextSearchFlags = (MFFullTextSearchFlags.MFFullTextSearchFlagsStemming
// | MFFullTextSearchFlags.MFFullTextSearchFlagsLookInMetaData
// | MFFullTextSearchFlags.MFFullTextSearchFlagsLookInFileData
// | MFFullTextSearchFlags.MFFullTextSearchFlagsTypeAnyWords),
// SearchFlags = MFSearchFlags.MFSearchFlagNone,
// ExpandUI = false
// };
// var oExpression = new Expression();
// oExpression.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
// oExpression.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp;
// var oTypedValue = new TypedValue();
// oTypedValue.SetValue(MFDataType.MFDatatypeBoolean, false);
// var oDeletedEx = new SearchConditionEx();
// oDeletedEx.SearchCondition.Set(oExpression, MFConditionType.MFConditionTypeEqual, oTypedValue);
// oDeletedEx.Enabled = true;
// oDeletedEx.Ignored = false;
// oDeletedEx.SpecialNULL = false;
// oSc.AdditionalConditions.Add(-1, oDeletedEx);
// var oViewNew1 =
// await Task.Run(() => vault.ViewOperations.AddTemporarySearchView(oViewNew, oSc)).ConfigureAwait(false);
// return await Task.Run(() => vault.ViewOperations.GetViewLocationInClient(oViewNew1.ID)).ConfigureAwait(false);
//}
internal static SearchConditionEx GetDelStatusSearchEx(bool deleted)
{
var delExp = new Expression();
delExp.DataStatusValueType = MFStatusType.MFStatusTypeDeleted;
delExp.DataStatusValueDataFunction = MFDataFunction.MFDataFunctionNoOp;
var delTv = new TypedValue();
delTv.SetValue(MFDataType.MFDatatypeBoolean, deleted);
var delSearchEx = new SearchConditionEx();
delSearchEx.SearchCondition.Set(delExp, MFConditionType.MFConditionTypeEqual, delTv);
delSearchEx.Enabled = true;
delSearchEx.Ignored = false;
delSearchEx.SpecialNULL = false;
return delSearchEx;
}
}
}
| 41.184713 | 136 | 0.499691 | [
"MIT"
] | FinchYang/test | AecPrivateCloud.ALL/Client/AecCloud.MfilesClientCore/MFilesVault.cs | 19,548 | 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;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup;
using Xunit;
namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted
{
/// <summary>
/// Always Encrypted public CspProvider Manual tests.
/// TODO: These tests are marked as Windows only for now but should be run for all platforms once the Master Key is accessible to this app from Azure Key Vault.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)]
public class CspProviderExt
{
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestKeysFromCertificatesCreatedWithMultipleCryptoProviders(string connectionString)
{
const string providersRegistryKeyPath = @"SOFTWARE\Microsoft\Cryptography\Defaults\Provider";
Microsoft.Win32.RegistryKey defaultCryptoProvidersRegistryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(providersRegistryKeyPath);
foreach (string subKeyName in defaultCryptoProvidersRegistryKey.GetSubKeyNames())
{
// NOTE: RSACryptoServiceProvider.SignData() fails for other providers when testing locally
if (!subKeyName.Contains(@"RSA and AES"))
{
Console.WriteLine(@"INFO: Skipping Certificate creation for {0}.", subKeyName);
continue;
}
string providerName;
string providerType;
string certificateName;
using (Microsoft.Win32.RegistryKey providerKey = defaultCryptoProvidersRegistryKey.OpenSubKey(subKeyName))
{
// Get Provider Name and its type
providerName = providerKey.Name.Substring(providerKey.Name.LastIndexOf(@"\") + 1);
providerType = providerKey.GetValue(@"Type").ToString();
// Create a certificate from that provider
certificateName = string.Format(@"AETest - {0}", providerName);
}
CertificateUtilityWin.CreateCertificate(certificateName, StoreLocation.CurrentUser.ToString(), providerName, providerType);
SQLSetupStrategyCspExt sqlSetupStrategyCsp = null;
try
{
if (false == CertificateUtilityWin.CertificateExists(certificateName, StoreLocation.CurrentUser))
{
Console.WriteLine(@"INFO: Certificate creation for provider {0} failed so skipping it.", providerName);
continue;
}
X509Certificate2 cert = CertificateUtilityWin.GetCertificate(certificateName, StoreLocation.CurrentUser);
string cspPath = CertificateUtilityWin.GetCspPathFromCertificate(cert);
if (string.IsNullOrEmpty(cspPath))
{
Console.WriteLine(@"INFO: Certificate provider {0} is not a csp provider so skipping it.", providerName);
continue;
}
Console.WriteLine("CSP path is {0}", cspPath);
sqlSetupStrategyCsp = new SQLSetupStrategyCspExt(cspPath);
string tableName = sqlSetupStrategyCsp.CspProviderTable.Name;
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
Table.DeleteData(tableName, sqlConn);
// insert 1 row data
Customer customer = new Customer(45, "Microsoft", "Corporation");
DatabaseHelper.InsertCustomerData(sqlConn, tableName, customer);
// Test INPUT parameter on an encrypted parameter
using (SqlCommand sqlCommand = new SqlCommand(string.Format(@"SELECT CustomerId, FirstName, LastName FROM [{0}] WHERE FirstName = @firstName", tableName),
sqlConn, null, SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
customerFirstParam.Direction = System.Data.ParameterDirection.Input;
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
ValidateResultSet(sqlDataReader);
Console.WriteLine(@"INFO: Successfully validated using a certificate using provider:{0}", providerName);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(@"INFO: Failed to validate using a certificate using provider:{0}", providerName);
Console.WriteLine(@"Exception: {0}", e.Message);
}
finally
{
CertificateUtilityWin.RemoveCertificate(certificateName, StoreLocation.CurrentUser);
// clean up database resources
sqlSetupStrategyCsp?.Dispose();
}
}
}
// [Fact(Skip="Run this in non-parallel mode")] or [ConditionalFact()]
[Fact(Skip = "Failing in TCE")]
public void TestRoundTripWithCSPAndCertStoreProvider()
{
const string providerName = "Microsoft Enhanced RSA and AES Cryptographic Provider";
string providerType = "24";
string certificateName = string.Format(@"AETest - {0}", providerName);
CertificateUtilityWin.CreateCertificate(certificateName, StoreLocation.CurrentUser.ToString(), providerName, providerType);
try
{
X509Certificate2 cert = CertificateUtilityWin.GetCertificate(certificateName, StoreLocation.CurrentUser);
string cspPath = CertificateUtilityWin.GetCspPathFromCertificate(cert);
string certificatePath = String.Concat(@"CurrentUser/my/", cert.Thumbprint);
SqlColumnEncryptionCertificateStoreProvider certProvider = new SqlColumnEncryptionCertificateStoreProvider();
SqlColumnEncryptionCspProvider cspProvider = new SqlColumnEncryptionCspProvider();
byte[] columnEncryptionKey = DatabaseHelper.GenerateRandomBytes(32);
byte[] encryptedColumnEncryptionKeyUsingCert = certProvider.EncryptColumnEncryptionKey(certificatePath, @"RSA_OAEP", columnEncryptionKey);
byte[] columnEncryptionKeyReturnedCert2CSP = cspProvider.DecryptColumnEncryptionKey(cspPath, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingCert);
Assert.True(columnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedCert2CSP));
byte[] encryptedColumnEncryptionKeyUsingCSP = cspProvider.EncryptColumnEncryptionKey(cspPath, @"RSA_OAEP", columnEncryptionKey);
byte[] columnEncryptionKeyReturnedCSP2Cert = certProvider.DecryptColumnEncryptionKey(certificatePath, @"RSA_OAEP", encryptedColumnEncryptionKeyUsingCSP);
Assert.True(columnEncryptionKey.SequenceEqual(columnEncryptionKeyReturnedCSP2Cert));
}
finally
{
CertificateUtilityWin.RemoveCertificate(certificateName, StoreLocation.CurrentUser);
}
}
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))]
[ClassData(typeof(AEConnectionStringProvider))]
public void TestEncryptDecryptWithCSP(string connectionString)
{
string providerName = @"Microsoft Enhanced RSA and AES Cryptographic Provider";
string keyIdentifier = DataTestUtility.GetUniqueNameForSqlServer("CSP");
try
{
CertificateUtilityWin.RSAPersistKeyInCsp(providerName, keyIdentifier);
string cspPath = String.Concat(providerName, @"/", keyIdentifier);
SQLSetupStrategyCspExt sqlSetupStrategyCsp = new SQLSetupStrategyCspExt(cspPath);
string tableName = sqlSetupStrategyCsp.CspProviderTable.Name;
try
{
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
Table.DeleteData(tableName, sqlConn);
// insert 1 row data
Customer customer = new Customer(45, "Microsoft", "Corporation");
DatabaseHelper.InsertCustomerData(sqlConn, tableName, customer);
// Test INPUT parameter on an encrypted parameter
using (SqlCommand sqlCommand = new SqlCommand(string.Format(@"SELECT CustomerId, FirstName, LastName FROM [{0}] WHERE FirstName = @firstName", tableName),
sqlConn, null, SqlCommandColumnEncryptionSetting.Enabled))
{
SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft");
customerFirstParam.Direction = System.Data.ParameterDirection.Input;
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
ValidateResultSet(sqlDataReader);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(@"Exception: {0}", e.Message);
}
finally
{
// clean up database resources
sqlSetupStrategyCsp.Dispose();
}
}
finally
{
CertificateUtilityWin.RSADeleteKeyInCsp(providerName, keyIdentifier);
}
}
/// <summary>
/// Validates that the results are the ones expected.
/// </summary>
/// <param name="sqlDataReader"></param>
private void ValidateResultSet(SqlDataReader sqlDataReader)
{
int rowsFound = 0;
while (sqlDataReader.Read())
{
if (sqlDataReader.FieldCount == 3)
{
Assert.Equal(45, sqlDataReader.GetInt32(0));
Assert.Equal(@"Microsoft", sqlDataReader.GetString(1));
Assert.Equal(@"Corporation", sqlDataReader.GetString(2));
}
rowsFound++;
}
Assert.Equal(1, rowsFound);
}
}
}
| 49.9163 | 178 | 0.588209 | [
"MIT"
] | GoodTekken/SqlClient | src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CspProviderExt.cs | 11,331 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.MachineLearningServices.V20200501Preview.Inputs
{
public sealed class SharedPrivateLinkResourceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The private link resource group id.
/// </summary>
[Input("groupId")]
public Input<string>? GroupId { get; set; }
/// <summary>
/// Unique name of the private link.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The resource id that private link links to.
/// </summary>
[Input("privateLinkResourceId")]
public Input<string>? PrivateLinkResourceId { get; set; }
/// <summary>
/// Request message.
/// </summary>
[Input("requestMessage")]
public Input<string>? RequestMessage { get; set; }
/// <summary>
/// Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service.
/// </summary>
[Input("status")]
public Input<string>? Status { get; set; }
public SharedPrivateLinkResourceArgs()
{
}
}
}
| 29.66 | 108 | 0.603506 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/MachineLearningServices/V20200501Preview/Inputs/SharedPrivateLinkResourceArgs.cs | 1,483 | C# |
using Fixie.AutoRun.VisualStudio;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Fixie.AutoRun.Workers
{
public static class Compiler
{
private const string MsBuildPath = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe";
private const string MsBuildArgs = "/p:Configuration=\"{0}\" /p:Platform=\"{1}\" /v:{2} /nologo /t:rebuild /tv:4.0 /m /nr:false";
public static async Task<bool> Execute(Params @params)
{
var arguments = string.Join(" ",
string.Format("\"{0}\"", @params.SolutionPath),
@params.Args,
string.Format(MsBuildArgs,
@params.Configuration,
@params.Platform,
@params.Verbosity));
var process = new Process
{
StartInfo = new ProcessStartInfo(MsBuildPath)
{
Arguments = arguments,
CreateNoWindow = true,
RedirectStandardOutput = true,
UseShellExecute = false
}
};
process.OutputDataReceived += (sender, args) => @params.Callback(args.Data);
process.Start();
process.BeginOutputReadLine();
while (!process.HasExited)
{
if (@params.CancellationToken.IsCancellationRequested)
{
process.Kill();
return false;
}
await Task.Delay(50, @params.CancellationToken);
}
return process.ExitCode == 0;
}
public class Params
{
public string Args { get; set; }
public string Configuration { get; set; }
public string Platform { get; set; }
public MsBuildVerbosity Verbosity { get; set; }
public string SolutionPath { get; set; }
public Action<string> Callback { get; set; }
public CancellationToken CancellationToken { get; set; }
}
}
} | 38.721311 | 135 | 0.477138 | [
"MIT"
] | JonasSamuelsson/fixie.AutoRun | src/Fixie.AutoRun/Workers/Compiler.cs | 2,364 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefenderButton : MonoBehaviour
{
[SerializeField] Defender defenderPrefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnMouseDown()
{
var buttons = FindObjectsOfType<DefenderButton>();
foreach(DefenderButton defenderButton in buttons){
defenderButton.GetComponent<SpriteRenderer>().color = new Color32(106, 106, 106, 255);
}
GetComponent<SpriteRenderer>().color = Color.white;
FindObjectOfType<DefenderSpawner>().SetSelectedDefender(defenderPrefab);
}
}
| 24.451613 | 98 | 0.663588 | [
"MIT"
] | lorenzo-iannaccaro/GardenDefense | Assets/Scripts/DefenderButton.cs | 760 | C# |
#if CSHotFix
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using CSHotFix.CLR.TypeSystem;
using CSHotFix.CLR.Method;
using CSHotFix.Runtime.Enviorment;
using CSHotFix.Runtime.Intepreter;
using CSHotFix.Runtime.Stack;
using CSHotFix.Reflection;
using CSHotFix.CLR.Utils;
using System.Linq;
namespace CSHotFix.Runtime.Generated
{
unsafe class UnityEngine_Android_Permission_Binding
{
public static void Register(CSHotFix.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
FieldInfo field;
Type[] args;
Type type = typeof(UnityEngine.Android.Permission);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("HasUserAuthorizedPermission", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, HasUserAuthorizedPermission_0);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("RequestUserPermission", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, RequestUserPermission_1);
field = type.GetField("Camera", flag);
app.RegisterCLRFieldGetter(field, get_Camera_0);
field = type.GetField("Microphone", flag);
app.RegisterCLRFieldGetter(field, get_Microphone_1);
field = type.GetField("FineLocation", flag);
app.RegisterCLRFieldGetter(field, get_FineLocation_2);
field = type.GetField("CoarseLocation", flag);
app.RegisterCLRFieldGetter(field, get_CoarseLocation_3);
field = type.GetField("ExternalStorageRead", flag);
app.RegisterCLRFieldGetter(field, get_ExternalStorageRead_4);
field = type.GetField("ExternalStorageWrite", flag);
app.RegisterCLRFieldGetter(field, get_ExternalStorageWrite_5);
app.RegisterCLRMemberwiseClone(type, PerformMemberwiseClone);
app.RegisterCLRCreateDefaultInstance(type, () => new UnityEngine.Android.Permission());
app.RegisterCLRCreateArrayInstance(type, s => new UnityEngine.Android.Permission[s]);
}
static void WriteBackInstance(CSHotFix.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref UnityEngine.Android.Permission instance_of_this_method)
{
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.Object:
{
__mStack[ptr_of_this_method->Value] = instance_of_this_method;
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
var t = __domain.GetType(___obj.GetType()) as CLRType;
t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var t = __domain.GetType(ptr_of_this_method->Value);
if(t is ILType)
{
((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityEngine.Android.Permission[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
break;
}
}
static StackObject* HasUserAuthorizedPermission_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @permission = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = UnityEngine.Android.Permission.HasUserAuthorizedPermission(@permission);
__ret->ObjectType = ObjectTypes.Integer;
__ret->Value = result_of_this_method ? 1 : 0;
return __ret + 1;
}
static StackObject* RequestUserPermission_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @permission = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
UnityEngine.Android.Permission.RequestUserPermission(@permission);
return __ret;
}
static object get_Camera_0(ref object o)
{
return UnityEngine.Android.Permission.Camera;
}
static object get_Microphone_1(ref object o)
{
return UnityEngine.Android.Permission.Microphone;
}
static object get_FineLocation_2(ref object o)
{
return UnityEngine.Android.Permission.FineLocation;
}
static object get_CoarseLocation_3(ref object o)
{
return UnityEngine.Android.Permission.CoarseLocation;
}
static object get_ExternalStorageRead_4(ref object o)
{
return UnityEngine.Android.Permission.ExternalStorageRead;
}
static object get_ExternalStorageWrite_5(ref object o)
{
return UnityEngine.Android.Permission.ExternalStorageWrite;
}
static object PerformMemberwiseClone(ref object o)
{
var ins = new UnityEngine.Android.Permission();
ins = (UnityEngine.Android.Permission)o;
return ins;
}
}
}
#endif
| 43.27907 | 203 | 0.601155 | [
"MIT"
] | 591094733/cshotfix | CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Generated/CLRGen1/UnityEngine_Android_Permission_Binding.cs | 7,444 | C# |
using NetFrame.EnDecode;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 下单(平空 平多 全平 对冲)
/// </summary>
[Serializable]
[ProtoContract]
public class ReqOrderTacticsMessage : BaseMessage
{
public static int V_Pid = 100005;
/// <summary>
/// 币种
/// </summary>
[ProtoMember(1)]
public string coin;
/// <summary>
/// 操作类型 ( 1:平空 -1:平多 0:全平 2:对冲)
/// </summary>
[ProtoMember(2)]
public int type;
public override BaseMessage ReadData(byte[] msgBytes)
{
return AbsCoding.Ins.MsgDecoding<ReqOrderTacticsMessage>(msgBytes);
}
public override byte[] WriteData()
{
return AbsCoding.Ins.MsgEncoding(this);
}
}
| 19.631579 | 75 | 0.631367 | [
"Apache-2.0"
] | yellow001/CoinAPP_Server | App/Net/Data/Operation/ReqOrderTacticsMessage.cs | 804 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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.Reflection;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence
{
public class LocalPresenceServicesConnector : ISharedRegionModule, IPresenceService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private PresenceDetector m_PresenceDetector;
/// <summary>
/// Underlying presence service. Do not use directly.
/// </summary>
public IPresenceService m_PresenceService;
public LocalPresenceServicesConnector()
{
}
public LocalPresenceServicesConnector(IConfigSource source)
{
Initialise(source);
}
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalPresenceServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("PresenceServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["PresenceService"];
if (inventoryConfig == null)
{
m_log.Error("[LOCAL PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini");
return;
}
string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL PRESENCE CONNECTOR]: No LocalServiceModule named in section PresenceService");
return;
}
Object[] args = new Object[] { source };
m_log.DebugFormat("[LOCAL PRESENCE CONNECTOR]: Service dll = {0}", serviceDll);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(serviceDll, args);
if (m_PresenceService == null)
{
m_log.Error("[LOCAL PRESENCE CONNECTOR]: Can't load presence service");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
//Init(source);
m_PresenceDetector = new PresenceDetector(this);
m_Enabled = true;
m_log.Info("[LOCAL PRESENCE CONNECTOR]: Local presence connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
// m_log.DebugFormat(
// "[LOCAL PRESENCE CONNECTOR]: Registering IPresenceService to scene {0}", scene.RegionInfo.RegionName);
scene.RegisterModuleInterface<IPresenceService>(this);
m_PresenceDetector.AddRegion(scene);
m_log.InfoFormat("[LOCAL PRESENCE CONNECTOR]: Enabled local presence for region {0}", scene.RegionInfo.RegionName);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_PresenceDetector.RemoveRegion(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
#region IPresenceService
public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
{
m_log.Warn("[LOCAL PRESENCE CONNECTOR]: LoginAgent connector not implemented at the simulators");
return false;
}
public bool LogoutAgent(UUID sessionID)
{
return m_PresenceService.LogoutAgent(sessionID);
}
public bool LogoutRegionAgents(UUID regionID)
{
return m_PresenceService.LogoutRegionAgents(regionID);
}
public bool ReportAgent(UUID sessionID, UUID regionID)
{
return m_PresenceService.ReportAgent(sessionID, regionID);
}
public PresenceInfo GetAgent(UUID sessionID)
{
return m_PresenceService.GetAgent(sessionID);
}
public PresenceInfo[] GetAgents(string[] userIDs)
{
return m_PresenceService.GetAgents(userIDs);
}
#endregion
}
}
| 33.92 | 152 | 0.61365 | [
"BSD-3-Clause"
] | N3X15/VoxelSim | OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/LocalPresenceServiceConnector.cs | 6,786 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplyAddAdjacentInt32()
{
var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultiplyAddAdjacentInt32
{
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyAddAdjacentInt32 testClass)
{
var result = Sse2.MultiplyAddAdjacent(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int32, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__MultiplyAddAdjacentInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__MultiplyAddAdjacentInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int16, Int16>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.MultiplyAddAdjacent(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.MultiplyAddAdjacent(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyAddAdjacent), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.MultiplyAddAdjacent(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.MultiplyAddAdjacent(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.MultiplyAddAdjacent(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.MultiplyAddAdjacent(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt32();
var result = Sse2.MultiplyAddAdjacent(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.MultiplyAddAdjacent(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.MultiplyAddAdjacent(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int32[] result, [CallerMemberName] string method = "")
{
if (result[0] != Math.Clamp(((right[1] * left[1]) + (right[0] * left[0])), int.MinValue, int.MaxValue))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Clamp(((right[(i * 2) + 1] * left[(i * 2) + 1]) + (right[i * 2] * left[i * 2])), int.MinValue, int.MaxValue))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MultiplyAddAdjacent)}<Int32>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| 44.366337 | 187 | 0.60193 | [
"MIT"
] | Frassle/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse2/MultiplyAddAdjacent.Int32.cs | 17,924 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Luis;
using Microsoft.Bot.Builder.AI.Luis;
using Microsoft.Bot.Schema;
using Newtonsoft.Json.Linq;
using WeatherSkill.Models.Action;
namespace WeatherSkill.Tests.Flow.Utterances
{
public class ForecastUtterances : BaseTestUtterances
{
public ForecastUtterances()
{
this.Add(AskWeatherWithLocation, GetWeatherSkillLuis(AskWeatherWithLocation, WeatherSkillLuis.Intent.CheckWeatherValue, GeographyV2s));
this.Add(AskWeatherWithoutLocation, GetWeatherSkillLuis(AskWeatherWithoutLocation, WeatherSkillLuis.Intent.CheckWeatherValue));
}
public static GeographyV2[] GeographyV2s { get; } = { new GeographyV2(GeographyV2.Types.City, "Beijing") };
public static string AskWeatherWithLocation { get; } = "What's the weather like in Beijing";
public static string AskWeatherWithoutLocation { get; } = "What's the weather like";
public static string Location { get; } = "Beijing";
public static string Coordinates { get; } = "47.0743,-122.29654";
public static Activity WeatherForecastAction { get; } = new Activity()
{
Type = ActivityTypes.Event,
Name = ActionNames.WeatherForecast,
Value = JObject.FromObject(new LocationInfo()
{
Location = Location,
})
};
public static Activity WeatherForecastActionWithCoordinates { get; } = new Activity()
{
Type = ActivityTypes.Event,
Name = ActionNames.WeatherForecast,
Value = JObject.FromObject(new LocationInfo()
{
Location = Coordinates
})
};
}
}
| 35.137255 | 147 | 0.652344 | [
"MIT"
] | ConnectionMaster/botframework-components | skills/csharp/tests/weatherSkill.tests/Flow/Utterances/ForecastUtterances.cs | 1,794 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Eventgrid
{
public partial class AzureEventgridTopicDeleteTask : ExternalProcessTaskBase<AzureEventgridTopicDeleteTask>
{
/// <summary>
/// Delete a topic.
/// </summary>
public AzureEventgridTopicDeleteTask(string name = null , string resourceGroup = null)
{
WithArguments("az eventgrid topic delete");
WithArguments("--name");
if (!string.IsNullOrEmpty(name))
{
WithArguments(name);
}
WithArguments("--resource-group");
if (!string.IsNullOrEmpty(resourceGroup))
{
WithArguments(resourceGroup);
}
}
protected override string Description { get; set; }
}
}
| 24.921053 | 112 | 0.607181 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Eventgrid/AzureEventgridTopicDeleteTask.cs | 947 | C# |
namespace CodeProject.Business.Common.Automapper
{
using AutoMapper;
using CodeProject.StoreDB.Model.DTO;
using CodeProject.StoreDB.Model.Entities;
/// <summary>
/// Defines the <see cref="AutoMapperConfig" />
/// </summary>
public class AutoMapperConfig
{
// public static IMapper Mapper = new Mapper();
/// <summary>
/// The ConfigureAutoMapper
/// </summary>
public static void ConfigureAutoMapper()
{
#pragma warning disable CS0618 // Type or member is obsolete
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Product, ProductDTO>()
.ForMember(p => p.ID, opt => opt.MapFrom(pm => pm.ID))
.ForMember(x => x.CategoryName, opt => opt.Ignore());
cfg.CreateMap<ProductCategory, ProductCategoryDTO>()
.ForMember(p => p.ID, opt => opt.MapFrom(pm => pm.ID))
.ForMember(p => p.Name, opt => opt.MapFrom(pm => pm.Name));
cfg.CreateMap<PostCategory, PostCategoryDTO>()
.ForMember(p => p.ID, opt => opt.MapFrom(pm => pm.ID))
.ForMember(p => p.Name, opt => opt.MapFrom(pm => pm.Name));
cfg.CreateMap<Post, PostDTO>()
.ForMember(p => p.ID, opt => opt.MapFrom(pm => pm.ID))
.ForMember(x => x.CategoryName, opt => opt.Ignore());
cfg.CreateMap<Order, OrderDTO>()
.ForMember(p => p.ID, opt => opt.MapFrom(pm => pm.ID));
cfg.CreateMap<OrderDetail, OrderDetailDTO>()
.ForMember(p => p.OrderID, opt => opt.MapFrom(pm => pm.OrderID))
.ForMember(p => p.ProductID, opt => opt.MapFrom(pm => pm.ProductID))
.ForMember(p => p.ProductName, opt => opt.Ignore());
});
#pragma warning restore CS0618 // Type or member is obsolete
Mapper.AssertConfigurationIsValid();
}
}
}
| 38.403846 | 84 | 0.537807 | [
"Apache-2.0"
] | thanhntggsunday/CodePoject.SoreDB.API | CodeProject.StoreDB.Common/Automapper/AutoMapperConfig.cs | 1,999 | C# |
using Caf.Etl.Nodes.LoggerNet.Transform;
using System.Collections.Generic;
using Xunit;
using Caf.Etl.Models.CosmosDBSqlApi.Core;
using Caf.Etl.Models.LoggerNet.TOA5;
using System;
using Caf.Etl.Models.LoggerNet.TOA5.DataTables;
using Caf.Etl.Models.CosmosDBSqlApi.Measurement;
namespace Caf.Etl.Nodes.LoggerNet.Tests
{
public class DocumentDbMeasurementV1TransformerTests_Meteorology
{
[Fact]
public void ToMeasurement_ValidData_ReturnCorrectMeasurements()
{
//# Arrange
MeasurementV1 expectedMeasurement_RH_Avg = new MeasurementV1(
"EcTower_CookEast_RelativeHumidityTsAvg",
"CookEast_RelativeHumidityTsAvg_2017-06-20T11:30:00.0000000Z",
"Measurement",
"RelativeHumidityTsAvg",
"1.0.0",
"CafMeteorologyEcTower",
"", "", "", "", null,
"CookEast",
new LocationV1("Point", 46.78152, -117.08205),
new DateTime(2017, 6, 20, 11, 30, 0),
new List<PhysicalQuantityV1>() { new PhysicalQuantityV1(
(decimal)56.22676, "%", 0, 0, 0,
DateTime.MaxValue,
"DocumentDbMeasurementTransformer")});
MeasurementV1 expectedMeasurement_amb_tmpr_Avg = new MeasurementV1(
"EcTower_CookEast_TemperatureAirTsAvg",
"CookEast_TemperatureAirTsAvg_2017-06-20T11:30:00.0000000Z",
"Measurement",
"TemperatureAirTsAvg",
"1.0.0",
"CafMeteorologyEcTower",
"", "", "", "", null,
"CookEast",
new LocationV1("Point", 46.78152, -117.08205),
new DateTime(2017, 6, 20, 11, 30, 0),
new List<PhysicalQuantityV1>() { new PhysicalQuantityV1(
(decimal)4.940109, "C", 0, 0, 0,
DateTime.MaxValue,
"DocumentDbMeasurementTransformer")});
MeasurementV1 expectedMeasurement_PAR_density_Avg = new MeasurementV1(
"EcTower_CookEast_ParDensityTsAvg",
"CookEast_ParDensityTsAvg_2017-06-20T11:30:00.0000000Z",
"Measurement",
"ParDensityTsAvg",
"1.0.0",
"CafMeteorologyEcTower",
"", "", "", "", null,
"CookEast",
new LocationV1("Point", 46.78152, -117.08205),
new DateTime(2017, 6, 20, 11, 30, 0),
new List<PhysicalQuantityV1>() { new PhysicalQuantityV1(
(decimal)0.001956598, "mol/(m^2 s)", 0, 0, 0,
DateTime.MaxValue,
"DocumentDbMeasurementTransformer")});
List<MeasurementV1> actualMeasurements = new List<MeasurementV1>();
//# Act
Mappers.MapFromMeteorologyDataTableToCafStandards map =
new Mappers.MapFromMeteorologyDataTableToCafStandards();
DocumentDbMeasurementV1Transformer sut =
new DocumentDbMeasurementV1Transformer(map, "1.0.0");
actualMeasurements = sut.ToMeasurements(GetMockMeteorology());
//# Assert
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_RH_Avg.Name)
.PhysicalQuantities[0].Value,
expectedMeasurement_RH_Avg.PhysicalQuantities[0].Value);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_RH_Avg.Name)
.PhysicalQuantities[0].Unit,
expectedMeasurement_RH_Avg.PhysicalQuantities[0].Unit);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_amb_tmpr_Avg.Name)
.PhysicalQuantities[0].Value,
expectedMeasurement_amb_tmpr_Avg.PhysicalQuantities[0].Value);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_amb_tmpr_Avg.Name)
.PhysicalQuantities[0].Unit,
expectedMeasurement_amb_tmpr_Avg.PhysicalQuantities[0].Unit);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.PhysicalQuantities[0].Value,
expectedMeasurement_PAR_density_Avg.PhysicalQuantities[0].Value);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.ID,
expectedMeasurement_PAR_density_Avg.ID);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.FieldID,
expectedMeasurement_PAR_density_Avg.FieldID);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.Location.Coordinates[0],
expectedMeasurement_PAR_density_Avg.Location.Coordinates[0]);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.MetadataID,
expectedMeasurement_PAR_density_Avg.MetadataID);
Assert.Equal(
actualMeasurements
.Find(m => m.Name == expectedMeasurement_PAR_density_Avg.Name)
.SchemaVersion,
expectedMeasurement_PAR_density_Avg.SchemaVersion);
}
private TOA5 GetMockMeteorology()
{
TOA5 met = new TOA5();
met.Observations = new List<IObservation>();
met.Observations.Add(new Meteorology()
{
TIMESTAMP = new System.DateTime(2017, 6, 20, 11, 30, 00),
RECORD = 15,
amb_tmpr_Avg = 4.940109,
rslt_wnd_spd = 4.940109,
wnd_dir_compass = 259.7,
RH_Avg = 56.22676,
Precipitation_Tot = 0,
amb_press_Avg = 93.25672,
PAR_density_Avg = 1956.598,
batt_volt_Avg = 13.63667,
panel_tmpr_Avg = 25.22728,
std_wnd_dir = 14.26,
VPD_air = 1.244421,
Rn_meas_Avg = 643.2509
});
met.Metadata = new Metadata()
{
FileFormat = "TOA5",
StationName = "LTAR_CookEast",
DataLoggerType = "CR3000",
SerialNumber = 6503,
OperatingSystemVersion = "CR3000.Std.31",
DataloggerProgramName = "CPU:DEFAULT.CR3",
DataloggerProgramSignature = 13636,
TableName = "LTAR_Met",
Variables = new List<Variable>()
{
new Variable()
{
FieldName = "TIMESTAMP",
Units = "TS",
Processing = ""
},
new Variable()
{
FieldName = "RECORD",
Units = "",
Processing = ""
},
new Variable()
{
FieldName = "amb_tmpr_Avg",
Units = "C",
Processing = "Avg"
},
new Variable()
{
FieldName = "rslt_wnd_spd",
Units = "m/s",
Processing = "Smp"
},
new Variable()
{
FieldName = "wnd_dir_compass",
Units = "degrees",
Processing = "Smp"
},
new Variable()
{
FieldName = "RH_Avg",
Units = "%",
Processing = "Avg"
},
new Variable()
{
FieldName = "Precipitation_Tot",
Units = "mm",
Processing = "Tot"
},
new Variable()
{
FieldName = "amb_press_Avg",
Units = "kPa",
Processing = "Avg"
},
new Variable()
{
FieldName = "PAR_density_Avg",
Units = "umol/(s m^2)",
Processing = "Avg"
},
new Variable()
{
FieldName = "batt_volt_Avg",
Units = "V",
Processing = "Avg"
},
new Variable()
{
FieldName = "panel_tmpr_Avg",
Units = "C",
Processing = "Avg"
},
new Variable()
{
FieldName = "std_wnd_dir",
Units = "degrees",
Processing = "Smp"
},
new Variable()
{
FieldName = "VPD_air",
Units = "kpa",
Processing = "Smp"
},
new Variable()
{
FieldName = "Rn_meas_Avg",
Units = "W/m^2",
Processing = "Avg"
}
}
};
return met;
}
}
}
| 40.804688 | 83 | 0.441222 | [
"CC0-1.0"
] | benichka/Caf.Etl | Caf.Etl.UnitTests/Nodes/LoggerNet/DocumentDbMeasurementV1TransformerTests_Meteorology.cs | 10,448 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SampleSystem.Subscriptions.Metadata")]
[assembly: ComVisible(false)] | 32.6 | 65 | 0.803681 | [
"MIT"
] | Luxoft/BSSFramework | src/_SampleSystem/SampleSystem.Subscriptions.Metadata/Properties/AssemblyInfo.cs | 161 | C# |
using Grpc.Core;
using MagicOnion.Client;
using MagicOnion.CompilerServices; // require this using in AsyncMethodBuilder
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using MessagePack;
namespace MagicOnion
{
/// <summary>
/// Represents the result of a Unary call that wraps AsyncUnaryCall as Task-like.
/// </summary>
public static class UnaryResult
{
/// <summary>
/// Creates a <see cref="T:MagicOnion.UnaryResult`1" /> with the specified result.
/// </summary>
public static UnaryResult<T> FromResult<T>(T value)
=> new UnaryResult<T>(value);
/// <summary>
/// Creates a <see cref="T:MagicOnion.UnaryResult`1" /> with the specified result task.
/// </summary>
public static UnaryResult<T> FromResult<T>(Task<T> task)
=> new UnaryResult<T>(task);
/// <summary>
/// Gets the result that contains <see cref="F:MessagePack.Nil.Default"/> as the result value.
/// </summary>
public static UnaryResult<Nil> Nil
=> new UnaryResult<Nil>(MessagePack.Nil.Default);
}
/// <summary>
/// Represents the result of a Unary call that wraps AsyncUnaryCall as Task-like.
/// </summary>
#if NON_UNITY || (CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6)))
[AsyncMethodBuilder(typeof(AsyncUnaryResultMethodBuilder<>))]
#endif
public readonly struct UnaryResult<TResponse>
{
internal readonly bool hasRawValue; // internal
internal readonly TResponse rawValue; // internal
internal readonly Task<TResponse> rawTaskValue; // internal
readonly Task<IResponseContext<TResponse>> response;
public UnaryResult(TResponse rawValue)
{
this.hasRawValue = true;
this.rawValue = rawValue;
this.rawTaskValue = null;
this.response = null;
}
public UnaryResult(Task<TResponse> rawTaskValue)
{
this.hasRawValue = true;
this.rawValue = default(TResponse);
this.rawTaskValue = rawTaskValue;
this.response = null;
}
public UnaryResult(Task<IResponseContext<TResponse>> response)
{
this.hasRawValue = false;
this.rawValue = default(TResponse);
this.rawTaskValue = null;
this.response = response;
}
/// <summary>
/// Asynchronous call result.
/// </summary>
public Task<TResponse> ResponseAsync
{
get
{
if (!hasRawValue)
{
return UnwrapResponse();
}
else if (rawTaskValue != null)
{
return rawTaskValue;
}
else
{
return Task.FromResult(rawValue);
}
}
}
/// <summary>
/// Asynchronous access to response headers.
/// </summary>
public Task<Metadata> ResponseHeadersAsync
{
get
{
return UnwrapResponseHeaders();
}
}
async Task<TResponse> UnwrapResponse()
{
var ctx = await response.ConfigureAwait(false);
return await ctx.ResponseAsync.ConfigureAwait(false);
}
async Task<Metadata> UnwrapResponseHeaders()
{
var ctx = await response.ConfigureAwait(false);
return await ctx.ResponseHeadersAsync.ConfigureAwait(false);
}
async void UnwrapDispose()
{
try
{
var ctx = await response.ConfigureAwait(false);
ctx.Dispose();
}
catch
{
}
}
IResponseContext<TResponse> TryUnwrap()
{
if (!response.IsCompleted)
{
throw new InvalidOperationException("UnaryResult request is not yet completed, please await before call this.");
}
return response.Result;
}
/// <summary>
/// Allows awaiting this object directly.
/// </summary>
public TaskAwaiter<TResponse> GetAwaiter()
{
return ResponseAsync.GetAwaiter();
}
/// <summary>
/// Gets the call status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
return TryUnwrap().GetStatus();
}
/// <summary>
/// Gets the call trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
return TryUnwrap().GetTrailers();
}
/// <summary>
/// Provides means to cleanup after the call.
/// If the call has already finished normally (request stream has been completed and call result has been received), doesn't do anything.
/// Otherwise, requests cancellation of the call which should terminate all pending async operations associated with the call.
/// As a result, all resources being used by the call should be released eventually.
/// </summary>
/// <remarks>
/// Normally, there is no need for you to dispose the call unless you want to utilize the
/// "Cancel" semantics of invoking <c>Dispose</c>.
/// </remarks>
public void Dispose()
{
if (!response.IsCompleted)
{
UnwrapDispose();
}
else
{
response.Result.Dispose();
}
}
}
} | 31.37766 | 145 | 0.552467 | [
"MIT"
] | Cysharp/MagicOnion | src/MagicOnion.Abstractions/UnaryResult.cs | 5,899 | C# |
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
namespace WInterop.Storage
{
/// <summary>
/// [WIN32_FIND_DATA]
/// </summary>
/// <msdn><see cref="https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-_win32_find_dataa"/></msdn>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public readonly struct Win32FindData
{
public readonly AllFileAttributes FileAttributes;
public readonly FileTime CreationTime;
public readonly FileTime LastAccessTime;
public readonly FileTime LastWriteTime;
public readonly HighLowUlong FileSize;
public readonly ReparseTag ReparseTag; // dwReserved0
public readonly uint Reserved1;
private readonly FixedString.Size260 _cFileName;
private readonly FixedString.Size14 _cAlternateFileName;
public ReadOnlySpan<char> FileName => _cFileName.Buffer;
public ReadOnlySpan<char> AlternateFileName => _cAlternateFileName.Buffer;
}
} | 42.142857 | 130 | 0.727966 | [
"MIT"
] | JeremyKuhne/WInterop | src/WInterop.Desktop/Storage/Win32FindData.cs | 1,182 | C# |
using System.Collections.Generic;
namespace HotChocolate.Data.Neo4J.Language;
/// <summary>
/// A dedicated map expression.
/// </summary>
public class MapExpression
: TypedSubtree<Expression>
, ITypedSubtree
{
private MapExpression(List<Expression> expressions) : base(expressions)
{
}
public override ClauseKind Kind => ClauseKind.MapExpression;
public MapExpression AddEntries(IEnumerable<Expression> entries)
{
var newContent = new List<Expression>();
newContent.AddRange(Children);
newContent.AddRange(entries);
return new MapExpression(newContent);
}
protected override IVisitable PrepareVisit(Expression child) =>
Expressions.NameOrExpression(child);
public static MapExpression WithEntries(List<Expression> entries) =>
new(entries);
public static MapExpression Create(params object[] input)
{
Ensure.IsTrue(input.Length % 2 == 0, "Need an even number of input parameters");
var newContent = new List<Expression>();
var knownKeys = new HashSet<string>();
for (var i = 0; i < input.Length; i += 2)
{
var entry = new KeyValueMapEntry((string)input[i], (Expression)input[i + 1]);
newContent.Add(entry);
knownKeys.Add(entry.Key);
}
return new MapExpression(newContent);
}
} | 28.875 | 89 | 0.655844 | [
"MIT"
] | ChilliCream/prometheus | src/HotChocolate/Neo4J/src/Data/Language/MapExpression.cs | 1,386 | C# |
using System;
namespace Redux.Space
{
public struct Point
{
public int X, Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
public int Distance(Point to)
{
return Math.Max(Math.Abs(X - to.X), Math.Abs(Y - to.Y));
}
}
}
| 16.2 | 68 | 0.432099 | [
"MIT"
] | luckymouse0/Redux-Conquer-Online-Server | Redux/Space/Point.cs | 326 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace XurNightfaller
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
}
} | 25.894737 | 95 | 0.626016 | [
"BSD-3-Clause"
] | KiaArmani/XurSuite | Services/XurNightfaller/Program.cs | 492 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.SimpleEmail")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Simple Email Service. Amazon SES is an outbound-only email-sending service that provides an easy, cost-effective way for you to send email.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.101.157")] | 47 | 226 | 0.750665 | [
"Apache-2.0"
] | Melvinerall/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/SimpleEmail/Properties/AssemblyInfo.cs | 1,504 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Outputs.App.V1Alpha1
{
[OutputType]
public sealed class KogitoMgmtConsoleStatusConditions
{
public readonly string LastTransitionTime;
public readonly string Message;
/// <summary>
/// ReasonType is the type of reason
/// </summary>
public readonly string Reason;
public readonly string Status;
/// <summary>
/// ConditionType is the type of condition
/// </summary>
public readonly string Type;
[OutputConstructor]
private KogitoMgmtConsoleStatusConditions(
string lastTransitionTime,
string message,
string reason,
string status,
string type)
{
LastTransitionTime = lastTransitionTime;
Message = message;
Reason = reason;
Status = status;
Type = type;
}
}
}
| 25.854167 | 81 | 0.613215 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/kogito-operator/dotnet/Kubernetes/Crds/Operators/KogitoOperator/App/V1Alpha1/Outputs/KogitoMgmtConsoleStatusConditions.cs | 1,241 | C# |
using Harmony;
using System;
using MelonLoader;
using UnityEngine;
namespace MooseSatchelMod
{
internal static class Patches
{
// load and save custom data
[HarmonyPatch(typeof(SaveGameSystem), "RestoreGlobalData", new Type[] { typeof(string) })]
internal class SaveGameSystemPatch_RestoreGlobalData
{
internal static void Postfix(string name)
{
MooseSatchelMod.LoadData(name);
}
}
[HarmonyPatch(typeof(SaveGameSystem), "SaveGlobalData", new Type[] { typeof(SaveSlotType), typeof(string) })]
internal class SaveGameSystemPatch_SaveGlobalData
{
public static void Postfix(SaveSlotType gameMode, string name)
{
MooseSatchelMod.SaveData(gameMode, name);
}
}
[HarmonyPatch(typeof(Inventory), "AddGear")]
public class Invetory_AddGear
{
public static void Postfix(GameObject go)
{
//MelonLogger.Log("AddGear " + go.name);
GearItem gi = go.GetComponent<GearItem>();
if (gi.name == "GEAR_Gut" || MooseSatchelMod.isPerishableFood(gi))
{
MooseSatchelMod.addToBag(gi);
}
}
}
[HarmonyPatch(typeof(Inventory), "DestroyGear", typeof(GameObject))]
public class Invetory_DestroyGear
{
public static void Postfix(GameObject go)
{
//MelonLogger.Log("DestroyGear " + go.name);
GearItem gi = go.GetComponent<GearItem>();
if (gi.name == "GEAR_Gut" || MooseSatchelMod.isPerishableFood(gi))
{
MooseSatchelMod.removeFromBag(gi);
}
}
}
[HarmonyPatch(typeof(GearItem), "Drop")]
public class GearItem_Drop
{
public static void Postfix(GearItem __instance)
{
//MelonLogger.Log("Drop " + __instance.name);
if (__instance.name == "GEAR_Gut" || MooseSatchelMod.isPerishableFood(__instance))
{
MooseSatchelMod.removeFromBag(__instance);
}
}
}
[HarmonyPatch(typeof(PlayerManager), "PutOnClothingItem")]
public class PlayerManager_PutOnClothingItem
{
public static void Postfix(GearItem gi)
{
//MelonLogger.Log("PutOn " + gi.name);
if (gi.name == "GEAR_MooseHideBag")
{
MooseSatchelMod.putBag(gi);
}
}
}
[HarmonyPatch(typeof(PlayerManager), "TakeOffClothingItem")]
public class PlayerManager_TakeOffClothingItem
{
public static void Postfix(GearItem gi)
{
//MelonLogger.Log("TakeOff " + gi.name);
if (gi.name == "GEAR_MooseHideBag")
{
MooseSatchelMod.removeBag(gi);
}
}
}
[HarmonyPatch(typeof(ItemDescriptionPage), "BuildItemDescription")]
public class ItemDescriptionPage_BuildItemDescription
{
private static void Postfix(GearItem gi, ref string __result)
{
if ((gi.name == "GEAR_Gut" || MooseSatchelMod.isPerishableFood(gi)) && MooseSatchelMod.isBagged(gi))
{
//MelonLogger.Log("BagDesc " + gi.name);
__result += "\n(This item is in Moose bag)";
}
}
}
}
} | 33.072072 | 117 | 0.527104 | [
"MIT"
] | ttr/tld-MooseSatchelMod | src/Patches.cs | 3,671 | C# |
namespace AMSExplorer
{
partial class DRM_GenerateToken
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DRM_GenerateToken));
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonOk = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.labelstep = new System.Windows.Forms.Label();
this.openFileDialogPreset = new System.Windows.Forms.OpenFileDialog();
this.label8 = new System.Windows.Forms.Label();
this.numericUpDownTokenDuration = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.checkBoxTokenUse = new System.Windows.Forms.CheckBox();
this.numericUpDownTokenUse = new System.Windows.Forms.NumericUpDown();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownTokenDuration)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownTokenUse)).BeginInit();
this.SuspendLayout();
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// buttonOk
//
resources.ApplyResources(this.buttonOk, "buttonOk");
this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOk.Name = "buttonOk";
this.buttonOk.UseVisualStyleBackColor = true;
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.Control;
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(this.buttonOk);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// labelstep
//
resources.ApplyResources(this.labelstep, "labelstep");
this.labelstep.ForeColor = System.Drawing.Color.DarkBlue;
this.labelstep.Name = "labelstep";
//
// openFileDialogPreset
//
this.openFileDialogPreset.DefaultExt = "xml";
resources.ApplyResources(this.openFileDialogPreset, "openFileDialogPreset");
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// numericUpDownTokenDuration
//
resources.ApplyResources(this.numericUpDownTokenDuration, "numericUpDownTokenDuration");
this.numericUpDownTokenDuration.Maximum = new decimal(new int[] {
36500,
0,
0,
0});
this.numericUpDownTokenDuration.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownTokenDuration.Name = "numericUpDownTokenDuration";
this.numericUpDownTokenDuration.Value = new decimal(new int[] {
5,
0,
0,
0});
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// checkBoxTokenUse
//
resources.ApplyResources(this.checkBoxTokenUse, "checkBoxTokenUse");
this.checkBoxTokenUse.Name = "checkBoxTokenUse";
this.checkBoxTokenUse.UseVisualStyleBackColor = true;
this.checkBoxTokenUse.CheckedChanged += new System.EventHandler(this.CheckBoxTokenUse_CheckedChanged);
//
// numericUpDownTokenUse
//
resources.ApplyResources(this.numericUpDownTokenUse, "numericUpDownTokenUse");
this.numericUpDownTokenUse.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownTokenUse.Name = "numericUpDownTokenUse";
this.numericUpDownTokenUse.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// DRM_GenerateToken
//
this.AcceptButton = this.buttonOk;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Window;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.numericUpDownTokenUse);
this.Controls.Add(this.checkBoxTokenUse);
this.Controls.Add(this.label2);
this.Controls.Add(this.label8);
this.Controls.Add(this.numericUpDownTokenDuration);
this.Controls.Add(this.labelstep);
this.Controls.Add(this.panel1);
this.Name = "DRM_GenerateToken";
this.Load += new System.EventHandler(this.DRM_WidevineLicense_Load);
this.DpiChanged += new System.Windows.Forms.DpiChangedEventHandler(this.DRM_GenerateToken_DpiChanged);
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownTokenDuration)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownTokenUse)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.Button buttonOk;
public System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label labelstep;
private System.Windows.Forms.OpenFileDialog openFileDialogPreset;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.NumericUpDown numericUpDownTokenDuration;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.CheckBox checkBoxTokenUse;
private System.Windows.Forms.NumericUpDown numericUpDownTokenUse;
}
} | 43.059172 | 149 | 0.596537 | [
"Apache-2.0"
] | eaglezzb/Azure-Media-Services-Explorer | AMSExplorer/Forms-DynamicEncryption/DRM_GenerateToken.designer.cs | 7,279 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.PowerPointApi
{
///<summary>
/// DispatchInterface RulerLevels
/// SupportByVersion PowerPoint, 9,10,11,12,14,15
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff745509.aspx
///</summary>
[SupportByVersionAttribute("PowerPoint", 9,10,11,12,14,15)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class RulerLevels : Collection
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(RulerLevels);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public RulerLevels(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public RulerLevels(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff744009.aspx
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9,10,11,12,14,15)]
public NetOffice.PowerPointApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.PowerPointApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.PowerPointApi.Application.LateBindingApiWrapperType) as NetOffice.PowerPointApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15
/// Get
/// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff745406.aspx
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("PowerPoint", 9,10,11,12,14,15)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion PowerPoint 9, 10, 11, 12, 14, 15
///
/// </summary>
/// <param name="index">Int32 index</param>
[SupportByVersionAttribute("PowerPoint", 9,10,11,12,14,15)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")]
public NetOffice.PowerPointApi.RulerLevel this[Int32 index]
{
get
{
object[] paramsArray = Invoker.ValidateParamsArray(index);
object returnItem = Invoker.MethodReturn(this, "Item", paramsArray);
NetOffice.PowerPointApi.RulerLevel newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.PowerPointApi.RulerLevel.LateBindingApiWrapperType) as NetOffice.PowerPointApi.RulerLevel;
return newObject;
}
}
#endregion
#pragma warning restore
}
} | 35.451613 | 209 | 0.690264 | [
"MIT"
] | NetOffice/NetOffice | Source/PowerPoint/DispatchInterfaces/RulerLevels.cs | 5,495 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MatchGame
{
using System.Windows.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
int tenthsOfSecondsElapsed;
int matchesFound;
public MainWindow()
{
InitializeComponent();
timer.Interval = TimeSpan.FromSeconds(.1);
timer.Tick += Timer_Tick;
SetUpGame();
}
private void Timer_Tick(object sender, EventArgs e)
{
tenthsOfSecondsElapsed++;
timeTextBlock.Text = (tenthsOfSecondsElapsed / 10F).ToString("0.0s");
if (matchesFound == 8)
{
timer.Stop();
timeTextBlock.Text = timeTextBlock.Text + " - Play again?";
}
}
private void SetUpGame()
{
List<string> animalEmoji = new List<string>()
{
"🐙", "🐙",
"🐡", "🐡",
"🐘", "🐘",
"🐳", "🐳",
"🐪", "🐪",
"🦕", "🦕",
"🦘", "🦘",
"🦔", "🦔",
};
Random random = new Random();
foreach (TextBlock textBlock in mainGrid.Children.OfType<TextBlock>())
{
if (textBlock.Name != "timeTextBlock")
{
textBlock.Visibility = Visibility.Visible;
int index = random.Next(animalEmoji.Count);
string nextEmoji = animalEmoji[index];
textBlock.Text = nextEmoji;
animalEmoji.RemoveAt(index);
}
}
timer.Start();
tenthsOfSecondsElapsed = 0;
matchesFound = 0;
}
TextBlock lastTextBlockClicked;
bool findingMatch = false;
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBlock textBlock = sender as TextBlock;
if (findingMatch == false)
{
textBlock.Visibility = Visibility.Hidden;
lastTextBlockClicked = textBlock;
findingMatch = true;
}
else if (textBlock.Text == lastTextBlockClicked.Text)
{
matchesFound++;
textBlock.Visibility = Visibility.Hidden;
findingMatch = false;
}
else
{
lastTextBlockClicked.Visibility = Visibility.Visible;
findingMatch = false;
}
}
private void TimeTextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
if (matchesFound == 8)
{
SetUpGame();
}
}
}
}
| 28.163793 | 83 | 0.51056 | [
"MIT"
] | elGuille-info/Animal-MatchGame | MatchGame/MainWindow.xaml.cs | 3,317 | C# |
using System.Windows;
using GalaSoft.MvvmLight.Threading;
namespace KinectGestureExplorer
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
static App()
{
DispatcherHelper.Initialize();
}
}
}
| 18.294118 | 42 | 0.598071 | [
"MIT"
] | galendai/KinectHelper | KinectGestureExplorer/App.xaml.cs | 313 | C# |
namespace Application.Models.Dto
{
public class CityDto
{
public long Id { get; init; }
public string Name { get; init; }
public IList<StationDto> Stations { get; init; }
public CityDto(long id, string name)
{
Id = id;
Name = name;
Stations = new List<StationDto>();
}
public void AddStation(long id, string stationName, string gegrLat, string gegrLon, string addressStreet)
{
if (Stations.Any(n => n.Id == id))
return;
var result = new StationDto(id, stationName, gegrLat, gegrLon, addressStreet);
Stations.Add(result);
}
}
} | 28.08 | 113 | 0.545584 | [
"MIT"
] | komorowski-seba/QLApi | Hangfire/Application/Models/Dto/CityDto.cs | 704 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZaifNet
{
public enum CurrencyPairsEnum
{
None,
xem_btc,
bch_jpy,
fscc_btc,
sjcx_jpy,
bitcrystals_jpy,
xcp_jpy,
zaif_jpy,
mona_jpy,
btc_jpy,
jpyz_jpy,
eth_btc,
bch_btc,
cicc_jpy,
pepecash_jpy,
pepecash_btc,
xem_jpy,
erc20cms_jpy,
ncxc_btc,
eth_jpy,
mona_btc,
sjcx_btc,
xcp_btc,
mosaiccms_jpy,
fscc_jpy,
zaif_btc,
cicc_btc,
ncxc_jpy,
bitcrystals_btc,
}
}
| 17.883721 | 34 | 0.504551 | [
"MIT"
] | 0V/Zaif.NET | Zaif.NET/Objects/Enum/CurrencyPairs.cs | 771 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using KspNalCommon;
using static KspCraftOrganizer.RegisterToolbar;
namespace KspCraftOrganizer
{
public class FileLocationService
{
private static FileLocationService _instance;
public static FileLocationService instance
{
get
{
if (_instance == null)
{
_instance = new FileLocationService();
}
return _instance;
}
}
private IKspAl ksp = IKspAlProvider.instance;
public string getCraftSaveFilePathForCurrentShip()
{
return getCraftSaveFilePathForShipName(ksp.getCurrentCraftName());
}
public string getCraftSaveFilePathForShipName(string shipName)
{
return getCraftFilePathFromPathAndCraftName(getCraftSaveDirectory(), shipName);
}
private string getCraftFilePathFromPathAndCraftName(string path, string shipName)
{
//we do not use shipName directly because it may contain special characters. We use translated file name
// - the translation is done by KSP itself.
String kraftPathProvidedByKsp = ksp.getSavePathForCraftName(shipName);
String fileName = Path.GetFileName(kraftPathProvidedByKsp);
PluginLogger.logDebug("getCraftFilePathFromPathAndCraftName. Craft name: " + shipName + ", file path provided by KSP: " + kraftPathProvidedByKsp + ", final file name: " + fileName);
String finalPath = Path.Combine(path, fileName);
PluginLogger.logDebug("getCraftFilePathFromPathAndCraftName. Final path: " + finalPath);
return finalPath;
}
public string getCraftFileFilter()
{
return "*.craft";
}
public string[] getAllCraftFilesInDirectory(string directory)
{
return Directory.GetFiles(directory, getCraftFileFilter());
}
public List<string> getAllDirectoriesInDirectory(string directory)
{
var dirs = Directory.GetDirectories(directory);
List<string> l = new List<string>();
foreach (var d in dirs)
{
var d1 = d.Substring(directory.Length + 1);
l.Add(d1);
}
return l;
}
public string getCraftSaveDirectory()
{
return Path.Combine(ksp.getBaseCraftDirectory(), ksp.getCurrentEditorFacilityType().directoryName);
}
public string getCraftSettingsFileForCraftFile(string craftFile)
{
string saveFolder = "";
for (int dirCnt = 0; dirCnt < ksp.StockDirs().Length; dirCnt++)
{
if (isPathInside(craftFile, getStockCraftDirectoryForCraftType(CraftType.SPH, dirCnt)))
{
saveFolder = Globals.combinePaths(ksp.getApplicationRootPath(), "saves", ksp.getNameOfSaveFolder(), "stock_ships_settings", ksp.StockDirs()[dirCnt], CraftType.SPH.directoryName);
}
else if (isPathInside(craftFile, getStockCraftDirectoryForCraftType(CraftType.VAB, dirCnt)))
{
saveFolder = Globals.combinePaths(ksp.getApplicationRootPath(), "saves", ksp.getNameOfSaveFolder(), "stock_ships_settings", ksp.StockDirs()[dirCnt], CraftType.VAB.directoryName);
}
}
if (saveFolder == "")
{
saveFolder = Path.GetDirectoryName(craftFile);
}
return Path.Combine(saveFolder, Path.GetFileNameWithoutExtension(craftFile)) + ".crmgr";
}
public ICollection<string> getAvailableSaveNames()
{
string savesFolder = Globals.combinePaths(ksp.getApplicationRootPath(), "saves");
string[] directories = Directory.GetDirectories(savesFolder);
List<string> toRet = new List<string>();
foreach (string dir in directories)
{
if (Directory.Exists(Globals.combinePaths(dir, "Ships")) || Directory.Exists(Globals.combinePaths(dir, "Subassemblies")))
{
toRet.Add(Path.GetFileName(dir));
}
}
return toRet;
}
public string getCraftDirectoryForCraftType(string saveName, CraftType type)
{
if (type != CraftType.SUBASSEMBLY)
return Globals.combinePaths(ksp.getApplicationRootPath(), "saves", saveName, "Ships", type.directoryName);
else
return Globals.combinePaths(ksp.getApplicationRootPath(), "saves", saveName, "Subassemblies");
}
public string getStockCraftDirectoryForCraftType(CraftType type, int dirCnt)
{
if (type != CraftType.SUBASSEMBLY)
{
return Path.Combine(ksp.getStockCraftDirectory(dirCnt), type.directoryName);
}
else
return Globals.combinePaths(ksp.getApplicationRootPath(), "Subassemblies");
}
public string getProfileSettingsFile(string saveName)
{
return Globals.combinePaths(ksp.getApplicationRootPath(), "saves", saveName, "profile_settings.pcrmgr");
}
public string renameCraft(string oldFile, string newName)
{
PluginLogger.logDebug("renameCraft");
string newFile = getCraftFilePathFromPathAndCraftName(Path.GetDirectoryName(oldFile), newName);
File.Move(oldFile, newFile);
ksp.renameCraftInsideFile(newFile, newName);
string oldSettingsFile = getCraftSettingsFileForCraftFile(oldFile);
if (File.Exists(oldSettingsFile))
{
string newSettingsFile = getCraftSettingsFileForCraftFile(newFile);
PluginLogger.logDebug("renameCraft. Old settings file exists, renaming it. Old name: " + oldSettingsFile + ", new name: " + newSettingsFile);
File.Move(oldSettingsFile, newSettingsFile);
CraftSettingsDto craftSettings = ksp.readCraftSettings(newSettingsFile);
craftSettings.craftName = newName;
ksp.writeCraftSettings(newSettingsFile, craftSettings);
}
string oldThumbPath = getThumbPath(oldFile);
if (File.Exists(oldThumbPath))
{
string newThumbPath = getThumbPath(newFile);
PluginLogger.logDebug("renameCraft. Old thumb file exists, renaming it. Old name: " + oldThumbPath + ", new name: " + newThumbPath);
File.Move(oldThumbPath, newThumbPath);
}
return newFile;
}
internal void deleteCraft(string craftFile)
{
File.Delete(craftFile);
string settingsFile = getCraftSettingsFileForCraftFile(craftFile);
if (File.Exists(settingsFile))
{
File.Delete(settingsFile);
}
string thumbPath = getThumbPath(craftFile);
if (File.Exists(thumbPath))
{
File.Delete(thumbPath);
}
}
public string getThumbPath(string filePath)
{
string thumbUrl = getThumbUrl(filePath);
if (thumbUrl == "")
{
return "";
}
else
{
return Path.Combine(ksp.getApplicationRootPath(), thumbUrl.Substring(1)) + ".png";
}
}
public string getThumbUrl(string craftPath)
{
PluginLogger.logDebug(String.Format("getThumbUrl: craftPath {0}", craftPath));
for (int dirCnt = 0; dirCnt < ksp.StockDirs().Length; dirCnt++)
{
if (isPathInside(craftPath, getStockCraftDirectoryForCraftType(CraftType.SPH, dirCnt)))
{
return ksp.StockDirs()[dirCnt]+ "/@thumbs/SPH/" + Path.GetFileNameWithoutExtension(craftPath);
}
if (isPathInside(craftPath, getStockCraftDirectoryForCraftType(CraftType.VAB, dirCnt)))
{
return ksp.StockDirs()[dirCnt] + "/@thumbs/VAB/" + Path.GetFileNameWithoutExtension(craftPath);
}
if (isPathInside(craftPath, getStockCraftDirectoryForCraftType(CraftType.SUBASSEMBLY, dirCnt)))
{
return "/Subassemblies/@thumbs/" + Path.GetFileNameWithoutExtension(craftPath);
}
}
string saveName = extractSaveNameFromCraftPath(craftPath);
if (isPathInside(craftPath, getCraftDirectoryForCraftType(saveName, CraftType.SPH)))
{
return "/thumbs/" + saveName + "_SPH_" + Path.GetFileNameWithoutExtension(craftPath);
}
if (isPathInside(craftPath, getCraftDirectoryForCraftType(saveName, CraftType.VAB)))
{
return "/thumbs/" + saveName + "_VAB_" + Path.GetFileNameWithoutExtension(craftPath);
}
if (isPathInside(craftPath, getCraftDirectoryForCraftType(saveName, CraftType.SUBASSEMBLY)))
{
return "/thumbs/" + saveName + "_Subassemblies_" + Path.GetFileNameWithoutExtension(craftPath);
}
return "";
}
public bool isPathInside(String path, String pathSupposelyInside)
{
return Path.GetFullPath(path).StartsWith(Path.GetFullPath(pathSupposelyInside));
}
string extractSaveNameFromCraftPath(string craftPath)
{
string[] pathElements =
craftPath.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
if (pathElements.Length >= 4)
{
return pathElements[pathElements.Length - 4];
}
else
{
return "";
}
}
public string getAutoSaveShipPath()
{
return getCraftSaveFilePathForShipName(ksp.getAutoSaveCraftName());
}
public string getThisPluginDirectory()
{
return Globals.combinePaths(ksp.getApplicationRootPath(), "GameData", "KspCraftOrganizer");
}
public string getPluginSettingsPath()
{
return Path.Combine(getThisPluginDirectory(), "settings.conf");
}
}
}
| 39.510949 | 199 | 0.578607 | [
"MIT"
] | linuxgurugamer/ksp-craft-organizer | KspCraftOrganizerPlugin/Services2/FileLocationService.cs | 10,828 | C# |
using System;
namespace Standard
{
internal enum MSGFLTINFO
{
NONE,
ALREADYALLOWED_FORWND,
ALREADYDISALLOWED_FORWND,
ALLOWED_HIGHER
}
}
| 14 | 33 | 0.620879 | [
"MIT"
] | 5653325/HandyControl | src/Shared/Microsoft.Windows.Shell/Standard/MSGFLTINFO.cs | 184 | C# |
using System.Threading;
using System.Threading.Tasks;
using CCS.Application.Domains.Handlers;
using CCS.Application.Domains.Requests;
using Xunit;
namespace CCS.ApplicationTest.Domains.Handlers
{
public class WeatherForecastHandlerTest
{
[Fact(DisplayName = "何らかのレスポンスがある")]
public async Task Ok()
{
var request = new WeatherForecastRequest();
var handler = new WeatherForecastHandler();
var result = await handler.Handle(request, new CancellationToken());
Assert.NotNull(result);
Assert.True(result.Length > 0);
}
}
}
| 28.409091 | 80 | 0.6592 | [
"MIT"
] | cadcad-sat/LearningDDDProject | CCS.ApplicationTest/Domains/Handlers/WeatherForecastHandlerTest.cs | 651 | C# |
using Fur.DependencyInjection;
using Fur.Extensions;
using Fur.UnifyResult;
using Fur.Utilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Linq;
using System.Net.Mime;
namespace Fur.DataValidation
{
/// <summary>
/// 数据验证控制器
/// </summary>
[SkipScan]
public sealed class DataValidationFilter : IActionFilter, IOrderedFilter
{
/// <summary>
/// MiniProfiler 分类名
/// </summary>
private const string MiniProfilerCategory = "validation";
/// <summary>
/// 过滤器排序
/// </summary>
internal const int FilterOrder = -1000;
/// <summary>
/// 排序属性
/// </summary>
public int Order => FilterOrder;
/// <summary>
/// 是否时可重复使用的
/// </summary>
public static bool IsReusable => true;
/// <summary>
/// 动作方法执行之前操作
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{
// 排除 Mvc 视图
var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (typeof(Controller).IsAssignableFrom(actionDescriptor.ControllerTypeInfo)) return;
var method = actionDescriptor.MethodInfo;
var modelState = context.ModelState;
// 跳过验证类型
var nonValidationAttributeType = typeof(NonValidationAttribute);
// 如果贴了 [NonValidation] 特性 或 所在类型贴了 [NonValidation] 特性,则跳过验证
if (actionDescriptor.Parameters.Count == 0 ||
method.IsDefined(nonValidationAttributeType, true) ||
method.ReflectedType.IsDefined(nonValidationAttributeType, true))
{
// 打印验证跳过消息
App.PrintToMiniProfiler(MiniProfilerCategory, "Skipped");
return;
}
// 如果动作方法参数为 0 或 验证通过,则跳过,
if (modelState.IsValid)
{
// 打印验证成功消息
App.PrintToMiniProfiler(MiniProfilerCategory, "Successed");
return;
}
// 返回验证失败结果
if (context.Result == null && !modelState.IsValid)
{
// 设置验证失败结果
SetValidateFailedResult(context, modelState, actionDescriptor);
}
}
/// <summary>
/// 设置验证失败结果
/// </summary>
/// <param name="context">动作方法执行上下文</param>
/// <param name="modelState">模型验证状态</param>
/// <param name="actionDescriptor"></param>
private static void SetValidateFailedResult(ActionExecutingContext context, ModelStateDictionary modelState, ControllerActionDescriptor actionDescriptor)
{
// 将验证错误信息转换成字典并序列化成 Json
var validationResults = modelState.ToDictionary(u => !JsonSerializerUtility.EnabledPascalPropertyNaming ? u.Key.ToTitlePascal() : u.Key
, u => modelState[u.Key].Errors.Select(c => c.ErrorMessage));
var validateFaildMessage = JsonSerializerUtility.Serialize(validationResults);
// 判断是否跳过规范化结果
if (UnifyResultContext.IsSkipUnifyHandler(actionDescriptor.MethodInfo, out var unifyResult))
{
// 返回 400 错误
var result = new BadRequestObjectResult(modelState);
// 设置返回的响应类型
result.ContentTypes.Add(MediaTypeNames.Application.Json);
result.ContentTypes.Add(MediaTypeNames.Application.Xml);
context.Result = result;
}
else context.Result = unifyResult.OnValidateFailed(context, modelState, validationResults, validateFaildMessage);
// 打印验证失败信息
App.PrintToMiniProfiler(MiniProfilerCategory, "Failed", $"Validation Failed:\r\n{validateFaildMessage}", true);
}
/// <summary>
/// 动作方法执行完成操作
/// </summary>
/// <param name="context"></param>
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
} | 35.016529 | 161 | 0.588152 | [
"Apache-2.0"
] | LiveFly/Fur | framework/Fur/DataValidation/Filters/DataValidationFilter.cs | 4,643 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit.Sdk;
namespace EntropyTests
{
public static class TestServices
{
public static void LogResponseOnFailedAssert(this ILogger logger, HttpResponseMessage response, string responseText, Action assert)
{
try
{
assert();
}
catch (XunitException)
{
logger.LogWarning(response.ToString());
if (!string.IsNullOrEmpty(responseText))
{
logger.LogWarning(responseText);
}
throw;
}
}
public static async Task RunSiteTest(string siteName, ServerType serverType, RuntimeFlavor runtimeFlavor, RuntimeArchitecture architecture, string applicationBaseUrl,
Func<HttpClient, ILogger, CancellationToken, Task> validator)
{
var logger = new LoggerFactory()
.AddConsole()
.CreateLogger(string.Format("{0}:{1}:{2}:{3}", siteName, serverType, runtimeFlavor, architecture));
using (logger.BeginScope("RunSiteTest"))
{
var deploymentParameters = new DeploymentParameters(GetApplicationDirectory(siteName), serverType, runtimeFlavor, architecture)
{
ApplicationBaseUriHint = applicationBaseUrl,
SiteName = "HttpTestSite",
PublishApplicationBeforeDeployment = true,
TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
ApplicationType = runtimeFlavor == RuntimeFlavor.Clr ? ApplicationType.Standalone : ApplicationType.Portable
};
using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, logger))
{
var deploymentResult = deployer.Deploy();
var httpClientHandler = new HttpClientHandler();
var httpClient = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(deploymentResult.ApplicationBaseUri),
Timeout = TimeSpan.FromSeconds(10)
};
await validator(httpClient, logger, deploymentResult.HostShutdownToken);
}
}
}
public static string GetApplicationDirectory(string applicationName)
{
var solutionRoot = GetSolutionDirectory();
return Path.Combine(solutionRoot, "samples", applicationName);
}
public static string GetSolutionDirectory()
{
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFile = new FileInfo(Path.Combine(directoryInfo.FullName, "Entropy.sln"));
if (solutionFile.Exists)
{
return directoryInfo.FullName;
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be located using application root {applicationBasePath}.");
}
}
}
| 39.755319 | 174 | 0.598609 | [
"Apache-2.0"
] | andrewhoi/Entropy | test/FunctionalTests/TestServices.cs | 3,737 | C# |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
namespace AnalyzerRunner
{
public abstract class DiagnosticVisitor
{
public virtual void ProjectDiagnostics(Project originalProject, ImmutableArray<Diagnostic> diagnostics)
{
}
public virtual void AnalyzersFound(ImmutableArray<DiagnosticAnalyzer> analyzers)
{
}
}
} | 25.647059 | 111 | 0.727064 | [
"MIT"
] | twsouthwick/AnalyzerRunner | AnalyzerRunner/DiagnosticVisitor.cs | 438 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using NewLife.Collections;
using NewLife.Reflection;
namespace NewLife.Serialization
{
/// <summary>Json序列化</summary>
/// <remarks>
/// 文档 https://www.yuque.com/smartstone/nx/json
/// </remarks>
public class Json : FormatterBase, IJson
{
#region 属性
/// <summary>是否缩进</summary>
public Boolean Indented { get; set; }
/// <summary>处理器列表</summary>
public IList<IJsonHandler> Handlers { get; private set; }
#endregion
#region 构造
/// <summary>实例化</summary>
public Json()
{
UseProperty = true;
// 遍历所有处理器实现
var list = new List<IJsonHandler>
{
new JsonGeneral { Host = this },
new JsonComposite { Host = this },
new JsonArray { Host = this }
};
//list.Add(new JsonDictionary { Host = this });
// 根据优先级排序
list.Sort();
Handlers = list;
}
#endregion
#region 处理器
/// <summary>添加处理器</summary>
/// <param name="handler"></param>
/// <returns></returns>
public Json AddHandler(IJsonHandler handler)
{
if (handler != null)
{
handler.Host = this;
Handlers.Add(handler);
// 根据优先级排序
(Handlers as List<IJsonHandler>).Sort();
}
return this;
}
/// <summary>添加处理器</summary>
/// <typeparam name="THandler"></typeparam>
/// <param name="priority"></param>
/// <returns></returns>
public Json AddHandler<THandler>(Int32 priority = 0) where THandler : IJsonHandler, new()
{
var handler = new THandler
{
Host = this
};
if (priority != 0) handler.Priority = priority;
return AddHandler(handler);
}
/// <summary>获取处理器</summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetHandler<T>() where T : class, IJsonHandler
{
foreach (var item in Handlers)
{
if (item is T) return item as T;
}
return default;
}
#endregion
#region 写入
/// <summary>写入一个对象</summary>
/// <param name="value">目标对象</param>
/// <param name="type">类型</param>
/// <returns></returns>
[DebuggerHidden]
public virtual Boolean Write(Object value, Type type = null)
{
if (type == null)
{
if (value == null) return true;
type = value.GetType();
// 一般类型为空是顶级调用
if (Hosts.Count == 0 && Log != null && Log.Enable) WriteLog("JsonWrite {0} {1}", type.Name, value);
}
//foreach (var item in Handlers)
//{
// if (item.Write(value, type)) return true;
//}
var sb = Pool.StringBuilder.Get();
Write(sb, value);
Stream.Write(sb.Put(true).GetBytes());
return false;
}
/// <summary>写入字符串</summary>
/// <param name="value"></param>
public virtual void Write(String value)
{
//_builder.Append(value);
}
/// <summary>写入</summary>
/// <param name="sb"></param>
/// <param name="value"></param>
public virtual void Write(StringBuilder sb, Object value)
{
if (value == null) return;
var type = value.GetType();
foreach (var item in Handlers)
{
if (item.Write(value, type)) return;
}
}
#endregion
#region 读取
/// <summary>读取指定类型对象</summary>
/// <param name="type"></param>
/// <returns></returns>
[DebuggerHidden]
public virtual Object Read(Type type)
{
var value = type.CreateInstance();
if (!TryRead(type, ref value)) throw new Exception("读取失败!");
return value;
}
/// <summary>读取指定类型对象</summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[DebuggerHidden]
public T Read<T>() => (T)Read(typeof(T));
/// <summary>尝试读取指定类型对象</summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <returns></returns>
[DebuggerHidden]
public virtual Boolean TryRead(Type type, ref Object value)
{
if (Hosts.Count == 0 && Log != null && Log.Enable) WriteLog("JsonRead {0} {1}", type.Name, value);
foreach (var item in Handlers)
{
if (item.TryRead(type, ref value)) return true;
}
return false;
}
/// <summary>读取</summary>
/// <param name="value"></param>
/// <returns></returns>
public virtual Boolean Read(String value) => true;
/// <summary>读取字节</summary>
/// <returns></returns>
public virtual Byte ReadByte()
{
var b = Stream.ReadByte();
if (b < 0) throw new Exception("数据流超出范围!");
return (Byte)b;
}
#endregion
#region 辅助函数
#endregion
}
} | 28.688442 | 116 | 0.468033 | [
"MIT"
] | NewLifeX/X | NewLife.Core/Serialization/Json/Json.cs | 6,001 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VSTOSharedAddin
{
public partial class UserControlWinForm : UserControl
{
// My Code
private System.Windows.Forms.Timer refreshTimer = new System.Windows.Forms.Timer();
private void RefreshValues()
{
this.txtThreadAwareness.Text = DPIHelper.GetThreadDpiAwareness().ToString();
this.txtProcessAwareness.Text = DPIHelper.GetProcessDpi().ToString();
if (this.Handle != null)
{
Debug.WriteLine("Toplevel context window hwnd={0}", this.Handle);
this.txtTaskpaneWindowAwareness.Text =
DPIHelper.GetWindowDpiAwareness(this.Handle).ToString();
}
this.txtHostWindowAwareness.Text =
DPIHelper.GetWindowDpiAwareness((IntPtr)Globals.ThisAddIn.Application.Hwnd).ToString();
}
public UserControlWinForm()
{
InitializeComponent();
// Setup timer callback
//refreshTimer.Tick += (Object o, EventArgs e) => RefreshValues();
//refreshTimer.Interval = 1000;
}
private void btnSetThreadSA_Click(object sender, EventArgs e)
{
SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_SYSTEM_AWARE, false);
Globals.ThisAddIn.CreateTaskpaneInstance();
}
private void btnSetThreadPMA_Click(object sender, EventArgs e)
{
SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE);
}
private void btnSetThreadPMAV2_Click(object sender, EventArgs e)
{
SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
}
private void btnOpenNonModalSA_Click(object sender, EventArgs e)
{
SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_SYSTEM_AWARE, false);
Form f1 = new Form1();
f1.Show();
}
private void btnSetCWMM_Click(object sender, EventArgs e)
{
DPIHelper.SetChildWindowMixedMode(DPIHelper.DPI_HOSTING_BEHAVIOR.DPI_HOSTING_BEHAVIOR_MIXED);
MessageBox.Show(String.Format("DPI Hosting Behavior is {0}", DPIHelper.GetChildWindowMixedMode(this.Handle).ToString()));
}
private void btnRefreshValues_Click(object sender, EventArgs e)
{
RefreshValues();
}
private void AutoRefreshValues(bool start)
{
if (start)
{
refreshTimer.Start();
}
else
{
refreshTimer.Stop();
}
}
private void SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT newvalue)
{
SetThreadDPI(newvalue, true);
}
private void SetThreadDPI(DPIHelper.DPI_AWARENESS_CONTEXT newvalue, bool showMessage)
{
DPIHelper.DPI_AWARENESS_CONTEXT previous =
DPIHelper.SetThreadDpiAwareness(newvalue);
int processId = Process.GetCurrentProcess().Id;
int threadId = Thread.CurrentThread.ManagedThreadId;
if (showMessage)
{
MessageBox.Show(String.Format("DPI Awareness set to {0}, was {1}\nProcessId {2}, ThreadId {3}", newvalue, previous, processId, threadId));
}
}
private void chkAutoRefresh_Click(object sender, EventArgs e)
{
AutoRefreshValues(this.chkAutoRefresh.Checked);
}
private void btnRefresh_Click(object sender, EventArgs e)
{
RefreshValues();
}
private void setCWMMNormal_Click(object sender, EventArgs e)
{
DPIHelper.SetChildWindowMixedMode(DPIHelper.DPI_HOSTING_BEHAVIOR.DPI_HOSTING_BEHAVIOR_DEFAULT);
MessageBox.Show(String.Format("DPI Hosting Behavior is {0}", DPIHelper.GetChildWindowMixedMode(this.Handle).ToString()));
}
}
}
| 35.307692 | 154 | 0.626967 | [
"MIT"
] | 3v1lW1th1n/PnP-OfficeAddins | Samples/dynamic-dpi/VSTO SharedAddin/VSTOSharedAddin/UserControlWinForm.cs | 4,133 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("eMarket.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("eMarket.Core")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("29bd1f88-6bbd-42bd-8a90-27d9627eaab9")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.567568 | 99 | 0.762439 | [
"MIT"
] | vladhrapov/trainings | patterns_and_practices/materials/004_n-tier/e-market/src/eMarket.Core/Properties/AssemblyInfo.cs | 2,007 | C# |
using System.ComponentModel.Composition;
using System.Windows.Media;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace B2VS.Language.Buildfile
{
#region Format definition
/// <summary>
/// Defines the editor format for the buildfile keyword type.
/// </summary>
// seems like there's already a definition registered for 'keyword'
/* [Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "keyword")]
[Name("keyword")]
[UserVisible(false)]
[Order(Before = Priority.Default)]
internal sealed class KeywordFmt : ClassificationFormatDefinition
{
public KeywordFmt()
{
DisplayName = "keyword";
ForegroundColor = Colors.Blue;
}
}
*/
#endregion //Format definition
}
| 27.516129 | 71 | 0.68347 | [
"MIT"
] | build2/build2-vs | build2-VS/Language/Buildfile/BuildfileElementFormatting.cs | 855 | C# |
using System.Linq;
using Wordroller.Content.Lists;
using Wordroller.Content.Properties.Sections.PageSizes;
using Xunit;
using Xunit.Abstractions;
namespace Wordroller.Tests
{
public class NumberingTests : TestsBase
{
public NumberingTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
{
}
[Fact]
public void CreateList()
{
using var document = TestHelper.CreateNewDocument();
var section = document.Body.Sections.First();
var w = section.Properties.Size.WidthTw;
var h = section.Properties.Size.HeightTw;
section.Properties.Size.Orientation = PageOrientation.Landscape;
section.Properties.Size.WidthTw = h;
section.Properties.Size.HeightTw = w;
var firstDefinition = document.NumberingCollection.CreateListDefinition("Multi-level List", MultiLevelType.HybridMultiLevel, "41A6377C", "BB30A3F6");
firstDefinition.CreateLevel(0, 1, NumberFormat.Bullet, ListNumberAlignment.Left, 720, 360, "%1.", true, "0409000F");
firstDefinition.CreateLevel(1, 1, NumberFormat.Chicago, ListNumberAlignment.Left, 1440, 360, "%1.%2.", true, "04090019");
firstDefinition.CreateLevel(2, 1, NumberFormat.Decimal, ListNumberAlignment.Right, 2160, 180, "%1.%2.%3.", true, "0409001B");
firstDefinition.CreateLevel(3, 1, NumberFormat.None, ListNumberAlignment.Left, 2880, 360, "%1.%2.%3.%4.", true, "0409000F");
firstDefinition.CreateLevel(4, 1, NumberFormat.CardinalText, ListNumberAlignment.Left, 3600, 360, "%1.%2.%3.%4.%5.", true, "04090019");
firstDefinition.CreateLevel(5, 1, NumberFormat.LowerRoman, ListNumberAlignment.Right, 4320, 180, "%1.%2.%3.%4.%5.%6.", true, "0409001B");
firstDefinition.CreateLevel(6, 1, NumberFormat.DecimalZero, ListNumberAlignment.Left, 5040, 360, "%1.%2.%3.%4.%5.%6.%7.", true, "0409000F");
firstDefinition.CreateLevel(7, 1, NumberFormat.OrdinalText, ListNumberAlignment.Left, 5762, 360, "%1.%2.%3.%4.%5.%6.%7.%8.", true, "04090019");
firstDefinition.CreateLevel(8, 1, NumberFormat.DecimalEnclosedCircle, ListNumberAlignment.Right, 6480, 180, "%1.%2.%3.%4.%5.%6.%7.%8.%9.", true, "0409001B");
var listDefinitions = document.NumberingCollection.ListDefinitions.ToArray();
TestOutputHelper.WriteLine($"{listDefinitions.Length} list definitions total.");
foreach (var definition in listDefinitions)
{
TestOutputHelper.WriteLine(definition.Name);
foreach (var level in definition.Levels.Values)
{
TestOutputHelper.WriteLine($"{level.Level}: {level.Format}");
}
}
var listDefinition = document.NumberingCollection.ListDefinitions.First();
var list = document.NumberingCollection.CreateList(listDefinition);
var p0 = section.AppendParagraph("Level 0").IncludeIntoList(list, 0);
var p1 = section.AppendParagraph("Level 1").IncludeIntoList(list, 1);
var p2 = section.AppendParagraph("Level 2").IncludeIntoList(list, 2);
var p3 = section.AppendParagraph("Level 3").IncludeIntoList(list, 3);
var p4 = section.AppendParagraph("Level 4").IncludeIntoList(list, 4);
var p5 = section.AppendParagraph("Level 5").IncludeIntoList(list, 5);
var p6 = section.AppendParagraph("Level 6").IncludeIntoList(list, 6);
var p7 = section.AppendParagraph("Level 7").IncludeIntoList(list, 7);
var p8 = section.AppendParagraph("Level 8").IncludeIntoList(list, 8);
var p9 = section.AppendParagraph("Level 0").IncludeIntoList(list, 0);
p9.ExcludeFromList();
SaveTempDocument(document, "Lists_Multilevel.docx");
}
}
} | 48.138889 | 160 | 0.73341 | [
"Apache-2.0"
] | shestakov/wordroller | Wordroller.Tests/NumberingTests.cs | 3,468 | 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 Apollo.AdminStore.WebForm.Report {
public partial class report_orders {
/// <summary>
/// lblDateFrom 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 lblDateFrom;
/// <summary>
/// txtDateFrom 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.TextBox txtDateFrom;
/// <summary>
/// lblDateTo 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 lblDateTo;
/// <summary>
/// txtDateTo 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.TextBox txtDateTo;
/// <summary>
/// cbNonEU 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.CheckBox cbNonEU;
/// <summary>
/// ddlShowBy 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.DropDownList ddlShowBy;
/// <summary>
/// btnRefresh 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.LinkButton btnRefresh;
/// <summary>
/// gvOrdersByHour 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.GridView gvOrdersByHour;
/// <summary>
/// gvOrdersByDay 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.GridView gvOrdersByDay;
/// <summary>
/// gvOrdersByWeek 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.GridView gvOrdersByWeek;
/// <summary>
/// gvOrdersByMonth 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.GridView gvOrdersByMonth;
/// <summary>
/// gvOrdersByQuarter 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.GridView gvOrdersByQuarter;
/// <summary>
/// gvOrdersByYear 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.GridView gvOrdersByYear;
/// <summary>
/// gvOrdersSum 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.GridView gvOrdersSum;
}
}
| 35.43662 | 84 | 0.543919 | [
"MIT"
] | hancheester/apollo | Store Admin/Apollo.AdminStore.WebForm/Report/report_orders.aspx.designer.cs | 5,034 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using DSerfozo.CefGlue.Contract.Common;
using DSerfozo.CefGlue.Contract.Renderer;
using DSerfozo.RpcBindings.CefGlue.Common;
using DSerfozo.RpcBindings.CefGlue.Renderer.Handlers;
using DSerfozo.RpcBindings.CefGlue.Renderer.Services;
using DSerfozo.RpcBindings.CefGlue.Renderer.Util;
using static DSerfozo.CefGlue.Contract.Renderer.CefGlobals;
namespace DSerfozo.RpcBindings.CefGlue.Renderer
{
public class MessageRenderProcessHandler : ICefRenderProcessHandler
{
private readonly IDictionary<int, BrowserController> browsers = new Dictionary<int, BrowserController>();
private readonly ExtensionHandler handler;
private readonly string bindingExtensionName;
private readonly PromiseService promiseService;
public event EventHandler<ProcessMessageReceivedArgs> ProcessMessageReceived;
public MessageRenderProcessHandler(string bindingExtensionName)
{
this.bindingExtensionName = bindingExtensionName;
handler = new ExtensionHandler(browsers);
var promiseResults = Observable.FromEvent<PromiseResult>(h => handler.PromiseResult += h,
h => handler.PromiseResult -= h);
promiseService = new PromiseService(promiseResults);
}
public bool OnBeforeNavigation(ICefBrowser browser, ICefFrame frame, ICefRequest request, CefNavigationType navigation_type,
bool isRedirect)
{
if (browsers.TryGetValue(browser.Identifier, out var browserController))
{
browserController.OnBeforeNavigate(frame, request, navigation_type, isRedirect);
}
return false;
}
public void OnContextReleased(ICefBrowser browser, ICefFrame frame, ICefV8Context context)
{
if (browsers.TryGetValue(browser.Identifier, out var browserController))
{
browserController.OnContextReleased(frame, context);
}
}
public void OnBrowserCreated(ICefBrowser browser)
{
browsers.Add(browser.Identifier, new BrowserController(browser, promiseService));
}
public void OnBrowserDestroyed(ICefBrowser browser)
{
if (browsers.TryGetValue(browser.Identifier, out var browserController))
{
browsers.Remove(browser.Identifier);
browserController.Dispose();
}
}
public void OnContextCreated(ICefBrowser browser, ICefFrame frame, ICefV8Context context)
{
if (browsers.TryGetValue(browser.Identifier, out var browserController))
{
browserController.OnContextCreated(frame, context);
}
}
public void OnWebKitInitialized()
{
CefRuntime.RegisterExtension(bindingExtensionName,
EmbeddedResourceReader.Read(typeof(MessageRenderProcessHandler), "/Renderer/Javascript/extension.js"),
handler);
//base.OnWebKitInitialized();
}
public bool OnProcessMessageReceived(ICefBrowser browser, CefProcessId sourceProcess,
ICefProcessMessage message)
{
var handled = false;
if (browsers.TryGetValue(browser.Identifier, out var browserController))
{
handled = browserController.OnProcessMessage(message);
}
if (!handled)
{
var args = new ProcessMessageReceivedArgs(browser, message);
ProcessMessageReceived?.Invoke(this, args);
handled = args.Handled;
}
return handled;
}
private void HandlerOnInitialized(object sender, EventArgs eventArgs)
{
//handler.Initialized -= HandlerOnInitialized;
//promiseService = new PromiseService(handler.IsPromise, handler.WaitForPromise, handler.PromiseCreator,
// Observable.FromEvent<PromiseResult>(action => handler.PromiseResult += action,
// action => handler.PromiseResult -= action));
}
}
}
| 37.678571 | 132 | 0.653791 | [
"MIT"
] | rpc-bindings/cefglue | src/DSerfozo.RpcBindings.CefGlue/Renderer/MessageRenderProcessHandler.cs | 4,222 | C# |
using System;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public static partial class TdApi
{
/// <summary>
/// Represents a secret chat
/// </summary>
public partial class SecretChat : Object
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "secretChat";
/// <summary>
/// Extra data attached to the object
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
/// <summary>
/// Secret chat identifier
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// Identifier of the chat partner
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("user_id")]
public int UserId { get; set; }
/// <summary>
/// State of the secret chat
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("state")]
public SecretChatState State { get; set; }
/// <summary>
/// True, if the chat was created by the current user; otherwise false
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("is_outbound")]
public bool IsOutbound { get; set; }
/// <summary>
/// Current message Time To Live setting (self-destruct timer) for the chat, in seconds
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("ttl")]
public int Ttl { get; set; }
/// <summary>
/// Hash of the currently used key for comparison with the hash of the chat partner's key. This is a string of 36 little-endian bytes, which must be split into groups of 2 bits, each denoting a pixel of one of 4 colors FFFFFF, D5E6F3, 2D5775, and 2F99C9.
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("key_hash")]
public byte[] KeyHash { get; set; }
/// <summary>
/// Secret chat layer; determines features supported by the chat partner's application. Video notes are supported if the layer >= 66; nested text entities and underline and strikethrough entities are supported if the layer >= 101
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("layer")]
public int Layer { get; set; }
}
}
} | 36.346154 | 266 | 0.531217 | [
"MIT"
] | EgartSites/tdsharp | TDLib.Api/Objects/SecretChat.cs | 2,835 | C# |
#region License
// Copyright (c) 2020 Jens Eisenbach
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace BricklinkSharp.Client
{
[Serializable]
public class Category
{
[JsonPropertyName("category_id")]
public int CategoryId { get; set; }
[JsonPropertyName("category_name")]
public string Name { get; set; } = null!;
[JsonPropertyName("parent_id")]
public int ParentId { get; set; }
[JsonIgnore]
[IgnoreDataMember]
public bool IsRoot => ParentId == 0;
public override string ToString()
{
if (IsRoot)
{
return $"{CategoryId}-{Name} (root)";
}
return $"{CategoryId}-{Name} (parent ID {ParentId})";
}
}
}
| 33.016667 | 68 | 0.686017 | [
"MIT"
] | aalex675/BricklinkSharp | BricklinkSharp.Client/Category.cs | 1,983 | C# |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void generateHiddenNumber()
{
Random r = new Random();
Session["hiddenNumber"] = r.Next(100) + 1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
generateHiddenNumber();
}
}
protected void BVerify_Click(object sender, EventArgs e)
{
try
{
if (Session["hiddenNumber"] == null) generateHiddenNumber();
int hiddenNumber = (int)Session["hiddenNumber"];
int guessedNumber = int.Parse(TBNumber.Text);
if (guessedNumber == hiddenNumber)
{
LAnswer.Text = "You guessed right!";
BTryAgain.Visible = true;
}
else if (guessedNumber < hiddenNumber)
{
LAnswer.Text = "Hidden number is higher";
}
else
{
LAnswer.Text = "Hidden number is lower";
}
}
catch (Exception)
{
LAnswer.Text = "Not a number!";
}
}
protected void BTryAgain_Click(object sender, EventArgs e)
{
generateHiddenNumber();
TBNumber.Text = "";
LAnswer.Text = "";
BTryAgain.Visible = false;
}
}
| 24.569231 | 72 | 0.549155 | [
"CC0-1.0"
] | PavelClaudiuStefan/FMI | An_3_Semestru_1/DezvoltareAplicatiiWebC#/GuessGame/Default.aspx.cs | 1,597 | C# |
namespace AngleSharp.Core.Tests.Mocks
{
using AngleSharp.Dom;
using AngleSharp.Dom.Events;
using System;
using System.Collections.Generic;
class EventReceiver<TReceivingEvent>
where TReceivingEvent : Event
{
private readonly List<TReceivingEvent> _received = new List<TReceivingEvent>();
public EventReceiver(Action<DomEventHandler> addHandler)
{
addHandler((s, ev) =>
{
if (ev is TReceivingEvent data)
{
Receive(data);
}
});
}
public List<TReceivingEvent> Received => _received;
public Action<TReceivingEvent> OnReceived
{
get;
set;
}
private void Receive(TReceivingEvent data)
{
OnReceived?.Invoke(data);
_received.Add(data);
}
}
}
| 22.390244 | 87 | 0.539216 | [
"MIT"
] | Aizeren/AngleSharp | src/AngleSharp.Core.Tests/Mocks/EventReceiver.cs | 920 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Interception
{
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Data.Entity.TestHelpers;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Xunit;
internal static partial class TestHelper
{
internal static string CollapseWhitespace(this string value)
{
value = value.Replace(Environment.NewLine, " ").Replace("\t", " ");
while (value.Contains(" "))
value = value.Replace(" ", " ");
return value;
}
}
public class DatabaseLogFormatterTests : FunctionalTestBase
{
private readonly StringResourceVerifier _resourceVerifier = new StringResourceVerifier(
new AssemblyResourceLookup(EntityFrameworkAssembly, "System.Data.Entity.Properties.Resources"));
public DatabaseLogFormatterTests()
{
using (var context = new BlogContextNoInit())
{
context.Database.Initialize(force: false);
}
}
[Fact]
[UseDefaultExecutionStrategy]
public void Simple_query_and_update_commands_can_be_logged()
{
var log = new StringWriter();
using (var context = new BlogContextNoInit())
{
context.Database.Log = log.Write;
BlogContext.DoStuff(context);
}
var logLines = log.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
#if NET40
const int selectCount = 4;
const int updateCount = 0;
const int asyncCount = 0;
const int paramCount = 2;
const int imALoggerCount = 0;
const int transactionCount = 1;
const int connectionCount = 3;
#else
const int selectCount = 5;
const int updateCount = 1;
const int asyncCount = 2;
const int paramCount = 4;
const int imALoggerCount = 1;
const int transactionCount = 2;
const int connectionCount = 4;
#endif
Assert.Equal(selectCount, logLines.Count(l => l.ToUpperInvariant().StartsWith("SELECT")));
Assert.Equal(1, logLines.Count(l => l.ToUpperInvariant().StartsWith("INSERT")));
Assert.Equal(updateCount, logLines.Count(l => l.ToUpperInvariant().StartsWith("UPDATE")));
Assert.Equal(asyncCount, logLines.Count(l => _resourceVerifier.IsMatch("CommandLogAsync", l)));
Assert.Equal(paramCount, logLines.Count(l => l.StartsWith("-- @")));
Assert.Equal(1, logLines.Count(l => l.StartsWith("-- @") && l.Contains("'Throw it away...'")));
Assert.Equal(imALoggerCount, logLines.Count(l => l.StartsWith("-- @") && l.Contains("'I'm a logger and I'm okay...'")));
Assert.Equal(paramCount / 2, logLines.Count(l => l.StartsWith("-- @") && l.Contains("'1'")));
Assert.Equal(selectCount, logLines.Count(l => _resourceVerifier.IsMatch("CommandLogComplete", l, new AnyValueParameter(), "SqlDataReader", "")));
Assert.Equal(updateCount, logLines.Count(l => _resourceVerifier.IsMatch("CommandLogComplete", l, new AnyValueParameter(), "1", "")));
Assert.Equal(transactionCount, logLines.Count(l => _resourceVerifier.IsMatch("TransactionStartedLog", l, new AnyValueParameter(), "")));
Assert.Equal(transactionCount, logLines.Count(l => _resourceVerifier.IsMatch("TransactionDisposedLog", l, new AnyValueParameter(), "")));
Assert.Equal(connectionCount, logLines.Count(l => _resourceVerifier.IsMatch("ConnectionOpenedLog", l, new AnyValueParameter(), "")));
Assert.Equal(connectionCount, logLines.Count(l => _resourceVerifier.IsMatch("ConnectionClosedLog", l, new AnyValueParameter(), "")));
}
[Fact]
public void Commands_that_result_in_exceptions_are_still_logged()
{
Exception exception;
var log = new StringWriter();
using (var context = new BlogContextNoInit())
{
context.Database.Log = log.Write;
exception = Assert.Throws<SqlException>(() => context.Blogs.SqlQuery("select * from No.Chance").ToList());
}
var logLines = log.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Assert.Equal(7, logLines.Length);
Assert.Equal("select * from No.Chance", logLines[1]);
_resourceVerifier.VerifyMatch("CommandLogFailed", logLines[3], new AnyValueParameter(), exception.Message, "");
}
#if NET452
[Fact]
public void DatabaseLogFormatter_is_disposed_even_if_the_context_is_not()
{
CreateContext(out var weakDbContext, out var weakStringWriter);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weakDbContext.IsAlive);
DbDispatchersHelpers.AssertNoInterceptors();
// Need a second pass as the DatabaseLogFormatter is removed from the interceptors in the InternalContext finalizer
GC.Collect();
Assert.False(weakStringWriter.IsAlive);
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static void CreateContext(out WeakReference weakDbContext, out WeakReference weakStringWriter)
{
var log = new StringWriter();
var context = new BlogContextNoInit();
context.Database.Log = log.Write;
weakDbContext = new WeakReference(context);
weakStringWriter = new WeakReference(log);
}
#endif
#if !NET40
[Fact]
public void Async_commands_that_result_in_exceptions_are_still_logged()
{
Exception exception;
var log = new StringWriter();
using (var context = new BlogContextNoInit())
{
context.Database.Log = log.Write;
var query = context.Blogs.SqlQuery("select * from No.Chance").ToListAsync();
exception = Assert.Throws<AggregateException>(() => query.Wait()).InnerException;
}
var logLines = log.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Assert.Equal(7, logLines.Length);
Assert.Equal("select * from No.Chance", logLines[1]);
_resourceVerifier.VerifyMatch("CommandLogAsync", logLines[2], new AnyValueParameter(), "");
_resourceVerifier.VerifyMatch("CommandLogFailed", logLines[3], new AnyValueParameter(), exception.Message, "");
}
#endif
[Fact]
public void The_command_formatter_to_use_can_be_changed()
{
var log = new StringWriter();
try
{
MutableResolver.AddResolver<Func<DbContext, Action<string>, DatabaseLogFormatter>>(
k => (Func<DbContext, Action<string>, DatabaseLogFormatter>)((c, w) => new TestDatabaseLogFormatter(c, w)));
using (var context = new BlogContextNoInit())
{
context.Database.Log = log.Write;
var blog = context.Blogs.Single();
Assert.Equal("Half a Unicorn", blog.Title);
}
}
finally
{
MutableResolver.ClearResolvers();
}
var logLines = log.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
Assert.Equal(3, logLines.Length);
Assert.Equal(
"Context 'BlogContextNoInit' is executing command 'SELECT TOP (2) [c].[Id] AS [Id], [c].[Title] AS [Title] FROM [dbo].[Blogs] AS [c]'",
logLines[0]);
Assert.Equal(
"Context 'BlogContextNoInit' finished executing command",
logLines[1]);
}
public class TestDatabaseLogFormatter : DatabaseLogFormatter
{
public TestDatabaseLogFormatter(DbContext context, Action<string> writeAction)
: base(context, writeAction)
{
}
public override void LogCommand<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
Write(
string.Format(
CultureInfo.CurrentCulture,
"Context '{0}' is executing command '{1}'{2}",
Context.GetType().Name,
command.CommandText.CollapseWhitespace(), Environment.NewLine));
}
public override void LogResult<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{
Write(
string.Format(
CultureInfo.CurrentCulture, "Context '{0}' finished executing command{1}", Context.GetType().Name,
Environment.NewLine));
}
public override void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
public override void Closed(DbConnection connection, DbConnectionInterceptionContext interceptionContext)
{
}
}
}
}
| 41.399142 | 157 | 0.600249 | [
"Apache-2.0"
] | CZEMacLeod/EntityFramework6 | test/EntityFramework/FunctionalTests/Interception/DatabaseLogFormatterTests.cs | 9,648 | C# |
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Google;
using Owin;
using RinnaiPortal.Models;
namespace RinnaiPortal
{
public partial class Startup {
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Default.aspx"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
}
| 48.871429 | 160 | 0.670564 | [
"MIT"
] | systemgregorypc/Agatha-inteligencia-artificial- | agathaIA-voice/agathaiaportal/App_Start/Startup.Auth.cs | 3,423 | C# |
using XUCore.Template.EasyFreeSql.Core;
namespace XUCore.Template.EasyFreeSql.Applaction.User.User
{
/// <summary>
/// 登录记录
/// </summary>
public class UserLoginRecordDto : DtoBase<UserLoginRecordDto>
{
/// <summary>
/// 用户id
/// </summary>
public long UserId { get; set; }
/// <summary>
/// 登录方式
/// </summary>
public string LoginWay { get; set; }
/// <summary>
/// 登录时间
/// </summary>
public DateTime LoginTime { get; set; }
/// <summary>
/// 登录ip
/// </summary>
public string LoginIp { get; set; }
/// <summary>
/// 用户名字
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户手机
/// </summary>
public string Mobile { get; set; }
/// <summary>
/// 用户账号
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 用户头像
/// </summary>
public string Picture { get; set; }
}
}
| 24.545455 | 65 | 0.463889 | [
"MIT"
] | xuyiazl/XUCore.Template | XUCore.Template.EasyFreeSql/Content/XUCore.Template.EasyFreeSql/XUCore.Template.EasyFreeSql.Applaction/AppServices/User/User/Dtos/UserLoginRecordDto.cs | 1,146 | 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 ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the AttachVpnGateway operation.
/// Attaches a virtual private gateway to a VPC. For more information, see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html">Adding
/// a Hardware Virtual Private Gateway to Your VPC</a> in the <i>Amazon Virtual Private
/// Cloud User Guide</i>.
/// </summary>
public partial class AttachVpnGatewayRequest : AmazonEC2Request
{
private string _vpcId;
private string _vpnGatewayId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public AttachVpnGatewayRequest() { }
/// <summary>
/// Instantiates AttachVpnGatewayRequest with the parameterized properties
/// </summary>
/// <param name="vpnGatewayId">The ID of the virtual private gateway.</param>
/// <param name="vpcId">The ID of the VPC.</param>
public AttachVpnGatewayRequest(string vpnGatewayId, string vpcId)
{
_vpnGatewayId = vpnGatewayId;
_vpcId = vpcId;
}
/// <summary>
/// Gets and sets the property VpcId.
/// <para>
/// The ID of the VPC.
/// </para>
/// </summary>
public string VpcId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this._vpcId != null;
}
/// <summary>
/// Gets and sets the property VpnGatewayId.
/// <para>
/// The ID of the virtual private gateway.
/// </para>
/// </summary>
public string VpnGatewayId
{
get { return this._vpnGatewayId; }
set { this._vpnGatewayId = value; }
}
// Check to see if VpnGatewayId property is set
internal bool IsSetVpnGatewayId()
{
return this._vpnGatewayId != null;
}
}
} | 32.202128 | 162 | 0.620086 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/AttachVpnGatewayRequest.cs | 3,027 | 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.Kusto.V20190907
{
public static class ListDatabasePrincipals
{
/// <summary>
/// The list Kusto database principals operation response.
/// </summary>
public static Task<ListDatabasePrincipalsResult> InvokeAsync(ListDatabasePrincipalsArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<ListDatabasePrincipalsResult>("azure-native:kusto/v20190907:listDatabasePrincipals", args ?? new ListDatabasePrincipalsArgs(), options.WithVersion());
}
public sealed class ListDatabasePrincipalsArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the Kusto cluster.
/// </summary>
[Input("clusterName", required: true)]
public string ClusterName { get; set; } = null!;
/// <summary>
/// The name of the database in the Kusto cluster.
/// </summary>
[Input("databaseName", required: true)]
public string DatabaseName { get; set; } = null!;
/// <summary>
/// The name of the resource group containing the Kusto cluster.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public ListDatabasePrincipalsArgs()
{
}
}
[OutputType]
public sealed class ListDatabasePrincipalsResult
{
/// <summary>
/// The list of Kusto database principals.
/// </summary>
public readonly ImmutableArray<Outputs.DatabasePrincipalResponse> Value;
[OutputConstructor]
private ListDatabasePrincipalsResult(ImmutableArray<Outputs.DatabasePrincipalResponse> value)
{
Value = value;
}
}
}
| 33.079365 | 204 | 0.650192 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Kusto/V20190907/ListDatabasePrincipals.cs | 2,084 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Text;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math.EC
{
internal class LongArray
{
//private static long DEInterleave_MASK = 0x5555555555555555L;
/*
* This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits.
* In a binary field, this operation is the same as squaring an 8 bit number.
*/
private static readonly ushort[] INTERLEAVE2_TABLE = new ushort[]
{
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015,
0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055,
0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115,
0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155,
0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415,
0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455,
0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515,
0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555,
0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055,
0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115,
0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155,
0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415,
0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455,
0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515,
0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555,
0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015,
0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115,
0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155,
0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415,
0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455,
0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515,
0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555,
0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015,
0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055,
0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155,
0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415,
0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455,
0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515,
0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};
/*
* This expands 7 bit indices into 21 bit contents (high bit 18), by inserting 0s between bits.
*/
private static readonly int[] INTERLEAVE3_TABLE = new int[]
{
0x00000, 0x00001, 0x00008, 0x00009, 0x00040, 0x00041, 0x00048, 0x00049,
0x00200, 0x00201, 0x00208, 0x00209, 0x00240, 0x00241, 0x00248, 0x00249,
0x01000, 0x01001, 0x01008, 0x01009, 0x01040, 0x01041, 0x01048, 0x01049,
0x01200, 0x01201, 0x01208, 0x01209, 0x01240, 0x01241, 0x01248, 0x01249,
0x08000, 0x08001, 0x08008, 0x08009, 0x08040, 0x08041, 0x08048, 0x08049,
0x08200, 0x08201, 0x08208, 0x08209, 0x08240, 0x08241, 0x08248, 0x08249,
0x09000, 0x09001, 0x09008, 0x09009, 0x09040, 0x09041, 0x09048, 0x09049,
0x09200, 0x09201, 0x09208, 0x09209, 0x09240, 0x09241, 0x09248, 0x09249,
0x40000, 0x40001, 0x40008, 0x40009, 0x40040, 0x40041, 0x40048, 0x40049,
0x40200, 0x40201, 0x40208, 0x40209, 0x40240, 0x40241, 0x40248, 0x40249,
0x41000, 0x41001, 0x41008, 0x41009, 0x41040, 0x41041, 0x41048, 0x41049,
0x41200, 0x41201, 0x41208, 0x41209, 0x41240, 0x41241, 0x41248, 0x41249,
0x48000, 0x48001, 0x48008, 0x48009, 0x48040, 0x48041, 0x48048, 0x48049,
0x48200, 0x48201, 0x48208, 0x48209, 0x48240, 0x48241, 0x48248, 0x48249,
0x49000, 0x49001, 0x49008, 0x49009, 0x49040, 0x49041, 0x49048, 0x49049,
0x49200, 0x49201, 0x49208, 0x49209, 0x49240, 0x49241, 0x49248, 0x49249
};
/*
* This expands 8 bit indices into 32 bit contents (high bit 28), by inserting 0s between bits.
*/
private static readonly int[] INTERLEAVE4_TABLE = new int[]
{
0x00000000, 0x00000001, 0x00000010, 0x00000011, 0x00000100, 0x00000101, 0x00000110, 0x00000111,
0x00001000, 0x00001001, 0x00001010, 0x00001011, 0x00001100, 0x00001101, 0x00001110, 0x00001111,
0x00010000, 0x00010001, 0x00010010, 0x00010011, 0x00010100, 0x00010101, 0x00010110, 0x00010111,
0x00011000, 0x00011001, 0x00011010, 0x00011011, 0x00011100, 0x00011101, 0x00011110, 0x00011111,
0x00100000, 0x00100001, 0x00100010, 0x00100011, 0x00100100, 0x00100101, 0x00100110, 0x00100111,
0x00101000, 0x00101001, 0x00101010, 0x00101011, 0x00101100, 0x00101101, 0x00101110, 0x00101111,
0x00110000, 0x00110001, 0x00110010, 0x00110011, 0x00110100, 0x00110101, 0x00110110, 0x00110111,
0x00111000, 0x00111001, 0x00111010, 0x00111011, 0x00111100, 0x00111101, 0x00111110, 0x00111111,
0x01000000, 0x01000001, 0x01000010, 0x01000011, 0x01000100, 0x01000101, 0x01000110, 0x01000111,
0x01001000, 0x01001001, 0x01001010, 0x01001011, 0x01001100, 0x01001101, 0x01001110, 0x01001111,
0x01010000, 0x01010001, 0x01010010, 0x01010011, 0x01010100, 0x01010101, 0x01010110, 0x01010111,
0x01011000, 0x01011001, 0x01011010, 0x01011011, 0x01011100, 0x01011101, 0x01011110, 0x01011111,
0x01100000, 0x01100001, 0x01100010, 0x01100011, 0x01100100, 0x01100101, 0x01100110, 0x01100111,
0x01101000, 0x01101001, 0x01101010, 0x01101011, 0x01101100, 0x01101101, 0x01101110, 0x01101111,
0x01110000, 0x01110001, 0x01110010, 0x01110011, 0x01110100, 0x01110101, 0x01110110, 0x01110111,
0x01111000, 0x01111001, 0x01111010, 0x01111011, 0x01111100, 0x01111101, 0x01111110, 0x01111111,
0x10000000, 0x10000001, 0x10000010, 0x10000011, 0x10000100, 0x10000101, 0x10000110, 0x10000111,
0x10001000, 0x10001001, 0x10001010, 0x10001011, 0x10001100, 0x10001101, 0x10001110, 0x10001111,
0x10010000, 0x10010001, 0x10010010, 0x10010011, 0x10010100, 0x10010101, 0x10010110, 0x10010111,
0x10011000, 0x10011001, 0x10011010, 0x10011011, 0x10011100, 0x10011101, 0x10011110, 0x10011111,
0x10100000, 0x10100001, 0x10100010, 0x10100011, 0x10100100, 0x10100101, 0x10100110, 0x10100111,
0x10101000, 0x10101001, 0x10101010, 0x10101011, 0x10101100, 0x10101101, 0x10101110, 0x10101111,
0x10110000, 0x10110001, 0x10110010, 0x10110011, 0x10110100, 0x10110101, 0x10110110, 0x10110111,
0x10111000, 0x10111001, 0x10111010, 0x10111011, 0x10111100, 0x10111101, 0x10111110, 0x10111111,
0x11000000, 0x11000001, 0x11000010, 0x11000011, 0x11000100, 0x11000101, 0x11000110, 0x11000111,
0x11001000, 0x11001001, 0x11001010, 0x11001011, 0x11001100, 0x11001101, 0x11001110, 0x11001111,
0x11010000, 0x11010001, 0x11010010, 0x11010011, 0x11010100, 0x11010101, 0x11010110, 0x11010111,
0x11011000, 0x11011001, 0x11011010, 0x11011011, 0x11011100, 0x11011101, 0x11011110, 0x11011111,
0x11100000, 0x11100001, 0x11100010, 0x11100011, 0x11100100, 0x11100101, 0x11100110, 0x11100111,
0x11101000, 0x11101001, 0x11101010, 0x11101011, 0x11101100, 0x11101101, 0x11101110, 0x11101111,
0x11110000, 0x11110001, 0x11110010, 0x11110011, 0x11110100, 0x11110101, 0x11110110, 0x11110111,
0x11111000, 0x11111001, 0x11111010, 0x11111011, 0x11111100, 0x11111101, 0x11111110, 0x11111111
};
/*
* This expands 7 bit indices into 35 bit contents (high bit 30), by inserting 0s between bits.
*/
private static readonly int[] INTERLEAVE5_TABLE = new int[] {
0x00000000, 0x00000001, 0x00000020, 0x00000021, 0x00000400, 0x00000401, 0x00000420, 0x00000421,
0x00008000, 0x00008001, 0x00008020, 0x00008021, 0x00008400, 0x00008401, 0x00008420, 0x00008421,
0x00100000, 0x00100001, 0x00100020, 0x00100021, 0x00100400, 0x00100401, 0x00100420, 0x00100421,
0x00108000, 0x00108001, 0x00108020, 0x00108021, 0x00108400, 0x00108401, 0x00108420, 0x00108421,
0x02000000, 0x02000001, 0x02000020, 0x02000021, 0x02000400, 0x02000401, 0x02000420, 0x02000421,
0x02008000, 0x02008001, 0x02008020, 0x02008021, 0x02008400, 0x02008401, 0x02008420, 0x02008421,
0x02100000, 0x02100001, 0x02100020, 0x02100021, 0x02100400, 0x02100401, 0x02100420, 0x02100421,
0x02108000, 0x02108001, 0x02108020, 0x02108021, 0x02108400, 0x02108401, 0x02108420, 0x02108421,
0x40000000, 0x40000001, 0x40000020, 0x40000021, 0x40000400, 0x40000401, 0x40000420, 0x40000421,
0x40008000, 0x40008001, 0x40008020, 0x40008021, 0x40008400, 0x40008401, 0x40008420, 0x40008421,
0x40100000, 0x40100001, 0x40100020, 0x40100021, 0x40100400, 0x40100401, 0x40100420, 0x40100421,
0x40108000, 0x40108001, 0x40108020, 0x40108021, 0x40108400, 0x40108401, 0x40108420, 0x40108421,
0x42000000, 0x42000001, 0x42000020, 0x42000021, 0x42000400, 0x42000401, 0x42000420, 0x42000421,
0x42008000, 0x42008001, 0x42008020, 0x42008021, 0x42008400, 0x42008401, 0x42008420, 0x42008421,
0x42100000, 0x42100001, 0x42100020, 0x42100021, 0x42100400, 0x42100401, 0x42100420, 0x42100421,
0x42108000, 0x42108001, 0x42108020, 0x42108021, 0x42108400, 0x42108401, 0x42108420, 0x42108421
};
/*
* This expands 9 bit indices into 63 bit (long) contents (high bit 56), by inserting 0s between bits.
*/
private static readonly long[] INTERLEAVE7_TABLE = new long[]
{
0x0000000000000000L, 0x0000000000000001L, 0x0000000000000080L, 0x0000000000000081L,
0x0000000000004000L, 0x0000000000004001L, 0x0000000000004080L, 0x0000000000004081L,
0x0000000000200000L, 0x0000000000200001L, 0x0000000000200080L, 0x0000000000200081L,
0x0000000000204000L, 0x0000000000204001L, 0x0000000000204080L, 0x0000000000204081L,
0x0000000010000000L, 0x0000000010000001L, 0x0000000010000080L, 0x0000000010000081L,
0x0000000010004000L, 0x0000000010004001L, 0x0000000010004080L, 0x0000000010004081L,
0x0000000010200000L, 0x0000000010200001L, 0x0000000010200080L, 0x0000000010200081L,
0x0000000010204000L, 0x0000000010204001L, 0x0000000010204080L, 0x0000000010204081L,
0x0000000800000000L, 0x0000000800000001L, 0x0000000800000080L, 0x0000000800000081L,
0x0000000800004000L, 0x0000000800004001L, 0x0000000800004080L, 0x0000000800004081L,
0x0000000800200000L, 0x0000000800200001L, 0x0000000800200080L, 0x0000000800200081L,
0x0000000800204000L, 0x0000000800204001L, 0x0000000800204080L, 0x0000000800204081L,
0x0000000810000000L, 0x0000000810000001L, 0x0000000810000080L, 0x0000000810000081L,
0x0000000810004000L, 0x0000000810004001L, 0x0000000810004080L, 0x0000000810004081L,
0x0000000810200000L, 0x0000000810200001L, 0x0000000810200080L, 0x0000000810200081L,
0x0000000810204000L, 0x0000000810204001L, 0x0000000810204080L, 0x0000000810204081L,
0x0000040000000000L, 0x0000040000000001L, 0x0000040000000080L, 0x0000040000000081L,
0x0000040000004000L, 0x0000040000004001L, 0x0000040000004080L, 0x0000040000004081L,
0x0000040000200000L, 0x0000040000200001L, 0x0000040000200080L, 0x0000040000200081L,
0x0000040000204000L, 0x0000040000204001L, 0x0000040000204080L, 0x0000040000204081L,
0x0000040010000000L, 0x0000040010000001L, 0x0000040010000080L, 0x0000040010000081L,
0x0000040010004000L, 0x0000040010004001L, 0x0000040010004080L, 0x0000040010004081L,
0x0000040010200000L, 0x0000040010200001L, 0x0000040010200080L, 0x0000040010200081L,
0x0000040010204000L, 0x0000040010204001L, 0x0000040010204080L, 0x0000040010204081L,
0x0000040800000000L, 0x0000040800000001L, 0x0000040800000080L, 0x0000040800000081L,
0x0000040800004000L, 0x0000040800004001L, 0x0000040800004080L, 0x0000040800004081L,
0x0000040800200000L, 0x0000040800200001L, 0x0000040800200080L, 0x0000040800200081L,
0x0000040800204000L, 0x0000040800204001L, 0x0000040800204080L, 0x0000040800204081L,
0x0000040810000000L, 0x0000040810000001L, 0x0000040810000080L, 0x0000040810000081L,
0x0000040810004000L, 0x0000040810004001L, 0x0000040810004080L, 0x0000040810004081L,
0x0000040810200000L, 0x0000040810200001L, 0x0000040810200080L, 0x0000040810200081L,
0x0000040810204000L, 0x0000040810204001L, 0x0000040810204080L, 0x0000040810204081L,
0x0002000000000000L, 0x0002000000000001L, 0x0002000000000080L, 0x0002000000000081L,
0x0002000000004000L, 0x0002000000004001L, 0x0002000000004080L, 0x0002000000004081L,
0x0002000000200000L, 0x0002000000200001L, 0x0002000000200080L, 0x0002000000200081L,
0x0002000000204000L, 0x0002000000204001L, 0x0002000000204080L, 0x0002000000204081L,
0x0002000010000000L, 0x0002000010000001L, 0x0002000010000080L, 0x0002000010000081L,
0x0002000010004000L, 0x0002000010004001L, 0x0002000010004080L, 0x0002000010004081L,
0x0002000010200000L, 0x0002000010200001L, 0x0002000010200080L, 0x0002000010200081L,
0x0002000010204000L, 0x0002000010204001L, 0x0002000010204080L, 0x0002000010204081L,
0x0002000800000000L, 0x0002000800000001L, 0x0002000800000080L, 0x0002000800000081L,
0x0002000800004000L, 0x0002000800004001L, 0x0002000800004080L, 0x0002000800004081L,
0x0002000800200000L, 0x0002000800200001L, 0x0002000800200080L, 0x0002000800200081L,
0x0002000800204000L, 0x0002000800204001L, 0x0002000800204080L, 0x0002000800204081L,
0x0002000810000000L, 0x0002000810000001L, 0x0002000810000080L, 0x0002000810000081L,
0x0002000810004000L, 0x0002000810004001L, 0x0002000810004080L, 0x0002000810004081L,
0x0002000810200000L, 0x0002000810200001L, 0x0002000810200080L, 0x0002000810200081L,
0x0002000810204000L, 0x0002000810204001L, 0x0002000810204080L, 0x0002000810204081L,
0x0002040000000000L, 0x0002040000000001L, 0x0002040000000080L, 0x0002040000000081L,
0x0002040000004000L, 0x0002040000004001L, 0x0002040000004080L, 0x0002040000004081L,
0x0002040000200000L, 0x0002040000200001L, 0x0002040000200080L, 0x0002040000200081L,
0x0002040000204000L, 0x0002040000204001L, 0x0002040000204080L, 0x0002040000204081L,
0x0002040010000000L, 0x0002040010000001L, 0x0002040010000080L, 0x0002040010000081L,
0x0002040010004000L, 0x0002040010004001L, 0x0002040010004080L, 0x0002040010004081L,
0x0002040010200000L, 0x0002040010200001L, 0x0002040010200080L, 0x0002040010200081L,
0x0002040010204000L, 0x0002040010204001L, 0x0002040010204080L, 0x0002040010204081L,
0x0002040800000000L, 0x0002040800000001L, 0x0002040800000080L, 0x0002040800000081L,
0x0002040800004000L, 0x0002040800004001L, 0x0002040800004080L, 0x0002040800004081L,
0x0002040800200000L, 0x0002040800200001L, 0x0002040800200080L, 0x0002040800200081L,
0x0002040800204000L, 0x0002040800204001L, 0x0002040800204080L, 0x0002040800204081L,
0x0002040810000000L, 0x0002040810000001L, 0x0002040810000080L, 0x0002040810000081L,
0x0002040810004000L, 0x0002040810004001L, 0x0002040810004080L, 0x0002040810004081L,
0x0002040810200000L, 0x0002040810200001L, 0x0002040810200080L, 0x0002040810200081L,
0x0002040810204000L, 0x0002040810204001L, 0x0002040810204080L, 0x0002040810204081L,
0x0100000000000000L, 0x0100000000000001L, 0x0100000000000080L, 0x0100000000000081L,
0x0100000000004000L, 0x0100000000004001L, 0x0100000000004080L, 0x0100000000004081L,
0x0100000000200000L, 0x0100000000200001L, 0x0100000000200080L, 0x0100000000200081L,
0x0100000000204000L, 0x0100000000204001L, 0x0100000000204080L, 0x0100000000204081L,
0x0100000010000000L, 0x0100000010000001L, 0x0100000010000080L, 0x0100000010000081L,
0x0100000010004000L, 0x0100000010004001L, 0x0100000010004080L, 0x0100000010004081L,
0x0100000010200000L, 0x0100000010200001L, 0x0100000010200080L, 0x0100000010200081L,
0x0100000010204000L, 0x0100000010204001L, 0x0100000010204080L, 0x0100000010204081L,
0x0100000800000000L, 0x0100000800000001L, 0x0100000800000080L, 0x0100000800000081L,
0x0100000800004000L, 0x0100000800004001L, 0x0100000800004080L, 0x0100000800004081L,
0x0100000800200000L, 0x0100000800200001L, 0x0100000800200080L, 0x0100000800200081L,
0x0100000800204000L, 0x0100000800204001L, 0x0100000800204080L, 0x0100000800204081L,
0x0100000810000000L, 0x0100000810000001L, 0x0100000810000080L, 0x0100000810000081L,
0x0100000810004000L, 0x0100000810004001L, 0x0100000810004080L, 0x0100000810004081L,
0x0100000810200000L, 0x0100000810200001L, 0x0100000810200080L, 0x0100000810200081L,
0x0100000810204000L, 0x0100000810204001L, 0x0100000810204080L, 0x0100000810204081L,
0x0100040000000000L, 0x0100040000000001L, 0x0100040000000080L, 0x0100040000000081L,
0x0100040000004000L, 0x0100040000004001L, 0x0100040000004080L, 0x0100040000004081L,
0x0100040000200000L, 0x0100040000200001L, 0x0100040000200080L, 0x0100040000200081L,
0x0100040000204000L, 0x0100040000204001L, 0x0100040000204080L, 0x0100040000204081L,
0x0100040010000000L, 0x0100040010000001L, 0x0100040010000080L, 0x0100040010000081L,
0x0100040010004000L, 0x0100040010004001L, 0x0100040010004080L, 0x0100040010004081L,
0x0100040010200000L, 0x0100040010200001L, 0x0100040010200080L, 0x0100040010200081L,
0x0100040010204000L, 0x0100040010204001L, 0x0100040010204080L, 0x0100040010204081L,
0x0100040800000000L, 0x0100040800000001L, 0x0100040800000080L, 0x0100040800000081L,
0x0100040800004000L, 0x0100040800004001L, 0x0100040800004080L, 0x0100040800004081L,
0x0100040800200000L, 0x0100040800200001L, 0x0100040800200080L, 0x0100040800200081L,
0x0100040800204000L, 0x0100040800204001L, 0x0100040800204080L, 0x0100040800204081L,
0x0100040810000000L, 0x0100040810000001L, 0x0100040810000080L, 0x0100040810000081L,
0x0100040810004000L, 0x0100040810004001L, 0x0100040810004080L, 0x0100040810004081L,
0x0100040810200000L, 0x0100040810200001L, 0x0100040810200080L, 0x0100040810200081L,
0x0100040810204000L, 0x0100040810204001L, 0x0100040810204080L, 0x0100040810204081L,
0x0102000000000000L, 0x0102000000000001L, 0x0102000000000080L, 0x0102000000000081L,
0x0102000000004000L, 0x0102000000004001L, 0x0102000000004080L, 0x0102000000004081L,
0x0102000000200000L, 0x0102000000200001L, 0x0102000000200080L, 0x0102000000200081L,
0x0102000000204000L, 0x0102000000204001L, 0x0102000000204080L, 0x0102000000204081L,
0x0102000010000000L, 0x0102000010000001L, 0x0102000010000080L, 0x0102000010000081L,
0x0102000010004000L, 0x0102000010004001L, 0x0102000010004080L, 0x0102000010004081L,
0x0102000010200000L, 0x0102000010200001L, 0x0102000010200080L, 0x0102000010200081L,
0x0102000010204000L, 0x0102000010204001L, 0x0102000010204080L, 0x0102000010204081L,
0x0102000800000000L, 0x0102000800000001L, 0x0102000800000080L, 0x0102000800000081L,
0x0102000800004000L, 0x0102000800004001L, 0x0102000800004080L, 0x0102000800004081L,
0x0102000800200000L, 0x0102000800200001L, 0x0102000800200080L, 0x0102000800200081L,
0x0102000800204000L, 0x0102000800204001L, 0x0102000800204080L, 0x0102000800204081L,
0x0102000810000000L, 0x0102000810000001L, 0x0102000810000080L, 0x0102000810000081L,
0x0102000810004000L, 0x0102000810004001L, 0x0102000810004080L, 0x0102000810004081L,
0x0102000810200000L, 0x0102000810200001L, 0x0102000810200080L, 0x0102000810200081L,
0x0102000810204000L, 0x0102000810204001L, 0x0102000810204080L, 0x0102000810204081L,
0x0102040000000000L, 0x0102040000000001L, 0x0102040000000080L, 0x0102040000000081L,
0x0102040000004000L, 0x0102040000004001L, 0x0102040000004080L, 0x0102040000004081L,
0x0102040000200000L, 0x0102040000200001L, 0x0102040000200080L, 0x0102040000200081L,
0x0102040000204000L, 0x0102040000204001L, 0x0102040000204080L, 0x0102040000204081L,
0x0102040010000000L, 0x0102040010000001L, 0x0102040010000080L, 0x0102040010000081L,
0x0102040010004000L, 0x0102040010004001L, 0x0102040010004080L, 0x0102040010004081L,
0x0102040010200000L, 0x0102040010200001L, 0x0102040010200080L, 0x0102040010200081L,
0x0102040010204000L, 0x0102040010204001L, 0x0102040010204080L, 0x0102040010204081L,
0x0102040800000000L, 0x0102040800000001L, 0x0102040800000080L, 0x0102040800000081L,
0x0102040800004000L, 0x0102040800004001L, 0x0102040800004080L, 0x0102040800004081L,
0x0102040800200000L, 0x0102040800200001L, 0x0102040800200080L, 0x0102040800200081L,
0x0102040800204000L, 0x0102040800204001L, 0x0102040800204080L, 0x0102040800204081L,
0x0102040810000000L, 0x0102040810000001L, 0x0102040810000080L, 0x0102040810000081L,
0x0102040810004000L, 0x0102040810004001L, 0x0102040810004080L, 0x0102040810004081L,
0x0102040810200000L, 0x0102040810200001L, 0x0102040810200080L, 0x0102040810200081L,
0x0102040810204000L, 0x0102040810204001L, 0x0102040810204080L, 0x0102040810204081L
};
// For toString(); must have length 64
private const string ZEROES = "0000000000000000000000000000000000000000000000000000000000000000";
internal static readonly byte[] BitLengths =
{
0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
};
// TODO make m fixed for the LongArray, and hence compute T once and for all
private long[] m_ints;
public LongArray(int intLen)
{
m_ints = new long[intLen];
}
public LongArray(long[] ints)
{
m_ints = ints;
}
public LongArray(long[] ints, int off, int len)
{
if (off == 0 && len == ints.Length)
{
m_ints = ints;
}
else
{
m_ints = new long[len];
Array.Copy(ints, off, m_ints, 0, len);
}
}
public LongArray(BigInteger bigInt)
{
if (bigInt == null || bigInt.SignValue < 0)
{
throw new ArgumentException("invalid F2m field value", "bigInt");
}
if (bigInt.SignValue == 0)
{
m_ints = new long[] { 0L };
return;
}
byte[] barr = bigInt.ToByteArray();
int barrLen = barr.Length;
int barrStart = 0;
if (barr[0] == 0)
{
// First byte is 0 to enforce highest (=sign) bit is zero.
// In this case ignore barr[0].
barrLen--;
barrStart = 1;
}
int intLen = (barrLen + 7) / 8;
m_ints = new long[intLen];
int iarrJ = intLen - 1;
int rem = barrLen % 8 + barrStart;
long temp = 0;
int barrI = barrStart;
if (barrStart < rem)
{
for (; barrI < rem; barrI++)
{
temp <<= 8;
uint barrBarrI = barr[barrI];
temp |= barrBarrI;
}
m_ints[iarrJ--] = temp;
}
for (; iarrJ >= 0; iarrJ--)
{
temp = 0;
for (int i = 0; i < 8; i++)
{
temp <<= 8;
uint barrBarrI = barr[barrI++];
temp |= barrBarrI;
}
m_ints[iarrJ] = temp;
}
}
public bool IsOne()
{
long[] a = m_ints;
if (a[0] != 1L)
{
return false;
}
for (int i = 1; i < a.Length; ++i)
{
if (a[i] != 0L)
{
return false;
}
}
return true;
}
public bool IsZero()
{
long[] a = m_ints;
for (int i = 0; i < a.Length; ++i)
{
if (a[i] != 0L)
{
return false;
}
}
return true;
}
public int GetUsedLength()
{
return GetUsedLengthFrom(m_ints.Length);
}
public int GetUsedLengthFrom(int from)
{
long[] a = m_ints;
from = System.Math.Min(from, a.Length);
if (from < 1)
{
return 0;
}
// Check if first element will act as sentinel
if (a[0] != 0)
{
while (a[--from] == 0)
{
}
return from + 1;
}
do
{
if (a[--from] != 0)
{
return from + 1;
}
}
while (from > 0);
return 0;
}
public int Degree()
{
int i = m_ints.Length;
long w;
do
{
if (i == 0)
{
return 0;
}
w = m_ints[--i];
}
while (w == 0);
return (i << 6) + BitLength(w);
}
private int DegreeFrom(int limit)
{
int i = (int)(((uint)limit + 62) >> 6);
long w;
do
{
if (i == 0)
{
return 0;
}
w = m_ints[--i];
}
while (w == 0);
return (i << 6) + BitLength(w);
}
// private int lowestCoefficient()
// {
// for (int i = 0; i < m_ints.Length; ++i)
// {
// long mi = m_ints[i];
// if (mi != 0)
// {
// int j = 0;
// while ((mi & 0xFFL) == 0)
// {
// j += 8;
// mi >>>= 8;
// }
// while ((mi & 1L) == 0)
// {
// ++j;
// mi >>>= 1;
// }
// return (i << 6) + j;
// }
// }
// return -1;
// }
private static int BitLength(long w)
{
int u = (int)((ulong)w >> 32), b;
if (u == 0)
{
u = (int)w;
b = 0;
}
else
{
b = 32;
}
int t = (int)((uint)u >> 16), k;
if (t == 0)
{
t = (int)((uint)u >> 8);
k = (t == 0) ? BitLengths[u] : 8 + BitLengths[t];
}
else
{
int v = (int)((uint)t >> 8);
k = (v == 0) ? 16 + BitLengths[t] : 24 + BitLengths[v];
}
return b + k;
}
private long[] ResizedInts(int newLen)
{
long[] newInts = new long[newLen];
Array.Copy(m_ints, 0, newInts, 0, System.Math.Min(m_ints.Length, newLen));
return newInts;
}
public BigInteger ToBigInteger()
{
int usedLen = GetUsedLength();
if (usedLen == 0)
{
return BigInteger.Zero;
}
long highestInt = m_ints[usedLen - 1];
byte[] temp = new byte[8];
int barrI = 0;
bool trailingZeroBytesDone = false;
for (int j = 7; j >= 0; j--)
{
byte thisByte = (byte)((ulong)highestInt >> (8 * j));
if (trailingZeroBytesDone || (thisByte != 0))
{
trailingZeroBytesDone = true;
temp[barrI++] = thisByte;
}
}
int barrLen = 8 * (usedLen - 1) + barrI;
byte[] barr = new byte[barrLen];
for (int j = 0; j < barrI; j++)
{
barr[j] = temp[j];
}
// Highest value int is done now
for (int iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--)
{
long mi = m_ints[iarrJ];
for (int j = 7; j >= 0; j--)
{
barr[barrI++] = (byte)((ulong)mi >> (8 * j));
}
}
return new BigInteger(1, barr);
}
// private static long shiftUp(long[] x, int xOff, int count)
// {
// long prev = 0;
// for (int i = 0; i < count; ++i)
// {
// long next = x[xOff + i];
// x[xOff + i] = (next << 1) | prev;
// prev = next >>> 63;
// }
// return prev;
// }
private static long ShiftUp(long[] x, int xOff, int count, int shift)
{
int shiftInv = 64 - shift;
long prev = 0;
for (int i = 0; i < count; ++i)
{
long next = x[xOff + i];
x[xOff + i] = (next << shift) | prev;
prev = (long)((ulong)next >> shiftInv);
}
return prev;
}
private static long ShiftUp(long[] x, int xOff, long[] z, int zOff, int count, int shift)
{
int shiftInv = 64 - shift;
long prev = 0;
for (int i = 0; i < count; ++i)
{
long next = x[xOff + i];
z[zOff + i] = (next << shift) | prev;
prev = (long)((ulong)next >> shiftInv);
}
return prev;
}
public LongArray AddOne()
{
if (m_ints.Length == 0)
{
return new LongArray(new long[]{ 1L });
}
int resultLen = System.Math.Max(1, GetUsedLength());
long[] ints = ResizedInts(resultLen);
ints[0] ^= 1L;
return new LongArray(ints);
}
// private void addShiftedByBits(LongArray other, int bits)
// {
// int words = bits >>> 6;
// int shift = bits & 0x3F;
//
// if (shift == 0)
// {
// addShiftedByWords(other, words);
// return;
// }
//
// int otherUsedLen = other.GetUsedLength();
// if (otherUsedLen == 0)
// {
// return;
// }
//
// int minLen = otherUsedLen + words + 1;
// if (minLen > m_ints.Length)
// {
// m_ints = resizedInts(minLen);
// }
//
// long carry = addShiftedByBits(m_ints, words, other.m_ints, 0, otherUsedLen, shift);
// m_ints[otherUsedLen + words] ^= carry;
// }
private void AddShiftedByBitsSafe(LongArray other, int otherDegree, int bits)
{
int otherLen = (int)((uint)(otherDegree + 63) >> 6);
int words = (int)((uint)bits >> 6);
int shift = bits & 0x3F;
if (shift == 0)
{
Add(m_ints, words, other.m_ints, 0, otherLen);
return;
}
long carry = AddShiftedUp(m_ints, words, other.m_ints, 0, otherLen, shift);
if (carry != 0L)
{
m_ints[otherLen + words] ^= carry;
}
}
private static long AddShiftedUp(long[] x, int xOff, long[] y, int yOff, int count, int shift)
{
int shiftInv = 64 - shift;
long prev = 0;
for (int i = 0; i < count; ++i)
{
long next = y[yOff + i];
x[xOff + i] ^= (next << shift) | prev;
prev = (long)((ulong)next >> shiftInv);
}
return prev;
}
private static long AddShiftedDown(long[] x, int xOff, long[] y, int yOff, int count, int shift)
{
int shiftInv = 64 - shift;
long prev = 0;
int i = count;
while (--i >= 0)
{
long next = y[yOff + i];
x[xOff + i] ^= (long)((ulong)next >> shift) | prev;
prev = next << shiftInv;
}
return prev;
}
public void AddShiftedByWords(LongArray other, int words)
{
int otherUsedLen = other.GetUsedLength();
if (otherUsedLen == 0)
{
return;
}
int minLen = otherUsedLen + words;
if (minLen > m_ints.Length)
{
m_ints = ResizedInts(minLen);
}
Add(m_ints, words, other.m_ints, 0, otherUsedLen);
}
private static void Add(long[] x, int xOff, long[] y, int yOff, int count)
{
for (int i = 0; i < count; ++i)
{
x[xOff + i] ^= y[yOff + i];
}
}
private static void Add(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff, int count)
{
for (int i = 0; i < count; ++i)
{
z[zOff + i] = x[xOff + i] ^ y[yOff + i];
}
}
private static void AddBoth(long[] x, int xOff, long[] y1, int y1Off, long[] y2, int y2Off, int count)
{
for (int i = 0; i < count; ++i)
{
x[xOff + i] ^= y1[y1Off + i] ^ y2[y2Off + i];
}
}
private static void Distribute(long[] x, int src, int dst1, int dst2, int count)
{
for (int i = 0; i < count; ++i)
{
long v = x[src + i];
x[dst1 + i] ^= v;
x[dst2 + i] ^= v;
}
}
public int Length
{
get { return m_ints.Length; }
}
private static void FlipWord(long[] buf, int off, int bit, long word)
{
int n = off + (int)((uint)bit >> 6);
int shift = bit & 0x3F;
if (shift == 0)
{
buf[n] ^= word;
}
else
{
buf[n] ^= word << shift;
word = (long)((ulong)word >> (64 - shift));
if (word != 0)
{
buf[++n] ^= word;
}
}
}
// private static long getWord(long[] buf, int off, int len, int bit)
// {
// int n = off + (bit >>> 6);
// int shift = bit & 0x3F;
// if (shift == 0)
// {
// return buf[n];
// }
// long result = buf[n] >>> shift;
// if (++n < len)
// {
// result |= buf[n] << (64 - shift);
// }
// return result;
// }
public bool TestBitZero()
{
return m_ints.Length > 0 && (m_ints[0] & 1L) != 0;
}
private static bool TestBit(long[] buf, int off, int n)
{
// theInt = n / 64
int theInt = (int)((uint)n >> 6);
// theBit = n % 64
int theBit = n & 0x3F;
long tester = 1L << theBit;
return (buf[off + theInt] & tester) != 0;
}
private static void FlipBit(long[] buf, int off, int n)
{
// theInt = n / 64
int theInt = (int)((uint)n >> 6);
// theBit = n % 64
int theBit = n & 0x3F;
long flipper = 1L << theBit;
buf[off + theInt] ^= flipper;
}
// private static void SetBit(long[] buf, int off, int n)
// {
// // theInt = n / 64
// int theInt = n >>> 6;
// // theBit = n % 64
// int theBit = n & 0x3F;
// long setter = 1L << theBit;
// buf[off + theInt] |= setter;
// }
//
// private static void ClearBit(long[] buf, int off, int n)
// {
// // theInt = n / 64
// int theInt = n >>> 6;
// // theBit = n % 64
// int theBit = n & 0x3F;
// long setter = 1L << theBit;
// buf[off + theInt] &= ~setter;
// }
private static void MultiplyWord(long a, long[] b, int bLen, long[] c, int cOff)
{
if ((a & 1L) != 0L)
{
Add(c, cOff, b, 0, bLen);
}
int k = 1;
while ((a = (long)((ulong)a >> 1)) != 0L)
{
if ((a & 1L) != 0L)
{
long carry = AddShiftedUp(c, cOff, b, 0, bLen, k);
if (carry != 0L)
{
c[cOff + bLen] ^= carry;
}
}
++k;
}
}
public LongArray ModMultiplyLD(LongArray other, int m, int[] ks)
{
/*
* Find out the degree of each argument and handle the zero cases
*/
int aDeg = Degree();
if (aDeg == 0)
{
return this;
}
int bDeg = other.Degree();
if (bDeg == 0)
{
return other;
}
/*
* Swap if necessary so that A is the smaller argument
*/
LongArray A = this, B = other;
if (aDeg > bDeg)
{
A = other; B = this;
int tmp = aDeg; aDeg = bDeg; bDeg = tmp;
}
/*
* Establish the word lengths of the arguments and result
*/
int aLen = (int)((uint)(aDeg + 63) >> 6);
int bLen = (int)((uint)(bDeg + 63) >> 6);
int cLen = (int)((uint)(aDeg + bDeg + 62) >> 6);
if (aLen == 1)
{
long a0 = A.m_ints[0];
if (a0 == 1L)
{
return B;
}
/*
* Fast path for small A, with performance dependent only on the number of set bits
*/
long[] c0 = new long[cLen];
MultiplyWord(a0, B.m_ints, bLen, c0, 0);
/*
* Reduce the raw answer against the reduction coefficients
*/
return ReduceResult(c0, 0, cLen, m, ks);
}
/*
* Determine if B will get bigger during shifting
*/
int bMax = (int)((uint)(bDeg + 7 + 63) >> 6);
/*
* Lookup table for the offset of each B in the tables
*/
int[] ti = new int[16];
/*
* Precompute table of all 4-bit products of B
*/
long[] T0 = new long[bMax << 4];
int tOff = bMax;
ti[1] = tOff;
Array.Copy(B.m_ints, 0, T0, tOff, bLen);
for (int i = 2; i < 16; ++i)
{
ti[i] = (tOff += bMax);
if ((i & 1) == 0)
{
ShiftUp(T0, (int)((uint)tOff >> 1), T0, tOff, bMax, 1);
}
else
{
Add(T0, bMax, T0, tOff - bMax, T0, tOff, bMax);
}
}
/*
* Second table with all 4-bit products of B shifted 4 bits
*/
long[] T1 = new long[T0.Length];
ShiftUp(T0, 0, T1, 0, T0.Length, 4);
// shiftUp(T0, bMax, T1, bMax, tOff, 4);
long[] a = A.m_ints;
long[] c = new long[cLen];
int MASK = 0xF;
/*
* Lopez-Dahab algorithm
*/
for (int k = 56; k >= 0; k -= 8)
{
for (int j = 1; j < aLen; j += 2)
{
int aVal = (int)((ulong)a[j] >> k);
int u = aVal & MASK;
int v = (int)((uint)aVal >> 4) & MASK;
AddBoth(c, j - 1, T0, ti[u], T1, ti[v], bMax);
}
ShiftUp(c, 0, cLen, 8);
}
for (int k = 56; k >= 0; k -= 8)
{
for (int j = 0; j < aLen; j += 2)
{
int aVal = (int)((ulong)a[j] >> k);
int u = aVal & MASK;
int v = (int)((uint)aVal >> 4) & MASK;
AddBoth(c, j, T0, ti[u], T1, ti[v], bMax);
}
if (k > 0)
{
ShiftUp(c, 0, cLen, 8);
}
}
/*
* Finally the raw answer is collected, reduce it against the reduction coefficients
*/
return ReduceResult(c, 0, cLen, m, ks);
}
public LongArray ModMultiply(LongArray other, int m, int[] ks)
{
/*
* Find out the degree of each argument and handle the zero cases
*/
int aDeg = Degree();
if (aDeg == 0)
{
return this;
}
int bDeg = other.Degree();
if (bDeg == 0)
{
return other;
}
/*
* Swap if necessary so that A is the smaller argument
*/
LongArray A = this, B = other;
if (aDeg > bDeg)
{
A = other; B = this;
int tmp = aDeg; aDeg = bDeg; bDeg = tmp;
}
/*
* Establish the word lengths of the arguments and result
*/
int aLen = (int)((uint)(aDeg + 63) >> 6);
int bLen = (int)((uint)(bDeg + 63) >> 6);
int cLen = (int)((uint)(aDeg + bDeg + 62) >> 6);
if (aLen == 1)
{
long a0 = A.m_ints[0];
if (a0 == 1L)
{
return B;
}
/*
* Fast path for small A, with performance dependent only on the number of set bits
*/
long[] c0 = new long[cLen];
MultiplyWord(a0, B.m_ints, bLen, c0, 0);
/*
* Reduce the raw answer against the reduction coefficients
*/
return ReduceResult(c0, 0, cLen, m, ks);
}
/*
* Determine if B will get bigger during shifting
*/
int bMax = (int)((uint)(bDeg + 7 + 63) >> 6);
/*
* Lookup table for the offset of each B in the tables
*/
int[] ti = new int[16];
/*
* Precompute table of all 4-bit products of B
*/
long[] T0 = new long[bMax << 4];
int tOff = bMax;
ti[1] = tOff;
Array.Copy(B.m_ints, 0, T0, tOff, bLen);
for (int i = 2; i < 16; ++i)
{
ti[i] = (tOff += bMax);
if ((i & 1) == 0)
{
ShiftUp(T0, (int)((uint)tOff >> 1), T0, tOff, bMax, 1);
}
else
{
Add(T0, bMax, T0, tOff - bMax, T0, tOff, bMax);
}
}
/*
* Second table with all 4-bit products of B shifted 4 bits
*/
long[] T1 = new long[T0.Length];
ShiftUp(T0, 0, T1, 0, T0.Length, 4);
// ShiftUp(T0, bMax, T1, bMax, tOff, 4);
long[] a = A.m_ints;
long[] c = new long[cLen << 3];
int MASK = 0xF;
/*
* Lopez-Dahab (Modified) algorithm
*/
for (int aPos = 0; aPos < aLen; ++aPos)
{
long aVal = a[aPos];
int cOff = aPos;
for (;;)
{
int u = (int)aVal & MASK;
aVal = (long)((ulong)aVal >> 4);
int v = (int)aVal & MASK;
AddBoth(c, cOff, T0, ti[u], T1, ti[v], bMax);
aVal = (long)((ulong)aVal >> 4);
if (aVal == 0L)
{
break;
}
cOff += cLen;
}
}
{
int cOff = c.Length;
while ((cOff -= cLen) != 0)
{
AddShiftedUp(c, cOff - cLen, c, cOff, cLen, 8);
}
}
/*
* Finally the raw answer is collected, reduce it against the reduction coefficients
*/
return ReduceResult(c, 0, cLen, m, ks);
}
public LongArray ModMultiplyAlt(LongArray other, int m, int[] ks)
{
/*
* Find out the degree of each argument and handle the zero cases
*/
int aDeg = Degree();
if (aDeg == 0)
{
return this;
}
int bDeg = other.Degree();
if (bDeg == 0)
{
return other;
}
/*
* Swap if necessary so that A is the smaller argument
*/
LongArray A = this, B = other;
if (aDeg > bDeg)
{
A = other; B = this;
int tmp = aDeg; aDeg = bDeg; bDeg = tmp;
}
/*
* Establish the word lengths of the arguments and result
*/
int aLen = (int)((uint)(aDeg + 63) >> 6);
int bLen = (int)((uint)(bDeg + 63) >> 6);
int cLen = (int)((uint)(aDeg + bDeg + 62) >> 6);
if (aLen == 1)
{
long a0 = A.m_ints[0];
if (a0 == 1L)
{
return B;
}
/*
* Fast path for small A, with performance dependent only on the number of set bits
*/
long[] c0 = new long[cLen];
MultiplyWord(a0, B.m_ints, bLen, c0, 0);
/*
* Reduce the raw answer against the reduction coefficients
*/
return ReduceResult(c0, 0, cLen, m, ks);
}
// NOTE: This works, but is slower than width 4 processing
// if (aLen == 2)
// {
// /*
// * Use common-multiplicand optimization to save ~1/4 of the adds
// */
// long a1 = A.m_ints[0], a2 = A.m_ints[1];
// long aa = a1 & a2; a1 ^= aa; a2 ^= aa;
//
// long[] b = B.m_ints;
// long[] c = new long[cLen];
// multiplyWord(aa, b, bLen, c, 1);
// add(c, 0, c, 1, cLen - 1);
// multiplyWord(a1, b, bLen, c, 0);
// multiplyWord(a2, b, bLen, c, 1);
//
// /*
// * Reduce the raw answer against the reduction coefficients
// */
// return ReduceResult(c, 0, cLen, m, ks);
// }
/*
* Determine the parameters of the Interleaved window algorithm: the 'width' in bits to
* process together, the number of evaluation 'positions' implied by that width, and the
* 'top' position at which the regular window algorithm stops.
*/
int width, positions, top, banks;
// NOTE: width 4 is the fastest over the entire range of sizes used in current crypto
// width = 1; positions = 64; top = 64; banks = 4;
// width = 2; positions = 32; top = 64; banks = 4;
// width = 3; positions = 21; top = 63; banks = 3;
width = 4; positions = 16; top = 64; banks = 8;
// width = 5; positions = 13; top = 65; banks = 7;
// width = 7; positions = 9; top = 63; banks = 9;
// width = 8; positions = 8; top = 64; banks = 8;
/*
* Determine if B will get bigger during shifting
*/
int shifts = top < 64 ? positions : positions - 1;
int bMax = (int)((uint)(bDeg + shifts + 63) >> 6);
int bTotal = bMax * banks, stride = width * banks;
/*
* Create a single temporary buffer, with an offset table to find the positions of things in it
*/
int[] ci = new int[1 << width];
int cTotal = aLen;
{
ci[0] = cTotal;
cTotal += bTotal;
ci[1] = cTotal;
for (int i = 2; i < ci.Length; ++i)
{
cTotal += cLen;
ci[i] = cTotal;
}
cTotal += cLen;
}
// NOTE: Provide a safe dump for "high zeroes" since we are adding 'bMax' and not 'bLen'
++cTotal;
long[] c = new long[cTotal];
// Prepare A in Interleaved form, according to the chosen width
Interleave(A.m_ints, 0, c, 0, aLen, width);
// Make a working copy of B, since we will be shifting it
{
int bOff = aLen;
Array.Copy(B.m_ints, 0, c, bOff, bLen);
for (int bank = 1; bank < banks; ++bank)
{
ShiftUp(c, aLen, c, bOff += bMax, bMax, bank);
}
}
/*
* The main loop analyzes the Interleaved windows in A, and for each non-zero window
* a single word-array XOR is performed to a carefully selected slice of 'c'. The loop is
* breadth-first, checking the lowest window in each word, then looping again for the
* next higher window position.
*/
int MASK = (1 << width) - 1;
int k = 0;
for (;;)
{
int aPos = 0;
do
{
long aVal = (long)((ulong)c[aPos] >> k);
int bank = 0, bOff = aLen;
for (;;)
{
int index = (int)(aVal) & MASK;
if (index != 0)
{
/*
* Add to a 'c' buffer based on the bit-pattern of 'index'. Since A is in
* Interleaved form, the bits represent the current B shifted by 0, 'positions',
* 'positions' * 2, ..., 'positions' * ('width' - 1)
*/
Add(c, aPos + ci[index], c, bOff, bMax);
}
if (++bank == banks)
{
break;
}
bOff += bMax;
aVal = (long)((ulong)aVal >> width);
}
}
while (++aPos < aLen);
if ((k += stride) >= top)
{
if (k >= 64)
{
break;
}
/*
* Adjustment for window setups with top == 63, the final bit (if any) is processed
* as the top-bit of a window
*/
k = 64 - width;
MASK &= MASK << (top - k);
}
/*
* After each position has been checked for all words of A, B is shifted up 1 place
*/
ShiftUp(c, aLen, bTotal, banks);
}
int ciPos = ci.Length;
while (--ciPos > 1)
{
if ((ciPos & 1L) == 0L)
{
/*
* For even numbers, shift contents and add to the half-position
*/
AddShiftedUp(c, ci[(uint)ciPos >> 1], c, ci[ciPos], cLen, positions);
}
else
{
/*
* For odd numbers, 'distribute' contents to the result and the next-lowest position
*/
Distribute(c, ci[ciPos], ci[ciPos - 1], ci[1], cLen);
}
}
/*
* Finally the raw answer is collected, reduce it against the reduction coefficients
*/
return ReduceResult(c, ci[1], cLen, m, ks);
}
public LongArray ModReduce(int m, int[] ks)
{
long[] buf = Arrays.Clone(m_ints);
int rLen = ReduceInPlace(buf, 0, buf.Length, m, ks);
return new LongArray(buf, 0, rLen);
}
public LongArray Multiply(LongArray other, int m, int[] ks)
{
/*
* Find out the degree of each argument and handle the zero cases
*/
int aDeg = Degree();
if (aDeg == 0)
{
return this;
}
int bDeg = other.Degree();
if (bDeg == 0)
{
return other;
}
/*
* Swap if necessary so that A is the smaller argument
*/
LongArray A = this, B = other;
if (aDeg > bDeg)
{
A = other; B = this;
int tmp = aDeg; aDeg = bDeg; bDeg = tmp;
}
/*
* Establish the word lengths of the arguments and result
*/
int aLen = (int)((uint)(aDeg + 63) >> 6);
int bLen = (int)((uint)(bDeg + 63) >> 6);
int cLen = (int)((uint)(aDeg + bDeg + 62) >> 6);
if (aLen == 1)
{
long a0 = A.m_ints[0];
if (a0 == 1L)
{
return B;
}
/*
* Fast path for small A, with performance dependent only on the number of set bits
*/
long[] c0 = new long[cLen];
MultiplyWord(a0, B.m_ints, bLen, c0, 0);
/*
* Reduce the raw answer against the reduction coefficients
*/
//return ReduceResult(c0, 0, cLen, m, ks);
return new LongArray(c0, 0, cLen);
}
/*
* Determine if B will get bigger during shifting
*/
int bMax = (int)((uint)(bDeg + 7 + 63) >> 6);
/*
* Lookup table for the offset of each B in the tables
*/
int[] ti = new int[16];
/*
* Precompute table of all 4-bit products of B
*/
long[] T0 = new long[bMax << 4];
int tOff = bMax;
ti[1] = tOff;
Array.Copy(B.m_ints, 0, T0, tOff, bLen);
for (int i = 2; i < 16; ++i)
{
ti[i] = (tOff += bMax);
if ((i & 1) == 0)
{
ShiftUp(T0, (int)((uint)tOff >> 1), T0, tOff, bMax, 1);
}
else
{
Add(T0, bMax, T0, tOff - bMax, T0, tOff, bMax);
}
}
/*
* Second table with all 4-bit products of B shifted 4 bits
*/
long[] T1 = new long[T0.Length];
ShiftUp(T0, 0, T1, 0, T0.Length, 4);
// ShiftUp(T0, bMax, T1, bMax, tOff, 4);
long[] a = A.m_ints;
long[] c = new long[cLen << 3];
int MASK = 0xF;
/*
* Lopez-Dahab (Modified) algorithm
*/
for (int aPos = 0; aPos < aLen; ++aPos)
{
long aVal = a[aPos];
int cOff = aPos;
for (; ; )
{
int u = (int)aVal & MASK;
aVal = (long)((ulong)aVal >> 4);
int v = (int)aVal & MASK;
AddBoth(c, cOff, T0, ti[u], T1, ti[v], bMax);
aVal = (long)((ulong)aVal >> 4);
if (aVal == 0L)
{
break;
}
cOff += cLen;
}
}
{
int cOff = c.Length;
while ((cOff -= cLen) != 0)
{
AddShiftedUp(c, cOff - cLen, c, cOff, cLen, 8);
}
}
/*
* Finally the raw answer is collected, reduce it against the reduction coefficients
*/
//return ReduceResult(c, 0, cLen, m, ks);
return new LongArray(c, 0, cLen);
}
public void Reduce(int m, int[] ks)
{
long[] buf = m_ints;
int rLen = ReduceInPlace(buf, 0, buf.Length, m, ks);
if (rLen < buf.Length)
{
m_ints = new long[rLen];
Array.Copy(buf, 0, m_ints, 0, rLen);
}
}
private static LongArray ReduceResult(long[] buf, int off, int len, int m, int[] ks)
{
int rLen = ReduceInPlace(buf, off, len, m, ks);
return new LongArray(buf, off, rLen);
}
// private static void deInterleave(long[] x, int xOff, long[] z, int zOff, int count, int rounds)
// {
// for (int i = 0; i < count; ++i)
// {
// z[zOff + i] = deInterleave(x[zOff + i], rounds);
// }
// }
//
// private static long deInterleave(long x, int rounds)
// {
// while (--rounds >= 0)
// {
// x = deInterleave32(x & DEInterleave_MASK) | (deInterleave32((x >>> 1) & DEInterleave_MASK) << 32);
// }
// return x;
// }
//
// private static long deInterleave32(long x)
// {
// x = (x | (x >>> 1)) & 0x3333333333333333L;
// x = (x | (x >>> 2)) & 0x0F0F0F0F0F0F0F0FL;
// x = (x | (x >>> 4)) & 0x00FF00FF00FF00FFL;
// x = (x | (x >>> 8)) & 0x0000FFFF0000FFFFL;
// x = (x | (x >>> 16)) & 0x00000000FFFFFFFFL;
// return x;
// }
private static int ReduceInPlace(long[] buf, int off, int len, int m, int[] ks)
{
int mLen = (m + 63) >> 6;
if (len < mLen)
{
return len;
}
int numBits = System.Math.Min(len << 6, (m << 1) - 1); // TODO use actual degree?
int excessBits = (len << 6) - numBits;
while (excessBits >= 64)
{
--len;
excessBits -= 64;
}
int kLen = ks.Length, kMax = ks[kLen - 1], kNext = kLen > 1 ? ks[kLen - 2] : 0;
int wordWiseLimit = System.Math.Max(m, kMax + 64);
int vectorableWords = (excessBits + System.Math.Min(numBits - wordWiseLimit, m - kNext)) >> 6;
if (vectorableWords > 1)
{
int vectorWiseWords = len - vectorableWords;
ReduceVectorWise(buf, off, len, vectorWiseWords, m, ks);
while (len > vectorWiseWords)
{
buf[off + --len] = 0L;
}
numBits = vectorWiseWords << 6;
}
if (numBits > wordWiseLimit)
{
ReduceWordWise(buf, off, len, wordWiseLimit, m, ks);
numBits = wordWiseLimit;
}
if (numBits > m)
{
ReduceBitWise(buf, off, numBits, m, ks);
}
return mLen;
}
private static void ReduceBitWise(long[] buf, int off, int BitLength, int m, int[] ks)
{
while (--BitLength >= m)
{
if (TestBit(buf, off, BitLength))
{
ReduceBit(buf, off, BitLength, m, ks);
}
}
}
private static void ReduceBit(long[] buf, int off, int bit, int m, int[] ks)
{
FlipBit(buf, off, bit);
int n = bit - m;
int j = ks.Length;
while (--j >= 0)
{
FlipBit(buf, off, ks[j] + n);
}
FlipBit(buf, off, n);
}
private static void ReduceWordWise(long[] buf, int off, int len, int toBit, int m, int[] ks)
{
int toPos = (int)((uint)toBit >> 6);
while (--len > toPos)
{
long word = buf[off + len];
if (word != 0)
{
buf[off + len] = 0;
ReduceWord(buf, off, (len << 6), word, m, ks);
}
}
{
int partial = toBit & 0x3F;
long word = (long)((ulong)buf[off + toPos] >> partial);
if (word != 0)
{
buf[off + toPos] ^= word << partial;
ReduceWord(buf, off, toBit, word, m, ks);
}
}
}
private static void ReduceWord(long[] buf, int off, int bit, long word, int m, int[] ks)
{
int offset = bit - m;
int j = ks.Length;
while (--j >= 0)
{
FlipWord(buf, off, offset + ks[j], word);
}
FlipWord(buf, off, offset, word);
}
private static void ReduceVectorWise(long[] buf, int off, int len, int words, int m, int[] ks)
{
/*
* NOTE: It's important we go from highest coefficient to lowest, because for the highest
* one (only) we allow the ranges to partially overlap, and therefore any changes must take
* effect for the subsequent lower coefficients.
*/
int baseBit = (words << 6) - m;
int j = ks.Length;
while (--j >= 0)
{
FlipVector(buf, off, buf, off + words, len - words, baseBit + ks[j]);
}
FlipVector(buf, off, buf, off + words, len - words, baseBit);
}
private static void FlipVector(long[] x, int xOff, long[] y, int yOff, int yLen, int bits)
{
xOff += (int)((uint)bits >> 6);
bits &= 0x3F;
if (bits == 0)
{
Add(x, xOff, y, yOff, yLen);
}
else
{
long carry = AddShiftedDown(x, xOff + 1, y, yOff, yLen, 64 - bits);
x[xOff] ^= carry;
}
}
public LongArray ModSquare(int m, int[] ks)
{
int len = GetUsedLength();
if (len == 0)
{
return this;
}
int _2len = len << 1;
long[] r = new long[_2len];
int pos = 0;
while (pos < _2len)
{
long mi = m_ints[(uint)pos >> 1];
r[pos++] = Interleave2_32to64((int)mi);
r[pos++] = Interleave2_32to64((int)((ulong)mi >> 32));
}
return new LongArray(r, 0, ReduceInPlace(r, 0, r.Length, m, ks));
}
public LongArray ModSquareN(int n, int m, int[] ks)
{
int len = GetUsedLength();
if (len == 0)
{
return this;
}
int mLen = (m + 63) >> 6;
long[] r = new long[mLen << 1];
Array.Copy(m_ints, 0, r, 0, len);
while (--n >= 0)
{
SquareInPlace(r, len, m, ks);
len = ReduceInPlace(r, 0, r.Length, m, ks);
}
return new LongArray(r, 0, len);
}
public LongArray Square(int m, int[] ks)
{
int len = GetUsedLength();
if (len == 0)
{
return this;
}
int _2len = len << 1;
long[] r = new long[_2len];
int pos = 0;
while (pos < _2len)
{
long mi = m_ints[(uint)pos >> 1];
r[pos++] = Interleave2_32to64((int)mi);
r[pos++] = Interleave2_32to64((int)((ulong)mi >> 32));
}
return new LongArray(r, 0, r.Length);
}
private static void SquareInPlace(long[] x, int xLen, int m, int[] ks)
{
int pos = xLen << 1;
while (--xLen >= 0)
{
long xVal = x[xLen];
x[--pos] = Interleave2_32to64((int)((ulong)xVal >> 32));
x[--pos] = Interleave2_32to64((int)xVal);
}
}
private static void Interleave(long[] x, int xOff, long[] z, int zOff, int count, int width)
{
switch (width)
{
case 3:
Interleave3(x, xOff, z, zOff, count);
break;
case 5:
Interleave5(x, xOff, z, zOff, count);
break;
case 7:
Interleave7(x, xOff, z, zOff, count);
break;
default:
Interleave2_n(x, xOff, z, zOff, count, BitLengths[width] - 1);
break;
}
}
private static void Interleave3(long[] x, int xOff, long[] z, int zOff, int count)
{
for (int i = 0; i < count; ++i)
{
z[zOff + i] = Interleave3(x[xOff + i]);
}
}
private static long Interleave3(long x)
{
long z = x & (1L << 63);
return z
| Interleave3_21to63((int)x & 0x1FFFFF)
| Interleave3_21to63((int)((ulong)x >> 21) & 0x1FFFFF) << 1
| Interleave3_21to63((int)((ulong)x >> 42) & 0x1FFFFF) << 2;
// int zPos = 0, wPos = 0, xPos = 0;
// for (;;)
// {
// z |= ((x >>> xPos) & 1L) << zPos;
// if (++zPos == 63)
// {
// String sz2 = Long.toBinaryString(z);
// return z;
// }
// if ((xPos += 21) >= 63)
// {
// xPos = ++wPos;
// }
// }
}
private static long Interleave3_21to63(int x)
{
int r00 = INTERLEAVE3_TABLE[x & 0x7F];
int r21 = INTERLEAVE3_TABLE[((uint)x >> 7) & 0x7F];
int r42 = INTERLEAVE3_TABLE[(uint)x >> 14];
return (r42 & 0xFFFFFFFFL) << 42 | (r21 & 0xFFFFFFFFL) << 21 | (r00 & 0xFFFFFFFFL);
}
private static void Interleave5(long[] x, int xOff, long[] z, int zOff, int count)
{
for (int i = 0; i < count; ++i)
{
z[zOff + i] = Interleave5(x[xOff + i]);
}
}
private static long Interleave5(long x)
{
return Interleave3_13to65((int)x & 0x1FFF)
| Interleave3_13to65((int)((ulong)x >> 13) & 0x1FFF) << 1
| Interleave3_13to65((int)((ulong)x >> 26) & 0x1FFF) << 2
| Interleave3_13to65((int)((ulong)x >> 39) & 0x1FFF) << 3
| Interleave3_13to65((int)((ulong)x >> 52) & 0x1FFF) << 4;
// long z = 0;
// int zPos = 0, wPos = 0, xPos = 0;
// for (;;)
// {
// z |= ((x >>> xPos) & 1L) << zPos;
// if (++zPos == 64)
// {
// return z;
// }
// if ((xPos += 13) >= 64)
// {
// xPos = ++wPos;
// }
// }
}
private static long Interleave3_13to65(int x)
{
int r00 = INTERLEAVE5_TABLE[x & 0x7F];
int r35 = INTERLEAVE5_TABLE[(uint)x >> 7];
return (r35 & 0xFFFFFFFFL) << 35 | (r00 & 0xFFFFFFFFL);
}
private static void Interleave7(long[] x, int xOff, long[] z, int zOff, int count)
{
for (int i = 0; i < count; ++i)
{
z[zOff + i] = Interleave7(x[xOff + i]);
}
}
private static long Interleave7(long x)
{
long z = x & (1L << 63);
return z
| INTERLEAVE7_TABLE[(int)x & 0x1FF]
| INTERLEAVE7_TABLE[(int)((ulong)x >> 9) & 0x1FF] << 1
| INTERLEAVE7_TABLE[(int)((ulong)x >> 18) & 0x1FF] << 2
| INTERLEAVE7_TABLE[(int)((ulong)x >> 27) & 0x1FF] << 3
| INTERLEAVE7_TABLE[(int)((ulong)x >> 36) & 0x1FF] << 4
| INTERLEAVE7_TABLE[(int)((ulong)x >> 45) & 0x1FF] << 5
| INTERLEAVE7_TABLE[(int)((ulong)x >> 54) & 0x1FF] << 6;
// int zPos = 0, wPos = 0, xPos = 0;
// for (;;)
// {
// z |= ((x >>> xPos) & 1L) << zPos;
// if (++zPos == 63)
// {
// return z;
// }
// if ((xPos += 9) >= 63)
// {
// xPos = ++wPos;
// }
// }
}
private static void Interleave2_n(long[] x, int xOff, long[] z, int zOff, int count, int rounds)
{
for (int i = 0; i < count; ++i)
{
z[zOff + i] = Interleave2_n(x[xOff + i], rounds);
}
}
private static long Interleave2_n(long x, int rounds)
{
while (rounds > 1)
{
rounds -= 2;
x = Interleave4_16to64((int)x & 0xFFFF)
| Interleave4_16to64((int)((ulong)x >> 16) & 0xFFFF) << 1
| Interleave4_16to64((int)((ulong)x >> 32) & 0xFFFF) << 2
| Interleave4_16to64((int)((ulong)x >> 48) & 0xFFFF) << 3;
}
if (rounds > 0)
{
x = Interleave2_32to64((int)x) | Interleave2_32to64((int)((ulong)x >> 32)) << 1;
}
return x;
}
private static long Interleave4_16to64(int x)
{
int r00 = INTERLEAVE4_TABLE[x & 0xFF];
int r32 = INTERLEAVE4_TABLE[(uint)x >> 8];
return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL);
}
private static long Interleave2_32to64(int x)
{
int r00 = INTERLEAVE2_TABLE[x & 0xFF] | INTERLEAVE2_TABLE[((uint)x >> 8) & 0xFF] << 16;
int r32 = INTERLEAVE2_TABLE[((uint)x >> 16) & 0xFF] | INTERLEAVE2_TABLE[(uint)x >> 24] << 16;
return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL);
}
// private static LongArray ExpItohTsujii2(LongArray B, int n, int m, int[] ks)
// {
// LongArray t1 = B, t3 = new LongArray(new long[]{ 1L });
// int scale = 1;
//
// int numTerms = n;
// while (numTerms > 1)
// {
// if ((numTerms & 1) != 0)
// {
// t3 = t3.ModMultiply(t1, m, ks);
// t1 = t1.modSquareN(scale, m, ks);
// }
//
// LongArray t2 = t1.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
// numTerms >>>= 1; scale <<= 1;
// }
//
// return t3.ModMultiply(t1, m, ks);
// }
//
// private static LongArray ExpItohTsujii23(LongArray B, int n, int m, int[] ks)
// {
// LongArray t1 = B, t3 = new LongArray(new long[]{ 1L });
// int scale = 1;
//
// int numTerms = n;
// while (numTerms > 1)
// {
// bool m03 = numTerms % 3 == 0;
// bool m14 = !m03 && (numTerms & 1) != 0;
//
// if (m14)
// {
// t3 = t3.ModMultiply(t1, m, ks);
// t1 = t1.modSquareN(scale, m, ks);
// }
//
// LongArray t2 = t1.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
//
// if (m03)
// {
// t2 = t2.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
// numTerms /= 3; scale *= 3;
// }
// else
// {
// numTerms >>>= 1; scale <<= 1;
// }
// }
//
// return t3.ModMultiply(t1, m, ks);
// }
//
// private static LongArray ExpItohTsujii235(LongArray B, int n, int m, int[] ks)
// {
// LongArray t1 = B, t4 = new LongArray(new long[]{ 1L });
// int scale = 1;
//
// int numTerms = n;
// while (numTerms > 1)
// {
// if (numTerms % 5 == 0)
// {
//// t1 = ExpItohTsujii23(t1, 5, m, ks);
//
// LongArray t3 = t1;
// t1 = t1.modSquareN(scale, m, ks);
//
// LongArray t2 = t1.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
// t2 = t1.modSquareN(scale << 1, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
//
// t1 = t1.ModMultiply(t3, m, ks);
//
// numTerms /= 5; scale *= 5;
// continue;
// }
//
// bool m03 = numTerms % 3 == 0;
// bool m14 = !m03 && (numTerms & 1) != 0;
//
// if (m14)
// {
// t4 = t4.ModMultiply(t1, m, ks);
// t1 = t1.modSquareN(scale, m, ks);
// }
//
// LongArray t2 = t1.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
//
// if (m03)
// {
// t2 = t2.modSquareN(scale, m, ks);
// t1 = t1.ModMultiply(t2, m, ks);
// numTerms /= 3; scale *= 3;
// }
// else
// {
// numTerms >>>= 1; scale <<= 1;
// }
// }
//
// return t4.ModMultiply(t1, m, ks);
// }
public LongArray ModInverse(int m, int[] ks)
{
/*
* Fermat's Little Theorem
*/
// LongArray A = this;
// LongArray B = A.modSquare(m, ks);
// LongArray R0 = B, R1 = B;
// for (int i = 2; i < m; ++i)
// {
// R1 = R1.modSquare(m, ks);
// R0 = R0.ModMultiply(R1, m, ks);
// }
//
// return R0;
/*
* Itoh-Tsujii
*/
// LongArray B = modSquare(m, ks);
// switch (m)
// {
// case 409:
// return ExpItohTsujii23(B, m - 1, m, ks);
// case 571:
// return ExpItohTsujii235(B, m - 1, m, ks);
// case 163:
// case 233:
// case 283:
// default:
// return ExpItohTsujii2(B, m - 1, m, ks);
// }
/*
* Inversion in F2m using the extended Euclidean algorithm
*
* Input: A nonzero polynomial a(z) of degree at most m-1
* Output: a(z)^(-1) mod f(z)
*/
int uzDegree = Degree();
if (uzDegree == 0)
{
throw new InvalidOperationException();
}
if (uzDegree == 1)
{
return this;
}
// u(z) := a(z)
LongArray uz = (LongArray)Copy();
int t = (m + 63) >> 6;
// v(z) := f(z)
LongArray vz = new LongArray(t);
ReduceBit(vz.m_ints, 0, m, m, ks);
// g1(z) := 1, g2(z) := 0
LongArray g1z = new LongArray(t);
g1z.m_ints[0] = 1L;
LongArray g2z = new LongArray(t);
int[] uvDeg = new int[]{ uzDegree, m + 1 };
LongArray[] uv = new LongArray[]{ uz, vz };
int[] ggDeg = new int[]{ 1, 0 };
LongArray[] gg = new LongArray[]{ g1z, g2z };
int b = 1;
int duv1 = uvDeg[b];
int dgg1 = ggDeg[b];
int j = duv1 - uvDeg[1 - b];
for (;;)
{
if (j < 0)
{
j = -j;
uvDeg[b] = duv1;
ggDeg[b] = dgg1;
b = 1 - b;
duv1 = uvDeg[b];
dgg1 = ggDeg[b];
}
uv[b].AddShiftedByBitsSafe(uv[1 - b], uvDeg[1 - b], j);
int duv2 = uv[b].DegreeFrom(duv1);
if (duv2 == 0)
{
return gg[1 - b];
}
{
int dgg2 = ggDeg[1 - b];
gg[b].AddShiftedByBitsSafe(gg[1 - b], dgg2, j);
dgg2 += j;
if (dgg2 > dgg1)
{
dgg1 = dgg2;
}
else if (dgg2 == dgg1)
{
dgg1 = gg[b].DegreeFrom(dgg1);
}
}
j += (duv2 - duv1);
duv1 = duv2;
}
}
public override bool Equals(object obj)
{
return Equals(obj as LongArray);
}
public virtual bool Equals(LongArray other)
{
if (this == other)
return true;
if (null == other)
return false;
int usedLen = GetUsedLength();
if (other.GetUsedLength() != usedLen)
{
return false;
}
for (int i = 0; i < usedLen; i++)
{
if (m_ints[i] != other.m_ints[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
int usedLen = GetUsedLength();
int hash = 1;
for (int i = 0; i < usedLen; i++)
{
long mi = m_ints[i];
hash *= 31;
hash ^= (int)mi;
hash *= 31;
hash ^= (int)((ulong)mi >> 32);
}
return hash;
}
public LongArray Copy()
{
return new LongArray(Arrays.Clone(m_ints));
}
public override string ToString()
{
int i = GetUsedLength();
if (i == 0)
{
return "0";
}
StringBuilder sb = new StringBuilder(Convert.ToString(m_ints[--i], 2));
while (--i >= 0)
{
string s = Convert.ToString(m_ints[i], 2);
// Add leading zeroes, except for highest significant word
int len = s.Length;
if (len < 64)
{
sb.Append(ZEROES.Substring(len));
}
sb.Append(s);
}
return sb.ToString();
}
}
}
#endif
| 38.446056 | 117 | 0.46076 | [
"MIT"
] | czlsy009/UnityAppMVCFramework | Framework/Assets/SilenceFramework/Libs/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/LongArray.cs | 84,812 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Rds.Transform;
using Aliyun.Acs.Rds.Transform.V20140815;
namespace Aliyun.Acs.Rds.Model.V20140815
{
public class ModifyInstanceAutoRenewalAttributeRequest : RpcAcsRequest<ModifyInstanceAutoRenewalAttributeResponse>
{
public ModifyInstanceAutoRenewalAttributeRequest()
: base("Rds", "2014-08-15", "ModifyInstanceAutoRenewalAttribute", "rds", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private long? resourceOwnerId;
private string clientToken;
private string duration;
private string dBInstanceId;
private string resourceOwnerAccount;
private string ownerAccount;
private long? ownerId;
private string autoRenew;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string ClientToken
{
get
{
return clientToken;
}
set
{
clientToken = value;
DictionaryUtil.Add(QueryParameters, "ClientToken", value);
}
}
public string Duration
{
get
{
return duration;
}
set
{
duration = value;
DictionaryUtil.Add(QueryParameters, "Duration", value);
}
}
public string DBInstanceId
{
get
{
return dBInstanceId;
}
set
{
dBInstanceId = value;
DictionaryUtil.Add(QueryParameters, "DBInstanceId", value);
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string AutoRenew
{
get
{
return autoRenew;
}
set
{
autoRenew = value;
DictionaryUtil.Add(QueryParameters, "AutoRenew", value);
}
}
public override ModifyInstanceAutoRenewalAttributeResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return ModifyInstanceAutoRenewalAttributeResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 23.279762 | 134 | 0.662235 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-rds/Rds/Model/V20140815/ModifyInstanceAutoRenewalAttributeRequest.cs | 3,911 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Stryker.Core.Options;
namespace Stryker.Core.Mutants
{
public abstract class MutantOrchestrator<T> : MutantOrchestrator
{
protected MutantOrchestrator() : base(null)
{
}
protected MutantOrchestrator(IStrykerOptions input) : base(input)
{
}
public abstract T Mutate(T input);
}
public abstract class MutantOrchestrator
{
public readonly IStrykerOptions _options;
public bool MustInjectCoverageLogic =>
_options != null && _options.Optimizations.HasFlag(OptimizationFlags.CoverageBasedTest) &&
!_options.Optimizations.HasFlag(OptimizationFlags.CaptureCoveragePerTest);
public ICollection<Mutant> Mutants { get; set; }
public int MutantCount { get; set; }
protected MutantOrchestrator(IStrykerOptions options)
{
_options = options;
}
/// <summary>
/// Gets the stored mutants and resets the mutant list to an empty collection
/// </summary>
public virtual IReadOnlyCollection<Mutant> GetLatestMutantBatch()
{
var tempMutants = Mutants;
Mutants = new Collection<Mutant>();
return (IReadOnlyCollection<Mutant>)tempMutants;
}
}
}
| 29.695652 | 102 | 0.645681 | [
"Apache-2.0"
] | 0xced/stryker-net | src/Stryker.Core/Stryker.Core/Mutants/MutantOrchestrator.cs | 1,366 | C# |
namespace SpanJson.Internal
{
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
public static partial class TextEncodings
{
public static partial class Utf16
{
static readonly AsymmetricKeyHashTable<string> s_stringCache = new AsymmetricKeyHashTable<string>(StringReadOnlySpanByteAscymmetricEqualityComparer.Instance);
/// <summary>For short strings use only.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string GetStringWithCache(in ReadOnlySpan<byte> utf16Source)
{
if (utf16Source.IsEmpty) { return string.Empty; }
if (s_stringCache.TryGetValue(utf16Source, out var value))
{
return value;
}
return GetStringWithCacheSlow(utf16Source);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetStringWithCacheSlow(in ReadOnlySpan<byte> utf16Source)
{
var buffer = utf16Source.ToArray();
var value = Encoding.Unicode.GetString(buffer);
s_stringCache.TryAdd(buffer, value);
return value;
}
}
}
}
| 35.921053 | 170 | 0.614652 | [
"MIT"
] | cuteant/SpanJson | src/SpanJson/Internal/TextEncodings.Utf16.cs | 1,367 | C# |
// CS1964: User-defined operator `C.implicit operator C(dynamic)' cannot convert to or from the dynamic type
// Line: 6
class C
{
public static implicit operator C (dynamic d)
{
}
}
| 18.6 | 108 | 0.715054 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/errors/cs1964.cs | 186 | C# |
using Microsoft.AspNetCore.Blazor.Browser.Rendering;
using Microsoft.AspNetCore.Blazor.Browser.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace BlazorRealworld
{
class Program
{
static void Main(string[] args)
{
var serviceProvider = new BrowserServiceProvider(configure =>
{
configure.Add(ServiceDescriptor.Singleton<AppState, AppState>());
configure.Add(ServiceDescriptor.Singleton<ApiClient, ApiClient>());
});
new BrowserRenderer(serviceProvider).AddComponent<App>("app");
}
}
}
| 28.863636 | 83 | 0.658268 | [
"Apache-2.0"
] | OsvaldoMartini/Blazor_Projects | blazor-realworld-example-app/src/BlazorRealworld/Program.cs | 637 | C# |
using System.ComponentModel.DataAnnotations.Schema;
namespace ColegioColombia.Web.Model
{
[Table("Alumnos")]
public class Alumno
{
public int Id { get; set; }
public string Nombre { get; set; }
public string Apellido { get; set; }
public long Cedula { get; set; }
public int Grado { get; set; }
public string Grupo { get; set; }
}
} | 26.533333 | 52 | 0.600503 | [
"MIT"
] | mdpl11/CursoNetBasico | ColegioColombia.Web/Model/Alumno.cs | 400 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.