Here are the examples of the csharp api System.Math.Floor(decimal) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
106 Examples
19
Source : MathFilters.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static int Floor(object value)
{
return value == null
? 0
: Convert.ToInt32(Math.Floor(Convert.ToDecimal(value)));
}
19
Source : RoundingSettings.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public decimal Round(decimal value)
{
var isNegative = (RoundingConventionMethod != null && RoundingConventionMethod != RoundingConvention.Normal) && value < 0;
if (RoundingConventionMethod != null && isNegative)
value = Math.Abs(value); // its very importend to have a positive number when using floor/Ceiling
switch (RoundingConventionMethod)
{
case null:
case RoundingConvention.Normal:
value = Math.Round(value, this.RowDecimalRoundTotal);
break;
case RoundingConvention.RoundUpp:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Ceiling(value * adjustment) / adjustment);
}
break;
case RoundingConvention.RoundDown:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Floor(value * adjustment) / adjustment);
}
break;
case RoundingConvention.None:
{
var adjustment = (decimal)Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Truncate(value * adjustment) / adjustment);
}
break;
}
if (isNegative)
value = -value;
return value;
}
19
Source : DecimalExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static decimal Floor(this decimal d)
{
return Math.Floor(d);
}
19
Source : Hash.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
public void Add(decimal val)
{
if (Offset == -1)
{
if (DecimalPlaces.HasValue)
{
val *= Pow10Decimal(DecimalPlaces.Value);
roundingFractions.Add((int)((val - Math.Floor(val)) * OFFSET_SIZE));
}
else if (SignificantFigures.HasValue)
{
if (val == 0.0M) roundingFractions.Add(0);
else
{
val *= Pow10Decimal(SignificantFigures.Value - 1 - (int)Math.Floor(Math.Log10((double)Math.Abs(val))));
roundingFractions.Add((int)((val - Math.Floor(val)) * OFFSET_SIZE));
}
}
}
else
{
if (DecimalPlaces.HasValue)
{
var scale = Pow10Decimal(DecimalPlaces.Value);
val = Math.Floor(val * scale + ((decimal)Offset / OFFSET_SIZE)) / scale;
}
else if (SignificantFigures.HasValue)
{
if (val != 0.0M)
{
var scale = Pow10Decimal(SignificantFigures.Value - 1 - (int)Math.Floor(Math.Log10((double)Math.Abs(val))));
val = Math.Floor(val * scale + ((decimal)Offset / OFFSET_SIZE)) / scale;
}
}
Stream(StreamSerializer.WriteDecimal, StreamSerializer.ReadDecimal, val);
var c = new DecimalConverter { D = val };
AddPrivate(c.flags);
AddPrivate(c.hi);
AddPrivate(c.mid);
AddPrivate(c.lo);
}
}
19
Source : MathImplementation.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public decimal floor(decimal decimalValue) => Floor(decimalValue);
19
Source : ExcelTime.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private void Init(decimal value)
{
// handle hour
decimal totalSeconds = value * SecondsPerDay;
decimal hour = Math.Floor(totalSeconds / SecondsPerHour);
Hour = (int)hour;
// handle minute
decimal remainingSeconds = totalSeconds - (hour * SecondsPerHour);
decimal minute = Math.Floor(remainingSeconds / SecondsPerMinute);
Minute = (int)minute;
// handle second
remainingSeconds = totalSeconds - (hour * SecondsPerHour) - (minute * SecondsPerMinute);
decimal second = Math.Round(remainingSeconds, MidpointRounding.AwayFromZero);
// Second might be rounded to 60... the SetSecond method handles that.
SetSecond((int)second);
}
19
Source : eliteGradientView.cs
with MIT License
from arqueror
with MIT License
from arqueror
public static void MoveToNextColor()
{
try
{
//Move to new color
step %= 1;
colorIndices[0] = colorIndices[1];
colorIndices[2] = colorIndices[3];
//pick two new target color indices
//do not pick the same as the current one
colorIndices[1] =
(int)(colorIndices[1] + Math.Floor((decimal)1 + new Random().Next(100) * (colors.Length - 1))) %
colors.Length;
colorIndices[3] =
(int)(colorIndices[3] + Math.Floor((decimal)1 + new Random().Next(100) * (colors.Length - 1))) %
colors.Length;
}
catch { }
}
19
Source : ValueAnimator.cs
with Apache License 2.0
from ascora
with Apache License 2.0
from ascora
private TimeSpan GetTimerInterval()
{
return TimeSpan.FromTicks((long)Math.Floor(TimeSpan.TicksPerSecond / (decimal)FrameRate));
}
19
Source : AmountHelper.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static decimal RoundAmount(decimal value, decimal digitsMultiplier) =>
Math.Floor(value * digitsMultiplier);
19
Source : NumberExtensions.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static decimal ToTokenDigits(this decimal tokens, decimal tokenDigitsMultiplier) =>
Math.Floor(tokens * tokenDigitsMultiplier);
19
Source : AmountHelper.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static decimal RoundDown(decimal d, decimal digitsMultiplier)
{
if (digitsMultiplier > 1000000000)
digitsMultiplier = 1000000000; // server decimal precision
return Math.Floor(d * digitsMultiplier) / digitsMultiplier;
}
19
Source : DecimalRuleHelper.cs
with MIT License
from Avanade
with MIT License
from Avanade
public static int CalcIntegerPartLength(decimal value)
{
if (value == 0)
return 0;
var floor = (double)Math.Floor(Math.Abs(value));
if (floor == 0)
return 0;
return (int)Math.Floor(Math.Log10(floor)) + 1;
}
19
Source : CreditCard.cs
with MIT License
from ay2015
with MIT License
from ay2015
private static string FakeCreditCardNumber(string prefix, int length)
{
string creditCardNumber = prefix;
int sum = 0, pos = 0;
while (creditCardNumber.Length < (length - 1))
{
double randomNumber = (new Random().NextDouble() * 1.0f - 0f);
creditCardNumber += Math.Floor(randomNumber * 10);
}
var creditCardNumberReversed = creditCardNumber.ToCharArray().Reverse();
var creditCardNumbers = creditCardNumberReversed.Select(c => Convert.ToInt32(c.ToString()));
int[] number = creditCardNumbers.ToArray();
while (pos < length - 1)
{
int odd = number[pos] * 2;
if (odd > 9) { odd -= 9; }
sum += odd;
if (pos != (length - 2)) { sum += number[pos + 1]; }
pos += 2;
}
int validDigit = Convert.ToInt32((Math.Floor((decimal) sum/10) + 1)*10 - sum)%10;
creditCardNumber += validDigit;
return creditCardNumber;
}
19
Source : ImageGenerator.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
public static void Create(byte[] payload, string image, string outputfile)
{
try
{
Bitmap img = new Bitmap(image);
int width = img.Size.Width;
int height = img.Size.Height;
//Lock the bitmap in memory so it can be changed programmatically.
Rectangle rect = new Rectangle(0, 0, width, height);
BitmapData bmpData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
IntPtr ptr = bmpData.Scan0;
// Copy the RGB values to an array for easy modification
int bytes = Math.Abs(bmpData.Stride) * img.Height;
byte[] rgbValues = new byte[bytes];
Marshal.Copy(ptr, rgbValues, 0, bytes);
//Check that the payload fits in the image
if (bytes / 2 < payload.Length)
{
Console.Write("Image not large enough to contain payload!");
img.UnlockBits(bmpData);
img.Dispose();
return;
}
//Generate a random string to use to fill other pixel info in the picture.
string randstr = RandomString(128);
byte[] randb = Encoding.ASCII.GetBytes(randstr);
//loop through the RGB array and copy the payload into it
for (int counter = 0; counter < (rgbValues.Length) / 3; counter++)
{
int paybyte1;
int paybyte2;
int paybyte3;
if (counter < payload.Length)
{
paybyte1 = (int)Math.Floor((decimal)(payload[counter] / 16));
paybyte2 = (payload[counter] & 0x0f);
paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
}
else
{
paybyte1 = (randb[counter % 113] & 0x0f);
paybyte2 = (randb[(counter + 1) % 67] & 0x0f);
paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
}
rgbValues[(counter * 3)] = (byte)((rgbValues[(counter * 3)] & 0xf0) | paybyte1);
rgbValues[(counter * 3 + 1)] = (byte)((rgbValues[(counter * 3 + 1)] & 0xf0) | paybyte2);
rgbValues[(counter * 3 + 2)] = (byte)((rgbValues[(counter * 3 + 2)] & 0xf0) | paybyte3);
}
//Copy the array of RGB values back to the bitmap
Marshal.Copy(rgbValues, 0, ptr, bytes);
img.UnlockBits(bmpData);
//Write the image to a file
img.Save(outputfile, ImageFormat.Png);
img.Dispose();
//Console.WriteLine("[*] Image file created {0}", outputfile);
}
catch (Exception e)
{
Console.WriteLine("[x] error: " + e.Message);
Console.WriteLine("[x] file : " + image);
Console.WriteLine("[x] error: " + e.StackTrace);
}
}
19
Source : ImageLoader.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
private static byte[] GetPayloadFromImage(Stream imgfile, int payloadlength)
{
Bitmap g = new Bitmap(imgfile);
int width = g.Size.Width;
int rows = (int)Math.Ceiling((decimal)payloadlength / width);
int array = (rows * width);
byte[] o = new byte[array];
int lrows = rows;
int lwidth = width;
int lpayload = payloadlength;
for (int i = 0; i < lrows; i++)
{
for (int x = 0; x < lwidth; x++)
{
Color pcolor = g.GetPixel(x, i);
o[i * width + x] = (byte)(Math.Floor((decimal)(((pcolor.B & 15) * 16) | (pcolor.G & 15))));
}
}
//o contain payload
byte[] otrue = new byte[lpayload];
Array.Copy(o, otrue, lpayload);
return otrue;
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
static void Main(string[] args)
{
string replacedemblypath = "";
string image = "";
string outputfile = "";
bool showHelp = false;
var p = new OptionSet() {
{ "a|replacedembly=", "replacedembly to hide.\n", v => replacedemblypath = v },
{ "i|image=", "Image src.", v => image = v },
{ "o|output=", "Output file", v => outputfile = v },
{ "h|help", "Show this message and exit.", v => showHelp = v != null },
};
try
{
try
{
p.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Try '--help' for more information.");
return;
}
if (showHelp)
{
ShowHelp(p);
return;
}
//Payload to work
byte[] payload = File.ReadAllBytes(replacedemblypath);
Bitmap img = new Bitmap(image);
int width = img.Size.Width;
int height = img.Size.Height;
//Lock the bitmap in memory so it can be changed programmatically.
Rectangle rect = new Rectangle(0, 0, width, height);
BitmapData bmpData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
IntPtr ptr = bmpData.Scan0;
// Copy the RGB values to an array for easy modification
int bytes = Math.Abs(bmpData.Stride) * img.Height;
byte[] rgbValues = new byte[bytes];
Marshal.Copy(ptr, rgbValues, 0, bytes);
//Check that the payload fits in the image
if(bytes/2 < payload.Length) {
Console.Write("Image not large enough to contain payload!");
img.UnlockBits(bmpData);
img.Dispose();
return;
}
//Generate a random string to use to fill other pixel info in the picture.
string randstr = RandomString(128);
byte[] randb = Encoding.ASCII.GetBytes(randstr);
//loop through the RGB array and copy the payload into it
for (int counter = 0; counter < (rgbValues.Length) / 3; counter++) {
int paybyte1;
int paybyte2;
int paybyte3;
if (counter < payload.Length){
paybyte1 = (int)Math.Floor((decimal)(payload[counter] / 16));
paybyte2 = (payload[counter] & 0x0f);
paybyte3 = (randb[(counter + 2) % 109] & 0x0f);
} else {
paybyte1 = (randb[counter % 113] & 0x0f);
paybyte2 = (randb[(counter + 1)% 67] & 0x0f);
paybyte3 = (randb[(counter + 2)% 109] & 0x0f);
}
rgbValues[(counter * 3)] = (byte)((rgbValues[(counter * 3)] & 0xf0) | paybyte1);
rgbValues[(counter * 3 + 1)] = (byte)((rgbValues[(counter * 3 + 1)] & 0xf0) | paybyte2);
rgbValues[(counter * 3 + 2)] = (byte)((rgbValues[(counter * 3 + 2)] & 0xf0) | paybyte3);
}
//Copy the array of RGB values back to the bitmap
Marshal.Copy(rgbValues, 0, ptr, bytes);
img.UnlockBits(bmpData);
//Write the image to a file
img.Save(outputfile, ImageFormat.Png);
img.Dispose();
Executereplacedembly(outputfile, payload.Length);
}
catch (Exception e)
{
Console.WriteLine("[x] error: " + e.Message);
Console.WriteLine("[x] error: " + e.StackTrace);
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik
with BSD 3-Clause "New" or "Revised" License
from b4rtik
private static void Executereplacedembly(string imgfile, int payloadlength)
{
Bitmap g = new Bitmap(imgfile);
int width = g.Size.Width;
int rows = (int)Math.Ceiling((decimal)payloadlength / width);
int array = (rows * width);
byte[] o = new byte[array];
int lrows = rows;
int lwidth = width;
int lpayload = payloadlength;
for (int i = 0; i < lrows; i++)
{
for (int x = 0; x < lwidth; x++)
{
Color pcolor = g.GetPixel(x, i);
o[i * width + x] = (byte)(Math.Floor((decimal)(((pcolor.B & 15) * 16) | (pcolor.G & 15))));
}
}
//o contain payload
byte[] otrue = new byte[lpayload];
Array.Copy(o, otrue, lpayload);
replacedembly replacedembly = replacedembly.Load(otrue);
replacedembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[0]);
}
19
Source : Util.cs
with MIT License
from bitrinjani
with MIT License
from bitrinjani
public static decimal RoundDown(decimal d, double decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(d * power) / power;
}
19
Source : LibraClient.cs
with MIT License
from blockcoli
with MIT License
from blockcoli
public async Task<bool> TransferCoins(Account sender, string receiverAddress, ulong amount, ulong gasUnitPrice = 0, ulong maxGasAmount = 1000000)
{
try
{
var accountState = await QueryBalance(sender.Address);
var payloadLCS = new PayloadLCS();
payloadLCS.Code = Convert.FromBase64String(Constant.ProgamBase64Codes.PeerToPeerTxn);
payloadLCS.TransactionArguments = new List<TransactionArgumentLCS>();
payloadLCS.TransactionArguments.Add(new TransactionArgumentLCS
{
ArgType = Types.TransactionArgument.Types.ArgType.Address,
Address = new AddressLCS { Value = receiverAddress }
});
payloadLCS.TransactionArguments.Add(new TransactionArgumentLCS
{
ArgType = Types.TransactionArgument.Types.ArgType.U64,
U64 = amount
});
var transaction = new RawTransactionLCS
{
Sender = new AddressLCS { Value = sender.Address },
SequenceNumber = accountState.SequenceNumber,
TransactionPayload = TransactionPayloadLCS.FromScript(payloadLCS),
MaxGasAmount = maxGasAmount,
GasUnitPrice = gasUnitPrice,
ExpirationTime = (ulong)Math.Floor((decimal)DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000) + 100
};
var transactionLCS = LCSCore.LCSDeserialization(transaction);
var digestSHA3 = new SHA3_256();
var saltDigest = digestSHA3.ComputeVariable(Constant.HashSaltValues.RawTransactionHashSalt.ToBytes());
var saltDigestAndTransaction = saltDigest.Concat(transactionLCS).ToArray();
var hash = digestSHA3.ComputeVariable(saltDigestAndTransaction);
var senderSignature = sender.KeyPair.Sign(hash);
var publicKeyLen = BitConverter.GetBytes((uint)sender.PublicKey.Length);
var signatureLen = BitConverter.GetBytes((uint)senderSignature.Length);
var txnBytes = transactionLCS.Concat(publicKeyLen).ToArray();
txnBytes = txnBytes.Concat(sender.PublicKey).ToArray();
txnBytes = txnBytes.Concat(signatureLen).ToArray();
txnBytes = txnBytes.Concat(senderSignature).ToArray();
var request = new SubmitTransactionRequest
{
Transaction = new SignedTransaction
{
TxnBytes = txnBytes.ToByteString()
}
};
var response = await acClient.SubmitTransactionAsync(request);
return response.AcStatus.Code == AdmissionControlStatusCode.Accepted;
}
catch (Exception ex)
{
throw ex;
}
}
19
Source : SerializationHelper.cs
with GNU Affero General Public License v3.0
from blockbasenetwork
with GNU Affero General Public License v3.0
from blockbasenetwork
public static byte[] ConvertNameToBytes(string name)
{
var a = new byte[8];
Int32 bit = 63;
for (int i = 0; i < name.Length; ++i)
{
var c = SerializationHelper.CharToSymbol(name[i]);
if (bit < 5)
c = (byte)(c << 1);
for (int j = 4; j >= 0; --j)
{
if (bit >= 0)
{
a[(int)Math.Floor((decimal)(bit / 8))] |= (byte)(((c >> j) & 1) << (bit % 8));
--bit;
}
}
}
return a;
}
19
Source : RangeRelation.cs
with Apache License 2.0
from blushingpenguin
with Apache License 2.0
from blushingpenguin
protected bool Match(string num, bool allowFractions)
{
decimal exprValue = Expr.Evaluate(num);
bool canRangeMatch = allowFractions ||
exprValue == Math.Floor(exprValue);
foreach (var range in Ranges)
{
if ((!range.High.HasValue && exprValue == range.Low) ||
(canRangeMatch && range.High.HasValue &&
exprValue >= range.Low && exprValue <= range.High))
{
return !Not;
}
}
return Not;
}
19
Source : Fluent.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public static long Round(this long number, long level)
{
return Convert.ToInt64(Math.Floor((decimal)number / level) * level);
}
19
Source : BtcTurkHelpers.cs
with MIT License
from burakoner
with MIT License
from burakoner
private static decimal Floor(decimal number)
{
return Math.Floor(number * 100000000) / 100000000;
}
19
Source : LineArea.cs
with Apache License 2.0
from cajuncoding
with Apache License 2.0
from cajuncoding
private InlineArea buildSimpleLeader(char c, int leaderLength)
{
int width = this.currentFontState.GetWidth(currentFontState.MapCharacter(c));
if (width == 0)
{
FonetDriver.ActiveDriver.FireFonetError(
"char '" + c + "' has width 0. Using width 100 instead.");
width = 100;
}
int factor = (int)Math.Floor((decimal)leaderLength / width);
char[] leaderChars = new char[factor];
for (int i = 0; i < factor; i++)
{
leaderChars[i] = c;
}
WordArea leaderPatternArea = new WordArea(currentFontState, this.red,
this.green, this.blue,
new String(leaderChars),
leaderLength);
leaderPatternArea.setYOffset(placementOffset);
return leaderPatternArea;
}
19
Source : numerical.cs
with MIT License
from ccxt-net
with MIT License
from ccxt-net
public static decimal TruncateDecimal(decimal value, int precision)
{
var _step = (decimal)Math.Pow(10, precision);
return Math.Floor(_step * value) / _step;
}
19
Source : PerformanceStatisticsManager.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
protected int GetQuantaAvgLength()
{
LastQuantaQueueLengths.Add(Context.QuantumHandler.QuantaQueueLenght);
if (LastQuantaQueueLengths.Count > 20)
LastQuantaQueueLengths.RemoveAt(0);
return (int)Math.Floor(decimal.Divide(LastQuantaQueueLengths.Sum(), LastQuantaQueueLengths.Count));
}
19
Source : PriceHistoryPeriodHelper.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
public static int GetDiff(this DateTime dateFrom, DateTime dateTo, PriceHistoryPeriod period)
{
if (dateFrom > dateTo)
{
throw new InvalidOperationException("Date from is greater than date to.");
}
switch (period)
{
case PriceHistoryPeriod.Month:
var totalDiff = 0;
while ((dateTo - dateFrom).TotalDays > 0)
{
dateFrom = dateFrom.AddMonths(1);
totalDiff++;
}
return totalDiff;
default:
return (int)Math.Floor(decimal.Divide(dateTo.Ticks - dateFrom.Ticks, TicksPerPeriod(period)));
}
}
19
Source : PriceHistoryManager.cs
with MIT License
from centaurus-project
with MIT License
from centaurus-project
public static (int market, PriceHistoryPeriod period) DecodereplacedetTradesResolution(long managerId)
{
return (
market: (int)Math.Floor(decimal.Divide(managerId, uint.MaxValue)),
period: (PriceHistoryPeriod)(int)(managerId % uint.MaxValue)
);
}
19
Source : OrderSizeExtensions.cs
with GNU Affero General Public License v3.0
from coj337
with GNU Affero General Public License v3.0
from coj337
public static decimal ToDecimalPlaces(this decimal originalNumber, int decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(originalNumber * power) / power;
}
19
Source : Tools.cs
with GNU General Public License v3.0
from CommentViewerCollection
with GNU General Public License v3.0
from CommentViewerCollection
private static string Encode(decimal num)
{
const string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
const int length = 64;
var encoded = "";
do
{
var n = num % length;
var a = alphabet[(int)n];
encoded = a + encoded;
num = Math.Floor((decimal)num / length);
} while (num > 0);
return encoded;
}
19
Source : FrameNewMedia.cs
with The Unlicense
from dantheman213
with The Unlicense
from dantheman213
private void ingestMediaUrl()
{
var f = new FrameCheckMetadata();
try
{
string url = textUrl.Text.Trim();
if (url != lastValidUrl && Common.isValidURL(url))
{
lastValidUrl = url;
this.Enabled = false;
f.Show();
Application.DoEvents();
var info = YouTubeDL.getMediaData(url);
string thumbnailFilePath = YouTubeDL.downloadThumbnail(info.thumbnail);
pbPreview.ImageLocation = thumbnailFilePath;
labelreplacedle.Text = info.replacedle;
labelDescription.Text = info.description;
// TODO: may need to be revised now that using --restrict-filenames flag in youtube-dl
textLocation.Text = FrameMain.settings.defaultDownloadPath + "\\" + String.Format("{0}{1}", Common.stripIllegalFileNameChars(info.filename.Substring(0, info.filename.LastIndexOf('.'))), info.filename.Substring(info.filename.LastIndexOf('.')));
if (info.formats != null && info.formats.Count > 0)
{
cbVideoFormat.Items.Clear();
cbAudioFormat.Items.Clear();
if (info.requestedFormats != null && info.requestedFormats.Count > 0)
{
info.formats.Insert(0, info.requestedFormats[0]);
if (info.requestedFormats.Count > 1)
{
info.formats.Insert(0, info.requestedFormats[1]);
}
}
string recommendedVideoFormat = "";
string recommendedAudioFormat = "";
var videoFormatList = new List<string>();
var audioFormatList = new List<string>();
videoIdLookupTable = new Dictionary<string, string>();
audioIdLookupTable = new Dictionary<string, string>();
foreach (var format in info.formats)
{
if (!String.IsNullOrEmpty(format.width) && !String.IsNullOrEmpty(format.height))
{
string codec = ((!String.IsNullOrEmpty(format.vcodec) && format.vcodec != "none") ? format.vcodec : "unknwon codec");
string tbr = ((!String.IsNullOrEmpty(format.tbr)) ? Math.Floor(Convert.ToDecimal(format.tbr)).ToString() + "k" : "---"); // rounds down
string fps = ((!String.IsNullOrEmpty(format.fps)) ? format.fps + "fps" : "---");
string note = ((!String.IsNullOrEmpty(format.formateNote)) ? format.formateNote : "---");
string str = String.Format("{0} x {1} / {2} / {3} / {4} / {5} {6}", format.width.PadRight(4), format.height.PadLeft(4), tbr.PadRight(7), format.ext.PadRight(5), note.PadRight(6), fps.PadLeft(6), codec);
if (info.requestedFormats != null && String.IsNullOrEmpty(recommendedVideoFormat))
{
str += " [Recommended]";
recommendedVideoFormat = str;
}
else
{
videoFormatList.Add(str);
}
if (!videoIdLookupTable.ContainsKey(str))
{
videoIdLookupTable.Add(str, format.formatId);
}
}
if (!String.IsNullOrEmpty(format.acodec) && format.acodec != "none")
{
var bitrate = (String.IsNullOrEmpty(format.abr) ? "---" : format.abr + " kbps");
var sampleRate = (String.IsNullOrEmpty(format.asr) ? "---" : format.asr + "Hz");
var str = String.Format("{0} / {1} / {2} / {3}", bitrate.PadRight(9), sampleRate.PadLeft(8), format.ext.PadRight(5), format.acodec);
if (info.requestedFormats != null && String.IsNullOrEmpty(recommendedAudioFormat))
{
str += " [Recommended]";
recommendedAudioFormat = str;
}
else
{
audioFormatList.Add(str);
}
if (!audioIdLookupTable.ContainsKey(str))
{
audioIdLookupTable.Add(str, format.formatId);
}
}
}
if (!String.IsNullOrEmpty(recommendedVideoFormat))
{
cbVideoFormat.Items.Add(recommendedVideoFormat);
}
try
{
videoFormatList.Sort((x, y) => Int32.Parse(x.Trim().Split(' ')[0]).CompareTo(Int32.Parse(y.Trim().Split(' ')[0])));
}
catch (FormatException ex)
{
Console.WriteLine(ex);
}
videoFormatList.Reverse(); // TODO: optimze this out
foreach (var item in videoFormatList)
{
cbVideoFormat.Items.Add(item);
}
if (!String.IsNullOrEmpty(recommendedAudioFormat))
{
cbAudioFormat.Items.Add(recommendedAudioFormat);
}
try
{
audioFormatList.Sort((x, y) => Int32.Parse(x.Trim().Split(' ')[0]).CompareTo(Int32.Parse(y.Trim().Split(' ')[0])));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
audioFormatList.Reverse(); // TODO: optimze this out
foreach (var item in audioFormatList)
{
cbAudioFormat.Items.Add(item);
}
if (cbVideoFormat.Items.Count < 1)
{
cbVideoFormat.Items.Add("(no video metadata could be extracted)");
}
cbVideoFormat.SelectedIndex = 0;
if (cbAudioFormat.Items.Count < 1)
{
cbAudioFormat.Items.Add("(no audio metadata could be extracted)");
}
cbAudioFormat.SelectedIndex = 0;
if (cbVideoEncoder.Items.Count > 0)
{
cbVideoEncoder.SelectedIndex = 0;
}
if (cbAudioEncoder.Items.Count > 0)
{
cbAudioEncoder.SelectedIndex = 0;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
MessageBox.Show("Unable to detect metadata!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
f.Close();
this.Enabled = true;
}
19
Source : SpriteSheet.cs
with GNU General Public License v3.0
from DarwinBaker
with GNU General Public License v3.0
from DarwinBaker
public static int GetFrameIndex(int frameCount)
{
if (frameCount < 1)
return 0;
//get the current animation frame index for a texture based on how many it has
decimal loops = Math.Floor(AnimationTime / frameCount);
return (int)(AnimationTime - (loops * frameCount));
}
19
Source : Core_vJoyInterfaceWrap.cs
with MIT License
from evilC
with MIT License
from evilC
public bool SetOutputState(OutputSubscriptionRequest subReq, BindingDescriptor bindingDescriptor, int state)
{
var devId = _subscriptionToDevice[subReq.SubscriptionDescriptor.SubscriberGuid];
if (!_vJoyDevices[devId].IsAcquired)
{
return false;
}
switch (bindingDescriptor.Type)
{
case BindingType.Axis:
return vJ.SetAxis((state + 32768) / 2, devId + 1, AxisIdToUsage[bindingDescriptor.Index]);
case BindingType.Button:
return vJ.SetBtn(state == 1, devId + 1, (uint)(bindingDescriptor.Index + 1));
case BindingType.POV:
int pov = (int)(Math.Floor((decimal)(bindingDescriptor.Index / 4)));
int dir = bindingDescriptor.Index % 4;
//Log("vJoy POV output requested - POV {0}, Dir {1}, State {2}", pov, dir, state);
_vJoyDevices[devId].SetPovState(pov, dir, state);
break;
default:
break;
}
return false;
}
19
Source : ShadowMapping.cs
with BSD 3-Clause "New" or "Revised" License
from EvolutionJobs
with BSD 3-Clause "New" or "Revised" License
from EvolutionJobs
public void Apply(ShapeOptions pso)
{
this.so = pso;
counter++;
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowType))
{
switch (this.so.OptionsByID[ShapeOptions.PropertyId.shadowType].op)
{
case 0: //offset
writeOffset();
break;
case 1: //double
this._writer.WriteStartElement("a", "effectLst", OpenXmlNamespaces.DrawingML);
this._writer.WriteStartElement("a", "prstShdw", OpenXmlNamespaces.DrawingML);
this._writer.WriteAttributeString("prst", "shdw13");
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowOffsetX))
if (this.so.OptionsByID[ShapeOptions.PropertyId.shadowOffsetX].op != 0)
writeDistDir();
writeColor();
this._writer.WriteEndElement();
this._writer.WriteEndElement();
break;
case 2: //rich
//shadow offset and a transformation
this._writer.WriteStartElement("a", "effectLst", OpenXmlNamespaces.DrawingML);
this._writer.WriteStartElement("a", "outerShdw", OpenXmlNamespaces.DrawingML);
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowOffsetX))
if (this.so.OptionsByID[ShapeOptions.PropertyId.shadowOffsetX].op != 0)
writeDistDir();
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowOriginX))
{
var bytes = BitConverter.GetBytes(this.so.OptionsByID[ShapeOptions.PropertyId.shadowOriginX].op);
int integral = BitConverter.ToInt16(bytes, 0);
uint fractional = BitConverter.ToUInt16(bytes, 2);
if (fractional == 0xffff) integral *= -1;
Decimal origX = integral; // +((decimal)fractional / (decimal)65536);
bytes = BitConverter.GetBytes(this.so.OptionsByID[ShapeOptions.PropertyId.shadowOriginY].op);
integral = BitConverter.ToInt16(bytes, 0);
fractional = BitConverter.ToUInt16(bytes, 2);
if (fractional == 0xffff) integral *= -1;
Decimal origY = integral; // +((decimal)fractional / (decimal)65536);
if (origX > 0)
{
if (origY > 0)
{
this._writer.WriteAttributeString("algn", "tl");
}
else
{
this._writer.WriteAttributeString("algn", "b");
}
}
else
{
if (origY > 0)
{
}
else
{
this._writer.WriteAttributeString("algn", "br");
}
}
}
else
{
this._writer.WriteAttributeString("algn", "b");
}
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowScaleXToX))
{
var bytes = BitConverter.GetBytes(this.so.OptionsByID[ShapeOptions.PropertyId.shadowScaleXToX].op);
int integral = -1 * BitConverter.ToInt16(bytes, 0);
uint fractional = BitConverter.ToUInt16(bytes, 2);
if (fractional == 0xffff) integral *= -1;
decimal result = integral + ((decimal)fractional / (decimal)65536);
result = 1 - (result / 65536);
this._writer.WriteAttributeString("sx", Math.Floor(result * 100000).ToString());
}
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowScaleXToY))
{
int scaleXY = Utils.EMUToMasterCoord((int)this.so.OptionsByID[ShapeOptions.PropertyId.shadowScaleXToY].op);
}
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowScaleYToX))
{
decimal scaleYX = (Decimal)(int)this.so.OptionsByID[ShapeOptions.PropertyId.shadowScaleYToX].op;
//_writer.WriteAttributeString("kx", System.Math.Floor(scaleYX / 138790 * 100 * 60000).ToString()); //The 138790 comes from reverse engineering. I can't find a hint in the spec about how to convert this
if (scaleYX < 0)
{
this._writer.WriteAttributeString("kx", "-2453606");
}
else
{
this._writer.WriteAttributeString("kx", "2453606");
}
}
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowScaleYToY))
{
var bytes = BitConverter.GetBytes(this.so.OptionsByID[ShapeOptions.PropertyId.shadowScaleYToY].op);
int integral = -1 * BitConverter.ToInt16(bytes, 0);
uint fractional = BitConverter.ToUInt16(bytes, 2);
if (fractional == 0xffff) integral *= -1;
Decimal result = integral; // +((decimal)fractional / (decimal)65536);
if (fractional != 0xffff)
{
result = 1 - (result / 65536);
}
else
{
result = (result / 65536);
}
if (result == 0)
{
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowScaleYToX))
{
result = (Decimal)(-0.5);
}
else
{
result = (Decimal)(-1);
}
}
this._writer.WriteAttributeString("sy", Math.Floor(result * 100000).ToString());
}
else
{
this._writer.WriteAttributeString("sy","50000");
}
writeColor();
this._writer.WriteEndElement();
this._writer.WriteEndElement();
break;
case 3: //shape
break;
case 4: //drawing
break;
case 5: //embossOrEngrave
this._writer.WriteStartElement("a", "effectLst", OpenXmlNamespaces.DrawingML);
this._writer.WriteStartElement("a", "prstShdw", OpenXmlNamespaces.DrawingML);
if (this.so.OptionsByID[ShapeOptions.PropertyId.shadowOffsetX].op == 0x319c)
{
this._writer.WriteAttributeString("prst", "shdw17");
}
else
{
this._writer.WriteAttributeString("prst", "shdw18");
}
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowOffsetX))
if (this.so.OptionsByID[ShapeOptions.PropertyId.shadowOffsetX].op != 0)
writeDistDir();
this._writer.WriteStartElement("a", "srgbClr", OpenXmlNamespaces.DrawingML);
string colorval = Utils.getRGBColorFromOfficeArtCOLORREF(this.so.OptionsByID[ShapeOptions.PropertyId.shadowColor].op, this.so.FirstAncestorWithType<Slide>(), this.so);
this._writer.WriteAttributeString("val", colorval);
if (this.so.OptionsByID.ContainsKey(ShapeOptions.PropertyId.shadowOpacity) && this.so.OptionsByID[ShapeOptions.PropertyId.shadowOpacity].op != 65536)
{
this._writer.WriteStartElement("a", "alpha", OpenXmlNamespaces.DrawingML);
this._writer.WriteAttributeString("val", Math.Round(((decimal)this.so.OptionsByID[ShapeOptions.PropertyId.shadowOpacity].op / 65536 * 100000)).ToString()); //we need the percentage of the opacity (65536 means 100%)
this._writer.WriteEndElement();
}
this._writer.WriteElementString("a", "gamma", OpenXmlNamespaces.DrawingML, "");
this._writer.WriteStartElement("a", "shade", OpenXmlNamespaces.DrawingML);
this._writer.WriteAttributeString("val", "60000");
this._writer.WriteEndElement();
this._writer.WriteElementString("a", "invGamma", OpenXmlNamespaces.DrawingML, "");
this._writer.WriteEndElement();
this._writer.WriteEndElement();
this._writer.WriteEndElement();
break;
}
}
else
{
//default is offset
writeOffset();
}
}
19
Source : SpellDataExtensions.cs
with GNU General Public License v3.0
from Exmortem
with GNU General Public License v3.0
from Exmortem
public static string IconUrl(this SpellData spell)
{
var icon = (decimal)spell.Icon;
var folder = (Math.Floor(icon / 1000) * 1000).ToString(CultureInfo.InvariantCulture).Trim().PadLeft(6, '0');
var image = spell.Icon.ToString(CultureInfo.InvariantCulture).Trim().PadLeft(6, '0');
return $@"https://secure.xivdb.com/img/game/{folder}/{image}.png";
}
19
Source : WizardPage.cs
with GNU General Public License v3.0
from GeoSOSDevelopers
with GNU General Public License v3.0
from GeoSOSDevelopers
protected override void OnPaint(PaintEventArgs e)
{
// raise paint event
base.OnPaint(e);
// check if custom style
if (this.style == WizardPageStyle.Custom)
{
// filter out
return;
}
// init graphic resources
Rectangle headerRect = this.ClientRectangle;
Rectangle glyphRect = Rectangle.Empty;
Rectangle replacedleRect = Rectangle.Empty;
Rectangle descriptionRect = Rectangle.Empty;
// determine text format
StringFormat textFormat = StringFormat.GenericDefault;
textFormat.LineAlignment = StringAlignment.Near;
textFormat.Alignment = StringAlignment.Near;
textFormat.Trimming = StringTrimming.EllipsisCharacter;
switch (this.style)
{
case WizardPageStyle.Standard:
// adjust height for header
headerRect.Height = HEADER_AREA_HEIGHT;
// draw header border
ControlPaint.DrawBorder3D(e.Graphics, headerRect, Border3DStyle.Etched, Border3DSide.Bottom);
// adjust header rect not to overwrite the border
headerRect.Height -= SystemInformation.Border3DSize.Height;
// fill header with window color
e.Graphics.FillRectangle(SystemBrushes.Window, headerRect);
// determine header image regtangle
int headerPadding = (int)Math.Floor(Convert.ToDecimal(HEADER_AREA_HEIGHT - HEADER_GLYPH_SIZE) / 2);
glyphRect.Location = new Point(this.Width - HEADER_GLYPH_SIZE - headerPadding, headerPadding);
glyphRect.Size = new Size(HEADER_GLYPH_SIZE, HEADER_GLYPH_SIZE);
// determine the header content
Image headerImage = null;
Font headerFont = this.Font;
Font headerreplacedleFont = this.Font;
if (this.Parent != null && this.Parent is Wizard)
{
// get content from parent wizard, if exists
Wizard parentWizard = (Wizard)this.Parent;
headerImage = parentWizard.HeaderImage;
headerFont = parentWizard.HeaderFont;
headerreplacedleFont = parentWizard.HeaderreplacedleFont;
}
// check if we have an image
if (headerImage == null)
{
// display a focus rect as a place holder
ControlPaint.DrawFocusRectangle(e.Graphics, glyphRect);
}
else
{
// draw header image
e.Graphics.DrawImage(headerImage, glyphRect);
}
// determine replacedle height
int headerreplacedleHeight = (int)Math.Ceiling(e.Graphics.MeasureString(this.replacedle, headerreplacedleFont, 0, textFormat).Height);
// calculate text sizes
replacedleRect.Location = new Point(HEADER_TEXT_PADDING,
HEADER_TEXT_PADDING);
replacedleRect.Size = new Size(glyphRect.Left - HEADER_TEXT_PADDING,
headerreplacedleHeight);
descriptionRect.Location = replacedleRect.Location;
descriptionRect.Y += headerreplacedleHeight + HEADER_TEXT_PADDING / 2;
descriptionRect.Size = new Size(replacedleRect.Width,
HEADER_AREA_HEIGHT - descriptionRect.Y);
// draw tilte text (single line, truncated with ellipsis)
e.Graphics.DrawString(this.replacedle,
headerreplacedleFont,
SystemBrushes.WindowText,
replacedleRect,
textFormat);
// draw description text (multiple lines if needed)
e.Graphics.DrawString(this.description,
headerFont,
SystemBrushes.WindowText,
descriptionRect,
textFormat);
break;
case WizardPageStyle.Welcome:
case WizardPageStyle.Finish:
// fill whole page with window color
e.Graphics.FillRectangle(SystemBrushes.Window, headerRect);
// determine welcome image regtangle
glyphRect.Location = Point.Empty;
glyphRect.Size = new Size(WELCOME_GLYPH_WIDTH, this.Height);
// determine the icon that should appear on the welcome page
Image welcomeImage = null;
Font welcomeFont = this.Font;
Font welcomereplacedleFont = this.Font;
if (this.Parent != null && this.Parent is Wizard)
{
// get content from parent wizard, if exists
Wizard parentWizard = (Wizard)this.Parent;
welcomeImage = parentWizard.WelcomeImage;
welcomeFont = parentWizard.WelcomeFont;
welcomereplacedleFont = parentWizard.WelcomereplacedleFont;
}
// check if we have an image
if (welcomeImage == null)
{
// display a focus rect as a place holder
ControlPaint.DrawFocusRectangle(e.Graphics, glyphRect);
}
else
{
// draw welcome page image
e.Graphics.DrawImage(welcomeImage, glyphRect);
}
// calculate text sizes
replacedleRect.Location = new Point(WELCOME_GLYPH_WIDTH + HEADER_TEXT_PADDING,
HEADER_TEXT_PADDING);
replacedleRect.Width = this.Width - replacedleRect.Left - HEADER_TEXT_PADDING;
// determine replacedle height
int welcomereplacedleHeight = (int)Math.Ceiling(e.Graphics.MeasureString(this.replacedle, welcomereplacedleFont, replacedleRect.Width, textFormat).Height);
descriptionRect.Location = replacedleRect.Location;
descriptionRect.Y += welcomereplacedleHeight + HEADER_TEXT_PADDING;
descriptionRect.Size = new Size(this.Width - descriptionRect.Left - HEADER_TEXT_PADDING,
this.Height - descriptionRect.Y);
// draw tilte text (multiple lines if needed)
e.Graphics.DrawString(this.replacedle,
welcomereplacedleFont,
SystemBrushes.WindowText,
replacedleRect,
textFormat);
// draw description text (multiple lines if needed)
e.Graphics.DrawString(this.description,
welcomeFont,
SystemBrushes.WindowText,
descriptionRect,
textFormat);
break;
}
}
19
Source : MoneyDistributor.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
public Money[] Distribute(decimal distribution)
{
if (distribution > 1 || distribution <= 0)
{
throw new ArgumentOutOfRangeException("distribution",
distribution,
"A uniform distribution must be " +
"greater than 0 and " +
"less than or equal to 1.0");
}
_distribution = new decimal[1];
_distribution[0] = distribution;
var distributionCount = (Int32)Math.Floor(1 / distribution);
var result = new Money[distributionCount];
_distributedTotal = new Money(0, _toDistribute.replacedet);
decimal quantum = (Decimal)Math.Pow(10, -(Int32)_precision);
for (int i = 0; i < distributionCount; i++)
{
var toDistribute = _toDistribute;
var part = toDistribute / distributionCount;
part = Math.Round(part - (0.5M * quantum),
(Int32)_precision,
MidpointRounding.AwayFromZero);
result[i] = part;
_distributedTotal += part;
}
var remainder = _toDistribute - _distributedTotal;
switch (_receiver)
{
case FractionReceivers.FirstToLast:
for (var i = 0; i < remainder / quantum; i++)
{
result[i] += quantum;
_distributedTotal += quantum;
}
break;
case FractionReceivers.LastToFirst:
for (var i = (Int32)(remainder / quantum); i > 0; i--)
{
result[i] += quantum;
_distributedTotal += quantum;
}
break;
case FractionReceivers.Random:
// need the mersenne twister code... System.Random isn't good enough
throw new NotImplementedException();
default:
break;
}
if (_distributedTotal != _toDistribute)
{
throw new MoneyAllocationException(_toDistribute,
_distributedTotal,
_distribution);
}
return result;
}
19
Source : Money.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
private Int32 roundFraction(Int32 exponent, MidpointRoundingRule rounding, out Int64 unit)
{
var denominator = FractionScale / (Decimal)Math.Pow(10, exponent);
var fraction = _decimalFraction / denominator;
switch (rounding)
{
case MidpointRoundingRule.ToEven:
fraction = Math.Round(fraction, MidpointRounding.ToEven);
break;
case MidpointRoundingRule.AwayFromZero:
{
var sign = Math.Sign(fraction);
fraction = Math.Abs(fraction); // make positive
fraction = Math.Floor(fraction + 0.5M); // round UP
fraction *= sign; // reapply sign
break;
}
case MidpointRoundingRule.TowardZero:
{
var sign = Math.Sign(fraction);
fraction = Math.Abs(fraction); // make positive
fraction = Math.Floor(fraction + 0.5M); // round DOWN
fraction *= sign; // reapply sign
break;
}
case MidpointRoundingRule.Up:
fraction = Math.Floor(fraction + 0.5M);
break;
case MidpointRoundingRule.Down:
fraction = Math.Ceiling(fraction - 0.5M);
break;
case MidpointRoundingRule.Stochastic:
if (_rng == null)
{
_rng = new MersenneTwister();
}
var coinFlip = _rng.NextDouble();
if (coinFlip >= 0.5)
{
goto case MidpointRoundingRule.Up;
}
goto case MidpointRoundingRule.Down;
default:
throw new ArgumentOutOfRangeException("rounding");
}
fraction *= denominator;
if (fraction >= FractionScale)
{
unit = 1;
fraction = fraction - (Int32)FractionScale;
}
else
{
unit = 0;
}
return (Int32)fraction;
}
19
Source : TA_Floor.cs
with BSD 3-Clause "New" or "Revised" License
from hmG3
with BSD 3-Clause "New" or "Revised" License
from hmG3
public static RetCode Floor(decimal[] inReal, int startIdx, int endIdx, decimal[] outReal, out int outBegIdx, out int outNbElement)
{
outBegIdx = outNbElement = 0;
if (startIdx < 0 || endIdx < 0 || endIdx < startIdx)
{
return RetCode.OutOfRangeStartIndex;
}
if (inReal == null || outReal == null)
{
return RetCode.BadParam;
}
int outIdx = default;
for (int i = startIdx; i <= endIdx; i++)
{
outReal[outIdx++] = Math.Floor(inReal[i]);
}
outBegIdx = startIdx;
outNbElement = outIdx;
return RetCode.Success;
}
19
Source : CustomerPointsManager.cs
with MIT License
from HotcakesCommerce
with MIT License
from HotcakesCommerce
public int PointsToIssueForSpend(decimal spend)
{
var storeSettings = Context.CurrentStore.Settings;
var pointsIssuedPerDollarSpent = storeSettings.RewardsPointsIssuedPerDollarSpent;
var spendRounded = Math.Floor(spend);
var points = spendRounded*pointsIssuedPerDollarSpent;
return (int) points;
}
19
Source : Paging.cs
with MIT License
from HotcakesCommerce
with MIT License
from HotcakesCommerce
public static string RenderPagerWithLimits(string link, int currentPage, int pages, int maxPagesToShow)
{
// don't render a pager if we don't need one
if (pages < 2) return string.Empty;
// Make sure current page is within limits
var current = currentPage;
if (current < 1) current = 1;
if (current > pages) current = pages;
// Truncate to 10 pages at a time
decimal limitToShow = maxPagesToShow;
var pageOfPages = Math.Floor((currentPage - 1)/limitToShow);
var startPage = (int) (limitToShow*pageOfPages + 1);
var endingPage = startPage + ((int) limitToShow - 1);
if (endingPage > pages) endingPage = pages;
var sb = new StringBuilder();
sb.Append("<div clreplaced=\"hcPager\"><ul>");
// Render previous page groups
if (startPage > limitToShow)
{
sb.Append("<li><a href=\"" + string.Format(link, startPage - 1) + "\">...</a></li>");
}
for (var i = startPage; i <= endingPage; i++)
{
sb.Append("<li");
if (current == i)
{
sb.Append(" clreplaced=\"hcCurrent\"");
}
sb.Append(">");
sb.Append("<a href=\"" + string.Format(link, i) + "\">" + i + "</a></li>");
}
// Render more pages if available
if (pages > endingPage)
{
sb.Append("<li><a href=\"" + string.Format(link, endingPage + 1) + "\">...</a></li>");
}
sb.Append("</ul></div>");
return sb.ToString();
}
19
Source : CoreMaker.cs
with MIT License
from hypar-io
with MIT License
from hypar-io
private Polygon PlaceCore(double setback, double rotation)
{
var offShells = Levels.Last().Perimeter.Offset(setback * -1);
if (offShells.Count() == 0)
{
return null;
}
var shell = offShells.OrderByDescending(s => s.Area()).First();
var occLevels = Levels.Where(l => l.Elevation >= 0.0).ToList();
var occArea = 0.0;
foreach (var level in occLevels)
{
occArea += level.Perimeter.Area();
}
var occupants = (int)Math.Ceiling(occArea / occupantLoad);
LiftQuanreplacedy = (int)Math.Ceiling(occArea / liftService);
if (LiftQuanreplacedy > 8)
{
LiftQuanreplacedy = 8;
}
LiftService = (int)Math.Floor((decimal)occLevels.Count() / LiftQuanreplacedy);
var positions = new List<Vector3> { shell.Centroid() };
var liftBank = Math.Floor(LiftQuanreplacedy * 0.5);
positions.AddRange(shell.FindInternalPoints((stairLength + (liftBank * liftSize)) * 0.5));
positions = positions.OrderBy(p => p.DistanceTo(shell.Centroid())).ToList();
foreach (var position in positions)
{
var corePerim = Polygon.Rectangle(stairLength + (liftBank * liftSize),
(stairWidth * 2) + bathWidth);
corePerim = corePerim.MoveFromTo(corePerim.Centroid(), position).Rotate(position, Rotation);
if (shell.Covers(corePerim))
{
Position = position;
return corePerim;
}
}
return null;
}
19
Source : Signing.cs
with Apache License 2.0
from iotaledger
with Apache License 2.0
from iotaledger
public int[] Digests(int[] key)
{
var digests = new int[(int) Math.Floor((decimal) key.Length / 6561) * 243];
var buffer = new int[243];
for (var i = 0; i < Math.Floor((decimal) key.Length / 6561); i++)
{
var keyFragment = new int[6561];
Array.Copy(key, i * 6561, keyFragment, 0, 6561);
for (var j = 0; j < 27; j++)
{
Array.Copy(keyFragment, j * 243, buffer, 0, 243);
for (var k = 0; k < 26; k++)
{
_curl.Reset();
_curl.Absorb(buffer, 0, buffer.Length);
_curl.Squeeze(buffer, 0, buffer.Length);
}
for (var k = 0; k < 243; k++) keyFragment[j * 243 + k] = buffer[k];
}
_curl.Reset();
_curl.Absorb(keyFragment, 0, keyFragment.Length);
_curl.Squeeze(buffer, 0, buffer.Length);
for (var j = 0; j < 243; j++) digests[i * 243 + j] = buffer[j];
}
return digests;
}
19
Source : MainForm.cs
with MIT License
from JamesMatchett
with MIT License
from JamesMatchett
private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//if not initiliased, or percentage has not increased since last execution
if(LastPercentageValue == 0 || e.ProgressPercentage == 0 || LastPercentageValue == e.ProgressPercentage)
{
LastPercentageTime = DateTime.Now;
LastPercentageValue = e.ProgressPercentage;
}
else
{
decimal PercentageDifference = e.ProgressPercentage - LastPercentageValue;
TimeSpan TimeDifference = DateTime.Now - LastPercentageTime;
//time for 1% = (1/percentageDifference * Time Difference)
decimal TimeFor1Percent = (1 / PercentageDifference) * Convert.ToDecimal(TimeDifference.TotalSeconds);
AverageTimeFor1Percent.Add(TimeFor1Percent);
if(AverageTimeFor1Percent.Count > 5)
{
AverageTimeFor1Percent.Remove(AverageTimeFor1Percent.First());
}
//now multiply time for 1% by the percentage remianing e.g. 45% done would be 55% percent to go
decimal SecondsRemaining = (AverageTimeFor1Percent.Average() * (100 - e.ProgressPercentage));
SecondsRemaining = Math.Floor(SecondsRemaining);
if (SecondsRemaining > 0)
{
//update labels and refresh values
TimeRemainingLabel.Text = ("Time Remaining: " + SecondsRemaining + " seconds");
LastPercentageTime = DateTime.Now;
LastPercentageValue = e.ProgressPercentage;
}
}
int percentage = Convert.ToInt32(e.ProgressPercentage);
//101 signifies finished, stop mulreplacedhread sending multiple "finished" signal
if (percentage == 101)
{
TimeRemainingLabel.Text = ("Time Remaining: " + 0 + " seconds");
progressBar.Value = 100;
MessageBox.Show("Finished!");
foreach (ArtMaker A in BWList)
{
A.stop();
}
progressBar.Value = 0;
Start.Enabled = true;
}
else
{
progressBar.Value = percentage;
}
}
19
Source : ExcelTime.cs
with GNU Lesser General Public License v2.1
from jet-global
with GNU Lesser General Public License v2.1
from jet-global
private void Init(decimal value)
{
// handle hour
decimal totalSeconds = value * SecondsPerDay;
decimal hour = Math.Floor(totalSeconds / SecondsPerHour);
Hour = (int)hour;
// handle minute
decimal remainingSeconds = totalSeconds - (hour * SecondsPerHour);
decimal minute = Math.Floor(remainingSeconds / SecondsPerMinute);
Minute = (int)minute;
// handle second
remainingSeconds = totalSeconds - (hour * SecondsPerHour) - (minute * SecondsPerMinute);
decimal second = Math.Round(remainingSeconds, MidpointRounding.AwayFromZero);
// Second might be rounded to 60... the SetSecond method handles that.
SetSecond((int)second);
}
19
Source : BinanceHelpers.cs
with MIT License
from JKorf
with MIT License
from JKorf
public static decimal Floor(decimal number)
{
return Math.Floor(number * 100000000) / 100000000;
}
19
Source : ExchangeHelpers.cs
with MIT License
from JKorf
with MIT License
from JKorf
public static decimal RoundDown(decimal i, double decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(i * power) / power;
}
19
Source : Benchmarker.cs
with MIT License
from jmrnilsson
with MIT License
from jmrnilsson
private (List<string>, List<string>) GenerateObjects(int numberOfObjects, out List<string> jsons, out List<string> xmls)
{
Instant lastShowProgress = SystemClock.Instance.GetCurrentInstant();
jsons = new List<string>();
xmls = new List<string>();
var jsonGenerator = new JsonGenerator(ntree);
var xmlGenerator = new XmlGenerator(ntree);
Log.Information("Preparing payload");
for (int i = 0; i < numberOfObjects; i++)
{
if (cancellationToken.IsCancellationRequested) return (new List<string>(), new List<string>());
Instant now = SystemClock.Instance.GetCurrentInstant();
if (now - lastShowProgress > showProgressEvery)
{
lastShowProgress = now;
Log.Information("{0} %", Math.Floor((decimal)i * 100 / numberOfObjects));
}
jsons.Add(jsonGenerator.GenerateObject());
xmls.Add(xmlGenerator.GenerateObject());
}
return (jsons, xmls);
}
19
Source : TheGridDataFactory.cs
with MIT License
from joadan
with MIT License
from joadan
public IEnumerable<TableResult<object, Item>> GetData(IEnumerable<Item> items, bool resetPage = false, bool addSorting = true, Item moveToItem = default)
{
var viewResult = new List<TableResult<object, Item>>();
if (items != null)
{
var query = items.AsQueryable();
query = AddSearch(query);
//if (state.CurrentEdireplacedem == null)
//{
// query = AddSearch(query);
//}
if (addSorting)
{
query = AddSorting(query);
}
state.TotalCount = query.Count();
if (resetPage)
{
state.PageNumber = 0;
}
else if (state.TotalCount == 0)
{
state.PageNumber = 0;
}
else if ((state.TotalCount - 1) < state.PageSize * state.PageNumber)
{
state.PageNumber = (int)Math.Floor((decimal)(state.TotalCount / state.PageSize)) - 1;
}
else if (moveToItem != null)
{
var pos = query.ToList().IndexOf(moveToItem);
if (pos > 0)
{
state.PageNumber = (int)Math.Floor((decimal)(pos / state.PageSize));
}
}
query = query.Skip(state.PageNumber * state.PageSize).Take(state.PageSize);
var columnGroup = columns.FirstOrDefault(e => e.GroupBy);
if (columnGroup == null)
{
viewResult.Add(new TableResult<object, Item>(null, query.ToList()));
}
else
{
columnGroup.GroupBy = true;
foreach (var r in query.GroupBy(columnGroup.Property))
{
viewResult.Add(new TableResult<object, Item>(r.Key, r.ToList())
{
GroupingTemplate = columnGroup.GroupingTemplate
});
}
}
}
return viewResult;
}
19
Source : HtmlEditor.cs
with MIT License
from joergkrause
with MIT License
from joergkrause
public string GetRawHtml(bool ClearDirty, bool fromActiveFrame) {
if (!IsCreated) {
throw new HtmlControlException("HtmlEditor.GetRawHtml: Doreplacedent not created");
}
string content = String.Empty;
Encoding tmpEnc = Encoding;
try {
OnSaving();
if (_fullDoreplacedentMode) {
Interop.IPersistStreamInit persistStream;
IStream uStream;
persistStream = (Interop.IPersistStreamInit)this.GetActiveDoreplacedent(!fromActiveFrame);
// Use COM streams to get content
Win32.CreateStreamOnHGlobal(Interop.NullIntPtr, true, out uStream);
persistStream.Save(uStream, ClearDirty ? 1 : 0);
STATSTG iStatStg;
uStream.Stat(out iStatStg, 1);
int i = (int)iStatStg.cbSize;
byte[] bs = new byte[(uint)i];
IntPtr j;
Win32.GetHGlobalFromStream(uStream, out j);
IntPtr k = Win32.GlobalLock(j);
if (k != Interop.NullIntPtr) {
Marshal.Copy(k, bs, 0, i);
Win32.GlobalUnlock(j);
int index = 0;
int blocks = (int)Math.Floor((decimal)bs.Length / 8192);
Encoding _enc;
while (true) {
if (bs[0] == Encoding.Unicode.GetPreamble()[0]
&&
bs[1] == Encoding.Unicode.GetPreamble()[1]) {
_enc = Encoding.Unicode;
break;
}
if (bs[0] == Encoding.UTF8.GetPreamble()[0]
&&
bs[1] == Encoding.UTF8.GetPreamble()[1]
&&
bs[2] == Encoding.UTF8.GetPreamble()[2]) {
_enc = Encoding.UTF8;
break;
}
if (bs[0] == Encoding.BigEndianUnicode.GetPreamble()[0]
&&
bs[1] == Encoding.BigEndianUnicode.GetPreamble()[1]) {
_enc = Encoding.BigEndianUnicode;
break;
}
_enc = this.Encoding;
break;
}
while (index <= blocks) {
content += _enc.GetString(bs, index * 8192, (index < blocks) ? 8192 : bs.Length - blocks * 8192);
if ((byte)content[0] == 255) {
content = content.Substring(1);
}
index++;
}
// HACK: A very dirty hack to remove the double http-equiv we get here; I've no idea what the reason is..
int i1 = 0;
while ((i1 = content.IndexOf(String.Concat(Environment.NewLine, "http-equiv"), i1)) > 0) {
int i2 = content.IndexOf("\"", i1 + 14);
if (i1 > 0 && i2 > 0) {
content = String.Concat(content.Substring(0, i1), content.Substring(++i2));
}
i1 = i2;
}
}
// Remove internally set temp file support base tag
Regex rx = new Regex(@"<BASE\s+href=""?(?<href>[^"">]*)""?/?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match baseTag;
if ((baseTag = rx.Match(content)).Success && baseTag.Groups["href"].Value.Equals(TempPath)) {
content = rx.Replace(content, "");
}
} else {
Interop.IHTMLElement body = this.GetBodyThreadSafe(false) as Interop.IHTMLElement;
if (body != null) {
content = body.GetInnerHTML();
}
}
if (ClearDirty) {
// TODO: Implement!
}
} catch {
content = String.Empty;
} finally {
OnSaved();
Encoding = tmpEnc;
}
if (content == null) {
content = String.Empty;
}
return content;
}
See More Examples