public string Build(BundleType type, IEnumerable<string> files) { if (files == null || !files.Any()) return string.Empty; string bundleVirtualPath = this.GetBundleVirtualPath(type, files); var bundleFor = BundleTable.Bundles.GetBundleFor(bundleVirtualPath); if (bundleFor == null) { lock (s_lock) { bundleFor = BundleTable.Bundles.GetBundleFor(bundleVirtualPath); if (bundleFor == null) { var nullOrderer = new NullOrderer(); Bundle bundle = (type == BundleType.Script) ? new CustomScriptBundle(bundleVirtualPath) as Bundle : new SmartStyleBundle(bundleVirtualPath) as Bundle; bundle.Orderer = nullOrderer; bundle.Include(files.ToArray()); BundleTable.Bundles.Add(bundle); } } } if (type == BundleType.Script) return Scripts.Render(bundleVirtualPath).ToString(); return Styles.Render(bundleVirtualPath).ToString(); }
public VertexArray(IOpenGL30 gl, IEnumerable<IVertexBuffer> buffers, IEnumerable<IVertexDescriptor> descriptors) { IVertexBuffer[] bufferObjects = buffers.ToArray(); IVertexDescriptor[] descs = descriptors.ToArray(); if (descs.Length != bufferObjects.Length) throw new InvalidOperationException("Number of buffers and number of descriptors must match."); uint[] handles = new uint[1]; gl.GenVertexArrays(1, handles); if(handles[0] == 0u) throw new NoHandleCreatedException(); _gl = gl; Handle = handles.Single(); Buffers = bufferObjects; using (Bind()) { int count = 0; for (int index = 0; index < bufferObjects.Length; index++) { var buffer = bufferObjects[index]; var desc = descs[index]; buffer.Bind(); Apply(desc, count); count += desc.Elements.Count(); } } }
public static JudgmentModel CrateJudgmentTree(JudgmentModel judgmentModel, IEnumerable<Property> properties, IEnumerable<Mark> marks) { for (Int32 i = 0; i < properties.Count() - 1; i++) { MarkOfPropertyModel shortInventoryObjectModel = new MarkOfPropertyModel { PropertyId = properties.ToArray()[i].Id, PropertyName = properties.ToArray()[i].Name, Objects = new List<MarkOfPropertyModel>() }; for (var j = i + 1; j < properties.Count(); j++) { shortInventoryObjectModel.Objects.Add(new MarkOfPropertyModel { PropertyId = properties.ToArray()[j].Id, PropertyName = properties.ToArray()[j].Name, Mark = marks.First(m => m.IsDefault).Id }); } judgmentModel.Objects.Add(shortInventoryObjectModel); } return judgmentModel; }
public ManaMismatchException(GameCard card, Player player, IEnumerable<Mana> mana) : base("Error: " + player + " attempted to cast " + card + " with " + mana.ToArray() + ".") { this.card = card; this.player = player; this.mana = mana.ToArray(); }
GetAssemblyNames(IEnumerable<string> filenames, Predicate<Assembly> filter) { #if PCL throw new NotImplementedException(); #else #if !WINRT var assemblyCheckerType = typeof(AssemblyChecker); var temporaryDomain = CreateTemporaryAppDomain(); try { var checker = (AssemblyChecker)temporaryDomain.CreateInstanceAndUnwrap( assemblyCheckerType.Assembly.FullName, assemblyCheckerType.FullName ?? string.Empty); return checker.GetAssemblyNames(filenames.ToArray(), filter); #else var checker = new AssemblyCheckerWinRT(); return checker.GetAssemblyListAsync(filenames.ToArray(), filter); #endif #if !WINRT } finally { AppDomain.Unload(temporaryDomain); } #endif #endif }
public int Delete(IEnumerable<int> Ids) { int num = _database.Execute("Delete from Terms where Id in (" + string.Join(",", Ids.ToArray()) + ")", new Dictionary<string, object>()); _database.Execute("Delete from UserTerms where TermId in (" + string.Join(",", Ids.ToArray()) + ")", new Dictionary<string, object>()); _database.Execute("Delete from GroupTerms where TermId in (" + string.Join(",", Ids.ToArray()) + ")", new Dictionary<string, object>()); return num; }
public override void DoWork(IEnumerable<string> args) { if (Utils.CheckArgs(ArgsNeed, args.Count())) { if (Utils.IsInGame()) { var request = new MoveRequest { From = args.ToArray()[0], To = args.ToArray()[1], InWhom = null, Player = CurrentUser.Name, GameId = CurrentUser.CurrentGame.Value }; var response = ServerProvider.MakeRequest(request); switch (response.Status) { case Statuses.Ok: Console.WriteLine("Move done."); CurrentUser.LastMove = new Move { From = request.From, InWhom = null, Player = CurrentUser.Name, To = request.To }; break; case Statuses.NeedPawnPromotion: Utils.Print("This pawn need promotion!"); Utils.Print("Your choise? (r - rook, n - knight, b - bishop, q - queen, c - cancel):"); CurrentUser.LastMove = new Move { From = request.From, InWhom = null, Player = CurrentUser.Name, To = request.To }; CurrentUser.NeedPawnPromotion = true; break; case Statuses.NoUser: Console.WriteLine("No opponent yet."); break; case Statuses.OpponentTurn: Console.WriteLine("Now is opponent turn."); break; case Statuses.WrongMove: Console.WriteLine("Wrong move."); break; case Statuses.WrongMoveNotation: Console.WriteLine("Wrong move notation."); break; default: Console.WriteLine("Wrong status."); break; } } } }
public void RegisterOperatorsForType(Type type, IEnumerable<Operator> possibleOperators) { if (type == null) throw new ArgumentNullException("type"); if (_opmap.ContainsKey(type)) _opmap[type] = possibleOperators.ToArray(); else _opmap.Add(type, possibleOperators.ToArray()); }
private IEnumerable<ScenarioLine> PreprocessLines(IEnumerable<ScenarioLine> lines, IEnumerable<string> fieldNames, IEnumerable<string> example) { foreach (var line in lines) { var processed = line.Text; for (var fieldIndex = 0; fieldIndex < fieldNames.ToArray().Length; fieldIndex++) { var name = fieldNames.ToArray()[fieldIndex]; processed = processed.Replace("<" + name + ">", example.ElementAtOrDefault(fieldIndex)); } yield return new ScenarioLine {Text = processed, LineNumber = line.LineNumber}; } }
/// <summary> /// Downloads the results of query defined by <paramref name="parameters"/>. /// </summary> public XDocument Download(IEnumerable<HttpQueryParameterBase> parameters) { parameters = parameters.ToArray(); if (LogDownloading) LogRequest(parameters); parameters = new[] { new HttpQueryParameter("format", "xml") }.Concat(parameters); if (UseMaxlag) parameters = parameters.Concat(new[] { new HttpQueryParameter("maxlag", "5") }); var client = new RestClient { BaseUrl = new Uri(m_wiki.ApiUrl.AbsoluteUri + "?rawcontinue"), CookieContainer = m_cookies, UserAgent = UserAgent }; var request = new RestRequest(Method.POST); WriteParameters(parameters, request); var response = client.Execute(request); return XDocument.Parse(response.Content); }
/// <summary> /// Saves all assemblies and returns true if all assemblies were saved to disk /// </summary> /// <param name="asms">All assemblies to save</param> /// <returns></returns> public static bool SaveAssemblies(IEnumerable<LoadedAssembly> asms) { var asmsAry = asms.ToArray(); if (asmsAry.Length == 0) return true; if (asmsAry.Length == 1) { var optsData = new SaveModuleOptionsVM(asmsAry[0].ModuleDefinition); var optsWin = new SaveModuleOptions(); optsWin.Owner = MainWindow.Instance; optsWin.DataContext = optsData; var res = optsWin.ShowDialog(); if (res != true) return false; var data = new SaveMultiModuleVM(optsData); var win = new SaveSingleModule(); win.Owner = MainWindow.Instance; win.DataContext = data; data.Save(); win.ShowDialog(); return MarkAsSaved(data, asmsAry); } else { var data = new SaveMultiModuleVM(asmsAry.Select(a => a.ModuleDefinition)); var win = new SaveMultiModule(); win.Owner = MainWindow.Instance; win.DataContext = data; win.ShowDialog(); return MarkAsSaved(data, asmsAry); } }
public Reference(int rowNum, IEnumerable<ReferenceFields> order, IEnumerable<string> values) { if (values.IsNullOrEmpty()) throw new ArgumentException("values"); if (order.IsNullOrEmpty()) throw new ArgumentException("order"); RowNum = rowNum; var vs = values.ToArray(); var fs = order.ToArray(); if (vs.Length != fs.Length) throw new InvalidOperationException(); var fillErrors = new List<ReferenceFields>(); for (var i = 0; i < vs.Length; i++) { try { SetValue(fs[i], vs[i]); } catch { fillErrors.Add(fs[i]); } } if (fillErrors.Any()) { throw new Exception("Error reading following fields: {0}". Fill(fillErrors.Cast<String>().CommaSeparated())); } }
public static void SetModel(this Parser parser, string definition, IEnumerable<Parser> subParsers = null) { // clean the models from old parsers var model = parser.GetModel(); model.Definition = definition; model.SubParsers = subParsers != null ? subParsers.ToArray() : null; }
public static double solve (bool isFine, IEnumerable<Constraint> cons) { var constraints = cons.ToArray (); // Get the parameters that need solving by selecting "free" ones Parameter[] x = constraints.SelectMany (p=>p) .Distinct () .Where(p=>p.free==true) .ToArray (); Console.WriteLine ("Number of free vars is " + x.Length); // Wrap our constraint error function for Accord.NET Func<double[], double> objective = args => { int i = 0; foreach (var arg in args) { x [i].Value = arg; i++; } return Constraint.calc (constraints); }; var nlConstraints = new List<NonlinearConstraint> (); // Finally, we create the non-linear programming solver var solver = new AugmentedLagrangianSolver(x.Length, nlConstraints); // Copy in the initial conditions x.Select(v=>v.Value).ToArray().CopyTo (solver.Solution,0); // And attempt to solve the problem return solver.Minimize(LogWrap(objective), LogWrap(Grad(x.Length, objective))); }
internal static List<BondStructureOTRCreator> GetXMktSpreads(IEnumerable<BondMarket> markets_, int index_ = -1) { var ret = new List<BondStructureOTRCreator>(); var markets = markets_.ToArray(); for (int i = 0; i < markets.Length; ++i) for (int j = i + 1; j < markets.Length; ++j) { // James needs to supply the order of convention to make this accurage var higherTenor = markets[i]; var lowerTenor = markets[j]; if (index_ == -1) { ret.AddRange(StructureConfigs.InterCountrySpreadPoints.Select(conf => new BondStructureOTRCreator(new[] { new Tuple<int, BondMarket, double>(conf[0], higherTenor, StructureWeightings.Curve_Near), new Tuple<int, BondMarket, double>(conf[0], lowerTenor, StructureWeightings.Curve_Far) }))); } else { ret.Add(new BondStructureOTRCreator(new[] { new Tuple<int,BondMarket,double>(StructureConfigs.InterCountrySpreadPoints[index_][0],higherTenor,StructureWeightings.Curve_Near), new Tuple<int,BondMarket,double>(StructureConfigs.InterCountrySpreadPoints[index_][0],lowerTenor,StructureWeightings.Curve_Far) })); } } return ret; }
public void OnLanguageCreated(IEnumerable<Language> languages) { if (languages != null) { OnLanguageCreated(languages.ToArray()); } }
public Context(MethodCall methodCall, IEnumerable<Step> steps) { Guard.AgainstNullArgument("steps", steps); this.methodCall = methodCall; this.steps = steps.ToArray(); }
public AddNewConfigurationDialog(bool solution, bool editPlatforms, IEnumerable<string> availableSourceItems, Predicate<string> checkNameValid) { this.checkNameValid = checkNameValid; // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); foreach (Control ctl in this.Controls) { ctl.Text = StringParser.Parse(ctl.Text); } createInAllCheckBox.Visible = solution; nameTextBox.TextChanged += delegate { okButton.Enabled = nameTextBox.TextLength > 0; }; copyFromComboBox.Items.Add(StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.EmptyItem}")); copyFromComboBox.Items.AddRange(availableSourceItems.ToArray()); copyFromComboBox.SelectedIndex = 0; if (solution) { if (editPlatforms) this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddSolutionPlatform}"); else this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddSolutionConfiguration}"); } else { if (editPlatforms) this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddProjectPlatform}"); else this.Text = StringParser.Parse("${res:Dialog.EditAvailableConfigurationsDialog.AddProjectConfiguration}"); } }
/// <summary> /// Gets the <see cref="Type" /> matching the provided members. /// </summary> /// <param name="sourceType">The <see cref="Type" /> to generate the runtime type from.</param> /// <param name="properties">The <see cref="MemberInfo" /> to use to generate properties.</param> /// <returns>A <see cref="Type" /> mathing the provided properties.</returns> public Type Get(Type sourceType, IEnumerable<MemberInfo> properties) { properties = properties.ToArray(); if (!properties.Any()) { throw new ArgumentOutOfRangeException("properties", "properties must have at least 1 property definition"); } var dictionary = properties.ToDictionary(f => _nameResolver.ResolveName(f), memberInfo => memberInfo); var className = GetTypeKey(sourceType, dictionary); return BuiltTypes.GetOrAdd( className, s => { var typeBuilder = ModuleBuilder.DefineType( className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable); Contract.Assume(typeBuilder != null); SetAttributes(typeBuilder, sourceType); foreach (var field in dictionary) { CreateProperty(typeBuilder, field); } return typeBuilder.CreateType(); }); }
/** * Create a collection of path filters. * <para /> * Paths may appear in any order within the collection. Sorting may be done * internally when the group is constructed if doing so will improve path * matching performance. * * @param paths * the paths to test against. Must have at least one entry. * @return a new filter for the list of paths supplied. */ public static TreeFilter create(IEnumerable<PathFilter> paths) { if (paths.Count() == 0) throw new ArgumentException("At least one path is required."); PathFilter[] p = paths.ToArray(); return create(p); }
public RecipientsMailboxManager(RecipientsMailboxManagerRouter router, IEnumerable<string> recipients, IMessagePostProcessor postProcessor) { _router = router; _postProcessor = postProcessor; _clientId = _router.RegisterMailbox(m => ShouldConsiderMessage(m, recipients.ToArray())); }
public static void PrintTagsShort(IEnumerable<TagInstance> tags) { var sorted = tags.ToArray(); Array.Sort(sorted, CompareTags); foreach (var tag in sorted) PrintTagShort(tag); }
public void Crawl(IEnumerable<string> filesAndFolders, Action<string> onLineReceived) { var file = Path.GetTempFileName(); File.WriteAllLines(file, filesAndFolders.ToArray()); run(string.Format("crawl-source \"{0}\"", file), onLineReceived); File.Delete(file); }
internal MessageTemplate(string text, IEnumerable<MessageTemplateToken> tokens) { _text = text; _tokens = tokens.ToArray(); var propertyTokens = _tokens.OfType<PropertyToken>().ToArray(); if (propertyTokens.Length != 0) { var allPositional = true; var anyPositional = false; foreach (var propertyToken in propertyTokens) { if (propertyToken.IsPositional) anyPositional = true; else allPositional = false; } if (allPositional) { _positionalProperties = propertyTokens; } else { if (anyPositional) SelfLog.WriteLine("Message template is malformed: {0}", text); _namedProperties = propertyTokens; } } }
/// <summary> /// Initializes a new instance of the <see cref="WebDavServer" /> class. /// </summary> /// <param name="store">The /// <see cref="IWebDavStore" /> store object that will provide /// collections and documents for this /// <see cref="WebDavServer" />.</param> /// <param name="listener">The /// <see cref="IHttpListener" /> object that will handle the web server portion of /// the WebDAV server; or /// <c>null</c> to use a fresh one.</param> /// <param name="methodHandlers">A collection of HTTP method handlers to use by this /// <see cref="WebDavServer" />; /// or /// <c>null</c> to use the built-in method handlers.</param> /// <exception cref="System.ArgumentNullException"><para> /// <paramref name="listener" /> is <c>null</c>.</para> /// <para>- or -</para> /// <para> /// <paramref name="store" /> is <c>null</c>.</para></exception> /// <exception cref="System.ArgumentException"><para> /// <paramref name="methodHandlers" /> is empty.</para> /// <para>- or -</para> /// <para> /// <paramref name="methodHandlers" /> contains a <c>null</c>-reference.</para></exception> public WebDavServer(IWebDavStore store, IHttpListener listener = null, IEnumerable<IWebDavMethodHandler> methodHandlers = null) { if (store == null) throw new ArgumentNullException("store"); if (listener == null) { listener = new HttpListenerAdapter(); _ownsListener = true; } methodHandlers = methodHandlers ?? WebDavMethodHandlers.BuiltIn; IWebDavMethodHandler[] webDavMethodHandlers = methodHandlers as IWebDavMethodHandler[] ?? methodHandlers.ToArray(); if (!webDavMethodHandlers.Any()) throw new ArgumentException("The methodHandlers collection is empty", "methodHandlers"); if (webDavMethodHandlers.Any(methodHandler => methodHandler == null)) throw new ArgumentException("The methodHandlers collection contains a null-reference", "methodHandlers"); _listener = listener; _store = store; var handlersWithNames = from methodHandler in webDavMethodHandlers from name in methodHandler.Names select new { name, methodHandler }; _methodHandlers = handlersWithNames.ToDictionary(v => v.name, v => v.methodHandler); _log = LogManager.GetCurrentClassLogger(); }
public static int Correcting(IEnumerable<int> correctAnswers, IEnumerable<int> submittedAnswers) { var correct = correctAnswers as int[] ?? correctAnswers.ToArray(); var submitted = submittedAnswers as int[] ?? submittedAnswers.ToArray(); return correct.Where((t, i) => t == submitted[i]).Count(); }
/// <summary> /// Creates a new instance /// </summary> /// <param name="asReadOnly">Set the new data object store to be readonly.</param> /// <param name="namespaceMappings">The initial set of CURIE prefix mappings</param> /// <param name="updateGraphUri">OPTIONAL: The URI identifier of the graph to be updated with any new triples created by operations on the store. If /// not defined, the default graph in the store will be updated.</param> /// <param name="datasetGraphUris">OPTIONAL: The URI identifiers of the graphs that will be queried to retrieve data objects and their properties. /// If not defined, all graphs in the store will be queried.</param> /// <param name="versionGraphUri">OPTIONAL: The URI identifier of the graph that contains version number statements for data objects. /// If not defined, the <paramref name="updateGraphUri"/> will be used.</param> protected DataObjectStoreBase(bool asReadOnly, Dictionary<string, string> namespaceMappings, string updateGraphUri = null, IEnumerable<string> datasetGraphUris = null, string versionGraphUri = null) { _isReadOnly = asReadOnly; _namespaceMappings = namespaceMappings ?? new Dictionary<string, string>(); _managedProxies = new Dictionary<string, DataObject>(); //_updateGraphUri = String.IsNullOrEmpty(updateGraphUri) ? Constants.DefaultGraphUri : updateGraphUri; _updateGraphUri = updateGraphUri; _datasetGraphUris = datasetGraphUris == null ? null : datasetGraphUris.ToArray(); if (_datasetGraphUris != null && _datasetGraphUris.Length == 0) { // caller provided an empty enumeration, so default to all graphs _datasetGraphUris = null; _datasetClause = String.Empty; } if (_datasetGraphUris != null) { var builder = new StringBuilder(); builder.Append("FROM "); foreach (var g in _datasetGraphUris) { builder.AppendFormat("<{0}> ", g); } _datasetClause = builder.ToString(); } _versionGraphUri = String.IsNullOrEmpty(versionGraphUri) ? _updateGraphUri : versionGraphUri; }
public ListCommandResult(IEnumerable<string> instances) { Assert.ArgumentNotNull(instances, "instances"); this.Instances = instances.ToArray(); this.Detailed = Empty; }
public void ComposeEmail( IEnumerable<string> to, IEnumerable<string> cc = null, string subject = null, string body = null, bool isHtml = false, IEnumerable<EmailAttachment> attachments = null, string dialogTitle = null) { if (!MFMailComposeViewController.CanSendMail) throw new MvxException("This device cannot send mail"); _mail = new MFMailComposeViewController(); _mail.SetMessageBody(body ?? string.Empty, isHtml); _mail.SetSubject(subject ?? string.Empty); if (cc != null) _mail.SetCcRecipients(cc.ToArray()); _mail.SetToRecipients(to?.ToArray() ?? new[] { string.Empty }); if (attachments != null) { foreach (var a in attachments) { _mail.AddAttachmentData(NSData.FromStream(a.Content), a.ContentType, a.FileName); } } _mail.Finished += HandleMailFinished; _modalHost.PresentModalViewController(_mail, true); }
private TkMetaRec[] AsArray(IEnumerable<TkMetaRec> recs) { if (recs == null) return null; return recs.ToArray (); }
/// <summary> /// Initializes a new instance of the <see cref="TransactionParticipants" /> class. /// </summary> /// <param name="transactionParticipants"> /// The participants /// </param> public TransactionParticipants(IEnumerable <TransactionParticipant> transactionParticipants) { this.transactionParticipants = transactionParticipants.ToArray(); }
public MultiExitStrategy(IEnumerable <IListExitStrategy <object> > exitStrategies) { Preconditions.CheckNotNull(exitStrategies); this.exitStrategies = exitStrategies.ToArray(); }
public AndCondition(IEnumerable <ICondition> conds) { _conds = conds.ToArray(); }
public static Datum ToList(this IEnumerable<Datum> datums) { return DatumHelpers.compound(datums.ToArray()); }
public RecalculatePageModel(IEnumerable <CalculationWithChangesets> calculations) { this.Calculations = calculations.ToArray(); }
private static string[] FormatCSharp(IEnumerable <string> source) { return(Extensions.CSharpFormatterExtensions.FormatCSharpCode(source.ToArray())); }
public OutputTypeOutput(IEnumerable <PSTypeName> outputTypes) { OutputTypes = outputTypes.ToArray(); }
public static string Join<T>(this IEnumerable<T> items, string separator) { return string.Join(separator, items.ToArray()); }
public AmbiguousTypeException(TypeName typeName, IEnumerable <string> candidates) { Candidates = candidates.ToArray(); TypeName = typeName; Diagnostics.Assert(Candidates.Length > 1, "AmbiguousTypeException can be created only when there are more then 1 candidate."); }
public SupportVectorMachineModel(svm_model model, RangeTransform rangeTransform, string targetVariable, IEnumerable <string> allowedInputVariables, IEnumerable <double> classValues) : this(model, rangeTransform, targetVariable, allowedInputVariables) { this.classValues = classValues.ToArray(); }
internal override Task WriteMessagesAsync(IEnumerable <LogMessage> messages, CancellationToken token) { Batches.Add(messages.ToArray()); return(Task.CompletedTask); }
public static Dictionary <System.String, Vendor> LoadByKeys(IEnumerable <System.String> uids) { return(FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item => item.Uid, item => item)); }
Round(int number, PlayerNumber matchedOther, IEnumerable <PlayerNumber> defeateds) { Number = number; MatchedOther = matchedOther; Defeateds = defeateds.ToArray(); }
/// <summary> /// Constructor /// </summary> /// <param name="File">The file being included</param> /// <param name="UniqueFragments">Unique fragments supplied by this file</param> public OutputFileReference(OutputFile File, IEnumerable <SourceFragment> UniqueFragments) { this.File = File; this.UniqueFragments = UniqueFragments.ToArray(); }
/// <summary> /// Join array with separator /// </summary> /// <param name="array">Array</param> /// <param name="separator">Separator</param> /// <returns></returns> public static string Join(this IEnumerable <object> array, string separator) { return(array == null ? "" : string.Join(separator, array.ToArray())); }
private static void WriteMarkdown(Entity entity, IEnumerable <string> crumbs, FileInfo sourceFile) { using (var reader = new StreamReader(sourceFile.FullName)) using (var writer = new StreamWriter(Path.Combine(MarkdownTarget.FullName, entity.MarkdownName))) { string alignment = String.IsNullOrWhiteSpace(entity.Alignment) ? String.Empty : $"[{entity.Alignment}]"; writer.WriteLine($"# {entity.FullName} {alignment}"); var crumbsArray = crumbs.ToArray(); if (crumbsArray.Length > 1) { writer.WriteLine(String.Join(" > ", crumbs)); } writer.WriteLine(); string line; while ((line = reader.ReadLine()) != null) { var parts = line.Split('^'); if (parts.Length == 1) { writer.WriteLine(line); } else { var lineBuilder = new StringBuilder(); for (int i = 0; i < parts.Length; i++) { if (i % 2 == 0) { lineBuilder.Append(parts[i]); } else { var metadataParts = parts[i].Split('.'); var ent = EntityDictionary[metadataParts[0]]; switch (metadataParts[1]) { case "Alignment": lineBuilder.Append(ent.Alignment); break; case "FullName": lineBuilder.Append(ent.FullName); break; case "FullNameLink": lineBuilder.Append(ent.FullNameLink); break; case "MarkdownName": lineBuilder.Append(ent.MarkdownName); break; case "Name": lineBuilder.Append(ent.Name); break; case "NameLink": lineBuilder.Append(ent.NameLink); break; case "Nickname": lineBuilder.Append(ent.Nickname); break; case "NicknameLink": lineBuilder.Append(ent.NicknameLink); break; } } } writer.WriteLine(lineBuilder.ToString()); } } } }
public void SendRequestMembers(IEnumerable <ulong> serverId, string query, int limit) => QueueMessage(new RequestMembersCommand { GuildId = serverId.ToArray(), Query = query, Limit = limit });
public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> source) => source.ToArray().ReadOnly();
internal AppIdentityResult(bool succeeded, IEnumerable <string> errors) { Succeeded = succeeded; Errors = errors.ToArray(); }
public void RemoveAll(IEnumerable <string> keys) { RemoveEntry(keys.ToArray()); }
private AssemblyPackageContainer GetAssemblyPackageFromLocal(IEnumerable <AssemblyPart> assemblyParts) { var assemblyNames = new List <string>(); List <string> files = new List <string>(); foreach (var dir in _assemblyFilesDirectories) { try { foreach (var file in System.IO.Directory.GetFiles(dir).Select(f => System.IO.Path.GetFileName(f)).OrderBy(f => f)) { var index = files.BinarySearch(file, StringComparer.OrdinalIgnoreCase); if (index < 0) { files.Insert(~index, file); } } } catch (Exception ex) { throw new DetailsException(ResourceMessageFormatter.Create(() => Properties.Resources.AssemblyRepository_GetFilesFromRepositoryDirectoryError, dir), ex); } } var parts2 = assemblyParts.ToArray(); IComparer <string> comparer = StringComparer.Create(System.Globalization.CultureInfo.InvariantCulture, true); foreach (var part in parts2) { var index = files.BinarySearch(part.Source, comparer); if (index >= 0) { assemblyNames.Add(files[index]); } } var analyzer = new AssemblyAnalyzer(); var assemblyPaths = new List <string>(); var names = new List <string>(); if (_assemblyInfoRepository != null) { AssemblyInfo info = null; Exception exception = null; var infos = new Queue <AssemblyInfo>(); var pending = new Queue <string>(assemblyNames); while (pending.Count > 0) { var assemblyName = pending.Dequeue(); if (names.FindIndex(f => StringComparer.InvariantCultureIgnoreCase.Equals(f, assemblyName)) < 0) { if (!_assemblyInfoRepository.TryGet(System.IO.Path.GetFileNameWithoutExtension(assemblyName), out info, out exception)) { continue; } foreach (var i in info.References) { pending.Enqueue(i + ".dll"); } names.Add(assemblyName); foreach (var dir in _assemblyFilesDirectories) { if (System.IO.File.Exists(System.IO.Path.Combine(dir, assemblyName))) { assemblyPaths.Add(System.IO.Path.Combine(dir, assemblyName)); } } } } } else { foreach (var assemblyName in assemblyNames) { string assemblyPath = null; foreach (var dir in _assemblyFilesDirectories) { assemblyPath = System.IO.Path.Combine(dir, assemblyName); if (System.IO.File.Exists(assemblyPath)) { break; } } AsmData data = null; try { data = analyzer.AnalyzeRootAssembly(assemblyPath); } catch (Exception ex) { throw new DetailsException(ResourceMessageFormatter.Create(() => Properties.Resources.AssemblyRepository_AnalyzeAssemblyError, assemblyName), ex); } var queue = new Queue <AsmData>(); queue.Enqueue(data); while (queue.Count > 0) { data = queue.Dequeue(); if (string.IsNullOrEmpty(data.Path)) { continue; } var fileName = System.IO.Path.GetFileName(data.Path); var index = names.FindIndex(f => StringComparer.InvariantCultureIgnoreCase.Equals(f, fileName)); if (index < 0) { names.Add(fileName); assemblyPaths.Add(data.Path); } foreach (var i in data.References) { if (!string.IsNullOrEmpty(i.Path) && names.FindIndex(f => f == System.IO.Path.GetFileName(i.Path)) < 0) { queue.Enqueue(i); } } } } } names.Reverse(); var languages = new IO.Xap.LanguageInfo[] { new IO.Xap.LanguageInfo(new string[] { ".dll" }, names.ToArray(), "") }; var configuration = new IO.Xap.XapConfiguration(new IO.Xap.AppManifestTemplate(), languages, null); if (assemblyPaths.Count > 0 && UseDirectoryAssemblyPackages) { return(new AssemblyPackageContainer(new DirectoryAssemblyPackage(_assemblyResolverManager, assemblyPaths))); } else if (assemblyPaths.Count > 0) { assemblyPaths.Reverse(); var entries = assemblyPaths.Select(f => { var fileInfo = new System.IO.FileInfo(f); return(new IO.Xap.XapBuilder.XapEntry(fileInfo.Name, new Lazy <System.IO.Stream>(() => fileInfo.OpenRead()), fileInfo.LastWriteTime)); }).ToArray(); var pkgUid = Guid.NewGuid(); try { var fileName = GetAssemblyPackageLocalFileName(pkgUid); if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } IO.Xap.XapBuilder.XapToDisk(configuration, entries, fileName); var pkg = new AssemblyPackageResult(_assemblyResolverManager, pkgUid, fileName).CreatePackage(); lock (_objLock) _packages.Add(new AssemblyPackageCacheEntry(pkg, null, fileName)); return(new AssemblyPackageContainer(pkg)); } finally { foreach (var i in entries) { i.Dispose(); } } } else { lock (_objLock) _packages.Add(new AssemblyPackageCacheEntry(null, parts2, null)); return(null); } }
public static T PickOne <T>(this IEnumerable <T> col) { var enumerable = col as T[] ?? col.ToArray(); return(enumerable[RandomService.GetRandom(0, enumerable.Count())]); }
/// <summary> /// 使用指定的分隔符将字符串可遍历对象连接起来 /// </summary> /// <param name="array">字符串可遍历对象</param> /// <param name="seperator">分隔符</param> /// <returns>参见 <see cref="T:System.String"/></returns> public static string Join(this IEnumerable<string> array, string seperator) { return array.ToArray().Join(seperator); }
/// <summary> /// Add recipient addresses to the suppressions list for a given group. /// If the group has been deleted, this request will add the address to the global suppression. /// </summary> /// <param name="groupId">ID of the suppression group</param> /// <param name="emails">Email addresses to add to the suppression group</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The async task. /// </returns> public Task AddAddressToUnsubscribeGroupAsync(int groupId, IEnumerable <string> emails, CancellationToken cancellationToken = default(CancellationToken)) { var data = new JObject(new JProperty("recipient_emails", JArray.FromObject(emails.ToArray()))); return(_client .PostAsync($"{_endpoint}/groups/{groupId}/suppressions") .WithJsonBody(data) .WithCancellationToken(cancellationToken) .AsMessage()); }
/// <summary> /// Adds an item to the collection if it isn't already in the collection /// </summary> /// <typeparam name="T">Collection type</typeparam> /// <param name="Collection">Collection to add to</param> /// <param name="Items">Items to add to the collection</param> /// <param name="Predicate">Predicate that an item needs to satisfy in order to be added</param> /// <returns>True if it is added, false otherwise</returns> public static bool AddIf <T>(this ICollection <T> Collection, Predicate <T> Predicate, IEnumerable <T> Items) { Contract.Requires <ArgumentNullException>(Collection != null, "Collection"); Contract.Requires <ArgumentNullException>(Predicate != null, "Predicate"); return(Collection.AddIf(Predicate, Items.ToArray())); }
public UserDeviceActionRequestedEventArgs(IEnumerable<UserDeviceActionRequest> requests) { Requests = requests.ToArray(); }
public override void Execute() { DoExport(_elements.ToArray()); }
public Source(IEnumerable <byte> data) { Data = data.ToArray(); }
public HeartbeatNodeRing(UniqueAddress selfAddress, IEnumerable <UniqueAddress> nodes, int monitoredByNumberOfNodes) : this(selfAddress, ImmutableSortedSet.Create(nodes.ToArray()), monitoredByNumberOfNodes) { }
public int[] ToArray() { return(_range.ToArray()); }