Exemple #1
0
        public ResultFunction <bool> Delete(string id, string file)
        {
            var res = new ResultFunction <bool>();

            int number;
            var test = int.TryParse(id, out number);

            if (test == false)
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorNoNumber, "\n"));
                return(res);
            }

            var linesList = File.ReadAllLines("./Files/Pets.csv").Where(a => !string.IsNullOrEmpty(a)).ToList();

            if (linesList.Count < number || number <= 0)
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorNoId, number, "\n"));
                return(res);
            }

            linesList.RemoveAt(number - 1);

            File.WriteAllLines($"./Files/{file}.csv", linesList.ToArray());

            res.Data = true;
            return(res);
        }
Exemple #2
0
        public ResultFunction <bool> Create(string pet, string file)
        {
            var res = new ResultFunction <bool>();

            var data = pet.Split(',');

            if (data.Length != 3)
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorWrongNumberOfParameters, "\n"));
                return(res);
            }

            if (data.Any(string.IsNullOrEmpty))
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorRequiredFild, "\n"));
                return(res);
            }

            if (data[2].ToLower() != "m" && data[2].ToLower() != "f" &&
                data[2].ToLower() != "male" && data[2].ToLower() != "female")
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorWrongGender, "\n"));
                return(res);
            }

            var date = DateTime.Now.ToString("yyyyMMdd-HHmmss");

            pet = $"\n{pet},{date}";
            File.AppendAllText($"./Files/{file}.csv", pet);

            res.Data = true;
            return(res);
        }
	public void setUp() {
		oneBoard = new NQueensBoard(1);
		eightBoard = new NQueensBoard(8);

		af = NQueensFunctionFactory.getIActionsFunction();
		rf = NQueensFunctionFactory.getResultFunction();
	}
Exemple #4
0
 public Problem(Object initialState, ActionsFunction actionsFunction,
         ResultFunction resultFunction, GoalTest goalTest)
     : this(initialState, actionsFunction, resultFunction, goalTest,
         new DefaultStepCostFunction())
 {
     
 }
Exemple #5
0
 public static ResultFunction getResultFunction()
 {
     if (null == resultFunction)
     {
         resultFunction = new MapResultFunction();
     }
     return(resultFunction);
 }
 public static ResultFunction getResultFunction()
 {
     if (null == _resultFunction)
     {
         _resultFunction = new EPResultFunction();
     }
     return(_resultFunction);
 }
 public static ResultFunction getResultFunction()
 {
     if (_resultFunction == null)
     {
         _resultFunction = new SlidingPuzzleResultFunction();
     }
     return(_resultFunction);
 }
 public static ResultFunction getResultFunction()
 {
     if (null == _resultFunction)
     {
     _resultFunction = new EPResultFunction();
     }
     return _resultFunction;
 }
Exemple #9
0
 /**
  * Constructs a problem with the specified components, which includes a step
  * cost function.
  *
  * @param initialState
  *            the initial state of the agent.
  * @param actionsFunction
  *            a description of the possible actions available to the agent.
  * @param resultFunction
  *            a description of what each action does; the formal name for
  *            this is the transition model, specified by a function
  *            RESULT(s, a) that returns the state that results from doing
  *            action a in state s.
  * @param goalTest
  *            test determines whether a given state is a goal state.
  * @param stepCostFunction
  *            a path cost function that assigns a numeric cost to each path.
  *            The problem-solving-agent chooses a cost function that
  *            reflects its own performance measure.
  */
 public Problem(Object initialState, ActionsFunction actionsFunction,
                ResultFunction resultFunction, GoalTest goalTest,
                StepCostFunction stepCostFunction)
 {
     this.initialState     = initialState;
     this.actionsFunction  = actionsFunction;
     this.resultFunction   = resultFunction;
     this.goalTest         = goalTest;
     this.stepCostFunction = stepCostFunction;
 }
Exemple #10
0
 public Problem(object initialSetup, OperatorsFunction operatorsFunction,
                ResultFunction resultFunction, GoalTest goalTest,
                StepCostFunction stepCostFunction)
 {
     this.initialSetup      = initialSetup;
     this.operatorsFunction = operatorsFunction;
     this.resultFunction    = resultFunction;
     this.goalTest          = goalTest;
     this.stepCostFunction  = stepCostFunction;
 }
Exemple #11
0
 public Problem(Object initialState, ActionsFunction actionsFunction,
         ResultFunction resultFunction, GoalTest goalTest,
         StepCostFunction stepCostFunction)
 {
     this.initialState = initialState;
     this.actionsFunction = actionsFunction;
     this.resultFunction = resultFunction;
     this.goalTest = goalTest;
     this.stepCostFunction = stepCostFunction;
 }
Exemple #12
0
 private BinaryOperatorOperation(string functionName, ResultFunction function, int precedence, bool isLeftAssociative, string operatorString)
     : base(functionName, function,
            (operatorString != null)
                           ? String.Format("{0}{2}{1}", "{0}", "{1}", operatorString)
                           : throw new ArgumentNullException(nameof(operatorString)),
            true)
 {
     Precedence        = precedence;
     IsLeftAssociative = isLeftAssociative;
     stringToOperation.Add(operatorString, this);
 }
	public void setUp() {
		ExtendableMap aMap = new ExtendableMap();
		aMap.addBidirectionalLink("A", "B", 5.0);
		aMap.addBidirectionalLink("A", "C", 6.0);
		aMap.addBidirectionalLink("B", "C", 4.0);
		aMap.addBidirectionalLink("C", "D", 7.0);
		aMap.addUnidirectionalLink("B", "E", 14.0);

		af = MapFunctionFactory.getActionsFunction(aMap);
		rf = MapFunctionFactory.getResultFunction();
	}
Exemple #14
0
    public static ResultFunction <T> Failed(params string[] errors)
    {
        var result = new ResultFunction <T> {
            Succeeded = false
        };

        if (errors != null)
        {
            result._errors.AddRange(errors);
        }
        return(result);
    }
Exemple #15
0
 public Problem(
     TState initalState,
     ActionFunction <TState, TAction> actionFunction,
     ResultFunction <TState, TAction> resultFunction,
     GoalTest <TState> goalTest, StepCost <TState, TAction> stepCost)
 {
     InitalState    = initalState;
     ActionFunction = actionFunction;
     ResultFunction = resultFunction;
     GoalTest       = goalTest;
     StepCost       = stepCost;
 }
Exemple #16
0
        public ResultFunction <List <Pet> > GetAll(string file)
        {
            var res   = new ResultFunction <List <Pet> >();
            var count = 1;
            var pets  = File.ReadAllLines($"./Files/{file}.csv").Select(a => a.Split(',')).Where(a => a.Length > 1).Select(pet => new Pet
            {
                Id = count++, Type = pet[0], Name = pet[1], Gender = pet[2] == "M" ? "Male" : "Female", Date = DateTime.ParseExact(pet[3], "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)
            });

            res.Data = pets.ToList();
            return(res);
        }
Exemple #17
0
        // Devuelve la lista de todos los nodos hijos del nodo que se desea expandir
        public List <Node> ExpandNode(Node node, Problem problem)
        {
            List <Node> childNodes = new List <Node>();

            OperatorsFunction operatorsFunction = problem.GetOperatorsFunction();
            ResultFunction    resultFunction    = problem.GetResultFunction();
            StepCostFunction  stepCostFunction  = problem.GetStepCostFunction();

            foreach (Operator op in operatorsFunction.Operators(node.GetSetup()))
            {
                object successorSetup = resultFunction.GetResult(node.GetSetup(), op);
                double stepCost       = stepCostFunction.GetCost(node.GetSetup(), op, successorSetup);
                childNodes.Add(new Node(successorSetup, node, op, stepCost));
            }
            metrics.set(METRIC_NODES_EXPANDED, metrics.getInt(METRIC_NODES_EXPANDED) + 1);

            return(childNodes);
        }
Exemple #18
0
        public Problem GetProblem(Object owner, IContextLookup globalVars, Object initialState)
        {
            Problem toReturn;
            var     objActionsFunction = ActionsFunction.EvaluateTyped(owner, globalVars);
            var     objResultFunction  = ResultFunction.EvaluateTyped(owner, globalVars);
            var     objGoalTest        = GoalTest.EvaluateTyped(owner, globalVars);

            if (StepCostFunction.Enabled)
            {
                var objStepCostFunction = StepCostFunction.Entity.EvaluateTyped(owner, globalVars);
                toReturn = new Problem(initialState, objActionsFunction, objResultFunction, objGoalTest, objStepCostFunction);
            }
            else
            {
                toReturn = new Problem(initialState, objActionsFunction, objResultFunction, objGoalTest);
            }
            return(toReturn);
        }
Exemple #19
0
        public List <Node> expandNode(Node node, Problem problem)
        {
            List <Node> childNodes = new List <Node>();

            ActionsFunction  actionsFunction  = problem.getActionsFunction();
            ResultFunction   resultFunction   = problem.getResultFunction();
            StepCostFunction stepCostFunction = problem.getStepCostFunction();

            foreach (Action action in actionsFunction.actions(node.getState()))
            {
                System.Object successorState = resultFunction.result(node.getState(),
                                                                     action);

                double stepCost = stepCostFunction.c(node.getState(), action,
                                                     successorState);
                childNodes.Add(new Node(successorState, node, action, stepCost));
            }
            metrics.set(METRIC_NODES_EXPANDED, metrics
                        .getInt(METRIC_NODES_EXPANDED) + 1);

            return(childNodes);
        }
Exemple #20
0
        private static void SolveProblem <TState, TAction>(
            ActionFunction <TState, TAction> actionFunction,
            ResultFunction <TState, TAction> resultFunction,
            GoalTest <TState> goalTest,
            StepCost <TState, TAction> stepCost,
            TState initialState,
            IGraphSearch <TState, TAction> searchAlgorithm)
        {
            var problem = new Problem <TState, TAction>(
                initialState, actionFunction, resultFunction, goalTest, stepCost);

            var solution = searchAlgorithm.Search(problem);

            Console.WriteLine("Solution:");
            Console.WriteLine("=========");
            foreach (var node in solution)
            {
                Console.WriteLine(node.State);
            }

            Console.ReadKey();
        }
Exemple #21
0
        /**
         * Returns the children obtained from expanding the specified node in the
         * specified problem.
         *
         * @param node
         *            the node to expand
         * @param problem
         *            the problem the specified node is within.
         *
         * @return the children obtained from expanding the specified node in the
         *         specified problem.
         */
        public List <Node> expand(Node node, Problem problem)
        {
            List <Node> successors = new List <Node>();

            ActionsFunction  actionsFunction  = problem.getActionsFunction();
            ResultFunction   resultFunction   = problem.getResultFunction();
            StepCostFunction stepCostFunction = problem.getStepCostFunction();

            foreach (Action action in actionsFunction.actions(node.State))
            {
                System.Object successorState = resultFunction.result(node.State, action);

                double stepCost = stepCostFunction.c(node.State, action, successorState);
                successors.Add(createNode(successorState, node, action, stepCost));
            }

            foreach (NodeListener listener in nodeListeners)
            {
                listener.onNodeExpanded(node);
            }
            counter++;
            return(successors);
        }
Exemple #22
0
        public void Authenticate(Account account, ResultFunction func)
        {
            if (this.result_func != null) {
            // Throw exception?
            Console.WriteLine("Connection::Authenticate: this.result_func != null");
            return;
            }

            this.result_func = func;
            lm_connection_authenticate(this._obj, account.username, account.password, account.resource, new _ResultFunction(this._HandleResult), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
        }
Exemple #23
0
 /**
  * Constructs a problem with the specified components, and a default step
  * cost function (i.e. 1 per step).
  *
  * @param initialState
  *            the initial state that the agent starts in.
  * @param actionsFunction
  *            a description of the possible actions available to the agent.
  * @param resultFunction
  *            a description of what each action does; the formal name for
  *            this is the transition model, specified by a function
  *            RESULT(s, a) that returns the state that results from doing
  *            action a in state s.
  * @param goalTest
  *            test determines whether a given state is a goal state.
  */
 public Problem(Object initialState, ActionsFunction actionsFunction,
                ResultFunction resultFunction, GoalTest goalTest)
     : this(initialState, actionsFunction, resultFunction, goalTest,
            new DefaultStepCostFunction())
 {
 }
Exemple #24
0
        public void Open(ResultFunction func)
        {
            if (this.result_func != null) {
            // Throw exception?
            Console.WriteLine("Connection::Open: this.result_func != null");
            return;
            }

            this.result_func = func;
            lm_connection_open(this._obj, new _ResultFunction(this._HandleResult), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
        }
 private UnaryOperation(string functionName, ResultFunction function)
     : this(functionName, function, null, false)
 {
 }
Exemple #26
0
        public ResultFunction <List <Pet> > Search(string param, string file)
        {
            var res = new ResultFunction <List <Pet> >();

            int number;
            var test = int.TryParse(param, out number);

            if (test == false)
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorNoNumber, "\n"));
                return(res);
            }

            if (number > 3 || number <= 0)
            {
                res.Errors.Add(string.Format(PetsStrings.ErrorNoOption, number, "\n"));
                return(res);
            }

            if (number == 1 || number == 2)
            {
                Console.WriteLine(PetsStrings.TextEnterField, "Spaces are not allowed", "\n");
            }

            if (number == 3)
            {
                Console.WriteLine(PetsStrings.TextEnterField, "Only one space is allowed", "\n");
            }

            var filter = Console.ReadLine();

            if (number == 1 || number == 2)
            {
                var validation = filter.Trim().Split(' ');
                if (validation.Length > 1)
                {
                    res.Errors.Add(string.Format(PetsStrings.ErrorNoSpaces, "\n"));
                    return(res);
                }
            }


            if (number == 3)
            {
                var validation = filter.Trim().Split(' ');
                if (validation.Length > 2)
                {
                    res.Errors.Add(string.Format(PetsStrings.ErrorOnlyOneSpace, "\n"));
                    return(res);
                }
            }


            var count = 1;
            var pets  = File.ReadAllLines($"./Files/{file}.csv").Select(a => a.Split(',')).Select(pet => new Pet
            {
                Id = count++, Type = pet[0], Name = pet[1], Gender = pet[2] == "M" ? "Male" : "Female", Date = DateTime.ParseExact(pet[3], "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture)
            });

            switch (number)
            {
            case 1:
                pets = pets.Where(a => a.Name.Contains(filter)).OrderBy(a => a.Name);
                break;

            case 2:
                pets = pets.Where(a => a.Type.Contains(filter)).OrderBy(a => a.Date);
                break;

            case 3:
                var filters = filter.Split(' ');
                pets = filters.Length > 1
                        ? pets.Where(a => a.Gender.Contains(filters[0]) && a.Type.Contains(filters[1]))
                       .OrderBy(a => a.Date)
                        : pets.Where(a => a.Gender.Contains(filters[0])).OrderBy(a => a.Date);
                break;

            default:
                break;
            }

            res.Data = pets.ToList();
            return(res);
        }
Exemple #27
0
 private void _HandleResult(IntPtr con, bool success, IntPtr ptr)
 {
     ResultFunction func = this.result_func;
     this.result_func = null;
     func(success);
 }
 private UnaryOperation(string functionName, ResultFunction function, string specialFormat, bool childrenInSpecialFormatMayNeedBrackets)
     : base(ArgumentType.Unary, functionName, specialFormat, childrenInSpecialFormatMayNeedBrackets)
 {
     Function = function;
 }
 public ListOperation(string functionName, ResultFunction function)
     : base(ArgumentType.List, functionName, null, false)
 {
     Function = function;
 }
 protected BinaryOperation(string functionName, ResultFunction function, string specialFormat, bool childrenMayNeedBrackets)
     : base(ArgumentType.Binary, functionName, specialFormat, childrenMayNeedBrackets)
 {
     Function = function;
 }
Exemple #31
0
        //
        // PUBLIC METHODS
        //

        // Construye un resolutor (no necesita el puzle, se le pasará después)
        public TankPuzzleSolver()
        {
            oFunction = TankPuzzleFunctionFactory.getOperatorsFunction();
            rFunction = TankPuzzleFunctionFactory.getResultFunction();
            goalTest  = new TankPuzzleGoalTest();
        }
Exemple #32
0
        protected StepCostFunction stepCostFunction; // path cost

        public Problem(object initialSetup, OperatorsFunction operatorsFunction,
                       ResultFunction resultFunction, GoalTest goalTest)
            : this(initialSetup, operatorsFunction, resultFunction, goalTest,
                   new DefaultStepCostFunction())
        {
        }
Exemple #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Responder&lt;T&gt;"/> class.
 /// You pass a Responder object to NetConnection.call() to handle return values from the server. You may pass null for either or both parameters.
 /// </summary>
 /// <param name="result">The function invoked if the call to the server succeeds and returns a result.</param>
 public Responder(ResultFunction <T> result)
     : this(result, null)
 {
 }
Exemple #34
0
        //
        // PUBLIC METHODS
        //

        // Construye un resolutor (no necesita el puzle, se le pasará después)
        public SlidingPuzzleSolver()
        {
            oFunction = SlidingPuzzleFunctionFactory.getOperatorsFunction();
            rFunction = SlidingPuzzleFunctionFactory.getResultFunction();
            goalTest  = new SlidingPuzzleGoalTest();
        }
Exemple #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Responder&lt;T&gt;"/> class.
 /// You pass a Responder object to NetConnection.call() to handle return values from the server. You may pass null for either or both parameters.
 /// </summary>
 /// <param name="result">The function invoked if the call to the server succeeds and returns a result.</param>
 /// <param name="status">The function invoked if the server returns an error.</param>
 public Responder(ResultFunction <T> result, StatusFunction status)
 {
     _result = result;
     _status = status;
 }
Exemple #36
0
        public override async Task ExecuteFunction(IAsyncStreamReader <BundledRows> requestStream,
                                                   IServerStreamWriter <BundledRows> responseStream,
                                                   ServerCallContext context)
        {
            var response = new QlikResponse();

            try
            {
                logger.Debug("The method 'ExecuteFunction' is called...");

                //Read function header
                var functionHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <FunctionRequestHeader>();

                //Read common header
                var commonHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <CommonRequestHeader>();

                //Set appid
                logger.Info($"The Qlik app id '{commonHeader?.AppId}' in header found.");
                var qlikAppId = commonHeader?.AppId;

                //Set qlik user
                logger.Info($"The Qlik user '{commonHeader?.UserId}' in header found.");
                var domainUser = new DomainUser(commonHeader?.UserId);

                //Very important code line
                await context.WriteResponseHeadersAsync(new Metadata { { "qlik-cache", "no-store" } });

                //Read parameter from qlik
                var row      = GetParameter(requestStream);
                var userJson = GetParameterValue(0, row);

                //Parse request from qlik script
                logger.Debug("Parse user request...");
                var request = QlikRequest.Parse(domainUser, qlikAppId, userJson);

                var functionCall = (ConnectorFunction)functionHeader.FunctionId;
                logger.Debug($"Call Function id: '{functionCall}' from client '{context?.Peer}'.");

                if (functionCall == ConnectorFunction.START)
                {
                    #region Switch qlik user to app owner
                    if (domainUser?.UserId == "sa_scheduler" && domainUser?.UserDirectory == "INTERNAL")
                    {
                        try
                        {
                            var oldUser = domainUser.ToString();
                            domainUser = new DomainUser("INTERNAL\\ser_scheduler");
                            logger.Debug($"Change Qlik user '{oldUser}' to task service user '{domainUser}'.");
                            var connection = RuntimeOptions.Config.Connection;
                            var tmpsession = RuntimeOptions.SessionHelper.Manager.CreateNewSession(connection, domainUser, qlikAppId);
                            if (tmpsession == null)
                            {
                                throw new Exception("No session cookie generated. (Qlik Task)");
                            }
                            var qrsHub = new QlikQrsHub(RuntimeOptions.Config.Connection.ServerUri, tmpsession.Cookie);
                            qrsHub.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                            domainUser = request.GetAppOwner(qrsHub, qlikAppId);
                            if (domainUser == null)
                            {
                                throw new Exception("The owner of the App could not found.");
                            }
                            logger.Debug($"App owner '{domainUser}' found.");
                            request.QlikUser = domainUser;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex, "Could not switch the task user to real qlik user.");
                        }
                    }
                    #endregion

                    #region Function call SER.START
                    logger.Debug("Function call SER.START...");
                    var newManagedTask = new ManagedTask()
                    {
                        StartTime    = DateTime.Now,
                        Message      = "Create new report job...",
                        Cancellation = new CancellationTokenSource(),
                        Status       = 0
                    };
                    RuntimeOptions.TaskPool.ManagedTasks.TryAdd(newManagedTask.Id, newManagedTask);
                    var startFunction = new StartFunction(RuntimeOptions);
                    startFunction.StartReportJob(request, newManagedTask);
                    response.TaskId = newManagedTask.Id.ToString();
                    #endregion
                }
                else if (functionCall == ConnectorFunction.STOP)
                {
                    #region Function call SER.STOP
                    logger.Debug("Function call SER.STOP...");
                    var stopFunction = new StopFunction(RuntimeOptions);
                    stopFunction.StopReportJobs(request);
                    if (request.ManagedTaskId == "all")
                    {
                        response.Log = "All report jobs is stopping...";
                    }
                    else
                    {
                        response.Log = $"Report job '{request.ManagedTaskId}' is stopping...";
                    }
                    response.Status = 4;
                    #endregion
                }
                else if (functionCall == ConnectorFunction.RESULT)
                {
                    #region Function call SER.RESULT
                    logger.Debug("Function call SER.RESULT...");
                    var resultFunction = new ResultFunction(RuntimeOptions);
                    response = resultFunction.FormatJobResult(request);
                    #endregion
                }
                else if (functionCall == ConnectorFunction.STATUS)
                {
                    #region Function call SER.STATUS
                    logger.Debug("Function call SER.STATUS...");
                    var statusFunction = new StatusFunction(RuntimeOptions);
                    response = statusFunction.GetStatusResponse(request);
                    #endregion
                }
                else
                {
                    throw new Exception($"The id '{functionCall}' of the function call was unknown.");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The method 'ExecuteFunction' failed with error '{ex.Message}'.");
                response.Status = -1;
                response.SetErrorMessage(ex);
            }
            finally
            {
                logger.Trace($"Qlik status result: {JsonConvert.SerializeObject(response)}");
                await responseStream.WriteAsync(GetResult(response));

                LogManager.Flush();
            }
        }
 protected BinaryOperation(string functionName, ResultFunction function)
     : this(functionName, function, null, false)
 {
 }