private void saveButton_Click(object sender, EventArgs e) { var allWarnings = new StringBuilder(); var allBlankCells = new List <DataGridViewCell>(); // validate that all channels have names foreach (var methodTablePair in isobaricMappingTables) { var tableWarnings = new StringBuilder(); foreach (var row in methodTablePair.Value.Rows.Cast <DataGridViewRow>()) { var blankCells = row.Cells.Cast <DataGridViewCell>().Where(o => o.Value == null || o.Value.ToString() == String.Empty); var blankChannels = blankCells.Select(o => methodTablePair.Value.Columns[o.ColumnIndex].HeaderText); if (blankChannels.Any()) { tableWarnings.AppendFormat("\t{0}: {1}\r\n", row.Cells[0].Value, String.Join(", ", blankChannels)); } allBlankCells.AddRange(blankCells); } if (tableWarnings.Length > 0) { allWarnings.AppendFormat("Some sample names for {0} were left blank:\r\n{1}\r\n\r\nDo you want to assign these channels to Empty?", methodTablePair.Key, tableWarnings); } } if (allWarnings.Length > 0) { if (MessageBox.Show(this, allWarnings.ToString(), "Warning", MessageBoxButtons.YesNo) == DialogResult.No) { return; } allBlankCells.ForEach(o => o.Value = "Empty"); } IDictionary <string, IList <string> > isobaricSampleMapping = new Dictionary <string, IList <string> >(); foreach (var methodTablePair in isobaricMappingTables) { foreach (var row in methodTablePair.Value.Rows.Cast <DataGridViewRow>()) { var sourceGroup = row.Cells[0].Value.ToString(); isobaricSampleMapping.Add(sourceGroup, new List <string>(row.Cells.Cast <DataGridViewCell>().Skip(1).Select(o => o.Value.ToString()))); } } var idpDbFilepath = session.Connection.GetDataSource(); var existingIsobaricSampleMapping = Embedder.GetIsobaricSampleMapping(idpDbFilepath); if (!existingIsobaricSampleMapping.SequenceEqual(isobaricSampleMapping)) { Embedder.EmbedIsobaricSampleMapping(idpDbFilepath, isobaricSampleMapping); DialogResult = DialogResult.OK; } else { DialogResult = DialogResult.Cancel; } Close(); }
public QuantitationSettingsForm(Embedder.XICConfiguration oldXicConfig, Embedder.QuantitationConfiguration oldIsobaricConfig, double maxQValue) { XicConfig = oldXicConfig; IsobaricConfig = oldIsobaricConfig; _maxQValue = maxQValue; InitializeComponent(); }
public void Platform_Supported() { var valid = new string [] { "OSX", "MacOSX", "MacOS", "Mac" }; foreach (var p in valid) { var embedder = new Embedder(); embedder.SetPlatform(p); Assert.That(embedder.Platform, Is.EqualTo(Platform.macOS), p); } foreach (var p in new string [] { "ios", "iOS" }) { var embedder = new Embedder(); embedder.SetPlatform(p); Assert.That(embedder.Platform, Is.EqualTo(Platform.iOS), p); } foreach (var p in new string [] { "tvos", "tvOS" }) { var embedder = new Embedder(); embedder.SetPlatform(p); Assert.That(embedder.Platform, Is.EqualTo(Platform.tvOS), p); } foreach (var p in new string [] { "watchos", "watchOS" }) { var embedder = new Embedder(); embedder.SetPlatform(p); Assert.That(embedder.Platform, Is.EqualTo(Platform.watchOS), p); } }
string CompileLibrary(Platform platform, string code = null, string libraryName = null) { int exitCode; if (libraryName == null) { libraryName = "library"; } var tmpdir = Xamarin.Cache.CreateTemporaryDirectory(); var cs_path = Path.Combine(tmpdir, libraryName + ".cs"); var dll_path = Path.Combine(tmpdir, libraryName + ".dll"); if (code == null) { code = "public class Test { public static void X () {} }"; } File.WriteAllText(cs_path, code); if (!Embedder.RunProcess("/Library/Frameworks/Mono.framework/Versions/Current/bin/csc", $"/target:library {Embedder.Quote (cs_path)} /out:{Embedder.Quote (dll_path)}", out exitCode)) { Assert.Fail("Failed to compile test code"); } return(dll_path); }
public async Task<EmbedInfo> Get() { Guid workspaceId = Guid.Parse("b487a335-6055-4b74-8572-396002ffc8e5"); Guid reportId = Guid.Parse("7eab73d7-4d38-4cf0-8c08-265a60823d21"); var embedInfo = await Embedder.GetEmbedInfo(workspaceId, reportId); return embedInfo; }
public void Platform_Invalid() { try { var embedder = new Embedder(); embedder.SetPlatform("invalid"); } catch (EmbeddinatorException ee) { Assert.True(ee.Error, "Error"); Assert.That(ee.Code, Is.EqualTo(3), "Code"); } }
public void Target_Supported() { var valid = new string [] { "ObjC", "Obj-C", "ObjectiveC", "objective-c" }; foreach (var t in valid) { var embedder = new Embedder(); embedder.SetTarget(t); Assert.That(embedder.TargetLanguage, Is.EqualTo(TargetLanguage.ObjectiveC), t); } }
public void ABI(Platform platform, string abi) { var dll = CompileLibrary(platform); var tmpdir = Xamarin.Cache.CreateTemporaryDirectory(); Driver.Main2("--platform", platform.ToString(), "--abi", abi, "-c", dll, "-o", tmpdir); string output; int exitCode; Assert.IsTrue(Embedder.RunProcess("xcrun", $"lipo -info {tmpdir}/libLibrary.dylib", out exitCode, out output), "lipo"); StringAssert.IsMatch($"Non-fat file: .* is architecture: {abi}", output, "architecture"); }
static void Main() { embedder = new Embedder("symbols.txt"); pngPath = embedder.SaveMatrixPng(id, size, margin); Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form = new MainForm()); RefreshPlot(); }
public Embed ShowMainAsync(int page = 1) { EmbedBuilder eb = Embedder.DefaultEmbed; eb.WithDescription("orikivo : modules".DiscordBlock()); // if the account wants to show tooltips... eb.WithFooter($"{Context.Server.Config.GetPrefix(Context)}help <module>"); IEnumerable <ModuleInfo> modules = GetActiveModules().Parents(); List <string> summaries = WriteModules(modules); return(Embedder.Paginate(summaries, page, eb)); }
public void Platform_NotSupported() { var notsupported = new string [] { "Windows", "Android", "iOS", "tvOS", "watchOS" }; foreach (var p in notsupported) { try { var embedder = new Embedder(); embedder.SetPlatform(p); } catch (EmbeddinatorException ee) { Assert.True(ee.Error, "Error"); Assert.That(ee.Code, Is.EqualTo(3), "Code"); } } }
public static void RunProcess(string filename, string arguments, out string stdout, string message) { int exitCode; Console.WriteLine($"{filename} {arguments}"); // We capture stderr too, otherwise it won't show up in the test unit pad's output. if (Embedder.RunProcess(filename, arguments, out exitCode, out stdout, capture_stderr: true)) { return; } Console.WriteLine($"Command failed with exit code: {exitCode}"); Console.WriteLine(stdout); Console.WriteLine($"Command failed with exit code: {exitCode}"); Assert.Fail($"Executing '{filename} {arguments}' failed with exit code {exitCode}: {message}"); }
public void Target_NotSupported() { var notsupported = new string [] { "C", "C++", "Java" }; foreach (var t in notsupported) { try { var embedder = new Embedder(); embedder.SetTarget(t); } catch (EmbeddinatorException ee) { Assert.True(ee.Error, "Error"); Assert.That(ee.Code, Is.EqualTo(4), "Code"); } } }
public void Output() { Random rnd = new Random(); string valid = Path.Combine(Path.GetTempPath(), "output-" + rnd.Next().ToString()); try { var embedder = new Embedder(); embedder.OutputDirectory = valid; Assert.That(Directory.Exists(valid), "valid"); try { embedder.OutputDirectory = "/:output"; Assert.Fail("invalid"); } catch (EmbeddinatorException ee) { Assert.True(ee.Error, "Error"); Assert.That(ee.Code, Is.EqualTo(1), "Code"); } } finally { Directory.Delete(valid); } }
public void CompilationTarget() { var embedder = new Embedder(); Asserts.ThrowsEmbeddinatorException(5, "The compilation target `invalid` is not valid.", () => Driver.Main2(new [] { "--target=invalid" })); Asserts.ThrowsEmbeddinatorException(5, "The compilation target `invalid` is not valid.", () => embedder.SetCompilationTarget("invalid")); foreach (var ct in new string [] { "library", "sharedlibrary", "dylib" }) { embedder.SetCompilationTarget(ct); Assert.That(embedder.CompilationTarget, Is.EqualTo(global::Embeddinator.CompilationTarget.SharedLibrary), ct); } foreach (var ct in new string [] { "framework" }) { embedder.SetCompilationTarget(ct); Assert.That(embedder.CompilationTarget, Is.EqualTo(global::Embeddinator.CompilationTarget.Framework), ct); } foreach (var ct in new string [] { "static", "staticlibrary" }) { embedder.SetCompilationTarget(ct); Assert.That(embedder.CompilationTarget, Is.EqualTo(global::Embeddinator.CompilationTarget.StaticLibrary), ct); } }
private void embedAllButton_Click(object sender, EventArgs e) { var searchPath = new StringBuilder(searchPathTextBox.Text); string extensions = extensionsTextBox.Text; Application.UseWaitCursor = true; deleteAllButton.Enabled = embedAllButton.Enabled = false; embeddedChanges = true; try { // add location of original idpDBs to the search path var mergedFilepaths = session.CreateSQLQuery("SELECT DISTINCT Filepath FROM MergedFiles").List <string>(); foreach (var filepath in mergedFilepaths) { searchPath.AppendFormat(";{0}", System.IO.Path.GetDirectoryName(filepath)); } } catch { // ignore if MergedFiles does not exist } var quantitationMethodBySource = new Dictionary <int, Embedder.QuantitationConfiguration>(); var xicConfigBySource = new Dictionary <int, Embedder.XICConfiguration> { { 0, _defaultXicConfig } }; foreach (DataGridViewRow row in dataGridView.Rows) { int id = (int)row.Cells[idColumn.Index].Value; var method = QuantitationMethodForRow(row.Index); if (IsLabelFree(method)) { xicConfigBySource[id] = (Embedder.XICConfiguration)row.Cells[quantitationSettingsColumn.Index].Value; quantitationMethodBySource[id] = new Embedder.QuantitationConfiguration(QuantitationMethod.LabelFree, _defaultIsobaricConfig.ToString()); } else if (IsIsobaric(method)) { quantitationMethodBySource[id] = (Embedder.QuantitationConfiguration)row.Cells[quantitationSettingsColumn.Index].Value; } } okButton.Text = "Cancel"; EmbedInProgress = true; new Thread(() => { try { var ilr = new IterationListenerRegistry(); ilr.addListener(new EmbedderIterationListener(this), 1); var tempFolder = string.Empty; var splitSourceList = new List <List <string> >(); if (quantitationMethodBySource.Any(x => IsLabelFree(x.Value.QuantitationMethod)) && xicConfigBySource.Any(x => x.Value.AlignRetentionTime)) { tempFolder = getTempFolder(); splitSourceList = GetRTAlignGroups(); } string idpDbFilepath = session.Connection.GetDataSource(); if (embedScanTimeOnlyBox.Checked) { Embedder.EmbedScanTime(idpDbFilepath, searchPath.ToString(), extensions, quantitationMethodBySource, ilr); } else { Embedder.Embed(idpDbFilepath, searchPath.ToString(), extensions, quantitationMethodBySource, ilr); } if (quantitationMethodBySource.Any(x => IsLabelFree(x.Value.QuantitationMethod))) { BeginInvoke(new MethodInvoker(() => ModeandDefaultPanel.Visible = false)); if (xicConfigBySource.Any(x => x.Value.AlignRetentionTime)) { try { RTAlignPreparations(splitSourceList, tempFolder); foreach (var kvp in xicConfigBySource) { kvp.Value.RTFolder = tempFolder; } } catch (Exception rtError) { MessageBox.Show("Error: Cannot prepare RT alignment. Skipping to next stage." + Environment.NewLine + rtError.Message); foreach (var kvp in xicConfigBySource) { kvp.Value.AlignRetentionTime = false; } } } Embedder.EmbedMS1Metrics(idpDbFilepath, searchPath.ToString(), extensions, quantitationMethodBySource, xicConfigBySource, ilr); if (!string.IsNullOrEmpty(tempFolder) && Directory.Exists(tempFolder)) { Directory.Delete(tempFolder, true); } BeginInvoke(new MethodInvoker(() => ModeandDefaultPanel.Visible = true)); } } catch (Exception ex) { if (ex.Message.Contains("QuantitationConfiguration")) { string message = ex.Message.Replace("[QuantitationConfiguration] ", ""); message = Char.ToUpper(message[0]) + message.Substring(1); MessageBox.Show(message); } else if (ex.Message.Contains("no filepath")) { bool multipleMissingFilepaths = ex.Message.Contains("\n"); string missingFilepaths = ex.Message.Replace("\n", "\r\n"); missingFilepaths = missingFilepaths.Replace("[embed] no", "No"); missingFilepaths = missingFilepaths.Replace("[embedScanTime] no", "No"); MessageBox.Show(missingFilepaths + "\r\n\r\nCheck that " + (multipleMissingFilepaths ? "these source files" : "this source file") + " can be found in the search path with one of the specified extensions."); } else { Program.HandleException(ex); } } BeginInvoke(new MethodInvoker(() => Refresh())); }).Start(); }
string FindDevice(params string [] valid_classes) { if (device_xml == null) { var cachedir = Cache.CreateTemporaryDirectory(); var xmlpath = Path.Combine(cachedir, "devices.xml"); Asserts.RunProcess("/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mlaunch", $"--listdev={Embedder.Quote (xmlpath)} --output-format=xml", "mlaunch --listdev"); device_xml = new XmlDocument(); device_xml.Load(xmlpath); } var nodes = device_xml.SelectNodes("/MTouch/Device[" + string.Join(" or ", valid_classes.Select((v) => "DeviceClass = \"" + v + "\"")) + "]/DeviceIdentifier"); var devices = new List <string> (); foreach (XmlNode node in nodes) { devices.Add(node.InnerText); } if (devices.Count == 0) { return(string.Empty); } devices.Sort(StringComparer.Ordinal); // Sort all applicable devices so the same test run always runs on the same device. return(devices [0]); }
void RunManagedTests(Platform platform, string test_destination = "", bool debug = true) { string dllname; string dlldir; string abi; List <string> defines = new List <string> (); var managedTestCount = CountTests(Path.Combine(XcodeProjectGenerator.TestsRootDirectory, "objc-cli/libmanaged/Tests/Tests.m")); var xamariniOSTestCount = CountTests(Path.Combine(XcodeProjectGenerator.TestsRootDirectory, "objcgentest/xcodetemplate/ios/test/iosTests.m")); var xamarinMacTestCount = CountTests(Path.Combine(XcodeProjectGenerator.TestsRootDirectory, "objcgentest/xcodetemplate/macos/test/macTests.m")); var xamarintvOSTestCount = CountTests(Path.Combine(XcodeProjectGenerator.TestsRootDirectory, "objcgentest/xcodetemplate/tvos/test/tvosTests.m")); switch (platform) { case Platform.macOSFull: dlldir = "macos-full"; dllname = "managed-macos-full.dll"; defines.Add("XAMARIN_MAC=1"); defines.Add("XAMARIN_MAC_FULL=1"); abi = "x86_64"; // FIXME: fat XM apps not supported yet managedTestCount += xamarinMacTestCount; break; case Platform.macOSSystem: dlldir = "macos-system"; dllname = "managed-macos-system.dll"; defines.Add("XAMARIN_MAC=1"); defines.Add("XAMARIN_MAC_SYSTEM=1"); abi = "x86_64"; // FIXME: fat XM apps not supported yet managedTestCount += xamarinMacTestCount; break; case Platform.macOSModern: dlldir = "macos-modern"; dllname = "managed-macos-modern.dll"; defines.Add("XAMARIN_MAC=1"); defines.Add("XAMARIN_MAC_MODERN=1"); abi = "x86_64"; // FIXME: fat XM apps not supported yet managedTestCount += xamarinMacTestCount; break; case Platform.macOS: dlldir = "generic"; dllname = "managed.dll"; abi = "i386,x86_64"; break; case Platform.iOS: dlldir = "ios"; dllname = "managed-ios.dll"; defines.Add("XAMARIN_IOS=1"); abi = "armv7,arm64,i386,x86_64"; managedTestCount += xamariniOSTestCount; break; case Platform.tvOS: dlldir = "tvos"; dllname = "managed-tvos.dll"; defines.Add("XAMARIN_TVOS=1"); abi = "arm64,x86_64"; managedTestCount += xamarintvOSTestCount; break; default: throw new NotImplementedException(); } defines.Add("TEST_FRAMEWORK=1"); var tmpdir = Cache.CreateTemporaryDirectory(); var configuration = debug ? "Debug" : "Release"; var dll_path = Path.Combine(XcodeProjectGenerator.TestsRootDirectory, "managed", dlldir, "bin", configuration, dllname); // This will build all the managed.dll variants, which is easier than calculating the relative path _as the makefile sees it_ to pass as the target. Asserts.RunProcess("make", $"all CONFIG={configuration} -C {Embedder.Quote (Path.Combine (XcodeProjectGenerator.TestsRootDirectory, "managed"))}", "build " + Path.GetFileName(dll_path)); var outdir = tmpdir + "/out"; var projectName = "foo"; var args = new List <string> (); if (debug) { args.Add("--debug"); } args.Add(dll_path); args.Add("-c"); args.Add($"--outdir={outdir}"); args.Add("--target=framework"); args.Add($"--platform={platform}"); args.Add($"--abi={abi}"); Asserts.Generate("generate", args.ToArray()); var framework_path = Path.Combine(outdir, Path.GetFileNameWithoutExtension(dll_path) + ".framework"); var projectDirectory = XcodeProjectGenerator.Generate(platform, tmpdir, projectName, framework_path, defines: defines.ToArray()); string output; var builddir = Path.Combine(tmpdir, "xcode-build-dir"); Asserts.RunProcess("xcodebuild", $"test -project {Embedder.Quote (projectDirectory)} -scheme Tests {test_destination} CONFIGURATION_BUILD_DIR={Embedder.Quote (builddir)}", out output, "run xcode tests"); // assert the number of tests passed, so that we can be sure we actually ran all the tests. Otherwise it's very easy to ignore when a bug is causing tests to not be built. Assert.That(output, Does.Match($"Test Suite 'All tests' passed at .*\n\t Executed {managedTestCount} tests, with 0 failures"), "test count"); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // get the list of sources, the group they're in, and their quantitation method var spectrumSources = session.Query <SpectrumSource>().ToList(); var sourcesByGroup = spectrumSources.GroupBy(o => o.Group); // find groups with more than 1 quantitation method; put these in a separate list for "invalid" groups var allGroupsByMethod = sourcesByGroup.GroupBy(o => o.Select(o2 => o2.QuantitationMethod)); var invalidGroups = allGroupsByMethod.Where(o => o.Count() > 1).SelectMany(o2 => o2.Select(o3 => o3.Key)); // divide valid source groups by quantitation method var validGroupsByMethod = sourcesByGroup.Where(o => !invalidGroups.Contains(o.Key)).GroupBy(o => o.Select(o2 => o2.QuantitationMethod).Distinct().Single()); if (validGroupsByMethod.Any()) { var existingIsobaricSampleMapping = Embedder.GetIsobaricSampleMapping(session.Connection.GetDataSource()); // specialize the default mapping table for each quantitation method foreach (var method in validGroupsByMethod) { var dgv = isobaricMappingDataGridView.CloneAsDesigned(); dgv.EditingControlShowing += isobaricMappingDataGridView_EditingControlShowing; isobaricMappingDataGridView.Columns.Cast <DataGridViewColumn>().ForEach(o => dgv.Columns.Add((DataGridViewColumn)o.Clone())); if (method.Key == QuantitationMethod.ITRAQ4plex) { foreach (int ion in new int[] { 114, 115, 116, 117 }) { var column = new DataGridViewTextBoxColumn { HeaderText = "iTRAQ-" + ion.ToString(), Name = "iTRAQ-" + ion.ToString() + "Column", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 0.25f, }; dgv.Columns.Add(column); } } else if (method.Key == QuantitationMethod.ITRAQ8plex) { foreach (int ion in new int[] { 113, 114, 115, 116, 117, 118, 119, 121 }) { var column = new DataGridViewTextBoxColumn { HeaderText = "iTRAQ-" + ion.ToString(), Name = "iTRAQ-" + ion.ToString() + "Column", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 0.125f }; dgv.Columns.Add(column); } } else if (method.Key == QuantitationMethod.TMT2plex) { foreach (string ion in new string[] { "126", "127" }) { var column = new DataGridViewTextBoxColumn { HeaderText = "TMT-" + ion, Name = "TMT-" + ion + "Column", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 0.5f }; dgv.Columns.Add(column); } } else if (method.Key == QuantitationMethod.TMT6plex) { foreach (string ion in new string[] { "126", "127", "128", "129", "130", "131" }) { var column = new DataGridViewTextBoxColumn { HeaderText = "TMT-" + ion, Name = "TMT-" + ion + "Column", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 0.1666f }; dgv.Columns.Add(column); } } else if (method.Key == QuantitationMethod.TMT10plex) { foreach (string ion in new string[] { "126", "127N", "127C", "128N", "128C", "129N", "129C", "130N", "130C", "131" }) { var column = new DataGridViewTextBoxColumn { HeaderText = "TMT-" + ion, Name = "TMT-" + ion + "Column", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 0.1f }; dgv.Columns.Add(column); } } // add source groups to the table foreach (var group in method) { int newRowIndex = dgv.Rows.Add(group.Key.Name); if (existingIsobaricSampleMapping.ContainsKey(group.Key.Name)) { var existingSampleNames = existingIsobaricSampleMapping[group.Key.Name]; if (existingSampleNames.Count != dgv.Columns.Count - 1) { continue; } for (int i = 0; i < existingSampleNames.Count; ++i) { dgv.Rows[newRowIndex].Cells[i + 1].Value = existingSampleNames[i]; } } } var tab = new TabPage(method.Key.ToString()); tab.Controls.Add(dgv); quantitationMethodsTabPanel.TabPages.Add(tab); isobaricMappingTables.Add(method.Key, dgv); } quantitationMethodsTabPanel.TabPages.Remove(noIsobaricMethodsTabPage); } quantitationMethodsTabPanel.TabPages.Remove(isobaricSampleMappingTabPage); }
public Message ApplyAndDisplay(ArcadeUser user) { var builder = new MessageBuilder(); var embedder = new Embedder(); string icon = "💸"; string type = "+"; string quote = Replies.GetReply(Flag, user, this); long value = Reward; ImmutableColor color = ImmutableColor.GammaGreen; Var.Add(user, 1, GimiStats.TimesPlayed); switch (Flag) { case GimiResultFlag.Win: case GimiResultFlag.Gold: Var.Clear(user, GimiStats.CurrentCurseStreak, GimiStats.CurrentLossStreak, GimiStats.CurrentLossAmount); Var.Add(user, 1, GimiStats.TimesWon, GimiStats.CurrentWinStreak); Var.Add(user, Reward, GimiStats.TotalWon, GimiStats.CurrentWinAmount); Var.SetIfGreater(user, GimiStats.LongestWin, GimiStats.CurrentWinStreak); Var.SetIfGreater(user, GimiStats.LargestWin, GimiStats.CurrentWinAmount); if (Flag == GimiResultFlag.Gold) { icon = "💎"; type = "+"; color = GammaPalette.Glass[Gamma.Max]; ItemHelper.GiveItem(user, Items.PocketLawyer); if (RandomProvider.Instance.Next(0, 1001) == 1000) { ItemHelper.GiveItem(user, Items.PaletteGold); } Var.Add(user, 1, GimiStats.TimesGold, GimiStats.CurrentGoldStreak); Var.SetIfGreater(user, GimiStats.LongestGold, GimiStats.CurrentGoldStreak); } else { Var.Clear(user, GimiStats.CurrentGoldStreak); Reward = CurrencyHelper.BoostValue(user, Reward, BoostType.Money); } long debt = user.Debt; user.Give(Reward); if (debt > Reward) { icon = "📃"; type = "-"; quote = Replies.Recover.Length > 0 ? (string)Randomizer.Choose(Replies.Recover) : Replies.RecoverGeneric; } else if (debt > 0 && Reward - debt == 0) { icon = "📧"; type = ""; quote = Replies.EvenGeneric; } break; case GimiResultFlag.Lose: case GimiResultFlag.Curse: type = "-"; color = ImmutableColor.NeonRed; Var.Clear(user, GimiStats.CurrentGoldStreak, GimiStats.CurrentWinStreak, GimiStats.CurrentWinAmount); Var.Add(user, 1, GimiStats.TimesLost, GimiStats.CurrentLossStreak); Var.Add(user, Reward, GimiStats.TotalLost, GimiStats.CurrentLossAmount); Var.SetIfGreater(user, GimiStats.LongestLoss, GimiStats.CurrentLossStreak); Var.SetIfGreater(user, GimiStats.LargestLoss, GimiStats.CurrentLossAmount); if (Flag == GimiResultFlag.Curse) { icon = "🌕"; type = "-"; color = GammaPalette.Alconia[Gamma.Standard]; Var.Add(user, 1, GimiStats.TimesCursed, GimiStats.CurrentCurseStreak); Var.SetIfGreater(user, GimiStats.LongestCurse, GimiStats.CurrentCurseStreak); } else { Var.Clear(user, GimiStats.CurrentCurseStreak); Reward = CurrencyHelper.BoostValue(user, Reward, BoostType.Money); } long balance = user.Balance; user.Take(Reward); if (balance < Reward) { icon = "📃"; type = "+"; value = Reward - balance; quote = Replies.Debt.Length > 0 ? (string)Randomizer.Choose(Replies.Debt) : Replies.DebtGeneric; } else if (balance > 0 && Reward - balance == 0) { icon = "📧"; value = Reward - balance; type = ""; quote = Replies.EvenGeneric; } break; } if (!string.IsNullOrWhiteSpace(type)) { type += ' '; } string header = $"**{type}{icon} {value:##,0}**"; string content = $"*\"{quote}\"*"; embedder.Header = header; embedder.Color = color; builder.Embedder = embedder; builder.Content = content; return(builder.Build()); }
public void EM0013() { var tmpdir = Xamarin.Cache.CreateTemporaryDirectory(); var csfile = Path.Combine(tmpdir, "foo.cs"); var dllfile = Path.Combine(tmpdir, "foo.dll"); File.WriteAllText(csfile, @"public class C { public Foundation.NSObject F () { throw new System.NotImplementedException (); } }"); Asserts.RunProcess("/Library/Frameworks/Mono.framework/Commands/csc", $"/target:library /out:{Embedder.Quote (dllfile)} {Embedder.Quote (csfile)} -r:/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/lib/mono/Xamarin.iOS/Xamarin.iOS.dll", "compile dll"); Asserts.ThrowsEmbeddinatorException(13, "Can't find the assembly 'Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065', referenced by 'foo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", () => Driver.Main2(dllfile, "--platform=tvOS", "--outdir=" + tmpdir)); }
public static int Main2(params string [] args) { var action = Action.None; var embedder = new Embedder(); CurrentEmbedder = embedder; var os = new OptionSet { { "c|compile", "Compiles the generated output", v => embedder.CompileCode = true }, { "e|extension", "Compiles the generated output as extension safe api", v => embedder.Extension = true }, { "nativeexception", "Compiles the generated output to throw native exceptions (Apple only)", v => embedder.NativeException = true }, { "bitcode=", "Compiles the generated output with bitcode (default, true, false)", v => embedder.SetBitcode(v) }, { "d|debug", "Build the native library with debug information.", v => embedder.Debug = true }, { "gen=", $"Target generator (default {embedder.TargetLanguage})", v => embedder.SetTarget(v) }, { "abi=", "A comma-separated list of ABIs to compile. If not specified, all ABIs applicable to the selected platform will be built. Valid values (also depends on platform): i386, x86_64, armv7, armv7s, armv7k, arm64.", (v) => { embedder.ABIs.AddRange(v.Split(',').Select((a) => a.ToLowerInvariant())); } }, { "o|out|outdir=", "Output directory", v => embedder.OutputDirectory = v }, { "p|platform=", $"Target platform (iOS, macOS [default], macos-[modern|full|system], watchOS, tvOS)", v => embedder.SetPlatform(v) }, { "vs=", $"Visual Studio version for compilation (unsupported)", v => { throw new EmbeddinatorException(2, $"Option `--vs` is not supported"); } }, { "h|?|help", "Displays the help", v => action = Action.Help }, { "v|verbose", "generates diagnostic verbose output", v => ErrorHelper.Verbosity++ }, { "version", "Display the version information.", v => action = Action.Version }, { "target=", "The compilation target (staticlibrary, sharedlibrary, framework).", embedder.SetCompilationTarget }, { "warnaserror:", "An optional comma-separated list of warning codes that should be reported as errors (if no warnings are specified all warnings are reported as errors).", v => { try { if (!string.IsNullOrEmpty(v)) { foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error, int.Parse(code)); } } else { ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Error); } } catch (Exception ex) { ErrorHelper.Error(26, ex, "Could not parse the command line argument '{0}': {1}", "--warnaserror", ex.Message); } } }, { "nowarn:", "An optional comma-separated list of warning codes to ignore (if no warnings are specified all warnings are ignored).", v => { try { if (!string.IsNullOrEmpty(v)) { foreach (var code in v.Split(new char [] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable, int.Parse(code)); } } else { ErrorHelper.SetWarningLevel(ErrorHelper.WarningLevel.Disable); } } catch (Exception ex) { ErrorHelper.Error(26, ex, "Could not parse the command line argument '{0}': {1}", "--nowarn", ex.Message); } } }, }; var assemblies = os.Parse(args); if (action == Action.None && assemblies.Count > 0) { action = Action.Generate; } switch (action) { case Action.None: case Action.Help: Console.WriteLine($"Embeddinator-4000 {Info.Version} ({Info.Branch}: {Info.Hash})"); Console.WriteLine("Generates target language bindings for interop with managed code."); Console.WriteLine(""); Console.WriteLine($"Usage: objcgen [options]+ ManagedAssembly1.dll [ManagedAssembly2.dll ...]"); Console.WriteLine(); os.WriteOptionDescriptions(Console.Out); return(0); case Action.Version: Console.WriteLine($"Embeddinator-4000 v0.1 ({Info.Branch}: {Info.Hash})"); return(0); case Action.Generate: try { var result = embedder.Generate(assemblies); if (embedder.CompileCode && (result == 0)) { result = embedder.Compile(); } Console.WriteLine("Done"); return(result); } catch (NotImplementedException e) { throw new EmbeddinatorException(9, true, e, $"The feature `{e.Message}` is not currently supported by the tool"); } default: throw ErrorHelper.CreateError(99, "Internal error: invalid action {0}. Please file a bug report with a test case (https://github.com/mono/Embeddinator-4000/issues)", action); } }
public void XcodeBuildErrorTest(string directoryTest, string csprojName, string objcmFileName, Platform platform, Configuration config, string errorToSearch) { Assert.IsTrue(Directory.Exists(XcodeFolderPath), "XcodeFolderPath"); Assert.IsTrue(File.Exists(MonoMsBuildPath), "MonoMsBuildPath"); Assert.IsTrue(File.Exists(MonoPath), "MonoPath"); var testcaseBaseDir = Path.Combine(XcodeFolderPath, directoryTest); var tempWorkingDir = Xamarin.Cache.CreateTemporaryDirectory(); var e4kOutputDir = Path.Combine(tempWorkingDir, "E4KOutput"); Asserts.RunProcess(MonoMsBuildPath, $"/p:Configuration={config} /p:IntermediateOutputPath={Path.Combine (tempWorkingDir, "obj")}/ /p:OutputPath={Path.Combine (tempWorkingDir, "DllOutput")} {Path.Combine (testcaseBaseDir, csprojName)}.csproj", "msbuildProc"); var eargs = new List <string> { "-c", $"{Path.Combine (tempWorkingDir, "DllOutput", csprojName)}.dll", $"-o={e4kOutputDir}" }; if (config == Configuration.Debug) { eargs.Add("--debug"); } Driver.Main2(eargs.ToArray()); // Sadly no C# 7 yet // (string sdk, string arch, string sdkName, string minVersion) build_info; Tuple <string, string, string, string> build_info = null; switch (platform) { case Platform.macOS: build_info = new Tuple <string, string, string, string> ("MacOSX", "x86_64", "macosx", "10.7"); break; case Platform.iOS: build_info = new Tuple <string, string, string, string> ("iPhoneSimulator", "x86_64", "ios-simulator", "8.0"); break; case Platform.tvOS: build_info = new Tuple <string, string, string, string> ("AppleTVSimulator", "x86_64", "tvos-simulator", "9.0"); break; case Platform.watchOS: build_info = new Tuple <string, string, string, string> ("WatchSimulator", "i386", "watchos-simulator", "2.0"); break; } var clangArgs = new StringBuilder("clang "); if (config == Configuration.Debug) { clangArgs.Append("-g -O0 "); } else { clangArgs.Append("-O2 "); } clangArgs.Append("-fobjc-arc "); clangArgs.Append("-ObjC "); clangArgs.Append($"-arch {build_info.Item2} "); clangArgs.Append($"-isysroot {Embedder.XcodeApp}/Contents/Developer/Platforms/{build_info.Item1}.platform/Developer/SDKs/{build_info.Item1}.sdk "); clangArgs.Append($"-m{build_info.Item3}-version-min={build_info.Item4} "); clangArgs.Append($"-I{e4kOutputDir} "); clangArgs.Append($"-c {Path.Combine (testcaseBaseDir, objcmFileName)} "); clangArgs.Append($"-o {Path.Combine (tempWorkingDir, "foo.o")} "); // Embedder.RunProcess returns false if exitcode != 0 Assert.IsFalse(Embedder.RunProcess("xcrun", clangArgs.ToString(), out int exitCode, out string output, capture_stderr: true), "clangbuild"); Assert.That(output, Does.Contain(errorToSearch), $"Not found: {errorToSearch}"); }
public Message ApplyAndDisplay(ArcadeUser user) { ImmutableColor color = ImmutableColor.GammaGreen; string type = IsSuccess ? "+" : "-"; long value = IsSuccess ? Reward : Wager; user.AddToVar(TickStats.TotalBet, Wager); user.AddToVar(TickStats.TimesPlayed); user.ChipBalance -= Wager; switch (Flag) { case TickResultFlag.Exact: case TickResultFlag.Win: user.SetVar(TickStats.CurrentLossStreak, 0); user.AddToVar(TickStats.TimesWon); user.AddToVar(TickStats.TotalWon, Reward); if (ExpectedTick == ActualTick) { user.AddToVar(TickStats.TimesWonExact); } user.AddToVar(TickStats.CurrentWinStreak); user.AddToVar(TickStats.CurrentWinAmount, Reward); Var.SetIfGreater(user, TickStats.LongestWin, TickStats.CurrentWinStreak); Var.SetIfGreater(user, TickStats.LargestWin, TickStats.CurrentWinAmount); Var.SetIfGreater(user, TickStats.LargestWinSingle, Reward); break; case TickResultFlag.Lose: Var.Clear(user, TickStats.CurrentWinStreak, TickStats.CurrentWinAmount); user.AddToVar(TickStats.TimesLost); user.AddToVar(TickStats.CurrentLossStreak); break; default: throw new ArgumentOutOfRangeException(nameof(Flag)); } if (IsSuccess) { user.ChipBalance += CurrencyHelper.BoostValue(user, Reward, BoostType.Chips); } string header = $"**{type} 🧩 {value:##,0}**"; string content = Replies.GetReply(Flag, user, this); //GetQuote(ExpectedTick, ActualTick, Multiplier, Reward, IsSuccess); var embedder = new Embedder { Header = header, Color = color }; var builder = new MessageBuilder(); builder.WithEmbedder(embedder) .WithContent(content); return(builder.Build()); }