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
|
|---|---|---|---|---|---|---|
2e859831b22671cb84193d7a8ea7b4d9cd065c0c
|
C#
|
noahbearx3/DuctTape-Dungeon
|
/Assets/Scripts/UI/CurrentWeapon.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CurrentWeapon : MonoBehaviour
{
// Sprites to be added in editor
public Sprite pistolSprite;
public Sprite ak47Sprite;
public Sprite shottieSprite;
// GameObject holding script to be added in inspector in order to access current weapon
public CrosshairAimPlusShoot bools;
public PlayerController items;
// Booleans to access the current weapon to display on the UI
private bool pistolUI;
private bool ak47UI;
private bool shotgunUI;
public Image img;
// Start is called before the first frame update
void Start()
{
// Get image component in order to change UI
img = GetComponent<Image>();
}
// Update is called once per frame
void Update()
{
//Call CheckWeapon Function once per frame
checkWeapon();
}
//Function is used to check current weapon
void checkWeapon(){
// Call the CrossHairAimPlusShoot script once per frame to check the booleans state constantly to see current weapon
pistolUI = bools.pistol;
ak47UI = bools.ak47;
shotgunUI = bools.shotgun;
//If functions used to check current weapon and then change sprite depending on weapon state
if(pistolUI == true && ak47UI == false && shotgunUI == false){
img.sprite = pistolSprite;
}
if(pistolUI == false && ak47UI == true && shotgunUI == false){
img.sprite = ak47Sprite;
}
if(pistolUI == false && ak47UI == false && shotgunUI == true){
img.sprite = shottieSprite;
}
}
}
|
b4b6b0cbff6237f3ecb3846184e02f1b1ba6ecc7
|
C#
|
KrotovTeam/Project
|
/WebUI/BusinessLogic.Managers/DrawManager.cs
| 2.953125
| 3
|
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using BusinessLogic.Abstraction;
using BusinessLogic.Dtos;
using Common.Constants;
namespace BusinessLogic.Managers
{
/// <summary>
/// Менеджер для отображения результатов
/// </summary>
public class DrawManager : IDrawManager
{
/// <summary>
/// Отображение динамики
/// </summary>
/// <param name="points">Точки</param>
/// <param name="pathFile">Путь к файлу</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void DrawDinamics(IList<ResultingPoint> boundaryPoints, IList<ClusterPoint> clusterPoints, string pathFile, int width, int height)
{
using (var bitmap = new Bitmap(width, height))
{
foreach (var point in clusterPoints)
{
var operand1 = point.Values[ChannelEnum.Channel5] - point.Values[ChannelEnum.Channel4];
var operand2 = point.Values[ChannelEnum.Channel5] + point.Values[ChannelEnum.Channel4];
var ndvi = operand1 / operand2;
var color = GetColorForNdvi(ndvi);
bitmap.SetPixel((int)point.Latitude, (int)point.Longitude, color);
}
var graphics = Graphics.FromImage(bitmap);
foreach (var point in boundaryPoints)
{
graphics.FillRectangle(Brushes.Red, new Rectangle
{
X = point.Values[CoordinateSystemEnum.Latitude],
Y = point.Values[CoordinateSystemEnum.Longitude],
Height = 4,
Width = 4
});
//bitmap.SetPixel(point.Values[CoordinateSystemEnum.Latitude], point.Values[CoordinateSystemEnum.Longitude]);
}
bitmap.Save(pathFile, ImageFormat.Bmp);
}
}
/// <summary>
/// Отображение обработанного снимка
/// </summary>
/// <param name="points">Точки</param>
/// <param name="pathFile">Путь к файлу</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public void DrawProcessedSnapshot(IList<ClusterPoint> points, string pathFile, int width, int height)
{
using (var bitmap = new Bitmap(width, height))
{
foreach (var point in points)
{
var operand1 = point.Values[ChannelEnum.Channel5] - point.Values[ChannelEnum.Channel4];
var operand2 = point.Values[ChannelEnum.Channel5] + point.Values[ChannelEnum.Channel4];
var ndvi = operand1/operand2;
var color = GetColorForNdvi(ndvi);
bitmap.SetPixel((int)point.Latitude, (int)point.Longitude, color);
}
bitmap.Save(pathFile, ImageFormat.Bmp);
}
}
/// <summary>
/// Определние цвета точки по значени ndvi
/// </summary>
/// <param name="ndvi">Значение NDVI</param>
/// <returns></returns>
private Color GetColorForNdvi(double ndvi)
{
Color color = new Color();
if (ndvi >= 0.9)
{
color = Color.FromArgb(0x001100);
}
else if (ndvi >= 0.8)
{
color = Color.FromArgb(0x002000);
}
else if (ndvi >= 0.7)
{
color = Color.FromArgb(0x003000);
}
else if (ndvi >= 0.6)
{
color = Color.FromArgb(0x003500);
}
else if (ndvi >= 0.5)
{
color = Color.FromArgb(0x004000);
}
else if (ndvi >= 0.4)
{
color = Color.FromArgb(005000);
}
else if (ndvi >= 0.3)
{
color = Color.FromArgb(0x428c02);
}
else if (ndvi >= 0.2)
{
color = Color.FromArgb(0x72ba14);
}
else if (ndvi >= 0.1)
{
color = Color.FromArgb(0x875b28);
}
else if (ndvi >= 0.0)
{
color = Color.FromArgb(0xe5dcd3);
}
else if (ndvi >= -1)
{
color = Color.FromArgb(0x030a33);
}
return color;
}
}
}
|
6e32a337b1acd16634c26dd2b8ea8cee0d57444e
|
C#
|
kcmollhagen/Lab-1-Part-1
|
/Lab 1 Part 1/Program.cs
| 4
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Numbers
{
class Program
{
static void Main(string[] args)
{
//ask for and read input to assign to variables
Console.WriteLine("Input a three digit number");
int num1 = int.Parse(Console.ReadLine());
int a1 = num1 / 100;
int a2 = (num1 / 10) % 10;
int a3 = num1 % 10;
Console.WriteLine("Input another three digit number");
int num2 = int.Parse(Console.ReadLine());
int b1 = num2 / 100;
int b2 = (num2 / 10) % 10;
int b3 = num2 % 10;
Console.WriteLine(CheckSums(a1, a2, a3, b1, b2, b3));
Console.ReadKey();
}
public static bool CheckSums(int a1, int a2, int a3, int b1, int b2, int b3)
{
int asum = a1 + b1;
int bsum = a2 + b2;
int csum = a3 + b3;
if (asum == bsum && bsum == csum)
return true;
else
return false;
}
}
}
|
97be22990050a1939191cfa0c3508add76ea089f
|
C#
|
matthewzar/metaphor-world-msc-thesis
|
/CSMetaphorWorld/CSMetaphorWorld/CSMetaphorWorld/Logical API classes/Variable.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSMetaphorWorld
{
public class Variable
{
public string name;
public string type;
int address; // a tuple like this -> (frameNo, frameVarNo, memAddrress) might be more usefull. Leaving it as an int for simcity right now
Value varsValue;
bool hexMemMode = false;
public Variable(string varType, string varName, int varAddress, string defaultValue = "")
{
//checking legality of various paramters
name = varName;
type = varType;
address = varAddress;
//if the defaultValue was left out try and figure it out based on the type, if you can't then leave it blank or make it null
#region defaultValue Evaluation (potentially a pointless parameter as VS does not allow unnassigned variable to be used);
if (defaultValue == "") //default values might
{
switch(type.ToLower())
{
case ("int"): case ("int16"): case ("int32"): case ("int64"):
case ("uint"): case ("uint16"): case ("uint32"): case ("uint64"):
case ("sbyte"): case ("byte"): case ("ushort"): case ("short"):
case ("long"): case ("ulong"):
{
defaultValue = "0";
break;
}
case ("float"): case ("double"):
{
defaultValue = "0.0";
break;
}
case ("bool"): case ("boolean"):
{
defaultValue = "false";
break;
}
default:
{
defaultValue = "null";
break;
}
}
}
#endregion
varsValue = new Value(defaultValue, varType, name);
}
public string readOrigin()
{
return varsValue.readOrigin();
}
public int getAddress()
{
return address;
}
public Variable(string varName, int varAddress, Value varValue)
{
name = varName;
type = varValue.readType();
address = varAddress;
varsValue = varValue;
}
public string read()
{
return varsValue.read();
}
public string readType()
{
//checking for consistency
//either the types are the same OR the one is a reference and the value is an int
//TODO: consider throwing an exceptions no matter what if the type don't match
if (varsValue.readType() != type)
{
//Is it something other than a reference type?
if (!type.ToLower().Contains("ptr") &&
!type.ToLower().Contains("pointer") &&
!type.ToLower().Contains("ref") &&
!type.ToLower().Contains("$") &&
!type.ToLower().Contains("*"))
throw new Exception(string.Format("The values type({0}) and the variables type{1} do not match", varsValue.readType(), type));
else
{
//TODO ensure that if the values type is not int that it still gets flagged as bad (memory shouldnt be refered to by anything except integers)
if (varsValue.readType().ToLower() == "int")
{
Console.WriteLine("The value contained in variable {0} is of type {1} (should be int), while the variable is a reference type ({2})", name, varsValue.readType(), type);
Console.WriteLine("This is acceptable only because references are numbers/addresses but we thought you should know just in case");
Console.WriteLine("we're going to cast it to a reference type");
varsValue = new Value(varsValue.read(), type, varsValue.readOrigin());
return type;
}
else
throw new Exception(string.Format("The values type({0}) and the variables type{1} do not match", varsValue.readType(), type));
}
}
//TODO decide whether to return values type or the variables type (which are usually the same)...or maybe return the values type when the variable IS NOT a reference
return varsValue.readType();//this allows the user to read the type of the value not the type of the variable
//the only time varsValue.readType() should deviate from the variables type is when the variable is a reference
}
public void consoleWriteContent()
{ //address int x -> 9
Console.WriteLine("{0}\t\t{1} {2} -> {3}",address.ToString(),type,name,varsValue.read());
}
public override string ToString()
{
if(hexMemMode)
return string.Format("Addr::{0} ({1}) {2} <- {3}", Calculator.intToHex(address), type, name, varsValue.read());
else
return string.Format("Addr::{0} ({1}) {2} <- {3}", address.ToString(), type, name, varsValue.read());
}
public void assignNewValue(Value newVal)
{
varsValue = newVal;
}
}
}
|
b609f4e7fcc59f80807eaa29dd3f5a951e3de9e2
|
C#
|
Suremaker/CodeBuilder
|
/CodeBuilder/Expressions/ValueTypePointerExpression.cs
| 2.59375
| 3
|
using System;
using System.Reflection.Emit;
using CodeBuilder.Context;
using CodeBuilder.Helpers;
namespace CodeBuilder.Expressions
{
public class ValueTypePointerExpression : Expression
{
private readonly Expression _expression;
internal ValueTypePointerExpression(Expression expression)
: base(Validators.NullCheck(expression, "expression").ExpressionType)
{
if (!expression.ExpressionType.IsValueType)
throw new ArgumentException("Expression has to be of value type");
_expression = expression;
}
internal override void Compile(IBuildContext ctx, int expressionId)
{
ctx.Compile(_expression);
var local = ctx.Generator.DeclareLocal(_expression.ExpressionType);
ctx.Generator.Emit(OpCodes.Stloc, local);
ctx.Generator.Emit(OpCodes.Ldloca, local);
}
internal override CodeBlock WriteDebugCode(IMethodSymbolGenerator symbolGenerator)
{
return symbolGenerator.GetCurrentPosition().BlockTo(symbolGenerator.Write(_expression).GetCurrentPosition());
}
protected override Expression ReturnCallableForm()
{
return this;
}
}
}
|
530e1740b651bb39b7d10e19544ea2c39ecc8a24
|
C#
|
hello-web/Neuroph.NET
|
/Neuroph/imgrec/filter/ImageFilterChain.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
namespace org.neuroph.imgrec.filter
{
/// <summary>
/// Process images by applying all filters in chain
/// @author Sanja
/// </summary>
[Serializable]
public class ImageFilterChain : ImageFilter
{
private List<ImageFilter> filters = new List<ImageFilter>();
private string chainName;
/// <summary>
/// Add filter to chain </summary>
/// <param name="filter"> filter to be added </param>
public virtual void addFilter(ImageFilter filter)
{
filters.Add(filter);
}
/// <summary>
/// Remove filter from chain </summary>
/// <param name="filter"> filter to be removed </param>
/// <returns> true if filter is removed </returns>
public virtual bool removeFilter(ImageFilter filter)
{
return filters.Remove(filter);
}
/// <summary>
/// Apply all filters from a chain on image </summary>
/// <param name="image"> image to process </param>
/// <returns> processed image </returns>
public virtual BufferedImage processImage(BufferedImage image)
{
BufferedImage tempImage = image;
foreach (ImageFilter filter in filters)
{
BufferedImage filteredImage = filter.processImage(tempImage);
tempImage = filteredImage;
}
return tempImage;
}
/// <summary>
/// Returns images of all stages in processing
/// Used for testing </summary>
/// <param name="image"> </param>
/// <returns> </returns>
public virtual List<FilteredImage> processImageTest(BufferedImage image)
{
List<FilteredImage> list = new List<FilteredImage>();
BufferedImage tempImage = image;
foreach (ImageFilter filter in filters)
{
BufferedImage processedImage = filter.processImage(tempImage);
string filterName = filter.ToString();
FilteredImage filteredImage = new FilteredImage(processedImage,filterName);
list.Add(filteredImage);
tempImage = processedImage;
}
return list;
}
/// <summary>
/// Get filters from chain </summary>
/// <returns> </returns>
public virtual List<ImageFilter> Filters
{
get
{
return filters;
}
set
{
this.filters = value;
}
}
public virtual string ChainName
{
get
{
return chainName;
}
set
{
this.chainName = value;
}
}
public override string ToString()
{
return chainName;
}
}
}
|
f7bc5703ed745bc102846c4dd96e01789afd8d13
|
C#
|
sbelenki/GmailProxy
|
/MyGoogleApi/Utils.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyGoogleApi
{
public class Utils
{
public static string MakeValidFileName(string fileName)
{
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach (var cur in fileName)
{
if (!invalid.Contains(cur))
{
builder.Append(cur);
}
}
return builder.ToString();
}
public static string DecodeBase64URLSafe(string input)
{
// TODO: use FromBase64ForUrlString from http://stackoverflow.com/questions/24779138/can-we-access-gmail-api-using-service-account
string codedBody = input.Replace("-", "+").Replace('_', '/');
byte[] data = Convert.FromBase64String(codedBody);
return Encoding.UTF8.GetString(data);
}
}
}
|
58d501c93186b389bdb9a215bb54d5b8ba30c846
|
C#
|
jasarsoft/ipcs-primjeri
|
/ipcs_12/vjezba01/IPCS_12-V1/Program.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace IPCS_12_V1
{
class Program
{
static void Main(string[] args)
{
//ulazni podaci
int vehicleCode = 1;
int speed = 30;
String[] vehicle = { "truck", "bus", "car" };
if (vehicle[vehicleCode] != "car")
{
switch (speed)
{
//RJESENJE 1
//case 10:
// Console.WriteLine(vehicle[vehicleCode] + " speed is 10");
// break;
//case 20:
// Console.WriteLine(vehicle[vehicleCode] + " speed is 20");
// break;
//case 30:
// Console.WriteLine(vehicle[vehicleCode] + " speed is 30");
// break;
//default:
// Console.WriteLine(vehicle[vehicleCode] + " speed is not 10, 20 or 30");
// break;
//RJESENJE 2
case 10:
case 20:
case 30:
Console.WriteLine(vehicle[vehicleCode] + " speed is " + speed);
break;
default:
Console.WriteLine(vehicle[vehicleCode] + " is not 10, 20 or 30");
break;
}
}
}
}
}
|
fe8c4138280fe168dd6768b8874b4da5b08c6571
|
C#
|
bgfa26/HPSCAdmin
|
/AdminSite/src/adminsite/adminsite/common/entities/Statistic.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace adminsite.common.entities
{
public class Statistic : IEquatable<Statistic>
{
public string title { get; set; }
public double value { get; set; }
public Statistic(string title, double value)
{
this.title = title;
this.value = value;
}
public bool Equals(Statistic other)
{
return this.title.Equals(other.title);
}
}
}
|
81243c409240c2e11912a8ff4906566e2fda1c89
|
C#
|
k-payl/Runner
|
/Assets/Scripts/LevelGeneration/Track3.cs
| 2.625
| 3
|
using System;
using LevelGeneration;
using UnityEngine;
using System.Collections;
namespace GamePlay
{
[Serializable]
public class TrackLine
{
public float XCoord;
public TrackLine(float x)
{
XCoord = x;
}
}
public class Track3 : TrackAbstract
{
public override float LineWidth
{
get { return lineWidth; }
set
{
lineWidth = value;
if ( lines == null )
lines = new[] { new TrackLine(-lineWidth), new TrackLine(0f), new TrackLine(lineWidth) };
else
{
lines[0].XCoord = -lineWidth;
lines[1].XCoord = 0f;
lines[2].XCoord = lineWidth;
}
}
}
public float CurrentXCoord
{
get { return XCoordOfLine(currentLine); }
}
private int currentLine;
[SerializeField] private TrackLine[] lines;
[SerializeField] private float lineWidth = 2.5f;
public float XCoordOfLine(int lineNumber)
{
if(lineNumber >= 0 && lineNumber < lines.Length)
return lines[lineNumber].XCoord + collider.bounds.center.x;
else
{
throw new ArgumentOutOfRangeException();
}
}
public override bool Turn(TurnDirection direction)
{
bool f = false;
switch(direction)
{
case TurnDirection.Left:
if (currentLine > 0)
{
currentLine--;
f = true;
}
break;
case TurnDirection.Right:
if (currentLine < lines.Length - 1)
{
currentLine++;
f = true;
}
break;
default:
throw new ArgumentOutOfRangeException("direction");
}
return f;
}
public override float MaxX()
{
float x = (lines.Length > 0) ? XCoordOfLine(lines.Length - 1) : transform.position.x;
return x;
}
public override float MinX()
{
return XCoordOfLine(0);
}
public override void CalculateTrackState(Vector3 pointAtTrack)
{
float x = pointAtTrack.x;
float d1 = Mathf.Abs(x - XCoordOfLine(0));
float d2 = Mathf.Abs(x - XCoordOfLine(1));
float d3 = Mathf.Abs(x - XCoordOfLine(2));
byte i = 0;
float min = d1;
if (d2 < d1) {i = 1;min = d2;}
if (d3 < min)i = 2;
currentLine = i;
}
protected override void Awake()
{
base.Awake();
LineWidth = lineWidth;
}
#if UNITY_EDITOR
protected override void OnDrawGizmos()
{
Vector3 startPoint = new Vector3(0, collider.bounds.max.y, collider.bounds.min.z);
Vector3 ednPoint = new Vector3(0, collider.bounds.max.y, collider.bounds.max.z);
Gizmos.color = Color.red;
for(int i = 0; i < lines.Length; i++)
{
Gizmos.DrawLine(startPoint + new Vector3(XCoordOfLine(i), 0f, 0),
ednPoint + new Vector3(XCoordOfLine(i), 0.01f, 0));
}
}
#endif
public static string[] LinesLiteralPresenation = new[] { "first", "second", "third" };
}
}
|
661585cd5750b7410bf80a949b307fcf258a843d
|
C#
|
RhysWareham/Unity-Maze-Game
|
/Simple Maze/Assets/Scripts/RedLockedDoorScript.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedLockedDoorScript : MonoBehaviour {
public GameObject door;
public GameObject accessToKeyScript;
public RedKeyScript script;
private bool mouseOver = false;
public bool keyPickedUp;
private bool moveDoor = false;
// Use this for initialization
void Start ()
{
//Gives the variable script, access to variables from RedKeyScript
script = accessToKeyScript.GetComponent<RedKeyScript>();
}
// Update is called once per frame
void Update ()
{
//Sets keyPickedUp to the value of keyObtained from RedKeyScript
keyPickedUp = script.keyObtained;
//If moveDoor is true and the translation Y axis value for door is less than 60...
if (moveDoor == true && door.GetComponent<Transform>().position.y < 60)
{
//...the door will slowly move upwards
door.transform.Translate(Vector3.up * 5 * Time.deltaTime, Space.Self);
}
}
//If the mouse is over the door, set mouseOver to true
void OnMouseOver()
{
mouseOver = true;
}
//If the mouse is not over the door, set mouseOver to false
void OnMouseExit()
{
mouseOver = false;
}
//If the mouse button has been clicked...
void OnMouseDown()
{
//...check if keyPickedUp is true
if (keyPickedUp == true)
{
//If so, set moveDoor to true
moveDoor = true;
}
}
//Function for pop up text hints
void OnGUI()
{
//If mouseOver is true and keyPickedUp is false...
if (mouseOver == true && keyPickedUp == false)
{
//...create a textbox which reads "Find The Red Key"
GUI.Box(
new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Find The Red Key");
}
//If mouseOver is true and keyPickedUp is true...
else if (mouseOver == true && keyPickedUp == true)
{
//...create a textbox which reads "Click To Interact"
GUI.Box(
new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Click To Interact");
}
}
}
|
b06c9fef8b7107856cbfa67babe92c25cea5d3b9
|
C#
|
omarvision/AI-car-drive-on-racetrack
|
/Checkpoint.cs
| 2.578125
| 3
|
using UnityEngine;
public class Checkpoints : MonoBehaviour
{
public Vector3 WallSize = new Vector3(1, 1, 1);
private void OnDrawGizmos()
{
if (this.transform.childCount < 2)
return;
//draw line between each of the checkpoints
for (int i = 0; i < this.transform.childCount - 1; i++)
{
Gizmos.color = Color.yellow;
Gizmos.DrawLine(this.transform.GetChild(i).position, this.transform.GetChild(i + 1).position);
}
//last line is red
Gizmos.color = Color.red;
Gizmos.DrawLine(this.transform.GetChild(this.transform.childCount - 1).position, this.transform.GetChild(0).position);
}
public void AngleSizeCheckpointWalls()
{
Transform currCheckpoint;
Transform nextCheckpoint;
Transform prevCheckpoint;
int next;
int prev;
Quaternion currRotation;
Quaternion prevRotation;
for (int i = 0; i < this.transform.childCount; i++)
{
next = idxNextCheckpoint(i);
prev = idxPrevCheckpoint(i);
//surrounding checkpoints
currCheckpoint = this.transform.GetChild(i);
nextCheckpoint = this.transform.GetChild(next);
prevCheckpoint = this.transform.GetChild(prev);
//wallsize
currCheckpoint.localScale = WallSize;
//angles to surrounding checkpoints
currCheckpoint.LookAt(nextCheckpoint);
currRotation = new Quaternion(currCheckpoint.transform.rotation.x, currCheckpoint.transform.rotation.y, currCheckpoint.transform.rotation.z, currCheckpoint.transform.rotation.w);
currCheckpoint.LookAt(prevCheckpoint);
prevRotation = new Quaternion(prevCheckpoint.transform.rotation.x, prevCheckpoint.transform.rotation.y, prevCheckpoint.transform.rotation.z, prevCheckpoint.transform.rotation.w);
//set checkpoint to smooth angle between surrounding checkpoints
currCheckpoint.transform.rotation = Quaternion.Lerp(currRotation, prevRotation, 0.5f);
}
}
private int idxNextCheckpoint(int i)
{
if (i < this.transform.childCount - 1)
return i + 1;
else
return 0;
}
private int idxPrevCheckpoint(int i)
{
if (i == 0)
return this.transform.childCount - 1;
else
return i - 1;
}
public string Description()
{
return string.Format("There are {0} checkpoints.", this.transform.childCount);
}
}
|
a7da446a740045205fa93f1249f9b3b505d1dd6a
|
C#
|
andrewjpoole/elasticband
|
/tests/DefaultHttpClientFactory.cs
| 2.84375
| 3
|
using System.Net.Http;
using System.Net.Security;
using System.Threading;
using System.Threading.Tasks;
namespace Tests
{
public class DefaultHttpClientFactory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString().ToLower() == "0b9c2ad6fb339c96da57c879b047b7d4281e6a5f")
{
return true;
}
return false;
};
return new HttpClient(httpClientHandler);
}
}
}
|
1943f54f5cd274aeb713637a5f6b5f4e147d6bf7
|
C#
|
shendongnian/download4
|
/latest_version_download2/96915-18594290-46534839-2.cs
| 2.625
| 3
|
public Form1() {
InitializeComponent();
textBox1.MinimumSize = new Size(32, 0);
textBox2.MinimumSize = new Size(32, 0);
textBox3.MinimumSize = new Size(32, 0);
textBox1.TextChanged += textBox_TextChanged;
textBox2.TextChanged += textBox_TextChanged;
textBox3.TextChanged += textBox_TextChanged;
}
void textBox_TextChanged(object sender, EventArgs e) {
TextBox tb = sender as TextBox;
if (tb != null) {
tb.Width = TextRenderer.MeasureText(tb.Text, tb.Font, Size.Empty,
TextFormatFlags.TextBoxControl).Width + 8;
}
}
|
b77d01cb9ce3a9520af205d758b223798ad67a77
|
C#
|
GensouSakuya/MySimpleDemos
|
/.Net Framework/AdapterPattern/Communication/Level2.cs
| 2.90625
| 3
|
using System;
using System.ServiceModel;
namespace Communication
{
[ServiceContract]
public interface IRobotClient:IClientMethods
{
[OperationContract(IsOneWay = true)]
void ReceiveMessage(string message);
}
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IRobotClient))]
public interface IRobotService: IServiceMethods
{
[OperationContract(IsOneWay = true)]
void SendMessage(string message);
}
public class RobotClient : ClientBase<IRobotService>, IRobotClient
{
public RobotClient(ClientAdapter adapter):base(adapter)
{
}
public void ReceiveMessage(string message)
{
Console.WriteLine("Client:" + message);
}
}
public class RobotService :ServiceBase<IRobotClient> , IRobotService
{
public void SendMessage(string message)
{
Console.WriteLine("Service:" + message);
var caller = GetCaller();
caller.ReceiveMessage(message);
}
public RobotService(ServiceAdapter adapter) : base(adapter)
{
}
}
}
|
15f27e73745f6b1505ebd5599297d0213dac9dfc
|
C#
|
ppedvAG/WPF_Stuttgart_2018_Oktober
|
/Models/BookSearchService.cs
| 3.109375
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public static class BookSearchService
{
public async static Task<IList<Book>> SucheBücherAsync(string name)
{
BookSearchResult result = null;
try
{
HttpClient client = new HttpClient();
string jsonString = await client.GetStringAsync($"https://www.googleapis.com/books/v1/volumes?q={name}");
//Sorgt dafür, dass der Klassen-Name mit ins JSON geschrieben wird, wichtig bei polymorphen Listen
JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects };
result = JsonConvert.DeserializeObject<BookSearchResult>(jsonString, settings);
}
catch (Exception)
{
return new List<Book>();
}
//if(result.items != null)
// return new List<Book>(result.items);
if(result.items != null) {
List<Book> multiplayBooks = new List<Book>();
for (int i = 0; i < 1000; i++)
{
foreach (var item in result.items)
{
multiplayBooks.Add(item);
}
}
return multiplayBooks;
}
return new List<Book>();
}
}
}
|
cc32830df58aac3128816b42d77ab279c65368a8
|
C#
|
magic9911/CopyForex
|
/testUnmanagedDLL/Client/MsgClient.cs
| 2.59375
| 3
|
using CopyForex.Client;
using Nore.CommonLib.Message;
using Nore.CommonLib.Service;
using Norr.CommonLib.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CopyForex {
/// <summary>
/// This class implements IChatClient to use to be invoked by Chat Server.
/// </summary>
internal class ChatClient : IMsgClient {
#region Private fields
/// <summary>
/// Reference to Chat Room window.
/// </summary>
private readonly IMsgView _chatRoom;
#endregion
#region Constructor
/// <summary>
/// Creates a new ChatClient.
/// </summary>
/// <param name="chatRoom">Reference to Chat Room window</param>
public ChatClient(IMsgView chatRoom) {
_chatRoom = chatRoom;
}
#endregion
#region IChatClient implementation
/// <summary>
/// This method is used to get user list from chat server.
/// It is called by server, once after user logged in to server.
/// </summary>
/// <param name="users">All online user informations</param>
public void GetUserList(UserInfo[] users) {
foreach (var user in users) {
_chatRoom.AddUserToList(user);
}
}
/// <summary>
/// This method is called from chat server to inform that a message
/// is sent to chat room publicly.
/// </summary>
/// <param name="nick">Nick of sender</param>
/// <param name="message">Message text</param>
public void OnMessageToRoom(string nick, MessageData message) {
_chatRoom.OnMessageReceived(nick, message);
}
public void OnOrderReceived(OrderData order) {
_chatRoom.OnOrderReceived(order);
}
/// <summary>
/// This method is called from chat server to inform that a message
/// is sent to the current used privately.
/// </summary>
/// <param name="nick">Nick of sender</param>
/// <param name="message">Message</param>
public void OnPrivateMessage(string nick, MessageData message) {
_chatRoom.OnPrivateMessageReceived(nick, message);
}
/// <summary>
/// This method is called from chat server to inform that a new user
/// joined to chat room.
/// </summary>
/// <param name="userInfo">Informations of new user</param>
public void OnUserLogin(UserInfo userInfo) {
_chatRoom.AddUserToList(userInfo);
}
/// <summary>
/// This method is called from chat server to inform that an existing user
/// has left the chat room.
/// </summary>
/// <param name="nick">Informations of new user</param>
public void OnUserLogout(string nick) {
_chatRoom.RemoveUserFromList(nick);
}
#endregion
}
}
|
5ef97eb5b2c469bb2a3539a0763c9714924dc33c
|
C#
|
Andy0903/Quoridor
|
/Messages/PlayerWonMessage.cs
| 2.578125
| 3
|
using Lidgren.Network;
namespace QuoridorNetwork
{
public class PlayerWonMessage : Message
{
public int PlayerSlot { get; private set; }
public PlayerWonMessage(int playerSlot)
{
PlayerSlot = playerSlot;
}
public PlayerWonMessage(NetIncomingMessage incMsg) : base(incMsg)
{
PlayerSlot = incMsg.ReadInt32();
}
public static implicit operator NetOutgoingMessage(PlayerWonMessage msg)
{
NetOutgoingMessage outMessage = NetworkManager.Peer.CreateMessage();
outMessage.Write((int)MessageType.PlayerWon);
outMessage.Write(msg.PlayerSlot);
return outMessage;
}
}
}
|
f2ae7794281797f85f98d6b48fb35dfea92ed27f
|
C#
|
balloman/Wizard-s-Assistant
|
/Wizardry Assistant/WizardController.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Xml.Serialization;
using Newtonsoft.Json;
using Wizardry_Assistant.Models;
namespace Wizardry_Assistant
{
public class WizardController
{
private const string WIZARD_FILE = "Wizard.wz";
public static WizardController Instance { get; } = new WizardController();
private Wizard Wizard { get; set; }
public List<AttackSpell> AttackSpells => Wizard.Spellbook.Attacks;
public List<CharmSpell> CharmSpells => Wizard.Spellbook.Charms;
public AttackSpell CurrentSpell { get; set; }
private WizardController()
{
Wizard = new Wizard {Spellbook = new Spellbook()};
LoadWizard();
}
public void AddSpell(Spell spell)
{
Wizard.Spellbook.AddSpell(spell);
Task.Run(SaveData);
}
public void AddAttack(uint cost, uint min, uint max, bool xCost, string school, string name)
{
var spell = new AttackSpell() {
Cost = cost,
MaxDamage = max,
MinDamage = min,
XCost = xCost,
Name = name,
};
spell.SetSchool(school);
AddSpell(spell);
}
public void AddCharm(uint cost, float amount, string school, string name)
{
var spell = new CharmSpell {
Amount = amount,
Cost = cost,
Name = name,
};
spell.SetSchool(school);
AddSpell(spell);
}
public void DeleteSpell(Spell spell)
{
}
private void SaveData()
{
var writer = new StreamWriter(WIZARD_FILE);
var output = JsonConvert.SerializeObject(Wizard, Formatting.Indented, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
writer.Write(output);
writer.Close();
}
private void LoadWizard()
{
if (!File.Exists(WIZARD_FILE)) {
return;
}
var fs = new StreamReader(WIZARD_FILE);
Wizard = JsonConvert.DeserializeObject<Wizard>(fs.ReadToEnd(), new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
fs.Close();
}
public float BaseDamage
{
get => Wizard.BaseDamage;
set
{
Wizard.BaseDamage = value;
Task.Run(SaveData);
}
}
public void UpdateListBox<T>(ItemsControl box, IEnumerable<T> items)
{
box.Items.Clear();
foreach (var item in items) {
box.Items.Add(item);
}
}
}
}
|
6a909069a774b192caa09b3d31032f17fbc91fcd
|
C#
|
commercetools/commercetools-dotnet-sdk
|
/commercetools.NET/ProductProjections/ProductProjectionManager.cs
| 2.703125
| 3
|
using System;
using System.Collections.Specialized;
using System.Threading.Tasks;
using commercetools.Common;
namespace commercetools.ProductProjections
{
/// <summary>
/// Provides access to the functions in the ProductProjections section of the API.
/// </summary>
/// <see href="http://dev.commercetools.com/http-api-projects-productProjections.html"/>
public class ProductProjectionManager
{
#region Constants
private const string ENDPOINT_PREFIX = "/product-projections";
#endregion
#region Member Variables
private readonly IClient _client;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="client">Client</param>
public ProductProjectionManager(IClient client)
{
_client = client;
}
#endregion
#region API Methods
/// <summary>
/// Gets the current or staged representation of a product in a catalog by ID.
/// </summary>
/// <param name="productId">Product ID</param>
/// <param name="staged">Whether to query for the current or staged projections.</param>
/// <param name="priceCurrency">The currency code compliant to ISO 4217. Enables price selection.</param>
/// <param name="priceCountry">A two-digit country code as per ISO 3166-1 alpha-2. Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceCustomerGroup">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceChannel">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <returns>ProductProjection</returns>
/// <see href="http://dev.commercetools.com/http-api-projects-productProjections.html#get-productprojection-by-id"/>
public Task<Response<ProductProjection>> GetProductProjectionByIdAsync(string productId, bool staged = false, string priceCurrency = null, string priceCountry = null, Guid priceCustomerGroup = new Guid(), Guid priceChannel = new Guid())
{
if (string.IsNullOrWhiteSpace(productId))
{
throw new ArgumentException("productId is required");
}
string endpoint = string.Concat(ENDPOINT_PREFIX, "/", productId);
return GetProductProjectionAsync(endpoint, staged, priceCurrency, priceCountry, priceCustomerGroup, priceChannel);
}
/// <summary>
/// Gets the current or staged representation of a product found by Key.
/// </summary>
/// <param name="key">Product key</param>
/// <param name="staged">Whether to query for the current or staged projections.</param>
/// <param name="priceCurrency">The currency code compliant to ISO 4217. Enables price selection.</param>
/// <param name="priceCountry">A two-digit country code as per ISO 3166-1 alpha-2. Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceCustomerGroup">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceChannel">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <returns>ProductProjection</returns>
/// <see href="http://dev.commercetools.com/http-api-projects-productProjections.html#get-productprojection-by-key"/>
public Task<Response<ProductProjection>> GetProductProjectionByKeyAsync(string key, bool staged = false, string priceCurrency = null, string priceCountry = null, Guid priceCustomerGroup = new Guid(), Guid priceChannel = new Guid())
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("key is required");
}
string endpoint = string.Concat(ENDPOINT_PREFIX, "/key=", key);
return GetProductProjectionAsync(endpoint, staged, priceCurrency, priceCountry, priceCustomerGroup, priceChannel);
}
/// <summary>
/// Private worker method for GetProductProjectionByIdAsync and GetProductProjectionByKeyAsync.
/// </summary>
/// <param name="endpoint">Request endpoint</param>
/// <param name="staged">Whether to query for the current or staged projections.</param>
/// <param name="priceCurrency">The currency code compliant to ISO 4217. Enables price selection.</param>
/// <param name="priceCountry">A two-digit country code as per ISO 3166-1 alpha-2. Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceCustomerGroup">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceChannel">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <returns>Product</returns>
/// <see href="http://dev.commercetools.com/http-api-projects-productProjections.html#get-productprojection"/>
private Task<Response<ProductProjection>> GetProductProjectionAsync(string endpoint, bool staged = false, string priceCurrency = null, string priceCountry = null, Guid priceCustomerGroup = new Guid(), Guid priceChannel = new Guid())
{
NameValueCollection values = new NameValueCollection
{
{ "staged", staged.ToString() }
};
if (!string.IsNullOrWhiteSpace(priceCurrency))
{
values.Add("priceCurrency", priceCurrency);
if (!string.IsNullOrWhiteSpace(priceCountry))
{
values.Add("priceCountry", priceCountry);
}
if (priceCustomerGroup != Guid.Empty)
{
values.Add("priceCustomerGroup", priceCustomerGroup.ToString());
}
if (priceChannel != Guid.Empty)
{
values.Add("priceChannel", priceChannel.ToString());
}
}
return _client.GetAsync<ProductProjection>(endpoint, values);
}
/// <summary>
/// You can use the product projections query endpoint to get the current or staged representations of Products.
/// </summary>
/// <remarks>
/// We suggest to use the performance optimized search endpoint which has a bunch functionalities, the query API lacks, like sorting on custom attributes, etc.
/// </remarks>
/// <param name="where">Where</param>
/// <param name="sort">Sort</param>
/// <param name="limit">Limit</param>
/// <param name="offset">Offset</param>
/// <param name="staged">Whether to query for the current or staged projections.</param>
/// <param name="priceCurrency">The currency code compliant to ISO 4217. Enables price selection.</param>
/// <param name="priceCountry">A two-digit country code as per ISO 3166-1 alpha-2. Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceCustomerGroup">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <param name="priceChannel">Enables price selection. Can only be used in conjunction with the priceCurrency parameter.</param>
/// <returns>ProductProjectionQueryResult</returns>
/// <see href="http://dev.commercetools.com/http-api-projects-productProjections.html#query-productprojections"/>
public Task<Response<ProductProjectionQueryResult>> QueryProductProjectionsAsync(
string where = null,
string sort = null,
int limit = -1,
int offset = -1,
bool staged = false,
string priceCurrency = null,
string priceCountry = null,
string priceCustomerGroup = null,
string priceChannel = null)
{
NameValueCollection values = new NameValueCollection
{
{ "staged", staged.ToString() }
};
if (!string.IsNullOrWhiteSpace(where))
{
values.Add("where", where);
}
if (!string.IsNullOrWhiteSpace(sort))
{
values.Add("sort", sort);
}
if (limit > 0)
{
values.Add("limit", limit.ToString());
}
if (offset >= 0)
{
values.Add("offset", offset.ToString());
}
if (!string.IsNullOrWhiteSpace(priceCurrency))
{
values.Add("priceCurrency", priceCurrency);
if (!string.IsNullOrWhiteSpace(priceCountry))
{
values.Add("priceCountry", priceCountry);
}
if (!string.IsNullOrWhiteSpace(priceCustomerGroup))
{
values.Add("priceCustomerGroup", priceCustomerGroup);
}
if (!string.IsNullOrWhiteSpace(priceChannel))
{
values.Add("priceChannel", priceChannel);
}
}
return _client.GetAsync<ProductProjectionQueryResult>(ENDPOINT_PREFIX, values);
}
#endregion
}
}
|
b2e3115f690c3f921a8e05b46c856056b8aa91d3
|
C#
|
YurchenokMaxim/EPAM-tasks
|
/stage 2/Task 2/Project/Command/Invoker.cs
| 3.203125
| 3
|
namespace Task7
{
public class Invoker
{
Command command;
/// <summary>
/// This method will set new command
/// </summary>
/// <param new command ="c"></param>
public void SetCommand(Command c)
{
if (c == null)
{
throw new System.NullReferenceException();
}
command = c;
}
/// <summary>
/// This method will run command
/// </summary>
public string Run()
{
return command.Execute();
}
}
}
|
c852015af766a45b609f6b0400678be80e737d1d
|
C#
|
luckyman81/trainyourprogrammer
|
/CS_Aufgabe_310_NonRecursive/Program.cs
| 3.03125
| 3
|
using System;
namespace CS_Aufgabe_310_NonRecursive
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int num = p.DoSomething(99);
}
int DoSomething(int n)
{
return n / 2;
}
}
}
|
040f0f52ac51e132f5249dfe6c2c9e21a3784364
|
C#
|
test-in-prod/cfa735-dotnet
|
/HelloWorld/Program.cs
| 2.84375
| 3
|
using Crypton.CrystalFontz;
using System;
using System.IO.Ports;
using System.Threading;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
using (var port = new SerialPort("COM15", 115200, Parity.None, 8, StopBits.One))
{
port.Open();
using (var cf = new CF735(port))
{
cf.Clear();
cf.SetCursorStyle(CursorStyles.None);
cf.SetBacklight(75, 25);
cf.KeypadKeyEvent += Cf_KeypadKeyEvent;
cf.SendData(1, 0, "Hello, world");
cf.SetLED(0, 100, 0);
cf.SetLED(1, 100, 100);
cf.SetLED(2, 0, 100);
cf.SetLED(3, 50, 50);
var marquee = new Marquee(cf);
marquee.Text = "The quick brown fox jumped over the lazy dog";
marquee.Row = 0;
marquee.Enabled = true;
Thread.Sleep(Timeout.Infinite);
}
}
}
private static void Cf_KeypadKeyEvent(object sender, KeypadEvent e)
{
Console.WriteLine($"Buttons!: {e}");
}
}
}
|
3bf94626d44ba4cee707ff4e2f5178999071ed7c
|
C#
|
mathiasoldfarm/chatbot_DBconnect
|
/DBConnect/Course/Answer.cs
| 3.140625
| 3
|
using System;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using Npgsql;
namespace DBConnect
{
public class Answer
{
[JsonIgnore]
public int id {
get; set;
}
public string answer {
get; set;
}
public string explanation {
get; set;
}
public Answer(DataRow row) {
try {
id = (int)row[0];
answer = (string)row[1];
explanation = (string)row[2];
} catch {
throw new Exception("Constructor argument DataRow was expected to have three arguments of type int, string string");
}
}
[JsonConstructor]
public Answer(int _id, string _answer, string _explantion)
{
id = _id;
answer = _answer;
explanation = _explantion;
}
public Answer(string _answer, string _explantion) {
answer = _answer;
explanation = _explantion;
}
public void GetQuery(List<NpgsqlCommand> queries, NpgsqlConnection connection)
{
NpgsqlCommand query = new NpgsqlCommand("INSERT INTO answers(id, answer, explanation) VALUES(@id, @answer, @explanation)", connection);
query.Parameters.AddWithValue("id", id);
query.Parameters.AddWithValue("answer", answer);
query.Parameters.AddWithValue("explanation", explanation);
queries.Add(query);
}
}
}
|
2dff484de067eb640105e03831f2504446e67f72
|
C#
|
chansen1395/ScrabbleScorer-9-23
|
/Scrabble/Models/Scorer.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
// method that takes in a string
// scoring dictionary {a, 1}, ...
// parse each letter into a list
// for loop
// if list[index] is in the dictionary[index2] --> score += dictionary[index2]
// {"a", "b", "c"} --> 7
// return score
namespace Scorer.Models
{
public class Game
{
public static int ScoreCalc(string word)
{
string inputWord = word.ToLower();
char[] wordLower = inputWord.ToCharArray();
char[] onePoint = {'a', 'e', 'i', 'o', 'u', 'l', 'n', 'r', 's', 't'};
char[] twoPoint = {'d', 'g'};
char[] threePoint = {'b', 'c', 'm', 'p'};
char[] fourPoint = {'f', 'h', 'v', 'w', 'y'};
char[] fivePoint = {'k'};
char[] eightPoint = {'j', 'x'};
char[] tenPoint = {'q', 'z'};
int totalScore = 0;
for (int i = 0; i < inputWord.Length; i++)
if (Array.Exists(onePoint, element => element == wordLower[i]))
{
totalScore += 1;
}
else if (Array.Exists(twoPoint, element => element == wordLower[i]))
{
totalScore += 2;
}
else if (Array.Exists(threePoint, element => element == wordLower[i]))
{
totalScore += 3;
}
else if (Array.Exists(fourPoint, element => element == wordLower[i]))
{
totalScore += 4;
}
else if (Array.Exists(fivePoint, element => element == wordLower[i]))
{
totalScore += 5;
}
else if (Array.Exists(eightPoint, element => element == wordLower[i]))
{
totalScore += 8;
}
else if (Array.Exists(tenPoint, element => element == wordLower[i]))
{
totalScore += 10;
}
else
{
totalScore += 0;
}
return totalScore;
}
}
}
|
d74d0e4459f30858253aa967ecc9a3826ba28894
|
C#
|
IrekRomaniuk/csharpwithmosh
|
/Workflow/Workflow/Workflow.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
namespace Workflow
{
public class WorkflowEngine : IWorkflowEngine
{
private IList<IActivity> _activities;
public WorkflowEngine()
{
_activities = new List<IActivity>();
}
public void Run()
{
foreach (var activity in _activities)
{
activity.Execute();
}
}
public void AddToWorkflow(IActivity activity)
{
_activities.Add(activity);
}
}
}
|
7ec0ddc0a1933f099c2983f4c9cb5386b8808fe3
|
C#
|
suteetoe/brsml
|
/SMLERPControl/_sideBar/OutlookStyleTabButton.cs
| 2.625
| 3
|
/*
* Proje : Outlook 2003 Style SideBar v 1.1
*
* Hazırlayan : Muhammed ŞAHİN
* eMail : muhammed.sahin@gmail.com
*
* Açıklama : Outlook 2003 Style Sidebar
* : Panel içerisine eklenen TabButtonlar
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace SMLERPControl
{
#region Class : OutlookStyleTabButton
/// <summary>
/// SidebarTabButton
/// </summary>
[Browsable(false)]
[ToolboxItem(false)]
public sealed class OutlookStyleTabButton : ToolStrip
{
// Delegate
#region Delegate & Events
public delegate void OnTabSelectedEventHandler(object sender, OutlookStyleTabButtonEventArgs e);
public event OnTabSelectedEventHandler OnTabSelected;
public delegate void OnTabMouseOverEventHandler(OutlookStyleTabButtonEventArgs e);
public event OnTabMouseOverEventHandler OnTabMouseOver;
public delegate void OnTabMouseLeaveEventHandler(OutlookStyleTabButtonEventArgs e);
public event OnTabMouseLeaveEventHandler OnTabMouseLeave;
public delegate void OnTabCaptionChangedEventHandler(string tOldCaption, string tNewCaption);
public event OnTabCaptionChangedEventHandler OnTabCaptionChanged;
public delegate void OnTabCaptionDescriptionChangedEventHandler(string tOldCaptionDesc, string tNewCaptionDesc);
public event OnTabCaptionDescriptionChangedEventHandler OnTabCaptionDescriptionChanged;
public delegate void OnTabFontChangeEventHandler(Font tOldFont, Font tNewFont);
public event OnTabFontChangeEventHandler OnTabFontChanged;
public delegate void OnTabThemeColorChangeEventHandler(OutlookStyleThemeColor tOldThemeColor, OutlookStyleThemeColor tNewThemeColor);
public event OnTabThemeColorChangeEventHandler OnTabThemeColorChanged;
#endregion
// Properties
#region ThemeColor
OutlookStyleThemeColor themeColor = null; //OutlookStyleThemeColor.GetThemeColor(ThemeColors.SystemDefault);
public OutlookStyleThemeColor ThemeColor
{
get { return themeColor; }
set
{
OutlookStyleThemeColor oldThemeColor = themeColor;
themeColor = value;
tsLabel.ForeColor = themeColor.TabButtonForeColor;
// Renderer
tsrNormal = new OutlookStyleRenderer(themeColor.LightColor, themeColor.DarkColor, true);
tsrOver = new OutlookStyleRenderer(themeColor.OverLightColor, themeColor.SelectedDarkColor, true);
tsrSelected = new OutlookStyleRenderer(themeColor.SelectedLightColor, themeColor.SelectedDarkColor, true);
if (Selected)
Renderer = tsrSelected;
else
Renderer = tsrNormal;
Invalidate();
if (OnTabThemeColorChanged != null)
OnTabThemeColorChanged(oldThemeColor, value);
}
}
#endregion
#region Image
private Image image = null;
/// <summary>
/// Tabbutton image (24x24 kullanın)
/// </summary>
public Image Image
{
get { return image; }
set
{
image = value;
tsLabel.Image = image;
Invalidate();
}
}
#endregion
#region HoverImage
private Image hoverImage = null;
/// <summary>
/// Tabbutton image (24x24 kullanın)
/// </summary>
public Image HoverImage
{
get { return hoverImage; }
set { hoverImage = value; }
}
#endregion
#region SelectedImage
private Image selectedImage = null;
/// <summary>
/// Tabbutton image (24x24 kullanın)
/// </summary>
public Image SelectedImage
{
get { return selectedImage; }
set { selectedImage = value; }
}
#endregion
#region Selected
private bool selected = false;
/// <summary>
/// Seçilimi
/// </summary>
public bool Selected
{
get { return selected; }
set
{
selected = value;
this.Renderer = selected ? tsrSelected : tsrNormal;
this.tsLabel.Image = this.SelectedImage != null ? this.SelectedImage : this.Image;
if (!selected)
this.tsLabel.Image = this.Image;
Invalidate();
}
}
#endregion
#region Caption
private string caption = "Caption";
/// <summary>
/// Tabbutton üzerinde gözükecek olan metin
/// </summary>
public string Caption
{
get { return caption; }
set
{
string oldCaption = caption;
caption = value;
tsLabel.Text = caption;
if (OnTabCaptionChanged != null)
OnTabCaptionChanged(oldCaption, caption);
}
}
#endregion
#region CaptionDescription
private string captionDesc = "Caption Description";
/// <summary>
/// Caption band üzerinde gözükecek metin
/// </summary>
public string CaptionDescription
{
get { return captionDesc; }
set
{
string oldCaptionDesc = caption;
captionDesc = value;
if (OnTabCaptionDescriptionChanged != null)
OnTabCaptionDescriptionChanged(oldCaptionDesc, captionDesc);
}
}
#endregion
#region Control
private Control control = null;
/// <summary>
/// Tabbuton seçildiğinde aktif edilecek kontrol
/// </summary>
public Control Control
{
get { return control; }
}
#endregion
#region TabButtonFont
private Font tabButtonFont = new Font("Tahoma", 8, FontStyle.Bold);
public Font TabButtonFont
{
get { return tabButtonFont; }
set
{
Font oldFont = tabButtonFont;
tabButtonFont = value;
this.Font = tabButtonFont;
this.tsLabel.Font = tabButtonFont;
if (OnTabFontChanged != null)
OnTabFontChanged(oldFont, tabButtonFont);
}
}
#endregion
// Var
ToolStripLabel tsLabel = new ToolStripLabel();
private OutlookStyleRenderer tsrNormal;
private OutlookStyleRenderer tsrOver;
private OutlookStyleRenderer tsrSelected;
#region Yapıcı metodlar
/// <summary>
/// Mutlaka tab seçildiğinde gösterilecek olan kontrol belirtilmeli
/// </summary>
/// <param name="tControl"></param>
public OutlookStyleTabButton(Control tControl)
{
if (tControl == null)
control = new Panel();
else
control = tControl; // Panel içerisinde gösterilecek nesne
control.Dock = DockStyle.Fill;
InitOutlookStyleTabButton();
}
/// <summary>
/// İlk Ayarlamalar
/// </summary>
void InitOutlookStyleTabButton()
{
// Control
AutoSize = false;
Stretch = true;
Dock = DockStyle.Bottom;
Cursor = Cursors.Hand;
MouseEnter += new EventHandler(OutlookStyleTabButton_MouseEnter);
MouseLeave += new EventHandler(OutlookStyleTabButton_MouseLeave);
Click += new EventHandler(OutlookStyleTabButton_Click);
Font = tabButtonFont;
// Renderer
OutlookStyleThemeColor thmColor = OutlookStyleThemeColor.SystemColor;
tsrNormal = new OutlookStyleRenderer(thmColor.LightColor, thmColor.DarkColor, true);
tsrOver = new OutlookStyleRenderer(thmColor.OverLightColor, thmColor.OverDarkColor, true);
tsrSelected = new OutlookStyleRenderer(thmColor.SelectedLightColor, thmColor.SelectedDarkColor, true);
thmColor = null;
this.Renderer = tsrNormal;
// tsLabel
tsLabel.Text = "Caption Description";
tsLabel.ImageScaling = ToolStripItemImageScaling.None;
tsLabel.TextImageRelation = TextImageRelation.ImageBeforeText;
tsLabel.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
tsLabel.Font = tabButtonFont;
//
this.Items.Add(tsLabel);
}
#endregion
#region TabButton olayları
/// <summary>
/// Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OutlookStyleTabButton_Click(object sender, EventArgs e)
{
selected = !selected;
if (OnTabSelected != null)
OnTabSelected(this, new OutlookStyleTabButtonEventArgs(this));
}
/// <summary>
/// Fare ile üstüne geldiginde normal render ayarlanacak
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OutlookStyleTabButton_MouseLeave(object sender, EventArgs e)
{
if (!selected)
{
this.Renderer = tsrNormal;
this.tsLabel.Image = this.Image;
}
if (OnTabMouseLeave != null)
OnTabMouseLeave(new OutlookStyleTabButtonEventArgs(this));
}
/// <summary>
/// Fare üstünden ayrıldığında normal görünüme getirilecek
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OutlookStyleTabButton_MouseEnter(object sender, EventArgs e)
{
if (!selected)
{
this.Renderer = tsrOver;
this.tsLabel.Image = this.HoverImage != null ? this.HoverImage : this.Image;
}
else
{
this.Renderer = tsrSelected;
this.tsLabel.Image = this.SelectedImage != null ? this.SelectedImage : this.Image;
}
if (OnTabMouseOver != null)
OnTabMouseOver(new OutlookStyleTabButtonEventArgs(this));
}
#endregion
}
#endregion
}
|
9fc773361379d759ae1c5bc204c6b081d61a252e
|
C#
|
BadgerTadger/DSM
|
/DSM_BLL/ShowsBL.cs
| 2.765625
| 3
|
using DSM_DATA;
using System;
using System.Data;
namespace BLL
{
public class ShowsBL
{
private string _connString = "";
public ShowsBL(string connString)
{
_connString = connString;
}
public DataTable GetShows()
{
DataTable retVal = null;
string spName = "spGetShows";
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, null);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowByShow_ID(Guid show_ID)
{
DataTable retVal = null;
string spName = "spGetShowByShow_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Show_ID", SSSDatabaseInfo.ParameterType.Guid, show_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Show. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsByClub_ID(Guid club_ID)
{
DataTable retVal = null;
string spName = "spGetShowsByClub_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Club_ID", SSSDatabaseInfo.ParameterType.Guid, club_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsByClub_ID_And_Show_Year_ID(Guid club_ID, int show_Year_ID)
{
DataTable retVal = null;
string spName = "spGetShowsByClub_ID_And_Show_Year_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Club_ID", SSSDatabaseInfo.ParameterType.Guid, club_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Year_ID", SSSDatabaseInfo.ParameterType.Int, show_Year_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsByShow_Type_ID(int show_Type_ID)
{
DataTable retVal = null;
string spName = "spGetShowsByShow_Type_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Show_Type_ID", SSSDatabaseInfo.ParameterType.Int, show_Type_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsByShow_Year(short show_Year_ID)
{
DataTable retVal = null;
string spName = "spGetShowsByShow_Year_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Show_Year_ID", SSSDatabaseInfo.ParameterType.Short, show_Year_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsByVenue_ID(Guid venue_ID)
{
DataTable retVal = null;
string spName = "spGetShowsByVenue_ID";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Venue_ID", SSSDatabaseInfo.ParameterType.Guid, venue_ID),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public DataTable GetShowsLikeShow_Name(string show_Name)
{
DataTable retVal = null;
string spName = "spGetShowsLikeShow_Name";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Show_Name", SSSDatabaseInfo.ParameterType.String, show_Name),
};
try
{
DataSet ds = SSSDatabaseInfo.ExecuteDataSet(_connString, spName, p);
retVal = ds.Tables[0];
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to get Shows. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public Guid? Insert_Shows(Guid? club_ID, int? show_Year_ID, int? show_Type_ID, Guid? venue_ID, DateTime? show_Opens, DateTime? judging_Commences,
string show_Name, DateTime? closing_Date, short? maxClassesPerDog, bool? linked_Show, Guid user_ID)
{
Guid? retVal = null;
string spName = "spInsert_tblShows";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Club_ID", SSSDatabaseInfo.ParameterType.Guid, club_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Year_ID", SSSDatabaseInfo.ParameterType.Int, show_Year_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Type_ID", SSSDatabaseInfo.ParameterType.Int, show_Type_ID),
new SSSDatabaseInfo.DatabaseParameter("Venue_ID", SSSDatabaseInfo.ParameterType.Guid, venue_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Opens", SSSDatabaseInfo.ParameterType.DateTime, show_Opens),
new SSSDatabaseInfo.DatabaseParameter("Judging_Commences", SSSDatabaseInfo.ParameterType.DateTime, judging_Commences),
new SSSDatabaseInfo.DatabaseParameter("Show_Name", SSSDatabaseInfo.ParameterType.String, show_Name),
new SSSDatabaseInfo.DatabaseParameter("Closing_Date", SSSDatabaseInfo.ParameterType.DateTime, closing_Date),
new SSSDatabaseInfo.DatabaseParameter("MaxClassesPerDog", SSSDatabaseInfo.ParameterType.Short, maxClassesPerDog),
new SSSDatabaseInfo.DatabaseParameter("Linked_Show", SSSDatabaseInfo.ParameterType.Bool, linked_Show),
new SSSDatabaseInfo.DatabaseParameter("User_ID", SSSDatabaseInfo.ParameterType.Guid, user_ID),
};
try
{
retVal = SSSDatabaseInfo.ExecuteScalarReturnGuid(_connString, spName, p);
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to insert Show. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
public bool Update_Shows(Guid original_ID, Guid? club_ID, int? show_Year_ID, int? show_Type_ID, Guid? venue_ID, DateTime? show_Opens, DateTime? judging_Commences,
string show_Name, DateTime? closing_Date, bool? entries_Complete, bool? judges_Allocated, bool? split_Classes, bool? running_Orders_Allocated,
bool? ring_Numbers_Allocated, short? maxClassesPerDog, bool? linked_Show, bool? deleted, Guid user_ID)
{
bool retVal = false;
string spName = "spUpdate_tblShows";
SSSDatabaseInfo.DatabaseParameter[] p = new SSSDatabaseInfo.DatabaseParameter[]
{
new SSSDatabaseInfo.DatabaseParameter("Original_ID", SSSDatabaseInfo.ParameterType.Guid, original_ID),
new SSSDatabaseInfo.DatabaseParameter("Club_ID", SSSDatabaseInfo.ParameterType.Guid, club_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Year_ID", SSSDatabaseInfo.ParameterType.Int, show_Year_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Type_ID", SSSDatabaseInfo.ParameterType.Int, show_Type_ID),
new SSSDatabaseInfo.DatabaseParameter("Venue_ID", SSSDatabaseInfo.ParameterType.Guid, venue_ID),
new SSSDatabaseInfo.DatabaseParameter("Show_Opens", SSSDatabaseInfo.ParameterType.DateTime, show_Opens),
new SSSDatabaseInfo.DatabaseParameter("Judging_Commences", SSSDatabaseInfo.ParameterType.DateTime, judging_Commences),
new SSSDatabaseInfo.DatabaseParameter("Show_Name", SSSDatabaseInfo.ParameterType.String, show_Name),
new SSSDatabaseInfo.DatabaseParameter("Closing_Date", SSSDatabaseInfo.ParameterType.DateTime, closing_Date),
new SSSDatabaseInfo.DatabaseParameter("Entries_Complete", SSSDatabaseInfo.ParameterType.Bool, entries_Complete),
new SSSDatabaseInfo.DatabaseParameter("Judges_Allocated", SSSDatabaseInfo.ParameterType.Bool, judges_Allocated),
new SSSDatabaseInfo.DatabaseParameter("Split_Classes", SSSDatabaseInfo.ParameterType.Bool, split_Classes),
new SSSDatabaseInfo.DatabaseParameter("Running_Orders_Allocated", SSSDatabaseInfo.ParameterType.Bool, running_Orders_Allocated),
new SSSDatabaseInfo.DatabaseParameter("Ring_Numbers_Allocated", SSSDatabaseInfo.ParameterType.Bool, ring_Numbers_Allocated),
new SSSDatabaseInfo.DatabaseParameter("MaxClassesPerDog", SSSDatabaseInfo.ParameterType.Short, maxClassesPerDog),
new SSSDatabaseInfo.DatabaseParameter("Linked_Show", SSSDatabaseInfo.ParameterType.Bool, linked_Show),
new SSSDatabaseInfo.DatabaseParameter("Deleted", SSSDatabaseInfo.ParameterType.Bool, deleted),
new SSSDatabaseInfo.DatabaseParameter("User_ID", SSSDatabaseInfo.ParameterType.Guid, user_ID),
};
try
{
SSSDatabaseInfo.ExecuteNonQuery(_connString, spName, p);
retVal = true;
}
catch (Exception ex)
{
ErrorLog.LogMessage(string.Format("Failed to update Person. Error: {0}", ex.Message));
throw ex;
}
return retVal;
}
}
}
|
a7e1dbc390ce7a207d831d4104529543a94bef88
|
C#
|
Floydan/discord-pickup-bot
|
/PickupBot.Commands/Infrastructure/AppVersionInfo.cs
| 2.71875
| 3
|
using System.Linq;
using System.Reflection;
namespace PickupBot.Commands.Infrastructure
{
public class AppVersionInfo
{
private string _gitHash;
private string _gitShortHash;
public string GitHash
{
get
{
if (string.IsNullOrEmpty(_gitHash))
{
var version = "1.0.0+LOCALBUILD"; // Dummy version for local dev
var appAssembly = typeof(AppVersionInfo).Assembly;
var infoVerAttr = (AssemblyInformationalVersionAttribute)appAssembly
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute)).FirstOrDefault();
if (infoVerAttr.InformationalVersion.Length > 6)
{
// Hash is embedded in the version after a '+' symbol, e.g. 1.0.0+a34a913742f8845d3da5309b7b17242222d41a21
version = infoVerAttr.InformationalVersion;
}
_gitHash = version.Substring(version.IndexOf('+') + 1);
}
return _gitHash;
}
}
public string ShortGitHash
{
get
{
if (string.IsNullOrEmpty(_gitShortHash))
{
_gitShortHash = GitHash.Substring(GitHash.Length - 6, 6);
}
return _gitShortHash;
}
}
}
}
|
4aa0add9d1cf10970cd87834e915cb276d4ba369
|
C#
|
dbogdan95/SA-MP.Gamemode.CSharp
|
/Game/World/Properties/Generic.cs
| 2.640625
| 3
|
using Game.Core;
using Game.Factions;
using MySql.Data.MySqlClient;
using SampSharp.GameMode;
using System;
using System.Collections.Generic;
using System.Text;
namespace Game.World.Properties
{
public class Generic : Property
{
private int __id;
private Generic(Interior interior, Vector3 pos, float angle, int id, int baseid)
: base(baseid, PropertyType.TypeGeneric, interior, pos, angle)
{
__id = id;
}
public Generic(Interior interior, Vector3 pos, float angle) : base(PropertyType.TypeGeneric, interior, pos, angle)
{
using (var conn = Database.Connect())
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO generic (baseProperty) VALUES (" + Id + ")", conn);
cmd.ExecuteNonQuery();
__id = (int)cmd.LastInsertedId;
}
}
public Faction Faction { get; set; }
public override void UpdateSql()
{
using (var conn = Database.Connect())
{
MySqlCommand cmd = new MySqlCommand("UPDATE generic SET baseFaction=@faction WHERE id=@id", conn);
if(Faction == null)
cmd.Parameters.AddWithValue("@faction", DBNull.Value);
else
cmd.Parameters.AddWithValue("@faction", Faction.Id);
cmd.Parameters.AddWithValue("@id", __id);
cmd.ExecuteNonQuery();
}
base.UpdateSql();
}
public static void Load()
{
int props = 0;
using (var conn = Database.Connect())
{
MySqlCommand cmd = new MySqlCommand("SELECT A.id, A.baseFaction as faction, A.baseProperty, C.x, C.y, c.z, C.a, C.locked, C.deposit, C.interior " +
"FROM generic as A " +
"INNER JOIN properties AS C " +
"ON c.id = A.baseProperty", conn);
MySqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
Generic g = new Generic(data["interior"] is DBNull ? null : Interior.FromIndex(data.GetInt32("interior")), new Vector3(data.GetFloat("x"), data.GetFloat("y"), data.GetFloat("z")), data.GetFloat("a"), data.GetInt32("id"), data.GetInt32("baseProperty"))
{
Deposit = data.GetInt32("deposit"),
Faction = data["faction"] is DBNull ? null : Faction.Find(data.GetInt32("faction"))
};
props++;
}
data.Close();
}
Console.WriteLine("** Loaded {0} generic properties from database.", props);
}
public override void SetOwnerUpdate(int id)
{
throw new NotImplementedException();
}
public override void UpdateLabel()
{
throw new NotImplementedException();
}
}
}
|
aed5cac6e3e4f18b5e5625d19f94f2b9aef67ba3
|
C#
|
denhamdagger/OData-v4-WebApi-Demo
|
/Part11/DataSource/Repository.cs
| 3.109375
| 3
|
using Part11.Models;
using System.Collections.Generic;
using System.Linq;
namespace Part11.DataSource
{
public class Repository
{
private List<Car> _cars;
public Repository()
{
_cars = new List<Car> {
new Car {Make = "Vauxhall", Model = "Zafira", Colour = "Blue", Price = 20000.00, Category = "SUV"},
new Car {Make = "Vauxhall", Model = "Mokka", Colour = "Silver", Price = 18500.00, Category = "4x4"},
new Car {Make = "Ford", Model = "Focus", Colour = "Black", Price = 22000.00, Category = "HatchBack"},
new Car {Make = "Peugeot", Model = "3008", Colour = "Green", Price = 19000.00, Category = "4x4"}
};
}
public IQueryable<Car> GetCars()
{
return _cars.AsQueryable();
}
public Car GetCar(string make, string model)
{
return _cars.Where(p => p.Make == make && p.Model == model).FirstOrDefault();
}
public IQueryable<Car> GetCars(string category)
{
return _cars.Where(p => p.Category == category).AsQueryable();
}
}
}
|
530280cf3cdb6f64db5bb781286370d7a501e7f6
|
C#
|
Lead007/-The-Mirror-Bridge-to-Euphoria-Myself
|
/JLQ_GameResources/Characters/CharacterBeCalled/AliceFigure.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JLQ_GameBase;
using MoreEnumerable;
namespace JLQ_GameResources.Characters.CharacterBeCalled
{
/// <summary>爱丽丝·玛格特洛依德 召唤出的人偶</summary>
public abstract class AliceFigure : Character
{
protected AliceFigure(PadPoint position, Group group, Game game)
: base(0, position, group, game)
{
}
public override void PreparingSection()
{
base.PreparingSection();
game.ButtonSC.DoAction(b => b.IsEnabled = false);
}
#region SC
public override void SC01()
{
throw new NotImplementedException();
}
public override void SC02()
{
throw new NotImplementedException();
}
public override void SC03()
{
throw new NotImplementedException();
}
#endregion
}
}
|
69046c12fa65e3d2a8310b71630dbf8f383aaf3a
|
C#
|
seobyeongky/ztar
|
/Assets/Scripts/Tilemap/TilePatternContainer.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TilePatternContainer : MonoBehaviour
{
[SerializeField]
[HideInInspector]
byte[] patternMap = new byte[0];
[SerializeField]
Vector2Int minski; // inclusive
[SerializeField]
Vector2Int maxski; // exclusive
Vector2Int size
{
get
{
return maxski - minski;
}
}
public void SetPattern(Vector2Int pos, byte pattern)
{
if (!IsCovered(pos))
{
if (minski == maxski)
{
ResetSize(pos, pos + new Vector2Int(1, 1));
}
else
{
var newMinski = new Vector2Int(
Mathf.Min(minski.x, pos.x)
, Mathf.Min(minski.y, pos.y));
var newMaxski = new Vector2Int(
Mathf.Max(maxski.x, pos.x + 1)
, Mathf.Max(maxski.y, pos.y + 1)
);
ResetSize(newMinski, newMaxski);
}
}
patternMap[GetIndex(pos)] = (byte)(pattern + 1);
}
public byte GetPattern(Vector2Int pos)
{
if (IsCovered(pos))
{
return (byte)(patternMap[GetIndex(pos)] - 1);
}
else
{
return 0;
}
}
int GetIndex(Vector2Int pos)
{
return size.x * (pos.y - minski.y) + (pos.x - minski.x);
}
public bool IsCovered(Vector2Int pos)
{
if (pos.x < minski.x || pos.y < minski.y
|| maxski.x <= pos.x || maxski.y <= pos.y)
{
return false;
}
return true;
}
public bool IsSet(Vector2Int pos)
{
if (!IsCovered(pos))
{
return false;
}
if (patternMap[GetIndex(pos)] == 0)
{
return false;
}
return true;
}
public void ResetSize(Vector2Int newMinski, Vector2Int newMaxski)
{
var newSize = (newMaxski - newMinski);
byte[]newPatternMap = new byte[newSize.x * newSize.y];
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
var pos = new Vector2Int(x + minski.x, y + minski.y);
newPatternMap[newSize.x * (pos.y - newMinski.y) + (pos.x - newMinski.x)]
= patternMap[size.x * y + x];
}
}
minski = newMinski;
maxski = newMaxski;
patternMap = newPatternMap;
}
}
|
2c2b28b8b3d4cbdeffec5741d9984c51f83479da
|
C#
|
PayHard/CastleDEMO
|
/CastleDEMO/Program.cs
| 2.8125
| 3
|
using System;
namespace CastleDEMO
{
class Program
{
static void Main(string[] args)
{
PersonDAL person = DaoContainer.GetDao<PersonDAL>();
Console.WriteLine("当前类型:{0},父类型:{1}", person.GetType(), person.GetType().BaseType);
Console.WriteLine();
person.SayHello();//拦截
Console.WriteLine();
person.SayName("Never、C");//拦截
Console.WriteLine();
person.SayOther();//普通方法,无法拦截
//person.AbstactSayOther();//抽象方法,可以拦截(但是如果方法没实现拦截时会报错)
Console.ReadLine();
}
}
}
|
ac7f0c66999e6f73f3f1dcc53caf8001c1b34682
|
C#
|
tlacure17/Collatz
|
/src/Collatz.Tests/CollatzSequenceTests.cs
| 2.640625
| 3
|
using NUnit.Framework;
using System;
using System.Collections.Immutable;
using System.Numerics;
namespace Collatz.Tests
{
public static class CollatzSequenceTests
{
[Test]
public static void Generate()
{
var start = new BigInteger(5);
var sequence = CollatzSequenceGenerator.Generate(start);
Assert.That(sequence, Is.EqualTo(ImmutableArray.Create<BigInteger>(5, 8, 4, 2, 1)));
}
[Test]
public static void GenerateWithIncorrectStartValue() =>
Assert.That(() => CollatzSequenceGenerator.Generate(BigInteger.One),
Throws.TypeOf<ArgumentException>());
[Test]
public static void GenerateStream()
{
var start = new BigInteger(5);
var sequence = CollatzSequenceGenerator.GenerateStream(start).ToImmutableArray();
Assert.That(sequence, Is.EqualTo(ImmutableArray.Create<BigInteger>(5, 8, 4, 2, 1)));
}
[Test]
public static void GenerateStreamWithIncorrectStartValue() =>
Assert.That(() => CollatzSequenceGenerator.GenerateStream(BigInteger.One).ToImmutableArray(),
Throws.TypeOf<ArgumentException>());
}
}
|
99f77bbe6de54c5b9b61936ea8517e18da954277
|
C#
|
NPNikolov/HomeWrks-Fundamentals-Jan-2018
|
/ByThemes/p01_debitCardNumber/p05_Character_Stats/Program.cs
| 3.65625
| 4
|
using System;
namespace p05_Character_Stats
{
class Program
{
static void Main(string[] args)
{
String name = Console.ReadLine();
int health = int.Parse(Console.ReadLine());
int maxHealth = int.Parse(Console.ReadLine());
int energy = int.Parse(Console.ReadLine());
int maxEnergy = int.Parse(Console.ReadLine());
char[] strArrHealth = new char[maxHealth+2];
char[] strArrEnergy = new char[maxEnergy+2];
strArrHealth[0] = '|';
strArrHealth[maxHealth+1] = '|';
strArrEnergy[0] = '|';
strArrEnergy[maxEnergy + 1] = '|';
for (int i = 1;i<= maxHealth; i++)
{
if (i > health)
{
strArrHealth[i] = '.';
}
else strArrHealth[i] = '|';
}
string hlth = "";
for (int i = 0; i <= maxHealth+1; i++)
{
hlth = hlth + strArrHealth[i];
}
for (int i = 1; i <= maxEnergy; i++)
{
if (i > energy)
{
strArrEnergy[i] = '.';
}
else strArrEnergy[i] = '|';
}
string enrg = "";
for (int i = 0; i <= maxEnergy + 1; i++)
{
enrg = enrg + strArrEnergy[i];
}
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Health: {hlth}");
Console.WriteLine($"Energy: {enrg}");
}
}
}
|
471a2c76ef5ae992b4a1eb707bde76edd905eed4
|
C#
|
asdfasdf126/ASL-Translation-Gesture-Recognition
|
/SeniorProject/DebugUC.xaml.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SeniorProject
{
/// <summary>
/// Interaction logic for DebugUC.xaml
/// </summary>
public partial class DebugUC : UserControl
{
public DebugUC()
{
InitializeComponent();
dataGrid.AutoGenerateColumns = false;
DataGridTextColumn nameCol = new DataGridTextColumn();
Binding nameBind = new Binding("Name");
nameCol.Binding = nameBind;
nameCol.Header = "Gesture Name";
DataGridTextColumn percentCol = new DataGridTextColumn();
Binding percentBind = new Binding("Percent");
percentCol.Binding = percentBind;
percentCol.Header = "Confidence level";
dataGrid.Columns.Add(nameCol);
dataGrid.Columns.Add(percentCol);
dataGrid.FontSize = 32;
dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
this.SizeChanged += DebugUC_SizeChanged;
}
private void DebugUC_SizeChanged(object sender, SizeChangedEventArgs e)
{
dataGrid.Height = this.Height;
dataGrid.Width = this.Width;
}
public void addGesture(string gestureName)
{
if (contains(gestureName) != -1)
return;
dataGrid.Items.Add(new GestureData() { Name = gestureName, Percent = 0 });
}
private int contains(string name)
{
for (int x = 0; x < dataGrid.Items.Count; x++)
{
GestureData gd = (GestureData)dataGrid.Items[x];
if (gd.Name.Equals(name))
return x;
}
return -1;
}
public void reset()
{
for (int x = 0; x < dataGrid.Items.Count; x++)
((GestureData)dataGrid.Items[x]).Percent = 0;
}
public void setPercent(string name, float percent)
{
int pos = contains(name);
if (pos == -1)
return;
GestureData gd = (GestureData)dataGrid.Items[contains(name)];
//if (gd.Percent < percent)
{
gd.Percent = (float)Math.Round(percent,2);
dataGrid.Items.Refresh();
}
}
}
}
|
12ad0114c060601aac1d44feb192cf180f7b1f02
|
C#
|
beller0ph0nt/Robot
|
/TSAnalisator 3.0/Robot/TransportStructures/Point/Point.cs
| 3
| 3
|
namespace Robot.TransportStructures
{
public class Point : IPoint
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public override string ToString()
{
return string.Format("[{0}; {1}]", X, Y);
}
}
}
|
7715327c6cf6f1546c7a3de69e89dcb2c71c80e3
|
C#
|
Drutol/CrossHMI
|
/CrossHMI/CrossHMI.LibraryIntegration.AzureGateway/Infrastructure/AzurePublisher.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CrossHMI.LibraryIntegration.AzureGateway.Interfaces;
using Microsoft.Extensions.Logging;
namespace CrossHMI.LibraryIntegration.AzureGateway.Infrastructure
{
///<inheritdoc/>
public class AzurePublisher : IAzurePublisher
{
private readonly ILogger<AzurePublisher> _logger;
private readonly List<AzurePublisherDeviceHandle> _deviceHandles = new List<AzurePublisherDeviceHandle>();
private Func<IAzureEnabledNetworkDevice, AzurePublisherDeviceHandle> _handleFactory;
public AzurePublisher(
Func<IAzureEnabledNetworkDevice, AzurePublisherDeviceHandle> handleFactory,
ILogger<AzurePublisher> logger = null)
{
_logger = logger;
_handleFactory = handleFactory;
}
///<inheritdoc/>
public async Task CancelDevicePublishingAsync(IAzureEnabledNetworkDevice device)
{
var existingHandle = _deviceHandles.FirstOrDefault(handle => handle.Device == device);
if (existingHandle is null)
throw new ArgumentException(
$"Provided {nameof(device)} parameter has not been registered for publishing.");
_deviceHandles.Remove(existingHandle);
await existingHandle.DisposeAsync();
}
///<inheritdoc/>
public async Task<bool> RegisterDeviceForPublishingAsync(IAzureEnabledNetworkDevice azureEnabledNetworkDevice)
{
try
{
var handle = _handleFactory(azureEnabledNetworkDevice);
if (await handle.Initialize().ConfigureAwait(false))
{
handle.StartPublishing();
}
else
{
_logger?.LogError(
$"Failed to register device {azureEnabledNetworkDevice?.AzureDeviceParameters?.AzureDeviceId}");
return false;
}
}
catch (Exception e)
{
_logger?.LogError(e,
$"Failed to register device {azureEnabledNetworkDevice?.AzureDeviceParameters?.AzureDeviceId}");
throw;
}
return true;
}
}
}
|
1e4d62a37bc21a248e3ac1fd25e408bd8c6d4e71
|
C#
|
EnhuiGuo/mvc-projects
|
/SouthlandMetals.Core/Domain/Repositories/StateRepository.cs
| 2.875
| 3
|
using SouthlandMetals.Core.Domain.DBModels;
using SouthlandMetals.Core.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace SouthlandMetals.Core.Domain.Repositories
{
public class StateRepository : IStateRepository, IDisposable
{
private readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private SouthlandDb _db;
private bool disposed = false;
public StateRepository()
{
_db = new SouthlandDb();
}
/// <summary>
/// get selectable states
/// </summary>
/// <returns></returns>
public List<SelectListItem> GetSelectableStates()
{
var states = new List<SelectListItem>();
try
{
states = _db.State.Select(y => new SelectListItem()
{
Text = y.Name,
Value = y.StateId.ToString()
}).OrderBy(z => z.Text).ToList();
}
catch (Exception ex)
{
logger.ErrorFormat("Error getting states: {0} ", ex.ToString());
}
return states;
}
/// <summary>
/// get state by id
/// </summary>
/// <param name="stateId"></param>
/// <returns></returns>
public State GetState(Guid? stateId)
{
var state = new State();
try
{
state = _db.State.FirstOrDefault(x => x.StateId == stateId);
}
catch (Exception ex)
{
logger.ErrorFormat("Error getting state: {0} ", ex.ToString());
}
return state;
}
/// <summary>
/// get state by name
/// </summary>
/// <param name="stateName"></param>
/// <returns></returns>
public State GetState(string stateName)
{
var state = new State();
try
{
if (stateName == "mg")
{
state = _db.State.FirstOrDefault(x => x.Abbreviation == "MG");
}
else
{
state = _db.State.FirstOrDefault(x => x.Abbreviation.Replace(" ", string.Empty).ToLower() == stateName.Replace(" ", string.Empty).ToLower());
}
}
catch (Exception ex)
{
logger.ErrorFormat("Error getting state: {0} ", ex.ToString());
}
return state;
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
_db.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
9c255814324428d6526f6f175a360f708095bee8
|
C#
|
Steveiwonder/DataMasker
|
/src/DataMasker/Models/ColumnConfig.cs
| 2.8125
| 3
|
using System.Collections.Generic;
using System.ComponentModel;
using Newtonsoft.Json;
namespace DataMasker.Models
{
/// <summary>
/// Column Configuration
/// </summary>
public class ColumnConfig
{
/// <summary>
/// The name of the column
/// </summary>
/// <value>
/// The name.
/// </value>
[JsonRequired]
public string Name { get; set; }
/// <summary>
/// The type of data contained within the column, fist name, last name, date of birth etc.
/// </summary>
/// <value>
/// The type.
/// </value>
[JsonRequired]
public DataType Type { get; set; }
/// <summary>
/// Specific value mappings
/// <remarks>
/// e.g. If value "Steve" is found always replace it with "John"
/// </remarks>
/// </summary>
/// <value>
/// The value mappings.
/// </value>
public IDictionary<object, object> ValueMappings { get; set; }
/// <summary>
/// When generated data for this column, take into consideration a gender column, can be null
/// </summary>
/// <value>
/// The use gender column.
/// </value>
[DefaultValue(null)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string UseGenderColumn { get; set; }
/// <summary>
/// When specifying a column that doesn't need to be masked but is needed in the select, such a gender column.
/// You don't want to change the gender, but you need the gender data to be able to create data for other columns
/// </summary>
/// <value>
/// <c>true</c> if ignore; otherwise, <c>false</c>.
/// </value>
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool Ignore { get; set; }
/// <summary>
/// Only used for some data tables, but when generating lorem ipsum you specify the number of words
/// </summary>
/// <value>
/// The maximum.
/// </value>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string Max { get; set; }
/// <summary>
/// Only used for some data tables, but when generating lorem ipsum you specify the number of words
/// </summary>
/// <value>
/// The minimum.
/// </value>
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string Min { get; set; }
/// <summary>
/// If the <see cref="Type"/> is <see cref="DataType.StringFormat"/> you can specify any a format to use when generating
/// that data
/// <remarks>See https://github.com/bchavez/Bogus#replace</remarks>
/// </summary>
/// <value>
/// The string format pattern.
/// </value>
[DefaultValue(null)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string StringFormatPattern { get; set; }
/// <summary>
/// When set, this value will be used for all rows
/// </summary>
/// <value>
/// The use value.
/// </value>
[DefaultValue(null)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public string UseValue { get; set; }
/// <summary>
/// When true, if the data loaded from the source is null, then no new data will be generated.
/// When false, if the data loaded from the source is null it will be replaced by new data
/// </summary>
/// <value>
/// <c>true</c> if [retain null values]; otherwise, <c>false</c>.
/// </value>
[DefaultValue(true)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool RetainNullValues { get; set; }
/// <summary>
/// When true, if the data loaded from the source is an empty string (String.IsNullOrWhitespace), then no new data will be generated.
/// When false, if the data loaded from the source is an empty string (String.IsNullOrWhitespace) it will be replaced by new data
/// </summary>
/// <value>
/// <c>true</c> if [retain empty values]; otherwise, <c>false</c>.
/// </value>
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool RetainEmptyStringValues { get; set; }
/// <summary>
/// When true, mappings specific to this column will be used
/// <remarks>
/// If you have 10 rows of data each with column "Surname" and you will for all the people with the same surname
/// to get a new surname but shared, this should be true.
/// </remarks>
/// </summary>
/// <value>
/// <c>true</c> if [use local value mappings]; otherwise, <c>false</c>.
/// </value>
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool UseLocalValueMappings { get; set; }
/// <summary>
/// This works the same way as <see cref="UseLocalValueMappings"/> but is shared across <see cref="TableConfig"/>'s
/// </summary>
/// <value>
/// <c>true</c> if [use global value mappings]; otherwise, <c>false</c>.
/// </value>
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool UseGlobalValueMappings { get; set; }
/// <summary>
/// When true, any values replaced in this column will be unique
/// </summary>
[DefaultValue(false)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool Unique { get; set; }
/// <summary>
/// Use in conjunction with <see cref="DataType.Sql" />
/// </summary>
public SqlValueConfig SqlValue { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Separator { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public string[] SourceColumns { get; set; }
}
}
|
7a25fea1e2c6339d3528a5606326678ea37eb576
|
C#
|
mjcarpenter/GeneticAlgorithms
|
/GeneticAlgorithms/GeneticAlgorithmLibrary/Models/GeneticAlgorithmConfig.cs
| 3.546875
| 4
|
namespace GeneticAlgorithmLibrary.Models
{
/// <summary>
/// Holds the configuration for a standard genetic algorithm.
/// </summary>
public abstract class GeneticAlgorithmConfig
{
#region Constructor
/// <summary>
/// Creates a new GeneticAlgorithmConfig to hold the provided configuration options.
/// </summary>
/// <param name="generations">The number of generations to evolve solutions for.</param>
/// <param name="populationSize">The candidate solution population size.</param>
/// <param name="mutationRate">The value to be used when determining whether to mutate a solution or not. (1/MutationRate probability to mutate).</param>
public GeneticAlgorithmConfig(int generations, int populationSize, int mutationRate)
{
Generations = generations;
PopulationSize = populationSize;
MutationRate = mutationRate;
}
#endregion
#region Properties
/// <summary>
/// The number of generations to evolve solutions for.
/// </summary>
public int Generations { get; private set; }
/// <summary>
/// The candidate solution population size.
/// </summary>
public int PopulationSize { get; private set; }
/// <summary>
/// The value to be used when determining whether to mutate a solution or not. (1/MutationRate probability to mutate).
/// </summary>
public int MutationRate { get; private set; }
#endregion
}
}
|
aaebf6682c3dcd73c6714897c4c5daa82d6b36fb
|
C#
|
andrii-baranov/algo1
|
/Algo1.Core/BitManipulations.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algo1.Core
{
public class BitManipulations
{
public static int CheckBitConversion(int a, int b)
{
int n = 0;
while (a != b)
{
if ((a & 1) != (b & 1))
{
n++;
}
a >>= 1;
b >>= 1;
}
return n;
}
public static int SwapOddAndEvenBits(int a)
{
uint aA = (uint)a;
uint maskOdd = 0x55555555 ;
uint maskEven = 0xAAAAAAA;
uint even_bits = (aA & maskEven) >> 1;
uint odd_bits = (aA & maskOdd) << 1;
return (int)(even_bits | odd_bits);
}
public static void Drawline(byte[] screen, int width, int x1, int x2, int y)
{
int height = screen.Length / width;
int startPos = y * width + x1;
int endPos = y * width + x1 + x2;
for (int i = startPos; i<endPos; i++)
{
screen[i] = Byte.MaxValue;
}
}
public bool IsPrimeNumber(int n)
{
if (n < 2)
{
return false;
}
for (int i = 2; i < Math.Sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
public bool[] CalculatePrimes(int max)
{
bool[] primeMatrix = new bool[max +1];
int count = 0;
int prime = 2;
while (prime <= max)
{
CrossNonPrimes(primeMatrix, prime);
prime = GetNextPrime(primeMatrix, prime);
}
return primeMatrix;
}
private static void CrossNonPrimes(bool[] primeM, int prime)
{
for (int i = prime * prime; i < primeM.Length; i = i + prime)
{
primeM[i] = true;
}
}
private static int GetNextPrime(bool[] primes,int currentPrime)
{
int next = currentPrime + 1;
while (next < primes.Length && primes[next] == false)
{
next++;
}
return next;
}
}
}
|
78ba73955f6dc3f663be1fb37cfe6e4feaabcf14
|
C#
|
unity-game-framework/ugf-messagepack
|
/MessagePack/MessagePackUnsafeUtility.cs
| 2.640625
| 3
|
using System;
using System.Runtime.CompilerServices;
namespace MessagePack
{
/// <summary>
/// Provides unsafe utilities.
/// </summary>
public static class MessagePackUnsafeUtility
{
/// <summary>
/// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo">TTo</typeparamref>.
/// </summary>
/// <param name="from">The reference to reinterpret.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref TTo As<TTFrom, TTo>(ref TTFrom from)
{
// IL_0000: ldarg.0
// IL_0001: ret
throw new NotSupportedException("This method must be patched.");
}
}
}
|
85ff57f34a9f59760cabcc63d20f789978fe098c
|
C#
|
petegamble/justgoride.cc
|
/src/JustGoRide.cc.Providers/ClubEntityFrameworkProvider.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JustGoRide.cc.Interfaces;
using JustGoRide.cc.Models;
namespace JustGoRide.cc.Providers
{
public class ClubEntityFrameworkProvider : IClubProvider
{
private ClubContext _context;
public ClubEntityFrameworkProvider(ClubContext context)
{
_context = context;
}
public List<Club> GetClubs()
{
using (_context)
{
var clubs = _context.Clubs.AsEnumerable();
return clubs.ToList();
}
}
public Club GetClub(Guid id)
{
using (_context)
{
var club = _context.Clubs.FirstOrDefault(c => c.Id == id);
return club;
}
}
}
}
|
4346aeff7d52641fe4bdde072de88e472e2e0298
|
C#
|
radtek/SmartQueueSys-master
|
/EntCodeGener/bin/Debug/bac/EntFrm.Business.Model/Collections/OutlineTypeCollections.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace EntFrm.Business.Model.Collections
{
public class OutlineTypeCollections:CollectionBase
{
public OutlineType this[int index]
{
get { return (OutlineType)List[index]; }
set { List[index] = value; }
}
public int Add(OutlineType value)
{
return (List.Add(value));
}
public int IndexOf(OutlineType value)
{
return (List.IndexOf(value));
}
public void Insert(int index, OutlineType value)
{
List.Insert(index, value);
}
public void Remove(OutlineType value)
{
List.Remove(value);
}
public bool Contains(OutlineType value)
{
return (List.Contains(value));
}
public OutlineType GetFirstOne()
{
return this[0];
}
}
}
|
5150f789a3cc8c70c698e4c6fd99d4158be25d8b
|
C#
|
joshvisler/YouControl-Test-Task
|
/SockNet/ClientSocket/SocketClient.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SockNet.Utils;
[assembly: InternalsVisibleTo("SockNet.UnitaryTests")]
[assembly: InternalsVisibleTo("SockNet.IntegrationTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace SockNet.ClientSocket
{
///<inheritdoc/>
public sealed class SocketClient : ISocketClient
{
#region private local variables declaration
private string _socketIP;
private int _socketPort;
private int _connectionTimeout;
private int _sendTimeout;
private int _receiveTimeout;
private ITcpClient _TcpClient;
private byte[] _messageReaded;
private int _bufferSize;
#endregion
/// <summary>
/// IP of the server specified.
/// </summary>
public string SocketIP { get => _socketIP; }
/// <summary>
/// Port of the server specified.
/// </summary>
public int SocketPort { get => _socketPort; }
/// <summary>
/// Timeout for the initial socket connection.
/// </summary>
public int ConnectionTimeout { get => _connectionTimeout; }
/// <summary>
/// Timeout for the sending messages.
/// </summary>
public int SendTimeout { get => _sendTimeout; }
/// <summary>
/// Timeout for when receiving data.
/// </summary>
public int ReceiveTimeout { get => _receiveTimeout; }
/// <summary>
/// Instance with information of the TcpClient and NetworkStream.
/// </summary>
internal ITcpClient TcpClient { get => _TcpClient; }
/// <summary>
/// Message readed from the server.
/// </summary>
public byte[] MessageReaded { get => _messageReaded; }
/// <summary>
/// Buffer size for tcp sending or receiving data.
/// </summary>
public int BufferSize { get => _bufferSize; }
/// <summary>
/// Constructor that sets connection IP and port for socket server connection.
/// </summary>
/// <param name="socketIP">IP represented as string.</param>
/// <param name="socketPort">Port number of the server listening.</param>
public SocketClient(string socketIP, int socketPort)
:this(
socketIP,
socketPort,
ServiceLocator.Current.Get<ITcpClient>()
)
{ }
internal SocketClient(string socketIP, int socketPort, ITcpClient tcpClient)
{
_socketIP = socketIP;
_socketPort = socketPort;
_TcpClient = tcpClient;
_connectionTimeout = 5000;
_sendTimeout = 10000;
_receiveTimeout = 10000;
_bufferSize = 512;
}
/// <inheritdoc/>
public async Task<bool> Connect()
{
bool success = false;
await TcpClient.Connect(SocketIP, SocketPort);
if (TcpClient.Connected())
{
TcpClient.GetStream();
if (TcpClient.IsValidNetStream()) success = true;
else success = false;
}
else success = false;
return success;
}
/// <inheritdoc/>
public void Disconnect()
{
if (TcpClient.Connected())
{
TcpClient.Disconnect();
}
}
/// <inheritdoc/>
public void Close()
{
TcpClient.Close();
}
/// <inheritdoc/>
public void Dispose()
{
TcpClient.Dispose();
}
/// <inheritdoc />
public async Task Send(string data)
{
if (string.IsNullOrWhiteSpace(data)) throw new ArgumentException(data, "The message to send can not be empty.");
await Send(Utils.Conversor.StringToBytes(data), SendTimeout);
}
/// <inheritdoc />
public async Task Send(byte[] data)
{
await Send(data, SendTimeout);
}
/// <inheritdoc />
public async Task Send(byte[] data, int sendTimeout)
{
if (data is null) throw new ArgumentNullException();
if (sendTimeout <= 0) throw new ArgumentException(sendTimeout.ToString(), "Timeout has to be greater than 0.");
await Utils.TcpStreamSender.SendData(data, _TcpClient, _sendTimeout);
}
/// <inheritdoc />
public async Task<byte[]> ReceiveBytes()
{
_messageReaded = await Utils.TcpStreamReceiver.ReceiveBytesUntilDataAvailableAsync(TcpClient, BufferSize, TcpClient.GetNetworkStream());
return _messageReaded;
}
/// <inheritdoc />
public async Task<byte[]> ReceiveBytes(int bufferSize)
{
_messageReaded = await Utils.TcpStreamReceiver.ReceiveBytesUntilDataAvailableAsync(TcpClient, bufferSize, TcpClient.GetNetworkStream());
return _messageReaded;
}
/// <inheritdoc />
public async Task<byte[]> ReceiveNumberOfBytes(int bufferSize, int numberBytesToRead)
{
_messageReaded = await Utils.TcpStreamReceiver.ReceiveNumberOfBytes(TcpClient, bufferSize, numberBytesToRead, TcpClient.GetNetworkStream());
return _messageReaded;
}
/// <inheritdoc />
public async Task<byte[]> ReceiveBytesWithDelimitators(byte[] startDelimitator, byte[] endDelimitator)
{
_messageReaded = await Utils.TcpStreamReceiver.ReceiveBytesWithDelimitators(TcpClient, startDelimitator, endDelimitator, TcpClient.GetNetworkStream());
return _messageReaded;
}
/// <inheritdoc />
public async Task<byte[]> ReceiveBytesWithEndDelimitator(byte[] endDelimitator)
{
_messageReaded = await Utils.TcpStreamReceiver.ReceiveBytesWithEndingDelimitator(TcpClient, endDelimitator, TcpClient.GetNetworkStream());
return _messageReaded;
}
/// <summary>
/// Converts the message received in bytes to ASCII string.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Encoding.ASCII.GetString(_messageReaded);
}
}
}
|
3eee5f175ff81cbbfc3063ff078d265910d7b918
|
C#
|
OlaPietka/Calculator-WPF-MVVM
|
/Calculator/ViewModel.cs
| 3.171875
| 3
|
using System;
using System.Windows.Input;
namespace Calculator
{
class ViewModel : ViewModelBase
{
bool isSumDisplayed = true;
double left = 0;
double right;
string rememberOperator;
bool firstOperation = true;
public ViewModel()
{
Number = new RelayCommand(
(parameter) =>
{
if (isSumDisplayed || Equation.Equals("0"))
Equation = (string)parameter;
else
Equation += parameter;
isSumDisplayed = false;
RefreshCanExecutes();
},
(obj) =>
{
return isSumDisplayed || Equation.Length < 16;
});
Point = new RelayCommand(
(obj) =>
{
if (Equation.Equals("0"))
Equation = "0.";
else
Equation += ".";
isSumDisplayed = false;
RefreshCanExecutes();
},
(obj) =>
{
return isSumDisplayed || !Equation.Contains(".");
});
Operator = new RelayCommand(
(parameter) =>
{
if (firstOperation)
{
left = Double.Parse(Equation);
firstOperation = false;
rememberOperator = (string)parameter;
HistoryEquation += left.ToString() + parameter;
}
else
{
right = Double.Parse(Equation);
HistoryEquation += right.ToString() + parameter;
switch (rememberOperator)
{
case "+":
left += right;
break;
case "-":
left -= right;
break;
case "*":
left *= right;
break;
case "/":
left /= right;
break;
}
rememberOperator = (string)parameter;
}
Equation = left.ToString();
isSumDisplayed = true;
RefreshCanExecutes();
},
(parameter) =>
{
return !isSumDisplayed;
});
Ce = new RelayCommand(
(obj) =>
{
left = 0;
HistoryEquation = "";
Equation = "0";
isSumDisplayed = false;
RefreshCanExecutes();
});
C = new RelayCommand(
(obj) =>
{
right = 0;
Equation = "0";
isSumDisplayed = false;
RefreshCanExecutes();
},
(obj) =>
{
return !isSumDisplayed;
});
Bcs = new RelayCommand(
(obj) =>
{
Equation = Equation.Substring(0, Equation.Length - 1);
if (Equation.Length == 0)
{
Equation = "0";
}
RefreshCanExecutes();
},
(obj) =>
{
return !isSumDisplayed && (Equation.Length > 1 || Equation[0] != '0');
});
}
void RefreshCanExecutes()
{
((RelayCommand)Bcs).OnCanExecuteChanged();
((RelayCommand)Number).OnCanExecuteChanged();
((RelayCommand)Point).OnCanExecuteChanged();
((RelayCommand)Operator).OnCanExecuteChanged();
}
public string Equation
{
private set { SetProperty(ref equation, value); }
get { return equation; }
}
public string HistoryEquation
{
private set { SetProperty(ref historyEquation, value); }
get { return historyEquation; }
}
public ICommand Number { private set; get; }
public ICommand Point { private set; get; }
public ICommand Operator { private set; get; }
public ICommand Ce { private set; get; }
public ICommand C { private set; get; }
public ICommand Bcs { private set; get; }
public string equation = "0";
public string historyEquation = "";
}
}
|
79892d431c5943772342725ef2e272892c8cdecb
|
C#
|
drich223/CSharp
|
/Lab4Pt2/Program.cs
| 3.6875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab4
{
class Program
{
class Person
{
public string firstName;
public string middleName;
public string lastName;
public string Street1;
public string Street2;
public string City;
public string State;
public string Zip;
public string Phone;
}
static void Main(string[] args)
{
//Helps not create errors from user
bool boolResult = false;
//Allows for temp to be used
Person temp = new Person();
//Gathers first name
Console.Write("\nPlease enter your first name: ");
temp.firstName = Console.ReadLine();
temp.firstName += " Poopy";
//Gathers middle name
Console.Write("\nPlease enter your middle name: ");
temp.middleName = Console.ReadLine();
//Gathers last name
Console.Write("\nPlease enter your last name: ");
temp.lastName = Console.ReadLine();
//Gathers Street1
Console.Write("\nPlease enter your primary street address: ");
temp.Street1 = Console.ReadLine();
//Gathers Street2
Console.Write("\nPlease enter any secondary street address (leave blank if there isn't any): ");
temp.Street2 = Console.ReadLine();
//Gathers City
Console.Write("\nPlease enter your city: ");
temp.City = Console.ReadLine();
//Gathers State
Console.Write("Please enter your State (MA,CA,FL,etc): ");
temp.State = Console.ReadLine();
//Gathers Zip
Console.Write("Please enter your zip code: ");
temp.Zip = Console.ReadLine();
//Gathers Phone
Console.Write("Please enter your phone number (with dashes):");
temp.Phone = Console.ReadLine();
Console.Clear();
//PRINTS DATA
Console.Write("Here is the information we gathered");
Console.Write("\n-----------------------------------");
Console.Write($"\nFirst Name: {temp.firstName}");
Console.Write($"\nMiddle Name: {temp.middleName}");
Console.Write($"\nLast Name: {temp.lastName}");
Console.Write($"\nStreet 1: {temp.Street1}");
Console.Write($"\nStreet 2: {temp.Street2}");
Console.Write($"\nCity: {temp.City}");
Console.Write($"\nState: {temp.State}");
Console.Write($"\nZip: {temp.Zip}");
Console.Write($"\nPhone: {temp.Phone}");
Console.Write("\nPress any key to exit: ");
Console.ReadKey();
}
}
}
|
3cbe665208ba6c55874dccb1a441c7d64b716106
|
C#
|
ysfada/Bookshelf_WinForms
|
/Database/Repositories/BookIssueRepository.cs
| 2.59375
| 3
|
using Bookshelf.Database.Entities;
using Bookshelf.Utilities;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Bookshelf.Database.Repositories
{
internal static class BookIssueRepository
{
//private const int RowPerPage = 2;
internal static async Task<BookIssueEntity> GiveBookAsync(BookIssueEntity bookIssue)
{
//await Task.Delay(3000);
await using var connection = Database.CreateConnection();
const string cmdText = @"
BEGIN TRANSACTION [BookIssueEntity_GiveBookAsync]
BEGIN TRY
UPDATE dbo.[Book]
SET [Borrowed]=1
WHERE [Id]=@bookId
DECLARE @bookIssueTableVariable TABLE(
[Id] UNIQUEIDENTIFIER NOT NULL,
[UserId] UNIQUEIDENTIFIER NOT NULL,
[BookId] UNIQUEIDENTIFIER NOT NULL,
[IssuerId] UNIQUEIDENTIFIER NOT NULL,
[ReceiverId] UNIQUEIDENTIFIER NULL,
[IssuedAt] DATETIME NOT NULL,
[DueDate] DATE NOT NULL,
[ReturnedAt] DATETIME NULL,
[Returned] BIT NOT NULL
);
INSERT INTO [dbo].[BookIssue]
([UserId], [BookId], [IssuerId], [DueDate])
OUTPUT Inserted.[Id], Inserted.[UserId], Inserted.[BookId], [Inserted].[IssuerId], [Inserted].[ReceiverId], [Inserted].[IssuedAt], [Inserted].[DueDate], [Inserted].[ReturnedAt], [Inserted].[Returned]
INTO @bookIssueTableVariable
VALUES (@userId, @bookId, @issuerId, @duaDate);
SELECT t.[Id], t.[UserId], usr.[Username], t.[BookId], book.[BookName], t.[IssuerId], issuer.[Username], t.[ReceiverId], receiver.[Username], t.[IssuedAt], t.[DueDate], t.[ReturnedAt], t.[Returned]
FROM @bookIssueTableVariable t
JOIN [dbo].[Book] book ON book.[Id] = t.[BookId]
JOIN [dbo].[User] usr ON usr.[Id] = t.[UserId]
JOIN [dbo].[User] issuer ON issuer.[Id] = t.[IssuerId]
LEFT OUTER JOIN [dbo].[User] receiver ON receiver.[Id] = t.[ReceiverId];
COMMIT TRANSACTION [BookIssueEntity_GiveBookAsync]
END TRY
BEGIN CATCH
DECLARE
@ErrorMessage NVARCHAR(max),
@ErrorSeverity INT,
@ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE() + ' Line ' + CAST(ERROR_LINE() AS NVARCHAR(5)),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
if @@TRANCOUNT > 0
ROLLBACK TRANSACTION [Tran1]
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH";
var command = new SqlCommand(cmdText, connection);
command.Parameters.Add("@userId", SqlDbType.UniqueIdentifier).Value = bookIssue.UserId;
command.Parameters.Add("@bookId", SqlDbType.UniqueIdentifier).Value = bookIssue.BookId;
command.Parameters.Add("@issuerId", SqlDbType.UniqueIdentifier).Value = bookIssue.IssuerId;
command.Parameters.Add("@duaDate", SqlDbType.Date).Value = bookIssue.DueDate;
await command.Connection.OpenAsync();
var reader = await command.ExecuteReaderAsync();
if (!reader.Read()) return null;
var newBookIssue = new BookIssueEntity()
{
Id = reader.GetGuid(0),
UserId = reader.GetGuid(1),
User = new UserEntity() {Username = reader.GetString(2)},
BookId = reader.GetGuid(3),
Book = new BookEntity() {BookName = reader.GetString(4)},
IssuerId = reader.GetGuid(5),
Issuer = new UserEntity() {Username = reader.GetString(6)},
ReceiverId = reader.GetGuidSafe(7),
Receiver = new UserEntity() {Username = reader.GetStringSafe(8)},
IssuedAt = reader.GetDateTime(9),
DueDate = reader.GetDateTime(10),
ReturnedAt = reader.GetDateTimeSafe(11),
Returned = reader.GetBoolean(12)
};
return newBookIssue;
}
internal static async Task<BookIssueEntity> TakeBookAsync(Guid bookId, Guid receiverId)
{
//await Task.Delay(3000);
await using var connection = Database.CreateConnection();
const string cmdText = @"
BEGIN TRANSACTION [BookIssueEntity_TakeBookAsync]
BEGIN TRY
UPDATE dbo.[Book]
SET [Borrowed]=0
WHERE [Id]=@bookId
DECLARE @bookIssueId TABLE (
[Id] UNIQUEIDENTIFIER NOT NULL
);
UPDATE TOP (1) [dbo].[BookIssue]
SET [Returned]=1,
[ReceiverId]=@receiverId
OUTPUT Inserted.[Id]
INTO @bookIssueId
WHERE [Id]=(
SELECT TOP (1) [Id]
FROM [dbo].[BookIssue]
WHERE [BookId]=@bookId AND [Returned]=0
);
SELECT TOP (1) bookIssue.[Id], bookIssue.[UserId], usr.[Username], bookIssue.[BookId], book.[BookName], bookIssue.[IssuerId], issuer.[Username], bookIssue.[ReceiverId], receiver.[Username], bookIssue.[IssuedAt], bookIssue.[DueDate], bookIssue.[ReturnedAt], bookIssue.[Returned]
FROM [dbo].[BookIssue] bookIssue
JOIN [dbo].[Book] book ON book.[Id] = bookIssue.[BookId]
JOIN [dbo].[User] usr ON usr.[Id] = bookIssue.[UserId]
JOIN [dbo].[User] issuer ON issuer.[Id] = bookIssue.[IssuerId]
LEFT OUTER JOIN [dbo].[User] receiver ON receiver.[Id] = bookIssue.[ReceiverId]
WHERE bookIssue.[Id]=(SELECT TOP (1) [Id] FROM @bookIssueId);
COMMIT TRANSACTION [BookIssueEntity_TakeBookAsync]
END TRY
BEGIN CATCH
DECLARE
@ErrorMessage NVARCHAR(max),
@ErrorSeverity INT,
@ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE() + ' Line ' + CAST(ERROR_LINE() AS NVARCHAR(5)),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
if @@TRANCOUNT > 0
ROLLBACK TRANSACTION [Tran1]
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH";
var command = new SqlCommand(cmdText, connection);
command.Parameters.Add("@bookId", SqlDbType.UniqueIdentifier).Value = bookId;
command.Parameters.Add("@receiverId", SqlDbType.UniqueIdentifier).Value = receiverId;
await command.Connection.OpenAsync();
var reader = await command.ExecuteReaderAsync();
if (!reader.Read()) return null;
var newBookIssue = new BookIssueEntity()
{
Id = reader.GetGuid(0),
UserId = reader.GetGuid(1),
User = new UserEntity() {Username = reader.GetString(2)},
BookId = reader.GetGuid(3),
Book = new BookEntity() {BookName = reader.GetString(4)},
IssuerId = reader.GetGuid(5),
Issuer = new UserEntity() {Username = reader.GetString(6)},
ReceiverId = reader.GetGuidSafe(7),
Receiver = new UserEntity() {Username = reader.GetStringSafe(8)},
IssuedAt = reader.GetDateTime(9),
DueDate = reader.GetDateTime(10),
ReturnedAt = reader.GetDateTimeSafe(11),
Returned = reader.GetBoolean(12)
};
return newBookIssue;
}
}
}
|
14221509dd648037546ae7f0b997a610a9a8bbf2
|
C#
|
nlhans/MemoryVision
|
/MemoryVision/DataGrabber/Grabber.cs
| 2.609375
| 3
|
using System;
using System.Threading;
using Triton;
using Triton.Memory;
namespace MemoryVision.DataGrabber
{
public class Grabber
{
public event Signal Done;
public Channels Channels { get; set; }
public Waveform Waveform { get; set; }
public Triggering Trigger { get; set; }
public Configuration Config { get; set; }
public MemoryReader Reader { get; set; }
private Thread _mGrabber;
private MicroStopwatch _mGrabberTiming;
private bool _mGrabberRunning = false;
public bool Running { get { return _mGrabberRunning; } }
public bool Triggered { get { return Trigger.IsTriggered; } }
public double Progress
{
get
{
if(Trigger.IsTriggered)
{
return (1000.0*Waveform.SampleIndex + Config.SamplesBeforeTrigger)/Config.Samples;
}
else
{
return (1000.0*Math.Min(Config.SamplesBeforeTrigger, Waveform.WriteCount))/Config.Samples;
}
}
}
private long _mGrabberCaptureTime = 0;
private long _mGrabberWaitTime = 0;
public Grabber(CheatEngineReader table, MemoryReader reader)
{
Config = new Configuration(this);
//TEMPORARY configuration!
Config.SamplesBeforeTrigger = 750;
Config.SamplesAfterTrigger = 750;
Config.SampleWaitTime = 10000;//ms, 1ms here
Config.Trigger_Simple_Channel = 0; // gear
Config.Trigger_Simple_Condition = TriggerCondition.IN_RANGE; // Rising up
Config.Trigger_Simple_ValueType = MemoryChannelType.INT32;
Config.Trigger_Simple_Value = new byte[4] { 3, 0, 0, 0 }; // INT32 (5)
Config.Trigger_Simple_Value2 = new byte[4] { 5, 0, 0, 0 }; // INT32 (5)
Config.Trigger_Simple = true;
Channels = new Channels(this,table);
Waveform = new Waveform(this);
Trigger = new Triggering(this);
this.Reader = reader;
_mGrabberTiming = new MicroStopwatch();
TritonBase.PreExit += Stop;
}
private void DataGrabber_Timing()
{
_mGrabberWaitTime += Config.SampleWaitTime;
while (_mGrabberTiming.ElapsedMicroseconds <= _mGrabberWaitTime)
Thread.SpinWait(5);
}
private void DataGrabber_Thread()
{
_mGrabberTiming.Start();
while(_mGrabberRunning)
{
if (Trigger.IsTriggered || Config.SamplesBeforeTrigger > 0)
Waveform.Push();
if (Trigger.IsTriggered)
{
if (Waveform.SampleIndex >= Config.Samples)
{
long totalTime = _mGrabberTiming.ElapsedMicroseconds - _mGrabberCaptureTime;
//totalTime /= Config.SampleWaitTime;
_mGrabberRunning = false;
}
}
else
{
Trigger.Check();
_mGrabberCaptureTime = _mGrabberTiming.ElapsedMicroseconds;
}
DataGrabber_Timing();
}
// Finalize waveform
Waveform.Finalize();
// Sent event DONE
if(Done!=null)
Done(this);
}
public void Start()
{
if (_mGrabber == null)
{
_mGrabberRunning = true;
_mGrabber = new Thread(DataGrabber_Thread);
_mGrabber.Start();
}
}
public void Stop()
{
if (_mGrabber != null)
{
_mGrabberRunning = false;
Thread.Sleep(1);
_mGrabber.Abort();
_mGrabber = null;
}
}
}
}
|
10905088a3d6d9fc3d5b8cdcd9711a7aaa4ceaf9
|
C#
|
ukeswani/RomanNumerals
|
/RomanNumerals/RepetitionValidator.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RomanNumerals
{
public class RepetitionValidator : IValidator
{
private IDictionary<char, int> _dict;
public RepetitionValidator(Dictionary<char, int> dict)
{
_dict = dict;
}
public bool IsValid(string input)
{
return
AllowedRepetitionValidation('I', input)
&&
AllowedRepetitionValidation('X', input)
&&
AllowedRepetitionValidation('C', input)
&&
AllowedRepetitionValidation('M', input)
&&
NoRepetitionValidation('D', input)
&&
NoRepetitionValidation('L', input)
&&
NoRepetitionValidation('V', input);
}
private bool NoRepetitionValidation
(
char symbol
, string input
)
{
var inputList = input.ToList();
var inputArray = input.ToArray();
var firstIndex = inputList.FindIndex((ch) => ch.Equals(symbol));
var lastIndex = inputList.FindLastIndex((ch) => ch.Equals(symbol));
var indexDiff = lastIndex - firstIndex;
if (indexDiff != 0)
{
Console.WriteLine("Invalid input\n");
return false;
}
else
{
return true;
}
}
private bool AllowedRepetitionValidation
(
char symbol
, string input
)
{
var inputList = input.ToList();
var inputArray = input.ToArray();
var firstIndex = inputList.FindIndex((ch) => ch.Equals(symbol));
var lastIndex = inputList.FindLastIndex((ch) => ch.Equals(symbol));
var indexDiff = lastIndex - firstIndex;
if (indexDiff > 4)
{
Console.WriteLine("Invalid input\n");
return false;
}
else if (
indexDiff == 4
&&
!(_dict[inputArray[lastIndex]] > _dict[inputArray[lastIndex - 1]])
)
{
Console.WriteLine("Invalid input\n");
return false;
}
else if (
indexDiff == 3
&&
!(
SameConsecutiveCharacters
(
inputArray
, 2
, firstIndex
)
&&
(_dict[inputArray[lastIndex]] > _dict[inputArray[lastIndex - 1]])
)
)
{
Console.WriteLine("Invalid input\n");
return false;
}
else if (
indexDiff == 2
&&
!SameConsecutiveCharacters
(
inputArray
, 3
, firstIndex
)
&&
!(_dict[inputArray[lastIndex]] > _dict[inputArray[lastIndex - 1]])
)
{
Console.WriteLine("Invalid input\n");
return false;
}
else
{
return true;
}
}
private bool SameConsecutiveCharacters
(
char[] inputArray
, int howMany
, int startingIndex
)
{
int count = 1;
for (int i = startingIndex + 1; i < (startingIndex + howMany); i++)
{
if (inputArray[i - 1].Equals(inputArray[i]))
{
count++;
}
}
return count == howMany;
}
}
}
|
6bc9bae8767d535200cb67fa2640066398cc0187
|
C#
|
Ramzi-dev611/TP2.net
|
/TP2_Activity1/DBA_ADO_Deconnecte/Program.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBA_ADO_Deconnecte
{
class Program
{
static void Main(string[] args)
{
DataAccessor dataAccessor = new DataAccessor();
Student student = new Student();
student.Name = "Ramzi";
student.LastName = "Latrous";
student.Email = "ramzi.latrous@insat.u-carthage.tn";
student.Age = 22;
dataAccessor.Add(student);
List <Student> students = dataAccessor.FindAll();
foreach (Student looper in students)
{
Console.WriteLine(looper);
}
Console.WriteLine("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
Student student1 = students[0];
Student student2 = students[1];
student1.Name = "New Name";
dataAccessor.Update(student1);
dataAccessor.Delete(student2.Id);
dataAccessor.CommitChanges();
students = dataAccessor.FindAll();
foreach (Student looper in students)
{
Console.WriteLine(looper);
}
Console.ReadKey();
}
}
}
|
059d4099722cd68debf17b01f25689be8e58da70
|
C#
|
mdiller/bpjson
|
/BpJson/BitPacking/ConstrainedUIntBinaryConverter.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BpJson.BitPacking
{
/// <summary>
/// Represents how to save/load an unsigned integer to/from bytes (values given are ints but theyre assumed to all be >= 0)
/// </summary>
public class ConstrainedUIntBinaryConverter : BinaryConverter<ulong>
{
/// <summary>
/// ctor
/// </summary>
private ConstrainedUIntBinaryConverter(int bitCount)
{
BitCount = bitCount;
}
/// <summary>
/// The maximum length of a string
/// </summary>
public int BitCount { get; }
/// <summary>
/// The length in bits that will be used to contain this type. 0 if length is variable.
/// </summary>
public override int Bits => BitCount;
/// <inheritdoc />
public override void Write(ulong value, BitWriter writer)
{
for (int i = 0; i < Bits; i++)
{
writer.WriteBit((value & ((ulong)1 << i)) != 0);
}
}
/// <inheritdoc />
public override ulong Read(BitReader reader)
{
ulong v = 0;
for (var i = 0; i < Bits; i++)
{
// set bit then shift over
if (reader.ReadBit())
{
v |= (ulong)1 << i;
}
}
return v;
}
/// <summary>
/// Gets the number of bits needed to represent the given max size
/// </summary>
/// <param name="maxValue">The maximum value needing to be stored</param>
/// <returns>The bits needed to store that amount</returns>
public static int MaxValueToBitCount(ulong maxValue)
{
return maxValue == 0 ? 0 : (int)Math.Log(maxValue, 2) + 1;
}
/// <summary>
/// Creates a bitconverter where the passed in value is the number of bits we have available to us
/// </summary>
/// <param name="bitCount">The number of bits we are to write to</param>
/// <returns>The bitconverter</returns>
public static ConstrainedUIntBinaryConverter FromBitCount(int bitCount)
{
return new ConstrainedUIntBinaryConverter(bitCount);
}
/// <summary>
/// Creates a bitconverter where the passed in value is the max value that will need to be represented
/// </summary>
/// <param name="maxValue">The max value that we are able to store</param>
/// <returns>The bitconverter</returns>
public static ConstrainedUIntBinaryConverter FromMaxValue(ulong maxValue)
{
return new ConstrainedUIntBinaryConverter(MaxValueToBitCount(maxValue));
}
}
}
|
0842c342770753233872da1367e3baae832c0b6b
|
C#
|
vdossantosmonteiro/Cadastro
|
/Cadastro/Projeto.Data/Repositories/ClienteRepository.cs
| 2.859375
| 3
|
using Projeto.Data.Contracts;
using Projeto.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using Dapper;
using System.Collections.ObjectModel;
namespace Projeto.Data.Repositories
{
public class ClienteRepository : IClienteRepository
{
private readonly string connectionString;
public ClienteRepository()
{
connectionString = ConfigurationManager.ConnectionStrings["BancoWpf"].ConnectionString;
}
public void Insert(Cliente obj)
{
var query = "insert into Cliente(Nome, Email, DataCriacao) " +
"values(@Nome, @Email, @DataCriacao)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Execute(query, obj);
}
}
public void Delete(int id)
{
var query = "delete from Cliente where IdCliente = @IdCliente";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Execute(query, new {IdCliente = id });
}
}
public ObservableCollection<Cliente> SelectAll()
{
var query = "Select * from Cliente";
using(var connection = new SqlConnection(connectionString))
{
return new ObservableCollection<Cliente>(connection.Query<Cliente>(query));
}
}
public Cliente SelectById(int id)
{
var query = "select * from Cliente where IdCliente = @IdCliente";
using (SqlConnection connection = new SqlConnection(connectionString))
{
return connection.Query<Cliente>(query, new { IdCliente = id }).SingleOrDefault();
}
}
public void Update(Cliente obj)
{
var query = "update Cliente set Nome = @Nome, Email = @Email, DataCriacao = @DataCriacao " +
"where IdCliente = @IdCliente";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Execute(query, obj);
}
}
}
}
|
2dd24be7c465dd8608cd4c37e6267d8084a76ca1
|
C#
|
yuletodim/DataStructuresCourse
|
/7.CoolectionsAndLibraries/3.1.FastSearchStringsInText/FastSearchStringsInText.cs
| 3.65625
| 4
|
namespace FastSearchStringsInText
{
using System;
using System.Collections.Generic;
using System.Linq;
using Wintellect.PowerCollections;
class FastSearchStringsInText
{
static void Main(string[] args)
{
var wantedStrings = ReadWantedStrings();
var readText = ReadText();
FindStringsCount(readText, wantedStrings);
Console.WriteLine("\nResults:");
foreach (var singleString in wantedStrings)
{
Console.WriteLine("{0} - {1}", singleString.Key, singleString.Value);
}
}
private static void FindStringsCount(BigList<char> readText, Dictionary<string, int> wantedStrings)
{
var keys = wantedStrings.Keys.ToList();
foreach (var key in keys)
{
string wantedString = key.ToLower();
var cloneList = readText.Clone();
var index = cloneList.IndexOf(wantedString[0]);
var stringLength = wantedString.Length;
while (index != -1)
{
var rangeToString = string.Join("", cloneList.GetRange(index, stringLength));
if (wantedString == rangeToString)
{
wantedStrings[key] += 1;
}
cloneList.RemoveAt(index);
index = cloneList.IndexOf(wantedString[0]);
}
}
}
private static Dictionary<string, int> ReadWantedStrings()
{
var wantedStrings = new Dictionary<string, int>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
var newString = Console.ReadLine();
wantedStrings.Add(newString, 0);
}
return wantedStrings;
}
private static BigList<char> ReadText()
{
var text = new BigList<char>();
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
char[] newLine = Console.ReadLine().ToLower().ToCharArray();
text.AddRange(newLine);
}
return text;
}
}
}
|
a6b160e7ea6a3c00441a9935a5d72736edf736b6
|
C#
|
PinnacleTechnology/Vantage.Measurements
|
/src/Vantage.Measurements/Prefixes/Nano.cs
| 2.53125
| 3
|
namespace Vantage.Measurements.Prefixes
{
/// <summary>
/// Denotes a factor of one billionth (0.000 000 001) [1e-9]
/// </summary>
public class Nano : IPrefix
{
public static Nano Data { get; } = new Nano();
public string Name { get; } = "Nano";
public string Symbol { get; } = "n";
public double Scale { get; } = 1e-9;
}
}
|
2e7ddf2c818655ce295684ef6bc9175215359121
|
C#
|
trungnam1601/Group-Practice
|
/QuanLyNhaHang/Helper/Table.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuanLyNhaHang.Helper
{
public class Table
{
public Table(string maBan, string trangThai)
{
this.MaBan = maBan;
this.TrangThai = trangThai;
}
public Table(DataRow row)
{
this.MaBan = row["MaBan"].ToString();
this.TrangThai = row["TrangThai"].ToString();
}
private string trangThai;
public string TrangThai
{
get { return trangThai; }
set { trangThai = value; }
}
private string maBan;
public string MaBan
{
get { return maBan; }
set { maBan = value; }
}
}
}
|
4339ba9156330799b99f77195bf088370efcdc6a
|
C#
|
tooml/dyp.webservice
|
/dyp.contracts/data/Ranking.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace dyp.contracts.data
{
public class RankingDataBasis
{
public class RankingOptionsData
{
public int Points;
public int Points_drawn;
public bool Drawn;
public bool Walkover;
}
public class RankingPlayerData
{
public string Player_id;
public string Player_name;
}
public class RankingMatchData
{
public class Team
{
public string Player_one_id;
public string Player_two_id;
public int Sets;
}
public Team Home;
public Team Away;
public bool Drawn;
public IEnumerable<string> Get_match_home_players()
{
return new string[] { Home.Player_one_id, Home.Player_two_id };
}
public IEnumerable<string> Get_match_away_players()
{
return new string[] { Away.Player_one_id, Away.Player_two_id };
}
public IEnumerable<string> Get_match_players()
{
return Get_match_home_players().Concat(Get_match_away_players());
}
public IEnumerable<string> Get_match_winners()
{
if (Home.Sets > Away.Sets) return Get_match_home_players();
else if (Home.Sets < Away.Sets) return Get_match_away_players();
else return Enumerable.Empty<string>();
}
public IEnumerable<string> Get_match_loosers()
{
if (Home.Sets > Away.Sets) return Get_match_away_players();
else if (Home.Sets < Away.Sets) return Get_match_home_players();
else return Enumerable.Empty<string>();
}
public IEnumerable<string> Get_match_drawn()
{
if (Home.Sets == Away.Sets) return Get_match_players();
else return Enumerable.Empty<string>();
}
}
public RankingOptionsData Options;
public List<RankingPlayerData> Players = new List<RankingPlayerData>();
public List<RankingMatchData> Matches = new List<RankingMatchData>();
public List<string> Walkover_played = new List<string>();
}
public class Ranking
{
public class RankingRow
{
public string Player_id { get; set; } = string.Empty;
public string Player_name { get; set; } = string.Empty;
public int Matches_played { get; set; } = 0;
public int Wins { get; set; } = 0;
public int Drawn { get; set; } = 0;
public int Loose { get; set; } = 0;
public int Points { get; set; } = 0;
public decimal Q1 { get => (Points != 0) ? decimal.Divide((decimal)Points, (decimal)Matches_played) : 0; }
public decimal Q2_total { get; set; } = 0;
public decimal Q2 { get => (Q2_total != 0) ? decimal.Divide((decimal)Q2_total, (decimal)Matches_played) : 0; }
public int Walkover { get; set; } = 0;
}
public List<RankingRow> Ranking_rows = new List<RankingRow>();
public Ranking(IEnumerable<RankingDataBasis.RankingPlayerData> players)
{
Ranking_rows = players.Select(p =>
new RankingRow()
{
Player_id = p.Player_id,
Player_name = p.Player_name
}).ToList();
}
public RankingRow Get_row(string player_id)
{
return Ranking_rows.FirstOrDefault(row => row.Player_id.Equals(player_id));
}
public IEnumerable<RankingRow> Get_rows(IEnumerable<string> player_ids)
{
foreach (var player_id in player_ids)
yield return Get_row(player_id);
}
public decimal Get_players_Q1(IEnumerable<string> player_ids)
{
return Get_rows(player_ids).Sum(player => player.Q1);
}
public void Apply_match_count(IEnumerable<string> player_ids)
{
var rows = Get_rows(player_ids);
Apply(rows, row => row.Matches_played++);
}
public void Apply_match_win(IEnumerable<string> player_ids, int points)
{
var rows = Get_rows(player_ids);
Apply(rows, row => {
row.Wins++;
row.Points += points;
});
}
public void Apply_match_drawn(IEnumerable<string> player_ids, int points)
{
var rows = Get_rows(player_ids);
Apply(rows, row => {
row.Drawn++;
row.Points += points;
});
}
public void Apply_match_loose(IEnumerable<string> player_ids)
{
var rows = Get_rows(player_ids);
Apply(rows, row => row.Loose++);
}
public void Apply_walkover(IEnumerable<string> player_ids)
{
var rows = Get_rows(player_ids);
Apply(rows, row => row.Walkover++);
}
public void Apply_Q2_total(IEnumerable<string> player_ids, decimal value)
{
var rows = Get_rows(player_ids);
Apply(rows, row => row.Q2_total += value);
}
private void Apply(IEnumerable<RankingRow> rows, Action<RankingRow> action)
{
rows.ToList().ForEach(row => action(row));
}
}
}
|
84876382bc27cff0f175c427e0e6a5db96cb0902
|
C#
|
AirlandKK/bookstoreSYS
|
/书店管理系统/书店管理系统/DAL/SalesDailsDal.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using model;
namespace DAL
{
public class SalesDailsDal
{
/// <summary>
/// 根据销售记录查询详情
/// </summary>
/// <param name="SaleID"></param>
/// <returns></returns>
public static DataTable SelectDailsBySalesID(int SaleID)
{
string sql = "select * from SalesDetail a,Books b where a.BooksID=b.BooksID and SalesID=" + SaleID;
return DBHelper.GetDataTable(sql);
}
/// <summary>
/// 查询
/// </summary>
/// <returns></returns>
public static double SelectDail()
{
double sum = 0;
string sql = "select * from SalesDetail a,Sales b,Books c where a.SalesID=b.SalesID and a.BooksID=c.BooksID";
DataTable dt = DBHelper.GetDataTable(sql);
for (int i = 0; i < dt.Rows.Count; i++)
{
sum += double.Parse(dt.Rows[i]["Quantity"].ToString()) * double.Parse(dt.Rows[i]["AloneAmount"].ToString());
}
return sum;
}
/// <summary>
/// 添加销售详情表
/// </summary>
/// <param name="sale"></param>
/// <returns></returns>
public static bool InsertSaleDail(SalesDetail sale)
{
string sql = string.Format("insert SalesDetail values({0},{1},{2},{3})", sale.SalesID, sale.BooksID, sale.Quantity,sale.AloneAmount);
return DBHelper.ExecuteNonQuery(sql);
}
}
}
|
5ec3df27f337767d72057dd4b71a98eb7c252fd2
|
C#
|
zaibatsutel/ZaibatsuPass
|
/ZaibatsuPass/PhysicalCard/Desfire/File/DesfireFile.cs
| 2.828125
| 3
|
using System;
using ZaibatsuPass.PhysicalCard.Desfire.File.Settings;
namespace ZaibatsuPass.PhysicalCard.Desfire.File
{
public class DesfireFile
{
public byte ID { get; private set; }
public DesfireFileSettings Settings { get; private set; }
public byte[] Data { get; private set; }
internal DesfireFile(byte i, Settings.DesfireFileSettings s, byte[] d )
{
ID = i;
Settings = s;
Data = d;
}
public static DesfireFile parse(byte i, DesfireFileSettings s, byte[] d)
{
System.Diagnostics.Debug.WriteLine("ZaibatsuPass: Attempting to parse file {0:X} with settings type {0}", i, s.GetType().ToString());
if (s is Desfire.File.Settings.ValueSettings)
return new ValueFile(i, s as Settings.ValueSettings, d);
else if (s is RecordSettings)
return new RecordFile(i, s as Settings.RecordSettings, d);
else if (s is StandardSettings)
return new DesfireFile(i, s, d);
else if (s is InvalidSettings || d == null)
return new InvalidFile(i);
else
throw new ArgumentException("Unknown settings kind???");
}
}
public class InvalidFile : DesfireFile
{
public InvalidFile(byte i): base(i, null,new byte[] { })
{
}
}
public class ValueFile : DesfireFile
{
public int Value { get; private set; }
public ValueFile(byte i, Settings.ValueSettings s, byte[] d) :base(i,s,d)
{
Value = d.MakeUint32();
}
}
public class RecordFile : DesfireFile
{
private DesfireRecord[] files;
public System.Collections.Generic.List<DesfireRecord> Records
{
get
{
return new System.Collections.Generic.List<DesfireRecord>(files);
}
}
public DesfireRecord this[int idx]
{
get {
if (files.Length < idx) return null;
else return this.files[idx];
}
}
public RecordFile(byte i, RecordSettings s, DesfireRecord[] records) : base(i,s,new byte[] { })
{
files = records;
}
public RecordFile(byte i, Settings.RecordSettings s, byte[] d) : base(i,s,d)
{
files = new DesfireRecord[s.CurRecords];
// curRecords -1 because NXP engineers tried to be clever.
for(int idx = 0; idx < s.CurRecords; idx++)
{
byte[] tmp = new byte[s.RecordSize];
Array.Copy(d, idx * s.RecordSize, tmp, 0, s.RecordSize);
files[idx] = new DesfireRecord(tmp);
}
}
}
}
|
25d0c6a743477e700b9ef2896b52c685bd3a2674
|
C#
|
sjakur/ASMembershipSystem
|
/backend/ASMembershipSystem/ASMembershipSystem.DataAccess/Repositories/MemberRepository.cs
| 2.8125
| 3
|
using ASMembershipSystem.Core.Contracts;
using ASMembershipSystem.Core.Domain;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
namespace ASMembershipSystem.DataAccess.Repositories
{
public class MemberRepository : IMemberRepository
{
private readonly ASMembershipContext _context;
public MemberRepository(ASMembershipContext context)
{
_context = context;
}
public void Add(Member member)
{
var sportsIds = new HashSet<int>(member.MemberSports.Select(ms => ms.SportId));
var validSportIds = _context.Sports.Where(s => sportsIds.Contains(s.Id))
.Select(s => s.Id);
member.MemberSports = validSportIds.Select(vid => new MemberSport
{
SportId = vid
}).ToList();
_context.Add(member);
_context.SaveChanges();
}
public List<Member> GetAll()
{
return _context.Members.ToList();
}
public Member GetById(int id)
{
return _context.Members.Include(m => m.MemberSports)
.ThenInclude(ms => ms.Sport)
.SingleOrDefault(m => m.Id == id);
}
public void Update(Member member)
{
var originalMember = _context.Members
.Include(m => m.MemberSports)
.SingleOrDefault(m => m.Id == member.Id);
var sportsIds = new HashSet<int>(member.MemberSports.Select(ms => ms.SportId));
var validSportIds = _context.Sports.Where(s => sportsIds.Contains(s.Id))
.Select(s => s.Id);
originalMember.MemberSports = validSportIds.Select(vid => new MemberSport
{
SportId = vid
}).ToList();
_context.Entry(originalMember).CurrentValues.SetValues(member);
_context.SaveChanges();
}
}
}
|
9114a56d889cfd7dc905d74ceb82556daf5b3a41
|
C#
|
huangjunjiegdmc/WpfControlEx
|
/WpfControlEx/Controls/MessageBoxEx.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfControlEx.Controls
{
public sealed class MessageBoxEx
{
//
// 摘要:
// 前面显示一个消息框在指定的时段。 该消息框显示消息、 标题栏标题、 按钮和图标;接受默认消息框的结果并返回一个结果。
//
// 参数:
// owner:
// 一个 System.Windows.Window ,它表示该消息框的所有者窗口。
//
// messageBoxText:
// 一个 System.String ,它指定要显示的文本。
//
// caption:
// 一个 System.String ,它指定要显示的标题栏标题。
//
// button:
// 一个 System.Windows.MessageBoxButton 值,该值指定哪个按钮或要显示的按钮。
//
// icon:
// 一个 System.Windows.MessageBoxImage 值,该值指定要显示的图标。
//
// defaultResult:
// 一个 System.Windows.MessageBoxResult 值,该值指定消息框的默认结果。
//
// 返回结果:
// 一个 System.Windows.MessageBoxResult 值,该值指定在用户单击哪个消息框按钮。
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxResult defaultResult)
{
MessageBoxWindow messageBoxEx = new MessageBoxWindow(owner, messageBoxText, caption, button, defaultResult);
messageBoxEx.ShowDialog();
return messageBoxEx.MessageBoxResult;
}
//
// 摘要:
// 前面显示一个消息框在指定的时段。 该消息框显示消息、 标题栏标题和按钮;它也会返回一个结果。
//
// 参数:
// owner:
// 一个 System.Windows.Window ,它表示该消息框的所有者窗口。
//
// messageBoxText:
// 一个 System.String ,它指定要显示的文本。
//
// caption:
// 一个 System.String ,它指定要显示的标题栏标题。
//
// button:
// 一个 System.Windows.MessageBoxButton 值,该值指定哪个按钮或要显示的按钮。
//
// 返回结果:
// 一个 System.Windows.MessageBoxResult 值,该值指定在用户单击哪个消息框按钮。
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
{
MessageBoxWindow messageBoxEx = new MessageBoxWindow(owner, messageBoxText, caption, button);
messageBoxEx.ShowDialog();
return messageBoxEx.MessageBoxResult;
}
//
// 摘要:
// 前面显示一个消息框在指定的时段。 该消息框显示消息和标题栏标题;它将返回结果。
//
// 参数:
// owner:
// 一个 System.Windows.Window ,它表示该消息框的所有者窗口。
//
// messageBoxText:
// 一个 System.String ,它指定要显示的文本。
//
// caption:
// 一个 System.String ,它指定要显示的标题栏标题。
//
// 返回结果:
// 一个 System.Windows.MessageBoxResult 值,该值指定在用户单击哪个消息框按钮。
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
{
MessageBoxWindow messageBoxEx = new MessageBoxWindow(owner, messageBoxText, caption);
messageBoxEx.ShowDialog();
return messageBoxEx.MessageBoxResult;
}
//
// 摘要:
// 前面显示一个消息框在指定的时段。 消息框中显示一条消息,并返回一个结果。
//
// 参数:
// owner:
// 一个 System.Windows.Window ,它表示该消息框的所有者窗口。
//
// messageBoxText:
// 一个 System.String ,它指定要显示的文本。
//
// 返回结果:
// 一个 System.Windows.MessageBoxResult 值,该值指定在用户单击哪个消息框按钮。
public static MessageBoxResult Show(Window owner, string messageBoxText)
{
MessageBoxWindow messageBoxEx = new MessageBoxWindow(owner, messageBoxText);
messageBoxEx.ShowDialog();
return messageBoxEx.MessageBoxResult;
}
}
}
|
5229d1c9558000d5bdbcbbbe07e56bedd6fcc7be
|
C#
|
zeroxenof/CodeZone
|
/RSA/JWTDemo/Program.cs
| 2.5625
| 3
|
using Jose;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Security.Cryptography;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace JWTDemo
{
class Program
{
private static CngKey GetPrivateKey(string p8File)
{
using (var reader = File.OpenText(p8File))
{
var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
return EccKey.New(x, y, d);
}
}
static void Main(string[] args)
{
string p8File = @"your p8 file";
var keyId = "your key id";
var teamId = "your team id";
var exp = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeSeconds();
var iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var payload = new Dictionary<string, object>
{
{ "iss", teamId },
{ "exp", exp },
{ "iat", iat}
};
var header = new Dictionary<string, object>
{
{ "kid", keyId},
{ "alg","ES256"}
};
var privateKey = GetPrivateKey(p8File);
string token = Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, header);
var url = "https://api.music.apple.com/v1/catalog/us/artists/1798556";
Console.WriteLine(token);
using (WebClient wc = new WebClient())
{
string URI = url;
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = $"Bearer {token}";
string HtmlResult = wc.DownloadString(URI);
Console.WriteLine(HtmlResult);
}
Console.Read();
}
}
}
|
7ce8872600ffbd14fd7c3b6e689b49bdabec17d8
|
C#
|
ClawmanCat/DartTracker
|
/DartTracker/Models/Tournament.cs
| 2.765625
| 3
|
using DartTracker.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DartTracker.Models
{
public abstract class GameModel : CompareFields
{
}
public class Score
{
private int _score;
public void SetScore(GameType value) => _score = (int) value;
public void SetScore(int value) => _score = (int)value;
public static explicit operator int(Score s) => s._score;
public Score()
{
}
public Score(Score s)
{
this._score = s._score;
}
public static Score operator -(Score s, int amount)
{
Score result = new Score();
result._score = s._score -= amount;
return result;
}
}
public enum SegmentModifier
{
SINGLE = 1,
DOUBLE = 2,
TRIPLE = 3
}
public enum GameType
{
SHORT = 301,
NORMAL = 501,
LONG = 701
}
public enum NamedSegmentType
{
OUTER_BULLSEYE = 25,
INNER_BULLSEYE = 50,
OUTSIDE_BOARD = 0
}
public class Tournament : INotifyPropertyChanged
{
private Player _winner;
private DateTime? _timeAndDate;
private List<Player> _players;
private List<Game> _games;
private int _gamesToWin;
private TimeSpan? _time;
public List<Player> Players
{
get { return _players; }
set { _players = value; OnPropertyChanged("Players"); }
}
public List<Game> Games
{
get { return _games; }
set { _games = value; OnPropertyChanged("Games"); }
}
public int GamesToWin
{
get { return _gamesToWin; }
set { _gamesToWin = value; OnPropertyChanged("GamesToWin"); }
}
public Player Winner
{
get { return _winner; }
set { _winner = value; OnPropertyChanged("Winner"); }
}
public DateTime? TimeAndDate
{
get { return _timeAndDate; }
set { _timeAndDate = value; OnPropertyChanged("TimeAndDate"); }
}
public TimeSpan? Time
{
get { return _time; }
set { _time = value; OnPropertyChanged("Time"); }
}
#region PropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
/// [TypeConverter(typeof (PlayerClassConverter))]
public class Player : INotifyPropertyChanged
{
private string _Name;
private int _Id;
public Player()
{
//Voor data inladen: Als de naam al bestaat krijgt de speler hetzelfde ID als hij in de data heeft, anders random
Random rnd = new Random();
_Id = rnd.Next();
}
public Player(string name, int id)
{
_Name = name;
_Id = id;
}
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set{
_Name = value;
OnPropertyChanged("Name");
}
}
private Score _score = new Score();
public Score score
{
get { return _score; }
set { _score = value; OnPropertyChanged("score"); }
}
public int TotalSetsWon { get; set; }
public int TotalLegsWon { get; set; }
private int _legsWon = 0;
public int legsWon
{
get { return _legsWon; }
set { _legsWon = value; OnPropertyChanged("legsWon"); }
}
private int _setsWon = 0;
public int setsWon
{
get { return _setsWon; }
set { _setsWon = value; OnPropertyChanged("setsWon"); }
}
private int _nineDarts = 0;
public int nineDarts
{
get { return _nineDarts; }
set { _nineDarts = value; OnPropertyChanged("nineDarts"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Game
{
[JsonIgnore] public Tournament parent;
public Player Winner;
public List<GameSet> gameSets;
public int? setsAmount;
public int? legsAmount;
}
public class GameSet
{
[JsonIgnore] public Game parent;
public List<GameLeg> legs;
public Player Winner;
}
public class GameLeg : INotifyPropertyChanged
{
/* private Dictionary<Player, ObservableCollection<Triplet>> _history;
[JsonProperty(Order = -2)]
public Dictionary<Player, ObservableCollection<Triplet>> history { get { return _history; } set { _history = value; OnPropertyChanged("history");} }*/
private Dictionary<int, ObservableCollection<Triplet>> _history;
[JsonProperty(Order = -2)]
public Dictionary<int, ObservableCollection<Triplet>> history
{
get { return _history; }
set
{
_history = value;
OnPropertyChanged("history");
}
}
[JsonIgnore]
public ObservableCollection<Triplet> HistoryPlayerOne => history.Values.ToArray()[0];
[JsonIgnore]
public ObservableCollection<Triplet> HistoryPlayerTwo => history.Values.ToArray()[1];
[JsonIgnore]
public ObservableCollection<int> ScorePlayerOne => ScoreHistory.Values.ToArray()[0];
[JsonIgnore]
public ObservableCollection<int> ScorePlayerTwo => ScoreHistory.Values.ToArray()[1];
[JsonProperty(Order = -2)]
public Dictionary<int, ObservableCollection<int>> ScoreHistory { get; set; }
[JsonIgnore] public GameSet parent;
public Player Winner;
private Player _currentTurn;
public Player CurrentTurn
{
get { return _currentTurn; }
set
{
_currentTurn = value;
OnPropertyChanged("CurrentTurn");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string porprtyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(porprtyName));
}
}
public class Triplet
{
public Triplet(Throw first, Throw second, Throw third)
{
throws = new ObservableCollection<Throw> {first, second, third};
}
public ObservableCollection<Throw> throws { get; set; }
}
public class Throw
{
public Throw(BoardSegment segment)
{
this.segment = segment;
}
public BoardSegment segment { get; set; }
}
public class BoardSegment : GameModel
{
public virtual int Score { get; }
public virtual string Display { get; }
}
public class NormalSegment : BoardSegment
{
public NormalSegment(int value, SegmentModifier modifier)
{
this.value = value;
this.modifier = modifier;
}
public int value;
public SegmentModifier modifier;
public override int Score
{
get => value * (int) modifier;
}
public override string Display
{
get
{
string result = value.ToString();
if (modifier == SegmentModifier.SINGLE) result += "S";
if (modifier == SegmentModifier.DOUBLE) result += "D";
if (modifier == SegmentModifier.TRIPLE) result += "T";
return result;
}
}
}
public class NamedSegment : BoardSegment
{
public NamedSegment(NamedSegmentType type)
{
this.segment = type;
}
public NamedSegmentType segment;
public override int Score
{
get => (int) segment;
}
public override string Display
{
get
{
if (segment == NamedSegmentType.OUTER_BULLSEYE) return "B";
if (segment == NamedSegmentType.INNER_BULLSEYE) return "BS";
if (segment == NamedSegmentType.OUTSIDE_BOARD) return "X";
return "?";
}
}
}
}
|
f8e2e9d6cd0954b4dbb91905a39c5132fa089926
|
C#
|
sabahat767/IPT_Assignment-03
|
/EmployeeData/HelperClasses/Employee.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeData.HelperClasses
{
public class Employee
{
public void AddEmplyee(string first_name, string last_name, string email,string phone_number,int department_id,string salary,int Job_id)
{
var db = new Employee_ManagementEntities();
Tbl_Employee emp = new Tbl_Employee();
emp.first_name = first_name;
emp.last_name = last_name;
emp.email = email;
emp.phone_number = phone_number;
emp.department_id = department_id;
emp.salary = salary;
emp.Job_id = Job_id;
db.Tbl_Employee.Add(emp);
db.SaveChanges();
db.Dispose();
}
}
}
|
51aa36fa17ffb88c197019da2b5631b673eee4e8
|
C#
|
Auros/Blossomic
|
/Blossomic/Converters/FlipArrayConverter.cs
| 2.796875
| 3
|
using Blossomic.Noodle;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Blossomic.Converters
{
public class FlipArrayConverter : JsonConverter<Flip>
{
public override Flip? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (JsonSerializer.Deserialize(ref reader, typeof(object[]), options) is not object[] deserialized)
throw new NullReferenceException(nameof(deserialized));
return new Flip
{
LineIndex = ((JsonElement)deserialized[0]).GetSingle(),
Jump = ((JsonElement)deserialized[1]).GetSingle(),
};
}
public override void Write(Utf8JsonWriter writer, Flip value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, new object[] { value.LineIndex, value.Jump }, typeof(object[]), options);
}
}
}
|
3ac0d315106e8cde63f7bead87ac47c4849c6130
|
C#
|
Karolina-Lach/RecipeSearch
|
/RecipesTest/RecipeModelTest.cs
| 2.859375
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RecipeSearch.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace RecipesTest
{
[TestClass]
public class RecipeModelTest
{
[TestMethod]
public void GetProductList_Test()
{
// Arrange
Recipe recipe = new Recipe(){ Ingredients = new List<Ingredient>() };
recipe.Ingredients.Add(new Ingredient()
{
Product = new Product() { Name = "apple", PluralName = "apples" }
});
List<Product> products = new List<Product>() {
new Product() { Name = "apple", PluralName = "apples" }};
// Act
List<Product> products1 = recipe.GetListOfProducts().ToList();
// Assert
Assert.AreEqual(products1.Count, products.Count);
}
[TestMethod]
public void AddCuisine_StartStringNull_Test()
{
// Arrange
string startString = null;
string toAdd = "american";
string expected = "american";
Recipe recipe = new Recipe() { CuisinesString = startString };
// Act
recipe.AddCuisine(toAdd);
// Assert
Assert.AreEqual(recipe.CuisinesString, expected);
}
[TestMethod]
public void AddCuisine_StartString_Test()
{
// Arrange
string startString = "british";
string toAdd = "american";
string expected = "british,american";
Recipe recipe = new Recipe() { CuisinesString = startString };
// Act
recipe.AddCuisine(toAdd);
// Assert
Assert.AreEqual(recipe.CuisinesString, expected);
}
[TestMethod]
public void AddCuisine_NothingToAdd_Test()
{
// Arrange
string startString = "british";
string toAdd = "nothing";
string expected = "british";
Recipe recipe = new Recipe() { CuisinesString = startString };
// Act
recipe.AddCuisine(toAdd);
// Assert
Assert.AreEqual(recipe.CuisinesString, expected);
}
}
}
|
bbf4e462adfe89e14300e9c8e31eb4d76d37839a
|
C#
|
kunana/Defence
|
/Defence Game/TileMaker.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TileMaker : MonoBehaviour
{
void Start()
{ // 가로가 1부터 8 까지, 세로가 1부터 18까지;
GameObject gameTile = Resources.Load("TileObject", typeof(GameObject)) as GameObject;
//첫줄
float y = 7.36f;
makeTile(gameTile, "rpgTile000", new Vector3(0.32f, y, 0));
for(int i = 1; i < 19; i++)
{
makeTile(gameTile, "rpgTile001", new Vector3(0.32f + (float)i * 0.64f, y, 0));
}
makeTile(gameTile, "rpgTile002", new Vector3(0.32f + 19.0f * 0.64f, y, 0));
//가운데줄
for(int i = 1; i < 11; i++)
{
y = 7.36f - (float)i * 0.64f;
makeTile(gameTile, "rpgTile018", new Vector3(0.32f, y, 0));
for (int j = 1; j < 19; j++)
{
makeTile(gameTile, "rpgTile019", new Vector3(0.32f + (float)j * 0.64f, y, 0));
}
makeTile(gameTile, "rpgTile020", new Vector3(0.32f + 19.0f * 0.64f, y, 0));
}
//마지막줄
makeTile(gameTile, "rpgTile036", new Vector3(0.32f, 0.33f, 0));
for (int i = 1; i < 19; i++)
{
makeTile(gameTile, "rpgTile037", new Vector3(0.32f + (float)i * 0.64f, 0.33f, 0));
}
makeTile(gameTile, "rpgTile038", new Vector3(12.48f, 0.33f, 0));
}
void makeTile(GameObject gameTile, string fileName, Vector3 position)
{
GameObject instance = Instantiate(gameTile) as GameObject;
SpriteRenderer pRenderer = instance.AddComponent<SpriteRenderer>();
Sprite tile = Resources.Load(fileName, typeof(Sprite)) as Sprite;
pRenderer.sprite = tile;
instance.transform.position = position;
}
void Update()
{
}
}
|
e81d07f79ec00e2f59811ed6141da98df399e7bb
|
C#
|
ThanhGT/Teacher-Registration-System
|
/Models/SeedData.cs
| 2.84375
| 3
|
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using Tran_Thanh_991515427_Exam.Models;
namespace Tran_Thanh_991515427_Exam.Models
{
public class SeedData
{
// receive an IApplication Builder argument(is an interface used in the Configure method in Startup.cs to register
// middleware's to handle HTTP requests)
//need to make it connects to the database in the Startup.cs
public static void DataPopulated(IApplicationBuilder app)
{
MBS_DBContext context = app.ApplicationServices
.CreateScope().ServiceProvider
.GetRequiredService<MBS_DBContext>();
//check if there are any pending migrations and if there are then do all the migrations (found in migration folder)
if (context.Database.GetPendingMigrations().Any())
{
context.Database.Migrate();
}
if (!context.Teachers.Any())
{
context.Teachers.AddRange(
new Teacher
{
FirstName = "Paul",
LastName = "Bonenfant",
Salary = 85000
},
new Teacher
{
FirstName = "Elizabeth",
LastName = "Dancy",
Salary = 82000
},
new Teacher
{
FirstName = "Yash",
LastName = "Shah",
Salary = 72000
},
new Teacher
{
FirstName = "John",
LastName = "Dafoe",
Salary = 77000
},
new Teacher
{
FirstName = "Mahboob",
LastName = "Ali",
Salary = 85000
});
context.SaveChanges();
}
}
}
}
|
858a104bb8604b4a6cd03d9c84a2b846fd660650
|
C#
|
Haarmees/SEVSTools
|
/SEScriptBuilder/ScriptBuilder/Analyzer/ScriptAnalyzer.cs
| 2.640625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SEScriptBuilder.ScriptBuilder.TaggedSyntax;
namespace SEScriptBuilder.ScriptBuilder.Analyzer
{
public class ScriptAnalyzer
{
private ScriptAnalyzerResourceHelper resourceHelper;
public ScriptAnalyzerResourceHelper ResourceHelper { get { return this.resourceHelper; } }
public ScriptAnalyzer(ScriptAnalyzerResourceHelper rHelper)
{
this.resourceHelper = rHelper;
}
public TaggedSyntaxLibrary AnalyzeNode(SyntaxNode node, TaggedSyntaxLibrary lib = null) {
if (lib == null)
{
lib = new TaggedSyntaxLibrary();
}
if (!lib.IsTagged(node))
{
Type type = node.GetType();
if (type == typeof(NamespaceDeclarationSyntax))
{
this.AnalyzeNameSpace(node as NamespaceDeclarationSyntax, lib);
}
else if (type == typeof(ClassDeclarationSyntax))
{
this.AnalyzeClass(node as ClassDeclarationSyntax, lib);
}
else if (type == typeof(VariableDeclaratorSyntax))
{
this.AnalyzeVariableDeclarator(node as VariableDeclaratorSyntax, lib);
}
else
{
this.DefaultAnalyze(node, lib);
}
this.ResourceAnalyze(node, lib);
}
return lib;
}
public TaggedSyntaxLibrary AnalyzeNameSpace(NamespaceDeclarationSyntax node, TaggedSyntaxLibrary lib)
{
lib.TagNode(node);
return lib;
}
public TaggedSyntaxLibrary AnalyzeClass(ClassDeclarationSyntax node, TaggedSyntaxLibrary lib)
{
lib.TagNode(node);
return lib;
}
public TaggedSyntaxLibrary AnalyzeVariableDeclarator(VariableDeclaratorSyntax node, TaggedSyntaxLibrary lib)
{
lib.TagNode(node);
if (node.Parent != null)
{
this.AnalyzeNode(node.Parent, lib);
}
this.DefaultAnalyze(node, lib);
return lib;
}
public TaggedSyntaxLibrary DefaultAnalyze(SyntaxNode node, TaggedSyntaxLibrary lib)
{
lib.TagNode(node);
IEnumerable<SyntaxNode> subnodes = node.DescendantNodes().Where(n => n.Parent == node);
if (subnodes != null && subnodes.Count()>0)
{
foreach (SyntaxNode subnode in subnodes)
{
this.AnalyzeNode(subnode, lib);
}
}
return lib;
}
public TaggedSyntaxLibrary ResourceAnalyze(SyntaxNode node, TaggedSyntaxLibrary lib) {
// analyze resources if any
List<SyntaxNode> resources = this.resourceHelper.GetSyntaxNodes(node, lib);
if (resources.Count() > 0)
{
foreach (SyntaxNode resource in resources)
{
this.AnalyzeNode(resource, lib);
}
}
return lib;
}
}
}
|
2b50e8c1506bbe84ad78b6601ec649332c9b735c
|
C#
|
kenfehling/World-of-Carbon
|
/Assets/Scripts/UI/CarbonDisplay.cs
| 2.515625
| 3
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class CarbonDisplay : MonoBehaviour {
private Text text;
private string displayText;
private int numOfCarbons;
private string currentFormula;
public string targetFormulaText;
public float stayTime = 8.0f;
public float fadeoutTimer;
public Color fadeColor;
public bool notification;
// Use this for initialization
void Start () {
text = gameObject.GetComponent<Text>();
fadeColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
fadeoutTimer = stayTime;
currentFormula = GameObject.FindObjectOfType<PlayerManager>().gameObject.GetComponentInChildren<Molecule>().formula;
if (currentFormula.Contains("Mantle"))
{
currentFormula = currentFormula.Substring(6);
}
if (currentFormula.Contains("Water"))
{
currentFormula = currentFormula.Substring(5);
}
numOfCarbons = 1;
if(!notification)
updateDisplay();
}
void Update()
{
if(fadeoutTimer > 0.0f)
{
fadeoutTimer -= Time.deltaTime;
fadeColor.a -= 0.15f* Time.deltaTime;
}
text.material.color = fadeColor;
}
private void updateDisplay()
{
if (!notification)
text.text = "Formula: " + currentFormula;
else
text.text = targetFormulaText;
}
public void setNumOfCarbons(int numOfCarbons)
{
this.numOfCarbons = numOfCarbons;
updateDisplay();
}
public void Notify(string note)
{
currentFormula = note;
updateDisplay();
}
public void setFormula(string formula)
{
if (formula == "")
{
formula = currentFormula;
}
else
{
if (formula.Contains("Mantle"))
{
formula = formula.Substring(6);
}
if (formula.Contains("Water"))
{
formula = formula.Substring(5);
}
}
currentFormula = formula;
fadeoutTimer = stayTime;
fadeColor = Color.white;
updateDisplay();
}
}
|
6cc220456db7fb4d4c4e58c5dec85f5fcb0fa8a0
|
C#
|
PeterPopma/blik
|
/Blik/DetectionObject.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace Blik
{
class DetectionObject
{
private Rectangle rectangle;
private float differenceNormal;
private float differenceTrigger;
private float secondLevelDifferenceNormal;
private float secondLevelDifferenceTrigger;
private bool trigger;
private bool normal;
private bool active = true;
private int offsetX;
private int offsetY;
public DetectionObject()
{
}
public DetectionObject(int x, int y, int width, int height)
{
rectangle = new Rectangle(x, y, width, height);
}
public Rectangle Rectangle
{
get
{
return rectangle;
}
set
{
rectangle = value;
}
}
public float DifferenceNormal
{
get
{
return differenceNormal;
}
set
{
differenceNormal = value;
}
}
public float DifferenceTrigger
{
get
{
return differenceTrigger;
}
set
{
differenceTrigger = value;
}
}
public bool Active
{
get
{
return active;
}
set
{
active = value;
}
}
public bool Normal
{
get
{
return normal;
}
set
{
normal = value;
}
}
public bool Trigger
{
get
{
return trigger;
}
set
{
trigger = value;
}
}
public int OffsetX
{
get
{
return offsetX;
}
set
{
offsetX = value;
}
}
public int OffsetY
{
get
{
return offsetY;
}
set
{
offsetY = value;
}
}
public float SecondLevelDifferenceNormal
{
get
{
return secondLevelDifferenceNormal;
}
set
{
secondLevelDifferenceNormal = value;
}
}
public float SecondLevelDifferenceTrigger
{
get
{
return secondLevelDifferenceTrigger;
}
set
{
secondLevelDifferenceTrigger = value;
}
}
public string displayStatus()
{
if (trigger)
{
return "Trigger";
}
if (normal)
{
return "Normal";
}
return "Undecided";
}
public void updateStatus()
{
/* if (differenceNormal < differenceTrigger && differenceNormal < 0.05 && secondLevelDifferenceNormal < 1200)
{
normal = true;
}
else
{
normal = false;
}
*/
if (/*differenceTrigger < differenceNormal &&*/ differenceTrigger < 0.12 && secondLevelDifferenceTrigger < 2500)
{
trigger = true;
}
else
{
trigger = false;
}
}
public String displayStatusInfo()
{
return "Active: " + active.ToString() + " Status: " + displayStatus();
}
public String displayAnalysisInfo()
{
return "normal%: " + differenceNormal.ToString("0.000") + " trigger%: " + differenceTrigger.ToString("0.000") + " 2L-Normal:" + SecondLevelDifferenceNormal.ToString("0.000") + " 2L-Trigger:" + SecondLevelDifferenceTrigger.ToString("0.000") + " OffsetX: " + offsetX + " OffsetY: " + offsetY;
}
}
}
|
80e733f212f2ff584c60c238e44b0723892be71b
|
C#
|
viktor02041991/omgtu
|
/2 semester/maltsev_tasks_2s_zas123/Form5.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace maltsev_tasks_2s_zas123
{
public partial class fCProject : Form
{
public fCProject()
{
InitializeComponent();
}
private void fCProject_Load(object sender, EventArgs e)
{
lab_Description.Text = "Описание задачи: " + Properties.Settings.Default.Task4Description;
}
private void btn_Execute_Click(object sender, EventArgs e)
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Запуск");
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Проверяем число " + Convert.ToString(nUD_Number.Value) + " на простоту с помощью решета Эратосфена");
int[] s = new int[Convert.ToInt32(nUD_Number.Value) + 1];
s[1] = 0;
Stopwatch st = new Stopwatch();
st.Start();
for (int k = 2; k <= nUD_Number.Value; k++)
{
s[k] = 1;
}
for (int k = 2; k * k <= nUD_Number.Value; k++)
{
if (s[k] == 1)
{
for (int l = k * k; l <= nUD_Number.Value; l += k)
{
s[l] = 0;
}
}
}
long result1, result2;
st.Stop();
result1 = st.ElapsedMilliseconds;
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] Затрачено {1} м.с.\r\n", DateTime.Now, result1);
if (s[Convert.ToInt32(nUD_Number.Value)] == 1)
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Результат: число " + Convert.ToString(nUD_Number.Value) + " простое");
} else
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Результат: число " + Convert.ToString(nUD_Number.Value) + " не простое");
}
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Проверяем число " + Convert.ToString(nUD_Number.Value) + " на простоту с помощью перебора делителей");
st.Reset();
st.Start();
Boolean flag = true;
if (nUD_Number.Value != 1)
{
for (int d = 2; d * d <= nUD_Number.Value; d++)
{
if (nUD_Number.Value % d == 0)
{
flag = false;
break;
}
}
}
else
{
flag = false;
}
st.Stop();
result2 = st.ElapsedMilliseconds;
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] Затрачено {1} м.с.\r\n", DateTime.Now, result2);
if (flag)
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Результат: число " + Convert.ToString(nUD_Number.Value) + " простое");
}
else
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Результат: число " + Convert.ToString(nUD_Number.Value) + " не простое");
}
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Завершение");
if ((result1 != 0) || (result2 != 0))
{
if (result1 > result2)
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Оптимальным алгоритмом является алгоритм - Перебор делителей");
} else
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Оптимальным алгоритмом является алгоритм - Решето Эратосфена ");
}
}
else
{
rtb_Text.Text += string.Format("[{0:dd.MM.yyy HH:mm:ss.fff}] {1}\r\n", DateTime.Now, "Сравнение алгоритмов невозможно, проверки происходят очень быстро. Введите новое число и повторите вычисления.");
}
rtb_Text.SelectionStart = rtb_Text.TextLength;
rtb_Text.ScrollToCaret();
}
}
}
|
6649ecd87aef149a7bc36f6d1dfa4427b73d452e
|
C#
|
jo3l17/CodiGo3
|
/Backend/Semana 10/Dia2/EF FluentAPI/EF FluentAPI/programContext.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF_FluentAPI
{
class ProgramContext : DbContext
{
public ProgramContext() : base("name = conexion")
{
Database.SetInitializer<ProgramContext>
(new DropCreateDatabaseIfModelChanges<ProgramContext>());
}
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("school");
modelBuilder.Entity<Student>().ToTable("Estudiantes");
modelBuilder.Entity<Course>().ToTable("Cursos");
modelBuilder.Entity<Student>().Map(m =>
{
// Pendiente no se puede mapear atributos NON-KEY
// m.Properties(p => new { p.idStudent,p.studentName });
m.Properties(p => new { p.idStudent});
m.ToTable("StudentInfo");
});
modelBuilder.Entity<Student>().HasKey<int>(s => s.idStudent);
modelBuilder.Entity<Course>().HasKey<int>(c => c.idCurso);
modelBuilder.Entity<Address>().HasKey<int>(a => a.idAddress);
modelBuilder.Entity<Student>()
.Property(p => p.birth)
.HasColumnName("Fecha de Nacimiento")
.HasColumnType("DateTime2")
.HasColumnOrder(3);
//columna nula
modelBuilder.Entity<Student>()
.Property(p => p.height)
.HasPrecision(4, 2)
.IsOptional();
//columna no nula
modelBuilder.Entity<Student>()
.Property(p => p.weight)
.HasPrecision(4,2)
.IsRequired();
modelBuilder.Entity<Student>()
.Property(p => p.studentName)
.IsRequired()
.HasMaxLength(50);
//crear 2 primary key
//modelBuilder.Entity<Course>().HasKey(c => new { c.idCurso, c.courseName });
//base.OnModelCreating(modelBuilder);
//RELACIONES
modelBuilder.Entity<Student>()
.HasOptional(a => a.Address)
.WithRequired(ad => ad.Student);
}
}
}
|
232ca3e3846a60b70c6096aabbbe2bb97d470114
|
C#
|
cmccandless/ExercismSolutions-csharp
|
/high-scores/HighScores.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
public class HighScores
{
private List<int> scores;
public HighScores(List<int> list)
{
this.scores = new List<int>(list);
}
public List<int> Scores()
{
return scores.ToList();
}
public int Latest()
{
return scores[scores.Count - 1];
}
public int PersonalBest()
{
return scores.Max();
}
public List<int> PersonalTop()
{
return scores.OrderByDescending(i => i).Take(3).ToList();
}
public string Report()
{
var latest = Latest();
var diff = PersonalBest() - latest;
var diff_msg = diff > 0 ? $"{diff} short of " : "";
return $"Your latest score was {latest}. That's {diff_msg}your personal best!";
}
}
|
ac88641585558493c1742a43df2a12d3d7eb6f94
|
C#
|
tieje/csharp-trading-bot
|
/ContextProvider.cs
| 2.796875
| 3
|
/*
The main purpose of the Context Provider is to either grab information that algorithms will use as input for their conditionals to activate, OR to activate the web scraper that will grab information for the algorithm to activate.
*/
using System;
using Alpaca.Markets;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
namespace StockTrading
{
public class ContextProvider : IDisposable
{
private string API_KEY = "Alpaca API key here";
private string API_SECRET = "Alpaca API secret key here";
public IAlpacaTradingClient alpacaAccountApi;
public IAlpacaDataClient alpacaDataApi;
public IAlpacaStreamingClient alpacaAccountStream;
public string API_KEY1 { get => API_KEY; }
public string API_SECRET1 { get => API_SECRET; }
/*
public async Task ProvideContextAsync()
{
// Insert break here
// Connecting Streams
alpacaAccountStream = Environments.Paper
.GetAlpacaStreamingClient(new SecretKey(API_KEY1, API_SECRET1));
// My Account information stream. Only deals with updates on trade statuses.
alpacaAccountStream.ConnectAndAuthenticateAsync().Wait();
alpacaAccountStream.OnTradeUpdate += HandleTradeUpdate;
//alpacaAccountStream.OnAccountUpdate += HandleAccountUpdate;
// Test account information account information.
// Delete this later
var account = await alpacaAccountApi.GetAccountAsync();
/*
Console.WriteLine(account.BuyingPower + " is your current buying power.");
// Universally useful information
// Time info
var calendars = (await alpacaAccountApi
.ListCalendarAsync(new CalendarRequest().SetTimeInterval(DateTime.Today.GetInclusiveIntervalFromThat())))
.ToList();
var calendarDate = calendars.First().TradingDateUtc;
var closingTime = calendars.First().TradingCloseTimeUtc;
var today = DateTime.Today;
}
// Stream event handlers
// For now, both event handlers will simple print information based on the trade information.
// Trade Update event handler
*/
public void HandleTradeUpdate(ITradeUpdate trade)
{
switch (trade.Event)
{
case TradeEvent.Fill:
Console.WriteLine("Trade filled.");
break;
case TradeEvent.Rejected:
Console.WriteLine("Trade rejected.");
break;
case TradeEvent.Canceled:
Console.WriteLine("Trade canceled.");
break;
// https://alpaca.markets/docs/api-documentation/api-v2/streaming/
// Other events can be included and potential events are defined in the link above
}
}
/*
// Account update event handler
// Looking around, I can't find the API for this... and I hope to never receive an account update because according to the following interface:
// https://github.com/alpacahq/alpaca-trade-api-csharp/blob/develop/Alpaca.Markets/Interfaces/IAccountUpdate.cs
// There is a shifty DeletedAtUtc property meaning this will tell me if my account got deleted.
private void HandleAccountUpdate(IAccountUpdate account)
{
switch (account.Event)
{
case
}
}
*/
// Dispose? I need to figure out dispose. I'm doing this for all external connections. I know it's about calling garbage collection.
public void Dispose()
{
alpacaAccountApi?.Dispose();
alpacaAccountStream?.Dispose();
}
}
}
|
0e02cd6617981de15e38f42c020d4d15b427be81
|
C#
|
ccrispin/SampleProjectMvcTest
|
/ProjectName.Common/Logger/Log4NetLogger.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using ProjectName.Interfaces.Common;
namespace ProjectName.Common.Logger
{
public class Log4NetLogger: ILogger
{
#region ILogger Members
private ILog _logger;
public Log4NetLogger()
{
_logger = LogManager.GetLogger(this.GetType());
}
public void Info(string message)
{
_logger.Info(message);
}
public void Warn(string message)
{
_logger.Warn(message);
}
public void Debug(string message)
{
_logger.Debug(message);
}
public void Error(string message)
{
_logger.Error(message);
}
public void Error(Exception x)
{
Error(LogUtility.BuildExceptionMessage(x));
}
public void Error(string message, Exception x)
{
_logger.Error(message, x);
}
public void Fatal(string message)
{
_logger.Fatal(message);
}
public void Fatal(Exception x)
{
Fatal(LogUtility.BuildExceptionMessage(x));
}
#endregion
#region ILogger Members
public void LogError(Exception ex, string source)
{
throw new NotImplementedException();
}
#endregion
}
}
|
03696f6048e48bd6e45d298eb3e81ef8aa8d1909
|
C#
|
jfcarocota/itesca-app-2D-01
|
/Assets/Scripts/Party.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Party : MonoBehaviour
{
[SerializeField]
List<Player> currentParty;
Player leader;
[SerializeField]
Player[] players;
// Start is called before the first frame update
void Start()
{
players = FindObjectsOfType(typeof(Player)) as Player[];
for(int i = 0; i < players.Length; i++)
{
Player p = players[i];
p.Leader = null;
if(p.IsLeader)
{
p.IsNPC = false;
if(currentParty.Count > 0)
{
currentParty.Insert(0, p);
}
else
{
currentParty.Add(p);
}
}
else
{
p.IsNPC = true;
currentParty.Add(p);
}
}
for(int i = 1; i < currentParty.Count; i++)
{
currentParty[i].Leader = currentParty[i - 1];
}
}
void Update()
{
if(Input.GetButtonDown("myInput"))
{
Player currentLeader = currentParty[0];
currentLeader.IsLeader = false;
currentLeader.IsNPC = true;
currentLeader.Leader = currentParty[currentParty.Count - 1];
currentParty.RemoveAt(0);
currentParty.Add(currentLeader);
currentParty[0].IsLeader = true;
currentParty[0].IsNPC = false;
currentParty[0].Leader = null;
}
}
}
|
6c96024acf8bd58d7ab629d3de5672e4d426a35e
|
C#
|
Cprice1771/RavenExplore
|
/RavenDBExample/Program.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Indexes;
using Raven.Json.Linq;
using RavenDBExample.Indexes;
namespace RavenDBExample {
class Program {
static void AggregateIndex() {
IndexCreation.CreateIndexes(typeof(Employees_EmployeeCountByTitle).Assembly, DocumentStoreHolder.Store);
using (var session = DocumentStoreHolder.Store.OpenSession()) {
var result = session.Query<Employees_EmployeeCountByTitle.Reduceresult, Employees_EmployeeCountByTitle>();
foreach (var item in result) {
Console.WriteLine($"{item.Title}: {item.Count}");
}
}
}
static void GetUpdateItem() {
using (var session = DocumentStoreHolder.Store.OpenSession()) {
var p1 = session.Load<Product>("products/1");
p1.Name = "LALALA";
session.SaveChanges();
var products = session.Query<Product, Product_ByName>().Where(x => x.Name == "LALALA").FirstOrDefault();
Console.WriteLine(products.Name);
}
}
static void Attatchments() {
var file = File.OpenRead(@"C:\rm.png");
DocumentStoreHolder.Store.DatabaseCommands.PutAttachment("images/1", null, data: file, metadata: new RavenJObject { { "Description", "A Picture" } });
using (var session = DocumentStoreHolder.Store.OpenSession()) {
var p1 = session.Load<Product>("products/1");
p1.ImageId = "images/1";
session.SaveChanges();
var attatch = DocumentStoreHolder.Store.DatabaseCommands.GetAttachment(p1.ImageId);
Console.WriteLine($"Size: {attatch.Size}");
}
}
static void Paging() {
using (var session = DocumentStoreHolder.Store.OpenSession()) {
int pageNumber = 0;
int resultsPerPage = 2;
RavenQueryStatistics stats;
var products = session.Query<Product>()
.Statistics(out stats)
.Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(10)))
.Skip(pageNumber * resultsPerPage)
.Take(resultsPerPage)
.ToArray();
foreach (var product in products) {
Console.WriteLine(product.Name);
}
Console.WriteLine($"Index Stale?: {stats.IsStale}");
Console.WriteLine($"Total Documents: {stats.TotalResults}");
}
}
static void Includes() {
using (var session = DocumentStoreHolder.Store.OpenSession()) {
var supplier = session.Query<Supplier>().FirstOrDefault();
var newProduct = new Product() {
Id = "product/125",
Name = "Apples for Apples",
Supplier = supplier.Id,
Category = "Board Game",
QuantityPerUnit = "1 x 10",
PricePerUnit = 20.00m,
UnitsInStock = 10,
UnitsOnOrder = 5,
Discontinued = false,
ReorderLevel = 0,
ImageId = null
};
session.Store(newProduct);
session.SaveChanges();
}
using (var session = DocumentStoreHolder.Store.OpenSession()) {
var product = session.Include<Product>(x => x.Supplier).Load<Product>("product/125");
Console.WriteLine(product.Name);
var supplier = session.Load<Supplier>(product.Supplier);
Console.WriteLine(supplier.Name);
}
}
static void Patch() {
var newTerritory = new Territory { Code = "123", Name = "404", Area = "South" };
DocumentStoreHolder.Store.DatabaseCommands.Patch("regions/3",
new[] {
new PatchRequest{
Type = PatchCommandType.Add,
Name = "Territories",
Value = RavenJObject.FromObject(newTerritory)
}
});
}
static void Main(string[] args) {
Patch();
}
}
}
|
fba17a92dbd32c5597a77954c8cce9c0d6411b8f
|
C#
|
nickgenov/Advanced-CCharp-May2016
|
/StacksAndQueues/BasicStackOperations/BasicStackOperationsMain.cs
| 4.03125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BasicStackOperations
{
public class BasicStackOperationsMain
{
public static void Main()
{
Stack<int> elementsStack = new Stack<int>();
string input = Console.ReadLine();
int[] commands = input.Split(' ').Select(int.Parse).ToArray();
int elementsToPushCount = commands[0];
int elementsToPopCount = commands[1];
int elementToCheck = commands[2];
input = Console.ReadLine();
int[] integers = input.Split(' ').Select(int.Parse).ToArray();
//push elements onto the stack
for (int i = 0; i < elementsToPushCount; i++)
{
int element = integers[i];
elementsStack.Push(element);
}
//pop elements from the top of the stack
for (int i = 0; i < elementsToPopCount; i++)
{
elementsStack.Pop();
}
//check for an element in the stack
if (elementsStack.Contains(elementToCheck))
{
Console.WriteLine("true");
}
else if(elementsStack.Count > 0)
{
Console.WriteLine(elementsStack.Min());
}
else
{
Console.WriteLine(0);
}
}
}
}
|
ce661d481da8ea108fe5e2c3bbb1840438b1fc81
|
C#
|
githubbylf/FreshFruit
|
/FreshFruit.Common/ToolsUtils/CommonUtils.cs
| 3.15625
| 3
|
using System;
using System.Text;
namespace FreshFruit.Common.ToolsUtils
{
public class CommonUtils
{
/// <summary>
/// Automatically generate random numbers
/// </summary>
/// <param name="minValue">Minimum value</param>
/// <param name="maxValue">Max value</param>
/// <param name="isAppend">Not enough digits, whether to append 0</param>
/// <returns></returns>
public string GetRandom(int minValue, int maxValue, bool isAppend)
{
Random r = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
if (isAppend)
{
return r.Next(minValue, maxValue).ToString().PadLeft(4, '0');
}
else
{
return r.Next(minValue, maxValue).ToString();
}
}
/// <summary>
/// Automatically generate Chinese
/// </summary>
/// <param name="strlength">length</param>
/// <returns></returns>
public static string CreateSimplifiedChinese(int strlength)
{
//定义一个字符串数组储存汉字编码的组成元素
string[] r = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
Random rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
//定义一个object数组用来
object[] bytes = new object[strlength];
//每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
//每个汉字有四个区位码组成
//区位码第1位和区位码第2位作为字节数组第一个元素
//区位码第3位和区位码第4位作为字节数组第二个元素
for (int i = 0; i < strlength; i++)
{
//区位码第1位
int r1 = rnd.Next(11, 14);
string str_r1 = r[r1].Trim();
//区位码第2位
rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));//更换随机数发生器的种子避免产生重复值
int r2;
if (r1 == 13)
r2 = rnd.Next(0, 7);
else
r2 = rnd.Next(0, 16);
string str_r2 = r[r2].Trim();
//区位码第3位
rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
int r3 = rnd.Next(10, 16);
string str_r3 = r[r3].Trim();
//区位码第4位
rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
int r4;
if (r3 == 10)
{
r4 = rnd.Next(1, 16);
}
else if (r3 == 15)
{
r4 = rnd.Next(0, 15);
}
else
{
r4 = rnd.Next(0, 16);
}
string str_r4 = r[r4].Trim();
//定义两个字节变量存储产生的随机汉字区位码
byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
//将两个字节变量存储在字节数组中
byte[] str_r = new byte[] { byte1, byte2 };
//将产生的一个汉字的字节数组放入object数组中
bytes.SetValue(str_r, i);
}
//获取GB2312编码页(表)
Encoding gb = Encoding.GetEncoding("gb2312");
Encoding utf8s = Encoding.GetEncoding("utf-8");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strlength; i++)
{
sb.Append(gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))));
}
return sb.ToString();
}
}
}
|
e4954ef8b001a99913c48c92e4184b4f1e00c19d
|
C#
|
sh1ch/Samples
|
/PrintSample/PrintSample/Page.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace PrintSample
{
/// <summary>
/// <see cref="Page"/> クラスは、印刷するページを表現するクラスです。
/// </summary>
public class Page
{
#region Properties
/// <summary>
/// 印刷するドット密度の単位を取得します。
/// </summary>
public int Dpi { get; }
/// <summary>
/// ページ要素の情報を取得します。
/// </summary>
public PageContent PageContent { get; private set; }
/// <summary>
/// ページ要素を取得します。
/// </summary>
public FixedPage FixedPage { get; private set; }
/// <summary>
/// ページの余白を取得します。
/// </summary>
public Thickness Margin { get; private set; }
/// <summary>
/// 印刷可能範囲の大きさを取得します。
/// </summary>
public Size PrintableSize { get; private set; }
/// <summary>
/// プリンター依存の余白を取得します。
/// </summary>
public Point OriginPoint { get; private set; }
#endregion
#region Initializes
/// <summary>
/// <see cref="Page"/> クラスの新しいインスタンスを初期化します。
/// </summary>
public Page() : this(72) { }
/// <summary>
/// <see cref="Page"/> クラスの新しいインスタンスを初期化します。
/// </summary>
/// <param name="dpi">印刷ドット密度の単位。</param>
public Page(int dpi)
{
Dpi = dpi;
}
#endregion
#region Public Methods
/// <summary>
/// ページ・余白のサイズを初期化します。
/// </summary>
/// <param name="printableSize">印刷可能なページの大きさ。</param>
/// <param name="originPoint">プリンター依存の余白。</param>
/// <param name="margin">拡張余白。</param>
public void BuildSize(Size printableSize, Point originPoint, Thickness margin)
{
PrintableSize = printableSize;
OriginPoint = originPoint;
Margin = margin;
}
/// <summary>
/// <see cref="PageContent"/> を初期化します。
/// </summary>
/// <param name="width">要素の幅。</param>
/// <param name="height">要素の高さ。</param>
/// <param name="originPoint">プリンター性能による必須余白。</param>
public void BuildContent(double width, double height, Point originPoint)
{
var content = new PageContent()
{
Width = width + originPoint.X * 2,
Height = height + originPoint.Y * 2
};
OriginPoint = originPoint;
PageContent = content;
}
/// <summary>
/// <see cref="PageContent"/> を初期化します。
/// </summary>
/// <param name="dpi">印刷するドット密度の単位。</param>
/// <param name="width">要素の幅。</param>
/// <param name="height">要素の高さ。</param>
/// <param name="originPoint">プリンター性能による必須余白。</param>
/// <param name="margin">余白。</param>
public void BuildFixedPage(int dpi, double width, double height, Point originPoint, Thickness margin)
{
var mm = ToMilliThickness(margin, dpi);
var page = new FixedPage()
{
Width = width + originPoint.X * 2,
Height = height + originPoint.Y * 2
};
page.Margin = new System.Windows.Thickness(originPoint.X + mm.Left, originPoint.Y + mm.Top, originPoint.X + mm.Right, originPoint.Y + mm.Bottom);
OriginPoint = originPoint;
Margin = margin;
FixedPage = page;
}
/// <summary>
/// 作成したページ要素を確定させます。
/// <para>
/// 確定した要素を <see cref="PageContentCollection"/> に追加することができます。
/// </para>
/// </summary>
/// <exception cref="ArgumentNullException" />
public void FinalizePage(FrameworkElement element)
{
if (element == null)
{
throw new ArgumentNullException();
}
FixedPage.Children.Add(element);
PageContent.Child = FixedPage;
}
#endregion
#region Private Methods
/// <summary>
/// mm で示された <see cref="Thickness"/> をドット単位に変換した <seealso cref="System.Windows.Thickness"/> を取得します。
/// </summary>
private System.Windows.Thickness ToMilliThickness(Thickness thickness, int dpi)
{
return new System.Windows.Thickness
(
ConvertMilliToDots(thickness.Left, dpi), ConvertMilliToDots(thickness.Top, dpi),
ConvertMilliToDots(thickness.Right, dpi), ConvertMilliToDots(thickness.Bottom, dpi)
);
}
/// <summary>
/// inch で示された <see cref="Thickness"/> をドット単位に変換した <seealso cref="System.Windows.Thickness"/> を取得します。
/// </summary>
private System.Windows.Thickness ToInchThickness(Thickness thickness, int dpi)
{
return new System.Windows.Thickness
(
ConvertInchToDots(thickness.Left, dpi), ConvertInchToDots(thickness.Top, dpi),
ConvertInchToDots(thickness.Right, dpi), ConvertInchToDots(thickness.Bottom, dpi)
);
}
/// <summary>
/// mm の大きさを表す値を ドット単位の大きさに変換します。
/// </summary>
/// <param name="value">mm の値。</param>
/// <param name="dpi">ドット密度。</param>
/// <returns>ドット単位の大きさ。</returns>
private double ConvertMilliToDots(double value, int dpi)
{
var inch = 25.4D; // 1inch = 25.4mm
return (value / inch) * dpi;
}
/// <summary>
/// inch の大きさを表す値を ドット単位の大きさに変換します。
/// </summary>
/// <param name="value">inch の値。</param>
/// <param name="dpi">ドット密度。</param>
/// <returns>ドット単位の大きさ。</returns>
private double ConvertInchToDots(double value, int dpi)
{
return value * dpi;
}
#endregion
}
}
|
593c96fb9e1b497599e798d075dfd23af945d4b6
|
C#
|
Madoxen/SSI
|
/kolos_pchlad/NeuralNetwork/Network.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
namespace NeuralNetwork
{
public class Network
{
static double LearningRate = 0.01;
internal List<Layer> Layers;
internal double[][] ExpectedResult;
double[][] differences;
public ITestStrategy testStrategy;
public bool TestHaltEnabled { get; set; }
public bool TestingEnabled { get; set; }
public Network(int numInputNeurons, int[] hiddenLayerSizes , int numOutputNeurons,
bool testHaltEnabled = false, bool testingEnabled = true, string path = null)
{
Console.WriteLine("\n Building neural network...");
if (numInputNeurons < 1 || hiddenLayerSizes.Length < 1 || numOutputNeurons < 1)
throw new Exception("Incorrect Network Parameters");
this.testStrategy = new MeanErrorTest(this);
this.TestHaltEnabled = testHaltEnabled;
this.TestingEnabled = testingEnabled;
Layers = new List<Layer>();
AddFirstLayer(numInputNeurons);
for (int i = 0; i < hiddenLayerSizes.Length; i++)
AddNextLayer(new Layer(hiddenLayerSizes[i]));
AddNextLayer(new Layer(numOutputNeurons));
differences = new double[Layers.Count][];
for (int i = 1; i < Layers.Count; i++)
differences[i] = new double[Layers[i].Neurons.Count];
if (File.Exists(path))
{
Console.WriteLine(" Loading weights...");
string[] lines = File.ReadAllLines(path);
if (lines.Length != Synapse.SynapsesCount)
Console.WriteLine(" Incorrect input file.");
else LoadWeights(lines);
}
}
private void AddFirstLayer(int inputneuronscount)
{
Layer inputlayer = new Layer(inputneuronscount);
foreach (Neuron neuron in inputlayer.Neurons)
neuron.AddInputSynapse(0);
Layers.Add(inputlayer);
}
private void AddNextLayer(Layer newlayer)
{
Layer lastlayer = Layers[Layers.Count - 1];
lastlayer.ConnectLayers(newlayer);
Layers.Add(newlayer);
}
public void PushInputValues(double[] inputs)
{
if (inputs.Length != Layers[0].Neurons.Count)
throw new Exception("Incorrect Input Size");
for (int i = 0; i < inputs.Length; i++)
Layers[0].Neurons[i].PushValueOnInput(inputs[i]);
}
public void PushExpectedValues(double[][] expectedvalues)
{
if (expectedvalues[0].Length != Layers[Layers.Count - 1].Neurons.Count)
throw new Exception("Incorrect Expected Output Size");
ExpectedResult = expectedvalues;
}
public List<double> GetOutput()
{
List<double> output = new List<double>();
for (int i = 0; i < Layers.Count; i++)
Layers[i].CalculateOutputOnLayer();
foreach (Neuron neuron in Layers[Layers.Count - 1].Neurons)
output.Add(neuron.OutputValue);
return output;
}
/// <summary>
/// Trains network with given data
/// </summary>
/// <param name="data">
/// [0] -> Input Data to be evaluated
/// [1] -> Expected Output Data
/// [2] -> Test Input Data
/// [3] -> Test Output Data</param>
/// <param name="epochCount"></param>
public void Train(double[][][] data, int epochCount)
{
double[][] inputs = data[0], expectedOutputs = data[1];
double[][] testInputs = data[2], testOutputs = data[3];
PushExpectedValues(expectedOutputs);
Console.WriteLine(" Training neural network...");
for (int i = 0; i < epochCount; i++)
{
List<double> outputs = new List<double>();
for (int j = 0; j < inputs.Length; j++)
{
PushInputValues(inputs[j]);
outputs = GetOutput();
ChangeWeights(outputs, j);
}
if (TestingEnabled == true)
{
testStrategy.Test(testInputs, testOutputs);
if (testStrategy.CheckHalt() && TestHaltEnabled == true)
break;
}
}
SaveWeights(@"weights.txt");
}
public void RandomizeWeights()
{
foreach (Layer l in Layers)
{
l.RandomizeWeights();
}
}
private void CalculateDifferences(List<double> outputs, int row)
{
for (int i = 0; i < Layers[Layers.Count - 1].Neurons.Count; i++)
differences[Layers.Count - 1][i] = (ExpectedResult[row][i] - outputs[i])
* Functions.BipolarDifferential(Layers[Layers.Count - 1].Neurons[i].InputValue);
for (int k = Layers.Count - 2; k > 0; k--)
for (int i = 0; i < Layers[k].Neurons.Count; i++)
{
differences[k][i] = 0;
for (int j = 0; j < Layers[k + 1].Neurons.Count; j++)
differences[k][i] += differences[k + 1][j] * Layers[k + 1].Neurons[j].Inputs[i].Weight;
differences[k][i] *= Functions.BipolarDifferential(Layers[k].Neurons[i].InputValue);
}
}
private void ChangeWeights(List<double> outputs, int row)
{
CalculateDifferences(outputs, row);
for (int k = Layers.Count - 1; k > 0; k--)
for (int i = 0; i < Layers[k].Neurons.Count; i++)
for (int j = 0; j < Layers[k - 1].Neurons.Count; j++)
Layers[k].Neurons[i].Inputs[j].Weight +=
LearningRate * 2 * differences[k][i] * Layers[k - 1].Neurons[j].OutputValue;
}
public void SaveWeights(string path)
{
List<string> tmp = ReadWeights();
File.WriteAllLines(path, tmp);
}
public void LoadWeights(string[] lines)
{
try
{
int i = 0;
foreach (Layer layer in Layers)
foreach (Neuron neuron in layer.Neurons)
foreach (Synapse synapse in neuron.Inputs)
synapse.Weight = Double.Parse(lines[i++]);
}
catch (Exception e) { Console.WriteLine(" Incorrect input file"); }
}
private List<string> ReadWeights()
{
List<string> tmp = new List<string>();
foreach (Layer layer in Layers)
foreach (Neuron neuron in layer.Neurons)
foreach (Synapse synapse in neuron.Inputs)
tmp.Add(synapse.Weight.ToString());
return tmp;
}
}
}
|
68e0dec39373c81c8694bea46b3226abecfe1a74
|
C#
|
TeodorAntonov/Softuni_Fundamentals_Mid_Exams_Practice
|
/04. Programming Fundamentals Mid Exam_03. Heart Delivery/Program.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Heart_Delivery
{
class Program
{
static void Main(string[] args)
{
List<int> neighborhood = Console.ReadLine().Split("@").Select(int.Parse).ToList();
string command = Console.ReadLine();
int lastposition = 0;
while (command != "Love!")
{
string[] cmd = command.Split().ToArray();
string jump = cmd[0];
int lenght = int.Parse(cmd[1]);
lastposition += lenght;
if (lastposition >= neighborhood.Count)
{
lastposition = 0;
}
if (neighborhood[lastposition] > 0)
{
neighborhood[lastposition] -= 2;
if (neighborhood[lastposition] == 0)
{
Console.WriteLine($"Place {lastposition} has Valentine's day.");
}
}
else
{
Console.WriteLine($"Place {lastposition} already had Valentine's day.");
}
command = Console.ReadLine();
}
Console.WriteLine($"Cupid's last position was {lastposition}.");
int countZeroes = 0;
int countNotZeroes = 0;
foreach (var item in neighborhood)
{
if (item == 0)
{
countZeroes++;
}
else
{
countNotZeroes++;
}
}
if (countZeroes == neighborhood.Count)
{
Console.WriteLine("Mission was successful.");
}
else
{
Console.WriteLine($"Cupid has failed {countNotZeroes} places.");
}
}
}
}
|
43beffc2a4be025d225aa86b658557fb9efa5478
|
C#
|
LordPilum/ValidationAttributes
|
/ValidationAttributes/CustomValidationAttribute/HasValueAttribute.cs
| 2.953125
| 3
|
using System;
using System.Linq;
namespace ValidationAttributes.CustomValidationAttribute
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class HasValueAttribute : ValidationAttribute
{
public string[] ValidValues { get; set; }
public override bool IsValid(object value)
{
return ValidValues.Contains(value?.ToString());
}
}
}
|
47917869bd739196ec6f730e2ff53a0c14a309ec
|
C#
|
KlichnikovDA/CGPaint
|
/CG_Paint/Axis.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace CG_Paint
{
public static class Axis
{
// Прорисовка осей координат
public static void DrawAxis(Graphics g)
{
g.DrawString("X", new Font("Arial", 14), new SolidBrush(Color.Black), 370, -30);
g.DrawLine(new Pen(Color.Black, 3), -400, 0,400, 0);
g.DrawString("Y", new Font("Arial", 14), new SolidBrush(Color.Black), 5, -290);
g.DrawLine(new Pen(Color.Black, 3), 0, -300, 0, 300);
}
}
}
|
9ab796a7aeab409a0968c966d0417aa6572fab44
|
C#
|
xoposhiy/stylist
|
/stylist/StyleChecker.cs
| 2.75
| 3
|
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
using Newtonsoft.Json;
using stylist.Checkers;
namespace stylist
{
public class StyleChecker
{
private readonly IChecker[] checkers;
public IChecker[] Checkers { get { return checkers; } }
public StyleChecker(Speller speller, CheckerOption[] options)
{
checkers =
CreateBaseCheckers(speller)
.Select(ch => InitChecker(ch, options))
.Where(ch => ch != null)
.ToArray();
}
private IChecker InitChecker(IChecker ch, CheckerOption[] options)
{
CheckerOption option = options.FirstOrDefault(opt => opt.Checker + "Checker" == ch.GetType().Name);
if (option == null) return ch;
if (option.Options == null) return null;
string json = JsonConvert.SerializeObject(option.Options);
JsonConvert.PopulateObject(json, ch);
return ch;
}
public StyleChecker(Speller speller)
: this(CreateBaseCheckers(speller).ToArray())
{
}
public static IEnumerable<IChecker> CreateBaseCheckers(Speller speller)
{
yield return new SpellChecker(speller);
yield return new NamingCaseChecker();
yield return new NameLengthChecker();
yield return new PredictableNamingChecker();
yield return new MethodLengthChecker();
yield return new IndentationChecker();
yield return new LineLengthChecker();
yield return new ArgumentsNumberChecker();
yield return new RedundantIfChecker();
}
public StyleChecker(params IChecker[] checkers)
{
this.checkers = checkers;
}
public CodeStyleIssue[] Check(string source)
{
var ast = new CSharpParser().Parse(source);
return Check(ast, source).Concat(ast.Errors.SelectMany(ErrorToIssue)).ToArray();
}
private IEnumerable<CodeStyleIssue> ErrorToIssue(Error err)
{
return TextSpan.Split(err.Region.Begin, err.Region.End)
.Select(span => new CodeStyleIssue(err.ErrorType.ToString(), err.Message, span));
}
public CodeStyleIssue[] Check(SyntaxTree ast, string source)
{
var codeIssues = new CodeIssues();
foreach (var checker in checkers.OfType<BaseAstChecker>())
{
checker.Initialize(codeIssues);
ast.AcceptVisitor(checker);
}
foreach (var checker in checkers.OfType<BaseTextChecker>())
{
checker.Initialize(codeIssues);
checker.Check(source);
}
return codeIssues.Issues.ToArray();
}
}
}
|
b121bb216cb20fe912a17d64fd56471de8c2652d
|
C#
|
Lachee/Code-Spaceship-Generator
|
/Form1.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace CodeSpaceshipGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Add a link to the LinkLabel.
LinkLabel.Link link = new LinkLabel.Link();
link.LinkData = "https://twitter.com/Managore/status/577252673621102592";
linkLabel1.Links.Add(link);
string path = "../../Form1.cs";
int lineHeight = 10;
int tabSize = 5;
Color bkgColor = Color.FromArgb(34, 34, 34);
Color polyColor = Color.White;
GenerateImage(path, lineHeight, tabSize, bkgColor, polyColor);
}
public void GenerateImage(string path, int lineHeight, int tabSize, Color bkgColor, Color polyColor, int imageWidth = 256)
{
//Get all the points. Its length will always be the length of the image
Point[] pointsA = GetTabPoints(path, imageWidth, 0, tabSize, lineHeight);
Point[] pointsB = GetTabPoints(path, imageWidth, 0, -tabSize, lineHeight);
//Prepare the bitmap
Bitmap image = new Bitmap(512, pointsA.Length * lineHeight);
//Background Color
//Color bkgColor = Color.FromArgb(34, 34, 34);
//Color polyColor = Color.White;
//Color polyColorOther = Color.White;
//Draw the polygon
using (Graphics graphics = Graphics.FromImage(image))
{
graphics.FillRectangle(new SolidBrush(bkgColor), 0, 0, image.Width - 1, image.Height - 1);
graphics.FillPolygon(new SolidBrush(polyColor), pointsA);
graphics.FillPolygon(new SolidBrush(polyColor), pointsB);
}
//Set the image
pictureBox1.Image = image;
//Save the image
if (checkbox_save.Checked)
{
string imageName = Path.GetFileName(path);
image.Save(imageName + ".bmp");
}
}
public Point[] GetTabPoints(string file, int x, int y, int xmod = 1, int ymod = 1)
{
if (!File.Exists(file))
{
//We cannot find the file, so return empty.
Console.WriteLine(file + " does not exist!");
return new Point[0];
}
//Prepare the points
List<Point> points = new List<Point>();
//Read the file lines
string[] lines = File.ReadAllLines(file);
//prepare the previous tab. This is used for when we come accross a empty line.
int preTabs = 0;
//Itterate through the lines
for (int i = 0; i < lines.Length; i++)
{
//Get the line
string ln = lines[i];
if (ln == "")
{
//if the line is empty, use the previous one and continue
string previousLine = i - 1 > 0 ? lines[i - 1] : "";
string nextLine = i + 1 < lines.Length ? lines[i+1] : "";
if (previousLine != "" && nextLine != "")
points.Add(new Point(x + ((preTabs + 1) * xmod), y + (i * ymod)));
else
points.Add(new Point(x + (preTabs * xmod), y + (i * ymod)));
continue;
}
//Count how many tabs there are
int tabs = GetLeadingWhitespaceLength(ln);
/*
Console.WriteLine();
Console.WriteLine("Line: " + ln);
Console.WriteLine("Number of Tabs: " + tabs);
Console.WriteLine();
*/
//Has the tab count changed?
if (tabs != preTabs)
{
//We must step from previous tabs to current tabs
points.Add(new Point(x + preTabs * xmod, y + i * ymod));
}
//Add it to the point list
points.Add(new Point(x + tabs * xmod, y + i * ymod));
//Store it as the previous points
preTabs = tabs;
}
points.Add(new Point(x + preTabs * xmod, y + lines.Length * ymod));
points.Add(new Point(x , y + lines.Length * ymod));
//return the point list
return points.ToArray();
}
public int GetLeadingWhitespaceLength(string s, int tabLength = 4, bool trimToLowerTab = true)
{
if (s.Length < tabLength) return 0;
int whiteSpaceCount = 0;
while (whiteSpaceCount < s.Length && Char.IsWhiteSpace(s[whiteSpaceCount])) whiteSpaceCount++;
if (whiteSpaceCount < tabLength) return 0;
if (trimToLowerTab)
{
whiteSpaceCount -= whiteSpaceCount % tabLength;
}
return whiteSpaceCount;
}
private void btn_browse_Click(object sender, EventArgs e)
{
openFileDialog.ShowDialog();
textbox_path.Text = openFileDialog.FileName;
}
private void btn_generate_Click(object sender, EventArgs e)
{
if (!File.Exists(textbox_path.Text))
{
MessageBox.Show("The path '" + textbox_path.Text + "' does not exist!", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int lineHeight = 10;
int tabSize = 5;
Color bkgColor = Color.FromArgb(34, 34, 34);
Color polyColor = Color.White;
GenerateImage(textbox_path.Text, lineHeight, tabSize, bkgColor, polyColor);
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void linkLabel1_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(e.Link.LinkData as string);
}
}
}
|
8975a4f60ea1ef2ea0cc5b5f37f3e30edcf00d27
|
C#
|
angelinn/ASOC-System-for-Online-Certificates
|
/src/SusiAPI/SusiAPI/SusiSession.cs
| 2.859375
| 3
|
using SusiAPI.Parser;
using SusiAPI.Responses;
using SusiAPICommon.Models;
using System;
using System.Threading.Tasks;
namespace SusiAPI
{
public class SusiSession
{
private ISusiParser parser;
public SusiSession(ISusiParser parser = null)
{
this.parser = parser ?? new ClassicSusiParser();
}
public async Task<LoginResponse> LoginAsync(string username, string password)
{
return await parser.LoginAsync(username, password);
}
public bool IsCurrentlyAStudent()
{
if (!parser.IsAuthenticated)
throw new Exception("Use login method first.");
return parser.IsCurrentlyAStudent;
}
public async Task<StudentInfo> GetStudentInfoAsync(string number = null)
{
if (!parser.IsAuthenticated)
throw new Exception("Use login method first.");
if (!String.IsNullOrEmpty(number))
await parser.SelectRoleAsync(number);
return await parser.GetStudentInfoAsync();
}
}
}
|
7757a5dc3f2e8b2afcd751ee69f204165950cac7
|
C#
|
lucas-miranda/Raccoon
|
/Raccoon/Graphics/Fonts/Shaders/TextShaderParameters.cs
| 2.609375
| 3
|
using Raccoon.Graphics;
namespace Raccoon.Fonts {
public class TextShaderParameters : IShaderParameters, IFontSizeShaderParameter {
#region Private Members
private float? _fontSize;
#endregion Private Members
#region Constructors
public TextShaderParameters(Font font) {
Font = font;
}
#endregion Constructors
#region Public Properties
public Font Font { get; set; }
public float FontSize {
get {
if (_fontSize.HasValue) {
return _fontSize.Value;
} else if (Font.ShaderParameters != null
&& Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter
) {
return fontSizeShaderParameter.FontSize;
}
return 0.0f;
}
set {
if (value <= 0.0f) {
_fontSize = null;
return;
}
_fontSize = value;
}
}
public float FontScale { get; set; } = 1.0f;
/// <summary>
/// A special kind of scale which only applies to font resolution size itself.
///
/// Some methods, such as MTSDF, can use a dynamic font scaling and any kind of view scaling which works as a transformation matrix, which we can't retrieve it's numeric value (e.g zoom) to properly calculate font size, should be applied here. Using it don't mess anything related to position or vertices scale, only font resolution.
/// </summary>
public float FontResolutionScale { get; set; } = 1.0f;
#endregion Public Properties
#region Public Methods
public void ApplyParameters(Shader shader) {
if (shader == null) {
throw new System.ArgumentNullException(nameof(shader));
}
if (Font == null || Font.ShaderParameters == null) {
return;
}
if (Font.ShaderParameters is FontMTSDFShaderParameters fontMTSDFShaderParameters) {
if (!(shader is FontMTSDFShader fontMTSDFShader)) {
throw new System.ArgumentException($"Expected '{nameof(FontMTSDFShader)}', but got '{shader.GetType().Name}' instead. (Because font shader parameters is '{nameof(FontMTSDFShaderParameters)}')");
}
fontMTSDFShaderParameters.ApplyParameters(shader);
fontMTSDFShader.ScreenPixelRange =
fontMTSDFShaderParameters.CalculateScreenPixelRange(FontSize, FontScale);
} else if (Font.ShaderParameters != null) {
Font.ShaderParameters.ApplyParameters(shader);
}
}
public IShaderParameters Clone() {
return new TextShaderParameters(Font) {
_fontSize = _fontSize,
FontScale = FontScale
};
}
public bool IsSafeFontScale(float fontSize, float fontScale) {
if (Font == null || Font.ShaderParameters == null) {
throw new System.InvalidOperationException($"{nameof(Font.ShaderParameters)} isn't defined.");
}
if (!(Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter)) {
throw new System.InvalidOperationException($"Current {nameof(Font.ShaderParameters)} doesn't implements {nameof(IFontSizeShaderParameter)}.");
}
return fontSizeShaderParameter.IsSafeFontScale(fontSize, fontScale);
}
public void SafeSetFontScale(float fontScale) {
if (Font == null || Font.ShaderParameters == null) {
throw new System.InvalidOperationException($"{nameof(Font.ShaderParameters)} isn't defined.");
}
if (!(Font.ShaderParameters is IFontSizeShaderParameter fontSizeShaderParameter)) {
throw new System.InvalidOperationException($"Current {nameof(Font.ShaderParameters)} doesn't implements {nameof(IFontSizeShaderParameter)}.");
}
if (fontSizeShaderParameter.IsSafeFontScale(FontSize, fontScale)) {
FontScale = fontScale;
}
}
public bool Equals(IShaderParameters other) {
return other != null
&& other is TextShaderParameters otherTextShaderParameters
&& otherTextShaderParameters.FontSize == FontSize
&& otherTextShaderParameters.FontScale == FontScale;
}
#endregion Public Methods
}
}
|
5eb60313368a0ab8c571133eea8945baee852340
|
C#
|
QuestroL/WhatBackend
|
/CharlieBackend.Business/Services/CourseService.cs
| 2.671875
| 3
|
using AutoMapper;
using CharlieBackend.Business.Services.Interfaces;
using CharlieBackend.Core.DTO.Course;
using CharlieBackend.Core.Entities;
using CharlieBackend.Data.Repositories.Impl.Interfaces;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CharlieBackend.Business.Services
{
public class CourseService : ICourseService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
public CourseService(IUnitOfWork unitOfWork, IMapper mapper)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
}
public async Task<CourseDto> CreateCourseAsync(CreateCourseDto courseModel)
{
try
{
var createdCourseEntity = _mapper.Map<Course>(courseModel);
_unitOfWork.CourseRepository.Add(createdCourseEntity);
await _unitOfWork.CommitAsync();
return _mapper.Map<CourseDto>(createdCourseEntity);
}
catch
{
_unitOfWork.Rollback();
return null;
}
}
public async Task<IList<CourseDto>> GetAllCoursesAsync()
{
var courses = _mapper.Map<List<CourseDto>>(await _unitOfWork.CourseRepository.GetAllAsync());
return courses;
}
public async Task<CourseDto> UpdateCourseAsync(long id, UpdateCourseDto courseModel)
{
try
{
var updatedEntity = _mapper.Map<Course>(courseModel);
updatedEntity.Id = id;
_unitOfWork.CourseRepository.Update(updatedEntity);
await _unitOfWork.CommitAsync();
return _mapper.Map<CourseDto>(updatedEntity);
}
catch
{
_unitOfWork.Rollback();
return null;
}
}
public Task<bool> IsCourseNameTakenAsync(string courseName)
{
return _unitOfWork.CourseRepository.IsCourseNameTakenAsync(courseName);
}
}
}
|
522aaa7ec96ea4cb1924cea48318f411f5711a17
|
C#
|
alco6/VideoDelay
|
/Assets/Scripts/TestWebCam.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestWebCam : MonoBehaviour {
//FPS
private int fps = 15;
private WebCamTexture webcam;
private Texture2D output;
private Color32[] data;
// Use this for initialization
void Start () {
// WebCamTexture webcamTexture = new WebCamTexture(1920, 1080, fps);
webcam = new WebCamTexture(1920, 1080, fps);
webcam.deviceName = "See3CAM_CU135";
webcam.Play();
output = new Texture2D(webcam.width, webcam.height);
GetComponent<Renderer>().material.mainTexture = output;
data = new Color32[webcam.width * webcam.height];
}
// Update is called once per frame
void Update () {
if (data != null)
{
webcam.GetPixels32(data);
// You can play around with data however you want here.
// Color32 has member variables of a, r, g, and b. You can read and write them however you want.
output.SetPixels32(data);
output.Apply();
}
}
}
|
f98a2c97783645ae96a5e758f0d003628d2d5fa5
|
C#
|
Aurbo99/vixen
|
/Modules/Property/Face/FaceMapItem.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization;
namespace VixenModules.Property.Face
{
public class FaceMapItem
{
public FaceMapItem()
{
PhonemeList = new Dictionary<string, Boolean>();
FaceComponents = new Dictionary<FaceComponent, bool>();
ElementColor = System.Drawing.Color.White;
}
public FaceMapItem Clone()
{
FaceMapItem retVal = new FaceMapItem();
retVal.PhonemeList = new Dictionary<string, bool>(PhonemeList);
retVal.ElementColor = ElementColor;
retVal.ElementGuid = ElementGuid;
retVal.FaceComponents = new Dictionary<FaceComponent, bool>(FaceComponents);
return retVal;
}
[DataMember]
public Dictionary<string, Boolean> PhonemeList { get; set; }
[DataMember]
public System.Drawing.Color ElementColor { get; set; }
[DataMember]
private string _stringName;
[DataMember]
public Guid ElementGuid { get; set; }
[DataMember]
public Dictionary<FaceComponent, bool> FaceComponents { get; set; }
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
if (FaceComponents == null)
{
FaceComponents = new Dictionary<FaceComponent, bool>();
if (PhonemeList.Values.Any(x => x))
{
FaceComponents.Add(FaceComponent.Mouth, true);
}
}
}
}
}
|
4928fa8fafae4d126bda7f3ae0af35bed3c942c7
|
C#
|
hasali19/SharpSDL
|
/SharpSDL/SDL.Mouse.cs
| 2.53125
| 3
|
using System;
using System.Runtime.InteropServices;
namespace SharpSDL
{
public enum SystemCursor
{
Arrow,
IBeam,
Wait,
Crosshair,
WaitArrow,
SizeNWSE,
SizeNESW,
SizeWE,
SizeNS,
SizeALL,
NO,
Hand
}
public enum MouseWheelDirection : uint
{
Normal,
Flipped
}
public enum Button : uint
{
Left = 1,
Middle = 2,
Right = 3,
X1 = 4,
X2 = 5,
}
[Flags]
public enum ButtonMask : uint
{
Left = 1 << ((int)Button.Left - 1),
Middle = 1 << ((int)Button.Middle - 1),
Right = 1 << ((int)Button.Right - 1),
X1 = 1 << ((int)Button.X1 - 1),
X2 = 1 << ((int)Button.X2 - 1)
}
[StructLayout(LayoutKind.Sequential)]
public struct Cursor
{
private readonly IntPtr ptr;
public Cursor(IntPtr ptr)
{
this.ptr = ptr;
}
public static implicit operator IntPtr(Cursor cursor)
{
return cursor.ptr;
}
public static implicit operator Cursor(IntPtr ptr)
{
return new Cursor(ptr);
}
}
public static unsafe partial class SDL
{
public static uint MOUSE(uint x)
{
return (uint)(1 << ((int)x - 1));
}
[DllImport(LibraryName, EntryPoint = "SDL_CaptureMouse", CallingConvention = CallingConvention.Cdecl)]
public static extern int CaptureMouse(bool enabled);
[DllImport(LibraryName, EntryPoint = "SDL_CreateCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern Cursor CreateCursor(byte* data, byte* mask, int w, int h, int hotX, int hotY);
[DllImport(LibraryName, EntryPoint = "SDL_CreateSystemCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern Cursor CreateSystemCursor(SystemCursor id);
[DllImport(LibraryName, EntryPoint = "SDL_FreeCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern void FreeCursor(Cursor cursor);
[DllImport(LibraryName, EntryPoint = "SDL_GetCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern Cursor GetCursor();
[DllImport(LibraryName, EntryPoint = "SDL_GetDefaultCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern Cursor GetDefaultCursor();
[DllImport(LibraryName, EntryPoint = "SDL_GetGlobalMouseState", CallingConvention = CallingConvention.Cdecl)]
public static extern ButtonMask GetGlobalMouseState(int* x, int* y);
[DllImport(LibraryName, EntryPoint = "SDL_GetMouseFocus", CallingConvention = CallingConvention.Cdecl)]
public static extern Window GetMouseFocus();
[DllImport(LibraryName, EntryPoint = "SDL_GetMouseState", CallingConvention = CallingConvention.Cdecl)]
public static extern ButtonMask GetMouseState(int* x, int* y);
[DllImport(LibraryName, EntryPoint = "SDL_GetRelativeMouseMode", CallingConvention = CallingConvention.Cdecl)]
public static extern bool GetRelativeMouseMode();
[DllImport(LibraryName, EntryPoint = "SDL_GetRelativeMouseState", CallingConvention = CallingConvention.Cdecl)]
public static extern ButtonMask GetRelativeMouseState(int* x, int* y);
[DllImport(LibraryName, EntryPoint = "SDL_SetCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern void SetCursor(Cursor cursor);
[DllImport(LibraryName, EntryPoint = "SDL_SetRelativeMouseMode", CallingConvention = CallingConvention.Cdecl)]
public static extern int SetRelativeMouseMode(bool enabled);
[DllImport(LibraryName, EntryPoint = "SDL_ShowCursor", CallingConvention = CallingConvention.Cdecl)]
public static extern int ShowCursor(int toggle);
[DllImport(LibraryName, EntryPoint = "SDL_WarpMouseGlobal", CallingConvention = CallingConvention.Cdecl)]
public static extern int WarpMouseGlobal(int x, int y);
[DllImport(LibraryName, EntryPoint = "SDL_WarpMouseInWindow", CallingConvention = CallingConvention.Cdecl)]
public static extern void WarpMouseInWindow(Window window, int x, int y);
}
}
|
0b6c5b1b9631a3e01096041a036790a5930f9913
|
C#
|
UkaszK95/SI_EchoStateNetwork
|
/SurveyESN/MainWindow.xaml.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LibraryESN;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Globalization;
namespace SurveyESN
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public EchoStateNetwork esn;
// Status
public bool fileSelected;
public String filePath;
public MainWindow()
{
fileSelected = false;
InitializeComponent();
CheckStatus();
}
public void CheckStatus()
{
// Check if data file is selected
if (fileSelected || esn != null)
{
teach.IsEnabled = true;
initValue.IsEnabled = true;
}
else
{
teach.IsEnabled = false;
initValue.IsEnabled = false;
}
// Check if ESN was teached
try
{
if (esn.isTeached == false)
{
askBox.IsEnabled = false;
askButton.IsEnabled = false;
}
else
{
askBox.IsEnabled = true;
askButton.IsEnabled = true;
}
}
catch (Exception e)
{
askBox.IsEnabled = false;
askButton.IsEnabled = false;
}
}
#region Buttons
// Utworzenie nowej sieci (okno z parametrami)
private void File_New_Click(object sender, RoutedEventArgs e)
{
showMessageBox("Zaczyna się generowanie sieci neuronowej" + Environment.NewLine + "Zostaniesz poinformowany/a o zakończeniu procesu za pomocą komunikatu", "Generowanie ESN");
File_New.IsEnabled = false;
reservoirValue.Text = "null";
leakValue.Text = "null";
mseValue.Text = "null";
answer.Text = "";
Thread th = new Thread(() => generateNewESN());
th.Start();
}
// Otwarcie zapisanej wcześniej sieci
private void File_Open_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "File"; // Default file name
dlg.DefaultExt = ".esn"; // Default file extension
dlg.Filter = "ESN file (.esn)|*.esn"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
FileStream fs;
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
fs = new FileStream(filename, FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
//Deserialize the hashtable from the file and
//assign the reference to the local variable.
esn = (EchoStateNetwork)formatter.Deserialize(fs);
mseValue.Text = esn.mse.ToString();
reservoirValue.Text = esn.size.ToString();
if (esn.mse == 0) { mseValue.Text = ""; } else { mseValue.Text = esn.mse.ToString(); }
leakValue.Text = esn.a.ToString();
if (esn.isTeached == true)
{
askBox.IsEnabled = true;
askButton.IsEnabled = true;
teach.IsEnabled = false;
initValue.IsEnabled = false;
}
else
{
askBox.IsEnabled = false;
askButton.IsEnabled = false;
teach.IsEnabled = true;
initValue.IsEnabled = true;
loadData.IsEnabled = true;
}
if(loadDataPath.Text.Equals("Nie wybrano pliku"))
{
teach.IsEnabled = false;
initValue.IsEnabled = false;
}
}
catch (Exception ex)
{
showMessageBox("Deserializacja nieudana. Powód: " + ex.Message, "Błąd");
throw;
}
fs.Close();
}
}
// Zapisanie obiektu sieci
private void File_Save_Click(object sender, RoutedEventArgs e)
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "ESN " + DateTime.Today.ToShortDateString(); // Default file name
dlg.DefaultExt = ".esn"; // Default file extension
dlg.Filter = "Esn file (.esn)|*.esn"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
FileStream fs;
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
fs = new FileStream(filename, FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
EchoStateNetwork temp = esn;
temp.data = null;
temp.Y = null;
temp.Yt = null;
temp.X = null;
formatter.Serialize(fs, temp);
}
catch (Exception ex)
{
showMessageBox("Serializacja nieudana. Powód: " + ex.Message, "Błąd");
throw;
}
fs.Close();
}
}
// Zamknięcie programu
private void File_Exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
// Okno z nami
private void Autors_Click(object sender, RoutedEventArgs e)
{
showMessageBox("Adam Matuszak" + Environment.NewLine + "Łukasz Knop" + Environment.NewLine + "Szymon Kaszuba", "Autorzy");
}
// Okienko z linkami do dokumentaji/git
private void Document_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/Tetrach121/SI_ESN");
}
// Wczytanie danych do nauki sieci
private void loadData_Click(object sender, RoutedEventArgs e)
{
// Wczytaj dane
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "File"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Txt file (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
filePath = dlg.FileName;
loadDataPath.Text = FileNameShow(dlg.FileName);// Wypisz ścieżkę w label loadDataPath
fileSelected = true; // Jeśli nie ma wyjątków to fileSelected = true
}
CheckStatus();
}
private string FileNameShow(string s)
{
string[] sSplit = s.Split('\\');
if(sSplit.Length > 5)
return "...\\" + sSplit[sSplit.Length - 4] + '\\' + sSplit[sSplit.Length - 3] + sSplit[sSplit.Length - 2] + '\\' + sSplit[sSplit.Length - 1];
if (sSplit.Length > 3)
return "...\\" + sSplit[sSplit.Length - 2] + '\\' + sSplit[sSplit.Length - 1];
return s;
}
// Wprowadź zapytanie
private void askButton_Click(object sender, RoutedEventArgs e)
{
double input;
//Try parsing in the current culture
if (!double.TryParse(askBox.Text, System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out input) &&
//Then try in US english
!double.TryParse(askBox.Text, System.Globalization.NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out input) &&
//Then in neutral language
!double.TryParse(askBox.Text, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out input))
{
input = 0;
}
double ans = esn.Ask(input);
answer.Text = "Wynik: " + ans.ToString();
}
// Nauczaj sieć wczytanymi danymi
private void teach_Click(object sender, RoutedEventArgs e)
{
showMessageBox("Rozpoczynam uczenie sieci", "Proces uczenia");
esn.Learn(filePath, int.Parse(initValue.Text));
mseValue.Text = esn.mse.ToString();
showMessageBox("Sieć została wyuczona");
CheckStatus();
}
#endregion
#region Logic
public void generateNewESN()
{
esn = new EchoStateNetwork(1000, 0.3);
reservoirValue.Dispatcher.Invoke(() => { reservoirValue.Text = "1000"; });
leakValue.Dispatcher.Invoke(() => { leakValue.Text = "0.3";});
File_New.Dispatcher.Invoke(() => { File_New.IsEnabled = true; });
showMessageBox("Sieć wygenerowana", "Zakończono proces");
}
static public void showMessageBox(String msg, String title = "Informacja")
{
MessageBox.Show(msg, title, MessageBoxButton.OK);
}
#endregion
}
}
|
5adc1c9d888c629ef2344b48c9a1e42fbb20238c
|
C#
|
Sushant1010/Projeect
|
/NCIT_MIS - Copy/Repository/A_CategoryRepo.cs
| 2.53125
| 3
|
using Dapper;
using NCIT_MIS.Models;
using NCIT_MIS.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NCIT_MIS.Repository
{
public class A_CategoryRepo
{
public int AddCategory(A_Category saveCate)
{
string sql = "insert into A_Category(CategoryName,CategoryCode,EnteredBy,EnteredDate,LastUpdatedBy,LastUpdatedDate,DepartmentId," +
"IsDeleted,DeletedBy,DeletedDate)" +
" values(@CategoryName,@CategoryCode,@EnteredBy,@EnteredDate,0,null,@DepartmentId," +
"0,0,null)";
using (var db = DbHelper.GetDBConnection())
{
int id = db.Query<int>(sql, saveCate).SingleOrDefault();
db.Close();
return id;
}
}
public List<A_CategoryVM> GetAllCategoryList()
{
string sql = "select * from A_Category c " +
"left join Sys_Department d on d.departmentId = c.departmentId" +
" where c.IsDeleted=0";
using (var db = DbHelper.GetDBConnection())
{
//db.Execute(sql);
var lst = db.Query<A_CategoryVM>(sql).ToList();
db.Close();
return lst;
}
}
public A_CategoryVM getCategoryDetail(int id)
{
string sql = "select * from A_Category c" +
" left join Sys_Department d on d.departmentId = c.departmentId" +
" where c.IsDeleted=0 and c.CategoryId=" + id;
using (var db = DbHelper.GetDBConnection())
{
var lst = db.Query<A_CategoryVM>(sql).SingleOrDefault();
db.Close();
return lst;
}
}
public bool UpdateCategory(A_Category updateCate, int Id)
{
string sql = " Update A_Category set CategoryName=@CategoryName, CategoryCode=@CategoryCode," +
"LastUpdatedDate=@LastUpdatedDate, LastUpdatedBy=@LastUpdatedBy where IsDeleted=0 and CategoryId= " + Id;
using (var db = DbHelper.GetDBConnection())
{
var lst = db.Execute(sql, updateCate);
db.Close();
if (lst > 0)
{
return true;
}
else
{
return false;
}
}
}
public bool DeleteCategory(int Id, DateTime deletedDate, int deletedby)
{
string sql = " Update A_Category set IsDeleted=1, DeletedBy=" + deletedby + ", DeletedDate=" + deletedDate + " where CategoryId= " + Id;
using (var db = DbHelper.GetDBConnection())
{
var lst = db.Execute(sql);
db.Close();
if (lst > 0)
{
return true;
}
else
{
return false;
}
}
}
}
}
|
08f297b18f491f7d80a1081f3cabae8d10065e9f
|
C#
|
guilhermebentomarques/Alura_CSharpProgramming
|
/Alura_CSharpProgramming/Alura_CSharpProgramming_Parte11/Alura_CSharpProgramming_Parte11/Aula06_TaskWaitAll.cs
| 3.3125
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Alura_CSharpProgramming_ParteZ11
{
class Aula06_TaskWaitAll
{
static void Metodo()
{
Console.WriteLine("Número de Threads - Início");
Console.WriteLine(Process.GetCurrentProcess().Threads.Count);
Task[] tarefas = new Task[10];
for (int i = 0; i < tarefas.Length; i++)
{
int numeroCorredor = i;
Task.Run(() => Correr(numeroCorredor));
}
Task.WaitAll(tarefas);
Console.WriteLine("Número de Threads - Fim");
Console.WriteLine(Process.GetCurrentProcess().Threads.Count);
Console.WriteLine("Término do processamento. Tecle [ENTER] para terminar.");
Console.ReadLine();
}
static void Correr(int numCorredor)
{
Console.WriteLine("Corredor {0} largou " + numCorredor);
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Corredor {0} terminou " + numCorredor);
Console.WriteLine("");
}
}
}
|
379c4a3edb6ee92418b8e875d7ecdebaa280dffa
|
C#
|
krishna3006/Dotnet
|
/C #/day6/New folder/Collectionsdemo/HasttabDemo/Program.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading.Tasks;
namespace HasttabDemo
{
class Program
{
public void Show()
{
Hashtable ht = new Hashtable();
ht.Add("1", "Krishna");
ht.Add("2", "Bhargav");
ht.Add("3", "Naga");
Console.WriteLine("Hashtable Data is");
foreach(DictionaryEntry ent in ht)
{
Console.WriteLine(ent.Key+" "+ent.Value);
}
}
static void Main(string[] args)
{
new Program().Show();
}
}
}
|
2ed88ff8d4dbb0342c2f6f36c19233ff1a066ee6
|
C#
|
shelehedaiv/Analysis7
|
/Analysis7/Converter/ProbabilityNameConverter.cs
| 2.84375
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace Analysis7.Converter
{
public class ProbabilityNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var probability = (double) values[0];
var status = (bool) values[1];
if (!status) return "";
if (probability < 0.2) return "Дуже низький";
else if (probability < 0.4) return "Низький";
else if (probability < 0.6) return "Середній";
else if (probability < 0.8) return "Високий";
else return "Дуже високий";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|