Here are the examples of the csharp api System.Math.Ceiling(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2819 Examples
19
Source : MobilePhoneApp.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void OpenPhoneBook()
{
Monitor.Log($"opening phone book");
ModEntry.appRunning = true;
ModEntry.phoneAppRunning = true;
ModEntry.runningApp = Helper.ModRegistry.ModID;
CreateCallableList();
listHeight = Config.ContactMarginY + (int)Math.Ceiling(callableList.Count / (float)ModEntry.gridWidth) * (Config.ContactHeight + Config.ContactMarginY);
Helper.Events.Display.RenderedWorld += Display_RenderedWorld;
Helper.Events.Input.ButtonPressed += Input_ButtonPressed;
Helper.Events.Input.MouseWheelScrolled += Input_MouseWheelScrolled;
}
19
Source : PhoneGameLoop.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
{
foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
{
Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
try
{
MobilePhonePackJSON json = contentPack.ReadJsonFile<MobilePhonePackJSON>("content.json") ?? null;
if(json != null)
{
if (json.apps != null && json.apps.Any())
{
foreach (AppJSON app in json.apps)
{
Texture2D tex = contentPack.Loadreplacedet<Texture2D>(app.iconPath);
if (tex == null)
{
continue;
}
ModEntry.apps.Add(app.id, new MobileApp(app.name, app.keyPress, app.closePhone, tex));
Monitor.Log($"Added app {app.name} from {contentPack.DirectoryPath}");
}
}
else if (json.iconPath != null)
{
Texture2D icon = contentPack.Loadreplacedet<Texture2D>(json.iconPath);
if (icon == null)
{
continue;
}
ModEntry.apps.Add(json.id, new MobileApp(json.name, json.keyPress, json.closePhone, icon));
Monitor.Log($"Added app {json.name} from {contentPack.DirectoryPath}");
}
if (json.invites != null && json.invites.Any())
{
foreach (EventInvite invite in json.invites)
{
MobilePhoneCall.eventInvites.Add(invite);
Monitor.Log($"Added event invite {invite.name} from {contentPack.DirectoryPath}");
}
}
}
}
catch (Exception ex)
{
Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "events")))
{
Monitor.Log($"Adding events");
string[] events = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "events"), "*.json");
Monitor.Log($"CP has {events.Length} events");
foreach (string eventFile in events)
{
try
{
string eventPath = Path.Combine("replacedets", "events", Path.GetFileName(eventFile));
Monitor.Log($"Adding events {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
Reminiscence r = contentPack.ReadJsonFile<Reminiscence>(eventPath);
MobilePhoneCall.contentPackReminiscences.Add(Path.GetFileName(eventFile).Replace(".json", ""), r);
Monitor.Log($"Added event {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins")))
{
Monitor.Log($"Adding skins");
string[] skins = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins"), "*_landscape.png");
Monitor.Log($"CP has {skins.Length} skins");
foreach (string skinFile in skins)
{
try
{
string skinPath = Path.Combine("replacedets", "skins", Path.GetFileName(skinFile));
Monitor.Log($"Adding skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
Texture2D skin = contentPack.Loadreplacedet<Texture2D>(skinPath.Replace("_landscape.png", ".png"));
Texture2D skinl = contentPack.Loadreplacedet<Texture2D>(skinPath);
ThemeApp.skinList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""));
ThemeApp.skinDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""), new Texture2D[] { skin, skinl});
Monitor.Log($"Added skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds")))
{
Monitor.Log($"Adding backgrounds");
string[] backgrounds = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
Monitor.Log($"CP has {backgrounds.Length} backgrounds");
foreach (string backFile in backgrounds)
{
try
{
string backPath = Path.Combine("replacedets", "backgrounds", Path.GetFileName(backFile));
Monitor.Log($"Adding background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
Texture2D back = contentPack.Loadreplacedet<Texture2D>(backPath.Replace("_landscape.png", ".png"));
Texture2D backl = contentPack.Loadreplacedet<Texture2D>(backPath);
ThemeApp.backgroundDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""), new Texture2D[] { back, backl });
ThemeApp.backgroundList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""));
Monitor.Log($"Added background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones")))
{
Monitor.Log($"Adding ringtones");
string[] rings = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones"), "*.wav");
Monitor.Log($"CP has {rings.Length} ringtones");
foreach (string path in rings)
{
try
{
object ring;
try
{
var type = Type.GetType("System.Media.SoundPlayer, System");
ring = Activator.CreateInstance(type, new object[] { path });
}
catch
{
ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
}
if (ring != null)
{
ThemeApp.ringDict.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")), ring);
ThemeApp.ringList.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")));
Monitor.Log($"loaded ring {path}");
}
else
Monitor.Log($"Couldn't load ring {path}");
}
catch (Exception ex)
{
Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
}
}
}
}
ModEntry.listHeight = Config.IconMarginY + (int)Math.Ceiling(ModEntry.apps.Count / (float)ModEntry.gridWidth) * (Config.IconHeight + Config.IconMarginY);
PhoneVisuals.CreatePhoneTextures();
PhoneUtils.RefreshPhoneLayout();
if (Helper.ModRegistry.IsLoaded("purrplingcat.npcadventure"))
{
INpcAdventureModApi api = Helper.ModRegistry.GetApi<INpcAdventureModApi>("purrplingcat.npcadventure");
if (api != null)
{
Monitor.Log("Loaded NpcAdventureModApi successfully");
ModEntry.npcAdventureModApi = api;
}
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private void RespawnChests()
{
Utility.ForAllLocations(delegate(GameLocation l)
{
if (l is FarmHouse || (!Config.AllowIndoorSpawns && !l.IsOutdoors) || !IsLocationAllowed(l))
return;
Monitor.Log($"Respawning chests in {l.name}");
IList<Vector2> objectsToRemovePos = l.overlayObjects
.Where(o => o.Value is Chest && o.Value.Name.StartsWith(namePrefix))
.Select(o => o.Key)
.ToList();
int rem = objectsToRemovePos.Count;
foreach (var pos in objectsToRemovePos)
{
l.overlayObjects.Remove(pos);
}
Monitor.Log($"Removed {rem} chests");
int width = l.map.Layers[0].LayerWidth;
int height = l.map.Layers[0].LayerHeight;
bool IsValid(Vector2 v) => !l.isWaterTile((int)v.X, (int)v.Y) && !l.isTileOccupiedForPlacement(v) && !l.isCropAtTile((int)v.X, (int)v.Y);
bool IsValidIndex(int i) => IsValid(new Vector2(i % width, i / width));
int freeTiles = Enumerable.Range(0, width * height).Count(IsValidIndex);
Monitor.Log($"Got {freeTiles} free tiles");
int maxChests = Math.Min(freeTiles, (int)Math.Floor(freeTiles * Config.ChestDensity) + (Config.RoundNumberOfChestsUp ? 1 : 0));
Monitor.Log($"Max chests: {maxChests}");
while (maxChests > 0)
{
Vector2 freeTile = l.getRandomTile();
if (!IsValid(freeTile))
continue;
Chest chest;
if (advancedLootFrameworkApi == null)
{
//Monitor.Log($"Adding ordinary chest");
chest = new Chest(0, new List<Item>() { MineShaft.getTreasureRoomItem() }, freeTile, false, 0);
}
else
{
double fraction = Math.Pow(myRand.NextDouble(), 1 / Config.RarityChance);
int level = (int)Math.Ceiling(fraction * Config.Mult);
//Monitor.Log($"Adding expanded chest of value {level} to {l.name}");
chest = advancedLootFrameworkApi.MakeChest(treasuresList, Config.ItemListChances, Config.MaxItems, Config.MinItemValue, Config.MaxItemValue, level, Config.IncreaseRate, Config.ItemsBaseMaxValue, Config.CoinBaseMin, Config.CoinBaseMax, freeTile);
chest.playerChoiceColor.Value = MakeTint(fraction);
}
chest.name = namePrefix;
l.overlayObjects[freeTile] = chest;
maxChests--;
}
});
}
19
Source : Traps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void FireballTrap(MineShaft shaft, Vector2 position)
{
shaft.playSound("furnace", SoundContext.Default);
foreach (Vector2 v in Utils.getCenteredSpots(position))
{
try
{
float x = position.X - v.X;
float y = position.Y - v.Y;
BasicProjectile projectile = new BasicProjectile((int)Math.Ceiling(Math.Sqrt(shaft.mineLevel * config.TrapDamageMult)), 10, 0, 1, 0.5f, x, y, v * Game1.tileSize, "", "", false, false, shaft, Game1.player, false, null);
projectile.ignoreTravelGracePeriod.Value = true;
projectile.maxTravelDistance.Value = 100;
shaft.projectiles.Add(projectile);
}
catch(Exception ex)
{
monitor.Log($"error creating fire: {ex}");
}
}
}
19
Source : ThemeApp.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void Display_RenderedWorld(object sender, StardewModdingAPI.Events.RenderedWorldEventArgs e)
{
if (ModEntry.callingNPC != null)
return;
if (!ModEntry.appRunning || !ModEntry.phoneOpen || ModEntry.runningApp != Helper.ModRegistry.ModID)
{
ModEntry.appRunning = false;
Helper.Events.Display.RenderedWorld -= Display_RenderedWorld;
Helper.Events.Input.ButtonPressed -= Input_ButtonPressed;
return;
}
Vector2 screenPos = PhoneUtils.GetScreenPosition();
Vector2 screenSize = PhoneUtils.GetScreenSize();
Rectangle headerRect = new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight);
Rectangle footerRect = new Rectangle((int)screenPos.X, (int)screenPos.Y + (int)screenSize.Y - Config.AppHeaderHeight, (int)screenSize.X, Config.AppHeaderHeight);
Point mousePos = Game1.getMousePosition();
if (Helper.Input.IsSuppressed(SButton.MouseLeft))
{
int dy = mousePos.Y - lastMousePositionY;
if (Math.Abs(dy) > 0 && ModEntry.screenRect.Contains(mousePos) && !headerRect.Contains(mousePos) && !footerRect.Contains(mousePos))
{
dragging = true;
}
if (dragging)
{
float listHeight;
if (whichTab == 0)
listHeight = skinListHeight;
else if (whichTab == 1)
listHeight = backListHeight;
else
listHeight = ringListHeight;
yOffset = (int)Math.Max(Math.Min(0, yOffset + dy), -1 * Math.Max(0, listHeight - screenSize.Y));
}
}
if (clicked && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
clicked = false;
Monitor.Log($"unclicked");
if (dragging)
{
Monitor.Log($"was dragging");
dragging = false;
}
else
{
if (headerRect.Contains(mousePos))
{
if (new Rectangle((int)screenPos.X + (int)screenSize.X - Config.AppHeaderHeight, (int)screenPos.Y, Config.AppHeaderHeight, Config.AppHeaderHeight).Contains(mousePos))
{
PhoneUtils.ToggleApp(false);
}
}
else if(footerRect.Contains(mousePos))
{
int newTab = (int)((mousePos.X - screenPos.X) / (screenSize.X / 3));
if(whichTab != newTab)
{
whichTab = newTab;
yOffset = 0;
int listcount = whichTab == 0 ? skinList.Count : (whichTab == 1 ? backgroundList.Count : ringList.Count);
Monitor.Log($"switching to tab {whichTab}: {listcount} items");
}
}
else
{
if (whichTab == 0)
{
for(int i = 0; i < skinList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {skinList[i]}");
SetSkin(skinList[i]);
}
}
}
else if (whichTab == 1)
{
for(int i = 0; i < backgroundList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {backgroundList[i]}");
SetBackground(backgroundList[i]);
}
}
}
else if (whichTab == 2)
{
for(int i = 0; i < ringList.Count; i++)
{
Vector2 pos = GereplacedemPos(i);
Rectangle r = new Rectangle((int)pos.X, (int)pos.Y, ModEntry.phoneWidth, Config.RingLisreplacedemHeight);
if (r.Contains(mousePos))
{
Monitor.Log($"switching to {ringList[i]}");
SetRing(ringList[i]);
}
}
}
}
}
}
lastMousePositionY = Game1.getMouseY();
int startListY = (int)screenPos.Y + Config.AppHeaderHeight;
if (whichTab == 2)
e.SpriteBatch.Draw(ModEntry.ringListBackgroundTexture, ModEntry.screenRect, Color.White);
else
e.SpriteBatch.Draw(ModEntry.backgroundTexture, ModEntry.phoneRect, Color.White);
if(yOffset < 0)
{
e.SpriteBatch.Draw(ModEntry.upArrowTexture, ModEntry.upArrowPosition, Color.White);
}
if (yOffset > PhoneUtils.GetScreenSize().Y - Config.AppHeaderHeight - skinListHeight)
{
e.SpriteBatch.Draw(ModEntry.downArrowTexture, ModEntry.downArrowPosition, Color.White);
}
int screenBottom = (int)(screenPos.Y + screenSize.Y);
int count = whichTab == 0 ? skinList.Count : (whichTab == 1 ? backgroundList.Count : ringList.Count );
for (int i = 0; i < count; i++)
{
Vector2 itemPos = GereplacedemPos(i);
if (whichTab < 2)
{
Rectangle r = new Rectangle(0,0,Config.PhoneWidth, Config.PhoneHeight);
Rectangle sourceRect = r;
Rectangle destRect;
destRect = new Rectangle((int)itemPos.X, (int)itemPos.Y, Config.ThemeItemWidth, Config.ThemeItemHeight);
float yScale = Config.ThemeItemHeight / (float)Config.PhoneHeight;
if (itemPos.Y < startListY - r.Height * yScale || itemPos.Y >= screenBottom)
{
continue;
}
int cutTop = 0;
int cutBottom = 0;
if (itemPos.Y < startListY)
{
cutTop = (int)Math.Ceiling((startListY - itemPos.Y) / yScale);
sourceRect = new Rectangle(r.X, (int)(r.Y + cutTop), r.Width, (int)(r.Height - cutTop));
destRect.Y = startListY;
destRect.Height -= (int)(cutTop * yScale);
itemPos = new Vector2(itemPos.X, startListY);
}
else if (itemPos.Y > screenBottom - r.Height * yScale - Config.AppHeaderHeight)
{
cutBottom = (int)Math.Ceiling((screenBottom - Config.AppHeaderHeight - r.Height * yScale - itemPos.Y) / yScale);
destRect.Height += (int)(cutBottom * yScale);
sourceRect = new Rectangle(r.X, r.Y, r.Width, r.Height + cutBottom);
}
Texture2D texture = whichTab == 0 ? skinDict[skinList[i]][0] : backgroundDict[backgroundList[i]][0];
//Monitor.Log($"drawing texture {i} {texture.Width}x{texture.Height} {destRect} {ModEntry.screenRect}");
e.SpriteBatch.Draw(texture, destRect, sourceRect, Color.White);
}
else
{
if (itemPos.Y < screenPos.Y || itemPos.Y >= screenBottom - Config.AppHeaderHeight)
{
continue;
}
if (ringList[i] == Config.PhoneRingTone)
e.SpriteBatch.Draw(ModEntry.ringListHighlightTexture, new Rectangle((int)(itemPos.X), (int)itemPos.Y, (int)(screenSize.X), Config.RingLisreplacedemHeight), Color.White);
string itemName = ringList[i];
if (itemName.Contains(":"))
itemName = itemName.Split(':')[1];
e.SpriteBatch.DrawString(Game1.dialogueFont, itemName, itemPos, Config.RingLisreplacedemColor, 0, Vector2.Zero, Config.RingLisreplacedemScale, SpriteEffects.None, 0.86f);
}
}
e.SpriteBatch.Draw(ModEntry.themesHeaderTexture, headerRect, Color.White);
e.SpriteBatch.Draw(ModEntry.themesHeaderTexture, footerRect, Color.White);
e.SpriteBatch.Draw(ModEntry.themesHighlightTexture, new Rectangle((int)(screenPos.X + (screenSize.X/3f) * whichTab),screenBottom - Config.AppHeaderHeight, (int)(screenSize.X / 3f), Config.AppHeaderHeight), Color.White);
string headerText = Helper.Translation.Get("themes");
string skinsText = Helper.Translation.Get("skins");
string backsText = Helper.Translation.Get("backs");
string ringsText = Helper.Translation.Get("rings");
Vector2 headerTextSize = Game1.dialogueFont.MeasureString(headerText) * Config.HeaderTextScale;
Vector2 skinsTextSize = Game1.dialogueFont.MeasureString(skinsText) * Config.TabTextScale;
Vector2 backsTextSize = Game1.dialogueFont.MeasureString(backsText) * Config.TabTextScale;
Vector2 ringsTextSize = Game1.dialogueFont.MeasureString(ringsText) * Config.TabTextScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, headerText, screenPos + new Vector2(screenSize.X / 2f - headerTextSize.X / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f ), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, "x", screenPos + new Vector2(screenSize.X - Config.AppHeaderHeight / 2f - Game1.dialogueFont.MeasureString("x").X * Config.HeaderTextScale / 2f, Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), Config.PhoneBookHeaderTextColor, 0, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, skinsText, screenPos + new Vector2(screenSize.X / 6f - skinsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 0 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, backsText, screenPos + new Vector2(screenSize.X / 2f - backsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 1 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.DrawString(Game1.dialogueFont, ringsText, screenPos + new Vector2(screenSize.X * 5f / 6f - ringsTextSize.X / 2f, screenSize.Y - Config.AppHeaderHeight / 2f - headerTextSize.Y / 2f), whichTab == 2 ? Config.ThemesHeaderHighlightedTextColor : Config.ThemesHeaderTextColor, 0, Vector2.Zero, Config.TabTextScale, SpriteEffects.None, 0.86f);
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private List<string> LengthenToMatch(List<string> smallerL, List<string> largerL)
{
// for 10 and 6
int multMax = (int)Math.Ceiling((double)(largerL.Count - 1) / (double)(smallerL.Count - 1)); // 9/5 = 2, leave last
int multMin = (int)Math.Floor((double)(largerL.Count - 1) / (double)(smallerL.Count - 1)); // 9/5 = 2
int multDiff = (largerL.Count - 1) - (smallerL.Count - 1) * multMin; // 9 - 5*1 = 4 remainder, number of entries that get extra
// total of 4*2 and 1*1 = 9, extra one will be add as last
List<string> outList = new List<string>();
for (int i = 0; i < smallerL.Count - 1; i++)
{
int no;
if (i >= multDiff) // those starting at multDiff(4) get repeated fewer (1), means (0-3)*2=8entries and (4)*1=1entries
{
no = multMin; // 4 gets 1
}
else
{
no = multMax; // 0-3 get 2
}
outList.Add(smallerL[i]); // always add original before adding modified in between
for (int j = 1; j < no; j++)
{
if (smallerL[i].Contains(" "))
{ // is rgb
string[] si = smallerL[i].Split(' ');
string[] sii = smallerL[i + 1].Split(' ');
int[] r = int.Parse(si[0]) > int.Parse(sii[0]) ? new int[] { int.Parse(si[0]), int.Parse(sii[0]), 1 } : new int[] { int.Parse(sii[0]), int.Parse(si[0]), -1 };
int[] g = int.Parse(si[1]) > int.Parse(sii[1]) ? new int[] { int.Parse(si[1]), int.Parse(sii[1]), 1 } : new int[] { int.Parse(sii[1]), int.Parse(si[1]), -1 };
int[] b = int.Parse(si[2]) > int.Parse(sii[2]) ? new int[] { int.Parse(si[2]), int.Parse(sii[2]), 1 } : new int[] { int.Parse(sii[2]), int.Parse(si[2]), -1 };
int rn = int.Parse(si[0]) - r[2] * (r[0] - r[1]) * j / no; // 200 - (200-100)*(0 or 1)/2 = fraction of difference based on which no
int gn = int.Parse(si[1]) - g[2] * (g[0] - g[1]) * j / no;
int bn = int.Parse(si[2]) - b[2] * (b[0] - b[1]) * j / no;
//Alert(smallerL[i]+" | "+ rn + " " + gn + " " + bn +" | " + smallerL[i+1]);
outList.Add(rn + " " + gn + " " + bn);
}
else // is grey
{
string grey = (float)no / i < 0.5 ? smallerL[i] : smallerL[i + 1];
outList.Add(grey);
}
}
}
outList.Add(smallerL[smallerL.Count - 1]);
//Alert(smallerL.Count + " " + largerL.Count);
//Alert(outList.Count + " " + largerL.Count);
return outList;
}
19
Source : JunimoFamiliar.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private int HealAmount()
{
return (int)(Math.Ceiling(Math.Sqrt(exp/10f)) * ModEntry.Config.JunimoHealAmountMult);
}
19
Source : ThemeApp.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void OpenThemesApp()
{
Monitor.Log($"opening customize app");
ModEntry.appRunning = true;
ModEntry.runningApp = Helper.ModRegistry.ModID;
skinListHeight = Config.ThemeItemMarginY + (int)Math.Ceiling(skinDict.Count / (float)ModEntry.themeGridWidth) * (Config.ThemeItemHeight + Config.ThemeItemMarginY) + Config.AppHeaderHeight * 2;
backListHeight = Config.ThemeItemMarginY + (int)Math.Ceiling(backgroundList.Count / (float)ModEntry.themeGridWidth) * (Config.ThemeItemHeight + Config.ThemeItemMarginY) + Config.AppHeaderHeight * 2;
ringListHeight = Config.RingLisreplacedemMarginY + ringList.Count * Config.RingLisreplacedemHeight + Config.AppHeaderHeight * 2;
Helper.Events.Display.RenderedWorld += Display_RenderedWorld;
Helper.Events.Input.ButtonPressed += Input_ButtonPressed;
}
19
Source : Traps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void LightningTrap(MineShaft shaft, Vector2 position)
{
Microsoft.Xna.Framework.Rectangle lightningSourceRect = new Rectangle(0, 0, 16, 16);
float markerScale = 8f;
Vector2 drawPosition = position + new Vector2(-16 * markerScale / 2 + 32f, -16 * markerScale / 2 + 32f);
shaft.temporarySprites.Add(new TemporaryAnimatedSprite("TileSheets\\Projectiles", lightningSourceRect, 9999f, 1, 999, drawPosition, false, Game1.random.NextDouble() < 0.5, (position.Y + 32f) / 10000f + 0.001f, 0.025f, Color.White, markerScale, 0f, 0f, 0f, false)
{
light = true,
lightRadius = 2f,
delayBeforeAnimationStart = 0,
lightcolor = Color.Black
});
shaft.playSound("thunder");
Utility.drawLightningBolt(position + new Vector2(32f, 32f), shaft);
FarmerCollection.Enumerator enumerator = shaft.farmers.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current.currentLocation == shaft && enumerator.Current.GetBoundingBox().Intersects(new Rectangle((int)Math.Round(position.X - 32), (int)Math.Round(position.Y - 32), 64, 64)))
{
enumerator.Current.takeDamage((int)Math.Ceiling(Math.Sqrt(shaft.mineLevel * config.TrapDamageMult)), true, null);
}
}
}
19
Source : ISyncStateService.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private async Task UpdateSyncTargetAsync()
{
// set the target to the lowest LIB
var chain = await _blockchainService.GetChainAsync();
var peers = _peerPool.GetPeers().ToList();
long minSyncTarget = chain.LastIrreversibleBlockHeight + NetworkOptions.InitialSyncOffset;
// determine the peers that are high enough to sync to
var candidates = peers
.Where(p => p.LastKnownLibHeight >= minSyncTarget)
.OrderBy(p => p.LastKnownLibHeight)
.ToList();
if (candidates.Count == 0)
{
// no peer has a LIB to sync to, stop the sync.
await SetSyncAsFinishedAsync();
Logger.LogInformation($"Finishing sync, not enough peers have a sufficiently high LIB (peer count: {_peerPool.PeerCount}).");
}
else
{
// If there's more than 2/3 of the nodes that we can
// sync to, take the lowest of them as target.
var minLib = candidates.First().LastKnownLibHeight;
if (candidates.Count >= Math.Ceiling(2d/3 * peers.Count))
{
SetSyncTarget(minLib);
Logger.LogDebug($"Set sync target to {minLib}.");
}
else
{
await SetSyncAsFinishedAsync();
Logger.LogInformation("Finishing sync, no peer has as a LIB high enough.");
}
}
}
19
Source : DynamicHierarchy.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
protected override void UpdateMulreplacedhreaded()
{
lock (Locker)
{
Overlaps.Clear();
if (root != null)
{
//To mulreplacedhread the tree traversals, we have to do a little single threaded work.
//Dive down into the tree far enough that there are enough nodes to split amongst all the threads in the thread manager.
//The depth to which we dive is offset by some precomputed values (when available) or a guess based on whether or not the
//thread count is a power of 2. Thread counts which are a power of 2 match well to the binary tree, while other thread counts
//require going deeper for better distributions.
int offset = ParallelLooper.ThreadCount <= threadSplitOffsets.Length
? threadSplitOffsets[ParallelLooper.ThreadCount - 1]
: (ParallelLooper.ThreadCount & (ParallelLooper.ThreadCount - 1)) == 0 ? 0 : 2;
int splitDepth = offset + (int)Math.Ceiling(Math.Log(ParallelLooper.ThreadCount, 2));
#if PROFILE
startRefit = Stopwatch.GetTimestamp();
#endif
MulreplacedhreadedRefitPhase(splitDepth);
#if PROFILE
endRefit = Stopwatch.GetTimestamp();
#endif
MulreplacedhreadedOverlapPhase(splitDepth);
#if PROFILE
endOverlap = Stopwatch.GetTimestamp();
#endif
}
}
}
19
Source : DataMap.cs
with MIT License
from aerosoul94
with MIT License
from aerosoul94
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
// Create main frame
_content = ClientRectangle;
// Create sub frames
var charSize = CreateGraphics().MeasureString("0", _font);
var rowInfoWidth = (int)(charSize.Width * 16);
var columnInfoHeight = (int)Math.Ceiling(charSize.Height);
_rowInfo = new Rectangle(_content.X,
_content.Y + columnInfoHeight,
rowInfoWidth,
_content.Height - columnInfoHeight);
_columnInfo = new Rectangle(_content.X + rowInfoWidth,
_content.Y,
(CellSize + 5) * 32,
columnInfoHeight);
_grid = new Rectangle(_content.X + rowInfoWidth,
_content.Y + columnInfoHeight,
(CellSize + 5) * 32,
_content.Height - columnInfoHeight);
if (vScrollVisible)
{
vScrollBar.Left = _content.X + _content.Width - vScrollBar.Width;
vScrollBar.Top = _content.Y;
vScrollBar.Height = _content.Height;
}
}
19
Source : ImageTools.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
public static Image RotateImage(Image image, int angle)
{
// Pythagoras on the X and Y coord of the bitmap gives us the maximum possible boundary required when all rotations considered
int newDimension = (int)Math.Ceiling(Math.Sqrt((image.Width * image.Width) + (image.Height * image.Height)));
Image newImage = new Bitmap(newDimension, newDimension);
Graphics graphic = Graphics.FromImage(newImage);
// Move the image to the center, rotate it, then move it back
graphic.TranslateTransform(newImage.Width / 2, newImage.Height / 2);
graphic.RotateTransform(angle);
graphic.TranslateTransform(-newImage.Width / 2, -newImage.Height / 2);
graphic.DrawImage(image, (newDimension - image.Width) / 2, (newDimension - image.Height) / 2, image.Width, image.Height);
return newImage;
}
19
Source : Map.cs
with GNU General Public License v3.0
from AHeroicLlama
with GNU General Public License v3.0
from AHeroicLlama
static int DrawLegend(Font font, Graphics imageGraphic)
{
if (FormMaster.legendItems.Count == 0)
{
return 0;
}
Dictionary<int, string> overridingLegendText = FormMaster.GatherOverriddenLegendTexts();
List<int> drawnGroups = new List<int>();
// Calculate the total height of all legend strings with their plot icons beside, combined
int legendTotalHeight = 0;
foreach (MapItem mapItem in FormMaster.legendItems)
{
// Skip legend groups that are merged/overridden and have already been accounted for
if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
{
continue;
}
legendTotalHeight += Math.Max(
(int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height),
SettingsPlot.IsIconOrTopographic() ? SettingsPlotIcon.iconSize : 0);
drawnGroups.Add(mapItem.legendGroup);
}
int skippedLegends = 0; // How many legend items did not fit onto the map
// The initial Y coord where first legend item should be written, in order to Y-center the entire legend
int legendCaretHeight = (mapDimension / 2) - (legendTotalHeight / 2);
// Reset the drawn groups list, as we need to iterate over the items again
drawnGroups = new List<int>();
// Loop over every MapItem and draw the legend
foreach (MapItem mapItem in FormMaster.legendItems)
{
// Skip legend groups that are merged/overridden and have already been drawn
if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
{
continue;
}
// Calculate positions and color for legend text (plus icon)
int fontHeight = (int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height);
PlotIcon icon = mapItem.GetIcon();
Image plotIconImg = SettingsPlot.IsIconOrTopographic() ? icon.GetIconImage() : null;
Color legendColor = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : mapItem.GetLegendColor();
Brush textBrush = new SolidBrush(legendColor);
int iconHeight = SettingsPlot.IsIconOrTopographic() ?
plotIconImg.Height :
0;
int legendHeight = Math.Max(fontHeight, iconHeight);
// If the icon is taller than the text, offset the text it so it sits Y-centrally against the icon
int textOffset = 0;
if (iconHeight > fontHeight)
{
textOffset = (iconHeight - fontHeight) / 2;
}
// If the legend text/item fits on the map vertically
if (legendCaretHeight > 0 && legendCaretHeight + legendHeight < mapDimension)
{
if (SettingsPlot.IsIconOrTopographic())
{
imageGraphic.DrawImage(plotIconImg, (float)(legendIconX - (plotIconImg.Width / 2d)), (float)(legendCaretHeight - (plotIconImg.Height / 2d) + (legendHeight / 2d)));
}
imageGraphic.DrawString(mapItem.GetLegendText(false), font, textBrush, new RectangleF(legendXMin, legendCaretHeight + textOffset, legendWidth, legendHeight));
}
else
{
skippedLegends++;
}
drawnGroups.Add(mapItem.legendGroup);
legendCaretHeight += legendHeight; // Move the 'caret' down for the next item, enough to fit the icon and the text
}
GC.Collect();
return skippedLegends;
}
19
Source : SoundBankMono.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
internal static int GetPaddedSize(int input)
{
return (int)(Math.Ceiling(input / 2048f) * 2048f);
}
19
Source : File.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Save()
{
if (Header.EntryCount > 0)
{
_stream.Position = 0;
var bw = new BinaryWriter(_stream);
Header.Write(bw);
// Recalculate the offset/sizes of the TOC entries
var tocOffset = _stream.Position;
// Find the max value here
var dataOffset = int.MinValue;
foreach (var entry in TOC)
{
var offset = entry.OffsetBlock + entry.UsedBlocks;
if (offset > dataOffset)
{
dataOffset = offset;
}
}
foreach (var entry in TOC)
{
if (entry.CustomData != null)
{
var blockCount = (int)Math.Ceiling((float)entry.CustomData.Length / TOCEntry.BlockSize);
if (blockCount <= entry.UsedBlocks)
{
// Clear up the old data
_stream.Seek(entry.OffsetBlock * TOCEntry.BlockSize, SeekOrigin.Begin);
bw.Write(new byte[entry.UsedBlocks * TOCEntry.BlockSize]);
// We can fit it in the existing block... so lets do that.
_stream.Seek(entry.OffsetBlock * TOCEntry.BlockSize, SeekOrigin.Begin);
}
else
{
// Clear up the old data
_stream.Seek(entry.OffsetBlock * TOCEntry.BlockSize, SeekOrigin.Begin);
bw.Write(new byte[entry.UsedBlocks * TOCEntry.BlockSize]);
// Fit it at the end of the stream
entry.OffsetBlock = dataOffset;
_stream.Seek(dataOffset*TOCEntry.BlockSize, SeekOrigin.Begin);
dataOffset += blockCount;
}
entry.UsedBlocks = (short)blockCount;
bw.Write(entry.CustomData);
if ((entry.CustomData.Length % TOCEntry.BlockSize) != 0)
{
var padding = new byte[blockCount * TOCEntry.BlockSize - entry.CustomData.Length];
bw.Write(padding);
}
entry.SetCustomData(null);
}
}
_stream.Seek(tocOffset, SeekOrigin.Begin);
TOC.Write(bw);
}
}
19
Source : TOC.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public int GetTOCBlockSize()
{
int size = _entries.Count*EntrySize;
foreach (var s in _nameTable)
{
size += s.Length + 1;
}
return (int)Math.Ceiling((float)size / TOCEntry.BlockSize);
}
19
Source : File.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Save()
{
if (Header.EntryCount > 0)
{
_stream.Position = 0;
var bw = new BinaryWriter(_stream);
Header.Write(bw);
// Recalculate the offset/sizes of the TOC entries
var tocOffset = 0x800;
// Find the max value here
var dataOffset = int.MinValue;
foreach (var entry in TOC)
{
var fileEntry = entry as FileEntry;
if (fileEntry != null)
{
var offset = fileEntry.Offset + fileEntry.SizeUsed;
if (offset > dataOffset)
{
dataOffset = offset;
}
}
}
foreach (var entry in TOC)
{
var fileEntry = entry as FileEntry;
if (fileEntry != null && fileEntry.CustomData != null)
{
var blockCount = (int)Math.Ceiling((float)fileEntry.CustomData.Length / FileEntry.BlockSize);
var blockSize = blockCount*FileEntry.BlockSize;
if (blockSize <= fileEntry.SizeUsed)
{
// Clear up the old data
_stream.Seek(fileEntry.Offset, SeekOrigin.Begin);
bw.Write(new byte[fileEntry.SizeUsed]);
// We can fit it in the existing block... so lets do that.
_stream.Seek(fileEntry.Offset, SeekOrigin.Begin);
}
else
{
// Clear up the old data
_stream.Seek(fileEntry.Offset, SeekOrigin.Begin);
bw.Write(new byte[fileEntry.SizeUsed]);
// Fit it at the end of the stream
fileEntry.Offset = dataOffset;
_stream.Seek(dataOffset, SeekOrigin.Begin);
dataOffset += blockSize;
}
fileEntry.SizeUsed = blockSize;
bw.Write(fileEntry.CustomData);
if ((fileEntry.CustomData.Length % FileEntry.BlockSize) != 0)
{
var padding = new byte[blockSize - fileEntry.CustomData.Length];
bw.Write(padding);
}
fileEntry.SetCustomData(null);
}
}
_stream.Seek(tocOffset, SeekOrigin.Begin);
TOC.Write(bw);
}
}
19
Source : FileEntry.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public override void Read(BinaryReader br)
{
NameOffset = br.ReadInt32();
Size = br.ReadInt32();
Offset = br.ReadInt32();
uint temp = br.ReadUInt32();
IsResourceFile = (temp & 0xC0000000) == 0xC0000000;
if (IsResourceFile)
{
ResourceType = (ResourceType) (Offset & 0xFF);
Offset = Offset & 0x7fffff00;
SizeInArchive = Size;
IsCompressed = false;
RSCFlags = temp;
}
else
{
SizeInArchive = (int) (temp & 0xbfffffff);
IsCompressed = (temp & 0x40000000) != 0;
}
SizeUsed = (int)Math.Ceiling((float)SizeInArchive / BlockSize) * BlockSize;
}
19
Source : Texture.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public Image DecodeAsThumbnail()
{
if (_thumbnailCache == null)
{
Image image = Decode();
int thumbWidth = ThumbnailSize;
int thumbHeight = ThumbnailSize;
if (Width > Height)
{
thumbHeight = (int)Math.Ceiling(((float) Height/Width)*ThumbnailSize);
}
else if (Height > Width)
{
thumbWidth = (int)Math.Ceiling(((float) Width/Height)*ThumbnailSize);
}
if (Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1)
{
// for Windows 7
// Don't use GetThumbnailImage as GDI+ is bugged.
_thumbnailCache = new Bitmap(thumbWidth, thumbHeight);
using (var g = Graphics.FromImage(_thumbnailCache))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImage(image, 0, 0, thumbWidth, thumbHeight);
}
}
else
{
_thumbnailCache = image.GetThumbnailImage(thumbWidth, thumbHeight, () => false, IntPtr.Zero);
}
}
return _thumbnailCache;
}
19
Source : SoundBankMultiChannel.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
// Read header
_fileHeader = new Header(br);
bool errorCondition = false;
if (!(_fileHeader.numBlocks > 0)) errorCondition = true;
if (!(_fileHeader.sizeBlock > 0)) errorCondition = true;
if (_fileHeader.numBlocks * _fileHeader.sizeBlock > br.BaseStream.Length) errorCondition = true;
if (_fileHeader.offsetBlockInfo > _fileHeader.sizeHeader) errorCondition = true;
if (errorCondition)
{
throw new SoundBankException("Unexpected values in Header");
}
// read adpcm state info
br.BaseStream.Seek(_fileHeader.offsetChannelInfo, SeekOrigin.Begin);
_channelInfoHeader = new ChannelInfoHeader[_fileHeader.numChannels];
for (int i = 0; i < _fileHeader.numChannels; i++)
{
_channelInfoHeader[i] = new ChannelInfoHeader(br);
}
_channelInfo = new ChannelInfo[_fileHeader.numChannels];
var currentOffset = br.BaseStream.Position;
for (int i = 0; i < _fileHeader.numChannels; i++)
{
br.BaseStream.Seek(currentOffset + _channelInfoHeader[i].offset, SeekOrigin.Begin);
_channelInfo[i] = new ChannelInfo(br);
if (_channelInfoHeader[i].size <= 36)
{
_isCompressed = false;
}
else
{
_channelInfo[i].adpcmInfo = new AdpcmInfo(br);
}
}
// Read comp block info (in header)
br.BaseStream.Seek(_fileHeader.offsetBlockInfo, SeekOrigin.Begin);
_blockInfoHeader = new BlockInfoHeader[_fileHeader.numBlocks];
for (int i = 0; i < _fileHeader.numBlocks; i++)
{
_blockInfoHeader[i] = new BlockInfoHeader(br);
}
// Read comp block info / channel info
_blockInfo = new BlockInfo[_fileHeader.numBlocks];
for (int i = 0; i < _fileHeader.numBlocks; i++)
{
var computedOffset = _fileHeader.sizeHeader + _fileHeader.sizeBlock*i;
br.BaseStream.Seek(computedOffset, SeekOrigin.Begin);
_blockInfo[i] = new BlockInfo(br);
_blockInfo[i].computed_offset = computedOffset;
_blockInfo[i].channelInfo = new BlockChannelInfo[_fileHeader.numChannels];
int numCodeIndices = 0;
for(int j=0; j<_fileHeader.numChannels; j++)
{
_blockInfo[i].channelInfo[j] = new BlockChannelInfo(br);
int end = _blockInfo[i].channelInfo[j].startIndex + _blockInfo[i].channelInfo[j].count;
if (numCodeIndices < end)
{
numCodeIndices = end;
}
}
_blockInfo[i].codeIndices = new CodeIndices[numCodeIndices];
for (int j = 0; j < numCodeIndices; j++)
{
_blockInfo[i].codeIndices[j] = new CodeIndices(br);
_blockInfo[i].codeIndices[j].computed_channel = -1;
if (_isCompressed)
{
_blockInfo[i].codeIndices[j].computed_adpcmIndex = _blockInfo[i].codeIndices[j].startIndex/
4096;
}
}
for (int j = 0; j < _fileHeader.numChannels; j++)
{
int channelIdxStart = _blockInfo[i].channelInfo[j].startIndex;
int channelIdxCount = _blockInfo[i].channelInfo[j].count;
for (int k = 0; k < channelIdxCount; k++)
{
_blockInfo[i].codeIndices[k + channelIdxStart].computed_channel = j;
}
}
int new_start =
(int) (Math.Ceiling((float) (_blockInfo[i].offset2 + 8*numCodeIndices)/BlockSize)*BlockSize);
_sizeBlockHeader = Math.Max(_sizeBlockHeader, new_start);
}
_waveInfos = new List<ISoundWave>(_fileHeader.numChannels);
for (int i = 0; i < _fileHeader.numChannels; i++)
{
_waveInfos.Add( new SoundWave(_fileHeader, _channelInfo[i]) );
}
_supportsMultichannelExport = ReorganizeForMultiChannelWave();
}
19
Source : File.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Rebuild()
{
if (Header.EntryCount > 0)
{
string tempFilename = _filename + ".temp";
var tempFS = new FileStream(tempFilename, FileMode.Create, FileAccess.Write);
try
{
var bw = new BinaryWriter(tempFS);
Header.Write(bw);
// Recalculate the offset/sizes of the TOC entries
var tocOffset = tempFS.Position;
var dataOffset = TOC.GetTOCBlockSize();
tempFS.Seek(dataOffset * TOCEntry.BlockSize, SeekOrigin.Begin);
foreach (var entry in TOC)
{
if (entry.CustomData == null)
{
bw.Write(ReadData(entry.OffsetBlock * TOCEntry.BlockSize, entry.UsedBlocks * TOCEntry.BlockSize));
}
else
{
var blockCount = (int) Math.Ceiling((float) entry.CustomData.Length/TOCEntry.BlockSize);
entry.UsedBlocks = (short)blockCount;
bw.Write( entry.CustomData );
if ( (entry.CustomData.Length % TOCEntry.BlockSize) != 0 )
{
var padding = new byte[ blockCount * TOCEntry.BlockSize - entry.CustomData.Length ];
bw.Write(padding);
}
}
entry.OffsetBlock = dataOffset;
dataOffset += entry.UsedBlocks;
}
tempFS.Seek(tocOffset, SeekOrigin.Begin);
TOC.Write( bw );
}
finally
{
tempFS.Close();
}
Close();
System.IO.File.Delete( _filename );
System.IO.File.Move( tempFilename, _filename );
Open(_filename);
}
}
19
Source : Math.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
[ContextMethod("НаименьшееЦел", "Ceiling")]
public double Ceiling(double p1)
{
return System.Math.Ceiling(p1);
}
19
Source : NumericManipulator.cs
with MIT License
from akaskela
with MIT License
from akaskela
private double RoundSignificantDigits(double value, int significantDigits, out int roundingPosition)
{
// this method will return a rounded double value at a number of signifigant figures.
// the sigFigures parameter must be between 0 and 15, exclusive.
roundingPosition = 0;
Precision p = new Precision();
if (p.AlmostEquals(value, 0d))
{
roundingPosition = significantDigits - 1;
return 0d;
}
if (double.IsNaN(value))
{
return double.NaN;
}
if (double.IsPositiveInfinity(value))
{
return double.PositiveInfinity;
}
if (double.IsNegativeInfinity(value))
{
return double.NegativeInfinity;
}
if (significantDigits < 1 || significantDigits > 15)
{
throw new ArgumentOutOfRangeException("significantDigits", value, "The significantDigits argument must be between 1 and 15.");
}
// if it's extremely insignificant, treat it as zero
if (((double)value).ToString() != value.ToString())
{
value = 0;
}
// The resulting rounding position will be negative for rounding at whole numbers, and positive for decimal places.
roundingPosition = significantDigits - 1 - (int)(Math.Floor(Math.Log10(Math.Abs(value))));
// try to use a rounding position directly, if no scale is needed.
// this is because the scale mutliplication after the rounding can introduce error, although
// this only happens when you're dealing with really tiny numbers, i.e 9.9e-14.
if (roundingPosition > 0 && roundingPosition < 16)
{
return Math.Round(value, roundingPosition, MidpointRounding.AwayFromZero);
}
// Shouldn't get here unless we need to scale it.
// Set the scaling value, for rounding whole numbers or decimals past 15 places
var scale = Math.Pow(10, Math.Ceiling(Math.Log10(Math.Abs(value))));
return Math.Round(value / scale, significantDigits, MidpointRounding.AwayFromZero) * scale;
}
19
Source : HtmlFromXamlConverter.cs
with GNU Affero General Public License v3.0
from akshinmustafayev
with GNU Affero General Public License v3.0
from akshinmustafayev
private static string ParseXamlThickness(string thickness)
{
string[] values = thickness.Split(',');
for (int i = 0; i < values.Length; i++)
{
double value;
if (double.TryParse(values[i], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
{
values[i] = Math.Ceiling(value).ToString(CultureInfo.InvariantCulture);
}
else
{
values[i] = "1";
}
}
string cssThickness;
switch (values.Length)
{
case 1:
cssThickness = thickness;
break;
case 2:
cssThickness = values[1] + " " + values[0];
break;
case 4:
cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0];
break;
default:
cssThickness = values[0];
break;
}
return cssThickness;
}
19
Source : RealExplosion.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public Dictionary<Fixture, Vector2> Activate(Vector2 pos, float radius, float maxForce)
{
AABB aabb;
aabb.LowerBound = pos + new Vector2(-radius, -radius);
aabb.UpperBound = pos + new Vector2(radius, radius);
Fixture[] shapes = new Fixture[MaxShapes];
// More than 5 shapes in an explosion could be possible, but still strange.
Fixture[] containedShapes = new Fixture[5];
bool exit = false;
int shapeCount = 0;
int containedShapeCount = 0;
// Query the world for overlapping shapes.
World.QueryAABB(
fixture =>
{
if (fixture.TestPoint(ref pos))
{
if (IgnoreWhenInsideShape)
{
exit = true;
return false;
}
containedShapes[containedShapeCount++] = fixture;
}
else
{
shapes[shapeCount++] = fixture;
}
// Continue the query.
return true;
}, ref aabb);
if (exit)
return new Dictionary<Fixture, Vector2>();
Dictionary<Fixture, Vector2> exploded = new Dictionary<Fixture, Vector2>(shapeCount + containedShapeCount);
// Per shape max/min angles for now.
float[] vals = new float[shapeCount * 2];
int valIndex = 0;
for (int i = 0; i < shapeCount; ++i)
{
PolygonShape ps;
CircleShape cs = shapes[i].Shape as CircleShape;
if (cs != null)
{
// We create a "diamond" approximation of the circle
Vertices v = new Vertices();
Vector2 vec = Vector2.Zero + new Vector2(cs.Radius, 0);
v.Add(vec);
vec = Vector2.Zero + new Vector2(0, cs.Radius);
v.Add(vec);
vec = Vector2.Zero + new Vector2(-cs.Radius, cs.Radius);
v.Add(vec);
vec = Vector2.Zero + new Vector2(0, -cs.Radius);
v.Add(vec);
ps = new PolygonShape(v, 0);
}
else
ps = shapes[i].Shape as PolygonShape;
if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null)
{
Vector2 toCentroid = shapes[i].Body.GetWorldPoint(ps.MreplacedData.Centroid) - pos;
float angleToCentroid = (float)Math.Atan2(toCentroid.Y, toCentroid.X);
float min = float.MaxValue;
float max = float.MinValue;
float minAbsolute = 0.0f;
float maxAbsolute = 0.0f;
for (int j = 0; j < ps.Vertices.Count; ++j)
{
Vector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos);
float newAngle = (float)Math.Atan2(toVertex.Y, toVertex.X);
float diff = (newAngle - angleToCentroid);
diff = (diff - MathHelper.Pi) % (2 * MathHelper.Pi);
// the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be
if (diff < 0.0f)
diff += 2 * MathHelper.Pi; // correction for not handling negs
diff -= MathHelper.Pi;
if (Math.Abs(diff) > MathHelper.Pi)
continue; // Something's wrong, point not in shape but exists angle diff > 180
if (diff > max)
{
max = diff;
maxAbsolute = newAngle;
}
if (diff < min)
{
min = diff;
minAbsolute = newAngle;
}
}
vals[valIndex] = minAbsolute;
++valIndex;
vals[valIndex] = maxAbsolute;
++valIndex;
}
}
Array.Sort(vals, 0, valIndex, _rdc);
_data.Clear();
bool rayMissed = true;
for (int i = 0; i < valIndex; ++i)
{
Fixture fixture = null;
float midpt;
int iplus = (i == valIndex - 1 ? 0 : i + 1);
if (vals[i] == vals[iplus])
continue;
if (i == valIndex - 1)
{
// the single edgecase
midpt = (vals[0] + MathHelper.Pi * 2 + vals[i]);
}
else
{
midpt = (vals[i + 1] + vals[i]);
}
midpt = midpt / 2;
Vector2 p1 = pos;
Vector2 p2 = radius * new Vector2((float)Math.Cos(midpt), (float)Math.Sin(midpt)) + pos;
// RaycastOne
bool hitClosest = false;
World.RayCast((f, p, n, fr) =>
{
Body body = f.Body;
if (!IsActiveOn(body))
return 0;
hitClosest = true;
fixture = f;
return fr;
}, p1, p2);
//draws radius points
if ((hitClosest) && (fixture.Body.BodyType == BodyType.Dynamic))
{
if ((_data.Any()) && (_data.Last().Body == fixture.Body) && (!rayMissed))
{
int laPos = _data.Count - 1;
ShapeData la = _data[laPos];
la.Max = vals[iplus];
_data[laPos] = la;
}
else
{
// make new
ShapeData d;
d.Body = fixture.Body;
d.Min = vals[i];
d.Max = vals[iplus];
_data.Add(d);
}
if ((_data.Count > 1)
&& (i == valIndex - 1)
&& (_data.Last().Body == _data.First().Body)
&& (_data.Last().Max == _data.First().Min))
{
ShapeData fi = _data[0];
fi.Min = _data.Last().Min;
_data.RemoveAt(_data.Count - 1);
_data[0] = fi;
while (_data.First().Min >= _data.First().Max)
{
fi.Min -= MathHelper.Pi * 2;
_data[0] = fi;
}
}
int lastPos = _data.Count - 1;
ShapeData last = _data[lastPos];
while ((_data.Count > 0)
&& (_data.Last().Min >= _data.Last().Max)) // just making sure min<max
{
last.Min = _data.Last().Min - 2 * MathHelper.Pi;
_data[lastPos] = last;
}
rayMissed = false;
}
else
{
rayMissed = true; // raycast did not find a shape
}
}
for (int i = 0; i < _data.Count; ++i)
{
if (!IsActiveOn(_data[i].Body))
continue;
float arclen = _data[i].Max - _data[i].Min;
float first = MathHelper.Min(MaxEdgeOffset, EdgeRatio * arclen);
int insertedRays = (int)Math.Ceiling(((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle);
if (insertedRays < 0)
insertedRays = 0;
float offset = (arclen - first * 2.0f) / ((float)MinRays + insertedRays - 1);
//Note: This loop can go into infinite as it operates on floats.
//Added FloatEquals with a large epsilon.
for (float j = _data[i].Min + first;
j < _data[i].Max || MathUtils.FloatEquals(j, _data[i].Max, 0.0001f);
j += offset)
{
Vector2 p1 = pos;
Vector2 p2 = pos + radius * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
Vector2 hitpoint = Vector2.Zero;
float minlambda = float.MaxValue;
List<Fixture> fl = _data[i].Body.FixtureList;
for (int x = 0; x < fl.Count; x++)
{
Fixture f = fl[x];
RayCastInput ri;
ri.Point1 = p1;
ri.Point2 = p2;
ri.MaxFraction = 50f;
RayCastOutput ro;
if (f.RayCast(out ro, ref ri, 0))
{
if (minlambda > ro.Fraction)
{
minlambda = ro.Fraction;
hitpoint = ro.Fraction * p2 + (1 - ro.Fraction) * p1;
}
}
// the force that is to be applied for this particular ray.
// offset is angular coverage. lambda*length of segment is distance.
float impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / MathHelper.Pi * (1.0f - Math.Min(1.0f, minlambda));
// We Apply the impulse!!!
Vector2 vectImp = Vector2.Dot(impulse * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)), -ro.Normal) * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
_data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint);
// We gather the fixtures for returning them
if (exploded.ContainsKey(f))
exploded[f] += vectImp;
else
exploded.Add(f, vectImp);
if (minlambda > 1.0f)
hitpoint = p2;
}
}
}
// We check contained shapes
for (int i = 0; i < containedShapeCount; ++i)
{
Fixture fix = containedShapes[i];
if (!IsActiveOn(fix.Body))
continue;
float impulse = MinRays * maxForce * 180.0f / MathHelper.Pi;
Vector2 hitPoint;
CircleShape circShape = fix.Shape as CircleShape;
if (circShape != null)
{
hitPoint = fix.Body.GetWorldPoint(circShape.Position);
}
else
{
PolygonShape shape = fix.Shape as PolygonShape;
hitPoint = fix.Body.GetWorldPoint(shape.MreplacedData.Centroid);
}
Vector2 vectImp = impulse * (hitPoint - pos);
fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint);
if (!exploded.ContainsKey(fix))
exploded.Add(fix, vectImp);
}
return exploded;
}
19
Source : BufferPool.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void EnsureCapacity(int capacity)
{
var neededBlockCount = (int)Math.Ceiling((double)capacity / BlockSize);
if (BlockCount < neededBlockCount)
{
if (neededBlockCount > Blocks.Length)
Array.Resize(ref Blocks, neededBlockCount);
for (int i = BlockCount; i < neededBlockCount; ++i)
{
Blocks[i] = new Block(BlockSize);
}
BlockCount = neededBlockCount;
}
}
19
Source : QueryableExtensions.cs
with MIT License
from albyho
with MIT License
from albyho
public static async Task<Page<T>> GetPageAsync<T>(this IQueryable<T> sourceQuery, PagingInfo pagingInfo, ICollection<T> topQuery = null) where T : clreplaced
{
if (sourceQuery == null)
{
throw new ArgumentNullException(nameof(sourceQuery));
}
sourceQuery = sourceQuery.AsNoTracking();
var page = new Page<T>();
// 跳过记录集无记录
if (topQuery == null || topQuery.Count == 0)
{
page.List = await sourceQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToListAsync();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync();
}
}
else
{
// 跳过的记录数
int topItemCount = topQuery.Count;
// 跳过的页数,比如一页显示10条,跳过4条、14条或24条,则跳过的页数为0、1或2
int skipPage = (int)Math.Floor((double)topItemCount / pagingInfo.PageSize);
// 如果目标页数在跳过的页数范围内,直接从topItems获取
if (skipPage > pagingInfo.PageIndex)
{
page.List = topQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
page.TotalItemCount = await sourceQuery.CountAsync() + topItemCount;
}
}
else
{
int topSkipCount = skipPage * pagingInfo.PageSize;
int topTakeCount = topItemCount % pagingInfo.PageSize;
var topItems = topQuery.Skip(topSkipCount).Take(topTakeCount);
int sourceSkipCount = (pagingInfo.PageIndex - skipPage) * pagingInfo.PageSize;
int sourceTakeCount = pagingInfo.PageSize - topTakeCount;
var sourceItems = await sourceQuery.Skip(sourceSkipCount).Take(sourceTakeCount).ToListAsync();
page.List = topItems.Concat(sourceItems).ToList();
if (!pagingInfo.IsExcludeMetaData)
{
// 查询集记录数
int sourceItemCount = await sourceQuery.CountAsync();
page.TotalItemCount = sourceItemCount + topItemCount;
}
}
}
page.TotalPageCount = (int)Math.Ceiling(page.TotalItemCount / (double)pagingInfo.PageSize);
return page;
}
19
Source : Earcut.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private static Node EliminateHoles(List<float> data, List<int> holeIndices, Node outerNode, int dim)
{
var i = 0;
var len = holeIndices.Count;
var start = 0;
var end = 0;
Node list = null;
var queue = new List<Node>(len);
for (i = 0; i < len; i++)
{
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : data.Count;
list = linkedList(data, start, end, dim, false);
if (list == list.next) list.steiner = true;
queue.Add(getLeftmost(list));
}
queue.Sort(delegate (Node a, Node b)
{
return (int)Math.Ceiling(a.x - b.x);
});
// process holes from left to right
for (i = 0; i < queue.Count; i++)
{
EliminateHole(queue[i], outerNode);
outerNode = FilterPoints(outerNode, outerNode.next);
}
return outerNode;
}
19
Source : Conversions.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private static Vector2 PixelsToTile(Vector2d p)
{
var t = new Vector2((int)Math.Ceiling(p.x / (double)TileSize) - 1, (int)Math.Ceiling(p.y / (double)TileSize) - 1);
return t;
}
19
Source : RoundingSettings.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public double Round(double 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 = Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Ceiling(value * adjustment) / adjustment);
}
break;
case RoundingConvention.RoundDown:
{
var adjustment = Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Floor(value * adjustment) / adjustment);
}
break;
case RoundingConvention.None:
{
var adjustment = Math.Pow(10, RowDecimalRoundTotal);
value = (Math.Truncate(value * adjustment) / adjustment);
}
break;
}
if (isNegative)
value = -value;
return value;
}
19
Source : NETImport.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private void ArrangeTypes()
{
const int Margin = Connection.Spacing * 2;
const int DiagramPadding = Shape.SelectionMargin;
int shapeCount = diagram.ShapeCount;
int columns = (int)Math.Ceiling(Math.Sqrt(shapeCount * 2));
int shapeIndex = 0;
int top = Shape.SelectionMargin;
int maxHeight = 0;
foreach (Shape shape in diagram.Shapes)
{
int column = shapeIndex % columns;
shape.Location = new Point(
(TypeShape.DefaultWidth + Margin) * column + DiagramPadding, top);
maxHeight = Math.Max(maxHeight, shape.Height);
if (column == columns - 1)
{
top += maxHeight + Margin;
maxHeight = 0;
}
shapeIndex++;
}
}
19
Source : Canvas.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private void SetScrolls()
{
if (HasDoreplacedent)
{
this.AutoScrollMinSize = new Size(
(int) Math.Ceiling(Doreplacedent.Size.Width * Doreplacedent.Zoom),
(int) Math.Ceiling(Doreplacedent.Size.Height * Doreplacedent.Zoom)
);
this.AutoScrollPosition = Doreplacedent.Offset;
}
else
{
this.AutoScrollMinSize = Size.Empty;
this.AutoScrollPosition = Point.Empty;
}
}
19
Source : ImageCreator.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
public static void CopyAsImage(IPrintable doreplacedent, bool selectedOnly)
{
if (doreplacedent == null)
throw new ArgumentNullException("doreplacedent");
RectangleF areaF = doreplacedent.GetPrintingArea(true);
areaF.Offset(0.5F, 0.5F);
Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));
using (Bitmap image = new Bitmap(area.Width, area.Height, PixelFormat.Format24bppRgb))
using (Graphics g = Graphics.FromImage(image))
{
// Set drawing parameters
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.TranslateTransform(-area.Left, -area.Top);
// Draw image
g.Clear(Style.CurrentStyle.BackgroundColor);
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
try
{
System.Windows.Forms.Clipboard.SetImage(image);
}
catch
{
//UNDONE: exception handling of CopyAsImage()
}
}
}
19
Source : AMD10CPU.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private double estimateTimeStampCounterMultiplier(double timeWindow) {
uint eax, edx;
// select event "076h CPU Clocks not Halted" and enable the counter
Ring0.Wrmsr(PERF_CTL_0,
(1 << 22) | // enable performance counter
(1 << 17) | // count events in user mode
(1 << 16) | // count events in operating-system mode
0x76, 0x00000000);
// set the counter to 0
Ring0.Wrmsr(PERF_CTR_0, 0, 0);
long ticks = (long)(timeWindow * Stopwatch.Frequency);
uint lsbBegin, msbBegin, lsbEnd, msbEnd;
long timeBegin = Stopwatch.GetTimestamp() +
(long)Math.Ceiling(0.001 * ticks);
long timeEnd = timeBegin + ticks;
while (Stopwatch.GetTimestamp() < timeBegin) { }
Ring0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin);
while (Stopwatch.GetTimestamp() < timeEnd) { }
Ring0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd);
Ring0.Rdmsr(COFVID_STATUS, out eax, out edx);
double coreMultiplier = GetCoreMultiplier(eax);
ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin;
ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd;
double coreFrequency = 1e-6 *
(((double)(countEnd - countBegin)) * Stopwatch.Frequency) /
(timeEnd - timeBegin);
double busFrequency = coreFrequency / coreMultiplier;
return 0.25 * Math.Round(4 * TimeStampCounterFrequency / busFrequency);
}
19
Source : GigabyteTAMG.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private string GetCompressedAndEncodedTable() {
string base64;
using (MemoryStream m = new MemoryStream()) {
using (GZipStream c = new GZipStream(m, CompressionMode.Compress)) {
c.Write(table, 0, table.Length);
}
base64 = Convert.ToBase64String(m.ToArray());
}
StringBuilder r = new StringBuilder();
for (int i = 0; i < Math.Ceiling(base64.Length / 64.0); i++) {
r.Append(" ");
for (int j = 0; j < 0x40; j++) {
int index = (i << 6) | j;
if (index < base64.Length) {
r.Append(base64[index]);
}
}
r.AppendLine();
}
return r.ToString();
}
19
Source : Shape.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
protected static Rectangle TransformRelativeToAbsolute(Rectangle rectangle,
float zoom, Point offset)
{
rectangle = Rectangle.FromLTRB(
(int) (rectangle.Left * zoom),
(int) (rectangle.Top * zoom),
(int) Math.Ceiling(rectangle.Right * zoom),
(int) Math.Ceiling(rectangle.Bottom * zoom));
rectangle.Offset(-offset.X, -offset.Y);
return rectangle;
}
19
Source : DatabaseCSharpDiagramGenerator.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private void ArrangeTypes()
{
const int Margin = Connection.Spacing * 2;
const int DiagramPadding = Shape.SelectionMargin;
int shapeCount = diagram.ShapeCount;
int columns = (int)Math.Ceiling(Math.Sqrt(shapeCount * 2));
int shapeIndex = 0;
int top = Shape.SelectionMargin;
int maxHeight = 0;
foreach (Shape shape in diagram.Shapes)
{
int column = shapeIndex % columns;
shape.Location = new Point(
(TypeShape.DefaultWidth + Margin) * column + DiagramPadding, top);
maxHeight = Math.Max(maxHeight, shape.Height);
if (column == columns - 1)
{
top += maxHeight + Margin;
maxHeight = 0;
}
shapeIndex++;
}
}
19
Source : GenericCPU.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void EstimateTimeStampCounterFrequency(double timeWindow,
out double frequency, out double error)
{
long ticks = (long)(timeWindow * Stopwatch.Frequency);
ulong countBegin, countEnd;
long timeBegin = Stopwatch.GetTimestamp() +
(long)Math.Ceiling(0.001 * ticks);
long timeEnd = timeBegin + ticks;
while (Stopwatch.GetTimestamp() < timeBegin) { }
countBegin = Opcode.Rdtsc();
long afterBegin = Stopwatch.GetTimestamp();
while (Stopwatch.GetTimestamp() < timeEnd) { }
countEnd = Opcode.Rdtsc();
long afterEnd = Stopwatch.GetTimestamp();
double delta = (timeEnd - timeBegin);
frequency = 1e-6 *
(((double)(countEnd - countBegin)) * Stopwatch.Frequency) / delta;
double beginError = (afterBegin - timeBegin) / delta;
double endError = (afterEnd - timeEnd) / delta;
error = beginError + endError;
}
19
Source : BaseTextControl.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label)
{
Performancereplacedyzer.Start("GetLabelSize");
CheckThread();
Font font = GetDrawingFont(node, context, label);
Size s = Size.Empty;
if (UseCompatibleTextRendering)
s = TextRenderer.MeasureText(label, font);
else
{
SizeF sf = context.Graphics.MeasureString(label, font);
s = new Size((int)Math.Ceiling(sf.Width), (int)Math.Ceiling(sf.Height));
}
Performancereplacedyzer.Finish("GetLabelSize");
if (!s.IsEmpty)
return s;
else
return new Size(10, Font.Height);
}
19
Source : SMBIOS.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public string GetReport() {
StringBuilder r = new StringBuilder();
if (version != null) {
r.Append("SMBIOS Version: "); r.AppendLine(version.ToString(2));
r.AppendLine();
}
if (BIOS != null) {
r.Append("BIOS Vendor: "); r.AppendLine(BIOS.Vendor);
r.Append("BIOS Version: "); r.AppendLine(BIOS.Version);
r.AppendLine();
}
if (System != null) {
r.Append("System Manufacturer: ");
r.AppendLine(System.ManufacturerName);
r.Append("System Name: ");
r.AppendLine(System.ProductName);
r.Append("System Version: ");
r.AppendLine(System.Version);
r.AppendLine();
}
if (Board != null) {
r.Append("Mainboard Manufacturer: ");
r.AppendLine(Board.ManufacturerName);
r.Append("Mainboard Name: ");
r.AppendLine(Board.ProductName);
r.Append("Mainboard Version: ");
r.AppendLine(Board.Version);
r.AppendLine();
}
if (Processor != null) {
r.Append("Processor Manufacturer: ");
r.AppendLine(Processor.ManufacturerName);
r.Append("Processor Version: ");
r.AppendLine(Processor.Version);
r.Append("Processor Core Count: ");
r.AppendLine(Processor.CoreCount.ToString());
r.Append("Processor Core Enabled: ");
r.AppendLine(Processor.CoreEnabled.ToString());
r.Append("Processor Thread Count: ");
r.AppendLine(Processor.ThreadCount.ToString());
r.Append("Processor External Clock: ");
r.Append(Processor.ExternalClock);
r.AppendLine(" Mhz");
r.AppendLine();
}
for (int i = 0; i < MemoryDevices.Length; i++) {
r.Append("Memory Device [" + i + "] Manufacturer: ");
r.AppendLine(MemoryDevices[i].ManufacturerName);
r.Append("Memory Device [" + i + "] Part Number: ");
r.AppendLine(MemoryDevices[i].PartNumber);
r.Append("Memory Device [" + i + "] Device Locator: ");
r.AppendLine(MemoryDevices[i].DeviceLocator);
r.Append("Memory Device [" + i + "] Bank Locator: ");
r.AppendLine(MemoryDevices[i].BankLocator);
r.Append("Memory Device [" + i + "] Speed: ");
r.Append(MemoryDevices[i].Speed);
r.AppendLine(" MHz");
r.AppendLine();
}
if (raw != null) {
string base64 = Convert.ToBase64String(raw);
r.AppendLine("SMBIOS Table");
r.AppendLine();
for (int i = 0; i < Math.Ceiling(base64.Length / 64.0); i++) {
r.Append(" ");
for (int j = 0; j < 0x40; j++) {
int index = (i << 6) | j;
if (index < base64.Length) {
r.Append(base64[index]);
}
}
r.AppendLine();
}
r.AppendLine();
}
return r.ToString();
}
19
Source : ImageCreator.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private static void SaveAsImage(IPrintable doreplacedent, string path,
ImageFormat format, bool selectedOnly, bool transparent)
{
const int Margin = 20;
RectangleF areaF = doreplacedent.GetPrintingArea(selectedOnly);
areaF.Offset(0.5F, 0.5F);
Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));
if (format == ImageFormat.Emf) // Save to metafile
{
Graphics metaG = control.CreateGraphics();
IntPtr hc = metaG.GetHdc();
Graphics g = null;
try
{
// Set drawing parameters
Metafile meta = new Metafile(path, hc);
g = Graphics.FromImage(meta);
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.TranslateTransform(-area.Left, -area.Top);
// Draw image
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
meta.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
metaG.ReleaseHdc();
metaG.Dispose();
if (g != null)
g.Dispose();
}
}
else // Save to rastered image
{
int width = area.Width + Margin * 2;
int height = area.Height + Margin * 2;
PixelFormat pixelFormat;
if (transparent)
pixelFormat = PixelFormat.Format32bppArgb;
else
pixelFormat = PixelFormat.Format24bppRgb;
using (Bitmap image = new Bitmap(width, height, pixelFormat))
using (Graphics g = Graphics.FromImage(image))
{
// Set drawing parameters
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.TranslateTransform(Margin - area.Left, Margin - area.Top);
// Draw image
if (!transparent)
g.Clear(Style.CurrentStyle.BackgroundColor);
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
try
{
image.Save(path, format);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
19
Source : DateTimeAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private IList<double> CreateDateTickValues(
double min, double max, double step, DateTimeIntervalType intervalType)
{
DateTime start = ToDateTime(min);
switch (intervalType)
{
case DateTimeIntervalType.Weeks:
// make sure the first tick is at the 1st day of a week
start = start.AddDays(-(int)start.DayOfWeek + (int)this.FirstDayOfWeek);
break;
case DateTimeIntervalType.Months:
// make sure the first tick is at the 1st of a month
start = new DateTime(start.Year, start.Month, 1);
break;
case DateTimeIntervalType.Years:
// make sure the first tick is at Jan 1st
start = new DateTime(start.Year, 1, 1);
break;
}
// Adds a tick to the end time to make sure the end DateTime is included.
DateTime end = ToDateTime(max).AddTicks(1);
DateTime current = start;
var values = new Collection<double>();
double eps = step * 1e-3;
DateTime minDateTime = ToDateTime(min - eps);
DateTime maxDateTime = ToDateTime(max + eps);
while (current < end)
{
if (current > minDateTime && current < maxDateTime)
{
values.Add(ToDouble(current));
}
switch (intervalType)
{
case DateTimeIntervalType.Months:
current = current.AddMonths((int)Math.Ceiling(step));
break;
case DateTimeIntervalType.Years:
current = current.AddYears((int)Math.Ceiling(step));
break;
default:
current = current.AddDays(step);
break;
}
}
return values;
}
19
Source : LogarithmicAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public override void GetTickValues(
out IList<double> majorLabelValues, out IList<double> majorTickValues, out IList<double> minorTickValues)
{
if (this.ActualMinimum <= 0)
{
this.ActualMinimum = 0.1;
}
double logBase = Math.Log(this.Base);
var e0 = (int)Math.Floor(Math.Log(this.ActualMinimum) / logBase);
var e1 = (int)Math.Ceiling(Math.Log(this.ActualMaximum) / logBase);
// find the min & max values for the specified base
// round to max 10 digits
double p0 = Math.Pow(this.Base, e0);
double p1 = Math.Pow(this.Base, e1);
double d0 = Math.Round(p0, 10);
double d1 = Math.Round(p1, 10);
if (d0 <= 0)
{
d0 = p0;
}
double d = d0;
majorTickValues = new List<double>();
minorTickValues = new List<double>();
double epsMin = this.ActualMinimum * 1e-6;
double epsMax = this.ActualMaximum * 1e-6;
while (d <= d1 + epsMax)
{
// d = RemoveNoiseFromDoubleMath(d);
if (d >= this.ActualMinimum - epsMin && d <= this.ActualMaximum + epsMax)
{
majorTickValues.Add(d);
}
for (int i = 1; i < this.Base; i++)
{
double d2 = d * (i + 1);
if (d2 > d1 + double.Epsilon)
{
break;
}
if (d2 > this.ActualMaximum)
{
break;
}
if (d2 >= this.ActualMinimum && d2 <= this.ActualMaximum)
{
minorTickValues.Add(d2);
}
}
d *= this.Base;
if (double.IsInfinity(d))
{
break;
}
if (d < double.Epsilon)
{
break;
}
if (double.IsNaN(d))
{
break;
}
}
if (majorTickValues.Count < 2)
{
base.GetTickValues(out majorLabelValues, out majorTickValues, out minorTickValues);
}
else
{
majorLabelValues = majorTickValues;
}
}
19
Source : LogarithmicAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
internal override void UpdateActualMaxMin()
{
if (this.PowerPadding)
{
double logBase = Math.Log(this.Base);
var e0 = (int)Math.Floor(Math.Log(this.ActualMinimum) / logBase);
var e1 = (int)Math.Ceiling(Math.Log(this.ActualMaximum) / logBase);
if (!double.IsNaN(this.ActualMinimum))
{
this.ActualMinimum = Math.Exp(e0 * logBase).RemoveNoiseFromDoubleMath();
}
if (!double.IsNaN(this.ActualMaximum))
{
this.ActualMaximum = Math.Exp(e1 * logBase).RemoveNoiseFromDoubleMath();
}
}
base.UpdateActualMaxMin();
}
19
Source : RangeAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private double CalculateActualInterval1(double availableSize, double maxIntervalSize)
{
int minTags = 5;
int maxTags = 20;
int numberOfTags = (int)(availableSize / maxIntervalSize);
double range = ActualMaximum - ActualMinimum;
double interval = range / numberOfTags;
const int k1 = 10;
interval = Math.Log10(interval / k1);
interval = Math.Ceiling(interval);
interval = Math.Pow(10, interval) * k1;
if (range / interval > maxTags) interval *= 5;
if (range / interval < minTags) interval *= 0.5;
if (interval <= 0) interval = 1;
return interval;
}
19
Source : RangeAxis.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private double CalculateActualInterval2(double availableSize, double maxIntervalSize)
{
Func<double, double> Exponent = x => Math.Ceiling(Math.Log(x, 10));
Func<double, double> Mantissa = x => x / Math.Pow(10, Exponent(x) - 1);
// reduce intervals for horizontal axis.
// double maxIntervals = Orientation == AxisOrientation.X ? MaximumAxisIntervalsPer200Pixels * 0.8 : MaximumAxisIntervalsPer200Pixels;
// real maximum interval count
double maxIntervalCount = availableSize / maxIntervalSize;
double range = Math.Abs(ActualMinimum - ActualMaximum);
double interval = Math.Pow(10, Exponent(range));
double tempInterval = interval;
// decrease interval until interval count becomes less than maxIntervalCount
while (true)
{
int mantissa = (int)Mantissa(tempInterval);
if (mantissa == 5)
{
// reduce 5 to 2
tempInterval = RemoveNoiseFromDoubleMath(tempInterval / 2.5);
}
else if (mantissa == 2 || mantissa == 1 || mantissa == 10)
{
// reduce 2 to 1,10 to 5,1 to 0.5
tempInterval = RemoveNoiseFromDoubleMath(tempInterval / 2.0);
}
if (range / tempInterval > maxIntervalCount)
{
break;
}
interval = tempInterval;
}
return interval;
}
19
Source : DoubleExtensions.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static double ToUpperMultiple(this double value, double step)
{
var i = (int)Math.Ceiling(value / step);
return (step * i).RemoveNoise();
}
19
Source : RenderingExtensions.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static void DrawClippedImage(
this IRenderContext rc,
OxyRect clippingRect,
OxyImage source,
double x,
double y,
double w,
double h,
double opacity,
bool interpolate)
{
if (x > clippingRect.Right || x + w < clippingRect.Left || y > clippingRect.Bottom || y + h < clippingRect.Top)
{
return;
}
if (rc.SetClip(clippingRect))
{
// The render context supports clipping, then we can draw the whole image
rc.DrawImage(source, x, y, w, h, opacity, interpolate);
rc.ResetClip();
return;
}
// The render context does not support clipping, we must calculate the rectangle
var info = rc.GetImageInfo(source);
if (info == null)
{
return;
}
// Fint the positions of the clipping rectangle normalized to image coordinates (0,1)
var i0 = (clippingRect.Left - x) / w;
var i1 = (clippingRect.Right - x) / w;
var j0 = (clippingRect.Top - y) / h;
var j1 = (clippingRect.Bottom - y) / h;
// Find the origin of the clipped source rectangle
var srcx = i0 < 0 ? 0u : i0 * info.Width;
var srcy = j0 < 0 ? 0u : j0 * info.Height;
srcx = (int)Math.Ceiling(srcx);
srcy = (int)Math.Ceiling(srcy);
// Find the size of the clipped source rectangle
var srcw = i1 > 1 ? info.Width - srcx : (i1 * info.Width) - srcx;
var srch = j1 > 1 ? info.Height - srcy : (j1 * info.Height) - srcy;
srcw = (int)srcw;
srch = (int)srch;
if ((int)srcw <= 0 || (int)srch <= 0)
{
return;
}
// The clipped destination rectangle
var destx = i0 < 0 ? x : x + (srcx / info.Width * w);
var desty = j0 < 0 ? y : y + (srcy / info.Height * h);
var destw = w * srcw / info.Width;
var desth = h * srch / info.Height;
rc.DrawImage(source, (uint)srcx, (uint)srcy, (uint)srcw, (uint)srch, destx, desty, destw, desth, opacity, interpolate);
}
19
Source : ClientSubnetOption.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
private int GetAddressLength()
{
return (int) Math.Ceiling(SourceNetmask / 8d);
}
See More Examples