Ejemplo n.º 1
0
		public Scope ()
		{
			m_scopes = new ScopeCollection (this);
			m_usings = new UsingCollection (this);
			m_constants = new ConstantCollection (this);
			m_variables = new VariableCollection (this);
		}
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of <see cref="Scope"/> having "Anonymous" as default name.
 /// </summary>
 public Scope()
   : base("Anonymous") {
   parent = null;
   variables = new VariableCollection();
   subScopes = new ScopeList();
   RegisterSubScopesEvents();
 }
Ejemplo n.º 3
0
        public DataManager(Game game)
            : base(game)
        {
            _switches = new SwitchCollection();
            _variables = new VariableCollection();
            _achievementsToCreate = new Stack<Achievement>();

            _switches["Achievement Test"] = new Switch()
            {
                Name = "Achievement Test"
            };
            _switches["switch_ponies"] = new Switch()
            {
                Name = "Multi Switch Check Test"
            };

            _switches["Achievement Test"].TurnOn();
            PlayerName = new Variable("Pinkie Pie");
            PlayerGold = new Variable(1000);
            PlayerSteps = new Variable(0);
            PlayerName.Value = "Pinkie Pie";
            _variables["{steps_taken}"] = PlayerSteps;
            _variables["{profilename}"] = PlayerName;
            _variables["{gold}"] = PlayerGold;
        }
Ejemplo n.º 4
0
        public DataManager(Game game)
            : base(game)
        {
            _switches = new SwitchCollection();
            _variables = new VariableCollection();

            _switches["Achievement Test"] = new Switch()
            {
                Name = "Achievement Test"
            };
            _switches["switch_ponies"] = new Switch()
            {
                Name = "Multi Switch Check Test"
            };

            _playerParty = new BattleDataCollection();
            _playerCharacters = new BattleDataCollection();
            _enemyCollection = new BattleDataCollection();

            _switches["Achievement Test"].TurnOn();
            PlayerName = new Variable("Pinkie Pie");
            PlayerGold = new Variable(1000);
            PlayerSteps = new Variable(0);
            PlayerName.Value = "Pinkie Pie";
            _variables["{steps_taken}"] = PlayerSteps;
            _variables["{profilename}"] = PlayerName;
            _variables["{gold}"] = PlayerGold;
        }
Ejemplo n.º 5
0
 public void Close(string message)
 {
     VariableCollection vars = new VariableCollection();
     vars.Add("message", message);
     var obj = new JukeboxMessage { Type = "close", Variables = vars, MessageId = -1 };
     WriteMessage(obj);
     Context.Disconnect();
 }
Ejemplo n.º 6
0
        public ScriptContext(ScriptEnvironment environment)
        {
            if (environment == null)
                throw new ArgumentNullException("environment");

            _environment = environment;

            Variables = new VariableCollection();
        }
Ejemplo n.º 7
0
 public FormResources(Entities.Form form, VariableCollection variables, EnvironmentResource environment, IEnumerable<MachineResource> machines,
     IEnumerable<string> roles, Dictionary<string, string> actions)
 {
     Form = form;
     Variables = variables;
     Environment = environment;
     Machines = machines;
     Roles = roles;
     Actions = actions;
 }
Ejemplo n.º 8
0
 private Scope(Scope original, Cloner cloner)
   : base(original, cloner) {
   if (original.variables.Count > 0) variables = cloner.Clone(original.variables);
   else variables = new VariableCollection();
   if (original.subScopes.Count > 0) {
     subScopes = cloner.Clone(original.subScopes);
     foreach (IScope child in SubScopes)
       child.Parent = this;
   } else subScopes = new ScopeList();
   RegisterSubScopesEvents();
 }
Ejemplo n.º 9
0
        public VariableCollection Invoke(string commandId, VariableCollection variables)
        {
            if (variables == null)
                variables = new VariableCollection();

            var context = this.Context;
            if (context == null)
                throw new IOException("Connection not open");

            variables.Add("commandId", commandId);

            var obj = new JukeboxMessage { Type = "command", Variables = variables, MessageId = GetNewId() };
            var response = InvokeCore(obj);
            return (response);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExpressionContext"/>
        /// class with the specified imports, owner and whether to ignore case.
        /// </summary>
        /// <param name="imports">The imports of the expression context.</param>
        /// <param name="owner">The owner of the expression context.</param>
        /// <param name="ignoreCase">True to ignore case; otherwise false.</param>
        public ExpressionContext(IEnumerable<Import> imports, object owner, bool ignoreCase)
        {
            Owner = owner;
            IgnoreCase = ignoreCase;

            Variables = new VariableCollection(
                ignoreCase
                ? StringComparer.OrdinalIgnoreCase
                : StringComparer.Ordinal
            );

            if (imports != null)
                Imports = new List<Import>(imports);
            else
                Imports = new List<Import>();
        }
Ejemplo n.º 11
0
        public static VariableCollection GetProjectVariables(this List<ResourceVariableSetPair> variableSets, ProjectResource project, Dictionary<ScopeField, ScopeValue> scopeDictionary)
        {
            VariableCollection variablesPaired = new VariableCollection();

            foreach (ResourceVariableSetPair variableSetPair in variableSets)
            {
                foreach (VariableResource variableResource in variableSetPair.VariableSet.Variables)
                {
                    if (scopeDictionary != null && !variableResource.Scope.IsApplicableTo(scopeDictionary))
                    {
                        continue;
                    }

                    variablesPaired.AddOrUpdate(variableResource, variableSetPair.Resource);

                }
            }
            return variablesPaired;
        }
Ejemplo n.º 12
0
        public override AstNode VisitMethodDecl(MethodDecl ast)
        {
            m_currentMethod = ast.MethodInfo;
            m_currentVariableIndex = 0;
            m_currentMethodParameters = new VariableCollection<Parameter>();

            foreach (var param in m_currentMethod.Parameters)
            {
                m_currentMethodParameters.Add(param);
            }

            m_currentMethodVariables = new VariableCollection<VariableInfo>();

            if (ast.Statements == null || ast.ReturnExpression == null)
            {
                m_errorManager.AddError(c_SE_NotSupported, ast.Name.Span, "A method must have body defined");
                return ast;
            }

            foreach (var statement in ast.Statements)
            {
                Visit(statement);
            }

            Visit(ast.ReturnExpression);

            return ast;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// We do this so we don't have to keep re-declaring the same
        /// constructor
        /// </summary>
        /// <param name="core">Core token</param>
        /// <param name="owner">Owner</param>
        public void ModuleVector(Core core, Primitive owner, VariableCollection vc)
        {
            if (core == null)
            {
                throw new NullCoreException();
            }

            this.core = core;
            this.db = core.Db;
            this.session = core.Session;
            this.tz = core.Tz;
            this.Owner = owner;
            this.LoggedInMember = session.LoggedInMember;
            this.parentModulesVariableCollection = vc;

            CreateTemplate();

            string mode = core.Http["mode"];

            EventHandler loadHandler = Load;
            if (loadHandler != null)
            {
                loadHandler(this, new EventArgs());
            }

            if (string.IsNullOrEmpty(mode) || !HasModeHandler(mode))
            {
                EventHandler showHandler = Show;
                if (showHandler != null)
                {
                    showHandler(this, new EventArgs());
                }
            }
            else if (!string.IsNullOrEmpty(mode))
            {
                ShowMode(mode);
            }

            RenderTemplate();
        }
        /// <summary>
        /// Compiles the start block of
        /// </summary>
        /// <param name="context"></param>
        public TypeInfo CompileNewProcessStart(CompileContext context, string name)
        {
            try {
                //Get this before we push a new type on the stack, we are going to need it...
                Dictionary<string, LocalBuilder> currentLocals = null;

                if (context.Type != null) {
                    currentLocals = context.Type.Locals;
                }

                if (context.CurrentMasterType != null) { //Are in a type, so let's create a nested one
                    TypeInfo nestedType = new TypeInfo();
                    nestedType.Builder = context.Type.Builder.DefineNestedType(name, TypeAttributes.NestedPublic | TypeAttributes.Class | TypeAttributes.BeforeFieldInit, typeof(ProcessBase));
                    context.PushType(nestedType);
                } else {
                    context.PushType(context.GetType(name));
                    context.CurrentMasterType = context.Type;
                }
                Type baseType = typeof(ProcessBase);

                if (this.PreProcessActions != null) {
                    this.PreProcessActions.Compile(context);
                    context.Type.IsPreProcessed = true;
                }
                if (this.ActionRestrictions != null) {
                    this.ActionRestrictions.Compile(context);
                    context.Type.IsRestricted = true;
                }

                MethodBuilder methodStart = context.Type.Builder.DefineMethod("RunProcess", MethodAttributes.Public | MethodAttributes.Virtual);
                context.Type.Builder.DefineMethodOverride(methodStart, baseType.GetMethod("RunProcess"));
                context.PushIL(methodStart.GetILGenerator());
                Call(new ThisPointer(typeof(ProcessBase)), "InitSetID", true).Compile(context);
                if (this.WrapInTryCatch) {
                    context.ILGenerator.BeginExceptionBlock();
                }

                if (context.Type.Constructor == null) { //Nested type which hasn't defined its constructor yet

                    VariableCollection col = new VariableCollection();
                    col.Start(this);
                    List<Type> paramTypes = new List<Type>();
                    List<Variable> constructorParams = new List<Variable>();
                    foreach (Variable v in col.Variables) {
                        if (currentLocals != null && currentLocals.ContainsKey(v.Name)) { //We have defined this local variable and so should pass it to the new process
                            paramTypes.Add(typeof(object));
                            constructorParams.Add(v);
                            context.Type.ConstructorParameters.Add(v.Name); //Needed to pass the right parameters along later
                            context.Type.Fields.Add(context.Type.Builder.DefineField(v.Name, typeof(object), FieldAttributes.Private));
                        }
                    }
                    context.Type.Constructor = context.Type.Builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, paramTypes.ToArray());
                    ILGenerator ilCon = context.Type.Constructor.GetILGenerator();
                    ilCon.Emit(OpCodes.Ldarg_0);
                    ilCon.Emit(OpCodes.Call, typeof(ProcessBase).GetConstructor(new Type[] { }));

                    for (int i = 0; i < constructorParams.Count; i++) {
                        context.Type.Constructor.DefineParameter(i + 1, ParameterAttributes.None, constructorParams[i].Name);
                        //save the variables argument we got passed in
                        ilCon.Emit(OpCodes.Ldarg_0);
                        ilCon.Emit(OpCodes.Ldarg, i + 1);
                        ilCon.Emit(OpCodes.Stfld, context.Type.GetField(constructorParams[i].Name));
                    }
                    ilCon.Emit(OpCodes.Ret);
                }

                //Do this after the constructor has been defined, because the fields
                //of the object are defined in the constructor...
                foreach (FieldBuilder field in context.Type.Fields) {
                    LocalBuilder local = context.ILGenerator.DeclareLocal(typeof(object));
                    if (context.Options.Debug) {
                        local.SetLocalSymInfo(field.Name);
                    }
                    context.Type.Locals.Add(field.Name, local);
                    //Add the field value to the local variable, so we can concentrate on only local vars
                    context.ILGenerator.Emit(OpCodes.Ldarg_0);
                    context.ILGenerator.Emit(OpCodes.Ldfld, field);
                    context.ILGenerator.Emit(OpCodes.Stloc, local);

                }

                return context.Type;
            } catch (Exception) {
                return null;
            }
        }
Ejemplo n.º 15
0

        
Ejemplo n.º 16
0
        private void backgroundWorker1_DoWork(object sender,
                                              DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker worker = sender as BackgroundWorker;

            //bar.limit = tmlim;
            //bar.backgroundWorker1.RunWorkerAsync();
            //bar.StartPosition = FormStartPosition.CenterScreen;
            //bar.Show();

            // Assign the result of the computation
            // to the Result property of the DoWorkEventArgs
            // object. This is will be available to the
            // RunWorkerCompleted eventhandler.

            try
            {
                label20.Text       = "Please wait...";
                progressBar1.Value = 0;

                DateTime now   = DateTime.Now;
                string   datum = now.ToString("dd-MM-yyy");
                datum = datum.Replace("-", "");

                string csv = directory + "\\" + projectName + "_csv_" + datum + ".csv";

                // Parse chosen .sol File to csv File

                XmlRootAttribute root = new XmlRootAttribute();
                root.ElementName = "CPLEXSolution";

                VariableCollection col = null;

                XmlSerializer s      = new XmlSerializer(typeof(VariableCollection), root);
                StreamReader  reader = new StreamReader(solFilePath);

                col = (VariableCollection)s.Deserialize(reader);
                reader.Close();


                // Write deserialized data in csv file.
                int count = col.var.Count();

                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(csv))
                {
                    int i = 1; // counter for number of stabs

                    foreach (Variable va in col.var)
                    {
                        decimal dwert = 0;

                        if (!va.value.Contains("e"))
                        {
                            string temp = va.value.Replace(".", ",");
                            dwert = Convert.ToDecimal(temp);
                        }


                        if ((dwert > 0.85m) && (dwert < 1.15m)) // only stabs with value near 1 written in csv file
                        {
                            if (va.name.Contains("S("))
                            {
                                Stab stab = nameToStab(va.name);

                                String force = getForce(stab, col);

                                file.WriteLine(stab.node1 + ";" + stab.node2 + ";" + stab.diameter + ";" + force);
                                i++;
                            }
                        }

                        int percentComplete =
                            (int)((float)i / (float)count * 100);
                        worker.ReportProgress(percentComplete);

                        //int pro = (int)((float)i / (float)count);
                        //worker.ReportProgress(pro*100);
                    }

                    //file.WriteLine("Stabs: " + i); // To check if every Stab is represented
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("An error occured: " + ex.ToString(), "Info");
            }
        }
Ejemplo n.º 17
0
        public void CheckDefaultTestCase()
        {
            StackFrame         frame  = GetFrame($"{DefaultModuleName}!DefaultTestCase");
            VariableCollection locals = frame.Locals;
            dynamic            p      = locals["p"];

            std.wstring string1 = new std.wstring(p.string1);
            Assert.Equal("qwerty", string1.Text);
            std.list <std.wstring>                       strings     = new std.list <std.wstring>(p.strings);
            std.vector <std.@string>                     ansiStrings = new std.vector <std.@string>(p.ansiStrings);
            std.map <std.wstring, std.@string>           stringMap   = new std.map <std.wstring, std.@string>(p.stringMap);
            std.unordered_map <std.wstring, std.@string> stringUMap  = new std.unordered_map <std.wstring, std.@string>(p.stringUMap);

            string[] stringsConverted     = strings.Select(s => s.Text).ToArray();
            string[] ansiStringsConverted = ansiStrings.Select(s => s.Text).ToArray();

            CompareArrays(new[] { "Foo", "Bar" }, stringsConverted);
            CompareArrays(new[] { "AnsiFoo", "AnsiBar" }, ansiStringsConverted);

            foreach (std.wstring s in strings)
            {
                Assert.True(s.Length <= s.Reserved);
            }
            for (int i = 0; i < ansiStrings.Count; i++)
            {
                Assert.True(ansiStrings[i].Length <= ansiStrings[i].Reserved);
            }

            VerifyMap(stringMap);
            VerifyMap(stringUMap);

            // Verify enum value
            dynamic e = locals["e"];

            Assert.Equal("enumEntry3", e.ToString());
            Assert.Equal(3, (int)e);

            dynamic pEnumeration      = p.enumeration;
            dynamic pInnerEnumeration = p.innerEnumeration;

            Assert.Equal("enumEntry2", pEnumeration.ToString());
            Assert.Equal(2, (int)pEnumeration);
            Assert.Equal("simple4", pInnerEnumeration.ToString());
            Assert.Equal(4, (int)pInnerEnumeration);

            if (ExecuteCodeGen)
            {
                InterpretInteractive($@"
MyTestClass global = ModuleGlobals.globalVariable;
AreEqual(1212121212, MyTestClass.staticVariable);
AreEqual(""qwerty"", global.string1.Text);
AreEqual(2, global.strings.Count);
AreEqual(""Foo"", global.strings.ElementAt(0).Text);
AreEqual(""Bar"", global.strings.ElementAt(1).Text);
AreEqual(2, global.ansiStrings.Count);
AreEqual(""AnsiFoo"", global.ansiStrings[0].Text);
AreEqual(""AnsiBar"", global.ansiStrings[1].Text);
AreEqual(MyEnum.enumEntry2, global.enumeration);
AreEqual(MyTestClass.MyEnumInner.simple4, global.innerEnumeration);
                    ");
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="socket">Socket</param>
 /// <param name="endPoint">EndPoint</param>
 protected TuringSocket(Socket socket, IPEndPoint endPoint)
 {
     _Socket   = socket;
     EndPoint  = endPoint;
     Variables = new VariableCollection <string, object>();
 }
Ejemplo n.º 19
0
 public RunSpec(IReadOnlyList <IOperationProvider> operationOverrides, VariableCollection vars)
 {
     _overrides = operationOverrides;
     _vars      = vars ?? new VariableCollection();
 }
 protected IProcessor SetupJsxBlockCommentsProcessor(VariableCollection vc)
 {
     IOperationProvider[] operations = JsxBlockCommentConditionalsOperations;
     return(SetupTestProcessor(operations, vc));
 }
Ejemplo n.º 21
0
        public void Primer()
        {
            //ExStart
            //ExFor:Document.Variables
            //ExFor:VariableCollection
            //ExFor:VariableCollection.Add
            //ExFor:VariableCollection.Clear
            //ExFor:VariableCollection.Contains
            //ExFor:VariableCollection.Count
            //ExFor:VariableCollection.GetEnumerator
            //ExFor:VariableCollection.IndexOfKey
            //ExFor:VariableCollection.Remove
            //ExFor:VariableCollection.RemoveAt
            //ExSummary:Shows how to work with a document's variable collection.
            Document           doc       = new Document();
            VariableCollection variables = doc.Variables;

            // Every document has a collection of key/value pair variables, which we can add items to.
            variables.Add("Home address", "123 Main St.");
            variables.Add("City", "London");
            variables.Add("Bedrooms", "3");

            Assert.AreEqual(3, variables.Count);

            // We can display the values of variables in the document body using DOCVARIABLE fields.
            DocumentBuilder  builder = new DocumentBuilder(doc);
            FieldDocVariable field   = (FieldDocVariable)builder.InsertField(FieldType.FieldDocVariable, true);

            field.VariableName = "Home address";
            field.Update();

            Assert.AreEqual("123 Main St.", field.Result);

            // Assigning values to existing keys will update them.
            variables.Add("Home address", "456 Queen St.");

            // We will then have to update DOCVARIABLE fields to ensure they display an up-to-date value.
            Assert.AreEqual("123 Main St.", field.Result);

            field.Update();

            Assert.AreEqual("456 Queen St.", field.Result);

            // Verify that the document variables with a certain name or value exist.
            Assert.True(variables.Contains("City"));
            Assert.True(variables.Any(v => v.Value == "London"));

            // The collection of variables automatically sorts variables alphabetically by name.
            Assert.AreEqual(0, variables.IndexOfKey("Bedrooms"));
            Assert.AreEqual(1, variables.IndexOfKey("City"));
            Assert.AreEqual(2, variables.IndexOfKey("Home address"));

            // Enumerate over the collection of variables.
            using (IEnumerator <KeyValuePair <string, string> > enumerator = doc.Variables.GetEnumerator())
                while (enumerator.MoveNext())
                {
                    Console.WriteLine($"Name: {enumerator.Current.Key}, Value: {enumerator.Current.Value}");
                }

            // Below are three ways of removing document variables from a collection.
            // 1 -  By name:
            variables.Remove("City");

            Assert.False(variables.Contains("City"));

            // 2 -  By index:
            variables.RemoveAt(1);

            Assert.False(variables.Contains("Home address"));

            // 3 -  Clear the whole collection at once:
            variables.Clear();

            Assert.That(variables, Is.Empty);
            //ExEnd
        }
 protected IProcessor SetupHamlLineCommentsProcessor(VariableCollection vc)
 {
     IOperationProvider[] operations = HamlLineCommentConditionalOperations;
     return(SetupTestProcessor(operations, vc));
 }
Ejemplo n.º 23
0
        public HydroMixProblem(HydroSourceValues values,
                               HydroMixModelConfig config,
                               Target target,
                               SourceConfiguration sourceConfiguration)
        {
            Model = new Model();
            //var sources = values.GetSources();
            var sources = values.Sources().Where(s => sourceConfiguration.SourcesUsage[s.Code]).ToList();

            Sources            = sources;
            SourceContribution = new VariableCollection <Source>(
                Model,
                sources,
                "SourceContributions",
                s => $"Source {s.Code} contribution",
                s => 0,
                s => s.MaxSourceContribution, // weights should be >= 0 <= 1
                s => OPTANO.Modeling.Optimization.Enums.VariableType.Continuous);

            SourceUsed = new VariableCollection <Source>(
                Model,
                sources,
                "SourceIsUsed",
                s => $"Indicator whether source {s.Code} is used.",
                s => 0,
                s => 1,
                s => OPTANO.Modeling.Optimization.Enums.VariableType.Binary);

            PositiveErrors = new VariableCollection <MarkerInfo>(Model,
                                                                 values.MarkerInfos(),
                                                                 "Epsilon (+) error for each marker", mi => $"Error for marker: {mi.MarkerName}.",
                                                                 mi => 0,
                                                                 mi => double.MaxValue,
                                                                 mi => VariableType.Continuous
                                                                 );

            NegativeErrors = new VariableCollection <MarkerInfo>(Model,
                                                                 values.MarkerInfos(),
                                                                 "Epsilon (-) error for each marker", mi => $"Error for marker: {mi.MarkerName}.",
                                                                 mi => 0,
                                                                 mi => double.MaxValue,
                                                                 mi => VariableType.Continuous
                                                                 );

            // https://math.stackexchange.com/questions/2571788/indicator-variable-if-x-is-in-specific-range

            // constraints
            foreach (var source in sources)
            {
                // force not-used when contribution = 0
                var indicator = SourceContribution[source] + SourceUsed[source] <= 1000 * SourceUsed[source];
                Model.AddConstraint(indicator, $"Indicator for {source.Code}");

                // force used when contribution > 0
                var indicator2 = SourceUsed[source] - SourceContribution[source] >= 0;
                Model.AddConstraint(indicator2, $"Indicator for {source.Code}");

                if (config.MinimalSourceContribution > 0)
                {
                    Model.AddConstraint(SourceContribution[source] >= config.MinimalSourceContribution * SourceUsed[source],
                                        $"Minimal source {source.Code} contribution.");
                }
            }

            // weights sum should be 1
            var contributionsSum = Expression.Sum(sources.Select(s => SourceContribution[s]));

            Model.AddConstraint(contributionsSum == 1, "Contributions sum equals 1");

            // max sources contributing
            var usedSourcesCount = Expression.Sum(sources.Select(s => SourceUsed[s]));

            if (config.MaxSourcesUsed.HasValue)
            {
                Model.AddConstraint(usedSourcesCount <= config.MaxSourcesUsed.Value);
            }

            // min sources contributing
            if (config.MinSourcesUsed.HasValue)
            {
                Model.AddConstraint(usedSourcesCount >= config.MinSourcesUsed.Value);
            }

            // equation for each marker
            foreach (var markerInfo in values.MarkerInfos()
                     //.Where(mi => mi.Weight > 0)
                     )
            {
                var positiveEpsilon = PositiveErrors[markerInfo];
                var negativeEpsilon = NegativeErrors[markerInfo];
                // get all values for current marker
                var markerValues = sources.Where(x => x.MaxSourceContribution > 0).Select(s => s.MarkerValues.Single(mv => mv.MarkerInfo == markerInfo));

                var sourcesContributedToMarker = Expression.Sum(
                    markerValues.Select(x => SourceContribution[x.Source] * x.Value));

                Model.AddConstraint(sourcesContributedToMarker == positiveEpsilon + target[markerInfo] - negativeEpsilon);
            }

            // min: diff between target and resulting mix
            Model.AddObjective(new Objective(Expression.Sum(
                                                 values.MarkerInfos().Where(mi => mi.Weight > 0).Select(mi => PositiveErrors[mi] * mi.Weight)

                                                 .Concat(values.MarkerInfos().Where(mi => mi.Weight > 0).Select(mi => NegativeErrors[mi] * mi.Weight))

                                                 ),
                                             "Difference between mix and target.",
                                             ObjectiveSense.Minimize));
        }
Ejemplo n.º 24
0
 public VariableCollection ProduceCollection(VariableCollection parent)
 {
     return(_vars);
 }
Ejemplo n.º 25
0
 private Statement ParseOtherStatement(bool unsafeCode, VariableCollection variables)
 {
     int num;
     bool flag = false;
     if (this.HasTypeSignature(1, unsafeCode, out num))
     {
         int count = this.GetNextCodeSymbolIndex(num + 1);
         if ((count != -1) && (this.symbols.Peek(count).SymbolType == SymbolType.Other))
         {
             count = this.GetNextCodeSymbolIndex(count + 1);
             if (count != -1)
             {
                 Symbol symbol = this.symbols.Peek(count);
                 if (((symbol.SymbolType == SymbolType.Equals) || (symbol.SymbolType == SymbolType.Semicolon)) || (symbol.SymbolType == SymbolType.Comma))
                 {
                     flag = true;
                 }
             }
         }
     }
     if (flag)
     {
         return this.ParseVariableDeclarationStatement(unsafeCode, variables);
     }
     int nextCodeSymbolIndex = this.GetNextCodeSymbolIndex(2);
     if ((nextCodeSymbolIndex == -1) || (this.symbols.Peek(nextCodeSymbolIndex).SymbolType != SymbolType.Colon))
     {
         return this.ParseExpressionStatement(unsafeCode);
     }
     return this.ParseLabelStatement(unsafeCode);
 }
 protected IProcessor SetupVBStyleNoCommentsProcessor(VariableCollection vc)
 {
     IOperationProvider[] operations = VBStyleNoCommentsConditionalOperations;
     return(SetupTestProcessor(operations, vc));
 }
        ///
        /// Sets up a processor with the input params.
        ///
        private IProcessor SetupTestProcessor(IOperationProvider[] operations, VariableCollection vc)
        {
            EngineConfig cfg = new EngineConfig(EnvironmentSettings, vc);

            return(Processor.Create(cfg, operations));
        }
Ejemplo n.º 28
0
    /// <summary>
    /// Read the XML file for a specific tree
    /// </summary>
    /// <param name="file">The path of the file to load</param>
    /// <returns></returns>
    public bool LoadXML(string file)
    {
        if (!System.IO.File.Exists(file))
        {
            return(false);
        }


        XmlReaderSettings settings = new XmlReaderSettings();

        settings.IgnoreComments = true;

        XmlReader reader = XmlReader.Create(file, settings);

        XmlDocument document = new XmlDocument();

        document.Load(reader);

        List <ImportProfile> avaliableCollections = new List <ImportProfile>();
        float totalWeight = 0.0f;

        // Read document
        XmlElement root = document.DocumentElement;

        foreach (XmlElement child in root.ChildNodes)
        {
            // Profile loading - TODO
            if (child.Name == "Profile")
            {
                float weight = 1.0f;
                if (child.HasAttribute("weight"))
                {
                    float.TryParse(child.GetAttribute("weight"), out weight);
                }

                ImportProfile profile = new ImportProfile(weight);
                totalWeight += weight;


                foreach (XmlElement var in child.ChildNodes)
                {
                    if (var.Name != "var")
                    {
                        Debug.LogError("Profile must only have child nodes of type 'var'");
                    }
                    if (!var.HasAttribute("name"))
                    {
                        Debug.LogError("Profile.var must have attribute 'name'");
                    }

                    float value = 0.0f;
                    float.TryParse(var.InnerXml, out value);
                    profile.vars.SetVar(var.GetAttribute("name"), value);
                }


                avaliableCollections.Add(profile);
            }

            // Load the actual tree
            if (child.Name == "Decision")
            {
                if (child.ChildNodes.Count != 1)
                {
                    Debug.LogError("Decision must have exactly 1 child");
                }

                rootDecision = ParseDecision((XmlElement)child.FirstChild);
            }
        }

        Debug.Log("Read from '" + file + "'");

        // Store all profiles for debug
        agentProfiles = new VariableCollection[avaliableCollections.Count];
        for (int i = 0; i < avaliableCollections.Count; ++i)
        {
            agentProfiles[i] = avaliableCollections[i].vars;
        }

        // Randomly assign a profile to this var
        if (totalWeight == 0.0f)
        {
            agentProfile = new VariableCollection();
        }
        else
        {
            // Fetch a profile based on it's weight
            float value = UnityEngine.Random.Range(0.0f, totalWeight);

            for (int i = 0; i < avaliableCollections.Count; ++i)
            {
                if (value < avaliableCollections[i].weight)
                {
                    agentProfile = avaliableCollections[i].vars;
                    break;
                }
                else
                {
                    value -= avaliableCollections[i].weight;
                }
            }
        }


        return(true);
    }
Ejemplo n.º 29
0
        private static void showDayEvents(Core core, Primitive owner, int year, int month, int day, VariableCollection weekVariableCollection, List<Event> events)
        {
            VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
            dayVariableCollection.Parse("DATE", day.ToString());
            dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year, month, day));

            DateTime now = core.Tz.Now;
            if (year == now.Year && month == now.Month && day == now.Day)
            {
                dayVariableCollection.Parse("CLASS", "today");
            }

            bool hasEvents = false;

            List<Event> expired = new List<Event>();
            foreach (Event calendarEvent in events)
            {
                // if the event starts after the end of the day, skip this day
                if (calendarEvent.GetStartTime(core.Tz).CompareTo(new DateTime(year, month, day, 23, 59, 59)) > 0)
                {
                    break;
                }

                VariableCollection eventVariableCollection = dayVariableCollection.CreateChild("event");

                eventVariableCollection.Parse("TITLE", calendarEvent.Subject);
                if (calendarEvent.GetStartTime(core.Tz).Day != day)
                {
                    eventVariableCollection.Parse("START_TIME", calendarEvent.GetStartTime(core.Tz).ToString("d MMMM h:mmt").ToLower());
                }
                else
                {
                    eventVariableCollection.Parse("START_TIME", calendarEvent.GetStartTime(core.Tz).ToString("h:mmt").ToLower());
                }
                eventVariableCollection.Parse("URI", calendarEvent.Uri);

                if (calendarEvent is BirthdayEvent)
                {
                    BirthdayEvent birthdayEvent = (BirthdayEvent)calendarEvent;

                    eventVariableCollection.Parse("BIRTH_DATE", birthdayEvent.User.Profile.DateOfBirth.Day + " " + core.Tz.MonthToString(birthdayEvent.User.Profile.DateOfBirth.Month));
                }

                hasEvents = true;

                // if the event ends before the end of the day, finish up the event
                if (calendarEvent.GetEndTime(core.Tz).CompareTo(new DateTime(year, month, day, 23, 59, 59)) <= 0)
                {
                    expired.Add(calendarEvent);
                }
            }

            if (hasEvents)
            {
                dayVariableCollection.Parse("EVENTS", "TRUE");
            }

            foreach (Event calendarEvent in expired)
            {
                events.Remove(calendarEvent);
            }
        }
Ejemplo n.º 30
0
        public void VerifyTinyPageReplacement()
        {
            string value    = @"test value test";
            string expected = @"test foo test";

            byte[]       valueBytes = Encoding.UTF8.GetBytes(value);
            MemoryStream input      = new MemoryStream(valueBytes);
            MemoryStream output     = new MemoryStream();

            IOperationProvider[] operations = { new Replacement("value".TokenConfig(), "foo", null, true) };
            EngineConfig         cfg        = new EngineConfig(_engineEnvironmentSettings.Host.Logger, VariableCollection.Environment(_engineEnvironmentSettings), "${0}$");
            IProcessor           processor  = Processor.Create(cfg, operations);

            //Changes should be made
            bool changed = processor.Run(input, output, 1);

            Verify(Encoding.UTF8, output, changed, value, expected);
        }
 protected IProcessor SetupXmlStyleProcessor(VariableCollection vc)
 {
     IOperationProvider[] operations = XmlStyleCommentConditionalsOperations;
     return(SetupTestProcessor(operations, vc));
 }
Ejemplo n.º 32
0
        public void VerifyThreeLevelNestedBlockComments()
        {
            string originalValue = @"Start
<!--#if (IF_LEVEL_1)
    Content: If Level 1
    <!--#if (IF_IF_LEVEL_2)
        Content: If IF Level 2
        <!--#if (IF_IF_IF_LEVEL_3)
            Content: If IF If Level 3
        #elseif (IF_IF_ELSEIF_LEVEL_3)
            Content: If If Elseif Level 3
        #elseif (IF_IF_ELSEIF_TWO_LEVEL_3)
            Content: If If Elseif Two Level 3
        #else
            Content: If If Else Level 3
        #endif-->
    #elseif (IF_ELSEIF_LEVEL_2)
        Content: If Elseif Level 2
        <!--#if (IF_ELSEIF_IF_LEVEL_3)
            Content: If Elseif If Level 3
        #elseif (IF_ELSEIF_ELSEIF_LEVEL_3)
            Content: If Elseif Elseif Level 3
        #else
            Content: If Elseif Else Level 3
        #endif-->
    #elseif (IF_ELSEIF_TWO_LEVEL_2)
        Content: If Elseif Two Level 2
        <!--#if (IF_ELSEIF_TWO_IF_LEVEL_3)
            Content: If Elseif Two If Level 3
        #elseif (IF_ELSEIF_TWO_ELSEIF_LEVEL_3)
            Content: If Elseif Two Elseif Level 3
        #else
            Content: If Elseif Two Else Level 3
        #endif-->
    #else
        Content: If Else Level 2
        <!--#if (IF_ELSE_IF_LEVEL_3)
            Content: If Else If Level 3
        #elseif (IF_ELSE_ELSEIF_LEVEL_3)
            Content: If Else Elseif Level 3
        #else
            Content: If Else Else Level 3
        #endif-->
    #endif-->
#elseif (ELSEIF_LEVEL_1)
    Content: Elseif Level 1
#else
    Content: Else Level 1
#endif-->
End";
            // if-if-if
            string             expectedValue = @"Start
    Content: If Level 1
        Content: If IF Level 2
            Content: If IF If Level 3
End";
            VariableCollection vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]       = true,
                ["IF_IF_LEVEL_2"]    = true,
                ["IF_IF_IF_LEVEL_3"] = true,
            };
            IProcessor processor = SetupXmlStyleProcessor(vc);

            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-if-elseif
            expectedValue = @"Start
    Content: If Level 1
        Content: If IF Level 2
            Content: If If Elseif Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]           = true,
                ["IF_IF_LEVEL_2"]        = true,
                ["IF_IF_IF_LEVEL_3"]     = false,
                ["IF_IF_ELSEIF_LEVEL_3"] = true
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-if-elseif2
            expectedValue = @"Start
    Content: If Level 1
        Content: If IF Level 2
            Content: If If Elseif Two Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]               = true,
                ["IF_IF_LEVEL_2"]            = true,
                ["IF_IF_IF_LEVEL_3"]         = false,
                ["IF_IF_ELSEIF_LEVEL_3"]     = false,
                ["IF_IF_ELSEIF_TWO_LEVEL_3"] = true
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-if-else
            expectedValue = @"Start
    Content: If Level 1
        Content: If IF Level 2
            Content: If If Else Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]               = true,
                ["IF_IF_LEVEL_2"]            = true,
                ["IF_IF_IF_LEVEL_3"]         = false,
                ["IF_IF_ELSEIF_LEVEL_3"]     = false,
                ["IF_IF_ELSEIF_TWO_LEVEL_3"] = false
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif-if
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Level 2
            Content: If Elseif If Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]           = true,
                ["IF_IF_LEVEL_2"]        = false,
                ["IF_ELSEIF_LEVEL_2"]    = true,
                ["IF_ELSEIF_IF_LEVEL_3"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif-elseif
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Level 2
            Content: If Elseif Elseif Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]               = true,
                ["IF_IF_LEVEL_2"]            = false,
                ["IF_ELSEIF_LEVEL_2"]        = true,
                ["IF_ELSEIF_IF_LEVEL_3"]     = false,
                ["IF_ELSEIF_ELSEIF_LEVEL_3"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif-else
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Level 2
            Content: If Elseif Else Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]               = true,
                ["IF_IF_LEVEL_2"]            = false,
                ["IF_ELSEIF_LEVEL_2"]        = true,
                ["IF_ELSEIF_IF_LEVEL_3"]     = false,
                ["IF_ELSEIF_ELSEIF_LEVEL_3"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif two-if
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Two Level 2
            Content: If Elseif Two If Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]               = true,
                ["IF_IF_LEVEL_2"]            = false,
                ["IF_ELSEIF_LEVEL_2"]        = false,
                ["IF_ELSEIF_TWO_LEVEL_2"]    = true,
                ["IF_ELSEIF_TWO_IF_LEVEL_3"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif two-elseif
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Two Level 2
            Content: If Elseif Two Elseif Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]                   = true,
                ["IF_IF_LEVEL_2"]                = false,
                ["IF_ELSEIF_LEVEL_2"]            = false,
                ["IF_ELSEIF_TWO_LEVEL_2"]        = true,
                ["IF_ELSEIF_TWO_IF_LEVEL_3"]     = false,
                ["IF_ELSEIF_TWO_ELSEIF_LEVEL_3"] = true
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-elseif two-else
            expectedValue = @"Start
    Content: If Level 1
        Content: If Elseif Two Level 2
            Content: If Elseif Two Else Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]                   = true,
                ["IF_IF_LEVEL_2"]                = false,
                ["IF_ELSEIF_LEVEL_2"]            = false,
                ["IF_ELSEIF_TWO_LEVEL_2"]        = true,
                ["IF_ELSEIF_TWO_IF_LEVEL_3"]     = false,
                ["IF_ELSEIF_TWO_ELSEIF_LEVEL_3"] = false
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-else-if
            expectedValue = @"Start
    Content: If Level 1
        Content: If Else Level 2
            Content: If Else If Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]            = true,
                ["IF_IF_LEVEL_2"]         = false,
                ["IF_ELSEIF_LEVEL_2"]     = false,
                ["IF_ELSEIF_TWO_LEVEL_2"] = false,
                ["IF_ELSE_IF_LEVEL_3"]    = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-else-elseif
            expectedValue = @"Start
    Content: If Level 1
        Content: If Else Level 2
            Content: If Else Elseif Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]             = true,
                ["IF_IF_LEVEL_2"]          = false,
                ["IF_ELSEIF_LEVEL_2"]      = false,
                ["IF_ELSEIF_TWO_LEVEL_2"]  = false,
                ["IF_ELSE_IF_LEVEL_3"]     = false,
                ["IF_ELSE_ELSEIF_LEVEL_3"] = true
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);

            // if-else-else
            expectedValue = @"Start
    Content: If Level 1
        Content: If Else Level 2
            Content: If Else Else Level 3
End";
            vc            = new VariableCollection
            {
                ["IF_LEVEL_1"]             = true,
                ["IF_IF_LEVEL_2"]          = false,
                ["IF_ELSEIF_LEVEL_2"]      = false,
                ["IF_ELSEIF_TWO_LEVEL_2"]  = false,
                ["IF_ELSE_IF_LEVEL_3"]     = false,
                ["IF_ELSE_ELSEIF_LEVEL_3"] = false
            };
            processor = SetupXmlStyleProcessor(vc);
            RunAndVerify(originalValue, expectedValue, processor, 9999);
        }
Ejemplo n.º 33
0
 public ImportProfile(float weight)
 {
     this.weight = weight;
     vars        = new VariableCollection();
 }
Ejemplo n.º 34
0
        public void VerifyMultipleNestedBlockComments()
        {
            // the actual tests for OUTER_IF_CLAUSE = true (inner else also happens because the other inners are false)
            string expectedValue = @"Start
    content: outer-if
        content: inner-else
Trailing stuff
<!- trailing comment -->";

            VariableCollection vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = true,
                ["INNER_IF_CLAUSE"]     = false,
                ["INNER_ELSEIF_CLAUSE"] = false,
                ["OUTER_ELSEIF_CLAUSE"] = false,
            };
            IProcessor processor = SetupXmlStyleProcessor(vc);

            // comment spans from inner if to outer endif
            // comments are unbalanced
            // invalid ???
            string inputValue = @"Start
<!--#if (OUTER_IF_CLAUSE) -->
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif-- >
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            RunAndVerify(inputValue, expectedValue, processor, 9999);

            // comments are balanced
            string inputValue2 = @"Start
<!--#if (OUTER_IF_CLAUSE) -->
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif-- >
<!--#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            RunAndVerify(inputValue2, expectedValue, processor, 9999);

            // inner elseif is default, comments are balanced and nesting-balanced.
            string inputValue3 = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE) -->
        content: inner-elseif
    <!--#else
        content: inner-else
    #endif-->
<!--#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            RunAndVerify(inputValue3, expectedValue, processor, 9999);
        }
Ejemplo n.º 35
0
 public EventReader(OsuFileReader reader, VariableCollection variables)
 {
     Variables   = variables;
     this.reader = new SectionReader(Section.Events, reader);
 }
Ejemplo n.º 36
0
        public void XmlBlockCommentBasicTest()
        {
            IList <string> testCases = new List <string>();

            string basicValue = @"Start
<!--#if (CLAUSE)
    content: if
#elseif (CLAUSE_2)
    content: elseif
#else
    content: else
#endif-->
Trailing stuff";

            testCases.Add(basicValue);

            string basicWithDefault = @"Start
<!--#if (CLAUSE) -->
    content: if
<!--#elseif (CLAUSE_2)
    content: elseif
#else
    content: else
#endif-->
Trailing stuff";

            testCases.Add(basicWithDefault);

            string expectedValueIfEmits = @"Start
    content: if
Trailing stuff";

            VariableCollection vc = new VariableCollection
            {
                ["CLAUSE"]   = true,
                ["CLAUSE_2"] = true,    // irrelevant
            };
            IProcessor processor = SetupXmlStyleProcessor(vc);

            foreach (string test in testCases)
            {
                RunAndVerify(test, expectedValueIfEmits, processor, 9999);
            }

            // change the clause values so the elseif emits
            string expectedValueElseifEmits = @"Start
    content: elseif
Trailing stuff";

            vc = new VariableCollection
            {
                ["CLAUSE"]   = false,
                ["CLAUSE_2"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, expectedValueElseifEmits, processor, 9999);
            }

            // change the clause values so the else emits
            string expectedValueElseEmits = @"Start
    content: else
Trailing stuff";

            vc = new VariableCollection
            {
                ["CLAUSE"]   = false,
                ["CLAUSE_2"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, expectedValueElseEmits, processor, 9999);
            }
        }
Ejemplo n.º 38
0
        public void XmlBlockCommentIfElseifElseTestWithCommentStripping()
        {
            IList <string> testCases = new List <string>();

            string originalValue = @"Start
<!--#if (IF_CLAUSE)
    content: if stuff, line 1
    content: if stuff line 2
#elseif (ELSEIF_CLAUSE) -->
    content: default stuff in the elseif
    content: default line 2 (elseif)
<!--#else
    content: else stuff, line 1
    content: default stuff in the else
    content: trailing else stuff, not default
#endif-->
Trailing stuff
<!-- trailing comment -->";

            testCases.Add(originalValue);

            string fullerCommentsOnlyValue = @"Start
<!--#if (IF_CLAUSE)
    content: if stuff, line 1
    content: if stuff line 2
#elseif (ELSEIF_CLAUSE) -->
    content: default stuff in the elseif
    content: default line 2 (elseif)
<!--#else
    content: else stuff, line 1
    content: default stuff in the else
    content: trailing else stuff, not default
#endif-->
Trailing stuff
<!-- trailing comment -->";

            testCases.Add(fullerCommentsOnlyValue);

            // note that there is no default here
            string oneBigCommentValue = @"Start
<!--#if (IF_CLAUSE)
    content: if stuff, line 1
    content: if stuff line 2
#elseif (ELSEIF_CLAUSE)
    content: default stuff in the elseif
    content: default line 2 (elseif)
#else
    content: else stuff, line 1
    content: default stuff in the else
    content: trailing else stuff, not default
#endif-->
Trailing stuff
<!-- trailing comment -->";

            testCases.Add(oneBigCommentValue);

            string             ifTrueExpectedValue = @"Start
    content: if stuff, line 1
    content: if stuff line 2
Trailing stuff
<!-- trailing comment -->";
            VariableCollection vc = new VariableCollection
            {
                ["IF_CLAUSE"]     = true,
                ["ELSEIF_CLAUSE"] = false,
            };
            IProcessor processor = SetupXmlStyleProcessor(vc);

            foreach (string test in testCases)
            {
                RunAndVerify(test, ifTrueExpectedValue, processor, 9999);
            }

            string elseifTrueExpectedValue = @"Start
    content: default stuff in the elseif
    content: default line 2 (elseif)
Trailing stuff
<!-- trailing comment -->";

            vc = new VariableCollection
            {
                ["IF_CLAUSE"]     = false,
                ["ELSEIF_CLAUSE"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, elseifTrueExpectedValue, processor, 9999);
            }

            string elseHappensExpectedValue = @"Start
    content: else stuff, line 1
    content: default stuff in the else
    content: trailing else stuff, not default
Trailing stuff
<!-- trailing comment -->";

            vc = new VariableCollection
            {
                ["IF_CLAUSE"]     = false,
                ["ELSEIF_CLAUSE"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, elseHappensExpectedValue, processor, 9999);
            }
        }
Ejemplo n.º 39
0
 public CodeClassType()
 {
     Methods = new Collection<Method>();
     StaticMethods = new Collection<Method>();
     Fields = new VariableCollection<Field>();
 }
Ejemplo n.º 40
0
        public void VerifyXmlBlockCommentEmbeddedInIfTest()
        {
            IList <string> testCases = new List <string>();

            string noDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif-- >
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(noDefaultValue);

            string outerIfDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE) -->
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(outerIfDefaultValue);

            string innerIfDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE) -->
        content: inner-if
    <!--#elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(innerIfDefaultValue);

            string innerElseifDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE) -->
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    <!--#elseif (INNER_ELSEIF_CLAUSE) -->
        content: inner-elseif
    <!--#else
        content: inner-else
    #endif
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(innerElseifDefaultValue);

            string innerElseDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    <!--#else-->
        content: inner-else
    <!--#endif
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(innerElseDefaultValue);

            string outerElseifDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif
<!--#elseif (OUTER_ELSEIF_CLAUSE)-->
    content: outer-elseif
#else
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(outerElseifDefaultValue);

            string outerElseDefaultValue = @"Start
<!--#if (OUTER_IF_CLAUSE)
    content: outer-if
    <!--#if (INNER_IF_CLAUSE)
        content: inner-if
    #elseif (INNER_ELSEIF_CLAUSE)
        content: inner-elseif
    #else
        content: inner-else
    #endif
#elseif (OUTER_ELSEIF_CLAUSE)
    content: outer-elseif
<!--#else-->
    content: outer-else
#endif-->
Trailing stuff
<!- trailing comment -->";

            testCases.Add(outerElseDefaultValue);

            // the actual tests for OUTER_IF_CLAUSE = true (inner else also happens because the other inners are false)
            string outerIfTrueExpectedValue = @"Start
    content: outer-if
        content: inner-else
Trailing stuff
<!- trailing comment -->";

            VariableCollection vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = true,
                ["INNER_IF_CLAUSE"]     = false,
                ["INNER_ELSEIF_CLAUSE"] = false,
                ["OUTER_ELSEIF_CLAUSE"] = false,
            };
            IProcessor processor = SetupXmlStyleProcessor(vc);

            foreach (string test in testCases)
            {
                RunAndVerify(test, outerIfTrueExpectedValue, processor, 9999);
            }

            // the actual tests for INNER_IF_CLAUSE = true (the OUTER_IF_CLAUSE must be true for this to matter)
            string innerIfTrueExpectedValue = @"Start
    content: outer-if
        content: inner-if
Trailing stuff
<!- trailing comment -->";

            vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = true,
                ["INNER_IF_CLAUSE"]     = true,
                ["INNER_ELSEIF_CLAUSE"] = false,
                ["OUTER_ELSEIF_CLAUSE"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, innerIfTrueExpectedValue, processor, 9999);
            }

            // the actual tests for INNER_ELSEIF_CLAUSE = true (the OUTER_IF_CLAUSE must be true for this to matter)
            string innerElseifTrueExpectedValue = @"Start
    content: outer-if
        content: inner-elseif
Trailing stuff
<!- trailing comment -->";

            vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = true,
                ["INNER_IF_CLAUSE"]     = false,
                ["INNER_ELSEIF_CLAUSE"] = true,
                ["OUTER_ELSEIF_CLAUSE"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, innerElseifTrueExpectedValue, processor, 9999);
            }

            // the actual tests for OUTER_ELSEIF_CLAUSE = true (the OUTER_IF_CLAUSE must be false for this to matter)
            string outerElseifTrueExpectedValue = @"Start
    content: outer-elseif
Trailing stuff
<!- trailing comment -->";

            vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = false,
                ["INNER_IF_CLAUSE"]     = false, // irrelevant
                ["INNER_ELSEIF_CLAUSE"] = false, // irrelevant
                ["OUTER_ELSEIF_CLAUSE"] = true,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, outerElseifTrueExpectedValue, processor, 9999);
            }

            // the actual tests for when the outer else happens
            string outerElseTrueExpectedValue = @"Start
    content: outer-else
Trailing stuff
<!- trailing comment -->";

            vc = new VariableCollection
            {
                ["OUTER_IF_CLAUSE"]     = false,
                ["INNER_IF_CLAUSE"]     = false, // irrelevant
                ["INNER_ELSEIF_CLAUSE"] = false, // irrelevant
                ["OUTER_ELSEIF_CLAUSE"] = false,
            };
            processor = SetupXmlStyleProcessor(vc);
            foreach (string test in testCases)
            {
                RunAndVerify(test, outerElseTrueExpectedValue, processor, 9999);
            }
        }
Ejemplo n.º 41
0
        public override AstNode VisitMainClass(MainClass ast)
        {
            m_currentType = ast.Type as CodeClassType;

            Debug.Assert(m_currentType.Methods.Count == 0);
            Debug.Assert(m_currentType.StaticMethods.Count == 1);
            m_currentMethod = m_currentType.StaticMethods[0];
            m_currentVariableIndex = 0;
            m_currentMethodParameters = new VariableCollection<Parameter>() { new Parameter() { Name = ast.ArgName.Value, Type = ArrayType.StrArray } };
            m_currentMethodVariables = new VariableCollection<VariableInfo>();

            foreach (var statement in ast.Statements)
            {
                Visit(statement);
            }

            return ast;
        }
Ejemplo n.º 42
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string s = input.Text;

            exp = new StringToValue(s);
            variableCollection = exp.GetVariables();
            try
            {
                result.Content = exp.getValue();
            }
            catch (UserException ue)
            {
                result.Content = ue.Message;
            }
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();
            listBox4.Items.Clear();
            namesList.Clear();
            rangesList.Clear();
            slidersList.Clear();
            valuesList.Clear();
            if (variableCollection.vlist != null)
            {
                for (int i = 0; i < variableCollection.vlist.Length; i++)
                {
                    Label name = new Label();
                    name.Content           = variableCollection.vlist[i].name;
                    name.Height            = 30;
                    name.MouseDoubleClick += new MouseButtonEventHandler(animation);

                    TextBox textBox = new TextBox();
                    textBox.Text              = "5";
                    textBox.Height            = 30;
                    textBox.Width             = listBox1.Width;
                    textBox.VerticalAlignment = VerticalAlignment.Center;
                    textBox.KeyDown          += new KeyEventHandler(undaterange);

                    Slider slider1 = new Slider();
                    slider1.Height = 30;
                    slider1.Value  = 6;
                    slider1.HorizontalAlignment = HorizontalAlignment.Center;
                    slider1.Width      = 200;
                    slider1.MouseMove += new MouseEventHandler(undateslide);

                    Label var_value = new Label();
                    var_value.Content = "1";
                    var_value.Height  = 30;

                    namesList.Add(name);
                    rangesList.Add(textBox);
                    slidersList.Add(slider1);
                    valuesList.Add(var_value);

                    listBox1.Items.Add(name);
                    listBox2.Items.Add(textBox);
                    listBox3.Items.Add(slider1);
                    listBox4.Items.Add(var_value);
                }
            }
        }
Ejemplo n.º 43
0
 /// <summary>
 /// We do this so we don't have to keep re-declaring the same
 /// constructor
 /// </summary>
 /// <param name="core">Core token</param>
 public void ModuleVector(Core core, VariableCollection vc)
 {
     ModuleVector(core, core.Session.LoggedInMember, vc);
 }
        /// <summary>
        /// Reads a statement beginning with an unknown word.
        /// </summary>
        /// <param name="parentReference">The parent code part.</param>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <param name="variables">Returns the list of variables defined in the statement.</param>
        /// <returns>Returns the statement.</returns>
        private Statement ParseOtherStatement(Reference<ICodePart> parentReference, bool unsafeCode, VariableCollection variables)
        {
            Param.AssertNotNull(parentReference, "parentReference");
            Param.Ignore(unsafeCode);
            Param.Ignore(variables);

            // Get the first symbol, which will be the unknown word.
            // Holds the statement to return.
            Statement statement = null;

            // Determine whether this has the signature of a type.
            bool variableDeclaration = false;
            int endIndex;
            if (this.HasTypeSignature(1, unsafeCode, out endIndex))
            {
                // Get the next symbol and check if it is another unknown word.
                int nextIndex = this.GetNextCodeSymbolIndex(endIndex + 1);
                if (nextIndex != -1)
                {
                    if (this.symbols.Peek(nextIndex).SymbolType == SymbolType.Other)
                    {
                        // If the next symbol is a semicolon, comma or equals then this is a variable
                        // declaration statement.
                        nextIndex = this.GetNextCodeSymbolIndex(nextIndex + 1);
                        if (nextIndex != -1)
                        {
                            Symbol temp = this.symbols.Peek(nextIndex);
                            if (temp.SymbolType == SymbolType.Equals ||
                                temp.SymbolType == SymbolType.Semicolon ||
                                temp.SymbolType == SymbolType.Comma)
                            {
                                // This is a variable declaration statement.
                                variableDeclaration = true;
                            }
                        }
                    }
                }
            }

            if (variableDeclaration)
            {
                statement = this.ParseVariableDeclarationStatement(parentReference, unsafeCode, variables);
            }
            else
            {
                // Get the next symbol after the name.
                int index = this.GetNextCodeSymbolIndex(2);
                if (index == -1 || this.symbols.Peek(index).SymbolType != SymbolType.Colon)
                {
                    statement = this.ParseExpressionStatement(unsafeCode);
                }
                else
                {
                    statement = this.ParseLabelStatement(parentReference, unsafeCode);
                }
            }

            return statement;
        }
Ejemplo n.º 45
0
        private Statement GetNextStatement(bool unsafeCode, VariableCollection variables)
        {
            Statement statement = null;
            if (!this.MoveToStatement())
            {
                return statement;
            }
            Symbol nextSymbol = this.GetNextSymbol();
            if (nextSymbol == null)
            {
                return statement;
            }
            switch (nextSymbol.SymbolType)
            {
                case SymbolType.OpenParenthesis:
                case SymbolType.Increment:
                case SymbolType.Decrement:
                case SymbolType.Base:
                case SymbolType.New:
                case SymbolType.This:
                    return this.ParseExpressionStatement(unsafeCode);

                case SymbolType.OpenCurlyBracket:
                    return this.ParseBlockStatement(unsafeCode);

                case SymbolType.Multiplication:
                    if (unsafeCode)
                    {
                        return this.ParseExpressionStatement(unsafeCode);
                    }
                    break;

                case SymbolType.LogicalAnd:
                    if (!unsafeCode)
                    {
                        break;
                    }
                    return this.ParseExpressionStatement(unsafeCode);

                case SymbolType.Break:
                    return this.ParseBreakStatement();

                case SymbolType.Checked:
                    return this.ParseCheckedStatement(unsafeCode);

                case SymbolType.Const:
                    return this.ParseVariableDeclarationStatement(unsafeCode, variables);

                case SymbolType.Continue:
                    return this.ParseContinueStatement();

                case SymbolType.Do:
                    return this.ParseDoWhileStatement(unsafeCode);

                case SymbolType.Semicolon:
                {
                    Microsoft.StyleCop.Node<CsToken> firstItemNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon));
                    return new EmptyStatement(new CsTokenList(this.tokens, firstItemNode, firstItemNode));
                }
                case SymbolType.Fixed:
                    return this.ParseFixedStatement(unsafeCode);

                case SymbolType.For:
                    return this.ParseForStatement(unsafeCode);

                case SymbolType.Foreach:
                    return this.ParseForeachStatement(unsafeCode);

                case SymbolType.Goto:
                    return this.ParseGotoStatement(unsafeCode);

                case SymbolType.If:
                    return this.ParseIfStatement(unsafeCode);

                case SymbolType.Lock:
                    return this.ParseLockStatement(unsafeCode);

                case SymbolType.Return:
                    return this.ParseReturnStatement(unsafeCode);

                case SymbolType.Sizeof:
                case SymbolType.Typeof:
                    return this.ParseExpressionStatement(unsafeCode);

                case SymbolType.Switch:
                    return this.ParseSwitchStatement(unsafeCode);

                case SymbolType.Throw:
                    return this.ParseThrowStatement(unsafeCode);

                case SymbolType.Try:
                    return this.ParseTryStatement(unsafeCode);

                case SymbolType.Unchecked:
                    return this.ParseUncheckedStatement(unsafeCode);

                case SymbolType.Unsafe:
                    return this.ParseUnsafeStatement();

                case SymbolType.Using:
                    return this.ParseUsingStatement(unsafeCode);

                case SymbolType.While:
                    return this.ParseWhileStatement(unsafeCode);

                case SymbolType.Other:
                    if (nextSymbol.Text == "yield")
                    {
                        statement = this.ParseYieldStatement(unsafeCode);
                        if (statement != null)
                        {
                            return statement;
                        }
                    }
                    return this.ParseOtherStatement(unsafeCode, variables);
            }
            throw new SyntaxException(this.document.SourceCode, nextSymbol.LineNumber);
        }
        private Statement GetNextStatement(Reference<ICodePart> parentReference, bool unsafeCode, VariableCollection variables)
        {
            Param.AssertNotNull(parentReference, "parentReference");
            Param.Ignore(unsafeCode);
            Param.Ignore(variables);

            // Saves the next statement.
            Statement statement = null;

            // Move past comments and whitepace.
            if (this.MoveToStatement(parentReference))
            {
                // Get the next symbol.
                Symbol symbol = this.GetNextSymbol(parentReference);
                if (symbol != null)
                {
                    switch (symbol.SymbolType)
                    {
                        case SymbolType.Other:
                        case SymbolType.Number:
                        case SymbolType.String:
                            if (symbol.Text == "yield")
                            {
                                statement = this.ParseYieldStatement(parentReference, unsafeCode);
                                if (statement != null)
                                {
                                    break;
                                }
                            }

                            statement = this.ParseOtherStatement(parentReference, unsafeCode, variables);
                            break;

                        case SymbolType.OpenCurlyBracket:
                            statement = this.ParseBlockStatement(unsafeCode);
                            break;

                        case SymbolType.If:
                            statement = this.ParseIfStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.While:
                            statement = this.ParseWhileStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Do:
                            statement = this.ParseDoWhileStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.For:
                            statement = this.ParseForStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Foreach:
                            statement = this.ParseForeachStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Switch:
                            statement = this.ParseSwitchStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Try:
                            statement = this.ParseTryStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Lock:
                            statement = this.ParseLockStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Using:
                            statement = this.ParseUsingStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Checked:
                            statement = this.ParseCheckedStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Unchecked:
                            statement = this.ParseUncheckedStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Fixed:
                            statement = this.ParseFixedStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Unsafe:
                            statement = this.ParseUnsafeStatement(parentReference);
                            break;

                        case SymbolType.Break:
                            statement = this.ParseBreakStatement(parentReference);
                            break;

                        case SymbolType.Continue:
                            statement = this.ParseContinueStatement(parentReference);
                            break;

                        case SymbolType.Goto:
                            statement = this.ParseGotoStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Return:
                            statement = this.ParseReturnStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Throw:
                            statement = this.ParseThrowStatement(parentReference, unsafeCode);
                            break;

                        case SymbolType.Typeof:
                        case SymbolType.Sizeof:
                        case SymbolType.Default:
                            statement = this.ParseExpressionStatement(unsafeCode);
                            break;

                        case SymbolType.Const:
                            statement = this.ParseVariableDeclarationStatement(parentReference, unsafeCode, variables);
                            break;

                        case SymbolType.Increment:
                        case SymbolType.Decrement:
                        case SymbolType.New:
                        case SymbolType.This:
                        case SymbolType.Base:
                        case SymbolType.OpenParenthesis:
                            statement = this.ParseExpressionStatement(unsafeCode);
                            break;

                        case SymbolType.Semicolon:
                            var emptyStatementReference = new Reference<ICodePart>();
                            Node<CsToken> tokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon, emptyStatementReference));

                            statement = new EmptyStatement(new CsTokenList(this.tokens, tokenNode, tokenNode));
                            emptyStatementReference.Target = statement;
                            break;

                        case SymbolType.Multiplication:
                            if (!unsafeCode)
                            {
                                goto default;
                            }

                            statement = this.ParseExpressionStatement(unsafeCode);
                            break;

                        case SymbolType.LogicalAnd:
                            if (!unsafeCode)
                            {
                                goto default;
                            }

                            statement = this.ParseExpressionStatement(unsafeCode);
                            break;

                        default:
                            throw new SyntaxException(this.document.SourceCode, symbol.LineNumber);
                    }
                }
            }

            return statement;
        }
Ejemplo n.º 47
0
 private VariableDeclarationStatement ParseVariableDeclarationStatement(bool unsafeCode, VariableCollection variables)
 {
     bool constant = false;
     Symbol nextSymbol = this.GetNextSymbol();
     CsToken token = null;
     Microsoft.StyleCop.Node<CsToken> firstItemNode = null;
     if (nextSymbol.SymbolType == SymbolType.Const)
     {
         constant = true;
         token = new CsToken(nextSymbol.Text, CsTokenType.Const, nextSymbol.Location, this.symbols.Generated);
         firstItemNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Const, SymbolType.Const));
         nextSymbol = this.GetNextSymbol();
     }
     if (nextSymbol.SymbolType != SymbolType.Other)
     {
         throw this.CreateSyntaxException();
     }
     LiteralExpression typeTokenExpression = this.GetTypeTokenExpression(unsafeCode, true);
     if ((typeTokenExpression == null) || (typeTokenExpression.Tokens.First == null))
     {
         throw new SyntaxException(this.document.SourceCode, token.LineNumber);
     }
     if (firstItemNode == null)
     {
         firstItemNode = typeTokenExpression.Tokens.First;
     }
     VariableDeclarationExpression expression = this.GetVariableDeclarationExpression(typeTokenExpression, ExpressionPrecedence.None, unsafeCode);
     this.tokens.Add(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon));
     if (variables != null)
     {
         VariableModifiers modifiers = constant ? VariableModifiers.Const : VariableModifiers.None;
         foreach (VariableDeclaratorExpression expression3 in expression.Declarators)
         {
             Variable variable = new Variable(expression.Type, expression3.Identifier.Token.Text, modifiers, expression3.Tokens.First.Value.Location.StartPoint, expression.Tokens.First.Value.Generated || expression3.Identifier.Token.Generated);
             if (!variables.Contains(expression3.Identifier.Token.Text))
             {
                 variables.Add(variable);
             }
         }
     }
     return new VariableDeclarationStatement(new CsTokenList(this.tokens, firstItemNode, this.tokens.Last), constant, expression);
 }
Ejemplo n.º 48
0
        public static void Show(Core core, TPage page, Primitive owner, int year, int month, int day)
        {
            core.Template.SetTemplate("Calendar", "viewcalendarday");

            // 15 year window
            if (year < DateTime.Now.Year - 10 || year > DateTime.Now.Year + 5)
            {
                core.Functions.Generate404();
            }

            if (month < 1 || month > 12)
            {
                core.Functions.Generate404();
            }

            if (day < 1 || day > DateTime.DaysInMonth(year, month))
            {
                core.Functions.Generate404();
            }

            /* pages */
            core.Display.ParsePageList(owner, true);

            core.Template.Parse("PAGE_TITLE", day.ToString() + " " + core.Functions.IntToMonth(month) + " " + year.ToString());

            core.Template.Parse("CURRENT_DAY", day.ToString());
            core.Template.Parse("CURRENT_MONTH", core.Functions.IntToMonth(month));
            core.Template.Parse("CURRENT_YEAR", year.ToString());

            long startTime = core.Tz.GetUnixTimeStamp(new DateTime(year, month, day, 0, 0, 0));
            long endTime = startTime + 60 * 60 * 24;

            Calendar cal = null;
            try
            {
                cal = new Calendar(core, owner);
            }
            catch (InvalidCalendarException)
            {
                cal = Calendar.Create(core, owner);
            }

            if (cal.Access.Can("CREATE_EVENTS"))
            {
                core.Template.Parse("U_NEW_EVENT", core.Hyperlink.BuildAccountSubModuleUri(owner, "calendar", "new-event", true,
                    string.Format("year={0}", year),
                    string.Format("month={0}", month),
                    string.Format("day={0}", day)));
            }

            List<Event> events = cal.GetEvents(core, owner, startTime, endTime);

            bool hasAllDaysEvents = false;

            foreach (Event calendarEvent in events)
            {
                if (calendarEvent.AllDay)
                {
                    hasAllDaysEvents = true;
                    VariableCollection eventVariableCollection = core.Template.CreateChild("event");

                    eventVariableCollection.Parse("TITLE", calendarEvent.Subject);
                    eventVariableCollection.Parse("URI", calendarEvent.Uri);
                }
            }

            if (hasAllDaysEvents)
            {
                core.Template.Parse("ALL_DAY_EVENTS", "TRUE");
            }

            VariableCollection[] hours = new VariableCollection[24];

            for (int hour = 0; hour < 24; hour++)
            {
                VariableCollection timeslotVariableCollection = core.Template.CreateChild("timeslot");

                DateTime hourTime = new DateTime(year, month, day, hour, 0, 0);

                timeslotVariableCollection.Parse("TIME", hourTime.ToString("h tt").ToLower());
                hours[hour] = timeslotVariableCollection;
            }

            showHourEvents(core, owner, year, month, day, hours, events);

            List<string[]> calendarPath = new List<string[]>();
            calendarPath.Add(new string[] { "calendar", core.Prose.GetString("CALENDAR") });
            calendarPath.Add(new string[] { year.ToString(), year.ToString() });
            calendarPath.Add(new string[] { month.ToString(), core.Functions.IntToMonth(month) });
            calendarPath.Add(new string[] { day.ToString(), day.ToString() });
            owner.ParseBreadCrumbs(calendarPath);
        }
        /// <summary>
        /// Checks variables to look for underscores.
        /// </summary>
        /// <param name="element">
        /// The parent element.
        /// </param>
        /// <param name="variables">
        /// The variables to check.
        /// </param>
        private void CheckUnderscores(CsElement element, VariableCollection variables)
        {
            Param.AssertNotNull(element, "element");
            Param.AssertNotNull(variables, "variables");

            foreach (Variable variable in variables)
            {
                if (variable.Name.StartsWith("_", StringComparison.Ordinal) && variable.Name != "__arglist")
                {
                    this.AddViolation(element, variable.Location.LineNumber, Rules.FieldNamesMustNotBeginWithUnderscore);
                }
            }
        }
Ejemplo n.º 50
0
 public DecisionTree()
 {
     globalVars        = new VariableCollection();
     agentProfile      = new VariableCollection();
     currentActionName = "None";
 }
        /// <summary>
        /// Reads the next variable declaration statement from the file and returns it.
        /// </summary>
        /// <param name="parentReference">The parent code unit.</param>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <param name="variables">Returns the list of variables defined in the statement.</param>
        /// <returns>Returns the statement.</returns>
        private VariableDeclarationStatement ParseVariableDeclarationStatement(
            Reference<ICodePart> parentReference, bool unsafeCode, VariableCollection variables)
        {
            Param.AssertNotNull(parentReference, "parentReference");
            Param.Ignore(unsafeCode);
            Param.Ignore(variables);

            bool constant = false;

            // Get the first symbol and make sure it is an unknown word or a const.
            Symbol symbol = this.GetNextSymbol(parentReference);

            CsToken firstToken = null;
            Node<CsToken> firstTokenNode = null;

            var statementReference = new Reference<ICodePart>();

            if (symbol.SymbolType == SymbolType.Const)
            {
                constant = true;

                firstToken = new CsToken(symbol.Text, CsTokenType.Const, symbol.Location, statementReference, this.symbols.Generated);
                firstTokenNode = this.tokens.InsertLast(this.GetToken(CsTokenType.Const, SymbolType.Const, statementReference));

                symbol = this.GetNextSymbol(statementReference);
            }

            if (symbol.SymbolType != SymbolType.Other)
            {
                throw this.CreateSyntaxException();
            }

            // Get the expression representing the type.
            LiteralExpression type = this.GetTypeTokenExpression(statementReference, unsafeCode, true);
            if (type == null || type.Tokens.First == null)
            {
                throw new SyntaxException(this.document.SourceCode, firstToken.LineNumber);
            }

            if (firstTokenNode == null)
            {
                firstTokenNode = type.Tokens.First;
            }

            // Get the rest of the declaration.
            VariableDeclarationExpression expression = this.GetVariableDeclarationExpression(type, ExpressionPrecedence.None, unsafeCode);

            // Get the closing semicolon.
            this.tokens.Add(this.GetToken(CsTokenType.Semicolon, SymbolType.Semicolon, statementReference));

            // Add each of the variables defined in this statement to the variable list being returned.
            if (variables != null)
            {
                VariableModifiers modifiers = constant ? VariableModifiers.Const : VariableModifiers.None;
                foreach (VariableDeclaratorExpression declarator in expression.Declarators)
                {
                    Variable variable = new Variable(
                        expression.Type,
                        declarator.Identifier.Token.Text,
                        modifiers,
                        CodeLocation.Join(expression.Type.Location, declarator.Identifier.Token.Location),
                        statementReference,
                        expression.Tokens.First.Value.Generated || declarator.Identifier.Token.Generated);

                    // There might already be a variable in this scope with the same name. This can happen
                    // in valid situation when there are ifdef's surrounding portions of the code.
                    // Just accept the first variable and ignore others.
                    if (!variables.Contains(declarator.Identifier.Token.Text))
                    {
                        variables.Add(variable);
                    }
                }
            }

            // Create the token list for the statement.
            CsTokenList partialTokens = new CsTokenList(this.tokens, firstTokenNode, this.tokens.Last);

            var statement = new VariableDeclarationStatement(partialTokens, constant, expression);
            statementReference.Target = statement;

            return statement;
        }
        private Model Model(EczaneNobetTekGrupDataModel data)
        {
            var model = new Model()
            {
                Name = "Eczane Nöbet Tekli Model"
            };

            #region Veriler
            var gunDegerler             = data.TarihAraligi.Select(s => s.NobetGunKuralId).Distinct().ToList();
            var diniBayramGunDegerleri  = data.TarihAraligi.Where(w => w.NobetGunKuralId == 8).Select(s => s.NobetGunKuralId).Distinct().ToList();
            var milliBayramGunDegerleri = data.TarihAraligi.Where(w => w.NobetGunKuralId == 9).Select(s => s.NobetGunKuralId).Distinct().ToList();
            var bayramGunDegerleri      = data.TarihAraligi.Where(w => w.NobetGunKuralId > 7).Select(s => s.NobetGunKuralId).Distinct().ToList();
            #endregion

            #region Karar Değişkenleri
            _x = new VariableCollection <EczaneNobetTarihAralik>(
                model,
                data.EczaneNobetTarihAralik,
                "_x", null,
                h => data.LowerBound,
                h => data.UpperBound,
                a => VariableType.Binary);
            #endregion

            #region Amaç Fonksiyonu
            var amac = new Objective(Expression.Sum((data.EczaneNobetTarihAralik
                                                     .Select(i => _x[i]))),
                                     "Sum of all item-values: ",
                                     ObjectiveSense.Minimize);
            model.AddObjective(amac);
            #endregion

            #region Kısıtlar

            #region Talep Kısıtları
            foreach (var nobetGrupGorevTip in data.NobetGrupGorevTipler)
            {
                foreach (var d in data.TarihAraligi)
                {
                    //nöbet gruplarının günlük nöbetçi sayısı
                    int talep = data.GerekliNobetSayisi;

                    var talepFarkli = data.NobetGrupTalepler
                                      .Where(s => s.NobetGrupGorevTipId == nobetGrupGorevTip.Id &&
                                             s.TakvimId == d.TakvimId)
                                      .Select(s => s.NobetciSayisi).SingleOrDefault();

                    if (talepFarkli > 0)
                    {
                        talep = talepFarkli;
                    }

                    model.AddConstraint(
                        Expression.Sum(data.EczaneNobetTarihAralik
                                       .Where(k => k.TakvimId == d.TakvimId)
                                       .Select(m => _x[m])) == talep,
                        $"her güne bir eczane atanmalı, {1}");
                }
            }
            #endregion

            #region Arz Kısıtları

            #region Peşpeşe Görev Yazılmasın
            foreach (var f in data.EczaneKumulatifHedefler)
            {
                foreach (var g in data.TarihAraligi.Take(data.TarihAraligi.Count() - data.PespeseNobet))
                {
                    //model.AddConstraint(
                    //  Expression.Sum(data.EczaneNobetTarihAralik
                    //                   .Where(e => e.EczaneNobetGrupId == f.EczaneNobetGrupId
                    //                               && e.NobetGorevTipId == f.NobetGorevTipId
                    //                               && (e.Gun >= g.Gun && e.Gun <= g.Gun + data.PespeseNobet)
                    //                         )
                    //                   .Select(m => _x[m])) <= 1,
                    //                   $"eczanelere peşpeşe nöbet yazılmasın, {f}");
                }
            }
            #endregion

            #region Her eczaneye yazılması gereken nöbetler Nöbet arzlarını(kapasitelerini-hedeflerini) ayarla

            foreach (var hedef in data.EczaneKumulatifHedefler)
            {
                #region Toplam

                model.AddConstraint(
                    Expression.Sum(data.EczaneNobetTarihAralik
                                   .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                          e.NobetGorevTipId == hedef.NobetGorevTipId)
                                   .Select(m => _x[m])) <= hedef.Toplam,
                    $"her eczaneye bir ayda nöbet grubunun hedefi kadar nöbet yazılmalı, {hedef}");

                model.AddConstraint(
                    Expression.Sum(data.EczaneNobetTarihAralik
                                   .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                          e.NobetGorevTipId == hedef.NobetGorevTipId)
                                   .Select(m => _x[m])) >= hedef.Toplam - 1,
                    $"her eczaneye bir ayda nöbet grubunun hedefi kadar nöbet yazılmalı, {hedef}");

                #endregion

                #region Bayram Toplamları

                if (bayramGunDegerleri.Count() > 0)
                {
                    var temp = hedef.ToplamBayram - 1;
                    if (temp < 0)
                    {
                        temp = 0;
                    }
                    model.AddConstraint(
                        Expression.Sum(data.EczaneNobetTarihAralik
                                       .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                              e.NobetGunKuralId > 7)
                                       .Select(m => _x[m])) <= hedef.ToplamBayram,
                        $"her eczaneye bir ayda nöbet grubunun hedefi kadar toplam bayram nöbeti yazılmalı, {hedef}");

                    model.AddConstraint(
                        Expression.Sum(data.EczaneNobetTarihAralik
                                       .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                              e.NobetGunKuralId > 7)
                                       .Select(m => _x[m])) >= temp,
                        $"her eczaneye bir ayda nöbet grubunun hedefi kadar toplam bayram nöbeti yazılmalı, {hedef}");
                }
                #endregion

                #region Diğer günler
                //gunDegerler: nöbet yazılacak tarih aralığındaki hafta ve bayram günleri
                foreach (var gunDeger in data.NobetGrupGunKurallar.Where(s => s.NobetGrupId == data.NobetGrup.Id).Select(s => s.NobetGunKuralId))
                {
                    //GetEczaneGunHedef2(out maxArz, out minArz, gunDeger, f.EczaneId);

                    GetEczaneGunHedef(hedef, out double maxArz, out double minArz, gunDeger);

                    model.AddConstraint(
                        Expression.Sum(data.EczaneNobetTarihAralik
                                       .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                              e.NobetGunKuralId == gunDeger)
                                       .Select(m => _x[m])) <= maxArz,
                        $"her eczaneye bir ayda nöbet grubunun {gunDeger} hedefi kadar nöbet yazılmalı, {hedef}");

                    model.AddConstraint(
                        Expression.Sum(data.EczaneNobetTarihAralik
                                       .Where(e => e.EczaneNobetGrupId == hedef.EczaneNobetGrupId &&
                                              e.NobetGunKuralId == gunDeger)
                                       .Select(m => _x[m])) >= minArz,
                        $"her eczaneye bir ayda nöbet grubunun {gunDeger} hedefi kadar nöbet yazılmalı, {hedef}");
                }
                #endregion
            }
            #endregion

            #region İstek Karşılansın
            //foreach (var f in data.EczaneNobetIstekler)
            //{
            //    model.AddConstraint(
            //              Expression.Sum(data.EczaneNobetTarihAralik
            //                               .Where(e => e.EczaneId == f.EczaneId
            //                                        && e.NobetGrupId == f.NobetGrupId
            //                                        && e.TakvimId == f.TakvimId
            //                                        && e.NobetGrupId == data.NobetGrup.Id
            //                                     )
            //                               .Select(m => _x[m])) == 1,
            //                               $"istege nobet yaz, {f}");
            //}
            #endregion

            #region Mazerete Görev Yazılmasın
            foreach (var f in data.EczaneNobetMazeretListe)
            {
                model.AddConstraint(
                    Expression.Sum(data.EczaneNobetTarihAralik
                                   .Where(e => e.EczaneId == f.EczaneId &&
                                          e.NobetGrupId == f.NobetGrupId &&
                                          e.TakvimId == f.TakvimId &&
                                          e.NobetGrupId == data.NobetGrup.Id
                                          )
                                   .Select(m => _x[m])) == 0,
                    $"mazerete nobet yazma, {f}");
            }
            #endregion

            #region Bayram günlerinde en fazla 1 görev yazılsın.
            //eğer bayram günleri ardışık günlerden fazlaysa
            if (data.TarihAraligi.Where(w => w.NobetGunKuralId > 7).Count() > data.PespeseNobet)
            {
                foreach (var f in data.EczaneKumulatifHedefler)
                {
                    foreach (var g in data.TarihAraligi.Where(w => w.NobetGunKuralId > 7))
                    {
                        //model.AddConstraint(
                        //  Expression.Sum(data.EczaneNobetTarihAralik
                        //                   .Where(e => e.EczaneNobetGrupId == f.EczaneNobetGrupId
                        //                               && e.Gun == g.Gun
                        //                         )
                        //                   .Select(m => _x[m])) <= 1,
                        //                   $"bayram nöbeti sınırlama, {f}");
                    }
                }
            }
            #endregion
            #endregion
            #endregion
            return(model);
        }
        /// <summary>
        /// Determines whether a matching local variable is contained in the given variable list.
        /// </summary>
        /// <param name="variables">
        /// The variable list. 
        /// </param>
        /// <param name="word">
        /// The variable name to check. 
        /// </param>
        /// <param name="item">
        /// The token containing the variable name. 
        /// </param>
        /// <returns>
        /// Returns true if there is a matching local variable. 
        /// </returns>
        private static bool ContainsVariable(VariableCollection variables, string word, CsToken item)
        {
            Param.AssertNotNull(variables, "variables");
            Param.AssertValidString(word, "word");
            Param.AssertNotNull(item, "item");

            word = word.SubstringAfter('@');
            Variable variable = variables[word];
            if (variable != null)
            {
                // Make sure the variable appears before the word.
                if (variable.Location.LineNumber < item.LineNumber)
                {
                    return true;
                }
                else if (variable.Location.LineNumber == item.LineNumber)
                {
                    if (variable.Location.StartPoint.IndexOnLine < item.Location.StartPoint.IndexOnLine)
                    {
                        return true;
                    }
                }
            }

            return false;
        }
        public IRunnableProjectConfig ReprocessWithParameters(IParameterSet parameters, VariableCollection rootVariableCollection, ITemplateSourceFile configFile, IOperationProvider[] operations)
        {
            IProcessor             processor = Processor.Create(new EngineConfig(rootVariableCollection), operations);
            IRunnableProjectConfig m;

            using (Stream configStream = configFile.OpenRead())
                using (Stream targetStream = new MemoryStream())
                {
                    processor.Run(configStream, targetStream);
                    targetStream.Position = 0;

                    using (TextReader tr = new StreamReader(targetStream, true))
                        using (JsonReader r = new JsonTextReader(tr))
                        {
                            JObject model = JObject.Load(r);
                            m = model.ToObject <ConfigModel>();
                        }
                }

            return(m);
        }
Ejemplo n.º 55
0
 public static void DisplayMiniCalendar(Core core, VariableCollection vc1, Primitive owner, int year, int month)
 {
     DisplayMiniCalendar(core, null, vc1, owner, year, month);
 }
Ejemplo n.º 56
0
 public δPlus(
     VariableCollection <IwIndexElement, IdIndexElement> value)
 {
     this.Value = value;
 }
Ejemplo n.º 57
0
        private static void DisplayMiniCalendar(Core core, Template template, VariableCollection vc1, Primitive owner, int year, int month)
        {
            int days = DateTime.DaysInMonth(year, month);
            DayOfWeek firstDay = new DateTime(year, month, 1).DayOfWeek;
            int offset = Calendar.GetFirstDayOfMonthOffset(firstDay);
            int weeks = (int)Math.Ceiling((days + offset) / 7.0);

            if (template != null)
            {
                template.Parse("CURRENT_MONTH", core.Functions.IntToMonth(month));
                template.Parse("CURRENT_YEAR", year.ToString());
            }
            else
            {
                vc1.Parse("MONTH", core.Functions.IntToMonth(month));
                vc1.Parse("U_MONTH", BuildMonthUri(core, owner, year, month));
            }

            for (int week = 0; week < weeks; week++)
            {
                VariableCollection weekVariableCollection;
                if (template != null)
                {
                    weekVariableCollection = template.CreateChild("week");
                }
                else
                {
                    weekVariableCollection = vc1.CreateChild("week");
                }

                weekVariableCollection.Parse("WEEK", (week + 1).ToString());

                if (week + 1 == 1)
                {
                    int daysPrev = DateTime.DaysInMonth(year - (month - 1) / 12, (month - 1) % 12 + 1);
                    for (int i = offset - 1; i >= 0; i--)
                    {
                        int day = daysPrev - i;

                        VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
                        dayVariableCollection.Parse("DATE", day.ToString());
                        dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year - (month - 2) / 12, (month - 2) % 12 + 1, day));
                    }
                    for (int i = offset; i < 7; i++)
                    {
                        int day = i - offset + 1;

                        VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
                        dayVariableCollection.Parse("DATE", day.ToString());
                        dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year, month, day));
                    }
                }
                else if (week + 1 == weeks)
                {
                    for (int i = week * 7 - offset; i < days; i++)
                    {
                        int day = i + 1;

                        VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
                        dayVariableCollection.Parse("DATE", day.ToString());
                        dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year, month, day));
                    }
                    for (int i = 0; i < weeks * 7 - days - offset; i++)
                    {
                        int day = i + 1;

                        VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
                        dayVariableCollection.Parse("DATE", day.ToString());
                        dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year + (month) / 12, (month) % 12 + 1, day));
                    }
                }
                else
                {
                    for (int i = 0; i < 7; i++)
                    {
                        int day = week * 7 + i + 1 - offset;

                        VariableCollection dayVariableCollection = weekVariableCollection.CreateChild("day");
                        dayVariableCollection.Parse("DATE", day.ToString());
                        dayVariableCollection.Parse("URI", Calendar.BuildDateUri(core, owner, year, month, day));
                    }
                }
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Compiles the start block of
        /// </summary>
        /// <param name="context"></param>
        public TypeInfo CompileNewProcessStart(CompileContext context, string name)
        {
            try {
                //Get this before we push a new type on the stack, we are going to need it...
                Dictionary <string, LocalBuilder> currentLocals = null;

                if (context.Type != null)
                {
                    currentLocals = context.Type.Locals;
                }

                if (context.CurrentMasterType != null)   //Are in a type, so let's create a nested one
                {
                    TypeInfo nestedType = new TypeInfo();
                    nestedType.Builder = context.Type.Builder.DefineNestedType(name, TypeAttributes.NestedPublic | TypeAttributes.Class | TypeAttributes.BeforeFieldInit, typeof(ProcessBase));
                    context.PushType(nestedType);
                }
                else
                {
                    context.PushType(context.GetType(name));
                    context.CurrentMasterType = context.Type;
                }
                Type baseType = typeof(ProcessBase);

                if (this.PreProcessActions != null)
                {
                    this.PreProcessActions.Compile(context);
                    context.Type.IsPreProcessed = true;
                }
                if (this.ActionRestrictions != null)
                {
                    this.ActionRestrictions.Compile(context);
                    context.Type.IsRestricted = true;
                }

                MethodBuilder methodStart = context.Type.Builder.DefineMethod("RunProcess", MethodAttributes.Public | MethodAttributes.Virtual);
                context.Type.Builder.DefineMethodOverride(methodStart, baseType.GetMethod("RunProcess"));
                context.PushIL(methodStart.GetILGenerator());
                Call(new ThisPointer(typeof(ProcessBase)), "InitSetID", true).Compile(context);
                if (this.WrapInTryCatch)
                {
                    context.ILGenerator.BeginExceptionBlock();
                }

                if (context.Type.Constructor == null)   //Nested type which hasn't defined its constructor yet

                {
                    VariableCollection col = new VariableCollection();
                    col.Start(this);
                    List <Type>     paramTypes        = new List <Type>();
                    List <Variable> constructorParams = new List <Variable>();
                    foreach (Variable v in col.Variables)
                    {
                        if (currentLocals != null && currentLocals.ContainsKey(v.Name))   //We have defined this local variable and so should pass it to the new process
                        {
                            paramTypes.Add(typeof(object));
                            constructorParams.Add(v);
                            context.Type.ConstructorParameters.Add(v.Name); //Needed to pass the right parameters along later
                            context.Type.Fields.Add(context.Type.Builder.DefineField(v.Name, typeof(object), FieldAttributes.Private));
                        }
                    }
                    context.Type.Constructor = context.Type.Builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, paramTypes.ToArray());
                    ILGenerator ilCon = context.Type.Constructor.GetILGenerator();
                    ilCon.Emit(OpCodes.Ldarg_0);
                    ilCon.Emit(OpCodes.Call, typeof(ProcessBase).GetConstructor(new Type[] { }));

                    for (int i = 0; i < constructorParams.Count; i++)
                    {
                        context.Type.Constructor.DefineParameter(i + 1, ParameterAttributes.None, constructorParams[i].Name);
                        //save the variables argument we got passed in
                        ilCon.Emit(OpCodes.Ldarg_0);
                        ilCon.Emit(OpCodes.Ldarg, i + 1);
                        ilCon.Emit(OpCodes.Stfld, context.Type.GetField(constructorParams[i].Name));
                    }
                    ilCon.Emit(OpCodes.Ret);
                }

                //Do this after the constructor has been defined, because the fields
                //of the object are defined in the constructor...
                foreach (FieldBuilder field in context.Type.Fields)
                {
                    LocalBuilder local = context.ILGenerator.DeclareLocal(typeof(object));
                    if (context.Options.Debug)
                    {
                        local.SetLocalSymInfo(field.Name);
                    }
                    context.Type.Locals.Add(field.Name, local);
                    //Add the field value to the local variable, so we can concentrate on only local vars
                    context.ILGenerator.Emit(OpCodes.Ldarg_0);
                    context.ILGenerator.Emit(OpCodes.Ldfld, field);
                    context.ILGenerator.Emit(OpCodes.Stloc, local);
                }

                return(context.Type);
            } catch (Exception) {
                return(null);
            }
        }
Ejemplo n.º 59
0
        private static void showHourEvents(Core core, Primitive owner, int year, int month, int day, VariableCollection[] timeslotVariableCollections, List<Event> events)
        {
            bool hasEvents = false;

            long startOfDay = core.Tz.GetUnixTimeStamp(new DateTime(year, month, day, 0, 0, 0));
            long endOfDay = startOfDay + 60 * 60 * 24;

            long[] heights = new long[events.Count];
            long[] tops = new long[events.Count];
            double[] widths = new double[events.Count];
            double[] lefts = new double[events.Count];
            int[] eventCount = new int[96];
            int[] eventNumber = new int[96];

            int hourHeight = 32;

            List<Event> expired = new List<Event>();
            int i = 0;
            foreach (Event calendarEvent in events)
            {
                if (calendarEvent.AllDay)
                {
                    continue;
                }

                long startTime = calendarEvent.StartTimeRaw;
                long endTime = calendarEvent.EndTimeRaw;

                if (endTime > endOfDay)
                {
                    endTime = endOfDay;
                }

                if (startTime < startOfDay)
                {
                    startTime = startOfDay;
                }

                DateTime startDateTime = core.Tz.DateTimeFromMysql(startTime);
                DateTime endDateTime = core.Tz.DateTimeFromMysql(endTime - 1);
                long startMinute = startDateTime.Minute;
                long startHour = startDateTime.Hour;
                long endMinute = endDateTime.Minute;
                long endHour = endDateTime.Hour;
                int startFifteen = (int)Math.Floor(startHour * 4.0 + startMinute / 15.0);
                int endFifteen = (int)Math.Floor(endHour * 4.0 + endMinute / 15.0);

                for (int j = startFifteen; j <= endFifteen; j++)
                {
                    eventCount[j]++;
                }

                heights[i] = (endTime - startTime) * hourHeight / 60 / 60;
                tops[i] = startMinute * 36 / 60;
                widths[i] = 100.0;
                lefts[i] = 100 - 100.0 / Math.Max(1, eventCount[startFifteen]);

                i++;
            }

            i = 0;
            foreach (Event calendarEvent in events)
            {
                if (calendarEvent.AllDay)
                {
                    continue;
                }

                long startTime = calendarEvent.StartTimeRaw;
                long endTime = calendarEvent.EndTimeRaw;

                if (endTime > endOfDay)
                {
                    endTime = endOfDay;
                }

                if (startTime < startOfDay)
                {
                    startTime = startOfDay;
                }

                DateTime startDateTime = core.Tz.DateTimeFromMysql(startTime);
                DateTime endDateTime = core.Tz.DateTimeFromMysql(endTime - 1);
                long startMinute = startDateTime.Minute;
                long startHour = startDateTime.Hour;
                long endMinute = endDateTime.Minute;
                long endHour = endDateTime.Hour;
                int startFifteen = (int)Math.Floor(startHour * 4.0 + startMinute / 15.0);
                int endFifteen = (int)Math.Floor(endHour * 4.0 + endMinute / 15.0);

                int maxEventsOnFifteen = 0;
                for (int j = startFifteen; j <= endFifteen; j++)
                {
                    eventNumber[j]++;
                    if (eventCount[j] > maxEventsOnFifteen)
                    {
                        maxEventsOnFifteen = eventCount[j];
                    }
                }

                lefts[i] = 100 - 100.0 * eventNumber[startFifteen] / Math.Max(1, maxEventsOnFifteen);

                widths[i] /= Math.Max(1, maxEventsOnFifteen);

                VariableCollection eventVariableCollection = timeslotVariableCollections[startHour].CreateChild("event");

                eventVariableCollection.Parse("TITLE", calendarEvent.Subject);
                eventVariableCollection.Parse("URI", calendarEvent.Uri);

                eventVariableCollection.Parse("LEFT", lefts[i].ToString());
                eventVariableCollection.Parse("WIDTH", widths[i].ToString());
                eventVariableCollection.Parse("TOP", tops[i].ToString());
                eventVariableCollection.Parse("HEIGHT", heights[i].ToString());

                timeslotVariableCollections[startHour].Parse("EVENTS", "TRUE");

                expired.Add(calendarEvent);
                i++;
            }

            foreach (Event calendarEvent in expired)
            {
                events.Remove(calendarEvent);
            }
        }
 internal IProcessor SetupCStyleWithCommentsProcessor(VariableCollection vc)
 {
     IOperationProvider[] operations = CStyleWithCommentsConditionalOperations;
     return(SetupTestProcessor(operations, vc));
 }