source
stringclasses 1
value | id
stringlengths 40
40
| language
stringclasses 2
values | date
stringclasses 1
value | author
stringclasses 1
value | url
stringclasses 1
value | title
stringclasses 1
value | extra
stringlengths 528
1.53k
| quality_signals
stringlengths 139
178
| text
stringlengths 6
1.05M
|
---|---|---|---|---|---|---|---|---|---|
TheStack | bd44ae13ad9e2a314cb73b5ca11c2f52cbd87be2 | C#code:C# | {"size": 10514, "ext": "cs", "max_stars_repo_path": "HandPosing_Unity/Hand Posing/Assets/PoseAuthoring/Scripts/HandPuppet.cs", "max_stars_repo_name": "DaenLee20/Hnd", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HandPosing_Unity/Hand Posing/Assets/PoseAuthoring/Scripts/HandPuppet.cs", "max_issues_repo_name": "DaenLee20/Hnd", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HandPosing_Unity/Hand Posing/Assets/PoseAuthoring/Scripts/HandPuppet.cs", "max_forks_repo_name": "DaenLee20/Hnd", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.6686746988, "max_line_length": 122, "alphanum_fraction": 0.5589689937} | using System.Collections.Generic;
using UnityEngine;
using static OVRSkeleton;
using static PoseAuthoring.HandSnapPose;
namespace PoseAuthoring
{
[DefaultExecutionOrder(-10)]
public class HandPuppet : MonoBehaviour
{
[SerializeField]
private OVRSkeleton trackedHand;
[SerializeField]
private Animator animator;
[SerializeField]
private Transform handAnchor;
[SerializeField]
private Transform gripPoint;
[SerializeField]
private Handeness handeness;
[SerializeField]
private HandMap trackedHandOffset;
[SerializeField]
private List<BoneMap> boneMaps;
public Transform Grip
{
get
{
return gripPoint;
}
}
public bool IsTrackingHands
{
get
{
return _trackingHands;
}
}
public Pose GripOffset
{
get
{
return this.handAnchor.RelativeOffset(this.gripPoint);
}
}
public System.Action OnPoseBeforeUpdate;
public System.Action OnPoseUpdated;
private class BoneCollection : Dictionary<BoneId, BoneMap> { };
private BoneCollection _bonesCollection;
private HandMap _originalHandOffset;
private Pose _originalGripOffset;
private Pose _pupettedGripOffset;
private Pose TrackedGripPose
{
get
{
Pose offset = _trackingHands ? _pupettedGripOffset : _originalGripOffset;
return this.handAnchor.GlobalPose(offset);
}
}
private bool _trackingHands;
private bool _usingOVRUpdates;
private void Awake()
{
_bonesCollection = InitializeBones();
if (trackedHand == null)
{
this.enabled = false;
}
InitializeOVRUpdates();
}
private BoneCollection InitializeBones()
{
var bonesCollection = new BoneCollection();
foreach (var boneMap in boneMaps)
{
BoneId id = boneMap.id;
bonesCollection.Add(id, boneMap);
}
return bonesCollection;
}
private void InitializeOVRUpdates()
{
OVRCameraRig rig = this.transform.GetComponentInParent<OVRCameraRig>();
if (rig != null)
{
rig.UpdatedAnchors += (r) => { UpdateHandPose(); };
_usingOVRUpdates = true;
}
else
{
_usingOVRUpdates = false;
}
}
private void Start()
{
StorePoses();
}
private void StorePoses()
{
_originalHandOffset = HandOffsetMapping();
_originalGripOffset = GripOffset;
_pupettedGripOffset = OffsetedGripPose(trackedHandOffset.positionOffset,
trackedHandOffset.RotationOffset * Quaternion.Euler(0f, 180f, 0f));
}
private Pose OffsetedGripPose(Vector3 posOffset, Quaternion rotOffset)
{
Transform hand = trackedHandOffset.transform;
Vector3 originalPos = hand.localPosition;
Quaternion originalRot = hand.localRotation;
hand.localRotation = rotOffset;
hand.localPosition = hand.localPosition + posOffset;
Pose pose = GripOffset;
hand.localRotation = originalRot;
hand.localPosition = originalPos;
return pose;
}
private void Update()
{
OnPoseBeforeUpdate?.Invoke();
if (!_usingOVRUpdates)
{
UpdateHandPose();
}
}
private void UpdateHandPose()
{
if (trackedHand != null
&& trackedHand.IsInitialized
&& trackedHand.IsDataValid)
{
EnableHandTracked();
}
else
{
DisableHandTracked();
}
OnPoseUpdated?.Invoke();
}
private void EnableHandTracked()
{
if (!_trackingHands)
{
_trackingHands = true;
animator.enabled = false;
}
SetLivePose(trackedHand);
}
private void DisableHandTracked()
{
if (_trackingHands)
{
_trackingHands = false;
animator.enabled = true;
RestoreHandOffset();
}
}
#region bone restoring
private HandMap HandOffsetMapping()
{
return new HandMap()
{
id = trackedHandOffset.id,
transform = trackedHandOffset.transform,
positionOffset = trackedHandOffset.transform.localPosition,
rotationOffset = trackedHandOffset.transform.localRotation.eulerAngles
};
}
public void RestoreHandOffset()
{
_originalHandOffset.transform.localPosition = _originalHandOffset.positionOffset;
_originalHandOffset.transform.localRotation = _originalHandOffset.RotationOffset;
}
#endregion
private void SetLivePose(OVRSkeleton skeleton)
{
for (int i = 0; i < skeleton.Bones.Count; ++i)
{
BoneId boneId = skeleton.Bones[i].Id;
if (_bonesCollection.ContainsKey(boneId))
{
Transform boneTransform = _bonesCollection[boneId].transform;
boneTransform.localRotation = UnmapRotation(skeleton.Bones[i],
_bonesCollection[boneId].RotationOffset);
}
else if (trackedHandOffset.id == boneId) //TODO, do I REALLY want to move this?
{
Transform boneTransform = trackedHandOffset.transform;
boneTransform.localRotation = UnmapRotation(skeleton.Bones[i],
trackedHandOffset.RotationOffset);
boneTransform.localPosition = trackedHandOffset.positionOffset
+ skeleton.Bones[i].Transform.localPosition;
}
}
Quaternion UnmapRotation(OVRBone trackedBone, Quaternion rotationOffset)
{
return rotationOffset * trackedBone.Transform.localRotation;
}
}
#region pose lerping
public void LerpToPose(HandSnapPose pose, Transform relativeTo, float bonesWeight = 1f, float positionWeight = 1f)
{
LerpBones(pose.Bones, bonesWeight);
LerpGripOffset(pose, positionWeight, relativeTo);
}
public void LerpBones(List<BoneRotation> bones, float weight)
{
if (weight > 0f)
{
foreach (var bone in bones)
{
BoneId boneId = bone.boneID;
if (_bonesCollection.ContainsKey(boneId))
{
Transform boneTransform = _bonesCollection[boneId].transform;
boneTransform.localRotation = Quaternion.Lerp(boneTransform.localRotation, bone.rotation, weight);
}
}
}
}
public void LerpGripOffset(HandSnapPose pose, float weight, Transform relativeTo)
{
Pose offset = new Pose(pose.relativeGripPos, pose.relativeGripRot);
LerpGripOffset(offset, weight, relativeTo);
}
public void LerpGripOffset(Pose pose, float weight, Transform relativeTo = null)
{
relativeTo = relativeTo ?? this.handAnchor;
Pose worldGrip = TrackedGripPose;
Quaternion rotationDif = Quaternion.Inverse(transform.rotation) * this.gripPoint.rotation;
Quaternion desiredRotation = (relativeTo.rotation * pose.rotation) * rotationDif;
Quaternion trackedRot = rotationDif * worldGrip.rotation;
Quaternion finalRot = Quaternion.Lerp(trackedRot, desiredRotation, weight);
transform.rotation = finalRot;
Vector3 positionDif = transform.position - this.gripPoint.position;
Vector3 desiredPosition = relativeTo.TransformPoint(pose.position) + positionDif;
Vector3 trackedPosition = worldGrip.position + positionDif;
Vector3 finalPos = Vector3.Lerp(trackedPosition, desiredPosition, weight);
transform.position = finalPos;
}
#endregion
#region currentPoses
public HandSnapPose TrackedPose(Transform relativeTo, bool includeBones = false)
{
Pose worldGrip = TrackedGripPose;
Vector3 trackedGripPosition = worldGrip.position;
Quaternion trackedGripRotation = worldGrip.rotation;
HandSnapPose pose = new HandSnapPose();
pose.relativeGripPos = relativeTo.InverseTransformPoint(trackedGripPosition);
pose.relativeGripRot = Quaternion.Inverse(relativeTo.rotation) * trackedGripRotation;
pose.handeness = this.handeness;
if(includeBones)
{
foreach (var bone in _bonesCollection)
{
BoneMap boneMap = bone.Value;
Quaternion rotation = boneMap.transform.localRotation;
pose.Bones.Add(new BoneRotation() { boneID = boneMap.id, rotation = rotation });
}
}
return pose;
}
public HandSnapPose VisualPose(Transform relativeTo)
{
HandSnapPose pose = new HandSnapPose();
pose.relativeGripPos = relativeTo.InverseTransformPoint(this.gripPoint.position);
pose.relativeGripRot = Quaternion.Inverse(relativeTo.rotation) * this.gripPoint.rotation;
pose.handeness = this.handeness;
foreach (var bone in _bonesCollection)
{
BoneMap boneMap = bone.Value;
Quaternion rotation = boneMap.transform.localRotation;
pose.Bones.Add(new BoneRotation() { boneID = boneMap.id, rotation = rotation });
}
return pose;
}
#endregion
}
} |
||||
TheStack | bd46be2e5b69a4e3e33743b4e01f3d4c1cdc38c5 | C#code:C# | {"size": 6646, "ext": "cs", "max_stars_repo_path": "com/netfx/src/clr/bcl/system/dbnull.cs", "max_stars_repo_name": "npocmaka/Windows-Server-2003", "max_stars_repo_stars_event_min_datetime": "2020-11-13T13:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T09:13:13.000Z", "max_issues_repo_path": "com/netfx/src/clr/bcl/system/dbnull.cs", "max_issues_repo_name": "sancho1952007/Windows-Server-2003", "max_issues_repo_issues_event_min_datetime": "2020-10-19T08:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-19T08:23:18.000Z", "max_forks_repo_path": "com/netfx/src/clr/bcl/system/dbnull.cs", "max_forks_repo_name": "sancho1952007/Windows-Server-2003", "max_forks_repo_forks_event_min_datetime": "2020-11-14T09:43:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T08:59:57.000Z"} | {"max_stars_count": 17.0, "max_issues_count": 2.0, "max_forks_count": 14.0, "avg_line_length": 45.8344827586, "max_line_length": 118, "alphanum_fraction": 0.6193198917} | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
// Void
// This class represents a Missing Variant
////////////////////////////////////////////////////////////////////////////////
namespace System {
using System;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull"]/*' />
[Serializable()] public sealed class DBNull : ISerializable, IConvertible {
//Package private constructor
private DBNull(){
}
private DBNull(SerializationInfo info, StreamingContext context) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DBNullSerial"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.Value"]/*' />
public static readonly DBNull Value = new DBNull();
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.GetObjectData"]/*' />
public void GetObjectData(SerializationInfo info, StreamingContext context) {
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.ToString"]/*' />
public override String ToString() {
return String.Empty;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.ToString1"]/*' />
public String ToString(IFormatProvider provider) {
return String.Empty;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.GetTypeCode"]/*' />
public TypeCode GetTypeCode() {
return TypeCode.DBNull;
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToBoolean"]/*' />
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToChar"]/*' />
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToSByte"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
sbyte IConvertible.ToSByte(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToByte"]/*' />
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt16"]/*' />
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt16"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ushort IConvertible.ToUInt16(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt32"]/*' />
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt32"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
uint IConvertible.ToUInt32(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToInt64"]/*' />
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToUInt64"]/*' />
/// <internalonly/>
[CLSCompliant(false)]
ulong IConvertible.ToUInt64(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToSingle"]/*' />
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDouble"]/*' />
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDecimal"]/*' />
/// <internalonly/>
decimal IConvertible.ToDecimal(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToDateTime"]/*' />
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <include file='doc\DBNull.uex' path='docs/doc[@for="DBNull.IConvertible.ToType"]/*' />
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
|
||||
TheStack | bd46d7e5c8c81c1566022c5d41e2778f47283e20 | C#code:C# | {"size": 1792, "ext": "cs", "max_stars_repo_path": "src/Injector.cs", "max_stars_repo_name": "guojianwei001/verySimpleDI", "max_stars_repo_stars_event_min_datetime": "2020-04-26T13:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T13:07:05.000Z", "max_issues_repo_path": "src/Injector.cs", "max_issues_repo_name": "guojianwei001/verySimpleDI", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Injector.cs", "max_forks_repo_name": "guojianwei001/verySimpleDI", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.4444444444, "max_line_length": 99, "alphanum_fraction": 0.58984375} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VerySimpleDI
{
public class ServiceDescriptor
{
public Type ServiceType { get; set; }
public Type ImplementationType { get; set; }
}
public class Injector
{
private List<ServiceDescriptor> _serviceDescriptors = new List<ServiceDescriptor>();
public void AddTransient<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
{
_serviceDescriptors.Add(new ServiceDescriptor
{
ServiceType = typeof(TService),
ImplementationType = typeof(TImplementation)
});
}
public T GetInstance<T>()
{
Type type = typeof(T);
var instance = this.getInstance(type);
return (T)instance;
}
private object getInstance(Type type)
{
var serviceDescriptor = _serviceDescriptors.FirstOrDefault(x => x.ServiceType == type);
if (serviceDescriptor == null)
{
throw new ArgumentException($"{type.Name} not exist!");
}
var ctorInfo = serviceDescriptor.ImplementationType.GetConstructors().FirstOrDefault();
var prameters = ctorInfo.GetParameters();
var paremeterInstanceList = new List<object>();
foreach (var parameter in prameters)
{
var parameterInstance = this.getInstance(parameter.ParameterType);
paremeterInstanceList.Add(parameterInstance);
}
var instance = ctorInfo.Invoke(paremeterInstanceList.ToArray());
return instance;
}
}
}
|
||||
TheStack | bd473d06169e372414715321e0d60a370aa07116 | C#code:C# | {"size": 2616, "ext": "cs", "max_stars_repo_path": "src/StateStores/Abstractions/IStateChannel.cs", "max_stars_repo_name": "JanDonnermayer/StateStores", "max_stars_repo_stars_event_min_datetime": "2019-11-29T11:05:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-15T00:41:24.000Z", "max_issues_repo_path": "src/StateStores/Abstractions/IStateChannel.cs", "max_issues_repo_name": "JanDonnermayer/StateStores", "max_issues_repo_issues_event_min_datetime": "2019-11-28T23:14:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T22:27:21.000Z", "max_forks_repo_path": "src/StateStores/Abstractions/IStateChannel.cs", "max_forks_repo_name": "JanDonnermayer/StateStores", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 2.0, "max_forks_count": null, "avg_line_length": 42.1935483871, "max_line_length": 93, "alphanum_fraction": 0.6108562691} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace StateStores
{
/// <summary>
/// Providing functionality to interact with a state.
/// </summary>
public interface IStateChannel<TState>
{
/// <summary>
/// Returns an <see cref="IObservable{TState}"/>,
/// that emits the current state,
/// everytime the state of the channel is set from no state to some state,
/// replaying the latest notification (if any) to new subscribers.
/// </summary>
IObservable<TState> OnAdd { get; }
/// <summary>
/// Returns an <see cref="IObservable{TState}"/>,
/// that emits a pair of the previous and the current state,
/// everytime the state of the channel is set from some state to some other state,
/// replaying the latest notification (if any) to new subscribers.
/// </summary>
IObservable<(TState previousState, TState currentState)> OnUpdate { get; }
/// <summary>
/// Returns an <see cref="IObservable{TState}"/>,
/// that emits the previous state,
/// everytime the state of the channel is set from some state to no state,
/// replaying the latest notification (if any) to new subscribers.
/// </summary>
IObservable<TState> OnRemove { get; }
/// <summary>
/// If the channel is currently set to no state,
/// sets it to the specified <paramref name="nextState"/>,
/// else: returns <see cref="StateError"/>
/// </summary>
/// <param name="nextState">The state to set for the channel.</param>
Task<StateStoreResult> AddAsync(TState nextState);
/// <summary>
/// If the channel is currently set to the specified <paramref name="currentState"/>,
/// sets it to the specified <paramref name="nextState"/>,
/// else: returns <see cref="StateError"/>.
/// </summary>
/// <param name="currentState">The expected state of the channel.</param>
/// <param name="nextState">The state to set for the channel.</param>
Task<StateStoreResult> UpdateAsync(TState currentState, TState nextState);
/// <summary>
/// If the channel is currently set to the specified <paramref name="currentState"/>,
/// sets it to no state,
/// else: returns <see cref="StateError"/>.
/// </summary>
/// <param name="currentState">The expected state of the channel.</param>
Task<StateStoreResult> RemoveAsync(TState currentState);
}
}
|
||||
TheStack | bd4779ab8aff358afbc9b532d330a9bf28ec2d5e | C#code:C# | {"size": 3282, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/WindowsManager.cs", "max_stars_repo_name": "nortages/GridGames", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/WindowsManager.cs", "max_issues_repo_name": "nortages/GridGames", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/WindowsManager.cs", "max_forks_repo_name": "nortages/GridGames", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.82, "max_line_length": 82, "alphanum_fraction": 0.6669713589} | using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class WindowsManager : MonoBehaviour
{
[SerializeField] private Button backToMainWin;
[SerializeField] private GameObject mainWindow;
[SerializeField] private GameObject scoresPanel;
[SerializeField] private GameObject scoresWindow;
[SerializeField] private GameObject menuBackground;
[SerializeField] private TextMeshProUGUI pauseScore;
[SerializeField] private TextMeshProUGUI scorePrefab;
[SerializeField] private TextMeshProUGUI mainWinTitle;
[SerializeField] private TextMeshProUGUI gameStateText;
[SerializeField] private string gameWinStatement = "You win!";
[SerializeField] private string gameOverStatement = "Game Over";
[SerializeField] private string gameLoseStatement = "You lose :(";
[SerializeField] private string gamePausedStatement = "Game paused";
[SerializeField] private Color winColor = Color.green;
[SerializeField] private Color loseColor = Color.red;
private bool isScoreWinOpen = false;
public Func<string> formatFunc;
private void Awake()
{
mainWindow.SetActive(false);
menuBackground.SetActive(false);
backToMainWin.onClick.AddListener(OnBackToMain);
}
private void OnBackToMain()
{
isScoreWinOpen = false;
}
public void HideMainWindow()
{
gameStateText.gameObject.SetActive(false);
pauseScore.gameObject.SetActive(false);
menuBackground.SetActive(false);
if (isScoreWinOpen) backToMainWin.onClick.Invoke();
mainWindow.SetActive(false);
}
internal void ShowMainWindow(GameState state, string formattedScore = default)
{
mainWindow.SetActive(true);
menuBackground.SetActive(true);
gameStateText.gameObject.SetActive(true);
if (state == GameState.Win)
{
mainWinTitle.text = gameOverStatement;
gameStateText.text = gameWinStatement;
gameStateText.color = winColor;
pauseScore.gameObject.SetActive(true);
pauseScore.text = $"Your score is {formattedScore}";
}
else if (state == GameState.Lose)
{
mainWinTitle.text = gameOverStatement;
gameStateText.text = gameLoseStatement;
gameStateText.color = loseColor;
}
else if (state == GameState.Paused)
{
mainWinTitle.text = gamePausedStatement;
gameStateText.gameObject.SetActive(false);
}
else if (state == GameState.Over)
{
mainWinTitle.text = gameOverStatement;
pauseScore.text = $"Your score is {formattedScore}";
pauseScore.gameObject.SetActive(true);
gameStateText.gameObject.SetActive(false);
}
}
internal void ShowScoresWindow(IEnumerable<string> scores)
{
isScoreWinOpen = true;
menuBackground.SetActive(true);
scoresWindow.SetActive(true);
scoresPanel.DestroyChildren();
foreach (var score in scores)
{
var scoreObj = Instantiate(scorePrefab, scoresPanel.transform);
scoreObj.text = score;
}
}
}
|
||||
TheStack | bd47aea0fe453fd9c5d26ac3b26bdde4df6a087f | C#code:C# | {"size": 4050, "ext": "cs", "max_stars_repo_path": "src/shared/standard/errorCode.cs", "max_stars_repo_name": "quantitative-technologies/ccxt.net", "max_stars_repo_stars_event_min_datetime": "2020-10-19T17:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:16:07.000Z", "max_issues_repo_path": "src/shared/standard/errorCode.cs", "max_issues_repo_name": "ekrembasari/ccxt.net", "max_issues_repo_issues_event_min_datetime": "2020-11-07T18:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T07:32:18.000Z", "max_forks_repo_path": "src/shared/standard/errorCode.cs", "max_forks_repo_name": "ekrembasari/ccxt.net", "max_forks_repo_forks_event_min_datetime": "2020-11-15T21:48:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T20:37:54.000Z"} | {"max_stars_count": 87.0, "max_issues_count": 16.0, "max_forks_count": 31.0, "avg_line_length": 27.1812080537, "max_line_length": 102, "alphanum_fraction": 0.5358024691} | using System.ComponentModel;
namespace CCXT.NET.Shared.Coin
{
/// <summary>
/// Type of nonce styles
/// </summary>
public enum ErrorCode : int
{
/// <summary>
/// general failure
/// </summary>
[Description("general failure")]
Failure = -1,
/// <summary>
/// general success
/// </summary>
[Description("general success")]
Success = 0,
/// <summary>
///
/// </summary>
[Description("rest response error")]
ResponseRestError = 100,
/// <summary>
///
/// </summary>
[Description("response data error")]
ResponseDataError = 101,
/// <summary>
///
/// </summary>
[Description("response data empty")]
ResponseDataEmpty = 102,
/// <summary>
///
/// </summary>
[Description("not found data")]
NotFoundData = 103,
/// <summary>
///
/// </summary>
[Description("not supported error")]
NotSupported,
/// <summary>
/// your time is ahead of server
/// </summary>
[Description("your time is ahead of server")]
InvalidNonce,
/// <summary>
/// Insufficient balance available for withdrawal
/// </summary>
[Description("insufficient balance available for withdrawal")]
InsufficientFunds,
/// <summary>
///
/// </summary>
[Description("cancel pending")]
CancelPending,
/// <summary>
/// Too many address
/// </summary>
[Description("too many address")]
TooManyAddress,
/// <summary>
/// Invalid amount
/// </summary>
[Description("invalid amount")]
InvalidAmount,
/// <summary>
/// Does not support market orders
/// </summary>
[Description("does not support market orders")]
InvalidOrder,
/// <summary>
/// no found order
/// </summary>
[Description("no found order")]
UnknownOrder,
/// <summary>
///
/// </summary>
[Description("unknown withdraw")]
UnknownWithdraw,
/// <summary>
/// operation failed! Orders have been completed or revoked, Unknown reference id
/// </summary>
[Description("operation failed! orders have been completed or revoked, unknown reference id")]
OrderNotFound,
/// <summary>
/// The signature did not match the expected signature
/// </summary>
[Description("the signature did not match the expected signature")]
InvalidSignature,
/// <summary>
/// Google authenticator is wrong, signature failed, API Authentication failed
/// </summary>
[Description("google authenticator is wrong, signature failed, api authentication failed")]
AuthenticationError,
/// <summary>
/// wrong apikey permissions
/// </summary>
[Description("wrong apikey permissions")]
PermissionDenied,
/// <summary>
/// API function do not exist, Invalid parameter
/// </summary>
[Description("api function do not exist, invalid parameter")]
ExchangeError,
/// <summary>
/// current network is unstable, Maintenance work in progress
/// API interface is locked or not enabled
/// </summary>
[Description("current network is unstable, maintenance work in progress")]
ExchangeNotAvailable,
/// <summary>
/// Requests were made too frequently
/// </summary>
[Description("requests were made too frequently")]
RateLimit,
/// <summary>
/// server busy please try again later, request too often
/// </summary>
[Description("server busy please try again later, request too often")]
DDoSProtection
}
} |
||||
TheStack | bd49a80e3b5d7f407ba2a03dcc94b7a158cc6556 | C#code:C# | {"size": 708, "ext": "cs", "max_stars_repo_path": "H5/H5/System/Diagnostics/Contracts/ContractException.cs", "max_stars_repo_name": "thomz12/h5", "max_stars_repo_stars_event_min_datetime": "2020-05-18T17:33:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T22:24:06.000Z", "max_issues_repo_path": "H5/H5/System/Diagnostics/Contracts/ContractException.cs", "max_issues_repo_name": "thomz12/h5", "max_issues_repo_issues_event_min_datetime": "2020-05-13T12:02:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T22:53:37.000Z", "max_forks_repo_path": "H5/H5/System/Diagnostics/Contracts/ContractException.cs", "max_forks_repo_name": "thomz12/h5", "max_forks_repo_forks_event_min_datetime": "2020-05-21T13:58:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T15:30:23.000Z"} | {"max_stars_count": 75.0, "max_issues_count": 54.0, "max_forks_count": 7.0, "avg_line_length": 24.4137931034, "max_line_length": 146, "alphanum_fraction": 0.604519774} | namespace System.Diagnostics.Contracts
{
[H5.Convention(Member = H5.ConventionMember.Field | H5.ConventionMember.Method, Notation = H5.Notation.CamelCase)]
[H5.External]
public sealed class ContractException : Exception
{
public extern ContractFailureKind Kind
{
get;
}
public extern string Failure
{
get;
}
public extern string UserMessage
{
get;
}
public extern string Condition
{
get;
}
public extern ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException);
}
} |
||||
TheStack | bd4d6d1fdf99b8981497b40c8f5c34c8fc135640 | C#code:C# | {"size": 1149, "ext": "cs", "max_stars_repo_path": "AutoTestPrep/dev/src/MinUnitDriverCodeGenerator/CodeGenerator/MinUnitCodeGenerator.cs", "max_stars_repo_name": "CountrySideEngineer/TestSupportTools", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AutoTestPrep/dev/src/MinUnitDriverCodeGenerator/CodeGenerator/MinUnitCodeGenerator.cs", "max_issues_repo_name": "CountrySideEngineer/TestSupportTools", "max_issues_repo_issues_event_min_datetime": "2021-08-08T00:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:33:13.000Z", "max_forks_repo_path": "AutoTestPrep/dev/src/MinUnitDriverCodeGenerator/CodeGenerator/MinUnitCodeGenerator.cs", "max_forks_repo_name": "CountrySideEngineer/TestSupportTools", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 12.0, "max_forks_count": null, "avg_line_length": 26.7209302326, "max_line_length": 85, "alphanum_fraction": 0.6884247171} | using CodeGenerator.Data;
using CodeGenerator.TestDriver.Template;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeGenerator.TestDriver.MinUnit
{
public abstract class MinUnitCodeGenerator : ICodeGenerator
{
/// <summary>
/// Generate test driver code using min_unit test framework.
/// </summary>
/// <param name="data">Data for code.</param>
/// <returns>Generated test driver code.</returns>
public string Generate(WriteData data)
{
Debug.Assert(null != data, $"{nameof(MinUnitCodeGenerator)}.{nameof(Generate)}");
try
{
var template = this.CreateTemplate(data);
return template.TransformText();
}
catch (Exception ex)
when ((ex is ArgumentNullException) || (ex is NullReferenceException))
{
Debug.WriteLine(ex.StackTrace);
throw;
}
}
/// <summary>
/// Abstract method to create template.
/// </summary>
/// <returns>StubTemplate class.</returns>
protected abstract MinUnitTemplate CreateTemplate(WriteData writeData);
}
}
|
||||
TheStack | bd4e6ebc8965344eeec7de84314346a1aba12c2e | C#code:C# | {"size": 7185, "ext": "cs", "max_stars_repo_path": "OpenLogger.Sample.MVVM/ViewModels/LoggingViewModel.cs", "max_stars_repo_name": "mtnman1010/OpenLogger", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OpenLogger.Sample.MVVM/ViewModels/LoggingViewModel.cs", "max_issues_repo_name": "mtnman1010/OpenLogger", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OpenLogger.Sample.MVVM/ViewModels/LoggingViewModel.cs", "max_forks_repo_name": "mtnman1010/OpenLogger", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.5693069307, "max_line_length": 140, "alphanum_fraction": 0.5682672234} | using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Command;
namespace OpenLogger.Sample.MVVM.ViewModels
{
public class LoggingViewModel : ViewModel, IHaveLoggerGroup, ILog
{
public enum LogOrderBy
{
Ascending = 0,
Descending = 1
}
private CrossThreadObservableCollection<LogEventArgs> logs;
private int logGroupId;
private LogOrderBy logOrder;
//private LogSeverity selectedLogSeverity;
private ObservableCollection<LogSeverity> logSeverities;
private ObservableCollection<LogSeverity> defaultSelectedLogSeverities;
private ObservableCollection<LogSeverity> selectedLogSeverities;
public LoggingViewModel(Dispatcher dispatcher, LoggerFacade loggerFacade)
{
this.Dispatcher = dispatcher;
Title = "Logging";
LoggerFacade = loggerFacade; // Option 1: Pass facade in since Group is defined outside LoggerViewModel
LoggerFacade.Logger = Logger.Instance;
logGroupId = loggerFacade.GroupId;
Logger.Instance.Attach(this);
logSeverities = new ObservableCollection<LogSeverity>(Enum.GetValues(typeof(LogSeverity)).Cast<LogSeverity>());
logOrder = LogOrderBy.Ascending;
defaultSelectedLogSeverities = new ObservableCollection<LogSeverity>(Enum.GetValues(typeof(LogSeverity)).Cast<LogSeverity>()); ;
RefreshLogCollection();
LoggerFacade.LogVerbose("Initialized Group Logging");
LogFilterChangedCommand = new RelayCommand(LogFilterChanged);
CopyLogItemCommand = new RelayCommand<LogEventArgs>(CopyLogItem);
CopyAllLogItemsCommand = new RelayCommand(CopyAllLogItems);
}
~LoggingViewModel()
{
Logger.Instance.Detach(this);
}
public ICommand LogFilterChangedCommand { get; set; }
public ICommand CopyLogItemCommand { get; set; }
public ICommand CopyAllLogItemsCommand { get; set; }
// Option 2: Use IHaveLoggerGroup setter to pass in Log Group Id since Group is defined outside LoggerViewModel
public int LogGroupId
{
get { return logGroupId; }
set
{
if (logGroupId != value)
{
logGroupId = value;
RefreshLogCollection();
}
}
}
public LogOrderBy LogOrder
{
get { return logOrder; }
set
{
if (logOrder != value)
{
logOrder = value;
RefreshLogCollection();
}
}
}
public ObservableCollection<LogOrderBy> LogOrdering
{
get { return new ObservableCollection<LogOrderBy>(Enum.GetValues(typeof(LogOrderBy)).Cast<LogOrderBy>()); }
}
public ObservableCollection<LogSeverity> LogSeverities
{
get
{
return logSeverities;
}
}
public ObservableCollection<LogSeverity> DefaultSelectedLogSeverities
{
get
{
return defaultSelectedLogSeverities;
}
set
{
defaultSelectedLogSeverities = value;
RefreshLogCollection();
}
}
public CrossThreadObservableCollection<LogEventArgs> Logs
{
get { return logs; }
set { Update(() => Logs, ref logs, value, false); }
}
public void Log(object sender, LogEventArgs e)
{
if (LogGroupId == 0)
{
if (logOrder == LogOrderBy.Ascending)
Logs.Add(e); // Add to bottom (must scroll)
else
Logs.Insert(0, e); // Add to top (visible)
}
else if (e.GroupId == LogGroupId)
{
if (logOrder == LogOrderBy.Ascending)
Logs.Add(e); // Add to bottom (must scroll)
else
Logs.Insert(0, e); // Add to top (visible)
}
//RefreshLogCollection();
}
private void LogFilterChanged()
{
RefreshLogCollection();
}
private void CopyLogItem(LogEventArgs logEventArg)
{
Clipboard.SetText(FormatLogEventArgString(logEventArg));
}
private void CopyAllLogItems()
{
var sb = new StringBuilder();
foreach (var logEventArg in Logs)
{
sb.Append(FormatLogEventArgString(logEventArg));
sb.Append(Environment.NewLine);
}
Clipboard.SetText(sb.ToString());
}
private void RefreshLogCollection()
{
if (LogGroupId == 0)
{
Logs = LogOrder == LogOrderBy.Ascending
? new CrossThreadObservableCollection<LogEventArgs>(Dispatcher,
LoggerFacade.Logger.Buffer.Where(x => defaultSelectedLogSeverities.Contains(x.Severity)))
: new CrossThreadObservableCollection<LogEventArgs>(Dispatcher,
LoggerFacade.Logger.Buffer.Where(x => defaultSelectedLogSeverities.Contains(x.Severity))
.OrderByDescending(x => x.Timestamp));
}
else
{
Logs = LogOrder == LogOrderBy.Ascending
? new CrossThreadObservableCollection<LogEventArgs>(Dispatcher,
LoggerFacade.Logger.Buffer.Where(x => defaultSelectedLogSeverities.Contains(x.Severity) && x.GroupId == LogGroupId))
: new CrossThreadObservableCollection<LogEventArgs>(Dispatcher,
LoggerFacade.Logger.Buffer.Where(x => defaultSelectedLogSeverities.Contains(x.Severity) && x.GroupId == LogGroupId)
.OrderByDescending(x => x.Timestamp));
}
}
private string FormatLogEventArgString(LogEventArgs logEventArg)
{
var sb = new StringBuilder();
sb.Append(string.Format("{0} - [{1}] ({2}) {3}", logEventArg.SeverityString,
logEventArg.Timestamp, logEventArg.Origin, logEventArg.Message));
sb.Append(FormatLogEventArgExceptionString(logEventArg.Exception));
return sb.ToString();
}
private string FormatLogEventArgExceptionString(Exception ex)
{
if (ex == null)
return string.Empty;
var sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append("Exception: " + ex.Message + Environment.NewLine);
sb.Append("Stack Trace: " + ex.StackTrace);
sb.Append(FormatLogEventArgExceptionString(ex.InnerException));
return sb.ToString();
}
}
}
|
||||
TheStack | bd4ed95c5970c5c7e59b7b1f7625f5f615b11997 | C#code:C# | {"size": 2669, "ext": "cs", "max_stars_repo_path": "AidEstimation.Web/Simple/Dependent.aspx.cs", "max_stars_repo_name": "pennym-davis/.Net_Financial_Aid_Est_constants", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AidEstimation.Web/Simple/Dependent.aspx.cs", "max_issues_repo_name": "pennym-davis/.Net_Financial_Aid_Est_constants", "max_issues_repo_issues_event_min_datetime": "2015-01-23T21:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T06:41:14.000Z", "max_forks_repo_path": "AidEstimation.Web/Simple/Dependent.aspx.cs", "max_forks_repo_name": "pennym-davis/.Net_Financial_Aid_Est_constants", "max_forks_repo_forks_event_min_datetime": "2015-12-03T00:10:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T17:41:16.000Z"} | {"max_stars_count": null, "max_issues_count": 12.0, "max_forks_count": 3.0, "avg_line_length": 44.4833333333, "max_line_length": 120, "alphanum_fraction": 0.6448107906} | using System;
using System.Linq;
using Ucsb.Sa.FinAid.AidEstimation.EfcCalculation;
using Ucsb.Sa.FinAid.AidEstimation.EfcCalculation.Arguments;
using Ucsb.Sa.FinAid.AidEstimation.Utility;
namespace Ucsb.Sa.FinAid.AidEstimation.Web.Simple
{
public partial class Dependent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// Collect user input
RawSimpleDependentEfcCalculatorArguments rawArgs = new RawSimpleDependentEfcCalculatorArguments();
rawArgs.MaritalStatus = inputMaritalStatus.SelectedValue;
rawArgs.StateOfResidency = inputStateOfResidency.SelectedValue;
rawArgs.ParentIncome = inputParentIncome.Text;
rawArgs.ParentOtherIncome = inputParentOtherIncome.Text;
rawArgs.ParentIncomeEarnedBy = inputParentIncomeEarnedBy.SelectedValue;
rawArgs.ParentIncomeTax = inputParentIncomeTax.Text;
rawArgs.ParentAssets = inputParentAssets.Text;
rawArgs.StudentIncome = inputStudentIncome.Text;
rawArgs.StudentOtherIncome = inputStudentOtherIncome.Text;
rawArgs.StudentIncomeTax = inputStudentIncomeTax.Text;
rawArgs.StudentAssets = inputStudentAssets.Text;
rawArgs.NumberInCollege = inputNumberInCollege.Text;
rawArgs.NumberInHousehold = inputNumberInHousehold.Text;
// Validate user input
AidEstimationValidator validator = new AidEstimationValidator();
DependentEfcCalculatorArguments args = validator.ValidateSimpleDependentEfcCalculatorArguments(rawArgs);
// If validation fails, display errors
if (validator.Errors.Any())
{
errorList.DataSource = validator.Errors;
errorList.DataBind();
return;
}
// Calculate
EfcCalculator calculator = EfcCalculatorConfigurationManager.GetEfcCalculator("2223");
EfcProfile profile = calculator.GetDependentEfcProfile(args);
// Display Results
formPlaceholder.Visible = false;
resultsPlaceholder.Visible = true;
studentContributionOutput.Text = profile.StudentContribution.ToString();
parentContributionOutput.Text = profile.ParentContribution.ToString();
expectedFamilyContributionOutput.Text = profile.ExpectedFamilyContribution.ToString();
}
}
}
} |
||||
TheStack | bd50aee203ecf591ae1e9e455b8a02e1925dce91 | C#code:C# | {"size": 7269, "ext": "cs", "max_stars_repo_path": "XRD.LibraryCatalog/XRD.LibraryCatalog/GoogleBooksApi/ResultContracts.cs", "max_stars_repo_name": "hilldata/LibraryCatalog", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "XRD.LibraryCatalog/XRD.LibraryCatalog/GoogleBooksApi/ResultContracts.cs", "max_issues_repo_name": "hilldata/LibraryCatalog", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "XRD.LibraryCatalog/XRD.LibraryCatalog/GoogleBooksApi/ResultContracts.cs", "max_forks_repo_name": "hilldata/LibraryCatalog", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.5340909091, "max_line_length": 169, "alphanum_fraction": 0.6408034117} | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace XRD.LibCat.GoogleBooksApi {
/// <summary>
/// The root of the result response from a Google Books API request.
/// </summary>
[DataContract]
public class SearchResult {
/// <summary>
/// The results kind (should be "books#volumes" [plural])
/// </summary>
[DataMember(Name = "kind")]
public string Kind { get; set; }
[DataMember(Name = "totalItems")]
string totalItems { get; set; }
[DataMember(Name = "items")]
public List<BookVolume> Items { get; set; }
/// <summary>
/// The total number of items that matched the search parameters.
/// </summary>
public int? TotalItems => int.TryParse(totalItems, out int res) ? res : (int?)null;
}
/// <summary>
/// The root item in the list.
/// </summary>
[DataContract]
public class BookVolume {
/// <summary>
/// The result kind (should be "books#volume" [singular]).
/// </summary>
[DataMember(Name = "kind")]
public string Kind { get; set; }
/// <summary>
/// The GoogleID for the book.
/// </summary>
[DataMember(Name = "id")]
public string GoogleId { get; set; }
/// <summary>
/// Subclass containing the details of the book.
/// </summary>
[DataMember(Name = "volumeInfo")]
public VolumeInfo VolumeInfo { get; set; }
public override string ToString() => System.Text.Json.JsonSerializer.Serialize(this);
}
/// <summary>
/// Class containing the interesting data for a specific Book Volume (many fields of the Google Books API result are ignored).
/// </summary>
[DataContract]
public class VolumeInfo {
/// <summary>
/// The Title of the book.
/// </summary>
[DataMember(Name = "title")]
public string Title { get; set; }
/// <summary>
/// The Subtitle for the book.
/// </summary>
[DataMember(Name = "subtitle")]
public string Subtitle { get; set; }
/// <summary>
/// List of Authors
/// </summary>
[DataMember(Name = "authors")]
public List<string> Authors { get; set; }
/// <summary>
/// The name of the publisher
/// </summary>
[DataMember(Name = "publisher")]
public string Publisher { get; set; }
[DataMember(Name = "publishedDate")]
public string publishedDate { get; set; }
/// <summary>
/// Brief description of the book.
/// </summary>
[DataMember(Name = "description")]
public string Description { get; set; }
/// <summary>
/// List of Industry Identifiers (ISBNs)
/// </summary>
[DataMember(Name = "industryIdentifiers")]
public List<IndustryIdentifier> IndustryIdentifiers { get; set; }
[DataMember(Name = "pageCount")]
string pageCount { get; set; }
/// <summary>
/// Categories (subjects) the book is listed under.
/// </summary>
[DataMember(Name = "categories")]
public List<string> Categories { get; set; }
/// <summary>
/// ImageLink subclass (contains thumbnail URLs)
/// </summary>
[DataMember(Name = "ImageLink")]
public List<ImageLink> ImageLink { get; set; }
#region Read-Only Properties
/// <summary>
/// The date the book was published.
/// </summary>
/// <remarks>
/// Some sample dates could not be parsed, so this performs a TryParse on the "publishedDate" string value.
/// </remarks>
public DateTime? PublishedDate => DateTime.TryParse(publishedDate, out DateTime res) ? res : (DateTime?)null;
/// <summary>
/// The actual string value of the "publishedDate" as was read from the API.
/// </summary>
public string PublishedDateAsString => publishedDate;
/// <summary>
/// A single string containing all authors.
/// </summary>
public string AuthorDisplay {
get {
if (Authors == null || Authors.Count < 1)
return null;
if (Authors.Count == 1)
return Authors[0];
System.Text.StringBuilder sb = new System.Text.StringBuilder(Authors[0]);
for (int i = 1; i < Authors.Count; i++) {
sb.Append("; ");
sb.Append(Authors[i]);
}
return sb.ToString();
}
}
/// <summary>
/// A single string containing all ISBNs
/// </summary>
public string IsbnDisplay {
get {
if (IndustryIdentifiers == null || IndustryIdentifiers.Count < 1)
return null;
if (IndustryIdentifiers.Count == 1)
return IndustryIdentifiers[0].Identifier;
System.Text.StringBuilder sb = new System.Text.StringBuilder(IndustryIdentifiers[0].Identifier);
for (int i = 1; i < IndustryIdentifiers.Count; i++) {
sb.Append("; ");
sb.Append(IndustryIdentifiers[i].Identifier);
}
return sb.ToString();
}
}
/// <summary>
/// Get a URL to use as the source for the volume's image.
/// </summary>
public string ImageUrl {
get {
if (ImageLink == null || ImageLink.Count < 1)
return null;
for (int i = 0; i < ImageLink.Count; i++) {
if (!string.IsNullOrWhiteSpace(ImageLink[i].Thumbnail))
return ImageLink[i].Thumbnail;
if (!string.IsNullOrWhiteSpace(ImageLink[i].SmallThumbnail))
return ImageLink[i].SmallThumbnail;
}
return null;
}
}
/// <summary>
/// The number of pages in the book.
/// </summary>
/// <remarks>
/// Performs a TryParse on the value read from the API. This is due to the fact that several samples were either null or empty strings or contained invalid characters.
/// </remarks>
public int? PageCount => int.TryParse(pageCount, out int res) ? res : (int?)null;
#endregion
}
/// <summary>
/// Class representing the ImageLinks (front cover thumbs) for a book.
/// </summary>
[DataContract]
public class ImageLink {
/// <summary>
/// The URL to the small thumbnail for the book.
/// </summary>
[DataMember(Name = "smallThumbnail")]
public string SmallThumbnail { get; set; }
/// <summary>
/// The URL to the thumbnail for the book.
/// </summary>
[DataMember(Name = "thumbnail")]
public string Thumbnail { get; set; }
private const string GOOGLE_IMAGE_CURL_PARM = "&edge=";
public string ImageUrl {
get {
string url = string.Empty;
if (string.IsNullOrWhiteSpace(Thumbnail)) {
if (string.IsNullOrWhiteSpace(SmallThumbnail))
return null;
else
url = SmallThumbnail;
} else {
url = Thumbnail;
}
if (string.IsNullOrWhiteSpace(url))
return null;
if (url.Contains(GOOGLE_IMAGE_CURL_PARM)) {
int i1 = url.IndexOf(GOOGLE_IMAGE_CURL_PARM);
int i2 = url.IndexOf("&", i1 + 1);
if (i2 < i1) // no further ampersands were found after the curl.
return url.Substring(0, 1);
else
return url.Remove(i1, i2 - i1);
} else
return url;
}
}
}
/// <summary>
/// Class representing an item of a list of Industry Identifier values.
/// </summary>
[DataContract]
public class IndustryIdentifier {
/// <summary>
/// The type of identifier
/// </summary>
[DataMember(Name = "type")]
public string Type { get; set; }
/// <summary>
/// The value of the identifier
/// </summary>
[DataMember(Name = "identifier")]
public string Identifier { get; set; }
/// <summary>
/// The type value for ISBN-13 identifiers
/// </summary>
public const string ISBN13 = "ISBN_13";
/// <summary>
/// The type value for ISBN-10 identifiers.
/// </summary>
public const string ISBN10 = "ISBN_10";
}
} |
||||
TheStack | bd52c49add3b700e1c11264787c39529cea003c1 | C#code:C# | {"size": 534, "ext": "cs", "max_stars_repo_path": "src/FuelWerx.Application/Authorization/Users/Dto/GetUserForEditOutput.cs", "max_stars_repo_name": "zberg007/project", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FuelWerx.Application/Authorization/Users/Dto/GetUserForEditOutput.cs", "max_issues_repo_name": "zberg007/project", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FuelWerx.Application/Authorization/Users/Dto/GetUserForEditOutput.cs", "max_forks_repo_name": "zberg007/project", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 12.4186046512, "max_line_length": 53, "alphanum_fraction": 0.670411985} | using Abp.Application.Services.Dto;
using System;
using System.Runtime.CompilerServices;
namespace FuelWerx.Authorization.Users.Dto
{
public class GetUserForEditOutput : IOutputDto, IDto
{
public int? ConvertToUserCustomerId
{
get;
set;
}
public Guid? ProfilePictureId
{
get;
set;
}
public UserRoleDto[] Roles
{
get;
set;
}
public UserEditDto User
{
get;
set;
}
public UserSettingDataEditDto UserSettingData
{
get;
set;
}
public GetUserForEditOutput()
{
}
}
} |
||||
TheStack | bd579a367eff64546a9448c5c64e0e3f7bd15195 | C#code:C# | {"size": 5996, "ext": "cs", "max_stars_repo_path": "UnityVrSandbox/Assets/External/New UI Widgets/Editor/AssemblyDefinitionsEditor.cs", "max_stars_repo_name": "cschladetsch/UnityTemplate", "max_stars_repo_stars_event_min_datetime": "2019-08-26T18:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:15:23.000Z", "max_issues_repo_path": "UnityVrSandbox/Assets/External/New UI Widgets/Editor/AssemblyDefinitionsEditor.cs", "max_issues_repo_name": "cschladetsch/UnityTemplate", "max_issues_repo_issues_event_min_datetime": "2020-03-29T21:52:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T05:34:14.000Z", "max_forks_repo_path": "UnityVrSandbox/Assets/External/New UI Widgets/Editor/AssemblyDefinitionsEditor.cs", "max_forks_repo_name": "cschladetsch/UnityTemplate", "max_forks_repo_forks_event_min_datetime": "2021-02-16T11:26:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T07:37:18.000Z"} | {"max_stars_count": 9.0, "max_issues_count": 28.0, "max_forks_count": 2.0, "avg_line_length": 34.0681818182, "max_line_length": 157, "alphanum_fraction": 0.7169779853} | namespace UIWidgets
{
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Assembly definitions editor.
/// </summary>
public static class AssemblyDefinitionsEditor
{
#if UNITY_2018_1_OR_NEWER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Reviewed.")]
[Serializable]
class AssemblyDefinition
{
/// <summary>
/// Path.
/// </summary>
[NonSerialized]
public string Path;
/// <summary>
/// Assembly name.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Reviewed.")]
public string name = string.Empty;
/// <summary>
/// References.
/// </summary>
public List<string> references = new List<string>();
/// <summary>
/// Optional references.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Reviewed.")]
public List<string> optionalUnityReferences = new List<string>();
/// <summary>
/// Include platforms.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Reviewed.")]
public List<string> includePlatforms = new List<string>();
/// <summary>
/// Exclude platforms.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Reviewed.")]
public List<string> excludePlatforms = new List<string>();
/// <summary>
/// Allow unsafe code.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Reviewed.")]
public bool allowUnsafeCode = false;
}
static readonly Dictionary<string, string[]> cachedGUIDs = new Dictionary<string, string[]>()
{
{ "l:UiwidgetsTMProRequiredAssemblyDefinition", new string[] {
"9b890130495c8904b9dcfaf28273b376", // New UI Widgets/Editor/UIWidgets.Editor.asmdef
"6db589689499ad14c8b33ef4478bb29d", // New UI Widgets/Examples/Editor/UIWidgets.Examples.Editor.asmdef
"ce661a99e9e51a34eb04bd42897d8e4c", // New UI Widgets/Examples/UIWidgets.Examples.asmdef
"8158a7b0409ed1b49a27393c5d96ca43", // New UI Widgets/Scripts/Style/Editor/UIWidgets.Styles.Editor.asmdef
"77b640ebe03a1194598db26ced37dd6e", // New UI Widgets/Scripts/UIWidgets.asmdef
} },
};
static List<AssemblyDefinition> Get(string search)
{
var guids = cachedGUIDs.ContainsKey(search)
? cachedGUIDs[search]
: AssetDatabase.FindAssets(search);
var result = new List<AssemblyDefinition>(guids.Length);
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
if (string.IsNullOrEmpty(path))
{
Debug.LogWarning("Path not found for the GUID: " + guid);
continue;
}
var asset = Compatibility.LoadAssetAtPath<TextAsset>(path);
if (asset != null)
{
var json = JsonUtility.FromJson<AssemblyDefinition>(asset.text);
json.Path = path;
result.Add(json);
}
}
return result;
}
#endif
/// <summary>
/// Add reference to assemblies.
/// </summary>
/// <param name="search">Search string for assemblies.</param>
/// <param name="reference">Reference.</param>
#if !UNITY_2018_1_OR_NEWER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "search", Justification = "Reviewed.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "reference", Justification = "Reviewed.")]
#endif
public static void Add(string search, string reference)
{
#if UNITY_2018_1_OR_NEWER
var assemblies = Get(search);
foreach (var assembly in assemblies)
{
if (!assembly.references.Contains(reference))
{
assembly.references.Add(reference);
File.WriteAllText(assembly.Path, JsonUtility.ToJson(assembly, true));
}
}
#endif
}
/// <summary>
/// Check if matched assemblies contains specified reference.
/// </summary>
/// <param name="search">Search string for assemblies.</param>
/// <param name="reference">Reference.</param>
/// <returns>true if all assemblies contains specified reference; otherwise false</returns>
#if !UNITY_2018_1_OR_NEWER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "search", Justification = "Reviewed.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "reference", Justification = "Reviewed.")]
#endif
public static bool Contains(string search, string reference)
{
#if UNITY_2018_1_OR_NEWER
var assemblies = Get(search);
foreach (var assembly in assemblies)
{
if (!assembly.references.Contains(reference))
{
return false;
}
}
#endif
return true;
}
/// <summary>
/// Remove reference from assemblies.
/// </summary>
/// <param name="search">Search string for assemblies.</param>
/// <param name="reference">Reference.</param>
#if !UNITY_2018_1_OR_NEWER
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "search", Justification = "Reviewed")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "reference", Justification = "Reviewed")]
#endif
public static void Remove(string search, string reference)
{
#if UNITY_2018_1_OR_NEWER
var assemblies = Get(search);
foreach (var assembly in assemblies)
{
assembly.references.Remove(reference);
File.WriteAllText(assembly.Path, JsonUtility.ToJson(assembly, true));
}
#endif
}
}
} |
||||
TheStack | bd58c30845f8e0fc0d974f179c465a5cf04fe7ab | C#code:C# | {"size": 4104, "ext": "cs", "max_stars_repo_path": "Questing/QuestManager.cs", "max_stars_repo_name": "ValentinGurkov/Unity-RPG-Scripts", "max_stars_repo_stars_event_min_datetime": "2019-10-08T13:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T13:35:44.000Z", "max_issues_repo_path": "Questing/QuestManager.cs", "max_issues_repo_name": "ValentinGurkov/Unity-RPG-Scripts", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Questing/QuestManager.cs", "max_forks_repo_name": "ValentinGurkov/Unity-RPG-Scripts", "max_forks_repo_forks_event_min_datetime": "2019-12-26T03:13:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T02:49:00.000Z"} | {"max_stars_count": 12.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 32.832, "max_line_length": 108, "alphanum_fraction": 0.5397173489} | using System;
using RPG.Saving;
using RPG.UI;
using UnityEngine;
namespace RPG.Questing
{
public class QuestManager : MonoBehaviour, ISaveable
{
[SerializeField] private QuestToDisplay questHUD;
private Quest m_LatestQuest;
private StageS m_LatestStage;
private QuestGiver m_QuestGiver;
private string m_QuestGiverName;
private void OnDisable()
{
if (m_LatestQuest == null) return;
m_LatestQuest.OnQuestCompleted -= QuestHasBeenCompleted;
for (int i = 0; i < m_LatestQuest.Stages.Count; i++)
{
m_LatestQuest.Stages[i].OnStageActivated -= StageHasBeenActivated;
for (int j = 0; j < m_LatestQuest.Stages[i].Goals.Count; j++)
{
m_LatestQuest.Stages[i].Goals[j].OnGoalCompleted -= questHUD.UpdateQuestDisplay;
}
}
}
private void OnEnable()
{
AttachEvents();
}
private void AttachEvents()
{
if (m_LatestQuest == null) return;
m_LatestQuest.OnQuestCompleted += QuestHasBeenCompleted;
for (int i = 0; i < m_LatestQuest.Stages.Count; i++)
{
m_LatestQuest.Stages[i].OnStageActivated += StageHasBeenActivated;
if (m_LatestQuest.Stages[i].Active)
{
m_LatestStage = m_LatestQuest.Stages[i];
}
for (int j = 0; j < m_LatestQuest.Stages[i].Goals.Count; j++)
{
m_LatestQuest.Stages[i].Goals[j].OnGoalCompleted += questHUD.UpdateQuestDisplay;
}
}
}
public void OnPlayeAction(string context)
{
if (m_LatestStage == null || m_LatestQuest.Completed) return;
for (int i = 0; i < m_LatestStage.Goals.Count; i++)
{
if (!m_LatestStage.Goals[i].Completed)
{
m_LatestStage.Goals[i].Evaluate(context);
}
}
}
private void QuestHasBeenCompleted()
{
m_QuestGiver.MarkQuestCompleted();
questHUD.DisplayDefaultText();
}
private void StageHasBeenActivated(StageS stage)
{
m_LatestStage = stage;
questHUD.UpdateQuestDisplay(stage);
}
public void AddQuest(QuestGiver qg, Quest quest)
{
if (qg == null || quest == null)
{
return;
}
m_QuestGiverName = qg.name;
m_QuestGiver = qg;
m_LatestQuest = Instantiate(quest);
m_LatestQuest.Init();
AttachEvents();
questHUD.UpdateQuestDisplay(m_LatestStage);
}
public object CaptureState()
{
if (m_LatestQuest == null) return new Tuple<string, string, int>(null, null, 0);
// fix scene prefab overrides!
QuestSaver.Save(m_LatestQuest);
return new Tuple<string, string, int>(m_LatestQuest.ID, m_QuestGiverName,
m_LatestQuest.Stages.IndexOf(m_LatestStage));
}
public void RestoreState(object state)
{
if (m_LatestQuest != null) return;
(string questName, string questGiverName, int latestStage) = (Tuple<string, string, int>) state;
if (string.IsNullOrEmpty(questName)) return;
m_LatestQuest = QuestSaver.Load(questName);
m_QuestGiverName = questGiverName;
if (!string.IsNullOrEmpty(m_QuestGiverName))
{
GameObject qgGObj = GameObject.Find(m_QuestGiverName);
if (qgGObj != null)
{
m_QuestGiver = qgGObj.GetComponent<QuestGiver>();
}
}
m_LatestQuest.Init();
m_LatestStage = m_LatestQuest.Stages[latestStage];
AttachEvents();
questHUD.UpdateQuestDisplay(m_LatestStage);
}
}
} |
||||
TheStack | bd58cebf98ca2ffb70b5cc8fe0cb9c9b85936a57 | C#code:C# | {"size": 1704, "ext": "cs", "max_stars_repo_path": "SpringBoneAssistant.cs", "max_stars_repo_name": "Wally869/Unity-Spring-Bone-Assistant", "max_stars_repo_stars_event_min_datetime": "2020-09-25T15:09:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T20:34:15.000Z", "max_issues_repo_path": "SpringBoneAssistant.cs", "max_issues_repo_name": "Wally869/Unity-Spring-Bone-Assistant", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SpringBoneAssistant.cs", "max_forks_repo_name": "Wally869/Unity-Spring-Bone-Assistant", "max_forks_repo_forks_event_min_datetime": "2021-01-22T13:27:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T21:03:10.000Z"} | {"max_stars_count": 10.0, "max_issues_count": null, "max_forks_count": 7.0, "avg_line_length": 27.9344262295, "max_line_length": 88, "alphanum_fraction": 0.5845070423} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpringBoneAssistant : MonoBehaviour
{
public UnityChan.SpringManager mSpringManager;
public Vector3 mTargetBoneAxis = new Vector3(0f, 1f, 0f);
public void MarkChildren()
{
//List<SpringBoneMarker> boneMarkers = new List<SpringBoneMarker>();
// get spring bones set
SpringBoneMarker[] boneMarkers = FindObjectsOfType<SpringBoneMarker>();
// mark children
for (int i = 0; i < boneMarkers.Length; i++)
{
boneMarkers[i].MarkChildren();
}
// get again, will include children
boneMarkers = FindObjectsOfType<SpringBoneMarker>();
List<UnityChan.SpringBone> springBones = new List<UnityChan.SpringBone> { };
for (int i = 0; i < boneMarkers.Length; i++)
{
// add spring bone
springBones.Add(boneMarkers[i].AddSpringBone());
// set vector
springBones[i].boneAxis = mTargetBoneAxis;
// unmark object
boneMarkers[i].UnmarkSelf();
}
mSpringManager.springBones = springBones.ToArray();
}
public void CleanUp()
{
SpringBoneMarker[] boneMarkers = FindObjectsOfType<SpringBoneMarker>();
UnityChan.SpringBone[] springBones = FindObjectsOfType<UnityChan.SpringBone>();
for (int i = 0; i < boneMarkers.Length; i++)
{
DestroyImmediate(boneMarkers[i]);
}
for (int i = 0; i < springBones.Length; i++)
{
DestroyImmediate(springBones[i]);
}
}
}
|
||||
TheStack | bd5947e7ea626310d91acc4c6d3cb2cd06f2ed32 | C#code:C# | {"size": 15659, "ext": "cs", "max_stars_repo_path": "sent-splitting/Algorithms/Searcher.cs", "max_stars_repo_name": "mamin-siberiayk/lingvo--SentSplitter", "max_stars_repo_stars_event_min_datetime": "2018-01-18T16:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T14:37:20.000Z", "max_issues_repo_path": "sent-splitting/Algorithms/Searcher.cs", "max_issues_repo_name": "mamin-siberiayk/lingvo--SentSplitter", "max_issues_repo_issues_event_min_datetime": "2017-03-20T23:40:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-05T15:28:30.000Z", "max_forks_repo_path": "sent-splitting/Algorithms/Searcher.cs", "max_forks_repo_name": "mamin-siberiayk/lingvo--SentSplitter", "max_forks_repo_forks_event_min_datetime": "2017-03-20T23:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-17T18:47:13.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 4.0, "max_forks_count": 4.0, "avg_line_length": 35.0313199105, "max_line_length": 236, "alphanum_fraction": 0.4173957469} | using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace lingvo.sentsplitting
{
/// <summary>
///
/// </summary>
internal struct ngram_t< T >
{
public ngram_t( string[] _words, T _value )
{
words = _words;
value = _value;
}
public string[] words { get; }
public T value { get; }
public override string ToString() => ('\'' + string.Join( "' '", words ) + "' (" + words.Length + "), '" + value + "'");
}
/// <summary>
///
/// </summary>
internal struct SearchResult< T >
{
/// <summary>
///
/// </summary>
public sealed class Comparer : IComparer< SearchResult< T > >
{
public static Comparer Inst { get; } = new Comparer();
private Comparer() { }
public int Compare( SearchResult< T > x, SearchResult< T > y )
{
var d = y.Length - x.Length;
if ( d != 0 )
return (d);
return (x.StartIndex - y.StartIndex);
//d = x.StartIndex - y.StartIndex;
//if ( d != 0 )
//return (d);
//return (y.Value - x.Value);
}
}
public SearchResult( int startIndex, int length, T value )
{
StartIndex = startIndex;
Length = length;
v = value;
}
public int StartIndex { get; }
public int Length { get; }
public T v { get; }
public override string ToString()
{
var s = v.ToString();
if ( string.IsNullOrEmpty( s ) )
{
return ("[" + StartIndex + ":" + Length + "]");
}
return ("[" + StartIndex + ":" + Length + "], value: '" + s + "'");
}
}
/// <summary>
///
/// </summary>
internal struct SearchResultOfHead2Left< T >
{
/// <summary>
///
/// </summary>
public sealed class Comparer : IComparer< SearchResultOfHead2Left< T > >
{
public static Comparer Inst { get; } = new Comparer();
private Comparer() { }
public int Compare( SearchResultOfHead2Left< T > x, SearchResultOfHead2Left< T > y ) => (y.Length - x.Length);
}
public SearchResultOfHead2Left( ss_word_t lastWord, int length, T value )
{
LastWord = lastWord;
Length = length;
v = value;
}
public ss_word_t LastWord { get; }
public int Length { get; }
public T v { get; }
public override string ToString()
{
var s = v.ToString();
if ( string.IsNullOrEmpty( s ) )
{
return ("[0:" + Length + "]");
}
return ("[0:" + Length + "], value: '" + s + "'");
}
}
/// <summary>
/// Class for searching string for one or multiple keywords using efficient Aho-Corasick search algorithm
/// </summary>
internal sealed class Searcher< T >
{
/// <summary>
/// Tree node representing character and its transition and failure function
/// </summary>
private sealed class TreeNode
{
/// <summary>
///
/// </summary>
private sealed class ngram_t_IEqualityComparer : IEqualityComparer< ngram_t< T > >
{
public static ngram_t_IEqualityComparer Inst { get; } = new ngram_t_IEqualityComparer();
private ngram_t_IEqualityComparer() { }
public bool Equals( ngram_t< T > x, ngram_t< T > y )
{
var len = x.words.Length;
if ( len != y.words.Length )
{
return (false);
}
for ( int i = 0; i < len; i++ )
{
if ( !string.Equals( x.words[ i ], y.words[ i ] ) )
{
return (false);
}
}
return (true);
}
public int GetHashCode( ngram_t< T > obj ) => obj.words.Length;
}
/// <summary>
/// Build tree from specified keywords
/// </summary>
public static TreeNode BuildTree( IEnumerable< ngram_t< T > > ngrams )
{
// Build keyword tree and transition function
var root = new TreeNode( null, null );
foreach ( var ngram in ngrams )
{
// add pattern to tree
var node = root;
foreach ( var word in ngram.words )
{
var nodeNew = node.GetTransition( word );
if ( nodeNew == null )
{
nodeNew = new TreeNode( node, word );
node.AddTransition( nodeNew );
}
node = nodeNew;
}
node.AddNgram( ngram );
}
// Find failure functions
var nodes = new List< TreeNode >();
// level 1 nodes - fail to root node
var transitions_root_nodes = root.Transitions;
if ( transitions_root_nodes != null )
{
nodes.Capacity = transitions_root_nodes.Count;
foreach ( var node in transitions_root_nodes )
{
node.Failure = root;
var transitions_nodes = node.Transitions;
if ( transitions_nodes != null )
{
foreach ( var trans in transitions_nodes )
{
nodes.Add( trans );
}
}
}
}
// other nodes - using BFS
while ( nodes.Count != 0 )
{
var newNodes = new List< TreeNode >( nodes.Count );
foreach ( var node in nodes )
{
var r = node.Parent.Failure;
var word = node.Word;
while ( (r != null) && !r.ContainsTransition( word ) )
{
r = r.Failure;
}
if ( r == null )
{
node.Failure = root;
}
else
{
node.Failure = r.GetTransition( word );
var failure_ngrams = node.Failure.Ngrams;
if ( failure_ngrams != null )
{
foreach ( var ng in failure_ngrams )
{
node.AddNgram( ng );
}
}
}
// add child nodes to BFS list
var transitions_nodes = node.Transitions;
if ( transitions_nodes != null )
{
foreach ( var child in transitions_nodes )
{
newNodes.Add( child );
}
}
}
nodes = newNodes;
}
root.Failure = root;
return (root);
}
#region [.ctor() & methods.]
/// <summary>
/// Initialize tree node with specified character
/// </summary>
/// <param name="parent">Parent node</param>
/// <param name="word">word</param>
public TreeNode( TreeNode parent, string word )
{
Word = word;
Parent = parent;
}
/// <summary>
/// Adds pattern ending in this node
/// </summary>
/// <param name="ngram">Pattern</param>
public void AddNgram( ngram_t< T > ngram )
{
if ( _Ngrams == null )
{
_Ngrams = new HashSet< ngram_t< T > >( ngram_t_IEqualityComparer.Inst );
}
_Ngrams.Add( ngram );
}
/// <summary>
/// Adds trabsition node
/// </summary>
/// <param name="node">Node</param>
public void AddTransition( TreeNode node )
{
if ( _TransDict == null )
{
_TransDict = new Dictionary< string, TreeNode >();
}
_TransDict.Add( node.Word, node );
}
/// <summary>
/// Returns transition to specified character (if exists)
/// </summary>
/// <param name="word">word</param>
/// <returns>Returns TreeNode or null</returns>
public TreeNode GetTransition( string word ) => (_TransDict != null) && _TransDict.TryGetValue( word, out var node ) ? node : null;
/// <summary>
/// Returns true if node contains transition to specified character
/// </summary>
/// <param name="c">Character</param>
/// <returns>True if transition exists</returns>
public bool ContainsTransition( string word ) => ((_TransDict != null) && _TransDict.ContainsKey( word ));
#endregion
#region [.properties.]
private Dictionary< string, TreeNode > _TransDict;
private HashSet< ngram_t< T > > _Ngrams;
/// <summary>
/// Character
/// </summary>
public string Word { get; private set; }
/// <summary>
/// Parent tree node
/// </summary>
public TreeNode Parent { get; private set; }
/// <summary>
/// Failure function - descendant node
/// </summary>
public TreeNode Failure { get; internal set; }
/// <summary>
/// Transition function - list of descendant nodes
/// </summary>
public ICollection< TreeNode > Transitions => ((_TransDict != null) ? _TransDict.Values : null);
/// <summary>
/// Returns list of patterns ending by this letter
/// </summary>
public ICollection< ngram_t< T > > Ngrams => _Ngrams;
public bool HasNgrams => (_Ngrams != null);
#endregion
public override string ToString() => ((Word != null) ? ('\'' + Word + '\'') : "ROOT") + ", transitions(descendants): " + ((_TransDict != null) ? _TransDict.Count : 0) + ", ngrams: " + ((_Ngrams != null) ? _Ngrams.Count : 0);
}
/// <summary>
///
/// </summary>
private struct Finder
{
private TreeNode _Root;
private TreeNode _Node;
public static Finder Create( TreeNode root ) => new Finder() { _Root = root, _Node = root };
public TreeNode Find( string word )
{
TreeNode transNode;
do
{
transNode = _Node.GetTransition( word );
if ( _Node == _Root )
{
break;
}
if ( transNode == null )
{
_Node = _Node.Failure;
}
}
while ( transNode == null );
if ( transNode != null )
{
_Node = transNode;
}
return (_Node);
}
}
#region [.private field's.]
private static SearchResult< T >[] EMPTY_RESULT_1 = new SearchResult< T >[ 0 ];
private static SearchResultOfHead2Left< T >[] EMPTY_RESULT_2 = new SearchResultOfHead2Left< T >[ 0 ];
/// <summary>
/// Root of keyword tree
/// </summary>
private TreeNode _Root;
#endregion
#region [.ctor().]
/// <summary>
/// Initialize search algorithm (Build keyword tree)
/// </summary>
/// <param name="keywords">Keywords to search for</param>
internal Searcher( IList< ngram_t< T > > ngrams )
{
_Root = TreeNode.BuildTree( ngrams );
NgramMaxLength = (0 < ngrams.Count) ? ngrams.Max( ngram => ngram.words.Length ) : 0;
}
#endregion
#region [.public method's & properties.]
internal int NgramMaxLength { get; }
internal ICollection< SearchResult< T > > FindAll( IList< ss_word_t > words )
{
var ss = default(SortedSet< SearchResult< T > >);
var finder = Finder.Create( _Root );
for ( int index = 0, len = words.Count; index < len; index++ )
{
var node = finder.Find( words[ index ].valueOriginal );
if ( node.HasNgrams )
{
if ( ss == null ) ss = new SortedSet< SearchResult< T > >( SearchResult< T >.Comparer.Inst );
foreach ( var ngram in node.Ngrams )
{
var r = ss.Add( new SearchResult< T >( index - ngram.words.Length + 1, ngram.words.Length, ngram.value ) );
Debug.Assert( r );
}
}
}
if ( ss != null )
{
return (ss);
}
return (EMPTY_RESULT_1);
}
internal ICollection< SearchResultOfHead2Left< T > > FindOfHead2Left( ss_word_t headWord )
{
var ss = default(SortedSet< SearchResultOfHead2Left< T > >);
var finder = Finder.Create( _Root );
int index = 0;
for ( var word = headWord; word != null; word = word.next )
{
var node = finder.Find( word.valueOriginal );
if ( node.HasNgrams )
{
foreach ( var ngram in node.Ngrams )
{
var wordIndex = index - ngram.words.Length + 1;
if ( wordIndex == 0 )
{
if ( ss == null ) ss = new SortedSet< SearchResultOfHead2Left< T > >( SearchResultOfHead2Left< T >.Comparer.Inst );
var r = ss.Add( new SearchResultOfHead2Left< T >( word, ngram.words.Length, ngram.value ) );
Debug.Assert( r );
}
}
}
index++;
}
if ( ss != null )
{
return (ss);
}
return (EMPTY_RESULT_2);
}
#endregion
public override string ToString() => ("[" + _Root + "]");
}
}
|
||||
TheStack | bd5a3a3a167ee4e13ce0e377c528a5dccc1fe80b | C#code:C# | {"size": 776, "ext": "cs", "max_stars_repo_path": "Services/DataX.Contract/Exception/GeneralException.cs", "max_stars_repo_name": "itshawi/data-accelerator", "max_stars_repo_stars_event_min_datetime": "2019-04-16T21:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T09:18:47.000Z", "max_issues_repo_path": "Services/DataX.Contract/Exception/GeneralException.cs", "max_issues_repo_name": "QPC-database/data-accelerator", "max_issues_repo_issues_event_min_datetime": "2019-05-10T21:10:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T08:23:00.000Z", "max_forks_repo_path": "Services/DataX.Contract/Exception/GeneralException.cs", "max_forks_repo_name": "QPC-database/data-accelerator", "max_forks_repo_forks_event_min_datetime": "2019-05-08T15:30:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T11:11:31.000Z"} | {"max_stars_count": 185.0, "max_issues_count": 45.0, "max_forks_count": 44.0, "avg_line_length": 38.8, "max_line_length": 98, "alphanum_fraction": 0.5721649485} | // *********************************************************************
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
// *********************************************************************
using System;
namespace DataX.Contract.Exception
{
[Serializable]
public class GeneralException : System.Exception
{
public GeneralException() { }
public GeneralException(string message) : base(message) { }
public GeneralException(string message, System.Exception inner) : base(message, inner) { }
protected GeneralException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
|
||||
TheStack | bd5cdd16eea9b0a6f6a29c293cc65688fb7d922f | C#code:C# | {"size": 1684, "ext": "cs", "max_stars_repo_path": "Gayak.ObservableDictionary/CollectionBasedDictionary.KeyCollection.cs", "max_stars_repo_name": "gayaK/Gayak.ObservableDictionary", "max_stars_repo_stars_event_min_datetime": "2017-04-18T03:36:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T14:52:46.000Z", "max_issues_repo_path": "Gayak.ObservableDictionary/CollectionBasedDictionary.KeyCollection.cs", "max_issues_repo_name": "gayaK/Gayak.ObservableDictionary", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gayak.ObservableDictionary/CollectionBasedDictionary.KeyCollection.cs", "max_forks_repo_name": "gayaK/Gayak.ObservableDictionary", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.0714285714, "max_line_length": 99, "alphanum_fraction": 0.606888361} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Gayak.Collections
{
public partial class CollectionBasedDictionary<TKey, TValue>
{
public class KeyCollection :
ICollection<TKey>,
#if !NET40
IReadOnlyList<TKey>,
#endif
ICollection
{
public KeyCollection(CollectionBasedDictionary<TKey, TValue> source)
{
_source = source ?? throw new NullReferenceException(nameof(source));
}
private CollectionBasedDictionary<TKey, TValue> _source;
public TKey this[int index] => _source[index].Key;
public int Count => _source.Count;
public bool IsReadOnly => true;
public object SyncRoot { get; } = new object();
public bool IsSynchronized => false;
public void Add(TKey item) => throw new NotSupportedException();
public bool Remove(TKey item) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public bool Contains(TKey item) => _source.ContainsKey(item);
public void CopyTo(TKey[] array, int arrayIndex) => _source
.Select(x => x.Value)
.ToArray()
.CopyTo(array, arrayIndex);
void ICollection.CopyTo(Array array, int index) => this.CopyTo((TKey[])array, index);
public IEnumerator<TKey> GetEnumerator() => _source.Select(x => x.Key).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
}
|
||||
TheStack | bd5f77070f5525411cb1dc90eeb9ddd33bd2ca75 | C#code:C# | {"size": 2376, "ext": "cs", "max_stars_repo_path": "Cyotek.Windows.Forms.TabList/Design/TabListPageDesigner.cs", "max_stars_repo_name": "cyotek/Cyotek.Windows.Forms.TabList", "max_stars_repo_stars_event_min_datetime": "2015-05-18T21:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T07:11:26.000Z", "max_issues_repo_path": "Cyotek.Windows.Forms.TabList/Design/TabListPageDesigner.cs", "max_issues_repo_name": "cyotek/Cyotek.Windows.Forms.TabList", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cyotek.Windows.Forms.TabList/Design/TabListPageDesigner.cs", "max_forks_repo_name": "cyotek/Cyotek.Windows.Forms.TabList", "max_forks_repo_forks_event_min_datetime": "2015-01-19T14:52:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T06:01:24.000Z"} | {"max_stars_count": 22.0, "max_issues_count": null, "max_forks_count": 9.0, "avg_line_length": 34.4347826087, "max_line_length": 169, "alphanum_fraction": 0.6851851852} | using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Cyotek.Windows.Forms.Design
{
// Cyotek TabList
// Copyright (c) 2012-2013 Cyotek.
// https://www.cyotek.com
// https://www.cyotek.com/blog/tag/tablist
// Licensed under the MIT License. See LICENSE.txt for the full text.
// If you use this control in your applications, attribution, donations or contributions are welcome.
/// <summary>
/// Extends the design mode behavior of a <see cref="TabListPage"/>.
/// </summary>
/// <seealso cref="T:System.Windows.Forms.Design.ScrollableControlDesigner"/>
public class TabListPageDesigner : ScrollableControlDesigner
{
#region Properties
/// <summary>
/// Gets the selection rules that indicate the movement capabilities of a component.
/// </summary>
/// <value>
/// A bitwise combination of <see cref="SelectionRules"/> values.
/// </value>
public override SelectionRules SelectionRules
{
get { return SelectionRules.Locked; }
}
#endregion
#region Methods
/// <summary>
/// Indicates if this designer's control can be parented by the control of the specified designer.
/// </summary>
/// <param name="parentDesigner">The <see cref="IDesigner"/> that manages the control to check.</param>
/// <returns>
/// <c>true</c> if the control managed by the specified designer can parent the control managed by this designer; otherwise, <c>false</c>.
/// </returns>
public override bool CanBeParentedTo(IDesigner parentDesigner)
{
return parentDesigner?.Component is TabList;
}
/// <summary>
/// Receives a call when the control that the designer is managing has painted its surface so the designer can paint any additional adornments on top of the control.
/// </summary>
/// <param name="pe">A <see cref="PaintEventArgs"/> the designer can use to draw on the control.</param>
protected override void OnPaintAdornments(PaintEventArgs pe)
{
base.OnPaintAdornments(pe);
if (!(this.Control is Panel) || ((Panel)this.Control).BorderStyle == BorderStyle.None)
{
// outline the control at design time if we don't have any borders
NativeMethods.DrawFocusRectangle(pe.Graphics, this.Control.ClientRectangle);
}
}
#endregion
}
}
|
||||
TheStack | bd608d635ba2944a7e6e974e2c5d0a5da5a2ba5c | C#code:C# | {"size": 214, "ext": "cs", "max_stars_repo_path": "Bookshelf.API/Bookshelf.API/Middlewares/CustomExtension.cs", "max_stars_repo_name": "omerozoglu/MyEssentialBookshelf", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bookshelf.API/Bookshelf.API/Middlewares/CustomExtension.cs", "max_issues_repo_name": "omerozoglu/MyEssentialBookshelf", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bookshelf.API/Bookshelf.API/Middlewares/CustomExtension.cs", "max_forks_repo_name": "omerozoglu/MyEssentialBookshelf", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.4545454545, "max_line_length": 75, "alphanum_fraction": 0.6074766355} | namespace Bookshelf.API.Middlewares
{
public static class CustomExtension
{
public static void UseCustomExtension(this IApplicationBuilder app)
{
//app.Use...
}
}
}
|
||||
TheStack | bd62a2afca8bb6764f18050a033922bf403550f6 | C#code:C# | {"size": 1235, "ext": "cs", "max_stars_repo_path": "src/Tests/Indices/StatusManagement/Flush/FlushApiTests.cs", "max_stars_repo_name": "RossLieberman/NEST", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Tests/Indices/StatusManagement/Flush/FlushApiTests.cs", "max_issues_repo_name": "RossLieberman/NEST", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tests/Indices/StatusManagement/Flush/FlushApiTests.cs", "max_forks_repo_name": "RossLieberman/NEST", "max_forks_repo_forks_event_min_datetime": "2020-11-17T02:11:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-17T02:11:08.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 36.3235294118, "max_line_length": 114, "alphanum_fraction": 0.7603238866} | using System;
using Elasticsearch.Net;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using Xunit;
using static Nest.Infer;
namespace Tests.Indices.StatusManagement.Flush
{
[Collection(IntegrationContext.ReadOnly)]
public class FlushApiTests : ApiIntegrationTestBase<IFlushResponse, IFlushRequest, FlushDescriptor, FlushRequest>
{
public FlushApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override LazyResponses ClientUsage() => Calls(
fluent: (client, f) => client.Flush(Index<Project>(), f),
fluentAsync: (client, f) => client.FlushAsync(Index<Project>(), f),
request: (client, r) => client.Flush(r),
requestAsync: (client, r) => client.FlushAsync(r)
);
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override HttpMethod HttpMethod => HttpMethod.POST;
protected override string UrlPath => "/project/_flush?allow_no_indices=true";
protected override Func<FlushDescriptor, IFlushRequest> Fluent => d => d.AllowNoIndices();
protected override FlushRequest Initializer => new FlushRequest(Index<Project>()) { AllowNoIndices = true };
}
}
|
||||
TheStack | bd6534d2d486a45bd9ef13b69178f059f47a8516 | C#code:C# | {"size": 1194, "ext": "cs", "max_stars_repo_path": "HttpMicroservice/Repositories/Queue/QueueRepository.cs", "max_stars_repo_name": "bcamposq1995/net6-docker", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HttpMicroservice/Repositories/Queue/QueueRepository.cs", "max_issues_repo_name": "bcamposq1995/net6-docker", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HttpMicroservice/Repositories/Queue/QueueRepository.cs", "max_forks_repo_name": "bcamposq1995/net6-docker", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.1176470588, "max_line_length": 128, "alphanum_fraction": 0.5108877722} | using System;
using System.Text;
using RabbitMQ.Client;
namespace HttpMicroservice.Repositories.Queue
{
public class QueueRepository : IQueueRepository
{
public void Enqueue<T>(T obj, string queueName)
{
var factory = new ConnectionFactory() { HostName = Environment.GetEnvironmentVariable("RABBIT_CONNECTION_STRING") };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
var jsonBytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
channel.BasicPublish(exchange: "",
routingKey: queueName,
basicProperties: null,
body: jsonBytes);
}
}
}
}
|
||||
TheStack | bd656e96d59e594eb38c95e7e9a29f7a9f2163d1 | C#code:C# | {"size": 1210, "ext": "cs", "max_stars_repo_path": "Code/CMSApplication/Areas/Administration/Models/PartiesModels.cs", "max_stars_repo_name": "ducanhtk5/RimSigns", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/CMSApplication/Areas/Administration/Models/PartiesModels.cs", "max_issues_repo_name": "ducanhtk5/RimSigns", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/CMSApplication/Areas/Administration/Models/PartiesModels.cs", "max_forks_repo_name": "ducanhtk5/RimSigns", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.8421052632, "max_line_length": 74, "alphanum_fraction": 0.5991735537} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CMS.Data;
namespace CMSApplication.Areas.Administration.Models
{
public class PartiesModels
{
public int Id { get; set; }
public int OrderId { get; set; }
public DateTime DateAssign { get; set; }
public int AssignById { get; set; }
public string AssignByName { get; set; }
///////////// Field not Entity
public string Name { get; set; }
public string OrderName { get; set; }
public static void ToModel(Party entity, ref PartiesModels model)
{
model.Id = entity.Id;
model.OrderId = entity.OrderId;
model.DateAssign = entity.DateAssign;
model.AssignById = entity.AssignById;
model.AssignByName = entity.AssignByName;
}
public static void ToEntity(PartiesModels model, ref Party entity)
{
entity.Id = model.Id;
entity.OrderId = model.OrderId;
entity.DateAssign = model.DateAssign;
entity.AssignById = model.AssignById;
entity.AssignByName = model.AssignByName;
}
}
} |
||||
TheStack | bd679f369a0e3f84c94dc3b6ff3e3f3b85998365 | C#code:C# | {"size": 936, "ext": "cs", "max_stars_repo_path": "src/ProjectPS.ServicePS.IoC/ApplicationExtensions.cs", "max_stars_repo_name": "owlvey/owlvey_template", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProjectPS.ServicePS.IoC/ApplicationExtensions.cs", "max_issues_repo_name": "owlvey/owlvey_template", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProjectPS.ServicePS.IoC/ApplicationExtensions.cs", "max_forks_repo_name": "owlvey/owlvey_template", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.4285714286, "max_line_length": 113, "alphanum_fraction": 0.7264957265} | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using ProjectPS.ServicePS.Components.Interfaces;
using ProjectPS.ServicePS.Components.Services;
using ProjectPS.ServicePS.Identity;
namespace ProjectPS.ServicePS.IoC
{
public static class ApplicationExtensions
{
public static void AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
{
// ASP.NET HttpContext dependency
// services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Application
services.AddTransient<IAppSettingQueryComponent, AppSettingQueryComponent>();
services.AddTransient<IAppSettingComponent, AppSettingComponent>();
// Infra
services.AddAspNetCoreIndentityService();
}
}
}
|
||||
TheStack | bd683779fa3a18cf1880d4d8081441fa60665e6a | C#code:C# | {"size": 2329, "ext": "cs", "max_stars_repo_path": "ClearCanvas.Common/ExtensionPointAttribute.cs", "max_stars_repo_name": "Sharemee/Dicom", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ClearCanvas.Common/ExtensionPointAttribute.cs", "max_issues_repo_name": "Sharemee/Dicom", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClearCanvas.Common/ExtensionPointAttribute.cs", "max_forks_repo_name": "Sharemee/Dicom", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.472972973, "max_line_length": 103, "alphanum_fraction": 0.633319021} | #region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// The ClearCanvas RIS/PACS open source project is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace ClearCanvas.Common
{
/// <summary>
/// Attribute used to mark a class as defining an extension point.
/// </summary>
/// <remarks>
/// Use this attribute to mark a class as defining an extension point. This attribute must only be
/// applied to subclasses of <see cref="ExtensionPoint" />.
/// </remarks>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExtensionPointAttribute : Attribute
{
private string _name;
private string _description;
/// <summary>
/// Attribute constructor.
/// </summary>
public ExtensionPointAttribute()
{
}
/// <summary>
/// A friendly name for the extension point.
/// </summary>
/// <remarks>
/// This is optional and may be supplied as a named parameter.
/// </remarks>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// A friendly description for the extension point.
/// </summary>
/// <remarks>
/// This is optional and may be supplied as a named parameter.
/// </remarks>
public string Description
{
get { return _description; }
set { _description = value; }
}
}
}
|
||||
TheStack | bd68559867be312f9ac18efcf0672f5a6a18b3f7 | C#code:C# | {"size": 2125, "ext": "cs", "max_stars_repo_path": "src/Technosoftware/DaAeHdaClient/Ae/StateMask.cs", "max_stars_repo_name": "technosoftware-gmbh/opc-daaehda-client-net", "max_stars_repo_stars_event_min_datetime": "2019-09-02T06:52:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T22:03:42.000Z", "max_issues_repo_path": "src/Technosoftware/DaAeHdaClient/Ae/StateMask.cs", "max_issues_repo_name": "technosoftware-gmbh/opc-daaehda-client-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Technosoftware/DaAeHdaClient/Ae/StateMask.cs", "max_forks_repo_name": "technosoftware-gmbh/opc-daaehda-client-net", "max_forks_repo_forks_event_min_datetime": "2019-08-10T10:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-22T12:55:32.000Z"} | {"max_stars_count": 11.0, "max_issues_count": null, "max_forks_count": 8.0, "avg_line_length": 29.9295774648, "max_line_length": 84, "alphanum_fraction": 0.6503529412} | #region Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
#endregion
namespace Technosoftware.DaAeHdaClient.Ae
{
/// <summary>
/// Defines masks to be used when modifying the subscription or item state.
/// </summary>
[Flags]
public enum TsCAeStateMask
{
/// <summary>
/// A name assigned to subscription.
/// </summary>
Name = 0x0001,
/// <summary>
/// The client assigned handle for the item or subscription.
/// </summary>
ClientHandle = 0x0002,
/// <summary>
/// Whether the subscription is active.
/// </summary>
Active = 0x0004,
/// <summary>
/// The maximum rate at which the server send event notifications.
/// </summary>
BufferTime = 0x0008,
/// <summary>
/// The requested maximum number of events that will be sent in a single callback.
/// </summary>
MaxSize = 0x0010,
/// <summary>
/// The maximum period between updates sent to the client.
/// </summary>
KeepAlive = 0x0020,
/// <summary>
/// All fields are valid.
/// </summary>
All = 0xFFFF
}
}
|
||||
TheStack | bd68ed25339de0959a6a8bd44a877427c07530d7 | C#code:C# | {"size": 4779, "ext": "cs", "max_stars_repo_path": "Helpers/ColorExtractor.cs", "max_stars_repo_name": "karl-sjogren/color-extraction-demo", "max_stars_repo_stars_event_min_datetime": "2020-07-06T20:15:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-06T20:15:11.000Z", "max_issues_repo_path": "Helpers/ColorExtractor.cs", "max_issues_repo_name": "karl-sjogren/color-extraction-demo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Helpers/ColorExtractor.cs", "max_forks_repo_name": "karl-sjogren/color-extraction-demo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.8536585366, "max_line_length": 130, "alphanum_fraction": 0.5381879054} | using System;
using System.IO;
using System.Linq;
using System.Text;
using color_extraction_demo.Models;
using Newtonsoft.Json;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Quantization;
namespace color_extraction_demo.Helpers {
public static class ColorExtractor {
public static ImageColors GetCached(Stream imageStream, string filename) {
var cachePath = "wwwroot\\cache\\" + filename + ".json";
if(File.Exists(cachePath)) {
var json = File.ReadAllText(cachePath, Encoding.UTF8);
return JsonConvert.DeserializeObject<ImageColors>(json);
}
var result = ProcessImage(imageStream, filename);
var resultJson = JsonConvert.SerializeObject(result, Formatting.Indented);
File.WriteAllText(cachePath, resultJson, Encoding.UTF8);
return result;
}
public static ImageColors ProcessImage(Stream imageStream, string filename) {
var image = Image.Load<Rgba32>(imageStream);
try {
if(image.Width > 800 || image.Height > 800)
image.Mutate(i => i.Resize(800, 800));
var imageFrame = image.Frames[0];
var quantizer = new WuQuantizer(new QuantizerOptions { MaxColors = 12 });
var frameQuantizer = quantizer.CreatePixelSpecificQuantizer<Rgba32>(Configuration.Default);
frameQuantizer.BuildPaletteAndQuantizeFrame(imageFrame, image.Bounds());
var quantizedColors = frameQuantizer.QuantizeFrame(imageFrame, image.Bounds());
var paletteColors = quantizedColors.Palette;
var frame = image.Frames[0];
var totalPixels = frame.Width * frame.Height;
frame.TryGetSinglePixelSpan(out var pixels);
var counter = new double[paletteColors.Length];
foreach(var pixel in pixels) {
var closestDistance = double.MaxValue;
var nearestColorIndex = -1;
for(var index = 0; index < paletteColors.Length; index++) {
var paletteColor = paletteColors.Span[index];
var distance = EuclideanDistance(paletteColor, pixel);
if(distance < closestDistance) {
closestDistance = distance;
nearestColorIndex = index;
}
}
counter[nearestColorIndex]++;
}
var colors = paletteColors.Span.ToArray().Select((color, idx) => {
var (hue, saturation, value) = ColorToHsv(color);
return new ExtractedColor {
Hsv = new HsvColor(hue, saturation, value),
Hex = color.ToHex().Substring(0, 6),
Fraction = counter[idx] / totalPixels
};
});
return new ImageColors {
Filename = filename,
Colors = colors.OrderByDescending(c => c.Fraction).ToList()
};
} finally {
image?.Dispose();
}
}
public static (float hue, float saturation, float value) ColorToHsv(Rgba32 color) {
var min = (float)Math.Min(Math.Min(color.R, color.G), color.B);
var value = (float)Math.Max(Math.Max(color.R, color.G), color.B);
var delta = value - min;
float saturation;
if(Math.Abs(value) < double.Epsilon)
saturation = 0;
else
saturation = delta / value;
var hue = 0f;
if(Math.Abs(saturation) < double.Epsilon) {
hue = 0.0f;
} else {
if(Math.Abs(color.R - value) < double.Epsilon)
hue = (color.G - color.B) / delta;
else if(Math.Abs(color.G - value) < double.Epsilon)
hue = 2f + (color.B - color.R) / delta;
else if(Math.Abs(color.B - value) < double.Epsilon)
hue = 4f + (color.R - color.G) / delta;
hue *= 60f;
if(hue < 0.0f)
hue += 360f;
}
return (hue, saturation, value / 255);
}
private static double EuclideanDistance(Rgba32 color1, Rgba32 color2) {
var distance = Math.Pow(color1.R - color2.R, 2) + Math.Pow(color1.G - color2.G, 2) + Math.Pow(color1.B - color2.B, 2);
return Math.Sqrt(distance);
}
}
} |
||||
TheStack | bd6c364f834e8e44c79d3890b1a0a15aee416426 | C#code:C# | {"size": 230, "ext": "cs", "max_stars_repo_path": "Assets/_Universal/Utility/StateMachine/State.cs", "max_stars_repo_name": "BrandonMCoffey/State-Machine-Project", "max_stars_repo_stars_event_min_datetime": "2021-12-04T13:36:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T13:36:22.000Z", "max_issues_repo_path": "Assets/_Universal/Utility/StateMachine/State.cs", "max_issues_repo_name": "BrandonMCoffey/State-Machine-Project", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/_Universal/Utility/StateMachine/State.cs", "max_forks_repo_name": "BrandonMCoffey/State-Machine-Project", "max_forks_repo_forks_event_min_datetime": "2021-12-04T13:36:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T13:36:27.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 20.9090909091, "max_line_length": 51, "alphanum_fraction": 0.6608695652} | using UnityEngine;
namespace Utility.StateMachine
{
public abstract class StateBase : MonoBehaviour
{
public abstract void Enter();
public abstract void Tick();
public abstract void Exit();
}
} |
||||
TheStack | bd6d518fb30b0c557b0fef47dcd5f09b53844e27 | C#code:C# | {"size": 608, "ext": "cs", "max_stars_repo_path": "Scripts/Managers/InventoryPro.cs", "max_stars_repo_name": "slumtrimpet/Inventory-Pro", "max_stars_repo_stars_event_min_datetime": "2019-09-27T20:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:53:23.000Z", "max_issues_repo_path": "Scripts/Managers/InventoryPro.cs", "max_issues_repo_name": "slumtrimpet/Inventory-Pro", "max_issues_repo_issues_event_min_datetime": "2019-10-05T03:10:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T01:56:07.000Z", "max_forks_repo_path": "Scripts/Managers/InventoryPro.cs", "max_forks_repo_name": "slumtrimpet/Inventory-Pro", "max_forks_repo_forks_event_min_datetime": "2019-09-18T08:26:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:35:01.000Z"} | {"max_stars_count": 619.0, "max_issues_count": 11.0, "max_forks_count": 169.0, "avg_line_length": 32.0, "max_line_length": 98, "alphanum_fraction": 0.7006578947} | using System;
using System.Collections.Generic;
using Devdog.General.ThirdParty.UniLinq;
using System.Text;
namespace Devdog.InventoryPro
{
public static class InventoryPro
{
public const string Version = "V2.5.16";
public const string ProductName = "Inventory Pro";
public const string ToolsMenuPath = "Tools/Inventory Pro/";
public const string AddComponentMenuPath = ProductName + "/";
public const string CreateAssetMenuPath = ProductName + "/";
public const string ProductUrl = "https://www.assetstore.unity3d.com/en/#!/content/66801";
}
}
|
||||
TheStack | bd6dd362113c23e45660cb990402d1a434a9e96b | C#code:C# | {"size": 1622, "ext": "cs", "max_stars_repo_path": "src/NuGetGallery/Helpers/GravatarHelper.cs", "max_stars_repo_name": "hach-que/NuGetGallery", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NuGetGallery/Helpers/GravatarHelper.cs", "max_issues_repo_name": "hach-que/NuGetGallery", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NuGetGallery/Helpers/GravatarHelper.cs", "max_forks_repo_name": "hach-que/NuGetGallery", "max_forks_repo_forks_event_min_datetime": "2020-11-04T04:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T04:28:43.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 33.7916666667, "max_line_length": 123, "alphanum_fraction": 0.610974106} | // 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.Web;
using Microsoft.Web.Helpers;
namespace NuGetGallery.Helpers
{
public static class GravatarHelper
{
private const string UnsecureGravatarUrl = "http://www.gravatar.com/";
private const string SecureGravatarUrl = "https://secure.gravatar.com/";
public static string Url(string email, int size)
{
var url = Gravatar.GetUrl(email, size, "retro", GravatarRating.G);
if (url != null && ShouldUseSecureGravatar())
{
url = url.Replace(UnsecureGravatarUrl, SecureGravatarUrl);
}
return HttpUtility.HtmlDecode(url);
}
public static HtmlString Image(string email, int size, object attributes = null)
{
// The maximum Gravatar size is 512 pixels.
if (size > 512)
{
size = 512;
}
var gravatarHtml = Gravatar.GetHtml(email, size, "retro", GravatarRating.G, attributes: attributes);
if (gravatarHtml != null && ShouldUseSecureGravatar())
{
gravatarHtml = new HtmlString(gravatarHtml.ToHtmlString().Replace(UnsecureGravatarUrl, SecureGravatarUrl));
}
return gravatarHtml;
}
private static bool ShouldUseSecureGravatar()
{
return (HttpContext.Current == null || HttpContext.Current.Request.IsSecureConnection);
}
}
} |
||||
TheStack | bd6f7ad560bbd29cc1bb6ce33cb622f2b53753b9 | C#code:C# | {"size": 762, "ext": "cs", "max_stars_repo_path": "Assets/Best HTTP (Pro)/Examples/SocketIO/SocketIO Json Encoders/LitJsonEncoder.cs", "max_stars_repo_name": "jakemoves/cohort-unity-client-demo", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:07:04.000Z", "max_issues_repo_path": "Assets/Best HTTP (Pro)/Examples/SocketIO/SocketIO Json Encoders/LitJsonEncoder.cs", "max_issues_repo_name": "jakemoves/cohort-unity-client-demo", "max_issues_repo_issues_event_min_datetime": "2019-10-05T16:30:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T23:55:02.000Z", "max_forks_repo_path": "Assets/Best HTTP (Pro)/Examples/SocketIO/SocketIO Json Encoders/LitJsonEncoder.cs", "max_forks_repo_name": "jakemoves/cohort-unity-client-demo", "max_forks_repo_forks_event_min_datetime": "2020-05-24T01:58:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T15:23:09.000Z"} | {"max_stars_count": 105.0, "max_issues_count": 23.0, "max_forks_count": 26.0, "avg_line_length": 25.4, "max_line_length": 109, "alphanum_fraction": 0.6089238845} | #if !BESTHTTP_DISABLE_SOCKETIO
using System.Collections.Generic;
using LitJson;
namespace BestHTTP.SocketIO.JsonEncoders
{
/// <summary>
/// This IJsonEncoder implementation uses the LitJson library located in the Examples\LitJson directory.
/// </summary>
public sealed class LitJsonEncoder : IJsonEncoder
{
public List<object> Decode(string json)
{
JsonReader reader = new JsonReader(json);
return JsonMapper.ToObject<List<object>>(reader);
}
public string Encode(List<object> obj)
{
JsonWriter writer = new JsonWriter();
JsonMapper.ToJson(obj, writer);
return writer.ToString();
}
}
}
#endif |
||||
TheStack | bd70b884f11ff7bbc75aae9b6165a2a2758fa72e | C#code:C# | {"size": 5084, "ext": "cs", "max_stars_repo_path": "Runtime/Systems/Extensions.cs", "max_stars_repo_name": "snorluxe/ecslite-unity-ugui", "max_stars_repo_stars_event_min_datetime": "2021-06-20T06:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T22:11:06.000Z", "max_issues_repo_path": "Runtime/Systems/Extensions.cs", "max_issues_repo_name": "snorluxe/ecslite-unity-ugui", "max_issues_repo_issues_event_min_datetime": "2021-08-01T17:25:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T21:09:28.000Z", "max_forks_repo_path": "Runtime/Systems/Extensions.cs", "max_forks_repo_name": "Leopotam/ecslite-unity-ugui", "max_forks_repo_forks_event_min_datetime": "2021-06-28T16:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:17:55.000Z"} | {"max_stars_count": 6.0, "max_issues_count": 1.0, "max_forks_count": 15.0, "avg_line_length": 51.3535353535, "max_line_length": 204, "alphanum_fraction": 0.5639260425} | // ----------------------------------------------------------------------------
// The MIT License
// Ugui bindings https://github.com/Leopotam/ecslite-unity-ugui
// for LeoECS Lite https://github.com/Leopotam/ecslite
// Copyright (c) 2021 Leopotam <[email protected]>
// ----------------------------------------------------------------------------
using System;
using System.Reflection;
using Leopotam.EcsLite.ExtendedSystems;
using UnityEngine;
namespace Leopotam.EcsLite.Unity.Ugui {
public sealed class EcsUguiNamedAttribute : Attribute {
public readonly string Name;
public EcsUguiNamedAttribute (string name) {
Name = name;
}
}
public static class EcsSystemsExtensions {
/// <summary>
/// Injects named UI objects and Emitter to all systems added to EcsSystems.
/// </summary>
/// <param name="ecsSystems">EcsSystems group.</param>
/// <param name="emitter">EcsUiEmitter instance.</param>
/// <param name="worldName">World name.</param>
/// <param name="skipNoExists">Not throw exception if named action not registered in emitter.</param>
/// <param name="skipDelHere">Skip DelHere() registration.</param>
public static EcsSystems InjectUgui (this EcsSystems ecsSystems, EcsUguiEmitter emitter, string worldName = null, bool skipNoExists = false, bool skipDelHere = false) {
if (!skipDelHere) {
AddDelHereSystems (ecsSystems, worldName);
}
emitter.SetWorld (ecsSystems.GetWorld (worldName));
var uiNamedType = typeof (EcsUguiNamedAttribute);
var goType = typeof (GameObject);
var componentType = typeof (Component);
var emitterType = typeof (EcsUguiEmitter);
IEcsSystem[] systems = null;
var systemsCount = ecsSystems.GetAllSystems (ref systems);
for (var i = 0; i < systemsCount; i++) {
var system = systems[i];
var systemType = system.GetType ();
foreach (var f in systemType.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
// skip statics.
if (f.IsStatic) {
continue;
}
// emitter.
if (f.FieldType == emitterType) {
f.SetValue (system, emitter);
continue;
}
// skip fields without [EcsUiNamed] attribute.
if (!Attribute.IsDefined (f, uiNamedType)) {
continue;
}
var name = ((EcsUguiNamedAttribute) Attribute.GetCustomAttribute (f, uiNamedType)).Name;
#if DEBUG
if (string.IsNullOrEmpty (name)) { throw new Exception ($"Cant Inject field \"{f.Name}\" at \"{systemType}\" due to [EcsUiNamed] \"Name\" parameter is invalid."); }
if (!(f.FieldType == goType || componentType.IsAssignableFrom (f.FieldType))) {
throw new Exception ($"Cant Inject field \"{f.Name}\" at \"{systemType}\" due to [EcsUiNamed] attribute can be applied only to GameObject or Component type.");
}
if (!skipNoExists && !emitter.GetNamedObject (name)) { throw new Exception ($"Cant Inject field \"{f.Name}\" at \"{systemType}\" due to there is no UI action with name \"{name}\"."); }
#endif
var go = emitter.GetNamedObject (name);
// GameObject.
if (f.FieldType == goType) {
f.SetValue (system, go);
continue;
}
// Component.
if (componentType.IsAssignableFrom (f.FieldType)) {
f.SetValue (system, go != null ? go.GetComponent (f.FieldType) : null);
}
}
}
return ecsSystems;
}
static void AddDelHereSystems (EcsSystems ecsSystems, string worldName) {
ecsSystems.DelHere<EcsUguiDragStartEvent> (worldName);
ecsSystems.DelHere<EcsUguiDragMoveEvent> (worldName);
ecsSystems.DelHere<EcsUguiDragEndEvent> (worldName);
ecsSystems.DelHere<EcsUguiDropEvent> (worldName);
ecsSystems.DelHere<EcsUguiClickEvent> (worldName);
ecsSystems.DelHere<EcsUguiDownEvent> (worldName);
ecsSystems.DelHere<EcsUguiUpEvent> (worldName);
ecsSystems.DelHere<EcsUguiEnterEvent> (worldName);
ecsSystems.DelHere<EcsUguiExitEvent> (worldName);
ecsSystems.DelHere<EcsUguiScrollViewEvent> (worldName);
ecsSystems.DelHere<EcsUguiSliderChangeEvent> (worldName);
ecsSystems.DelHere<EcsUguiTmpDropdownChangeEvent> (worldName);
ecsSystems.DelHere<EcsUguiTmpInputChangeEvent> (worldName);
ecsSystems.DelHere<EcsUguiTmpInputEndEvent> (worldName);
}
}
} |
||||
TheStack | bd72494669ffa2615e7b3d5368ea875745fa53e8 | C#code:C# | {"size": 8140, "ext": "cs", "max_stars_repo_path": "AngouriMath/Core/TreeAnalysis/Additional.cs", "max_stars_repo_name": "MomoDeve/AngouriMath", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AngouriMath/Core/TreeAnalysis/Additional.cs", "max_issues_repo_name": "MomoDeve/AngouriMath", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AngouriMath/Core/TreeAnalysis/Additional.cs", "max_forks_repo_name": "MomoDeve/AngouriMath", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.6023391813, "max_line_length": 180, "alphanum_fraction": 0.5450859951} |
/* Copyright (c) 2019-2020 Angourisoft
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using AngouriMath.Core.Exceptions;
using AngouriMath.Core.Numerix;
using AngouriMath.Functions.DiscreteMath;
using PeterO.Numbers;
namespace AngouriMath.Core.TreeAnalysis
{
internal static partial class TreeAnalyzer
{
// TODO: realize all methods
/// <summary>
/// Counts all combinations of roots, for example
/// 3 ^ 0.5 + 4 ^ 0.25 will return a set of 8 different numbers
/// </summary>
/// <param name="expr"></param>
/// <returns></returns>
internal static Set EvalAll(Entity expr)
{
throw new NotImplementedException();
}
internal static void EvalCombs(Entity expr, Set set)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds out how many terms we get after expansion via binomial coefficients, e. g
/// (a + b) ^ 3 -> 2, 3 -> 4
/// </summary>
/// <param name="numberOfTerms"></param>
/// <param name="power"></param>
/// <returns></returns>
internal static EInteger EstimateTermCount(int numberOfTerms, int power)
=> Combinatorics.C(power + numberOfTerms - 1, power);
/// <summary>
/// Returns a list of linear children over sum
/// where at most one term doesn't contain x, e. g.
/// x2 + x + a + b + x
/// =>
/// [x2, x, a + b, x]
/// </summary>
/// <param name="expr"></param>
/// <param name="x"></param>
/// <returns></returns>
internal static List<Entity> GatherLinearChildrenOverAndExpand(Entity expr, Func<Entity, bool> conditionForUniqueTerms)
{
if (expr.Name != "sumf" && expr.Name != "minusf")
return SmartExpandOver(expr, conditionForUniqueTerms);
var res = new List<Entity>();
Entity freeTerm = 0;
foreach (var child in TreeAnalyzer.LinearChildrenOverSum(expr))
if (conditionForUniqueTerms(child))
{
var expanded = SmartExpandOver(child, conditionForUniqueTerms);
if (expanded is null)
return null;
res.AddRange(expanded);
}
else
freeTerm += child;
res.Add(freeTerm);
return res;
}
/// <summary>
/// expr is NEITHER + NOR -
/// </summary>
/// <param name="expr"></param>
/// <param name="x"></param>
/// <returns></returns>
internal static List<Entity> SmartExpandOver(Entity expr, Func<Entity, bool> conditionForUniqueTerms)
{
var keepResult = new List<Entity> { expr };
if (expr.entType != Entity.EntType.OPERATOR && expr.entType != Entity.EntType.FUNCTION)
return keepResult;
var newChildren = new List<Entity>();
var result = new List<Entity>();
switch (expr.Name)
{
case "sumf":
case "minusf":
throw new SysException("SmartExpandOver must be only called of non-sum expression");
case "divf":
var numChildren = GatherLinearChildrenOverAndExpand(expr.Children[0], conditionForUniqueTerms);
if (numChildren is null)
return null;
if (numChildren.Count > MathS.Settings.MaxExpansionTermCount)
return null;
return numChildren.Select(c => c / expr.Children[1]).ToList();
case "mulf":
var oneChildren = GatherLinearChildrenOverAndExpand(expr.Children[0], conditionForUniqueTerms);
var twoChildren = GatherLinearChildrenOverAndExpand(expr.Children[1], conditionForUniqueTerms);
if (oneChildren is null || twoChildren is null)
return null;
if (oneChildren.Count * twoChildren.Count > MathS.Settings.MaxExpansionTermCount)
return null;
foreach (var one in oneChildren)
foreach (var two in twoChildren)
newChildren.Add(one * two);
return newChildren;
case "powf":
IntegerNumber power = null;
if (expr.Children[1].entType != Entity.EntType.NUMBER || !expr.Children[1].GetValue().IsInteger() || (power = expr.Children[1].GetValue() as IntegerNumber) < 1)
return keepResult;
var linBaseChildren = GatherLinearChildrenOverAndExpand(expr.Children[0], conditionForUniqueTerms);
if (linBaseChildren is null)
return null;
if (linBaseChildren.Count == 1)
{
var baseChild = linBaseChildren[0];
if (baseChild.entType != Entity.EntType.OPERATOR)
return new List<Entity> {expr};
if (baseChild.Name != "divf" && baseChild.Name != "mulf")
return new List<Entity> { expr };
// (a / b)^2 = a^2 / b^2
baseChild.Children[0] = baseChild.Children[0].Pow(expr.Children[1]);
baseChild.Children[1] = baseChild.Children[1].Pow(expr.Children[1]);
return new List<Entity> {baseChild};
}
if (power.Value > 20 && linBaseChildren.Count > 1 ||
EstimateTermCount(linBaseChildren.Count, (int) power.Value) >
EInteger.FromInt32(MathS.Settings.MaxExpansionTermCount))
return null;
foreach (var powerListForTerm in Combinatorics.CombinateSums(linBaseChildren.Count, power))
{
EInteger biCoef = 1;
EInteger sumPow = power.Value;
foreach (var pow in powerListForTerm)
{
biCoef *= Combinatorics.C((int)sumPow, pow);
sumPow -= pow;
}
Entity term = Number.Create(biCoef);
for (int i = 0; i < powerListForTerm.Count; i++)
if (powerListForTerm[i] == 1)
term *= linBaseChildren[i];
else if (powerListForTerm[i] > 1)
term *= MathS.Pow(linBaseChildren[i], powerListForTerm[i]);
newChildren.AddRange(SmartExpandOver(term, conditionForUniqueTerms));
}
return newChildren;
}
return new List<Entity>{expr};
}
}
}
|
||||
TheStack | bd73be917cc96d75578ad563d7a022c7707d07fe | C#code:C# | {"size": 3095, "ext": "cs", "max_stars_repo_path": "server-agent/Web/WebServiceTask.cs", "max_stars_repo_name": "hdmun/server-agent", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server-agent/Web/WebServiceTask.cs", "max_issues_repo_name": "hdmun/server-agent", "max_issues_repo_issues_event_min_datetime": "2022-03-16T08:25:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T08:25:48.000Z", "max_forks_repo_path": "server-agent/Web/WebServiceTask.cs", "max_forks_repo_name": "hdmun/server-agent", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 27.389380531, "max_line_length": 86, "alphanum_fraction": 0.4856219709} | using log4net;
using ServerAgent.Web.Controller;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Threading.Tasks;
namespace ServerAgent.Web
{
public class WebServiceTask : IServiceTask
{
private readonly ILog logger;
private readonly IList<IController> controllers;
private readonly IRouter router;
private readonly string bindUrl;
private readonly HttpListener httpListener;
private Task taskJob;
private bool isRunning;
public WebServiceTask(IWebServiceContext context)
{
logger = LogManager.GetLogger(typeof(WebServiceTask));
controllers = new List<IController>()
{
new ServerController(context)
};
router = new Router();
bindUrl = ConfigurationManager.AppSettings["HttpUrl"];
httpListener = new HttpListener();
httpListener.Prefixes.Add($"{bindUrl}");
taskJob = null;
isRunning = false;
}
public void OnStart()
{
logger.Info("starting web service task");
foreach (var controller in controllers)
{
router.Register(controller);
}
isRunning = true;
taskJob = Task.Run(() => RunServer());
}
public void OnStop()
{
logger.Info("stopping web service task");
isRunning = false;
httpListener.Stop();
Task.WaitAll(new Task[] { taskJob });
}
private void RunServer()
{
try
{
httpListener.Start();
logger?.Info($"start HttpListener: {bindUrl}");
}
catch (HttpListenerException ex)
{
logger?.Error("failed to start HttpListener", ex);
return;
}
while (isRunning)
{
HttpListenerResponse response = null;
try
{
HttpListenerContext ctx = httpListener.GetContext();
response = ctx.Response;
int routing = router.Route(ctx);
if (routing <= 0)
{
response.StatusCode = (int)HttpStatusCode.NotFound;
response.Close();
}
response = null;
}
catch (HttpListenerException)
{
}
catch (Exception ex)
{
logger?.Error("Exception - WebServiceTaskJob", ex);
if (response != null)
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response?.Close();
}
}
}
httpListener.Close();
logger?.Info("closed HttpListener");
}
}
}
|
||||
TheStack | bd743b31cc49ae5e35e43f35fca936485501b65c | C#code:C# | {"size": 2424, "ext": "cs", "max_stars_repo_path": "Src/MoneyFox.Foundation/Constants/ServiceConstants.cs", "max_stars_repo_name": "DanielBHughes/MoneyFox", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/MoneyFox.Foundation/Constants/ServiceConstants.cs", "max_issues_repo_name": "DanielBHughes/MoneyFox", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/MoneyFox.Foundation/Constants/ServiceConstants.cs", "max_forks_repo_name": "DanielBHughes/MoneyFox", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.1304347826, "max_line_length": 97, "alphanum_fraction": 0.5771452145} | #pragma warning disable CA1707 // Identifiers should not contain underscores
namespace MoneyFox.Foundation.Constants
{
/// <summary>
/// Contains constants for the services used in the app.
/// </summary>
public sealed class ServiceConstants
{
/// <summary>
/// Return URL for the OneDrive authentication
/// </summary>
public const string RETURN_URL = "https://login.live.com/oauth20_desktop.srf";
/// <summary>
/// Returns the base URL of the OneDrive Service
/// </summary>
public const string BASE_URL = "https://api.onedrive.com/v1.0";
/// <summary>
/// Authentication URL for the OneDrive authentication
/// </summary>
public const string AUTHENTICATION_URL = "https://login.live.com/oauth20_authorize.srf";
/// <summary>
/// Logout URL for the OneDrive authentication
/// </summary>
public const string LOGOUT_URL = "https://login.live.com/oauth20_logout.srf";
/// <summary>
/// The Token URL is used to retrieve a access token in the code flow OAUTH
/// </summary>
public const string TOKEN_URL = "https://login.live.com/oauth20_token.srf";
/// <summary>
/// String constant for the access token.
/// </summary>
public const string ACCESS_TOKEN = "access_token";
/// <summary>
/// String constant for the refresh token.
/// </summary>
public const string REFRESH_TOKEN = "refresh_token";
/// <summary>
/// String constant for the code.
/// </summary>
public const string CODE = "code";
/// <summary>
/// Scopes for OneDrive access
/// </summary>
public static string[] Scopes = {"onedrive.readwrite", "wl.offline_access", "wl.signin"};
/// <summary>
/// Maximum number of attempts to sync the database
/// </summary>
public const int SYNC_ATTEMPTS = 2;
/// <summary>
/// The amount of time to wait for the OneDrive backup to be completed
/// </summary>
public const int BACKUP_OPERATION_TIMEOUT = 10000;
/// <summary>
/// The amount of time to wait before retrying to sync
/// </summary>
public const int BACKUP_REPEAT_DELAY = 2000;
}
} |
||||
TheStack | bd7474090bd4b1d029adab7dfa79d60cafe0284a | C#code:C# | {"size": 4723, "ext": "cs", "max_stars_repo_path": "books/tech/.net/c#_6.0_7_ed_a_troelsen/ch_03-CORE_C#_PROGRAMMING_CONSTRUCTS-PART_1/10-basic_string_manipulation/Project/Program.cs", "max_stars_repo_name": "ordinary-developer/win_education", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "books/tech/.net/c#_6.0_7_ed_a_troelsen/ch_03-CORE_C#_PROGRAMMING_CONSTRUCTS-PART_1/10-basic_string_manipulation/Project/Program.cs", "max_issues_repo_name": "ordinary-developer/win_education", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/tech/.net/c#_6.0_7_ed_a_troelsen/ch_03-CORE_C#_PROGRAMMING_CONSTRUCTS-PART_1/10-basic_string_manipulation/Project/Program.cs", "max_forks_repo_name": "ordinary-developer/win_education", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.7279411765, "max_line_length": 92, "alphanum_fraction": 0.4677112005} | using System;
using System.Text;
namespace Project
{
class Program
{
public static void Main(string[] args)
{
BasicStringFunctionality();
StringConcatenation();
EscapeChars();
UseVerbatimStrings();
StringEquality();
StringsImmutability();
UsingStringBuilder();
Console.ReadLine();
}
private static void BasicStringFunctionality()
{
Console.WriteLine("=> Basic string functionality");
string firstName = "Freddy";
Console.WriteLine("Value of firstName: {0}", firstName);
Console.WriteLine("firstName has {0} characters.", firstName.Length);
Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper());
Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower());
Console.WriteLine("firstName contains the letter y?: {0}",
firstName.Contains("y"));
Console.WriteLine("firstName after replace: {0}", firstName.Replace("dy", ""));
Console.WriteLine();
}
private static void StringConcatenation()
{
Console.WriteLine("=> String concatenation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
string s4 = String.Concat(s1, s2);
Console.WriteLine(s3);
Console.WriteLine(s4);
Console.WriteLine();
}
private static void EscapeChars()
{
Console.WriteLine("=> Escape characters:\a");
string strWithTabs = "Model\tColor\tSpeed\tPet Name\a";
Console.WriteLine(strWithTabs);
Console.WriteLine("Everyone loves \"Hello World\"\a ");
Console.WriteLine("C:\\MyApp\\bin\\Debug\a");
Console.WriteLine("All finished.\n\n\n\n\a");
Console.WriteLine();
}
private static void UseVerbatimStrings()
{
Console.WriteLine(@"C:\MyApp\bin\Debug");
string myLongString = @"This is a very
very
very
long string";
Console.WriteLine(myLongString);
Console.WriteLine(@"Cerebus ""Darrr! Pret-ty sun-sets""");
Console.WriteLine();
}
private static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 == HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo!.Equals(s2): {0}", "Yo!".Equals(s2));
Console.WriteLine();
}
private static void StringsImmutability()
{
Console.WriteLine("=> String immutability:");
string s1 = "This is my string.";
Console.WriteLine("s1 = {0}", s1);
string upperString = s1.ToUpper();
Console.WriteLine("upperString = {0}", upperString);
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine();
}
private static void UsingStringBuilder()
{
Console.WriteLine("=> Using the StringBuilder:");
StringBuilder sb = new StringBuilder("**** Fantastic Games ****");
sb.Append("\n");
sb.AppendLine("Half Life");
sb.AppendLine("Morrowind");
sb.AppendLine("Deux Ex" + "2");
sb.AppendLine("System Shock");
Console.WriteLine(sb.ToString());
sb.Replace("2", " Invisible War");
Console.WriteLine(sb.ToString());
Console.WriteLine("sb has {0} chars.", sb.Length);
Console.WriteLine();
}
}
} |
||||
TheStack | bd76a7bc3e9a0fd0988aabe36f4dc3cc98c3a557 | C#code:C# | {"size": 503, "ext": "cs", "max_stars_repo_path": "H2F/H2F.Common/Timing/UnspecifiedClockProvider.cs", "max_stars_repo_name": "warrenhu08/H2F", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "H2F/H2F.Common/Timing/UnspecifiedClockProvider.cs", "max_issues_repo_name": "warrenhu08/H2F", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "H2F/H2F.Common/Timing/UnspecifiedClockProvider.cs", "max_forks_repo_name": "warrenhu08/H2F", "max_forks_repo_forks_event_min_datetime": "2018-12-11T09:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-02T09:06:45.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 20.9583333333, "max_line_length": 61, "alphanum_fraction": 0.662027833} | using System;
using System.Collections.Generic;
using System.Text;
namespace H2F.Standard .Common.Timing
{
public class UnspecifiedClockProvider:IClockProvider
{
public DateTime Now => DateTime.Now;
public DateTimeKind Kind => DateTimeKind.Unspecified;
public bool SupportsMultipleTimezone => false;
public DateTime Normalize(DateTime dateTime)
{
return dateTime;
}
internal UnspecifiedClockProvider()
{ }
}
}
|
||||
TheStack | bd792a7629f29c299822b8450fcd7105bf5867c4 | C#code:C# | {"size": 358, "ext": "cshtml", "max_stars_repo_path": "src/OpenRealEstate.NET.WebSite/Views/Shared/_Layout.cshtml", "max_stars_repo_name": "OpenRealEstate/OpenRealEstate.NET.Website", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OpenRealEstate.NET.WebSite/Views/Shared/_Layout.cshtml", "max_issues_repo_name": "OpenRealEstate/OpenRealEstate.NET.Website", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OpenRealEstate.NET.WebSite/Views/Shared/_Layout.cshtml", "max_forks_repo_name": "OpenRealEstate/OpenRealEstate.NET.Website", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.0588235294, "max_line_length": 62, "alphanum_fraction": 0.5} | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>OpenRealEstate validator</title>
</head>
<body>
<div>
@RenderBody()
</div>
<script src="/js/jquery-2.2.3.min.js"></script>
@RenderSection("scripts", false)
</body>
</html> |
||||
TheStack | bd7a7962e118cac46ce3d928e7a3dff3b814c0d7 | C#code:C# | {"size": 165, "ext": "cs", "max_stars_repo_path": "src/NPOI/Label.cs", "max_stars_repo_name": "hypertherm/NPOI", "max_stars_repo_stars_event_min_datetime": "2017-08-18T16:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:38:58.000Z", "max_issues_repo_path": "src/NPOI/Label.cs", "max_issues_repo_name": "mihir-vinchhi/NPOI", "max_issues_repo_issues_event_min_datetime": "2017-08-20T19:24:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T11:51:05.000Z", "max_forks_repo_path": "src/NPOI/Label.cs", "max_forks_repo_name": "mihir-vinchhi/NPOI", "max_forks_repo_forks_event_min_datetime": "2017-08-18T08:12:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:38:38.000Z"} | {"max_stars_count": 1703.0, "max_issues_count": 163.0, "max_forks_count": 396.0, "avg_line_length": 13.75, "max_line_length": 44, "alphanum_fraction": 0.5757575758} | using System.Drawing;
namespace NPOI
{
public class Label
{
public Color ForeColor { get; set; }
public string Text { get; set; }
}
}
|
||||
TheStack | bd7ca70c7c7ac33516df8439ad422c9c66f4447b | C#code:C# | {"size": 2380, "ext": "cs", "max_stars_repo_path": "MediaViewer/ImageViewer.cs", "max_stars_repo_name": "hdunderscore/UrhoAngelscriptIDE", "max_stars_repo_stars_event_min_datetime": "2016-08-26T07:20:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-20T18:26:19.000Z", "max_issues_repo_path": "MediaViewer/ImageViewer.cs", "max_issues_repo_name": "hdunderscore/UrhoAngelscriptIDE", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MediaViewer/ImageViewer.cs", "max_forks_repo_name": "hdunderscore/UrhoAngelscriptIDE", "max_forks_repo_forks_event_min_datetime": "2016-03-01T18:25:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T11:35:33.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 34.4927536232, "max_line_length": 90, "alphanum_fraction": 0.5298319328} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
namespace MediaViewer
{
public class ImageViewer : PluginLib.IFileEditor
{
public bool CanEditFile(string filePath, string fileExtension)
{
if (fileExtension.ToLowerInvariant().Equals(".png") ||
fileExtension.ToLowerInvariant().Equals(".bmp") ||
fileExtension.ToLowerInvariant().Equals(".tga") ||
fileExtension.ToLowerInvariant().Equals(".dds") ||
fileExtension.ToLowerInvariant().Equals(".jpg") ||
fileExtension.ToLowerInvariant().Equals(".jpeg"))
{
return true;
}
return false;
}
public PluginLib.IExternalControlData CreateEditorContent(string filePath)
{
StackPanel grid = new StackPanel();
Image img = new Image();
grid.Children.Add(img);
grid.CanVerticallyScroll = true;
grid.CanHorizontallyScroll = true;
grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
grid.VerticalAlignment = System.Windows.VerticalAlignment.Center;
img.MouseWheel += img_MouseWheel;
img.Source = new BitmapImage(new Uri(filePath));
img.Width = img.Source.Width;
img.Height = img.Source.Height;
ControlData ret = new ControlData();
ret.Control = grid;
img.Tag = ret;
return ret;
}
void img_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
Image img = sender as Image;
if (img != null)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (e.Delta > 0)
{
img.Width = img.Width * 1.1;
img.Height = img.Height * 1.1;
}
else
{
img.Width = img.Width * 0.9;
img.Height = img.Height * 0.9;
}
}
}
}
}
}
|
||||
TheStack | bd7e8be4caafafc05d07e49c48c536d4d63f901c | C#code:C# | {"size": 2321, "ext": "cs", "max_stars_repo_path": "auth/WebService/v1/Controllers/Users.cs", "max_stars_repo_name": "Azure/Azure_IoT_Solution_Accelerators_dotnet", "max_stars_repo_stars_event_min_datetime": "2018-08-07T15:18:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:49:09.000Z", "max_issues_repo_path": "auth/WebService/v1/Controllers/Users.cs", "max_issues_repo_name": "Azure/Azure_IoT_Solution_Accelerators_dotnet", "max_issues_repo_issues_event_min_datetime": "2018-07-30T16:40:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T21:39:37.000Z", "max_forks_repo_path": "auth/WebService/v1/Controllers/Users.cs", "max_forks_repo_name": "Azure/Azure_IoT_Solution_Accelerators_dotnet", "max_forks_repo_forks_event_min_datetime": "2018-07-31T06:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T16:47:33.000Z"} | {"max_stars_count": 33.0, "max_issues_count": 123.0, "max_forks_count": 51.0, "avg_line_length": 37.435483871, "max_line_length": 111, "alphanum_fraction": 0.6428263679} | // Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.IoTSolutions.Auth.Services;
using Microsoft.Azure.IoTSolutions.Auth.WebService.Auth;
using Microsoft.Azure.IoTSolutions.Auth.WebService.v1.Filters;
using Microsoft.Azure.IoTSolutions.Auth.WebService.v1.Models;
namespace Microsoft.Azure.IoTSolutions.Auth.WebService.v1.Controllers
{
[Route(Version.PATH + "/[controller]"), TypeFilter(typeof(ExceptionsFilterAttribute))]
public class UsersController : Controller
{
private readonly IUsers users;
public UsersController(IUsers users)
{
this.users = users;
}
[HttpGet("{id}")]
public UserApiModel Get(string id)
{
var user = this.users.GetUserInfo(this.Request.GetCurrentUserClaims());
if (id != "current" && id != user.Id) return null;
return new UserApiModel(user);
}
/// <summary>
/// This action is used by other services to get allowed action based on
/// user roles extracted from JWT token but not requiring to pass the token.
/// </summary>
/// <param name="id">user object id</param>
/// <param name="roles">a list of role names</param>
/// <returns>a list of allowed actions</returns>
[HttpPost("{id}/allowedActions")]
public IEnumerable<string> GetAllowedActions([FromRoute]string id, [FromBody]IEnumerable<string> roles)
{
return this.users.GetAllowedActions(roles);
}
/// <summary>
/// This action is used by Web UI and other services to get ARM token for
/// the application to perform resource management task.
/// </summary>
/// <param name="id">user object id</param>
/// <param name="audience">audience of the token, use ARM as default audience</param>
/// <returns>token for the audience</returns>
[HttpGet("{id}/token")]
[Authorize("AcquireToken")]
public async Task<TokenApiModel> GetToken([FromRoute]string id, [FromQuery]string audience)
{
var token = await this.users.GetToken(audience);
return new TokenApiModel(token);
}
}
}
|
||||
TheStack | bd7e9e5421a4ca23051c2e2fc03593f0cc150e84 | C#code:C# | {"size": 687, "ext": "cs", "max_stars_repo_path": "src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs", "max_stars_repo_name": "lkts/coreclr", "max_stars_repo_stars_event_min_datetime": "2019-05-19T20:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-19T20:44:03.000Z", "max_issues_repo_path": "src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs", "max_issues_repo_name": "lkts/coreclr", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeMethods.cs", "max_forks_repo_name": "lkts/coreclr", "max_forks_repo_forks_event_min_datetime": "2020-11-17T14:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-17T14:55:53.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 27.48, "max_line_length": 74, "alphanum_fraction": 0.6885007278} | // 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.
#if FEATURE_COMINTEROP
namespace System.Runtime.InteropServices
{
/// <summary>
/// Part of ComEventHelpers APIs which allow binding managed delegates
/// to COM's connection point based events.
/// </summary>
internal static class NativeMethods
{
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00020400-0000-0000-C000-000000000046")]
internal interface IDispatch
{
}
}
}
#endif
|
||||
TheStack | bd7fd4b9cfdfaeeae07a4f08222e6f5226e828be | C#code:C# | {"size": 1542, "ext": "cs", "max_stars_repo_path": "src/devices/Sht3x/samples/Program.cs", "max_stars_repo_name": "paulmey/iot", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/devices/Sht3x/samples/Program.cs", "max_issues_repo_name": "paulmey/iot", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/devices/Sht3x/samples/Program.cs", "max_forks_repo_name": "paulmey/iot", "max_forks_repo_forks_event_min_datetime": "2020-11-04T23:28:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T23:28:09.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 37.6097560976, "max_line_length": 143, "alphanum_fraction": 0.6121919585} | // 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.Device.I2c;
using System.Threading;
using Iot.Device.Common;
using UnitsNet;
namespace Iot.Device.Sht3x.Samples
{
internal class Program
{
public static void Main(string[] args)
{
I2cConnectionSettings settings = new I2cConnectionSettings(1, (byte)I2cAddress.AddrLow);
I2cDevice device = I2cDevice.Create(settings);
using (Sht3x sensor = new Sht3x(device))
{
while (true)
{
var tempValue = sensor.Temperature;
var humValue = sensor.Humidity;
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Relative humidity: {humValue:0.#}%");
// WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
Console.WriteLine();
Thread.Sleep(1000);
}
}
}
}
}
|
||||
TheStack | bd80561c960d38919a1ef339e84b1d90d39b7e22 | C#code:C# | {"size": 1966, "ext": "cs", "max_stars_repo_path": "AdaptiveRoads/NSInterface/ARCustomFlags.cs", "max_stars_repo_name": "Elesbaan70/AdaptiveNetworks", "max_stars_repo_stars_event_min_datetime": "2021-12-19T12:31:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T14:34:42.000Z", "max_issues_repo_path": "AdaptiveRoads/NSInterface/ARCustomFlags.cs", "max_issues_repo_name": "Elesbaan70/AdaptiveNetworks", "max_issues_repo_issues_event_min_datetime": "2021-12-26T03:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T05:37:42.000Z", "max_forks_repo_path": "AdaptiveRoads/NSInterface/ARCustomFlags.cs", "max_forks_repo_name": "Elesbaan70/AdaptiveNetworks", "max_forks_repo_forks_event_min_datetime": "2021-12-27T13:19:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T01:48:25.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 13.0, "max_forks_count": 3.0, "avg_line_length": 33.3220338983, "max_line_length": 91, "alphanum_fraction": 0.5442522889} | namespace AdaptiveRoads.NSInterface {
using AdaptiveRoads.Manager;
using System;
using System.Linq;
using KianCommons;
using AdaptiveRoads.Data.NetworkExtensions;
public class ARCustomFlags : ICloneable {
public NetSegmentExt.Flags Segment;
public NetSegmentEnd.Flags SegmentEnd;
public NetNodeExt.Flags Node;
public NetLaneExt.Flags[] Lanes;
public ARCustomFlags() { }
public ARCustomFlags(int nLanes) {
Lanes = new NetLaneExt.Flags[nLanes];
}
public ARCustomFlags Clone() {
var ret = MemberwiseClone() as ARCustomFlags;
ret.Lanes = ret.Lanes.Clone() as NetLaneExt.Flags[];
return ret;
}
object ICloneable.Clone() => this.Clone();
public override bool Equals(object obj) {
return obj is ARCustomFlags data &&
Segment.Equals(data.Segment) &&
SegmentEnd.Equals(data.SegmentEnd) &&
Node.Equals(data.Node) &&
Lanes.SequenceEqual(data.Lanes);
}
public override int GetHashCode() {
unchecked {
int hc = Segment.GetHashCode();
hc = unchecked(hc * 314159 + Node.GetHashCode());
hc = unchecked(hc * 314159 + SegmentEnd.GetHashCode());
hc = unchecked(hc * 314159 + Node.GetHashCode());
for(int i = 0; i < Lanes.Length; ++i)
hc = unchecked(hc * 314159 + Lanes[i].GetHashCode());
return hc;
}
}
public bool IsDefault() {
return
Segment == default &&
SegmentEnd == default &&
Node == default &&
Lanes.All(lane => lane == default);
}
public override string ToString() =>
$"segment:{Segment} segmentEnd:{SegmentEnd} node:{Node} lanes:{Lanes.ToSTR()}";
}
}
|
||||
TheStack | bd80737c41dcd235af85f81d60ce4c57bd3b2ace | C#code:C# | {"size": 4878, "ext": "cs", "max_stars_repo_path": "src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Generators/ResultFromEntityTypeMapperGenerator.cs", "max_stars_repo_name": "cliedeman/hotchocolate", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Generators/ResultFromEntityTypeMapperGenerator.cs", "max_issues_repo_name": "cliedeman/hotchocolate", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Generators/ResultFromEntityTypeMapperGenerator.cs", "max_forks_repo_name": "cliedeman/hotchocolate", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.2366412214, "max_line_length": 97, "alphanum_fraction": 0.540795408} | using System;
using System.Collections.Generic;
using StrawberryShake.CodeGeneration.CSharp.Builders;
using StrawberryShake.CodeGeneration.CSharp.Extensions;
using StrawberryShake.CodeGeneration.Descriptors.TypeDescriptors;
using StrawberryShake.CodeGeneration.Extensions;
using static StrawberryShake.CodeGeneration.Descriptors.NamingConventions;
namespace StrawberryShake.CodeGeneration.CSharp.Generators
{
public class ResultFromEntityTypeMapperGenerator : TypeMapperGenerator
{
private const string _entity = "entity";
protected const string entityStore = "entityStore";
private const string _entityStore = "_entityStore";
private const string _map = "Map";
private const string _snapshot = "snapshot";
protected override bool CanHandle(ITypeDescriptor descriptor,
CSharpSyntaxGeneratorSettings settings)
{
return descriptor.Kind == TypeKind.Entity && !descriptor.IsInterface() &&
!settings.NoStore;
}
protected override void Generate(ITypeDescriptor typeDescriptor,
CSharpSyntaxGeneratorSettings settings,
CodeWriter writer,
out string fileName,
out string? path,
out string ns)
{
// Setup class
ComplexTypeDescriptor descriptor =
typeDescriptor as ComplexTypeDescriptor ??
throw new InvalidOperationException(
"A result entity mapper can only be generated for complex types");
fileName = descriptor.ExtractMapperName();
path = State;
ns = CreateStateNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal);
ClassBuilder classBuilder = ClassBuilder
.New()
.AddImplements(
TypeNames.IEntityMapper
.WithGeneric(
descriptor.ExtractType().ToString(),
descriptor.RuntimeType.Name))
.SetName(fileName);
ConstructorBuilder constructorBuilder = ConstructorBuilder
.New()
.SetTypeName(descriptor.Name);
AddConstructorAssignedField(
TypeNames.IEntityStore,
_entityStore,
entityStore,
classBuilder,
constructorBuilder);
// Define map method
MethodBuilder mapMethod = MethodBuilder
.New()
.SetName(_map)
.SetAccessModifier(AccessModifier.Public)
.SetReturnType(descriptor.RuntimeType.Name)
.AddParameter(
ParameterBuilder
.New()
.SetType(
descriptor.Kind == TypeKind.Entity
? CreateEntityType(
descriptor.Name,
descriptor.RuntimeType.NamespaceWithoutGlobal)
.ToString()
: descriptor.Name)
.SetName(_entity))
.AddParameter(
_snapshot,
b => b.SetDefault("null")
.SetType(TypeNames.IEntityStoreSnapshot.MakeNullable()));
mapMethod
.AddCode(IfBuilder
.New()
.SetCondition($"{_snapshot} is null")
.AddCode(AssignmentBuilder
.New()
.SetLefthandSide(_snapshot)
.SetRighthandSide($"{_entityStore}.CurrentSnapshot")))
.AddEmptyLine();
MethodCallBuilder constructorCall =
MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName(descriptor.RuntimeType.Name);
if (typeDescriptor is ComplexTypeDescriptor complexTypeDescriptor)
{
foreach (PropertyDescriptor property in complexTypeDescriptor.Properties)
{
constructorCall.AddArgument(BuildMapMethodCall(settings, _entity, property));
}
}
mapMethod.AddCode(constructorCall);
if (constructorBuilder.HasParameters())
{
classBuilder.AddConstructor(constructorBuilder);
}
classBuilder.AddMethod(mapMethod);
AddRequiredMapMethods(
settings,
_entity,
descriptor,
classBuilder,
constructorBuilder,
new HashSet<string>());
classBuilder.Build(writer);
}
}
}
|
||||
TheStack | bd81d51536c671a48c70b18c17b15626a9972d2b | C#code:C# | {"size": 2623, "ext": "cs", "max_stars_repo_path": "Source/ConfigurationValidation.Tests/ConfigurationValidationExceptionTests.cs", "max_stars_repo_name": "salixzs/ConfigurationValidation", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/ConfigurationValidation.Tests/ConfigurationValidationExceptionTests.cs", "max_issues_repo_name": "salixzs/ConfigurationValidation", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/ConfigurationValidation.Tests/ConfigurationValidationExceptionTests.cs", "max_forks_repo_name": "salixzs/ConfigurationValidation", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.7424242424, "max_line_length": 126, "alphanum_fraction": 0.6191383912} | using System.Collections.Generic;
using FluentAssertions;
using Xunit;
namespace ConfigurationValidation.Tests
{
public class ConfigurationValidationExceptionTests
{
[Fact]
public void ValidationException_Construct_EmptyValidations()
{
var ex = new ConfigurationValidationException();
ex.Message.Should().Be("Configuration validation threw exception.");
ex.ToString().Should().Be("Configuration validation threw exception.");
ex.ValidationData.Should().NotBeNull();
ex.ValidationData.Count.Should().Be(0);
}
[Fact]
public void ValidationException_ConstructColl_NotEmptyValidations()
{
var vals = new ConfigurationValidationCollection();
vals.Add(new ConfigurationValidationItem("Sect", "cfg", 22, "Something"));
vals.Add(new ConfigurationValidationItem("Sect", "set", true, "bool"));
var ex = new ConfigurationValidationException(vals);
ex.Message.Should().Be("Configuration validation threw exception.");
ex.ToString().Should().Be("Cofiguration validation found problems with configured values. 2 validations failed.");
ex.ValidationData.Should().NotBeNull();
ex.ValidationData.Count.Should().Be(2);
}
[Fact]
public void ValidationException_ConstructList_EmptyValidations()
{
var vals = new List<ConfigurationValidationItem>
{
new ConfigurationValidationItem("Sect", "cfg", 22, "Something"),
new ConfigurationValidationItem("Sect", "set", true, "bool")
};
var ex = new ConfigurationValidationException("Test", vals);
ex.Message.Should().Be("Test");
ex.ToString().Should().Be("Test. 2 validations failed.");
ex.ValidationData.Should().NotBeNull();
ex.ValidationData.Count.Should().Be(2);
}
[Fact]
public void ValidationException_ConstructArr_EmptyValidations()
{
var vals = new ConfigurationValidationItem[2];
vals[0] = new ConfigurationValidationItem("Sect", "cfg", 22, "Something");
vals[1] = new ConfigurationValidationItem("Sect", "set", true, "bool");
var ex = new ConfigurationValidationException("Test", vals);
ex.Message.Should().Be("Test");
ex.ToString().Should().Be("Test. 2 validations failed.");
ex.ValidationData.Should().NotBeNull();
ex.ValidationData.Count.Should().Be(2);
}
}
}
|
||||
TheStack | bd82a84ccdf13f702df1c33977a2af1f71ec0ad8 | C#code:C# | {"size": 60747, "ext": "cs", "max_stars_repo_path": "Mods/HelloWorld/Main.cs", "max_stars_repo_name": "uf0wxxel/ScrollOfTaiwuMods", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mods/HelloWorld/Main.cs", "max_issues_repo_name": "uf0wxxel/ScrollOfTaiwuMods", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mods/HelloWorld/Main.cs", "max_forks_repo_name": "uf0wxxel/ScrollOfTaiwuMods", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 42.3324041812, "max_line_length": 247, "alphanum_fraction": 0.5330962846} | using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Linq;
using Harmony12;
using UnityEngine;
using UnityModManagerNet;
namespace BossGongfaFixEnhance
{
public class Settings : UnityModManager.ModSettings
{
public override void Save(UnityModManager.ModEntry modEntry) => Save(this, modEntry);
public bool poisonImmunity = false;
public bool injuryImmunity = false;
public bool worsenImmunity = false;
public bool gongfaImmunity = false;
public bool bianzhaoEnhance = false;
public bool bianzhaoProhibit = false;
public bool alwaysHitGongfa = false;
public bool spFix = false;
public bool noPrepareGongfa = false;
public bool removeGangLimit = false;
public bool noDeath = false;
public bool bossGongfa1_1 = false;
public bool bossGongfa1_2 = false;
public bool bossGongfa1_3 = false;
public bool bossGongfa1_4 = false;
public bool bossGongfa1_5 = false;
public bool bossGongfa1_6 = false;
public bool bossGongfa1_7 = false;
public bool bossGongfa1_8 = false;
public bool bossGongfa1_9 = false;
public bool bossGongfa2_1 = false;
public bool bossGongfa2_2 = false;
public bool bossGongfa2_3 = false;
public bool bossGongfa2_4 = false;
public bool bossGongfa2_5 = false;
public bool bossGongfa2_6 = false;
public bool bossGongfa2_7 = false;
public bool bossGongfa2_8 = false;
public bool bossGongfa2_9 = false;
public bool bossGongfa2_10 = false;
public bool randTeam = false;
public string randTeamMember1 = "6009";
public string randTeamMember2 = "6008";
public string randTeamMember3 = "6007";
public string randTeamMember4 = "";
public bool randActor = false;
public string randTeamMember0 = "2001";
public bool modXXLevel = false;
public string xxLevel = "0";
}
public static class Main
{
public static UnityModManager.ModEntry Mod { get; private set; }
public static Settings settings;
public static UnityModManager.ModEntry.ModLogger Logger => Mod?.Logger;
public static int[] attackPartChooseAlways = {100, 100, 100, 100, 100, 100, 100};
public static int[] attackPartChooseOriginal;
public static int actorBol;
public static int actorRel;
public static int actorEve;
public static int actorDir;
public const bool DEBUG = false;
public static bool Load(UnityModManager.ModEntry modEntry)
{
settings = Settings.Load<Settings>(modEntry);
Mod = modEntry;
HarmonyInstance.Create(Mod.Info.Id).PatchAll(Assembly.GetExecutingAssembly());
Mod.OnGUI = OnGUI;
Mod.OnSaveGUI = OnSaveGUI;
return true;
}
private static void OnGUI(UnityModManager.ModEntry modEntry)
{
var gameVersionText = DateFile.instance?.gameVersion?.Trim();
GUILayout.BeginVertical("Box");
GUILayout.Label($"已测试的游戏版本:0.2.8.4, 当前游戏版本:{gameVersionText}");
settings.poisonImmunity = GUILayout.Toggle(settings.poisonImmunity, "战斗中免疫我方所有毒素增加");
settings.injuryImmunity = GUILayout.Toggle(settings.injuryImmunity, "战斗中免疫我方所有伤势增加");
settings.worsenImmunity = GUILayout.Toggle(settings.worsenImmunity, "战斗中免疫我方所有伤势恶化");
settings.gongfaImmunity = GUILayout.Toggle(settings.gongfaImmunity, "战斗中敌方所有摧破功法零成");
settings.bianzhaoEnhance = GUILayout.Toggle(settings.bianzhaoEnhance, "战斗中我方所有变招必成功");
settings.bianzhaoProhibit = GUILayout.Toggle(settings.bianzhaoProhibit, "战斗中敌方所有变招被禁止");
settings.alwaysHitGongfa = GUILayout.Toggle(settings.alwaysHitGongfa, "战斗中我方所有功法不被化解");
settings.spFix = GUILayout.Toggle(settings.spFix, "战斗中我方所有真气不减");
settings.noPrepareGongfa = GUILayout.Toggle(settings.noPrepareGongfa, "战斗中我方所有功法无需准备");
settings.removeGangLimit = GUILayout.Toggle(settings.removeGangLimit, "战斗中我方所有功法帮派不限");
settings.noDeath = GUILayout.Toggle(settings.noDeath, "战斗中我方不死");
GUILayout.Label("战斗中我方开启以下功法:(战斗开始前设置)");
GUILayout.BeginHorizontal();
settings.bossGongfa1_1 = GUILayout.Toggle(settings.bossGongfa1_1, "闻恶声");
settings.bossGongfa1_2 = GUILayout.Toggle(settings.bossGongfa1_2, "祛善");
settings.bossGongfa1_3 = GUILayout.Toggle(settings.bossGongfa1_3, "唤目");
settings.bossGongfa1_4 = GUILayout.Toggle(settings.bossGongfa1_4, "妖心示显");
settings.bossGongfa1_5 = GUILayout.Toggle(settings.bossGongfa1_5, "百邪");
settings.bossGongfa1_6 = GUILayout.Toggle(settings.bossGongfa1_6, "堕心九部众");
settings.bossGongfa1_7 = GUILayout.Toggle(settings.bossGongfa1_7, "众相生");
settings.bossGongfa1_8 = GUILayout.Toggle(settings.bossGongfa1_8, "神断护法");
settings.bossGongfa1_9 = GUILayout.Toggle(settings.bossGongfa1_9, "玄狱九老");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
settings.bossGongfa2_1 = GUILayout.Toggle(settings.bossGongfa2_1, "神女还剑");
settings.bossGongfa2_2 = GUILayout.Toggle(settings.bossGongfa2_2, "镇狱伏邪");
settings.bossGongfa2_3 = GUILayout.Toggle(settings.bossGongfa2_3, "奇寒灵气");
settings.bossGongfa2_4 = GUILayout.Toggle(settings.bossGongfa2_4, "七字五彩");
settings.bossGongfa2_5 = GUILayout.Toggle(settings.bossGongfa2_5, "倾国绝世");
settings.bossGongfa2_6 = GUILayout.Toggle(settings.bossGongfa2_6, "龙胎化命");
settings.bossGongfa2_7 = GUILayout.Toggle(settings.bossGongfa2_7, "溶尘化玉");
settings.bossGongfa2_8 = GUILayout.Toggle(settings.bossGongfa2_8, "八肱八趾");
settings.bossGongfa2_9 = GUILayout.Toggle(settings.bossGongfa2_9, "方天敕令");
settings.bossGongfa2_10 = GUILayout.Toggle(settings.bossGongfa2_10, "相枢真身");
GUILayout.EndHorizontal();
settings.randTeam = GUILayout.Toggle(settings.randTeam, "战斗中我方随机生成队友");
if (settings.randTeam) {
GUILayout.Label("使用以下id作为队友:(无效id会导致原队友不变)");
GUILayout.BeginHorizontal();
settings.randTeamMember1 = GUILayout.TextField(settings.randTeamMember1, GUILayout.Width(100f));
settings.randTeamMember2 = GUILayout.TextField(settings.randTeamMember2, GUILayout.Width(100f));
settings.randTeamMember3 = GUILayout.TextField(settings.randTeamMember3, GUILayout.Width(100f));
settings.randTeamMember4 = GUILayout.TextField(settings.randTeamMember4, GUILayout.Width(100f));
GUILayout.EndHorizontal();
}
settings.randActor = GUILayout.Toggle(settings.randActor, "战斗中我方随机生成主角");
if (settings.randActor) {
GUILayout.Label("使用以下id作为主角:(无效id会导致原队友不变)");
GUILayout.BeginHorizontal();
settings.randTeamMember0 = GUILayout.TextField(settings.randTeamMember0, GUILayout.Width(100f));
GUILayout.EndHorizontal();
}
settings.modXXLevel = GUILayout.Toggle(settings.modXXLevel, "修改已击败剑冢个数");
if (settings.modXXLevel) {
GUILayout.Label("输入整数0-9:(默认为0)");
GUILayout.BeginHorizontal();
settings.xxLevel = GUILayout.TextField(settings.xxLevel, GUILayout.Width(100f));
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
private static void OnSaveGUI(UnityModManager.ModEntry modEntry) => settings.Save(modEntry);
}
[HarmonyPatch(typeof(BattleSystem), "SetDamage")]
public static class BattleSystem_SetDamage_Patch
{
static readonly HashSet<OpCode> branchCodes = new HashSet<OpCode>
{
OpCodes.Br_S, OpCodes.Brfalse_S, OpCodes.Brtrue_S, OpCodes.Beq_S, OpCodes.Bge_S, OpCodes.Bgt_S,
OpCodes.Ble_S, OpCodes.Blt_S, OpCodes.Bne_Un_S, OpCodes.Bge_Un_S, OpCodes.Bgt_Un_S, OpCodes.Ble_Un_S,
OpCodes.Blt_Un_S, OpCodes.Br, OpCodes.Brfalse, OpCodes.Brtrue, OpCodes.Beq, OpCodes.Bge, OpCodes.Bgt,
OpCodes.Ble, OpCodes.Blt, OpCodes.Bne_Un, OpCodes.Bge_Un, OpCodes.Bgt_Un, OpCodes.Ble_Un, OpCodes.Blt_Un
};
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
if (Main.DEBUG) Main.Logger.Log("BattleSystem_SetDamage_Patch1 start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c45) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
if (i < codes.Count) {
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_2) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].opcode = OpCodes.Ldc_I4_S;
codes[i].operand = (sbyte)100;
break;
}
}
if (Main.DEBUG && i < codes.Count) Main.Logger.Log("BattleSystem_SetDamage_Patch1 success");
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_SetDamage_Patch2 start");
for (i = 0; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c48) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
if (i < codes.Count) {
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x1e) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = (sbyte)100;
break;
}
}
if (i < codes.Count) {
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c48) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
if (i < codes.Count) {
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x1e) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = (sbyte)0x32;
break;
}
}
if (Main.DEBUG && i < codes.Count) Main.Logger.Log("BattleSystem_SetDamage_Patch2 success");
}
}
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_SetDamage_Patch3 start");
i = 0;
var startIndex = -1;
var endIndex = -1;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4) {
int val = (int)codes[i].operand;
if (val == 0x7534) {
startIndex = i - 1;
break;
}
}
}
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4) {
int val = (int)codes[i].operand;
if (val == 0x7534) {
break;
}
}
}
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Starg_S) {
break;
}
}
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldarg_1) {
endIndex = i;
break;
}
}
if (startIndex < 0 || endIndex <= startIndex) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("1: " + startIndex.ToString());
if (Main.DEBUG) Main.Logger.Log("1: " + endIndex.ToString());
var modified = codes.GetRange(startIndex, endIndex - startIndex);
for (i = 0; i < modified.Count; i++) {
List<Label> temp = modified[i].labels;
modified[i] = modified[i].Clone();
if (temp.Any()) {
modified[i].labels = new List<Label>(temp);
}
}
modified[0].labels.Clear();
object inst1 = null;
object inst2 = null;
for (i = 0; i < modified.Count; i++) {
if (modified[i].opcode == OpCodes.Ldfld) {
inst1 = modified[i].operand;
break;
}
}
if (Main.DEBUG) Main.Logger.Log("2: " + i.ToString());
for (i++; i < modified.Count; i++) {
if (modified[i].opcode == OpCodes.Ldfld) {
inst2 = modified[i].operand;
break;
}
}
if (Main.DEBUG) Main.Logger.Log("2: " + i.ToString());
if (inst1 == null || inst2 == null) return instructions;
var j = 0;
for (i = 0; i < modified.Count && j < 8; i++) {
if (modified[i].opcode == OpCodes.Ldfld) {
if (j % 2 == 0) {
modified[i].operand = inst2;
if (Main.DEBUG) Main.Logger.Log("3.1: " + i.ToString());
} else {
modified[i].operand = inst1;
if (Main.DEBUG) Main.Logger.Log("3.2: " + i.ToString());
}
j++;
}
}
for (i = 0; i < modified.Count; i++) {
if (modified[i].opcode == OpCodes.Ldc_I4 && (int)modified[i].operand == 0x7534) {
modified[i].operand = 0x9c44;
if (Main.DEBUG) Main.Logger.Log("4: " + i.ToString());
}
}
var rpLabels = new Dictionary<Label, Label>();
for (i = 0; i < modified.Count; i++) {
if (modified[i].labels.Any()) {
if (Main.DEBUG) Main.Logger.Log("5: " + i.ToString());
for (j = 0; j < modified[i].labels.Count; j++) {
var oldLabel = modified[i].labels[j];
modified[i].labels[j] = generator.DefineLabel();
rpLabels[oldLabel] = modified[i].labels[j];
}
}
}
for (i = 0; i < modified.Count; i++) {
if (branchCodes.Contains(modified[i].opcode)) {
Label tempLabel;
if (rpLabels.TryGetValue((Label)modified[i].operand, out tempLabel)) {
if (Main.DEBUG) Main.Logger.Log("6.1: " + i.ToString());
modified[i].operand = tempLabel;
} else {
if (Main.DEBUG) Main.Logger.Log("6.0: " + i.ToString());
}
}
}
codes.InsertRange(endIndex, modified);
var newEnd = endIndex + modified.Count;
if (Main.DEBUG) Main.Logger.Log("7: " + newEnd.ToString());
codes[endIndex].labels = new List<Label>(codes[newEnd].labels);
codes[newEnd].labels.Clear();
Label newLabel = generator.DefineLabel();
codes[newEnd].labels.Add(newLabel);
for (i = endIndex; i < newEnd; i++) {
if (codes[i].opcode == OpCodes.Brfalse) {
if (Main.DEBUG) Main.Logger.Log("8.0: " + i.ToString());
codes[i].operand = newLabel;
break;
}
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_SetDamage_Patch3 success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleSystem), "AutoSetDefGongFa")]
class BattleSystem_AutoSetDefGongFa_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleSystem_AutoSetDefGongFa_Patch start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
var index = -1;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4) {
int val = (int)codes[i].operand;
if (val == 0x9c44) {
index = i;
break;
}
}
}
if (index < 0) return instructions;
for (index = -1; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_M1) {
index = i;
break;
}
}
if (index < 0) return instructions;
CodeInstruction copy = null;
for (index = -1; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_1) {
index = i;
break;
}
if (codes[i].opcode == OpCodes.Call) {
copy = codes[i].Clone();
}
}
if (index < 0 || copy == null) return instructions;
if (Main.DEBUG) Main.Logger.Log(index.ToString());
var toInsert = new List<CodeInstruction>(2);
toInsert.Add(new CodeInstruction(OpCodes.Ldc_I4_4));
toInsert.Add(copy);
codes.InsertRange(index + 1, toInsert);
if (Main.DEBUG) Main.Logger.Log("BattleSystem_AutoSetDefGongFa_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleSystem), "UseGongFa")]
class BattleSystem_UseGongFa_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
if (Main.DEBUG) Main.Logger.Log("BattleSystem_UseGongFa_Patch1 start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c4a) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
if (i < codes.Count) {
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x96) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = 0x12c;
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x12c) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = 0x258;
break;
}
}
if (Main.DEBUG && i < codes.Count) Main.Logger.Log("BattleSystem_UseGongFa_Patch1 success");
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_UseGongFa_Patch2 start");
i = 0;
var index = -1;
var found = false;
for (; i + 2 < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldarg_0 && codes[i + 1].opcode == OpCodes.Ldfld && codes[i + 2].opcode == OpCodes.Ldloc_2) {
if (found) {
index = i + 1;
break;
} else {
found = true;
}
}
}
if (index < 1) {
return instructions;
}
CodeInstruction copy1 = codes[index].Clone();
if (Main.DEBUG) Main.Logger.Log(index.ToString());
CodeInstruction copy3 = null;
for (i = index - 2; i >= 0; i--) {
if (codes[i].opcode == OpCodes.Ldfld) {
copy3 = codes[i].Clone();
break;
}
}
if (Main.DEBUG) Main.Logger.Log(i.ToString());
CodeInstruction copy2 = null;
for (i = index + 2; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldfld) {
copy2 = codes[i].Clone();
break;
}
}
if (Main.DEBUG) Main.Logger.Log(i.ToString());
if (copy2 == null || copy3 == null) {
return instructions;
}
for (index = -1, i = 0; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x4e29) {
index = i;
break;
}
}
if (index < 0) {
return instructions;
}
for (index = -1; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldfld && codes[i].operand == copy2.operand) {
index = i;
break;
}
}
if (index < 0) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log(index.ToString());
Label l1 = generator.DefineLabel();
Label l2 = generator.DefineLabel();
codes[index].labels.Add(l1);
codes[index + 1].labels.Add(l2);
var toInsert = new List<CodeInstruction>(5);
toInsert.Add(new CodeInstruction(OpCodes.Ldloc_0));
toInsert.Add(copy3.Clone());
toInsert.Add(new CodeInstruction(OpCodes.Brfalse_S, l1));
toInsert.Add(copy1.Clone());
toInsert.Add(new CodeInstruction(OpCodes.Br_S, l2));
codes.InsertRange(index, toInsert);
for (index = -1, i += 7; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldfld && codes[i].operand == copy2.operand) {
index = i;
break;
}
}
if (index < 0) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log(index.ToString());
l1 = generator.DefineLabel();
l2 = generator.DefineLabel();
codes[index].labels.Add(l1);
codes[index + 1].labels.Add(l2);
toInsert = new List<CodeInstruction>(5);
toInsert.Add(new CodeInstruction(OpCodes.Ldloc_0));
toInsert.Add(copy3.Clone());
toInsert.Add(new CodeInstruction(OpCodes.Brfalse_S, l1));
toInsert.Add(copy1.Clone());
toInsert.Add(new CodeInstruction(OpCodes.Br_S, l2));
codes.InsertRange(index, toInsert);
if (Main.DEBUG) Main.Logger.Log("BattleSystem_UseGongFa_Patch2 success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleSystem), "ActionGongFaDamage")]
class BattleSystem_ActionGongFaDamage_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleSystem_ActionGongFaDamage_Patch start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c49) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x19) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = (sbyte)0x32;
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 10) {
if (Main.DEBUG) Main.Logger.Log("1: " + i.ToString());
codes[i].operand = (sbyte)20;
break;
}
}
i++;
for (var j = 0; i < codes.Count && j < 2; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_0) {
j++;
}
}
if (i < codes.Count) {
if (Main.DEBUG) Main.Logger.Log("1x: " + i.ToString());
codes[i].opcode = OpCodes.Ldc_I4_1;
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c49) {
if (Main.DEBUG) Main.Logger.Log("0: " + i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x19) {
if (Main.DEBUG) Main.Logger.Log("2: " + i.ToString());
codes[i].operand = (sbyte)0x32;
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_5) {
if (Main.DEBUG) Main.Logger.Log("2: " + i.ToString());
codes[i].opcode = OpCodes.Ldc_I4_S;
codes[i].operand = (sbyte)10;
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_0) {
break;
}
}
if (++i < codes.Count) {
if (Main.DEBUG) Main.Logger.Log("2x: " + i.ToString());
codes[i].opcode = OpCodes.Ldc_I4_1;
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_ActionGongFaDamage_Patch success");
return codes.AsEnumerable();
}
static void Prefix(BattleSystem __instance, ref int ___enemyChooseSkillAttackPart, bool isActor, ref int basePower, int attackOrder, int customAttackPart = -1)
{
if (Main.settings.gongfaImmunity && !isActor) {
basePower = 0;
}
if (Main.settings.bianzhaoEnhance && isActor) {
Main.attackPartChooseOriginal = __instance.attackPartChooseObbs;
__instance.attackPartChooseObbs = Main.attackPartChooseAlways;
}
if (Main.settings.bianzhaoProhibit && !isActor) {
___enemyChooseSkillAttackPart = -1;
}
}
static void Postfix(BattleSystem __instance, bool isActor, ref int basePower, int attackOrder, int customAttackPart = -1)
{
if (Main.settings.bianzhaoEnhance && isActor) {
__instance.attackPartChooseObbs = Main.attackPartChooseOriginal;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "ActionEventEndAttack")]
class BattleSystem_ActionEventEndAttack_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleSystem_ActionEventEndAttack_Patch start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c41) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 100) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
codes[i].opcode = OpCodes.Ldc_I4;
codes[i].operand = 0xc8;
break;
}
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleSystem_ActionEventEndAttack_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleVaule), "GetMagicSpeed")]
class BattleVaule_GetMagicSpeed_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetMagicSpeed_Patch start");
var codes = new List<CodeInstruction>(instructions);
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c43) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x3c) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
codes[i].operand = (sbyte)0x28;
break;
}
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetMagicSpeed_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleVaule), "GetMoveSpeed")]
class BattleVaule_GetMoveSpeed_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetMoveSpeed_Patch start");
var codes = new List<CodeInstruction>(instructions);
codes[78].opcode = OpCodes.Nop;
codes[79].opcode = OpCodes.Ldc_I4_1;
codes[80].opcode = OpCodes.Nop;
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c43) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x3c) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
codes[i].operand = (sbyte)0x28;
break;
}
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetMoveSpeed_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleVaule), "GetAttackSpeedPower")]
class BattleVaule_GetAttackSpeedPower_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetAttackSpeedPower_Patch start");
var codes = new List<CodeInstruction>(instructions);
codes[8].opcode = OpCodes.Nop;
codes[9].opcode = OpCodes.Ldc_I4_1;
codes[10].opcode = OpCodes.Nop;
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c43) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 0x3c) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
codes[i].operand = (sbyte)0x28;
break;
}
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetAttackSpeedPower_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleVaule), "GetDeferDefuse")]
class BattleVaule_GetDeferDefuse_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetDeferDefuse_Patch start");
var codes = new List<CodeInstruction>(instructions);
codes[150].opcode = OpCodes.Nop;
codes[151].opcode = OpCodes.Ldc_I4_1;
codes[152].opcode = OpCodes.Nop;
var i = 0;
for (; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4 && (int)codes[i].operand == 0x9c47) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
break;
}
}
for (i++; i < codes.Count; i++) {
if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 20) {
if (Main.DEBUG) Main.Logger.Log(i.ToString());
codes[i].operand = (sbyte)100;
break;
}
}
if (i >= codes.Count) {
return instructions;
}
if (Main.DEBUG) Main.Logger.Log("BattleVaule_GetDeferDefuse_Patch success");
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(BattleSystem), "SetPoisonDamage")]
class BattleSystem_SetPoisonDamage_Patch
{
static void Prefix(bool isActor, int actorId, int typ, ref int value, bool canUseEffect = true)
{
if (Main.settings.poisonImmunity && isActor) {
value = 0;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "AddBattleInjury")]
class BattleSystem_AddBattleInjury_Patch
{
static void Prefix(bool isActor, int actorId, int attackerId, int injuryId, ref int injuryPower, bool realDamage = false, bool sendEvent = true, bool directDamage = false)
{
if (Main.settings.injuryImmunity && isActor) {
injuryPower = 0;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "ActionEventAttack")]
class BattleSystem_ActionEventAttack_Patch
{
static void Prefix(BattleSystem __instance, ref int ___enemyChooseAttackPart, bool isActor)
{
if (Main.settings.bianzhaoEnhance && isActor) {
Main.attackPartChooseOriginal = __instance.attackPartChooseObbs;
__instance.attackPartChooseObbs = Main.attackPartChooseAlways;
}
if (Main.settings.bianzhaoProhibit && !isActor) {
___enemyChooseAttackPart = -1;
}
}
static void Postfix(BattleSystem __instance, bool isActor)
{
if (Main.settings.bianzhaoEnhance && isActor) {
__instance.attackPartChooseObbs = Main.attackPartChooseOriginal;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "GetActorGongFa")]
class BattleSystem_GetActorGongFa_Patch
{
static void Prefix(BattleSystem __instance)
{
if (Main.settings.randActor) {
Dictionary<int, int[]> dictionary = new Dictionary<int, int[]>(DateFile.instance.GetActorEquipGongFa(__instance.ActorId(true, false)));
for (int l = 0; l < 9; l++) {
if (dictionary[4][l] >= 170001 && dictionary[4][l] <= 170010) {
dictionary[4][l] = 0;
}
}
}
}
static void Postfix(Dictionary<int, int[]> ___actorOtherEffect)
{
int i = -1;
if (Main.settings.bossGongfa1_1) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20001, array);
}
if (Main.settings.bossGongfa1_2) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20002, array);
}
if (Main.settings.bossGongfa1_3) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20003, array);
}
if (Main.settings.bossGongfa1_4) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20004, array);
}
if (Main.settings.bossGongfa1_5) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20005, array);
}
if (Main.settings.bossGongfa1_6) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20006, array);
}
if (Main.settings.bossGongfa1_7) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20007, array);
}
if (Main.settings.bossGongfa1_8) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20008, array);
}
if (Main.settings.bossGongfa1_9) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(20009, array);
}
if (Main.settings.bossGongfa2_1) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40001, array);
}
if (Main.settings.bossGongfa2_2) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40002, array);
}
if (Main.settings.bossGongfa2_3) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40003, array);
}
if (Main.settings.bossGongfa2_4) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40004, array);
}
if (Main.settings.bossGongfa2_5) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40005, array);
}
if (Main.settings.bossGongfa2_6) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40006, array);
}
if (Main.settings.bossGongfa2_7) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40007, array);
}
if (Main.settings.bossGongfa2_8) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40008, array);
}
if (Main.settings.bossGongfa2_9) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40009, array);
}
if (Main.settings.bossGongfa2_10) {
int[] array = new int[2];
array[0] = --i;
___actorOtherEffect.Add(40010, array);
}
}
}
[HarmonyPatch(typeof(BattleSystem), "ActionEvent")]
class BattleSystem_ActionEvent_Patch
{
static void Prefix(ref int ___actorBol, ref int ___actorEve, ref int ___actorRel, ref int ___actorDir, int ___enemyBol, int ___enemyEve, int ___enemyRel, int ___enemyDir, string animationName, string eventName, bool isActor, bool other) {
if (Main.settings.alwaysHitGongfa && isActor) {
Main.actorBol = ___actorBol;
Main.actorEve = ___actorEve;
Main.actorRel = ___actorRel;
Main.actorDir = ___actorDir;
if (___actorBol <= ___enemyBol) {
___actorBol = ___enemyBol + 10;
}
if (___actorEve <= ___enemyEve) {
___actorEve = ___enemyEve + 10;
}
if (___actorRel <= ___enemyRel) {
___actorRel = ___enemyRel + 10;
}
if (___actorDir <= ___enemyDir) {
___actorDir = ___enemyDir + 10;
}
}
}
static void Postfix(ref int ___actorBol, ref int ___actorEve, ref int ___actorRel, ref int ___actorDir, int ___enemyBol, int ___enemyEve, int ___enemyRel, int ___enemyDir, string animationName, string eventName, bool isActor, bool other) {
if (Main.settings.alwaysHitGongfa && isActor) {
___actorBol = Main.actorBol;
___actorEve = Main.actorEve;
___actorRel = Main.actorRel;
___actorDir = Main.actorDir;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "ActionEventDefWindow")]
class BattleSystem_ActionEventDefWindow_Patch
{
static void Prefix(ref int ___actorBol, ref int ___actorEve, ref int ___actorRel, ref int ___actorDir, int ___enemyBol, int ___enemyEve, int ___enemyRel, int ___enemyDir, bool isActor, int attackOrder) {
if (Main.settings.alwaysHitGongfa && isActor) {
Main.actorBol = ___actorBol;
Main.actorEve = ___actorEve;
Main.actorRel = ___actorRel;
Main.actorDir = ___actorDir;
if (___actorBol <= ___enemyBol) {
___actorBol = ___enemyBol + 10;
}
if (___actorEve <= ___enemyEve) {
___actorEve = ___enemyEve + 10;
}
if (___actorRel <= ___enemyRel) {
___actorRel = ___enemyRel + 10;
}
if (___actorDir <= ___enemyDir) {
___actorDir = ___enemyDir + 10;
}
}
}
static void Postfix(ref int ___actorBol, ref int ___actorEve, ref int ___actorRel, ref int ___actorDir, int ___enemyBol, int ___enemyEve, int ___enemyRel, int ___enemyDir, bool isActor, int attackOrder) {
if (Main.settings.alwaysHitGongfa && isActor) {
___actorBol = Main.actorBol;
___actorEve = Main.actorEve;
___actorRel = Main.actorRel;
___actorDir = Main.actorDir;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "WorsenInjury")]
class BattleSystem_WorsenInjury_Patch
{
static bool Prefix(BattleSystem __instance, int actorId, int injuryId, int worsenPower, bool isPercent = true, bool getWin = true) {
if (Main.settings.worsenImmunity && actorId == __instance.ActorId(true, false)) {
return false;
}
return true;
}
}
[HarmonyPatch(typeof(BattleSystem), "ChangeActorSp")]
class BattleSystem_ChangeActorSp_Patch
{
static void Prefix(bool isActor, int index, ref int value) {
if (Main.settings.spFix && isActor && value < 0) {
value = 0;
}
}
}
[HarmonyPatch(typeof(BattleSystem), "SetUseGongFa")]
class BattleSystem_SetUseGongFa_Patch
{
static void Postfix(ref int ___actorNeedUseGongFa, bool isActor, int gongFaId) {
if (Main.settings.noPrepareGongfa && isActor) {
if (___actorNeedUseGongFa != 0) {
BattleSystem.UseCombatSkillImmediately(true, ___actorNeedUseGongFa, true, true);
___actorNeedUseGongFa = 0;
}
}
}
}
[HarmonyPatch(typeof(DateFile), "IsUserGangGongFa")]
class DateFile_IsUserGangGongFa_Patch
{
static bool Prefix() {
if (Main.settings.removeGangLimit) {
return false;
}
return true;
}
}
[HarmonyPatch(typeof(BattleSystem), "BattlerIsDead")]
class BattleSystem_BattlerIsDead_Patch
{
static bool Prefix(ref bool __result, bool isActor, int index) {
if (Main.settings.noDeath && isActor) {
__result = false;
return false;
}
return true;
}
}
[HarmonyPatch(typeof(v2.SpecialEffects.AttackSkills.KongSangPai.Throw.GuiGuXueHaiTang), "AddBegoniaCount")]
class GuiGuXueHaiTang_AddBegoniaCount_Patch
{
static bool Prefix(int actorId, bool isAlly) {
if (Main.settings.noDeath && isAlly && v2.SpecialEffects.AttackSkills.KongSangPai.Throw.GuiGuXueHaiTang.actorBegoniaCount.ContainsKey(actorId) &&
v2.SpecialEffects.AttackSkills.KongSangPai.Throw.GuiGuXueHaiTang.actorBegoniaCount[actorId] >= 4) {
return false;
}
return true;
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(BattleSystem), "GetActor")]
class BattleSystem_GetActor_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[357].opcode = OpCodes.Ldc_I4;
codes[357].operand = -1;
codes[358].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
static void Postfix(BattleSystem __instance, Dictionary<int, int> ___actorDoRageSize) {
int id = __instance.ActorId(true, false);
int num1 = (int.Parse(DateFile.instance.GetActorDate(id, 23, true)) <= 0) ? 0 : Mathf.Clamp(DateFile.instance.GetActorValue(id, 509, true) / 100, 1, 3);
int num2 = (int.Parse(DateFile.instance.GetActorDate(id, 1110, true)) <= 0) ? 0 : Mathf.Clamp(DateFile.instance.GetActorValue(id, 510, true) / 100, 1, 3);
int num3 = 1;
if (DateFile.instance.enemyBorn <= 1) {
num1 = Mathf.Min(num1, DateFile.instance.enemyBorn);
num2 = Mathf.Min(num2, DateFile.instance.enemyBorn);
num3 = Mathf.Min(num3, DateFile.instance.enemyBorn);
}
__instance.actorDoHealSize[id] = num1;
__instance.actorDoRemovePoisonSize[id] = num2;
___actorDoRageSize[id] = num3;
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(StartBattle), "UpdateActorHSQP")]
class StartBattle_UpdateActorHSQP_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[194].opcode = OpCodes.Ldc_I4;
codes[194].operand = -1;
codes[195].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(StartBattle), "UpdateBattlePlan")]
class StartBattle_UpdateBattlePlan_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[18].opcode = OpCodes.Ldc_I4;
codes[18].operand = -1;
codes[19].opcode = OpCodes.Ceq;
codes[64].opcode = OpCodes.Ldc_I4;
codes[64].operand = -1;
codes[65].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(StartBattle), "UpdateBattler")]
class StartBattle_UpdateBattler_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[318].opcode = OpCodes.Ldc_I4;
codes[318].operand = -1;
codes[319].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(StartBattle), "UpdateBattlerFace")]
class StartBattle_UpdateBattlerFace_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[11].opcode = OpCodes.Ldc_I4;
codes[11].operand = -1;
codes[12].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(ActorMenu), "ShowActorMenu")]
class ActorMenu_ShowActorMenu_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[162].opcode = OpCodes.Ldc_I4;
codes[162].operand = -1;
codes[163].opcode = OpCodes.Ceq;
codes[166].opcode = OpCodes.Brtrue_S;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(BattleSystem), "GetActionStar")]
class BattleSystem_GetActionStar_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[20].opcode = OpCodes.Ldc_I4;
codes[20].operand = -1;
codes[21].opcode = OpCodes.Beq_S;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(BattleSystem), "SetActorDate")]
class BattleSystem_SetActorDate_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[12].opcode = OpCodes.Ldc_I4;
codes[12].operand = -1;
codes[13].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(BattleSystem), "SetActorTeamAction")]
class BattleSystem_SetActorTeamAction_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[15].opcode = OpCodes.Ldc_I4;
codes[15].operand = -1;
codes[16].opcode = OpCodes.Beq_S;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(DateFile), "GetTeamResources")]
class DateFile_GetTeamResources_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[25].opcode = OpCodes.Ldc_I4;
codes[25].operand = -1;
codes[26].opcode = OpCodes.Ceq;
return codes.AsEnumerable();
}
}
/* For BVB test only. */
[HarmonyPatch(typeof(BattleEndWindow), "BattleEnd")]
class BattleEndWindow_BattleEnd_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[148].opcode = OpCodes.Ldc_I4;
codes[148].operand = -1;
codes[149].opcode = OpCodes.Ceq;
codes[152].opcode = OpCodes.Brtrue;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleVaule), "GetAttackPoison")]
class BattleVaule_GetAttackPoison_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[82].opcode = OpCodes.Nop;
codes[83].opcode = OpCodes.Ldc_I4_1;
codes[84].opcode = OpCodes.Nop;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleVaule), "SetGongFaValue")]
class BattleVaule_SetGongFaValue_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[467].opcode = OpCodes.Nop;
codes[468].opcode = OpCodes.Ldc_I4_1;
codes[469].opcode = OpCodes.Nop;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleVaule), "GetWeaponHit")]
class BattleVaule_GetWeaponHit_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[252].opcode = OpCodes.Nop;
codes[253].opcode = OpCodes.Ldc_I4_1;
codes[254].opcode = OpCodes.Nop;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleVaule), "GetWeaponDestroy")]
class BattleVaule_GetWeaponDestroy_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[143].opcode = OpCodes.Nop;
codes[144].opcode = OpCodes.Ldc_I4_1;
codes[145].opcode = OpCodes.Nop;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleSystem), "UpdateEnemyAI")]
class BattleSystem_UpdateEnemyAI_Patch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var codes = new List<CodeInstruction>(instructions);
codes[2290].opcode = OpCodes.Ldc_I4_1;
codes[2476].opcode = OpCodes.Ldc_I4_1;
return codes.AsEnumerable();
}
}
/* For BVB only. */
[HarmonyPatch(typeof(StartBattle), "UpdateStartBattle")]
class StartBattle_UpdateStartBattle_Patch
{
private static int[] original = {-1, -1, -1, -1, -1};
private static int num10 = 0;
private static int enemyTeamId = 0;
private static void addMember(string member, int index)
{
int m = -1;
if (!string.IsNullOrEmpty(member) && int.TryParse(member, out m)) {
if (int.Parse(DateFile.instance.GetActorDate(m, 6, false)) == 2) {
DateFile.instance.acotrTeamDate[index] = DateFile.instance.MakeXXEnemy(m, num10, int.Parse(DateFile.instance.enemyTeamDate[enemyTeamId][15]) == 0);
} else {
if (DateFile.instance.presetActorDate.ContainsKey(m)) {
if (DateFile.instance.enemyRandDate.ContainsKey(int.Parse(DateFile.instance.presetActorDate[m][8]))) {
DateFile.instance.acotrTeamDate[index] = DateFile.instance.MakeRandEnemy(m, -16 - index);
} else {
DateFile.instance.acotrTeamDate[index] = DateFile.instance.MakeNewActor(m, int.Parse(DateFile.instance.presetActorDate[m][7]) == 1, -16 - index, -1, -1, null, null, null, null, 20);
}
}
}
}
}
static void Prefix(StartBattle __instance)
{
if (Main.settings.randTeam || Main.settings.randActor) {
DateFile.instance.RemoveActor(new List<int> {-16, -17, -18, -19, -20}, true, false);
enemyTeamId = __instance.enemyTeamId;
num10 = int.Parse(DateFile.instance.enemyTeamDate[enemyTeamId][7]);
num10 = ((num10 != 0) ? (num10 - 1) : 0);
}
if (Main.settings.randTeam) {
for (var i = 1; i <= 4; i++) {
original[i] = DateFile.instance.acotrTeamDate[i];
}
string member1 = Main.settings.randTeamMember1?.Trim();
string member2 = Main.settings.randTeamMember2?.Trim();
string member3 = Main.settings.randTeamMember3?.Trim();
string member4 = Main.settings.randTeamMember4?.Trim();
addMember(member1, 1);
addMember(member2, 2);
addMember(member3, 3);
addMember(member4, 4);
}
if (Main.settings.randActor) {
original[0] = DateFile.instance.acotrTeamDate[0];
string member0 = Main.settings.randTeamMember0?.Trim();
addMember(member0, 0);
}
}
static void Postfix(StartBattle __instance)
{
if (Main.settings.randTeam) {
int num = 30000 * int.Parse(DateFile.instance.enemyTeamDate[__instance.enemyTeamId][9]) / 100;
for (var i = 1; i <= 4; i++) {
int id = DateFile.instance.acotrTeamDate[i];
if (id != original[i]) {
DateFile.instance.enemyFavor.Add(id, num + num * UnityEngine.Random.Range(-20, 21) / 100);
}
}
for (var i = 1; i <= 4; i++) {
DateFile.instance.acotrTeamDate[i] = original[i];
}
}
if (Main.settings.randActor) {
DateFile.instance.acotrTeamDate[0] = original[0];
}
}
}
/* For BVB only. */
[HarmonyPatch(typeof(DateFile), "ResetBattleDate")]
class DateFile_ResetBattleDate_Patch
{
static void Postfix()
{
if (Main.settings.randTeam || Main.settings.randActor) {
DateFile.instance.RemoveActor(new List<int> {-16, -17, -18, -19, -20}, true, false);
}
}
}
/* For BVB only. */
[HarmonyPatch(typeof(BattleVaule), "GetActionCdSpeed")]
class BattleVaule_GetActionCdSpeed_Patch
{
static bool Prefix(ref int __result, bool isActor, int key)
{
if (Main.settings.randTeam) {
int actorId = BattleSystem.instance.ActorId(true, false);
int num = isActor ? (DateFile.instance.GetActorFavor(actorId != key, actorId, key, false, false) / 1000)
: (DateFile.instance.GetActorFavor(true, BattleSystem.instance.ActorId(false, false), key, false, false) / 1000);
__result = Mathf.Max(1, num);
return false;
}
return true;
}
}
/* For BVB only. */
[HarmonyPatch(typeof(DateFile), "GetWorldXXLevel")]
class DateFile_GetWorldXXLevel_Patch
{
static bool Prefix(ref int __result, bool getBaseLevel)
{
if (Main.settings.modXXLevel) {
int.TryParse(Main.settings.xxLevel, out __result);
Mathf.Clamp(__result, 0, 9);
if (getBaseLevel) {
__result *= 4;
}
return false;
}
return true;
}
}
}
|
||||
TheStack | bd8442693b3436473023dca9812659f71367cb5d | C#code:C# | {"size": 1041, "ext": "cs", "max_stars_repo_path": "src/GovUk.Education.ExploreEducationStatistics.Publisher/Utils/EnvironmentUtils.cs", "max_stars_repo_name": "dfe-analytical-services/explore-education-statistics", "max_stars_repo_stars_event_min_datetime": "2018-12-17T13:19:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:40:54.000Z", "max_issues_repo_path": "src/GovUk.Education.ExploreEducationStatistics.Publisher/Utils/EnvironmentUtils.cs", "max_issues_repo_name": "dfe-analytical-services/explore-education-statistics", "max_issues_repo_issues_event_min_datetime": "2019-01-22T11:56:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:26:07.000Z", "max_forks_repo_path": "src/GovUk.Education.ExploreEducationStatistics.Publisher/Utils/EnvironmentUtils.cs", "max_forks_repo_name": "dfe-analytical-services/explore-education-statistics", "max_forks_repo_forks_event_min_datetime": "2019-01-31T15:57:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T11:19:48.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 268.0, "max_forks_count": 6.0, "avg_line_length": 40.0384615385, "max_line_length": 119, "alphanum_fraction": 0.6762728146} | #nullable enable
using System;
using Microsoft.Extensions.Hosting;
namespace GovUk.Education.ExploreEducationStatistics.Publisher.Utils
{
public static class EnvironmentUtils
{
/// <summary>
/// Use the presence of 'Development' as the environment value to detect if the function is running on a local
/// computer.
/// </summary>
/// <remarks>
/// Azure Functions Core Tools sets AZURE_FUNCTIONS_ENVIRONMENT as 'Development' when running on a local
/// computer and this can't overriden in local.settings.json file. In all Azure environments the environment is
/// 'Production' unless altered.
/// </remarks>
/// <returns>True if the function is running on a local computer otherwise false</returns>
public static bool IsLocalEnvironment()
{
var environment = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT");
return environment?.Equals(EnvironmentName.Development) ?? false;
}
}
}
|
||||
TheStack | dbddd37eeb650aa3382a75fe2de671cdda62442c | C#code:C# | {"size": 5190, "ext": "cs", "max_stars_repo_path": "SRPUtilities/DataValidation.cs", "max_stars_repo_name": "iafb/greatreadingadventure", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SRPUtilities/DataValidation.cs", "max_issues_repo_name": "iafb/greatreadingadventure", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SRPUtilities/DataValidation.cs", "max_forks_repo_name": "iafb/greatreadingadventure", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5294117647, "max_line_length": 115, "alphanum_fraction": 0.4747591522} | using System;
using System.Text;
using System.Text.RegularExpressions;
namespace GRA.SRP.Core.Utilities
{
public class DataValidation
{
public const string VALID_EMAIL_EXPRESSION = @"^[A-Za-z0-9_\-\.]+@(([A-Za-z0-9\-])+\.)+([A-Za-z\-])+$";
public const string VALID_GUID_EXPRESSION =
@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$";
public const string VALID_ZIPCODE_EXPRESSION = @"^\d{5}(-\d{4})?$";
private static Regex _isEmailRegEx;
private static Regex _isGuidRegEx;
private static Regex _isZipCodeRegEx;
public static Regex IsGuidRegEx
{
get
{
if (_isGuidRegEx == null)
_isGuidRegEx = new Regex(VALID_GUID_EXPRESSION, RegexOptions.Compiled);
return _isGuidRegEx;
}
}
public static Regex IsZipCodeRegEx
{
get
{
if (_isZipCodeRegEx == null)
_isZipCodeRegEx = new Regex(VALID_ZIPCODE_EXPRESSION, RegexOptions.Compiled);
return _isZipCodeRegEx;
}
}
public static Regex IsEmailRegEx
{
get
{
if (_isEmailRegEx == null)
_isEmailRegEx = new Regex(VALID_EMAIL_EXPRESSION, RegexOptions.Compiled);
return _isEmailRegEx;
}
}
public static bool IsValidDateTimeOrBlank(string value)
{
if (string.IsNullOrEmpty(value))
return true;
value = value.Trim();
if (value.Length == 0)
return true;
return IsValidDateTime(value);
}
public static bool IsValidDateTime(string value)
{
DateTime testdate;
return DateTime.TryParse(value, out testdate);
}
public static bool IsValidGuid(string value)
{
return value != null
?
IsGuidRegEx.IsMatch(value)
:
false;
}
public static bool IsValidGuid(string candidate, out Guid output)
{
bool isValid = false;
output = Guid.Empty;
if (candidate != null)
{
if (IsGuidRegEx.IsMatch(candidate))
{
output = new Guid(candidate);
isValid = true;
}
}
return isValid;
}
public static bool IsValidUSZipcode(string value)
{
return IsZipCodeRegEx.IsMatch(value);
}
public static bool IsValidEmailAddress(string value)
{
return IsEmailRegEx.IsMatch(value);
}
public static bool IsValidUnsignedInt(string value, int length)
{
if (
value.StartsWith("-") ||
value.StartsWith("+") ||
value.Length != length)
return false;
int i;
return int.TryParse(value, out i);
}
/// <summary>
/// Determines whether the string value represents a valid it of the specified length
/// </summary>
/// <param name="value">The value.</param>
/// <param name="length">The length.</param>
/// <returns>
/// <c>true</c> if the string passed int/lenth test; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidInt(string value, int length)
{
if (value.Length != length)
return false;
int i;
return int.TryParse(value, out i);
}
public static bool IsValidInt(string value)
{
int i;
return int.TryParse(value, out i);
}
public static bool FixUsPhone(ref string phone)
{
string[] parts = phone.Split(new[] { '(', '-', '/', ')', ' ' },
StringSplitOptions.RemoveEmptyEntries);
var phoneBuffer = new StringBuilder();
int partCount = 0;
foreach (string part in parts)
{
if (part != "1")
{
++partCount;
if (phoneBuffer.ToString().Length > 0)
phoneBuffer.Append('-');
phoneBuffer.Append(part);
}
}
if (
// First part must be 3 digit numaric
phoneBuffer.ToString().IndexOf('-') == 3 &&
IsValidUnsignedInt(phoneBuffer.ToString().Substring(0, 3), 3) &&
// no more than three sections
partCount < 4 &&
// only the two sizes
(phoneBuffer.ToString().Length == 8 ||
phoneBuffer.ToString().Length == 12)
)
{
phone = phoneBuffer.ToString();
return true;
}
return false;
}
}
} |
||||
TheStack | dbe2b19f105564fa2822a773bfda12f4ff79a5b7 | C#code:C# | {"size": 14712, "ext": "cs", "max_stars_repo_path": "Artemis_XNA_INDEPENDENT/System/EntityComponentProcessingSystem.cs", "max_stars_repo_name": "Maximusya/artemis_CSharp", "max_stars_repo_stars_event_min_datetime": "2015-01-17T23:49:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T18:11:39.000Z", "max_issues_repo_path": "Artemis_XNA_INDEPENDENT/System/EntityComponentProcessingSystem.cs", "max_issues_repo_name": "Maximusya/artemis_CSharp", "max_issues_repo_issues_event_min_datetime": "2015-02-16T22:12:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-14T18:14:50.000Z", "max_forks_repo_path": "Artemis_XNA_INDEPENDENT/System/EntityComponentProcessingSystem.cs", "max_forks_repo_name": "Maximusya/artemis_CSharp", "max_forks_repo_forks_event_min_datetime": "2015-01-22T17:11:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T20:11:17.000Z"} | {"max_stars_count": 250.0, "max_issues_count": 24.0, "max_forks_count": 62.0, "avg_line_length": 55.7272727273, "max_line_length": 430, "alphanum_fraction": 0.6635399674} | #region File description
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntityComponentProcessingSystem.cs" company="GAMADU.COM">
// Copyright © 2013 GAMADU.COM. All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// THIS SOFTWARE IS PROVIDED BY GAMADU.COM '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 GAMADU.COM 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.
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of GAMADU.COM.
// </copyright>
// <summary>
// System which processes entities calling Process(Entity entity, T component) every update.
// Automatically extracts the components specified by the type parameters.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion File description
namespace Artemis.System
{
#region Using statements
using global::System.Collections.Generic;
using Artemis.Interface;
#endregion
// TODO: GrafSeismo: To be honest, this class is the worst design i have ever seen and should be removed or replaced by anything that do not limit generics by its count of arguments. Also to replace a useful class (EntityProcessingSystem) by this is also a very bad idea in a framework, you may first set an "Obsolete" attribute to get rid of old classes/interfaces. In my game i use the original version near by for any case.
/// <summary>System which processes entities calling Process(Entity entity, T component) every update.
/// Automatically extracts the components specified by the type parameters.</summary>
/// <typeparam name="T">The component.</typeparam>
public abstract class EntityComponentProcessingSystem<T> : EntitySystem
where T : IComponent
{
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T}"/> class with an aspect which processes entities which have all the specified component types.</summary>
protected EntityComponentProcessingSystem()
: this(Aspect.Empty())
{
}
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T}"/> class with an aspect which processes entities which have all the specified component types as well as the any additional constraints specified by the aspect.</summary>
/// <param name="aspect">The aspect specifying the additional constraints.</param>
protected EntityComponentProcessingSystem(Aspect aspect)
: base(aspect.GetAll(typeof(T)))
{
}
/// <summary>Called for every entity in this system with the components automatically passed as arguments.</summary>
/// <param name="entity">The entity that is processed </param>
/// <param name="component1">The component.</param>
public abstract void Process(Entity entity, T component1);
/// <summary>Processes the entities.</summary>
/// <param name="entities">The entities.</param>
protected override void ProcessEntities(IDictionary<int, Entity> entities)
{
foreach (Entity entity in entities.Values)
{
this.Process(entity, entity.GetComponent<T>());
}
}
}
/// <summary>System which processes entities calling Process(Entity entity, T1 component1, T2 component2) every update.
/// Automatically extracts the components specified by the type parameters.</summary>
/// <typeparam name="T1">The first component.</typeparam>
/// <typeparam name="T2">The second component.</typeparam>
public abstract class EntityComponentProcessingSystem<T1, T2> : EntitySystem
where T1 : IComponent
where T2 : IComponent
{
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2}"/> class
/// with an aspect which processes entities which have all the specified component types.</summary>
protected EntityComponentProcessingSystem()
: this(Aspect.Empty())
{
}
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2}"/> class
/// with an aspect which processes entities which have all the specified component types as well as
/// the any additional constraints specified by the aspect.</summary>
/// <param name="aspect"> The aspect specifying the additional constraints. </param>
protected EntityComponentProcessingSystem(Aspect aspect)
: base(aspect.GetAll(typeof(T1), typeof(T2)))
{
}
/// <summary>Called every for every entity in this system with the components automatically passed as arguments.</summary>
/// <param name="entity">The entity that is processed </param>
/// <param name="component1">The first component.</param>
/// <param name="component2">The second component.</param>
public abstract void Process(Entity entity, T1 component1, T2 component2);
/// <summary>Processes the entities.</summary>
/// <param name="entities">The entities.</param>
protected override void ProcessEntities(IDictionary<int, Entity> entities)
{
foreach (Entity entity in entities.Values)
{
this.Process(entity, entity.GetComponent<T1>(), entity.GetComponent<T2>());
}
}
}
/// <summary>
/// System which processes entities calling Process(Entity entity, T1 component1, T2 component2, T3 component3) every update.
/// Automatically extracts the components specified by the type parameters.
/// </summary>
/// <typeparam name="T1">The first component.</typeparam>
/// <typeparam name="T2">The second component.</typeparam>
/// <typeparam name="T3">The third component.</typeparam>
public abstract class EntityComponentProcessingSystem<T1, T2, T3> : EntitySystem
where T1 : IComponent
where T2 : IComponent
where T3 : IComponent
{
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3}"/> class
/// with an aspect which processes entities which have all the specified component types.</summary>
protected EntityComponentProcessingSystem()
: this(Aspect.Empty())
{
}
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3}"/> class
/// with an aspect which processes entities which have all the specified component types
/// as well as the any additional constraints specified by the aspect.</summary>
/// <param name="aspect">The aspect specifying the additional constraints.</param>
protected EntityComponentProcessingSystem(Aspect aspect)
: base(aspect.GetAll(typeof(T1), typeof(T2), typeof(T3)))
{
}
/// <summary>Called for every entity in this system with the components automatically passed as arguments.</summary>
/// <param name="entity">The entity that is processed</param>
/// <param name="component1">The first component.</param>
/// <param name="component2">The second component.</param>
/// <param name="component3">The third component.</param>
public abstract void Process(Entity entity, T1 component1, T2 component2, T3 component3);
/// <summary>Processes the entities.</summary>
/// <param name="entities">The entities.</param>
protected override void ProcessEntities(IDictionary<int, Entity> entities)
{
foreach (Entity entity in entities.Values)
{
this.Process(entity, entity.GetComponent<T1>(), entity.GetComponent<T2>(), entity.GetComponent<T3>());
}
}
}
/// <summary>System which processes entities calling Process(Entity entity, T1 t1, T2 t2, T3 t3, T4 t4) every update.
/// Automatically extracts the components specified by the type parameters.</summary>
/// <typeparam name="T1">The first component.</typeparam>
/// <typeparam name="T2">The second component.</typeparam>
/// <typeparam name="T3">The third component.</typeparam>
/// <typeparam name="T4">The fourth component.</typeparam>
public abstract class EntityComponentProcessingSystem<T1, T2, T3, T4> : EntitySystem
where T1 : IComponent
where T2 : IComponent
where T3 : IComponent
where T4 : IComponent
{
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3, T4}"/> class
/// with an aspect which processes entities which have all the specified component types.</summary>
protected EntityComponentProcessingSystem()
: this(Aspect.Empty())
{
}
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3, T4}"/> class
/// with an aspect which processes entities which have all the specified component types
/// as well as the any additional constraints specified by the aspect.</summary>
/// <param name="aspect">The aspect specifying the additional constraints.</param>
protected EntityComponentProcessingSystem(Aspect aspect)
: base(aspect.GetAll(typeof(T1), typeof(T2), typeof(T3), typeof(T4)))
{
}
/// <summary>Called every for every entity in this system with the components automatically passed as arguments.</summary>
/// <param name="entity">The entity that is processed</param>
/// <param name="component1">The first component.</param>
/// <param name="component2">The second component.</param>
/// <param name="component3">The third component.</param>
/// <param name="component4">The fourth component.</param>
public abstract void Process(Entity entity, T1 component1, T2 component2, T3 component3, T4 component4);
/// <summary>Processes the entities.</summary>
/// <param name="entities">The entities.</param>
protected override void ProcessEntities(IDictionary<int, Entity> entities)
{
foreach (Entity entity in entities.Values)
{
this.Process(entity, entity.GetComponent<T1>(), entity.GetComponent<T2>(), entity.GetComponent<T3>(), entity.GetComponent<T4>());
}
}
}
/// <summary>System which processes entities calling Process(Entity entity, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) every update.
/// Automatically extracts the components specified by the type parameters.</summary>
/// <typeparam name="T1">The first component.</typeparam>
/// <typeparam name="T2">The second component.</typeparam>
/// <typeparam name="T3">The third component.</typeparam>
/// <typeparam name="T4">The fourth component.</typeparam>
/// <typeparam name="T5">The fifth component.</typeparam>
public abstract class EntityComponentProcessingSystem<T1, T2, T3, T4, T5> : EntitySystem
where T1 : IComponent
where T2 : IComponent
where T3 : IComponent
where T4 : IComponent
where T5 : IComponent
{
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3, T4, T5}"/> class
/// with an aspect which processes entities which have all the specified component types.</summary>
protected EntityComponentProcessingSystem()
: this(Aspect.Empty())
{
}
/// <summary>Initializes a new instance of the <see cref="EntityComponentProcessingSystem{T1, T2, T3, T4, T5}"/> class
/// with an aspect which processes entities which have all the specified component types
/// as well as the any additional constraints specified by the aspect.</summary>
/// <param name="aspect">The aspect specifying the additional constraints.</param>
protected EntityComponentProcessingSystem(Aspect aspect)
: base(aspect.GetAll(typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5)))
{
}
/// <summary>Called every for every entity in this system with the components automatically passed as arguments.</summary>
/// <param name="entity">The entity that is processed</param>
/// <param name="component1">The first component.</param>
/// <param name="component2">The second component.</param>
/// <param name="component3">The third component.</param>
/// <param name="component4">The fourth component.</param>
/// <param name="component5">The fifth component.</param>
public abstract void Process(Entity entity, T1 component1, T2 component2, T3 component3, T4 component4, T5 component5);
/// <summary>Processes the entities.</summary>
/// <param name="entities">The entities.</param>
protected override void ProcessEntities(IDictionary<int, Entity> entities)
{
foreach (Entity entity in entities.Values)
{
this.Process(entity, entity.GetComponent<T1>(), entity.GetComponent<T2>(), entity.GetComponent<T3>(), entity.GetComponent<T4>(), entity.GetComponent<T5>());
}
}
}
}
|
||||
TheStack | dbe2daebc7b69f0ddc33271ee77df190fb4e8080 | C#code:C# | {"size": 38302, "ext": "cs", "max_stars_repo_path": "src/AssemblyDefender/Obfuscation/ControlFlow/ControlFlowGenerator.cs", "max_stars_repo_name": "nickyandreev/AssemblyDefender", "max_stars_repo_stars_event_min_datetime": "2019-07-09T11:55:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T23:23:45.000Z", "max_issues_repo_path": "src/AssemblyDefender/Obfuscation/ControlFlow/ControlFlowGenerator.cs", "max_issues_repo_name": "nickyandreev/AssemblyDefender", "max_issues_repo_issues_event_min_datetime": "2020-09-14T19:09:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T19:09:52.000Z", "max_forks_repo_path": "src/AssemblyDefender/Obfuscation/ControlFlow/ControlFlowGenerator.cs", "max_forks_repo_name": "nickyandreev/AssemblyDefender", "max_forks_repo_forks_event_min_datetime": "2019-08-04T05:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T18:58:18.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 1.0, "max_forks_count": 5.0, "avg_line_length": 44.1267281106, "max_line_length": 88, "alphanum_fraction": 0.7283170592} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AssemblyDefender.Net;
namespace AssemblyDefender
{
/// <summary>
/// internal static int ControlFlow1;
/// internal static int ControlFlow2;
/// internal static int ControlFlow3;
/// internal static int ControlFlow4;
/// internal static int ControlFlow5;
/// internal static int ControlFlow6;
/// internal static int ControlFlow7;
/// internal static int ControlFlow8;
/// internal static void InitializeControlFlow();
/// </summary>
internal class ControlFlowGenerator
{
#region Fields
private MainType _mainType;
private BuildModule _module;
#endregion
#region Ctors
internal ControlFlowGenerator(BuildModule module)
{
_module = module;
_mainType = module.MainType;
}
#endregion
#region Methods
internal void Generate()
{
GenerateFields();
GenerateCctor();
GenerateInitialize();
}
private void GenerateFields()
{
var fields = _mainType.Fields;
// ControlFlow5 : [mscorlib]System.Int32
var field = fields.Add();
field.Name = "ControlFlow5";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow3 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow3";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow1 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow1";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow8 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow8";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow6 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow6";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow2 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow2";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow4 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow4";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
// ControlFlow7 : [mscorlib]System.Int32
field = fields.Add();
field.Name = "ControlFlow7";
field.Visibility = FieldVisibilityFlags.Assembly;
field.IsStatic = true;
field.FieldType =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly);
}
private void GenerateCctor()
{
var instructions = new List<Instruction>(20);
instructions.Add(new Instruction(OpCodes.Ldc_I4_1));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_2));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_3));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_4));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_5));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_6));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_7));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldc_I4_8));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Call,
new MethodReference(
"InitializeControlFlow",
new TypeReference(_mainType.Name, _mainType.Namespace, false),
new CallSite(
false,
false,
MethodCallingConvention.Default,
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Void, _module.Assembly),
new TypeSignature[0],
-1,
0))));
var cctorMethod = _mainType.Methods.GetOrCreateStaticConstructor();
var methodBody = MethodBody.Load(cctorMethod);
methodBody.Instructions.InsertRange(methodBody.Instructions.Count - 1, instructions);
methodBody.Build(cctorMethod);
}
/// <summary>
/// static InitializeControlFlow() : [mscorlib]System.Void
/// </summary>
private void GenerateInitialize()
{
var method = _mainType.Methods.Add();
method.Name = "InitializeControlFlow";
method.Visibility = MethodVisibilityFlags.Assembly;
method.IsStatic = true;
method.IsHideBySig = true;
// Return type
{
var returnType = method.ReturnType;
returnType.Type =
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Void, _module.Assembly);
}
// Body
{
var methodBody = new MethodBody();
methodBody.MaxStackSize = 2;
methodBody.InitLocals = false;
// Instructions
{
var instructions = methodBody.Instructions;
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)42));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)152));
instructions.Add(new Instruction(OpCodes.Br, (int)185));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)148));
instructions.Add(new Instruction(OpCodes.Br_S, (sbyte)-115));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Bgt_S, (sbyte)39));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)120));
instructions.Add(new Instruction(OpCodes.Br, (int)-154));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)-73));
instructions.Add(new Instruction(OpCodes.Ret));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)-145));
instructions.Add(new Instruction(OpCodes.Ret));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)-222));
instructions.Add(new Instruction(OpCodes.Br, (int)-269));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)42));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)152));
instructions.Add(new Instruction(OpCodes.Br, (int)185));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)148));
instructions.Add(new Instruction(OpCodes.Br_S, (sbyte)-115));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Bgt_S, (sbyte)39));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)120));
instructions.Add(new Instruction(OpCodes.Br, (int)-154));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow5",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow2",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble_S, (sbyte)-73));
instructions.Add(new Instruction(OpCodes.Ret));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow7",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Sub));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow3",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)-145));
instructions.Add(new Instruction(OpCodes.Ret));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow4",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Stsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow8",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow6",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Add));
instructions.Add(new Instruction(OpCodes.Ldsfld,
new FieldReference(
"ControlFlow1",
TypeReference.GetPrimitiveType(PrimitiveTypeCode.Int32, _module.Assembly),
new TypeReference(_mainType.Name, _mainType.Namespace, false))));
instructions.Add(new Instruction(OpCodes.Ble, (int)-222));
instructions.Add(new Instruction(OpCodes.Br, (int)-269));
instructions.Add(new Instruction(OpCodes.Ret));
}
methodBody.Build(method);
}
}
#endregion
#region Static
public static void Generate(BuildModule module)
{
var generator = new ControlFlowGenerator(module);
generator.Generate();
}
#endregion
#region C# Code
/***************************************************************************
internal static int ControlFlow5 = 1;
internal static int ControlFlow3 = 2;
internal static int ControlFlow1 = 3;
internal static int ControlFlow8 = 4;
internal static int ControlFlow6 = 5;
internal static int ControlFlow2 = 6;
internal static int ControlFlow4 = 7;
internal static int ControlFlow7 = 8;
internal static void InitializeControlFlow()
{
L1:
ControlFlow4 = ControlFlow7 - ControlFlow5;
if (ControlFlow4 - ControlFlow8 > ControlFlow2) goto L2; else goto L3;
L2:
ControlFlow6 = ControlFlow8 - ControlFlow7;
if (ControlFlow6 - ControlFlow3 > ControlFlow8) goto L8; else goto L7;
L3:
ControlFlow7 = ControlFlow6 - ControlFlow1;
if (ControlFlow7 - ControlFlow4 > ControlFlow6) goto L1; else goto L8;
L4:
ControlFlow3 = ControlFlow7 + ControlFlow2;
if (ControlFlow3 - ControlFlow2 > ControlFlow5) goto L6; else goto L5;
L5:
ControlFlow2 = ControlFlow6 + ControlFlow2;
if (ControlFlow2 - ControlFlow8 > ControlFlow3) goto L2; else goto L11;
L6:
ControlFlow5 = ControlFlow4 - ControlFlow7;
if (ControlFlow5 - ControlFlow8 > ControlFlow2) goto END; else goto L5;
L7:
ControlFlow1 = ControlFlow5 + ControlFlow1;
if (ControlFlow1 - ControlFlow6 > ControlFlow3) goto END; else goto L4;
L8:
ControlFlow8 = ControlFlow4 + ControlFlow2;
if (ControlFlow8 - ControlFlow6 > ControlFlow1) goto L2; else goto L3;
L11:
ControlFlow4 = ControlFlow3 - ControlFlow1;
if (ControlFlow4 - ControlFlow8 > ControlFlow2) goto L12; else goto L13;
L12:
ControlFlow6 = ControlFlow6 - ControlFlow5;
if (ControlFlow6 - ControlFlow3 > ControlFlow8) goto L18; else goto L17;
L13:
ControlFlow7 = ControlFlow7 + ControlFlow5;
if (ControlFlow7 - ControlFlow4 > ControlFlow6) goto L11; else goto L18;
L14:
ControlFlow3 = ControlFlow4 - ControlFlow1;
if (ControlFlow3 + ControlFlow2 > ControlFlow1) goto L16; else goto L15;
L15:
ControlFlow2 = ControlFlow6 - ControlFlow4;
if (ControlFlow2 - ControlFlow8 > ControlFlow3) goto L12; else goto END;
L16:
ControlFlow5 = ControlFlow4 + ControlFlow1;
if (ControlFlow5 + ControlFlow1 > ControlFlow2) goto END; else goto L15;
L17:
ControlFlow1 = ControlFlow3 - ControlFlow7;
if (ControlFlow1 - ControlFlow6 > ControlFlow3) goto END; else goto L14;
L18:
ControlFlow8 = ControlFlow1 + ControlFlow4;
if (ControlFlow8 + ControlFlow6 > ControlFlow1) goto L12; else goto L13;
END:
return;
}
***************************************************************************/
#endregion
}
}
|
||||
TheStack | dbe33c3707f07488d392d04b64dd2ba5b39cb3ee | C#code:C# | {"size": 3900, "ext": "cs", "max_stars_repo_path": "AxFixEntities/ConvertersGenerator.cs", "max_stars_repo_name": "agilitix/agilelib", "max_stars_repo_stars_event_min_datetime": "2016-10-05T22:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-05T22:35:12.000Z", "max_issues_repo_path": "AxFixEntities/ConvertersGenerator.cs", "max_issues_repo_name": "agilitix/agilelib", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AxFixEntities/ConvertersGenerator.cs", "max_forks_repo_name": "agilitix/agilelib", "max_forks_repo_forks_event_min_datetime": "2019-07-03T08:14:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T08:14:07.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 39.7959183673, "max_line_length": 152, "alphanum_fraction": 0.4720512821} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace AxFixEntities
{
public static class ConvertersGenerator
{
public static void Generate()
{
SpecDoc spec = SpecDoc.Load(@".\Spec\FIX44.xml");
TypeMappingDoc typeMap = TypeMappingDoc.Load(@".\Spec\TypeMapping.xml");
TypeResolver typeResolver = new TypeResolver(spec, typeMap);
StringBuilder sb = new StringBuilder();
sb.AppendLine("using System;");
sb.AppendLine("using System.Linq;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using System.Globalization;");
sb.AppendLine("using QuickFix;");
sb.AppendLine();
sb.AppendLine("// Generated file");
sb.AppendLine();
sb.AppendLine("namespace FIX44.Entities");
sb.Append("{\n");
sb.AppendFormat("public static class Converters\n");
sb.Append("{\n");
foreach (var message in spec.Messages)
{
sb.AppendFormat("public static {0} ToEntity(this QuickFix.FIX44.{0} v)\n", message.Name);
sb.Append("{\n");
sb.AppendFormat("var r = new {0}();\n", message.Name);
foreach (var field in message.Fields)
{
if (!field.Required)
{
sb.AppendFormat("if(v.IsSet{0}())\n", field.Name);
sb.AppendFormat("r.{0} = {1};\n", field.Name, typeResolver.MakePropertyAssignment("v", field.Name));
}
else
{
sb.AppendFormat("r.{0} = {1};\n", field.Name, typeResolver.MakePropertyAssignment("v", field.Name));
}
}
foreach (var group in message.Groups)
{
var groupInternalType = message.Name + "." + group.Name + "Item";
if (group.Required == false)
{
sb.AppendFormat("if(v.IsSet{0}())\n", group.Name);
sb.Append("{\n");
}
sb.AppendFormat("var {0}List = new List<{1}>();\n", group.Name, groupInternalType);
sb.AppendFormat("for (var i = 1; i <= v.{0}.getValue(); i++)\n", group.Name);
sb.Append("{\n");
sb.AppendFormat("var fixGroup = (QuickFix.FIX44.{0}.{1}Group)v.GetGroup(i, QuickFix.Fields.Tags.{1});\n", message.Name, group.Name);
sb.AppendFormat("var groupItem = new {0}();\n", groupInternalType);
foreach (var field in @group.Fields)
{
if (!field.Required)
{
sb.AppendFormat("if(fixGroup.IsSet{0}())\n", field.Name);
sb.AppendFormat("groupItem.{0} = {1};\n", field.Name, typeResolver.MakePropertyAssignment("fixGroup", field.Name));
}
else
{
sb.AppendFormat("groupItem.{0} = {1};\n", field.Name, typeResolver.MakePropertyAssignment("fixGroup", field.Name));
}
}
sb.AppendFormat("{0}List.Add(groupItem);\n", group.Name);
sb.Append("}\n");
sb.AppendFormat("r.{0} = {0}List.ToArray();\n", group.Name);
sb.Append(group.Required ? string.Empty : "}\n" );
}
sb.AppendLine("return r;\n");
sb.Append("}\n");
}
sb.Append("}\n");
File.WriteAllText("Converters.cs", sb.ToString());
}
}
}
|
||||
TheStack | dbe373984bad14ef44153c1ab895e1ac40a5ebe5 | C#code:C# | {"size": 1443, "ext": "cs", "max_stars_repo_path": "Dependency/SocketStream.cs", "max_stars_repo_name": "lewjc/Messenger", "max_stars_repo_stars_event_min_datetime": "2019-11-05T17:38:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T17:38:28.000Z", "max_issues_repo_path": "Dependency/SocketStream.cs", "max_issues_repo_name": "lewjc/Messenger", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dependency/SocketStream.cs", "max_forks_repo_name": "lewjc/Messenger", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.7954545455, "max_line_length": 109, "alphanum_fraction": 0.5945945946} | using System;
using System.Net.Sockets;
using System.Text;
namespace Dependency
{
public abstract class SocketStream
{
protected static readonly int MAX_MESSAGE = 2048;
protected TcpListener instanceSocket;
/// <summary>
/// Sends a message to the specified client's input stream
/// </summary>
/// <param name="message">The message to be sent.</param>
/// <param name="clientStream">The clients input stream of which the message is being sent..</param>
public static void SendMessage(string message, NetworkStream clientStream)
{
byte[] textBuffer = Encoding.ASCII.GetBytes(message);
// Output the menu
clientStream.Write(textBuffer, 0, textBuffer.Length);
clientStream.Flush();
Console.WriteLine("Message sent");
}
/// <summary>
/// Waits to recieve a message
/// </summary>
/// <returns>The message.</returns>
/// <param name="stream">Stream.</param>
public static string RecieveMessage(NetworkStream stream)
{
byte[] textBuffer = new byte[MAX_MESSAGE];
int response = stream.Read(textBuffer, 0, textBuffer.Length);
// Converting the bytes to a manipulatiable string
return Encoding.ASCII.GetString(textBuffer, 0, response);
}
}
}
|
||||
TheStack | dbe3fddca8104209843e77a91020f7ee4f4aab99 | C#code:C# | {"size": 1099, "ext": "cs", "max_stars_repo_path": "src/Thinktecture.IO.FileSystem.Abstractions/Extensions/FileStreamExtensions.cs", "max_stars_repo_name": "ManuelRauber/Thinktecture.Abstractions", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Thinktecture.IO.FileSystem.Abstractions/Extensions/FileStreamExtensions.cs", "max_issues_repo_name": "ManuelRauber/Thinktecture.Abstractions", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Thinktecture.IO.FileSystem.Abstractions/Extensions/FileStreamExtensions.cs", "max_forks_repo_name": "ManuelRauber/Thinktecture.Abstractions", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.7027027027, "max_line_length": 89, "alphanum_fraction": 0.695177434} | using System.IO;
using JetBrains.Annotations;
using Thinktecture.IO;
using Thinktecture.IO.Adapters;
// ReSharper disable once CheckNamespace
namespace Thinktecture
{
/// <summary>
/// Extensions for <see cref="FileStream"/>.
/// </summary>
public static class FileStreamExtensions
{
/// <summary>
/// Converts file stream to <see cref="IFileStream"/>.
/// </summary>
/// <param name="file">File stream to convert.</param>
/// <returns>Converted file stream.</returns>
[CanBeNull]
public static IFileStream ToInterface([CanBeNull] this FileStream file)
{
return (file == null) ? null : new FileStreamAdapter(file);
}
/// <summary>
/// Converts provided <see cref="IFileStream"/> info to <see cref="FileStream"/>.
/// </summary>
/// <param name="abstraction">Instance of <see cref="IFileStream"/> to convert.</param>
/// <returns>An instance of <see cref="FileStream"/>.</returns>
[CanBeNull]
public static FileStream ToImplementation([CanBeNull] this IFileStream abstraction)
{
return ((IAbstraction<FileStream>)abstraction)?.UnsafeConvert();
}
}
}
|
||||
TheStack | dbe5fdc71850166077764fa4312fc5a3b09068ec | C#code:C# | {"size": 543, "ext": "cs", "max_stars_repo_path": "src/FluentEvents/Pipelines/Filters/FilterPipelineModule.cs", "max_stars_repo_name": "luca-esse/FluentEvents", "max_stars_repo_stars_event_min_datetime": "2019-03-26T11:35:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T10:43:19.000Z", "max_issues_repo_path": "src/FluentEvents/Pipelines/Filters/FilterPipelineModule.cs", "max_issues_repo_name": "nowakprojects/FluentEvents", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FluentEvents/Pipelines/Filters/FilterPipelineModule.cs", "max_forks_repo_name": "nowakprojects/FluentEvents", "max_forks_repo_forks_event_min_datetime": "2019-08-07T07:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T13:32:28.000Z"} | {"max_stars_count": 12.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 28.5789473684, "max_line_length": 85, "alphanum_fraction": 0.6556169429} | using System.Threading.Tasks;
namespace FluentEvents.Pipelines.Filters
{
internal class FilterPipelineModule : IPipelineModule<FilterPipelineModuleConfig>
{
public Task InvokeAsync(
FilterPipelineModuleConfig config,
PipelineContext pipelineContext,
NextModuleDelegate invokeNextModule
)
{
return config.IsMatching(pipelineContext.PipelineEvent.Event)
? invokeNextModule(pipelineContext)
: Task.CompletedTask;
}
}
}
|
||||
TheStack | dbe80cb14cb6ed0306701603b120d1b0cfadf867 | C#code:C# | {"size": 443, "ext": "cs", "max_stars_repo_path": "AppStudio.Shared/ViewModels/PrivacyViewModel.cs", "max_stars_repo_name": "llalonde/AppStudio-Bandsintown-Demo", "max_stars_repo_stars_event_min_datetime": "2016-08-10T14:22:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-17T12:04:41.000Z", "max_issues_repo_path": "AppStudio.Shared/ViewModels/PrivacyViewModel.cs", "max_issues_repo_name": "llalonde/AppStudio-Bandsintown-Demo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AppStudio.Shared/ViewModels/PrivacyViewModel.cs", "max_forks_repo_name": "llalonde/AppStudio-Bandsintown-Demo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.0384615385, "max_line_length": 68, "alphanum_fraction": 0.4762979684} | using AppStudio.Data;
using System;
using Windows.ApplicationModel;
namespace AppStudio.ViewModels
{
public class PrivacyViewModel : BindableBase
{
public Uri Url
{
get
{
return new Uri(UrlText, UriKind.RelativeOrAbsolute);
}
}
public string UrlText
{
get
{
return "";
}
}
}
}
|
||||
TheStack | dbe89b17218eacc8f43069c4fecbfa46650d98d8 | C#code:C# | {"size": 1135, "ext": "cs", "max_stars_repo_path": "e3net.Common/Encrypt/QQEncryptUtil.cs", "max_stars_repo_name": "ludycool/NetCore.Admin", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "e3net.Common/Encrypt/QQEncryptUtil.cs", "max_issues_repo_name": "ludycool/NetCore.Admin", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "e3net.Common/Encrypt/QQEncryptUtil.cs", "max_forks_repo_name": "ludycool/NetCore.Admin", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.6756756757, "max_line_length": 93, "alphanum_fraction": 0.6193832599} | using System;
using System.Collections.Generic;
using System.Text;
namespace e3net.Common.Encrypt
{
//QQ的EncryptUtil
public class QQEncryptUtil
{
public static string EncodePasswordWithVerifyCode(string password, string verifyCode)
{
return MD5(MD5_3(password) + verifyCode.ToUpper());
}
static string MD5_3(string arg)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(arg);
buffer = md5.ComputeHash(buffer);
buffer = md5.ComputeHash(buffer);
buffer = md5.ComputeHash(buffer);
return BitConverter.ToString(buffer).Replace("-", "").ToUpper();
}
static string MD5(string arg)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(arg);
buffer = md5.ComputeHash(buffer);
return BitConverter.ToString(buffer).Replace("-", "").ToUpper();
}
}
}
|
||||
TheStack | dbe902c4ee31fde62fd60e63f244da6efe754ff7 | C#code:C# | {"size": 668, "ext": "cs", "max_stars_repo_path": "PIO.Bots.ServerLib/Tables/HarvestOrderTable.cs", "max_stars_repo_name": "dfgs/PIO", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PIO.Bots.ServerLib/Tables/HarvestOrderTable.cs", "max_issues_repo_name": "dfgs/PIO", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PIO.Bots.ServerLib/Tables/HarvestOrderTable.cs", "max_forks_repo_name": "dfgs/PIO", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.4, "max_line_length": 147, "alphanum_fraction": 0.7694610778} | using NetORMLib.Columns;
using NetORMLib.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIO.Bots.ServerLib.Tables
{
public class HarvestOrderTable:Table
{
public static readonly Column<int> HarvestOrderID = new Column<int>() { Constraint = NetORMLib.ColumnConstraints.PrimaryKey, IsIdentity = true };
public static readonly Column<int> OrderID = new Column<int>();
// planet ID cannot be part of order table because of constraint
public static readonly Column<int> PlanetID = new Column<int>();
public static readonly Column<int> BuildingID = new Column<int>();
}
}
|
||||
TheStack | dbe92b50b22186c5056e71252dc5b2cdfde0a621 | C#code:C# | {"size": 3213, "ext": "cs", "max_stars_repo_path": "Src/CoreTests/VulnerabilityDataTests.cs", "max_stars_repo_name": "rajbos/NuGetDefense.Core", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/CoreTests/VulnerabilityDataTests.cs", "max_issues_repo_name": "rajbos/NuGetDefense.Core", "max_issues_repo_issues_event_min_datetime": "2020-04-20T00:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T06:22:25.000Z", "max_forks_repo_path": "Src/CoreTests/VulnerabilityDataTests.cs", "max_forks_repo_name": "rajbos/NuGetDefense.Core", "max_forks_repo_forks_event_min_datetime": "2020-04-19T21:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T02:16:53.000Z"} | {"max_stars_count": null, "max_issues_count": 2.0, "max_forks_count": 3.0, "avg_line_length": 41.7272727273, "max_line_length": 114, "alphanum_fraction": 0.5415499533} | using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Common;
using NuGetDefense;
using NuGetDefense.Core;
using Xunit;
using Xunit.Abstractions;
namespace CoreTests
{
public class VulnerabilityDataTests
{
private readonly ITestOutputHelper _testOutputHelper;
public VulnerabilityDataTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper;
[Fact]
public void SaveLoadVulnerabilityData()
{
var testVulnDict = new Dictionary<string, Dictionary<string, VulnerabilityEntry>>
{
{
"Test",
new Dictionary<string, VulnerabilityEntry>
{
{
"CVE-Test",
new VulnerabilityEntry
{
Cwe = "Test-CWE",
Vector = Vulnerability.AccessVectorType.NETWORK,
Vendor = "Test Vendor",
Versions = new[] {"1.1.1", "1.2.5"},
Description = "Test Description",
References = new[] {"Test Reference"},
Score = 4.3
}
}
}
}
};
Task.Run(() =>
{
_testOutputHelper.WriteLine("Locking File");
using var file = File.Open("TestVulnerabilityData.bin", FileMode.Open, FileAccess.ReadWrite,
FileShare.None);
Thread.Sleep(TimeSpan.FromSeconds(5));
_testOutputHelper.WriteLine("Releasing File");
file.Close();
});
Thread.Sleep(TimeSpan.FromSeconds(1));
_testOutputHelper.WriteLine("Reading File");
VulnerabilityData.SaveToBinFile(testVulnDict, "TestVulnerabilityData.bin", TimeSpan.FromSeconds(10));
var LoadedVulnBinDict = VulnerabilityData.LoadFromBinFile("TestVulnerabilityData.bin");
testVulnDict.Count.IsSameOrEqualTo(LoadedVulnBinDict.Count);
foreach (var (key, value) in testVulnDict)
{
var testValue = LoadedVulnBinDict[key];
Assert.Equal(testValue.Count, value.Count);
foreach (var (innerKey, innerValue) in value)
{
Assert.Equal(innerValue.Cwe, LoadedVulnBinDict[key][innerKey].Cwe);
Assert.Equal(innerValue.Description, LoadedVulnBinDict[key][innerKey].Description);
Assert.Equal(innerValue.References, LoadedVulnBinDict[key][innerKey].References);
Assert.Equal(innerValue.Score, LoadedVulnBinDict[key][innerKey].Score);
Assert.Equal(innerValue.Vector, LoadedVulnBinDict[key][innerKey].Vector);
Assert.Equal(innerValue.Versions, LoadedVulnBinDict[key][innerKey].Versions);
}
}
}
}
} |
||||
TheStack | dbeb21e90f6a645c60ecf2f0d2b5e8b2907e260f | C#code:C# | {"size": 3146, "ext": "cs", "max_stars_repo_path": "EvolutionRunner.cs", "max_stars_repo_name": "Amadek/stock-wallet-calculator", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EvolutionRunner.cs", "max_issues_repo_name": "Amadek/stock-wallet-calculator", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EvolutionRunner.cs", "max_forks_repo_name": "Amadek/stock-wallet-calculator", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.8395061728, "max_line_length": 164, "alphanum_fraction": 0.5829624921} | using System.Collections.Generic;
using System.Linq;
namespace StockWalletCalculator
{
class EvolutionRunner
{
private readonly GenomeGenerator _genomeGenerator;
private readonly GenomeCrossover _genomeCrossover;
private readonly GenomeMutator _genomeMutator;
private readonly IFitnessCalculator _fitnessCalculator;
public EvolutionRunner(
GenomeGenerator genomeGenerator,
GenomeCrossover genomeCrossover,
GenomeMutator genomeMutator,
IFitnessCalculator fitnessCalculator)
{
_genomeGenerator = genomeGenerator;
_genomeCrossover = genomeCrossover;
_genomeMutator = genomeMutator;
_fitnessCalculator = fitnessCalculator;
}
public EvolutionResult Evolve(int generationLimit, decimal fitnessLimit)
{
List<GenomeWithFitness> oldGeneration = _genomeGenerator.GenerateGeneration()
.Select(g => new GenomeWithFitness { Genome = g, Fitness = _fitnessCalculator.Calculate(g) })
.OrderByDescending(g => g.Fitness)
.ToList();
GenomeWithFitness bestGenome = null;
int generationIndex;
for (generationIndex = 0; generationIndex < generationLimit; generationIndex++)
{
List<GenomeWithFitness> newGeneration = oldGeneration.Take(2).ToList();
oldGeneration = oldGeneration.Skip(2).ToList();
for (int genomeIndex = 0; genomeIndex < oldGeneration.Count / 2; genomeIndex++)
{
string[] crossedGenomes = _genomeCrossover.CrossoverGenomes(oldGeneration[genomeIndex].Genome, oldGeneration[genomeIndex + 1].Genome).ToArray();
foreach (string crossedGenome in crossedGenomes)
{
string mutatedGenome = _genomeMutator.MutateGenome(crossedGenome);
GenomeWithFitness newGenome = new GenomeWithFitness { Genome = mutatedGenome, Fitness = _fitnessCalculator.Calculate(mutatedGenome) };
newGeneration.Add(newGenome);
}
}
bestGenome = newGeneration.OrderByDescending(g => g.Fitness).First();
if (bestGenome.Fitness >= fitnessLimit)
{
return new EvolutionResult
{
FinalGenome = bestGenome.Genome,
Fitness = bestGenome.Fitness,
GenerationIndex = generationIndex
};
}
oldGeneration = newGeneration.OrderByDescending(g => g.Fitness).ToList();
}
return new EvolutionResult
{
FinalGenome = bestGenome.Genome,
Fitness = bestGenome.Fitness,
GenerationIndex = generationIndex
};
}
private class GenomeWithFitness
{
public string Genome { get; set; }
public decimal Fitness { get; set; }
}
}
}
|
||||
TheStack | dbeb483dfb62b69e84e66d59f38e258b884336b3 | C#code:C# | {"size": 2762, "ext": "cs", "max_stars_repo_path": "snippets/csharp/System/ArraySegmentT/Overview/arraysegment.cs", "max_stars_repo_name": "cston/dotnet-api-docs", "max_stars_repo_stars_event_min_datetime": "2022-03-09T02:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T02:25:54.000Z", "max_issues_repo_path": "snippets/csharp/System/ArraySegmentT/Overview/arraysegment.cs", "max_issues_repo_name": "cston/dotnet-api-docs", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/csharp/System/ArraySegmentT/Overview/arraysegment.cs", "max_forks_repo_name": "cston/dotnet-api-docs", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.1836734694, "max_line_length": 111, "alphanum_fraction": 0.622737147} | // The following code example passes an ArraySegment to a method.
// <Snippet1>
using System;
public class SamplesArray {
public static void Main() {
// Create and initialize a new string array.
String[] myArr = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" };
// Display the initial contents of the array.
Console.WriteLine( "The original array initially contains:" );
PrintIndexAndValues( myArr );
// Define an array segment that contains the entire array.
ArraySegment<string> myArrSegAll = new ArraySegment<string>( myArr );
// Display the contents of the ArraySegment.
Console.WriteLine( "The first array segment (with all the array's elements) contains:" );
PrintIndexAndValues( myArrSegAll );
// Define an array segment that contains the middle five values of the array.
ArraySegment<string> myArrSegMid = new ArraySegment<string>( myArr, 2, 5 );
// Display the contents of the ArraySegment.
Console.WriteLine( "The second array segment (with the middle five elements) contains:" );
PrintIndexAndValues( myArrSegMid );
// Modify the fourth element of the first array segment myArrSegAll.
myArrSegAll.Array[3] = "LION";
// Display the contents of the second array segment myArrSegMid.
// Note that the value of its second element also changed.
Console.WriteLine( "After the first array segment is modified, the second array segment now contains:" );
PrintIndexAndValues( myArrSegMid );
}
public static void PrintIndexAndValues( ArraySegment<string> arrSeg ) {
for ( int i = arrSeg.Offset; i < (arrSeg.Offset + arrSeg.Count); i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arrSeg.Array[i] );
}
Console.WriteLine();
}
public static void PrintIndexAndValues( String[] myArr ) {
for ( int i = 0; i < myArr.Length; i++ ) {
Console.WriteLine( " [{0}] : {1}", i, myArr[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The original array initially contains:
[0] : The
[1] : quick
[2] : brown
[3] : fox
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
The first array segment (with all the array's elements) contains:
[0] : The
[1] : quick
[2] : brown
[3] : fox
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
The second array segment (with the middle five elements) contains:
[2] : brown
[3] : fox
[4] : jumps
[5] : over
[6] : the
After the first array segment is modified, the second array segment now contains:
[2] : brown
[3] : LION
[4] : jumps
[5] : over
[6] : the
*/
// </Snippet1>
|
||||
TheStack | dbebb343ed78512de0e27c0820457aae55bf21aa | C#code:C# | {"size": 1863, "ext": "cs", "max_stars_repo_path": "Sources/Tests/UnitTests/Convenience/PriorityTest.cs", "max_stars_repo_name": "Suchiman/AngouriMath", "max_stars_repo_stars_event_min_datetime": "2021-05-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T10:21:30.000Z", "max_issues_repo_path": "Sources/Tests/UnitTests/Convenience/PriorityTest.cs", "max_issues_repo_name": "Suchiman/AngouriMath", "max_issues_repo_issues_event_min_datetime": "2020-11-21T12:07:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T09:13:12.000Z", "max_forks_repo_path": "Sources/Tests/UnitTests/Convenience/PriorityTest.cs", "max_forks_repo_name": "Suchiman/AngouriMath", "max_forks_repo_forks_event_min_datetime": "2021-06-11T17:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T17:52:53.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 5.0, "max_forks_count": 1.0, "avg_line_length": 46.575, "max_line_length": 114, "alphanum_fraction": 0.4551798175} | using Xunit;
using AngouriMath.Extensions;
namespace UnitTests.Common
{
public class PriorityTest
{
[Theory]
[InlineData("a + b", "a + b")]
[InlineData("a + b - c", "(a + b) - c")]
[InlineData("a + b * c", "a + (b * c)")]
[InlineData("a ^ b ^ c", "a ^ (b ^ c)")]
[InlineData("a + b = c + d", "(a + b) = (c + d)")]
[InlineData("a > b = c > d", "(a > b) = (c > d)")]
[InlineData("a < b = c < d", "(a < b) = (c < d)")]
[InlineData(@"A = B \/ C", @"A = (B \/ C)")]
[InlineData(@"A = B \ C", @"A = (B \ C)")]
[InlineData(@"B \ C = A", @"(B \ C) = A")]
[InlineData(@"A /\ B \/ C", @"(A /\ B) \/ C")]
[InlineData(@"A \/ B /\ C", @"A \/ (B /\ C)")]
[InlineData(@"A \/ B = B /\ C", @"(A \/ B) = (B /\ C)")]
[InlineData("a and b or c", "(a and b) or c")]
[InlineData("a or b and c", "a or (b and c)")]
[InlineData("a or b implies c or d", "(a or b) implies (c or d)")]
[InlineData("not a or not b implies not c or not d", "((not a) or (not b)) implies ((not c) or (not d))")]
[InlineData("a and b = c > d", "a and (b = (c > d))")]
[InlineData("a provided b", "a provided b")]
[InlineData("a provided b provided c", "(a provided b) provided c")]
[InlineData("a provided (b provided c)", "a provided (b provided c)")]
[InlineData("a provided b and c", "a provided (b and c)")]
[InlineData("a provided b + c > 0", "a provided (b + c > 0)")]
[InlineData("a + b provided b + c > 0", "(a + b) provided (b + c > 0)")]
[InlineData("a + b provided b + c > 0 provided d", "((a + b) provided (b + c > 0)) provided d")]
public void Test(string implic, string explic)
{
Assert.Equal(explic.ToEntity(), implic.ToEntity());
}
}
}
|
||||
TheStack | dbebf07c63cb45901e00d83f45b94d8b72a5f169 | C#code:C# | {"size": 1159, "ext": "cs", "max_stars_repo_path": "Core/Shared/Modules/IntegrationModules/BeckhoffAds/BeckhoffAdsIntegrationModuleInstructionsMessage.cs", "max_stars_repo_name": "stec-zcps/mdaa", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/Shared/Modules/IntegrationModules/BeckhoffAds/BeckhoffAdsIntegrationModuleInstructionsMessage.cs", "max_issues_repo_name": "stec-zcps/mdaa", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/Shared/Modules/IntegrationModules/BeckhoffAds/BeckhoffAdsIntegrationModuleInstructionsMessage.cs", "max_forks_repo_name": "stec-zcps/mdaa", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 41.3928571429, "max_line_length": 214, "alphanum_fraction": 0.7532355479} | using System.Collections.Generic;
using Fraunhofer.IPA.DataAggregator.Communication.Messages;
using Newtonsoft.Json;
namespace Fraunhofer.IPA.DataAggregator.Modules.IntegrationModules.BeckhoffAds
{
public class BeckhoffAdsIntegrationModuleInstructionsMessage : InstructionsMessage
{
#region Attributes
public Dictionary<string, BeckhoffAdsSymbol> AdsSymbolsFromTarget = new Dictionary<string, BeckhoffAdsSymbol>();
public Dictionary<string, BeckhoffAdsSymbol> AdsSymbolsToTarget = new Dictionary<string, BeckhoffAdsSymbol>();
#endregion Attributes
#region Constructors
[JsonConstructor]
public BeckhoffAdsIntegrationModuleInstructionsMessage(string moduleId) : base(moduleId)
{
}
public BeckhoffAdsIntegrationModuleInstructionsMessage(string moduleId, Dictionary<string, BeckhoffAdsSymbol> AdsSymbolsFromTarget, Dictionary<string, BeckhoffAdsSymbol> AdsSymbolsToTarget) : base(moduleId)
{
this.AdsSymbolsFromTarget = AdsSymbolsFromTarget;
this.AdsSymbolsToTarget = AdsSymbolsToTarget;
}
#endregion Constructors
}
} |
||||
TheStack | dbec41ea0026bd8c2ea65970d7ba0bd4abe8beb5 | C#code:C# | {"size": 1373, "ext": "cs", "max_stars_repo_path": "src/UIWeb/Models/Funds/_ViewModels.cs", "max_stars_repo_name": "NotMyself/Gringotts", "max_stars_repo_stars_event_min_datetime": "2017-03-19T01:48:39.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-11T01:10:54.000Z", "max_issues_repo_path": "src/UIWeb/Models/Funds/_ViewModels.cs", "max_issues_repo_name": "ssdug/Gringotts", "max_issues_repo_issues_event_min_datetime": "2017-03-19T03:02:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-19T03:02:07.000Z", "max_forks_repo_path": "src/UIWeb/Models/Funds/_ViewModels.cs", "max_forks_repo_name": "NotMyself/Gringotts", "max_forks_repo_forks_event_min_datetime": "2017-06-07T12:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T16:51:06.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 1.0, "max_forks_count": 4.0, "avg_line_length": 28.6041666667, "max_line_length": 65, "alphanum_fraction": 0.6059723234} | using System.Collections.Generic;
using System.Linq;
using Wiz.Gringotts.UIWeb.Models.Accounts;
using Wiz.Gringotts.UIWeb.Models.Clients;
using Wiz.Gringotts.UIWeb.Models.Transactions;
using PagedList;
namespace Wiz.Gringotts.UIWeb.Models.Funds
{
public class FundDetails
{
public Fund Fund { get; set; }
public SearchPager Pager { get; set; }
public IPagedList<FundSubsidiary> Items { get; set; }
public IPagedList<TransactionBatch> Batches { get; set; }
}
public class FundSubsidiary
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Total { get; set; }
public decimal Encumbered { get; set; }
public decimal Available { get; set; }
public IEnumerable<string> BankNumbers { get; set; }
}
public class FundClientSubsidiary : FundSubsidiary
{
public IEnumerable<Account> Accounts { get; set; }
public Client Client
{
get
{
return this.Accounts.Cast<ClientAccount>()
.Select(a => a.Residency.Client)
.FirstOrDefault();
}
}
}
public class FundsSearchResult : IPagedSearchResult<Fund>
{
public SearchPager Pager { get; set; }
public IPagedList<Fund> Items { get; set; }
}
} |
||||
TheStack | dbecd6ceffb20f45709615e78c333f9c5938145f | C#code:C# | {"size": 873, "ext": "cs", "max_stars_repo_path": "ExamPreparation/04.WorkHours/Program.cs", "max_stars_repo_name": "SpleefDinamix/SoftuniCSProgrammingBasics", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExamPreparation/04.WorkHours/Program.cs", "max_issues_repo_name": "SpleefDinamix/SoftuniCSProgrammingBasics", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExamPreparation/04.WorkHours/Program.cs", "max_forks_repo_name": "SpleefDinamix/SoftuniCSProgrammingBasics", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.1612903226, "max_line_length": 68, "alphanum_fraction": 0.5326460481} | using System;
namespace _04.WorkHours
{
class Program
{
static void Main()
{
int estimatedWorkHours = int.Parse(Console.ReadLine());
int numOfWorkers = int.Parse(Console.ReadLine());
int workDays = int.Parse(Console.ReadLine());
var totalWorkHours = numOfWorkers * workDays * 8;
if (estimatedWorkHours < totalWorkHours)
{
var hoursLeft = totalWorkHours - estimatedWorkHours;
Console.WriteLine(hoursLeft + " hours left");
}
else
{
var overTime = estimatedWorkHours - totalWorkHours;
var penalties = overTime * workDays;
Console.WriteLine(overTime + " overtime");
Console.WriteLine("Penalties: " + penalties);
}
}
}
}
|
||||
TheStack | dbed261cba9d8f01764becaf6ce45a5579334bd2 | C#code:C# | {"size": 9540, "ext": "cshtml", "max_stars_repo_path": "src/Modules/Laser.Orchard.StartupConfig/Views/EditorTemplates/Parts.Common.SummaryInfoFor_Edit.cshtml", "max_stars_repo_name": "INVA-Spa/Laser.Orchard.Platform", "max_stars_repo_stars_event_min_datetime": "2018-11-22T18:59:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T18:44:03.000Z", "max_issues_repo_path": "src/Modules/Laser.Orchard.StartupConfig/Views/EditorTemplates/Parts.Common.SummaryInfoFor_Edit.cshtml", "max_issues_repo_name": "INVA-Spa/Laser.Orchard.Platform", "max_issues_repo_issues_event_min_datetime": "2019-11-04T16:08:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T07:10:38.000Z", "max_forks_repo_path": "src/Modules/Laser.Orchard.StartupConfig/Views/EditorTemplates/Parts.Common.SummaryInfoFor_Edit.cshtml", "max_forks_repo_name": "INVA-Spa/Laser.Orchard.Platform", "max_forks_repo_forks_event_min_datetime": "2019-04-26T18:10:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T17:28:38.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 15.0, "max_forks_count": 5.0, "avg_line_length": 58.527607362, "max_line_length": 303, "alphanum_fraction": 0.4751572327} | @model Orchard.Core.Common.Models.CommonPart
@using System.Globalization;
@using Orchard.ContentManagement;
@using Orchard.Core.Common.Models;
@using Orchard.Core.Contents;
@using Orchard.Autoroute.Models;
@{
Script.Require("Bootstrap").AtHead();
Style.Require("Bootstrap").AtHead();
Style.Require("FontAwesome").AtHead();
Style.Require("LaserBase").AtHead();
var cultureInfo = CultureInfo.GetCultureInfo(WorkContext.CurrentCulture);
DateTime? createdUtc = Model == null ? null : Model.CreatedUtc;
DateTime? publishedUtc = Model == null ? null : Model.PublishedUtc;
DateTime? modifiedUtc = Model == null ? null : Model.ModifiedUtc;
var contentItem = Model.ContentItem == null ? null : (ContentItem)Model.ContentItem;
var autoroutePart = contentItem.As<AutoroutePart>();
}
@{
// Defaults
var statusBackgroundColor = "green";
var statusIconClass = "fa fa-check";
var statusText = T("Published");
var statusDraftText = T("No Draft");
var statusDraftBackgrundColor = "green";
//Not Published
if (!contentItem.HasPublished()) {
statusBackgroundColor = "red";
statusIconClass = "fa fa-arrow-down";
statusText = T("not Published");
}
// Does the page have a draft
if (contentItem.HasDraft()) {
statusDraftText = T("Has Draft");
statusDraftBackgrundColor = "yellow";
}
}
<div class="edit-item-info-box-container">
<div class="row">
<!-- /.col -->
<div class="col-md-12 col-lg-6 col-12 custom-width-info-box">
<div class="info-box">
<span class="info-box-icon bg-aqua"><i class="fa fa-cog"></i></span>
<div class="info-box-content">
@if (createdUtc.HasValue) {
<span class="info-box-text col-sm-4">@T("Created on")</span>
<span class="info-box-number col-sm-8">@createdUtc.Value.ToString("dddd, dd MMMM yyyy HH:mm:ss", cultureInfo)</span>
}
@if (publishedUtc.HasValue) {
<span class="info-box-text col-sm-4">@T("Published on")</span>
<span class="info-box-number col-sm-8">@publishedUtc.Value.ToString("dddd, dd MMMM yyyy HH:mm:ss", cultureInfo)</span>
}
@if (modifiedUtc.HasValue) {
<span class="info-box-text col-sm-4">@T("Modified on")</span>
<span class="info-box-number col-sm-8">@modifiedUtc.Value.ToString("dddd, dd MMMM yyyy HH:mm:ss", cultureInfo)</span>
}
<span class="info-box-text col-sm-4">@T("Last Modified")</span>
<span class="info-box-number col-sm-8">@Display.CommonMetadataLastModified(ContentPart: Model)</span>
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
<!-- /.col -->
<!-- .col -->
<div class="col-md-12 col-lg-6 col-12 custom-width-info-box">
<div class="info-box">
<span class="info-box-icon bg-@statusBackgroundColor"><i class="@statusIconClass"></i></span>
<div class="info-box-content">
<span class="info-box-text col-sm-4">@T("Status")</span>
<span class="info-box-number col-sm-4"><i class="fa fa-circle fa-lg text-@statusBackgroundColor"></i> @statusText</span>
<span class="col-sm-4">
@if (autoroutePart != null) {
if (contentItem.HasPublished()) {
<a href="@Url.ItemDisplayUrl(contentItem)"
class="btn btn-success btn-xs text-white width-80"
target="_blank"
title="@T("View")">
<span class="glyphicon glyphicon-new-window"></span>
@T("View").Text
</a>
@*@Html.ItemDisplayLink(T("View").Text, contentItem, new { @class = "btn btn-success btn-xs text-white" })*@
}
}
</span>
<br />
<span class="info-box-text col-sm-4">@T("Draft")</span>
<span class="info-box-number col-sm-4"><i class="fa fa-circle fa-lg text-@statusDraftBackgrundColor"></i> @statusDraftText</span>
@{
var publishLaterPart = ((dynamic)Model.ContentItem).PublishLaterPart;
if (publishLaterPart != null) {
DateTime? versionPublishedUtc = publishLaterPart.VersionPublishedUtc == null ? null : publishLaterPart.VersionPublishedUtc;
if (publishLaterPart != null && contentItem != null) {
if ((((DateTime?)publishLaterPart.ScheduledPublishUtc.Value).HasValue &&
((DateTime?)publishLaterPart.ScheduledPublishUtc.Value) > DateTime.UtcNow) || (contentItem.HasPublished() && versionPublishedUtc.HasValue)) {
if (!contentItem.HasPublished() && !versionPublishedUtc.HasValue) {
<span class="info-box-text col-sm-4">@T("Publish on")</span>
<span class="info-box-number col-sm-8"><i class="fa fa-calendar-check-o fa-lg text-green"></i> @Display.DateTime(DateTimeUtc: ((Orchard.ContentManagement.Utilities.LazyField<System.DateTime?>)publishLaterPart.ScheduledPublishUtc).Value, CustomFormat: null)</span>
}
}
}
}
}
@{
var archiveLaterPart = ((dynamic)Model.ContentItem).ArchiveLaterPart;
if (archiveLaterPart != null) {
var scheduledArchiveUtc = archiveLaterPart.ScheduledArchiveUtc.Value;
var isPublished = (archiveLaterPart.ContentItem.VersionRecord != null && archiveLaterPart.ContentItem.VersionRecord.Published);
if ((isPublished && scheduledArchiveUtc != null && scheduledArchiveUtc > DateTime.UtcNow)) {
<span class="info-box-text col-sm-4">@T("Unpublish on")</span>
<span class="info-box-number col-sm-4">
<i class="fa fa-calendar-times-o fa-lg text-red" aria-hidden="true"></i> @Display.DateTime(DateTimeUtc: (DateTime)scheduledArchiveUtc, CustomFormat: null)
</span>
}
}
}
<span class="col-sm-4">
@if (autoroutePart != null) {
if (contentItem.HasPublished()) {
if (contentItem.HasDraft()) {
if (Authorizer.Authorize(Permissions.PreviewContent, contentItem)) {
<a href="@Url.Action("Display", "Item", new { area = "Contents", id = contentItem.Id, version = contentItem.Version })"
class="btn btn-warning btn-xs text-white width-80"
target="_blank"
title="@T("Preview")">
<span class="glyphicon glyphicon-new-window"></span>
@T("Preview").Text
</a>
@*@Html.ActionLink(T("Preview").Text, "Display", "Item", new { area = "Contents", id = contentItem.Id, version = contentItem.Version }, new { @class = "btn btn-warning btn-xs text-white" })*@
}
}
}
else {
if (contentItem.HasDraft()) {
if (Authorizer.Authorize(Permissions.PreviewContent, contentItem)) {
<a href="@Url.Action("Display", "Item", new { area = "Contents", id = contentItem.Id, version = contentItem.Version })"
class="btn btn-warning btn-xs text-white width-80"
target="_blank"
title="@T("Preview")">
<span class="glyphicon glyphicon-new-window"></span>
@T("Preview").Text
</a>
@*@Html.ActionLink(T("Preview").Text, "Display", "Item", new { area = "Contents", id = contentItem.Id, version = contentItem.Version }, new { @class = "btn btn-warning btn-xs text-white" })*@
}
}
}
}
</span>
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
<!-- /.col -->
</div>
</div> |
||||
TheStack | dbf0d8fff59606ba2eef494cca4cd750a2eb0668 | C#code:C# | {"size": 693, "ext": "cs", "max_stars_repo_path": "LazySQL/Core/Tools/Modules/CircleTool.cs", "max_stars_repo_name": "hjh1126123/LazySql", "max_stars_repo_stars_event_min_datetime": "2018-10-19T07:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T07:04:19.000Z", "max_issues_repo_path": "LazySQL/Core/Tools/Modules/CircleTool.cs", "max_issues_repo_name": "hjh1126123/LazySql", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LazySQL/Core/Tools/Modules/CircleTool.cs", "max_forks_repo_name": "hjh1126123/LazySql", "max_forks_repo_forks_event_min_datetime": "2018-10-19T07:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-19T07:15:56.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 31.5, "max_line_length": 155, "alphanum_fraction": 0.6637806638} | using System;
using System.CodeDom;
namespace LazySQL.Core.Tools.Modules
{
public class CircleTool
{
public CodeIterationStatement CreateCircle(string initStatement,string testExpression,string incrementStatement,Func<CodeStatementCollection> func)
{
CodeIterationStatement ret = new CodeIterationStatement
{
InitStatement = new CodeSnippetStatement(initStatement),
TestExpression = new CodeSnippetExpression(testExpression),
IncrementStatement = new CodeSnippetStatement(incrementStatement)
};
ret.Statements.AddRange(func());
return ret;
}
}
}
|
||||
TheStack | dbf3e9cc5137493332f8aabd06b2c59b7656bcc0 | C#code:C# | {"size": 362, "ext": "cs", "max_stars_repo_path": "test/Armory.Test/Users/UsersUnitTestCase.cs", "max_stars_repo_name": "cantte/Armory.Api", "max_stars_repo_stars_event_min_datetime": "2021-06-10T19:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T16:50:12.000Z", "max_issues_repo_path": "test/Armory.Test/Users/UsersUnitTestCase.cs", "max_issues_repo_name": "cantte/Armory.Api", "max_issues_repo_issues_event_min_datetime": "2021-07-30T19:52:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T05:10:15.000Z", "max_forks_repo_path": "test/Armory.Test/Users/UsersUnitTestCase.cs", "max_forks_repo_name": "cantte/Armory.Api", "max_forks_repo_forks_event_min_datetime": "2021-08-04T23:56:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T23:56:15.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 67.0, "max_forks_count": 1.0, "avg_line_length": 21.2941176471, "max_line_length": 67, "alphanum_fraction": 0.682320442} | using Armory.Shared.Test.Infrastructure;
using Armory.Users.Domain;
using Moq;
namespace Armory.Test.Users
{
public class UsersUnitTestCase : UnitTestCase
{
protected readonly Mock<IArmoryUsersRepository> Repository;
protected UsersUnitTestCase()
{
Repository = new Mock<IArmoryUsersRepository>();
}
}
}
|
||||
TheStack | dbf4b5f03c62608310be527ea3072b7e66f9974b | C#code:C# | {"size": 233, "ext": "cs", "max_stars_repo_path": "WoWDatabaseEditor.Common/WDE.Common/Services/IClipboardService.cs", "max_stars_repo_name": "Intemporel/WoWDatabaseEditor", "max_stars_repo_stars_event_min_datetime": "2018-08-31T00:59:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:13:20.000Z", "max_issues_repo_path": "WoWDatabaseEditor.Common/WDE.Common/Services/IClipboardService.cs", "max_issues_repo_name": "gitter-badger/WoWDatabaseEditor", "max_issues_repo_issues_event_min_datetime": "2018-08-13T14:58:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T20:16:16.000Z", "max_forks_repo_path": "WoWDatabaseEditor.Common/WDE.Common/Services/IClipboardService.cs", "max_forks_repo_name": "gitter-badger/WoWDatabaseEditor", "max_forks_repo_forks_event_min_datetime": "2017-12-15T19:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T23:37:24.000Z"} | {"max_stars_count": 137.0, "max_issues_count": 85.0, "max_forks_count": 90.0, "avg_line_length": 19.4166666667, "max_line_length": 38, "alphanum_fraction": 0.6824034335} | using System.Threading.Tasks;
using WDE.Module.Attributes;
namespace WDE.Common.Services
{
[UniqueProvider]
public interface IClipboardService
{
Task<string> GetText();
void SetText(string text);
}
} |
||||
TheStack | dbf637915ddb317c22e5bddd57373d667b197e8e | C#code:C# | {"size": 1354, "ext": "cshtml", "max_stars_repo_path": "KnockoutMvcDemo/Views/Home/QuickStart.cshtml", "max_stars_repo_name": "NigelWhatling/knockout-mvc", "max_stars_repo_stars_event_min_datetime": "2015-01-04T21:38:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T06:40:02.000Z", "max_issues_repo_path": "KnockoutMvcDemo/Views/Home/QuickStart.cshtml", "max_issues_repo_name": "NigelWhatling/knockout-mvc", "max_issues_repo_issues_event_min_datetime": "2015-03-16T14:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-04T18:07:32.000Z", "max_forks_repo_path": "KnockoutMvcDemo/Views/Home/QuickStart.cshtml", "max_forks_repo_name": "NigelWhatling/knockout-mvc", "max_forks_repo_forks_event_min_datetime": "2015-02-01T18:37:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T06:18:58.000Z"} | {"max_stars_count": 94.0, "max_issues_count": 8.0, "max_forks_count": 60.0, "avg_line_length": 35.6315789474, "max_line_length": 150, "alphanum_fraction": 0.6477104874} | @{
ViewBag.Title = "Quick start";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="well">
<h2>Quick start</h2>
<ul>
<li>Install <a href="https://nuget.org/packages/kMVC/">kMVC NuGet package</a></li>
<li>Add links to next js-files:
<pre class="prettyprint lang-xml">
<script src="@Url.Content("~/Scripts/jquery-x.y.z.min.js")" type="text/javascript"></script> <!-- Use your version of jQuery -->
<script src="@Url.Content("~/Scripts/knockout-x.y.z.js")" type="text/javascript"></script> <!-- Use your version of knockout -->
<script src="@Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/perpetuum.knockout.js")" type="text/javascript"></script></pre>
</li>
<li>Use next template for view:
<pre class="prettyprint lang-cs">
@using PerpetuumSoft.Knockout
@model <!-- You model -->
@{
var ko = Html.CreateKnockoutContext();
}
<!-- Your page -->
@ko.Apply(Model)</pre>
</li>
<li>Inherit your controller from <code>KnockoutController:</code>
<pre class="prettyprint lang-cs">
public class FooController : KnockoutController {
public ActionResult Index()
{
return View();
}
}</pre>
</li>
</ul>
</div>
|
||||
TheStack | dbf7d3f035f60656de1773156c59f93baf7ac0c3 | C#code:C# | {"size": 30794, "ext": "cs", "max_stars_repo_path": "chart/Statistical Analysis/Chart Utility Functions/CS/Form1.cs", "max_stars_repo_name": "aTiKhan/winforms-demos", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "chart/Statistical Analysis/Chart Utility Functions/CS/Form1.cs", "max_issues_repo_name": "aTiKhan/winforms-demos", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chart/Statistical Analysis/Chart Utility Functions/CS/Form1.cs", "max_forks_repo_name": "aTiKhan/winforms-demos", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 44.3717579251, "max_line_length": 330, "alphanum_fraction": 0.590212379} | using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Syncfusion.Windows.Forms.Chart;
using Syncfusion.Windows.Forms.Chart.Statistics;
using Syncfusion.Drawing;
using Syncfusion.Windows.Forms;
namespace ChartUtilityFunctions1
{
public class Form1 : Syncfusion.Windows.Forms.MetroForm
{
#region Private Members
private Syncfusion.Windows.Forms.Chart.ChartControl chartControl1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.ComboBox comboBox2;
private System.Windows.Forms.ComboBox comboBox3;
private System.Windows.Forms.ComboBox comboBox4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.Panel panel1;
private double doubleX;
private double y;
private double coef;
private double beta;
private double n;
private double m;
private ChartSeries series;
private Label label6;
private Label label7;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#endregion
#region Form's Constructor, Main And Dispose
public Form1()
{
//
// Required for Windows Form Designer support
//
BorderColor = Color.FromArgb(0xFF, 0xCD, 0xCD, 0xCD);
BorderThickness = 3;
CaptionBarHeight = (int)DpiAware.LogicalToDeviceUnits(75.0f);
CaptionBarColor = Color.FromArgb(0xFF, 0x1B, 0xA1, 0xE2);
CaptionFont = new Font("Segoe UI", 22.0f);
CaptionForeColor = Color.White;
CaptionAlign = HorizontalAlignment.Left;
ShowIcon = false;
CaptionButtonColor = Color.White;
CaptionButtonHoverColor = Color.White;
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(DemoCommon.FindLicenseKey());
Application.EnableVisualStyles();
Application.Run(new Form1());
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#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(Form1));
this.chartControl1 = new Syncfusion.Windows.Forms.Chart.ChartControl();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.comboBox3 = new System.Windows.Forms.ComboBox();
this.comboBox4 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// chartControl1
//
this.chartControl1.BackInterior = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.PathEllipse, System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))), System.Drawing.Color.White);
this.chartControl1.BorderAppearance.SkinStyle = Syncfusion.Windows.Forms.Chart.ChartBorderSkinStyle.Emboss;
this.chartControl1.ChartArea.BackInterior = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.Vertical, System.Drawing.Color.Transparent, System.Drawing.Color.Transparent);
this.chartControl1.ChartArea.CursorLocation = new System.Drawing.Point(0, 0);
this.chartControl1.ChartArea.CursorReDraw = false;
this.chartControl1.ChartArea.XAxesLayoutMode = Syncfusion.Windows.Forms.Chart.ChartAxesLayoutMode.SideBySide;
this.chartControl1.ChartArea.YAxesLayoutMode = Syncfusion.Windows.Forms.Chart.ChartAxesLayoutMode.SideBySide;
this.chartControl1.ChartAreaMargins = new Syncfusion.Windows.Forms.Chart.ChartMargins(10, 10, 20, 10);
this.chartControl1.ChartInterior = new Syncfusion.Drawing.BrushInfo(Syncfusion.Drawing.GradientStyle.PathRectangle, System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))), System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))));
this.chartControl1.DataSourceName = "";
this.chartControl1.ForeColor = System.Drawing.Color.Black;
this.chartControl1.IsWindowLess = false;
//
//
//
this.chartControl1.Legend.Font = new System.Drawing.Font("Verdana", 10F);
this.chartControl1.Legend.Location = new System.Drawing.Point(70, 476);
this.chartControl1.Legend.Orientation = Syncfusion.Windows.Forms.Chart.ChartOrientation.Horizontal;
this.chartControl1.Legend.Position = Syncfusion.Windows.Forms.Chart.ChartDock.Bottom;
this.chartControl1.Localize = null;
this.chartControl1.Location = new System.Drawing.Point(0, 0);
this.chartControl1.Name = "chartControl1";
this.chartControl1.PrimaryXAxis.Crossing = double.NaN;
this.chartControl1.PrimaryXAxis.Margin = true;
this.chartControl1.PrimaryYAxis.Crossing = double.NaN;
this.chartControl1.PrimaryYAxis.Margin = true;
this.chartControl1.Size = new System.Drawing.Size(700, 570);
this.chartControl1.TabIndex = 0;
this.chartControl1.Text = "Chart-Utility Function";
//
//
//
this.chartControl1.Title.Font = new System.Drawing.Font("Verdana", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(161)));
this.chartControl1.Title.Name = "Def_title";
this.chartControl1.Title.Text = "Chart-Utility Function";
this.chartControl1.Titles.Add(this.chartControl1.Title);
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBox1.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.comboBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.comboBox1.Location = new System.Drawing.Point(34, 93);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(191, 28);
this.comboBox1.TabIndex = 1;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// comboBox2
//
this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBox2.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.comboBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.comboBox2.Items.AddRange(new object[] {
"0.1",
"0.2",
"0.3",
"0.4",
"0.5",
"0.6",
"0.7",
"0.8",
"0.9",
"0.99"});
this.comboBox2.Location = new System.Drawing.Point(34, 159);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(191, 28);
this.comboBox2.TabIndex = 2;
this.comboBox2.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged);
//
// comboBox3
//
this.comboBox3.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBox3.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.comboBox3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.comboBox3.Items.AddRange(new object[] {
"2",
"3",
"4",
"5",
"8",
"10",
"15",
"20",
"30"});
this.comboBox3.Location = new System.Drawing.Point(35, 266);
this.comboBox3.Name = "comboBox3";
this.comboBox3.Size = new System.Drawing.Size(191, 28);
this.comboBox3.TabIndex = 3;
this.comboBox3.SelectedIndexChanged += new System.EventHandler(this.comboBox3_SelectedIndexChanged);
//
// comboBox4
//
this.comboBox4.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox4.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.comboBox4.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.comboBox4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.comboBox4.Items.AddRange(new object[] {
"2",
"3",
"4",
"5",
"8",
"10",
"15",
"20",
"30"});
this.comboBox4.Location = new System.Drawing.Point(35, 333);
this.comboBox4.Name = "comboBox4";
this.comboBox4.Size = new System.Drawing.Size(191, 28);
this.comboBox4.TabIndex = 4;
this.comboBox4.SelectedIndexChanged += new System.EventHandler(this.comboBox4_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label1.Location = new System.Drawing.Point(31, 130);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(81, 20);
this.label1.TabIndex = 5;
this.label1.Text = "Probability";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label2.Location = new System.Drawing.Point(30, 203);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(182, 25);
this.label2.TabIndex = 6;
this.label2.Text = "Degrees of Freedom";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label3.Location = new System.Drawing.Point(32, 239);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(20, 20);
this.label3.TabIndex = 7;
this.label3.Text = "N";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label4.Location = new System.Drawing.Point(32, 306);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(22, 20);
this.label4.TabIndex = 8;
this.label4.Text = "M";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label5.Location = new System.Drawing.Point(32, 441);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(52, 20);
this.label5.TabIndex = 9;
this.label5.Text = "Values";
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.Color.DarkGray;
this.textBox1.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.textBox1.Location = new System.Drawing.Point(33, 474);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(191, 27);
this.textBox1.TabIndex = 10;
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.checkBox1.Location = new System.Drawing.Point(36, 375);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(156, 24);
this.checkBox1.TabIndex = 11;
this.checkBox1.Text = "Inverse Distribution";
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.checkBox2.Location = new System.Drawing.Point(36, 406);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(83, 24);
this.checkBox2.TabIndex = 12;
this.checkBox2.Text = "One Tail";
//
// panel1
//
this.panel1.Dock = DockStyle.Right;
this.panel1.AutoScroll = true;
this.panel1.AutoSize = true;
this.panel1.BackColor = System.Drawing.Color.WhiteSmoke;
this.panel1.Controls.Add(this.label6);
this.panel1.Controls.Add(this.label7);
this.panel1.Controls.Add(this.comboBox4);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.checkBox2);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.comboBox1);
this.panel1.Controls.Add(this.comboBox2);
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.comboBox3);
this.panel1.Controls.Add(this.checkBox1);
this.panel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.panel1.Location = new System.Drawing.Point(700, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(260, 585);
this.panel1.TabIndex = 13;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label6.Location = new System.Drawing.Point(31, 64);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(93, 20);
this.label6.TabIndex = 14;
this.label6.Text = "Distributions";
//
// label7
//
this.label7.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(66)))), ((int)(((byte)(66)))), ((int)(((byte)(66)))));
this.label7.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.label7.Location = new System.Drawing.Point(31, 30);
this.label7.Name = "label7";
this.label7.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.label7.Size = new System.Drawing.Size(161, 24);
this.label7.TabIndex = 13;
this.label7.Text = "Utitlity Functions";
this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// Form1
//
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(954, 581);
this.Controls.Add(this.chartControl1);
this.Controls.Add(this.panel1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(712, 400);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Utility Functions";
this.Load += new System.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Form Load
private void Form1_Load(object sender, System.EventArgs e)
{
this.comboBox1.Items.Add("Normal Distribution");
this.comboBox1.Items.Add("T Cumulative Distribution");
this.comboBox1.Items.Add("F Cumulative Distribution");
this.comboBox1.SelectedIndex = 0;
this.comboBox2.SelectedIndex = 0;
this.comboBox3.SelectedIndex = 0;
this.comboBox4.SelectedIndex = 0;
ChartAppearance.ApplyChartStyles(this.chartControl1);
this.chartControl1.Dock = DockStyle.Fill;
}
#endregion
#region Helper Methods
#region NormalDistribution
/// <summary>
/// Updates Normal Distribution chart based on the changed values.
/// </summary>
protected void FillNDistribution()
{
double values = 0.0;
if (!this.checkBox1.Checked)
values = UtilityFunctions.NormalDistribution(Convert.ToDouble(this.comboBox2.SelectedItem));
else
values = UtilityFunctions.InverseNormalDistribution(Convert.ToDouble(this.comboBox2.SelectedItem));
this.textBox1.Text = values.ToString("G5");
}
protected void InitializeNormalDistributionChart()
{
this.chartControl1.Series.Clear();
//Initializes the Normal distribution series.
series = new ChartSeries();
series.Name = "Normal Distribution";
series.Type = ChartSeriesType.SplineArea;
series.Text = series.Name;
coef = 1.0 / Math.Sqrt(2 * Math.PI);
for (int x = -50; x <= 50; x++)
{
doubleX = x / 10.0;
y = coef * Math.Exp(doubleX * doubleX / -2);
//Add the data points to the series.
series.Points.Add(doubleX - 0.05, y);
}
series.Style.Border.Color = Color.Transparent;
//Add the series to the chart series collection.
this.chartControl1.Series.Add(series);
}
#endregion
#region TDistribution
/// <summary>
/// Updates the T Distribution chart based on the changed values.
/// </summary>
protected void FillTDistribution()
{
double values = 0.0;
if (!this.checkBox1.Checked)
values = UtilityFunctions.TCumulativeDistribution(double.Parse(this.comboBox2.SelectedItem.ToString()), double.Parse(this.comboBox3.SelectedItem.ToString()), this.checkBox2.Checked);
else
values = UtilityFunctions.InverseTCumulativeDistribution(double.Parse(this.comboBox2.SelectedItem.ToString()), double.Parse(this.comboBox3.SelectedItem.ToString()), this.checkBox2.Checked);
this.textBox1.Text = values.ToString("G5");
}
protected void InitializeTDistributionChart()
{
this.chartControl1.Series.Clear();
//Initializes the T distribution series.
series = new ChartSeries();
series.Name = "T Distribution";
series.Type = ChartSeriesType.SplineArea;
series.Text = series.Name;
//Set the degree of freedom.
n = double.Parse(this.comboBox3.SelectedItem.ToString());
//Calculates the Beta function.
beta = UtilityFunctions.Beta(0.5, n / 2.0);
// Calculate coefficient of T Distribution.
coef = Math.Pow(n, -0.5) / beta;
// Calculate Data Points
for (int x = -120; x <= 120; x++)
{
doubleX = x / 10.0;
y = coef / Math.Pow(1.0 + doubleX * doubleX / n, (n + 1.0) / 2.0);
//Add data points to the series.
series.Points.Add(doubleX, y);
}
series.Style.Border.Color = Color.Transparent;
//Add the series to the chart series collection.
this.chartControl1.Series.Add(series);
}
#endregion
#region FDistribution
/// <summary>
/// Updates the F Distribution chart based on the changed values.
/// </summary>
protected void FillFDistribution()
{
double values = 0.0;
if (this.comboBox2.Text != "" && this.comboBox3.Text != "" && this.comboBox4.Text != "")
{
if (!this.checkBox1.Checked)
values = UtilityFunctions.FCumulativeDistribution(double.Parse(this.comboBox2.SelectedItem.ToString()), double.Parse(this.comboBox3.SelectedItem.ToString()), double.Parse(this.comboBox4.SelectedItem.ToString()));
else
values = UtilityFunctions.InverseFCumulativeDistribution(double.Parse(this.comboBox2.SelectedItem.ToString()), double.Parse(this.comboBox3.SelectedItem.ToString()), double.Parse(this.comboBox4.SelectedItem.ToString()));
}
this.textBox1.Text = values.ToString("G5");
}
/// <summary>
/// Initializes F distribution chart.
/// </summary>
protected void InitializeFDistributionChart()
{
this.chartControl1.Series.Clear();
//Initializes the F distribution series.
series = new ChartSeries();
series.Name = "F Distribution";
series.Type = ChartSeriesType.SplineArea;
series.Text = series.Name;
// Set degrees of freedom
n = double.Parse(comboBox3.SelectedItem.ToString());
m = double.Parse(comboBox4.SelectedItem.ToString());
// Calculate the Beta function
beta = UtilityFunctions.Beta(n / 2.0, m / 2.0);
// Find coefficient
coef = Math.Pow(n / m, n / 2.0) / beta;
// Go through all data points and calculate values
for (double x = 0.01; x <= 15; x += 0.1)
{
doubleX = x;
y = coef * (Math.Pow(doubleX, n / 2.0 - 1.0) / Math.Pow(1.0 + n * doubleX / m, (n + m) / 2.0));
// Add data points to the series.
series.Points.Add(doubleX, y);
}
series.Style.Border.Color = Color.Transparent;
//Add the series to the chart series collection.
this.chartControl1.Series.Add(series);
}
#endregion
#region DisplayChart
/// <summary>
/// Displays the distribution chart based on the selected value.
/// </summary>
protected void DisplayChart()
{
switch (this.comboBox1.SelectedItem.ToString())
{
case "Normal Distribution":
InitializeNormalDistributionChart();
this.comboBox3.Enabled = false;
this.comboBox4.Enabled = false;
this.checkBox2.Enabled = true;
this.label3.ForeColor = Color.Gray;
this.label4.ForeColor = Color.Gray;
FillNDistribution();
break;
case "T Cumulative Distribution":
InitializeTDistributionChart();
this.comboBox3.Enabled = true;
this.comboBox4.Enabled = false;
this.checkBox2.Enabled = true;
this.label4.ForeColor = Color.Gray;
this.label3.ForeColor = SystemColors.ControlText;
FillTDistribution();
break;
case "F Cumulative Distribution":
InitializeFDistributionChart();
this.comboBox3.Enabled = true;
this.comboBox4.Enabled = true;
this.checkBox2.Enabled = false;
this.label4.ForeColor = SystemColors.ControlText;
this.label3.ForeColor = SystemColors.ControlText;
FillFDistribution();
break;
default:
InitializeNormalDistributionChart();
break;
}
}
#endregion
#endregion
#region Events
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DisplayChart();
}
private void comboBox2_SelectedIndexChanged(object sender, System.EventArgs e)
{
DisplayChart();
}
private void comboBox3_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(this.comboBox1.SelectedItem.ToString() == "T Cumulative Distribution")
{
DisplayChart();
FillTDistribution();
}
else if(this.comboBox1.SelectedItem.ToString() == "F Cumulative Distribution")
{
if (comboBox4.Text != "")
InitializeFDistributionChart();
FillFDistribution();
}
}
private void comboBox4_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(this.comboBox1.SelectedItem.ToString() == "T Cumulative Distribution")
{
DisplayChart();
FillTDistribution();
}
else if(this.comboBox1.SelectedItem.ToString() == "F Cumulative Distribution")
{
if (comboBox3.Text != "")
InitializeFDistributionChart();
FillFDistribution();
}
}
#endregion
}
/// <summary>
/// Represents a class that is used to find the licensing file for Syncfusion controls.
/// </summary>
public class DemoCommon
{
/// <summary>
/// Finds the license key from the Common folder.
/// </summary>
/// <returns>Returns the license key.</returns>
public static string FindLicenseKey()
{
string licenseKeyFile = "..\\Common\\SyncfusionLicense.txt";
for (int n = 0; n < 20; n++)
{
if (!System.IO.File.Exists(licenseKeyFile))
{
licenseKeyFile = @"..\" + licenseKeyFile;
continue;
}
return System.IO.File.ReadAllText(licenseKeyFile);
}
return string.Empty;
}
}
}
|
||||
TheStack | dbf7dc8b87625878c8a869ce2d1cc63d37293dd3 | C#code:C# | {"size": 763, "ext": "cs", "max_stars_repo_path": "src/ExpectedObjects.Specs/TypeMismatchSpecs.cs", "max_stars_repo_name": "nsarris/expectedObjects", "max_stars_repo_stars_event_min_datetime": "2020-05-02T01:55:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-02T01:55:36.000Z", "max_issues_repo_path": "src/ExpectedObjects.Specs/TypeMismatchSpecs.cs", "max_issues_repo_name": "nsarris/expectedObjects", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ExpectedObjects.Specs/TypeMismatchSpecs.cs", "max_forks_repo_name": "nsarris/expectedObjects", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.6129032258, "max_line_length": 91, "alphanum_fraction": 0.5504587156} | using System;
using ExpectedObjects.Specs.TestTypes;
using Machine.Specifications;
namespace ExpectedObjects.Specs
{
public class when_comparing_mismatch_types
{
static ExpectedObject _expected;
static SimpleType _actual;
static Exception _exception;
Establish context = () =>
{
_expected = new
{
StringProperty = 1
}.ToExpectedObject();
_actual = new SimpleType
{
StringProperty = "1"
};
};
Because of = () => _exception = Catch.Exception(() => _expected.Matches(_actual));
It should_not_throw_an_exception = () => _exception.ShouldBeNull();
}
} |
||||
TheStack | dbf9ea03c7ec3544f875ba17b23a286d138088fc | C#code:C# | {"size": 310, "ext": "cs", "max_stars_repo_path": "src/Horse.Mvc/Auth/AnonymousAttribute.cs", "max_stars_repo_name": "horse-framework/horse-http", "max_stars_repo_stars_event_min_datetime": "2020-07-12T18:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-12T08:13:06.000Z", "max_issues_repo_path": "src/Horse.Mvc/Auth/AnonymousAttribute.cs", "max_issues_repo_name": "twino-framework/twino-mvc", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Horse.Mvc/Auth/AnonymousAttribute.cs", "max_forks_repo_name": "twino-framework/twino-mvc", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.8461538462, "max_line_length": 70, "alphanum_fraction": 0.6838709677} | using System;
namespace Horse.Mvc.Auth
{
/// <summary>
/// Authorization attribute for Horse MVC.
/// Can be used for controllers and actions.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AllowAnonymousAttribute : Attribute
{ }
}
|
||||
TheStack | dbfacf829a78c7575acd6b25f9b761e06a2eb91c | C#code:C# | {"size": 1094, "ext": "cs", "max_stars_repo_path": "src/Geo.MapQuest/Models/Responses/Response.cs", "max_stars_repo_name": "JustinCanton/Geo.NET", "max_stars_repo_stars_event_min_datetime": "2022-01-07T06:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T19:36:32.000Z", "max_issues_repo_path": "src/Geo.MapQuest/Models/Responses/Response.cs", "max_issues_repo_name": "JustinCanton/Geo.NET", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geo.MapQuest/Models/Responses/Response.cs", "max_forks_repo_name": "JustinCanton/Geo.NET", "max_forks_repo_forks_event_min_datetime": "2022-01-07T03:07:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:36:36.000Z"} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 29.5675675676, "max_line_length": 106, "alphanum_fraction": 0.5904936015} | // <copyright file="Response.cs" company="Geo.NET">
// Copyright (c) Geo.NET.
// Licensed under the MIT license. See the LICENSE file in the solution root for full license information.
// </copyright>
namespace Geo.MapQuest.Models.Responses
{
using System.Collections.Generic;
using Newtonsoft.Json;
/// <summary>
/// The response from a MapQuest request.
/// </summary>
/// <typeparam name="T">The type of request result.</typeparam>
public class Response<T>
where T : class
{
/// <summary>
/// Gets or sets the information related to the request.
/// </summary>
[JsonProperty("info")]
public Information Information { get; set; }
/// <summary>
/// Gets or sets the options related to the request.
/// </summary>
[JsonProperty("options")]
public Options Options { get; set; }
/// <summary>
/// Gets the results from the request.
/// </summary>
[JsonProperty("results")]
public IList<T> Results { get; } = new List<T>();
}
}
|
||||
TheStack | dbfc487cc021091906442c3c0c7778a35155d4dd | C#code:C# | {"size": 3707, "ext": "cs", "max_stars_repo_path": "Components/TimesheetsTests/TimeEntryControllerTest.cs", "max_stars_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Components/TimesheetsTests/TimeEntryControllerTest.cs", "max_issues_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Components/TimesheetsTests/TimeEntryControllerTest.cs", "max_forks_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.8265306122, "max_line_length": 117, "alphanum_fraction": 0.59374157} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Timesheets;
using Timesheets.Data;
using Timesheets.ProjectClient;
using Xunit;
namespace TimesheetsTests
{
public class TimeEntryControllerTest
{
private readonly Mock<ITimeEntryDataGateway> _gateway;
private readonly Mock<IProjectClient> _client;
private readonly TimeEntryController _controller;
public TimeEntryControllerTest()
{
_gateway = new Mock<ITimeEntryDataGateway>();
_client = new Mock<IProjectClient>();
_controller = new TimeEntryController(_gateway.Object, _client.Object);
}
[Fact]
public void TestPost()
{
_gateway.Setup(g => g.Create(55432, 4765, DateTime.Parse("2015-05-17"), 8))
.Returns(new TimeEntryRecord(1234, 55432, 4765, DateTime.Parse("2015-05-17"), 8));
_client.Setup(c => c.Get(55432)).Returns(Task.FromResult(new ProjectInfo(true)));
var response = _controller.Post(new TimeEntryInfo(-1, 55432, 4765, DateTime.Parse("2015-05-17"), 8, ""));
var body = (TimeEntryInfo) ((ObjectResult) response).Value;
Assert.IsType<CreatedResult>(response);
Assert.Equal(1234, body.Id);
Assert.Equal(55432, body.ProjectId);
Assert.Equal(4765, body.UserId);
Assert.Equal(17, body.Date.Day);
Assert.Equal(5, body.Date.Month);
Assert.Equal(2015, body.Date.Year);
Assert.Equal(8, body.Hours);
Assert.Equal("entry info", body.Info);
}
[Fact]
public void TestPost_InactiveProject()
{
_gateway.Setup(g => g.Create(55432, 4765, DateTime.Parse("2015-05-17"), 8))
.Returns(new TimeEntryRecord(1234, 55432, 4765, DateTime.Parse("2015-05-17"), 8));
_client.Setup(c => c.Get(55432)).Returns(Task.FromResult(new ProjectInfo(false)));
var response = _controller.Post(new TimeEntryInfo(-1, 55432, 4765, DateTime.Parse("2015-05-17"), 8, ""));
Assert.IsType<StatusCodeResult>(response);
Assert.Equal(304, ((StatusCodeResult) response).StatusCode);
}
[Fact]
public void TestGet()
{
_gateway.Setup(g => g.FindBy(4765)).Returns(new List<TimeEntryRecord>
{
new TimeEntryRecord(1234, 55432, 4765, DateTime.Parse("2015-05-17"), 8),
new TimeEntryRecord(5678, 55433, 4765, DateTime.Parse("2015-05-18"), 6)
});
var response = _controller.Get(4765);
var body = (List<TimeEntryInfo>) ((ObjectResult) response).Value;
Assert.IsType<OkObjectResult>(response);
Assert.Equal(2, ((List<TimeEntryInfo>) ((ObjectResult) response).Value).Count);
Assert.Equal(1234, body[0].Id);
Assert.Equal(55432, body[0].ProjectId);
Assert.Equal(4765, body[0].UserId);
Assert.Equal(17, body[0].Date.Day);
Assert.Equal(5, body[0].Date.Month);
Assert.Equal(2015, body[0].Date.Year);
Assert.Equal(8, body[0].Hours);
Assert.Equal("entry info", body[0].Info);
Assert.Equal(5678, body[1].Id);
Assert.Equal(55433, body[1].ProjectId);
Assert.Equal(4765, body[1].UserId);
Assert.Equal(18, body[1].Date.Day);
Assert.Equal(5, body[1].Date.Month);
Assert.Equal(2015, body[1].Date.Year);
Assert.Equal(6, body[1].Hours);
Assert.Equal("entry info", body[1].Info);
}
}
} |
||||
TheStack | dbfd156928db22f9229cf487c9e2e26700e6317d | C#code:C# | {"size": 4135, "ext": "cs", "max_stars_repo_path": "tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Elasticsearch/V7/Transport_RequestAsync_Integration.cs", "max_stars_repo_name": "rnburn/dd-trace-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Elasticsearch/V7/Transport_RequestAsync_Integration.cs", "max_issues_repo_name": "rnburn/dd-trace-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Elasticsearch/V7/Transport_RequestAsync_Integration.cs", "max_forks_repo_name": "rnburn/dd-trace-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 50.4268292683, "max_line_length": 250, "alphanum_fraction": 0.6822249093} | // <copyright file="Transport_RequestAsync_Integration.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
using System;
using System.ComponentModel;
using System.Threading;
using Datadog.Trace.ClrProfiler.CallTarget;
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Elasticsearch.V7
{
/// <summary>
/// Elasticsearch.Net.RequestPipeline.CallElasticsearchAsync<T> calltarget instrumentation
/// </summary>
[InstrumentMethod(
AssemblyName = ElasticsearchV7Constants.ElasticsearchAssemblyName,
TypeName = ElasticsearchV7Constants.TransportTypeName,
MethodName = "RequestAsync",
ReturnTypeName = ClrNames.GenericParameterTask,
ParameterTypeNames = new[] { "Elasticsearch.Net.HttpMethod", ClrNames.String, ClrNames.CancellationToken, "Elasticsearch.Net.PostData", "Elasticsearch.Net.IRequestParameters" },
MinimumVersion = ElasticsearchV7Constants.Version7,
MaximumVersion = ElasticsearchV7Constants.Version7,
IntegrationName = ElasticsearchV7Constants.IntegrationName)]
// ReSharper disable once InconsistentNaming
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public class Transport_RequestAsync_Integration
{
/// <summary>
/// OnMethodBegin callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="THttpMethod">The type of the HttpMethod parameter</typeparam>
/// <typeparam name="TPostData">The type of the PostData parameter</typeparam>
/// <typeparam name="TRequestParameters">The type of the request parameters</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="method">The HTTP method of the request</param>
/// <param name="path">The path of the request</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="postData">The payload of the request</param>
/// <param name="requestParameters">The parameters of the request</param>
/// <returns>Calltarget state value</returns>
public static CallTargetState OnMethodBegin<TTarget, THttpMethod, TPostData, TRequestParameters>(TTarget instance, THttpMethod method, string path, CancellationToken cancellationToken, TPostData postData, TRequestParameters requestParameters)
{
var scope = ElasticsearchNetCommon.CreateScope(Tracer.Instance, ElasticsearchV7Constants.IntegrationId, path, method.ToString(), requestParameters, out var tags);
return new CallTargetState(scope, tags);
}
/// <summary>
/// OnAsyncMethodEnd callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <typeparam name="TResponse">Type of the response</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="response">The response</param>
/// <param name="exception">Exception instance in case the original code threw an exception.</param>
/// <param name="state">Calltarget state value</param>
/// <returns>A response value, in an async scenario will be T of Task of T</returns>
public static TResponse OnAsyncMethodEnd<TTarget, TResponse>(TTarget instance, TResponse response, Exception exception, CallTargetState state)
where TResponse : IElasticsearchResponse
{
var uri = response?.ApiCall?.Uri?.ToString();
if (uri != null)
{
var tags = (ElasticsearchTags)state.State;
if (tags != null)
{
tags.Url = uri;
}
}
state.Scope.DisposeWithException(exception);
return response;
}
}
}
|
||||
TheStack | dbfd4804ccce89e3b0fbcd7dddf1ec2f7ad90cb6 | C#code:C# | {"size": 982, "ext": "cs", "max_stars_repo_path": "src/Braco.Generator/AppInitializer.cs", "max_stars_repo_name": "HorvatJosip/Braco", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Braco.Generator/AppInitializer.cs", "max_issues_repo_name": "HorvatJosip/Braco", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Braco.Generator/AppInitializer.cs", "max_forks_repo_name": "HorvatJosip/Braco", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.55, "max_line_length": 72, "alphanum_fraction": 0.715885947} | using Braco.Services;
using Braco.Utilities.Wpf;
namespace Braco.Generator
{
class AppInitializer : Initializer
{
public AppInitializer() : base(addEverything: false)
{
AddServiceSetups
(
// Braco.Services
typeof(FileConfigurationServiceSetup),
typeof(FileManagerSetup),
typeof(MapperSetup),
typeof(ResourceManagerSetup),
typeof(SecurityServiceSetup),
typeof(WindowsProcessStarterSetup),
// Braco.Utilities.Wpf
typeof(ChooserDialogsServiceSetup),
typeof(ImageGetterSetup),
typeof(LocalizedCollectionsSetup),
typeof(ToolTipGetterSetup),
typeof(ViewModelsSetup),
typeof(WindowsManagerSetup),
typeof(WpfDictionaryLocalizerSetup),
typeof(WpfMethodServiceSetup),
// Custom
typeof(AssemblyGetterSetup),
typeof(ProjectManagerSetup),
typeof(MainWindowViewModelSetup)
);
AddPostServiceBuildInitializers(typeof(ResourceManagerInitializer));
}
}
}
|
||||
TheStack | dbfe189c7aba29b5e3a06803b4b0b09de14801b6 | C#code:C# | {"size": 11302, "ext": "cs", "max_stars_repo_path": "Agile.NET-Deobfuscator-DNLIB/Protections/StringDecryptionModule.cs", "max_stars_repo_name": "little3388/Agile.NET-Deobfuscator", "max_stars_repo_stars_event_min_datetime": "2020-07-08T23:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:11:58.000Z", "max_issues_repo_path": "Agile.NET-Deobfuscator-DNLIB/Protections/StringDecryptionModule.cs", "max_issues_repo_name": "little3388/Agile.NET-Deobfuscator", "max_issues_repo_issues_event_min_datetime": "2020-10-11T23:20:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T06:50:09.000Z", "max_forks_repo_path": "Agile.NET-Deobfuscator-DNLIB/Protections/StringDecryptionModule.cs", "max_forks_repo_name": "little3388/Agile.NET-Deobfuscator", "max_forks_repo_forks_event_min_datetime": "2020-07-10T07:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T10:08:54.000Z"} | {"max_stars_count": 75.0, "max_issues_count": 11.0, "max_forks_count": 28.0, "avg_line_length": 58.2577319588, "max_line_length": 210, "alphanum_fraction": 0.4584144399} | using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Agile.NET_Deobfuscator_DNLIB.Protections
{
public class StringDecryption
{
private static int decrypted = 0;
public static void Execute()
{
try
{
if (Globals.IsDLL)//Check to see if the file is a dll or not this is important so it can identify the correct names/values
{
byte[] byteInit = GetArrayInitDll();//Get the initialize array for the strings in the dll
if (byteInit != null)//if the array does not equal null/nothing
{
foreach (ModuleDef module in Globals.ASM.Modules)//Go through all the modules in the assembly
{
foreach (TypeDef type in module.GetTypes())//Go through all the types in the module
{
foreach (MethodDef method in type.Methods)//Go through all the methods in the type
{
if (method.HasBody && method.Body.HasInstructions)//if the method has a valid body and instructions in it
{
for (int i = 0; i < method.Body.Instructions.Count; i++)//Go through all the instructions in the method
{
var Ins = method.Body.Instructions[i];
if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr &&
method.Body.Instructions[i + 1].OpCode == OpCodes.Call//Here is where we find the encoded string
&& method.Body.Instructions[i + 1].Operand.ToString().Contains("2XY="))//This might change in new updates.
{ //We dont need the extra check for the method name but having it ensures that its accurate.
string operand = method.Body.Instructions[i].Operand.ToString();//Get the encoded string
string decypted = DecryptStringAgile6(operand, byteInit);//decrypt the string with the function
if (decypted != null)//if the returned decrypted string does not equal to null or nothing
{
method.Body.Instructions[i].Operand = decypted;//replace the encoded string with the decrypted one
method.Body.Instructions[i + 1].OpCode = OpCodes.Nop;//Nop the useless call to the decryption method
decrypted++;//Add 1 to the decrypted count
}
}
}
}
}
}
}
}
else
{
//Contact for me to update in future update
}
}
else//if the file is a exe
{
byte[] byteInit = GetArrayInitExe();//Get the initialize array for the strings in the exe
if (byteInit != null)//if the array does not equal null/nothing
{
foreach (ModuleDef module in Globals.ASM.Modules)//Go through all the modules in the assembly
{
foreach (TypeDef type in module.GetTypes())//Go through all the types and nested types in the module
{
foreach (MethodDef method in type.Methods)//Go through all the methods in the type
{
if (method.HasBody && method.Body.HasInstructions)//Check to see if the method has a valid body with instructions
{
for (int i = 0; i < method.Body.Instructions.Count; i++)//Go through all the instructions in the method
{
var Ins = method.Body.Instructions[i];
if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr &&
method.Body.Instructions[i + 1].OpCode == OpCodes.Call//Here is where we find the encoded string
&& method.Body.Instructions[i + 1].Operand.ToString().Contains("oRM="))//This might change in new updates.
{ //We dont need the extra check for the method name but having it ensures that its accurate.
string operand = method.Body.Instructions[i].Operand.ToString();//Get the encoded string
string decypted = DecryptStringAgile6(operand, byteInit);//decrypt the encrypted string with the function
if (decypted != null)//if the decrpyted string not equals null or nothing
{
method.Body.Instructions[i].Operand = decypted;//replace the encoded string with the decrypted one
method.Body.Instructions[i + 1].OpCode = OpCodes.Nop;//Nop the useless call to the decryption method
decrypted++;//Add 1 to the decrypted count
}
}
}
}
}
}
}
}
else
{
}
}//EXE
}
catch (Exception ex)// any problems are printed
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("[-] Looks like something bad happened in the string-decryption phase : {0}", ex.Message));
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(string.Format("[+] Decrypted {0} encoded strings", decrypted));
}
private static byte[] GetArrayInitExe()
{
FieldDef initField = null;
byte[] byteKey = null;
foreach (ModuleDef module in Globals.ASM.Modules)//Go through all the modules in the assembly
{
foreach (TypeDef type in module.GetTypes())//Go through all the types in the module
{
if (type.Name == "<AgileDotNetRT>")//if the type name is <AgileDotNetRT> we go into it
{
foreach (FieldDef field in type.Fields)//Go through all the fields in the type
{
if (field.Name == "pRM=")//if we find a field with this name we set it to our variable.
{ // this name might change in newer updates
initField = field;
}
}
}
}
}
if(initField == null)//if it wasnt found its a sign of no string encryption or it failed for other reasons
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[?] Initialize field not found for string decryption");
return null;
}
//First defualt way
byteKey = initField.InitialValue;//We grab the value using default dnlib
if(byteKey == null)//if it is equal to null or nothing
{
//Reflection alternative we use reflection to get it instead!
var info = Globals.ASMREF.ManifestModule.ResolveField(initField.MDToken.ToInt32());
byteKey = (byte[])info.GetValue(null);
}
return byteKey;
}
private static byte[] GetArrayInitDll()
{
FieldDef initField = null;
byte[] byteKey = null;
foreach (ModuleDef module in Globals.ASM.Modules)//Go through all the modules in the assembly
{
foreach (TypeDef type in module.GetTypes())//Go through all the types and nested types in the module
{
if (type.Name == "<AgileDotNetRT>")//if the type name is equal to <AgileDotNetRT> we go into it
{
foreach (FieldDef field in type.Fields)//Go through all the fields in the type
{
if (field.Name == "3XY=")//if the field name is equal to this value we set it to out variable
{ //this value may again change in newer updates
initField = field;
}
}
}
}
}
if (initField == null)//if it wasnt found its a sign of no string encryption or it failed for other reasons
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[?] Initialize field not found for string decryption");
return null;
}
//First defualt way
byteKey = initField.InitialValue;
if (byteKey == null)
{
//Reflection alternative we use reflection to get it instead!
var info = Globals.ASMREF.ManifestModule.ResolveField(initField.MDToken.ToInt32());
byteKey = (byte[])info.GetValue(null);
}
return byteKey;
}
private static string DecryptStringAgile6(string A_0, byte[] arr)//Latest i believe of Agile.NET, let me know if it is not so i can update.
{ //Simply copied the method from the runtime of agile and simplified it as well as replaced the variables
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < A_0.Length; i++)
{
stringBuilder.Append(Convert.ToChar((int)(A_0[i] ^ (char)arr[i % arr.Length])));
}
return stringBuilder.ToString();
}
}
}
|
||||
TheStack | dbfedbaf5e2cbef4dcae85ffc55b22a48691886a | C#code:C# | {"size": 368, "ext": "cs", "max_stars_repo_path": "test/Exercism.Representers.CSharp.IntegrationTests/Solutions/DictionaryInitializations/ObjectInitWithNestedArgs/Fake.cs", "max_stars_repo_name": "exercism-bot/csharp-representer", "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-27T15:04:07.000Z", "max_issues_repo_path": "test/Exercism.Representers.CSharp.IntegrationTests/Solutions/DictionaryInitializations/ObjectInitWithNestedArgs/Fake.cs", "max_issues_repo_name": "exercism-bot/csharp-representer", "max_issues_repo_issues_event_min_datetime": "2019-11-21T15:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T01:32:08.000Z", "max_forks_repo_path": "test/Exercism.Representers.CSharp.IntegrationTests/Solutions/DictionaryInitializations/ObjectInitWithNestedArgs/Fake.cs", "max_forks_repo_name": "FaisalAfroz/csharp-representer", "max_forks_repo_forks_event_min_datetime": "2019-11-03T11:24:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T08:33:45.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 20.0, "max_forks_count": 5.0, "avg_line_length": 33.4545454545, "max_line_length": 77, "alphanum_fraction": 0.6820652174} | using System;
using System.Collections.Generic;
using System.Reflection;
public class Fake
{
Dictionary<Dictionary<long, DateTime>, Dictionary<byte, short>> dict
= new Dictionary<Dictionary<long, DateTime>, Dictionary<byte, short>>
{[new Dictionary<long, DateTime> {[1L] = DateTime.Now}] =
new Dictionary<byte,short> {[42] = 1729}};
} |
||||
TheStack | dbff1b43fb73c66d59236f74768f0a252bd438b9 | C#code:C# | {"size": 12962, "ext": "cs", "max_stars_repo_path": "Plugin/Util.cs", "max_stars_repo_name": "FNKGino/poderosa", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugin/Util.cs", "max_issues_repo_name": "FNKGino/poderosa", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugin/Util.cs", "max_forks_repo_name": "FNKGino/poderosa", "max_forks_repo_forks_event_min_datetime": "2018-11-14T14:42:19.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-14T14:42:19.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 33.6675324675, "max_line_length": 137, "alphanum_fraction": 0.534099676} | /*
* Copyright 2004,2006 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: Util.cs,v 1.4 2012/03/17 14:34:23 kzmi Exp $
*/
using System;
using System.Diagnostics;
using System.Collections;
using System.Text;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
//using Microsoft.JScript;
using System.CodeDom.Compiler;
#if UNITTEST
using System.Configuration;
using NUnit.Framework;
#endif
using Poderosa.Boot;
namespace Poderosa {
/// <summary>
/// <ja>
/// 標準的な成功/失敗を示します。
/// </ja>
/// <en>
/// A standard success/failure is shown.
/// </en>
/// </summary>
public enum GenericResult {
/// <summary>
/// <ja>成功しました</ja>
/// <en>Succeeded</en>
/// </summary>
Succeeded,
/// <summary>
/// <ja>失敗しました</ja>
/// <en>Failed</en>
/// </summary>
Failed
}
//Debug.WriteLineIfあたりで使用
/// <summary>
///
/// </summary>
/// <exclude/>
public static class DebugOpt {
#if DEBUG
public static bool BuildToolBar = false;
public static bool CommandPopup = false;
public static bool DrawingPerformance = false;
public static bool DumpDocumentRelation = false;
public static bool IntelliSense = false;
public static bool IntelliSenseMenu = false;
public static bool LogViewer = false;
public static bool Macro = false;
public static bool MRU = false;
public static bool PromptRecog = false;
public static bool Socket = false;
public static bool SSH = false;
public static bool ViewManagement = false;
public static bool WebBrowser = false;
#else //RELEASE
public static bool BuildToolBar = false;
public static bool CommandPopup = false;
public static bool DrawingPerformance = false;
public static bool DumpDocumentRelation = false;
public static bool IntelliSense = false;
public static bool IntelliSenseMenu = false;
public static bool LogViewer = false;
public static bool Macro = false;
public static bool MRU = false;
public static bool PromptRecog = false;
public static bool Socket = false;
public static bool SSH = false;
public static bool ViewManagement = false;
public static bool WebBrowser = false;
#endif
}
/// <summary>
///
/// </summary>
/// <exclude/>
public static class RuntimeUtil {
public static void ReportException(Exception ex) {
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
string errorfile = ReportExceptionToFile(ex);
//メッセージボックスで通知。
//だがこの中で例外が発生することがSP1ではあるらしい。しかもそうなるとアプリが強制終了だ。
//Win32のメッセージボックスを出しても同じ。ステータスバーなら大丈夫のようだ
try {
string msg = String.Format(InternalPoderosaWorld.Strings.GetString("Message.Util.InternalError"), errorfile, ex.Message);
MessageBox.Show(msg, "Poderosa", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception ex2) {
Debug.WriteLine("(MessageBox.Show() failed) " + ex2.Message);
Debug.WriteLine(ex2.StackTrace);
}
}
public static void SilentReportException(Exception ex) {
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
ReportExceptionToFile(ex);
}
public static void DebuggerReportException(Exception ex) {
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
}
//ファイル名を返す
private static string ReportExceptionToFile(Exception ex) {
string errorfile = null;
//エラーファイルに追記
StreamWriter sw = null;
try {
sw = GetErrorLog(ref errorfile);
ReportExceptionToStream(ex, sw);
}
finally {
if (sw != null)
sw.Close();
}
return errorfile;
}
private static void ReportExceptionToStream(Exception ex, StreamWriter sw) {
sw.WriteLine(DateTime.Now.ToString());
sw.WriteLine(ex.Message);
sw.WriteLine(ex.StackTrace);
//inner exceptionを順次
Exception i = ex.InnerException;
while (i != null) {
sw.WriteLine("[inner] " + i.Message);
sw.WriteLine(i.StackTrace);
i = i.InnerException;
}
}
private static StreamWriter GetErrorLog(ref string errorfile) {
errorfile = PoderosaStartupContext.Instance.ProfileHomeDirectory + "error.log";
return new StreamWriter(errorfile, true/*append!*/, Encoding.Default);
}
public static Font CreateFont(string name, float size) {
try {
return new Font(name, size);
}
catch (ArithmeticException) {
//JSPagerの件で対応。msvcr71がロードできない環境もあるかもしれないので例外をもらってはじめて呼ぶようにする
Win32.ClearFPUOverflowFlag();
return new Font(name, size);
}
}
public static string ConcatStrArray(string[] values, char delimiter) {
StringBuilder bld = new StringBuilder();
for (int i = 0; i < values.Length; i++) {
if (i > 0)
bld.Append(delimiter);
bld.Append(values[i]);
}
return bld.ToString();
}
//min未満はmin, max以上はmax、それ以外はvalueを返す
public static int AdjustIntRange(int value, int min, int max) {
Debug.Assert(min <= max);
if (value < min)
return min;
else if (value > max)
return max;
else
return value;
}
}
/// <summary>
///
/// </summary>
/// <exclude/>
public static class ParseUtil {
public static bool ParseBool(string value, bool defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
return Boolean.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
public static byte ParseByte(string value, byte defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
return Byte.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
public static int ParseInt(string value, int defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
return Int32.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
public static float ParseFloat(string value, float defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
return Single.Parse(value);
}
catch (Exception) {
return defaultvalue;
}
}
public static int ParseHexInt(string value, int defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
return Int32.Parse(value, System.Globalization.NumberStyles.HexNumber);
}
catch (Exception) {
return defaultvalue;
}
}
public static Color ParseColor(string t, Color defaultvalue) {
if (t == null || t.Length == 0)
return defaultvalue;
else {
if (t.Length == 8) { //16進で保存されていることもある。窮余の策でこのように
int v;
if (Int32.TryParse(t, System.Globalization.NumberStyles.HexNumber, null, out v))
return Color.FromArgb(v);
}
else if (t.Length == 6) {
int v;
if (Int32.TryParse(t, System.Globalization.NumberStyles.HexNumber, null, out v))
return Color.FromArgb((int)((uint)v | 0xFF000000)); //'A'要素は0xFFに
}
Color c = Color.FromName(t);
return c.ToArgb() == 0 ? defaultvalue : c; //へんな名前だったとき、ARGBは全部0になるが、IsEmptyはfalse。なのでこれで判定するしかない
}
}
public static T ParseEnum<T>(string value, T defaultvalue) {
try {
if (value == null || value.Length == 0)
return defaultvalue;
else
return (T)Enum.Parse(typeof(T), value, false);
}
catch (Exception) {
return defaultvalue;
}
}
public static bool TryParseEnum<T>(string value, ref T parsed) {
if (value == null || value.Length == 0) {
return false;
}
try {
parsed = (T)Enum.Parse(typeof(T), value, false);
return true;
}
catch (Exception) {
return false;
}
}
//TODO Generics化
public static ValueType ParseMultipleEnum(Type enumtype, string t, ValueType defaultvalue) {
try {
int r = 0;
foreach (string a in t.Split(','))
r |= (int)Enum.Parse(enumtype, a, false);
return r;
}
catch (FormatException) {
return defaultvalue;
}
}
}
#if UNITTEST
public static class UnitTestUtil {
public static void Trace(string text) {
Console.Out.WriteLine(text);
Debug.WriteLine(text);
}
public static void Trace(string fmt, params object[] args) {
Trace(String.Format(fmt, args));
}
//configuration fileからロード 現在はPoderosa.Monolithic.configファイルを仮定
public static string GetUnitTestConfig(string entry_name) {
string r = ConfigurationManager.AppSettings[entry_name];
if (r == null)
Assert.Fail("the entry \"{0}\" is not found in Poderosa.Monolithic.config file.", entry_name);
return r;
}
public static string DumpStructuredText(StructuredText st) {
StringWriter wr = new StringWriter();
new TextStructuredTextWriter(wr).Write(st);
wr.Close();
return wr.ToString();
}
}
[TestFixture]
public class RuntimeUtilTests {
[Test] //ごくふつうのケース
public void ParseColor1() {
Color c1 = Color.Red;
Color c2 = ParseUtil.ParseColor("Red", Color.White);
Assert.AreEqual(c1, c2);
}
[Test] //hex 8ケタのARGB
public void ParseColor2() {
Color c1 = Color.FromArgb(10, 20, 30);
Color c2 = ParseUtil.ParseColor("FF0A141E", Color.White);
Assert.AreEqual(c1, c2);
}
[Test] //hex 6ケタのRGB
public void ParseColor3() {
Color c1 = Color.FromArgb(10, 20, 30);
Color c2 = ParseUtil.ParseColor("0A141E", Color.White);
Assert.AreEqual(c1, c2);
}
[Test] //KnownColorでもOK
public void ParseColor4() {
Color c1 = Color.FromKnownColor(KnownColor.WindowText);
Color c2 = ParseUtil.ParseColor("WindowText", Color.White);
Assert.AreEqual(c1, c2);
}
[Test] //ARGBは一致でもColorの比較としては不一致
public void ParseColor5() {
Color c1 = Color.Blue;
Color c2 = ParseUtil.ParseColor("0000FF", Color.White);
Assert.AreNotEqual(c1, c2);
Assert.AreEqual(c1.ToArgb(), c2.ToArgb());
}
[Test] //知らない名前はラストの引数と一致
public void ParseColor6() {
Color c1 = Color.White;
Color c2 = ParseUtil.ParseColor("asdfghj", Color.White); //パースできない場合
Assert.AreEqual(c1, c2);
}
[Test] //ついでなので仕様確認 ToString()ではだめですよ
public void ColorToString() {
Color c1 = Color.Red;
Color c2 = Color.FromName("Red");
Color c3 = Color.FromKnownColor(KnownColor.WindowFrame);
Color c4 = Color.FromArgb(255, 0, 0);
Assert.AreEqual(c1, c2);
Assert.AreEqual("Red", c1.Name);
Assert.AreEqual("Red", c2.Name);
Assert.AreEqual("WindowFrame", c3.Name);
Assert.AreEqual("ffff0000", c4.Name);
}
}
#endif
}
|
||||
TheStack | e0000be2f2137bc2a4fa4425247de40318007a8c | C#code:C# | {"size": 6955, "ext": "cs", "max_stars_repo_path": "DeepSpace.Core/ShipManager.cs", "max_stars_repo_name": "ardliath/DeepSpace", "max_stars_repo_stars_event_min_datetime": "2018-10-08T08:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-08T18:36:53.000Z", "max_issues_repo_path": "DeepSpace.Core/ShipManager.cs", "max_issues_repo_name": "ardliath/DeepSpace", "max_issues_repo_issues_event_min_datetime": "2018-09-28T18:15:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-13T07:31:15.000Z", "max_forks_repo_path": "DeepSpace.Core/ShipManager.cs", "max_forks_repo_name": "ardliath/DeepSpace", "max_forks_repo_forks_event_min_datetime": "2018-10-01T21:02:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-10T18:51:28.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 23.0, "max_forks_count": 6.0, "avg_line_length": 35.8505154639, "max_line_length": 149, "alphanum_fraction": 0.5680805176} | using DeepSpace.Contracts;
using DeepSpace.Data;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DeepSpace.Core
{
/// <summary>
/// All the business logic for creating/managing ships
/// </summary>
public class ShipManager : IShipManager
{
public ShipManager(IShipDataAccess shipDataAccess)
{
this.ShipDataAccess = shipDataAccess;
}
public IShipDataAccess ShipDataAccess { get; }
public async Task<Ship> CreateShipAsync(string name)
{
var startLocation = DetermineStartLocation();
var ship = new Ship
{
Name = name,
CommandCode = Guid.NewGuid().ToString(),
TransponderCode = Guid.NewGuid().ToString(),
Location = startLocation,
ShieldUpgrades = new List<IShieldUpgrades>(),
Statistics = new Statistics
{
Speed = 1,
ScanRange = DeepSpaceConstants.BASE_SCANRANGE,
BaseHealth = DeepSpaceConstants.BASE_HEALTH,
CurrentHealth = DeepSpaceConstants.BASE_HEALTH,
FirePower = DeepSpaceConstants.BASE_FIREPOWER
}
};
await this.ShipDataAccess.InsertShipAsync(ship);
return ship;
}
private Location DetermineStartLocation()
{
var random = new Random();
var x = random.Next(100) - 50;
var y = random.Next(100) - 50;
var z = random.Next(100) - 50;
return new Location(x, y, z);
}
public async Task<Ship> GetShipAsync(string commandCode)
{
var ship = this.ShipDataAccess.GetShip(commandCode);
if (this.UpdateMovements(ship))
{
await this.ShipDataAccess.UpsertShipAsync(ship);
}
return await Task.FromResult(ship);
}
public async Task<Move> MoveAsync(string commandCode, decimal x, decimal y, decimal z)
{
var ship = await this.GetShipAsync(commandCode);
if (this.UpdateMovements(ship))
{
await this.ShipDataAccess.UpsertShipAsync(ship);
}
if (ship.Location == null) // if the ship is already in flight then return their current move
{
return ship.Move;
}
var destination = new Location { X = x, Y = y, Z = z };
var speed = ship.Statistics.Speed;
double overallMovement = GetDistance(ship.Location, destination);
// Then simple Time = Distance / Speed calc. We're going to round because you're using TimeSpan.
var timeToMove = Convert.ToInt32(Math.Round((overallMovement / speed), 0, MidpointRounding.AwayFromZero));
var time = new TimeSpan(0, timeToMove, 0);
var now = DateTime.UtcNow;
var move = new Move
{
StartTime = now,
ArrivalTime = now.Add(time),
Duration = time,
From = ship.Location,
To = destination
};
ship.Location = null;
ship.Move = move;
await this.ShipDataAccess.UpsertShipAsync(ship);
return move;
}
public static double GetDistance(Location firstLocation, Location secondLocation)
{
// Source: https://stackoverflow.com/questions/8914669
var deltaX = firstLocation.X - secondLocation.X;
var deltaY = firstLocation.Y - secondLocation.Y;
var deltaZ = firstLocation.Z - secondLocation.Z;
return Math.Sqrt((double) (deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ));
}
public async Task AddShieldUpgradeAsync(string commandCode, IShieldUpgrades upgrade)
{
var ship = await GetShipAsync(commandCode);
Console.WriteLine($"{ship.Name} ship bought {upgrade.Name} adding {upgrade.ShieldValue} shield points");
ship.ShieldUpgrades.Add(upgrade);
UpdateHealth(ship, DeepSpaceConstants.BASE_SHIELD_HEALTH);
}
public async Task AttackShipAsync(string commandCode, string transponderCode)
{
var attackingShip = await GetShipAsync(commandCode); // get the attacking ship
var defendingShip = this.ShipDataAccess.GetShipByTransponderCode(transponderCode); // and the defending ship
if (this.UpdateMovements(defendingShip)) // if the defender's position has changed then update it
{
await this.ShipDataAccess.UpsertShipAsync(defendingShip);
}
UpdateHealth(defendingShip, -attackingShip.Statistics.FirePower); // reduce the defending ship's health by the firepower of the main ship
}
public async Task RepairAsync(string commandCode)
{
var ship = await GetShipAsync(commandCode);
UpdateHealth(ship, DeepSpaceConstants.BASE_AMOUNT_HEALTH_PER_REPAIR);
}
public async Task RestoreAsync(string commandCode)
{
var ship = await GetShipAsync(commandCode);
UpdateHealth(ship, ship.Statistics.BaseHealth + ship.Shield);
}
private void UpdateHealth(Ship ship, int healthChange)
{
ship.Statistics.CurrentHealth += healthChange;
Console.WriteLine($"{ship.Name} Health {healthChange}");
if(ship.Statistics.CurrentHealth <= 0) // if it's dead
{
this.KillShip(); // then kill it
}
else
{
this.ShipDataAccess.UpsertShipAsync(ship); // otherwise update them with the new health
}
}
private void KillShip()
{
throw new NotImplementedException();
}
public async Task<IEnumerable<Ship>> ScanAsync(string commandCode)
{
var ship = this.ShipDataAccess.GetShip(commandCode);
if (this.UpdateMovements(ship))
{
await this.ShipDataAccess.UpsertShipAsync(ship);
}
if (ship.Location == null)
{
return new Ship[] { }; // cannot scan while in flight
}
var nearbyShips = this.ShipDataAccess.ScanForShips(ship.CommandCode, ship.Location, ship.Statistics.ScanRange);
return nearbyShips;
}
private bool UpdateMovements(Ship ship)
{
var now = DateTime.UtcNow;
if (ship.Move != null && ship.Move.ArrivalTime < now)
{
ship.Location = ship.Move.To;
ship.Move = null;
return true;
}
return false;
}
}
}
|
||||
TheStack | e000113d37a0f31ab057b4b438b0800c93894088 | C#code:C# | {"size": 6289, "ext": "cs", "max_stars_repo_path": "Source/Library/PackageCache/[email protected]/Editor/Settings/AddressableAssetGroupSchema.cs", "max_stars_repo_name": "WeLikeIke/DubitaC", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Library/PackageCache/[email protected]/Editor/Settings/AddressableAssetGroupSchema.cs", "max_issues_repo_name": "WeLikeIke/DubitaC", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Library/PackageCache/[email protected]/Editor/Settings/AddressableAssetGroupSchema.cs", "max_forks_repo_name": "WeLikeIke/DubitaC", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.0573248408, "max_line_length": 153, "alphanum_fraction": 0.5593894101} | using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor.AddressableAssets.GUI;
using UnityEngine;
using UnityEngine.ResourceManagement.Util;
using UnityEngine.Serialization;
namespace UnityEditor.AddressableAssets.Settings
{
/// <summary>
/// Contains data for AddressableAssetGroups.
/// </summary>
public class AddressableAssetGroupSchema : ScriptableObject
{
[FormerlySerializedAs("m_group")] [AddressableReadOnly] [SerializeField]
AddressableAssetGroup m_Group;
/// <summary>
/// Get the group that the schema belongs to.
/// </summary>
public AddressableAssetGroup Group
{
get { return m_Group; }
internal set
{
m_Group = value;
if (m_Group != null)
{
OnSetGroup(m_Group);
Validate();
}
}
}
/// <summary>
/// Override this method to perform post creation initialization.
/// </summary>
/// <param name="group">The group that the schema is added to.</param>
protected virtual void OnSetGroup(AddressableAssetGroup group)
{
}
internal virtual void Validate()
{
}
/// <summary>
/// Used to display the GUI of the schema.
/// </summary>
public virtual void OnGUI()
{
var type = GetType();
var so = new SerializedObject(this);
var p = so.GetIterator();
p.Next(true);
while (p.Next(false))
{
var prop = type.GetField(p.name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (prop != null)
EditorGUILayout.PropertyField(p, true);
}
so.ApplyModifiedProperties();
}
/// <summary>
/// Used to display the GUI of multiple selected groups.
/// </summary>
/// <param name="otherSchemas">Schema instances in the other selected groups</param>
public virtual void OnGUIMultiple(List<AddressableAssetGroupSchema> otherSchemas)
{
}
/// <summary>
/// Used to notify the addressables settings that data has been modified. This must be called by subclasses to ensure proper cache invalidation.
/// </summary>
/// <param name="postEvent">Determines if this method call will post an event to the internal addressables event system</param>
protected void SetDirty(bool postEvent)
{
if (m_Group != null)
{
if (m_Group.Settings != null && m_Group.Settings.IsPersisted)
{
EditorUtility.SetDirty(this);
AddressableAssetUtility.OpenAssetIfUsingVCIntegration(this);
}
if (m_Group != null)
m_Group.SetDirty(AddressableAssetSettings.ModificationEvent.GroupSchemaModified, this, postEvent, false);
}
}
/// <summary>
/// Used for drawing properties in the inspector.
/// </summary>
public virtual void ShowAllProperties()
{
}
/// <summary>
/// Display mixed values for the specified property found in a list of schemas.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="otherSchemas">The list of schemas that may contain the property.</param>
/// <param name="type">The property type.</param>
/// <param name="propertyName">The property name.</param>
protected void ShowMixedValue(SerializedProperty property, List<AddressableAssetGroupSchema> otherSchemas, Type type, string propertyName)
{
foreach (var schema in otherSchemas)
{
var s_prop = (new SerializedObject(schema)).FindProperty(propertyName);
if ((property.propertyType == SerializedPropertyType.Enum && (property.enumValueIndex != s_prop.enumValueIndex)) ||
(property.propertyType == SerializedPropertyType.String && (property.stringValue != s_prop.stringValue)) ||
(property.propertyType == SerializedPropertyType.Integer && (property.intValue != s_prop.intValue)) ||
(property.propertyType == SerializedPropertyType.Boolean && (property.boolValue != s_prop.boolValue)))
{
EditorGUI.showMixedValue = true;
return;
}
if (type == typeof(ProfileValueReference))
{
var field = property.serializedObject.targetObject.GetType().GetField(property.name,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly);
string lhsId = (field?.GetValue(property.serializedObject.targetObject) as ProfileValueReference)?.Id;
string rhsId = (field?.GetValue(s_prop.serializedObject.targetObject) as ProfileValueReference)?.Id;
if (lhsId != null && rhsId != null && lhsId != rhsId)
{
EditorGUI.showMixedValue = true;
return;
}
}
if (type == typeof(SerializedType))
{
var field = property.serializedObject.targetObject.GetType().GetField(property.name,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly);
Type lhs = ((SerializedType)field?.GetValue(property.serializedObject.targetObject)).Value;
Type rhs = ((SerializedType)field?.GetValue(s_prop.serializedObject.targetObject)).Value;
if (lhs != null && rhs != null && lhs != rhs)
{
EditorGUI.showMixedValue = true;
return;
}
}
}
}
}
}
|
||||
TheStack | e001a934376c2f2bd05815d49fbf5429584d8fa2 | C#code:C# | {"size": 2420, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/GameScripts/Galeon/PointAndClickInput.cs", "max_stars_repo_name": "BlazeNeko/UnityAvanzado", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/GameScripts/Galeon/PointAndClickInput.cs", "max_issues_repo_name": "BlazeNeko/UnityAvanzado", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/GameScripts/Galeon/PointAndClickInput.cs", "max_forks_repo_name": "BlazeNeko/UnityAvanzado", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.5934065934, "max_line_length": 136, "alphanum_fraction": 0.6797520661} | using UnityEngine;
using System.Collections;
/// <summary>
/// Point and click input. Heredamos de InputController. Los InputController no son mas que controladores
/// del input concretos al juego que estamos desarrollando y que se almacenan en el InputMgr.
/// Solo puede haber uno por escena.
///
/// Componente que implementa un imput PointAndClick. Se registra automaticamente en el InputManager y extiende la funcionalidad de este
/// aportando funcionalidad concreta de este tipo de control de Input.
/// </summary>
public class PointAndClickInput : InputController {
//Evento de Cambiar Arma definido como un delegado.
public delegate void ChangeWapon(int index );
protected int m_nextWeaponMovile = 0;
//Clase interna serializable para poder mostrarla desde el inspector.
[System.Serializable]
public class TWeapons
{
public int weaponIndex;
public KeyCode keyCode;
}
//array de armas disponibles.
public TWeapons[] m_weaponKeyAsign;
//Ofrecemos una interfaz para que los componentes se registren al Input y pueda recibir eventos.
public void RegisterChangeWeapon(ChangeWapon del)
{
m_changeWeapon += del;
}
//Desregistramos al componente del evento.
public void UnRegisterChangeWeapon(ChangeWapon del)
{
m_changeWeapon -= del;
}
protected override void Update()
{
base.Update();
#if UNITY_IPHONE || UNITY_ANDROID
ProccessTouchEvent();
#else
OnChangeWeapon();
#endif
}
protected void ProccessTouchEvent()
{
//Hemos decidido que para cambiar de arma pulsaremos con dos dedos la pantalla.
if(Input.touchCount == 2)
{
if(m_changeWeapon != null)
{
m_nextWeaponMovile++;
m_nextWeaponMovile = m_nextWeaponMovile % m_weaponKeyAsign.Length;
m_changeWeapon(m_nextWeaponMovile);
}
}
}
protected void OnChangeWeapon()
{
//En la version de pc, usaremos las teclas KeyCode del array apra cambiar de arma.
//TODO 1: lanzamos el evento m_changeWeapon si Input.GetKeyDown(weapon.keyCode)
var input = Input.inputString;
switch (input)
{
case "1":
m_changeWeapon(0);
break;
case "2":
m_changeWeapon(1);
break;
case "3":
m_changeWeapon(2 );
break;
default:
break;
}
}
protected ChangeWapon m_changeWeapon;
}
|
||||
TheStack | e00265152d7d45374a73d5de222540158e04410b | C#code:C# | {"size": 7480, "ext": "cs", "max_stars_repo_path": "Regul.S3PI/Resources/CatalogResource/TerrainPaintBrushCatalogResource.cs", "max_stars_repo_name": "Onebeld/Regul.S3PI", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Regul.S3PI/Resources/CatalogResource/TerrainPaintBrushCatalogResource.cs", "max_issues_repo_name": "Onebeld/Regul.S3PI", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Regul.S3PI/Resources/CatalogResource/TerrainPaintBrushCatalogResource.cs", "max_forks_repo_name": "Onebeld/Regul.S3PI", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.4324324324, "max_line_length": 290, "alphanum_fraction": 0.5248663102} | /***************************************************************************
* Copyright (C) 2010 by Peter L Jones *
* [email protected] *
* *
* This file is part of the Sims 3 Package Interface (s3pi) *
* *
* s3pi is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* s3pi is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with s3pi. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using Regul.S3PI.Interfaces;
namespace Regul.S3PI.Resources.CatalogResource
{
public class TerrainPaintBrushCatalogResource : TerrainGeometryWaterBrushCatalogResource
{
#region Attributes
TGIBlock brushTexture = null;
TerrainType terrain;//version>=0x04
CategoryType category;//version>=0x04
#endregion
#region Constructors
public TerrainPaintBrushCatalogResource(Stream s) : base(s) { }
public TerrainPaintBrushCatalogResource(Stream unused, TerrainPaintBrushCatalogResource basis)
: base(null, basis)
{
this.brushTexture = (TGIBlock)basis.brushTexture.Clone(OnResourceChanged);
this.terrain = basis.terrain;
this.category = basis.category;
}
public TerrainPaintBrushCatalogResource(uint version,
uint brushVersion,
Common common,
BrushOperation normalOperation, BrushOperation oppositeOperation, TGIBlock profileTexture,
BrushOrientation orientation,
float width, float strength, byte baseTextureValue, float wiggleAmount,
TGIBlock brushTexture)
: this(version,
brushVersion,
common,
normalOperation,
oppositeOperation,
profileTexture,
orientation,
width,
strength,
baseTextureValue,
wiggleAmount,
brushTexture,
0, 0
)
{
if (version >= 0x00000004)
throw new InvalidOperationException(String.Format("Constructor requires terrain and category for version {0}", version));
}
public TerrainPaintBrushCatalogResource(uint version,
uint brushVersion,
Common common,
BrushOperation normalOperation, BrushOperation oppositeOperation, TGIBlock profileTexture,
BrushOrientation orientation,
float width, float strength, byte baseTextureValue, float wiggleAmount,
TGIBlock brushTexture,
TerrainType terrain, CategoryType category)
: base(version,
brushVersion,
common,
normalOperation,
oppositeOperation,
profileTexture,
orientation,
width,
strength,
baseTextureValue,
wiggleAmount
)
{
this.brushTexture = (TGIBlock)brushTexture.Clone(OnResourceChanged);
this.terrain = terrain;
this.category = category;
}
#endregion
#region Data I/O
protected override void Parse(Stream s)
{
base.Parse(s);
this.brushTexture = new TGIBlock(OnResourceChanged, s);
if (version >= 4)
{
BinaryReader r = new BinaryReader(s);
this.terrain = (TerrainType)r.ReadUInt32();
this.category = (CategoryType)r.ReadUInt32();
}
if (this.GetType().Equals(typeof(TerrainPaintBrushCatalogResource)) && s.Position != s.Length)
throw new InvalidDataException(String.Format("Data stream length 0x{0:X8} is {1:X8} bytes longer than expected at {2:X8}",
s.Length, s.Length - s.Position, s.Position));
}
protected override Stream UnParse()
{
Stream s = base.UnParse();
if (brushTexture == null) brushTexture = new TGIBlock(OnResourceChanged);
brushTexture.UnParse(s);
if (version >= 4)
{
BinaryWriter w = new BinaryWriter(s);
w.Write((uint)terrain);
w.Write((uint)category);
}
return s;
}
#endregion
#region AApiVersionedFields
/// <summary>
/// The list of available field names on this API object
/// </summary>
public override List<string> ContentFields
{
get
{
List<string> res = base.ContentFields;
if (this.version < 0x00000004)
{
res.Remove("Terrain");
res.Remove("Category");
}
return res;
}
}
#endregion
#region Sub-classes
public enum TerrainType : uint
{
Grass = 0x1,
Flowers = 0x2,
Rock = 0x3,
DirtSand = 0x4,
Other = 0x5,
}
public enum CategoryType : uint
{
None = 0x00,
Grass = 0x01,
Flowers = 0x02,
Rock = 0x03,
Dirt_Sand = 0x04,
Other = 0x05,
}
#endregion
#region Content Fields
//--insert TerrainGeometryWaterBrushCatalogResource
[ElementPriority(41)]
public TGIBlock BrushTexture
{
get { return brushTexture; }
set { if (brushTexture != value) { brushTexture = new TGIBlock(OnResourceChanged, value); OnResourceChanged(this, EventArgs.Empty); } }
}
[ElementPriority(42)]
public TerrainType Terrain { get { if (version < 0x00000004) throw new InvalidOperationException(); return terrain; } set { if (version < 0x00000004) throw new InvalidOperationException(); if (terrain != value) { terrain = value; OnResourceChanged(this, EventArgs.Empty); } } }
[ElementPriority(43)]
public CategoryType Category { get { if (version < 0x00000004) throw new InvalidOperationException(); return category; } set { if (version < 0x00000004) throw new InvalidOperationException(); if (category != value) { category = value; OnResourceChanged(this, EventArgs.Empty); } } }
#endregion
}
} |
||||
TheStack | e002a43acdf9ee8f6e29475954ce00510c46468e | C#code:C# | {"size": 15309, "ext": "cs", "max_stars_repo_path": "src/Yaksa.OrckestraCommerce.Client/Model/TargetingCondition.cs", "max_stars_repo_name": "Yaksa-ca/eShopOnWeb", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Yaksa.OrckestraCommerce.Client/Model/TargetingCondition.cs", "max_issues_repo_name": "Yaksa-ca/eShopOnWeb", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Yaksa.OrckestraCommerce.Client/Model/TargetingCondition.cs", "max_forks_repo_name": "Yaksa-ca/eShopOnWeb", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.3684210526, "max_line_length": 434, "alphanum_fraction": 0.5478476713} | /*
* Overture API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Yaksa.OrckestraCommerce.Client.Client.OpenAPIDateConverter;
namespace Yaksa.OrckestraCommerce.Client.Model
{
/// <summary>
/// TargetingCondition
/// </summary>
[DataContract(Name = "TargetingCondition")]
public partial class TargetingCondition : IEquatable<TargetingCondition>, IValidatableObject
{
/// <summary>
/// The binary operator which will be apply between the children targeting conditions.
/// </summary>
/// <value>The binary operator which will be apply between the children targeting conditions.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum BinaryOperatorEnum
{
/// <summary>
/// Enum Unspecified for value: Unspecified
/// </summary>
[EnumMember(Value = "Unspecified")]
Unspecified = 1,
/// <summary>
/// Enum And for value: And
/// </summary>
[EnumMember(Value = "And")]
And = 2,
/// <summary>
/// Enum Or for value: Or
/// </summary>
[EnumMember(Value = "Or")]
Or = 3
}
/// <summary>
/// The binary operator which will be apply between the children targeting conditions.
/// </summary>
/// <value>The binary operator which will be apply between the children targeting conditions.</value>
[DataMember(Name = "binaryOperator", EmitDefaultValue = false)]
public BinaryOperatorEnum? BinaryOperator { get; set; }
/// <summary>
/// Gets or sets the operator to apply on the Value to get the promotion when the target is used on a collection.
/// </summary>
/// <value> Gets or sets the operator to apply on the Value to get the promotion when the target is used on a collection.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum CollectionOperatorEnum
{
/// <summary>
/// Enum Unspecified for value: Unspecified
/// </summary>
[EnumMember(Value = "Unspecified")]
Unspecified = 1,
/// <summary>
/// Enum All for value: All
/// </summary>
[EnumMember(Value = "All")]
All = 2,
/// <summary>
/// Enum Any for value: Any
/// </summary>
[EnumMember(Value = "Any")]
Any = 3
}
/// <summary>
/// Gets or sets the operator to apply on the Value to get the promotion when the target is used on a collection.
/// </summary>
/// <value> Gets or sets the operator to apply on the Value to get the promotion when the target is used on a collection.</value>
[DataMember(Name = "collectionOperator", EmitDefaultValue = false)]
public CollectionOperatorEnum? CollectionOperator { get; set; }
/// <summary>
/// The operator to apply on the Value to get the promotion.
/// </summary>
/// <value>The operator to apply on the Value to get the promotion.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum OperatorEnum
{
/// <summary>
/// Enum Unspecified for value: Unspecified
/// </summary>
[EnumMember(Value = "Unspecified")]
Unspecified = 1,
/// <summary>
/// Enum Equals for value: Equals
/// </summary>
[EnumMember(Value = "Equals")]
Equals = 2,
/// <summary>
/// Enum GreaterThan for value: GreaterThan
/// </summary>
[EnumMember(Value = "GreaterThan")]
GreaterThan = 3,
/// <summary>
/// Enum GreaterThanOrEqual for value: GreaterThanOrEqual
/// </summary>
[EnumMember(Value = "GreaterThanOrEqual")]
GreaterThanOrEqual = 4,
/// <summary>
/// Enum LessThan for value: LessThan
/// </summary>
[EnumMember(Value = "LessThan")]
LessThan = 5,
/// <summary>
/// Enum LessThanOrEqual for value: LessThanOrEqual
/// </summary>
[EnumMember(Value = "LessThanOrEqual")]
LessThanOrEqual = 6,
/// <summary>
/// Enum Matches for value: Matches
/// </summary>
[EnumMember(Value = "Matches")]
Matches = 7,
/// <summary>
/// Enum In for value: In
/// </summary>
[EnumMember(Value = "In")]
In = 8,
/// <summary>
/// Enum HasValue for value: HasValue
/// </summary>
[EnumMember(Value = "HasValue")]
HasValue = 9,
/// <summary>
/// Enum IsEmpty for value: IsEmpty
/// </summary>
[EnumMember(Value = "IsEmpty")]
IsEmpty = 10
}
/// <summary>
/// The operator to apply on the Value to get the promotion.
/// </summary>
/// <value>The operator to apply on the Value to get the promotion.</value>
[DataMember(Name = "operator", EmitDefaultValue = false)]
public OperatorEnum? Operator { get; set; }
/// <summary>
/// The type of condition
/// </summary>
/// <value>The type of condition</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum Unspecified for value: Unspecified
/// </summary>
[EnumMember(Value = "Unspecified")]
Unspecified = 1,
/// <summary>
/// Enum PropertyFilter for value: PropertyFilter
/// </summary>
[EnumMember(Value = "PropertyFilter")]
PropertyFilter = 2,
/// <summary>
/// Enum CollectionFilter for value: CollectionFilter
/// </summary>
[EnumMember(Value = "CollectionFilter")]
CollectionFilter = 3,
/// <summary>
/// Enum SegmentFilter for value: SegmentFilter
/// </summary>
[EnumMember(Value = "SegmentFilter")]
SegmentFilter = 4,
/// <summary>
/// Enum TargetingGroup for value: TargetingGroup
/// </summary>
[EnumMember(Value = "TargetingGroup")]
TargetingGroup = 5
}
/// <summary>
/// The type of condition
/// </summary>
/// <value>The type of condition</value>
[DataMember(Name = "type", EmitDefaultValue = false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TargetingCondition" /> class.
/// </summary>
/// <param name="binaryOperator">The binary operator which will be apply between the children targeting conditions..</param>
/// <param name="children">The children of this targeting condition..</param>
/// <param name="collectionOperator"> Gets or sets the operator to apply on the Value to get the promotion when the target is used on a collection..</param>
/// <param name="not"> Gets or sets a value indicating whether to use the Operator should NOT be matched..</param>
/// <param name="_operator">The operator to apply on the Value to get the promotion..</param>
/// <param name="propertyPath">The relative path of the property used for the condition.</param>
/// <param name="type">The type of condition.</param>
/// <param name="value">Object.</param>
public TargetingCondition(BinaryOperatorEnum? binaryOperator = default(BinaryOperatorEnum?), List<TargetingCondition> children = default(List<TargetingCondition>), CollectionOperatorEnum? collectionOperator = default(CollectionOperatorEnum?), bool not = default(bool), OperatorEnum? _operator = default(OperatorEnum?), string propertyPath = default(string), TypeEnum? type = default(TypeEnum?), Object value = default(Object))
{
this.BinaryOperator = binaryOperator;
this.Children = children;
this.CollectionOperator = collectionOperator;
this.Not = not;
this.Operator = _operator;
this.PropertyPath = propertyPath;
this.Type = type;
this.Value = value;
}
/// <summary>
/// The children of this targeting condition.
/// </summary>
/// <value>The children of this targeting condition.</value>
[DataMember(Name = "children", EmitDefaultValue = false)]
public List<TargetingCondition> Children { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use the Operator should NOT be matched.
/// </summary>
/// <value> Gets or sets a value indicating whether to use the Operator should NOT be matched.</value>
[DataMember(Name = "not", EmitDefaultValue = true)]
public bool Not { get; set; }
/// <summary>
/// The relative path of the property used for the condition
/// </summary>
/// <value>The relative path of the property used for the condition</value>
[DataMember(Name = "propertyPath", EmitDefaultValue = false)]
public string PropertyPath { get; set; }
/// <summary>
/// Object
/// </summary>
/// <value>Object</value>
[DataMember(Name = "value", EmitDefaultValue = false)]
public Object Value { 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 TargetingCondition {\n");
sb.Append(" BinaryOperator: ").Append(BinaryOperator).Append("\n");
sb.Append(" Children: ").Append(Children).Append("\n");
sb.Append(" CollectionOperator: ").Append(CollectionOperator).Append("\n");
sb.Append(" Not: ").Append(Not).Append("\n");
sb.Append(" Operator: ").Append(Operator).Append("\n");
sb.Append(" PropertyPath: ").Append(PropertyPath).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Value: ").Append(Value).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 virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as TargetingCondition);
}
/// <summary>
/// Returns true if TargetingCondition instances are equal
/// </summary>
/// <param name="input">Instance of TargetingCondition to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TargetingCondition input)
{
if (input == null)
return false;
return
(
this.BinaryOperator == input.BinaryOperator ||
this.BinaryOperator.Equals(input.BinaryOperator)
) &&
(
this.Children == input.Children ||
this.Children != null &&
input.Children != null &&
this.Children.SequenceEqual(input.Children)
) &&
(
this.CollectionOperator == input.CollectionOperator ||
this.CollectionOperator.Equals(input.CollectionOperator)
) &&
(
this.Not == input.Not ||
this.Not.Equals(input.Not)
) &&
(
this.Operator == input.Operator ||
this.Operator.Equals(input.Operator)
) &&
(
this.PropertyPath == input.PropertyPath ||
(this.PropertyPath != null &&
this.PropertyPath.Equals(input.PropertyPath))
) &&
(
this.Type == input.Type ||
this.Type.Equals(input.Type)
) &&
(
this.Value == input.Value ||
(this.Value != null &&
this.Value.Equals(input.Value))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.BinaryOperator.GetHashCode();
if (this.Children != null)
hashCode = hashCode * 59 + this.Children.GetHashCode();
hashCode = hashCode * 59 + this.CollectionOperator.GetHashCode();
hashCode = hashCode * 59 + this.Not.GetHashCode();
hashCode = hashCode * 59 + this.Operator.GetHashCode();
if (this.PropertyPath != null)
hashCode = hashCode * 59 + this.PropertyPath.GetHashCode();
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.Value != null)
hashCode = hashCode * 59 + this.Value.GetHashCode();
return hashCode;
}
}
/// <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;
}
}
}
|
||||
TheStack | e002cf1e9136539ff51804ee6fdae7ff7e37fc3e | C#code:C# | {"size": 5621, "ext": "cs", "max_stars_repo_path": "Manufaktura.Controls/Rendering/Postprocessing/DrawMissingStemsFinishingTouch.cs", "max_stars_repo_name": "prepare/Ajcek_manufakturalibraries", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Manufaktura.Controls/Rendering/Postprocessing/DrawMissingStemsFinishingTouch.cs", "max_issues_repo_name": "prepare/Ajcek_manufakturalibraries", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Manufaktura.Controls/Rendering/Postprocessing/DrawMissingStemsFinishingTouch.cs", "max_forks_repo_name": "prepare/Ajcek_manufakturalibraries", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 48.0427350427, "max_line_length": 247, "alphanum_fraction": 0.6285358477} | /*
* Copyright 2018 Manufaktura Programów Jacek Salamon http://musicengravingcontrols.com/
* MIT LICENCE
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 Manufaktura.Controls.Model;
using Manufaktura.Controls.Primitives;
using System;
using System.Linq;
namespace Manufaktura.Controls.Rendering.Postprocessing
{
internal class DrawMissingStemsFinishingTouch : IFinishingTouch
{
/// <summary>
/// Applies DrawMissingStemsFinishingTouch to a measure.
/// </summary>
/// <param name="measure">Measure</param>
/// <param name="renderer">Score renderer</param>
public void PerformOnMeasure(Measure measure, ScoreRendererBase renderer)
{
Perform(measure.Staff, measure, renderer);
}
/// <summary>
/// This method does nothing in this implementation of IFinishingTouch.
/// </summary>
/// <param name="score">Score</param>
/// <param name="renderer">Score renderer</param>
public void PerformOnScore(Score score, ScoreRendererBase renderer)
{
}
/// <summary>
/// Applies DrawMissingStemsFinishingTouch to a staff.
/// </summary>
/// <param name="staff">Staff</param>
/// <param name="renderer">Score renderer</param>
public void PerformOnStaff(Staff staff, ScoreRendererBase renderer)
{
Perform(staff, null, renderer);
}
private Note GetLastNoteInBeam(Note note, Staff staff)
{
for (int i = staff.Elements.IndexOf(note) + 1; i < staff.Elements.Count; i++)
{
Note note2 = staff.Elements[i] as Note;
if (note2 == null) continue;
if (note2.BeamList.Count > 0)
{
if (note2.BeamList[0] == NoteBeamType.End)
{
return note2;
}
}
}
return null;
}
private void Perform(Staff staff, Measure measure, ScoreRendererBase renderer)
{
//Draw missing stems / Dorysuj brakujące ogonki:
Note lastNoteInBeam = null;
Note firstNoteInBeam = null;
foreach (Note note in staff.Elements.OfType<Note>())
{
//Search for the end of the beam / Przeszukaj i znajdź koniec belki:
if (note.BeamList.Count == 0) continue;
if (note.BeamList[0] == NoteBeamType.End) continue;
if (note.BeamList[0] == NoteBeamType.Start)
{
firstNoteInBeam = note;
continue;
}
if (note.BeamList[0] != NoteBeamType.Continue) continue;
if (note.HasCustomStemEndPosition) continue;
lastNoteInBeam = GetLastNoteInBeam(note, staff);
double newStemEndPosition = Math.Abs(note.StemEndLocation.X -
firstNoteInBeam.StemEndLocation.X) *
((Math.Abs(lastNoteInBeam.StemEndLocation.Y - firstNoteInBeam.StemEndLocation.Y)) /
(Math.Abs(lastNoteInBeam.StemEndLocation.X - firstNoteInBeam.StemEndLocation.X)));
//Jeśli ostatnia nuta jest wyżej, to odejmij y zamiast dodać
//If the last note is higher, subtract y instead of adding
if (lastNoteInBeam.StemEndLocation.Y < firstNoteInBeam.StemEndLocation.Y)
newStemEndPosition *= -1;
Point newStemEndPoint = new Point(note.StemEndLocation.X, firstNoteInBeam.StemEndLocation.Y + newStemEndPosition);
if (measure != null && note.Measure != measure) continue; //Odśwież tylko stemy z wybranego taktu w trybie odświeżania jednego taktu
if (note.StemDirection == VerticalDirection.Down)
{
var chord = NoteRenderStrategy.GetChord(note, staff);
var highestNoteInChord = chord.Last();
renderer.DrawLine(new Point(note.StemEndLocation.X, highestNoteInChord.TextBlockLocation.Y), new Point(newStemEndPoint.X, newStemEndPoint.Y), new Pen(renderer.CoalesceColor(note), renderer.Settings.DefaultStemThickness), note);
}
else
renderer.DrawLine(new Point(note.StemEndLocation.X, note.TextBlockLocation.Y), new Point(newStemEndPoint.X, newStemEndPoint.Y), new Pen(renderer.CoalesceColor(note), renderer.Settings.DefaultStemThickness), note);
if (lastNoteInBeam == null) continue;
}
}
}
} |
||||
TheStack | e002f754a0f4e56ac24a2e243339d2b54276ff34 | C#code:C# | {"size": 232, "ext": "cs", "max_stars_repo_path": "Assets/Kakomi/Scripts/Common/Presentation/Controller/Interface/IVolumeUpdatable.cs", "max_stars_repo_name": "kitatas/Kakomi", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Kakomi/Scripts/Common/Presentation/Controller/Interface/IVolumeUpdatable.cs", "max_issues_repo_name": "kitatas/Kakomi", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Kakomi/Scripts/Common/Presentation/Controller/Interface/IVolumeUpdatable.cs", "max_forks_repo_name": "kitatas/Kakomi", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.2, "max_line_length": 57, "alphanum_fraction": 0.6465517241} | namespace Kakomi.Common.Presentation.Controller.Interface
{
public interface IVolumeUpdatable
{
void SetMute(bool value);
bool IsMute();
void SetVolume(float value);
float GetVolume();
}
} |
||||
TheStack | e0056ec40ebe7d19af71d551f00fe539e62a46f6 | C#code:C# | {"size": 8872, "ext": "cs", "max_stars_repo_path": "Mozu.Api/Resources/Commerce/Catalog/Admin/PublishingScopeResource.cs", "max_stars_repo_name": "Mozu/mozu-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mozu.Api/Resources/Commerce/Catalog/Admin/PublishingScopeResource.cs", "max_issues_repo_name": "Mozu/mozu-dotnet", "max_issues_repo_issues_event_min_datetime": "2018-11-16T20:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-03T19:47:40.000Z", "max_forks_repo_path": "Mozu.Api/Resources/Commerce/Catalog/Admin/PublishingScopeResource.cs", "max_forks_repo_name": "Mozu/mozu-dotnet", "max_forks_repo_forks_event_min_datetime": "2015-03-11T13:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-19T20:18:28.000Z"} | {"max_stars_count": null, "max_issues_count": 3.0, "max_forks_count": 17.0, "avg_line_length": 42.8599033816, "max_line_length": 294, "alphanum_fraction": 0.719116321} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Codezu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Mozu.Api.Security;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Threading;
namespace Mozu.Api.Resources.Commerce.Catalog.Admin
{
/// <summary>
/// Use the Product Publishing resource to publish or discard pending changes to products in a master catalog, or to add or remove pending changes to and from product publish sets.You can use product publish sets to group pending product changes together and publish them all at the same time.
/// </summary>
public partial class PublishingScopeResource {
///
/// <see cref="Mozu.Api.ApiContext"/>
///
private readonly IApiContext _apiContext;
private readonly DataViewMode _dataViewMode;
public PublishingScopeResource(IApiContext apiContext)
{
_apiContext = apiContext;
_dataViewMode = DataViewMode.Live;
}
public PublishingScopeResource CloneWithApiContext(Action<IApiContext> contextModification)
{
return new PublishingScopeResource(_apiContext.CloneWith(contextModification), _dataViewMode);
}
public PublishingScopeResource(IApiContext apiContext, DataViewMode dataViewMode)
{
_apiContext = apiContext;
_dataViewMode = dataViewMode;
}
/// <summary>
///
/// </summary>
/// <param name="publishSetCode">The unique identifier of the publish set.</param>
/// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <returns>
/// <see cref="Mozu.Api.Contracts.ProductAdmin.PublishSet"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var publishSet = await publishingscope.GetPublishSetAsync( publishSetCode, responseFields);
/// </code>
/// </example>
public virtual async Task<Mozu.Api.Contracts.ProductAdmin.PublishSet> GetPublishSetAsync(string publishSetCode, string responseFields = null, CancellationToken ct = default(CancellationToken))
{
MozuClient<Mozu.Api.Contracts.ProductAdmin.PublishSet> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.GetPublishSetClient( publishSetCode, responseFields);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
/// <summary>
///
/// </summary>
/// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <returns>
/// <see cref="Mozu.Api.Contracts.ProductAdmin.PublishSetCollection"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var publishSetCollection = await publishingscope.GetPublishSetsAsync( responseFields);
/// </code>
/// </example>
public virtual async Task<Mozu.Api.Contracts.ProductAdmin.PublishSetCollection> GetPublishSetsAsync(string responseFields = null, CancellationToken ct = default(CancellationToken))
{
MozuClient<Mozu.Api.Contracts.ProductAdmin.PublishSetCollection> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.GetPublishSetsClient( responseFields);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
/// <summary>
///
/// </summary>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <param name="publishScope">Describes the scope of the product publishing update, which can include individual product codes or all pending changes.</param>
/// <returns>
/// <see cref="System.IO.Stream"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var stream = await publishingscope.DiscardDraftsAsync(_dataViewMode, publishScope);
/// </code>
/// </example>
public virtual async Task<System.IO.Stream> DiscardDraftsAsync(Mozu.Api.Contracts.ProductAdmin.PublishingScope publishScope, CancellationToken ct = default(CancellationToken))
{
MozuClient<System.IO.Stream> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.DiscardDraftsClient(_dataViewMode, publishScope);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
/// <summary>
///
/// </summary>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <param name="publishScope">Describes the scope of the product publishing update, which can include individual product codes or all pending changes.</param>
/// <returns>
/// <see cref="System.IO.Stream"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var stream = await publishingscope.PublishDraftsAsync(_dataViewMode, publishScope);
/// </code>
/// </example>
public virtual async Task<System.IO.Stream> PublishDraftsAsync(Mozu.Api.Contracts.ProductAdmin.PublishingScope publishScope, CancellationToken ct = default(CancellationToken))
{
MozuClient<System.IO.Stream> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.PublishDraftsClient(_dataViewMode, publishScope);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
/// <summary>
///
/// </summary>
/// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <param name="publishSet">The details of the publish to which you want to assign products.</param>
/// <returns>
/// <see cref="Mozu.Api.Contracts.ProductAdmin.PublishSet"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var publishSet = await publishingscope.AssignProductsToPublishSetAsync( publishSet, responseFields);
/// </code>
/// </example>
public virtual async Task<Mozu.Api.Contracts.ProductAdmin.PublishSet> AssignProductsToPublishSetAsync(Mozu.Api.Contracts.ProductAdmin.PublishSet publishSet, string responseFields = null, CancellationToken ct = default(CancellationToken))
{
MozuClient<Mozu.Api.Contracts.ProductAdmin.PublishSet> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.AssignProductsToPublishSetClient( publishSet, responseFields);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
/// <summary>
///
/// </summary>
/// <param name="discardDrafts">Specifies whether to discard all the drafts assigned to the publish set when the publish set is deleted.</param>
/// <param name="publishSetCode">The unique identifier of the publish set.</param>
/// <param name="dataViewMode">{<see cref="Mozu.Api.DataViewMode"/>}</param>
/// <returns>
/// <see cref="System.IO.Stream"/>
/// </returns>
/// <example>
/// <code>
/// var publishingscope = new PublishingScope();
/// var stream = await publishingscope.DeletePublishSetAsync( publishSetCode, discardDrafts);
/// </code>
/// </example>
public virtual async Task<System.IO.Stream> DeletePublishSetAsync(string publishSetCode, bool? discardDrafts = null, CancellationToken ct = default(CancellationToken))
{
MozuClient<System.IO.Stream> response;
var client = Mozu.Api.Clients.Commerce.Catalog.Admin.PublishingScopeClient.DeletePublishSetClient( publishSetCode, discardDrafts);
client.WithContext(_apiContext);
response = await client.ExecuteAsync(ct).ConfigureAwait(false);
return await response.ResultAsync();
}
}
}
|
||||
TheStack | e005b09668af5b83d04d96423bd71c793b359d99 | C#code:C# | {"size": 2386, "ext": "cs", "max_stars_repo_path": "src/Be.Stateless.Dsl.Configuration/Xml/Extensions/XmlDocumentExtensions.cs", "max_stars_repo_name": "icraftsoftware/Be.Stateless.Dsl.Configuration", "max_stars_repo_stars_event_min_datetime": "2021-02-16T11:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T11:40:14.000Z", "max_issues_repo_path": "src/Be.Stateless.Dsl.Configuration/Xml/Extensions/XmlDocumentExtensions.cs", "max_issues_repo_name": "icraftsoftware/Be.Stateless.Dsl.Configuration", "max_issues_repo_issues_event_min_datetime": "2021-02-01T13:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T13:21:49.000Z", "max_forks_repo_path": "src/Be.Stateless.Dsl.Configuration/Xml/Extensions/XmlDocumentExtensions.cs", "max_forks_repo_name": "icraftsoftware/Be.Stateless.Dsl.Configuration", "max_forks_repo_forks_event_min_datetime": "2021-01-10T17:44:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-10T17:44:11.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 38.4838709677, "max_line_length": 168, "alphanum_fraction": 0.7904442582} | #region Copyright & License
// Copyright © 2012 - 2021 François Chabot & Emmanuel Benitez
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Be.Stateless.Dsl.Configuration;
using Be.Stateless.Dsl.Configuration.Resolver;
using Be.Stateless.Dsl.Configuration.Xml.XPath;
using Be.Stateless.Extensions;
using Be.Stateless.Xml.XPath;
namespace Be.Stateless.Xml.Extensions
{
internal static class XmlDocumentExtensions
{
internal static NamespaceAffinitiveXPathNavigator CreateDslNamespaceAffinitiveXPathNavigator(this XmlDocument document)
{
var navigator = document.CreateNamespaceAffinitiveXPathNavigator();
navigator.NamespaceManager.AddNamespace(Constants.NAMESPACE_URI_PREFIX, Constants.NAMESPACE_URI);
return navigator;
}
internal static IEnumerable<string> GetTargetConfigurationFiles(this XmlDocument document, IEnumerable<IConfigurationFileResolverStrategy> configurationFileResolvers)
{
var configurationFileResolver = new ConfigurationFileResolver(
configurationFileResolvers ?? new IConfigurationFileResolverStrategy[] {
new ClrConfigurationFileResolverStrategy(), new ConfigurationFileResolverStrategy()
});
var monikerExtractor = new ConfigurationFileMonikersExtractor(document);
return monikerExtractor.Extract()
.SelectMany(configurationFileResolver.Resolve)
.Distinct();
}
internal static XmlElement PatchDomAfterXPath(this XmlDocument document, string xpath)
{
if (xpath.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(xpath), $"'{nameof(xpath)}' cannot be null or empty.");
return (XmlElement) new XPathExpression(xpath)
.GetLocationSteps()
.Aggregate<XPathLocationStep, XmlNode>(document, (current, locationStep) => current.SelectOrAppendElement(locationStep));
}
}
}
|
||||
TheStack | e00607c523235cb65bbdf3c69ee3d3b87db43f53 | C#code:C# | {"size": 952, "ext": "cshtml", "max_stars_repo_path": "Demos/Demo.Extenso.AspNetCore.Mvc/Views/Home/Index.cshtml", "max_stars_repo_name": "gordon-matt/Extenso", "max_stars_repo_stars_event_min_datetime": "2018-05-16T16:27:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T21:50:49.000Z", "max_issues_repo_path": "Demos/Demo.Extenso.AspNetCore.Mvc/Views/Home/Index.cshtml", "max_issues_repo_name": "gordon-matt/Extenso", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Demos/Demo.Extenso.AspNetCore.Mvc/Views/Home/Index.cshtml", "max_forks_repo_name": "gordon-matt/Extenso", "max_forks_repo_forks_event_min_datetime": "2018-05-19T11:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:36:11.000Z"} | {"max_stars_count": 24.0, "max_issues_count": null, "max_forks_count": 9.0, "avg_line_length": 28.8484848485, "max_line_length": 97, "alphanum_fraction": 0.5724789916} | @using Extenso.AspNetCore.Mvc.Rendering
@model IEnumerable<PersonModel>
@{
ViewData["Title"] = "Home Page";
}
@Html.Table(Model, new { @class = "table" })
<hr />
<form>
<div class="form-group">
<label>Cultures</label>
@Html.CulturesDropDownList("Cultures", htmlAttributes: new { @class = "form-control" })
</div>
<div class="form-group">
<label>Time Zones</label>
@Html.TimeZonesDropDownList("TimeZones", htmlAttributes: new { @class = "form-control" })
</div>
<div class="form-group">
<label>CheckBox List</label>
@Html.CheckBoxList(
"DaysOfWeek",
Html.GetEnumSelectList<DayOfWeek>(),
null,
new { @class = "form-check-label" },
new { @class = "form-check-input" },
inputInsideLabel: true,
wrapInDiv: true,
wrapperHtmlAttributes: new { @class = "form-check" })
</div>
</form> |
||||
TheStack | e0087a5f14f918e486b0f241635f048119fe165a | C#code:C# | {"size": 808, "ext": "cs", "max_stars_repo_path": "BlazorServerEFCoreSample/T0001/OutHandoverCheck.cs", "max_stars_repo_name": "twoutlook/BlazorServerDbContextExample", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BlazorServerEFCoreSample/T0001/OutHandoverCheck.cs", "max_issues_repo_name": "twoutlook/BlazorServerDbContextExample", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BlazorServerEFCoreSample/T0001/OutHandoverCheck.cs", "max_forks_repo_name": "twoutlook/BlazorServerDbContextExample", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.6666666667, "max_line_length": 97, "alphanum_fraction": 0.603960396} | // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0001
{
public partial class OutHandoverCheck
{
public string Id { get; set; }
public string Cerpcode { get; set; }
public string Cinvcode { get; set; }
public string Cinvname { get; set; }
public decimal? Iqty { get; set; }
public decimal? QtyDemand { get; set; }
public decimal? QtyOut { get; set; }
public decimal? QtyHandover { get; set; }
public DateTime? Createtime { get; set; }
public string Createowner { get; set; }
public decimal? Cstatus { get; set; }
public string Sncode { get; set; }
}
} |
||||
TheStack | e0089809c44db00ee1269b5eabc8fe2ec38af1ee | C#code:C# | {"size": 1667, "ext": "cs", "max_stars_repo_path": "source/Oliviann.Common/Data/SqlClient/SqlIntegerExtensions.cs", "max_stars_repo_name": "hype8912/Oliviann", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Oliviann.Common/Data/SqlClient/SqlIntegerExtensions.cs", "max_issues_repo_name": "hype8912/Oliviann", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Oliviann.Common/Data/SqlClient/SqlIntegerExtensions.cs", "max_forks_repo_name": "hype8912/Oliviann", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.0576923077, "max_line_length": 80, "alphanum_fraction": 0.5824835033} | namespace Oliviann.Data.SqlClient
{
#region Usings
using System.Data.SqlTypes;
#endregion Usings
/// <summary>
/// Represents a collection of commonly used extension methods for extending
/// SQL integers.
/// </summary>
public static class SqlIntegerExtensions
{
#region Converts
/// <summary>
/// Converts a 16-bit SQL integer value to a nullable 16-bit integer
/// value.
/// </summary>
/// <param name="value">The 16-bit SQL integer value.</param>
/// <returns>A 32-bit nullable integer of the same value.</returns>
public static short? ToNullableInt16(this SqlInt16 value)
{
return value.IsNull ? (short?)null : value.Value;
}
/// <summary>
/// Converts a 32-bit SQL integer value to a nullable 32-bit integer
/// value.
/// </summary>
/// <param name="value">The 32-bit SQL integer value.</param>
/// <returns>A 32-bit nullable integer of the same value.</returns>
public static int? ToNullableInt32(this SqlInt32 value)
{
return value.IsNull ? (int?)null : value.Value;
}
/// <summary>
/// Converts a 64-bit SQL integer value to a nullable 64-bit integer
/// value.
/// </summary>
/// <param name="value">The 64-bit SQL integer value.</param>
/// <returns>A 64-bit nullable integer of the same value.</returns>
public static long? ToNullableInt64(this SqlInt64 value)
{
return value.IsNull ? (long?)null : value.Value;
}
#endregion Converts
}
} |
||||
TheStack | e008df08912bf4c1ba92ab4c3246584473cc6e30 | C#code:C# | {"size": 354, "ext": "cs", "max_stars_repo_path": "Source/Events/Applications/AzureStorageAccountSetForApplication.cs", "max_stars_repo_name": "aksio-insurtech/Management", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Events/Applications/AzureStorageAccountSetForApplication.cs", "max_issues_repo_name": "aksio-insurtech/Management", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Events/Applications/AzureStorageAccountSetForApplication.cs", "max_forks_repo_name": "aksio-insurtech/Management", "max_forks_repo_forks_event_min_datetime": "2022-03-03T23:39:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:39:43.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 35.4, "max_line_length": 101, "alphanum_fraction": 0.8192090395} | // Copyright (c) Aksio Insurtech. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Concepts.Azure;
namespace Events.Applications;
[EventType("df24d5c8-b4dd-4ff5-8636-588ec6699177")]
public record AzureStorageAccountSetForApplication(AzureStorageAccountName AccountName);
|
||||
TheStack | e00c3edbc9d57f6096628a5b86b940da2f92c7ea | C#code:C# | {"size": 425, "ext": "cs", "max_stars_repo_path": "Aplicacion/Codigo y Pruebas/VideoOnDemand/VideoOnDemand.Data/Repositories/FavoritoRepository.cs", "max_stars_repo_name": "NestorGuemez123/BlockbusterWeb", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Aplicacion/Codigo y Pruebas/VideoOnDemand/VideoOnDemand.Data/Repositories/FavoritoRepository.cs", "max_issues_repo_name": "NestorGuemez123/BlockbusterWeb", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Aplicacion/Codigo y Pruebas/VideoOnDemand/VideoOnDemand.Data/Repositories/FavoritoRepository.cs", "max_forks_repo_name": "NestorGuemez123/BlockbusterWeb", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.25, "max_line_length": 79, "alphanum_fraction": 0.7505882353} | using ltracker.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VideoOnDemand.Data;
using VideoOnDemand.Entities;
namespace VideoOnDemand.Repositories
{
public class FavoritoRepository : BaseRepository<Favorito>
{
public FavoritoRepository(VideoOnDemandContext context) : base(context)
{
}
}
}
|
||||
TheStack | e00d8f1c055a515c979df9630874812dd87c5a38 | C#code:C# | {"size": 290, "ext": "cs", "max_stars_repo_path": "HUD.cs", "max_stars_repo_name": "ryskulova/UnityGame", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HUD.cs", "max_issues_repo_name": "ryskulova/UnityGame", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HUD.cs", "max_forks_repo_name": "ryskulova/UnityGame", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.3333333333, "max_line_length": 36, "alphanum_fraction": 0.7620689655} | using UnityEngine;
using System.Collections;
public class HUD : MonoBehaviour {
public GameObject Player1;
public GameObject Player2;
public BoxCollider2D topWall;
public BoxCollider2D bottomWall;
public BoxCollider2D leftWall;
public BoxCollider2D rightWall;
}
|
||||
TheStack | e00e5533db2efc347d0f5c2c0b958836a099a344 | C#code:C# | {"size": 1421, "ext": "cs", "max_stars_repo_path": "Framework/Tools/WiXLib/Fragment.cs", "max_stars_repo_name": "PervasiveDigital/netmf-interpreter", "max_stars_repo_stars_event_min_datetime": "2015-03-10T00:17:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T02:21:19.000Z", "max_issues_repo_path": "Framework/Tools/WiXLib/Fragment.cs", "max_issues_repo_name": "PervasiveDigital/netmf-interpreter", "max_issues_repo_issues_event_min_datetime": "2015-03-10T22:02:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-16T13:05:00.000Z", "max_forks_repo_path": "Framework/Tools/WiXLib/Fragment.cs", "max_forks_repo_name": "PervasiveDigital/netmf-interpreter", "max_forks_repo_forks_event_min_datetime": "2015-03-10T08:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T04:18:36.000Z"} | {"max_stars_count": 529.0, "max_issues_count": 495.0, "max_forks_count": 332.0, "avg_line_length": 34.6585365854, "max_line_length": 143, "alphanum_fraction": 0.6164672766} | using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace Microsoft.SPOT.WiX
{
public class Fragment : WiXElement
{
public Fragment(string Id) : base(new XmlDocument(), "Fragment", Id)
{
thisElement.OwnerDocument.CreateXmlDeclaration("1.0", "utf-8", null);
thisElement.OwnerDocument.AppendChild(thisElement.OwnerDocument.CreateElement("Wix", "http://schemas.microsoft.com/wix/2006/wi"));
thisElement.OwnerDocument.DocumentElement.SetAttribute("xmlns", "http://schemas.microsoft.com/wix/2006/wi");
thisElement.OwnerDocument.DocumentElement.AppendChild(thisElement);
}
public void AppendInclude(string includeFile)
{
thisElement.AppendChild(
thisElement.OwnerDocument.CreateProcessingInstruction(
"include", includeFile));
}
public void PrependInclude(string includeFile)
{
thisElement.PrependChild(
thisElement.OwnerDocument.CreateProcessingInstruction(
"include", includeFile));
}
public void PrependDefine(string definition)
{
thisElement.PrependChild(
thisElement.OwnerDocument.CreateProcessingInstruction(
"define", definition));
}
}
}
|
||||
TheStack | e00e69c6425f55f7edf32d4fcd3e7124b7d37c1c | C#code:C# | {"size": 861, "ext": "cs", "max_stars_repo_path": "RepoDb.Benchmarks/RepoDb.Benchmarks.SqlServer/NHibernate/GetAllNHibernateBenchmarks.cs", "max_stars_repo_name": "Swoorup/RepoDB", "max_stars_repo_stars_event_min_datetime": "2018-04-18T08:27:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T19:53:06.000Z", "max_issues_repo_path": "RepoDb.Benchmarks/RepoDb.Benchmarks.SqlServer/NHibernate/GetAllNHibernateBenchmarks.cs", "max_issues_repo_name": "Swoorup/RepoDB", "max_issues_repo_issues_event_min_datetime": "2018-04-13T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T09:47:54.000Z", "max_forks_repo_path": "RepoDb.Benchmarks/RepoDb.Benchmarks.SqlServer/NHibernate/GetAllNHibernateBenchmarks.cs", "max_forks_repo_name": "Swoorup/RepoDB", "max_forks_repo_forks_event_min_datetime": "2018-06-19T13:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T15:15:58.000Z"} | {"max_stars_count": 1060.0, "max_issues_count": 472.0, "max_forks_count": 78.0, "avg_line_length": 28.7, "max_line_length": 73, "alphanum_fraction": 0.6515679443} | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using NHibernate.Transform;
using RepoDb.Benchmarks.SqlServer.Models;
namespace RepoDb.Benchmarks.SqlServer.NHibernate
{
public class GetAllNHibernateBenchmarks : NHibernateBaseBenchmarks
{
private readonly Consumer consumer = new ();
[Benchmark]
public void QueryAll()
{
using var session = SessionFactory.OpenStatelessSession();
session.Query<Person>().Consume(consumer);
}
[Benchmark]
public void CreateSQLQueryAll()
{
using var session = SessionFactory.OpenStatelessSession();
session.CreateSQLQuery("select * from Person")
.SetResultTransformer(Transformers.AliasToBean<Person>())
.List<Person>().Consume(consumer);
}
}
} |
||||
TheStack | e0118576e0f0e0349dfd8261eb17068bdfd2fb0a | C#code:C# | {"size": 1234, "ext": "cs", "max_stars_repo_path": "Serenity.Script.UI/Editor/EditorTypeEditor.cs", "max_stars_repo_name": "davidzhang9990/SimpleProject", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Serenity.Script.UI/Editor/EditorTypeEditor.cs", "max_issues_repo_name": "davidzhang9990/SimpleProject", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Serenity.Script.UI/Editor/EditorTypeEditor.cs", "max_forks_repo_name": "davidzhang9990/SimpleProject", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.641025641, "max_line_length": 119, "alphanum_fraction": 0.5680713128} | using jQueryApi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Serenity
{
[Editor, DisplayName("Editör Tipi")]
[Element("<input type=\"hidden\" />")]
public class EditorTypeEditor : SelectEditor, IStringValue
{
private static List<object> editorTypeList;
public EditorTypeEditor(jQueryObject select)
: base(select, new SelectEditorOptions { EmptyOptionText = Q.Text("Controls.SelectEditor.EmptyItemText") })
{
}
protected override List<object> GetItems()
{
if (editorTypeList == null)
{
editorTypeList = new List<object>();
foreach (var info in PublicEditorTypes.RegisteredTypes)
editorTypeList.Add(new object[] { info.Key, info.Value.DisplayName });
editorTypeList.Sort((x, y) =>
{
var xn = x.As<object[]>()[1].As<string>();
var yn = y.As<object[]>()[1].As<string>();
return Q.Externals.TurkishLocaleCompare(xn, yn);
});
}
return editorTypeList;
}
}
} |
||||
TheStack | e012d86b6ac1bf1b50ca431145041cdaeee848d5 | C#code:C# | {"size": 628, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Camera/CameraControlImplementations.cs", "max_stars_repo_name": "awjc/MENDEL-Sim", "max_stars_repo_stars_event_min_datetime": "2015-04-13T03:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-20T01:32:37.000Z", "max_issues_repo_path": "Assets/Scripts/Camera/CameraControlImplementations.cs", "max_issues_repo_name": "awjc/MENDEL-Sim", "max_issues_repo_issues_event_min_datetime": "2016-03-27T11:33:16.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-27T11:33:16.000Z", "max_forks_repo_path": "Assets/Scripts/Camera/CameraControlImplementations.cs", "max_forks_repo_name": "awjc/MENDEL-Sim", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 22.4285714286, "max_line_length": 82, "alphanum_fraction": 0.6624203822} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public enum CameraControlImplementation
{
Keyboard,
Gamepad
}
public class CameraControlImplementations
{
public static ICameraControls GetControlsFor(CameraControlImplementation impl)
{
switch (impl)
{
case CameraControlImplementation.Keyboard:
return new KeyboardCameraControls();
case CameraControlImplementation.Gamepad:
return new KeyboardCameraControls();
default:
return new NoOpCameraControls();
}
}
}
|
||||
TheStack | e01462c2c425e94145ffe1480d361e659bd87b15 | C#code:C# | {"size": 376, "ext": "cs", "max_stars_repo_path": "src/Iauq.Data/Migrations/201207030741286_LogLevelAddedToLogs.cs", "max_stars_repo_name": "m-sadegh-sh/Iauq", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Iauq.Data/Migrations/201207030741286_LogLevelAddedToLogs.cs", "max_issues_repo_name": "m-sadegh-sh/Iauq", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Iauq.Data/Migrations/201207030741286_LogLevelAddedToLogs.cs", "max_forks_repo_name": "m-sadegh-sh/Iauq", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.1176470588, "max_line_length": 75, "alphanum_fraction": 0.5718085106} | using System.Data.Entity.Migrations;
namespace Iauq.Data.Migrations
{
public partial class LogLevelAddedToLogs : DbMigration
{
public override void Up()
{
AddColumn("Logs", "LevelShort", c => c.Short(nullable: false));
}
public override void Down()
{
DropColumn("Logs", "LevelShort");
}
}
} |