コード例 #1
8
        public Dictionary<string, string> Generate(List<NameNode> idNameNodes, IEnumerable<string> excludedNames)
        {
            Generator.Reset();

            int varCount = idNameNodes.Count;
            string[] newNames = new string[varCount];
            var newSubstitution = new Dictionary<string, string>();

            for (int i = 0; i < varCount; i++)
            {
                string newName;
                do
                {
                    newName = Generator.Next();
                }
                while (excludedNames.Contains(newName) || NamesGenerator.CSharpKeywords.Contains(newName));
                newNames[i] = newName;
            }

            int ind = 0;
            foreach (NameNode v in idNameNodes)
                if (!newSubstitution.ContainsKey(v.Name))
                    newSubstitution.Add(v.Name, newNames[ind++]);

            return newSubstitution;
        }
コード例 #2
3
        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();
        }
コード例 #3
2
ファイル: Discount.cs プロジェクト: richinoz/Orchard1.6
 public bool Applies(ShoppingCartQuantityProduct quantityProduct, IEnumerable<ShoppingCartQuantityProduct> cartProducts) {
     if (DiscountPart == null) return false;
     var now = _clock.UtcNow;
     if (DiscountPart.StartDate != null && DiscountPart.StartDate > now) return false;
     if (DiscountPart.EndDate != null && DiscountPart.EndDate < now) return false;
     if (DiscountPart.StartQuantity != null &&
         DiscountPart.StartQuantity > quantityProduct.Quantity)
         return false;
     if (DiscountPart.EndQuantity != null &&
         DiscountPart.EndQuantity < quantityProduct.Quantity)
         return false;
     if (!string.IsNullOrWhiteSpace(DiscountPart.Pattern)) {
         string path;
         if (DiscountPart.DisplayUrlResolver != null) {
             path = DiscountPart.DisplayUrlResolver(quantityProduct.Product);
         }
         else {
             var urlHelper = new UrlHelper(_wca.GetContext().HttpContext.Request.RequestContext);
             path = urlHelper.ItemDisplayUrl(quantityProduct.Product);
         }
         if (!path.StartsWith(DiscountPart.Pattern, StringComparison.OrdinalIgnoreCase))
             return false;
     }
     if (DiscountPart.Roles.Any()) {
         var user = _wca.GetContext().CurrentUser;
         if (user.Has<UserRolesPart>()) {
             var roles = user.As<UserRolesPart>().Roles;
             if (!roles.Any(r => DiscountPart.Roles.Contains(r))) return false;
         }
     }
     return true;
 }
コード例 #4
1
 /// <summary>
 /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
 /// </summary>
 /// <param name="mediaType">The media type.</param>
 /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="actionName">Name of the action.</param>
 /// <param name="parameterNames">The parameter names.</param>
 public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
 {
     if (mediaType == null)
     {
         throw new ArgumentNullException("mediaType");
     }
     if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
     {
         throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
     }
     if (controllerName == null)
     {
         throw new ArgumentNullException("controllerName");
     }
     if (actionName == null)
     {
         throw new ArgumentNullException("actionName");
     }
     if (parameterNames == null)
     {
         throw new ArgumentNullException("parameterNames");
     }
     ControllerName = controllerName;
     ActionName = actionName;
     MediaType = mediaType;
     ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
     SampleDirection = sampleDirection;
 }
コード例 #5
1
        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("[property_type]=1");

            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'"
                                                            , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                            ));

            yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                ));

            yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                , filters.Single(f => f.Target == Target.Levels).Caption
                                                ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Properties);
            if (filter!=null)
                yield return new CommandFilter(string.Format("[property_caption]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
コード例 #6
1
 /// <summary>
 /// Executes this operation
 /// </summary>
 /// <param name="rows">The rows.</param>
 /// <returns></returns>
 public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
 {
     using (IDbConnection connection = Use.Connection(ConnectionStringName))
     using (IDbTransaction transaction = connection.BeginTransaction())
     {
         foreach (Row row in new SingleRowEventRaisingEnumerator(this, rows))
         {
             using (IDbCommand cmd = connection.CreateCommand())
             {
                 currentCommand = cmd;
                 currentCommand.Transaction = transaction;
                 PrepareCommand(currentCommand, row);
                 currentCommand.ExecuteNonQuery();
             }
         }
         if (PipelineExecuter.HasErrors)
         {
             Warn("Rolling back transaction in {0}", Name);
             transaction.Rollback();
             Warn("Rolled back transaction in {0}", Name);
         }
         else
         {
             Debug("Committing {0}", Name);
             transaction.Commit();
             Debug("Committed {0}", Name);
         }
     }
     yield break;
 }
コード例 #7
1
ファイル: TraceLogAttribute.cs プロジェクト: NetUtil/Util
 /// <summary>
 /// 添加参数列表
 /// </summary>
 private void AddParams( IEnumerable<KeyValuePair<string, object>> paramList ) {
     foreach ( var parameter in paramList ) {
         if ( IsSecret( parameter.Key ) )
             continue;
         AddParams( parameter );
     }
 }
コード例 #8
1
        /////////////////////////////////////////////////////////////////////////////
        public static void AddFilesToProject( InputFile srcFile, IEnumerable<string> resultFiles, IExtSvcProvider service )
        {
            // ******
            var allPossibleFiles = GetPossibleFileNames( srcFile, resultFiles );
            var filesThatExist = DiscoverGeneratedFiles( srcFile, resultFiles );
            var filesThatDontExist = allPossibleFiles.Except( filesThatExist );

            // ******
            service.AddFilesToProject( filesThatExist );
            service.RemoveFilesFromProject( filesThatDontExist );

            //// ******
            //var sb = new StringBuilder { };
            //
            //sb.Append( "Files that are in, or have just been added to project:\r\n" );
            //foreach( var name in filesThatExist ) {
            //	sb.AppendFormat( "  {0}\r\n", name );
            //}
            //
            //sb.Append( "Files that have been removed from the project:\r\n" );
            //foreach( var name in filesThatDontExist ) {
            //	sb.AppendFormat( "  {0}\r\n", name );
            //}
            //
            //// ******
            //return sb.ToString();
        }
 /// <summary>
 /// Add a decorator to the enumerable for additional processing
 /// </summary>
 /// <param name="operation">The operation.</param>
 /// <param name="enumerator">The enumerator.</param>
 protected override IEnumerable<Row> DecorateEnumerableForExecution(IOperation operation, IEnumerable<Row> enumerator)
 {
     foreach (Row row in new EventRaisingEnumerator(operation, enumerator))
     {
         yield return row;
     }
 }
コード例 #10
1
 public void AddDoseTimes(IEnumerable<TimeOfDay> times)
 {
     foreach (var time in times)
     {
         AddDoseTime(time);
     }
 }
コード例 #11
1
ファイル: SettingsViewModel.cs プロジェクト: 4ux-nbIx/gemini
        protected override void OnInitialize()
        {
            base.OnInitialize();

            var pages = new List<SettingsPageViewModel>();
            _settingsEditors = IoC.GetAll<ISettingsEditor>();

            foreach (ISettingsEditor settingsEditor in _settingsEditors)
            {
                List<SettingsPageViewModel> parentCollection = GetParentCollection(settingsEditor, pages);

                SettingsPageViewModel page =
                    parentCollection.FirstOrDefault(m => m.Name == settingsEditor.SettingsPageName);

                if (page == null)
                {
                    page = new SettingsPageViewModel
                    {
                        Name = settingsEditor.SettingsPageName,
                    };
                    parentCollection.Add(page);
                }

                page.Editors.Add(settingsEditor);
            }

            Pages = pages;
            SelectedPage = GetFirstLeafPageRecursive(pages);
        }
コード例 #12
1
 public SetUnmodifiedCommand(string sitePath, IEnumerable<DocumentFile> documents, IEnumerable<StaticFile> files, IEnumerable<LastRunDocument> lastRunState)
 {
     this.Documents = documents;
     this.Files = files;
     this.LastRunState = lastRunState;
     this.SitePath = sitePath;
 }
コード例 #13
1
        public Organisation(
            User createdByUser,
            string name,
            string description,
            string website,
            MediaResource avatar,
            MediaResource background,
            IEnumerable<string> categories,
            DateTime createdDateTime,
            Group parentGroup)
            : base(createdByUser,
            name,
            createdDateTime,
            parentGroup)
        {
            Check.RequireNotNull(categories != null, "categories");

            InitMembers();

            SetOrganisationDetails(
                description,
                website,
                avatar,
                background,
                categories);

            ApplyEvent(new DomainModelCreatedEvent<Organisation>(this, createdByUser, this));
        }
コード例 #14
1
 public static void AddRoleClaims(IEnumerable<string> roles, IList<Claim> claims)
 {
     foreach (string role in roles)
     {
         claims.Add(new Claim(RoleClaimType, role, ClaimsIssuer));
     }
 }
コード例 #15
1
ファイル: Export.cs プロジェクト: Condeti/spark
 public void Add(IEnumerable<Interaction> set)
 {
     foreach (Interaction interaction in set)
     {
         Add(interaction);
     }
 }
コード例 #16
1
ファイル: ConflictResolution.cs プロジェクト: Rickinio/roslyn
        internal async Task RemoveAllRenameAnnotationsAsync(IEnumerable<DocumentId> documentWithRenameAnnotations, AnnotationTable<RenameAnnotation> annotationSet, CancellationToken cancellationToken)
        {
            foreach (var documentId in documentWithRenameAnnotations)
            {
                if (_renamedSpansTracker.IsDocumentChanged(documentId))
                {
                    var document = _newSolution.GetDocument(documentId);
                    var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                    // For the computeReplacementToken and computeReplacementNode functions, use 
                    // the "updated" node to maintain any annotation removals from descendants.
                    var newRoot = root.ReplaceSyntax(
                        nodes: annotationSet.GetAnnotatedNodes(root),
                        computeReplacementNode: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        tokens: annotationSet.GetAnnotatedTokens(root),
                        computeReplacementToken: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
                        computeReplacementTrivia: null);

                    _intermediateSolutionContainingOnlyModifiedDocuments = _intermediateSolutionContainingOnlyModifiedDocuments.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
                }
            }

            _newSolution = _intermediateSolutionContainingOnlyModifiedDocuments;
        }
コード例 #17
1
 public void HttpMethodProviderAttributes_ReturnsCorrectHttpMethodSequence(
     IActionHttpMethodProvider httpMethodProvider,
     IEnumerable<string> expectedHttpMethods)
 {
     // Act & Assert
     Assert.Equal(expectedHttpMethods, httpMethodProvider.HttpMethods);
 }
コード例 #18
1
 public PerformanceCounterInfo(string name, PerformanceCounter performanceCounters, string alias, IEnumerable<ITag> tags)
 {
     _name = name;
     _performanceCounters = performanceCounters;
     _alias = alias;
     _tags = (tags ?? new List<ITag>()).ToList();
 }
コード例 #19
1
 private static void ApplyMetadataAwareAttributes(IEnumerable<Attribute> attributes, ModelMetadata result)
 {
     foreach (IMetadataAware awareAttribute in attributes.OfType<IMetadataAware>())
     {
         awareAttribute.OnMetadataCreated(result);
     }
 }
コード例 #20
1
ファイル: VertexArray.cs プロジェクト: GeirGrusom/ModGL
        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();
                }
            }
        }
コード例 #21
1
 private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
 {
     var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
     SyntaxNode newRoot;
     if (mainDocGroup == null)
     {
         newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
     }
     else
     {
         var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
         newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
         newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
         foreach (var diagnosticNode in diagnosticNodes)
         {
             var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
             var tokenParent = token.Parent;
             if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
             var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
             if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
             var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
             if (memberAccess == null) continue;
             var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
         }
     }
     var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
     return newSolution;
 }
コード例 #22
1
ファイル: CreateEffectWarhead.cs プロジェクト: OpenRA/OpenRA
        public override void DoImpact(Target target, Actor firedBy, IEnumerable<int> damageModifiers)
        {
            if (!target.IsValidFor(firedBy))
                return;

            var pos = target.CenterPosition;
            var world = firedBy.World;
            var targetTile = world.Map.CellContaining(pos);
            var isValid = IsValidImpact(pos, firedBy);

            if ((!world.Map.Contains(targetTile)) || (!isValid))
                return;

            var palette = ExplosionPalette;
            if (UsePlayerPalette)
                palette += firedBy.Owner.InternalName;

            var explosion = Explosions.RandomOrDefault(Game.CosmeticRandom);
            if (Image != null && explosion != null)
                world.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, w, Image, explosion, palette)));

            var impactSound = ImpactSounds.RandomOrDefault(Game.CosmeticRandom);
            if (impactSound != null)
                Game.Sound.Play(impactSound, pos);
        }
コード例 #23
1
        public AppUpdateControl(IEnumerable<IAppVersion> appVersions, Action<IAppVersion> updateAction)
        {
            this.NewestVersion = appVersions.First();
            InitializeComponent();

            this.AppIconImage.ImageFailed += (sender, e) => { this.AppIconImage.Source = new BitmapImage(new Uri("/Assets/windows_phone.png", UriKind.RelativeOrAbsolute)); };
            this.AppIconImage.Source = new BitmapImage(new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".png"));

            this.ReleaseNotesBrowser.Opacity = 0;
            this.ReleaseNotesBrowser.Navigated += (sender, e) => { (this.ReleaseNotesBrowser.Resources["fadeIn"] as Storyboard).Begin(); };
            this.ReleaseNotesBrowser.NavigateToString(WebBrowserHelper.WrapContent(NewestVersion.Notes));
            this.ReleaseNotesBrowser.Navigating += (sender, e) =>
            {
                e.Cancel = true;
                WebBrowserTask browserTask = new WebBrowserTask();
                browserTask.Uri = e.Uri;
                browserTask.Show();
            };
            this.InstallAETX.Click += (sender, e) =>
            {
                WebBrowserTask webBrowserTask = new WebBrowserTask();
                webBrowserTask.Uri = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".aetx", UriKind.Absolute);
                webBrowserTask.Show();
            };
            this.InstallOverApi.Click += (sender, e) => {
                this.Overlay.Visibility = Visibility.Visible;
                updateAction.Invoke(NewestVersion); 
            };
            
        }
コード例 #24
1
        static IEnumerable<FileRiskFactor> Calculate(IEnumerable<FileModificationStatistics> statistics)
        {
            var riskFactors = new List<FileRiskFactor>();

            foreach (var statistic in statistics)
            {
                var fileRiskFactor = new FileRiskFactor
                {
                    CreatedAt = DateTime.Now,
                    FileName = statistic.FileName,

                    Statistics = statistic
                };

                var existingDuration = GetDaysDuration(statistic.FirstCommit.ModifiedAt, DateTime.Now);
                var localStatistic = statistic;

                foreach (var duration in statistic.OtherCommits.Select(commit => GetDaysDuration(localStatistic.FirstCommit.ModifiedAt, commit.ModifiedAt)))
                {
                    fileRiskFactor.Score += Score(duration, existingDuration);
                }

                riskFactors.Add(fileRiskFactor);
            }

            return riskFactors;
        }
コード例 #25
1
 public SupportPowerTimerWidget(World world)
 {
     powers = world.ActorsWithTrait<SupportPowerManager>()
         .Where(p => !p.Actor.IsDead() && !p.Actor.Owner.NonCombatant)
         .SelectMany(s => s.Trait.Powers.Values)
         .Where(p => p.Instances.Any() && p.Info.DisplayTimer && !p.Disabled);
 }
コード例 #26
1
        public Announcement(string description, string type, string operatorName, DateTime? startDate, DateTime? endDate, Coordinate location, IEnumerable<string> modes)
        {
            this.OperatorName = operatorName;
            this.Description = description;
            this.StartDate = startDate;
            this.EndDate = endDate;
            this.Location = location;
            this.Type = type;
            this.Modes.AddRange(modes);
            this.RelativeDateString = TimeConverter.ToRelativeDateString(StartDate, true);

            if (modes != null)
            {
                if (modes.Select(x => x.ToLower()).Contains("bus"))
                    this.ModeImages.Add("/Images/64/W/ModeBus.png");
                if (modes.Select(x => x.ToLower()).Contains("rail"))
                    this.ModeImages.Add("/Images/64/W/ModeRail.png");
                if (modes.Select(x => x.ToLower()).Contains("taxi"))
                    this.ModeImages.Add("/Images/64/W/ModeTaxi.png");
                if (modes.Select(x => x.ToLower()).Contains("boat"))
                    this.ModeImages.Add("/Images/64/W/ModeBoat.png");

                if (!this.ModeImages.Any())
                    this.ModeImages.Add("/Images/64/W/ModeBus.png");
            }
            else
            {
                this.Modes.Add("bus");
                this.ModeImages.Add("/Images/64/W/ModeBus.png");
            }
        }
コード例 #27
1
 public static Obj_AI_Hero GetTarget(this Spell spell,
     bool ignoreShields = true,
     Vector3 from = default(Vector3),
     IEnumerable<Obj_AI_Hero> ignoredChampions = null)
 {
     return TargetSelector.GetTarget(spell, ignoreShields, from, ignoredChampions);
 }
コード例 #28
1
 public string GenerateTestFixture(IEnumerable<Test> tests, string fileName)
 {
     var generator = new CodeGenerator(TemplateEnum.MbUnitTestFixture, TestText, MethodText, PropertyText, TypeText,
                                       AssertText);
     var code = generator.GenerateTestFixture(tests.ToList(), fileName);
     return code;
 }
コード例 #29
1
ファイル: AssetTagBuilder.cs プロジェクト: joemcbride/fubumvc
        public IEnumerable<HtmlTag> BuildScriptTags(IEnumerable<string> scripts)
        {
            Func<string, string> toFullUrl = url => _request.ToFullUrl(url);

            while (_queuedScripts.Any())
            {
                var asset = _queuedScripts.Dequeue();
                if (_writtenScripts.Contains(asset)) continue;

                _writtenScripts.Add(asset);

                yield return new ScriptTag(toFullUrl, asset);
            }

            foreach (var x in scripts)
            {
                var asset = _finder.FindAsset(x);

                if (asset == null)
                {
                    yield return new ScriptTag(toFullUrl, null, x);
                }
                else if (!_writtenScripts.Contains(asset))
                {
                    _writtenScripts.Add(asset);
                    yield return new ScriptTag(toFullUrl, asset, x);
                }
            }
        }
コード例 #30
0
        public Dictionary<string, List<Event>> CreateEvents(string calendarId, IEnumerable<CalendarItem> eventsToCreate)
        {
            var service = _GetCalendarService();
            var eventsToBeCreated = eventsToCreate.Select(eventFromCalendarItem);
            var created = new List<Event>();
            var errored = new List<Event>();

            foreach (var eventToBeCreated in eventsToBeCreated)
            {
                try {
                    Console.WriteLine(string.Format("    -- Creating EVENT [{0}] for dates [{1}]"
                        ,eventToBeCreated.Summary, eventToBeCreated.Start.DateTime.Value));
                    var result = service.Events.Insert(eventToBeCreated, calendarId).Execute();
                    if (result.Id != null && result.Id != "")
                    {
                        created.Add(result);
                    }
                }catch(Exception ex)
                {
                    Console.WriteLine(ex);
                    errored.Add(eventToBeCreated);
                }
            }
            return new Dictionary<string, List<Event>>()
            {
                { "created", created },
                { "errored", errored}
            };
        }
コード例 #31
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static void Foreach<T>(this IEnumerable<T> ie, Action<T> act) {
     foreach (var item in ie) {
         act(item);
     }
 }
コード例 #32
0
        public IEnumerable<string> GetMatchedFiles(IEnumerable<PathInfo> paths)
        {
            bool hasItems = false;
            foreach (var item in paths)
            {
                string value = Utility.ResolveRelativePath_Current(item.Path);

                string filter = null;
                if (value.Contains("*"))
                {
                    filter = Path.GetFileName(value);
                    value = value.Substring(0, value.Length - filter.Length);
                }
                // is directory or file?
                

                if (!Directory.Exists(value))
                {
                    // perhaps its a file?
                    if (filter==null && !File.Exists(value))
                    {
                        Console.WriteLine(string.Format("Ignoring missing file or directory: {0}", value));
                        continue;
                    }
                    else
                    {
                        yield return value;
                        continue;
                    }
                }
                List<DirectoryInfo> directorys = new List<DirectoryInfo>() { 
                            new DirectoryInfo(value) };
                while (directorys.Count > 0)
                {
                    DirectoryInfo di = directorys[0];
                    directorys.RemoveAt(0);
                    FileInfo[] files;
                    if (!string.IsNullOrWhiteSpace(filter))
                    {
                        files = di.GetFiles(filter);
                    }
                    else
                    {
                        files = di.GetFiles();
                    }

                    List<string> allFiles = new List<string>();
                    foreach (FileInfo fi in files)
                    {
                        allFiles.Add(fi.FullName);
                    }

                    if (item.Recurse)
                    {
                        directorys.AddRange(di.GetDirectories());
                    }
                    
                    
                    foreach (string matchedFile in FilePathMatcher.MatchFiles(ExcludeFiles, allFiles, true))
                    {
                        yield return matchedFile;
                    }


                }
            }
            if (!hasItems)
            {
                yield break;
            }
        }
コード例 #33
0
        /// <summary>
        /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names.
        /// </summary>
        /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="parameterNames">The parameter names.</param>
        public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
        {
            if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
            {
                throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
            }
            if (controllerName == null)
            {
                throw new ArgumentNullException("controllerName");
            }
            if (actionName == null)
            {
                throw new ArgumentNullException("actionName");
            }
            if (parameterNames == null)
            {
                throw new ArgumentNullException("parameterNames");
            }

            ControllerName = controllerName;
            ActionName = actionName;
            ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
            SampleDirection = sampleDirection;
        }
コード例 #34
0
ファイル: BundleRoute.cs プロジェクト: darkmice/junior-route
        public BundleRoute(Bundle bundle, string routeName, Scheme scheme, string relativePath, IAssetConcatenator concatenator, IEnumerable <IAssetTransformer> transformers)
        {
            bundle.ThrowIfNull("bundle");
            routeName.ThrowIfNull("routeName");
            relativePath.ThrowIfNull("relativePath");
            concatenator.ThrowIfNull("concatenator");
            transformers.ThrowIfNull("transformers");

            _bundle       = bundle;
            _routeName    = routeName;
            _scheme       = scheme;
            _relativePath = relativePath;
            _concatenator = concatenator;
            _transformers = transformers;
        }
コード例 #35
0
ファイル: DataUtil.cs プロジェクト: trainboy2019/PKHeX
 /// <summary>
 /// Gets the names of the properties defined in the given input
 /// </summary>
 /// <param name="input">Enumerable of translation definitions in the form "Property = Value".</param>
 /// <returns></returns>
 private static string[] GetProperties(IEnumerable<string> input)
 {
     return input.Select(l => l.Substring(0, l.IndexOf(TranslationSplitter, StringComparison.Ordinal))).ToArray();
 }
コード例 #36
0
 private static CommandProblemDetails FormatProblemDetails(this IEnumerable<Failure> failures) => new CommandProblemDetails
 {
     Title = "One or more validation errors occurred.",
     Errors = failures.GroupBy(k => k.Id).ToDictionary(s => s.Key, s => s.Map(k => k.Error.Message).ToArray())
 };
コード例 #37
0
        static PrimePowerOrderFieldTests()
        {
            Gf8 = new PrimePowerOrderField(8, new Polynomial(new PrimeOrderField(2), 1, 1, 0, 1));
            Gf27 = new PrimePowerOrderField(27, new Polynomial(new PrimeOrderField(3), 2, 2, 0, 1));

            IncorrectFieldCreationTestsData = new[]
                                              {
                                                  new object[] {8, null},
                                                  new object[] {8, new Polynomial(new PrimeOrderField(3), 1)},
                                                  new object[] {8, new Polynomial(new PrimeOrderField(2), 1)},
                                                  new object[] {8, new Polynomial(new PrimeOrderField(2), 0, 0, 0, 1)}
                                              };
            SumTestsData = new[]
                            {
                                new object[] {Gf8, 3, 4, 7},
                                new object[] {Gf8, 1, 3, 2},
                                new object[] {Gf8, 1, 6, 7},
                                new object[] {Gf8, 5, 6, 3},
                                new object[] {Gf8, 4, 7, 3},
                                new object[] {Gf8, 5, 5, 0},
                                new object[] {Gf27, 3, 4, 7},
                                new object[] {Gf27, 10, 12, 22},
                                new object[] {Gf27, 11, 10, 18},
                                new object[] {Gf27, 18, 9, 0},
                                new object[] {Gf27, 20, 17, 7},
                                new object[] {Gf27, 9, 21, 3}
                            };
            SubtractTestsData = new[]
                                 {
                                     new object[] {Gf8, 3, 4, 7},
                                     new object[] {Gf8, 1, 3, 2},
                                     new object[] {Gf8, 1, 6, 7},
                                     new object[] {Gf8, 5, 6, 3},
                                     new object[] {Gf8, 4, 7, 3},
                                     new object[] {Gf8, 5, 5, 0},
                                     new object[] {Gf27, 3, 4, 2},
                                     new object[] {Gf27, 10, 12, 7},
                                     new object[] {Gf27, 11, 14, 6},
                                     new object[] {Gf27, 18, 9, 9},
                                     new object[] {Gf27, 20, 17, 12},
                                     new object[] {Gf27, 9, 21, 24}
                                 };
            MultiplyTestsData = new[]
                                 {
                                     new object[] {Gf8, 0, 4, 0},
                                     new object[] {Gf8, 2, 4, 3},
                                     new object[] {Gf8, 3, 4, 7},
                                     new object[] {Gf8, 2, 3, 6},
                                     new object[] {Gf8, 6, 7, 4},
                                     new object[] {Gf8, 2, 7, 5},
                                     new object[] {Gf27, 0, 4, 0},
                                     new object[] {Gf27, 12, 5, 1},
                                     new object[] {Gf27, 3, 4, 12},
                                     new object[] {Gf27, 21, 3, 17},
                                     new object[] {Gf27, 20, 21, 26},
                                     new object[] {Gf27, 2, 7, 5}
                                 };
            DivideTestsData = new[]
                               {
                                   new object[] {Gf8, 0, 3, 0},
                                   new object[] {Gf8, 4, 3, 5},
                                   new object[] {Gf8, 7, 2, 6},
                                   new object[] {Gf8, 2, 7, 3},
                                   new object[] {Gf27, 0, 3, 0},
                                   new object[] {Gf27, 15, 7, 6},
                                   new object[] {Gf27, 11, 26, 14},
                                   new object[] {Gf27, 10, 17, 15},
                                   new object[] {Gf27, 2, 23, 25}
                               };
        }
コード例 #38
0
 public IEnumerable<CaseStatus> GetDailyCases(IEnumerable<CaseStatus> statuses)
 {
     throw new NotImplementedException();
 }
コード例 #39
0
        public async Task <IEnumerable <IdentityResource> > FindIdentityResourcesByScopeAsync(IEnumerable <string> names)
        {
            if (names == null)
            {
                throw new ArgumentNullException(nameof(names));
            }
            var identityResources = await FetchAllIdentityResourceAsync();

            var identity = from i in identityResources
                           where names.Contains(i.Name)
                           select i;

            return(identity);
        }
コード例 #40
0
 public DefaultNotificationHub(AgentConfiguration config, IEnumerable <INotificationRequestFilter> filters)
 {
     _config = config;
     LoadFilters(filters);
 }
コード例 #41
0
 /// <summary>
 /// Creates a range of items.
 /// </summary>
 public int CreateItems(IEnumerable <Item> items)
 {
     ctx.Items.AddRange(items);
     return(ctx.SaveChanges());
 }
コード例 #42
0
        public new void AddRange(IEnumerable <MediaItem> list)
        {
            base.AddRange(list);

            SetMediaItemIds(Items);
        }
コード例 #43
0
        public Coroutine Process(IEnumerable<IEnumerator> logic, Action onCompleted)
        {
            var coroutine = StartCoroutine(CoroutineProcessing(logic, onCompleted));

            return coroutine;
        }
コード例 #44
0
 /// <summary>
 /// Deletes a list of items from the database.
 /// Returns -1 if SaveChanges() is delayed by unit of work.
 /// </summary>
 public int DeleteItems(IEnumerable <Item> items)
 {
     ctx.Items.RemoveRange(items);
     return(ctx.SaveChanges());
 }
コード例 #45
0
 public MultipleTenants(IEnumerable <Guid> tenantIds, string resourceName)
 {
     TenantIds    = tenantIds;
     ResourceName = resourceName;
 }
コード例 #46
0
 public IEnumerable<Tile> TilesInRangeTest([PexAssumeUnderTest]Tile target, int range)
 {
     IEnumerable<Tile> result = target.TilesInRange(range);
     return result;
     // TODO: add assertions to method TileTest.TilesInRangeTest(Tile, Int32)
 }
コード例 #47
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static int Count<T>(this IEnumerable<T> l, T target) => l.Count(x => x.Equals(target));
コード例 #48
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static List<long> Imos(this IEnumerable<long> @this) {
     var rt = @this.ToList();
     for (var i = 0; i < rt.Count - 1; i++) rt[i + 1] += rt[i];
     return rt;
 }
コード例 #49
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static void JoinWL<T>(this IEnumerable<T> @this, string sp = " ") => @this.StringJoin(sp).WL();
コード例 #50
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static string StringJoin<T>(this IEnumerable<T> l, string separator = "") => string.Join(separator, l);
コード例 #51
0
ファイル: LibraryTable.cs プロジェクト: jgrisham/Power-Fx
        private static IEnumerable <DValue <RecordValue> > LazyAddColumns(EvalVisitor runner, SymbolContext context, IEnumerable <DValue <RecordValue> > sources, IRContext recordIRContext, NamedLambda[] newColumns)
        {
            foreach (var row in sources)
            {
                if (row.IsValue)
                {
                    // $$$ this is super inefficient... maybe a custom derived RecordValue?
                    var fields = new List <NamedValue>(row.Value.Fields);

                    var childContext = context.WithScopeValues(row.Value);

                    foreach (var column in newColumns)
                    {
                        var value = column.Lambda.Eval(runner, childContext);
                        fields.Add(new NamedValue(column.Name, value));
                    }

                    yield return(DValue <RecordValue> .Of(new InMemoryRecordValue(recordIRContext, fields.ToArray())));
                }
                else
                {
                    yield return(row);
                }
            }
        }
コード例 #52
0
ファイル: 3047972.cs プロジェクト: qifanyyy/CLCDSA
 public static void WL<T>(this IEnumerable<T> list) => list.ToList().ForEach(x => x.WL());
コード例 #53
0
 public IEnumerable<CaseStatus> GetCummiliativeCases(IEnumerable<CaseStatus> statuses)
 {
     return statuses.Where(x=>x.District == District.State);
 }
コード例 #54
0
ファイル: Batch.cs プロジェクト: sworld1110/easypost-csharp
 /// <summary>
 /// Remove shipments from the batch.
 /// </summary>
 /// <param name="shipments">List of Shipment objects to be removed.</param>
 public void RemoveShipments(IEnumerable<Shipment> shipments) {
     RemoveShipments(shipments.Select(shipment => shipment.id).ToList());
 }
コード例 #55
0
 protected AppCommandBarBase(string name, CommandBarPosition position, IEnumerable <ICommandMenuItem> items)
 {
     _name     = name;
     _position = position;
     _items    = items.ToDictionary(item => item, item => null as ICommandBarControl);
 }
コード例 #56
0
        public ActionResult PostValidate(PostViewModel model)
        {
            EditorType editorType;
            if (model.PostEditor.PostID == 0)
                editorType = EditorType.Create;
            else
                editorType = EditorType.Edit;

            var thread = _threadServices.GetThread(model.ThreadID);
            var forum = thread.Forum;

            if (editorType == EditorType.Create)
            {
                if (!_permissionServices.CanReply(forum.ForumID, _currentUser.UserID))
                {
                    if (thread.IsLocked)
                    {
                        SetNotice("You can't reply to this thread because it is locked");
                        return RedirectToAction("ViewThread", "Board", new { ThreadID = thread.ThreadID });
                    }
                    else
                    {
                        SetNotice("You don't have permission to reply in this forum");
                        return RedirectToAction("ViewForum", "Board", new { ForumID = forum.ForumID });
                    }
                }
            }
            else
            {
                if (!_postServices.CanEditPost(model.PostEditor.PostID, _currentUser.UserID))
                {
                    SetError("You can't edit this post");
                    return RedirectToAction("ViewThread", "Board", new { ThreadID = thread.ThreadID });
                }
            }

            HttpPostedFileBase[] files = null;
            if (_permissionServices.CanCreateAttachment(forum.ForumID, _currentUser.UserID))
            {
                if (model.PostEditor.Files != null)
                {
                    ValidatePostedFiles(model.PostEditor.Files);
                    files = model.PostEditor.Files.Where(item => item != null && item.ContentLength > 0 && !string.IsNullOrWhiteSpace(item.FileName)).ToArray();
                }
            }
            else
                model.PostEditor.Files = null;

            if (IsModelValidAndPersistErrors() && !model.Preview.HasValue)
            {
                if (editorType == EditorType.Create)
                {
                    if (_threadServices.IsSubscribed(thread.ThreadID, _currentUser.UserID) && model.PostEditor.SubscribeToThread)
                        _threadServices.Subscribe(thread.ThreadID, _currentUser.UserID);

                    var post = _postServices.CreatePost(model.ThreadID, _currentUser.UserID, model.PostEditor.Message, model.PostEditor.ShowSignature, files);
                    string postUrl = Url.Action("ViewThread", "Board", new { ThreadID = post.ThreadID, PostID = post.PostID }) + "#" + post.PostID;
                    IEnumerable<Subscription> subscriptions = thread.Subscriptions;
                    _emailServices.NewPostEmail(subscriptions, post, post.Thread, postUrl);

                    SetSuccess("Your reply was posted");
                    return Redirect(Url.Action("ViewThread", "Board", new { ThreadID = model.ThreadID, LastPost = true, NewPost = true }) + "#" + post.PostID);
                }
                else
                {
                    if (model.PostEditor.Delete != null)
                        _fileServices.DeleteAttachments(model.PostEditor.Delete);

                    _postServices.UpdatePost(model.PostEditor.PostID, model.PostEditor.Message, files);
                    SetSuccess("Post edited");
                    return Redirect(Url.Action("ViewThread", "Board", new { ThreadID = thread.ThreadID, LastPost = true, PostID = model.PostEditor.PostID }) + "#" + model.PostEditor.PostID);
                }
            }

            if (model.Preview.HasValue)
            {
                TempData["Preview_Text"] = model.PostEditor.Message;
            }

            if (editorType == EditorType.Create)
                return RedirectToAction("CreatePost", new { ThreadID = model.ThreadID });
            else
                return RedirectToAction("EditPost", new { PostID = model.PostEditor.PostID });
        }
コード例 #57
0
 public ISpan Log(DateTimeOffset timestamp, IEnumerable <KeyValuePair <string, object> > fields)
 {
     // noop
     return(this);
 }
コード例 #58
0
ファイル: Batch.cs プロジェクト: sworld1110/easypost-csharp
 /// <summary>
 /// Add shipments to the batch.
 /// </summary>
 /// <param name="shipments">List of Shipment objects to be added.</param>
 public void AddShipments(IEnumerable<Shipment> shipments) {
     AddShipments(shipments.Select(shipment => shipment.id).ToList());
 }
コード例 #59
0
 /// <summary>
 /// Returns the appropriate content-type for this format.
 /// </summary>
 /// <param name="mediaType">The specified media type.</param>
 /// <param name="encoding">The specified encoding.</param>
 /// <param name="writingResponse">True if the message writer is being used to write a response.</param>
 /// <param name="mediaTypeParameters"> The resultant parameters list of the media type. Parameters list could be updated
 /// when getting content type and should be returned if that is the case.
 /// </param>
 /// <returns>The content-type value for the format.</returns>
 internal virtual string GetContentType(ODataMediaType mediaType, Encoding encoding,
                                        bool writingResponse, out IEnumerable <KeyValuePair <string, string> > mediaTypeParameters)
 {
     mediaTypeParameters = mediaType.Parameters;
     return(HttpUtils.BuildContentType(mediaType, encoding));
 }
コード例 #60
0
 public ISpan Log(IEnumerable <KeyValuePair <string, object> > fields)
 {
     return(Log(DateTimeOffset.UtcNow, fields));
 }