コード例 #1
0
        public void Case6()
        {
            var text = @"linvar age for range (0, 150]
{
    `teenager` = Trapezoid(10, 12, 17, 20);
}";

            var codeEntity = Parse(text);

            CheckCodeEntity(codeEntity, "age");

            var lingiusticVariable = codeEntity.LinguisticVariable;

            lingiusticVariable.CheckDirty();

            Assert.AreEqual(lingiusticVariable.Name, NameHelper.CreateName("age"));

            CheckRange(lingiusticVariable.Range, false, 0, 150, true);

            Assert.AreEqual(lingiusticVariable.Constraint.IsEmpty, true);

            var term = lingiusticVariable.Values.Single();

            Assert.AreEqual(term.Name, NameHelper.CreateName("teenager"));
            Assert.AreEqual(term.Parent, lingiusticVariable);

            var handler = term.Handler;

            Assert.AreNotEqual(handler, null);

            Assert.AreEqual(handler.Kind, KindOfFuzzyLogicMemberFunction.Trapezoid);

            var handlerStr = handler.ToString();

            Assert.AreEqual(handlerStr.Contains("_a = 10"), true);
            Assert.AreEqual(handlerStr.Contains("_b = 12"), true);
            Assert.AreEqual(handlerStr.Contains("_c = 17"), true);
            Assert.AreEqual(handlerStr.Contains("_d = 20"), true);
        }
コード例 #2
0
        public void Should_add_policy_to_policycontainers()
        {
            // Arrange
            var controllerName   = NameHelper.Controller <AdminController>();
            var policyContainers = new List <PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast <IPolicyContainerConfiguration>().ToList());
            var policy = new DenyAnonymousAccessPolicy();

            // Act
            conventionPolicyContainer.AddPolicy(policy);

            // Assert
            Assert.That(policyContainers[0].GetPolicies().First(), Is.EqualTo(policy));
            Assert.That(policyContainers[1].GetPolicies().First(), Is.EqualTo(policy));
            Assert.That(policyContainers[2].GetPolicies().First(), Is.EqualTo(policy));
        }
コード例 #3
0
 public AutoColliderModel(MVRScript script, AutoCollider autoCollider, ColliderPreviewConfig config)
     : base(script, autoCollider, $"[au] {NameHelper.Simplify(autoCollider.name)}")
 {
     _initialCollisionEnabled     = _collisionEnabled = autoCollider.collisionEnabled;
     _initialColliderLength       = _colliderLength = autoCollider.colliderLength;
     _initialColliderRadius       = _colliderRadius = autoCollider.colliderRadius;
     _initialHardColliderBuffer   = _hardColliderBuffer = autoCollider.hardColliderBuffer;
     _initialColliderLookOffset   = _colliderLookOffset = autoCollider.colliderLookOffset;
     _initialColliderUpOffset     = _colliderUpOffset = autoCollider.colliderUpOffset;
     _initialColliderRightOffset  = _colliderRightOffset = autoCollider.colliderRightOffset;
     _initialAutoLengthBuffer     = _autoLengthBuffer = autoCollider.autoLengthBuffer;
     _initialAutoRadiusBuffer     = _autoRadiusBuffer = autoCollider.autoRadiusBuffer;
     _initialAutoRadiusMultiplier = _autoRadiusMultiplier = autoCollider.autoRadiusMultiplier;
     if (Component.hardCollider != null)
     {
         _ownedColliders.Add(ColliderModel.CreateTyped(script, autoCollider.hardCollider, config));
     }
     if (Component.jointCollider != null)
     {
         _ownedColliders.Add(ColliderModel.CreateTyped(script, Component.jointCollider, config));
     }
 }
コード例 #4
0
        public static void Export(IList <string> lists, string file)
        {
            file = file.Replace(".vcf", "");
            int count = (int)Math.Ceiling((double)lists.Count / 5000);
            var tasks = new Task[count];

            for (var i = 0; i < count; i++)
            {
                tasks[i] = new Task(index =>
                {
                    var start      = (int)index * 5000;
                    var length     = Math.Min(5000, lists.Count - start);
                    var writer     = new StreamWriter(file + index + ".vcf", false, Encoding.ASCII);
                    var nameHelper = new NameHelper();
                    for (var j = 0; j < length; j++)
                    {
                        var name = lists[start + j];
                        writer.WriteLine("BEGIN:VCARD");
                        writer.WriteLine("VERSION:2.1");
                        writer.WriteLine("N;CHARSET=UTF-8:" + name);
                        writer.WriteLine("TEL:" + name);
                        writer.WriteLine("END:VCARD");
                    }
                    writer.Close();
                }, i);
            }
            var continuation = Task.Factory.ContinueWhenAll(tasks, (task) =>
                                                            { });

            foreach (var task in tasks)
            {
                task.Start();
            }
            while (!continuation.IsCompleted)
            {
                Thread.Sleep(1000);
            }
        }
コード例 #5
0
        /// <inheritdoc/>
        protected override void OnFinish()
        {
            if (Result.Name == null || Result.Name.IsEmpty)
            {
                Result.Name = NameHelper.CreateRuleOrFactName();
            }

            var secondaryPartsList = Result.SecondaryParts;

            if (secondaryPartsList.IsNullOrEmpty())
            {
                var primaryPart = Result.PrimaryPart;

                if (primaryPart.HasQuestionVars)
                {
                    Result.Kind = KindOfRuleInstance.Question;
                }
                else
                {
                    Result.Kind = KindOfRuleInstance.Fact;
                }
            }
            else
            {
                Result.Kind = KindOfRuleInstance.Rule;

                var primaryPart = Result.PrimaryPart;

                primaryPart.SecondaryParts = secondaryPartsList.ToList();

                foreach (var secondaryPart in secondaryPartsList)
                {
                    secondaryPart.PrimaryPart = primaryPart;
                }
            }

            Result.CheckDirty();
        }
コード例 #6
0
        private void RouteBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var route = RouteBox.SelectedItem as Route;

            if (route == null)
            {
                return;
            }
            PrevStopBox.DataSource    = null;
            PrevStopBox.DisplayMember = "DisplayMember";
            PrevStopBox.ValueMember   = "ValueMember";
            PrevStopBox.DataSource    = Context.RouteStops
                                        .Include(x => x.Stop).Include(x => x.Prev).Where(x => x.Route.Id == route.Id).ToList()
                                        .Select(x =>
                                                new
            {
                DisplayMember = NameHelper.GetFullName(x),
                ValueMember   = x
            }
                                                )
                                        .OrderBy(x => NameHelper.GetNest(x.DisplayMember)).ToList();
            PrevStopBox.SelectedItem = null;
        }
コード例 #7
0
        /// <summary>
        /// Creates the LLVM types.
        /// </summary>
        private void createTypes()
        {
            string typeName = NameHelper.CreateTypeName(mType);

            foreach (KeyValuePair <TypeDefinition, Dictionary <string, int> > names in mNameTable)
            {
                string name = string.Format("vtable_{0}_part_{1}", typeName, NameHelper.CreateTypeName(names.Key));
                Dictionary <string, int> idDict = names.Value;

                // Initialize to pointers.
                TypeRef[] types = new TypeRef[idDict.Count];
                for (int i = 0; i < names.Value.Count; i++)
                {
                    types[i] = TypeHelper.VoidPtr;
                }

                TypeRef  type   = LLVM.StructTypeInContext(mCompiler.ModuleContext, types, false);
                ValueRef global = LLVM.AddGlobal(mCompiler.Module, type, name);
                LLVM.SetLinkage(global, Linkage.PrivateLinkage);

                mGeneratedTable.Add(names.Key, new Tuple <TypeRef, ValueRef>(type, global));
            }
        }
コード例 #8
0
        /// <summary>
        /// Saves the page source.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The saved source file</returns>
        public string SavePageSource(string fileName)
        {
            if (BaseConfiguration.GetPageSourceEnabled)
            {
                var fileNameShort = Regex.Replace(fileName, "[^0-9a-zA-Z._]+", "_");
                fileNameShort = NameHelper.ShortenFileName(this.PageSourceFolder, fileNameShort, "_", 255);
                var path = Path.Combine(this.PageSourceFolder, string.Format(CultureInfo.CurrentCulture, "{0}{1}", fileNameShort, ".html"));
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                var pageSource = this.driver.PageSource;
                pageSource = pageSource.Replace("<head>", string.Format(CultureInfo.CurrentCulture, "<head><base href=\"http://{0}\" target=\"_blank\">", BaseConfiguration.Host));
                File.WriteAllText(path, pageSource);

                Logger.Error(CultureInfo.CurrentCulture, "Test failed: page Source saved to {0}.", path);
                Logger.Info(CultureInfo.CurrentCulture, "##teamcity[publishArtifacts '{0}']", path);
                return(path);
            }

            return(null);
        }
コード例 #9
0
        /// <summary>
        /// Create new instance of <see cref="ColumnsToImportControl"/>
        /// </summary>
        public ColumnsToImportControl()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.SelectionMode       = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.Columns.Clear();
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = NameHelper <ColumnInfoWrapper> .Name(x => x.ColumnName),
                HeaderText       = "ValueColumn",
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = NameHelper <ColumnInfoWrapper> .Name(x => x.SiteName),
                HeaderText       = "Site"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = NameHelper <ColumnInfoWrapper> .Name(x => x.VariableName),
                HeaderText       = "Variable"
            });
        }
コード例 #10
0
        public string[] FindNames(string query, int maxResults)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return new string[] { }
            }
            ;

            query = query.Trim();

            return(HandleQuery(session => {
                var names = session.Query <AlbumName>()
                            .Where(a => !a.Album.Deleted)
                            .AddEntryNameFilter(query, NameMatchMode.Auto)
                            .Select(n => n.Value)
                            .OrderBy(n => n)
                            .Distinct()
                            .Take(maxResults)
                            .ToArray();

                return NameHelper.MoveExactNamesToTop(names, query);
            }));
        }
コード例 #11
0
        public static EnumModel Parse(FieldModel parent, EnumAttributeMetadata metadata)
        {
            if (metadata is null)
            {
                return(null);
            }

            var items =
                metadata?.OptionSet.Options.Select(
                    o => new EnumModelItem
            {
                DisplayName = NameHelper.GetProperVariableName(o.Label.UserLocalizedLabel.Label),
                Value       = o.Value ?? 1,
            }
                    ).ToArray();

            return(new EnumModel(
                       parent,
                       metadata.OptionSet.DisplayName(),
                       metadata?.OptionSet.Name,
                       metadata.OptionSet.IsGlobal ?? false,
                       items));
        }
コード例 #12
0
        protected override void MoreMapDataBC(FormViewModel viewData, T workflowInstance)
        {
            var properites = workflowInstance.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            if (properites != null && properites.Count() > 0)
            {
                JObject content = (JObject)viewData.dataItem;
                properites.Each(p => {
                    try
                    {
                        p.SetValue(workflowInstance, content.ToObject(p.Name, p.PropertyType), null);
                    } catch
                    {
                        try
                        {
                            p.SetValue(workflowInstance, content.ToObject(NameHelper.TransformName(p.Name), p.PropertyType), null);
                        } catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    }
                });
            }
        }
コード例 #13
0
        private Dictionary <StrongIdentifierValue, Value> NormalizeNamedParameters(Dictionary <StrongIdentifierValue, Value> source)
        {
            var result = new Dictionary <StrongIdentifierValue, Value>();

            foreach (var namedParameter in source)
            {
                var parameterName = namedParameter.Key;

#if DEBUG
                //Log($"parameterName = {parameterName}");
#endif

                var kindOfParameterName = parameterName.KindOfName;

                switch (kindOfParameterName)
                {
                case KindOfName.Var:
                    break;

                case KindOfName.Concept:
                    parameterName = NameHelper.CreateName($"@{parameterName.NameValue}");
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(kindOfParameterName), kindOfParameterName, null);
                }

#if DEBUG
                //Log($"parameterName (after) = {parameterName}");
#endif

                result[parameterName] = namedParameter.Value;
            }

            return(result);
        }
コード例 #14
0
        /// <summary>
        /// Saves the screenshot.
        /// </summary>
        /// <param name="errorDetail">The error detail.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="title">The title.</param>
        /// <returns>Path to the screenshot</returns>
        public string SaveScreenshot(ErrorDetail errorDetail, string folder, string title)
        {
            var fileName        = string.Format(CultureInfo.CurrentCulture, "{0}_{1}_{2}.png", title, errorDetail.DateTime.ToString("yyyy-MM-dd HH-mm-ss-fff", CultureInfo.CurrentCulture), "browser");
            var correctFileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(CultureInfo.CurrentCulture), string.Empty));

            correctFileName = Regex.Replace(correctFileName, "[^0-9a-zA-Z._]+", "_");
            correctFileName = NameHelper.ShortenFileName(folder, correctFileName, "_", 255);

            var filePath = Path.Combine(folder, correctFileName);

            try
            {
                errorDetail.Screenshot.SaveAsFile(filePath, ScreenshotImageFormat.Png);
                Logger.Error(CultureInfo.CurrentCulture, "Test failed: screenshot saved to {0}.", filePath);
                Logger.Info(CultureInfo.CurrentCulture, "##teamcity[publishArtifacts '{0}']", filePath);
                return(filePath);
            }
            catch (NullReferenceException)
            {
                Logger.Error("Test failed but was unable to get webdriver screenshot.");
            }

            return(null);
        }
コード例 #15
0
        public void Should_clear_all_cache_strategies()
        {
            var controllerName   = NameHelper.Controller <AdminController>();
            var policyContainers = new List <PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast <IPolicyContainerConfiguration>().ToList());

            conventionPolicyContainer.Cache <RequireAnyRolePolicy>(Cache.PerHttpRequest);

            // Act
            conventionPolicyContainer.ClearCacheStrategies();

            // Assert
            var containers = policyContainers.ToList();

            Assert.That(containers[0].CacheStrategies.Any(), Is.False);
            Assert.That(containers[1].CacheStrategies.Any(), Is.False);
            Assert.That(containers[2].CacheStrategies.Any(), Is.False);
        }
コード例 #16
0
        private static void AssertAllControllerActionsHasContainer(ConfigurationExpression configurationExpression)
        {
            var policyContainers = configurationExpression.Runtime.PolicyContainers;

            Assert.That(policyContainers.Count(), Is.EqualTo(21));
            var blog    = NameHelper.Controller <BlogController>();
            var admin   = NameHelper.Controller <AdminController>();
            var root    = NameHelper.Controller <RootController>();
            var include = NameHelper.Controller <IncludedController>();
            var exclude = NameHelper.Controller <ExcludedController>();

            Assert.That(policyContainers.GetContainerFor(blog, "Index"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(blog, "ListPosts"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(blog, "AddPost"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(blog, "EditPost"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(blog, "DeletePost"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(blog, "AjaxList"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(admin, "Index"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(admin, "LogIn"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(admin, "LogOut"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(root, "Index"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(include, "Index"), Is.Not.Null);
            Assert.That(policyContainers.GetContainerFor(exclude, "Index"), Is.Not.Null);
        }
コード例 #17
0
        public int EnterEmail(int name, int server, int country)
        {
            var email = string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}{3}{4}", NameHelper.RandomName(name), "@", NameHelper.RandomName(server), ".", NameHelper.RandomName(country));

            Logger.Info(CultureInfo.CurrentCulture, "Random generated Email'{0}'", email);
            this.Driver.GetElement(this.emailTextBox).SendKeys(email);
            return(email.Length - 2);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: Symontoclay/SymOntoClay
        private static void TstCreateName()
        {
            _logger.Log("Begin");

            var parserContext = new TstMainStorageContext();

            var nameVal1 = "dog";

            _logger.Log($"{nameof(nameVal1)} = {nameVal1}");

            //var result = ParseName(nameVal1);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal2 = "dog (animal)";

            //_logger.Info($"{nameof(nameVal2)} = {nameVal2}");

            //result = ParseName(nameVal2);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal3 = "dog (animal | instrument)";

            //_logger.Info($"{nameof(nameVal3)} = {nameVal3}");

            //result = ParseName(nameVal3);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal4 = "dog (animal (alive))";

            //_logger.Info($"{nameof(nameVal4)} = {nameVal4}");

            //result = ParseName(nameVal4);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal5 = "dog (alive::animal)";

            //_logger.Info($"{nameof(nameVal5)} = {nameVal5}");

            //result = ParseName(nameVal5);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal6 = "dog (alive::animal | instrument (big))";

            //_logger.Info($"{nameof(nameVal6)} = {nameVal6}");

            //result = ParseName(nameVal6);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal7 = "animal::dog";

            //result = ParseName(nameVal7);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            //var nameVal8 = "(animal | instrument)::dog";

            //result = ParseName(nameVal8);

            //_logger.Info($"result = {JsonConvert.SerializeObject(result, Formatting.Indented)}");

            var name = NameHelper.CreateName(nameVal1);

            _logger.Log($"name = {name}");

            _logger.Log("End");
        }
コード例 #19
0
ファイル: EmitLdftn.cs プロジェクト: SharpNative/CSharpLLVM
        /// <summary>
        /// Emits a ldftn instruction.
        /// </summary>
        /// <param name="instruction">The instruction.</param>
        /// <param name="context">The context.</param>
        /// <param name="builder">The builder.</param>
        public void Emit(Instruction instruction, MethodContext context, BuilderRef builder)
        {
            MethodDefinition method  = (MethodDefinition)instruction.Operand;
            ValueRef         result  = LLVM.BuildIntToPtr(builder, context.Compiler.Lookup.GetFunction(NameHelper.CreateMethodName(method)).Value, TypeHelper.NativeIntType, "ldftn");
            StackElement     element = new StackElement(result, typeof(IntPtr).GetTypeReference(), TypeHelper.NativeIntType);

            context.CurrentStack.Push(element);
        }
        public void Run()
        {
            _logger.Log("Begin");

            var complexContext = TstEngineContextHelper.CreateAndInitContext();

            var context      = complexContext.EngineContext;
            var worldContext = complexContext.WorldContext;

            //var dictionary = context.Dictionary;

            var platformListener = new TstPlatformHostListener();

            var npcSettings = new HumanoidNPCSettings();

            npcSettings.Id = "#020ED339-6313-459A-900D-92F809CEBDC5";
            //npcSettings.HostFile = Path.Combine(Directory.GetCurrentDirectory(), @"Source\Hosts\PeaceKeeper\PeaceKeeper.host");
            npcSettings.LogicFile       = Path.Combine(Directory.GetCurrentDirectory(), @"Source\Apps\PeaceKeeper\PeaceKeeper.sobj");
            npcSettings.HostListener    = platformListener;
            npcSettings.PlatformSupport = new PlatformSupportCLIStub();

            _logger.Log($"npcSettings = {npcSettings}");

            var tstBaseManualControllingGameComponent = new TstBaseManualControllingGameComponent(npcSettings, worldContext);

            var methodName = NameHelper.CreateName("go");

            var command = new Command();

            command.Name       = methodName;
            command.ParamsDict = new Dictionary <StrongIdentifierValue, Value>();

            var param1Value = new WaypointValue(25, 36, context);
            var param1Name  = NameHelper.CreateName("to");

            command.ParamsDict[param1Name] = param1Value;

            var param2Value = new NumberValue(12.4);
            var param2Name  = NameHelper.CreateName("speed");

            command.ParamsDict[param2Name] = param2Value;

            _logger.Log($"command = {command}");

            //ExecuteCommand(tstBaseManualControllingGameComponent, command);

            methodName = NameHelper.CreateName("shoot");

            command      = new Command();
            command.Name = methodName;

            ExecuteCommand(tstBaseManualControllingGameComponent, command);

            var gameObjectSettings = new GameObjectSettings();

            gameObjectSettings.Id = "#120ED339-6313-459A-900D-92F809CEBDC5";

            var gunPlatformHostListener = new TstGunPlatformHostListener();

            gameObjectSettings.HostListener = gunPlatformHostListener;

            _logger.Log($"gameObjectSettings = {gameObjectSettings}");

            var gameObject = new GameObjectImplementation(gameObjectSettings, worldContext);

            tstBaseManualControllingGameComponent.AddToManualControl(gameObject, 12);

            methodName = NameHelper.CreateName("shoot");

            command      = new Command();
            command.Name = methodName;

            ExecuteCommand(tstBaseManualControllingGameComponent, command);

            var manualControlledObjectsList = tstBaseManualControllingGameComponent.GetManualControlledObjects();

            //_logger.Log($"manualControlledObjectsList = {manualControlledObjectsList.WriteListToString()}");
            _logger.Log($"manualControlledObjectsList.Count = {manualControlledObjectsList.Count}");

            tstBaseManualControllingGameComponent.RemoveFromManualControl(gameObject);

            manualControlledObjectsList = tstBaseManualControllingGameComponent.GetManualControlledObjects();

            _logger.Log($"manualControlledObjectsList.Count = {manualControlledObjectsList.Count}");

            _logger.Log("End");
        }
コード例 #21
0
        public void Run()
        {
            _logger.Log("Begin");

            var context = TstEngineContextHelper.CreateAndInitContext().EngineContext;

            var applicationInheritanceItem = new InheritanceItem()
            {
                IsSystemDefined = true
            };

            applicationInheritanceItem.SubName   = NameHelper.CreateName("PeaseKeeper");
            applicationInheritanceItem.SuperName = context.CommonNamesStorage.AppName;
            applicationInheritanceItem.Rank      = new LogicalValue(1.0F);

            context.Storage.GlobalStorage.InheritanceStorage.SetInheritance(applicationInheritanceItem);

            var compiledFunctionBody = new CompiledFunctionBody();

            var strVal = new StringValue("The beatles!");

            var command = new ScriptCommand();

            command.OperationCode = OperationCode.PushVal;
            command.Value         = strVal;

            _logger.Log($"command = {command}");

            compiledFunctionBody.Commands[0] = command;

            var identifier = NameHelper.CreateName("@>log");

            command = new ScriptCommand();
            command.OperationCode = OperationCode.PushVal;
            command.Value         = identifier;
            command.Position      = 1;

            _logger.Log($"command = {command}");

            compiledFunctionBody.Commands[1] = command;


            command = new ScriptCommand();
            command.OperationCode  = OperationCode.CallBinOp;
            command.KindOfOperator = KindOfOperator.LeftRightStream;
            command.Position       = 2;

            _logger.Log($"command = {command}");

            compiledFunctionBody.Commands[2] = command;

            command = new ScriptCommand();
            command.OperationCode = OperationCode.Return;
            command.Position      = 3;

            _logger.Log($"command = {command}");

            compiledFunctionBody.Commands[3] = command;

            _logger.Log($"compiledFunctionBody = {compiledFunctionBody}");
            _logger.Log($"compiledFunctionBody = {compiledFunctionBody.ToDbgString()}");

            var codeFrame = new CodeFrame();

            codeFrame.CompiledFunctionBody = compiledFunctionBody;
            codeFrame.LocalContext         = new LocalCodeExecutionContext();
            codeFrame.LocalContext.Storage = context.Storage.GlobalStorage;
            codeFrame.LocalContext.Holder  = NameHelper.CreateName("PixKeeper");
            //codeFrame.LocalContext.Holder = new Name();

            _logger.Log($"codeFrame = {codeFrame}");
            _logger.Log($"codeFrame = {codeFrame.ToDbgString()}");

            var threadExecutor = new SyncThreadExecutor(context);

            threadExecutor.SetCodeFrame(codeFrame);

            threadExecutor.Start();

            _logger.Log("End");
        }
コード例 #22
0
        /// <summary>
        /// Applies the content to target.
        /// </summary>
        /// <param name="target">The target information.</param>
        /// <param name="run">The target output information.</param>
        /// <param name="writerSetup">The writer setup.</param>
        /// <param name="textOutput">The output.</param>
        /// <returns>
        /// A <see cref="Task" />.
        /// </returns>
        public async Task <string> ApplyContentToTargetAsync(IProject target, ICodeRun run, IMsBuildWriterSetup writerSetup, ITextOutput textOutput)
        {
            var filePath = Path.Combine(
                target.FolderPath,
                Path.Combine(NameHelper.GetFolderPath(run.Namespace).ToArrayIfNeeded()),
                run.Name + writerSetup.FileNameSuffix + writerSetup.FileExtension);

            if (this.project == null)
            {
                await IO.File.WriteAllTextAsync(filePath, textOutput.Text).ConfigureAwait(false);
            }
            else
            {
                var document = this.project.Documents.FirstOrDefault(x => filePath.Equals(x.FilePath));
                if (document != null)
                {
                    await IO.File.WriteAllTextAsync(filePath, textOutput.Text).ConfigureAwait(false);
                }
                else
                {
                    document     = this.project.AddDocument(run.Name, textOutput.Text, NameHelper.GetFolderPath(run.Namespace), filePath);
                    this.project = document.Project;
                }
            }

            return(filePath);
        }
コード例 #23
0
 private void CalculateIdForFacts()
 {
     _idForFacts = NameHelper.NormalizeNameStr(_id);
 }
コード例 #24
0
ファイル: NameHelperTests.cs プロジェクト: artberri/nombres
        public void NormalizeQuantities_WhenQuantityTypeTotal_ReturnsArrayOfTenTotalInts(int total, int max, int min, string expected)
        {
            var result = NameHelper.GetStyle(total, max, min);

            Assert.Equal(expected, result);
        }
コード例 #25
0
        public void Should_have_1_policycontainer()
        {
            SecurityConfigurator.Reset();

            // Act
            SecurityConfigurator.Configure(configuration =>
            {
                configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                configuration.GetRolesFrom(StaticHelper.GetRolesExcludingOwner);
                configuration.For <BlogController>(x => x.Index());
                configuration.For <BlogController>(x => x.Index());
            });

            Assert.That(SecurityConfiguration.Current.PolicyContainers.Count(), Is.EqualTo(1));
            Assert.That(SecurityConfiguration.Current.PolicyContainers.First().ControllerName, Is.EqualTo(NameHelper <BlogController> .Controller()));
            Assert.That(SecurityConfiguration.Current.PolicyContainers.First().ActionName, Is.EqualTo("Index"));
        }
コード例 #26
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            SimulationState state = CurrentState;

            if (state == null)
            {
                return;
            }

            DrawSky();

            effect.CurrentTechnique.Passes[0].Apply();
            effect.Projection = camera.ProjectionMatrix;
            effect.View       = camera.ViewMatrix;

            DrawPlayground();

            Selection selectedItem  = new Selection();
            Pickray   pickray       = camera.Pickray;
            Point     mousePosition = camera.MousePosition;

            // Selektionsinfos zurücksetzen
            selectedItem.SelectionType = SelectionType.Nothing;
            selectedItem.Item          = null;
            float distanceToSelectedItem = VIEWRANGE_MAX * VIEWRANGE_MAX;


            // Draw Bugs
            float distance;

            foreach (var bug in state.BugStates)
            {
                if ((distance = DrawBug(bug, pickray, false)) > 0)
                {
                    if (distance < distanceToSelectedItem)
                    {
                        distanceToSelectedItem     = distance;
                        selectedItem.Item          = bug;
                        selectedItem.SelectionType = SelectionType.Bug;
                    }
                }
            }

            // Draw Sugar
            foreach (var sugar in state.SugarStates)
            {
                if ((distance = DrawSugar(sugar, pickray, false)) > 0)
                {
                    if (distance < distanceToSelectedItem)
                    {
                        distanceToSelectedItem     = distance;
                        selectedItem.Item          = sugar;
                        selectedItem.SelectionType = SelectionType.Sugar;
                    }
                }
            }

            // Draw Fruit
            foreach (var fruit in state.FruitStates)
            {
                if ((distance = DrawFruit(fruit, pickray, false)) > 0)
                {
                    if (distance < distanceToSelectedItem)
                    {
                        distanceToSelectedItem     = distance;
                        selectedItem.Item          = fruit;
                        selectedItem.SelectionType = SelectionType.Fruit;
                    }
                }
            }

            // Draw Colony Base
            foreach (var colony in state.ColonyStates)
            {
                // Draw AntHills
                foreach (var anthill in colony.AnthillStates)
                {
                    if ((distance = DrawAnthill(colony.Id, anthill, pickray, false)) > 0)
                    {
                        if (distance < distanceToSelectedItem)
                        {
                            distanceToSelectedItem      = distance;
                            selectedItem.Item           = anthill;
                            selectedItem.SelectionType  = SelectionType.Anthill;
                            selectedItem.AdditionalInfo = CurrentState.ColonyStates[anthill.ColonyId - 1].ColonyName;
                        }
                    }
                }

                // Draw Ants
                foreach (var ant in colony.AntStates)
                {
                    // Debug Messages aktualisieren
                    if (!string.IsNullOrEmpty(ant.DebugMessage))
                    {
                        DebugMessage msg;
                        if (debugMessages.ContainsKey(ant.Id))
                        {
                            msg = debugMessages[ant.Id];
                        }
                        else
                        {
                            msg = new DebugMessage();
                            debugMessages.Add(ant.Id, msg);
                        }

                        msg.CreateRound = state.CurrentRound;
                        msg.Message     = ant.DebugMessage;
                    }

                    // Draw
                    if ((distance = DrawAnt(colony.Id, ant, pickray, false)) > 0)
                    {
                        if (distance < distanceToSelectedItem)
                        {
                            distanceToSelectedItem      = distance;
                            selectedItem.Item           = ant;
                            selectedItem.SelectionType  = SelectionType.Ant;
                            selectedItem.AdditionalInfo = CurrentState.ColonyStates[ant.ColonyId - 1].ColonyName;
                        }
                    }
                }

                // Remove old Messages
                foreach (var key in debugMessages.Keys.ToArray())
                {
                    DebugMessage msg = debugMessages[key];
                    if (state.CurrentRound - msg.CreateRound > DebugMessage.ROUNDS_TO_LIFE)
                    {
                        debugMessages.Remove(key);
                    }
                }
            }

            // Draw Marker
            foreach (var colony in state.ColonyStates)
            {
                foreach (var marker in colony.MarkerStates)
                {
                    DrawMarker(colony.Id, marker);
                }
            }

            // render all sprites in one SpriteBatch.Begin()-End() cycle to save performance
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);



            // Draw debug ant-thoughts
            if (showDebugInfo)
            {
                foreach (var colony in CurrentState.ColonyStates)
                {
                    foreach (var ant in colony.AntStates)
                    {
                        // Draw actual debug text
                        if (debugMessages.ContainsKey(ant.Id))
                        {
                            DebugMessage msg       = debugMessages[ant.Id];
                            Vector3      pos       = new Vector3(ant.PositionX - playgroundWidth, 4, -ant.PositionY + playgroundHeight);
                            Vector2      screenPos = debugRenderer.WorldToScreen(pos, new Vector2(0, -20));
                            Color        boxCol    = new Color(0.5f * playerColors[ant.ColonyId - 1]);
                            boxCol.A = 128;
                            DrawTextBox(msg.Message, screenPos, boxCol, Color.White);
                        }
                    }
                }
            }

            // Draw Infobox
            DrawInfobox(state);

            // Draw Info-Tag at selected item
            if (selectedItem.SelectionType != SelectionType.Nothing)
            {
                string line1;
                string line2;
                switch (selectedItem.SelectionType)
                {
                case SelectionType.Ant:

                    AntState ameise  = (AntState)selectedItem.Item;
                    string   antName = NameHelper.GetFemaleName(ameise.Id);
                    line1 = string.Format(Strings.HovertextAntLine1, antName, selectedItem.AdditionalInfo);
                    line2 = string.Format(Strings.HovertextAntLine2, ameise.Vitality);
                    break;

                case SelectionType.Anthill:
                    line1 = Strings.HovertextAnthillLine1;
                    line2 = string.Format(Strings.HovertextAnthillLine2, selectedItem.AdditionalInfo);
                    break;

                case SelectionType.Bug:
                    BugState bugState = (BugState)selectedItem.Item;
                    string   bugName  = NameHelper.GetMaleName(bugState.Id);
                    line1 = string.Format(Strings.HovertextBugLine1, bugName);
                    line2 = string.Format(Strings.HovertextBugLine2, bugState.Vitality);
                    break;

                case SelectionType.Fruit:
                    FruitState fruitState = (FruitState)selectedItem.Item;
                    line1 = Strings.HovertextFruitLine1;
                    line2 = string.Format(Strings.HovertextFruitLine2, fruitState.Amount);
                    break;

                case SelectionType.Sugar:
                    SugarState sugar = (SugarState)selectedItem.Item;
                    line1 = Strings.HovertextSugarLine1;
                    line2 = string.Format(Strings.HovertextSugarLine2, sugar.Amount);
                    break;

                default:
                    line1 = String.Empty;
                    line2 = String.Empty;
                    break;
                }

                // Text an Mausposition ausgeben
                if (line1 != String.Empty || line2 != String.Empty)
                {
                    DrawInfoTag(mousePosition, line1, line2);
                }
            }


            spriteBatch.End();

            base.Draw(gameTime);
        }
コード例 #27
0
ファイル: OtherService.cs プロジェクト: sethura/vocadb
        public string[] FindNames(string query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return new string[] {}
            }
            ;

            query = query.Trim();
            const int maxResults = 10;

            var canonized = ArtistHelper.GetCanonizedName(query);
            var matchMode = FindHelpers.GetMatchMode(query, NameMatchMode.Auto);
            var words     = (matchMode == NameMatchMode.Words ? FindHelpers.GetQueryWords(query) : null);

            return(HandleQuery(session => {
                var artistNames = session.Query <ArtistName>()
                                  .FilterByArtistName(query, canonized, NameMatchMode.Auto, null)       // Can't use the existing words collection here as they are noncanonized
                                  .Where(a => !a.Artist.Deleted)
                                  .Select(n => n.Value)
                                  .OrderBy(n => n)
                                  .Distinct()
                                  .Take(maxResults)
                                  .ToArray();

                var albumNames = session.Query <AlbumName>()
                                 .AddEntryNameFilter(query, NameMatchMode.Auto, words)
                                 .Where(a => !a.Album.Deleted)
                                 .Select(n => n.Value)
                                 .OrderBy(n => n)
                                 .Distinct()
                                 .Take(maxResults)
                                 .ToArray();

                var songNames = session.Query <SongName>()
                                .AddEntryNameFilter(query, NameMatchMode.Auto, words)
                                .Where(a => !a.Song.Deleted)
                                .Select(n => n.Value)
                                .OrderBy(n => n)
                                .Distinct()
                                .Take(maxResults)
                                .ToArray();

                var tagNames =
                    session.Query <Tag>()
                    .Where(t => t.Name.Contains(query))
                    .OrderBy(t => t.Name)
                    .Select(t => t.Name)
                    .Take(maxResults)
                    .ToArray();

                var allNames = artistNames
                               .Concat(albumNames)
                               .Concat(songNames)
                               .Concat(tagNames)
                               .Distinct()
                               .OrderBy(n => n)
                               .Take(maxResults)
                               .ToArray();

                return NameHelper.MoveExactNamesToTop(allNames, query);
            }));
        }
コード例 #28
0
        public void Should_throw_when_the_user_is_anonymous()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.For <BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act
            var exception = Assert.Throws <PolicyViolationException>(() => securityHandler.HandleSecurityFor(NameHelper.Controller <BlogController>(), "Index", SecurityContext.Current));

            // Assert
            Assert.That(exception.PolicyType, Is.EqualTo(typeof(DenyAnonymousAccessPolicy)));
            Assert.That(exception.Message, Is.StringContaining("Anonymous access denied"));
        }
コード例 #29
0
 public void AddANameElementToStoredPatient()
 {
     _fhirResourceRepository.Patient.Name.Add(NameHelper.CreateName(HumanName.NameUse.Nickname, "AdditionalGiven", "AdditionalFamily"));
 }
コード例 #30
0
        public void Should_throw_when_the_user_does_not_have_the_role_Owner()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.GetRolesFrom(StaticHelper.GetRolesExcludingOwner);
                policy.For <BlogController>(x => x.DeletePost(0)).RequireRole(UserRole.Owner);
            });

            var securityHandler = new SecurityHandler();

            // Act
            var exception = Assert.Throws <PolicyViolationException>(() => securityHandler.HandleSecurityFor(NameHelper.Controller <BlogController>(), "DeletePost", SecurityContext.Current));

            // Assert
            Assert.That(exception.PolicyType, Is.EqualTo(typeof(RequireRolePolicy)));
            Assert.That(exception.Message, Is.StringContaining("Access requires one of the following roles: Owner."));
        }