Print() public static méthode

public static Print ( ) : void
Résultat void
        public async Task SetValueToMtu(
            dynamic value = null)
        {
            Utils.PrintDeep(Environment.NewLine + "------WRITE_TO_MTU-------");
            Utils.Print("Register -> SetValueToMtu -> " + this.id + ((value != null) ? " = " + value : ""));

            // Set value in temporary memory map before write it to the MTU
            if (value != null)
            {
                await this.SetValue(value);
            }

            // Write value set in memory map to the MTU
            if (valueType == RegType.BOOL)
            {
                await this.SetBitToMtu();
            }
            else
            {
                // Recover byte array with length equals to the value to set,
                // not the length ( sizeGet ) that will be used to recover/get
                await this.lexi.Write(( uint )this.address, this.funcGetByteArray ( false ));
            }

            Utils.PrintDeep("---WRITE_TO_MTU_FINISH---" + Environment.NewLine);
        }
        public void Solve()
        {
            var delta = _eps / 3;

            do
            {
                var x1 = (_a + _b - delta) / 2;
                var x2 = (_a + _b + delta) / 2;

                var firstFunction  = _function.Solve(x1);
                var secondFunction = _function.Solve(x2);

                if (firstFunction <= secondFunction)
                {
                    _b = x2;
                }
                else
                {
                    _a = x1;
                }

                _iterationAmount++;
            } while (!(_b - _a < _eps));

            var point    = Utils.RoundToEps(_eps, (_a + _b) / 2);
            var function = Utils.RoundToEps(_eps, _function.Solve(point));

            Utils.Print("Dichotomy", _eps, point, function, _iterationAmount, _function.CallAmount);
        }
        private void OnError()
        {
            Task.Run(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Error error = Errors.LastError;

                    ContentView_Scripting_textScript.Text = "Error code: " + error.Id + "\n" + error.Message;

                    Utils.Print("[ Scripting ] " + ContentView_Scripting_textScript.Text + ((error.HasMessagePopup) ? " | " + error.MessagePopup : string.Empty));

                    Device.BeginInvokeOnMainThread(() =>
                    {
                        backdark_bg.IsVisible           = false;
                        indicator.IsVisible             = false;
                        ContentView_Scripting.IsEnabled = true;
                        _userTapped = false;
                        ContentView_Scripting_label_read.Text = "Script Execution Error";

                        Device.OpenUri(new Uri(resultCallback + "?" +
                                               "status=error" +
                                               Compression.GetUriParameter() +
                                               "&message=" + Compression.CompressToUrlUsingGlobal("Error code: " + error.Id + "\n" + error.MessagePopup) +
                                               "&output_filename=" + resultScriptName +
                                               "&output_data=" + Compression.CompressToUrlUsingGlobal(Errors.lastErrorLogGenerated)));

                        FormsApp.ble_interface.Close();

                        // Close the app
                        System.Diagnostics.Process.GetCurrentProcess().Kill();
                    });
                });
            });
        }
        private void runScript()
        {
            Task.Run(async() =>
            {
                PrintToConsole("runScript Tarea Asincrona - InvokeMethod");
                await Task.Delay(150);
                Device.BeginInvokeOnMainThread(() =>
                {
                    try
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            PrintToConsole("Mostrar barra de progreso - InvokeMethod");

                            backdark_bg.IsVisible            = true;
                            indicator.IsVisible              = true;
                            ContentView_DeviceList.IsEnabled = false;
                            ContentView_Scripting.IsEnabled  = false;
                            _userTapped = true;
                            ContentView_Scripting_label_read.Text = "Executing Script ... ";
                        });


                        Device.BeginInvokeOnMainThread(() =>
                        {
                            Task.Factory.StartNew(scriptFunction);
                        });
                    }
                    catch (Exception e2)
                    {
                        Utils.Print(e2.StackTrace);
                    }
                });
            });
        }
 public void PrintToConsole(string printConsole)
 {
     if (DEBUG_MODE_ON)
     {
         Utils.Print("DEBUG_ACL: " + printConsole);
     }
 }
Exemple #6
0
    static void TestStateMonad()
    {
        Func <string, Monad.StateAccess <FPList <Tuple <string, int> >, int> > read = k => {
            return(state => {
                return new Tuple <FPList <Tuple <string, int> >, int>(state, state.Where(n => n.Item1 == k).Value.Item2);
            });
        };
        Func <string, int, Monad.StateAccess <FPList <Tuple <string, int> >, object> > write = (k, v) => {
            return(state => {
                var state2 = state.Contain(n => n.Item1 == k)
                    ? state.Select(n => n.Item1 == k ? new Tuple <string, int>(k, v) : n)
                    : state.Push(new Tuple <string, int>(k, v));
                return new Tuple <FPList <Tuple <string, int> >, object>(state2, null);
            });
        };

        var r = from k in write("x", 1)
                .Then(write("y", 10), (a, b) => a)
                .Then(read("x"), (a, x) => x)
                .Then(read("y"), (x, y) => x + y)
                from k2 in write("x", 2)
                .Then(read("x"), (a, x) => x)
                .Then(read("y"), (x, y) => x + y)
                select new { K = k, K2 = k2 };

        Utils.Print(r(null).Item2);
    }
Exemple #7
0
        private static void ReadFile(string filePath)
        {
            string line;

            try
            {
                using (StreamReader fileReader = new StreamReader(@filePath))
                {
                    while ((line = fileReader.ReadLine()) != null)
                    {
                        if (line.Equals(""))
                        {
                            continue;
                        }
                        Utils.Print($"[*] Reading command: {line}", verbose: verbose);
                        ParseLine(line);
                        Utils.Print($"[*] Done...{Environment.NewLine}", verbose: verbose);
                    }
                }
            }
            catch (Exception exc)
            {
                Utils.Print($"[x] Error during script processing: {exc.Message}{Environment.NewLine}{Environment.NewLine}{exc.StackTrace}", verbose: true);
            }
        }
Exemple #8
0
        public static PersistentProgram RunHoudiniPass(PersistentProgram prog)
        {
            Stats.resume("houdini");

            HashSet <Variable> templateVars = new HashSet <Variable>();
            List <Requires>    reqs         = new List <Requires>();
            List <Ensures>     enss         = new List <Ensures>();
            SimpleHoudini      houdini      = new SimpleHoudini(templateVars, reqs, enss, -1, -1);

            houdini.ExtractLoops = true;
            SimpleHoudini.fastRequiresInference = false;
            //SimpleHoudini.checkAsserts = true;
            houdini.printHoudiniQuery = null; // "candidates.bpl";
            // turnning on several switches: InImpOutNonNull + InNonNull infer most assertions
            houdini.InImpOutNonNull = false;
            houdini.InImpOutNull    = false;
            houdini.InNonNull       = false;
            houdini.OutNonNull      = false;
            houdini.addContracts    = false;

            prog.writeToFile("beforeHoudini.bpl");
            PersistentProgram newP = houdini.run(prog);

            newP.writeToFile("afterHoudini.bpl");

            //BoogieUtil.PrintProgram(newP.getProgram(), "afterHoudini.bpl");
            Utils.Print("End Houdini Pass ...");
            Stats.stop("houdini");

            return(newP);
        }
Exemple #9
0
        static void Main(string[] args)
        {
            Utils.Print("Write integer a and b (a<b): ");
            Utils.Print("a: ");
            var aStr = Console.ReadLine();

            Utils.Print("b: ");
            var bStr = Console.ReadLine();
            int a;
            int b;

            if (Int32.TryParse(aStr, out a) && Int32.TryParse(bStr, out b) && a < b)
            {
                Utils.Print("Numbers");
                NumberBetween(a, b);
                var sum = 0;
                sum = GetNumberSum(a, b, sum);
                Utils.Print($"Sum = {sum}");
            }
            else
            {
                Utils.Print("Values entered are not correct.");
            }
            Utils.Pause();
        }
Exemple #10
0
        public void Take(XuLiskovRequest request, EXuLiskovOperation operation)
        {
            List <ServerData>       replicasList = backgroundClientView.ReplicasList;
            CancellationTokenSource tokenSource  = new CancellationTokenSource();

            tokenSource.CancelAfter(timeout);
            CancellationToken cancellationToken = tokenSource.Token;

            Utils.Print($" [*] Waiting servers for <TAKE - PHASE 1> Acknowledge...");

            Task <ReplyData>[] tasksArray = InitiateServerCalls(replicasList, request, cancellationToken);

            if (operation == EXuLiskovOperation.TakeOne)
            {
                TakeOne(tasksArray, request, cancellationToken);
            }
            else if (operation == EXuLiskovOperation.TakeTwo)
            {
                TakeTwo(tasksArray, request, cancellationToken);
            }
            else if (operation == EXuLiskovOperation.Unlock)
            {
                TakeUnlock(tasksArray, request, cancellationToken);
            }
            else
            {
                Utils.Print($" [x] Error: Unable to identify <TAKE> phase...");
            }
        }
Exemple #11
0
        private void TakeWaitAll(Task <ReplyData>[] tasksArray, XuLiskovRequest request, CancellationToken cancellationToken, bool isTakeTwo = true)
        {
            int tasksCount = tasksArray.Length;

            try
            {
                Task.WaitAll(tasksArray, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                RepeatOperation(EOperationType.Take, request, reason: "one or more servers timed out");
                return;
            }

            for (int tidx = 0; tidx < tasksCount; tidx++)
            {
                ReplyData replyData = tasksArray[tidx].Result;

                if (!Utils.IsValidRemoteReply(tasksArray[tidx], typeof(AckReply)))
                {
                    TryUpdateView(tasksArray[tidx]);
                    RepeatOperation(EOperationType.Take, request, $"at least a server failed to acknowledge <TAKE-{(isTakeTwo ? "PHASE2> commit" : "UNLOCK> request")}");
                    return;
                }
            }

            Utils.Print($" >> Success on <TAKE-{(isTakeTwo ? "PHASE2" : "UNLOCK> ")}>...");
        }
        // collect bug from the bug report file produce by AVN
        private static HashSet <string> collectBugs(string p)
        {
            HashSet <string> ret = new HashSet <string>();

            try
            {
                foreach (string line in File.ReadLines(p))
                {
                    if (line.StartsWith("Description"))
                    {
                        continue;
                    }
                    // extract line from bug report
                    ret.Add(line);
                }
            }
            catch (FileNotFoundException)
            {
                Utils.Print(string.Format("Bug report file not found: {0}", p));
            }
            catch (Exception e)
            {
                Utils.Print(string.Format("Error when processing bug report: {0}", p));
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            return(ret);
        }
        private static int getMetric(int traceno, string trace_file)
        {
            int num_lines = 0;

            try
            {
                foreach (string line in File.ReadLines(trace_file))
                {
                    num_lines++;
                }
            }

            catch (FileNotFoundException)
            {
                Utils.Print(string.Format("Trace file not found: {0}", trace_file));
            }
            catch (Exception e)
            {
                Utils.Print(string.Format("Error while processing trace file: {0}", trace_file));
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            return(num_lines);
        }
        // locate binary in the system
        private static string findExe(string exe)
        {
            string ret    = null;
            var    runDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            if (!File.Exists(Path.Combine(runDir, exe)))
            {
                var enviromentPath = System.Environment.GetEnvironmentVariable("PATH"); // look up in PATH
                var paths          = enviromentPath.Split(';');
                ret = paths.Select(x => Path.Combine(x, exe))
                      .Where(x => File.Exists(x))
                      .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(avnPath))
                {
                    throw new FileNotFoundException("Cannot find executable: " + exe);
                }
            }
            else
            {
                ret = Path.Combine(runDir, exe);
            }
            Utils.Print(String.Format("Found {0} at: {1}", exe, ret));

            return(ret);
        }
Exemple #15
0
        private static List <ServerData> ReadInitialServers()
        {
            string filePath = $"{serversDirectory}/knownReplicas.json";

            Directory.CreateDirectory(serversDirectory);

            if (!File.Exists(filePath))
            {
                Console.WriteLine($"[x] File {filePath} not found. Exiting...");
                Environment.Exit(-1);
            }

            using (StreamReader streamReader = new StreamReader(@filePath))
                using (JsonReader jsonReader = new JsonTextReader(streamReader))
                {
                    List <ServerData> replicasList;
                    JsonSerializer    serializer = new JsonSerializer();
                    replicasList = serializer.Deserialize <List <ServerData> >(jsonReader);

                    Utils.Print("[*] Loading known replicas information...", verbose: true);

                    foreach (ServerData server in replicasList)
                    {
                        Utils.Print($" >> tcp://{server.ServerURL}/{server.ServerName}", verbose: true);
                    }

                    return(replicasList);
                }
        }
Exemple #16
0
        internal ReplyData DeliverRequest(RequestData requestData)
        {
            mIdTable[requestData.ClientId] = requestData.RequestId;

            Random random     = new Random();
            int    delayValue = random.Next(minDelay, maxDelay);

            Thread.Sleep(delayValue);

            Utils.Print(" [*] SMR Server: Delivering Request", verbose: Verbose);

            switch (requestData.Operation)
            {
            case EOperationType.Read:
                Utils.Print(" [*] Executing <READ> operation...", verbose: Verbose);
                return(Read(requestData));

            case EOperationType.Take:
                Utils.Print(" [*] Executing <TAKE> operation...", verbose: Verbose);
                return(Take(requestData));

            case EOperationType.Write:
                Utils.Print(" [*] Executing <WRITE> operation...", verbose: Verbose);
                return(Write(requestData));

            default:
                return(new DiscardedMsgReply(requestData.RequestId));
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            Utils.Print("Ваш рост(см): ");
            var heightStr = Console.ReadLine();

            Utils.Print("Ваш вес(кг): ");
            var    weightStr = Console.ReadLine();
            double height;
            double weight;

            if (Double.TryParse(heightStr, out height) && Double.TryParse(weightStr, out weight))
            {
                var index = GetIndex(height, weight);
                Utils.Print("Индекс массы тела: " + index.ToString("0.00"));
                var indexResult = GetIndexResult(index);
                Utils.Print(GetReccomend(indexResult));
                if (indexResult != IndexResult.Norm)
                {
                    Utils.Print(GetAccurateReccomend(indexResult, index, height, weight));
                }
            }
            else
            {
                Utils.Print("Невозможно обработать введенные значения");
            }
            Utils.Pause();
        }
Exemple #18
0
        public void ComplexParameter(XElement parent, ActionResult result, InterfaceParameters parameter, int portNumber = 0)
        {
            Parameter param = result.getParameterByTag(parameter.Name, parameter.Source, portNumber);

            Utils.Print("Log Param: " + parameter.Name + " " + parameter.Source + " " + portNumber +
                        " = " + ((param == null) ? "..." : param.Value));

            /*
             * if ( ! string.IsNullOrEmpty ( parameter.Source ) )
             * {
             *  try
             *  {
             *      param = result.getParameterByTag ( parameter.Source.Split(new char[] { '.' })[1], parameter.Source, 0 );
             *  }
             *  catch (Exception e)
             *  {
             *
             *  }
             * }
             * if (param == null)
             *  param = result.getParameterByTag ( parameter.Name, parameter.Source, 0 );
             */

            if (param != null)
            {
                Parameter(parent, param);
            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var isLogin     = false;
            var countChance = 0;

            do
            {
                Utils.Print("Login");
                var login = Console.ReadLine();
                Utils.Print("Password");
                var password = Console.ReadLine();
                isLogin = IsLogin(login, password);
                if (isLogin)
                {
                    break;
                }
                Utils.Print("Incorrect login or password");
                countChance++;
            }while (countChance != 3);
            if (isLogin)
            {
                Utils.Print("Success login");
            }
            else
            {
                Utils.Print("Try later");
            }
            Utils.Pause();
        }
        /// <summary>
        /// Talk command allows player to talk to this NPC
        /// </summary>
        public override void Talk()
        {
            base.Talk();
            Utils.Print();
            switch (Utils.AskQuestion(question))
            {
            case "yes":
            case "y":
                if (Program.player.gold < price)
                {
                    Utils.Add("You don't have enough gold");
                    return;
                }
                Program.player.gold -= price;
                Utils.Add($"You spend {Utils.ColorText(price.ToString(), TextColor.YELLOW)} gold and sleep for the night");
                Program.player.Home = Program.player.currentLocation;
                break;

            case "no":
            case "n":
                Utils.Add("Okay, talk to me again if you change your mind");
                break;

            default:
                Utils.Add("uh, alright?");
                break;
            }
        }
Exemple #21
0
        private void CallToInitApp(
            IBluetoothLowEnergyAdapter adapter,
            IUserDialogs dialogs,
            string appVersion)
        {
            // Catch unhandled exceptions
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
            TaskScheduler.UnobservedTaskException      += TaskSchedulerOnUnobservedTaskException;

            Utils.Print("FormsApp: Interactive [ " + Data.Get.IsFromScripting + " ]");

            appVersion_str = appVersion;

            deviceId = CrossDeviceInfo.Current.Id;

            // Profiles manager
            credentialsService = new CredentialsService();

            // Initializes Bluetooth
            ble_interface = new BleSerial(adapter);

            AppResources.Culture = CrossMultilingual.Current.DeviceCultureInfo;

            // Config path
            ConfigPaths();

            if (Device.RuntimePlatform == Device.iOS)
            {
                var MamServ = DependencyService.Get <IMAMService>();
                MamServ.UtilMAMService();
            }

            this.LoadConfigurationAndOpenScene(dialogs);
        }
Exemple #22
0
 static void Main(string[] args)
 {
     Utils.Print("Write integer! 0 - exit");
     var sum = GetSum();
     Utils.Print($"Sum of odd positive = {sum}");
     Utils.Pause();
 }
        private async void CallRoute(Company company, DateTime date)
        {
            CheckLoading(1);
            String     startDate = Utils.GetFormattedDate(date);
            HttpClient client    = new HttpClient();

            try {
                HttpResponseMessage message = await client.GetAsync(Utils.GetUrl(company.symbol, startDate));

                String mes = await message.Content.ReadAsStringAsync();

                StockResponse res = Newtonsoft.Json.JsonConvert.DeserializeObject <StockResponse>(mes);

                company.closeStockValues.Clear();
                company.tradingDays.Clear();
                for (int i = 0; i < res.results.Count; i++)
                {
                    Result r = res.results[i];
                    company.closeStockValues.Add(r.close);
                    company.tradingDays.Add(DateTime.ParseExact(r.tradingDay, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture));
                }
                CheckLoading(-1);
            } catch (Exception e) {
                Utils.Print(e.Message);
                CheckLoading(-1);
            }
        }
Exemple #24
0
        internal override void ReceiveTotalOrder(TotalOrderData totalorderData)
        {
            int requestId = totalorderData.RequestId;

            Utils.Print(" [*] SMR Server: Received TotalOrderData.", verbose: Verbose);

            if (holdbackQueue.ContainsKey(requestId))
            {
                int totalorderId = totalorderData.TotalOrderId;

                if (totalorderId < rg)
                {
                    Utils.Print(" [x] SMR Server: Received unexpected TotalOrderData.");
                }
                else if (totalorderId > rg)
                {
                    deliveryQueue.Add(requestId, totalorderData);
                }
                else
                {
                    ExecuteRequest(requestId);
                }
            }
            else
            {
                deliveryQueue.Add(requestId, totalorderData);
            }
        }
Exemple #25
0
        public override List <DIDATuple> SendMatchingTuples(DIDATuple didaTuple)
        {
            List <DIDATuple> matchingTuples = GetMatchingTuples(didaTuple);

            Utils.Print($" [*] Sending Matching Tuples for {didaTuple.ToString()}. Found {matchingTuples.Count()}.", verbose: Verbose);
            return(matchingTuples);
        }
        private bool Get(string id, out object result)
        {
            if (this.dictionary.ContainsKey(id))
            {
                dynamic register = this.dictionary[id];

                result = this.dictionary[id];

                /*
                 * if ( register.registerType == REGISTER_TYPE.REGISTER )
                 * {
                 *  // Some registers have customized get method
                 *  if ( ! register.HasCustomMethod_Get )
                 *       result = ( object )this.dictionary[ id ].GetValueRaw (); // Invokes funGet method
                 *  else result = ( object )this.dictionary[ id ].GetValue ();    // Invokes funGetCustom method
                 * }
                 * else // Overload
                 *  result = ( object )this.dictionary[ id ].GetValue ();
                 */

                return(true);
            }

            // Selected dynamic member not exists
            Utils.Print("Get " + id + ": Error - Selected register is not loaded");
            throw new MemoryRegisterNotExistException(MemoryMap.EXCEP_SET_USED + " [ Get ]: " + id);
        }
Exemple #27
0
        public static void Test()
        {
            var      obj  = new IsSubPath_1367();
            ListNode head = null;
            TreeNode root = null;

            Utils.Print($"res = {obj.IsSubPath(head, root)}");
        }
 /// <summary>
 /// Clear out the attack system
 /// </summary>
 public void EndAttack()
 {
     player.creature  = null;
     monster.creature = null;
     Utils.Print();
     //Hide the window
     HideWindow();
 }
Exemple #29
0
        internal void SendResponse(RequestData requestData, ReplyData replyData)
        {
            string         clientProxyURL = $"{requestData.ClientURL}/{requestData.ClientId}";
            IClientService clientProxy    = (IClientService)Activator.GetObject(typeof(IClientService), clientProxyURL);

            clientProxy.ReceiveAnswer(ServerData, replyData);
            Utils.Print("[*] SMR Server: Sent Response.");
        }
Exemple #30
0
        static void Main(string[] args)
        {
            var a = 1234137875;

            Utils.Print($"Number Of Digits {a}");
            Utils.Print(NumberOfDigits(a).ToString());
            Utils.Pause();
        }