Project Name File Name Usage Source Code Link
Hermod AutoDiscovery.cs Parallel.ForEach(Directory.GetFiles(_Path), _ActualFile => { var _FileInfo = new FileInfo(_ActualFile); if (myFileExtensions.Contains(_FileInfo.Extension)) _ConcurrentBag.Add(_FileInfo.FullName); }) Link To Source File
Hermod AutoDiscovery.cs #endregion #region Scan files of implementations of T Parallel.ForEach(_ConcurrentBag, _File => { // Seems to be a mono bug! if (_File != null) { Console.WriteLine(_File); try { if (_File != null) foreach (var _ActualType in Assembly.LoadFrom(_File).GetTypes()) { if (!_ActualType.IsAbstract && _ActualType.IsPublic && _ActualType.IsVisible) { var _ActualTypeGetInterfaces = _ActualType.GetInterfaces(); if (_ActualTypeGetInterfaces != null) { foreach (var _Interface in _ActualTypeGetInterfaces) { if (_Interface == typeof(T)) { try { var __Id = _ActualType.Name; if (myIdentificator != null) __Id = myIdentificator(_ActualType); if (__Id != null && __Id != String.Empty) _TypeDictionary.TryAdd(__Id, _ActualType); } catch (Exception e) { throw new AutoDiscoveryException("Could not activate or register " + typeof(T).Name + "-instance '" + _ActualType.Name + "'!", e); } } } } } } } catch (Exception e) { throw new AutoDiscoveryException("Autodiscovering implementations of interface '" + typeof(T).Name + "' within file '" + _File + "' failed!", e); } } }) Link To Source File
Illias AutoDiscovery.cs Parallel.ForEach(Directory.GetFiles(_Path), _ActualFile => { var _FileInfo = new FileInfo(_ActualFile); if (myFileExtensions.Contains(_FileInfo.Extension)) _ConcurrentBag.Add(_FileInfo.FullName); }) Link To Source File
Illias AutoDiscovery.cs #endregion #region Scan files of implementations of T Parallel.ForEach(_ConcurrentBag, _File => { // Seems to be a mono bug! if (_File != null) { Console.WriteLine(_File); try { if (_File != null) foreach (var _ActualType in Assembly.LoadFrom(_File).GetTypes()) { if (!_ActualType.IsAbstract && _ActualType.IsPublic && _ActualType.IsVisible) { var _ActualTypeGetInterfaces = _ActualType.GetInterfaces(); if (_ActualTypeGetInterfaces != null) { foreach (var _Interface in _ActualTypeGetInterfaces) { if (_Interface == typeof(T)) { try { var __Id = _ActualType.Name; if (myIdentificator != null) __Id = myIdentificator(_ActualType); if (__Id != null && __Id != String.Empty) _TypeDictionary.TryAdd(__Id, _ActualType); } catch (Exception e) { throw new AutoDiscoveryException("Could not activate or register " + typeof(T).Name + "-instance '" + _ActualType.Name + "'!", e); } } } } } } } catch (Exception e) { throw new AutoDiscoveryException("Autodiscovering implementations of interface '" + typeof(T).Name + "' within file '" + _File + "' failed!", e); } } }) Link To Source File
Crm2011SolutionComparer Label.cs Parallel.ForEach(labels, (localizedLabel) => AddLocalizedLabel(localizedLabel)) Link To Source File
FlexTime.Plugins TimeTargetView.xaml.cs Parallel.ForEach(timeTargets, Refresh) Link To Source File
siren LastFMUpdater.cs Parallel.ForEach(artistUpdates, new ParallelOptions { MaxDegreeOfParallelism = 4 }, delegate(Artist artist) { var update = UpdateArtist(artist); lock (lockObj) info.Add(update); }) Link To Source File
siren LastFMUpdater.cs Parallel.ForEach(toUpdate, new ParallelOptions {MaxDegreeOfParallelism = 4}, (album) => { using (var repo = DataAccessContext.GetRepository()) { var artistName = repo.Artists.Where(x => x.Id == album.ArtistId).First().Name; var image = API.Album.GetInfo(album.Id, artistName, album.Name).Images[ImageSize.ExtraLarge]; if (image.Length == 0) return; var client = new WebClient(); var bytes = client.DownloadData(image); Binary imgData; BitmapImage bitmap; int height; int width; try { bitmap = ImageUtilities.ImageFromBuffer(bytes); height = (int) bitmap.Height; width = (int) bitmap.Width; imgData = new Binary(bytes); } catch (Exception e) { try { bitmap = ImageUtilities.ImageFromGDIPlus(bytes); height = (int) bitmap.Height; width = (int) bitmap.Width; var b = ImageUtilities.BufferFromImage(bitmap); //var fs = File.OpenRead(@"C:/Temp/" + guid + ".bmp"); //var b = new byte[fs.Length]; //fs.Read(b, 0, (int) fs.Length); //fs.Close(); imgData = new Binary(b); } catch (Exception e1) { return; } } var img = new Image { Id = Guid.NewGuid(), Size = (int) ImageSize.ExtraLarge, Height = height, Width = width, ImageData = imgData, Url = image, LinkedId = album.Id }; repo.Images.InsertOnSubmit(img); repo.SubmitChanges(); } ReportProgress(100, album); } ) Link To Source File
siren LastFMUpdater.cs Parallel.ForEach(toUpdate, new ParallelOptions {MaxDegreeOfParallelism = 4}, delegate(Artist a) { var image = API.Artist.GetImages(a.Name, 10); foreach (var i in image.ImageUrls) { var client = new WebClient(); var bytes = client.DownloadData(i.Value); Binary imgData; BitmapImage bitmap; int height; int width; try { bitmap = ImageUtilities.ImageFromBuffer(bytes); height = (int) bitmap.Height; width = (int) bitmap.Width; imgData = new Binary(bytes); } catch (Exception e) { try { bitmap = ImageUtilities.ImageFromGDIPlus(bytes); height = (int) bitmap.Height; width = (int) bitmap.Width; var b = ImageUtilities.BufferFromImage(bitmap); //var fs = File.OpenRead(@"C:/Temp/" + guid + ".bmp"); //var b = new byte[fs.Length]; //fs.Read(b, 0, (int) fs.Length); //fs.Close(); imgData = new Binary(b); } catch (Exception e1) { return; } } using (var repo = DataAccessContext.GetRepository()) { var img = new Image { Id = Guid.NewGuid(), Size = (int) i.Key, Height = height, Width = width, ImageData = imgData, Url = i.Value, LinkedId = a.Id }; repo.Images.InsertOnSubmit(img); repo.SubmitChanges(); } } ReportProgress(100, a); }) Link To Source File
siren RepositoryScanner.cs Parallel.ForEach(paths, new ParallelOptions {MaxDegreeOfParallelism = 15}, delegate(string path) { var repo = DataAccessContext.GetRepository(); pathCount += 1; ReportProgress( CalculatePercentage(pathCount, paths.Count, repositoryCount, totalRepositories), new RepositoryScannerState {CurrentPath = path, CurrentRepository = repository.Location}); var mediaFile = repo.MediaFiles.FirstOrDefault(x => x.FullPath == path); Track track; if (mediaFile != null) { if (mediaFile.LastModified < (new FileInfo(mediaFile.FullPath)).LastWriteTime.AddMinutes(-1)) { track = repo.Tracks.First(x => x.Id == mediaFile.TrackId); //Update Track metadata ProcessTrack(path, ref track, ref repo); repo.SubmitChanges(); } } else { track = new Track {Id = Guid.NewGuid()}; //Update Track metadata ProcessTrack(path, ref track, ref repo); repo.Tracks.InsertOnSubmit(track); repo.SubmitChanges(); var file = new FileInfo(path); mediaFile = new MediaFile { Id = Guid.NewGuid(), RepositoryId = repository.Id, FullPath = path, DateAdded = DateTime.Now, LastModified = file.LastWriteTime, FileType = file.Extension, Size = file.Length, TrackId = track.Id }; repo.MediaFiles.InsertOnSubmit(mediaFile); repo.SubmitChanges(); } }) Link To Source File
doc-db VowelCalc.cs Parallel.ForEach(source, sourceItem => { foreach (var mapResult in map(sourceItem)) { mapResults.Add(mapResult); } }) Link To Source File
doc-db VowelCalc.cs Parallel.ForEach(reduceSources, reduceItem => resultCollection.Add(reduce(reduceItem))) Link To Source File
lucene.net SimpleFacetedSearch.cs //SETP 3 //create a single BitSet for each combination //BitSet1: A AND I AND 1 //BitSet2: A AND I AND 2 etc. //and remove impossible comb's (for ex, B J 3) from list. Parallel.ForEach(cp, combinations => { OpenBitSetDISI bitSet = new OpenBitSetDISI(_Reader.MaxDoc()); bitSet.Set(0, bitSet.Size()); List comb = combinations.ToList(); for (int j = 0; j < comb.Count; j++) { bitSet.And(fieldValuesBitSets[j].FieldValueBitSetPair[comb[j]]); } //STEP 3 if (bitSet.Cardinality() > 0) { lock(_Groups) _Groups.Add(new KeyValuePair, OpenBitSetDISI>(comb, bitSet)); } }) Link To Source File
stahc Utilities.cs Parallel.ForEach(stagingFiles.ListBlobs(), options, blob => { // get the url var fileName = Path.GetFileName(blob.Uri.ToString()); var localPath = Path.Combine(targetPath, fileName); var blockBlob = container.GetBlockBlobReference(blob.Uri.ToString()); //blockBlob.DownloadToFile(localPath, new BlobRequestOptions() { Timeout = TimeSpan.FromSeconds(180) }); blockBlob.ParallelDownloadToFile(localPath, 4194304); OnFileDownloaded(new StachFileDownloadEventArgs() { FileName = fileName }); blockBlob = null; }) Link To Source File
nCQRS TableOnlyStore.cs Parallel.ForEach( eventStream.Select(es => es.EventSourceId).Distinct(), (eventSourceId) => SaveEvents(eventSourceId, eventStream.Where(es => es.EventSourceId == eventSourceId)) ) Link To Source File
Super2013 TableOnlyStore.cs Parallel.ForEach( eventStream.Select(es => es.EventSourceId).Distinct(), (eventSourceId) => SaveEvents(eventSourceId, eventStream.Where(es => es.EventSourceId == eventSourceId)) ) Link To Source File
Bootstrapper-Sample IVhptHeartbeatGenerator.cs Parallel.ForEach(awares, aware => aware.Bumm()) Link To Source File
Bootstrapper-Sample IVphtMessageBus.cs Parallel.ForEach(this.supportedHandlers, (pair, state) => { if (pair.Key.IsAssignableFrom(messageType)) { pair.Value.Invoke(target, new[] { message }); Console.WriteLine("MessageBus: {0} was sent.", message); state.Break(); } }) Link To Source File
sable-fx EditGraphInstance.cs Parallel.ForEach(renderList, renderItem => { var ri = renderItem.Owner as EditGeometry; if (ri != null) { var rci = new RayCastInfo { EditElement = ri }; if (filter == null || filter(ri)) { if (ri.SourceVisualInstance != null) { ray.ForEachIntersection(ri.SourceVisualInstance, (Action) hitAction, rci, false); } else { if (filter == null || filter(ri.SourceVisual)) { var osRay = ray.Transform(ri.DisplayObject.WorldTransform.Inverse.Matrix); Ray3IntersectionExtensions.ForEachIntersection(osRay, (IAbstractVisual)ri.SourceVisual, (Action ) hitAction, rci, ri.DisplayObject.WorldTransform, false); } } } } }) Link To Source File
sable-fx EditGraphInstance.cs Parallel.ForEach(renderList, renderItem => { var ri = renderItem.Owner as EditGeometry; if (ri != null && (filter == null || filter(ri))) { Sable.SceneGraph.RayCastInfo rci; if (ri.SourceVisualInstance != null) { if (filter == null || filter(ri.SourceVisualInstance)) if (ray.IntersectionTest(ri.SourceVisualInstance, out rci, filter, false)) hitInfoList.Push(new RayCastInfo(rci, ri)); } else { if (filter == null || filter(ri.SourceVisual)) { var osRay = ray.Transform(ri.DisplayObject.WorldTransform.Inverse.Matrix); if (osRay.IntersectionTest(ri.SourceVisual, out rci, filter, false)) hitInfoList.Push(new RayCastInfo(rci, ri)); } } } }) Link To Source File
sable-fx EditGraphInstance.cs Parallel.ForEach(renderList .Where(ri => ri.Owner != null && ri.Owner is EditElement && ((EditElement)ri.Owner).SourceVisual != null) .SelectMany(ri => ((IEnumerable)((EditElement)ri.Owner).SourceVisual.VisualChildren)), primitive => { var selIndexes = new List[1]; ray.ForEachIntersectionTriangles((IHasTriangles)primitive, hrci => { if (selIndexes[0] == null) selIndexes[0] = new List(); selIndexes[0].Add(hrci.TargetPrimitiveIndex); }, new RayCastInfo(), null, false); if (selIndexes[0] != null) { var selEntity = ((IArraySelectable)primitive).GetSelectionTargetEntity(PrimitiveIds.Triangles); lock (newSelection) { newSelection.Add(selEntity); newSelIndexes.Add(new CompressedIndexList(selIndexes[0])); } } }) Link To Source File
pedamorf TestConcurrentConversion.cs Parallel.ForEach(images, currentFile => { TestImage(currentFile); }) Link To Source File
pedamorf TestConcurrentConversion.cs Parallel.ForEach(documents, currentFile => { TestFile(currentFile); }) Link To Source File
sshnet Session.NET40.cs Parallel.ForEach( from m in this._messagesMetadata where m.Name == messageName select m, (item) => { item.Enabled = true; item.Activated = true; }) Link To Source File
sshnet Session.NET40.cs Parallel.ForEach( from m in this._messagesMetadata where m.Name == messageName select m, (item) => { item.Enabled = false; item.Activated = false; }) Link To Source File
c-raft Server.cs System.Threading.Tasks.Parallel.ForEach(authClients, (client) => client.SendPacket(packet)) Link To Source File
c-raft Server.cs Parallel.ForEach(nearbyClients, (client) => { client.SendPacket(packet); }) Link To Source File
c-raft Server.cs Parallel.ForEach(nearbyClients, (client) => { if (excludedClient != client) client.SendPacket(packet); else packet.Release(); }) Link To Source File
c-raft Server.cs Parallel.ForEach(nearbyClients, (client) => { if (excludedClient != client) { foreach (Packet packet in packets) client.SendPacket(packet); } else { foreach (Packet packet in packets) packet.Release(); } }) Link To Source File
c-raft WorldManager.cs Parallel.ForEach(Server.GetClients(), c => c.CheckAlive()) Link To Source File
c-raft WorldManager.cs Parallel.ForEach(Server.GetEntities().Where((entity) => entity.World == this), (e) => { e.Update(); }) Link To Source File
dextop DextopApplication.cs Parallel.ForEach(Modules, (m) => { m.Initialize(); }) Link To Source File
NGauge FromFroming.cs Parallel.ForEach(_listA, a => { foreach (var b in _listB) { foreach (var c in _listC) { var item = new DataTriplet(a, b, c); queue.Enqueue(item); } } }) Link To Source File
Life GameViewModel.cs Parallel.ForEach(Cells, vm => _assignNeighbors(vm)) Link To Source File
Life GameViewModel.cs Parallel.ForEach(Cells, vm => Settings.RulesManager.Evaluate(vm.Cell, vm.Context)) Link To Source File
Life GameViewModel.cs Parallel.ForEach(Cells, vm => { vm.Health = vm.Context.FutureHealth; vm.Context.FutureHealth = 0M; }) Link To Source File
Life RulesManager.cs Parallel.ForEach(Rules, r => { evaluated |= r.Evaluate(cell, context); }) Link To Source File
Plywood AwsHelpers.cs Parallel.ForEach(listResponse.S3Objects, folderObject => { using (var copyResponse = client.CopyObject(new CopyObjectRequest() { SourceBucket = context.BucketName, DestinationBucket = context.BucketName, SourceKey = folderObject.Key, DestinationKey = ".recycled/" + folderObject.Key, })) { } }) Link To Source File
Plywood AwsHelpers.cs Parallel.ForEach(listResponse.S3Objects, folderObject => { using (var deleteReponse = client.DeleteObject(new DeleteObjectRequest() { BucketName = context.BucketName, Key = folderObject.Key, })) { } }) Link To Source File
Plywood Program.cs Parallel.ForEach(listResponse.S3Objects, s3obj => { using (var delResponse = client.DeleteObject(new Amazon.S3.Model.DeleteObjectRequest() { BucketName = context.BucketName, Key = s3obj.Key, })) { } }) Link To Source File
localtunnel-net-client Session.NET40.cs Parallel.ForEach( from m in this._messagesMetadata where m.Name == messageName select m, (item) => { item.Enabled = true; item.Activated = true; }) Link To Source File
localtunnel-net-client Session.NET40.cs Parallel.ForEach( from m in this._messagesMetadata where m.Name == messageName select m, (item) => { item.Enabled = false; item.Activated = false; }) Link To Source File
MaximusParserX ClientBuildInfo.cs Parallel.ForEach(names, name => { MaximusParserX.ClientBuild value; Enum.TryParse(name, out value); clientBuildList.Add((int)value, name.ToString().Replace("v", string.Empty).Replace("_", ".")); }) Link To Source File
Footloose MessageOriginator.cs Parallel.ForEach(messages, parallelOptions, msg => { if (!TrySendMessage(msg, cancellationTokenSource)) { logger.Debug( () => string.Format("[Task {0}] Message[{1}] '{2}' timed out. Canceling task!", Task.CurrentId, msg.Type, msg.Id)); cancellationTokenSource.Cancel(); } }) Link To Source File
Kata KnowledgeViewModel.cs Parallel.ForEach(Gurus, AddGuruToGuruViewModels) Link To Source File
Ganondorf Program.cs Parallel.ForEach( Enumerable.Range(1, TestIterations), x => { Stopwatch s = new Stopwatch(); s.Start(); var input = new ValueTypeTestClass { TestString = "Test String", TestInt = int.MaxValue, TestDecimal = decimal.MaxValue, TestFloat = float.MaxValue, TestDouble = double.MaxValue / 10d, TestLong = long.MaxValue, TestBool = true, TestShort = short.MaxValue, TestChar = 'Y', TestUnsignedInt = uint.MaxValue, TestUnsignedLong = ulong.MaxValue, TestUnsignedShort = ushort.MaxValue, TestByte = byte.MaxValue, TestSignedByte = sbyte.MaxValue, }; var qs = serialiser.Map(input); serialiser.Load(qs); s.Stop(); timings.Add(s.ElapsedMilliseconds); }) Link To Source File
CityIndexScreensaver MassStreamingTests.cs Parallel.ForEach(Const.MarketIds, options, marketId => { lock (sync) { var listener = streamingClient.BuildPricesListener(new[] { marketId }); listeners.Add(listener); listener.MessageReceived += listener_MessageReceived; listener.Start(); } Debug.WriteLine("item: {0}", i++); }) Link To Source File
ForgeCraft-OutDatedVersion World.cs Parallel.ForEach(w.chunkData.Keys, delegate(Point pt) { w.SaveChunk(pt.x, pt.z); }) Link To Source File
Bargains BattleNetCraftParser.cs Parallel.ForEach(((IEnumerable) Enum.GetValues(typeof (Profession))), prof => { foreach (Craft r in Parse(GetCraftPage(prof), prof)) reagents.Add(r); }) Link To Source File
Bargains WowheadIconDownloader.cs Parallel.ForEach(icons, (icon) => { var ba = GetIcon(icon, "http://wow.zamimg.com/images/wow/icons/small/{0}.jpg"); var iconStream = File.OpenWrite(String.Format("D://icons//small//{0}.jpg", icon)); var task = Task.Factory.FromAsync(iconStream.BeginWrite, iconStream.EndWrite, ba, 0, ba.Length, null); task.ContinueWith(c => iconStream.Close()); }) Link To Source File
Bargains WowheadIconDownloader.cs Parallel.ForEach(icons, (icon) => { var ba = GetIcon(icon, "http://wow.zamimg.com/images/wow/icons/large/{0}.jpg"); var iconStream = File.OpenWrite(String.Format("D://icons//large//{0}.jpg", icon)); var task = Task.Factory.FromAsync(iconStream.BeginWrite, iconStream.EndWrite, ba, 0, ba.Length, null); task.ContinueWith(c => iconStream.Close()); }) Link To Source File
RecommendationSystem NaiveTester.cs Parallel.ForEach(rss, rs => { switch (rs) { case "ar": var arrs = new AverageRatingRecommendationSystem(); var arModel = arrs.Trainer.TrainModel(TrainUsers, Artists, TrainRatings); var rv = TestRecommendationSystem(arrs, TestUsers, arModel, Artists); Write(string.Format("AverageRating: {0} ({1})", rv, arModel.AverageRating)); break; case "mr": var mrrs = new MedianRatingRecommendationSystem(); var mrModel = mrrs.Trainer.TrainModel(TrainUsers, Artists, TrainRatings); rv = TestRecommendationSystem(mrrs, TestUsers, mrModel, Artists); Write(string.Format("MedianRating: {0} ({1})", rv, mrModel.MedianRating)); break; case "mcr": var mcrrs = new MostCommonRatingRecommendationSystem(); var mcrModel = mcrrs.Trainer.TrainModel(TrainUsers, Artists, TrainRatings); rv = TestRecommendationSystem(mcrrs, TestUsers, mcrModel, Artists); Write(string.Format("MostCommonRating: {0} ({1})", rv, mcrModel.MostCommonRating)); break; } }) Link To Source File
PugRanking Ranking Bot.cs Parallel.ForEach(RankingAlgorithms, delegate(IRankingAlgorithm ranker) { ranker.LoadPickingStatistics(Games); }) Link To Source File
PugRanking Ranking Bot.cs Parallel.ForEach(RankingAlgorithms, delegate(IRankingAlgorithm ranker) { ranker.LoadPickingStatistics(Games); }) Link To Source File
Twiddler RequestConductor.cs Parallel.ForEach(_tweetRequesters, RequestAndAddNewTweetsToStore) Link To Source File
Stateless Program.cs Parallel.ForEach(results, m => { Parallel.For(0, 10, i => { C.WriteLine(ConsoleColor.Black, "firing {0}", i); m.Fire(' ', i); }); }) Link To Source File
Stateless Program.cs Parallel.ForEach(results, m => { Parallel.For(0, 10, i => { C.WriteLine(ConsoleColor.Black, "firing {0}", i); m.Fire(' ', i); }); }) Link To Source File
ILSpy DecompileAllCommand.cs Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate(LoadedAssembly asm) { if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); Exception exception = null; using (var writer = new System.IO.StreamWriter("c://temp//decompiled//" + asm.ShortName + ".cs")) { try { new CSharpLanguage().DecompileAssembly(asm, new Decompiler.PlainTextOutput(writer), new DecompilationOptions { FullDecompilation = true, CancellationToken = ct }); } catch (Exception ex) { writer.WriteLine(ex.ToString()); exception = ex; } } lock (output) { output.Write(asm.ShortName + " - " + w.Elapsed); if (exception != null) { output.Write(" - "); output.Write(exception.GetType().Name); } output.WriteLine(); } } }) Link To Source File
ILSpy CSharpLanguage.cs Parallel.ForEach( files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, delegate(IGrouping file) { using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule); foreach (TypeDefinition type in file) { codeDomBuilder.AddType(type); } codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(new PlainTextOutput(w)); } }) Link To Source File
ILSpy VBLanguage.cs Parallel.ForEach( files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, delegate(IGrouping file) { using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.MainModule); foreach (TypeDefinition type in file) { codeDomBuilder.AddType(type); } RunTransformsAndGenerateCode(codeDomBuilder, new PlainTextOutput(w), options, assembly.MainModule); } }) Link To Source File
SharpDevelop ParseProjectContent.cs Parallel.ForEach( fileContents, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2, CancellationToken = progressMonitor.CancellationToken }, fileName => { // Don't read files we don't have a parser for. // This avoids loading huge files (e.g. sdps) when we have no intention of parsing them. if (ParserService.GetParser(fileName) != null) { ITextBuffer content = finder.Create(fileName); if (content != null) ParserService.ParseFile(this, fileName, content); } lock (progressLock) { progressMonitor.Progress += fileCountInverse; } } ) Link To Source File
NETGen Network.cs // Then process them in parallel System.Threading.Tasks.Parallel.ForEach(lines, s => { string[] vertices = s.Split(' ', '/t'); if(vertices.Length>=2) { Vertex v1 = net.SearchVertex(vertices[0]); Vertex v2 = net.SearchVertex(vertices[1]); // this needs to be atomic lock(net) { if(v1 == null) v1 = net.CreateVertex(vertices[0]); if (v2 == null) v2 = net.CreateVertex(vertices[1]); } Edge e = net.CreateEdge(v1, v2, EdgeType.Undirected); if (vertices.Length==3) { try { e.Weight = float.Parse(vertices[2]); } catch { Logger.AddMessage(LogEntryType.Warning, "Could not parse edge weight."); } } } }) Link To Source File
NETGen FruchtermanReingoldLayout.cs // parallely Calculate repulsive forces of nodes to every new node Parallel.ForEach(_newVertices, v => { disp[v] = new Vector3(0d, 0d, 1d); // computation of repulsive forces foreach(Vertex u in vertices) { if (v != u) { Vector3 delta = _vertexPositions[v] - _vertexPositions[u]; disp[v] = disp[v] + (delta / Vector3.Length(delta)) * repulsion(Vector3.Length(delta), _k); } } }) Link To Source File
NETGen FruchtermanReingoldLayout.cs // Parallely calculate attractive forces for all pairs of connected nodes Parallel.ForEach(edges, e => { Vertex v = e.Source; Vertex w = e.Target; Vector3 delta = _vertexPositions[v] - _vertexPositions[w]; if(_newVertices.Contains(v)) disp[v] = disp[v] - (delta / Vector3.Length(delta)) * attraction(Vector3.Length(delta), _k); if(_newVertices.Contains(w)) disp[w] = disp[w] + (delta / Vector3.Length(delta)) * attraction(Vector3.Length(delta), _k); }) Link To Source File
NETGen FruchtermanReingoldLayout.cs // Limit to frame and include temperature cooling that reduces displacement step by step Parallel.ForEach(_newVertices, v => { Vector3 vPos = _vertexPositions[v] + (disp[v] / Vector3.Length(disp[v])) * Math.Min(Vector3.Length(disp[v]), t); vPos.X = Math.Min(Width-10, Math.Max(10, vPos.X)); vPos.Y = Math.Min(Height-10, Math.Max(10, vPos.Y)); _vertexPositions[v] = vPos; }) Link To Source File
NETGen RadialLayout.cs //assign levels Parallel.ForEach(Network.Vertices.ToArray(), v => { int level = (int)Math.Round(Math.Log(n / 2, exp_base) - Math.Log(Math.Max((double)v.Degree, 7d), exp_base)); if (level < 0) level = (int)Math.Round(Math.Log(n / 2, exp_base) - Math.Log(1d, exp_base)); maxLevel = Math.Max(level, maxLevel); if (!nodesPerLevel.ContainsKey(level)) { nodesPerLevel[level] = 1; if (!startPosPerLevel.ContainsKey(level)) startPosPerLevel[level] = Network.NextRandomDouble() * Math.PI * 2d; } else nodesPerLevel[level]++; }) Link To Source File
NETGen RadialLayout.cs // assign positions Parallel.ForEach(Network.Vertices.ToArray(), v => { int level = (int)Math.Round(Math.Log(n / 2, exp_base) - Math.Log(Math.Max((double)v.Degree, 7d), exp_base)); if (level < 0) level = (int)Math.Round(Math.Log(n / 2, exp_base) - Math.Log(1d, exp_base)); if (!countPerLevel.ContainsKey(level)) countPerLevel[level] = 1; else countPerLevel[level]++; double radius = ((double)Width / 2d) / ((double)maxLevel + 1); double angle = startPosPerLevel[level] + ((double)countPerLevel[level] / (double)nodesPerLevel[level]) * Math.PI * 2d; _vertexPositions[v] = getPosition(Width, Height, angle, level, radius); // v.VertexSize = Math.Max((int)(5 + (((double)v.Degree) / (double)(n / 2)) * 20d), 1); }) Link To Source File
MiniTwitter-Mod MainWindow.xaml.cs Parallel.ForEach(Timelines.Where(p => p.Type == TimelineType.User || p.Type == TimelineType.List || p.Type == TimelineType.Search), item => { Settings.Default.Timelines.Add(item); }) Link To Source File
MiniTwitter-Mod MainWindow.xaml.cs Parallel.ForEach(Timelines, timeline => { if (timeline.Items.Contains(item)) { timeline.UnreadCount--; } }) Link To Source File
Craig-s-Utility-Library IEnumerableExtensions.cs Parallel.ForEach(List, Action) Link To Source File
Craig-s-Utility-Library IEnumerableExtensions.cs Parallel.ForEach(List, delegate(T Item) { try { Action(Item); } catch { if (CatchAction != null) CatchAction(Item); } }) Link To Source File
Craig-s-Utility-Library IEnumerableExtensions.cs Parallel.ForEach(List, Action) Link To Source File
Craig-s-Utility-Library IEnumerableExtensions.cs Parallel.ForEach(List, delegate(T Item) { try { Action(Item); } catch { if (CatchAction != null) CatchAction(Item); } }) Link To Source File
HereSay SitemapDecorator.cs Parallel.ForEach(definitions, definition => { definition.EnsureTab( EditModeTabs.PageInformationName, EditModeTabs.PageInformationTitle, EditModeTabs.PageInformationSortOrder); int sortOrder = definition.GetMaxEditableSortOrder(); definition.AddEditableCheckBox( EditModeFields.Syndication.ExcludeFromSiteMapTitle, ++sortOrder, EditModeTabs.PageInformationName, EditModeFields.Syndication.ExcludeFromSiteMapName, false); }) Link To Source File
HereSay SyndicationDecorator.cs Parallel.ForEach(definitions, definition => { definition.EnsureTab( EditModeTabs.PageInformationName, EditModeTabs.PageInformationTitle, EditModeTabs.PageInformationSortOrder); int sortOrder = definition.GetMaxEditableSortOrder(); definition.AddEditableDate( EditModeFields.Syndication.ContentPublishDateTitle, ++sortOrder, EditModeTabs.PageInformationName, EditModeFields.Syndication.ContentPublishDateName, EditModeFields.Syndication.ContentPublishDateShowDateBox, EditModeFields.Syndication.ContentPublishDateShowTimeBox, EditModeFields.Syndication.ContentPublishDateHelpTitle, EditModeFields.Syndication.ContentPublishDateHelpBody); definition.AddEditableCheckBox( EditModeFields.Syndication.ExcludeFromFeedTitle, ++sortOrder, EditModeTabs.PageInformationName, EditModeFields.Syndication.ExcludeFromFeedName, false, EditModeFields.Syndication.ExcludeFromFeedTitle, EditModeFields.Syndication.ExcludeFromFeedHelpBody); }) Link To Source File
HereSay ConsistentUrlResponseModifier.cs Parallel.ForEach(homePageDefinitions, definition => { Type itemType = definition.ItemType; if (IsPage(itemType)) { definition.EnsureTab( EditModeTabs.Advanced, EditModeTabs.Advanced, EditModeTabs.AdvancedSortOrder); int sortOrder = definition.GetMaxEditableSortOrder(); definition.AddEditableCheckBox( "Disable consistent URLs", ++sortOrder, EditModeTabs.Advanced, DisabledPropertyName, DisabledDefaultValue, "Consistent URLs", "Forces URLs to be consistent by issuing a 301-redirect to clients that errors in the requested URL. For example: mysite.com/My-Page might be redirected to mysite.com/my-page/."); } }) Link To Source File
HereSay CachingDecorator.cs // foreach (ItemDefinition definition in this.Definitions) Parallel.ForEach(this.Definitions, definition => { Type itemType = definition.ItemType; if (IsPage(itemType)) { definition.EnsureTab( EditModeTabs.Advanced, EditModeTabs.Advanced, EditModeTabs.AdvancedSortOrder); int sortOrder = definition.GetMaxEditableSortOrder(); definition.AddEditableEnum( CacheabilityTitle, ++sortOrder, typeof(Cacheability), EditModeTabs.Advanced, CacheabilityName, CacheabilityHelpTitle, CacheabilityHelpText); definition.AddEditableTextBox( CacheDurationTitle, ++sortOrder, 6, EditModeTabs.Advanced, CacheDurationName, CacheDurationHelpTitle, CacheDurationHelpText); } }) Link To Source File
cityindex Program.cs Parallel.ForEach( markets, (n, loopState, index) => { GetPriceBarResponseDTO priceBars = _ctx.GetPriceBars(markets[index], interval, 1, no); Console.WriteLine("Received bar from parallel sync call:" + markets[index]); priceBarResults.Add(markets[index], priceBars.PriceBars); } //close lambda expression ) Link To Source File
BrewRoom Recipe.cs Parallel.ForEach(grains, (grain) => { result += grain.GravityContributionInPoints; }) Link To Source File
BrewRoom Recipe.cs Parallel.ForEach(grains, (grain) => { result += grain.GravityContributionInPoints; }) Link To Source File
BsonSqlServer BsonSqlCollection.cs //go through all of our servers and execute them Parallel.ForEach(servers, server => { List singleResults = ExecuteQueryAgainstSingleConnection(cursor, server.ConnectionId, query, transaction, instance, fields, finalSql, returnMultipleDocuments); if (singleResults != null && singleResults.Count > 0) { lock (combinedResults) { combinedResults.AddRange(singleResults); } } }) Link To Source File
BsonSqlServer BsonSqlCollection.cs //go through all of our servers and execute them Parallel.ForEach(servers, server => { int singleCount = ExecuteCountAgainstSingleConnection(server.ConnectionId, query, transaction, instance, finalSql); if (singleCount > 0) { lock (syncCount) { combinedCount += singleCount; } } }) Link To Source File
BsonSqlServer BsonSqlCollection.cs //go through all of our servers and execute them Parallel.ForEach(servers, server => { ExecuteRemoveAgainstSingleConnection(server.ConnectionId, query, limit, transaction, instance, finalSql); }) Link To Source File
Mystique ConnectionManager.cs Parallel.ForEach(addeds, i => { // 新規接続 UserInformationManager.ReceiveInidividualInfo(i); RefreshConnection(i); }) Link To Source File
Mystique ConnectionManager.cs Parallel.ForEach(keeps, i => { RefreshConnection(i); }) Link To Source File
Mystique PostOffice.cs Parallel.ForEach(infos, (d) => { var ud = d.UserViewModel; // ふぁぼり状態更新 if (ud != null) status.RegisterFavored(ud); try { favoriteInjection.Execute(new Tuple(d, status)); } catch (Exception ex) { success = false; if (ud != null) status.RemoveFavored(ud); if (ex is FavoriteSuspendedException && Setting.Instance.InputExperienceProperty.EnableFavoriteFallback) { // ふぁぼ規制 -> フォールバック AccountInfo fallback = null; if(!String.IsNullOrEmpty( d.AccountProperty.FallbackAccount) && (fallback = AccountStorage.Get(d.AccountProperty.FallbackAccount)) != null && !status.FavoredUsers.Contains(fallback.UserViewModel)) { NotifyStorage.Notify("Fav fallbackします: @" + d.ScreenName + " >> @"); FavTweetSink(new[] { fallback }, status); } } else { NotifyStorage.Notify("Favに失敗しました: @" + d.ScreenName); if (!(ex is ApplicationException)) { ExceptionStorage.Register(ex, ExceptionCategory.TwitterError, "Fav操作時にエラーが発生しました"); } } } }) Link To Source File
Mystique PostOffice.cs Parallel.ForEach(infos, (d) => { var ud = d.UserViewModel; // ふぁぼり状態更新 if (ud != null) status.RemoveFavored(ud); try { unfavoriteInjection.Execute(new Tuple(d, status)); } catch (Exception ex) { success = false; if (ud != null) status.RegisterFavored(ud); NotifyStorage.Notify("Unfavに失敗しました: @" + d.ScreenName); if (!(ex is ApplicationException)) { ExceptionStorage.Register(ex, ExceptionCategory.TwitterError, "Unfav操作時にエラーが発生しました"); } } }) Link To Source File
Mystique PostOffice.cs Parallel.ForEach(infos.Select(i => CheckFallback(i)).Where(i => i != null).Distinct(), d => { // リツイート状態更新 var ud = d.UserViewModel; if (ud != null) status.RegisterRetweeted(ud); try { retweetInjection.Execute(new Tuple(d, status)); } catch (Exception ex) { if (ud != null) status.RemoveRetweeted(ud); success = false; NotifyStorage.Notify("Retweetに失敗しました: @" + d.ScreenName); if (!(ex is ApplicationException)) { ExceptionStorage.Register(ex, ExceptionCategory.TwitterError, "Retweet操作時にエラーが発生しました"); } } }) Link To Source File
Mystique PostOffice.cs Parallel.ForEach(infos, d => { // リツイート状態更新 var ud = d.UserViewModel; if (ud != null) status.RegisterRetweeted(ud); try { unretweetInjection.Execute(new Tuple(d, status)); } catch (Exception ex) { if (ud != null) status.RemoveRetweeted(ud); success = false; NotifyStorage.Notify("Retweetキャンセルに失敗しました: @" + d.ScreenName); if (!(ex is ApplicationException)) { ExceptionStorage.Register(ex, ExceptionCategory.TwitterError, "Retweetキャンセル操作時にエラーが発生しました"); } } }) Link To Source File
Mystique FollowManagerViewModel.cs Parallel.ForEach(Relations, r => r.CommitRelation()) Link To Source File
KMLib FrobeniusParameterSelection.cs Parallel.ForEach(rangeC, paramC => { //do cross validation Stopwatch timer = Stopwatch.StartNew(); Validation valid = new Validation(); valid.Evaluator = new SequentialDualEvaluator(); valid.TrainingProblem = problem; //but here kernel should be different because // in CSVM.Init we set the problem to kernel valid.Kernel = new FrobeniusKernel(); valid.C = (float)paramC; double acc = valid.CrossValidateOnFolds(problem.ElementsCount, foldsElements, foldsLabels); lock (lockObj) { if (acc > crossValidation) { crossValidation = acc; maxC = paramC; // bestKernel = tmpKernel; } } Debug.WriteLine( string.Format( "CrossValidation time={0},C={1}->{2:0.#####}", timer.Elapsed, paramC, acc)); }) Link To Source File
KMLib LinearParameterSelection.cs Parallel.ForEach(rangeC, paramC => { //do cross validation Stopwatch timer = Stopwatch.StartNew(); Validation valid = new Validation(); valid.Evaluator = new SequentialDualEvaluator(); valid.TrainingProblem = problem; //but here kernel should be different because // in CSVM.Init we set the problem to kernel valid.Kernel = new LinearKernel(); valid.C = (float)paramC; double acc = valid.CrossValidateOnFolds(problem.ElementsCount, foldsElements, foldsLabels); //old code //var tmpKernel = new LinearKernel(); //double acc = Validation.CrossValidateOnFolds(problem.ElementsCount, // foldsElements, // foldsLabels, tmpKernel, // (float)paramC); lock (lockObj) { if (acc > crossValidation) { crossValidation = acc; maxC = paramC; // bestKernel = tmpKernel; } } Debug.WriteLine( string.Format( "CrossValidation time={0},C={1}->{2:0.#####}", timer.Elapsed, paramC, acc)); }) Link To Source File
KMLib RBFParameterSelection.cs //paralle search for best C and gamma, for each kernel try different C //foreach (var rbfKernel in rbfKernels) //{ //Parallel.ForEach(rbfKernels, (rbfKernel) => //{ Parallel.ForEach(gammaRange,gamma=>{ Validation valid = new Validation(); valid.Evaluator = new SequentialDualEvaluator(); valid.TrainingProblem = problem; //but here kernel should be different because // in CSVM.Init we set the problem to kernel valid.Kernel = new RbfKernel((float) gamma); for (int j = 0; j < rangeC.Count; j++) { valid.C =(float) rangeC[j]; //do cross validation Stopwatch timer = Stopwatch.StartNew(); double acc = valid.CrossValidateOnFolds(problem.ElementsCount, foldsElements, foldsLabels); lock (lockObj) { if (acc > crossValidation) { crossValidation = acc; maxC = rangeC[j]; bestGamma =(float) gamma; } } Debug.WriteLine( string.Format( "CrossValidation time={0},C={1},gamma={2}->{3:0.#####}", timer.Elapsed, rangeC[j], gamma, acc)); } }) Link To Source File
KMLib ParallelSmoFanSolver.cs #region Find Max pair in parallel Parallel.ForEach(partition, () => new Pair(-1, -INF), (range, loopState, localMax) => { int endRange = range.Item2; for (int t = range.Item1; t < endRange; t++) { if (y[t] == +1) { if (!is_upper_bound(t)) { if (-G[t] > localMax.Second) //wcześniej było większe lub równe { localMax.First = t; localMax.Second = -G[t]; } } } else { if (!is_lower_bound(t)) { if (G[t] > localMax.Second) //wcześniej było >= { localMax.First = t; localMax.Second = G[t]; } } } } return localMax; }, (localMax) => { lock (lockObj) { if (localMax.Second > maxPair.Second) { maxPair = localMax; } } } ) Link To Source File
KMLib ParallelSmoFanSolver.cs //todo: to many allocation, use range partitioner Parallel.ForEach(rangePart, () => new Pair>(-INF, new Pair(-1, INF)), (range, loopState, maxMinPair) => { int endRange = range.Item2; for (int j = range.Item1; j < endRange; j++) { if (y[j] == +1) { if (!is_lower_bound(j)) { float grad_diff = GMax + G[j]; if (G[j] >= maxMinPair.First) maxMinPair.First = G[j]; if (grad_diff > 0) { float obj_diff; float quad_coef = (float)(Q_i[i] + QD[j] - 2.0 * y[i] * Q_i[j]); if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = (float)(-(grad_diff * grad_diff) / 1e-12); if (obj_diff < maxMinPair.Second.Second) { maxMinPair.Second.First = j; maxMinPair.Second.Second = obj_diff; } } } } else { if (!is_upper_bound(j)) { float grad_diff = GMax - G[j]; if (-G[j] >= maxMinPair.First) maxMinPair.First = -G[j]; if (grad_diff > 0) { float obj_diff; float quad_coef = (float)(Q_i[i] + QD[j] + 2.0 * y[i] * Q_i[j]); if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = (float)(-(grad_diff * grad_diff) / 1e-12); if (obj_diff < maxMinPair.Second.Second) { maxMinPair.Second.First = j; maxMinPair.Second.Second = obj_diff; } } } } } return maxMinPair; }, (maxMinPair) => { lock (lockObj) { if (GMax2Tmp < maxMinPair.First) GMax2Tmp = maxMinPair.First; //todo: in this solver we use only one value and index, minIdx.Add(maxMinPair.Second.First, maxMinPair.Second.Second); } } ) Link To Source File
KMLib ParallelSMOSolver.cs //foreach (var i2 in GlobalHeuristic(k)) //{ // StepPairVariable ap = ComputeAlphaStep(st1, i2); // if (ap == null) continue; // newAlphas.Add(ap); // if (newAlphas.Count >= cores) // break; //} #region Parallel version Parallel.ForEach(GlobalHeuristic(k), (i2, loopState) => { if (loopState.ShouldExitCurrentIteration) return; StepPairVariable ap = ComputeAlphaStep(st1, i2); if (ap == null) return; lock (lockObj) { if (newAlphas.Count >= cores) { //stop searching loopState.Stop(); return; } else { newAlphas.Add(ap); if (newAlphas.Count >= cores) loopState.Stop(); } } }) Link To Source File
Realtime-CSG CSGCategorization.cs // // Here we run build the meshes and perform csg on them either in serial or parallel // /* foreach (var node in nodes) buildMesh(node); CSGUtility.UpdateBounds(root); foreach (var item in meshes) updateDelegate(item); /*/ Parallel.ForEach(nodes, buildMesh) Link To Source File
Realtime-CSG CSGCategorization.cs Parallel.ForEach(meshes, updateDelegate) Link To Source File
PexFaultLocalization ParallelBreadthFirstSearchAlgorithm.cs // initialize vertex u Parallel.ForEach(this.VisitedGraph.Vertices, delegate(TVertex v) { if (cancelManager.IsCancelling) return; OnInitializeVertex(v); }) Link To Source File
EmmLabsRemote SerialCommunicationChannel.cs Parallel.ForEach(messages, msg => { Port.Write(message.Value); #if DEBUG Debug.WriteLine(String.Format("Message Written. ({0})", message.Value)); #endif }) Link To Source File
ChameleonCoder PluginManager.cs Parallel.ForEach(Directory.GetFiles(Path.Combine(App.AppDir, "Components"), "*.dll"), dll => { System.Reflection.Assembly ass = null; try { ass = System.Reflection.Assembly.LoadFile(dll); } catch (BadImageFormatException e) { App.Log("ChameleonCoder.Plugins.PluginManager->Load()", "could not assembly '" + dll + "'", e.ToString()); } if (ass != null && ass.IsFullyTrusted && Attribute.IsDefined(ass, typeof(CCPluginAttribute))) { Load(ass.GetTypes()); } }) Link To Source File
ChameleonCoder PluginManager.cs Parallel.ForEach(Filter(plugins), plugin => Add(plugin)) Link To Source File
ChameleonCoder PluginManager.cs Parallel.ForEach(types, type => { if (Attribute.IsDefined(type, typeof(CCPluginAttribute)) // filter non-plugin types && !type.IsAbstract && type.IsClass && type.IsPublic // filter types that can't be instantiated && type.GetInterface(typeof(IPlugin).FullName) != null // only use those that implement plugin interface && type.GetConstructor(Type.EmptyTypes) != null) // filter types without parameterless constructor filtered.Add(type); // if everything ok: add it to the list }) Link To Source File
SuperSocket AppServer.cs System.Threading.Tasks.Parallel.ForEach(timeOutSessions, s => { if (Logger.IsInfoEnabled) Logger.Info(s, string.Format("The socket session has been closed for {0} timeout, last active time: {1}!", now.Subtract(s.LastActiveTime).TotalSeconds, s.LastActiveTime)); s.Close(CloseReason.TimeOut); }) Link To Source File
SuperSocket AppServer.cs System.Threading.Tasks.Parallel.ForEach(timeOutSessions, s => { Logger.LogInfo(s, string.Format("The socket session has been closed for {0} timeout, last active time: {1}!", now.Subtract(s.LastActiveTime).TotalSeconds, s.LastActiveTime)); s.Close(CloseReason.TimeOut); }) Link To Source File
Schumix2 ExtraAddon.cs Parallel.ForEach(urlsin, url => sFunctions.HandleWebTitle(sIRCMessage, url)) Link To Source File
AzureStorageLibrary Retrieval.cs Parallel.ForEach(_TablesToDelete, x => _Service.DeleteTable(x)) Link To Source File
AzureStorageLibrary EqualityFilters.cs Parallel.ForEach(_TablesToDelete, x => _Service.DeleteTable(x)) Link To Source File
AzureStorageLibrary Updating.cs Parallel.ForEach(_TablesToDelete, x => _Service.DeleteTable(x)) Link To Source File
AzureStorageLibrary Deleting.cs Parallel.ForEach(_TablesToDelete, x => _Service.DeleteTable(x)) Link To Source File
AzureStorageLibrary Inserting.cs Parallel.ForEach(_TablesToDelete, x => _Service.DeleteTable(x)) Link To Source File
AzureStorageLibrary TableOperations.cs Parallel.ForEach(_TablesToDelete, new ParallelOptions { CancellationToken = cts.Token }, x => _TableService.DeleteTable(x)) Link To Source File
SwarmIntelligence Command.cs Parallel.ForEach(pendingActions, d => d()) Link To Source File
LunchCrawler LunchRestaurantAnalyzer.cs Parallel.ForEach(restaurantsToBeAnalyzed, AnalyzeLunchRestaurantWithTimeout) Link To Source File
LunchCrawler LunchRestaurantSeeker.cs Parallel.ForEach(allUrls, ScoreLunchRestaurant) Link To Source File
MerchantTribe Global.asax.cs System.Threading.Tasks.Parallel.ForEach(stores, CallTasksOnStore) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(orders, ImportSingleOrder) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(products, ImportSingleProduct) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(orders, ImportSingleOrder) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(products, ImportSingleProduct) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(oldOrders.Content, ImportSingleOrder) Link To Source File
MerchantTribe Migrator.cs System.Threading.Tasks.Parallel.ForEach(allProducts.Content, ImportSingleProduct) Link To Source File
mooege DebugNavMesh.cs Parallel.ForEach(scenes, scene => { if (scene.Parent == null) this.MasterScenes.Add(scene); else this.SubScenes.Add(scene); this.AnalyzeScene(scene); }) Link To Source File
mooege DebugNavMesh.cs Parallel.ForEach(actors, actor => { if (actor is Player) this.Players.Add(actor as Player); else if (actor is NPC) this.NPCs.Add(actor as NPC); else if (actor is Monster) this.Monsters.Add(actor as Monster); }) Link To Source File
mooege DebugNavMesh.cs Parallel.ForEach(scene.NavZone.NavCells, cell => { float x = scene.Position.X + cell.Min.X; float y = scene.Position.Y + cell.Min.Y; float sizex = cell.Max.X - cell.Min.X; float sizey = cell.Max.Y - cell.Min.Y; var rect = new Rect(x, y, sizex, sizey); // TODO: Feature request: Also allow drawing of NavCellFlags.NOSpawn, NavCellFlags.LevelAreaBit0, NavCellFlags.LevelAreaBit1 cells. /raist. if ((cell.Flags & Mooege.Common.MPQ.FileFormats.Scene.NavCellFlags.AllowWalk) != Mooege.Common.MPQ.FileFormats.Scene.NavCellFlags.AllowWalk) UnWalkableCells.Add(rect); else WalkableCells.Add(rect); }) Link To Source File
GameServer FlottenManagement.cs Parallel.ForEach(dataList, data => { double newdistance = data.distance - data.speed; if (newdistance <= 0) { // Ankunft im System: foreach (Ship ship in data.ship) { ship.Position = data.destination; } travelList.Remove(data); } else { TravelData neu = new TravelData(); neu.destination = data.destination; neu.fleet = data.fleet; neu.origin = data.origin; neu.route = data.route; neu.ship = data.ship; neu.speed = data.speed; neu.distance = newdistance; neu.timeRemaining = newdistance / data.speed; } }) Link To Source File
GameServer Map.cs Parallel.ForEach(systemList, system => { if ((system != null) && sysok) { if (getSystemsInRange(system, 0).Count > 0) { Console.WriteLine("Invalides System endteckt!"); system.nodes.Clear(); foreach (Node node in system.nodes) { node.pointa.nodes.Remove(node); node.pointb.nodes.Remove(node); } try { delet.Add(system); } catch { } } else if (system.nodes.Count == 0) { LinkedList near = getSystemsInRange(system, connectrange * 2); if (near.Count > 0) { int anzahl = (new Random()).Next(1, near.Count); int j = 0; foreach (Solarsystem nearSystem in near) { j++; if (j > anzahl) { break; } if ((getConnectionCount(system) < 2) && (getConnectionCount(nearSystem) < maxconnections) && !isConnection(system, nearSystem)) { Node node = new Node(); node.pointa = system; node.pointb = nearSystem; node.distance = getDistance(system, nearSystem); system.nodes.Add(node); nearSystem.nodes.Add(node); } } } if (system.nodes.Count == 0) { main.log("Unnereichbares System gefunden! Bitte Passen Sie die Map-Daten oder die AnwendungsKonfiguration an"); sysok = false; } } } }) Link To Source File
GameServer Map.cs Parallel.ForEach(systemList, system => { for (int i = 0; i < random.Next(15); i++) { Planet planet = new Planet(Game.Game.Data.Names.PlanetNames[random.Next(Game.Game.Data.Names.PlanetNames.Length - 1)]); planet.type = planetTypes[random.Next(planetTypes.Count - 1)]; if (system.planets == null) { system.planets = new List(); } system.planets.Add(planet); planet.Solarsystem = system; } }) Link To Source File
GameServer Map.cs Parallel.ForEach(systemList, system => { if ((system != null) && (start != system)) { double distance = getDistance(start, system); if (distance <= range) { lock (list) { list.AddLast(system); } } } }) Link To Source File
GameServer Map.cs Parallel.ForEach(start.nodes, node => { if ((node.pointa == end) || (node.pointb == end)) { connection = true; } }) Link To Source File
GameServer Modul.cs Parallel.ForEach(list, el => { if (el.Equals(element)) { count++; } }) Link To Source File
GameServer NodeTrackingSystem.cs Parallel.ForEach(nodelist, node => // foreach (Node node in nodelist) { try { Solarsystem other = (node.pointa == current) ? node.pointb : node.pointa; Node[] visitedNode2 = new Node[visitedNode.Length + 1]; copyArray(visitedNode, visitedNode2); visitedNode2[visitedNode2.Length - 1] = node; pingSolarsystem(other, source, destination, visited2, visitedNode2, maxResults, depth + 1); //} } catch (TrackingCanceledException) { error = true; } }) Link To Source File
GameServer Resources.cs Parallel.ForEach(userList, user => { fkt_checkRes(user); }) Link To Source File
GameServer Tech.cs System.Threading.Tasks.Parallel.ForEach(userlist, user => { fkt_checkTech(user); }) Link To Source File
GameServer Update.cs System.Threading.Tasks.Parallel.ForEach(userlist, user => { CheckUpdates(user); }) Link To Source File
NewsService NewsService.cs Parallel.ForEach(Settings.Newsfeeds, x => { try { XDocument doc = XDocument.Load(x); XElement xChannel = doc.Descendants("channel").First(); foreach ( XElement newsItemModel in xChannel.Descendants("item")) { items.Add(GetNewsItem(newsItemModel)); } } catch (Exception e) { exceptions.Enqueue(e); } }) Link To Source File
ncqrs TableOnlyStore.cs Parallel.ForEach( eventStream.Select(es => es.EventSourceId).Distinct(), (eventSourceId) => SaveEvents(eventSourceId, eventStream.Where(es => es.EventSourceId == eventSourceId)) ) Link To Source File
MonkeyBallz ClientManager.cs Parallel.ForEach(_clients, client => RecievePendingMessages(client)) Link To Source File
MonkeyBallz ServerCommandHandler.cs Parallel.ForEach(Server.ClientManager.Clients, client => { var clientListCommand = Server.CommandFactory.CreateClientList( Server.ClientManager.Clients.Select( x => x.ClientInformation).ToList(), client, Server.ServerInformation); Server.CommandQueueService.Enqueue(clientListCommand); }) Link To Source File
DataLab DataLoader.cs Parallel.ForEach(Producer.GetEntitiesEnumerator(exceptionNotifier), options, i => { try { Processor.ProcessEntity(Params.TableMetadataEntity.EntitySet, i); } catch (Exception ex) { if (exceptionNotifier != null) exceptionNotifier(new EntityProcessingException(i.ToString(), ex)); } if (progressNotifier != null) progressNotifier(Producer.EntityCount, Interlocked.Increment(ref count)); }) Link To Source File
coapp Registrar.cs Parallel.ForEach(Directory.GetDirectories(PackageManagerSettings.CoAppCacheDirectory), dir => Directory.Delete(dir, true)) Link To Source File
coapp Registrar.cs Parallel.ForEach(Directory.GetFiles(PackageManagerSettings.CoAppCacheDirectory), File.Delete) Link To Source File
Radiator MessageBus.cs Parallel.ForEach(consumers, consumer => consumer.Consume(message)) Link To Source File
Viola-Jones-Mono StrongClassifier.cs //foreach (var feature in featuresValues) { Parallel.ForEach(featuresValues, (feature) => { var newClassifier = TestWeakClassifier.Train(tests, validWeight, feature); if (best.Errors > newClassifier.Errors) best = newClassifier; }) Link To Source File
ravendb FileToRavenCommand.cs Parallel.ForEach(from generator in taskGenerators from action in generator select action, new ParallelOptions { MaxDegreeOfParallelism = 10 }, action => { try { action(); } catch (WebException e) { var readToEnd = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); Console.WriteLine(readToEnd); throw; } }) Link To Source File
ravendb XMLToFileCommand.cs Parallel.ForEach(processes, GenerateJsonDocuments) Link To Source File
ravendb ReducingExecuter.cs Parallel.ForEach(indexesToWorkOn, new ParallelOptions { MaxDegreeOfParallelism = context.Configuration.MaxNumberOfParallelIndexTasks, TaskScheduler = scheduler }, HandleReduceForIndex) Link To Source File
ravendb IndexingExecuter.cs Parallel.ForEach(results, new ParallelOptions { MaxDegreeOfParallelism = context.Configuration.MaxNumberOfParallelIndexTasks, TaskScheduler = scheduler, }, result => transactionalStorage.Batch(actions => IndexDocuments(actions, result.Item1.IndexName, result.Item2))) Link To Source File
ravendb ConcurrentPatching.cs Parallel.ForEach(patches, data => store.DatabaseCommands.Patch("posts/1", new[]{data})) Link To Source File
QuickGraph ParallelBreadthFirstSearchAlgorithm.cs // initialize vertex u Parallel.ForEach(this.VisitedGraph.Vertices, delegate(TVertex v) { if (cancelManager.IsCancelling) return; OnInitializeVertex(v); }) Link To Source File
AzureBlobDrive AzureOperations.cs Parallel.ForEach(GetBlobsStartingWith(prefix, container, true), blob => { try { var blobDetail = GetBlobDetail(blob.Uri); FileInformation finfo = new FileInformation(); finfo.FileName = System.Web.HttpUtility.UrlDecode(blobDetail.Uri.ToBlobFilename()); finfo.Attributes = System.IO.FileAttributes.Normal; finfo.LastAccessTime = DateTime.Now; finfo.LastWriteTime = DateTime.Now; finfo.CreationTime = DateTime.Now; finfo.Length = blobDetail.Properties.Length; lock (localsync) { files.Add(finfo); } } catch { } }) Link To Source File
DynamicScript ParallelAggregator.cs Parallel.ForEach(collection1, item1 => Parallel.ForEach(collection2, item2 => Aggregate(item1, item2))) Link To Source File
DynamicScript ParallelAggregator.cs Parallel.ForEach(collection2, item2 => Aggregate(item1, item2)) Link To Source File
Bundle.net GitBundleRepository.cs Parallel.ForEach(Directory.GetDirectories(PackageRepositoryPath), packageRootPath => { foreach (var packagePath in Directory.GetDirectories(packageRootPath)) { if (File.Exists(Path.Combine(packagePath, "metadata.xml"))) { files.Add(Path.Combine(packagePath, "metadata.xml")); } } }) Link To Source File
HAW-Stundenplan PlanFile.cs //var opt = new ParallelOptions // { // MaxDegreeOfParallelism = 5, // }; Parallel.ForEach(semGroupBlocks, /*opt,*/ block => { try { ParseSeminarGroupBlock(block); } catch (Exception exp) { Console.WriteLine(""); } finally { OnStatusMessageChanged("Noch {0} Seminargruppen zu lesen", blocksLeft--); } }) Link To Source File
CCNet.Extensions CleaningFolder.cs Parallel.ForEach( projectPaths, CleanProjectFolder) Link To Source File
NutaParser Program.cs Parallel.ForEach(s_all, CheckOne) Link To Source File
codegallery ServiceWrapper.cs Parallel.ForEach(GetItems(collectionSize), x => ServiceCall(x)) Link To Source File
Zetetic.Ldap MassDeleter.cs Parallel.ForEach(ISE(resp.Entries), entry => { try { var delreq = new DeleteRequest(entry.DistinguishedName); delreq.Controls.Add(lazy); conns[Thread.CurrentThread.ManagedThreadId % connCount].SendRequest(delreq); Console.Error.WriteLine("Deleted {0}", entry.DistinguishedName); } catch (Exception ex) { Console.Error.WriteLine("Failed to delete {0}: {1}", entry.DistinguishedName, ex.Message); throw; } } ) Link To Source File
sones ExecuteVertexHandler.cs Parallel.ForEach(myIndices, idx => idx.Add(myVertex)) Link To Source File
sones ExecuteVertexHandler.cs Parallel.ForEach(myIndices, idx => idx.Remove(myVertex)) Link To Source File
sones InMemoryNonRevisionedFS.cs Parallel.ForEach(myReplicationStream, aVertex => { if (!tempVertexStore.ContainsKey(aVertex.VertexTypeID)) { tempVertexStore.TryAdd(aVertex.VertexTypeID, new ConcurrentDictionary()); } tempVertexStore[aVertex.VertexTypeID].TryAdd(aVertex.VertexID, TransferToInMemoryVertex(aVertex)); }) Link To Source File
sones GraphDBImport_GQL.cs #endregion #region check lines and execute query Parallel.ForEach(myLines, parallelOptions, (line, state) => { if (!IsComment(line, comments)) { Interlocked.Increment(ref numberOfLine); var qresult = ExecuteQuery(line, myIGraphQL, mySecurityToken, myTransactionToken); #region VerbosityTypes.Full: Add result if (myVerbosityType == VerbosityTypes.Full) { lock (aggregatedResults) { aggregatedResults.Add(qresult.Vertices); } } #endregion #region !VerbosityTypes.Silent: Add errors and break execution if (qresult.TypeOfResult != ResultType.Successful && myVerbosityType != VerbosityTypes.Silent) { if (qresult.Error != null) throw qresult.Error; else throw new ImportFailedException(new UnknownException()); } #endregion } }) Link To Source File
sones SonesIndex.cs Parallel.ForEach(myKeys, k => Remove(k)) Link To Source File
hoehoe2 FavoriteQueue.cs Parallel.ForEach(_cacheList, new Action((long stsId) => { _tw.PostFavAdd(stsId); })) Link To Source File
mbta DirectedGraph.cs Parallel.ForEach(Nodes.Values, startNode => //foreach(var startNode in Nodes.Values) { Dictionary bestConnections = new Dictionary(); Stack sinfos = new Stack(); sinfos.Push(new SearchInfo() { TargetId = startNode.Id, Cost = 0.0f }); while (sinfos.Count > 0) { SearchInfo sinfo = sinfos.Pop(); string targetId = sinfo.TargetId; if (sinfo.NumConnections < MaxDepth + 1 && (!bestConnections.ContainsKey(targetId) || bestConnections[targetId].Cost > sinfo.Cost)) { //MBTA.Log("{0} to {1} in {2}/{3}", startNode.Id, targetId, sinfo.Cost, sinfo.Connections.Count); bestConnections[targetId] = sinfo; GraphNode currNode = Nodes[targetId]; foreach (IDirectedGraphConnection connection in currNode.Connections) { sinfos.Push(BranchTo(sinfo, connection)); } } } lock (solvedConnections) { solvedConnections[startNode.Id] = (from conn in bestConnections.Values select CombineConnections(conn.Cost, Nodes[conn.TargetId] as IGraphNode)).ToList(); } lock (fun) { numSolved++; //MBTA.Log("Solved {0}, {1} of {2}", startNode.Id, numSolved, numTotal); //MBTA.Log("average: {0}", (from conn in solvedConnections[startNode.Id] select (conn as LocConnection).Cost).Average()); //MBTA.Log("count: {0}", (from conn in solvedConnections[startNode.Id] select (conn as LocConnection).Cost).Count()); MBTA.Progress(numSolved, numTotal); } }) Link To Source File
mbta Loader.cs Parallel.ForEach(Enumerable.Range(0, boston.Height), j => { isPixelWater(i, j); }) Link To Source File
mbta Loader.cs Parallel.ForEach(allPts(), pt => { PointF otherLocF = latLonFromPix(pt); Loc ptLoc = locs[(conn as LocConnection).TargetId]; float dist = Geo.Dist(new PointF(ptLoc.Lon, ptLoc.Lat), otherLocF); const float invWalkingSpeed = 60.0f / 4.8f; // 4.8km/h in km/min float time = dist * invWalkingSpeed + baseCost; if (getPix(pt) > time) { setPix(pt, time); } }) Link To Source File
ScreenCap World.cs // bmpSS is locked in here as necessary to avoid conflicts Parallel.ForEach(Group, p => p.UpdateFromScreen(bmpSS, LastScreenshotTime)) Link To Source File
Rob.DataDemo ParallelWrapper.cs Parallel.ForEach(collection, element => { try { action(element); } catch (Exception ex) { exceptions.Enqueue(ex); } }) Link To Source File
Ycyj.Client KnowledgeTreeManager.cs Parallel.ForEach(children, child => ExtractChildren(child.Item1, child.Item2)) Link To Source File
torshify-client BackdropService.cs Parallel.ForEach(nodelist.Cast(), node => ProcessImage(node.InnerText, downloadFolder)) Link To Source File
torshify-r4dio BackdropService.cs Parallel.ForEach(nodelist.Cast(), node => ProcessImage(node.InnerText, downloadFolder)) Link To Source File
torshify-r4dio TrackDJResultsViewModel.cs Parallel.ForEach(artists, artist => { var tracks = _radio.GetTracksByArtist(artist.Key, 0, 100); foreach (var songBucketItem in artist) { var track = tracks.FirstOrDefault( t => t.Name.Equals(songBucketItem.Title, StringComparison. InvariantCultureIgnoreCase)); if (track != null) { track.ExtraData.Terms = null; Task .Factory .StartNew(FindArtistInformation, Tuple.Create(track, songBucketItem)); allTracks.Add(track); Application.Current.Dispatcher.BeginInvoke( new Action(_tracks.Add), track); } } }) Link To Source File
alaris PublicMessageHandler.cs Parallel.ForEach(urlsin, url => Utilities.HandleWebTitle(chan, url)) Link To Source File
alaris CommandManager.cs Parallel.ForEach(asms, asm => { var types = asm.GetTypes(); Parallel.ForEach(types, type => { var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static); //Utilities.ExecuteSafely( // () => ProcessMethods(methods)); ProcessMethods(methods); }); }) Link To Source File
alaris CommandManager.cs Parallel.ForEach(types, type => { var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static); //Utilities.ExecuteSafely( // () => ProcessMethods(methods)); ProcessMethods(methods); }) Link To Source File
alaris CommandManager.cs Parallel.ForEach(methods, method => { var passEverything = false; foreach (var attribute in Attribute.GetCustomAttributes(method)) { if (attribute.IsOfType(typeof(AlarisCommandAttribute)) || attribute.IsOfType(typeof(ParameterizedAlarisCommand))) { if (attribute.IsOfType(typeof(ParameterizedAlarisCommand))) { var patt = attribute.Cast(); if (patt.IsParameterCountUnspecified) passEverything = true; else if (method.GetParameters().Length != patt.ParameterCount + 1) continue; } var attr = (AlarisCommandAttribute)attribute; lock (MapLock) { CommandMethodMap.Add(new AlarisCommandWrapper { Command = attr.Command, Permission = attr.Permission, IsParameterCountUnspecified = passEverything }, new AlarisMethod(method, attr, attr.CanBeCastedTo < ParameterizedAlarisCommand >())); } } else if (attribute.IsOfType(typeof(AlarisSubCommandAttribute)) || attribute.IsOfType(typeof(ParameterizedAlarisSubCommand))) { if (attribute.IsOfType(typeof(ParameterizedAlarisSubCommand))) { var patt = (ParameterizedAlarisSubCommand)attribute; if (patt.IsParameterCountUnspecified) passEverything = true; else if (method.GetParameters().Length != patt.ParameterCount + 1) continue; } var attr = (AlarisSubCommandAttribute)attribute; lock (MapLock) { CommandMethodMap.Add(new AlarisCommandWrapper { Command = attr.Command, Permission = attr.Permission, IsParameterCountUnspecified = passEverything }, new AlarisMethod(method, attr, attr.CanBeCastedTo < ParameterizedAlarisSubCommand >())); } } } }) Link To Source File
alaris IrcExtensions.cs Parallel.ForEach(channels, chan => { if (chan.IsValidChannelName()) connection.Sender.Join(chan); Log.Debug("Joined channel: {0}", chan); }) Link To Source File
xna-morijobi-win my_space.cs Parallel.ForEach(sc, sp => { sp.sa.effect_from(sp.sb); }) Link To Source File
ORTS Engine.cs Parallel.ForEach(Factory.GameObjects, gameobject => gameobject.Update(tickTime)) Link To Source File
SharpEngine GameEngine.cs Parallel.ForEach(Factory.GameObjects, gameobject => gameobject.Value.Update(tickTime)) Link To Source File
KillSwitch DeleteService.cs Parallel.ForEach(files, currentFile => { result.FileDeleteResults.Add(FileSecureDelete(currentFile)); }) Link To Source File
MadCow DeleteHelper.cs Parallel.ForEach(foldersArray.Select(folder => new DirectoryInfo(folder)), info => { Directory.Delete(info.FullName, true); Console.WriteLine("Deleted: {0}", info.Name); }) Link To Source File
FooSync FooSync.cs Parallel.ForEach(repo.Files, file => { var filename = file.Key; ChangeStatus status = ChangeStatus.Identical; if (source.Files.ContainsKey(filename)) { repoMissingFiles.Remove(filename); int comp = file.Value.CompareTo(source.Files[filename]); status = (ChangeStatus)comp; } else { if (state.Source.MTimes.ContainsKey(filename)) { status = ChangeStatus.SourceDeleted; } else { status = ChangeStatus.SourceMissing; } } if (status != ChangeStatus.Identical) { changeset.Add(filename, status); } }) Link To Source File
FooSync FooSync.cs Parallel.ForEach(repoMissingFiles, filename => { ChangeStatus status = ChangeStatus.Undetermined; if (state.Repository.MTimes.ContainsKey(filename)) { status = ChangeStatus.RepoDeleted; } else { status = ChangeStatus.RepoMissing; } changeset.Add(filename, status); }) Link To Source File
lucene.net SimpleFacetedSearch.cs //SETP 3 //create a single BitSet for each combination //BitSet1: A AND I AND 1 //BitSet2: A AND I AND 2 etc. //and remove impossible comb's (for ex, B J 3) from list. Parallel.ForEach(cp, combinations => { OpenBitSetDISI bitSet = new OpenBitSetDISI(_Reader.MaxDoc()); bitSet.Set(0, bitSet.Size()); List comb = combinations.ToList(); for (int j = 0; j < comb.Count; j++) { bitSet.And(fieldValuesBitSets[j].FieldValueBitSetPair[comb[j]]); } //STEP 3 if (bitSet.Cardinality() > 0) { lock(_Groups) _Groups.Add(new KeyValuePair, OpenBitSetDISI>(comb, bitSet)); } }) Link To Source File
movielens RecommendationSystem.cs Parallel.ForEach(similarMoviesTmp, x => { if (!movieIds.Contains(x.Movie.Id)) { if (totalWeightedScores.ContainsKey(x.Movie)) { var existing = totalWeightedScores[x.Movie]; //double sum = existing == null ? 0 : (double)existing; //sum = existing + x.Score * rate.Rate; totalWeightedScores[x.Movie] = existing + x.Score * rate.Rate; } else { totalWeightedScores[x.Movie] = 0.0d; } if (totalSim.ContainsKey(x.Movie)) { var existing2 = totalSim[x.Movie]; //double sum2 = existing2 == null ? 0 : (double)existing2; totalSim[x.Movie] = existing2 + x.Score; } else { totalSim[x.Movie] = 0; } } }) Link To Source File
movielens RecommendationSystem.cs Parallel.ForEach(similarMoviesTmp, x => { if (!movieIds.Contains(x.Movie.Id)) { if (totalWeightedScores.ContainsKey(x.Movie)) { var existing = totalWeightedScores[x.Movie]; //double sum = existing == null ? 0 : (double)existing; //sum = existing + x.Score * rate.Rate; totalWeightedScores[x.Movie] = existing + x.Score * rate.Rate; } else { totalWeightedScores[x.Movie] = 0.0d; } if (totalSim.ContainsKey(x.Movie)) { var existing2 = totalSim[x.Movie]; //double sum2 = existing2 == null ? 0 : (double)existing2; totalSim[x.Movie] = existing2 + x.Score; } else { totalSim[x.Movie] = 0; } } }) Link To Source File
YANFOE.v2 DatabaseIOFactory.cs Parallel.ForEach( files, parallelOptions, file => { string json = Gzip.Decompress(file); var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel; if (json.Contains(@"ChangedText"":false")) { movieModel.ChangedText = false; } if (json.Contains(@"ChangedPoster"":false")) { movieModel.ChangedPoster = false; } if (json.Contains(@"ChangedFanart"":false")) { movieModel.ChangedFanart = false; } movieModel.DatabaseSaved = true; if (movieModel.AssociatedFiles.GetMediaCollection().Count > 0) { if (!File.Exists(movieModel.AssociatedFiles.GetMediaCollection()[0].PathAndFilename)) { Log.WriteToLog( LogSeverity.Info, LoggerName.GeneralLog, "Internal > DatabaseIOFactory > LoadMovieDB", string.Format( "Deleting {0}. Movie not found on the filesystem", movieModel.AssociatedFiles.GetMediaCollection()[0].FileName)); // We should check for network path and make sure the file has actually been deleted or removed File.Delete(file); } } if (movieModel != null) { lock (database) { database.Add(movieModel); } } string title = FileNaming.RemoveIllegalChars(movieModel.Title); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; if (File.Exists(poster)) { movieModel.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { movieModel.SmallFanart = ImageHandler.LoadImage(fanart); } }) Link To Source File
YANFOE.v2 DatabaseIOFactory.cs Parallel.ForEach( files, parallelOptions, file => { var json = Gzip.Decompress(file); var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series; string title = FileNaming.RemoveIllegalChars(series.SeriesName); string poster = path + title + ".poster.jpg"; string fanart = path + title + ".fanart.jpg"; string banner = path + title + ".banner.jpg"; if (File.Exists(poster)) { series.SmallPoster = ImageHandler.LoadImage(poster); } if (File.Exists(fanart)) { series.SmallFanart = ImageHandler.LoadImage(fanart); } if (File.Exists(banner)) { series.SmallBanner = ImageHandler.LoadImage(banner); } foreach (var season in series.Seasons) { for (int index = 0; index < season.Value.Episodes.Count; index++) { var episode = season.Value.Episodes[index]; if (episode.FilePath.PathAndFilename != string.Empty && !File.Exists(episode.FilePath.PathAndFilename)) { Log.WriteToLog( LogSeverity.Info, LoggerName.GeneralLog, "Internal > DatabaseIOFactory > LoadTvDB", string.Format( "Deleting {0}. Episode not found on the filesystem", episode.FilePath.PathAndFilename)); // We should check for network path and make sure the file has actually been deleted or removed File.Delete(file); series.Seasons[season.Key].Episodes.Remove(episode); } } } lock (TvDBFactory.TvDatabase) { TvDBFactory.TvDatabase.Add(series.SeriesName, series); } }) Link To Source File
YANFOE.v2 DatabaseIOFactory.cs Parallel.ForEach( database, parallelOptions, movie => { SavingCount++; var path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar; var title = FileNaming.RemoveIllegalChars(movie.Title); string writePath; if (movie.Hidden) { writePath = path + title + ".hiddenmovie"; } else { writePath = path + title + ".movie"; } movie.DatabaseSaved = true; var json = JsonConvert.SerializeObject(movie); Gzip.CompressString(json, writePath + ".gz"); var posterPath = path + title + ".poster.jpg"; var fanartPath = path + title + ".fanart.jpg"; if (movie.SmallPoster != null) { movie.SmallPoster.Save(posterPath); } if (movie.SmallFanart != null) { movie.SmallFanart.Save(fanartPath); } Application.DoEvents(); SavingMovieValue++; }) Link To Source File
YANFOE.v2 DatabaseIOFactory.cs Parallel.ForEach( TvDBFactory.TvDatabase, parallelOptions, series => { var title = FileNaming.RemoveIllegalChars(series.Value.SeriesName); var seriesPath = string.Concat(Get.FileSystemPaths.PathDatabases, OutputName.TvDb, Path.DirectorySeparatorChar, title, ".Series.gz"); json = JsonConvert.SerializeObject(series.Value); Gzip.CompressString(json, seriesPath); if (series.Value.SmallBanner != null) { var smallBanner = new Bitmap(series.Value.SmallBanner); smallBanner.Save(path + title + ".banner.jpg"); } if (series.Value.SmallFanart != null) { var smallFanart = new Bitmap(series.Value.SmallFanart); smallFanart.Save(path + title + ".fanner.jpg"); } if (series.Value.SmallPoster != null) { var smallPoster = new Bitmap(series.Value.SmallPoster); smallPoster.Save(path + title + ".poster.jpg"); } SavingTVDBValue++; Application.DoEvents(); }) Link To Source File
MyMediaLite Items.cs Parallel.ForEach(test_users, user_id => { try { var correct_items = new HashSet(test_user_matrix[user_id]); correct_items.IntersectWith(candidate_items); // the number of items that will be used for this user var candidate_items_in_train = new HashSet(training_user_matrix[user_id]); candidate_items_in_train.IntersectWith(candidate_items); int num_eval_items = candidate_items.Count - (repeated_events ? 0 : candidate_items_in_train.Count()); // skip all users that have 0 or #candidate_items test items if (correct_items.Count == 0) return; if (num_eval_items == correct_items.Count) return; IList prediction_list = recommender.PredictItems(user_id, candidate_items); if (prediction_list.Count != candidate_items.Count) throw new Exception("Not all items have been ranked."); ICollection ignore_items = repeated_events ? new int[0] : training_user_matrix[user_id]; double auc = AUC.Compute(prediction_list, correct_items, ignore_items); double map = PrecisionAndRecall.AP(prediction_list, correct_items, ignore_items); double ndcg = NDCG.Compute(prediction_list, correct_items, ignore_items); double rr = ReciprocalRank.Compute(prediction_list, correct_items, ignore_items); var positions = new int[] { 5, 10 }; var prec = PrecisionAndRecall.PrecisionAt(prediction_list, correct_items, ignore_items, positions); var recall = PrecisionAndRecall.RecallAt(prediction_list, correct_items, ignore_items, positions); // thread-safe incrementing lock (result) { num_users++; result["AUC"] += (float) auc; result["MAP"] += (float) map; result["NDCG"] += (float) ndcg; result["MRR"] += (float) rr; result["prec@5"] += (float) prec[5]; result["prec@10"] += (float) prec[10]; result["recall@5"] += (float) recall[5]; result["recall@10"] += (float) recall[10]; } if (num_users % 1000 == 0) Console.Error.Write("."); if (num_users % 60000 == 0) Console.Error.WriteLine(); } catch (Exception e) { Console.Error.WriteLine("===> ERROR: " + e.Message + e.StackTrace); throw e; } }) Link To Source File
MyMediaLite ItemsFiltered.cs Parallel.ForEach (test_users, user_id => { var filtered_items = GetFilteredItems(user_id, test, item_attributes); int last_user_id = -1; foreach (int attribute_id in filtered_items.Keys) { var filtered_candidate_items = new HashSet(items_by_attribute[attribute_id]); filtered_candidate_items.IntersectWith(candidate_items); var correct_items = new HashSet(filtered_items[attribute_id]); correct_items.IntersectWith(filtered_candidate_items); // the number of candidate items for this user var candidate_items_in_train = new HashSet(train.UserMatrix[user_id]); candidate_items_in_train.IntersectWith(filtered_candidate_items); int num_eval_items = filtered_candidate_items.Count - candidate_items_in_train.Count; // skip all users that have 0 or #filtered_candidate_items test items if (correct_items.Count == 0) return; if (num_eval_items - correct_items.Count == 0) return; // evaluation IList prediction_list = recommender.PredictItems(user_id, filtered_candidate_items.ToArray()); ICollection ignore_items = repeated_events ? new int[0] : train.UserMatrix[user_id]; double auc = AUC.Compute(prediction_list, correct_items, ignore_items); double map = PrecisionAndRecall.AP(prediction_list, correct_items, ignore_items); double ndcg = NDCG.Compute(prediction_list, correct_items, ignore_items); double rr = ReciprocalRank.Compute(prediction_list, correct_items, ignore_items); var positions = new int[] { 5, 10 }; var prec = PrecisionAndRecall.PrecisionAt(prediction_list, correct_items, ignore_items, positions); var recall = PrecisionAndRecall.RecallAt(prediction_list, correct_items, ignore_items, positions); // thread-safe incrementing lock(result) { // counting stats num_lists++; if (last_user_id != user_id) { last_user_id = user_id; num_users++; } // result bookkeeping result["AUC"] += (float) auc; result["MAP"] += (float) map; result["NDCG"] += (float) ndcg; result["MRR"] += (float) rr; result["prec@5"] += (float) prec[5]; result["prec@10"] += (float) prec[10]; result["recall@5"] += (float) recall[5]; result["recall@10"] += (float) recall[10]; } if (prediction_list.Count != filtered_candidate_items.Count) throw new Exception("Not all items have been ranked."); if (num_lists % 5000 == 0) Console.Error.Write("."); if (num_lists % 300000 == 0) Console.Error.WriteLine(); } }) Link To Source File