protected override IScope[] Select(List<IScope> scopes) {
      IRandom random = RandomParameter.ActualValue;
      int children = ChildrenParameter.ActualValue.Value;
      int parents = ParentsPerChildParameter.ActualValue.Value;
      int parentsAvailable = scopes.Count;

      if (parents > parentsAvailable)
        throw new InvalidOperationException("WithoutRepeatingBatchedRandomSelector: Cannot select more parents per child than there are parents available");

      IScope[] result = new IScope[children * parents];
      int count = 0;
      HashSet<int> selectedParents = new HashSet<int>();
      for (int i = 0; i < children; i++) {
        selectedParents.Clear();
        for (int j = 0; j < parents; j++) {
          int nextParent = j; // will be used in case parents == parentsAvailable
          if (parents < parentsAvailable) {
            do {
              nextParent = random.Next(parentsAvailable);
            } while (selectedParents.Contains(nextParent));
          }

          result[count++] = (IScope)scopes[nextParent].Clone();
          selectedParents.Add(nextParent);
        }
      }

      return result;
    }
Exemplo n.º 2
0
        protected internal Init(NRefactory.VariableInitializer variableInitializer, IScope scope, INRefcatoryExpressionVisitor visitor)
            : base(scope, visitor) {
            NRefactory.Expression initializer = null;

            _variableInitializer = variableInitializer;
            initializer = variableInitializer.Initializer;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Add built-in array functions to the scope
 /// </summary>
 internal static void Register(IScope scope)
 {
     scope.SetValue("l3.mapToMap", new MapToMap());
     scope.SetValue("l3.mapToArray", new MapToArray());
     scope.SetValue("l3.getMapKeys", new GetMapKeys());
     scope.SetValue("l3.getMapValues", new GetMapValues());
 }
Exemplo n.º 4
0
 /// <summary>
 /// Lookups the input type of the provider.
 /// </summary>
 /// <param name="scope">The scope.</param>
 /// <param name="name">The provider name.</param>
 /// <returns><code>Live</code> if live, <code>Vod</code> if VOD stream, <code>NotFound</code> otherwise.</returns>
 /// <remarks>Live is checked first and VOD second.</remarks>
 public InputType LookupProviderInputType(IScope scope, string name)
 {
     InputType result = InputType.NotFound;
     if (scope.GetBasicScope(Constants.BroadcastScopeType, name) != null)
     {
         //We have live input
         result = InputType.Live;
     }
     else
     {
         try
         {
             FileInfo file = GetStreamFile(scope, name);
             if (file != null)
             {
                 //We have vod input
                 result = InputType.Vod;
             }
         }
         catch (Exception ex)
         {
             log.Warn(string.Format("Exception attempting to lookup file: {0}", name), ex);
         }
     }
     return result;
 }
Exemplo n.º 5
0
 public IMessageInput GetProviderInput(IScope scope, string name)
 {
     IMessageInput msgIn = GetLiveProviderInput(scope, name, false);
     if (msgIn == null)
         return GetVODProviderInput(scope, name);
     return msgIn;
 }
        protected internal AbstractExpression(IScope scope, IExpressionConfigurationVisitor visitor) {
            if (scope != null) {
                Scope = scope;
            }

            Visitor = visitor;
        }
Exemplo n.º 7
0
 public SummonAction(IScope scope, ICost cost, UnitData unit, IScreenEffect screenEffect)
 {
     _scope = scope;
     _cost = cost;
     _unit = unit;
     _screenEffect = screenEffect;
 }
Exemplo n.º 8
0
        protected override void InternalExecute(IScope scope) {
            var commands = Regex.Split(CommandText, @"(?i)(^|[\r\n])\s*go\s*([\r\n]|$)")
                .Where(_=>!string.IsNullOrWhiteSpace(_) && _.Trim().ToLowerInvariant()!="go").ToArray();
            using (var c = GetConnection(null, scope))
            {
                c.WellOpen();
                L.Trace(">>>> start script " +TaskCode + " : " + TaskName);
                for (var i = 0; i < commands.Length; i++) {
                    var command = c.CreateCommand();
                    command.CommandText = commands[i];
                    try {
                        command.ExecuteNonQuery();
                    }
                    catch (Exception e) {
                        if (ErrorLevel <= LogLevel.Trace) {
                            L.Trace("<<<<< error " + TaskCode + " : " + i + " : " + e.Message);
                            continue;

                        }
                        throw;
                    }
                    L.Info(">>>> executed " + TaskCode + " : " + i);
                    L.Debug(commands[i]);
                }
                L.Trace("<<<<< end script " + TaskCode + " : " + TaskName);
            }
        }
Exemplo n.º 9
0
        internal SystemContext(ServiceContainer container)
        {
            scope = container.OpenScope(ContextNames.System);
            scope.RegisterInstance<ISystemContext>(this);

            EventRegistry = new EventRegistry(this);
        }
Exemplo n.º 10
0
        protected internal Index(NRefactory.IndexerExpression indexerExpression, IScope scope, INRefcatoryExpressionVisitor visitor)
            : base(scope, visitor) {
            bool isAssignment = false;
            PropertyReference propertyReference = null;

            _indexerExpression = indexerExpression;
            isAssignment = IsAssignment();
            Target = indexerExpression.Target.AcceptVisitor(Visitor, ParentScope);
            TryGetArguments();

            if (indexerExpression.HasAnnotationOf<PropertyReference>(out propertyReference)) {
                var propertyInfo = Target.Type.GetProperty(propertyReference.Name);

                InternalType = propertyInfo.PropertyType;
                _indexer = propertyInfo;
            }
            else {
                _isArrayIndex = true;
                var targetType = Target.Type;

                if (targetType.HasElementType) {
                    targetType = Target.Type.GetElementType();
                }

                InternalType = targetType;
                _methodCall = _isAssignment ? Expression.ArrayAccess : (Func<Expression, IEnumerable<Expression>, Expression>)Expression.ArrayAccess;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="statement">The statement.</param>
        /// <param name="sqlStatement"></param>
        /// <param name="scope"></param>
        public ProcedureSql(IScope scope, string sqlStatement, IStatement statement)
        {
            _sqlStatement = sqlStatement;
            _statement = statement;

            _dataExchangeFactory = scope.DataExchangeFactory;
        }
 protected internal Identifier(NRefactory.IdentifierExpression identifierExpression, IScope scope, INRefcatoryExpressionVisitor visitor)
     : base(scope, visitor) {
     _identifierExpression = identifierExpression;
     Expression = scope.Find(_identifierExpression.Identifier);
     InternalType = Expression.Type;
     Name = _identifierExpression.Identifier;
 }
Exemplo n.º 13
0
 protected internal Switch(NRefactory.SwitchStatement switchStatement, IScope scope, INRefcatoryExpressionVisitor visitor)
     : base(scope, visitor) {
     _switchStatement = switchStatement;
     SwitchValue = switchStatement.Expression.AcceptVisitor(Visitor, scope);
     BuildSwitchCases();
     InternalType = TypeSystem.Void;
 }
Exemplo n.º 14
0
 protected VScope(IScope Parent)
 {
     this.OnDateType = new Dictionary<string, List<Type>>();
     this.ScopeVariables = new List<Expression>();
     this.ScopeFunctions = new List<FunctionMeta>();
     this.Parent = Parent;
 }
Exemplo n.º 15
0
 public ParameterScope( IScope parent, string[] parameters )
 {
     _parent = parent;
     _contents = new StandardScope();
     foreach( string p in parameters )
     _contents.set( p, null );
 }
Exemplo n.º 16
0
 internal static Value Do(List<DelimiterList> parsedLines, IScope scope)
 {
     // run each line, returning value of last line
     Value retval = null;
     int count = parsedLines.Count;
     int indent = -1;
     for (int i = 0; i < count; i++)
     {
         DelimiterList line = parsedLines[i];
         if (indent == -1)
             indent = line.Indent;
         if (indent == line.Indent)
         {	// only run lines that are at the original indentation
             ILineRequestor requestor = Utility.GetSubLineRequestor(parsedLines, i, out i);
             try
             {
                 retval = EvalList.Do(line.Nodes, scope, requestor);
             }
             catch (Loki3Exception e)
             {	// this line is the correct context if there isn't already one there
                 if (!e.Errors.ContainsKey(Loki3Exception.keyLineContents))
                     e.AddLine(line.Original);
                 if (requestor != null && !e.Errors.ContainsKey(Loki3Exception.keyLineNumber))
                     e.AddLineNumber(requestor.GetCurrentLineNumber());
                 throw e;
             }
         }
     }
     return (retval == null ? new ValueNil() : retval);
 }
Exemplo n.º 17
0
		/// <summary>
		/// Initializes a new instance of the FileConsumer class.
		/// </summary>
		/// <param name="scope">Scope of consumer.</param>
		/// <param name="file">File.</param>
		public FileConsumer(IScope scope, FileInfo file) {
			_scope = scope;
			_file = file;
			_offset = 0;
			_lastTimestamp = 0;
			_startTimestamp = -1;
		}
Exemplo n.º 18
0
        protected internal New(NRefactory.ObjectCreateExpression objectCreation, IScope scope, INRefcatoryExpressionVisitor visitor)
            : base(scope, visitor) {
            
            _objectCreation = objectCreation;

            if (!objectCreation.Type.IsNull) {
                InternalType = objectCreation.Type.AcceptVisitor(Visitor, ParentScope).Type;

                if (objectCreation.Initializer != null) {
                    if (objectCreation.Arguments.Count == 2) {
                        Expression expression;
                        NRefactory.Expression @this = objectCreation.Arguments.First();
                        NRefactory.Expression func = objectCreation.Arguments.Last();

                        if (TryHandleAnonymousMethod(@this, func as NRefactory.InvocationExpression, out expression)) {
                            Expression = expression;
                            return;
                        }
                    }

                    if (objectCreation.Initializer != NRefactory.ArrayInitializerExpression.Null) {
                        Expression = objectCreation.Initializer.AcceptVisitor(Visitor, ParentScope);
                        return;
                    }
                }

                Expression = BuildConstructor();
            }
            else {
                Expression = HandleAnonymousType();
            }
        }
Exemplo n.º 19
0
 internal static Value Do(List<Value> valueLines, IScope parent)
 {
     // run each line, returning value of last line
     Value retval = null;
     int count = valueLines.Count;
     for (int i = 0; i < count; i++)
     {
         Value v = valueLines[i];
         if (v is ValueString)
         {
             ILineRequestor requestor = Utility.GetSubLineRequestor(valueLines, i, out i);
             DelimiterList line = ParseLine.Do(v.AsString, parent);
             retval = EvalList.Do(line.Nodes, parent, requestor);
         }
         else if (v is ValueRaw)
         {
             ValueRaw raw = v as ValueRaw;
             // use value's scope if present, otherwise use passed in scope
             IScope rawScope = (raw.Scope != null ? raw.Scope : parent);
             retval = EvalList.Do(raw.GetValue().Nodes, rawScope);
         }
         else
         {
             throw new Loki3Exception().AddBadLine(v);
         }
     }
     return (retval == null ? new ValueNil() : retval);
 }
Exemplo n.º 20
0
        public RunTimeView(IEnterInterpreterHost pEnterClientInterface, Epi.View pView, int pParentRecordId, string pParentGlobalRecordId, IScope pScope = null)
        {
            // to do set the enter interpreter
            // application domain.
            Assembly a = Assembly.Load(pView.Project.EnterMakeviewIntepreter);
            // Get the type to use.
            Type myType = a.GetType(pView.Project.EnterMakeviewIntepreter + ".EpiInterpreterParser");

            // Create an instance.
            if (pScope == null)
            {
                this.mEpiInterpreter = (IEnterInterpreter)Activator.CreateInstance(myType, new object[] { pEnterClientInterface });
            }
            else
            {
                this.mEpiInterpreter = (IEnterInterpreter)Activator.CreateInstance(myType, new object[] { pEnterClientInterface, pScope });
            }
            this.mEpiInterpreter.Context.Scope.Name = pView.Name;
            this.mEpiInterpreter.Host = pEnterClientInterface;

            this.EnterClientInterface = pEnterClientInterface;
            this.AfterStack = new Stack<KeyValuePair<EventActionEnum, StackCommand>>();
            this.parentViewRecordId = pParentRecordId;
            this.parentViewGlobalRecordId = pParentGlobalRecordId;
            this.RecordNumberMap = new Dictionary<int, int>();
            this.mView = pView;
            this.mView.ForeignKeyField.CurrentRecordValueString = this.ParentGlobalRecordId;
        }
Exemplo n.º 21
0
 private void DoBuildHtml(IReportContext context, IScope scope) {
     var htmlconfig = new HtmlConfig();
     bool standalone = context.Request.Standalone;
     if (standalone) {
         htmlconfig.DocHeader = RenderXml(context, scope, DocHeader, null, "DocHeader");
     }
     htmlconfig.Header = RenderXml(context, scope, Header, null, "Header");
     htmlconfig.Content = RenderXml(context, scope, Content, null, "Content");
     var items = context.Data.arr("items");
     IList<ItemXml> xitems = new List<ItemXml>();
     if (null != items) {
         var i = 0;
         foreach (var item in items) {
             var itemScope = new Scope(scope);
             itemScope["_item"] = item;
             itemScope["_idx"] = i;
             var xitem = new ItemXml();
             xitem.Before = RenderXml(context, itemScope, BeforeItem, item, "BeforeItem");
             xitem.Item = RenderXml(context, itemScope, Item, item, "Item");
             xitem.After = RenderXml(context, itemScope, AfterItem, item, "AfterItem");
             if (null != (xitem.Before ?? xitem.After ?? xitem.Before)) {
                 xitems.Add(xitem);
             }
             i++;
         }
     }
     htmlconfig.Items = xitems;
     htmlconfig.Footer = RenderXml(context, scope, Footer, null, "Footer");
     XElement docfooter = null;
     if (standalone) {
         htmlconfig.DocFooter = RenderXml(context, scope, DocFooter, null, "DocFooter");
     }
     var xmlhtml = CompileHtml(context, scope, htmlconfig);
     context.Write(xmlhtml.ToString());
 }
 public GiveAbnormalConditionAction(IScope scope, ICost cost, IScreenEffect screenEffect, IAbnormalCondition cond)
 {
     _scope = scope;
     _cost = cost;
     _screenEffect = screenEffect;
     _cond = cond;
 }
 public override bool Equals(IScope x, IScope y) {
   if (object.ReferenceEquals(x, y)) return true;
   if (x == null || y == null) return false;
   double q1 = ((DoubleValue)x.Variables[QualityVariableName].Value).Value;
   double q2 = ((DoubleValue)y.Variables[QualityVariableName].Value).Value;
   return q1.IsAlmost(q2) && CalculateSolutionSimilarity(x, y).IsAlmost(1.0);
 }
Exemplo n.º 24
0
 /// <summary>
 /// Eval a list of DelimiterNodes and return a Value
 /// </summary>
 internal static Value Do(List<DelimiterNode> nodes, IScope scope, ILineRequestor requestor)
 {
     ListEval eval = new ListEval(nodes, scope);
     while (eval.EvalNext(requestor))
         ;
     return eval.GetValue();
 }
		public string GenerateFilename(IScope scope, string name, string extension, GenerationType type) {
			string result = GetStreamDirectory(scope) + name;
			if (extension != null && !string.Empty.Equals(extension)) {
				result += extension;
			}
			return result;
		}
 protected internal NamedExpression(NRefactory.NamedExpression namedExpression, IScope scope, INRefcatoryExpressionVisitor visitor)
     : base(scope, visitor) {
     Name = namedExpression.Identifier;
     _namedExpression = namedExpression;
     Expression = _namedExpression.Expression.AcceptVisitor(Visitor, ParentScope);
     InternalType = Expression.Type;
 }
        protected internal Invocation(NRefactory.InvocationExpression invocationExpression, IScope scope, INRefcatoryExpressionVisitor visitor)
            : base(scope, visitor) {
            
            var methodReference = invocationExpression.Annotation<Mono.Cecil.MethodReference>();

            _invocationExpression = invocationExpression;

            if (methodReference != null) {
                MethodInfo methodInfo = null;
                Member = methodInfo = methodReference.GetActualMethod<MethodInfo>();

                if (IsInitializeArray(methodInfo)) {
                    var first = _invocationExpression.Arguments.First().AcceptVisitor(Visitor, ParentScope);
                    var invocation = _invocationExpression.Arguments.Last() as NRefactory.InvocationExpression;
                    var second = invocation.Arguments.First();
                    var memberReference = invocationExpression.Target as NRefactory.MemberReferenceExpression;
                    var target = memberReference.Target as NRefactory.TypeReferenceExpression;
                    var type = target.Type.GetActualType();
                    var parameters = methodReference.Parameters;
                    return;
                }
            }

            BuildInvocation();
        }
Exemplo n.º 28
0
        /// <summary>Read and eval all the lines in a file</summary>
        internal static void Do(string file, IScope scope)
        {
            StreamReader stream = null;
            try
            {
                List<string> lines = new List<string>();
                stream = new StreamReader(file);
                while (!stream.EndOfStream)
                    lines.Add(stream.ReadLine());

                LineConsumer consumer = new LineConsumer(lines);
                EvalLines.Do(consumer, scope);
                stream.Close();
            }
            catch (Loki3Exception e)
            {
                e.AddFileName(file);
                if (stream != null)
                    stream.Close();
                throw e;
            }
            catch (System.Exception e)
            {
                if (stream != null)
                    stream.Close();
                throw e;
            }
        }
Exemplo n.º 29
0
 protected EngineAlgorithm()
   : base() {
   globalScope = new Scope("Global Scope");
   globalScope.Variables.Add(new Variable("Results", new ResultCollection()));
   operatorGraph = new OperatorGraph();
   Initialize();
 }
Exemplo n.º 30
0
        //interface
        public static IInterface evaluate(Node_Interface node, IScope scope)
        {
            IList<IInterface> inheritees = new List<IInterface>();
            IList<Callee> callees = new List<Callee>();
            IList<Breeder> breeders = new List<Breeder>();
            IList<Property> props = new List<Property>();
            IList<Method> meths = new List<Method>();

            foreach( INode_Expression inherNode in node.inheritees )
            inheritees.Add(
                Bridge.toNativeInterface(
                    Executor.executeAny(inherNode, scope)));

            foreach( Node_StatusedMember sm in node.members ) {
            //xxx member status (sm.memberStatus) is ignored
            INode_InterfaceMember member = sm.member;
            if( member is Node_Callee )
                callees.Add(evaluate(member as Node_Callee, scope));
            if( member is Node_Breeder )
                breeders.Add(evaluate(member as Node_Breeder, scope));
            if( member is Node_Property )
                props.Add(evaluate(member as Node_Property, scope));
            if( member is Node_Method )
                meths.Add(evaluate(member as Node_Method, scope));
            }

            return new Interface(
            inheritees, callees, breeders, props, meths );
        }
Exemplo n.º 31
0
 /// <summary>
 /// Connect to another scope on server.
 /// </summary>
 /// <param name="scope">New scope.</param>
 /// <returns>true on success, false otherwise.</returns>
 public bool Connect(IScope scope)
 {
     return(Connect(scope, null));
 }
Exemplo n.º 32
0
 internal DataSource(IScope scope)
 {
     this.scope = scope;
 }
 public IScope GetNewScope(string pName, IScope pParent)
 {
     return(new SymbolTable(pName, pParent));
 }
        private void Initialize()
        {
            IScope scope = this.currentScope;

            while (scope.GetEnclosingScope() != null)
            {
                if (scope.Name == "global")
                {
                    LoadPermanentVariables(scope);
                    break;
                }
                scope = scope.GetEnclosingScope();
            }

            ProgramText  = new StringBuilder();
            DLLClassList = new Dictionary <string, IDLLClass>(StringComparer.OrdinalIgnoreCase);

            _parsedUndefinedVariables = new List <string>();
            _parsedFieldNames         = new List <string>();
            _parsedPageNames          = new List <string>();

            Page_Checkcode  = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            Field_Checkcode = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);

            BeforeCheckCode             = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            AfterCheckCode              = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            PageBeforeCheckCode         = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            PageAfterCheckCode          = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            FieldBeforeCheckCode        = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            FieldAfterCheckCode         = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            FieldClickCheckCode         = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            Subroutine                  = new Dictionary <string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            _IsVariableValidationEnable = false;
            SelectCommandList.Add(CommandNames.ABS);
            SelectCommandList.Add(CommandNames.ASSIGN);
            SelectCommandList.Add(CommandNames.ASCENDING);
            SelectCommandList.Add(CommandNames.AND);
            SelectCommandList.Add(CommandNames.ALWAYS);
            SelectCommandList.Add(CommandNames.APPEND);
            SelectCommandList.Add(CommandNames.MOD);
            SelectCommandList.Add(CommandNames.LIKE);
            SelectCommandList.Add(CommandNames.OR);
            SelectCommandList.Add(CommandNames.XOR);
            SelectCommandList.Add(CommandNames.NOT);
            SelectCommandList.Add(CommandNames.EXP);
            SelectCommandList.Add(CommandNames.LN);
            SelectCommandList.Add(CommandNames.LOG);
            SelectCommandList.Add(CommandNames.NUMTODATE);
            SelectCommandList.Add(CommandNames.NUMTOTIME);
            SelectCommandList.Add(CommandNames.RECORDCOUNT);
            SelectCommandList.Add(CommandNames.RND);
            SelectCommandList.Add(CommandNames.ROUND);
            SelectCommandList.Add(CommandNames.STEP);
            SelectCommandList.Add(CommandNames.SIN);
            SelectCommandList.Add(CommandNames.COS);
            SelectCommandList.Add(CommandNames.TAN);
            SelectCommandList.Add(CommandNames.TRUNC);
            SelectCommandList.Add(CommandNames.PFROMZ);
            SelectCommandList.Add(CommandNames.ZSCORE);
            SelectCommandList.Add(CommandNames.YEARS);
            SelectCommandList.Add(CommandNames.MONTHS);
            SelectCommandList.Add(CommandNames.DAYS);
            SelectCommandList.Add(CommandNames.YEAR);
            SelectCommandList.Add(CommandNames.MONTH);
            SelectCommandList.Add(CommandNames.DAY);
            SelectCommandList.Add(CommandNames.CURRENTUSER);
            SelectCommandList.Add(CommandNames.EXISTS);
            SelectCommandList.Add(CommandNames.FILEDATE);
            SelectCommandList.Add(CommandNames.SYSTEMDATE);
            SelectCommandList.Add(CommandNames.SYSTEMTIME);
            SelectCommandList.Add(CommandNames.HOURS);
            SelectCommandList.Add(CommandNames.MINUTES);
            SelectCommandList.Add(CommandNames.SECONDS);
            SelectCommandList.Add(CommandNames.HOUR);
            SelectCommandList.Add(CommandNames.MINUTE);
            SelectCommandList.Add(CommandNames.SECOND);
            SelectCommandList.Add(CommandNames.FINDTEXT);
            SelectCommandList.Add(CommandNames.FORMAT);
            SelectCommandList.Add(CommandNames.LINEBREAK);
            SelectCommandList.Add(CommandNames.STRLEN);
            SelectCommandList.Add(CommandNames.SUBSTRING);
            SelectCommandList.Add(CommandNames.TXTTONUM);
            SelectCommandList.Add(CommandNames.TXTTODATE);
            SelectCommandList.Add(CommandNames.UPPERCASE);
            SelectCommandList.Add(CommandNames.ISUNIQUE);
            SelectCommandList.Add(CommandNames.EPIWEEK);
            SelectCommandList.Add("(");
            SelectCommandList.Add(",");
        }
 public Rule_Context(IScope pScope)
 {
     this.currentScope = new SymbolTable(pScope);
     this.Initialize();
 }
 public Rule_Context()
 {
     this.currentScope = new SymbolTable("global", null);
     Rule_Context.LoadPermanentVariables(this.currentScope);
     this.Initialize();
 }
Exemplo n.º 37
0
 public DataModule(IScope scope, string connectionString)
 {
     Scope            = scope;
     ConnectionString = connectionString;
 }
 public DelegateOnDisposeScopeDecorator(Action @delegate, IScope scope)
 {
     _delegate = @delegate;
     _scope    = scope;
 }
Exemplo n.º 39
0
        public override IOperation Apply()
        {
            double maxSelPress    = MaximumSelectionPressureParameter.ActualValue.Value;
            double successRatio   = SuccessRatioParameter.ActualValue.Value;
            IScope scope          = ExecutionContext.Scope;
            IScope parents        = scope.SubScopes[0];
            IScope offspring      = scope.SubScopes[1];
            int    populationSize = parents.SubScopes.Count;

            // retrieve actual selection pressure and success ratio
            DoubleValue selectionPressure = SelectionPressureParameter.ActualValue;

            if (selectionPressure == null)
            {
                selectionPressure = new DoubleValue(0);
                SelectionPressureParameter.ActualValue = selectionPressure;
            }
            DoubleValue currentSuccessRatio = CurrentSuccessRatioParameter.ActualValue;

            if (currentSuccessRatio == null)
            {
                currentSuccessRatio = new DoubleValue(0);
                CurrentSuccessRatioParameter.ActualValue = currentSuccessRatio;
            }

            // retrieve next population
            ItemList <IScope> population         = OffspringPopulationParameter.ActualValue;
            ItemList <IScope> virtual_population = OffspringVirtualPopulationParameter.ActualValue;

            IntValue successfulOffspring;

            if (population == null)
            {
                population = new ItemList <IScope>();
                OffspringPopulationParameter.ActualValue = population;
                selectionPressure.Value   = 0; // initialize selection pressure for this round
                currentSuccessRatio.Value = 0; // initialize current success ratio for this round
                successfulOffspring       = new IntValue(0);
                OffspringPopulationWinnersParameter.ActualValue = successfulOffspring;

                virtual_population = new ItemList <IScope>();
                OffspringVirtualPopulationParameter.ActualValue = virtual_population;
            }
            else
            {
                successfulOffspring = OffspringPopulationWinnersParameter.ActualValue;
            }

            int successfulOffspringAdded = 0;

            // implement the ActualValue fetch here - otherwise the parent scope would also be included, given that there may be 1000 or more parents, this is quite unnecessary
            string tname          = SuccessfulOffspringParameter.TranslatedName;
            double tmpSelPress    = selectionPressure.Value;
            double tmpSelPressInc = 1.0 / populationSize;

            for (int i = 0; i < offspring.SubScopes.Count; i++)
            {
                // fetch value
                IVariable tmpVar;
                if (!offspring.SubScopes[i].Variables.TryGetValue(tname, out tmpVar))
                {
                    throw new InvalidOperationException(Name + ": Could not determine if an offspring was successful or not.");
                }
                BoolValue tmp = (tmpVar.Value as BoolValue);
                if (tmp == null)
                {
                    throw new InvalidOperationException(Name + ": The variable that indicates whether an offspring is successful or not must contain a BoolValue.");
                }

                // add to population
                if (tmp.Value)
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.RemoveAt(i);
                    i--; // next loop should continue with the subscope at index i which replaced currentOffspring
                    population.Add(currentOffspring);
                    successfulOffspringAdded++;
                }
                else
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.RemoveAt(i);
                    i--;
                    virtual_population.Add(currentOffspring); // add to losers pool
                }
                tmpSelPress += tmpSelPressInc;

                double tmpSuccessRatio = (successfulOffspring.Value + successfulOffspringAdded) / ((double)populationSize);
                if (tmpSuccessRatio >= successRatio && (population.Count + virtual_population.Count) >= populationSize)
                {
                    break;
                }
            }
            successfulOffspring.Value += successfulOffspringAdded;

            // calculate actual selection pressure and success ratio
            selectionPressure.Value   = tmpSelPress;
            currentSuccessRatio.Value = successfulOffspring.Value / ((double)populationSize);

            // check if enough children have been generated (or limit of selection pressure or evaluted solutions is reached)
            if (((EvaluatedSolutionsParameter.ActualValue.Value < MaximumEvaluatedSolutionsParameter.ActualValue.Value) &&
                 (selectionPressure.Value < maxSelPress) &&
                 (currentSuccessRatio.Value < successRatio)) ||
                ((population.Count + virtual_population.Count) < populationSize))
            {
                // more children required -> reduce left and start children generation again
                scope.SubScopes.Remove(parents);
                scope.SubScopes.Remove(offspring);
                while (parents.SubScopes.Count > 0)
                {
                    IScope parent = parents.SubScopes[0];
                    parents.SubScopes.RemoveAt(0); // TODO: repeated call of RemoveAt(0) is inefficient?
                    scope.SubScopes.Add(parent);   // order of subscopes is reversed
                }

                IOperator offspringCreator = OffspringCreatorParameter.ActualValue as IOperator;
                if (offspringCreator == null)
                {
                    throw new InvalidOperationException(Name + ": More offspring are required, but no operator specified for creating them.");
                }
                return(ExecutionContext.CreateOperation(offspringCreator)); // this assumes that this operator will be called again indirectly or directly
            }
            else
            {
                // enough children generated
                var fitnessComparer = new FitnessComparer(QualityParameter.TranslatedName, MaximizationParameter.ActualValue.Value);
                population.Sort(fitnessComparer); // sort individuals by descending fitness

                // keeps only the best successRatio * populationSize solutions in the population (the remaining ones are added to the virtual population)
                int removed = 0;
                for (int i = 0; i < population.Count; i++)
                {
                    double tmpSuccessRatio = i / (double)populationSize;
                    if (tmpSuccessRatio > successRatio)
                    {
                        virtual_population.Add(population[i]);
                        removed++;
                    }
                }
                population.RemoveRange(population.Count - removed, removed);

                //fill up population with best remaining children (successful or unsuccessful)
                virtual_population.Sort(fitnessComparer);
                int offspringNeeded = populationSize - population.Count;
                for (int i = 0; i < offspringNeeded && i < virtual_population.Count; i++)
                {
                    population.Add(virtual_population[i]); // children are sorted by descending fitness
                }

                offspring.SubScopes.Clear();
                offspring.SubScopes.AddRange(population);

                scope.Variables.Remove(OffspringPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringVirtualPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringPopulationWinnersParameter.TranslatedName);
                return(base.Apply());
            }
        }
Exemplo n.º 40
0
 /// <summary>
 /// Initializes a new instance of the ScopeNotFoundException class.
 /// </summary>
 /// <param name="scope"></param>
 /// <param name="childName"></param>
 public ScopeNotFoundException(IScope scope, string childName)
     : base(__Res.GetString(__Res.Scope_ChildNotFound, childName, scope.Name))
 {
 }
Exemplo n.º 41
0
 public NamespaceSymbol(string name, IScope enclosingScope) : base(name)
 {
     base.SetEnclosingScope(enclosingScope);
 }
Exemplo n.º 42
0
 public Singleton(IScope scope)
 {
     Name = scope.Name;
 }
Exemplo n.º 43
0
 public EngineHiveTask(EngineTask engineTask, IScope parentScopeClone)
     : base(engineTask)
 {
     this.parentScopeClone = parentScopeClone;
 }
Exemplo n.º 44
0
 internal ParagraphImpl(Microsoft.ReportingServices.ReportIntermediateFormat.Paragraph paragraphDef, Microsoft.ReportingServices.RdlExpressions.ReportRuntime reportRT, IErrorContext iErrorContext, IScope scope)
 {
     m_textRuns = new TextRunsImpl(paragraphDef, reportRT, iErrorContext, scope);
 }
Exemplo n.º 45
0
 public void HandleOperationBefore(IExecutionContext context, IScope scope)
 {
 }
Exemplo n.º 46
0
 protected EngineHiveTask(EngineHiveTask original, Cloner cloner)
     : base(original, cloner)
 {
     this.parentScopeClone = cloner.Clone(original.parentScopeClone);
 }
Exemplo n.º 47
0
 /// <summary>
 /// Executes as part of the upgrade scope and before all migrations have executed.
 /// </summary>
 public virtual void BeforeMigrations(IScope scope, ILogger logger)
 {
 }
Exemplo n.º 48
0
 public void HandleOperationAfter(IExecutionContext context, IScope scope)
 {
 }
Exemplo n.º 49
0
 /// <summary>
 /// Выполняет транзакцию
 /// </summary>
 /// <param name="actions"></param>
 /// <param name="context"></param>
 public static void ExecuteTransaction(this IEnumerable <TransactionAction> actions, IScope context = null)
 {
     if (actions == null)
     {
         throw new ArgumentNullException("actions");
     }
     actions = actions.ToArray();
     context = context ?? new Scope();
     try
     {
         foreach (var a in actions)
         {
             a.Execute(context);
         }
         //если все выполнилось успешно - можно коммитить
         foreach (var a in actions)
         {
             a.Commit(context);
         }
     }
     catch
     {
         foreach (var a in actions)
         {
             a.Rollback(context);
         }
     }
 }
Exemplo n.º 50
0
 /// <summary>
 /// Executes as part of the upgrade scope and after all migrations have executed.
 /// </summary>
 public virtual void AfterMigrations(IScope scope, ILogger logger)
 {
 }
Exemplo n.º 51
0
 /// <summary>
 /// Выполняет операцию применения (для транзакций)
 /// </summary>
 /// <param name="context"></param>
 public abstract void Commit(IScope context);
        public ParagraphsImpl(AspNetCore.ReportingServices.ReportIntermediateFormat.TextBox textBoxDef, AspNetCore.ReportingServices.RdlExpressions.ReportRuntime reportRT, IErrorContext iErrorContext, IScope scope)
        {
            this.m_textBoxDef    = textBoxDef;
            this.m_reportRT      = reportRT;
            this.m_iErrorContext = iErrorContext;
            this.m_scope         = scope;
            List <AspNetCore.ReportingServices.ReportIntermediateFormat.Paragraph> paragraphs = this.m_textBoxDef.Paragraphs;

            if (paragraphs != null)
            {
                this.m_paragraphs = new ParagraphImpl[paragraphs.Count];
            }
            else
            {
                this.m_paragraphs = new ParagraphImpl[0];
            }
        }
        /// <summary>
        /// Parse Inline ParameterMap
        /// </summary>
        /// <param name="statement"></param>
        /// <param name="sqlStatement"></param>
        /// <returns>A new sql command text.</returns>
        /// <param name="scope"></param>
        public SqlText ParseInlineParameterMap(IScope scope, IStatement statement, string sqlStatement)
        {
            string    newSql             = sqlStatement;
            ArrayList mappingList        = new ArrayList();
            Type      parameterClassType = null;

            if (statement != null)
            {
                parameterClassType = statement.ParameterClass;
            }

            StringTokenizer parser       = new StringTokenizer(sqlStatement, PARAMETER_TOKEN, true);
            StringBuilder   newSqlBuffer = new StringBuilder();

            string token     = null;
            string lastToken = null;

            IEnumerator enumerator = parser.GetEnumerator();

            while (enumerator.MoveNext())
            {
                token = (string)enumerator.Current;

                if (PARAMETER_TOKEN.Equals(lastToken))
                {
                    if (PARAMETER_TOKEN.Equals(token))
                    {
                        newSqlBuffer.Append(PARAMETER_TOKEN);
                        token = null;
                    }
                    else
                    {
                        ParameterProperty mapping = null;
                        if (token.IndexOf(PARAM_DELIM) > -1)
                        {
                            mapping = OldParseMapping(token, parameterClassType, scope);
                        }
                        else
                        {
                            mapping = NewParseMapping(token, parameterClassType, scope);
                        }

                        mappingList.Add(mapping);
                        newSqlBuffer.Append("? ");

                        enumerator.MoveNext();
                        token = (string)enumerator.Current;
                        if (!PARAMETER_TOKEN.Equals(token))
                        {
                            throw new DataMapperException("Unterminated inline parameter in mapped statement (" + statement.Id + ").");
                        }
                        token = null;
                    }
                }
                else
                {
                    if (!PARAMETER_TOKEN.Equals(token))
                    {
                        newSqlBuffer.Append(token);
                    }
                }

                lastToken = token;
            }

            newSql = newSqlBuffer.ToString();

            ParameterProperty[] mappingArray = (ParameterProperty[])mappingList.ToArray(typeof(ParameterProperty));

            SqlText sqlText = new SqlText();

            sqlText.Text       = newSql;
            sqlText.Parameters = mappingArray;

            return(sqlText);
        }
Exemplo n.º 54
0
 /// <summary>
 /// Осуществляет откат
 /// </summary>
 /// <param name="context"></param>
 public abstract void Rollback(IScope context);
        /// <summary>
        /// Parse inline parameter with syntax as
        /// #propertyName,type=string,dbype=Varchar,direction=Input,nullValue=N/A,handler=string#
        /// </summary>
        /// <param name="token"></param>
        /// <param name="parameterClassType"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private ParameterProperty NewParseMapping(string token, Type parameterClassType, IScope scope)
        {
            ParameterProperty mapping = new ParameterProperty();

            StringTokenizer paramParser     = new StringTokenizer(token, "=,", false);
            IEnumerator     enumeratorParam = paramParser.GetEnumerator();

            enumeratorParam.MoveNext();

            mapping.PropertyName = ((string)enumeratorParam.Current).Trim();

            while (enumeratorParam.MoveNext())
            {
                string field = (string)enumeratorParam.Current;
                if (enumeratorParam.MoveNext())
                {
                    string value = (string)enumeratorParam.Current;
                    if ("type".Equals(field))
                    {
                        mapping.CLRType = value;
                    }
                    else if ("dbType".Equals(field))
                    {
                        mapping.DbType = value;
                    }
                    else if ("direction".Equals(field))
                    {
                        mapping.DirectionAttribute = value;
                    }
                    else if ("nullValue".Equals(field))
                    {
                        mapping.NullValue = value;
                    }
                    else if ("handler".Equals(field))
                    {
                        mapping.CallBackName = value;
                    }
                    else
                    {
                        throw new DataMapperException("Unrecognized parameter mapping field: '" + field + "' in " + token);
                    }
                }
                else
                {
                    throw new DataMapperException("Incorrect inline parameter map format (missmatched name=value pairs): " + token);
                }
            }

            if (mapping.CallBackName.Length > 0)
            {
                mapping.Initialize(scope, parameterClassType);
            }
            else
            {
                ITypeHandler handler = null;
                if (parameterClassType == null)
                {
                    handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                }
                else
                {
                    handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory,
                                                 parameterClassType, mapping.PropertyName,
                                                 mapping.CLRType, mapping.DbType);
                }
                mapping.TypeHandler = handler;
                mapping.Initialize(scope, parameterClassType);
            }

            return(mapping);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Производит выполнение операции обновления (может генерировать ошибки)
 /// </summary>
 public abstract void Execute(IScope context);
Exemplo n.º 57
0
 public CustomScopeManager(IScope scope)
 {
     _scope = scope;
 }
        /// <summary>
        /// Parse inline parameter with syntax as
        /// #propertyName:dbType:nullValue#
        /// </summary>
        /// <param name="token"></param>
        /// <param name="parameterClassType"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private ParameterProperty OldParseMapping(string token, Type parameterClassType, IScope scope)
        {
            ParameterProperty mapping = new ParameterProperty();

            if (token.IndexOf(PARAM_DELIM) > -1)
            {
                StringTokenizer paramParser     = new StringTokenizer(token, PARAM_DELIM, true);
                IEnumerator     enumeratorParam = paramParser.GetEnumerator();

                int n1 = paramParser.TokenNumber;
                if (n1 == 3)
                {
                    enumeratorParam.MoveNext();
                    string propertyName = ((string)enumeratorParam.Current).Trim();
                    mapping.PropertyName = propertyName;

                    enumeratorParam.MoveNext();
                    enumeratorParam.MoveNext(); //ignore ":"
                    string dBType = ((string)enumeratorParam.Current).Trim();
                    mapping.DbType = dBType;

                    ITypeHandler handler = null;
                    if (parameterClassType == null)
                    {
                        handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                    }
                    else
                    {
                        handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, propertyName, null, dBType);
                    }
                    mapping.TypeHandler = handler;
                    mapping.Initialize(scope, parameterClassType);
                }
                else if (n1 >= 5)
                {
                    enumeratorParam.MoveNext();
                    string propertyName = ((string)enumeratorParam.Current).Trim();
                    enumeratorParam.MoveNext();
                    enumeratorParam.MoveNext(); //ignore ":"
                    string dBType = ((string)enumeratorParam.Current).Trim();
                    enumeratorParam.MoveNext();
                    enumeratorParam.MoveNext(); //ignore ":"
                    string nullValue = ((string)enumeratorParam.Current).Trim();
                    while (enumeratorParam.MoveNext())
                    {
                        nullValue = nullValue + ((string)enumeratorParam.Current).Trim();
                    }

                    mapping.PropertyName = propertyName;
                    mapping.DbType       = dBType;
                    mapping.NullValue    = nullValue;
                    ITypeHandler handler = null;
                    if (parameterClassType == null)
                    {
                        handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                    }
                    else
                    {
                        handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, propertyName, null, dBType);
                    }
                    mapping.TypeHandler = handler;
                    mapping.Initialize(scope, parameterClassType);
                }
                else
                {
                    throw new ConfigurationException("Incorrect inline parameter map format: " + token);
                }
            }
            else
            {
                mapping.PropertyName = token;
                ITypeHandler handler = null;
                if (parameterClassType == null)
                {
                    handler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                }
                else
                {
                    handler = ResolveTypeHandler(scope.DataExchangeFactory.TypeHandlerFactory, parameterClassType, token, null, null);
                }
                mapping.TypeHandler = handler;
                mapping.Initialize(scope, parameterClassType);
            }
            return(mapping);
        }
Exemplo n.º 59
0
 public DirectoryScope(string name, IScope enclosingScope) : base(enclosingScope)
 {
     Name = name;
 }
Exemplo n.º 60
0
 public override void HandleAfter(IExecutionContext executionContext, IScope scope)
 {
     factory
     .GetInstace(executionContext.RequestContext.RequestName)
     .HandleOperationAfter(executionContext, scope);
 }