blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
75a4a7a80c0d0e557e5db5dd9963bdd007598b4b
|
C#
|
VenciNanov/TechModuleSeptember2017
|
/10.FilesExceptions-Homework/04.MaxSequenceOfEqualSums/Program.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.MaxSequenceOfEqualSums
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = File.ReadAllText("input.txt")
.Split(' ')
.Select(int.Parse)
.ToList();
int maxStart = 0;
int maxLen = 1;
int currentStart = 0;
int currentLen = 1;
for (int i = 1; i <= numbers.Count - 1; i++)
{
if (numbers[i] == numbers[currentStart])
{
currentLen++;
if (currentLen > maxLen)
{
maxLen = currentLen;
maxStart = currentStart;
}
}
else
{
currentLen = 1;
currentStart = i;
}
}
File.Delete("output.txt");
for (int i = maxStart; i < maxStart + maxLen; i++)
{
File.AppendAllText("output.txt", numbers[i].ToString()+" ");
}
}
}
}
|
0e1379d18e74f93bf4181e82cbec3bdc206e401e
|
C#
|
Man-of-Manis/Witchs-Brew
|
/Assets/Scripts/Interactables/Items/KeyCube.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum KeyCubeColor { Red = 0, Orange = 1, Yellow = 2, Green = 3, Blue = 4, Purple = 5 };
public class KeyCube : MonoBehaviour, IItems
{
[SerializeField] private KeyCubeColor keyCubeType;
private ChestKeyCubeSpawner cubeSpawner;
/// <summary>
/// Gets the color of the KeyCube.
/// </summary>
public KeyCubeColor KeyColor
{
get { return keyCubeType; }
}
/// <summary>
/// Gets and Sets the chest the KeyCube spawned from.
/// </summary>
public ChestKeyCubeSpawner Spawner
{
get { return cubeSpawner; }
set { cubeSpawner = value; }
}
/// <summary>
/// Resets the chest the cube spawned from and destroys the cube.
/// </summary>
public void Killbox()
{
if (Spawner != null)
{
Spawner.ResetChest();
}
Destroy(this.gameObject);
}
/// <summary>
/// Destroys KeyCube when added to satchel.
/// </summary>
public void AddToSatchel()
{
Destroy(this.gameObject);
}
}
|
51a505327769732f0452767dcbcb8620a0577d2d
|
C#
|
robin-han/typescript-converter
|
/src/TypeScriptObject/Source/Array.cs
| 3.171875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TypeScript.CSharp
{
public class Array<T> : Object, IEnumerable<T>
{
#region Fields
/// <summary>
///
/// </summary>
private List<T> _list;
private object _from = null; //Used for As,
#endregion
#region Constructors
/// <summary>
///
/// </summary>
public Array()
{
this.__value__ = this._list = new List<T>();
}
/// <summary>
///
/// </summary>
public Array(Number length)
{
this.__value__ = this._list = new List<T>();
this.length = length;
}
/// <summary>
///
/// </summary>
/// <param name="v"></param>
public Array(T v)
{
this.__value__ = this._list = new List<T>();
this._list.Add(v);
}
/// <summary>
/// Initialize a new instance with the items.
/// </summary>
public Array(IEnumerable<T> items)
{
if (items == null)
{
throw new ArgumentNullException();
}
this.__value__ = this._list = new List<T>(items);
}
/// <summary>
///
/// </summary>
private Array(Undefined value)
{
this._list = null;
this.__value__ = value;
}
#endregion
#region Properties
/// <summary>
///
/// </summary>
public Type ValueType
{
get { return typeof(T); }
}
/// <summary>
///
/// </summary>
public T this[Number index]
{
get
{
return this[(int)index];
}
set
{
this[(int)index] = value;
}
}
/// <summary>
///
/// </summary>
public T this[int index]
{
get
{
this.CheckUndefined();
if (0 <= index && index < _list.Count)
{
return _list[(int)index];
}
return default(T);
}
set
{
this.CheckUndefined();
int count = _list.Count;
if (index >= count)
{
this.length = index + 1;
}
_list[index] = value;
}
}
/// <summary>
///
/// </summary>
public Number length
{
get
{
this.CheckUndefined();
return _list.Count;
}
set
{
this.CheckUndefined();
int newCount = Convert.ToInt32((double)value);
if (value < 0 || newCount != (double)value)
{
throw new ArgumentException("length must be 0 or positive integer.");
}
int count = this._list.Count;
if (newCount < count)
{
this.InternalRemoveRange(newCount, count - newCount);
}
else if (newCount > count)
{
for (int i = count; i < newCount; i++)
{
this.InternalAdd(default(T));
}
}
}
}
/// <summary>
///
/// </summary>
public Number Length
{
get { return this.length; }
set { this.length = value; }
}
/// <summary>
///
/// </summary>
public int Count
{
get
{
return (int)this.length;
}
set
{
this.length = value;
}
}
#endregion
#region Operator Implicit
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(Undefined value)
{
return new Array<T>(value);
}
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(List<T> list)
{
if (list == null)
{
return null;
}
Array<T> arr = new Array<T>();
arr.__value__ = arr._list = list;
return arr;
}
/// <summary>
///
/// </summary>
public static implicit operator List<T>(Array<T> array)
{
return array == null ? null : array._list;
}
/// <summary>
///
/// </summary>
public static implicit operator T[](Array<T> array)
{
return array == null ? null : array._list.ToArray();
}
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(T[] ts)
{
return ts == null ? null : new Array<T>(ts);
}
#endregion
#region Operator Implicit(list<string/bool/double/datetime)
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(List<string> list)
{
if (list == null)
{
return null;
}
if (typeof(T).Name != "String")
{
throw new InvalidOperationException("can not convert string to " + typeof(T).Name);
}
Array<T> ret = new Array<T>();
foreach (string item in list)
{
ret.Add((T)Convert.ChangeType((String)item, typeof(T)));
}
return ret;
}
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(List<double> list)
{
if (list == null)
{
return null;
}
if (typeof(T).Name != "Number")
{
throw new InvalidOperationException("can not convert double to " + typeof(T).Name);
}
Array<T> ret = new Array<T>();
foreach (double item in list)
{
ret.Add((T)Convert.ChangeType((Number)item, typeof(T)));
}
return ret;
}
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(List<bool> list)
{
if (list == null)
{
return null;
}
if (typeof(T).Name != "Boolean")
{
throw new InvalidOperationException("can not convert bool to " + typeof(T).Name);
}
Array<T> ret = new Array<T>();
foreach (bool item in list)
{
ret.Add((T)Convert.ChangeType((Boolean)item, typeof(T)));
}
return ret;
}
/// <summary>
///
/// </summary>
public static implicit operator Array<T>(List<DateTime> list)
{
if (list == null)
{
return null;
}
if (typeof(T).Name != "Date")
{
throw new InvalidOperationException("can not convert DateTime to " + typeof(T).Name);
}
Array<T> ret = new Array<T>();
foreach (DateTime item in list)
{
ret.Add((T)Convert.ChangeType((Date)item, typeof(T)));
}
return ret;
}
#endregion
#region Implements Interfaces
/// <summary>
///
/// </summary>
public IEnumerator<T> GetEnumerator()
{
this.CheckUndefined();
return _list.GetEnumerator();
}
/// <summary>
///
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
this.CheckUndefined();
return _list.GetEnumerator();
}
#endregion
#region Methods
/// <summary>
///
/// </summary>
public void Add(T item)
{
this.CheckUndefined();
this.InternalAdd(item);
}
/// <summary>
///
/// </summary>
public void AddRange(IEnumerable<T> items)
{
this.CheckUndefined();
this.InternalAddRange(items);
}
/// <summary>
///
/// </summary>
/// <typeparam name="U"></typeparam>
/// <returns></returns>
public override Array<U> AsArray<U>()
{
if (typeof(U) == typeof(T))
{
return (this as Array<U>);
}
Array<U> ret = new Array<U>();
bool canAs = (this._list.Count > 0 ? this._list[0] is U : false);
foreach (object item in this._list)
{
if (item == null || canAs)
{
ret.push((U)item);
}
else
{
string type = item.GetType().Name;
switch (type)
{
case "Double":
case "Int32":
case "Int64":
double dItem = (double)item;
ret.push((U)Convert.ChangeType((Number)dItem, typeof(U)));
break;
case "String":
string sItem = (string)item;
ret.push((U)Convert.ChangeType((String)sItem, typeof(U)));
break;
case "Boolean":
bool bItem = (bool)item;
ret.push((U)Convert.ChangeType((Boolean)bItem, typeof(U)));
break;
default:
throw new InvalidCastException(string.Format("Cannot convert from {0} to {1}", item.GetType().Name, typeof(U).Name)); ;
}
}
}
ret._from = this;
return ret;
}
/// <summary>
///
/// </summary>
public void clear()
{
this.CheckUndefined();
this.InternalClear();
}
/// <summary>
///
/// </summary>
public Array<T> concat()
{
return this.concat(new Array<T>());
}
/// <summary>
///
/// </summary>
public Array<T> concat(params T[] items)
{
return this.concat(items.ToList());
}
/// <summary>
///
/// </summary>
public Array<T> concat(params T[][] items)
{
Array<T> all = new Array<T>();
foreach (var item in items)
{
all.AddRange(item);
}
return this.concat(all);
}
/// <summary>
///
/// </summary>
public Array<T> concat(Array<T> items)
{
this.CheckUndefined();
Array<T> ret = new Array<T>(this);
ret.AddRange(items);
return ret;
}
//public abstract Array<T> copyWithin(Number index);
//public abstract Array<T> copyWithin(Number index, Number from);
//public abstract Array<T> copyWithin(Number index, Number from, Number to);
//public abstract IEnumerable<TypeScript.KeyValuePair> entries();
//public abstract Number[] keys();
/// <summary>
///
/// </summary>
public bool every(Func<T, bool> predicate)
{
this.CheckUndefined();
return this._list.All(predicate);
}
public bool every(Func<T, Number, bool> predicate)
{
this.CheckUndefined();
List<T> items = this._list;
for (int i = 0, count = items.Count; i < count; i++)
{
if (!predicate(items[i], i))
{
return false;
}
}
return true;
}
/// <summary>
///
/// </summary>
public Array<T> filter(Func<T, bool> predicate)
{
this.CheckUndefined();
var items = this._list.Where(predicate);
return new Array<T>(items);
}
/// <summary>
///
/// </summary>
public Array<T> filter(Func<T, int, bool> predicate)
{
this.CheckUndefined();
var items = this._list.Where(predicate);
return new Array<T>(items);
}
/// <summary>
///
/// </summary>
public T find(Predicate<T> match)
{
this.CheckUndefined();
return this._list.Find(match);
}
/// <summary>
///
/// </summary>
public Number findIndex(Predicate<T> match)
{
this.CheckUndefined();
return this._list.FindIndex(match);
}
/// <summary>
///
/// </summary>
public void forEach(Action<T> action)
{
this.CheckUndefined();
this._list.ForEach(action);
}
/// <summary>
///
/// </summary>
public void forEach(Action<T, Number> action)
{
this.CheckUndefined();
for (int i = 0; i < this._list.Count; i++)
{
action(this._list[i], i);
}
}
/// <summary>
///
/// </summary>
public bool includes(T item)
{
return this.includes(item, 0);
}
/// <summary>
///
/// </summary>
public bool includes(T item, Number fromIndex)
{
this.CheckUndefined();
return this._list.IndexOf(item, (int)fromIndex) >= 0;
}
/// <summary>
///
/// </summary>
public Number indexOf(T item)
{
return this.indexOf(item, 0);
}
/// <summary>
///
/// </summary>
public Number indexOf(T item, Number fromIndex)
{
this.CheckUndefined();
return this._list.IndexOf(item, 0);
}
/// <summary>
///
/// </summary>
public String join()
{
return this.join(",");
}
/// <summary>
///
/// </summary>
public String join(String separator)
{
return string.Join(separator, this._list);
}
/// <summary>
///
/// </summary>
public Number lastIndexOf(T item)
{
return this.lastIndexOf(item, this._list.Count - 1);
}
/// <summary>
///
/// </summary>
public Number lastIndexOf(T item, Number fromIndex)
{
this.CheckUndefined();
return this._list.LastIndexOf(item, (int)fromIndex);
}
/// <summary>
///
/// </summary>
public Array<U> map<U>(Func<T, U> func)
{
this.CheckUndefined();
Array<U> ret = new Array<U>();
foreach (var item in this._list)
{
ret.Add(func(item));
}
return ret;
}
/// <summary>
///
/// </summary>
public Array<U> map<U>(Func<T, Number, U> func)
{
this.CheckUndefined();
Array<U> ret = new Array<U>();
for (int i = 0; i < this._list.Count; i++)
{
ret.Add(func(this._list[i], i));
}
return ret;
}
/// <summary>
///
/// </summary>
public T pop()
{
this.CheckUndefined();
int index = this._list.Count - 1;
if (index < 0)
{
return default(T);
}
T ret = this._list[index];
this.InternalRemoveAt(index);
return ret;
}
/// <summary>
///
/// </summary>
public Number push(params T[] items)
{
this.CheckUndefined();
this.InternalAddRange(items);
return this._list.Count;
}
/// <summary>
///
/// </summary>
public Number push(T item)
{
this.CheckUndefined();
this.InternalAdd(item);
return this._list.Count;
}
public T reduce(Func<T, T, T> func, T initialValue = default(T))
{
return this.reduce<T>(func, initialValue);
}
/// <summary>
///
/// </summary>
public T1 reduce<T1>(Func<T1, T, T1> func, T1 initialValue = default(T1))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
int index = 0;
if (initialValue == null && items.Count > 0)
{
initialValue = (T1)Convert.ChangeType(items[0], typeof(T1));
index++;
}
T1 result = initialValue;
for (; index < items.Count; index++)
{
result = func(result, items[index]);
}
return result;
}
/// <summary>
///
/// </summary>
public T reduce(Func<T, T, Number, T> func, T initialValue = default(T))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
int index = 0;
if (initialValue == null && items.Count > 0)
{
initialValue = items[0];
index++;
}
T result = initialValue;
for (; index < items.Count; index++)
{
result = func(result, items[index], index);
}
return result;
}
/// <summary>
///
/// </summary>
public U reduce<U>(Func<U, T, Number, U> func, U initialValue = default(U))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
U result = initialValue;
for (int i = 0; i < items.Count; i++)
{
result = func(result, items[i], i);
}
return result;
}
/// <summary>
///
/// </summary>
public T reduceRight(Func<T, T, T> func, T initialValue = default(T))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
int index = items.Count - 1;
if (initialValue == null && items.Count > 0)
{
initialValue = items[items.Count - 1];
index--;
}
T result = initialValue;
for (; index >= 0; index--)
{
result = func(result, items[index]);
}
return result;
}
/// <summary>
///
/// </summary>
public T reduceRight(Func<T, T, Number, T> func, T initialValue = default(T))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
int index = items.Count - 1;
if (initialValue == null && items.Count > 0)
{
initialValue = items[items.Count - 1];
index--;
}
T result = initialValue;
for (; index >= 0; index--)
{
result = func(result, items[index], index);
}
return result;
}
/// <summary>
///
/// </summary>
public U reduceRight<U>(Func<U, T, Number, U> func, U initialValue = default(U))
{
this.CheckUndefined();
List<T> items = this._list;
if (initialValue == null && items.Count == 0)
{
throw new InvalidOperationException("Reduce of empty array with no initial value");
}
U result = initialValue;
for (int i = items.Count - 1; i >= 0; i--)
{
result = func(result, items[i], i);
}
return result;
}
/// <summary>
///
/// </summary>
public Array<T> reverse()
{
this.CheckUndefined();
this.InternalReverse();
return this;
}
/// <summary>
///
/// </summary>
public T shift()
{
this.CheckUndefined();
if (this._list.Count == 0)
{
return default(T);
}
T ret = this._list[0];
this.InternalRemoveAt(0);
return ret;
}
/// <summary>
///
/// </summary>
public Array<T> slice()
{
return this.slice(0, this._list.Count);
}
/// <summary>
///
/// </summary>
public Array<T> slice(Number start)
{
return this.slice(start, this._list.Count);
}
/// <summary>
///
/// </summary>
public Array<T> slice(Number begin, Number end)
{
this.CheckUndefined();
List<T> items = this._list;
if (IsNull(begin) || IsUndefined(begin))
{
begin = 0;
}
if (begin < 0)
{
begin = System.Math.Max(0, items.Count + begin);
}
if (IsNull(end) || IsUndefined(end))
{
end = items.Count;
}
if (end < 0)
{
end = System.Math.Max(0, items.Count + end);
}
end = System.Math.Min(end, items.Count);
Array<T> ret = new Array<T>();
int beginIndex = (int)begin;
int endIndex = (int)end;
for (int i = beginIndex; i < endIndex; i++)
{
ret.Add(items[i]);
}
return ret;
}
/// <summary>
///
/// </summary>
public bool some(Func<T, bool> predicate)
{
this.CheckUndefined();
return this._list.Any(predicate);
}
/// <summary>
///
/// </summary>
public bool some(Func<T, Number, bool> func)
{
this.CheckUndefined();
List<T> items = this._list;
for (int i = 0; i < items.Count; i++)
{
if (func(items[i], i))
{
return true;
}
}
return false;
}
/// <summary>
///
/// </summary>
public Array<T> sort(IComparer<T> comparer = null)
{
this.CheckUndefined();
if (comparer == null)
{
this.InternalSort();
}
else
{
this.InternalCompareSort(comparer);
}
return this;
}
/// <summary>
///
/// </summary>
public Array<T> sort(Func<T, T, Number> fn)
{
ArrayComparer<T> compare = new ArrayComparer<T>(fn);
return this.sort(compare);
}
/// <summary>
///
/// </summary>
public Array<T> sort(Comparison<T> comparison)
{
ArrayComparer<T> compare = new ArrayComparer<T>(comparison);
return this.sort(compare);
}
/// <summary>
///
/// </summary>
public Array<T> splice(Number start, Number deleteCount = null, params T[] addItems)
{
this.CheckUndefined();
List<T> items = this._list;
if (IsNull(start) || IsUndefined(start))
{
start = items.Count;
}
if (start < 0)
{
start = System.Math.Max(0, items.Count + start);
}
if (IsNull(deleteCount) || IsUndefined(deleteCount))
{
deleteCount = items.Count;
}
deleteCount = System.Math.Max(0, deleteCount);
//
int index = (int)start;
int count = (int)deleteCount;
Array<T> ret = items.GetRange(index, count);
items.RemoveRange(index, count);
items.InsertRange(index, addItems);
return ret;
}
/// <summary>
///
/// </summary>
public Number unshift(params T[] items)
{
this.InternalInsertRange(0, items);
return this._list.Count;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Array<T> valueOf()
{
return this;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override String toString()
{
List<string> stringItems = new List<string>();
foreach (T item in this._list)
{
if (IsNull(item))
{
stringItems.Add("");
}
else if (item is Object)
{
if (IsUndefined(item as Object))
{
stringItems.Add("");
}
else
{
stringItems.Add((item as Object).toString());
}
}
else
{
stringItems.Add(item.ToString());
}
}
return string.Join(",", stringItems);
}
#region Private Methods
private void InternalAdd(T item)
{
this._list.Add(item);
if (this._from != null)
{
System.Reflection.MethodInfo addMethod = this._from.GetType().GetMethod("InternalAdd", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
Type fromType = this.ValueType;
addMethod.Invoke(this._from, new object[] { this.TypeCast(fromType, toType, item) });
}
}
private void InternalAddRange(IEnumerable<T> items)
{
this._list.AddRange(items);
if (this._from != null)
{
System.Reflection.MethodInfo addMethod = this._from.GetType().GetMethod("InternalAdd", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
Type fromType = this.ValueType;
foreach (var item in items)
{
addMethod.Invoke(this._from, new object[] { this.TypeCast(fromType, toType, item) });
}
}
}
private void InternalInsert(int index, T item)
{
this._list.Insert(index, item);
if (this._from != null)
{
System.Reflection.MethodInfo insertMethod = this._from.GetType().GetMethod("InternalInsert", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
Type fromType = this.ValueType;
insertMethod.Invoke(this._from, new object[] { index, this.TypeCast(fromType, toType, item) });
}
}
private void InternalInsertRange(int index, IEnumerable<T> items)
{
this._list.InsertRange(index, items);
if (this._from != null)
{
System.Reflection.MethodInfo insertMethod = this._from.GetType().GetMethod("InternalInsert", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
Type fromType = this.ValueType;
for (int i = items.Count() - 1; i >= 0; i--)
{
insertMethod.Invoke(this._from, new object[] { index, this.TypeCast(fromType, toType, items.ElementAt(i)) });
}
}
}
private void InternalRemoveAt(int index)
{
this._list.RemoveAt(index);
if (this._from != null)
{
System.Reflection.MethodInfo removeAtMethod = this._from.GetType().GetMethod("InternalRemoveAt", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
removeAtMethod.Invoke(this._from, new object[] { index });
}
}
private void InternalRemoveRange(int index, int count)
{
this._list.RemoveRange(index, count);
if (this._from != null)
{
System.Reflection.MethodInfo removeAtMethod = this._from.GetType().GetMethod("InternalRemoveAt", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
for (int i = 0; i < count; i++)
{
removeAtMethod.Invoke(this._from, new object[] { index });
}
}
}
private void InternalClear()
{
this._list.Clear();
if (this._from != null)
{
System.Reflection.MethodInfo clearMethod = this._from.GetType().GetMethod("InternalClear", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
clearMethod.Invoke(this._from, new object[] { });
}
}
private void InternalSort()
{
this._list = this._list.OrderBy(item => item).ToList();
if (this._from != null)
{
System.Reflection.MethodInfo sortMethod = this._from.GetType().GetMethod("InternalSort", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
sortMethod.Invoke(this._from, new object[] { });
}
}
private void InternalCompareSort(IComparer<T> comparer)
{
this._list = this._list.OrderBy(item => item, comparer).ToList();
if (this._from != null)
{
if (comparer is IComparer)
{
System.Reflection.MethodInfo compareSortMethod = this._from.GetType().GetMethod("InternalCompareSort2", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
compareSortMethod.Invoke(this._from, new object[] { comparer });
}
else
{
Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
throw new InvalidCastException(string.Format("Cannot cast from {0} to System.Collections.Generic.IComparer<{1}>", comparer.GetType(), toType));
}
}
}
private void InternalCompareSort2(IComparer comparer)
{
IComparer<T> orderByComparer = null;
if (comparer is IComparer<T>)
{
orderByComparer = (IComparer<T>)comparer;
}
else
{
orderByComparer = new ArrayComparer<T>(comparer);
}
this._list = this._list.OrderBy(item => item, orderByComparer).ToList();
if (this._from != null)
{
System.Reflection.MethodInfo compareSortMethod = this._from.GetType().GetMethod("InternalCompareSort2", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
compareSortMethod.Invoke(this._from, new object[] { comparer });
}
}
private void InternalReverse()
{
this._list.Reverse();
if (this._from != null)
{
System.Reflection.MethodInfo reverseMethod = this._from.GetType().GetMethod("InternalReverse", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
reverseMethod.Invoke(this._from, new object[] { });
}
}
private object TypeCast(Type fromType, Type toType, object item)
{
if (fromType.Name == "Number" && toType.Name == "Double")
{
return item == null ? 0 : (double)(Number)item;
}
else
{
return item;
}
}
#endregion
#endregion
}
class ArrayComparer<T> : IComparer<T>, IComparer
{
private readonly Func<T, T, Number> _fn;
private readonly Comparison<T> _comparison;
private readonly IComparer _comparer;
public ArrayComparer(Func<T, T, Number> fn)
{
this._fn = fn ?? throw new ArgumentNullException("fn");
}
public ArrayComparer(Comparison<T> comparison)
{
this._comparison = comparison ?? throw new ArgumentNullException("comparison");
}
public ArrayComparer(IComparer comparer)
{
this._comparer = comparer;
}
public int Compare(T x, T y)
{
double result = 0;
if (this._fn != null)
{
result = _fn(x, y);
}
else if (this._comparison != null)
{
result = this._comparison(x, y);
}
else if (this._comparer != null)
{
result = this._comparer.Compare(x, y);
}
if (result > 0)
{
return 1;
}
else if (result < 0)
{
return -1;
}
else
{
return 0;
}
}
public int Compare(object x, object y)
{
return this.Compare((T)x, (T)y);
}
}
public class Array : Array<object>
{
public Array(object arg)
{
if (ObjectUtil.IsNumber(arg))
{
double value = ObjectUtil.ToDouble(arg);
int length = Convert.ToInt32(value);
if (length < 0 || length != value)
{
throw new ArgumentException("length must be 0 or position integer.");
}
this.Length = length;
}
else
{
this.Add(arg);
}
}
public static bool isArray(object obj)
{
if (obj == null)
{
return false;
}
return obj.GetType().Name == "Array`1";
}
}
}
|
27440b6d252d8d5a1d07604a4c8719c543eaf204
|
C#
|
frostsergei/Multiplication_Division_Matrix
|
/ControlWork1/ControlWork1/MultiplicationPage.xaml.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ControlWork1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MultiplicationPage : ContentPage
{
public MultiplicationPage ()
{
InitializeComponent ();
}
private static bool isNumber(string s)
{
bool b = int.TryParse(s, out int i);
return b;
}
private static bool isNumber(string str1, string str2)
{
bool b = ((isNumber(str1)) && (isNumber(str2)));
return b;
}
private static bool checkEmpty(string str1, string str2)
{
bool b = ((str1 == null) || (str2 == null));
return b;
}
public bool badData(string str1, string str2)
{
bool b1 = checkEmpty(str1, str2);
bool b2 = isNumber(str1, str2);
bool b = (b1 ? true : !b2);
if (b) DisplayAlert("Warning!", "Заполните пустые строки и проверьте корректность введённых чисел!", "Сейчас проверю!");
return b;
}
public bool goodData(string n, string p)
{
if ((p == "0") && (n == "0"))
{
DisplayAlert("...", "Зачем Вы пытаетесь перемножить два нуля друг на друга?", "Ой!");
return false;
}
if ((p == "0") || (n == "0"))
{
DisplayAlert("Секундочку...", "Зачем Вы пытаетесь определить умножить на 0?", "Ой!");
return false;
}
return true;
}
private void FourieClicked(object sender, EventArgs e)
{
if (badData(TextBox1.Text, TextBox2.Text)) return;
string x = TextBox1.Text;
string y = TextBox2.Text;
string log = string.Empty;
if (!goodData(x, y)) return;
string res = Fourie.FourieMultiplication(x, y, ref log);
Result.Text = res;
Solution.Text = log;
}
private void ShortClicked(object sender, EventArgs e)
{
if (badData(TextBox1.Text, TextBox2.Text)) return;
string x = TextBox1.Text;
string y = TextBox2.Text;
string log = string.Empty;
if (!goodData(x, y)) return;
string res = Shortened.ShortMultiplication(x, y, ref log);
Result.Text = res;
Solution.Text = log;
}
private void RussianClicked(object sender, EventArgs e)
{
if (badData(TextBox1.Text, TextBox2.Text)) return;
ulong x = (ulong)Convert.ToInt64(TextBox1.Text);
ulong y = (ulong)Convert.ToInt64(TextBox2.Text);
string log = string.Empty;
if (!goodData(x.ToString(), y.ToString())) return;
string res = Russian.RussianMultiplication(x, y, ref log);
Result.Text = res;
Solution.Text = log;
}
private void KarazubaClicked(object sender, EventArgs e)
{
if (badData(TextBox1.Text, TextBox2.Text)) return;
ulong x = (ulong)Convert.ToInt64(TextBox1.Text);
ulong y = (ulong)Convert.ToInt64(TextBox2.Text);
string log = string.Empty;
if (!goodData(x.ToString(), y.ToString())) return;
string res = Karazuba.KarazubaMultiplication(x, y, ref log, 0).ToString();
Result.Text = res;
Solution.Text = log;
}
}
}
|
ff9235b6dd34dc804e3992c1c8c4f5b48d07c9a8
|
C#
|
Dacheng-Wang/ExcelMerge
|
/ExcelMerge.GUI/Commands/DiffCommand.cs
| 2.515625
| 3
|
using System.Collections.Generic;
using System.IO;
using ExcelMerge.GUI.Views;
using ExcelMerge.GUI.ViewModels;
namespace ExcelMerge.GUI.Commands
{
public class DiffCommand : ICommand
{
public static readonly List<string> DefaultEnabledExtensions = new List<string>
{
".xls", ".xlsx", ".csv", "tsv",
};
public CommandLineOption Option { get; }
public DiffCommand(CommandLineOption option)
{
Option = option;
}
public void Execute()
{
var window = new MainWindow();
var diffView = new DiffView();
var windowViewModel = new MainWindowViewModel(diffView);
var diffViewModel = new DiffViewModel(Option.SrcPath, Option.DstPath, windowViewModel);
window.DataContext = windowViewModel;
diffView._diffViewModel = diffViewModel;
diffView.DataContext = diffViewModel;
App.Current.MainWindow = window;
window.Show();
}
public void ValidateOption()
{
if (Option == null)
throw new Exceptions.ExcelMergeException(true, "Option is null");
if (!string.IsNullOrEmpty(Option.SrcPath) && Path.GetFileName(Option.SrcPath) == Option.EmptyFileName)
Option.SrcPath = EnsureFile(Option.SrcPath);
if (!string.IsNullOrEmpty(Option.DstPath) && Path.GetFileName(Option.DstPath) == Option.EmptyFileName)
Option.DstPath = EnsureFile(Option.DstPath);
if (Option.ValidateExtension)
{
if (!string.IsNullOrEmpty(Option.SrcPath) && !DefaultEnabledExtensions.Contains(Path.GetExtension(Option.SrcPath)) ||
!string.IsNullOrEmpty(Option.DstPath) && !DefaultEnabledExtensions.Contains(Path.GetExtension(Option.DstPath)))
{
throw new Exceptions.ExcelMergeException(!Option.ImmediatelyExecuteExternalCommand, "Invalid extension.");
}
}
}
private string EnsureFile(string path)
{
if (!File.Exists(path))
return CreateEmptyFile(ExcelWorkbookType.XLSX);
var workbookType = ExcelUtility.GetWorkbookType(path);
if (workbookType == ExcelWorkbookType.None)
return CreateEmptyFile(ExcelWorkbookType.XLSX);
return path;
}
private string CreateEmptyFile(ExcelWorkbookType workbookType)
{
var emptyFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xlsx");
ExcelUtility.CreateWorkbook(emptyFilePath, workbookType);
return emptyFilePath;
}
}
}
|
bf64084b2cab3e801ae960f381c2d43e7c1acb7d
|
C#
|
Vulnerator/Vulnerator
|
/Model/Entity/DADMS_Network.cs
| 2.515625
| 3
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Vulnerator.Model.Entity
{
public class DADMS_Network : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DADMS_Network()
{ Softwares = new ObservableCollection<Software>(); }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long DADMS_Network_ID { get; set; }
[Required]
[StringLength(100)]
public string DADMS_NetworkName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Software> Softwares { get; set; }
}
}
|
fbdc9f21f7527aefbec211058d4b813c8d3a9813
|
C#
|
charantejg/GislenSoftware
|
/PubSubusingEvents/Program.cs
| 3.390625
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
// Creating Instance of Publisher
Publisher youtube = new Publisher("Youtube.Com", 2000);
Publisher facebook = new Publisher("Facebook.com", 1000);
//Create Instances of Subscribers
Subscriber sub1 = new Subscriber("Florin");
Subscriber sub2 = new Subscriber("Piagio");
Subscriber sub3 = new Subscriber("Shawn");
//Pass the publisher obj to their Subscribe function
sub1.Subscribe(facebook);
sub3.Subscribe(facebook);
sub1.Subscribe(youtube);
sub2.Subscribe(youtube);
//sub1.Unsubscribe(facebook);
//Concurrently running multiple publishers thread
Task task1 = Task.Factory.StartNew(() => youtube.Publish());
Task task2 = Task.Factory.StartNew(() => facebook.Publish());
Task.WaitAll(task1, task2);
Task task3 = Task.Factory.StartNew(()=> youtube.Publish());
}
}
public class NotificationEvent{
public string NotificationMessage { get; private set; }
public DateTime NotificationDate { get; private set; }
public NotificationEvent(DateTime _dateTime, string _message)
{
NotificationDate = _dateTime;
NotificationMessage = _message;
}
}
public class Publisher{
public string PublisherName { get; private set; }
public int NotificationInterval { get; private set; }
//** Declare an Event...
// declare a delegate with any name
public delegate void Notify(Publisher p, NotificationEvent e);
// declare a variable of the delegate with event keyword
public event Notify OnPublish;
public Publisher(string _publisherName, int _notificationInterval){
PublisherName = _publisherName;
NotificationInterval = _notificationInterval;
}
//publish function publishes a Notification Event
public void Publish(){
while (true){
Thread.Sleep(NotificationInterval); // fire event after certain interval
if (OnPublish != null)
{
NotificationEvent notificationObj = new NotificationEvent(DateTime.Now, "New Notification Arrived from");
OnPublish(this, notificationObj);
}
Thread.Yield();
}
}
}
public class Subscriber{
public string SubscriberName { get; private set; }
public Subscriber(string _subscriberName){
SubscriberName = _subscriberName;
}
// This function subscribe to the events of the publisher
public void Subscribe(Publisher p){
// register OnNotificationReceived with publisher event
p.OnPublish += OnNotificationReceived; // multicast delegate
}
// This function unsubscribe from the events of the publisher
public void Unsubscribe(Publisher p){
// unregister OnNotificationReceived from publisher
p.OnPublish -= OnNotificationReceived; // multicast delegate
}
// It get executed when the event published by the Publisher
protected virtual void OnNotificationReceived(Publisher p, NotificationEvent e){
Console.WriteLine("Hey " + SubscriberName + ", " + e.NotificationMessage +" - "+ p.PublisherName + " at " + e.NotificationDate);
}
}
|
08393fb4edc39e99cc7cab4615e9db01c9e0a909
|
C#
|
shendongnian/download4
|
/code10/1882905-56259473-198244808-4.cs
| 2.671875
| 3
|
List<string> inputFileLines = null;
try
{
inputFileLines = GetInputFileFormatted(mailFile);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found");
}
|
98c87176a761aa439a5b2f71971cc02eed0ec759
|
C#
|
TheOtherBanana/AWSProjects
|
/AmazonPriceUpdate/EmailUtils/Net/TemplateEmailSender.cs
| 2.765625
| 3
|
using EmailUtils.Templating;
using EmailUtils.Xml;
using System;
using System.IO;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace EmailUtils.Net
{
public class TemplateEmailSender : ITemplateEmailSender
{
#region Fields
private readonly ITemplateCompiler _templateCompiler;
private readonly Regex _replaceRegex = new Regex(Regex.Escape("<!-- Content -->"), RegexOptions.Compiled);
private readonly IXmlSerializer _xmlSerializer;
private string _layoutHtml;
#endregion Fields
public string LayoutFilePath { get; set; }
protected string LayoutHtml
{
get
{
lock (this)
{
if (LayoutFilePath == null)
{
return null;
}
return _layoutHtml ?? (_layoutHtml = GetBaseHtmlContent());
}
}
}
#region Constructor
public TemplateEmailSender(ITemplateCompiler templateCompiler, IXmlSerializer xmlSerializer)
{
if (templateCompiler == null) throw new ArgumentNullException("templateCompiler");
if (xmlSerializer == null) throw new ArgumentNullException("xmlSerializer");
_templateCompiler = templateCompiler;
_xmlSerializer = xmlSerializer;
}
#endregion Constructor
#region Methods
public MailMessage ConstructMailMessage(string templatePath, object variables)
{
if (templatePath == null) throw new ArgumentNullException("templatePath");
if (!File.Exists(templatePath))
{
throw new FileNotFoundException("Template file not found.", templatePath);
}
var compiler = _templateCompiler;
string compiled;
using (var xmlStream = new MemoryStream())
{
_xmlSerializer.ToXml(variables, xmlStream);
xmlStream.Position = 0;
var sr = new StreamReader(xmlStream);
string myStr = sr.ReadToEnd();
using (var output = new MemoryStream())
{
compiler.CompileXsltFromFile(xmlStream, templatePath, output);
output.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(output))
{
compiled = reader.ReadToEnd();
}
}
}
string layoutHtml = LayoutHtml;
if (layoutHtml != null)
{
compiled = _replaceRegex.Replace(layoutHtml, compiled);
}
compiled = compiled.Replace("<", "<").Replace(">", ">");
var mailMessage = new MailMessage
{
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8,
Body = compiled
};
return mailMessage;
}
private string GetBaseHtmlContent()
{
string filePath = LayoutFilePath;
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Layout file not found.", filePath);
}
using (var reader = new StreamReader(filePath))
{
return reader.ReadToEnd();
}
}
#endregion Methods
}
}
|
3fa53e737945c84760962f79c8e4395b464a671f
|
C#
|
Team-Artemis-TelerikAcademy/Movie-Hunter
|
/MovieHunter/MovieHunter.Importer/ImdbDownloader/ImdbDownloader.cs
| 2.953125
| 3
|
namespace MovieHunter.Importer.ImdbDownloader
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using DeserializationModels;
using Newtonsoft.Json;
public class Downloader
{
private static ICollection<MovieModel> Movies = new List<MovieModel>();
private static ICollection<TrailerModel> Trailers = new List<TrailerModel>();
/// <summary>
/// Releases any downloaded content.
/// </summary>
public static void Flush()
{
Movies.Clear();
Trailers.Clear();
}
/// <summary>
/// Downloads trailer info and info about their respective movies from the specified pages into the RAM memory. Uses the classes from DeserializationModels folder.
/// </summary>
/// <param name="startPage"></param>
/// <param name="endPage"></param>
public static void Download(int startPage = 1, int endPage = 5)
{
Console.WriteLine("Download started for pages " + startPage + " to " + endPage);
for (int i = startPage; i <= endPage; i++)
{
Console.SetCursorPosition(0, 1);
Console.WriteLine("Downloading page " + i);
var trailers = GetTrailersArray(i);
foreach (var t in trailers)
{
Trailers.Add(t);
}
DownloadMoviesForTrailers(trailers, i);
Console.Clear();
}
Console.WriteLine("\nFinished downloading");
}
/// <summary>
/// Saves the downloaded info in the specified folder. The folder is created if it doesn't exist.
/// </summary>
/// <param name="folderPath"></param>
public static void SaveToFolder(string folderPath = "../../SampleData")
{
Console.WriteLine("Saving...");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
File.AppendAllText(folderPath + "/movies.json", JsonConvert.SerializeObject(Movies));
File.AppendAllText(folderPath + "/trailers.json", JsonConvert.SerializeObject(Trailers));
Console.WriteLine("Data saved successfully");
}
private static void DownloadMoviesForTrailers(TrailerModel[] trailers, int part)
{
var counter = 0;
foreach (var item in trailers)
{
DownloadMovieByTitle(item.title, part);
if (counter % 5 == 0)
{
Console.Write('.');
}
}
}
private static void DownloadMovieByTitle(string title, int part)
{
var request = (HttpWebRequest)WebRequest.Create(
string.Format("http://www.myapifilms.com/imdb?title={0}&format=JSON&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=M&exactFilter=0&limit=1&forceYear=0&lang=en-us&actors=F&biography=0&trailer=0&uniqueName=0&filmography=0&bornDied=0&starSign=0&actorActress=0&actorTrivia=0&movieTrivia=0&awards=1&moviePhotos=N&movieVideos=N&similarMovies=0&adultSearch=0", title));
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
var response = (HttpWebResponse)request.GetResponse();
var receiveStream = response.GetResponseStream();
var readStream = new StreamReader(receiveStream, Encoding.UTF8);
var json = readStream.ReadToEnd();
MovieModel[] result;
try
{
result = JsonConvert.DeserializeObject<MovieModel[]>(json);
foreach (var item in result)
{
Movies.Add(item);
}
}
catch (Exception)
{
return;
}
response.Close();
readStream.Close();
}
private static TrailerModel[] GetTrailersArray(int page)
{
var request = (HttpWebRequest)WebRequest.Create("http://www.myapifilms.com/imdb/trailers?format=JSON&trailers=PM&page=" + page);
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
var response = (HttpWebResponse)request.GetResponse();
var receiveStream = response.GetResponseStream();
var readStream = new StreamReader(receiveStream, Encoding.UTF8);
var json = readStream.ReadToEnd(); ;
var result = JsonConvert.DeserializeObject<TrailerRoot>(json).trailers;
foreach (var item in result)
{
Trailers.Add(item);
}
response.Close();
readStream.Close();
return result;
}
}
}
|
e2533bb0653a91913b795bf9903558020d827cd7
|
C#
|
darkl/Calculators
|
/src/Calculators/Algebra/Implementation/Generic/FractionExtensions.cs
| 2.765625
| 3
|
using System;
using Calculators.Algebra.Abstract;
namespace Calculators.Algebra
{
public static class FractionExtensions
{
public static Fraction<T> CreateFraction<T>(this IRing<T> ring,
T numerator,
T denominator)
{
if (ring.Comparer.Equals(denominator, ring.Zero))
{
throw new DivideByZeroException();
}
IEuclideanRing<T> euclideanRing = ring as IEuclideanRing<T>;
if (euclideanRing != null)
{
T gcd = euclideanRing.Gcd(numerator, denominator);
T zero;
numerator = euclideanRing.Divide(numerator, gcd, out zero);
denominator = euclideanRing.Divide(denominator, gcd, out zero);
}
return new Fraction<T>(numerator, denominator);
}
}
}
|
276c72e2783bb11250585de4fb457242fc65b5df
|
C#
|
Chris-MorrisUK/racoonMiddleware
|
/UserManager/UserStore.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using REDISConnector;
namespace UserManager
{
public class UserStore
{
private static UserStore theUserStore;
private static object theUserStoreLock = new object();
private UserStore()
{
}
private static UserStore getTheUserStore()
{
if (theUserStore != null)
return theUserStore;
lock (theUserStoreLock)
{
theUserStore = new UserStore();
return theUserStore;
}
}
private bool checkIfUserExists(string userName)
{
if (userName.Contains(":"))//it's bit of an edge case, but it could act like a sql injection attack - username:othervar may exist when username doesn't
throw new ArgumentException("Usernames do not contain a :.", userName);
return REDISConnector.REDISConnector.CheckForExistance(userName);
}
public static bool CheckIfUserExists(string userName)
{
return getTheUserStore().checkIfUserExists(userName);
}
}
}
|
d33d80d6439c06b79963a5223b7e71ff7d8c9804
|
C#
|
Taegost/TexasHoldEm
|
/TexasHoldEm/Library/Player.cs
| 3.765625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TexasHoldEm.Library
{
public class Player
{
public string Name { get; set; }
public int Chips { get; set; }
public List<Card> Hand { get; set; } = new List<Card>();
public Player(string name, int chips)
{
Name = name;
Chips = chips;
} // constructor
public void NewHand()
{
Hand = new List<Card>();
} // method NewHand
public void AcceptCard(Card newCard)
{
// With this application, the exception criteria should never be reached, so if it is, it is a true exception
if (Hand.Count == 3) { throw new ArgumentOutOfRangeException("The player already has 3 cards and can not have any more"); }
Hand.Add(newCard);
} // method AcceptCard
public bool HasCards()
{
return Hand.Count > 0;
} // method HasCards
public bool PayOut(int amount)
{
if (Chips - amount >= 0)
{
Chips -= amount;
return true;
}
else
{ return false; }
} // method PayOut
public void AcceptChips(int payout)
{
Chips += payout;
} // method AcceptChips
public string ShowHand()
{
string returnStr = "";
if (Hand.Count > 0)
{
foreach (Card card in Hand)
{ returnStr += $"{card.ToString()}\n"; }
}
else
{
returnStr = "No cards in hand";
}
return returnStr.Trim();
} // method ShowHand
public override string ToString()
{
string returnStr = $"{Name} has {Chips} chips and {Hand.Count} card(s) in hand.";
return returnStr;
} // method ToString
} // class Player
}
|
813f6fbe64e7cb20f7186dfd318e886e7ce5fb84
|
C#
|
ExtendRealityLtd/Zinnia.Unity
|
/Tests/Utility/Mock/UnityEventListenerMock.cs
| 2.765625
| 3
|
namespace Test.Zinnia.Utility.Mock
{
/// <summary>
/// The UnityEventListenerMock creates a simple mechanism of registering a listener with a UnityEvent and checking if the event was emitted.
/// </summary>
public class UnityEventListenerMock
{
/// <summary>
/// The state of whether the event emitted was received by the listener.
/// </summary>
public bool Received
{
get;
private set;
}
/// <summary>
/// The Reset method resets the listener state.
/// </summary>
public virtual void Reset()
{
Received = false;
}
public virtual void Listen()
{
Received = true;
}
public virtual void Listen<T0>(T0 a)
{
Received = true;
}
public virtual void Listen<T0, T1>(T0 a, T1 b)
{
Received = true;
}
public virtual void Listen<T0, T1, T2>(T0 a, T1 b, T2 c)
{
Received = true;
}
public virtual void Listen<T0, T1, T2, T3>(T0 a, T1 b, T2 c, T3 d)
{
Received = true;
}
}
}
|
b418dad61372023d2cb07058a62e6e0e0e9ab735
|
C#
|
riyadparvez/Non-Blocking-CSharp
|
/NonBlockingCSharp/NonBlockingCSharp/ConcurrentStack/ConcurrentStack.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NonBlockingCSharp.Utilities;
namespace NonBlockingCSharp.ConcurrentStack
{
[Serializable]
public class ConcurrentStack<T>
{
private Node<T> head;
public ConcurrentStack()
{
head = new Node<T>(default(T));
}
public bool TryPop(out T result)
{
Node<T> node;
do
{
node = head.next;
if (node == null)
{
result = default(T);
return false;
}
} while (!AtomicOperationsUtilities.CompareAndSwap(ref head.next, node, node.next));
result = node.item;
return true;
}
public void Push(T item)
{
Node<T> node = new Node<T>(item);
do
{
node.next = head.next;
} while (!AtomicOperationsUtilities.CompareAndSwap(ref head.next, node.next, node));
}
[Serializable]
private class Node<T>
{
public Node<T> next;
public T item;
public Node(T item)
{
this.item = item;
}
}
}
}
|
b34d76072f0d430c5b2ea990c99cd6268c639613
|
C#
|
dalpendre/EI_SI
|
/Ficha2/Worksheet2-Solution/Exercise 2 - Client/Client.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_2___Client
{
class Client
{
static void Main(string[] args)
{
#region VARIABLES
int bufferSize = 1400;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
TcpClient client = null;
NetworkStream stream = null;
IPEndPoint endpoint = null;
#endregion
try
{
#region SOCKET SET UP
endpoint = new IPEndPoint(IPAddress.Loopback, 9999);
client = new TcpClient();
client.Connect(endpoint); //Client tenta-se conectar ao endpoint com o porto 9999
stream = client.GetStream(); //Devolve a stream usada para enviar e receber dados
#endregion COMMUNICATION - Byte Array
byte[] arrayMsg = new byte[2] { 83, 73 };
Console.WriteLine("Sending Byte Array ");
stream.Write(arrayMsg, 0, arrayMsg.Length); //Escreve bytes do array para a stream
Console.WriteLine("Waiting for Client");
bytesRead = stream.Read(buffer, 0, bufferSize); //Lê stream recebida
Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(buffer, 0, bytesRead));
#region COMMUNICATION - String
string msg = "EI.SI";
byte[] stringMsg = Encoding.UTF8.GetBytes(msg);
Console.WriteLine("Sending Byte Array ");
stream.Write(stringMsg, 0, stringMsg.Length);
Console.WriteLine("Waiting for ACK");
bytesRead = stream.Read(buffer, 0, bufferSize);
Console.WriteLine("Received: {0}", Encoding.UTF8.GetString(buffer, 0, bytesRead));
#endregion
#region COMMUNICATION - Integer
int intToSend = 42;
byte[] intMsg = BitConverter.GetBytes(intToSend);
Console.WriteLine("Sending Integer ");
stream.Write(intMsg, 0, intMsg.Length);
Console.WriteLine("Waiting for ACK");
bytesRead = stream.Read(buffer, 0, bufferSize);
Console.WriteLine("Received: {0}", Encoding.UTF8.GetString(buffer, 0, bytesRead));
#endregion
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
finally
{
if(stream != null)
{
stream.Close();
}
if(client != null)
{
client.Close();
}
Console.ReadKey();
}
}
}
}
|
a8b5727d5dfc93d49dc488c6dabd5413b4152aec
|
C#
|
phalcr004/Bullet-Hell-Game-S1DCS
|
/Bullet-Hell-2D-Game/Assets/_Scripts/Enemy/EnemySpawning/AcceleratorEnemy.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(EnemyHealth))]
public class AcceleratorEnemy : MonoBehaviour, IEnemy {
// Acceleration and initial speed
private float speed = 1f;
private float acceleration = 15f;
// Track enemy state and adjust "AI" accordingly
private enum EnemyStates { Spawning, Targetting, Charging }
private EnemyStates enemyState;
// Stop player from destroying enemy before it fully enters screen
public bool canTakeDamage;
private float invincibilityDuration = 2f;
// Timer to keep track of state changes
private float timer;
// Delay between moving and targetting states
private float targettingUpdateDelay = 0.1f;
// Transform of the player
private Transform playerTransform;
// Rigidbody of the enemy
private Rigidbody2D rigidbody;
// Direction and distance variables
private Vector2 directionToPlayer;
private float distanceToPlayer;
private float minDistanceFromPlayer = 5f;
// Boundaries
private float xBoundary = 15f;
private float yBoundary = 4.5f;
void Start() {
// Find player transform and enemy rigidbody
playerTransform = GameObject.Find("Player").GetComponent<Transform>();
rigidbody = GetComponent<Rigidbody2D>();
// Rotate enemy so sprite faces correct direction
transform.Rotate(new Vector3(0f, 0f, 180f));
// Initialise variables
enemyState = EnemyStates.Spawning;
canTakeDamage = false;
timer = Time.time + invincibilityDuration;
}
// Update is called once per frame
void Update() {
switch(enemyState) {
case EnemyStates.Spawning:
// Period of invincibility before attacking
MoveOnSpawn();
break;
case EnemyStates.Targetting:
// Targets the player
TargetPlayer();
break;
}
// If the grace period is over
if(enemyState != EnemyStates.Spawning) {
// Destroy enemy if moves off screen (i.e player dodges)
if(transform.position.x < -xBoundary || transform.position.x > xBoundary || transform.position.y < -yBoundary || transform.position.y > yBoundary) {
Destroy(gameObject);
}
}
}
void FixedUpdate() {
if(enemyState == EnemyStates.Charging) {
// Moves in direction of target
AccelerateTowardsPlayer();
}
}
private void MoveOnSpawn() {
// If the invincibility should end, change state and begin "AI"
if(Time.time > timer) {
enemyState = EnemyStates.Targetting;
canTakeDamage = true;
}
// Move in the "forward" direction of the sprite
transform.Translate(Vector2.down * speed * Time.deltaTime);
}
private void TargetPlayer() {
// Keep track of how long before returning to this method
timer = Time.time + targettingUpdateDelay;
// Get the distance and direction between enemy and player
distanceToPlayer = (playerTransform.position - transform.position).magnitude;
directionToPlayer = (playerTransform.position - transform.position).normalized;
// Rotate the enemy "forwards" towards the player
transform.up = -directionToPlayer;
// Change state to charging
enemyState = EnemyStates.Charging;
}
private void AccelerateTowardsPlayer() {
// If the targetting timer is over and the enemy is not too close to the player:
if(Time.time > timer && distanceToPlayer > minDistanceFromPlayer) {
// Run the targetPlayer method
enemyState = EnemyStates.Targetting;
}
// Accelerate by x units/s/s
speed += acceleration * Time.deltaTime;
// Move in the "forward" direction relative to the sprite
Vector2 moveVector = directionToPlayer * speed * Time.fixedDeltaTime;
rigidbody.MovePosition(rigidbody.position + moveVector);
}
private void OnCollisionEnter2D(Collision2D collision) {
if(!canTakeDamage) {
return;
}
// If hit player, remove a life
if(collision.gameObject.CompareTag("Player")) {
PlayerController.playerLives -= 1;
Destroy(gameObject);
}
}
public bool CanTakeDamage() {
return canTakeDamage;
}
public void ActionOnDeath() {
Destroy(gameObject);
}
}
|
d7e7c6f4eb6ab1822bddac67334b835b2f579d22
|
C#
|
s-avdonin/Rochambeau
|
/Rochambeau_server/ServerProgram.cs
| 3.328125
| 3
|
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Rochambeau_server
{
public class AsynchIoServer
{
// keeps connected player's data
class Player
{
public string name;
public IPEndPoint endPoint;
public byte turn;
public Player() { }
public Player(string name)
{
this.name = name;
}
}
// listening for new connections
static TcpListener tcpListener = new TcpListener(IPAddress.Any, 44111);
static Player player1 = new Player("Player 1");
static Player player2 = new Player("Player 2");
static void Listeners()
{
// add new socket for each client & accept client's connection
Socket socketForClient = tcpListener.AcceptSocket();
try
{
if (socketForClient.Connected)
{
// creating streams for this connection
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
if (!bothPlayersRegistered(player1, player2))
{
// Adding new player if needed
Player thePlayer = addNewPlayer(socketForClient.RemoteEndPoint as IPEndPoint, player1, player2);
// here we recieve client's message.
while (true)
{
// starting to wait for this player's turn
string theString = streamReader.ReadLine();
Console.WriteLine("{0} send: {1}", socketForClient.RemoteEndPoint, theString);
// if this client exit break the loop
if (theString == "name")
{
streamWriter.WriteLine(thePlayer.name);
streamWriter.Flush();
Console.WriteLine("Sent name to " + thePlayer.name);
continue;
}
if (theString == null)
{
break;
}
thePlayer.turn = byte.Parse(theString);
// processing turn
while (true)
{
if (player1.turn != 0 && player2.turn != 0)
{
Console.WriteLine("Sending started to the player " + thePlayer.endPoint);
string result = gameResult(thePlayer);
streamWriter.Write(result);
streamWriter.Flush();
thePlayer.turn = 0;
break;
}
}
}
Console.WriteLine(thePlayer.name + " at " + thePlayer.endPoint.ToString() + " quit the game.");
}
// closing streams for this connection
streamReader.Close();
streamWriter.Close();
networkStream.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Error! " + ex.Message);
}
finally
{
socketForClient.Close();
}
}
// get game result for this player
private static string gameResult(Player thePlayer)
{
if (thePlayer == player1)
{
return getResult(player1.turn, player2.turn);
}
// else
return getResult(player2.turn, player1.turn);
}
// calculate game result from turns
private static string getResult(byte myTurn, byte opponentTurn)
{
string[,] results = new string[3, 3]{
{"It's draw! You both chose Rock.", "You win! Opponent chose Scissors.", "You lose! Opponent chose Paper."},
{"You lose! Opponent chose Rock.", "It's draw! You both chose Scissors.", "You win! Opponent chose Paper." },
{"You win! Opponent chose Rock.", "You lose! Opponent chose Scissors.", "It's draw! You both chose Paper."} };
return (results[(myTurn - 1), (opponentTurn - 1)] + "\n");
}
public static void Main()
{
// start listening for connections
tcpListener.Start();
Console.WriteLine("Server started at " + getMyIp().ToString() + ". Waiting for connections.");
// new thread for each client connected (here max = 2)
int threadCount = 0;
do
{
Thread nextThread = new Thread(new ThreadStart(Listeners));
nextThread.Start();
threadCount++;
} while (threadCount < 2/* this is MAX connections */);
Console.ReadKey();
}
// register new player
private static Player addNewPlayer(IPEndPoint remoteIpEndPoint, Player player1, Player player2)
{
Player player;
Console.WriteLine("Registering new player...");
if (player1.endPoint == null)
{
player = player1;
}
else
{
player = player2;
}
player.endPoint = remoteIpEndPoint as IPEndPoint;
Console.WriteLine(String.Format("{0} successfully registered from {1}.", player.name, player.endPoint));
return player;
}
// true if both players have IPEndPoints
private static bool bothPlayersRegistered(Player player1, Player player2)
{
bool result = true ? (player1.endPoint != null && player2.endPoint != null) : false;
return result;
}
// getting my inet IP address
private static IPAddress getMyIp()
{
IPAddress[] allMyIp = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress myInetIp = allMyIp[0];
foreach (IPAddress item in allMyIp)
{
if (item.AddressFamily == AddressFamily.InterNetwork)
{
myInetIp = item;
}
}
return myInetIp;
}
}
}
|
01e3b4efc1c10b349df40919811ec1556d3f38ba
|
C#
|
Toby-TheBlock/PCB_Drawing_Tool
|
/PCB_Drawing_Tool/CanvasManager.cs
| 3.171875
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
namespace PCB_Drawing_Tool
{
class CanvasManager
{
private static CanvasManager singleton = null;
private Dictionary<CanvasObject, PictureBox> allCanvasObjects;
private PictureBox selectedObject;
private Dictionary<CanvasObject, PictureBox> previewObject;
private CanvasManager()
{
allCanvasObjects = new Dictionary<CanvasObject, PictureBox>();
previewObject = new Dictionary<CanvasObject, PictureBox>();
}
public Dictionary<CanvasObject, PictureBox> AllCanvasObjects
{
get { return allCanvasObjects; }
}
public PictureBox SelectedObject
{
get { return selectedObject; }
set { selectedObject = value; }
}
public Dictionary<CanvasObject, PictureBox> PreviewObject
{
get { return previewObject; }
set { previewObject = value; }
}
public static CanvasManager Singleton
{
get
{
if (singleton == null)
{
singleton = new CanvasManager();
}
return singleton;
}
}
public int GetCountOfCanvasObjects()
{
return allCanvasObjects.Count();
}
/// <summary>
/// Registers the creation of a new CanvasObject, by storing it in the allCanvasObjects and allCanvasGraphics collections.
/// </summary>
/// <param name="newObject"></param>
/// <param name="newGraphic"></param>
public void AddObject(CanvasObject newObject, PictureBox newGraphic)
{
allCanvasObjects.Add(newObject, newGraphic);
}
/// <summary>
/// Removes an entry from the allCanvasObjects collection.
/// </summary>
/// <param name="value">The PictureBox which is the value of a stored dictionary entry.</param>
public void RemoveObject(PictureBox value)
{
CanvasObject dictKey = null;
foreach (var entry in allCanvasObjects)
{
if (entry.Value == value)
{
dictKey = entry.Key;
}
}
if (dictKey != null)
{
allCanvasObjects.Remove(dictKey);
}
}
/// <summary>
/// Gets the reference to a stored CanvasObject from allCanvasObjects.
/// </summary>
/// <param name="entryValue">The PictureBox whos the value of the desired CanvasObject.</param>
/// <returns>The CanvasObject used for creating the provided PictureBox.</returns>
public CanvasObject GetCanvasObject(PictureBox entryValue)
{
foreach (var element in new Dictionary<CanvasObject, PictureBox>(allCanvasObjects))
{
if (element.Value == entryValue)
{
return element.Key;
}
}
return null;
}
/// <summary>
/// Removes the last CanvasObject from the allCanvasObjects collection.
/// </summary>
/// <returns>The corresponding PictureBox which is physically represented on the main Canvas in the Form.</returns>
public PictureBox RemoveLastObjectFromCanvas()
{
if (GetCountOfCanvasObjects() > 0)
{
PictureBox removedObject = allCanvasObjects[allCanvasObjects.Keys.Last()];
allCanvasObjects.Remove(allCanvasObjects.Keys.Last());
return removedObject;
}
else
{
MessageBox.Show("There are no objects that can be removed!");
return null;
}
}
/// <summary>
/// If the right mouse button is being pressed onto a PictureBox, make it the selected object.
/// </summary>
public void SelectObject(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
PictureBox clickedObject = sender as PictureBox;
ChangeSelectedObject(clickedObject);
}
}
/// <summary>
/// Change the PictureBox stored in selectedObject.
/// If the provided object is the same as the one stored in selectedObject, it will be replaced with a null reference.
/// </summary>
/// <param name="objectToChange">The PictureBox which is to be stored in selectedObject.</param>
public void ChangeSelectedObject(PictureBox objectToChange)
{
if (objectToChange != selectedObject)
{
if (selectedObject != null)
{
selectedObject.BackColor = Color.Black;
}
objectToChange.BackColor = ColorTranslator.FromHtml("#7f7f7f");
}
else
{
objectToChange.BackColor = Color.Black;
objectToChange = null;
}
selectedObject = objectToChange;
MainProgram.MainForm.UpdateButtonStatus("delete");
}
/// <summary>
/// Clears the selectedObject value.
/// </summary>
/// <returns>The PictureBox which was stored in the selectedObject.</returns>
public PictureBox ClearSelectedObject()
{
PictureBox pb = selectedObject;
ChangeSelectedObject(selectedObject);
return pb;
}
/// <summary>
/// Clears the previewObject value.
/// </summary>
/// <returns>The PictureBox which was stored in the previewObject.</returns>
public PictureBox ClearPreviewObject()
{
PictureBox pb = null;
if (previewObject.Count != 0)
{
pb = previewObject.First().Value;
previewObject.Remove(previewObject.First().Key);
}
return pb;
}
}
}
|
7bb2f57c46727fd877ebab48ffe21704fac1dd06
|
C#
|
EnergeticApps/Energetic.PeoplePlacesAndBusinesses.ValueObjects
|
/People/PersonName.cs
| 2.984375
| 3
|
using Energetic.Text;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using Energetic.ValueObjects;
namespace Energetic.People.ValueObjects
{
//TODO: I think we can just use default JSON serialization for this class. Check if that's right
//[JsonConverter(typeof(PersonNameJsonConverter))]
//[TypeConverter(typeof(PersonNameTypeConverter))]
public record PersonName : ValueObject<PersonName, (PersonTitle?, string?, IEnumerable<string>?, string?, IEnumerable<string>?, string?, string?)>
{
public PersonName(string givenName) : this(PersonTitle.None, givenName)
{
if (string.IsNullOrWhiteSpace(givenName))
throw new StringArgumentNullOrWhiteSpaceException(nameof(givenName));
}
public PersonName(string givenName,
string familyName) : this(PersonTitle.None, givenName, null, familyName)
{
}
public PersonName(PersonTitle title,
string familyName) : this(title, string.Empty, familyName)
{
}
public PersonName(PersonTitle title,
string givenName,
string familyName) : this(title, givenName, null, familyName)
{
}
public PersonName(PersonTitle title,
string? givenName = null,
IEnumerable<string>? middleNames = null,
string? familyName = null,
IEnumerable<string>? nickNames = null,
string? preferredName = null,
string? fullName = null) : base((title, givenName, middleNames, familyName, nickNames, preferredName, fullName))
{
Title = title;
GivenName = givenName?.Trim();
MiddleNames = middleNames;
FamilyName = familyName?.Trim();
FullName = fullName ?? MakeFullName( title, givenName, middleNames, familyName);
NickNames = nickNames;
PreferredName = preferredName ?? MakePreferredName(title, givenName, middleNames, familyName);
}
public PersonTitle Title { get; }
public string? GivenName { get; }
public IEnumerable<string>? MiddleNames { get; }
public string? FamilyName { get; }
public string FullName { get; }
public IEnumerable<string>? NickNames { get; }
public string PreferredName { get; }
public bool HasTitle => !Title.HasNone();
private static string MakePreferredName(
PersonTitle? title,
string? givenName,
IEnumerable<string>? middleNames,
string? familyName)
{
if (!string.IsNullOrWhiteSpace(title?.Value) && !string.IsNullOrWhiteSpace(familyName))
return $"{title.Value} {familyName}";
if (!string.IsNullOrWhiteSpace(title?.Value) && !string.IsNullOrWhiteSpace(givenName))
return $"{title.Value} {givenName}";
if (!string.IsNullOrWhiteSpace(givenName))
return givenName;
if (!string.IsNullOrWhiteSpace(familyName))
return familyName;
if (middleNames is { })
return middleNames.FirstOrDefault(m => !string.IsNullOrWhiteSpace(m));
throw new ArgumentException("Not enough information about this person was passed to generate a value for" +
$"his/her {nameof(PreferredName)}.");
}
private static string MakeFullName(
PersonTitle? title,
string? givenName,
IEnumerable<string>? middleNames,
string? familyName)
{
StringBuilder builder = new StringBuilder(title?.Value);
builder.Append($" {givenName}");
if (middleNames is { })
{
foreach (string middleName in middleNames)
{
builder.Append($" {middleName}");
}
}
if(!string.IsNullOrWhiteSpace(familyName))
{
builder.Append($" {familyName}");
}
return builder.ToString().CollapseMultipleSpaces().Trim();
}
}
}
|
d131ed71da85df12c5fabbfdfaf1d347775520ba
|
C#
|
arnel-sanchez/CinePlus
|
/CinePlus/DataAccess/HomeDataAccess.cs
| 2.65625
| 3
|
using CinePlus.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CinePlus.DataAccess
{
public class HomeDataAccess : IHomeRepository
{
private CinePlusDBContext _context;
public HomeDataAccess(CinePlusDBContext context)
{
_context = context;
}
public List<MovieOnTop10> GetMovieOnTop10s()
{
try
{
return _context.MovieOnTop10
.Include(x => x.Movie)
.Include(x => x.Top10)
.OrderBy(x=>x.Top10Id)
.ToList();
}
catch (Exception)
{
return new List<MovieOnTop10>();
}
}
}
}
|
765adf62dd63175815a1f1c249dc945a1e65bdc8
|
C#
|
smb123w64gb/MDL2MBCH
|
/MDL2MBCH/MDL2MBCH/IO/FileOutput.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MDL2MBCH.IO
{
public class FileOutput
{
readonly List<byte> data = new List<byte>();
public enum Endianness
{
Little = 0,
Big = 1
}
public Endianness Endian;
public byte[] getBytes()
{
return data.ToArray();
}
public void writeString(String s)
{
char[] c = s.ToCharArray();
for (int i = 0; i < c.Length; i++)
data.Add((byte)c[i]);
}
public int size()
{
return data.Count;
}
public void insert(int pos, int size)
{
data.InsertRange(pos, new byte[size]);
}
public void writeOutput(FileOutput d)
{
foreach (RelocOffset o in d.Offsets)
{
o.Position += data.Count;
Offsets.Add(o);
}
foreach (RelocOffset o in Offsets)
{
if (o.output == d || o.output == null)
o.Value += data.Count;
}
foreach (byte b in d.data)
data.Add(b);
}
private static char[] HexToCharArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.Select(x => Convert.ToChar(x))
.ToArray();
}
public void writeHex(string s)
{
char[] c = HexToCharArray(s);
for (int i = 0; i < c.Length; i++)
data.Add((byte)c[i]);
}
public void writeInt(int i)
{
if (Endian == Endianness.Little)
{
data.Add((byte)((i) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i >> 16) & 0xFF));
data.Add((byte)((i >> 24) & 0xFF));
}
else
{
data.Add((byte)((i >> 24) & 0xFF));
data.Add((byte)((i >> 16) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i) & 0xFF));
}
}
public void writeUInt(uint i)
{
if (Endian == Endianness.Little)
{
data.Add((byte)((i) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i >> 16) & 0xFF));
data.Add((byte)((i >> 24) & 0xFF));
}
else
{
data.Add((byte)((i >> 24) & 0xFF));
data.Add((byte)((i >> 16) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i) & 0xFF));
}
}
public void writeIntAt(int i, int p)
{
if (Endian == Endianness.Little)
{
data[p++] = (byte)((i) & 0xFF);
data[p++] = (byte)((i >> 8) & 0xFF);
data[p++] = (byte)((i >> 16) & 0xFF);
data[p++] = (byte)((i >> 24) & 0xFF);
}
else
{
data[p++] = (byte)((i >> 24) & 0xFF);
data[p++] = (byte)((i >> 16) & 0xFF);
data[p++] = (byte)((i >> 8) & 0xFF);
data[p++] = (byte)((i) & 0xFF);
}
}
public void writeShortAt(int i, int p)
{
if (Endian == Endianness.Little)
{
data[p++] = (byte)((i) & 0xFF);
data[p++] = (byte)((i >> 8) & 0xFF);
}
else
{
data[p++] = (byte)((i >> 8) & 0xFF);
data[p++] = (byte)((i) & 0xFF);
}
}
public void writeBytesAt(byte[] bytes, int p)
{
foreach (byte b in bytes)
data[p++] = (byte)((p) & 0xFF);
}
public void writeString(string name, int size)
{
if (name.Length <= 68)
{
string NewName = name;
writeString(NewName);
var num = NewName.ToCharArray().Count();
while (num < size)
{
writeByte(0);
num++;
}
}
else
throw new ArgumentOutOfRangeException("Character limit is 68");
}
public void align(int i)
{
while ((data.Count % i) != 0)
writeByte(0);
}
public void align(int i, int v)
{
while ((data.Count % i) != 0)
writeByte(v);
}
public void writeFloat(float f)
{
writeInt(SingleToInt32Bits(f));
}
public void writeFloatAt(float f, int p)
{
writeIntAt(SingleToInt32Bits(f), p);
}
//The return value is big endian representation
public static int SingleToInt32Bits(float value)
{
return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}
public void writeShort(int i)
{
if (Endian == Endianness.Little)
{
data.Add((byte)((i) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
}
else
{
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i) & 0xFF));
}
}
public void writeUShort(ushort i)
{
if (Endian == Endianness.Little)
{
data.Add((byte)((i) & 0xFF));
data.Add((byte)((i >> 8) & 0xFF));
}
else
{
data.Add((byte)((i >> 8) & 0xFF));
data.Add((byte)((i) & 0xFF));
}
}
public void writeByte(int i)
{
data.Add((byte)((i) & 0xFF));
}
public void writeSByte(sbyte i)
{
data.Add((byte)((i) & 0xFF));
}
public void writeBytes(byte[] bytes)
{
foreach (byte b in bytes)
writeByte(b);
}
public void writeBool(bool b)
{
if (b)
writeByte(1);
else
writeByte(0);
}
public int pos()
{
return data.Count;
}
public void save(String fname)
{
File.WriteAllBytes(fname, data.ToArray());
}
public void save(String fname, List<byte> bytes)
{
File.WriteAllBytes(fname, bytes.ToArray());
}
public class RelocOffset
{
public int Value;
public int Position;
public FileOutput output;
}
public List<RelocOffset> Offsets = new List<RelocOffset>();
public void WriteOffset(int i, FileOutput fo)
{
Offsets.Add(new RelocOffset() { Value = i, output = fo, Position = data.Count });
writeInt(i);
}
}
}
|
d15321137e4ff421a3ede1e3a03662962e16a151
|
C#
|
Zane6888/syncsoft
|
/soft/FileHelper.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace syncsoft
{
static class FileHelper
{
private static MD5 md5 = MD5.Create();
public static String GetAbsolute(String relative)
{
String absolute = Config.getAbsolute(relative);
if (absolute != null)
return absolute;
List<String> relPaths = Config.getAllRelative();
String relBase = relPaths.Find(s => relative.Contains(s));
return relative.Replace(relBase,Config.getAbsolute(relBase));
}
public static String GetRelative(String absolute)
{
String relative = Config.getRelative(absolute);
if (relative != null)
return relative;
List<String> absPaths = Config.getAllAbsolute();
String absBase = absPaths.Find(s => absolute.Contains(s));
return absolute.Replace(absBase, Config.getAbsolute(absBase));
}
public static Byte[] GetMD5(String path)
{
using (Stream st = File.OpenRead(path))
{
return md5.ComputeHash(st);
}
}
public static bool ContainsFile(this List<String> list, String file)
{
if (list.Count == 0)
return false;
if (list.Contains(file))
return true;
try{
list.First(s => file.Contains(s));
return true;
}
catch(Exception)
{
return false;
}
}
}
}
|
f6779c7ae46c8118d4d704d261236b3de6c32af9
|
C#
|
nike4613/GoosMods.3
|
/HatGoos/Readers/HatFileReader.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HatGoos.Readers
{
public sealed class HatFileReader : IHatfileReader
{
private readonly ZipArchive file;
public HatFileReader(string path)
{
try
{
file = ZipFile.OpenRead(path);
}
catch
{
throw new InvalidOperationException();
}
}
public void Dispose()
{
file.Dispose();
}
public IHatfileEntry GetEntry(string name)
{
var e = file.GetEntry(name);
if (e is null) return null;
else return new Entry(e);
}
private sealed class Entry : IHatfileEntry
{
private readonly ZipArchiveEntry entry;
public Entry(ZipArchiveEntry e)
=> entry = e;
public void Dispose() { }
public Stream GetStream()
=> entry.Open();
}
}
}
|
eefc5f00e1eb381ff2d3c5969989b37406794a85
|
C#
|
chromesome/PPOP_ChallengeProject
|
/Assets/Scripts/Tiles/Tile.cs
| 2.9375
| 3
|
using System.Collections;
using System.Collections.Generic;
using PathFinding;
using UnityEngine;
public class Tile : MonoBehaviour, IAStarNode
{
// public variables
public bool traversable;
// private variables
[SerializeField] string _tileType;
[SerializeField] int _traverseCost;
int _x;
int _y;
bool _selected;
private List<Tile> _neighbourTiles;
// getter and setters
public string TileType { get => _tileType; }
public int TraverseCost { get => _traverseCost; }
public int X { get => _x; set => _x = value; }
public int Y { get => _y; set => _y = value; }
public IEnumerable<IAStarNode> Neighbours
{
get
{
foreach(Tile tile in _neighbourTiles)
{
if (tile.traversable)
{
yield return tile;
}
}
}
}
private void Awake()
{
_neighbourTiles = new List<Tile>();
}
public float CostTo(IAStarNode neighbour)
{
Tile neighbourHex = neighbour as Tile;
Debug.Assert(neighbourHex != null, "Neighbour is not a Tile");
if (neighbourHex != null)
{
return neighbourHex.TraverseCost;
}
else
{
throw new System.Exception("Neighbour is not a Tile");
}
}
public float EstimatedCostTo(IAStarNode target)
{
Tile targetHex = target as Tile;
Debug.Assert(targetHex != null, "Neighbour is not a Tile");
if (targetHex != null)
{
int xDistance = Mathf.Abs(this.X - targetHex.X);
int yDistance = Mathf.Abs(this.Y - targetHex.Y);
return xDistance + yDistance;
}
else
{
// TODO: handle gracefully
throw new System.Exception("Target is not a tile");
}
}
public void AddNeighbour(Tile neighbour)
{
_neighbourTiles.Add(neighbour);
}
private void OnMouseDown()
{
Select();
}
/// <summary>
/// Set tile as selected.
/// </summary>
public void Select()
{
if(traversable)
{
if(!_selected)
{
_selected = true;
GameManager.instance.TileSelected(this);
}
HighlightTile(Color.green);
}
}
/// <summary>
/// Tile was traversed, we are going places
/// </summary>
public void Traverse()
{
if(!_selected)
{
HighlightTile(Color.red);
}
else
{
HighlightTile(Color.green);
}
}
/// <summary>
/// Set tile as unselected
/// </summary>
public void UnSelect()
{
HighlightTile(Color.white);
_selected = false;
}
/// <summary>
/// Change tile material color
/// </summary>
private void HighlightTile(Color color)
{
Renderer renderer = this.GetComponent<Renderer>();
renderer.material.color = color;
}
}
|
3cb777f3f6b07f166a51c5cd623b71c35a77a8d6
|
C#
|
dalebarr/Cff.SaferTrader---Dev-Branch-1
|
/Cff.SaferTrader.Core/LikelyRepurchasesLine.cs
| 2.59375
| 3
|
using System;
namespace Cff.SaferTrader.Core
{
[Serializable]
public class LikelyRepurchasesLine
{
private readonly int customerid;
private readonly int customerNumber;
private readonly string customerName;
private readonly string title;
private readonly int age;
private readonly decimal amount;
private readonly decimal balance;
private readonly decimal sum;
private readonly Date dated;
private readonly Date processed;
private string transaction;
private string reference;
public LikelyRepurchasesLine(int custid, int custNum, string custName, string theTitle, int theAge,
decimal amt, decimal bal, decimal sum, Date thedate, Date procdate, string trans, string trxref)
{
ArgumentChecker.ThrowIfNullOrEmpty(customerName, "customerName");
this.customerid = custid;
this.customerNumber = custNum;
this.customerName = custName;
this.title = theTitle;
this.age = theAge;
this.amount = amt;
this.balance = bal;
this.sum = sum;
this.dated = thedate;
this.processed = procdate;
this.transaction = trans;
this.reference = trxref;
}
public int CustId { get { return this.customerid; }}
public int CustomerNumber {get { return this.customerNumber; }}
public string CustomerName { get { return this.customerName; } }
public string Title { get { return this.title; } }
public int Age { get { return this.age; } }
public decimal Amount { get { return this.amount; } }
public decimal Balance { get { return this.balance; } }
public decimal Sum { get { return this.sum; } }
public Date Dated { get { return this.dated; } }
public Date Processed { get { return this.processed; } }
public string Transaction { get { return this.transaction; } }
public string Reference { get { return this.reference; } }
}
}
|
55789011d0032b831c65c37325a722636683d3f5
|
C#
|
withakay/ably-dotnet-authcallbackexample
|
/example/Program.cs
| 2.890625
| 3
|
using System;
using System.Net;
using System.Threading.Tasks;
using IO.Ably;
using IO.Ably.Realtime;
using Newtonsoft.Json;
namespace example
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var options = new ClientOptions
{
AuthCallback = async tokenParams =>
{
return await GetTokenRequestStringFromYourServer();
// or return a TokenDetails object
// return await GetTokenDetailsFromYourServer();
}
};
var client = new AblyRealtime(options);
client.Connection.Once(ConnectionState.Connected, change =>
{
Console.WriteLine("connected");
});
client.Connection.On(x =>
{
Console.WriteLine(x.Reason.ToString());
});
Console.ReadLine();
}
static async Task<object> GetTokenDetailsFromYourServer()
{
Console.WriteLine("Getting token details from web server.");
var webClient = new WebClient();
string tokenJson = string.Empty;
try
{
tokenJson = await webClient.DownloadStringTaskAsync("http://localhost:5000/ablyauth/tokendetails");
}
catch (Exception ex)
{
Console.WriteLine("Error getting token from web server, is started?");
Console.WriteLine(ex.Message);
}
return JsonConvert.DeserializeObject<TokenDetails>(tokenJson);
}
static async Task<object> GetTokenRequestStringFromYourServer()
{
Console.WriteLine("Getting token request from web server.");
var webClient = new WebClient();
string tokenJson = string.Empty;
try
{
tokenJson = await webClient.DownloadStringTaskAsync("http://localhost:5000/ablyauth/tokenrequest");
}
catch (Exception ex)
{
Console.WriteLine("Error getting token from web server, is started?");
Console.WriteLine(ex.Message);
}
return tokenJson;
}
}
}
|
156db0e12967321f1b4f7406f7213502599e00b2
|
C#
|
EliyaHammer/ROCKY-POOL-2.6-AND-UP
|
/RockyClock/Converters/DayOfWeekConverter.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace RockyClock.Converters
{
class DayOfWeekConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string Value = value.ToString();
string Result = null;
switch (Value)
{
case "Sunday": Result = "ראשון";
break;
case "Monday": Result = "שני";
break;
case "Tuesday":
Result = "שלישי";
break;
case "Wednesday":
Result = "רביעי";
break;
case "Thursday":
Result = "חמישי";
break;
case "Friday":
Result = "שישי";
break;
case "Saturday":
Result = "שבת";
break;
}
return (string)Result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
d25e3f98762fbaf6063e5bdd8d5e7ec453fb1601
|
C#
|
AnnetteMur/Filters
|
/Filters.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.ComponentModel;
using System.Globalization;
namespace WindowsFormsApp1
{
abstract class Filters
{
public int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
//уникальна для каждого фильтра
public abstract Color calculateNewPixelColor(Bitmap sourceImage, int x, int y);
//General part
public virtual Bitmap processImage(Bitmap sourceImage, BackgroundWorker worker)
{
Bitmap resultImage = new Bitmap(sourceImage.Width, sourceImage.Height);
for (int i = 0; i < sourceImage.Width; i++)
{
worker.ReportProgress((int)((float)i / resultImage.Width * 100));
if (worker.CancellationPending)
return null;
for (int j = 0; j < sourceImage.Height; j++)
{
resultImage.SetPixel(i, j, calculateNewPixelColor(sourceImage, i, j));
}
}
return resultImage;
}
}
class InvertFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color sourceColor = sourceImage.GetPixel(x, y);
Color resultColor = Color.FromArgb(255 - sourceColor.R, 255 - sourceColor.G, 255 - sourceColor.B);
return resultColor;
}
}
class GrayScaleFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color sourceColor = sourceImage.GetPixel(x, y);
int intensity = (int)(0.299 * sourceColor.R + 0.287 * sourceColor.G + 0.114 * sourceColor.B);
Color resultColor = Color.FromArgb(intensity, intensity, intensity);
return resultColor;
}
}
class SepiaFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color sourceColor = sourceImage.GetPixel(x, y);
int k = 15;
int intensity = (int)(0.299 * sourceColor.R + 0.287 * sourceColor.G + 0.114 * sourceColor.B);
int resultR = (int)(intensity + 2 * k);
int resultG = (int)(intensity + 0.5 * k);
int resultB = (int)(intensity - 1 * k);
Color resultColor = Color.FromArgb(Clamp(resultR, 0, 255), Clamp(resultG, 0, 255), Clamp(resultB, 0, 255));
return resultColor;
}
}
class BrightnessFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color sourceColor = sourceImage.GetPixel(x, y);
int k = 100;
int resultR = (int)(sourceColor.R + k);
int resultG = (int)(sourceColor.G + k);
int resultB = (int)(sourceColor.B + k);
Color resultColor = Color.FromArgb(Clamp(resultR, 0, 255), Clamp(resultG, 0, 255), Clamp(resultB, 0, 255));
return resultColor;
}
}
class CarryFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int k = Clamp((int)x - 50, 0, sourceImage.Width - 1);
int l = y;
return sourceImage.GetPixel(k, l);
}
}
class WavesFilter1 : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int k = Clamp((int)(x - (20 * Math.Sin(2 * Math.PI * y / 60))), 0, sourceImage.Width - 1);
int l = y;
return sourceImage.GetPixel(k, l);
}
}
class WavesFilter2 : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int k = Clamp((int)(x - (20 * Math.Sin(2 * Math.PI * x / 60))), 0, sourceImage.Width - 1);
int l = y;
return sourceImage.GetPixel(k, l);
}
}
class RotationFilter : Filters
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int x0 = sourceImage.Width / 2;
int y0 = sourceImage.Height / 2;
double angle = Math.PI / 6;
int k = Clamp((int)((x - x0) * Math.Cos(angle) - (y - y0) * Math.Sin(angle) + x0), 0, sourceImage.Width - 1);
int l = Clamp((int)((x - x0) * Math.Sin(angle) + (y - y0) * Math.Cos(angle) + y0), 0, sourceImage.Height - 1);
return sourceImage.GetPixel(k, l);
}
}
class GlassFilter : Filters
{
Random rand = new Random();
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int k = Clamp((int)(x + (rand.NextDouble() - 0.5) * 10), 0, sourceImage.Width - 1);
int l = Clamp((int)(y + (rand.NextDouble() - 0.5) * 10), 0, sourceImage.Height - 1);
return sourceImage.GetPixel(k, l);
}
}
class MatrixFilter : Filters
{
protected float[,] kernel = null;
protected MatrixFilter() { }
public MatrixFilter(float[,] kernel)
{
this.kernel = kernel;
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int radiusX = kernel.GetLength(0) / 2;
int radiusY = kernel.GetLength(1) / 2;
float resultR = 0;
float resultG = 0;
float resultB = 0;
for (int l = -radiusY; l <= radiusY; l++)
for (int k = -radiusX; k <= radiusX; k++)
{
int idX = Clamp(x + k, 0, sourceImage.Width - 1);
int idY = Clamp(y + k, 0, sourceImage.Height - 1);
Color neighborColor = sourceImage.GetPixel(idX, idY);
resultR += kernel[k + radiusX, l + radiusY] * neighborColor.R;
resultG += kernel[k + radiusX, l + radiusY] * neighborColor.G;
resultB += kernel[k + radiusX, l + radiusY] * neighborColor.B;
}
return Color.FromArgb(
Clamp((int)resultR, 0, 255),
Clamp((int)resultG, 0, 255),
Clamp((int)resultB, 0, 255)
);
}
}
class BlurFilter : MatrixFilter
{
public BlurFilter()
{
int sizeX = 3;
int sizeY = 3;
kernel = new float[sizeX, sizeY];
for (int i = 0; i < sizeX; i++)
for (int j = 0; j < sizeY; j++)
kernel[i, j] = 1.0f / (float)(sizeX * sizeY);
}
}
class GaussianFilter : MatrixFilter
{
public void createGaussianKernal(int radius, float sigma)
{
int size = 2 * radius + 1;
kernel = new float[size, size];
float norm = 0;
for (int i = -radius; i <= radius; i++)
for (int j = -radius; j <= radius; j++)
{
kernel[i + radius, j + radius] = (float)(Math.Exp(-(i * i + j * j) / (2 * sigma * sigma)));
norm += kernel[i + radius, j + radius];
}
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
kernel[i, j] /= norm;
}
public GaussianFilter()
{
createGaussianKernal(3, 2);
}
}
class SobelFilterX : MatrixFilter
{
public SobelFilterX()
{
kernel = new float[,] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
}
}
class SobelFilterY : MatrixFilter
{
public SobelFilterY()
{
kernel = new float[,] { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
}
}
class SobelFilter : MatrixFilter
{
Filters FilterX;
Filters FilterY;
public SobelFilter()
{
FilterX = new SobelFilterX();
FilterY = new SobelFilterY();
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color dX = FilterX.calculateNewPixelColor(sourceImage, x, y);
Color dY = FilterY.calculateNewPixelColor(sourceImage, x, y);
float resultR = (float)Math.Sqrt(dX.R * dX.R + dY.R * dY.R);
float resultG = (float)Math.Sqrt(dX.G * dX.G + dY.G * dY.G);
float resultB = (float)Math.Sqrt(dX.B * dX.B + dY.B * dY.B);
return Color.FromArgb(
Clamp((int)resultR, 0, 255),
Clamp((int)resultG, 0, 255),
Clamp((int)resultB, 0, 255)
);
}
}
class SharpnessFilter : MatrixFilter
{
public SharpnessFilter()
{
kernel = new float[,] { { 0, -1, 0 }, { -1, 5, -1 }, { 0, -1, 0 } };
}
}
class EmbossingFilterCalc : Filters
{
protected float[,] kernel = null;
protected EmbossingFilterCalc() { }
public EmbossingFilterCalc(float[,] kernel)
{
this.kernel = kernel;
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
int radiusX = kernel.GetLength(0) / 2;
int radiusY = kernel.GetLength(1) / 2;
float resultR = 0;
float resultG = 0;
float resultB = 0;
for (int l = -radiusY; l <= radiusY; l++)
for (int k = -radiusX; k <= radiusX; k++)
{
int idX = Clamp(x + k, 0, sourceImage.Width - 1);
int idY = Clamp(y + k, 0, sourceImage.Height - 1);
Color neighborColor = sourceImage.GetPixel(idX, idY);
float inten = (float)(0.299 * neighborColor.R + 0.287 * neighborColor.G + 0.114 * neighborColor.B);
resultR += (inten) * kernel[k + radiusX, l + radiusY];
resultG += (inten) * kernel[k + radiusX, l + radiusY];
resultB += (inten) * kernel[k + radiusX, l + radiusY];
}
return Color.FromArgb(
Clamp(((int)resultR + 255) / 2, 0, 255),
Clamp(((int)resultG + 255) / 2, 0, 255),
Clamp(((int)resultB + 255) / 2, 0, 255)
);
}
}
class EmbossingFilter : EmbossingFilterCalc
{
public EmbossingFilter()
{
kernel = new float[,] { { 0, 1, 0 }, { 1, 0, -1 }, { 0, -1, 0 } };
}
}
class SharraFilterX : MatrixFilter
{
public SharraFilterX()
{
kernel = new float[,] { { 3, 10, -3 }, { 10, 0, -10 }, { 3, 0, -3 } };
}
}
class SharraFilterY : MatrixFilter
{
public SharraFilterY()
{
kernel = new float[,] { { 3, 10, 3 }, { 0, 0, 0 }, { -3, -10, -3 } };
}
}
class SharraFilter : MatrixFilter
{
Filters FilterX;
Filters FilterY;
public SharraFilter()
{
FilterX = new SharraFilterX();
FilterY = new SharraFilterY();
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color dX = FilterX.calculateNewPixelColor(sourceImage, x, y);
Color dY = FilterY.calculateNewPixelColor(sourceImage, x, y);
float resultR = (float)Math.Sqrt(dX.R * dX.R + dY.R * dY.R);
float resultG = (float)Math.Sqrt(dX.G * dX.G + dY.G * dY.G);
float resultB = (float)Math.Sqrt(dX.B * dX.B + dY.B * dY.B);
return Color.FromArgb(
Clamp((int)resultR, 0, 255),
Clamp((int)resultG, 0, 255),
Clamp((int)resultB, 0, 255)
);
}
}
class PruitteFilterX : MatrixFilter
{
public PruitteFilterX()
{
kernel = new float[,] { { -1, 0, -1 }, { -1, 0, 1 }, { -1, 0, 1 } };
}
}
class PruitteFilterY : MatrixFilter
{
public PruitteFilterY()
{
kernel = new float[,] { { -1, -1, -1 }, { 0, 0, 0 }, { 1, 1, 1 } };
}
}
class PruitteFilter : MatrixFilter
{
Filters FilterX;
Filters FilterY;
public PruitteFilter()
{
FilterX = new PruitteFilterX();
FilterY = new PruitteFilterY();
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color dX = FilterX.calculateNewPixelColor(sourceImage, x, y);
Color dY = FilterY.calculateNewPixelColor(sourceImage, x, y);
float resultR = (float)Math.Sqrt(dX.R * dX.R + dY.R * dY.R);
float resultG = (float)Math.Sqrt(dX.G * dX.G + dY.G * dY.G);
float resultB = (float)Math.Sqrt(dX.B * dX.B + dY.B * dY.B);
return Color.FromArgb(
Clamp((int)resultR, 0, 255),
Clamp((int)resultG, 0, 255),
Clamp((int)resultB, 0, 255)
);
}
}
class SharpnessFilter2 : MatrixFilter
{
public SharpnessFilter2()
{
kernel = new float[,] { { -1, -1, -1 }, { -1, 9, -1 }, { -1, -1, -1 } };
}
}
class MotionBlurFilter : MatrixFilter
{
public MotionBlurFilter()
{
int n = 9;
kernel = new float[n, n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j)
{
kernel[i, j] = 1.0f / n;
}
else
{
kernel[i, j] = 0;
}
}
}
}
}
class GrayWorldFilter
{
public int Clamp(int value, int min, int max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
public Bitmap processImage(Bitmap sourceImage)
{
float N = sourceImage.Width * sourceImage.Height;
int sumR = 0;
int sumG = 0;
int sumB = 0;
for (int i = 0; i < sourceImage.Width; i++)
{
for (int j = 0; j < sourceImage.Height; j++)
{
Color sourcecolor1 = sourceImage.GetPixel(i, j);
sumR += sourcecolor1.R;
sumG += sourcecolor1.G;
sumB += sourcecolor1.B;
}
}
float avgR = sumR / N;
float avgG = sumG / N;
float avgB = sumB / N;
double avg = (avgR + avgG + avgB) / 3;
Bitmap resultImage = new Bitmap(sourceImage.Width, sourceImage.Height);
for (int i = 0; i < sourceImage.Width; i++)
{
for (int j = 0; j < sourceImage.Height; j++)
{
Color sourceColor = sourceImage.GetPixel(i, j);
Color resultColor = Color.FromArgb(Clamp((int)(sourceColor.R * avg / avgR), 0, 255), Clamp((int)(sourceColor.G * avg / avgG), 0, 255), Clamp((int)(sourceColor.B * avg / avgB), 0, 255));
resultImage.SetPixel(i, j, resultColor);
}
}
return resultImage;
}
}
class GistFilter
{
public int Clamp(int value, int min, int max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
public Bitmap processImage(Bitmap sourceImage)
{
Bitmap resultImage = new Bitmap(sourceImage.Width, sourceImage.Height);
float min = 255;
float max = 0;
for (int i = 0; i < sourceImage.Width; i++)
for (int j = 0; j < sourceImage.Height; j++)
{
float intensity = (sourceImage.GetPixel(i, j).R + sourceImage.GetPixel(i, j).G + sourceImage.GetPixel(i, j).B) / 3;
if (intensity > max)
{
max = intensity;
}
if (intensity < min)
{
min = intensity;
}
}
if (min == max)
{
max++;
}
for (int i = 0; i < sourceImage.Width; i++)
for (int j = 0; j < sourceImage.Height; j++)
{
float intensity = (sourceImage.GetPixel(i, j).R + sourceImage.GetPixel(i, j).G + sourceImage.GetPixel(i, j).B) / 3;
float g = (intensity - min) * (255 / (max - min));
float resR = sourceImage.GetPixel(i, j).R / intensity;
float resG = sourceImage.GetPixel(i, j).G / intensity;
float resB = sourceImage.GetPixel(i, j).B / intensity;
Color resultColor = Color.FromArgb(Clamp((int)(g * resR), 0, 255), Clamp((int)(g * resG), 0, 255), Clamp((int)(g * resB), 0, 255));
resultImage.SetPixel(i, j, resultColor);
}
return resultImage;
}
}
class MedianFilter : MatrixFilter
{
int Sort(int n, int[] mass)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (mass[j] > mass[j + 1])
{
int temp;
temp = mass[j];
mass[j] = mass[j + 1];
mass[j + 1] = temp;
}
}
}
return (mass[n / 2 + 1]);
}
public Bitmap processImage(int radius, Bitmap image)
{
int[] massR = new Int32[radius * radius];
int[] massG = new Int32[radius * radius];
int[] massB = new Int32[radius * radius];
Bitmap resultImage = new Bitmap(image.Width, image.Height);
int resultR = 0;
int resultG = 0;
int resultB = 0;
int kkk = image.Height;
for (int x = radius / 2 + 1; x < image.Height - radius / 2 - 2; x++)
for (int y = (radius / 2 + 1); y < image.Width - radius / 2 - 2; y++)
{
int k = 0;
for (int i = y - radius / 2; i < y + radius / 2 + 1; i++)
{
for (int j = x - radius / 2; j < x + radius / 2 + 1; j++)
{
Color sourceColor = image.GetPixel(i, j);
massR[k] = (Int32)(sourceColor.R);
massG[k] = (Int32)(sourceColor.G);
massB[k] = (Int32)(sourceColor.B);
k++;
}
}
resultR = Sort(radius * radius, massR);
resultG = Sort(radius * radius, massG);
resultB = Sort(radius * radius, massB);
Color resultColor = Color.FromArgb(
Clamp(resultR, 0, 255),
Clamp(resultG, 0, 255),
Clamp(resultB, 0, 255)
);
resultImage.SetPixel(y, x, resultColor);
}
return resultImage;
}
}
abstract class MorfologeFilter : Filters
{
protected int MW = 3, MH = 3;
protected int[,] Mask = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } };
public override Bitmap processImage(Bitmap sourceImage, BackgroundWorker worker)
{
Bitmap resultImage = new Bitmap(sourceImage.Width, sourceImage.Height);
for (int i = MW / 2; i < sourceImage.Width - MW / 2; i++)
{
worker.ReportProgress((int)((float)i / resultImage.Width * 100));
if (worker.CancellationPending)
return null;
for (int j = MH / 2; j < sourceImage.Height - MH / 2; j++)
resultImage.SetPixel(i, j, calculateNewPixelColor(sourceImage, i, j));
}
return resultImage;
}
}
class ErosionFilter : MorfologeFilter
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color min = Color.FromArgb(255, 255, 255);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] != 0 && pixel.R < min.R && pixel.G < min.G && pixel.B < min.B)
min = pixel;
}
return min;
}
}
class DilationFilter : MorfologeFilter
{
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color max = Color.FromArgb(0, 0, 0);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] == 1 && pixel.R > max.R && pixel.G > max.G && pixel.B > max.B)
max = pixel;
}
return max;
}
}
class OpeningFilter : MorfologeFilter
{
public override Bitmap processImage(Bitmap sourceImage, BackgroundWorker worker)
{
Bitmap erosion = new Bitmap(sourceImage.Width, sourceImage.Height);
for (int i = MW / 2; i < erosion.Width - MW / 2; i++)
{
worker.ReportProgress((int)((float)i / erosion.Width * 50));
if (worker.CancellationPending)
return null;
for (int j = MH / 2; j < erosion.Height - MH / 2; j++)
erosion.SetPixel(i, j, calculateNewPixelColor(sourceImage, i, j));
}
Bitmap result = new Bitmap(erosion);
for (int i = MW / 2; i < result.Width - MW / 2; i++)
{
worker.ReportProgress((int)((float)i / result.Width * 50 + 50));
if (worker.CancellationPending)
return null;
for (int j = MH / 2; j < result.Height - MH / 2; j++)
result.SetPixel(i, j, calcDilation(erosion, i, j));
}
return result;
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color min = Color.FromArgb(255, 255, 255);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] != 0 && pixel.R < min.R && pixel.G < min.G && pixel.B < min.B)
min = pixel;
}
return min;
}
private Color calcDilation(Bitmap sourceImage, int x, int y)
{
Color max = Color.FromArgb(0, 0, 0);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] == 1 && pixel.R > max.R && pixel.G > max.G && pixel.B > max.B)
max = pixel;
}
return max;
}
}
class ClosingFilter : MorfologeFilter
{
public override Bitmap processImage(Bitmap sourceImage, BackgroundWorker worker)
{
Bitmap dilation = new Bitmap(sourceImage.Width, sourceImage.Height);
for (int i = MW / 2; i < dilation.Width - MW / 2; i++)
{
worker.ReportProgress((int)((float)i / dilation.Width * 50));
if (worker.CancellationPending)
return null;
for (int j = MH / 2; j < dilation.Height - MH / 2; j++)
dilation.SetPixel(i, j, calculateNewPixelColor(sourceImage, i, j));
}
Bitmap result = new Bitmap(dilation);
for (int i = MW / 2; i < result.Width - MW / 2; i++)
{
worker.ReportProgress((int)((float)i / result.Width * 50 + 50));
if (worker.CancellationPending)
return null;
for (int j = MH / 2; j < result.Height - MH / 2; j++)
result.SetPixel(i, j, calcErosion(dilation, i, j));
}
return result;
}
public override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
Color max = Color.FromArgb(0, 0, 0);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] == 1 && pixel.R > max.R && pixel.G > max.G && pixel.B > max.B)
max = pixel;
}
return max;
}
private Color calcErosion(Bitmap sourceImage, int x, int y)
{
Color min = Color.FromArgb(255, 255, 255);
for (int j = -MH / 2; j <= MH / 2; j++)
for (int i = -MW / 2; i <= MW / 2; i++)
{
Color pixel = sourceImage.GetPixel(x + i, y + j);
if (Mask[i + MW / 2, j + MH / 2] != 0 && pixel.R < min.R && pixel.G < min.G && pixel.B < min.B)
min = pixel;
}
return min;
}
}
}
|
1c5ee713a8d0f43a632429eead20be9fb75c95a1
|
C#
|
RobaLinan/open4051
|
/Open4051/ToolBarWindow.cs
| 2.59375
| 3
|
using System;
using System.Diagnostics;
namespace Open4051
{
public partial class ToolBarWindow : Gtk.Window
{
private string browser;
private string kbdPosition = "middle";
public string KbdPositoin
{
get{ return kbdPosition; }
set{ kbdPosition = value; }
}
public string Browser
{
get{ return browser; }
set{ browser = value; }
}
public ToolBarWindow()
: base(Gtk.WindowType.Toplevel)
{
this.Build();
this.KeepAbove = true;
int width, height;
this.GetSize(out width, out height);
this.Move(Screen.Width - width, 0);
}
protected void OnBtnCloseAllClicked(object sender, EventArgs e)
{
foreach (Process p in Process.GetProcessesByName("ScreenKeyboard"))
{
p.Kill();
}
CloseBrowser();
this.ParentWindow.Destroy();
}
protected void OnBtnKeyboardClicked(object sender, EventArgs e)
{
KeyboardCtrl();
}
public void CloseBrowser()
{
string processname = browser.Substring(1 + browser.LastIndexOf("\\"));
processname = processname.Substring(0, processname.IndexOf(".exe"));
foreach (Process p in Process.GetProcessesByName(processname))
{
p.Kill();
}
}
public void KeyboardCtrl()
{
foreach (Process p in Process.GetProcessesByName("ScreenKeyboard"))
{
p.Kill();
return;
}
Process kbdProcess = new Process();
kbdProcess.StartInfo.Arguments = kbdPosition;
kbdProcess.StartInfo.FileName = "ScreenKeyboard.exe";
kbdProcess.Start();
}
protected void OnBtnCloseBrowserClicked(object sender, EventArgs e)
{
CloseBrowser();
}
}
}
|
410545214f497a6444195c5c4bf3de3510bf1125
|
C#
|
shendongnian/download4
|
/first_version_download2/359226-30817294-92746104-2.cs
| 2.9375
| 3
|
public bool SendMessage(SerialPort port, string phoneNo, string message)
{
bool isSend = false;
try
{
string recievedData = SendATCommand(port,"AT", 300, "No phone connected");
string command = "AT+CMGF=1" + char.ConvertFromUtf32(13);
recievedData = SendATCommand(port,command, 300, "Failed to set message format.");
// AT Command Syntax - http://www.smssolutions.net/tutorials/gsm/sendsmsat/
command = "AT+CMGS=\"" + phoneNo + "\"" + char.ConvertFromUtf32(13);
recievedData = SendATCommand(port, command, 300,
"Failed to accept phoneNo");
command = message + char.ConvertFromUtf32(26);
recievedData = SendATCommand(port, command, 3000,
"Failed to send message"); //3 seconds
if (recievedData.EndsWith("\r\nOK\r\n"))
isSend = true;
else if (recievedData.Contains("ERROR"))
isSend = false;
return isSend;
}
catch (Exception ex)
{
throw ex;
}
}
|
4e8a88712ffc9dd921258cc87d7ae2d212e331c9
|
C#
|
red-panda-web/CourseWorkSemest5
|
/WpfApp1/ChangeEmployee.xaml.cs
| 2.921875
| 3
|
using System;
using System.Linq;
using System.Windows;
namespace WpfApp1
{
public partial class ChangeEmployee : Window
{
int id;
string conString;
int idCurrentEmpl;
public ChangeEmployee(string str, int empl_id)
{
InitializeComponent();
conString = str;
idCurrentEmpl = empl_id;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
id = Convert.ToInt32(empl_id.Text);
if (id > 0)
{
using (ADOmodel db = new ADOmodel(conString))
{
var EmployeeExists = db.Employees.Any(em => em.id_Employee == id);
if (EmployeeExists)
{
empl_data.IsEnabled = true;
change_btn.IsEnabled = true;
empl_found.Content = "Сотрудник с таким id найден!";
}
else MessageBox.Show("Сотрудник с таким id не найден!", "Изменение", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
else MessageBox.Show("Некорректный id!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
}
catch (Exception)
{
MessageBox.Show("Некорректный id!", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void change_btn_Click(object sender, RoutedEventArgs e)
{
AdminPage main = this.Owner as AdminPage;
string name = empl_Name.Text;
string surname = empl_Surname.Text;
string patronymic = empl_Patronymic.Text;
var pos = empl_Position.SelectedIndex;
var role = empl_Role.SelectedIndex;
string log = empl_Log.Text;
string pas = empl_Password.Text;
using (ADOmodel db = new ADOmodel(conString))
{
try
{
var employee = db.Employees.Where(em => em.id_Employee == id).FirstOrDefault();
if (name != "") employee.Name = name;
if (surname != "") employee.Surname = surname;
if (patronymic != "") employee.Patronymic = patronymic;
if (pos != -1) employee.id_Position = pos + 1;
if (role != -1) employee.id_Role = role + 1;
if (log != "") employee.Login = log;
if (pas != "") employee.Password = pas;
db.SaveChanges();
MessageBox.Show("Данные успешно изменены!", "Изменение", MessageBoxButton.OK, MessageBoxImage.Information);
if (idCurrentEmpl == id && log != "" || idCurrentEmpl == id && pas != "")
{
MessageBox.Show("Необходимо произвести вход с помощью новых данных.", "Изменение", MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
MainWindow mw = new MainWindow();
mw.Show();
main.Close();
}
else this.Close();
}
catch(System.Data.Entity.Infrastructure.DbUpdateException)
{
MessageBox.Show("Ошибка. Попробуйте менять логин и пароль по очереди, а не одновременно.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
}
|
951abe1a69f3d1a5b23e72c9b0b962e0ae932ffb
|
C#
|
manycore/harvester
|
/Harvester.Analysis/Processors/CoherencyProcessor.cs
| 2.515625
| 3
|
using Diagnostics.Tracing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Harvester.Analysis
{
public class CoherencyProcessor : EventProcessor
{
/// <summary>
/// Constructs a new processor for the provided data files.
/// </summary>
/// <param name="preprocessor">Preprocessor to use</param>
public CoherencyProcessor(EventProcessor preprocessor) : base(preprocessor) { }
/// <summary>
/// Invoked when an analysis needs to be performed.
/// </summary>
protected override EventOutput OnAnalyze()
{
// Here we will store our results
var output = new EventOutput(this.Process.Name, this.Start);
// Process every frame
foreach (var frame in this.Frames)
{
// Build some shortcuts
var core = frame.Core;
// Get corresponding hardware counters
var cn = frame.HwCounters;
// Process every thread within this frame
foreach (var thread in frame.Threads)
{
// Get the multiplier for that thread
var multiplier = frame.GetOnCoreRatio(thread);
output.Add("l1Invalidations", frame, thread, Math.Round(multiplier * cn.L1Invalidations));
output.Add("l2Invalidations", frame, thread, Math.Round(multiplier * cn.L2Invalidations));
output.Add("l1miss", frame, thread, Math.Round(multiplier * cn.L1Misses));
output.Add("l2miss", frame, thread, Math.Round(multiplier * cn.L2Misses));
}
}
// Return the results
return output;
}
}
}
|
65fe36b9b61183f11c9079a3632f6937f1bccda5
|
C#
|
mslitao/Leetcode
|
/Other.food-menu-ordering.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
/*
Your task is to process the following menu of food items, and determine which combination of food items could be purchased for the receipt values below.
The Menu: (I'll try to provide this in a hash or map data structure as an input)
veggie sandwich: 6.85
extra veggies: 2.20
chicken sandwich: 7.85
extra chicken: 3.20
cheese: 1.25
chips: 1.40
nachos: 3.45
soda: 2.05
The receipt values to test, also provided as an input:
4.85, 11.05, 13.75, 17.75, 18.25, 19.40, 28.25, 40.30, 75.00
- your script should process as many of these receipt values as possible in under 30 seconds
- you must use 100% of the money, we don't want any money left over
- you can order any quantity of any menu item
- none of the receipt values are "tricks", they all have combinations that add up to exactly their money amount
Part One:
Find a single combination of menu items that add up to exactly these amounts of money, and output them as your script runs. Output format is up to you, but here are a few examples:
13.75, 3 items, ['veggie sandwich', 'nachos', 'nachos']
13.75, 3 items, {'veggie sandwich': 1, 'nachos': 2}
Part Two:
Each receipt value above has many possible combinations. Next, refactor your algorithm to identify which combination contains fewer total items than other answers.
Example:
4.85 receipt has three combinations:
- best: nachos, chips (2 total items)
- extra veggies, chips, cheese (3 total times)
- chips, chips, soda (3 total items)
*/
class SolutionCombine
{
public IList<IList<int>> CombinationSum(int[] candidates, int target) {
IList<IList<int>> results = new List<IList<int>>();
if(candidates==null || candidates.Length ==0 ) return results;
List<int> current = new List<int>();
BacktrackCombinationSum(current, 0, 0, candidates, target, results);
return results;
}
public void BacktrackCombinationSum(List<int> current, int sum, int idx, int[] nums, int target, IList<IList<int>> results)
{
if(sum == target)
{
var res = new List<int>(current);
results.Add(res);
return;
}
if(sum > target)
{
return;
}
for(int i = idx; i < nums.Length; ++i)
{
var num = nums[i];
var pos = current.Count;
current.Add(num);
BacktrackCombinationSum(current, sum+num, i, nums, target, results);
current.RemoveAt(pos);
}
}
//131. Palindrome Partitioning
public IList<IList<string>> PartitionString(string s) {
IList<IList<string>> results = new List<IList<string>>();
if(string.IsNullOrEmpty(s)) return results;
int len = s.Length;
bool[,] dp = new bool[len, len];
int result = 0;
for(int i =len-1; i >=0 ; --i)
for(int j =i; j < len; ++j)
{
if(s[i] == s[j] && (j <= i +1 || dp[i+1, j-1]))
{
dp[i, j] = true;
result++;
}
}
List<string> current = new List<string>();
BPPartitionString(current, 0, s, results, dp);
return results;
}
public void BPPartitionString(List<string> current, int idx, string s, IList<IList<string>> results, bool[,] dp)
{
if(idx >= s.Length)
{
List<string> res = new List<string>(current);
results.Add(res);
return;
}
for(int i =idx; i < s.Length; ++i)
{
if(!dp[idx, i]) continue;
int pos = current.Count;
current.Add(s.Substring(idx, i-idx+1));
BPPartitionString(current, i+1, s, results, dp);
current.RemoveAt(pos);
}
}
public int CountSubstrings(string s) {
if(string.IsNullOrEmpty(s)) return 0;
int len = s.Length;
bool[,] dp = new bool[len, len];
int result = 0;
for(int i =len-1; i >=0 ; --i)
for(int j =i; j < len; ++j)
{
if(s[i] == s[j] && (j <= i +1 || dp[i+1, j-1]))
{
dp[i, j] = true;
result++;
}
}
return result;
}
static void Main1(string[] args)
{
float [] receipts =new [] {4.85F, 11.05F, 13.75F, 17.75F, 18.25F, 19.40F, 28.25F, 40.30F, 75.00F};
Dictionary<string, float> menu_items = new Dictionary<string, float>();
menu_items.Add("veggie sandwich", 6.85F);
menu_items.Add("extra veggies", 2.20F);
menu_items.Add("chicken sandwich", 7.85F);
menu_items.Add("extra chicken", 3.20F);
menu_items.Add("cheese", 1.25F);
menu_items.Add("chips", 1.40F);
menu_items.Add("nachos", 3.45F);
menu_items.Add("soda", 2.05F);
/*foreach(var receipt in receipts)
{
float current = 0.0F;
List<string> items = new List<string>();
List<List<string>> results = new List<List<string>>();
FindPurchaseItems(current, items, receipt, menu_items, results);
int minItems = int.MaxValue;
List<string> bestResult = null;
foreach(var result in results)
{
if(result.Count < minItems)
{
bestResult = result;
minItems = result.Count;
}
}
Console.WriteLine(String.Format("{0}, {1} items, {2}",
receipt,
minItems,
string.Join(",", bestResult)));
}*/
foreach(var receipt in receipts)
{
Console.WriteLine(String.Format("{0}, {1} items, {2}",
receipt,
DPFindPurchaseItems(receipt, menu_items),
""));
}
}
public static void FindPurchaseItems(float current, List<string> items, float receipt, Dictionary<string, float> menuItems, List<List<string>> results)
{
if(current == receipt)
{
List<string> result = new List<string>(items);
results.Add(result);
return;
}
else if(current > receipt)
{
return;
}
else
{
foreach(var item in menuItems)
{
var cnt = items.Count;
items.Add(item.Key);
FindPurchaseItems(current + item.Value, items, receipt, menuItems, results);
items.RemoveAt(cnt);
}
}
}
public static int DPFindPurchaseItems(float receipt, Dictionary<string, float> menuItems)
{
// Step 1: Initilize the dp array
int size = (int)(100.0* receipt) ;
int[] dpCnt = new int[size + 1];
List<List<string>> dpItems = new List<List<string>>();
dpCnt[0] = 0;
dpItems.Add(new List<string>());
//Step 2: update the DP array
for(int i = 1; i <= size; ++i)
{
int minItems = int.MaxValue;
foreach(var item in menuItems)
{
int cnt = 1;
while((receipt - item.Value* cnt) >=0)
{
var pos = (int)(100.0 *(receipt - item.Value*cnt));
if(dpCnt[pos] >=0)
{
minItems = Math.Min(minItems, cnt + dpCnt[pos]);
}
cnt ++;
}
}
if(minItems == int.MaxValue)
{
dpCnt[i] = -1;
}
else
{
dpCnt[i] = minItems;
}
}
// R
return dpCnt[size];
}
}
/*
BT:
1. BPFun(current, list<> items, price)
DP
0.0 -> target (0.01)
1. min items to purchase and meet the price
2. 0 to n
f(i) = Min(f(i - ), )
*/
/*
best answers for part 2:
4.85: 2 items, ['chips', 'nachos']
11.05: 2 items, ['extra chicken', 'chicken sandwich']
13.75: 3 items, ['nachos', 'nachos', 'veggie sandwich']
17.75: 3 items, ['soda', 'chicken sandwich', 'chicken sandwich']
18.25: 5 items, ['cheese', 'cheese', 'soda', 'veggie sandwich', 'veggie sandwich']
19.40: 4 items, ['cheese', 'nachos', 'veggie sandwich', 'chicken sandwich']
28.25: 5 items, ['cheese', 'nachos', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich']
40.30: 6 items, ['soda', 'veggie sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich']
75.00: 12 items, ['cheese', 'soda', 'soda', 'veggie sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich', 'chicken sandwich']
alternate for $75 receipt, also 12 items:
['soda','nachos','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','veggie sandwich','chicken sandwich']
*/
// To execute C#, please define "static void Main" on a class
// named Solution.
|
e9dff922e86c54ea328e8a601ae9a7ec2868f0e7
|
C#
|
shendongnian/download4
|
/code11/1908223-57341898-202829573-2.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> records = doc.Descendants("record").ToList();
List<string> uniquetagNames = records.SelectMany(x => x.Elements().Select(y => y.Name.LocalName)).Distinct().ToList();
foreach (XElement record in records)
{
XElement newRecord = new XElement("record");
foreach (string uniquetagName in uniquetagNames)
{
if (record.Element(uniquetagName) == null)
{
newRecord.Add(new XElement(uniquetagName));
}
else
{
newRecord.Add(record.Element(uniquetagName));
}
}
record.ReplaceWith(newRecord);
}
}
}
}
|
42ed1bf6626696b4850036070b955c430bde25d1
|
C#
|
morerokk/softwareontwerpeindscrum
|
/SoftwareOntwerpEindOpdrachtScrum/Scrum/ProxySprint.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareOntwerpEindOpdrachtScrum.Scrum
{
public class ProxySprint : Sprint
{
private RealSprint _realSprint;
public override string Name
{
get
{
return _realSprint.Name;
}
set
{
if(!_realSprint.State.CanEdit)
{
throw new InvalidOperationException("Sprints cannot be edited once started!");
}
_realSprint.Name = value;
}
}
public override DateTime StartDate
{
get
{
return _realSprint.StartDate;
}
set
{
if (!_realSprint.State.CanEdit)
{
throw new InvalidOperationException("Sprints cannot be edited once started!");
}
_realSprint.StartDate = value;
}
}
public override DateTime EndDate
{
get
{
return _realSprint.EndDate;
}
set
{
if (!_realSprint.State.CanEdit)
{
throw new InvalidOperationException("Sprints cannot be edited once started!");
}
_realSprint.EndDate = value;
}
}
public override bool Review
{
get
{
return _realSprint.Review;
}
set
{
if (!_realSprint.State.CanEdit)
{
throw new InvalidOperationException("Sprints cannot be edited once started!");
}
_realSprint.Review = value;
}
}
public override SprintState State
{
get
{
return _realSprint.State;
}
set
{
_realSprint.State = value;
}
}
public override string ReviewSummaryDocument
{
get
{
return _realSprint.ReviewSummaryDocument;
}
set
{
_realSprint.ReviewSummaryDocument = value;
}
}
public ProxySprint()
{
this._realSprint = new RealSprint();
}
public ProxySprint(RealSprint sprint)
{
this._realSprint = sprint;
}
public override void Start()
{
_realSprint.Start();
}
public override void Close()
{
//If this sprint is closed with a review, check if a document has been uploaded.
if(this.Review && this.ReviewSummaryDocument == null)
{
throw new InvalidOperationException("A summary document of the sprint review has not been uploaded yet!");
}
this._realSprint.Close();
}
public override void Attach(IObserver observer)
{
_realSprint.Attach(observer);
}
public override void Detach(IObserver observer)
{
_realSprint.Detach(observer);
}
public override void NotifyObservers()
{
_realSprint.NotifyObservers();
}
}
}
|
c517d76a6c8164ad82c4637d3a774e5415d4d97f
|
C#
|
TheGrandCoding/chat-program
|
/chat-program/chat-program/Server/CommandManager.cs
| 2.65625
| 3
|
using ChatProgram.Server.Commands;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ChatProgram.Server
{
public class CommandManager
{
public List<CommandGroup> Commands;
public Dictionary<Type, TypeParsers.TypeParser> TypeParsers;
List<Command> Search(string text)
{
List<Command> POSSIBLE_COMMANDS = new List<Command>();
text = text.Substring(1); // remove /
string[] splitith = text.Split(' ');
foreach (var group in Commands)
{
string combined = "";
int indexForGroup = -1;
int counter = -1;
foreach (var word in splitith)
{
counter++;
combined += word.ToLower() + " ";
if (combined.StartsWith(group.Group))
{
indexForGroup = counter;
break;
}
}
if (group.Group == "" || indexForGroup > -1)
{
var args = splitith.Skip(indexForGroup - 1);
foreach(var command in group.Children)
{
combined = "";
indexForGroup = -1;
counter = -1;
foreach(var word in args)
{
combined += word.ToLower() + " ";
if(combined.StartsWith(command.Name))
{
indexForGroup = counter;
POSSIBLE_COMMANDS.Add(command);
break;
}
}
}
}
}
return POSSIBLE_COMMANDS;
}
object parseArg(CommandContext context, string text, ParameterInfo par)
{
if(TypeParsers.TryGetValue(par.ParameterType, out var parser))
{
var result = parser.Parse(context, text);
if (result.IsSuccess)
return result.Object;
}
return null;
}
ParseParamaterResult ParseParamaters(CommandContext context, Command command, string[] arguments)
{
List<object> OUTPUTS = new List<object>();
var parameters = command.CommandMethod.GetParameters();
if (parameters.Count() > arguments.Count())
return new ParseParamaterResult($"Expected at least {parameters.Count()} args, but {arguments.Count()} given");
if (parameters.Count() == 0 && arguments.Count() > 0)
return new ParseParamaterResult($"Expected no args, but {arguments.Count()} given");
for (int i = 0; i < arguments.Count() && i < parameters.Count(); i++)
{
var arg = arguments.ElementAt(i);
var par = parameters.ElementAt(i);
if (i == parameters.Count() - 1 && par.ParameterType == typeof(string))
{ // this is last param, so we shall see if this be a string
// if it is, so we take all the remainder of the argument string given
var args = arguments.Skip(i);
string joined = string.Join(" ", args);
OUTPUTS.Add(joined);
} else
{
try
{
var parsed = parseArg(context, arg, par);
if (parsed != null)
OUTPUTS.Add(parsed);
else
return new ParseParamaterResult($"Could not parse {arg} to {par.ParameterType.FullName}");
} catch (Exception ex)
{
return new ParseParamaterResult($"{ex.Message}");
}
}
}
return new ParseParamaterResult(OUTPUTS);
}
CommandValidResult checkSingularCmd(CommandContext context, Command command)
{
var pars = ParseParamaters(context, command, GetArguments(command, context.Message.Content));
if (!pars.IsSuccess)
return new CommandValidResult(pars.ErrorReason);
foreach(var cond in command.Preconditions)
{
var rs = cond.CheckPrecondition(context);
if(!rs.IsSuccess)
{
return new CommandValidResult(rs.ErrorReason);
}
}
return new CommandValidResult(pars);
}
List<CommandValidResult> FilterInvalids(CommandContext context, List<Command> commands)
{
if(commands.Count == 1)
{
var cmd = commands[0];
var res = checkSingularCmd(context, cmd);
if(!res.IsSuccess)
{
ReplyToUser($"Error: {res.ErrorReason}", context.User);
return new List<CommandValidResult>();
}
return new List<CommandValidResult>() { new CommandValidResult(cmd, res.ParamResult) };
}
var FILTERED = new List<CommandValidResult>();
foreach(var cmd in commands)
{
var result = checkSingularCmd(context, cmd);
if (result.IsSuccess)
FILTERED.Add(new CommandValidResult(cmd, result.ParamResult));
}
return FILTERED;
}
string[] GetArguments(Command cmd, string input)
{
if (input.StartsWith("/")) input = input.Substring(1);
string starts = $"{(string.IsNullOrWhiteSpace(cmd.Parent.Group) ? "" : $"{cmd.Parent.Group} ")}{cmd.Name}";
string argument = input.Replace(starts, "");
return argument.Split(' ').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray();
}
void ReplyToUser(string message, Classes.User usr)
{
var msg = new Classes.Message();
msg.Colour = message.StartsWith("Error:") ? Color.Red : Color.Black;
msg.Author = Menu.Server.SERVERUSER;
msg.Content = message;
msg.Id = Common.IterateMessageId();
Menu.Server.Server.SendTo(usr, new Classes.Packet(Classes.PacketId.NewMessage, msg.ToJson()));
}
public void Execute(Classes.Message message)
{
var context = new CommandContext(message.Author, message);
var cmds = Search(message.Content);
var valids = FilterInvalids(context, cmds);
var first = valids.OrderByDescending(x => x.Command.Priority).FirstOrDefault();
if(first == null)
{
ReplyToUser($"Unable to find any command that matches your input", context.User);
} else
{
var command = first.Command;
command.Invoke(context, first.ParamResult.Output.ToArray());
}
}
public void LoadCommands()
{
Commands = new List<CommandGroup>();
var type = typeof(CommandBase);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsSubclassOf(type));
foreach(var groupType in types)
{
if (groupType.FullName == "ChatProgram.Server.CommandGroup")
continue;
try
{
var group = walkGroupTree(groupType);
Commands.Add(group);
} catch (Exception ex)
{
Logger.LogMsg($"{groupType.FullName}: {ex.ToString()}", LogSeverity.Error);
}
}
}
public void LoadTypeParsers()
{
TypeParsers = new Dictionary<Type, TypeParsers.TypeParser>();
TypeParsers[typeof(string)] = new TypeParsers.StringTypeParser();
TypeParsers[typeof(int)] = new TypeParsers.IntTypeParser();
TypeParsers[typeof(bool)] = new TypeParsers.BoolTypeParser();
TypeParsers[typeof(Classes.User)] = new TypeParsers.UserTypeParser();
}
static string GetNotNull(ValueStringAttribute attribute, string message)
{
if (attribute == null)
throw new Exception(message);
if (string.IsNullOrWhiteSpace(attribute.Value))
throw new Exception(message);
return attribute.Value;
}
CommandGroup walkGroupTree(Type groupType)
{
var group = new CommandGroup();
var nameAttribute = groupType.GetCustomAttribute<NameAttribute>();
var name = GetNotNull(nameAttribute, $"{groupType.FullName} has no Name attribute set");
group.Name = name;
var groupAttr = groupType.GetCustomAttribute<GroupAttribute>();
group.Group = groupAttr?.Value ?? "";
group.CommandClass = groupType;
var methods = groupType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
group.Children = new List<Command>();
foreach(var method in methods)
{
try
{
walkCommand(group, method);
} catch (Exception ex)
{
Logger.LogMsg($"{name}/{method.Name}: {ex.ToString()}", LogSeverity.Error);
}
}
return group;
}
void walkCommand(CommandGroup parent, MethodInfo method)
{
var cmd = new Command();
cmd.Parent = parent;
cmd.CommandMethod = method;
cmd.CommandClass = parent.CommandClass;
var nameAttr = method.GetCustomAttribute<NameAttribute>();
var name = GetNotNull(nameAttr, $"{method.Name} cmd has no name");
cmd.Name = name;
var intAttr = method.GetCustomAttribute<PriorityAttribute>();
cmd.Priority = (intAttr?.Value ?? 0);
cmd.Preconditions = new List<PreconditionAttribute>();
foreach (var attribute in method.GetCustomAttributes<PreconditionAttribute>())
cmd.Preconditions.Add(attribute);
parent.Children.Add(cmd);
}
}
public class CommandContext
{
public ChatProgram.Classes.User User { get; }
public ChatProgram.Classes.Message Message { get; }
public Classes.User ServerUser { get; }
public ServerForm Server { get; }
internal CommandContext(Classes.User user, Classes.Message message)
{
User = user;
Message = message;
Server = Menu.Server;
ServerUser = Server.SERVERUSER;
}
}
public abstract class CommandBase
{
protected CommandContext Context { get; private set; }
internal CommandBase() { }
internal CommandBase WithContext(CommandContext c)
{
Context = c;
return this;
}
protected virtual void BeforeExecute()
{
}
protected virtual void AfterExecute()
{
}
protected virtual void BroadCast(string message, System.Drawing.Color? color = null)
{
var msg = new Classes.Message();
msg.Colour = color ?? Color.Black;
msg.Author = Context.ServerUser;
msg.Content = message;
msg.Id = Common.IterateMessageId();
var packet = new Classes.Packet(Classes.PacketId.NewMessage, msg.ToJson());
Context.Server.Server.Broadcast(packet);
Context.Server.Server._internalServerMessage(msg);
}
protected virtual void Reply(string message, System.Drawing.Color? color = null)
{
var msg = new Classes.Message();
msg.Colour = color ?? Color.DarkGray;
msg.Author = Context.ServerUser;
msg.Content = message;
msg.Id = Common.IterateMessageId();
if(Context.User.Id == Context.ServerUser.Id)
{
Context.Server.Server._internalServerMessage(msg);
} else
{
var packet = new Classes.Packet(Classes.PacketId.NewMessage, msg.ToJson());
Context.Server.Server.SendTo(Context.User, packet);
}
}
protected virtual void SendTo(Classes.User user, string message, System.Drawing.Color? color = null)
{
var msg = new Classes.Message();
msg.Colour = color ?? Color.Black;
msg.Author = Context.ServerUser;
msg.Content = message;
msg.Id = Common.IterateMessageId();
if (user.Id == Context.ServerUser.Id)
{
Context.Server.Server._internalServerMessage(msg);
}
else
{
var packet = new Classes.Packet(Classes.PacketId.NewMessage, msg.ToJson());
Context.Server.Server.SendTo(user, packet);
}
}
}
public class Command
{
public string Name { get; set; }
public int Priority { get; set; }
public List<PreconditionAttribute> Preconditions { get; set; }
public Type CommandClass;
public MethodInfo CommandMethod;
public CommandGroup Parent;
public void Invoke(CommandContext context, object[] args)
{
CommandBase cmdBase = (CommandBase)Activator.CreateInstance(CommandClass);
cmdBase.WithContext(context);
CommandMethod.Invoke(cmdBase, parameters: args);
}
}
public class CommandGroup
{
public string Name { get; set; }
public string Group { get; set; }
public Type CommandClass;
public List<Command> Children;
}
public class Result
{
public bool IsSuccess { get; }
public string ErrorReason { get; }
public Result(bool s, string err)
{
IsSuccess = s;
ErrorReason = err;
}
}
public class CommandValidResult : Result
{
public Command Command;
public ParseParamaterResult ParamResult;
public CommandValidResult(string err) : base(false, err)
{
}
public CommandValidResult(ParseParamaterResult r) : base(true, null)
{
ParamResult = r;
}
public CommandValidResult(Command cmd, ParseParamaterResult r) : base(true, null)
{
Command = cmd;
ParamResult = r;
}
}
public class ParseParamaterResult : Result
{
public List<object> Output { get; }
public ParseParamaterResult(List<object> objs) : base(true, "")
{
Output = objs;
}
public ParseParamaterResult(string err) : base(false, err) { }
}
public abstract class PreconditionAttribute : Attribute
{
public abstract Result CheckPrecondition(CommandContext context);
}
}
|
59e0a2f8eac87eeb7abff5ddc72fe838c9fba3b8
|
C#
|
ITGlobal/CLI
|
/src/CLI.Terminal/Impl/Ansi.Generated.cs
| 2.609375
| 3
|
using System;
namespace ITGlobal.CommandLine.Impl
{
partial class Ansi
{
public static AnsiAttributes ForegroundColorToAttributes(ConsoleColor? color)
{
switch (color)
{
case ConsoleColor.Black:
return AnsiAttributes.ATTR_FG_BLACK;
case ConsoleColor.DarkRed:
return AnsiAttributes.ATTR_FG_RED;
case ConsoleColor.DarkGreen:
return AnsiAttributes.ATTR_FG_GREEN;
case ConsoleColor.DarkYellow:
return AnsiAttributes.ATTR_FG_YELLOW;
case ConsoleColor.DarkBlue:
return AnsiAttributes.ATTR_FG_BLUE;
case ConsoleColor.DarkMagenta:
return AnsiAttributes.ATTR_FG_MAGENTA;
case ConsoleColor.DarkCyan:
return AnsiAttributes.ATTR_FG_CYAN;
case ConsoleColor.DarkGray:
return AnsiAttributes.ATTR_FG_WHITE;
case ConsoleColor.Gray:
return AnsiAttributes.ATTR_FG_BRIGHT_BLACK;
case ConsoleColor.Red:
return AnsiAttributes.ATTR_FG_BRIGHT_RED;
case ConsoleColor.Green:
return AnsiAttributes.ATTR_FG_BRIGHT_GREEN;
case ConsoleColor.Yellow:
return AnsiAttributes.ATTR_FG_BRIGHT_YELLOW;
case ConsoleColor.Blue:
return AnsiAttributes.ATTR_FG_BRIGHT_BLUE;
case ConsoleColor.Magenta:
return AnsiAttributes.ATTR_FG_BRIGHT_MAGENTA;
case ConsoleColor.Cyan:
return AnsiAttributes.ATTR_FG_BRIGHT_CYAN;
case ConsoleColor.White:
return AnsiAttributes.ATTR_FG_BRIGHT_WHITE;
default:
return 0;
}
}
public static AnsiAttributes BackgroundColorToAttributes(ConsoleColor? color)
{
switch (color)
{
case ConsoleColor.Black:
return AnsiAttributes.ATTR_BG_BLACK;
case ConsoleColor.DarkRed:
return AnsiAttributes.ATTR_BG_RED;
case ConsoleColor.DarkGreen:
return AnsiAttributes.ATTR_BG_GREEN;
case ConsoleColor.DarkYellow:
return AnsiAttributes.ATTR_BG_YELLOW;
case ConsoleColor.DarkBlue:
return AnsiAttributes.ATTR_BG_BLUE;
case ConsoleColor.DarkMagenta:
return AnsiAttributes.ATTR_BG_MAGENTA;
case ConsoleColor.DarkCyan:
return AnsiAttributes.ATTR_BG_CYAN;
case ConsoleColor.DarkGray:
return AnsiAttributes.ATTR_BG_WHITE;
case ConsoleColor.Gray:
return AnsiAttributes.ATTR_BG_BRIGHT_BLACK;
case ConsoleColor.Red:
return AnsiAttributes.ATTR_BG_BRIGHT_RED;
case ConsoleColor.Green:
return AnsiAttributes.ATTR_BG_BRIGHT_GREEN;
case ConsoleColor.Yellow:
return AnsiAttributes.ATTR_BG_BRIGHT_YELLOW;
case ConsoleColor.Blue:
return AnsiAttributes.ATTR_BG_BRIGHT_BLUE;
case ConsoleColor.Magenta:
return AnsiAttributes.ATTR_BG_BRIGHT_MAGENTA;
case ConsoleColor.Cyan:
return AnsiAttributes.ATTR_BG_BRIGHT_CYAN;
case ConsoleColor.White:
return AnsiAttributes.ATTR_BG_BRIGHT_WHITE;
default:
return 0;
}
}
public static ConsoleColor? ForegroundColorFromAttributes(AnsiAttributes attributes)
{
switch(attributes)
{
case AnsiAttributes.ATTR_FG_BLACK:
return ConsoleColor.Black;
case AnsiAttributes.ATTR_FG_RED:
return ConsoleColor.DarkRed;
case AnsiAttributes.ATTR_FG_GREEN:
return ConsoleColor.DarkGreen;
case AnsiAttributes.ATTR_FG_YELLOW:
return ConsoleColor.DarkYellow;
case AnsiAttributes.ATTR_FG_BLUE:
return ConsoleColor.DarkBlue;
case AnsiAttributes.ATTR_FG_MAGENTA:
return ConsoleColor.DarkMagenta;
case AnsiAttributes.ATTR_FG_CYAN:
return ConsoleColor.DarkCyan;
case AnsiAttributes.ATTR_FG_WHITE:
return ConsoleColor.DarkGray;
case AnsiAttributes.ATTR_FG_BRIGHT_BLACK:
return ConsoleColor.Gray;
case AnsiAttributes.ATTR_FG_BRIGHT_RED:
return ConsoleColor.Red;
case AnsiAttributes.ATTR_FG_BRIGHT_GREEN:
return ConsoleColor.Green;
case AnsiAttributes.ATTR_FG_BRIGHT_YELLOW:
return ConsoleColor.Yellow;
case AnsiAttributes.ATTR_FG_BRIGHT_BLUE:
return ConsoleColor.Blue;
case AnsiAttributes.ATTR_FG_BRIGHT_MAGENTA:
return ConsoleColor.Magenta;
case AnsiAttributes.ATTR_FG_BRIGHT_CYAN:
return ConsoleColor.Cyan;
case AnsiAttributes.ATTR_FG_BRIGHT_WHITE:
return ConsoleColor.White;
default:
return null;
}
}
public static ConsoleColor? BackgroundColorFromAttributes(AnsiAttributes attributes)
{
switch(attributes)
{
case AnsiAttributes.ATTR_BG_BLACK:
return ConsoleColor.Black;
case AnsiAttributes.ATTR_BG_RED:
return ConsoleColor.DarkRed;
case AnsiAttributes.ATTR_BG_GREEN:
return ConsoleColor.DarkGreen;
case AnsiAttributes.ATTR_BG_YELLOW:
return ConsoleColor.DarkYellow;
case AnsiAttributes.ATTR_BG_BLUE:
return ConsoleColor.DarkBlue;
case AnsiAttributes.ATTR_BG_MAGENTA:
return ConsoleColor.DarkMagenta;
case AnsiAttributes.ATTR_BG_CYAN:
return ConsoleColor.DarkCyan;
case AnsiAttributes.ATTR_BG_WHITE:
return ConsoleColor.DarkGray;
case AnsiAttributes.ATTR_BG_BRIGHT_BLACK:
return ConsoleColor.Gray;
case AnsiAttributes.ATTR_BG_BRIGHT_RED:
return ConsoleColor.Red;
case AnsiAttributes.ATTR_BG_BRIGHT_GREEN:
return ConsoleColor.Green;
case AnsiAttributes.ATTR_BG_BRIGHT_YELLOW:
return ConsoleColor.Yellow;
case AnsiAttributes.ATTR_BG_BRIGHT_BLUE:
return ConsoleColor.Blue;
case AnsiAttributes.ATTR_BG_BRIGHT_MAGENTA:
return ConsoleColor.Magenta;
case AnsiAttributes.ATTR_BG_BRIGHT_CYAN:
return ConsoleColor.Cyan;
case AnsiAttributes.ATTR_BG_BRIGHT_WHITE:
return ConsoleColor.White;
default:
return null;
}
}
}
}
|
b75e87fe6f27f8e8a6910f0a6c92658b4f4c3381
|
C#
|
shu-man-ski/ASP.NET
|
/Lab_7/Lab_7/Lab_7/Controllers/PhoneController.cs
| 2.71875
| 3
|
using System;
using System.Linq;
using System.Web.Mvc;
namespace Lab_7.Controllers
{
public class PhoneController : Controller
{
Models.PersonContext context = new Models.PersonContext();
[HttpGet]
public ActionResult Index()
{
return View("Index", context.Persons.AsEnumerable());
}
[HttpGet]
public ActionResult Add()
{
Models.Person person = new Models.Person();
person.BDay = DateTime.Now.AddYears(-18);
return View("Add", person);
}
[HttpPost]
public ActionResult Add(Models.Person person)
{
try
{
if (person.BDay < DateTime.Now.AddYears(-120))
{
ModelState.AddModelError("BDay", "Значение даты не может быть меньше текущей, больше чем на 120 лет");
}
if (ModelState.IsValid)
{
context.Persons.Add(person);
context.SaveChanges();
return RedirectToAction("Index", context.Persons.AsEnumerable());
}
return View(person);
}
catch
{
return View("Index", context.Persons.AsEnumerable());
}
}
[HttpGet]
public ActionResult Update(string phone)
{
Models.Person person = context.Persons.Find(phone);
return View("Update", person);
}
[HttpPost]
public ActionResult Update(Models.Person person)
{
try
{
if (person.BDay < DateTime.Now.AddYears(-120))
{
ModelState.AddModelError("BDay", "Значение даты не может быть меньше текущей, больше чем на 120 лет");
}
if (ModelState.IsValid)
{
context.Entry(person).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index", context.Persons.AsEnumerable());
}
return View(person);
}
catch
{
return View("Index", context.Persons.AsEnumerable());
}
}
[HttpGet]
public ActionResult Delete(string phone)
{
try
{
Models.Person person = context.Persons.Find(phone);
if (person != null)
{
context.Persons.Remove(person);
}
context.SaveChanges();
return RedirectToAction("Index", context.Persons.AsEnumerable());
}
catch
{
return View("Index", context.Persons.AsEnumerable());
}
}
}
}
|
7e130f5ec1d5491355ab97d2235fec1dad0c5314
|
C#
|
spolinaa/intersection
|
/CalculatorLibrary/calculator.cs
| 3.546875
| 4
|
/* Library for calculating an intersection of a circle and a segment
by Sokolova Polina */
using System;
namespace geometry
{
public class Calculator
{
private static double sqr(int x)
{
return Math.Pow(x, 2);
}
public static bool intersection(int x0, int y0, int r, int x1, int y1, int x2, int y2)
{
if ((x1 == x2) && (y1 == y2))
{
throw new System.ArgumentException("Points must be different");
}
double a = sqr(x2 - x1) + sqr(y2 - y1);
double b = 2 * ((x2 - x1) * (x1 - x0) + (y2 - y1) * (y1 - y0));
double c = sqr(x1 - x0) + sqr(y1 - y0) - sqr(r);
double D = Math.Pow(b, 2.0) - 4 * a * c;
if (D < 0) { return false; }
double t1 = (-b + Math.Sqrt(D)) / (2 * a);
double t2 = (-b - Math.Sqrt(D)) / (2 * a);
if (((t1 < 0) || (t1 > 1)) && ((t2 < 0) || (t2 > 1))) { return false; }
return true;
}
}
}
|
f252a02e3af82535502d0e36dae27e5c8119c631
|
C#
|
ThatGuyRussell/Team-Alight
|
/Wolf Game/PlayerMovement.cs
| 2.546875
| 3
|
using UnityEngine;
using UnitySampleAssets.CrossPlatformInput;
namespace CompleteProject
{
public class PlayerMovement : MonoBehaviour
{
public float speed = 0.2f; // The speed that the player will move at.
Vector3 movement; // The vector to store the direction of the player's movement.
Rigidbody playerRigidbody; // Reference to the player's rigidbody.
int floorMask; // A layer mask so that a ray can be cast just at gameobjects on the floor layer.
float camRayLength = 100f; // The length of the ray from the camera into the scene.
void Awake ()
{
floorMask = LayerMask.GetMask ("Floor");
// Set up references.
playerRigidbody = GetComponent <Rigidbody> ();
}
void FixedUpdate ()
{
// Turn the player to face the mouse cursor and move towards me.
Move ();
}
void Move ()
{
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
//transform.Rotate(Vector3.up * h * 1.6f);
transform.Translate (Vector3.forward * v * speed, Space.World);
transform.Translate (Vector3.right * h * speed, Space.World);
Vector3 testScale = transform.localScale;
if (h > 0) {
testScale.x = -1;
transform.eulerAngles = new Vector3(0, 270, 0);
} else if (h < 0){
testScale.x = 1;
transform.eulerAngles = new Vector3(0, 90, 0);
}
transform.localScale = testScale;
}
}
}
|
44be77fc429d41e4061107eca2fcdfdb4eeafe0c
|
C#
|
stasadev/SimpleCiphers
|
/SimpleCiphers/Models/SloganCipher.cs
| 3.171875
| 3
|
using System.Linq;
namespace SimpleCiphers.Models
{
public class SloganCipher : ICipher
{
public string Encrypt(string text, string key, string abc) => Crypt(text, key, abc, true);
public string Decrypt(string text, string key, string abc) => Crypt(text, key, abc, false);
public string[,] GetEncryptedAlphabet(string text, string key, string abc)
{
Checker.KeyNull(key);
Checker.KeyContain(key, abc);
var encAbc = key.Union(abc).Select(x => $"{x}").ToArray();
return ArrayOperations.Turn1DTo2D(encAbc);
}
public string[] GetRowAlphabet(string key, string abc) => null;
public string[] GetColAlphabet(string key, string abc) => abc.Select(x => $"{x}").ToArray();
public string Crypt(string text, string key, string abc, bool encrypt)
{
Checker.KeyNull(key);
Checker.KeyContain(key, abc);
Checker.TextNull(text);
Checker.TextContain(text, abc);
var encAbc = string.Join("", key.Union(abc));
var result = "";
foreach (var ch in text)
{
for (var j = 0; j < abc.Length; j++)
{
if (encrypt)
{
if (ch == abc[j])
{
result += encAbc[j];
break;
}
}
else
{
if (ch == encAbc[j])
{
result += abc[j];
break;
}
}
}
}
return result;
}
}
}
|
459b0ac676aea95c3d9ebd1ec1ffa03ed2e9ea45
|
C#
|
shendongnian/download4
|
/code1/108050-20373840-52879203-2.cs
| 2.890625
| 3
|
public static int getCheckedRadioButton(Control c)
{
Control.ControlCollection cc = c.Controls;
for (int i = 0; i < cc.Count; i++)
{
RadioButton rb = cc[i] as RadioButton;
if (rb.Checked)
{
return i;
}
}
return 0;
}
|
1a449444279bc036855c1fcac634051d3ced5f81
|
C#
|
pwflynn655/sharedclustering
|
/Models/EndogamyProber.cs
| 2.578125
| 3
|
using AncestryDnaClustering.ViewModels;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace AncestryDnaClustering.Models
{
internal class EndogamyProber
{
private readonly AncestryMatchesRetriever _matchesRetriever;
public EndogamyProber(AncestryMatchesRetriever matchesRetriever)
{
_matchesRetriever = matchesRetriever;
}
public async Task ProbeAsync(string name, string guid, int matchIndexTarget, int numMatchesToTest, Throttle throttle, ProgressData progressData)
{
var shiftKeyDown = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
var pageNum = matchIndexTarget / _matchesRetriever.MatchesPerPage + 1;
var matches = await _matchesRetriever.GetMatchesPageAsync(guid, pageNum, false, throttle, progressData);
var icwTasks = matches
.Take(numMatchesToTest)
.Select(match => _matchesRetriever.GetRawMatchesInCommonAsync(guid, match.TestGuid, 1, 0, throttle))
.ToList();
var icws = await Task.WhenAll(icwTasks);
var orderedIcwCounts = icws.Select(l => l.Count).OrderBy(c => c).ToList();
var medianIcwCount = orderedIcwCounts.Skip(orderedIcwCounts.Count() / 2).FirstOrDefault();
string primaryMessage;
string secondaryMessage;
if (medianIcwCount <= 20)
{
// Median 0-20: No endogamy
primaryMessage = $"The test results for {name} do not show any significant endogamy. ";
secondaryMessage = "Clustering should work well.";
}
else if (medianIcwCount < _matchesRetriever.MatchesPerPage * 3 / 4)
{
// Median 20-150: Some endogamy but probably not all lines
primaryMessage = $"The test results for {name} may show some endogamy in some ancestral lines. ";
secondaryMessage = "Clustering should work well for the ancestral lines without endogamy, but may be difficult to interpret for others.";
}
else
{
// Median 150-200: Heavy endogamy
primaryMessage = $"The test results for {name} show significant endogamy. ";
secondaryMessage = "Clustering by itself may not work well. Considering using the 'Endogamy special' downloading option combined with Similarity to find more distant matches.";
}
if (shiftKeyDown)
{
secondaryMessage = secondaryMessage + Environment.NewLine + Environment.NewLine + string.Join(", ", orderedIcwCounts);
}
MessageBox.Show(primaryMessage + Environment.NewLine + Environment.NewLine + secondaryMessage,
"Endogamy test", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
|
c9464d8852ea41adc5c6bd2d51558713d1079318
|
C#
|
Keydol/Lab1
|
/Program.cs
| 3.515625
| 4
|
using System;
namespace Lab1
{
class Program
{
delegate double function(double x);
static double f1(double x)
{
return Math.Pow(x, 3) + 3 * Math.Pow(x, 2) - 24 * x + 1;
}
static double f2(double x)
{
return Math.Tan(1.2 * x) - 2 + 3 * x;
}
static double derivativeFunction(double x)
{
return 3 * Math.Pow(x, 2) + 6 * x - 24;
}
static double derivativeTranscendentalFunction(double x)
{
return 3 +(1.2 / Math.Pow(Math.Cos(1.2 * x),2));
}
static double secondDerivativeFunction(double x)
{
return 6 * x + 6;
}
static double secondDerivativeTranscendentalFunction(double x)
{
return 2.88 * (Math.Sin(1.2 * x)/Math.Cos(1.2 * x));
}
static void Main(string[] args)
{
double x1;
double x2;
double E = 1e-3; //точність
string arithmeticEquation = "x^3 + 3x^2 - 24x + 1 = 0";
string transcendentalEquation = "tg(1,2x) - 2 + 3x = 0";
Console.WriteLine("======== Алгебраїчне рiвняння x^3 + 3x^2 - 24x + 1 ========");
x1 = 3;
x2 = 4;
Console.WriteLine($"======== Уточнення коренiв на вiдрiзку [{x1} ; {x2}] ========\n");
methodNewton(x1, x2, E, f1, derivativeFunction, secondDerivativeFunction,arithmeticEquation);
methodIterracii(x1, x2, E, f1, derivativeFunction);
methodDyhotomii(x1, x2, E, f1);
methodHord(x1, x2, E, f1);
methodKombinovanyi(x1, x2, E, f1, derivativeFunction);
Console.WriteLine("\n\n======== Трансцендентне рiвняння tg(1,2x) - 2 + 3x ========");
x1 = 0;
x2 = 1;
Console.WriteLine($"======== Уточнення коренiв на вiдрiзку [{x1} ; {x2}] ========\n");
methodNewton(x1, x2,E, f2, derivativeTranscendentalFunction, secondDerivativeTranscendentalFunction,transcendentalEquation);
methodIterracii(x1, x2, E, f2, derivativeTranscendentalFunction);
methodDyhotomii(x1, x2, E, f2);
methodHord(x1, x2, E, f2);
methodKombinovanyi(x1, x2, E, f2, derivativeTranscendentalFunction);
Console.ReadLine();
}
static void methodKombinovanyi(double x1, double x2, double E, function f, function derivativeFunction)
{
Console.WriteLine("\t== Комбiнований метод ==\n");
double a = x1;
double b = x2;
double x = 0;
int i = 0;
while(Math.Abs(a - b) > E)
{
a -= f(a) * (a - b) / (f(a) - f(b));
b = b - f(b) / derivativeFunction(b);
x = (a + b) / 2;
i++;
Console.WriteLine("Поточна iтерацiя {0} = {1}", i, x);
}
Console.WriteLine($" x = {Math.Round(x, 3)}");
Console.WriteLine($" Кiлькiсть iтерацiй = {i}\n");
}
static void methodDyhotomii(double x1, double x2, double E, function f)
{
Console.WriteLine("\t== Метод дихотомiї ==\n");
int i = 0;
double x = x1;
double xLast = x;
double xTo = x2;
double dx = double.MaxValue;
while (Math.Abs(dx) > 2*E)
{
i++;
x = (xTo + xLast) / 2;
if (f(xTo) * f(x) < 0) xLast = x;
else if (f(xTo) * f(x) == 0) break;
else xTo = x;
dx = xTo - xLast;
Console.WriteLine("Поточна iтерацiя {0} = {1}", i, x);
}
Console.WriteLine($" x = {Math.Round(x, 3)}");
Console.WriteLine($" Кiлькiсть iтерацiй = {i}\n");
}
static void methodHord(double x1, double x2, double E, function f)
{
Console.WriteLine("\t== Метод хорд ==\n");
int i = 0;
double x_next = x1;
double x_curr = x2;
double x_last;
double dx = double.MaxValue;
while (Math.Abs(dx) > E)
{
i++;
x_last = x_curr;
x_curr = x_next;
x_next -= f(x_curr) * (x_curr - x_last) / (f(x_curr) - f(x_last));
dx = x_next - x_curr;
Console.WriteLine("Поточна iтерацiя {0} = {1}", i, x_next);
}
Console.WriteLine($" x = {Math.Round(x_next, 3)}");
Console.WriteLine($" Кiлькiсть iтерацiй = {i}\n");
}
static void methodNewton(double x1, double x2, double E, function functionTask,function derivativeFunction, function secondDerivativeFunction,String equation)
{
Console.WriteLine("\t== Метод Ньютона (дотичних) ==\n");
int iterator = 1;
double initValueX;
double iValueX;
double a = x1;
double b = x2;
double e = E;
if (functionTask(a) * functionTask(b) > 0) // Якщо знаки функції на краях відрізків однакові, то функція коренів немає
{
Console.WriteLine("На даному iнтервалi [{0};{1}] рiвняння {2} немає розв'язкiв",a,b,equation);
}
else
{
initValueX = functionTask(a) * secondDerivativeFunction(a) > 0 ? a : b; // Визначаємо нерухомий кінець та задаємо початкове значення
iValueX = initValueX - functionTask(initValueX) / derivativeFunction(initValueX); // Визначаємо перше наближення
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, iValueX);
while (Math.Abs(initValueX - iValueX) > e) // Поки різниця по модулю між коренями не стане меншою за точність e
{
iterator++;
initValueX = iValueX;
iValueX = initValueX - functionTask(initValueX) / derivativeFunction(initValueX);
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, iValueX);
}
Console.WriteLine($" x = {Math.Round(iValueX, 3)}");
Console.WriteLine($" Кiлькiсть iтерацiй = {iterator}\n");
}
}
static void methodIterracii(double x1, double x2, double E, function f1, function derivateFunction)
{
Console.WriteLine("\t== Метод простої iтерацiї ==\n");
double min = derivateFunction(x1);
double max = derivateFunction(x2);
double lmb;
double X0 = x1;
int iterator=1;
if (min != 0)
{
lmb = 2 / (min + max);
}
else lmb = 1 / max;
double q = 1 - lmb;
double X = Phi(X0, lmb,f1);
if (q <= 0.5)
{
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, X);
while (Math.Abs(X - X0) > ((1 - q) / q) * E)
{
iterator++;
X0 = X;
X = Phi(X0, lmb,f1);
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, X);
}
}
else
{
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, X);
if (q > 0.5 && q < 1)
{
while (Math.Abs(X - X0) > E)
{
iterator++;
X0 = X;
X = Phi(X0, lmb, f1);
Console.WriteLine("Поточна iтерацiя {0} = {1}", iterator, X);
}
}
}
Console.WriteLine($" x = {Math.Round(X, 3)}");
Console.WriteLine($" Кiлькiсть iтерацiй = {iterator}\n");
}
static double Phi(double x, double lmb, function f)
{
return x - lmb * f(x);
}
}
}
|
dc72a16ecb8dcd242319a04bf965fdad7de01e38
|
C#
|
sgw-dev/neuromancer
|
/Neuromancer/Assets/Script/Controllers/HexTileController.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexTileController : MonoBehaviour
{
public HexTile hexPrefab;
[SerializeField] HexTile head;
[SerializeField] int amountTiles;
[SerializeField] float cellSize;
float halfX;
float halfY;
Vector3[] adjacentHexes;
public void Awake()
{
CreateHexPositions();
GenerateTiles();
}
public HexTile FindHex(Vector3 position)
{
return FindHex(position, head);
}
public HexTile FindHex(Vector3 pos, HexTile ht)
{
HexTile previous = ht;
HexTile rtn = FindNextHex(pos, ht);
while (rtn != previous)
{
previous = rtn;
rtn = FindNextHex(pos, rtn);
}
return rtn;
}
HexTile FindNextHex(Vector3 point, HexTile ht)
{
HexTile rtn = ht;
float minMag = (ht.Position - point).sqrMagnitude;
for (int i = 0; i < 6; i++)
{
HexTile temp = ht.nexts[i];
if (temp == null)
continue;
float mag = (temp.Position - point).sqrMagnitude;
if (mag < minMag)
{
rtn = temp;
minMag = mag;
}
}
return rtn;
}
public int FindHexDistance(Vector3 a, Vector3 b)
{
float x = Mathf.Abs(b.x - a.x);
float y = Mathf.Abs(b.y - a.y);
int hexCount = 0;
while (y >= halfY)
{
y -= halfY;
x -= halfX;
hexCount++;
}
while (x >= cellSize)
{
x -= cellSize;
hexCount++;
}
return hexCount;
}
public List<HexTile> FindRadius(HexTile hexTile, int radius, bool checkObstacle = false)
{
List<HexTile> list = new List<HexTile>();
for (int i = 0; i < 6; i++)
{
FindRadius(hexTile.nexts[i], ref list, radius, i, checkObstacle);
}
return list;
}
void FindRadius(HexTile current, ref List<HexTile> list, int radius, int dir, bool checkObstacle)
{
if(current == null || radius <= 0)
{
return;
}
list.Add(current);
if (checkObstacle && (current.IsObstacle || current.HoldingObject != null))
{
FindRadius(current.nexts[dir], ref list, radius - 2, dir, checkObstacle);
}
else
{
FindRadius(current.nexts[dir], ref list, radius - 1, dir, checkObstacle);
}
int x = (dir + 1) % 6;
FindRadius(current.nexts[x], ref list, radius - 1, x, checkObstacle);
}
void GenerateTiles()
{
Queue<HexTile> queue = new Queue<HexTile>();
HexTile currentHT = head;
int max = amountTiles - 1;
while (max > 0)
{
for (int i = 0; i < currentHT.nexts.Length && max > 0; i++)
{
if (currentHT.nexts[i] == null)
{
queue.Enqueue(AddHexTile(currentHT, i));
max--;
}
}
currentHT = queue.Dequeue();
}
}
HexTile AddHexTile(HexTile ht, int side)
{
HexTile newHT = Instantiate(hexPrefab, transform);
newHT.Position = ht.Position + adjacentHexes[side];
ht.InsertNext(side, newHT);
int add = (side + 1) % 6;
int minus = side - 1;
if (minus == -1)
minus = 5;
if (ht.nexts[add] != null)
ht.nexts[add].InsertNext(minus, newHT);
if (ht.nexts[minus] != null)
ht.nexts[minus].InsertNext(add, newHT);
return newHT;
}
public float CellSize
{
get { return CellSize; }
}
public float HalfX
{
get { return halfX; }
}
public float HalfY
{
get { return halfY; }
}
public Vector3[] CloseHexes
{
get { return adjacentHexes; }
}
public HexTile Head
{
get { return head; }
set { head = value; }
}
void CreateHexPositions()
{
halfX = cellSize / 2;
halfY = cellSize * .75f;
adjacentHexes = new Vector3[6];
adjacentHexes[0] = new Vector3(cellSize, 0);
adjacentHexes[1] = new Vector3(halfX, halfY);
adjacentHexes[2] = new Vector3(-halfX, halfY);
adjacentHexes[3] = new Vector3(-cellSize, 0);
adjacentHexes[4] = new Vector3(-halfX, -halfY);
adjacentHexes[5] = new Vector3(halfX, -halfY);
}
}
|
f053fedb70e83926e5285d5a844f39fa2b787ef2
|
C#
|
shendongnian/download4
|
/code8/1489755-40889456-132764062-2.cs
| 3.5625
| 4
|
public static void Main(string[] args)
{
string str = "Test1,Test2,Test3";
string test1 = MyFunction("Test1", "Test2", "Test3");
string test2 = MyFunction(str.Split(','));
}
public static string MyFunction(params string[] parameters)
{
StringBuilder sb = new StringBuilder();
foreach(var item in parameters)
{
sb.AppendLine(item);
}
return sb.ToString();
}
|
a86faa2ce7a7302f29218a322e392edafa04bfe2
|
C#
|
MarkwardtMarcello/Asp.Net---AULA
|
/Aula1406_Views_Controllers/Aula1406_Views_Controllers/Controllers/CategoriasController.cs
| 2.71875
| 3
|
using Aula1406_Views_Controllers.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace Aula1406_Views_Controllers.Controllers
{
public class CategoriasController : Controller
{
// GET: Categorias(carregamento da pagina)
public ActionResult Index()
{
List<Categoria> categorias = new List<Categoria>();
//Retornar a lista de objetos cadastrados
return View(categorias);
}
public ActionResult Create() //GET - carregar pagina
{
return View();
}
[HttpPost] // pag carregada
public ActionResult Create(Categoria categoria)
{
if (ModelState.IsValid)
{
//objeto é valido, podendo ir para o banco.
}
return View(categoria);
}
//get editar
public ActionResult Edit(int? id)
{
//carregar a tela
//verificar se veio a ID, badresquest mal feita
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
//erro 400.0
}
//pesquisa no banco, o objeto a editar
Categoria categoria = new Categoria()
{
CategoriaID = id.Value,
Nome = "Carros",
Descricao = "Veloz",
Ativo = true
};
//se nao foi encontrado no banco
if (categoria == null)
{
return HttpNotFound();
//erro 404
}
return View(categoria);
}
//Post
public ActionResult Edit(Categoria categoria)
{
if (ModelState.IsValid)
{
//Receber e guardar!
try
{
//update
//redirecionar
}
catch(Exception ex)
{
throw ex;
}
}
return View(categoria);
}
//get excluir
public ActionResult Delete(int ? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Categoria categoria = new Categoria()
{
CategoriaID = id.Value,
Nome = "Motos",
Descricao = "1000cc",
Ativo = true
};
if (categoria == null)
{
return HttpNotFound();
}
return View(categoria);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
//pesquisar obj por id
// alterar status do obj para deleted ou ativo para false
TempData["Mensagem "] = "Categoria excluida !";
return RedirectToAction("Index");
}
}
}
|
a212ca2e6d676aa567e28426eafb540ac5769e4b
|
C#
|
Angel94Jim/Interaccion-Humano-Computadora-1220194
|
/Practicas HIC/Assets/Scrips/Inventory.cs
| 3.09375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
static protected Inventory _instance;
static public Inventory Instance { get {return _instance;}}
public delegate void OnChange();
public OnChange onChange;
public List<Item> items = new List<Item>();
public int space = 8;
void Awake()
{
_instance = this;
}
public void Add(Item item)
{
if (items.Count < space)
{
items.Add(item);
if (onChange != null)
{
onChange.Invoke();
}
}
else
{
Debug.LogWarning("No hay más espacio en inventario");
}
}
public void Remove(Item item)
{
if (items.Contains(item))
{
items.Remove(item);
if (onChange != null)
{
onChange.Invoke();
}
}
else
{
Debug.LogWarning("Item no se encontró en inventario");
}
}
}
|
31f7d034ae7e8b2205ff4e6a05d0941970b88700
|
C#
|
hj0807/HJ-Project
|
/Unity_Pattern/Assets/Scripts/Observer_Pattern/Ex2/WeatherData.cs
| 3.171875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ObserverPattern.ex2
{
public class WeatherData : ISubject
{
private List<IObserver> observerList;
private float temperature;
private float humidity;
private float pressure;
public WeatherData()
{
observerList = new List<IObserver>();
}
public void RegisterObserver(IObserver observer)
{
observerList.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
observerList.Remove(observer);
}
public void NotifyObservers()
{
for(int i=0; i<observerList.Count; i++)
{
observerList[i].Update(temperature, humidity, pressure);
}
}
public void ChangeMeasurements()
{
NotifyObservers();
}
public void SetMeasurements(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
}
public float GetTemperature()
{
return temperature;
}
public float GetHumidity()
{
return humidity;
}
public float GetPressure()
{
return pressure;
}
}
}
|
1594e5b061c35261d959edf18f457720f2990078
|
C#
|
KSU-CIS300-Spring-2019/lab-assignment-22-tylertoad88
|
/Ksu.Cis300.TrieLibrary/TrieWithNoChildren.cs
| 3.578125
| 4
|
/* Filename: TrieWithNoChildren.cs
* Author: Tyler Braddock
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ksu.Cis300.TrieLibrary
{
/// <summary>
/// Public method TrieWithNoChildren
/// </summary>
public class TrieWithNoChildren : ITrie
{
/// <summary>
/// Private field telling whether the string cotains the empty string.
/// </summary>
private bool _containsMT = false;
/// <summary>
/// A public method to Add a given string s to the Trie.
/// </summary>
/// <param name="s">string to be added</param>
/// <returns>returns the trie with the string added to it</returns>
public ITrie Add(string s)
{
if (s == "")
{
_containsMT = true;
return this;
}
else
{
return new TrieWithOneChild(s, _containsMT);
}
}
/// <summary>
/// A public method to tell if trie contains the given string s.
/// </summary>
/// <param name="s">string to be found in trie</param>
/// <returns></returns>
public bool Contains(string s)
{
if (s == "")
{
return _containsMT;
}
else
{
return false;
}
}
}
}
|
c4ed28e268a546aa4d5177fb24fce211ec1180a3
|
C#
|
JL-INK/LabsForKolos
|
/Lab1/Lab1/Tasks/Task3.cs
| 3.328125
| 3
|
using System;
using System.Text.RegularExpressions;
namespace Lab1.Tasks
{
class Task3
{
public void Task()
{
var Program = new Program();
Console.Clear();
Console.WriteLine("Введите текст");
string text = Console.ReadLine();
if (!Regex.IsMatch(text, @"\P{IsCyrillic}"))
{
Console.WriteLine("Текст введен на русском языке!");
}
else if(!Regex.IsMatch(text, "[a - zA - Z]"))
{
Console.WriteLine("Текст введен на английском языке!");
}
else
{
Console.WriteLine("Не удалось определить язык!");
}
Console.ReadKey();
Program.Retry();
}
}
}
|
3c3913040eb2085a1280cd30f319c156fc688c54
|
C#
|
dobrosol/TechUniverseTestShop
|
/OnlineShop/Domain/Concrete/Cart.cs
| 3.4375
| 3
|
using System.Collections.Generic;
using System.Linq;
using Domain.Concrete.ProductEntities;
namespace Domain.Concrete
{
public class Cart
{
List<CartLine> lines = new List<CartLine>();
public void AddItem(Product product, int quantity)
{
CartLine line = lines.Where(l => l.Product.Name == product.Name).FirstOrDefault();
if (line == null)
lines.Add(new CartLine()
{
Product = product,
Quantity = quantity
});
else
line.Quantity += quantity;
}
public void RemoveLine(string name)
{
lines.RemoveAll(l => l.Product.Name == name);
}
public decimal CalcTotalPrice()
{
return lines.Sum(l => l.Product.Price * l.Quantity);
}
public decimal CalcTotalCount()
{
return lines.Sum(l => l.Quantity);
}
public void Clear()
{
lines.Clear();
}
public IEnumerable<CartLine> Lines
{
get { return lines; }
}
}
public class CartLine
{
public Product Product { get; set; }
public int Quantity { get; set; }
}
}
|
bbe06c9c2e487d226458d4b863eac957ff8b6c68
|
C#
|
PirateX0/MultipleThread
|
/信号/Program.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 信号
{
class Program
{
static void Main(string[] args)
{
//ManualResetEvent mre = new ManualResetEvent(false);
////构造函数false表示“初始状态为关门”,设置为true则初始化为开门状态
//Thread t1 = new Thread(() => {
// Console.WriteLine("wait for opening the door");
// mre.WaitOne();
// Console.WriteLine("run");
//});
//t1.Start();
//Console.WriteLine("press any key to open the door");
//Console.ReadKey();
//mre.Set();//开门
//Console.ReadKey();
//ManualResetEvent mre = new ManualResetEvent(false);
////false表示“初始状态为关门”
//Thread t1 = new Thread(() => {
// Console.WriteLine("wait for opening the door");
// if (mre.WaitOne(5000))
// {
// Console.WriteLine("run");
// }
// else
// {
// Console.WriteLine("5 seconds passed. I will leave.");
// }
//});
//t1.Start();
//Console.WriteLine("press any key to open the door");
//Console.ReadKey();
//mre.Set();//开门
//Console.ReadKey();
//ManualResetEvent mre = new ManualResetEvent(false);
////false表示“初始状态为关门”
//Thread t1 = new Thread(() => {
// while (true)
// {
// Console.WriteLine("wait for opening the door");
// mre.WaitOne();
// Console.WriteLine("run");
// }
//});
//t1.Start();
//Console.WriteLine("press any key to open the door");
//Console.ReadKey();
//mre.Set();//开门
//Console.ReadKey();
//mre.Reset();//关门
//Console.ReadKey();
AutoResetEvent are = new AutoResetEvent(false);
Thread t1 = new Thread(() => {
while (true)
{
Console.WriteLine("wait for opening the door");
are.WaitOne();
Console.WriteLine("run");
}
});
t1.Start();
Console.WriteLine("press any key to open the door");
Console.ReadKey();
are.Set();//开门
Console.WriteLine("press any key to open the door");
Console.ReadKey();
are.Set();
Console.WriteLine("press any key to open the door");
Console.ReadKey();
are.Set();
Console.ReadKey();
}
}
}
|
a2ceddab8d20e0b80655b55b10773f2c80a3ff5a
|
C#
|
marekpraski/interProcessCommunication
|
/ICPEvents/IPCClient.cs
| 3.140625
| 3
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace IPC
{
/// <summary>
/// Represents the client side application.
/// </summary>
internal class IPCClient
{
private Socket clientSocket;
private int port;
internal IPCClient(int port)
{
this.port = port;
}
internal bool setupClient()
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Change IPAddress.Loopback to a remote IP to connect to a remote host.
clientSocket.Connect(IPAddress.Loopback, port);
return true;
}
catch (SocketException ex)
{
return false;
}
}
internal bool sendMessage(string message)
{
try
{
clientSocket.Send(Encoding.ASCII.GetBytes(message));
return true;
}
catch
{
return false;
}
}
internal void closeClient()
{
clientSocket.Close();
Environment.Exit(0);
}
}
}
|
68eb6b4835280f02cd4946ce4f2e5b353eb6e93b
|
C#
|
Ken884/education
|
/C#/quiz057/VOCALOID_DB/Dao.cs
| 2.90625
| 3
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DBAccess
{
class Dao
{
// 接続文字列
private const string ConnectStatement =
"userid=root; password=password; database=vocaloid_songs; Host=localhost";
// 可変長WHERE句を作りやすくするフレーズ
private const string WhereTrueStatement = "where 1=1 ";
/* 条件に合う曲の一覧を返す */
// MODIFY BELOW CODE / CHECK
public DataTable SearchSongs(string song, int? vocaloidId, string producer, string publishYear)
{
// SQL検索クエリ
string searchSongQuery =
"SELECT s.name AS 曲名, GROUP_CONCAT(v.name separator ', ') AS VOCALOID, p.name AS 作曲者, s.publish_at AS 発表日, s.views AS 再生数 "
+ "FROM vocaloid_songs.songs AS s " +
"LEFT JOIN vocaloid_songs.song_vocaloid AS sv ON sv.song_id = s.id " +
"LEFT JOIN vocaloid_songs.vocaloids AS v ON v.id = sv.vocaloid_id " +
"LEFT JOIN vocaloid_songs.producers AS p ON p.id = s.producer_id";
string searchSongQueryGroupBy = "GROUP BY s.name, s.publish_at";
// データを格納するテーブル作成
DataTable dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
// SQL文を作成
StringBuilder querySb = new StringBuilder();
querySb.Append(" " + searchSongQuery);
querySb.Append(" " + WhereTrueStatement);
// SQL文のWhere句を作成
StringBuilder where = new StringBuilder();
if (!string.IsNullOrWhiteSpace(song))
{
AppendWhere(where, "s.name like @SONG");
}
if (vocaloidId != null)
{
AppendWhere(where, "s.id IN (SELECT song_id FROM vocaloid_songs.song_vocaloid WHERE vocaloid_id = @VOCALOID)");
}
if (!string.IsNullOrWhiteSpace(producer))
{
AppendWhere(where, "p.name = @PRODUCER");
}
if (!string.IsNullOrWhiteSpace(publishYear))
{
AppendWhere(where, "s.publish_at >= @PUBLISH_FROM AND publish_at <= @PUBLISH_END");
}
querySb.Append(where.ToString());
// GROUP BY句を追加
querySb.Append(searchSongQueryGroupBy);
// パラメタ置換
var songSearchCmd = new MySqlCommand(querySb.ToString(), conn);
songSearchCmd.Parameters.Add(new MySqlParameter("@SONG", "%" + song + "%"));
songSearchCmd.Parameters.Add(new MySqlParameter("@VOCALOID", vocaloidId));
songSearchCmd.Parameters.Add(new MySqlParameter("@PRODUCER", producer));
if (!string.IsNullOrWhiteSpace(publishYear))
{
songSearchCmd.Parameters.Add(new MySqlParameter("@PUBLISH_FROM", new DateTime(int.Parse(publishYear), 1, 1)));
songSearchCmd.Parameters.Add(new MySqlParameter("@PUBLISH_END", new DateTime(int.Parse(publishYear), 12, 31)));
}
// SQL文と接続情報を指定し、データアダプタを作成
MySqlDataAdapter da = new MySqlDataAdapter(songSearchCmd);
// 検索を実行しDataTableに格納
da.Fill(dt);
}
return dt;
}
/* VOCALOIDリストを取得する */
public DataTable FetchVocaloids()
{
// SQL文を作成
string fetchVocaloidsQuery = "SELECT id, name FROM vocaloid_songs.vocaloids";
// データを格納するDataTableを作成
DataTable dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
// SQL文と接続情報を指定し、データアダプタを作成
MySqlDataAdapter da = new MySqlDataAdapter(fetchVocaloidsQuery, conn);
// 検索を実行しDataTableに格納
da.Fill(dt);
}
return dt;
}
/* 曲を追加する。*/
public void CreateSong(string song, string producer, IEnumerable<int> vocaloids, string views, DateTime? publishAt)
{
// 再生数null処理
/* INSERT YOUR CODE /CHECK*/
if(views == "")
{
views = null;
}
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
// 作曲者IDを取得
int producerId = FindProducerIdAndIfNeededCreateProducer(producer);
// 曲IDの最大値+1を取得
int nextSongId = FindMaxSongId() + 1;
// 曲を挿入するSQL文を作成
string insertSongQuery = "INSERT INTO songs (id, name, producer_id, publish_at, views) " +
"VALUES (@ID, @NAME, @PRODUCER_ID, @PUBLISHAT, @VIEWS)";
// パラメタ置換
var insertSongCmd = new MySqlCommand(insertSongQuery, conn);
/* INSERT YOUR CODE /CHECK*/
insertSongCmd.Parameters.Add(new MySqlParameter("@ID", nextSongId));
insertSongCmd.Parameters.Add(new MySqlParameter("@NAME", song));
insertSongCmd.Parameters.Add(new MySqlParameter("@PRODUCER_ID", producerId));
insertSongCmd.Parameters.Add(new MySqlParameter("@PUBLISHAT", publishAt));
insertSongCmd.Parameters.Add(new MySqlParameter("@VIEWS", views));
// SQL実行
insertSongCmd.ExecuteNonQuery();
// 曲-VOCALOID中間テーブルにデータを挿入する
// SQL文を作成
string insertSongVocaloidQuery =
"INSERT INTO song_vocaloid (song_id, vocaloid_id) " +
"VALUES(@SONG_ID, @VOCALOID_ID)";
// 受け取ったVOCALOIDIDそれぞれに対して処理を行う
/* INSERT YOUR CODE */
foreach (var vocaloidId in vocaloids)
{
var insertSongVocaloidCmd = new MySqlCommand(insertSongVocaloidQuery, conn);
insertSongVocaloidCmd.Parameters.Add(new MySqlParameter("@SONG_ID", nextSongId));
insertSongVocaloidCmd.Parameters.Add(new MySqlParameter("@VOCALOID_ID", vocaloidId));
insertSongVocaloidCmd.ExecuteNonQuery();
}
MessageBox.Show("登録しました");
}
}
/* 作曲者IDを返す。
* 存在しなければ作曲者を追加したうえで、その作曲者IDを返す。 */
private int FindProducerIdAndIfNeededCreateProducer(string producer)
{
// SQL文作成
string searchProducerQuery = "SELECT id FROM producers WHERE name = @PRODUCER";
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
// パラメタ置換
var cmd = new MySqlCommand(searchProducerQuery, conn);
cmd.Parameters.Add(new MySqlParameter("@PRODUCER", producer));
// SQL実行(なければnull)
int? producerId = (int?)cmd.ExecuteScalar();
// 作曲者IDが存在すれば、それを返す
if (producerId != null)
{
return (int)producerId;
}
// もしも作曲者が存在しなかった場合は、作曲者を追加しそのIDを返す
else
{
// INSERT用SQL文作成
/* INSERT YOUR CODE /DONE*/
string insertProducerQuery = "INSERT INTO producers (id, name) VALUES (@ID, @NAME)";
// 挿入するべき作曲者IDを取得
/* INSERT YOUR CODE /DONE*/
int nextProducerId = FindMaxProducerId() + 1;
// パラメタ置換
/* INSERT YOUR CODE /DONE*/
var insertProducerCmd = new MySqlCommand(insertProducerQuery, conn);
insertProducerCmd.Parameters.Add(new MySqlParameter("@ID", nextProducerId));
insertProducerCmd.Parameters.Add(new MySqlParameter("@NAME", producer));
// SQL実行
cmd.ExecuteNonQuery();
// 作曲者IDを返す
/* MODIFY BELOW CODE /DONE*/
return nextProducerId;
}
}
}
/* 曲IDの最大値を取得する */
private int FindMaxSongId()
{
// SQL文作成
string searchMaxSongIdQuery = "SELECT MAX(id) FROM songs ";
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
var searchMaxSongIdcmd = new MySqlCommand(searchMaxSongIdQuery, conn);
// SQL実行
return (int)searchMaxSongIdcmd.ExecuteScalar();
}
}
/* 作曲者IDの最大値を取得する */
private int FindMaxProducerId()
{
/* INSERT YOUR CODE AND MODIFY BELOW CODE /DONE*/
string searchMaxProducerIdQuery = "SELECT MAX(id) FROM producers ";
using (MySqlConnection conn = new MySqlConnection(ConnectStatement))
{
conn.Open();
var searchMaxProducerIdcmd = new MySqlCommand(searchMaxProducerIdQuery, conn);
// SQL実行
return (int)searchMaxProducerIdcmd.ExecuteScalar();
}
}
/* 可変長WHERE句を生成する。
* 渡されたStringBuilderにstringを連結する */
public void AppendWhere(StringBuilder sb, string str)
{
sb.Append(" and " + str + " ");
}
}
}
|
374e53046d548346df0c23882b91ba2f0e9a5b08
|
C#
|
RobolabGs2/computer_graphics_labs
|
/Lab04/Tools/PolygonsDrawing.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Lab04.Tools
{
class PolygonsDrawing : ITool
{
public Bitmap image => Properties.Resources.Polygon;
Context context;
Polygon p;
bool onLine;
public void Init(Context context)
{
this.context = context;
onLine = false;
}
private int CountOfInterseptions(Point p1, Point p2, int pcount)
{
int countInter = 0;
LineSegment newedge = new LineSegment(p1, p2);
for (int i = 0; i < pcount; i++)
{
LineSegment polyedge = new LineSegment(p.Points[i], p.Points[i + 1]);
var inter = newedge.Intersection(polyedge);
if (inter.onLine)
countInter++;
}
return countInter;
}
public void Restart()
{
if (p == null)
return;
p.Repair();
if (p.Points.Count <= 2 || CountOfInterseptions(p.Points[p.Points.Count - 1], p.Points[0], p.Points.Count - 1) == 2)
{
context.Add(p);
context.Selected.Clear();
context.Selected.Add(p);
}
p = null;
}
public void Move(Point point, Graphics graphics)
{
if (p == null)
return;
Pen pen = new Pen(Color.Blue, 2);
p.PartialDraw(graphics, pen);
int count = p.Points.Count();
LineSegment newedge = new LineSegment(p.Points[count - 1], point);
newedge.Draw(graphics, pen);
onLine = false;
pen.Color = Color.Red;
for (int i = 0; i < count - 2; i++)
{
LineSegment polyedge = new LineSegment(p.Points[i], p.Points[i + 1]);
var inter = newedge.Intersection(polyedge);
if (inter.onLine)
{
inter.p.Draw(graphics, pen);
onLine = true;
}
}
pen.Dispose();
}
public void Down(Point point, Graphics graphics)
{
if (p == null)
p = new Polygon();
if (!onLine || p.Points.Count == 0)
p.Add(point);
onLine = false;
Move(point, graphics);
}
public Matrix Draw(Point start, Point end, Graphics graphics)
{
return Matrix.Ident();
}
public bool Active()
{
p = null;
return true;
}
}
}
|
c409cf5e9263277f9192e72cb5dd1b2bc67a23b8
|
C#
|
jacobguin/Discord-Bot-CSharp
|
/Discord Bot/Discord Bot/Commands/SetPrefix.cs
| 2.8125
| 3
|
namespace Discord_Bot.Commands
{
using System;
using System.Threading.Tasks;
using Discord.Commands;
public class SetPrefix : ModuleBase<SocketCommandContext>
{
[Command("setprefix")]
[Summary("Changes the user prefix")]
public async Task Sp(params string[] prefix)
{
try
{
if (prefix.Length > 1)
{
await Context.Channel.SendMessageAsync("That is not a valid prefix!");
}
else if (prefix.Length < 1)
{
await Context.Channel.SendMessageAsync("Please provide a prefix!");
}
else
{
if (prefix[0].Length != 1)
{
await Context.Channel.SendMessageAsync("That is not a valid prefix!");
}
else
{
Database.Update("users", "id", $"{Context.User.Id}{Context.Guild.Id}", Database.CreateParameter("Prefix", prefix[0]));
await Context.Channel.SendMessageAsync($"your prefix is now '{prefix[0]}'");
}
}
}
catch (Exception ex)
{
await Utils.ReportError(Context, "SetPrefix", ex);
}
}
}
}
|
17d2ac49a4d9ed358e65f675960c3de16e129279
|
C#
|
scbrady/lynicon
|
/Lynicon/Utility/TypeRegistry.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lynicon.Utility
{
/// <summary>
/// A registry of handlers for different types
/// </summary>
/// <typeparam name="I">The type of a type handler</typeparam>
/// <typeparam name="DefaultT">The default type handler type (when nothing else is registered)</typeparam>
public class TypeRegistry<I>
{
private Dictionary<Type, I> registered = new Dictionary<Type, I>();
private I defaultHandler = default(I);
/// <summary>
/// Get the default handler
/// </summary>
public I DefaultHandler
{
get { return defaultHandler; }
set { defaultHandler = value; }
}
/// <summary>
/// Register a handler for a type
/// </summary>
/// <param name="type">The type</param>
/// <param name="typeHandler">The handler for the type</param>
public virtual void Register(Type type, I typeHandler)
{
if (type == null)
defaultHandler = typeHandler;
else
registered[type] = typeHandler;
}
/// <summary>
/// Get the registered handler for a type
/// </summary>
/// <param name="type">Type</param>
/// <returns>Handler registered for type (or default if none registered)</returns>
public I Registered(Type type)
{
I typeHandler = registered.FirstSelectOrDefault(r => r.Key.IsAssignableFrom(type), r => r.Value);
if (typeHandler == null)
typeHandler = defaultHandler;
return typeHandler;
}
/// <summary>
/// Get the registered handler for a type
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <returns>Handler registered for type (or default if none registered)</returns>
public I Registered<T>()
{
return Registered(typeof(T));
}
}
}
|
dba11dca213354b265561b81ff0694386488fd5c
|
C#
|
aykuttasil/algorithms
|
/move-zeroes/Program.cs
| 3.796875
| 4
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
/*
- Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*/
namespace move_zeroes
{
class Program
{
static Stopwatch watch = new Stopwatch();
static void Main(string[] args)
{
int[] nums = new int[] { 0, 1, 0, 3, 12, 0, 2, 3, 5, 12 };
watch.Reset();
MoveZeroes1(nums);
watch.Reset();
MoveZeroes2(nums);
watch.Reset();
MoveZeroes3(nums);
}
// Method 1
public static void MoveZeroes1(int[] nums)
{
watch.Start();
int countNonZero = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != 0)
{
nums[countNonZero++] = nums[i];
}
}
while (countNonZero < nums.Length)
{
nums[countNonZero++] = 0;
}
watch.Stop();
printScreen(nums);
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
}
// Method 2
public static void MoveZeroes2(int[] nums)
{
watch.Start();
int index = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != 0)
{
nums[index++] = nums[i];
}
}
for (int i = index; i < nums.Length; i++)
{
nums[i] = 0;
}
watch.Stop();
printScreen(nums);
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
}
// Method 3
public static void MoveZeroes3(int[] nums)
{
watch.Start();
List<int> list = new List<int>();
int zeroCount = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != 0)
{
list.Add(nums[i]);
}
else
{
zeroCount++;
}
}
for (int i = 0; i < zeroCount; i++)
{
list.Add(0);
}
watch.Stop();
printScreen(nums);
Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
}
public static void printScreen(int[] nums)
{
for (int i = 0; i < nums.Length; i++)
{
Console.WriteLine("i:" + nums[i]);
}
}
}
}
|
5e5c284ec30b279b83643893f5a2e9876a8bb970
|
C#
|
lcy03406/Candle
|
/CandleLib/Hello.cs
| 3
| 3
|
using System;
namespace CandleLib {
public class Hello {
string who;
public Hello(string who) {
this.who = who;
}
public string Say() {
return string.Format("hello, {0}", who);
}
}
}
|
73ff638cec7d04af05b763dced40eb6cdfa4029a
|
C#
|
shubhamsn/MagicHat
|
/Assets/Scripts/BlackHoleController.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* *
* attach with BlackHole
* make it more realistic
*
* */
public class BlackHoleController : MonoBehaviour {
private float xVal, yVal;
private Camera cam;
private Vector3 targetWidth;
[SerializeField]
private float initialWaitTime = 10;
// Use this for initialization
void Start ()
{
if (cam == null)
cam = Camera.main;
Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
targetWidth = cam.ScreenToWorldPoint (upperCorner);
StartCoroutine (Movement ());
}
private IEnumerator Movement()
{
xVal = Random.Range (-0.3f, 0.3f);
yVal = Random.Range (-0.3f, 0.3f);
yield return new WaitForSeconds (initialWaitTime);
while (!GameController.instance.gameOver)
{
xVal += (xVal > 0f) ? (Random.Range (-0.5f, 0.1f)) : (Random.Range (-0.1f, 0.5f));
//xVal = (xVal > 0f) ? (Random.Range (-0.25f, 0.75f)) : (Random.Range (-0.75f, 0.25f));
//xVal += Random.Range (-0.1f, 0.1f);
if(xVal >= 0.6 || xVal <= -0.6)
xVal = Random.Range (-0.3f, 0.3f);
//Debug.Log ("val " + xVal + " " + yVal);
yVal += (yVal > 0f) ? (Random.Range (-0.5f, 0.1f)) : (Random.Range (-0.1f, 0.5f));
if(yVal >= 0.3 || yVal <= -0.3)
yVal -= Random.Range (-0.3f, 0.3f);
this.GetComponent<Rigidbody2D> ().velocity = GetVelocity ();
yield return new WaitForSeconds (2f);
}
}
private Vector2 GetVelocity()
{
if (transform.position.x > targetWidth.x)
xVal = -0.5f;
if (transform.position.x < -targetWidth.x)
xVal = 0.5f;
if (transform.position.y > targetWidth.y)
yVal = -0.5f;
if (transform.position.y < -targetWidth.y)
yVal = 0.5f;
Vector2 vel = new Vector2 (xVal,yVal);
//Debug.Log ("Velocity " + vel);
return vel;
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.tag == "Ball")
{
Destroy (other.gameObject);
}
}
}
|
c2f01ec08acebfc3eaf0325419378b79b134016e
|
C#
|
Tajoreh/WarCraft-Tiger
|
/Code/UOM.Domain/Model/Dimensions/Dimension.cs
| 3.015625
| 3
|
using UOM.Domain.Model.Dimensions.Exceptions;
namespace UOM.Domain.Model.Dimensions
{
public class Dimension
{
public string Title { get; private set; }
public string AlternateTitle { get;private set; }
public string Symbol { get;private set; }
public Dimension(string title, string alternateTitle, string symbol)
{
GaurdAgainstEmptyTitle(title);
this.Title = title;
this.AlternateTitle = alternateTitle;
this.Symbol = symbol;
}
private static void GaurdAgainstEmptyTitle(string title)
{
if (string.IsNullOrEmpty(title))
{
throw new InvalidTitleException("Title should not be empty");
}
}
}
}
|
cdf9caab542368b04968f2f94135dd1231ddb6bc
|
C#
|
Toranyan/ToraLib
|
/Scripts/Input/CRaycastController.cs
| 2.640625
| 3
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
namespace tora.input {
/// <summary>
/// Transforms clicks to raycasts
/// </summary>
public class CRaycastController : MonoBehaviour {
[SerializeField]
protected Camera m_raycastCamera;
[SerializeField]
protected LayerMask m_layerMask;
[SerializeField]
protected float m_maxDistance = 100000;
[SerializeField]
protected bool m_logEnabled = true;
public event Action<RaycastHit> OnClickEvent;
public event Action<RaycastHit> OnRightClickEvent;
public void Update() {
if (Input.GetMouseButtonDown (0)) {
OnClick (0, Input.mousePosition);
}
if (Input.GetMouseButtonDown (1)) {
OnClick (1, Input.mousePosition);
}
}
public void OnClick(int button, Vector3 screenPoint) {
//Raycast
Ray ray = m_raycastCamera.ScreenPointToRay(screenPoint);
RaycastHit hitInfo;
if (Physics.Raycast (ray, out hitInfo, m_maxDistance, (int)m_layerMask)) {
Debug.Log ("Hit");
if (button == 0) { //left click
if (OnClickEvent != null) {
OnClickEvent (hitInfo);
}
} else if (button == 1) { //right click
if (OnRightClickEvent != null) {
OnRightClickEvent (hitInfo);
}
}
} else {
Debug.Log ("Nohit");
}
}
}
}
|
da1bc91c2003a3aedac8b4710c5cd013c6e4adb6
|
C#
|
MonkSoul/Xamarin.Android.Bindings
|
/Xamarin.Android.ZXing.Android.Embedded/src/Xamarin.Android.ZXing.Android.Embedded/Additions/CameraThread.cs
| 2.671875
| 3
|
using Android.OS;
using Java.Lang;
namespace Com.Journeyapps.Barcodescanner.Camera
{
public class CameraThread : Object
{
private const string TAG = nameof(CameraThread);
private static CameraThread instance;
public static CameraThread GetInstance()
{
if (instance == null)
{
instance = new CameraThread();
}
return instance;
}
private Handler handler;
private HandlerThread thread;
private int openCount = 0;
private static readonly object LOCK = new object();
private CameraThread()
{
}
protected void Enqueue(IRunnable runnable)
{
lock (LOCK)
{
CheckRunning();
this.handler.Post(runnable);
}
}
protected void EnqueueDelayed(IRunnable runnable, long delayMillis)
{
lock (LOCK)
{
CheckRunning();
this.handler.PostDelayed(runnable, delayMillis);
}
}
private void CheckRunning()
{
lock (LOCK)
{
if (this.handler == null)
{
if (openCount <= 0)
{
throw new IllegalStateException("CameraThread is not open");
}
this.thread = new HandlerThread("CameraThread");
this.thread.Start();
this.handler = new Handler(thread.Looper);
}
}
}
private void Quit()
{
lock (LOCK)
{
this.thread.Quit();
this.thread = null;
this.handler = null;
}
}
protected void DecrementInstances()
{
lock (LOCK)
{
openCount -= 1;
if (openCount == 0)
{
Quit();
}
}
}
protected void IncrementAndEnqueue(Runnable runner)
{
lock (LOCK)
{
openCount += 1;
Enqueue(runner);
}
}
}
}
|
67dcbfa8f6d5c01999c9662e05ee629d9bdf8338
|
C#
|
Novonil/Leetcode
|
/Leetcode/BFS/SuroundedRegions.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Leetcode.BFS
{
class SuroundedRegions
{
public static void Solve(char[][] board)
{
if (board == null || board.Length == 0)
return;
int rows = board.Length;
int cols = board[0].Length;
for (int i = 0; i < rows; i++)
{
if (board[i][0] == 'O')
bfs(board, i, 0);
if (board[i][cols - 1] == 'O')
bfs(board, i, cols - 1);
}
for (int j = 0; j < cols; j++)
{
if (board[0][j] == 'O')
bfs(board, 0, j);
if (board[rows - 1][j] == 'O')
bfs(board, rows - 1, j);
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (board[i][j] == 'O')
board[i][j] = 'X';
if (board[i][j] == '*')
board[i][j] = 'O';
}
}
}
public static void bfs(char[][] board, int i, int j)
{
int rows = board.Length;
int cols = board[0].Length;
Queue<(int, int)> queue = new Queue<(int, int)>();
queue.Enqueue((i, j));
while (queue.Count > 0)
{
int row = queue.Peek().Item1;
int col = queue.Peek().Item2;
queue.Dequeue();
board[row][col] = '*';
if (row - 1 >= 0 && board[row - 1][col] == 'O')
queue.Enqueue((row - 1, col));
if (row + 1 < rows && board[row + 1][col] == 'O')
queue.Enqueue((row + 1, col));
if (col - 1 >= 0 && board[row][col - 1] == 'O')
queue.Enqueue((row, col - 1));
if (col + 1 < cols && board[row][col + 1] == 'O')
queue.Enqueue((row, col + 1));
}
}
}
}
|
f506b576776c44f34d6241b6af213c444ace16b5
|
C#
|
Gcarvalhu/DesenvolvimentoWeb
|
/TskukarWeb/Repositorio/MarcasRepositorio.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.IO;
using TskukarWeb.Models;
namespace TskukarWeb.Repositorio
{
public class MarcasRepositorio
{
public List<MarcaModel> Listar(){
List<MarcaModel> listaDeMarcas = new List<MarcaModel>();
string[] linhas = File.ReadAllLines("Database/marcas.csv");
MarcaModel marca;
foreach (var item in linhas)
{
if(string.IsNullOrEmpty(item)){
continue;
}
string[] linha = item.Split(";");
marca = new MarcaModel(
id: int.Parse(linha[0]),
nome: linha[1]
);
listaDeMarcas.Add(marca);
}
return listaDeMarcas;
}//fim de listar
}
}
|
d688e0f0d1ca526732284a5fe1500ca2c4b6d492
|
C#
|
MilosSimic/snakeRoot
|
/XMLSerializer/ListValidator.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace XMLSerializer
{
public class ListValidator
{
public static bool validateXML(String filename)
{
try
{
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add(null, @"assets\ListSchema.xsd");
xmlSettings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(filename, xmlSettings);
// Parse the file.
while (reader.Read()) ;
return true;
}
catch (Exception ex)
{
return false;
}
}
public static bool validateXML(Stream filename)
{
try
{
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
xmlSettings.Schemas.Add(null, @"assets\ListSchema.xsd");
xmlSettings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(filename, xmlSettings);
// Parse the file.
while (reader.Read()) ;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
|
06d432dff448bd5543e3bb0e494eea5113350fee
|
C#
|
uzbekdev1/DeepRL
|
/DeepQL/Gyms/AcrobotEnv.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using DeepQL.Environments;
using DeepQL.Misc;
using DeepQL.Spaces;
using Neuro.Tensors;
namespace DeepQL.Gyms
{
public class AcrobotEnv : Env
{
/**
Acrobot is a 2-link pendulum with only the second joint actuated
Initially, both links point downwards. The goal is to swing the
end-effector at a height at least the length of one link above the base.
Both links can swing freely and can pass by each other, i.e., they don't
collide when they have the same angle.
**STATE:**
The state consists of the sin() and cos() of the two rotational joint
angles and the joint angular velocities :
[cos(theta1) sin(theta1) cos(theta2) sin(theta2) thetaDot1 thetaDot2].
For the first link, an angle of 0 corresponds to the link pointing downwards.
The angle of the second link is relative to the angle of the first link.
An angle of 0 corresponds to having the same angle between the two links.
A state of [1, 0, 1, 0, ..., ...] means that both links point downwards.
**ACTIONS:**
The action is either applying +1, 0 or -1 torque on the joint between
the two pendulum links.
.. note::
The dynamics equations were missing some terms in the NIPS paper which
are present in the book. R. Sutton confirmed in personal correspondence
that the experimental results shown in the paper and the book were
generated with the equations shown in the book.
However, there is the option to run the domain with the paper equations
by setting book_or_nips = 'nips'
**REFERENCE:**
.. seealso::
R. Sutton: Generalization in Reinforcement Learning:
Successful Examples Using Sparse Coarse Coding (NIPS 1996)
.. seealso::
R. Sutton and A. G. Barto:
Reinforcement learning: An introduction.
Cambridge: MIT press, 1998.
.. warning::
This version of the domain uses the Runge-Kutta method for integrating
the system dynamics and is more realistic, but also considerably harder
than the original version which employs Euler integration,
see the AcrobotLegacy class.
**/
public AcrobotEnv()
: base(new Discrete(3),
new Box(new [] { -1, -1, -1, -1, -MAX_VEL_1, -MAX_VEL_2 },
new [] { 1, 1, 1, 1, MAX_VEL_1, MAX_VEL_2 }, new Shape(6)))
{
Reset();
}
public override byte[] Render(bool toRgbArray = false)
{
var s = State;
if (Viewer == null)
{
Viewer = new Rendering.Viewer(500, 500);
var bound = LINK_LENGTH_1 + LINK_LENGTH_2 + 0.2f; // 2.2 for default
Viewer.SetBounds(-bound, bound, -bound, bound);
}
if (s == null)
return null;
var p1 = new [] { LINK_LENGTH_1 * (float)Math.Sin(s[0]), - LINK_LENGTH_1 * (float)Math.Cos(s[0]) };
//var p2 = new [] { p1[0] - LINK_LENGTH_2 * Math.Cos(s[0] + s[1]), p1[1] + LINK_LENGTH_2 * Math.Sin(s[0] + s[1]) };
var xys = new List<float[]>{ new float[] {0, 0}, p1 };
var thetas = new [] { s[0]-(float)Math.PI/2, s[0]+s[1]- (float)Math.PI / 2 };
var linkLengths = new[] {LINK_LENGTH_1, LINK_LENGTH_2};
Viewer.DrawLine(new []{-2.2f, 1}, new []{2.2f, 1});
for (int i = 0; i < linkLengths.Length; ++i)
{
float x = xys[i][0], y = xys[i][1], th = thetas[i], llen = linkLengths[i];
float l = 0, r = llen, t = .1f,b = -.1f;
var jTransform = new Rendering.Transform(new []{x, y}, th);
var link = Viewer.DrawPolygon(new List<float[]> { new[] { l, b }, new[] { l, t }, new[] { r, t }, new[] { r, b } });
link.AddAttr(jTransform);
link.SetColor(0, .8f, .8f);
var circ = Viewer.DrawCircle(.1f);
circ.SetColor(.8f, .8f, 0);
circ.AddAttr(jTransform);
}
Viewer.Render();
return null;
}
protected override Tensor GetObservation()
{
var s = State;
return new Tensor(new []{ (float)Math.Cos(s[0]), (float)Math.Sin(s[0]), (float)Math.Cos(s[1]), (float)Math.Sin(s[1]), s[2], s[3]}, ObservationSpace.Shape);
}
public override Tensor Reset()
{
State = new Tensor(new Shape(4));
State.FillWithRand(-1, -0.1f, 0.1f);
return GetObservation();
}
public override bool Step(Tensor action, out Tensor observation, out float reward)
{
var s = State;
var a = (int)action[0];
var torque = AVAIL_TORQUE[a];
// Add noise to the force action
if (TORQUE_NOISE_MAX > 0)
torque += Rng.NextFloat(-TORQUE_NOISE_MAX, TORQUE_NOISE_MAX);
// Now, augment the state with our force action so it can be passed to _dsdt
float[] sAugmented = s.GetValues().Concat(new []{torque}).ToArray();
var nsFull = Rk4(Dsdt, sAugmented, new [] { 0, DT });
// only care about final timestep of integration returned by integrator
//ns = ns[-1];
//ns = ns[:4] // omit action
var ns = new float[4];
var lastRow = nsFull.GetLength(0) - 1;
for (int n = 0; n < 4; ++n)
ns[n] = nsFull[lastRow, n];
// ODEINT IS TOO SLOW!
// ns_continuous = integrate.odeint(self._dsdt, self.s_continuous, [0, self.dt])
// self.s_continuous = ns_continuous[-1] // We only care about the state
// at the ''final timestep'', self.dt
ns[0] = Wrap(ns[0], -(float)Math.PI, (float)Math.PI);
ns[1] = Wrap(ns[1], -(float)Math.PI, (float)Math.PI);
ns[2] = Bound(ns[2], -MAX_VEL_1, MAX_VEL_1);
ns[3] = Bound(ns[3], -MAX_VEL_2, MAX_VEL_2);
State = new Tensor(ns, State.Shape);
bool terminal = Terminal();
reward = terminal ? 0 : -1.0f;
observation = GetObservation();
return terminal;
}
public override void Dispose()
{
Viewer.Dispose();
Viewer = null;
base.Dispose();
}
private bool Terminal()
{
var s = State;
return -Math.Cos(s[0]) - Math.Cos(s[1] + s[0]) > 1.0;
}
private float[] Dsdt(float[] s_augmented, float t)
{
var m1 = LINK_MASS_1;
var m2 = LINK_MASS_2;
var l1 = LINK_LENGTH_1;
var lc1 = LINK_COM_POS_1;
var lc2 = LINK_COM_POS_2;
var I1 = LINK_MOI;
var I2 = LINK_MOI;
var g = 9.8f;
var a = s_augmented.Last();
var s = s_augmented.Take(s_augmented.Length - 1).ToArray();
var theta1 = s[0];
var theta2 = s[1];
var dtheta1 = s[2];
var dtheta2 = s[3];
var d1 = m1 * lc1 * lc1 + m2 * (l1 * l1 + lc2 * lc2 + 2 * l1 * lc2 * (float)Math.Cos(theta2)) + I1 + I2;
var d2 = m2 * (lc2 * lc2 + l1 * lc2 * (float)Math.Cos(theta2)) + I2;
var phi2 = m2 * lc2 * g * (float)Math.Cos(theta1 + theta2 - (float)Math.PI / 2.0);
var phi1 = -m2 * l1 * lc2 * dtheta2 * dtheta2 * (float)Math.Sin(theta2) -
2 * m2 * l1 * lc2 * dtheta2 * dtheta1 * (float)Math.Sin(theta2) +
(m1 * lc1 + m2 * l1) * g * (float)Math.Cos(theta1 - (float)Math.PI / 2) + phi2;
var ddtheta2 = 0.0f;
if (BookOrNips == "nips")
{
// the following line is consistent with the description in the paper
ddtheta2 = (a + d2 / d1 * phi1 - phi2) / (m2 * lc2 * lc2 + I2 - d2 * d2 / d1);
}
else
{
// the following line is consistent with the java implementation and the book
ddtheta2 = (a + d2 / d1 * phi1 - m2 * l1 * lc2 * dtheta1 * dtheta1 * (float)Math.Sin(theta2) - phi2) / (m2 * lc2 * lc2 + I2 - d2 * d2 / d1);
}
var ddtheta1 = -(d2 * ddtheta2 + phi1) / d1;
return new float[] {dtheta1, dtheta2, ddtheta1, ddtheta2, 0.0f};
}
private float Wrap(float x, float m, float M)
{
/**
:param x: a scalar
:param m: minimum possible value in range
:param M: maximum possible value in range
Wraps x so m <= x <= M; but unlike bound() which truncates, wrap() wraps x around the coordinate system defined by m,M.
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
**/
var diff = M - m;
while (x > M)
x = x - diff;
while (x < m)
x = x + diff;
return x;
}
private float Bound(float x, float m, float M)
{
// bound x between min (m) and Max (M)
return Math.Min(Math.Max(x, m), M);
}
private float Bound(float x, float[] m)
{
// bound x between min (m) and Max (M)
return Math.Min(Math.Max(x, m[0]), m[1]);
}
private delegate float[] Derivs(float[] s_augmented, float t);
private float[,] Rk4(Derivs derivs, float[] y0, float[] t)
{
/**
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
*y0*
initial state vector
*t*
sample times
*derivs*
returns the derivative of the system and has the
signature ``dy = derivs(yi, ti)``
Example 1 ::
//// 2D system
def derivs6(x,t):
d1 = x[0] + 2*x[1]
d2 = -3*x[0] + 4*x[1]
return (d1, d2)
dt = 0.0005
t = arange(0.0, 2.0, dt)
y0 = (1,2)
yout = rk4(derivs6, y0, t)
Example 2::
//// 1D system
alpha = 2
def derivs(x,t):
return -alpha*x + exp(-t)
y0 = 1
yout = rk4(derivs, y0, t)
If you have access to scipy, you should probably be using the
scipy.integrate tools rather than this function.
**/
var ny = y0.Length;
var yOut = new float[t.Length, ny];
for (int n = 0; n < ny; ++n)
yOut[0,n] = y0[n];
for (int i = 0; i < t.Length - 1; ++i)
{
var thisT = t[i];
var dt = t[i + 1] - thisT;
var dt2 = dt / 2.0f;
for (int n = 0; n < ny; ++n)
y0[n] = yOut[i, n];
var k1 = derivs(y0, thisT);
var k2 = derivs(y0.Zip(k1, (a,b) => a + dt2 * b).ToArray() , thisT + dt2);
var k3 = derivs(y0.Zip(k2, (a, b) => a + dt2 * b).ToArray(), thisT + dt2);
var k4 = derivs(y0.Zip(k3, (a, b) => a + dt * b).ToArray(), thisT + dt);
for (int n = 0; n < ny; ++n)
yOut[i + 1, n] = y0[n] + dt / 6.0f * (k1[n] + 2 * k2[n] + 2 * k3[n] + k4[n]);
}
return yOut;
}
private const float DT = .2f;
private const float LINK_LENGTH_1 = 1.0f; // [m]
private const float LINK_LENGTH_2 = 1.0f; // [m]
private const float LINK_MASS_1 = 1.0f; //: [kg] mass of link 1
private const float LINK_MASS_2 = 1.0f; //: [kg] mass of link 2
private const float LINK_COM_POS_1 = 0.5f; //: [m] position of the center of mass of link 1
private const float LINK_COM_POS_2 = 0.5f; //: [m] position of the center of mass of link 2
private const float LINK_MOI = 1.0f; //: moments of inertia for both links
private const float MAX_VEL_1 = 4 * (float)Math.PI;
private const float MAX_VEL_2 = 9 * (float)Math.PI;
private readonly float[] AVAIL_TORQUE = { -1.0f, 0.0f, 1.0f };
private float TORQUE_NOISE_MAX = 0.0f;
//use dynamics equations from the nips paper or the book
private string BookOrNips = "book";
private Rendering.Viewer Viewer;
}
}
|
8ecec5f79c4e7f2931dd1456e0e52a724bfc5c32
|
C#
|
JHPham687/MIS-3013
|
/Participations/Coin Toss/Program.cs
| 3.78125
| 4
|
using System;
namespace Coin_Toss
{
class Program
{
const string Developer = "\n -Jo Pham";
static void Main(string[] args)
{
Console.WriteLine("Heads or Tails?");
string guess = Console.ReadLine();
Random rnd = new Random();
int number = rnd.Next(0, 2);
if (number == 0) //0 = Heads
{
Console.WriteLine("\n It is Heads");
if (guess == "Heads")
{
Console.WriteLine("\n You won! :D");
}
else if (guess == "Tails")
{
Console.WriteLine("\n You lost. :(");
}
}
else if (number == 1) //1 = Tails
{
Console.WriteLine("\n It is Tails");
if (guess == "Tails")
{
Console.WriteLine("\n You won! :D");
}
else if (guess == "Heads")
{
Console.WriteLine("\n You lost. :(");
}
}
Console.WriteLine(Developer);
}
}
}
|
911fe9ccfbe264191e5ceb440e6a0e6fe388b6fb
|
C#
|
rhk98/JustSaying.Examples.Orderprocessing
|
/full/OrderProcessor/OrderPlacementWithIntermittentDbError.cs
| 2.5625
| 3
|
using System;
using JustSaying.Messaging;
using Messages.Commands;
namespace JustSaying.Examples.OrderProcessing.OrderProcessor
{
internal class OrderPlacementWithIntermittentDbError : OrderPlacement
{
private int _i;
internal OrderPlacementWithIntermittentDbError(IMessagePublisher publisher) : base(publisher)
{
}
public override bool Handle(PlaceOrder message)
{
_i ++;
if (_i%2 == 0) // Process 50% of order requests successfully
{
Console.WriteLine("OOPS, DB error processing order for {0}", message.CustomerName);
throw new Exception("DB BLEW UP!");
}
return base.Handle(message);
}
}
}
|
86dafce1ea7d4dc10405a5dc787b0f60237a755d
|
C#
|
gonzaloperezbarrios/Domain-Driven-Design
|
/Example.Infrastructure/Migrations/Configuration.cs
| 2.765625
| 3
|
namespace Example.Infrastructure.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Example.Infrastructure.persistence.entityFramework.CarContext>
{
public Configuration()
{
//Mapea la entidad y agrega automaticamente las columnas a la base de datos
AutomaticMigrationsEnabled = true;
}
protected override void Seed(Example.Infrastructure.persistence.entityFramework.CarContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.CarOwner.AddOrUpdate(x => x.Id, new Transversal.domain.entities.car.CarOwnerEntitie()
{
Id = 1,
Name = "Gonzalo Perez",
Age = "30",
CarId=1
});
}
}
}
|
bb62300a454c97267f61e902678182bb0cb37c76
|
C#
|
lkucera94/BlueBadgeProject
|
/MilitaryBaseRater.Services/BaseRatingService.cs
| 2.609375
| 3
|
using MilitaryBaseRater.Data;
using MilitaryBaseRater.Models.RatingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MilitaryBaseRater.Services
{
public class BaseRatingService
{
private readonly Guid _userId;
public BaseRatingService(Guid userId)
{
_userId = userId;
}
public BaseRatingService() { }
public bool CreateRating(RatingCreate model)
{
var rating = new BaseRating
{
OwnerID = _userId,
BaseID = model.BaseID,
RaterID = model.RaterID,
OverallRating = model.OverallRating,
HousingRating = model.HousingRating,
FoodRating = model.FoodRating,
ActivitiesRating = model.ActivitiesRating,
TrainingSitesRating = model.TrainingSitesRating,
Comments = model.Comments
};
using (var ctx = new ApplicationDbContext())
{
ctx.Ratings.Add(rating);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<RatingListItem> GetRatingsByUserID(Guid userId)
{
using (var ctx = new ApplicationDbContext())
{
var query = ctx.Ratings.Where(b => b.OwnerID == userId).Select(b => new RatingListItem
{
BaseID = b.BaseID,
RatingID = b.RatingID,
BaseName = b.Base.BaseName,
OverallRating = b.OverallRating
});
return query.ToArray();
}
}
public IEnumerable<RatingListItem> GetRatings()
{
using (var ctx = new ApplicationDbContext())
{
var query = ctx.Ratings.Select(r => new RatingListItem
{
BaseID = r.BaseID,
RatingID = r.RatingID,
UserName = r.Rater.UserName,
Branch = r.Rater.Branch,
Job = r.Rater.Job,
Rank = r.Rater.Rank,
Age = r.Rater.Age,
BaseName = r.Base.BaseName,
OverallRating = r.OverallRating
});
return query.ToArray();
}
}
public RatingDetail GetRatingsByRatingID(int ratingId)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Ratings.FirstOrDefault(r => r.RatingID == ratingId);
var model = new RatingDetail()
{
RatingID = entity.RatingID,
UserName = entity.Rater.UserName,
BaseName = entity.Base.BaseName,
OverallRating = entity.OverallRating,
HousingRating = entity.HousingRating,
FoodRating = entity.FoodRating,
ActivitiesRating = entity.ActivitiesRating,
TrainingSitesRating = entity.TrainingSitesRating,
Comments = entity.Comments
};
return model;
}
}
public bool EditBaseRating(RatingEdit model)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Ratings.Single(r => r.RatingID == model.RatingID);
entity.BaseID = model.BaseID;
entity.OverallRating = model.OverallRating;
entity.HousingRating = model.HousingRating;
entity.FoodRating = model.FoodRating;
entity.ActivitiesRating = model.ActivitiesRating;
entity.TrainingSitesRating = model.TrainingSitesRating;
entity.Comments = model.Comments;
return ctx.SaveChanges() == 1;
}
}
public bool DeleteRating(int id)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Ratings.Single(r => r.RatingID == id);
ctx.Ratings.Remove(entity);
return ctx.SaveChanges() == 1;
}
}
}
}
|
a671a542a5b77a7dd26e40f69da953adf59dc4d3
|
C#
|
dalemorgan04/Mortgage-Site-with-API
|
/MortgageApi/Api/Entities/SearchRequest.cs
| 2.796875
| 3
|
using MortgageApi.Models.Enums;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Text;
namespace MortgageApi.Api.Entities
{
public class SearchRequest
{
[JsonProperty("customer_id")]
public Guid CustomerId { get; set; }
[JsonProperty("property_value")]
public decimal PropertyValue { get; set; }
[JsonProperty("deposit")]
public decimal Deposit { get; set; }
[JsonProperty("mortgage_type")]
public int MortgageTypeInt { get; set; }
public MortgageTypeIdentifier MortgageType => (MortgageTypeIdentifier)MortgageTypeInt;
public bool IsValid => String.IsNullOrEmpty(GetValidationMessage);
public string GetValidationMessage
{
get
{
var sb = new StringBuilder();
if (PropertyValue <= 0 || PropertyValue > 9999999) sb.Append("Property Value not valid; ");
if (Deposit < 0 || Deposit > 9999999)sb.Append("Deposit not valid; ");
if (LoanToValue > 0.9M || LoanToValue <= 0M) sb.Append("Your loan to value ratio disqualifies you; ");
return sb.ToString();
}
}
public decimal LoanToValue { get
{
if (PropertyValue <= 0)
{
return 0M;
}
else
{
return (decimal)(PropertyValue - Deposit) / PropertyValue;
}
} }
}
}
|
7ab7e94275a75f489e5047685bd48e8f9a2b12b3
|
C#
|
johnathaningle/Func
|
/Fs.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace Testing
{
public static class Fs
{
public static string Open(string fname)
{
var assembly = Assembly.GetExecutingAssembly();
var file = "";
using (Stream stream = assembly.GetManifestResourceStream(fname))
using (StreamReader reader = new StreamReader(stream)) {
file = reader.ReadToEnd();
}
return file;
}
}
}
|
8f7d6b5a641787a07bb57187613a92bf18c498f4
|
C#
|
rikusov/DataProcessing
|
/nba.stat_parse/GetStatic.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.IO;
using System.Threading.Tasks;
namespace ParseStatic
{
enum TypeStage {Predseson=1,Season,AllStar,PlayOFF}//типы игр в индексе
struct IndexoftheMatch//индекс матча на сайте
{
private TypeStage type;
private int season;
private int index;
public string IndexGame { get; private set;}
public IndexoftheMatch(TypeStage ts, int _season, int _index)//создание индексов
{
type = ts;
if (_season < 1983 || _season>DateTime.Now.Year) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex("Invalid year of index(year should be more 1983)");
season = _season;
if (type==TypeStage.Season)
if (!Default.Usual.SwitchinRangeCountGame(_index,_season,type)) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex($"Invalid number game of index(game {_index.ToString()}) in year {_season} dont dound");
index = _index;
string template = index.ToString();
while (template.Length != 5) template = '0' + template;
IndexGame = "00" + ((int)type).ToString() + (_season % 100).ToString()+template;
}
public IndexoftheMatch(string _index)//создание индексов
{
if (_index.Length != 10) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex("Invalid year of index(index is ten symbols)");
int _typestage = Convert.ToInt32(_index[2].ToString());
type = (TypeStage)_typestage;
if (_typestage<1 || _typestage>4) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex("Invalid year of index(false type stage)");
int _season = Convert.ToInt32(_index[3].ToString() + _index[4].ToString());
if (_season <= DateTime.Now.Year - 2000) _season += 2000;
else _season += 1900;
if (_season<1983 || _season>DateTime.Now.Year) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex("Invalid year of index(year should be more 1983)");
season = _season;
int ind = Convert.ToInt32(_index[5].ToString()+_index[6].ToString()+ _index[7].ToString() + _index[8].ToString() + _index[9].ToString());
if (type == TypeStage.Season)
if (!Default.Usual.SwitchinRangeCountGame(ind,_season,type)) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex($"Invalid number game of index(game {ind.ToString()}) in year {_season} dont found");
index = ind;
IndexGame = _index;
}
public void Increment()//инкримент
{
index++;
if (type == TypeStage.Season)
if (!Default.Usual.SwitchinRangeCountGame(index, season,type)) throw DataExeption.DataProcessingExeptions.ErrorFormatIndex($"Invalid number game of index(game {index.ToString()}) in year {season} dont dound");
string template = index.ToString();
while (template.Length != 5) template = '0' + template;
IndexGame = "00" + ((int)type).ToString() + (season % 100).ToString() + template;
}
public int CompareTo(IndexoftheMatch _index)//сравнение идексов
{
if (_index.type != type) throw DataExeption.DataProcessingExeptions.ErrorCompare("It is impossible to compare indices of different types");
if (_index.season != season) throw DataExeption.DataProcessingExeptions.ErrorCompare("It is impossible to compare indices of different seasons");
return index.CompareTo(_index.index);
}
public int Subtraction(IndexoftheMatch _index)//вычетание
{
if (_index.type != type) throw DataExeption.DataProcessingExeptions.ErrorCompare("It is impossible to subtract indices of different types");
if (_index.season != season) throw DataExeption.DataProcessingExeptions.ErrorCompare("It is impossible to subtract indices of different seasons");
return (index - _index.index);
}
}
static class GetStatic//Класс для получения данных с сайта
{
public delegate void Progress(int _progress);//делегат для сообщения прогресса в ассинхронных процесах
public delegate void Answer(string[] _answer,int id_queue);//делигат для вывода результата ассихронного процесса
private static int MinYearoftheGame = 1983;//минимальная возможная дата(год)
public static string[] GetListMatchinData(DateTime dataTime)//Список матчей в опеделенныею дату
{
if (dataTime.Year < MinYearoftheGame) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Invalid date");
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
string url = $"http://stats.nba.com/scores/{dataTime.Month.ToString()}/{dataTime.Day.ToString()}/{dataTime.Year.ToString()}";
WebBrowser.Navigate().GoToUrl(url);
IEnumerator<IWebElement> ListFindingElements;
if (dataTime.Date.CompareTo(DateTime.Now.Date) < 0)
ListFindingElements = WebBrowser.FindElements(By.CssSelector("div.linescores-container span.team-name")).GetEnumerator();
else ListFindingElements = WebBrowser.FindElements(By.CssSelector("div.linescores-container span.team-abbrv")).GetEnumerator();
List<string> ListMatch = new List<string>();
ListFindingElements.Reset();
while (ListFindingElements.MoveNext())
{
string temporary = ListFindingElements.Current.Text;
if (!ListFindingElements.MoveNext())
{
ListFindingElements.Dispose();
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
throw DataExeption.DataProcessingExeptions.ErrorWriteData("Сould not read data from the site");
}
ListMatch.Add(temporary + '\t' + ListFindingElements.Current.Text);
}
ListFindingElements.Dispose();
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
return ListMatch.ToArray();
}
private static Task<string[]> GetListMatchinDataHide(DateTime dataTime)//ассинхронный метод чтения данных(скрытый)
{
return Task.Run(() => GetListMatchinData(dataTime));
}
public static async void GetListMatchinDataAcync(DateTime dt ,Answer _answ=null,int id_queue=-1,Progress _prog = null)//ассинхронный метод чтения списка матчей по дате
{
_prog?.Invoke(0);
var output = await GetListMatchinDataHide(dt);
_prog?.Invoke(100);
_answ?.Invoke(output,id_queue);
}
public static string[] GetListIndexMatchinData(DateTime dataTime)//получение индексов матчей в определенную дату
{
if (dataTime.Year < MinYearoftheGame) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Invalid date");
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
string url = $"http://stats.nba.com/scores/{dataTime.Month.ToString()}/{dataTime.Day.ToString()}/{dataTime.Year.ToString()}";
WebBrowser.Navigate().GoToUrl(url);
IEnumerator<IWebElement> ListFindingElementsIndex, ListFindingElementsMatch;
if (dataTime.Date.CompareTo(DateTime.Now.Date) < 0)
{
ListFindingElementsIndex = WebBrowser.FindElementsByLinkText("Box Score").GetEnumerator();
ListFindingElementsMatch = WebBrowser.FindElements(By.CssSelector("div.linescores-container span.team-name")).GetEnumerator();
}
else
{
WebBrowser.Quit();
ChromeService.Dispose();
WebBrowser.Dispose();
throw DataExeption.DataProcessingExeptions.ErrorWriteData("Invalid date");
}
List<string> ListMatch = new List<string>();
ListFindingElementsIndex.Reset();
ListFindingElementsMatch.Reset();
while (ListFindingElementsMatch.MoveNext())
{
string temporary = ListFindingElementsMatch.Current.Text;
if (!ListFindingElementsMatch.MoveNext()) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Could not read data from the site");
temporary += '\t' + ListFindingElementsMatch.Current.Text;
if (!ListFindingElementsIndex.MoveNext()) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Could not read data from the site");
temporary += '\t' + Default.TextWorker.Repalase(ListFindingElementsIndex.Current.GetAttribute("href"),
new string[] { "http://stats.nba.com/game/", "/" }, "");
ListMatch.Add(temporary);
}
WebBrowser.Quit();
ListFindingElementsIndex.Dispose();
ListFindingElementsMatch.Dispose();
WebBrowser.Dispose();
ChromeService.Dispose();
return ListMatch.ToArray();
}
private static Task<string[]> GetListIndexMatchinDataHide(DateTime dataTime)//ассинхронный метод получене индексов(скрытый)
{
return Task.Run(() => GetListIndexMatchinData(dataTime));
}
public static async void GetListIndexMatchinDataAcync(DateTime dt, Answer _answ = null, int id_queue = -1, Progress _prog = null)////ассинхронный метод чтения списка индексов матчей по дате
{
_prog?.Invoke(0);
var output = await GetListIndexMatchinDataHide(dt);
_prog?.Invoke(100);
_answ?.Invoke(output, id_queue);
}
private static string[] GetStaticinIndex(IndexoftheMatch _index, ChromeDriver chrome)//получение показателей матча
{
chrome.Navigate().GoToUrl($"http://stats.nba.com/game/{_index.IndexGame}/");
IReadOnlyCollection<IWebElement> ListNamesTeam;
IEnumerator<IWebElement> ListIndecatorsTeam;
ListNamesTeam = chrome.FindElements(By.CssSelector("div.game-summary-team__name a"));
ListIndecatorsTeam = chrome.FindElements(By.CssSelector("div.nba-stat-table__overflow tfoot td")).GetEnumerator();
if (ListNamesTeam.Count != 2) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Reading names teams");
string names = "";
foreach (var _name in ListNamesTeam) names += _name.Text + '\t';
List<string> indecatorsteam = new List<string>();
while (ListIndecatorsTeam.MoveNext())
if (ListIndecatorsTeam.Current.Text == "Totals:")
{
if (!ListIndecatorsTeam.MoveNext())
{
chrome.Quit();
chrome.Dispose();
ListIndecatorsTeam.Dispose();
throw DataExeption.DataProcessingExeptions.ErrorWriteData("Reading indecators");
}
indecatorsteam.Add(Default.Usual.ReadIndecatorsTeam(ListIndecatorsTeam));
}
if (indecatorsteam.Count != 2)
{
chrome.Quit();
chrome.Dispose();
ListIndecatorsTeam.Dispose();
throw DataExeption.DataProcessingExeptions.ErrorWriteData("Reading indecators");
}
ListIndecatorsTeam.Dispose();
return new string[] { names, indecatorsteam[0], indecatorsteam[1] };
}
private static Task<string[]> GetStaticinIndexHide(IndexoftheMatch _index, ChromeDriver chrome)//срытый ассинхорный получение показателей матча
{
return Task.Run(() => GetStaticinIndex(_index, chrome));
}
public static string[] GetStaticinIndex(IndexoftheMatch beginindex)//получение показателей по индексу
{
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
var output = GetStaticinIndex(beginindex, WebBrowser);
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
return output;
}
public static async void GetStaticinIndexAsync(IndexoftheMatch beginindex, Answer _answ = null, int id_queue = -1, Progress _prog = null)//получение показателей по индексу(ассинхронный)
{
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
_prog?.Invoke(0);
var output = await GetStaticinIndexHide(beginindex, WebBrowser);
_prog?.Invoke(100);
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
_answ?.Invoke(output,id_queue);
}
public static string[] GetStaticinIndex(IndexoftheMatch beginindex, IndexoftheMatch endindex, Progress _progress=null)// считывание матчей от индекса а до б
{
if (beginindex.CompareTo(endindex) == 1) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Initial index is greater than the final");
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
int partproc = endindex.Subtraction(beginindex)+1;
var output = new List<string>();
_progress(0);
while (beginindex.CompareTo(endindex) != 1)
{
output.AddRange(GetStaticinIndex(beginindex, WebBrowser));
_progress?.Invoke((100 - endindex.Subtraction(beginindex) * 100 / partproc));
beginindex.Increment();
}
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
return output.ToArray();
}
public async static void GetStaticinIndexAsync(IndexoftheMatch beginindex, IndexoftheMatch endindex, Answer _answ = null, int id_queue = -1, Progress _prog = null)// считывание матчей от индекса а до б(accинхронный)
{
if (beginindex.CompareTo(endindex) == 1) throw DataExeption.DataProcessingExeptions.ErrorWriteData("Initial index is greater than the final");
var ChromeService = ChromeDriverService.CreateDefaultService(System.IO.Directory.GetCurrentDirectory());
ChromeService.HideCommandPromptWindow = true;//скрываем консоль веб драйвера
var WebBrowser = new ChromeDriver(ChromeService); //Иницализация веб драйвера Chrome
int partproc = endindex.Subtraction(beginindex) + 1;
var output = new List<string>();
_prog(0);
while (beginindex.CompareTo(endindex) != 1)
{
output.AddRange(await GetStaticinIndexHide(beginindex, WebBrowser));
_prog?.Invoke((100 - endindex.Subtraction(beginindex) * 100 / partproc));
beginindex.Increment();
}
WebBrowser.Quit();
WebBrowser.Dispose();
ChromeService.Dispose();
_answ?.Invoke(output.ToArray(),id_queue);
}
}
}
|
3ad59f87132f4ab076baf84b22419e1923b23472
|
C#
|
yoshioka440/KingIsAlone
|
/Assets/Scripts/Bullet.cs
| 2.734375
| 3
|
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
public int attack_power,block_power;
public bool is_ground;
[SerializeField]float destroy_wait_time;
void Start(){
is_ground = false;
}
public int Damage(){
int damage;
if (is_ground) {
damage = block_power;
Destroy (gameObject, destroy_wait_time);
} else {
damage = attack_power;
Destroy (gameObject);
}
return damage;
}
void OnCollisionEnter(Collision col){
if (col.gameObject.tag == "Ground") {
is_ground = true;
}
if (col.gameObject.tag == "Bullet") {
is_ground = true;
}
}
void OnCollisionExit(Collision col){
if (col.gameObject.tag == "Ground") {
is_ground = false;
}
}
}
|
be6e7f948b22bc14b055760f51dfee571097cfe7
|
C#
|
Agobin/LearningCSharp
|
/Lesson02/Lesson02/Program.cs
| 3.65625
| 4
|
using System;
namespace Lesson02
{
class Program
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
Rectangle s = new Rectangle { Length = 2.0, Width = 2.0 };
rect.Length = 20.0;
rect.Width = 10.0;
double area = rect.GetArea();
Console.WriteLine("The area of the rectangle is {0}", area);
}
}
}
|
cf9651e459c0a254c6b5ca8c0e81bf729f4ccdc2
|
C#
|
Earthraid/TheVigilante
|
/TheVigilante/TheVigilante/Classes/CombatClass.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TheVigilante.Classes
{
public class CombatClass
{
private bool run = false;
private string input;
private bool stillFighting = true;
private int playerAttack;
private int criminalAttack;
static Random rnd = new Random();
//Determines order of attack
public void FightOrder()
{
stillFighting = true;
//Decides fight order
int fightOrder = rnd.Next(0, 1);
//Player hits first
if (fightOrder == 0)
{
Console.WriteLine(" You got the jump on this scum-bag.\n");
while (stillFighting)
{
Console.Clear();
Console.WriteLine($" Player Health: {PlayerClass.PlayerHitPoints} Criminal Health: {CriminalClass.CriminalHitPoints} \n");
PlayerAttack();
Console.WriteLine($" You hit {CriminalClass.CriminalName} for {playerAttack}.\n");
CheckHitPonts(CriminalClass.CriminalHitPoints);
Thread.Sleep(500);
CriminalAttack();
Console.WriteLine($" Oof. You got hit for {criminalAttack}.\n");
CheckHitPonts(PlayerClass.PlayerHitPoints);
Thread.Sleep(500);
Console.Write(" Do you want to keep fighting? (Y)es or (N)o?: ");
input = Console.ReadLine().ToLower();
Run(input);
Console.WriteLine();
Console.WriteLine();
}
}
//Criminal hits first
else
{
Console.WriteLine(" This jack ass saw you coming a mile away.\n");
while (stillFighting)
{
Console.Clear();
Console.WriteLine($" Player Health: {PlayerClass.PlayerHitPoints} Criminal Health: {CriminalClass.CriminalHitPoints} \n");
CriminalAttack();
Console.WriteLine($" Oof. You got hit for {criminalAttack}.\n");
CheckHitPonts(PlayerClass.PlayerHitPoints);
Thread.Sleep(1000);
PlayerAttack();
Console.WriteLine($" You hit {CriminalClass.CriminalName} for {playerAttack}.\n");
CheckHitPonts(CriminalClass.CriminalHitPoints);
Thread.Sleep(1000);
Console.Write(" Do you want to wimp out and run away? (Y)es or (N)o?: ");
input = Console.ReadLine().ToLower();
Console.WriteLine();
Run(input);
CombatEndFight();
Console.WriteLine();
}
}
}
//Calculates and applies player's attack value
public int PlayerAttack()
{
playerAttack = rnd.Next(PlayerClass.PlayerLevel + 10, PlayerClass.PlayerLevel + 20) + PlayerClass.OwnedWeaponDamage;
CriminalClass.CriminalHitPoints -= playerAttack;
CheckHitPonts(CriminalClass.CriminalHitPoints);
return playerAttack;
}
//Calculates and applies criminal's attack value
public int CriminalAttack()
{
criminalAttack = rnd.Next(CriminalClass.CriminalLevel + 9, CriminalClass.CriminalLevel + 19) - PlayerClass.OwnedArmorValue;
PlayerClass.PlayerHitPoints -= criminalAttack;
CheckHitPonts(PlayerClass.PlayerHitPoints);
return criminalAttack;
}
//Gives consequences of the fight ending, however that may be
public void CombatEndFight()
{
if (PlayerClass.PlayerHitPoints <= 0)
{
Console.WriteLine();
Console.WriteLine(" You got knocked out! Hey, at least they didn't kill you.\n");
Console.WriteLine($" You've lost {(PlayerClass.PlayerMoney / 10).ToString("C")}\n");
Thread.Sleep(3000);
Console.Clear();
PlayerClass.EndFight(false, PlayerClass.PlayerMoney / 10);
CriminalClass.CriminalMaxHitPoints();
stillFighting = false;
}
else if (CriminalClass.CriminalHitPoints <= 0)
{
Console.WriteLine();
Console.WriteLine(" You've won. Justice.\n");
Console.WriteLine($" You've gained {(CriminalClass.CriminalMoney).ToString("C")}\n");
Console.WriteLine($" You've gained {CriminalClass.CriminalExperience} XP.\n");
Thread.Sleep(3000);
Console.Clear();
PlayerClass.EndFight(true, CriminalClass.CriminalMoney);
CriminalClass.CriminalMaxHitPoints();
stillFighting = false;
}
}
//Gives player the opprtunity to run from fight at a cost of 10% of $$
public void Run(string input)
{
//Causes player to run from battle
if (input == "n" || input == "no")
{
Console.Clear();
Console.WriteLine();
Console.WriteLine(" Just another coward posing as a hero.\n");
Console.WriteLine($" You've lost {(PlayerClass.PlayerMoney / 10).ToString("C")}\n");
Console.WriteLine(" Cry in your pillow at home...\n");
Thread.Sleep(3000);
PlayerClass.EndFight(false, PlayerClass.PlayerMoney / 10);
stillFighting = false;
}
//Continues fight wth criminal
else if (input == "y" || input == "yes")
{
Console.WriteLine();
Console.WriteLine(" You suck it up and keep fighting.\n");
}
//Mocks fail
else
{
Console.WriteLine();
Console.WriteLine(" Not too good at directions, huh?\n");
Console.WriteLine(" Hopefully you survive this round.\n");
Console.WriteLine();
}
}
//Checks hitpoints to end fight if one's hitpoints falls to 0 or below.
public void CheckHitPonts(int hitPoints)
{
if (hitPoints <= 0)
{
CombatEndFight();
}
}
}
}
|
a70a15215d7c6afc22ec6626c23d0929be02635c
|
C#
|
andrewlord607/Asteroids
|
/Asteroids/Assets/Scripts/AsteroidsUtils.cs
| 3.078125
| 3
|
using UnityEngine;
namespace Utils
{
// Класс, содержащий вспомогательные методы
static class AsteroidsUtils
{
// 4 вида границы экрана для GetWorldPositionOfBorder
public enum Border
{
top,
bottom,
left,
right
}
/// <summary>
/// Получить случайный знак
/// </summary>
public static float RandomSign() => Random.value < 0.5 ? -1f : 1f;
/// <summary>
/// Получить границу камеры(зависит от текущего разрешения) в мировых координатах
/// </summary>
public static Vector3 GetWorldPositionOfBorder(Border border)
{
var camera = Camera.main;
// На основе переданного типа границы экрана вычисляется мировые координаты
// Вычисление происходит путём перевода координат Viewport, которые всегда определяются промежутком между 0 и 1
return border switch
{
Border.top => camera.ViewportToWorldPoint(Vector3.up),
Border.bottom => camera.ViewportToWorldPoint(Vector3.down),
Border.left => camera.ViewportToWorldPoint(Vector3.zero),
Border.right => camera.ViewportToWorldPoint(Vector3.right),
_ => Vector3.zero,
};
}
/// <summary>
/// Получить случайную координату внутри границ экрана
/// </summary>
public static Vector3 GetRandomPointInsideBorder()
{
var camera = Camera.main;
// Вычисление происходит путём перевода координат Viewport, которые всегда определяются промежутком между 0 и 1
return camera.ViewportToWorldPoint(new Vector3(Random.value, Random.value, 0));
}
}
}
|
b2c8ebbf7f5215436f723751007ead9d94d483de
|
C#
|
ahsanikgb/ShakeelGitHubTripKaroApiV0b1
|
/TripkaroApiV0b1/Controllers/SpecialOffersController.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TripkaroApiV0b1.Helpers;
using TripkaroApiV0b1.MyDbContext;
namespace TripkaroApiV0b1.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class SpecialOffersController : ControllerBase
{
private readonly DataContext _context;
public SpecialOffersController(DataContext context)
{
_context = context;
}
// GET: api/SpecialOffers
[HttpGet]
public async Task<ActionResult<IEnumerable<SpecialOffer>>> GetSpecialOffers()
{
return await _context.SpecialOffers.ToListAsync();
}
// GET: api/SpecialOffers/5
[HttpGet("{id}")]
public async Task<ActionResult<SpecialOffer>> GetSpecialOffer(int id)
{
var specialOffer = await _context.SpecialOffers.FindAsync(id);
if (specialOffer == null)
{
return NotFound();
}
return specialOffer;
}
/// <summary>
/// PUT: api/SpecialOffers/5
/// This method can update SpecialOffers But (SpecialOfferSId,ModifiedBy,ModifiedDate,ModifiedUserId)
/// Will Automatically Updated
/// </summary>
/// <param name="id"></param>
/// <param name="currentTrip"></param>
/// <returns></returns>
[Authorize(Roles = Role.Admin)]
[HttpPut("{id}")]
public async Task<IActionResult> PutSpecialOffer(int id, SpecialOffer specialOffer)
{
var claimsIdentity = this.User.Identity as ClaimsIdentity; // Calling User Data From Users Controller
var Myusername = claimsIdentity.FindFirst(ClaimTypes.Surname)?.Value; // Finding Current User
if (id != specialOffer.SpecialOfferId)
{
return BadRequest();
}
specialOffer.SpecialOfferId = id;
specialOffer.ModifiedUserId = int.Parse(User.Identity.Name); // Auto Update
specialOffer.ModifiedBy = Myusername; // Auto Update
specialOffer.ModifiedDate = DateTime.Now; // Auto Update
_context.Entry(specialOffer).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!SpecialOfferExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
/// <summary>
/// POST: api/SpecialOffers
/// this Method can Insert Record In SpecialOffers, The Admin And Organization Role can Insert Records
/// Visiter has not permition to Insert Data
/// </summary>
/// <param name="currentTrip"></param>
/// <returns></returns>
[Authorize(Roles = "Admin, Organization")]
[HttpPost]
public async Task<ActionResult<SpecialOffer>> PostSpecialOffer(SpecialOffer specialOffer)
{
var claimsIdentity = this.User.Identity as ClaimsIdentity;
var Myusername = claimsIdentity.FindFirst(ClaimTypes.Surname)?.Value;
specialOffer.UserId = int.Parse(User.Identity.Name);
specialOffer.CreatedBy = Myusername;
specialOffer.CreatedDate = DateTime.Now;
_context.SpecialOffers.Add(specialOffer);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSpecialOffer", new { id = specialOffer.SpecialOfferId }, specialOffer);
}
/// <summary>
/// DELETE: api/SpecialOffers/5
/// This is a delete Request. And Only Admin Has the permition to delete from SpecialOffers data
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Authorize(Roles = Role.Admin)]
[HttpDelete("{id}")]
public async Task<ActionResult<SpecialOffer>> DeleteSpecialOffer(int id)
{
var specialOffer = await _context.SpecialOffers.FindAsync(id);
if (specialOffer == null)
{
return NotFound();
}
_context.SpecialOffers.Remove(specialOffer);
await _context.SaveChangesAsync();
return Ok(new
{
Message = "Record Deleted Sucessfully",
Data = specialOffer
});
}
private bool SpecialOfferExists(int id)
{
return _context.SpecialOffers.Any(e => e.SpecialOfferId == id);
}
}
}
|
5b23cf670950beca699b4e97c66ad09fadef7e23
|
C#
|
SACHSTech/cpt-joshua
|
/CPT/MainWindow.xaml.cs
| 2.515625
| 3
|
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace CPT
{
/**
* Class to control the UI
* @author Joshua Shuttleworth
*/
public partial class MainWindow : Window
{
// Creates the dataset and create a new instance of a dataset to be sorted in it
// Creates the table
private Dataset ds = new Dataset();
private Table tb;
// Reads the data from the csv files
public MainWindow()
{
InitializeComponent();
ds.loadGPU();
ds.loadCPU();
}
// Creates custom colors
private SolidColorBrush moreInf = new SolidColorBrush(Color.FromRgb(99, 186, 236));
private SolidColorBrush buttonHighlight = new SolidColorBrush(Color.FromArgb(40, 0, 0, 0));
private bool clickHold = false;
private double gpu_removed = 0;
private double cpu_removed = 0;
/**
* GPU click for more info button controls.
* Hover and left mouse button press.
*/
private void GPU_More_Info_MouseEnter(object sender, MouseEventArgs e)
{
GPU_More_Info.Foreground = Brushes.White;
}
private void GPU_More_Info_MouseLeave(object sender, MouseEventArgs e)
{
GPU_More_Info.Foreground = moreInf;
}
private async void GPU_More_Info_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
clickHold = true;
await Task.Delay(300);
clickHold = false;
}
private void GPU_More_Info_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if(clickHold)
{
GPU_More_Info_Grid.Visibility = Visibility.Visible;
}
}
/**
* CPU click for more info button controls.
* Hover and left mouse button press.
*/
private void CPU_More_Info_MouseEnter(object sender, MouseEventArgs e)
{
CPU_More_Info.Foreground = Brushes.White;
}
private void CPU_More_Info_MouseLeave(object sender, MouseEventArgs e)
{
CPU_More_Info.Foreground = moreInf;
}
private async void CPU_More_Info_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
clickHold = true;
await Task.Delay(300);
clickHold = false;
}
private void CPU_More_Info_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (clickHold)
{
CPU_More_Info_Grid.Visibility = Visibility.Visible;
}
}
/**
* Close button for the application
*/
private void Close_MouseEnter(object sender, MouseEventArgs e)
{
Close.Background = buttonHighlight;
}
private void Close_MouseLeave(object sender, MouseEventArgs e)
{
Close.Background = null;
}
private void Close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
/**
* Minimize button for the application
*/
private void Min_MouseEnter(object sender, MouseEventArgs e)
{
Min.Background = buttonHighlight;
}
private void Min_MouseLeave(object sender, MouseEventArgs e)
{
Min.Background = null;
}
private void Min_MouseDown(object sender, MouseButtonEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
/**
* Allows to window to be draggable when left mouse button is held down
*/
private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
this.DragMove();
}
/**
* Creates and displays a graph that compares the usage percent of each gpu manufactuer
*/
private void GPU_Graph_Loaded(object sender, RoutedEventArgs e)
{
Graph gr = new Graph(241, 134, 1, false);
this.GPU_Graph = gr.DrawGraph(this.GPU_Graph);
double nvidiaPercent = 0.00, amdPercent = 0.00, intelPercent = 0.00, otherPercent = 0.00;
foreach (GPU gpu in ds.getGPUList())
{
string gpuMfg = gpu.getName().Substring(0, 3);
switch (gpuMfg)
{
case "NVI":
nvidiaPercent += gpu.getJulPercent();
break;
case "AMD":
amdPercent += gpu.getJulPercent();
break;
case "Int":
intelPercent += gpu.getJulPercent();
break;
case "Oth":
otherPercent += gpu.getJulPercent();
break;
}
}
gr.AddBar(otherPercent, 30, new SolidColorBrush(Color.FromRgb(0xF9, 0xE0, 0x7F)), 20, "Other", 12, 0, -5);
gr.AddBar(nvidiaPercent, 30, new SolidColorBrush(Color.FromRgb(0x98, 0xb3, 0x54)), 70, "Nvidia", 12, -2, -5);
gr.AddBar(intelPercent, 30, new SolidColorBrush(Color.FromRgb(0x00, 0xBC, 0xB4)), 120, "Intel", 12, 4, -5);
gr.AddBar(amdPercent, 30, new SolidColorBrush(Color.FromRgb(0xD4, 0x6C, 0x4E)), 170, "AMD", 12, 1.5, -5);
}
/**
* Creates and displays a graph that compares the percent of computers that have a certain number of cores
*/
private void CPU_Graph_Loaded(object sender, RoutedEventArgs e)
{
Graph gr2 = new Graph(241, 134, 1, false);
this.CPU_Graph = gr2.DrawGraph(this.CPU_Graph);
double other = 0.00, eight = 0.00, six = 0.00, four = 0.00, two = 0.00;
foreach (CPU cpu in ds.getCPUList())
{
switch (cpu.Cores)
{
case 8:
eight += cpu.Jul;
break;
case 6:
six += cpu.Jul;
break;
case 4:
four += cpu.Jul;
break;
case 2:
two += cpu.Jul;
break;
default:
other += cpu.Jul;
break;
}
}
gr2.AddBar(Math.Round(other / 3, 2), 20, new SolidColorBrush(Color.FromRgb(0xEE, 0xE7, 0xDF)), 20, "Other", 12, -4, -5);
gr2.AddBar(Math.Round(eight / 3, 2), 20, new SolidColorBrush(Color.FromRgb(0x4D, 0x85, 0x81)), 60, "8 core", 12, -6, -5);
gr2.AddBar(Math.Round(six / 3, 2), 20, new SolidColorBrush(Color.FromRgb(0xDB, 0xCB, 0xBE)), 100, "6 core", 12, -6, -5);
gr2.AddBar(Math.Round(four / 3, 2), 20, new SolidColorBrush(Color.FromRgb(0xB0, 0x98, 0x8E)), 140, "4 core", 12, -6, -5);
gr2.AddBar(Math.Round(two / 3, 2), 20, new SolidColorBrush(Color.FromRgb(0xAB, 0xDE, 0xD7)), 180, "2 core", 12, -6, -5);
}
/**
* Loads the tables
*/
private void GPU_More_Info_Grid_Loaded(object sender, RoutedEventArgs e)
{
tb = new Table(580, 3075, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
private void CPU_More_Info_Grid_Loaded(object sender, RoutedEventArgs e)
{
tb = new Table(466, 1550, 1);
this.CPU_StackColumn = tb.loadCPUTable(this.CPU_StackColumn, ds);
}
/**
* Sort Data ID button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_Data_ID_MouseEnter(object sender, MouseEventArgs e)
{
Sort_Data_Highlight.Visibility = Visibility.Visible;
}
private void Sort_Data_ID_MouseLeave(object sender, MouseEventArgs e)
{
Sort_Data_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_Data_ID_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getRanking"); ;
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort Name button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_Name_MouseEnter(object sender, MouseEventArgs e)
{
Sort_Name_Highlight.Visibility = Visibility.Visible;
}
private void Sort_Name_MouseLeave(object sender, MouseEventArgs e)
{
Sort_Name_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_Name_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortStrings(ds.getGPUList(), 0, ds.getGPUSize() - 1);
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort March button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_March_MouseEnter(object sender, MouseEventArgs e)
{
Sort_March_Highlight.Visibility = Visibility.Visible;
}
private void Sort_March_MouseLeave(object sender, MouseEventArgs e)
{
Sort_March_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_March_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getMarPercent");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort April button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_April_MouseEnter(object sender, MouseEventArgs e)
{
Sort_April_Highlight.Visibility = Visibility.Visible;
}
private void Sort_April_MouseLeave(object sender, MouseEventArgs e)
{
Sort_April_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_April_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getAprPercent");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort May button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_May_MouseEnter(object sender, MouseEventArgs e)
{
Sort_May_Highlight.Visibility = Visibility.Visible;
}
private void Sort_May_MouseLeave(object sender, MouseEventArgs e)
{
Sort_May_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_May_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getMayPercent");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort June button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_June_MouseEnter(object sender, MouseEventArgs e)
{
Sort_June_Highlight.Visibility = Visibility.Visible;
}
private void Sort_June_MouseLeave(object sender, MouseEventArgs e)
{
Sort_June_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_June_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getJunPercent");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort July button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_July_MouseEnter(object sender, MouseEventArgs e)
{
Sort_July_Highlight.Visibility = Visibility.Visible;
}
private void Sort_July_MouseLeave(object sender, MouseEventArgs e)
{
Sort_July_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_July_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getJulPercent");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Sort Change button controls.
* On button press the array is sorted and table is re drawn
*/
private void Sort_Change_MouseEnter(object sender, MouseEventArgs e)
{
Sort_Change_Highlight.Visibility = Visibility.Visible;
}
private void Sort_Change_MouseLeave(object sender, MouseEventArgs e)
{
Sort_Change_Highlight.Visibility = Visibility.Hidden;
}
private void Sort_Change_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Sort sort = new Sort();
sort.SortDoubles(ds.getGPUList(), 0, ds.getGPUSize() - 1, "getChange");
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Back button controls for the back button on the GPU tab
* The mouse hover is animated
*/
private async void GPU_Back_MouseEnter(object sender, MouseEventArgs e)
{
// Back_Highlight.Visibility = Visibility.Visible;
GPU_Back_Highlight.Width = 0;
GPU_Back_Highlight.Visibility = Visibility.Visible;
while (GPU_Back_Highlight.Width < 20)
{
GPU_Back_Highlight.Width += 4;
await Task.Delay(10);
}
}
private async void GPU_Back_MouseLeave(object sender, MouseEventArgs e)
{
// Back_Highlight.Visibility = Visibility.Hidden;
while (GPU_Back_Highlight.Width > 0)
{
GPU_Back_Highlight.Width -= 4;
await Task.Delay(10);
}
GPU_Back_Highlight.Visibility = Visibility.Hidden;
}
private async void GPU_Back_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
clickHold = true;
await Task.Delay(300);
clickHold = false;
}
private void GPU_Back_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (clickHold)
{
GPU_More_Info_Grid.Visibility = Visibility.Hidden;
}
}
/**
* Controls for the search bar on the GPU tab
* When the search bar text is changed it removes all the elements from the array that do contain the string
* The table is then re drawn
*/
private async void GPU_Search_bar_TextChanged(object sender, TextChangedEventArgs e)
{
gpu_removed = 0;
if (GPU_Search_bar.Text != "")
{
GPU_Search_label.Visibility = Visibility.Hidden;
ds.loadGPU();
for (int t = 0; t < 10; t++)
{
for (int i = 0; i < ds.getGPUSize(); i++)
{
if (!ds.getGPU(i).getRanking().ToString().Contains(GPU_Search_bar.Text) && ds.getGPU(i).getName().IndexOf(GPU_Search_bar.Text, 0, StringComparison.CurrentCultureIgnoreCase) == -1 && !ds.getGPU(i).getMarPercent().ToString().Contains(GPU_Search_bar.Text) && !ds.getGPU(i).getAprPercent().ToString().Contains(GPU_Search_bar.Text) && !ds.getGPU(i).getMayPercent().ToString().Contains(GPU_Search_bar.Text) && !ds.getGPU(i).getJunPercent().ToString().Contains(GPU_Search_bar.Text) && !ds.getGPU(i).getJulPercent().ToString().Contains(GPU_Search_bar.Text) && !ds.getGPU(i).getChange().ToString().Contains(GPU_Search_bar.Text))
{
ds.removeGPU(ds.getGPU(i));
gpu_removed += 30;
}
}
}
}
else
{
GPU_Search_label.Visibility = Visibility.Visible;
ds.loadGPU();
}
await Task.Delay(300);
tb = new Table(580, 3075 - gpu_removed, 1);
this.StackColumn = tb.loadGPUTable(this.StackColumn, ds);
}
/**
* Back button controls for the back button on the CPU tab
* The mouse hover is animated
*/
private void CPU_Back_MouseEnter(object sender, MouseEventArgs e)
{
CPU_Back_Highlight.Visibility = Visibility.Visible;
}
private void CPU_Back_MouseLeave(object sender, MouseEventArgs e)
{
CPU_Back_Highlight.Visibility = Visibility.Hidden;
}
private async void CPU_Back_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
clickHold = true;
await Task.Delay(300);
clickHold = false;
}
private void CPU_Back_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (clickHold)
{
CPU_More_Info_Grid.Visibility = Visibility.Hidden;
}
}
/**
* Controls for the search bar on the CPU tab
* When the search bar text is changed it removes all the elements from the array that do contain the string
* The table is then re drawn
*/
private async void CPU_Search_bar_TextChanged(object sender, TextChangedEventArgs e)
{
cpu_removed = 0;
if (CPU_Search_bar.Text != "")
{
CPU_Search_label.Visibility = Visibility.Hidden;
ds.loadCPU();
for (int t = 0; t < 10; t++)
{
for (int i = 0; i < ds.getCPUSize(); i++)
{
if (!ds.getCPU(i).Ranking.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).Cores.ToString().Contains(CPU_Search_bar.Text) && ds.getCPU(i).OS.IndexOf(CPU_Search_bar.Text, 0, StringComparison.CurrentCultureIgnoreCase) == -1 && !ds.getCPU(i).Mar.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).Apr.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).May.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).Jun.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).Jul.ToString().Contains(CPU_Search_bar.Text) && !ds.getCPU(i).Change.ToString().Contains(CPU_Search_bar.Text))
{
ds.removeCPU(ds.getCPU(i));
cpu_removed += 30;
}
}
}
}
else
{
CPU_Search_label.Visibility = Visibility.Visible;
ds.loadCPU();
}
await Task.Delay(300);
tb = new Table(466, 1550 - cpu_removed, 1);
this.CPU_StackColumn = tb.loadCPUTable(this.CPU_StackColumn, ds);
}
}
}
|
72ae4b16f80ec8833bb67fc68345920a86617838
|
C#
|
jtrindade/isel-ave-1516-2
|
/aulas/20160505/LINQ.cs
| 3.640625
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class Linq
{
class Student
{
public int Number { get; set; }
public string Name { get; set; }
public bool HasQuit { get; set; }
public int Grade { get; set; }
}
static List<Student> students = new List<Student>()
{
new Student { Number = 1111, Name = "Afonso", HasQuit = false, Grade = 16 },
new Student { Number = 2222, Name = "Sancho", HasQuit = true },
new Student { Number = 3333, Name = "Dinis", HasQuit = false, Grade = 13 },
new Student { Number = 4444, Name = "Pedro", HasQuit = false, Grade = 17 },
new Student { Number = 5555, Name = "Fernando", HasQuit = true },
};
static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items) action(item);
}
static void Show(IEnumerable<Student> data)
{
data.Where(s => !s.HasQuit).OrderBy(s => s.Grade).Select(s => s.Name).ForEach(Console.WriteLine);
}
public static void Main(string[] args)
{
Show(students);
}
}
|
13450308231eab18bdf0b5781e5148cdedfc346d
|
C#
|
robhogo/game-engine
|
/Contexts/Converters/CharacterLvlConverter.cs
| 2.609375
| 3
|
using RoBHo_GameEngine.Contexts.DataModels;
using RoBHo_GameEngine.Models;
using System;
namespace RoBHo_GameEngine.Contexts.Converters
{
public class CharacterLvlConverter : IDataModelConverter<CharacterLvlDataModel, CharacterLvl, LvlType>
{
public CharacterLvl DataModelToModel(CharacterLvlDataModel dataModel)
{
return new CharacterLvl
{
Id = dataModel.Id,
Lvl = dataModel.Lvl,
LvlType = dataModel.LvlType,
CurrentXp = dataModel.CurrentXp
};
}
public CharacterLvlDataModel ModelToDataModel(CharacterLvl model)
{
throw new NotImplementedException();
}
public CharacterLvlDataModel RequestToDataModel(LvlType request)
{
return new CharacterLvlDataModel
{
Lvl = 1,
CurrentXp = 0,
LvlType = request,
};
}
}
}
|
a25cee1760fafe9fd4714883dfcef4e5caf76faa
|
C#
|
shendongnian/download4
|
/latest_version_download2/220445-47971713-163466760-4.cs
| 2.53125
| 3
|
private static ConditionalExpression ExpressionA(int num)
{
return Expression.Condition(
Expression.Constant(num > 10),
Expression.Constant("num is greater than 10"),
Expression.Constant("num is smaller than 10")
);
}
|
d88a53eac30a004b78aa84f54c575851cfb33a4a
|
C#
|
shendongnian/download4
|
/code8/1369521-37062333-117446079-4.cs
| 2.59375
| 3
|
List<String> tableList = serviceMethod.getTableList();
DataTable dtAllType = new DataTable();
foreach (string table in tableList)
{
DataTable dtTemp = new DataTable();
myConnection.Open();
string query = string.Format("SELECT Type, Sum(Expense) AS TotalExpenses FROM [{0}] group by Type", table);
OleDbCommand cmd = new OleDbCommand(query, myConnection);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dtTemp);
myConnection.Close();
dtAllType.Merge(dtTemp);
}
|
9a0e1cb7c864475bae66faef2254ed708bd217d4
|
C#
|
jerryrox/project-beats-framework
|
/Dependencies/InitWithDependencyAttribute.cs
| 2.8125
| 3
|
using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using PBFramework.Exceptions;
namespace PBFramework.Dependencies
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class InitWithDependencyAttribute : Attribute
{
private static BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
/// <summary>
/// Whether null dependency passing is allowed.
/// </summary>
public bool AllowNulls { get; set; }
public InitWithDependencyAttribute(bool allowNulls = false)
{
AllowNulls = allowNulls;
}
/// <summary>
/// Returns the injection handler for method with this attribute on specified type.
/// </summary>
public static TypeInjector.InjectionHandler GetActivator(Type type)
{
var methods = type.GetMethods(Flags).Where(m => m.GetCustomAttribute<InitWithDependencyAttribute>() != null).ToArray();
// The injection for this attribute only supports 1 method.
if(methods.Length == 1)
{
var method = methods[0];
var allowNulls = method.GetCustomAttribute<InitWithDependencyAttribute>().AllowNulls;
var parameters = method.GetParameters().Select(p => p.ParameterType).Select(t => GetParameter(t, type, allowNulls));
return (obj, container) => {
try
{
method.Invoke(obj, parameters.Select(p => p(container)).ToArray());
}
catch(TargetInvocationException e)
{
throw new InitWithDependencyFailedException(type, e.InnerException);
}
};
}
return delegate {};
}
private static Func<IDependencyContainer, object> GetParameter(Type type, Type requestingType, bool allowNulls)
{
return (IDependencyContainer container) => {
var param = container.Get(type);
if(param == null && !allowNulls)
throw new DependencyNotCachedException(type, requestingType);
return param;
};
}
}
}
|
aca5e6b22337fb450859aaa95ae459384fd1ffd3
|
C#
|
shendongnian/download4
|
/code4/627491-53177689-185291458-4.cs
| 3.078125
| 3
|
//Lower level - parts that work differently for sync/async version.
//When isAsync is false there are no await operators and method is running synchronously.
private static async Task Wait(bool isAsync, int milliseconds)
{
if (isAsync)
{
await Task.Delay(milliseconds);
}
else
{
System.Threading.Thread.Sleep(milliseconds);
}
}
//Middle level - the main algorithm.
//When isAsync is false the only awaited method is running synchronously,
//so the whole algorithm is running synchronously.
private async Task<ThirdPartyResult> Execute(bool isAsync, ThirdPartyOptions options)
{
ThirdPartyComponent.Start(options);
await Wait(isAsync, 1000);
return ThirdPartyComponent.GetResult();
}
//Upper level - public synchronous API.
//Internal method runs synchronously and will be already finished when Result property is accessed.
public ThirdPartyResult ExecuteSync(ThirdPartyOptions options)
{
return Execute(false, options).Result;
}
//Upper level - public asynchronous API.
public async Task<ThirdPartyResult> ExecuteAsync(ThirdPartyOptions options)
{
return await Execute(true, options);
}
|
f1097476dd404924363b1c60193cad96bf588e39
|
C#
|
Nitudon/CloudAR_Pet
|
/Assets/CloudPetAR/CloudPet/Pet/PetDefine.cs
| 2.515625
| 3
|
using System;
using CloudPet.Commons;
using UnityEngine;
namespace CloudPet.Pet
{
public struct PetInfo : IEquatable<PetInfo>
{
public string Name;
public PetAvater Avater;
public bool Equals(PetInfo other)
{
return string.Equals(Name, other.Name) && Avater.Equals(other.Avater);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is PetInfo other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Avater.GetHashCode();
}
}
}
public struct PetAvater
{
}
public enum PetState
{
None,
Idle,
Eat,
Play,
}
public static class PetDefine
{
public static readonly string PET_PREFAB_PATH = "PetCharacter";
private static readonly string[] CLIP_PATH =
{
"Pet_Idle",
"Pet_Eat",
"Pet_Play"
};
public static AnimationClip GetPetMotion(PetState state)
{
if (state == PetState.None)
{
Debug.LogError("Invalid Pet State For Animation Clip Resource Loading");
return null;
}
return Resources.Load<AnimationClip>(CLIP_PATH[(int) state + 1]);
}
}
}
|
3437d750f733ce14426442ab9326378826bb7b59
|
C#
|
DeltaTwozero/KingdomFight
|
/Kingdom_Fight/Assets/Script/EnemyManager.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
//Stats
[SerializeField] int meleeDamage, rangedDamage, meleeHP, rangedHP, enemyMeleeCount, enemyMeleeCountMAX, enemyRangedCount, enemyRangedCountMAX;
//Unit list
[SerializeField] List<GameObject> unitList;
//[SerializeField] Mob_Melee melee;
[SerializeField] GameObject spawnPos;
void Start()
{
}
void Update()
{
}
public void SpawnUnits()
{
DamageUp();
HealthUp();
CountUp();
for (int i = 1; i <= enemyMeleeCount; i++)
{
if (i == 1)
{
Mob_Melee melee = unitList[0].GetComponent<Mob_Melee>();
melee.team1 = false;
Instantiate(unitList[0], spawnPos.transform.position, spawnPos.transform.rotation);
}
else
{
Mob_Melee melee = unitList[0].GetComponent<Mob_Melee>();
melee.team1 = false;
Instantiate(unitList[0], new Vector3(spawnPos.transform.position.x + i, spawnPos.transform.position.y, spawnPos.transform.position.z), spawnPos.transform.rotation);
}
print(i);
}
//for (int i = 1; i <= enemyRangedCount; i++)
//{
// if (i == 1)
// Instantiate(unitList[1], spawnPos.transform.position, spawnPos.transform.rotation);
// else
// Instantiate(unitList[1], new Vector3(spawnPos.transform.position.x + i / 2, spawnPos.transform.position.y, spawnPos.transform.position.z), spawnPos.transform.rotation);
// print(i);
//}
}
void DamageUp()
{
Roll();
if (Roll())
{
if (meleeDamage < 100)
meleeDamage += 5;
}
else
{
if(rangedDamage < 50)
rangedDamage += 5;
}
}
void HealthUp()
{
Roll();
if (Roll())
{
if (meleeHP < 100)
meleeHP += 5;
}
else
{
if(rangedHP < 75)
rangedHP += 5;
}
}
void CountUp()
{
Roll();
if (Roll())
{
if (enemyMeleeCount < enemyMeleeCountMAX)
enemyMeleeCount += 1;
}
else
{
if(enemyRangedCount < enemyRangedCountMAX)
enemyRangedCount += 1;
}
}
bool Roll()
{
int roll = Random.Range(0, 2);
bool rollResult;
if (roll == 0)
rollResult = false;
else
rollResult = true;
print(roll);
print(rollResult);
return rollResult;
}
#region Get Melee Stats
public int GetMeleeDamage()
{
return meleeDamage;
}
public int GetMeleeHP()
{
return meleeHP;
}
#endregion
#region Get Ranged Stats
public int GetRangedDamage()
{
return rangedDamage;
}
public int GetRangedHP()
{
return rangedHP;
}
#endregion
}
|
e84afdb799228f3f06ef84e9662e55e60316da70
|
C#
|
harris-boyce/Phema.RabbitMQ
|
/src/Phema.RabbitMQ/Queues/Extensions/RabbitMQQueueBindingBuilderExtensions.cs
| 2.53125
| 3
|
namespace Phema.RabbitMQ
{
public static class RabbitMQQueueBindingBuilderExtensions
{
/// <summary>
/// Declare exchange to exchange routing key
/// </summary>
public static IRabbitMQQueueBindingBuilder RoutedTo(
this IRabbitMQQueueBindingBuilder builder,
string routingKey)
{
builder.Declaration.RoutingKey = routingKey;
return builder;
}
/// <summary>
/// Nowait for exchange to queue declaration
/// </summary>
public static IRabbitMQQueueBindingBuilder NoWait(this IRabbitMQQueueBindingBuilder builder)
{
builder.Declaration.NoWait = true;
return builder;
}
/// <summary>
/// Delete queue binding
/// </summary>
public static IRabbitMQQueueBindingBuilder Deleted(this IRabbitMQQueueBindingBuilder builder)
{
builder.Declaration.Deleted = true;
return builder;
}
/// <summary>
/// Declare RabbitMQ arguments. Allow multiple
/// </summary>
public static IRabbitMQQueueBindingBuilder Argument<TValue>(
this IRabbitMQQueueBindingBuilder builder,
string argument,
TValue value)
{
builder.Declaration.Arguments.Add(argument, value);
return builder;
}
}
}
|
77d2b2ade3c101ae890695e12e1c980fe5f74547
|
C#
|
YULuoOo/ASimpleGame
|
/Scripts/Messenger.cs
| 2.828125
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
internal static class Messenger {
public static Dictionary<GameEvent, Delegate> mEventTable = new Dictionary<GameEvent, Delegate>();
private static bool OnAddListener(GameEvent eventType, Delegate handler)
{
if(!mEventTable.ContainsKey(eventType))
{
mEventTable.Add(eventType, null);
}
Delegate d = mEventTable[eventType];
if(d != null && d.GetType() != handler.GetType())
{
Debug.LogError(eventType+ "加入监听回调与当前监听类型不符合,当前类型为" + d.GetType().Name + "加入类型为" + handler.GetType().Name);
return false;
}
return true;
}
private static bool OnRemoveListener(GameEvent eventType, Delegate handler)
{
if(mEventTable.ContainsKey(eventType))
{
Delegate d = mEventTable[eventType];
if(d == null)
{
Debug.LogError("试图移除" + eventType + ",但当前监听为空");
return false;
}
else if(d.GetType() != handler.GetType())
{
Debug.LogError("试图移除" + eventType + ",与当前类型不符合,当前类型" + d.GetType().Name);
return false;
}
}
else
{
Debug.LogError("Messenger不包含要移除的对象" + eventType);
return false;
}
return true;
}
//添加监听
public static void AddListener(GameEvent eventType, CallBack handler)
{
if(!OnAddListener(eventType,handler))
{
return;
}
mEventTable[eventType] = (CallBack)mEventTable[eventType] + handler;
}
public static void AddListener<T>(GameEvent eventType, CallBack<T> handler)
{
if(!OnAddListener(eventType,handler))
{
return;
}
mEventTable[eventType] = (CallBack<T>)mEventTable[eventType] + handler;
}
//移除监听
public static void RemoveListener(GameEvent eventType, CallBack handler)
{
if(!OnRemoveListener(eventType,handler))
{
return;
}
mEventTable[eventType] = (CallBack)mEventTable[eventType] - handler;
if(mEventTable[eventType] == null)
{
mEventTable.Remove(eventType);
}
}
public static void RemoveListener<T>(GameEvent eventType, CallBack<T> handler)
{
if (!OnRemoveListener(eventType, handler))
{
return;
}
mEventTable[eventType] = (CallBack<T>)mEventTable[eventType] - handler;
if (mEventTable[eventType] == null)
{
mEventTable.Remove(eventType);
}
}
//广播监听
public static void Broadcast(GameEvent eventType)
{
if(!mEventTable.ContainsKey(eventType))
{
return;
}
Delegate d;
if(mEventTable.TryGetValue(eventType,out d))
{
CallBack callback = d as CallBack;
if(callback != null)
{
callback();
}
else
{
Debug.LogError("广播" + eventType + "为空");
}
}
}
public static void Broadcast<T>(GameEvent eventType, T arg1)
{
if (!mEventTable.ContainsKey(eventType))
{
return;
}
Delegate d;
if (mEventTable.TryGetValue(eventType, out d))
{
CallBack<T> callback = d as CallBack<T>;
if (callback != null)
{
callback(arg1);
}
else
{
Debug.LogError("广播" + eventType + "为空");
}
}
}
}
|
c817a84324e88732896667ee2f2e7b68173edd67
|
C#
|
bMedarski/SoftUni
|
/C#/C#Fundamentals/Advanced/Stacks and Queues - Lab/6.MathPotato/Program.cs
| 3.828125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.Hot_Potato
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine().Split(' ');
var step = int.Parse(Console.ReadLine());
var queue = new Queue<string>(input);
var counter = 1;
while (queue.Count > 1)
{
for (int i = 0; i < step - 1; i++)
{
string item = queue.Dequeue();
queue.Enqueue(item);
}
if (!IsPrime(counter))
{
Console.WriteLine("Removed {0}", queue.Dequeue());
counter++;
}
else
{
Console.WriteLine("Prime {0}", queue.Peek());
counter++;
}
}
Console.WriteLine("Last is {0}", queue.Dequeue());
}
public static bool IsPrime(int candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
// Note:
// ... This version was changed to test the square.
// ... Original version tested against the square root.
// ... Also we exclude 1 at the end.
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
}
|
718386b09eafc281ea422591eb34ac1de100c1ae
|
C#
|
shendongnian/download4
|
/code9/1529305-42930683-141342122-2.cs
| 2.625
| 3
|
using System.IO;
using Xbim.Common.Geometry;
using Xbim.Ifc;
using Xbim.ModelGeometry.Scene;
using Xbim.Common.XbimExtensions;
namespace CreateWexBIM
{
class Program
{
static void Main(string[] args)
{
const string file = @"4walls1floorSite.ifc";
var model = IfcStore.Open(file);
var context = new Xbim3DModelContext(model);
context.CreateContext();
var instances = context.ShapeInstances();
foreach (var instance in instances)
{
var geometry = context.ShapeGeometry(instance);
var data = ((IXbimShapeGeometryData)geometry).ShapeData;
using (var stream = new MemoryStream(data))
{
using (var reader = new BinaryReader(stream))
{
var mesh = reader.ReadShapeTriangulation();
}
}
}
}
}
}
|
03d2f5196a366ab1b41241af63096301d5fd7163
|
C#
|
nisbus/propeller.framer
|
/nisbus.Propeller.Frames/H48CFrame.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using nisbus.Propeller.Base;
namespace nisbus.Propeller.Frames
{
/// <summary>
/// A frame to manage the input from a H48C tri-axis accelerometer.
/// See the H48C Pulse.spin program in the spin folder
/// </summary>
public class H48CFrame : AbstractPropellerFrame, IPropellerFrame
{
#region Properties
/// <summary>
/// Gets or sets the X.
/// </summary>
/// <value>The X.</value>
public double X { get; set; }
/// <summary>
/// Gets or sets the Y.
/// </summary>
/// <value>The Y.</value>
public double Y { get; set; }
/// <summary>
/// Gets or sets the Z.
/// </summary>
/// <value>The Z.</value>
public double Z { get; set; }
/// <summary>
/// Gets or sets the V ref.
/// </summary>
/// <value>The V ref.</value>
public double VRef { get; set; }
/// <summary>
/// Gets or sets the theta A.
/// </summary>
/// <value>The theta A.</value>
public double ThetaA { get; set; }
/// <summary>
/// Gets or sets the theta B.
/// </summary>
/// <value>The theta B.</value>
public double ThetaB { get; set; }
/// <summary>
/// Gets or sets the theta C.
/// </summary>
/// <value>The theta C.</value>
public double ThetaC { get; set; }
#endregion
#region Methods
/// <summary>
/// Determines whether an array of bytes represents an H48CFrame.
/// </summary>
/// <param name="buffer">The byte array.</param>
/// <returns>
/// <c>true</c> if the array of bytes matches a H48CFrame; otherwise, <c>false</c>.
/// <seealso cref="nisbus.Propeller.Base.AbstractPropellerFrame"/> for a concrete implementation.
/// </returns>
public bool IsFrameType(byte[] buffer)
{
return base.IsFrameType(buffer, @"VREF=-*\d*X=-*\d*Y=-*\d*Z=-*\d*ThetaA=-*\d*ThetaB=-*\d*ThetaC=-*\d* \r");
}
/// <summary>
/// Returns a new H48CFrame.
/// </summary>
/// <param name="buffer">The byte array to process into a H48CFrame.</param>
/// <returns>A H48CFrame</returns>
public IPropellerFrame GetFrame(byte[] buffer)
{
if (IsFrameType(buffer))
{
var strings = base.DecodeBufferToString(buffer).Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
return new H48CFrame
{
VRef = double.Parse(strings[1].Substring(0, strings[1].IndexOf("X")),CultureInfo.InvariantCulture),
X = double.Parse(strings[2].Substring(0, strings[2].IndexOf("Y")), CultureInfo.InvariantCulture),
Y = double.Parse(strings[3].Substring(0, strings[3].IndexOf("Z")), CultureInfo.InvariantCulture),
Z = double.Parse(strings[4].Substring(0, strings[4].IndexOf("ThetaA")), CultureInfo.InvariantCulture),
ThetaA = double.Parse(strings[5].Substring(0, strings[5].IndexOf("ThetaB")), CultureInfo.InvariantCulture),
ThetaB = double.Parse(strings[6].Substring(0, strings[6].IndexOf("ThetaC")), CultureInfo.InvariantCulture),
ThetaC = double.Parse(strings[7], CultureInfo.InvariantCulture)
};
}
else
throw new ArgumentException("buffer does not match frame type");
}
#endregion
public override string ToString()
{
return string.Format("X {0}, Y {1}, Z {2}, Theta A {3}, Theta B {4}, Theta C {5}. (VREF {6})",this.X,this.Y, this.Z, this.ThetaA, this.ThetaB, this.ThetaC, this.VRef);
}
}
}
|
05fe2e987c8f9ada96f1ac64116b2c06a4e6cccd
|
C#
|
toxicgorilla/MondoAspNetMvcSample
|
/ViewModels/Accounts/ViewModels.cs
| 2.671875
| 3
|
namespace MondoAspNetMvcSample.ViewModels.Accounts
{
using System;
using System.Collections.Generic;
using MondoAspNetMvcSample.App_Classes;
public class AccountViewModelBase : ViewModelBase
{
public AccountViewModelBase()
{
this.SiteSection = SiteSection.Accounts;
}
}
public sealed class IndexViewModel : AccountViewModelBase
{
#region Constructor
public IndexViewModel(bool hasAccessToken)
{
this.HasAccessToken = hasAccessToken;
this.AccountSummaries = new List<AccountSummary>();
}
#endregion
#region Properties
public bool HasAccessToken { get; private set; }
public List<AccountSummary> AccountSummaries { get; }
#endregion
#region Methods
public void AddAccountSummary(AccountSummary accountSummary)
{
this.AccountSummaries.Add(accountSummary);
}
#endregion
#region Classes
public class AccountSummary
{
public AccountSummary(string id, DateTime createdDate, string description, string currencyCode, decimal balance)
{
this.Id = id;
this.CreatedDate = createdDate;
this.Description = description;
this.CurrencyCode = currencyCode;
this.Balance = balance;
}
public string Id { get; private set; }
public DateTime CreatedDate { get; private set; }
public string Description { get; private set; }
public string CurrencyCode { get; private set; }
public decimal Balance { get; private set; }
}
#endregion
}
public sealed class DetailViewModel : AccountViewModelBase
{
public DetailViewModel(string id, string currency, long balance)
{
this.Id = id;
this.Currency = currency;
this.Balance = balance;
this.Transactions = new List<TransactionViewModel>();
}
public string Id { get; private set; }
public string Currency { get; private set; }
public long Balance { get; private set; }
public IList<TransactionViewModel> Transactions { get; }
public void AddTransaction(TransactionViewModel transactionViewModel)
{
this.Transactions.Add(transactionViewModel);
}
#region Classes
public sealed class TransactionViewModel
{
public TransactionViewModel(string id, DateTime created, string currency, long amount, long accountBalance, string notes)
{
this.Id = id;
this.Created = created;
this.Currency = currency;
this.Amount = amount;
this.AccountBalance = accountBalance;
this.Notes = notes;
}
public string Id { get; private set; }
public DateTime Created { get; private set; }
public string Currency { get; private set; }
public long Amount { get; private set; }
public long AccountBalance { get; private set; }
public string Notes { get; private set; }
}
#endregion
}
}
|
f60bdbb52e0c9d81046028a929ed1f86ed880a70
|
C#
|
AreTrash/MasterFromExcel
|
/Assets/MasterSample/Data/AaaaData.cs
| 2.53125
| 3
|
/////////////////////////////////////////////////
//自動生成ファイルです!直接編集しないでください!//
/////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Master
{
public class AaaaData : ScriptableObject
{
public List<Aaaa> Data = new List<Aaaa>();
}
[Serializable]
public class Aaaa
{
public AaaaKey Key;
public int Arg;
public string Effect;
public float FloatTest;
public double DoubleTest;
public bool BoolTest;
public string[] ArrayStringTest;
public int[] ArrayIntTest;
public TestEnum TestEnum;
}
public interface IAaaaDao
{
IEnumerable<Aaaa> GetAll();
Aaaa Get(AaaaKey key);
}
public class AaaaDao : IAaaaDao
{
readonly Dictionary<AaaaKey, Aaaa> dataDic;
public AaaaDao()
{
var AaaaObject = Resources.Load<AaaaData>("MasterSample/Aaaa.asset");
dataDic = AaaaObject.Data.ToDictionary(d => d.Key);
Resources.UnloadAsset(AaaaObject);
}
public IEnumerable<Aaaa> GetAll()
{
return dataDic.Values;
}
public Aaaa Get(AaaaKey key)
{
return dataDic.ContainsKey(key) ? dataDic[key] : null;
}
}
}
|
79b848a15666b40a48d94efa3976b603c74e157b
|
C#
|
jgomezmnm/LinqJoinLab
|
/LinqCycles/LoggingEnumerator.cs
| 3.109375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace LinqCycles
{
public class LoggingEnumerator<T> : IEnumerator<T>
{
private readonly IEnumerator<T> _enumerator;
private readonly Action<string> _log;
public LoggingEnumerator(IEnumerator<T> enumerator, Action<string> log)
{
_enumerator = enumerator;
_log = log;
}
public void Dispose()
{
_log("Dispose");
_enumerator.Dispose();
}
public bool MoveNext()
{
_log("MoveNext");
return _enumerator.MoveNext();
}
public void Reset()
{
_log("Reset");
_enumerator.Reset();
}
public T Current
{
get
{
_log("get_Current");
return _enumerator.Current;
}
}
object IEnumerator.Current
{
get { return Current; }
}
}
}
|
3b5ad32040dbddc35a754c4189ae5bb3d40fab3c
|
C#
|
PedroMorenoTrujillo/tryDotNetProjectWithSqlServer
|
/Aplicacion/Cursos/Eliminar.cs
| 2.78125
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Persistencia;
namespace Aplicacion.Cursos
{
public class Eliminar
{
public class Ejecuta : IRequest{
public int Id { get; set; }
}
public class Manejador : IRequestHandler<Ejecuta>
{
private readonly CursosOnlineContext _context;
public Manejador(CursosOnlineContext context){
_context = context;
}
public async Task<Unit> Handle(Ejecuta request, CancellationToken cancellationToken)
{
var curso = await _context.Curso.FindAsync(request.Id);
if(curso==null){
throw new Exception("No se puede eliminar el Curso");
}
_context.Remove(curso);
var resultado = await _context.SaveChangesAsync();
if(resultado>0){
return Unit.Value;
}
throw new Exception("No se pudieron guardar los cambios");
}
}
}
}
|
812b906c70dd33c76589d88f973f7b0c6c577a9a
|
C#
|
TheSteveIAm/AdventOfCode-2018
|
/AdventOfCode/Solutions/Day8.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AdventOfCode
{
class Node
{
public int nodeId;
public int childrenCount;
public int metaDataCount;
public List<Node> children;
public List<int> metaData;
public Node parent;
//public int nodeValue;
public Node()
{
children = new List<Node>();
metaData = new List<int>();
}
public int CalcValue()
{
int value = 0;
if (childrenCount > 0)
{
//Console.WriteLine("Node: )F
for (int i = 0; i < metaDataCount; i++)
{
if (metaData[i] > 0 && metaData[i] <= childrenCount)
{
int reference = metaData[i] - 1;
value += children[reference].CalcValue();
}
}
}
else
{
value = metaData.Sum();
}
return value;
}
}
class Day8
{
private string path = "../../Input/input8.txt";
bool parsed = false;
string line;
Queue<int> inputQueue = new Queue<int>();
List<Node> nodeTree = new List<Node>();
int metaDataSum = 0;
int rootValue = 0;
private void ParseInput(string path)
{
if (parsed)
return;
StreamReader reader = new StreamReader(path);
while ((line = reader.ReadLine()) != null)
{
string[] stringSplit = line.Split(' ').ToArray();
for (int i = 0; i < stringSplit.Length; i++)
{
inputQueue.Enqueue(int.Parse(stringSplit[i]));
}
}
reader.Close();
parsed = true;
}
public void GetAnswerA()
{
Console.WriteLine("Answer A: ");
ParseInput(path);
Node currentNode, childNode;
//create root node
currentNode = new Node()
{
childrenCount = inputQueue.Dequeue(),
metaDataCount = inputQueue.Dequeue(),
nodeId = nodeTree.Count
};
nodeTree.Add(currentNode);
while (inputQueue.Count > 1)
{
while (currentNode.children.Count < currentNode.childrenCount)
{
childNode = new Node()
{
childrenCount = inputQueue.Dequeue(),
metaDataCount = inputQueue.Dequeue(),
parent = currentNode,
nodeId = nodeTree.Count
};
nodeTree.Add(childNode);
currentNode.children.Add(childNode);
currentNode = childNode;
}
if (currentNode.metaDataCount > currentNode.metaData.Count)
{
for (int i = 0; i < currentNode.metaDataCount; i++)
{
int metaData = inputQueue.Dequeue();
metaDataSum += metaData;
currentNode.metaData.Add(metaData);
}
}
currentNode = currentNode.parent;
}
Console.WriteLine(metaDataSum);
}
public void GetAnswerB()
{
Console.WriteLine("Answer B: ");
rootValue = nodeTree[0].CalcValue();
Console.WriteLine(rootValue);
}
}
}
|