public Connection(IMessageBus newMessageBus, IJsonSerializer jsonSerializer, string baseSignal, string connectionId, IList<string> signals, IList<string> groups, ITraceManager traceManager, IAckHandler ackHandler, IPerformanceCounterManager performanceCounterManager, IProtectedData protectedData) { if (traceManager == null) { throw new ArgumentNullException("traceManager"); } _bus = newMessageBus; _serializer = jsonSerializer; _baseSignal = baseSignal; _connectionId = connectionId; _signals = new List<string>(signals.Concat(groups)); _groups = new DiffSet<string>(groups); _traceSource = traceManager["SignalR.Connection"]; _ackHandler = ackHandler; _counters = performanceCounterManager; _protectedData = protectedData; }
public int Calculate(IList<int> numbers, decimal currentSum, int globalMax) { int result = 0; decimal max = numbers.Count == 0 ? 1 : numbers[numbers.Count - 1]; for (decimal i = max + 1; i <= globalMax; i++) { decimal sum = currentSum + values[(int)i]; if (sum > half) break; if (Math.Abs(sum-half)< 0.000000001m) { foreach (var number in numbers.Concat(new int[] {(int)i})) { Console.Write(number.ToString()+","); } Console.Write(" " +sum.ToString()); Console.WriteLine(); result++; break; } if (i<globalMax && sum + sumOfValues[(int)i+1]< half) break; List<int> newNumbers = new List<int>(numbers); newNumbers.Add((int)i); result += Calculate(newNumbers, sum, globalMax); } return result; }
public Connection(IMessageBus newMessageBus, JsonSerializer jsonSerializer, string baseSignal, string connectionId, IList<string> signals, IList<string> groups, ILoggerFactory loggerFactory, IAckHandler ackHandler, IPerformanceCounterManager performanceCounterManager, IProtectedData protectedData, IMemoryPool pool) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } _bus = newMessageBus; _serializer = jsonSerializer; _baseSignal = baseSignal; _connectionId = connectionId; _signals = new List<string>(signals.Concat(groups)); _groups = new DiffSet<string>(groups); _logger = loggerFactory.CreateLogger<Connection>(); _ackHandler = ackHandler; _counters = performanceCounterManager; _protectedData = protectedData; _excludeMessage = m => ExcludeMessage(m); _pool = pool; }
public ParseRelationOperation(IEnumerable<ParseObject> adds, IEnumerable<ParseObject> removes) { adds = adds ?? new ParseObject[0]; removes = removes ?? new ParseObject[0]; this.targetClassName = adds.Concat(removes).Select(o => o.ClassName).FirstOrDefault(); this.adds = new ReadOnlyCollection<string>(IdsFromObjects(adds).ToList()); this.removes = new ReadOnlyCollection<string>(IdsFromObjects(removes).ToList()); }
private static bool CheckDigits (IList <int> digits, Tuple <int, int> factorsPair) { var allDigits = digits .Concat (factorsPair.Item1.GetDigits ()) .Concat (factorsPair.Item2.GetDigits ()) .ToList (); if (allDigits.Count != 9) return false; return nineDigits.SequenceEqual ( allDigits.OrderBy (d => d)); }
public static IList<string> ProcessWatchers(this IBot bot, string repositoryName, IList<string> existingWatchers, IEnumerable<dynamic> watchers) { var currentWatchers = watchers.Select(c => c.login.ToString()).Cast<string>().ToList(); var newWatchers = currentWatchers.Except(existingWatchers).ToList(); foreach (var w in newWatchers) { bot.SayToAllRooms(string.Format("{0} is now watching {1}", w, repositoryName)); } var noLongerWatching = existingWatchers.Except(currentWatchers).ToList(); foreach (var w in noLongerWatching) { bot.SayToAllRooms(string.Format("{0} is no longer watching {1}", w, repositoryName)); } return existingWatchers.Concat(newWatchers).Except(noLongerWatching).ToList(); }
public IList<UserPostDto> GetPostsByInterests(IList<Interest> interests) { //get user interests //get sibling and parent interests var interestAndParentInterests = interests .Concat(interests.Select(x => x.ParentInterest)) .Where(x => x != null) .Distinct() .ToList(); var posts = _postRepository.GetPostsByInterestTypes(interestAndParentInterests).ToList(); //get all media with any matching interests order by date desc limit by 100 var recentPosts = posts.OrderByDescending(x => x.CreateDate).Take(200); /* * my thinking is take the last 100 because a user probably won't read past that.. * if we only grab the first 10 then there is the problem that 11th might be extremely relevent * but shows up much later on cause it's * slightly older */ return recentPosts.Select( post => { int rank = 0; //we know the medium has a userInterest tied to it if (interests.Contains(post.Interest)) rank = 10; else if (post.Interest.ParentInterest != null && interestAndParentInterests.Contains(post.Interest.ParentInterest)) rank = 2; else if (interestAndParentInterests.Contains(post.Interest)) rank = 1; int daysSinceMediumCreated = (DateTime.UtcNow - post.CreateDate).Days; rank -= daysSinceMediumCreated; return new { Rank = rank, FeedItem = new UserPostDto(post) }; }).OrderByDescending(x => x.Rank).Select(x => x.FeedItem).ToList(); }
private IEnumerable<IList<Color>> GetNextLayer(IList<Color> list) { var colors = new List<Color>() { Color.NotSet, Color.Blue, Color.Black, Color.Red, Color.White, Color.Yellow }; foreach (var color in colors) { yield return list.Concat(new List<Color>() { color }).ToList(); } }
private IList<DssExportHistory> GroupData(IList<LocationTransaction> locTrans, DssOutboundControl dssOutboundControl, DateTime effectiveDate) { #region 补充0成品工单 var fgOrderDetIdList = locTrans .Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO)) .Select(l => l.OrderDetailId).Distinct().ToList(); var rmOrderDetIdList = locTrans .Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_ISS_WO)) .Select(l => l.OrderDetailId).Distinct().ToList(); var addList = rmOrderDetIdList.Except(fgOrderDetIdList).Distinct().ToList(); #region 添加虚拟RCT-WO if (addList.Count > 0) { IList<LocationTransaction> virtualWOList = this.GetVirRctWo(addList);//GetVirtualRCTWO 修改为 GetVirRctWo if (virtualWOList.Count > 0) { foreach (var virtualWO in virtualWOList) { virtualWO.TransactionType = BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO; virtualWO.EffectiveDate = effectiveDate; virtualWO.Qty = 0; } locTrans = locTrans.Concat(virtualWOList).ToList(); } } #endregion #endregion #region Transformer var fgQuery = locTrans.Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_WO)).ToList(); var rmQuery = locTrans.Where(l => StringHelper.Eq(l.TransactionType, BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_ISS_WO)).ToList(); log.Debug("Begin to group single data, count:" + fgQuery.Count); IList<DssExportHistory> dssExportHistoryList = this.GroupSingleDssExportHistory(fgQuery, rmQuery, dssOutboundControl, effectiveDate); #endregion return dssExportHistoryList; }
public static IList<ParameterName> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames = null) { reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameColon != null)).ToList(); var parameterNames = reservedNames.Concat( arguments.Select(semanticModel.GenerateNameForArgument)).ToList(); return GenerateNames(reservedNames, isFixed, parameterNames); }
private static IList<TAgents> SonAgentMethod(int id, APIDataDataContext db, IList<TAgents> agent) { var sonagents = (from c in db.TAgents where c.DirectAgentID == id select c).ToList(); foreach (var item in sonagents) { agent = SonAgentMethod(item.ID, db, agent); } agent = agent.Concat(sonagents).ToList(); return agent; }
private static void ParseParameters(IList<IWhere> wheres) { var index = 1; var list = new List<string>(); var innerparams = wheres .Where(w => w.Parameter.Type == ParameterType.Query) .SelectMany(w => ((IAdfQuery) w.Parameter.Value).Wheres); // NULL and NOT NULL are rendered different and dont use a parameter var allWheres = wheres.Concat(innerparams).Where(w => w.Operator != OperatorType.IsNull && w.Operator != OperatorType.IsNotNull); foreach (var where in allWheres) { if (where.Parameter.Name.IsNullOrEmpty()) { where.Parameter.Name = where.Column.ColumnName; } if (list.Contains(where.Parameter.Name)) { where.Parameter.Name += index++; } list.Add(where.Parameter.Name); ApplyLike(where); } }
private static BasicBlock InlineIR(this CALLInstruction call, IList<BasicBlockInstruction> preamble, BasicBlock backend, Dictionary<Subprogram, Dictionary<VirtualRegister, VirtualRegister>> inlineRegMaps) { Dictionary<VirtualRegister, VirtualRegister> inlineRegMap; if (!inlineRegMaps.TryGetValue(call.Target, out inlineRegMap)) { inlineRegMap = call.Target.LocalVariables.Select(lv => new KeyValuePair<VirtualRegister, VirtualRegister>(lv, new VirtualRegister(lv.UnderlyingType, lv.StateSpace))). ToDictionary(kvp => kvp.Key, kvp => kvp.Value); inlineRegMaps.Add(call.Target, inlineRegMap); } inlineRegMap = inlineRegMap.Concat(call.Target.FormalParameters.Zip(call.Arguments, (formal, actual) => new KeyValuePair<VirtualRegister, VirtualRegister>(formal, (actual is VirtualRegister) ? (actual as VirtualRegister) : (formal.StateSpace != StateSpaces.REG) ? new VirtualRegister(formal.UnderlyingType, formal.StateSpace) : new VirtualRegister(formal.DataType)))). ToDictionary(kvp => kvp.Key, kvp => kvp.Value); Dictionary<BasicBlock, BasicBlock> cfgmap = call.Target.GetBasicBlocks().Select(bb => { VirtualRegister flag = (bb.Trailer is JumpIfInstruction) ? (bb.Trailer as JumpIfInstruction).Flag.MapOperand(inlineRegMap) : null; ControlFlowInstruction trailer; switch (bb.Trailer.OpCode) { case IROpCodes.RET: trailer = new JMPInstruction() { Target = backend }; break; case IROpCodes.JMP: trailer = new JMPInstruction(); break; case IROpCodes.JT: trailer = new JTInstruction(flag); break; case IROpCodes.JF: trailer = new JFInstruction(flag); break; default: throw new NotSupportedException(); } return new KeyValuePair<BasicBlock, BasicBlock>(bb, new BasicBlock(bb.Code.Select(bbi => bbi.MapInstruction(inlineRegMap)).ToList(), trailer)); }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); foreach (KeyValuePair<BasicBlock, BasicBlock> bbmap in cfgmap) { if (bbmap.Key.Successor != null) bbmap.Value.Successor = cfgmap[bbmap.Key.Successor]; if (bbmap.Key.Target != null) bbmap.Value.Target = cfgmap[bbmap.Key.Target]; } BasicBlock root = cfgmap[call.Target.CFGRoot]; return new BasicBlock(preamble.Concat(root.Code).ToList(), root.Trailer); }
/// <summary> /// Process test storage and add dependent assemblies to dependencyDeploymentItems. /// </summary> /// <param name="testSource">The test source.</param> /// <param name="configFile">The config file.</param> /// <param name="deploymentItems">Deployment items.</param> /// <param name="warnings">Warnings.</param> private void AddDependencies(string testSource, string configFile, IList <DeploymentItem> deploymentItems, IList <string> warnings) { Debug.Assert(!string.IsNullOrEmpty(testSource), "testSource should not be null or empty."); // config file can be null. Debug.Assert(deploymentItems != null, "deploymentItems should not be null."); Debug.Assert(Path.IsPathRooted(testSource), "path should be rooted."); // Note: if this is not an assembly we simply return empty array, also: // we do recursive search and report missing. IList <string> warningList; string[] references = this.AssemblyUtility.GetFullPathToDependentAssemblies(testSource, configFile, out warningList); if (warningList != null && warningList.Count > 0) { warnings = warnings.Concat(warningList).ToList(); } if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DeploymentManager: Source:{0} has following references", testSource); } foreach (string reference in references) { DeploymentItem deploymentItem = new DeploymentItem(reference, string.Empty, DeploymentItemOriginType.Dependency); this.DeploymentItemUtility.AddDeploymentItem(deploymentItems, deploymentItem); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("DeploymentManager: Reference:{0} ", reference); } } }
/// <summary> /// Gets all user groups. /// </summary> /// <returns></returns> public virtual IList <UserGroup> GetAllUserGroups() { if (_userGroups != null) { return(_userGroups); } Domain domain = Domain.GetDomain(_sitecoreContext.BackendDomainName); IList <Role> sitecoreDomainRoles = domain.GetRoles().ToList(); IList <UserGroup> existingUserGroups = UserGroup.All().ToList(); //If number of roles matches in both ends we assume everything is up to date. if (sitecoreDomainRoles.Count == existingUserGroups.Count) { _userGroups = sitecoreDomainRoles.Select(x => MapExternalUserGroupToInternalUserGroup(x.LocalName)).ToList(); return(_userGroups); } lock (_lock) { var roleNamesNotCreatedAsUserGroups = sitecoreDomainRoles.Where(x => existingUserGroups.All(y => y.ExternalId != x.LocalName)).Select(x => x.LocalName).ToList(); var newGroups = MapExternalUserGroupsToInternalUserGroups(roleNamesNotCreatedAsUserGroups); ObjectFactory.Instance.Resolve <IRepository <UserGroup> >().Save(newGroups); var allGroups = existingUserGroups.Concat(newGroups).ToList(); _userGroups = allGroups; return(_userGroups); } }
public Connection(IMessageBus newMessageBus, JsonSerializer jsonSerializer, string baseSignal, string connectionId, IList <string> signals, IList <string> groups, ILoggerFactory loggerFactory, IAckHandler ackHandler, IPerformanceCounterManager performanceCounterManager, IProtectedData protectedData, IMemoryPool pool) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } _bus = newMessageBus; _serializer = jsonSerializer; _baseSignal = baseSignal; _connectionId = connectionId; _signals = new List <string>(signals.Concat(groups)); _groups = new DiffSet <string>(groups); _logger = loggerFactory.CreateLogger <Connection>(); _ackHandler = ackHandler; _counters = performanceCounterManager; _protectedData = protectedData; _excludeMessage = m => ExcludeMessage(m); _pool = pool; }
public ScreenRecordForm( IPluginHost pluginHost ) : base(pluginHost) { this.StickyWindow = new DroidExplorer.UI.StickyWindow ( this ); CommonResolutions = GetCommonResolutions ( ); InitializeComponent ( ); var defaultFile = "screenrecord_{0}_{1}.mp4".With ( this.PluginHost.Device, DateTime.Now.ToString ( "yyyy-MM-dd-hh" ) ); this.location.Text = "/sdcard/{0}".With ( defaultFile ); var resolution = new VideoSize ( PluginHost.CommandRunner.GetScreenResolution ( ) ); var sizes = CommonResolutions.Concat ( new List<VideoSize> { resolution } ).OrderBy ( x => x.Size.Width ).Select ( x => x ).ToList ( ); resolutionList.DataSource = sizes; resolutionList.DisplayMember = "Display"; resolutionList.ValueMember = "Size"; resolutionList.SelectedItem = resolution; rotateList.DataSource = GetRotateArgumentsList ( ); rotateList.DisplayMember = "Display"; rotateList.ValueMember = "Arguments"; var bitrates = new List<BitRate> ( ); for ( int i = 1; i < 25; i++ ) { bitrates.Add ( new BitRate ( i ) ); } bitrateList.DataSource = bitrates; bitrateList.DisplayMember = "Display"; bitrateList.ValueMember = "Value"; bitrateList.SelectedItem = bitrates.Single ( x => x.Mbps == 4 ); var ts = new TimeSpan ( 0, 0, 0, timeLimit.Value, 0 ); displayTime.Text = ts.ToString ( ); }
public IHttpActionResult GetAirlinesNames() { Dictionary <long, string> numberAndAirlineDict = new Dictionary <long, string>(); IList <Flight> flights1 = anonymous.GetFlightsDepartureAtNext12Hours(); IList <Flight> flights2 = anonymous.GetFlightsLandAtNext12Hours(); var flights = flights1.Concat(flights2); if (flights.Count() == 0) { return(NotFound()); } foreach (Flight f in flights) { long Id = f.AirlineCompanyId; string name = apiFacade.GetMyCompany(f.AirlineCompanyId).AirlineName; if (numberAndAirlineDict.ContainsKey(Id)) { continue; } else { numberAndAirlineDict.Add(Id, name); } } return(Ok(numberAndAirlineDict)); }
public IHttpActionResult GetDestinationCountryNames() { Dictionary <long, string> numberAndCountryDict = new Dictionary <long, string>(); IList <Flight> flights1 = anonymous.GetFlightsDepartureAtNext12Hours(); IList <Flight> flights2 = anonymous.GetFlightsLandAtNext12Hours(); var flights = flights1.Concat(flights2); if (flights.Count() == 0) { return(NotFound()); } foreach (Flight f in flights) { long Id = f.DestinationCountryCode; string name = anonymous.GetNameCountryById(f.DestinationCountryCode); if (numberAndCountryDict.ContainsKey(Id)) { continue; } else { numberAndCountryDict.Add(Id, name); } } return(Ok(numberAndCountryDict)); }
public void PreSave(IList <object> added, IList <object> updated, IList <object> removed) { foreach (var item in added.Concat(updated)) { this.ValidateObjectAndThrow(item); } }
public static IList <DocumentScore> CombineOrPhrase(IList <DocumentScore> first, IList <DocumentScore> other) { if (first == null && other == null) { return(new DocumentScore[0]); } if (first == null) { return(other); } if (other == null) { return(first); } return(first.Concat(other).GroupBy(x => x.DocumentId).Select(group => { var list = group.ToArray(); var top = list[0]; for (int index = 1; index < list.Length; index++) { top.Add(list[index]); } return top; }).ToArray()); }
/// Creates an instance of a MultiLayerSurfaceFiberTissue /// </summary> /// <param name="surfaceFiberRegion">circular surface fiber region and characteristics</param> /// <param name="layerRegions">list of tissue regions comprising tissue</param> /// <remarks>air above and below tissue needs to be specified for a slab geometry</remarks> public MultiLayerWithSurfaceFiberTissue(ITissueRegion surfaceFiberRegion, IList <ITissueRegion> layerRegions) : base(layerRegions.Concat(surfaceFiberRegion).ToArray()) { _layerRegions = layerRegions.Select(region => (LayerTissueRegion)region).ToArray(); _surfaceFiberRegion = surfaceFiberRegion; }
public Fonts(IList <Typeface> localTypefaces, float pointSize) : base(pointSize) { var typefaces = localTypefaces.Concat(GlobalTypefaces); Typefaces = typefaces; MathTypeface = typefaces.First(t => t.HasMathTable()); }
private void UpdateBranches(RemoteActionResult <IList <IGitRef> > branchList) { Cursor = Cursors.Default; if (branchList.HostKeyFail) { string remoteUrl = _NO_TRANSLATE_From.Text; if (FormRemoteProcess.AskForCacheHostkey(this, Module, remoteUrl)) { LoadBranches(); } } else if (branchList.AuthenticationFail) { string loadedKey; if (FormPuttyError.AskForKey(this, out loadedKey)) { LoadBranches(); } } else { string text = _NO_TRANSLATE_Branches.Text; List <string> branchlist = _defaultBranchItems.Concat(branchList.Result.Select(o => o.LocalName)).ToList(); _NO_TRANSLATE_Branches.DataSource = branchlist; if (branchlist.Any(a => a == text)) { _NO_TRANSLATE_Branches.Text = text; } } }
/// <summary> /// 向各个订阅的客户端发布消息。 /// </summary> /// <param name="type">发布消息的类型。</param> /// <param name="msg">待发布的消息。</param> /// <returns>发布管道的执行上下文。</returns> public EventContext Publish(string type, object msg) { var context = new EventContext(msg); IList <ISubscriber> result = null; if (Store.TryGetValue(type, out result)) { if (GlobalPublish != null && GlobalPublish.Any()) { result = result.Concat(GlobalPublish) .Distinct(new EqualComparer <ISubscriber>((x, y) => object.ReferenceEquals(x, y))) .OrderBy(p => p.Index) .ToList(); } else { result = result.ToList(); } } else { result = GlobalPublish.ToList(); } PublishCore(result, context); return(context); }
/// <summary> /// Creates a copy of this WebRequester, with an additional requestModifier /// </summary> /// <param name="requestModifier">An Action for modifying the request message before send.</param> /// <returns>a copy of this WebRequester, with an additional requestModifier</returns> public WebRequester With(Action <HttpRequestMessage> requestModifier) { if (requestModifier == null) { throw new ArgumentNullException(nameof(requestModifier)); } return(CopyWith(requestModifiers: _requestModifiers.Concat(new[] { requestModifier }))); }
/// <summary> /// Recursive method to find all child name change unit hierarchies. /// </summary> /// <param name="hierarchies"></param> /// <returns></returns> public virtual IList <UnitHierarchy> GetChildChangedNameUnitHierarchiesRecursive(IList <UnitHierarchy> hierarchies) { var children = this.UnitHierarchyChildren .Where(x => !x.Archive && string.Equals(x.UnitHierarchyType.UnitHierarchyTypeName, UnitHierarchyType.NAME_CHANGED_NAME_TO)) .OrderBy(x => x.ParentUnit.UnitName); if (children.Any()) { hierarchies = hierarchies.Concat(children).ToList(); foreach (UnitHierarchy child in children) { hierarchies = hierarchies.Concat(child.Unit.GetChildChangedNameUnitHierarchiesRecursive(hierarchies)).ToList(); } } return(hierarchies.Distinct().ToList()); }
public Tile(int pennants, int cloisters, IList<Edge> edges, Uri imageUri, IList<Follower> followerPositions) { ImageUri = imageUri; Pennants = pennants; Cloisters = cloisters; this.edges = edges.Concat(edges).ToList(); this.followerPositions = followerPositions; }
public static (int one, int three) FindDifferences(IList <int> adapters) { var max = adapters.Max(); var sorted = adapters.Concat(new[] { 0, max + 3 }).OrderBy(i => i).ToList(); var differences = sorted.Zip(sorted.Skip(1), (i, j) => j - i).ToList(); return(differences.Count(i => i == 1), differences.Count(i => i == 3)); }
public Diff(IList <IModule> added, IList <IModule> updated, IList <IModule> desiredStatusUpdated, IList <string> removed) { this.Updated = Preconditions.CheckNotNull(updated, nameof(updated)).ToImmutableHashSet(); this.Removed = Preconditions.CheckNotNull(removed, nameof(removed)).ToImmutableHashSet(); this.DesiredStatusUpdated = Preconditions.CheckNotNull(desiredStatusUpdated, nameof(desiredStatusUpdated)).ToImmutableHashSet(); this.Added = Preconditions.CheckNotNull(added, nameof(added)).ToImmutableHashSet(); this.AddedOrUpdated = added.Concat(updated).ToImmutableHashSet(); }
/// <summary> /// Given two integers expressed as a list of prime factors, multiplies these numbers /// together and returns an integer also expressed as a set of prime factors. /// This allows multiplication to overflow well beyond a Int64 if necessary. /// </summary> /// <param name="lhs">Left Hand Side argument, expressed as list of prime factors.</param> /// <param name="rhs">Right Hand Side argument, expressed as list of prime factors.</param> /// <returns>Product, expressed as list of prime factors.</returns> public static List <int> MultiplyPrimeFactors(IList <int> lhs, IList <int> rhs) { var product = lhs.Concat(rhs).ToList(); product.Sort(); return(product); }
public static long CountArrangements(IList <int> adapters) { var max = adapters.Max(); var sorted = adapters.Concat(new[] { 0, max + 3 }).OrderBy(i => i).ToList(); var differences1 = sorted.Zip(sorted.Skip(1), (i, j) => j - i).ToList(); var differences2 = sorted.Zip(sorted.Skip(2), (i, j) => j - i); var differences3 = sorted.Zip(sorted.Skip(3), (i, j) => j - i); var nbOk = differences2.Zip(differences3, (a, b) => (a: a, b: b)) .Select(tuple => { var count = 0; if (tuple.b <= 3) { count++; } if (tuple.a <= 3) { count++; } return(count + 1); }).ToList(); int x = 0, y = 0, z = 0; var runLength = 0; for (int i = 0; i < differences1.Count(); i++) { if (differences1[i] == 1) { runLength++; } else { switch (runLength) { case 2: x++; break; case 3: y++; break; case 4: z++; break; } runLength = 0; } } return((long)(Math.Pow(2, x) * Math.Pow(4, y) * Math.Pow(7, z))); }
/// <summary> /// Get all the flights from this server and other servers. /// </summary> /// <param name="relativeTo"> Time at the student's. </param> /// <returns> All the flights. </returns> public async Task <IList <Flight.Flight> > GetAllFlightsSync(DateTime relativeTo) { // Get first all local flights. Task <IList <Flight.Flight> > localFlights = GetAllFlights(relativeTo); /* Create a list contains lists of external flights. * Each inner list represents flights from a specifiec server. */ IList <Task <IList <Flight.Flight> > > externalFlights = new List <Task <IList <Flight.Flight> > >(); IList <KeyValuePair <string, string> > serversUpdates = new List <KeyValuePair <string, string> >(); await foreach (Server server in serversDB.GetAllServers()) { // For each server, ask it for all its flights. HTTPClient client = new HTTPClient(server); Task <IList <Flight.Flight> > externals = client.GetFlights( relativeTo.ToString("yyyy-MM-ddTHH:mm:ssZ")); IList <Flight.Flight> res = await externals; if (res == null) { continue; } foreach (Flight.Flight flight in res) { /* Change isExternal property of the flight to true, * as it was retrieved from an external server. */ flight.IsExternal = true; serversUpdates.Add(new KeyValuePair <string, string>( flight.FlightID, server.Id)); } externalFlights.Add(externals); } IList <Flight.Flight> temp = await localFlights; /* Join all the lists from the servers and the list of the local flight to * one list of flights. */ foreach (Task <IList <Flight.Flight> > flightsList in externalFlights) { temp = temp.Concat(await flightsList).ToList(); } foreach (KeyValuePair <string, string> pair in serversUpdates) { /* Add the id of the flight to the data base. Connect it to its server. * Next time we want the flight plan we can * simply ask it from the relevant server. */ await flightsServersDB.AddFlightServer( new Servers.FlightServer(pair.Key, pair.Value)); } return(temp); }
public IEnumerable <IEntityMapConfig> GetEntityMaps(MultiTenancySides?sides = null) { if (sides == null) { return(_hostEntityMaps.Concat(_tenantEntityMaps)); } return(sides.Value == MultiTenancySides.Host ? _hostEntityMaps : _tenantEntityMaps); }
private void btnSaveUpList_Click(object sender, EventArgs e) { using (var save = DialogFactory.SaveFile()) { save.Filter = string.Format(OSGeo.MapGuide.MaestroAPI.Strings.GenericFilter, OSGeo.MapGuide.MaestroAPI.Strings.PickTxt, "txt"); //NOXLATE if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (chkIncludeSelected.Checked) { System.IO.File.WriteAllLines(save.FileName, _selResources.Concat(_uplist)); } else { System.IO.File.WriteAllLines(save.FileName, _uplist); } } } }
void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.HighQuality; if (algorithmSet == null || algorithmSet.Nodes == null) { return; } matrix = new TransformationMatrix(sender as Control, boundingRectangle.ToGDI()); var board = new GDI.Drawingboard(matrix, e.Graphics); if (checkBox1.Checked) { var counter = 0; foreach (var c in algorithmSet.Nodes) { board.DrawCoordinate(c.ToGDI(), algorithmSet.Nodes.Count < 100, (++counter).ToString()); } } if (algorithmSet.LastRoute != null && checkBox3.Checked) { using (var pen = new Pen(Color.Blue, 0)) e.Graphics.DrawLines(pen, algorithmSet.LastRoute.Concat(new[] { algorithmSet.LastRoute.First() }).Select(h => algorithmSet.Nodes[h].ToGDI()).ToArray()); } //else if (algorithmSet.LastTSPResult != null && checkBox3.Checked) //{ // using (var pen = new Pen(Color.Blue, 0)) // { // e.Graphics.DrawLines(pen, algorithmSet.LastTSPResult.TourOrPath.Concat(new[] { algorithmSet.LastTSPResult.TourOrPath.First() }).Select(h => h.ToGDI()).ToArray()); // } //} if (lastTSPResultWithClusters != null && checkBox4.Checked) { using (var pen = new Pen(Color.Red, 0)) { e.Graphics.DrawLines(pen, lastTSPResultWithClusters.Concat(new[] { lastTSPResultWithClusters.First() }).Select(h => h.ToGDI()).ToArray()); } } if (algorithmSet.Clusters != null && checkBox2.Checked) { using (var pen = new Pen(Color.Green, 0)) foreach (var cluster in algorithmSet.Clusters) { if (cluster.Nodes.Count() > 1) { //var hul = new ConvexHull().Algorithm(cluster); //e.Graphics.DrawPolygon(pen, hul.Select(h => h.ToGDI()).ToArray()); e.Graphics.DrawLines(pen, cluster.Nodes.Select(h => h.ToGDI()).ToArray()); } } } }
public override IAstNode VisitScopedBlock(MicroCParser.ScopedBlockContext context) { _symbolTable.AddScope(); IList <IStatement> declarations = context.declaration().Select(x => Visit(x) as IStatement).ToList(); IList <IStatement> statements = context.statement().Select(x => Visit(x) as IStatement).ToList(); _symbolTable.RemoveScope(); return(new ScopedBlock(declarations.Concat(statements))); }
override protected async Task <bool> Predict(string groupId, double matchThreshold, IList <Guid> faces1, IList <Guid> faces2) { var allPeople = await IdentifyPeople(faces1.Concat(faces2), groupId, matchThreshold); var people1 = allPeople.Where(candidates => faces1.Contains(candidates.FaceId)).SelectMany(candidates => candidates.Candidates).Select(person => person.PersonId).ToHashSet(); var people2 = allPeople.Where(candidates => faces2.Contains(candidates.FaceId)).SelectMany(candidates => candidates.Candidates).Select(person => person.PersonId).ToHashSet(); return(people1.Any(person => people2.Contains(person))); }
/// <summary> /// Performs the actual registration. /// </summary> /// <param name="addititionalInjectionMembers">additional injection members that will be added to those previously specified</param> public void Register(params InjectionMember[] addititionalInjectionMembers) { BuildInjectionMember(); var injectionMembers = addititionalInjectionMembers == null ? _injectionMembers.ToArray() : _injectionMembers.Concat(addititionalInjectionMembers).ToArray(); _container.RegisterType(typeof(TFrom), typeof(TTo), _name, _lifetimeManager, injectionMembers); }
public void Add(IActionSource3 source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Sources = Sources.Concat(source).ToList(); }
public AVRelationOperation(IEnumerable <AVObject> adds, IEnumerable <AVObject> removes) { adds = adds ?? new AVObject[0]; removes = removes ?? new AVObject[0]; this.targetClassName = adds.Concat(removes).Select(o => o.ClassName).FirstOrDefault(); this.adds = new ReadOnlyCollection <string>(IdsFromObjects(adds).ToList()); this.removes = new ReadOnlyCollection <string>(IdsFromObjects(removes).ToList()); }
protected virtual async Task <PropertyListing> LoadAgents(PropertyListing listing) { IList <ApplicationUser> admins = await _account.GetUsersInRole("Admin"); IList <ApplicationUser> editors = await _account.GetUsersInRole("Editor"); listing.AvailableAgents = editors.Concat(admins).Distinct().OrderBy(u => u.FirstName).ThenBy(u => u.Email).ToList(); return(listing); }
public IEnumerable <PropertyMap> GetPropertyMaps() { if (_sealed) { return(_orderedPropertyMaps); } return(_propertyMaps.Concat(_inheritedMaps)); }
private static IList <T> EndOptions(IList <T> options, T end) { if (options.Count == 0 || options.Last().Equivalent(end) || SumBytesLength(options) % 4 == 0) { return(options); } return(new List <T>(options.Concat(end))); }
public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames = null) { reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameEquals != null)).ToList(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a))).ToList(); return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList(); }
/// <summary> /// Returns the test counts. /// </summary> private static IList<BuildTestCount> GetTestCounts( IList<BuildTestCount> allBuildTestCounts) { if (allBuildTestCounts.Count == 1) { // The charting library does not work well with only one point. // So we'll give it two identical points. allBuildTestCounts = allBuildTestCounts .Concat(allBuildTestCounts) .ToList(); } return allBuildTestCounts; }
/// <summary> /// Prepare model /// </summary> /// <param name="alreadyFilteredSpecOptionIds">IDs of already filtered specification options</param> /// <param name="filterableSpecificationAttributeOptionIds">IDs of filterable specification options</param> /// <param name="specificationAttributeService"></param> /// <param name="webHelper">Web helper</param> /// <param name="workContext">Work context</param> /// <param name="cacheManager">Cache manager</param> public virtual void PrepareSpecsFilters(IList<int> alreadyFilteredSpecOptionIds, int[] filterableSpecificationAttributeOptionIds, ISpecificationAttributeService specificationAttributeService, IWebHelper webHelper, IWorkContext workContext, ICacheManager cacheManager) { Enabled = false; var optionIds = filterableSpecificationAttributeOptionIds != null ? string.Join(",", filterableSpecificationAttributeOptionIds) : string.Empty; var cacheKey = string.Format(ModelCacheEventConsumer.SPECS_FILTER_MODEL_KEY, optionIds, workContext.WorkingLanguage.Id); var allOptions = specificationAttributeService.GetSpecificationAttributeOptionsByIds(filterableSpecificationAttributeOptionIds); var allFilters = cacheManager.Get(cacheKey, () => allOptions.Select(sao => new SpecificationAttributeOptionFilter { SpecificationAttributeId = sao.SpecificationAttribute.Id, SpecificationAttributeName = sao.SpecificationAttribute.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id), SpecificationAttributeDisplayOrder = sao.SpecificationAttribute.DisplayOrder, SpecificationAttributeOptionId = sao.Id, SpecificationAttributeOptionName = sao.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id), SpecificationAttributeOptionColorRgb = sao.ColorSquaresRgb, SpecificationAttributeOptionDisplayOrder = sao.DisplayOrder }).ToList()); if (!allFilters.Any()) return; //sort loaded options allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder) .ThenBy(saof => saof.SpecificationAttributeName) .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder) .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList(); //prepare the model properties Enabled = true; var removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM); RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper); //get already filtered specification options var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId)); AlreadyFilteredItems = alreadyFilteredOptions.Select(x => new SpecificationFilterItem { SpecificationAttributeName = x.SpecificationAttributeName, SpecificationAttributeOptionName = x.SpecificationAttributeOptionName, SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb }).ToList(); //get not filtered specification options NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x => { //filter URL var alreadyFiltered = alreadyFilteredSpecOptionIds.Concat(new List<int> { x.SpecificationAttributeOptionId }); var queryString = string.Format("{0}={1}", QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList())); var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), queryString, null); return new SpecificationFilterItem() { SpecificationAttributeName = x.SpecificationAttributeName, SpecificationAttributeOptionName = x.SpecificationAttributeOptionName, SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb, FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper) }; }).ToList(); }
private static IList<string> OrderScripts(IList<string> dependencyScripts, IEnumerable<string> originalScripts) { var scripts = dependencyScripts.Concat(originalScripts).Distinct().ToList(); if (scripts.Any(x => x.Contains("sf-list-selector"))) { scripts.Insert(0, "client-components/selectors/common/sf-list-selector.js"); } scripts.Insert(0, "client-components/selectors/common/sf-selectors.js"); scripts.Insert(0, "client-components/selectors/common/sf-services.js"); if (scripts.Any(x => x.Contains("sf-fields"))) { scripts.Insert(0, "client-components/fields/sf-fields.js"); } var mvcScripts = scripts.Where(x => x.IndexOf("Mvc/Scripts/", 0, StringComparison.Ordinal) >= 0).ToList(); foreach (var mvcScript in mvcScripts) { scripts.Insert(0, mvcScript); } var angularScripts = scripts.Where(x => x.IndexOf("angular", 0, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); foreach (var angularScript in angularScripts) { scripts.Insert(0, angularScript); } return scripts.Distinct().ToList(); }
private static IList<int> Merge2ListRecurseImple(IList<int> thisList, IList<int> thatList, int thisCounter, int thatCounter, int thisLength, int thatLength, IList<int> result) { Contract.Requires(thisList != null && thatList != null); //Base Case //Do nothing when reaches end of lists if (thisCounter == thisLength && thatCounter == thatLength) return result; if (thisCounter < thisLength && thatCounter < thatLength) { if (thisList[thisCounter] > thatList[thatCounter]) { result.Add(thatList[thatCounter]); ++thatCounter; } else { result.Add(thisList[thisCounter]); ++thisCounter; } } if (thisCounter == thisLength) { result = result.Concat(thatList).ToList(); return result; } if (thatCounter == thatLength) { result = result.Concat(thisList).ToList(); return result; } Contract.Ensures(result != null); return Merge2ListRecurseImple(thisList, thatList, thisCounter, thatCounter, thisLength, thatLength, result); }
public LevelsEntitiesController() { Entities = new List<LevelsEntity>(); for (int i = 1; i <= 10; i++) { if (i % 2 == 1) { var newEntity = new LevelsEntity { ID = i, Name = "Name " + i, Parent = Entities.LastOrDefault(), BaseEntities = Entities.Concat(new[] { new LevelsBaseEntity { ID = i + 10, Name = "Name " + (i + 10) } }).ToArray(), DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray() }; Entities.Add(newEntity); } else { var newEntity = new LevelsDerivedEntity { ID = i, Name = "Name " + i, DerivedName = "DerivedName " + i, Parent = Entities.LastOrDefault(), BaseEntities = Entities.Concat(new[] { new LevelsBaseEntity { ID = i + 10, Name = "Name " + (i + 10) } }).ToArray(), DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray(), AncestorsInDerivedEntity = Entities.ToArray() }; Entities.Add(newEntity); } } Entities[8].Parent = Entities[9]; Entities[1].DerivedAncestors = new LevelsDerivedEntity[] { (LevelsDerivedEntity)Entities[3] }; }
private IBuilder MergeSteps(IList<IBuilder> additionalSteps, MSBuildRunner msbuild, IEnumerable<Project> projects) { var prjs = projects.ToArray(); if (additionalSteps.Count > 0) { return coreBuilderFactory.CreateMergingBuilder(additionalSteps.Concat(new[] { msbuild }), new ProjectBuilderTag(String.Format("Runtime deps with project builders for {0}", String.Join(", ", prjs.Select(p => p.Name))), prjs)); } else { return msbuild; } }
public Neighbour Choose(IList<Neighbour> neighbours, Neighbour self) { LogFacade.Instance.LogDebug("Choosing a master, candidates = " + (neighbours.IsNull() ? 0 : neighbours.Count)); var n = neighbours.IsNull() ? null : neighbours.Concat(new [] { self }).Where(_ => !_.InEligibleForElection).Aggregate((i, j) => i.AbsoluteBootTime < j.AbsoluteBootTime ? i : j); LogFacade.Instance.LogInfo("Candidate selected: " + (n.IsNull() ? "None - thus self" : n.Name)); return n; }
/// <summary> /// Continue the upload functionality with setting of properties /// </summary> /// <param name="request">Current Http request object</param> /// <param name="refreshToken">Refresh token</param> /// <param name="environment">Flag to determine on-line or on-premise deployment</param> /// <param name="upload">Object for current file</param> /// <param name="fileExtension">Extension of current file</param> /// <param name="originalName">Original name of the file</param> /// <param name="listResponse">List of responses</param> /// <param name="folderName">Path of the folder</param> /// <param name="fileName">Name of the file</param> /// <param name="clientContext">SP client context</param> /// <param name="folder">Name of the folder</param> /// <param name="documentLibraryName">Name of the document library</param> /// <returns>list of all the responses being sent</returns> private static IList<string> SetDocumentProperties(HttpRequest request, string refreshToken, HttpPostedFile upload, string fileExtension, string originalName, IList<string> listResponse, string folderName, string fileName, ClientContext clientContext, string folder, string documentLibraryName) { Dictionary<string, string> mailProperties = ContinueUpload(request, refreshToken, upload, fileExtension); //setting original name property for attachment if (string.IsNullOrWhiteSpace(mailProperties[ConstantStrings.MailOriginalName])) { mailProperties[ConstantStrings.MailOriginalName] = originalName; } return listResponse = listResponse.Concat(UploadDocument(folderName, upload, fileName, mailProperties, clientContext, folder, documentLibraryName)).ToList(); }
private int CalculateRequiredDronesForDefense(int zoneId, IList<DroneWithDistance> myDrones, IEnumerable<DroneWithDistance> enemyDroneSquad, out int nbrTurnsToFail) { _log.WriteLine("Defense of zone {0}", zoneId); _log.WriteLine("My drones: {0}", string.Join(",", myDrones.Select(d => d.NbrTurns).OrderBy(n => n))); _log.WriteLine("Enemies: {0}", string.Join(",", enemyDroneSquad.Select(d => d.NbrTurns).OrderBy(n => n))); var myTeamId = myDrones[0].Drone.TeamId; int nbrAllies = 0, nbrEnemies = 0; nbrTurnsToFail = nbrTurnsConsidered; var sortedDroneWaves = myDrones.Concat(enemyDroneSquad) .ToLookup(d => d.NbrTurns) .OrderBy(w => w.Key); foreach(var wave in sortedDroneWaves) { if(wave.Key > nbrTurnsConsidered) break; int alliesBackup = 0; int enemiesBackup = 0; foreach(var drone in wave) { if(drone.Drone.TeamId == myTeamId) alliesBackup++; else enemiesBackup++; } if(nbrAllies + alliesBackup < nbrEnemies + enemiesBackup) { nbrTurnsToFail = wave.Key; return nbrAllies; } nbrAllies += alliesBackup; nbrEnemies += enemiesBackup; } return nbrEnemies; }
protected SignatureHelpItem CreateItem( ISymbol orderSymbol, SemanticModel semanticModel, int position, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, bool isVariadic, Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory, IList<SymbolDisplayPart> prefixParts, IList<SymbolDisplayPart> separatorParts, IList<SymbolDisplayPart> suffixParts, IList<SignatureHelpSymbolParameter> parameters, IList<SymbolDisplayPart> descriptionParts = null) { prefixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position, symbolDisplayService); separatorParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position, symbolDisplayService); suffixParts = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position, symbolDisplayService); parameters = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService)).ToList(); descriptionParts = descriptionParts == null ? SpecializedCollections.EmptyList<SymbolDisplayPart>() : descriptionParts; var allParts = prefixParts.Concat(separatorParts) .Concat(suffixParts) .Concat(parameters.SelectMany(p => p.GetAllParts())) .Concat(descriptionParts); var directAnonymousTypeReferences = from part in allParts where part.Symbol.IsNormalAnonymousType() select (INamedTypeSymbol)part.Symbol; var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo( orderSymbol, directAnonymousTypeReferences, semanticModel, position, symbolDisplayService); if (info.AnonymousTypesParts.Count > 0) { var anonymousTypeParts = new List<SymbolDisplayPart> { new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n") }; anonymousTypeParts.AddRange(info.AnonymousTypesParts); return new SymbolKeySignatureHelpItem( orderSymbol, isVariadic, documentationFactory, info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(), info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(), info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(), parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p), anonymousTypeParts.ToTaggedText()); } return new SymbolKeySignatureHelpItem( orderSymbol, isVariadic, documentationFactory, prefixParts.ToTaggedText(), separatorParts.ToTaggedText(), suffixParts.ToTaggedText(), parameters.Select(p => (SignatureHelpParameter)p), descriptionParts.ToTaggedText()); }