long Solve(string input, bool hasNat) { var machines = ( from address in Enumerable.Range(0, 50) select Nic(input, address) ).ToList(); var natAddress = 255; if (hasNat) { machines.Add(Nat(natAddress)); } var packets = new Packets(); while (!packets.Any(packet => packet.address == natAddress)) { foreach (var machine in machines) { packets = machine(packets); } } return(packets.Single(packet => packet.address == natAddress).y); }
private Unit GroupBy(Func <Cod, Cod, bool> equiparator, List <Cod> cods) { Unit unit = new Unit(); if (IsNullOrEmptyList(cods)) { return(unit); } Seq seq = new Seq(); unit.Add(seq); seq.Add(cods[0]); for (int i = 1; i < cods.Count; i++) { if (!equiparator(cods[i - 1], cods[i])) { seq = new Seq(); unit.Add(seq); } seq.Add(cods[i]); } return(unit); }
void TestLinq() { //magic!! var Scores = new SCG.List() { new { name = "Оля", score = 97 }, new { name = "Петя", score = 60 }, new { name = "Вася", score = 92 }, new { name = "Маша", score = 81 } }; // Create the query. var queryHighScores = from rec in Scores where rec.score > 80 orderby rec.score descending, rec.name select rec; // Execute the query. foreach (var rec in queryHighScores) { Console.WriteLine(rec); } Console.WriteLine(); }
/// <summary> /// Round splits to the nearest penny. /// </summary> /// <param name="amountSpent"></param> /// <returns>Item1 owes Item2 Item3 pennies</returns> /// <remarks> /// Over the course of splitting a bill people can end up owing a fractional number of pennies. /// Thie method rounds peoples debts to the nearest penny, while preserving the invarient that /// the total amount owed in this group of debts does not change. /// </remarks> List <(Person debtor, Person creditor, int pennies)> SplitPennies(MultiCreditorDebtList amountSpent) { var pennies = amountSpent .Select(tup => new { Debtor = tup.debtor, Debts = tup.debts.Select(debt => (creditor: debt.creditor, amount: (int)Math.Floor(debt.amount))).ToList(), PennyFraction = tup.debts.Select(debt => debt.amount - Math.Floor(debt.amount)).Sum() })
private void AddNativeLibraries(ArchiveFileList files, string [] supportedAbis) { var libs = NativeLibraries.Concat(BundleNativeLibraries ?? Enumerable.Empty <ITaskItem> ()) .Select(v => new LibInfo { Path = v.ItemSpec, Abi = GetNativeLibraryAbi(v) }); AddNativeLibraries(files, supportedAbis, libs); }
void AddNativeLibrary (ArchiveFileList files, string path, string abi, string archiveFileName) { string fileName = string.IsNullOrEmpty (archiveFileName) ? Path.GetFileName (path) : archiveFileName; var item = (filePath: path, archivePath: $"lib/{abi}/{fileName}"); if (files.Any (x => x.archivePath == item.archivePath)) { Log.LogCodedWarning ("XA4301", path, 0, Properties.Resources.XA4301, item.archivePath); return; } files.Add (item); }
private void AddAdditionalNativeLibraries (ArchiveFileList files, string [] supportedAbis) { if (AdditionalNativeLibraryReferences == null || !AdditionalNativeLibraryReferences.Any ()) return; var libs = AdditionalNativeLibraryReferences .Select (l => new LibInfo { Path = l.ItemSpec, Abi = AndroidRidAbiHelper.GetNativeLibraryAbi (l) }); AddNativeLibraries (files, supportedAbis, libs); }
/// <summary> 测试方法 耗时2.5s </summary> public static void LongTimeMethod() { var list2 = new Collections.Generic.List <string>(); for (int i = 0; i < 5000000; i++) { list2.Add(i.ToString()); } list2 = null; }
void AddNativeLibraries (ArchiveFileList files, string [] supportedAbis, System.Collections.Generic.IEnumerable<LibInfo> libs) { if (libs.Any (lib => lib.Abi == null)) Log.LogCodedWarning ( "XA4301", Properties.Resources.XA4301_ABI_Ignoring, string.Join (", ", libs.Where (lib => lib.Abi == null).Select (lib => lib.Path))); libs = libs.Where (lib => lib.Abi != null); libs = libs.Where (lib => supportedAbis.Contains (lib.Abi)); foreach (var info in libs) AddNativeLibrary (files, info.Path, info.Abi, info.ArchiveFileName); }
public static MinDifferenceSolutions FindMinDifferenceAfterModification( int[] ints, int k) { int min, max, minIndex, maxIndex; min = max = ints[0]; minIndex = maxIndex = 0; for (int i = 1; i < ints.Length; i++) { if (ints[i] < min) { (min, minIndex) = (ints[i], i); } if (ints[i] > max) { (max, maxIndex) = (ints[i], i); } } int diff = max - min; var solutions = new MinDifferenceSolutions(); if (diff <= k) { solutions.Add((diff, values: ints.Select(x => x + k).ToList())); solutions.Add((diff, values: ints.Select(x => x - k).ToList())); return(solutions); } if (minIndex != 0) { (ints[minIndex], ints[0]) = (ints[0], ints[minIndex]); } if (maxIndex != 1) { (ints[maxIndex], ints[1]) = (ints[1], ints[maxIndex]); } var currentSolution = ( diff : int.MaxValue, values : new List <int>() ); var choices = new Dictionary <int, int>(); FindMinDifferenceAfterModificationRecursively( ints, k, 0, max, min, currentSolution, choices, solutions ); return(solutions); }
void AddNativeLibrary(ArchiveFileList files, string path, string abi) { var item = (filePath : path, archivePath : $"lib/{abi}"); string filename = "/" + Path.GetFileName(item.filePath); string inArchivePath = item.archivePath + filename; if (files.Any(x => (x.archivePath + "/" + Path.GetFileName(x.filePath)) == inArchivePath)) { Log.LogCodedWarning("XA4301", path, 0, Properties.Resources.XA4301, inArchivePath); return; } files.Add(item); }
void AddNativeLibrary(ArchiveFileList files, string path, string abi) { var item = (filePath : path, archivePath : $"lib/{abi}"); string filename = "/" + Path.GetFileName(item.filePath); string inArchivePath = item.archivePath + filename; if (files.Any(x => (x.archivePath + "/" + Path.GetFileName(x.filePath)) == inArchivePath)) { Log.LogCodedWarning("XA4301", path, 0, $"Apk already contains the item {inArchivePath}; ignoring."); return; } files.Add(item); }
MultiCreditorDebtList SplitDebtsBetweenPayers(List <Debt> amountSpent) { var ret = new MultiCreditorDebtList(); foreach (var p in amountSpent) { var creditors = new List <(Person creditor, double amount)>(); foreach (var payer in mPayer) { creditors.Add((payer, p.Amount / mPayer.Length)); } ret.Add((p.Debtor, creditors)); } return(ret); }
private static (ILine first, ILine second) GetOverlapping(ILine first, ILine second) { var firstOverlap = new Line(); var secondOverlap = new Line(); foreach (var firstTilePosition in first) { var secondTilePosition = second.FirstOrDefault(tilePosition => tilePosition.Coordinates.IsOverlapping(firstTilePosition.Coordinates)); if (secondTilePosition != default(TilePosition)) { firstOverlap.Add(firstTilePosition); secondOverlap.Add(secondTilePosition); } } return(firstOverlap, secondOverlap); }
private int CompareSeq(Seq seq1, Seq seq2) { if (IsNullOrEmptyList(seq1) && IsNullOrEmptyList(seq2)) { return(0); } if (IsNullOrEmptyList(seq1)) { return(-1); } if (IsNullOrEmptyList(seq2)) { return(1); } return(seq1[0].Item2.CompareTo(seq2[0].Item2)); }
public DesiredShape ForLoop() { var counts = new Dictionary <string, int>(); foreach (var c in Customers) { counts.TryGetValue(c.State, out var count); counts[c.State] = count + 1; } var results = new DesiredShape(); foreach (var c in counts) { results.Add((c.Key, c.Value)); } return(results); }
private static Tiles ConnectDoorsViaConnectingLine(Tiles tilesWithUnconnectedDoors, ILine firstProjection, ILine secondProjection, ILine connectingLine) { var startOfConnectingLine = connectingLine.First(); var firstDoor = firstProjection.Single(tilePosition => tilesWithUnconnectedDoors.IsTileType <Door>(tilePosition.Coordinates)); var fromFirstToConnecting = ExtractLineBetween(firstProjection, firstDoor.Coordinates, startOfConnectingLine.Coordinates); var endOfConnectingLine = connectingLine.Last(); var secondDoor = secondProjection.Single(tilePosition => tilesWithUnconnectedDoors.IsTileType <Door>(tilePosition.Coordinates)); var fromConnectingToSecond = ExtractLineBetween(secondProjection, secondDoor.Coordinates, endOfConnectingLine.Coordinates); var finalRoute = new Line(); finalRoute.AddRange(fromFirstToConnecting); finalRoute.AddRange(connectingLine.Select(Tunnel)); finalRoute.AddRange(fromConnectingToSecond); var stateChange = finalRoute.ToTilesState(); var tilesWithNewlyConnectedDoors = tilesWithUnconnectedDoors.Clone(stateChange); return(tilesWithNewlyConnectedDoors); }
void AddNativeLibraries(ArchiveFileList files, string [] supportedAbis, System.Collections.Generic.IEnumerable <LibInfo> libs) { if (libs.Any(lib => lib.Abi == null)) { Log.LogCodedWarning( "XA4301", "Could not determine abi of some native libraries, ignoring those: " + string.Join(", ", libs.Where(lib => lib.Abi == null).Select(lib => lib.Path))); } libs = libs.Where(lib => lib.Abi != null); libs = libs.Where(lib => supportedAbis.Contains(lib.Abi)); foreach (var arm in ArmAbis) { foreach (var info in libs.Where(lib => lib.Abi == arm)) { AddNativeLibrary(files, info.Path, info.Abi); } } foreach (var info in libs.Where(lib => !ArmAbis.Contains(lib.Abi))) { AddNativeLibrary(files, info.Path, info.Abi); } }
private static TilesChange StateChangeForInput(DispatchRegistry registry, IList <string> lines) { var tilesChanged = new TilesChange(); var row = 0; foreach (var line in lines) { var column = 0; foreach (var actorChar in line) { var coordinates = new Coordinate(row, column); var actor = ActorBuilder.Build(actorChar, coordinates, registry); tilesChanged.Add((actor?.UniqueId, coordinates)); column++; } row++; } return(tilesChanged); }
private List <int> ListExt(Seq seq) { return(ListComprehension(seq, (Cod cod) => cod.Item3)); }
private void AddNativeLibraries(ArchiveFileList files, string [] supportedAbis) { var frameworkLibs = FrameworkNativeLibraries.Select(v => new LibInfo { Path = v.ItemSpec, Link = v.GetMetadata("Link"), Abi = GetNativeLibraryAbi(v), ArchiveFileName = GetArchiveFileName(v) }); AddNativeLibraries(files, supportedAbis, frameworkLibs); var libs = NativeLibraries.Concat(BundleNativeLibraries ?? Enumerable.Empty <ITaskItem> ()) .Where(v => IncludeNativeLibrary(v)) .Select(v => new LibInfo { Path = v.ItemSpec, Link = v.GetMetadata("Link"), Abi = GetNativeLibraryAbi(v), ArchiveFileName = GetArchiveFileName(v) } ); AddNativeLibraries(files, supportedAbis, libs); if (String.IsNullOrWhiteSpace(CheckedBuild)) { return; } string mode = CheckedBuild; string sanitizerName; if (String.Compare("asan", mode, StringComparison.Ordinal) == 0) { sanitizerName = "asan"; } else if (String.Compare("ubsan", mode, StringComparison.Ordinal) == 0) { sanitizerName = "ubsan_standalone"; } else { LogSanitizerWarning($"Unknown checked build mode '{CheckedBuild}'"); return; } if (!IncludeWrapSh) { LogSanitizerError("Checked builds require the wrapper script to be packaged. Please set the `$(AndroidIncludeWrapSh)` MSBuild property to `true` in your project."); return; } if (!libs.Any(info => IsWrapperScript(info.Path, info.Link))) { LogSanitizerError($"Checked builds require the wrapper script to be packaged. Please add `wrap.sh` appropriate for the {CheckedBuild} checker to your project."); return; } NdkUtil.Init(AndroidNdkDirectory); string clangDir = NdkUtil.GetClangDeviceLibraryPath(AndroidNdkDirectory); if (String.IsNullOrEmpty(clangDir)) { LogSanitizerError($"Unable to find the clang compiler directory. Is NDK installed?"); return; } foreach (string abi in supportedAbis) { string clangAbi = MonoAndroidHelper.MapAndroidAbiToClang(abi); if (String.IsNullOrEmpty(clangAbi)) { LogSanitizerError($"Unable to map Android ABI {abi} to clang ABI"); return; } string sanitizerLib = $"libclang_rt.{sanitizerName}-{clangAbi}-android.so"; string sanitizerLibPath = Path.Combine(clangDir, sanitizerLib); if (!File.Exists(sanitizerLibPath)) { LogSanitizerError($"Unable to find sanitizer runtime for the {CheckedBuild} checker at {sanitizerLibPath}"); return; } AddNativeLibrary(files, sanitizerLibPath, abi, sanitizerLib); } }
void ExecuteWithAbi(string [] supportedAbis, string apkInputPath, string apkOutputPath, bool debug, bool compress, IDictionary <string, CompressedAssemblyInfo> compressedAssembliesInfo) { if (InterpreterEnabled) { foreach (string abi in supportedAbis) { if (String.Compare("x86", abi, StringComparison.OrdinalIgnoreCase) == 0) { Log.LogCodedError("XA0124", Properties.Resources.XA0124); return; } } } ArchiveFileList files = new ArchiveFileList(); bool refresh = true; if (apkInputPath != null && File.Exists(apkInputPath) && !File.Exists(apkOutputPath)) { Log.LogDebugMessage($"Copying {apkInputPath} to {apkInputPath}"); File.Copy(apkInputPath, apkOutputPath, overwrite: true); refresh = false; } using (var apk = new ZipArchiveEx(apkOutputPath, File.Exists(apkOutputPath) ? FileMode.Open : FileMode.Create)) { if (refresh) { for (long i = 0; i < apk.Archive.EntryCount; i++) { ZipEntry e = apk.Archive.ReadEntry((ulong)i); Log.LogDebugMessage($"Registering item {e.FullName}"); existingEntries.Add(e.FullName); } } if (apkInputPath != null && File.Exists(apkInputPath) && refresh) { var lastWriteOutput = File.Exists(apkOutputPath) ? File.GetLastWriteTimeUtc(apkOutputPath) : DateTime.MinValue; var lastWriteInput = File.GetLastWriteTimeUtc(apkInputPath); using (var packaged = new ZipArchiveEx(apkInputPath, FileMode.Open)) { foreach (var entry in packaged.Archive) { // NOTE: aapt2 is creating zip entries on Windows such as `assets\subfolder/asset2.txt` var entryName = entry.FullName; if (entryName.Contains("\\")) { entryName = entryName.Replace('\\', '/'); Log.LogDebugMessage($"Fixing up malformed entry `{entry.FullName}` -> `{entryName}`"); } Log.LogDebugMessage($"Deregistering item {entryName}"); existingEntries.Remove(entryName); if (lastWriteInput <= lastWriteOutput) { continue; } if (apk.Archive.ContainsEntry(entryName)) { ZipEntry e = apk.Archive.ReadEntry(entryName); // check the CRC values as the ModifiedDate is always 01/01/1980 in the aapt generated file. if (entry.CRC == e.CRC && entry.CompressedSize == e.CompressedSize) { Log.LogDebugMessage($"Skipping {entryName} from {apkInputPath} as its up to date."); continue; } } var ms = new MemoryStream(); entry.Extract(ms); Log.LogDebugMessage($"Refreshing {entryName} from {apkInputPath}"); apk.Archive.AddStream(ms, entryName, compressionMethod: entry.CompressionMethod); } } } apk.FixupWindowsPathSeparators((a, b) => Log.LogDebugMessage($"Fixing up malformed entry `{a}` -> `{b}`")); // Add classes.dx foreach (var dex in DalvikClasses) { string apkName = dex.GetMetadata("ApkName"); string dexPath = string.IsNullOrWhiteSpace(apkName) ? Path.GetFileName(dex.ItemSpec) : apkName; AddFileToArchiveIfNewer(apk, dex.ItemSpec, DalvikPath + dexPath); } if (EmbedAssemblies && !BundleAssemblies) { AddAssemblies(apk, debug, compress, compressedAssembliesInfo); } AddRuntimeLibraries(apk, supportedAbis); apk.Flush(); AddNativeLibraries(files, supportedAbis); AddAdditionalNativeLibraries(files, supportedAbis); if (TypeMappings != null) { foreach (ITaskItem typemap in TypeMappings) { AddFileToArchiveIfNewer(apk, typemap.ItemSpec, RootPath + Path.GetFileName(typemap.ItemSpec), compressionMethod: UncompressedMethod); } } int count = 0; foreach (var file in files) { var item = Path.Combine(file.archivePath.Replace(Path.DirectorySeparatorChar, '/')); existingEntries.Remove(item); CompressionMethod compressionMethod = GetCompressionMethod(file.filePath); if (apk.SkipExistingFile(file.filePath, item, compressionMethod)) { Log.LogDebugMessage($"Skipping {file.filePath} as the archive file is up to date."); continue; } Log.LogDebugMessage("\tAdding {0}", file.filePath); apk.Archive.AddFile(file.filePath, item, compressionMethod: compressionMethod); count++; if (count >= ZipArchiveEx.ZipFlushFilesLimit) { apk.Flush(); count = 0; } } var jarFiles = (JavaSourceFiles != null) ? JavaSourceFiles.Where(f => f.ItemSpec.EndsWith(".jar")) : null; if (jarFiles != null && JavaLibraries != null) { jarFiles = jarFiles.Concat(JavaLibraries); } else if (JavaLibraries != null) { jarFiles = JavaLibraries; } var libraryProjectJars = MonoAndroidHelper.ExpandFiles(LibraryProjectJars) .Where(jar => !MonoAndroidHelper.IsEmbeddedReferenceJar(jar)); var jarFilePaths = libraryProjectJars.Concat(jarFiles != null ? jarFiles.Select(j => j.ItemSpec) : Enumerable.Empty <string> ()); jarFilePaths = MonoAndroidHelper.DistinctFilesByContent(jarFilePaths); count = 0; foreach (var jarFile in jarFilePaths) { using (var stream = File.OpenRead(jarFile)) using (var jar = ZipArchive.Open(stream)) { foreach (var jarItem in jar) { if (jarItem.IsDirectory) { continue; } var name = jarItem.FullName; if (!PackagingUtils.CheckEntryForPackaging(name)) { continue; } var path = RootPath + name; existingEntries.Remove(path); if (apk.SkipExistingEntry(jarItem, path)) { Log.LogDebugMessage($"Skipping {path} as the archive file is up to date."); continue; } if (apk.Archive.Any(e => e.FullName == path)) { Log.LogDebugMessage("Failed to add jar entry {0} from {1}: the same file already exists in the apk", name, Path.GetFileName(jarFile)); continue; } byte [] data; using (var d = new MemoryStream()) { jarItem.Extract(d); data = d.ToArray(); } Log.LogDebugMessage($"Adding {path} as the archive file is out of date."); apk.Archive.AddEntry(data, path); } } count++; if (count >= ZipArchiveEx.ZipFlushFilesLimit) { apk.Flush(); count = 0; } } // Clean up Removed files. foreach (var entry in existingEntries) { Log.LogDebugMessage($"Removing {entry} as it is not longer required."); apk.Archive.DeleteEntry(entry); } apk.Flush(); FixupArchive(apk); } }
private void Bar() { List list1 = null; System.Collections.Generic.List list2 = null; }
/// <summary> /// Aggregates the indexed calendar items into buckets. Each bucket contains the sequence of overlapping items. /// The items in a bucket don't overlap all with each other, but cannot overlap with items in other buckets. /// </summary> /// <param name="buckets">The list of agregated items</param> /// <param name="indexedItem">The item to put in a bucket</param> /// <returns>A list of buckets</returns> private CalendarItemGroups groupOverlappingItems( CalendarItemGroups buckets, (CalendarItem Item, int Index) indexedItem)
private Tree MapTreeToSeqGaps(Tree tree) { return(MapList(tree, (Unit unit) => MergeUnits(unit, ListComprehension(Gaps(ListSeq(unit)), (int s) => new Seq { (unit[0][0].Item1, s, 0) }))));
public virtual async Task <JobList> CreateJobsAsync(Rule rule, DomainId ruleId, Envelope <IEvent> @event, bool ignoreStale = true) { Guard.NotNull(rule, nameof(rule)); Guard.NotNull(@event, nameof(@event)); var result = new JobList(); try { if (!rule.IsEnabled) { return(result); } if (!(@event.Payload is AppEvent)) { return(result); } var typed = @event.To <AppEvent>(); if (typed.Payload.FromRule) { return(result); } var actionType = rule.Action.GetType(); if (!ruleTriggerHandlers.TryGetValue(rule.Trigger.GetType(), out var triggerHandler)) { return(result); } if (!ruleActionHandlers.TryGetValue(actionType, out var actionHandler)) { return(result); } var now = clock.GetCurrentInstant(); var eventTime = @event.Headers.ContainsKey(CommonHeaders.Timestamp) ? @event.Headers.Timestamp() : now; if (ignoreStale && eventTime.Plus(Constants.StaleTime) < now) { return(result); } var expires = now.Plus(Constants.ExpirationTime); if (!triggerHandler.Trigger(typed.Payload, rule.Trigger, ruleId)) { return(result); } var appEventEnvelope = @event.To <AppEvent>(); var enrichedEvents = await triggerHandler.CreateEnrichedEventsAsync(appEventEnvelope); foreach (var enrichedEvent in enrichedEvents) { try { await eventEnricher.EnrichAsync(enrichedEvent, typed); if (!triggerHandler.Trigger(enrichedEvent, rule.Trigger)) { continue; } var actionName = typeNameRegistry.GetName(actionType); var job = new RuleJob { Id = DomainId.NewGuid(), ActionData = string.Empty, ActionName = actionName, AppId = enrichedEvent.AppId.Id, Created = now, EventName = enrichedEvent.Name, ExecutionPartition = enrichedEvent.Partition, Expires = expires, RuleId = ruleId }; try { var(description, data) = await actionHandler.CreateJobAsync(enrichedEvent, rule.Action); var json = jsonSerializer.Serialize(data); job.ActionData = json; job.ActionName = actionName; job.Description = description; result.Add((job, null)); } catch (Exception ex) { job.Description = "Failed to create job"; result.Add((job, ex)); } } catch (Exception ex) { log.LogError(ex, w => w .WriteProperty("action", "createRuleJobFromEvent") .WriteProperty("status", "Failed")); } } } catch (Exception ex) { log.LogError(ex, w => w .WriteProperty("action", "createRuleJob") .WriteProperty("status", "Failed")); } return(result); }
private Unit MapUnitToExtGaps(Unit unit) { return(MapList(unit, (Seq seq) => ListComprehension(Gaps(ListExt(seq)), (int e) => (seq[0].Item1, seq[0].Item2, e)))); }
private Tree MapTreeToExtGaps(Tree tree) { return(MapList(tree, (Unit unit) => MapUnitToExtGaps(unit))); }
private Tree MapTreeToGaps(Tree tree) { return(MapTreeToSeqGaps(MapTreeToExtGaps(tree))); }
private void SortSeqs(Unit unit) { unit.Sort((Seq seq1, Seq seq2) => CompareSeq(seq1, seq2)); }