Saturday, June 18, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Snowflake not able to give permission in azure, it's showing unverified

Posted: 18 Jun 2022 04:05 AM PDT

While connecting azure with snowflake not able to give permission in azure, it's showing unverified Please find the attached document.

Function does not work when entering number javascript

Posted: 18 Jun 2022 04:05 AM PDT

I have a function that reverses a string. I would like the function to return "Null" when a number is entered however when i input a number my function stops working. Is there something i am missing?

    let eachLetter = words.split("");        let reverseLetter = eachLetter.reverse();        let combineLetter = reverseLetter.join("");        if (typeof words !== "string") {          return null;      } else {          return combineLetter;      }  }    console.log(reverseWords(89));  

Python Tkinter Button widget

Posted: 18 Jun 2022 04:04 AM PDT

few days ago i tried to create connect between sql.connector and tkinter but I noticed there is problem with Button widget and with command option, so i tried to create a simple program with tkinter without using mysql.connector but still there's problem with it , here is my code and Button widget does not work :

from tkinter import *    win = Tk()    t1=IntVar()  t2=IntVar()    def adder():      var1 = int(t1.get())      var2 = int(t2.get())      return var1 + var2    win.geometry("750x750")    l1 = Label(win , text = "Number 1").grid(row = 0 , column = 0)  e1 = Entry(win , textvariable = t1).grid(row = 0 , column = 1)    l2 = Label(win , text = "Number 2").grid(row = 1 , column = 0)  e2 = Entry(win , textvariable = t2).grid(row = 1 , column = 1)    do = adder    b1 = Button(win , text = "Adder" , command = do)  b1.grid(row = 2 , column = 2)    lb = Listbox(win)  lb.grid(row = 4 , column = 4)  lb.insert(1 , do())    win.mainloop()  

and the problem is Button widget doesn't even show in window , why ?

Find missing numbers in list. The ouput i get: [6,9,10,16,18,19,20] The ouput i need like: [[6],[9,10],[16],[18,19,20]].'

Posted: 18 Jun 2022 04:03 AM PDT

get_user_input_list = [1,2,3,4,5,7,8,11,12,13,14,15,17,21]  missing_item_in_list = []  start = get_user_input_list[0]  stop = get_user_input_list[-1]    for i in range(start,stop+1):      if i not in get_user_input_list:          missing_item_in_list.append(i)  

'The ouput i get: [6,9,10,16,18,19,20] The ouput i need like: [[6],[9,10],[16],[18,19,20]].'

CreatePseudoConsole and raw mode / cooked mode

Posted: 18 Jun 2022 04:03 AM PDT

i'm writing a terminal emulator in python (using pyte) and I need it to support all kind of applications (like vim,nano, for example). I'm on Windows and i have vim.exe and nano.exe as part of Git installation.

I'm using CreatePseudoConsole with pipes and CreateProcess function to launch cmd.exe and inside it I execute vim. But I don't know how to handle input! I know that there are different modes of input like "raw" and "cooked".

The question is how can I differentiate between these modes? like when does vim want to switch to one or another mode?

Validation on update Laravel doesn't find parameters in function rules

Posted: 18 Jun 2022 04:03 AM PDT

I'm trying to validate some forms in Laravel, and when I call the function rules where I validate the form, it doesn't find the parameters: name, org., and image. Image of error message here

public function update($id)      {          $game  = Game::find($id);          $game->name = $this->rules()->name;          $game->organization = $this->rules()->organization;          $game->image = $this->rules()->image;          $game->save();            return redirect('games');      }        public function rules()      {          return [              'name' => 'required',              'organization' => 'required',              'image' => 'required',          ];      }  

How to import a single method form python library and still keep the namespace?

Posted: 18 Jun 2022 04:04 AM PDT

So, I want to import the random.sample() method, but I can either import the whole library by typing "import random" or loose the namespace by typing "from random import sample". How can i just import the single method but a able to call it with random.sample() ? Is there a elegant way to do it?

How psycopg2 connect to postgres by kube nodeport host?

Posted: 18 Jun 2022 04:04 AM PDT

I'll use testarchiver send robotframework output to postgres then grafana hook data from postgres show to dashboard. I have install postgres on kubernetes and use nodeport for access postgres from outside. I use testarchiver(python lib) for send robotframework output to postgres but It error that psycopg2.OperationalError: could not translate host name "my kube ip:30005" to address: Name or service not known.

I config db_config.json for use in testarchiver like this: {

    "db_engine": "postgresql",      "database": "my_db",      "host": "my kube ip:30005",      "port": "5432",      "user": "root",      "password": "My Password",      "require_ssl": "False"  

}

I thought in host can't use ip with port.

how resolve this problem?

how I set host with port for psycopg2 connect to my postgres?

Loop throw column cells in golang and excelize

Posted: 18 Jun 2022 04:05 AM PDT

i was wondered ho to loop over a column cells of excel sheet in golang , any one can help ,

enter image description here

i have tried this piece of code for other reason

package main    import (      "fmt"      "github.com/xuri/excelize/v2"  )    func main() {        f, err := excelize.OpenFile("pricematching.xlsx")      if err != nil {          fmt.Println(err)          return      }        // Get all the rows in the sheet1 section.      rows, err := f.GetCellValue("sheet1", "A2")        fmt.Print(rows, "\t")    }      

How can a Powershell function specify a ComObject parameter type?

Posted: 18 Jun 2022 04:04 AM PDT

Let's say that I'm trying to write a Powershell function that prints a result set to an Excel worksheet, like this:

function Write-ToWorksheet {    param (      [Parameter( Position = 0, Mandatory = $true )]      [MyLibrary.MyCustomResultType[]]      $ResultSet,        [Parameter( Position = 1, Mandatory = $true )]      [Excel.Worksheet]      $Worksheet    )    # ... Implementation goes here ...  }  

And let's say that I'm calling it in a way something like this:

$excel = New-Object -ComObject Excel.Application  $wb = $excel.Workbooks.Add()    $results = Get-MyResults # Never mind what this does.    Write-ToWorksheet -ResultSet $results -Worksheet $wb.Sheets[ 1 ]  

And this code will almost work, except that it chokes on my type specification of [Excel.Worksheet].

I realize that it is not necessary to specify the parameter type, and that the code will work just fine without it, as this answer points out.

But to please my inner pedant, is there any way to constrain the parameter type using a reference to a COM object type like Excel.Worksheet?

How change the second letter in char *name = "exemple"; with char *name

Posted: 18 Jun 2022 04:06 AM PDT

I am studying c++ to get a good understanding of memory.

char *name = "example";     *(&name+1) = (char*)'A';    std::cout << name << std::endl;  

is returning example not eAample.

My idea is to get the memory address of 'x' and changed it.

Is not a const so I should be able to change the value of the address right?

obs: I know how do it in other ways, I am curious to make this way.

Execute a program loaded in RAM without making executable files [duplicate]

Posted: 18 Jun 2022 04:04 AM PDT

I want to make a launcher that loads into RAM a program and then execute it. I know how RAM works at low-levels, but still, i dont know where or how i must allocate or mallocate memory to be executed in the CPU. I tried to use pointers to allocate the memory, but as long as i cant test it, i dont even know if it will work.

this may require of assembler, languaje that, i dont know so much. I can handle it in C/C++. Still, if necesary I will work in assembler.

Anyway, the program must be loaded in the data part of the program (.data / .text) or can allocated dynamically in RAM? Plus i cant allocate it in ROM, the point of this is to change the very source code dynamically,so i cant load the program in ROM.

this question also have to do with "What does the Operative System exactly do to run a program" and that is also usefull, but still i cant allocate it in ROM,thing that the OS do sometimes

I think i may can use char** or char* as the program code vector,But i need to know if this will point to the next part of the program correctly, because it maybe allocates the memory in other addres,and,execute something else. ¿is that even posible? I've passed like a month searching about this, and found nothing of implementation or tons, TONS of steps that the OS do when running a program but never how does it make the CPU execute it. That's why i am asking here.

I also know that using a struct probably will not work. (If you have a struct wich have a char* and a int (uint16_t*). The diferent types of data will make it error. ¿or not? I think it will).

I am not pretty sure of what I readed it's correct and what it's not, because sometimes a post contradicts to another.

Also I searched for polimorfic code, but it's not what i am searching for. Because i need the launcher thing.

Multiline output to single line concatenation with delimiter string

Posted: 18 Jun 2022 04:05 AM PDT

I use this command to get a list of all the files that has changed in a pull-request.

git diff --name-only HEAD master  

Sample output:

my/repo/file1.java  my/repo/file3.java  my/repo/file5.java  

I would like to convert this output to the following:

file:my/repo/file1.java||file:my/repo/file3.java||file:my/repo/file5.java  

so that I can run code analysis only on these files from IntelliJ IDEA.

What have I tried so far?

git diff --name-only HEAD master |  sed -e 's/^/file:/'  | paste -s -d "||" -  

This gives me the following output:

file:my/repo/file1.java|file:my/repo/file3.java|file:my/repo/file5.java  

Notice the single |.

Also, please simplify the command if possible.

C# BlockingCollection loop on IsCompleted instead of GetConsumingEnumerable

Posted: 18 Jun 2022 04:05 AM PDT

In an application, many actions need to be logged in the database. but this logging process should not slow down the request. So they should be done in an asynchronous queue or something.

This is my big picture:

big picture

And this is my example implementation:

Model:

public class ActivityLog  {      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]      public string Id { get; set; }      public IPAddress IPAddress { get; set; }      public string Action { get; set; }      public string? Metadata { get; set; }      public string? UserId { get; set; }      public DateTime CreationTime { get; set; }  }  

Queue:

public class LogQueue  {      private const int QueueCapacity = 1_000_000; // is one million enough?        private readonly BlockingCollection<ActivityLog> logs = new(QueueCapacity);        public bool IsCompleted => logs.IsCompleted;      public void Add(ActivityLog log) => logs.Add(log);      public IEnumerable<ActivityLog> GetConsumingEnumerable() => logs.GetConsumingEnumerable();      public void Complete() => logs.CompleteAdding();  }  

Worker (the problem is here):

public class DbLogWorker : IHostedService  {      private readonly LogQueue queue;      private readonly IServiceScopeFactory scf;      private Task jobTask;        public DbLogWorker(LogQueue queue, IServiceScopeFactory scf)      {          this.queue = queue;          this.scf = scf;            jobTask = new Task(Job, TaskCreationOptions.LongRunning);      }          private void Job()      {          using var scope = scf.CreateScope();          var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();            // The following code does not work          // My intension was to reduce DB trips          //while(!queue.IsCompleted)          //{          //    var items = queue.GetConsumingEnumerable();          //    dbContext.AddRange(items);          //    dbContext.SaveChanges();          //}            // But this works          // If I have 10 items available, I'll have 10 DB trips (not good), right?          foreach (var item in queue.GetConsumingEnumerable())          {              dbContext.Add(item);              dbContext.SaveChanges();          }      }        public Task StartAsync(CancellationToken cancellationToken)      {          jobTask.Start();          return Task.CompletedTask;      }        public Task StopAsync(CancellationToken cancellationToken)      {          queue.Complete();          jobTask.Wait(); // or 'await jobTask' ?          return Task.CompletedTask; // unnecessary if I use 'await jobTask'      }  }  

Dependency Injection:

builder.Services.AddSingleton<LogQueue>();  builder.Services.AddHostedService<DbLogWorker>();  

Controller:

[HttpGet("/")]  public IActionResult Get(string? name = "N/A")  {      var log = new ActivityLog()      {          CreationTime = DateTime.UtcNow,          Action = "Home page visit",          IPAddress = HttpContext.Connection.RemoteIpAddress ?? IPAddress.Any,          Metadata = $"{{ name: {name} }}",          UserId = User.FindFirstValue(ClaimTypes.NameIdentifier)      };        queue.Add(log);        return Ok("Welcome!");  }  

As I explained in the comments, I want to get as many as items that are available and save them with one DB trip. My solution was the following code, but it doesn't work:

while (!queue.IsCompleted)  {      var items = queue.GetConsumingEnumerable();      dbContext.AddRange(items);      dbContext.SaveChanges();  }  

So instead, I'm using this which does a DB trip per each row:

foreach (var item in queue.GetConsumingEnumerable())  {      dbContext.Add(item);      dbContext.SaveChanges();  }  

I also have two side questions: How can I increase workers? How can I increase workers dynamically based on queue count?

I created an example project for this question:

enter image description here

Login to Flutter web app returns flutter_service_worker.js error

Posted: 18 Jun 2022 04:04 AM PDT

When I deploy a flutter web app on a cloud ubuntu server I can see the login screen ok but on login the flutter logs show this error.

preparing port 5000 ...  Server starting on port 5000 ...  172.19.0.14 - - [18/Jun/2022 11:02:06] "GET / HTTP/1.1" 304 -  172.19.0.14 - - [18/Jun/2022 11:02:07] "GET /flutter_service_worker.js?v=1208050259 HTTP/1.1" 304 -  

The go api returns this error

"OPTIONS http://api.mydomain.com/login HTTP/1.1" from 172.19.0.14:59572 - 405 0B in 36.92µs  

If I run my app locally as a linux client against the same api on a cloud server it logs in fine so the issue is with the web browser I guess. I get the same result from either Firefox or Chrome.

Here is my flutter Dockerfile:

FROM ubuntu:22.04    ARG DEBIAN_FRONTEND=noninteractive     ENV TZ=Australia/Adelaide    RUN apt-get update   RUN apt-get install -y apt-utils psmisc  RUN apt-get install -y curl git wget unzip libgconf-2-4 gdb libstdc++6 libglu1-mesa fonts-droid-fallback lib32stdc++6 python3  RUN apt-get clean    # download Flutter SDK from Flutter Github repo  RUN git clone https://github.com/flutter/flutter.git /usr/local/flutter    # Set flutter environment path  ENV PATH="/usr/local/flutter/bin:/usr/local/flutter/bin/cache/dart-sdk/bin:${PATH}"    # Run flutter doctor  RUN flutter doctor    # Enable flutter web  RUN flutter channel master  RUN flutter upgrade  RUN flutter config --enable-web    # Copy files to container and build  RUN mkdir /app/  COPY . /app/  WORKDIR /app/  RUN flutter build web    # Record the exposed port  EXPOSE 5000    # make server startup script executable and start the web server  RUN ["chmod", "+x", "/app/server/server.sh"]    ENTRYPOINT [ "/app/server/server.sh"]  

Here is my server.sh script

#!/bin/bash    PORT=5000    echo 'preparing port' $PORT '...'  fuser -k 5000/tcp    cd build/web/    echo 'Server starting on port' $PORT '...'  python3 -m http.server $PORT  

How to decompress buffers from ETW - ETL files produced by PktMon?

Posted: 18 Jun 2022 04:05 AM PDT

I'm trying to extract packets in a cross-platform way, that is, without using Windows API, from .etl files captured by using PktMon, (e.g. pktmon start --capture --pkt-size 0 -f packets.etl ) .
At least on Win 11, PktMon goes (usually) into LogFileMode: 0x4010001, so buffers are re-logged with some compression (think is LZNT1, not sure about it).
How those buffers could be decompressed after reading them from the .etl file?

Found some clues in Geoff Chappell's comments on the bottom of this page but not the effective detailed layout and mechanism.

Train test split and Cross validation

Posted: 18 Jun 2022 04:04 AM PDT

Is this approach right?

Since I have a small data set. I split the data into training and testing set. Perform cross validation on the training set for hyper parameter tuning. And finally test the model on the test set. But in doing so I am getting test accuracy higher than the training accuracy.

Code:

def objective(trial, data=X_train, target=y_train):      score=[]      params = {'alpha':trial.suggest_loguniform('alpha', 1e-2, 1e2)}      rkf = RepeatedKFold(n_splits=10, n_repeats=1, random_state=42)            for train_index, test_index in rkf.split(data, target):          train_X, test_X, train_y, test_y = X_train.iloc[train_index], X_train.iloc[test_index], y_train.iloc[train_index], y_train.iloc[test_index]          lasso = Lasso(**params)          lasso.fit(train_X, train_y)          y_pred = lasso.predict(test_X)          score.append(r2_score(test_y, y_pred))  #     print(score)      return np.mean(score)    study = optuna.create_study(direction='maximize')  study.optimize(objective, n_trials=25)  print('Number of finished trials:', len(study.trials))  print('Best trial:', study.best_trial.params)  print('Accuracy:{}'.format(study.best_trial.value))  
lasso = Lasso(**study.best_trial.params)  lasso.fit(X_train, y_train)  y_pred = lasso.predict(X_test)  print(r2_score(y_test, y_pred))  

How to add a token to a yield farm and get sender's balance

Posted: 18 Jun 2022 04:05 AM PDT

I'm trying to allow users to add a token to a Farm for staking. After deploying the reward and staking token, I deployed the farm contract with the two tokens as arguments for the constructor. However when I try to execute the stakeTokens function, the balance of stakingToken is 0.

My Farm

contract MyFarm {            mapping(address => uint256) public rewardBalance;      mapping(address => uint256) public startBlock;      mapping(address => uint256) public stakingBalance;      mapping(address => bool) public staking;        RewardToken public rewardToken;      StakingToken public stakingToken;      uint256 private rewardTokensPerBlock;        event Stake(address indexed from, string lp1, uint256 amountLp1);      event Unstake(address indexed from, string lp1, uint256 amountLp1);      event HarvestRewards(address indexed to, uint256 amount);            constructor(RewardToken _rewardToken, StakingToekn _stakingToken) {          rewardTokensPerBlock = 100;          rewardToken = _rewardToken;          stakingToken = _stakingToken;      }        function stakeToken(uint256 amount) public {          uint256 stakeTokenBal = stakingToken.balanceOf(msg.sender);          require(amount > 0 && stakingToken.balanceOf(msg.sender) >= amount,          "Cannot stake zero LP tokens to the farm / User must own enough LP tokens as specified");            if (staking[msg.sender] == true) {              uint256 amtToTransferToRewards = getCurrentYield(msg.sender);              rewardBalance[msg.sender] += amtToTransferToRewards;          }            stakingToken.transferFrom(msg.sender, address(this), amount);          stakingBalance[msg.sender] += amount;            startBlock[msg.sender] = block.number;          staking[msg.sender] = true;            uint256 stakingRewards = rewardTokensPerBlock;          stakingToken.mint(msg.sender, stakingRewards);          emit Stake(msg.sender, "STK", amount);      }        function getCurrentYield(address user) public view returns (uint256) {          uint256 endBlock = block.number;          uint256 numBlocksSince = endBlock - startBlock[user];          uint256 stakingTokenYield = milkStakingBalance[user] * 10 / 100;          uint256 totalYield = numBlocksSince * stakingTokenYield;          return totalYield;      }  }    

StakingToken:

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";    contract StakingToken is ERC20 {      constructor (address user, uint256 initialSupply) ERC20("StakingToken", "STK") {          _mint(user, initialSupply);      }  }  

I'm not sure why my stakingToken balance is 0 as I had already minted a supply of stakingTokens to myself?

My guess is that the farm contract does not own any of the stakingTokens and the msg.sender in this case is referring to the farm contract?

Or could someone show me the right way to add tokens to a farm contract?

Apache Spark unable to recognize columns in UTF-16 csv file

Posted: 18 Jun 2022 04:06 AM PDT

Question: Why I am getting following error on the last line of the code below, how the issue can be resolved?

AttributeError: 'DataFrame' object has no attribute 'OrderID'

CSV File encoding: UTF-16 LE BOM

Number of columns: 150

Rows: 5000

Language etc.: Python, Apache Spark, Azure-Databricks

MySampleDataFile.txt:

FirstName~LastName~OrderID~City~.....  Kim~Doe~1234~New York~...............  Bob~Mason~456~Seattle~...............  ..................  

Code sample:

from pyspark.sql.types import DoubleType  df = spark.read.option("encoding","UTF-16LE").option("multiline","true").csv("abfss://mycontainder@myAzureStorageAccount.dfs.core.windows.net/myFolder/MySampleDataFile.txt", sep='~', escape="\"", header="true", inferSchema="false")            display(df.limit(4))  df1 = df.withColumn("OrderID", df.OrderID.cast(DoubleType()))  

Output of display(df.limit(4)) It successfully displays the content of df in a tabular format with column header - similar to the example here:

---------------------------------------  |FirstName|LastName|OrderID|City|.....|  ---------------------------------------  |Kim~Doe|1234|New York|...............|  |Bob|Mason|456|Seattle|...............|  |................                     |  ---------------------------------------  

Communicate Java and C without Sockets?

Posted: 18 Jun 2022 04:03 AM PDT

I was tasked to write a service in C that listens to a named or unnamed Windows OS pipe (two way data transfer should be possible) and the "host application" that writes data to the OS pipe should be a java program. I am not allowed to use sockets (for performance reasons) or any external non-default library.

Is it possible to write data to named/unnamed OS pipes with Java (if possible without turning the program into C code with JNI?) I've been thinking of running a CMD script that writes to an OS pipe with java but I'm pretty sure that it would be extremely inefficient. I've also looked into the java Pipe class but if I understood correctly, this is only for inter-thread communication inside the JVM and not a "real" OS pipe. How exactly can I write data to a "real" OS pipe? Performance is very important for this because I need a Java program to communicate with a C program, which runs CUDA operation so I can't afford to waste a lot of performance on sending/receiving the data.

Unity XR cannot recognize controller devices via script

Posted: 18 Jun 2022 04:05 AM PDT

I am trying to use my oculus quest to develop some hand controls with the oculus touch controllers. However, the script I'm using is unable to detect my touch devices for some reason while it looks perfectly functional from the XR interaction Debugger and is even functional when using the XR Direct Interactor component provided by the XR Interaction Toolkit.

The script I'm using to test the controls is as follows:

using System.Collections;  using System.Collections.Generic;  using UnityEngine;  using UnityEngine.XR;    public class HandController : MonoBehaviour  {      List<InputDevice> devices = new List<InputDevice>();        void Start()      {          InputDevices.GetDevices(devices);              foreach (var item in devices)          {              Debug.Log(item.name + item.characteristics);          }      }        void Update()      {          foreach(var item in devices)          {              Debug.Log(item.name + item.characteristics);          }      }  }  

Here are the console and XR Interaction Debugger outputs for reference:

Console Output XR Interaction Debugger

How to use HL7 to send a patient's information usingl Laravel-8? [closed]

Posted: 18 Jun 2022 04:05 AM PDT

I'm using Laravel 8 & I installed senaranya/HL7 for hl7 service. Now I want to send a patient information like patient's name, date of birth, address...., and his/her pdf reports/Images to another EMR. Anyone here to provide me the code sample please?

Google Sheet App Script For next LOOP error [closed]

Posted: 18 Jun 2022 04:04 AM PDT

Want to generate a loop for picking next symbols from Table A in Sheet "RANK!R9:S".

Then want to copy every next row symbol to "PF Sheet!B20" (cell only) for 1st Loop. This is going to generate a new set of values in "PF Sheet!D16:D", for each value copied to "PF Sheet!B20" cell.

Pl. refer the google Sheet link

https://docs.google.com/spreadsheets/d/1r0_oHLTcT9tmTJPgKVgkGwGWhooBM8uluwmWcC92eOk/edit?usp=sharing

'''' function permutation() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();    var rank = ss.getSheetByName('Rank');    var pf_sheet = ss.getSheetByName('PF Sheet');      var symbols = pf_sheet.getRange('B20')    var start = rank.getRange('S9');    var end = rank.getRange('S4');        rownum = start.getRowIndex()    rowTarget = end.getValue()      for (let i = rownum; i <= rowTarget; i++) {       var value = rank.getRange(i+1,19,).getValue();      value.getValue().copyTo(symbols());        // wait to complete all the changes on the spreadsheet      SpreadsheetApp.flush();        var start_2 = 2       var end_2 = pf_sheet.getRange('D10').getValue()        for (let i = start_2; i <= end_2; i++) {          Logger.log(symbols,start_1)           }      }    }  

''' Error Line 16

Google Analytics does not detect Windows 11 [closed]

Posted: 18 Jun 2022 04:04 AM PDT

My application uses Measurement Protocol to send analytics data to Google Analytics service.

Example of HTTP post:

POST https://ssl.google-analytics.com/collect HTTP/1.1  User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; X64; HP; HP Pavilion Notebook)  Content-Type: text/plain; charset=utf-8  Host: ssl.google-analytics.com  Content-Length: 268  Expect: 100-continue  Connection: Keep-Alive    v=1&tid=UA-XXXXXXXX-XX&cid=XXXXXXXXXXXXXX&an=MyApplicatii&av=1.1.179&aid=XXX.XXXXX&aip=1&sr=1920x1080&vp=1920x1030&ul=en&sd=32-bits&uid=XXXXXXXX&t=event&ec=Activities&ea=Document%20edited&el=Local&qt=8012&z=2082723772  

User-Agent (UA) header is used to sent platform information to GA service. As you see from example it's something like:
Mozilla/5.0 (Windows NT 10.0; Win64; X64; [Vendor]; [Device])

The problem is with detecting that user works on Windows 11 host.

According UA format platform version for Windows system should be Windows NT [Major Version].[Minor Version]. But for Windows 10 and Windows 11 there is no difference in major and minor version numbers, both are 10.0. The difference only in build number (Windows 11 starts from 22000) that doesn't take part in UA format.

Is there some way how to inform Google Analytics service about correct OS version where application run?

P.S.: For browsers there is new standard that substitutes UA it is User-Agent Client Hint. But seems GA service does not support it.

P.P.S.: I've found the same question on Google Support but without answer. And the same on Reddit

Advance a Interpolation

Posted: 18 Jun 2022 04:03 AM PDT

Hi I would like to use Universal Kriging in my code. For this I have data that is structured as follows:

      Latitude   Longitude  Altitude          H2        O18        Date    Year  month       dates  a_diffO       O18a  0    45.320000  -75.670000     114.0  -77.500000 -11.110000  2004-09-15  2004.0    9.0  2004-09-15   -0.228 -10.882000  1    48.828100    9.200000     314.0  -31.350000  -4.880000  2004-09-15  2004.0    9.0  2004-09-15   -0.628  -4.252000  2    51.930000  -10.250000       9.0  -18.800000  -3.160000  2004-09-15  2004.0    9.0  2004-09-15   -0.018  -3.142000  3    48.248611   16.356389     198.0  -45.000000  -6.920000  2004-09-15  2004.0    9.0  2004-09-15   -0.396  -6.524000  4    50.338100    7.600000      85.0  -19.200000  -3.190000  2004-09-15  2004.0    9.0  2004-09-15   -0.170  -3.020000    

You can find my data here:https://wetransfer.com/downloads/9c02e4fc1c2da765d5ee9137e6d7df4920220618071144/8f450e

I want to interpolate the data (Latitude, Longitude, Altitude and O18) with Universal Kriging and use the height as a drift function.

So far I have programmed this here but I am not getting anywhere, e.g. I don't know how to effectively use the height as a drift function and the information from the Pykrige documentation is of limited help:

from traceback import print_tb  from typing_extensions import Self  import numpy as np  from pykrige.uk import UniversalKriging  from pykrige.kriging_tools import write_asc_grid  import pykrige.kriging_tools as kt  import matplotlib.pyplot as plt  from mpl_toolkits.basemap import Basemap  from matplotlib.patches import Path, PathPatch  import pandas as pd  from osgeo import gdal     def load_data():      df = pd.read_csv(r"File")      return(df)    def get_data(df):      return {          "lons": df['Longitude'],          "lats": df['Latitude'],          "values": df['O18'],      }    def extend_data(data):      return {          "lons": np.concatenate([np.array([lon-360 for lon in data["lons"]]), data["lons"], np.array([lon+360 for lon in data["lons"]])]),          "lats": np.concatenate([data["lats"], data["lats"], data["lats"]]),          "values":  np.concatenate([data["values"], data["values"], data["values"]]),      }    def generate_grid(data, basemap, delta=1):      grid = {          'lon': np.arange(-180, 180, delta),          'lat': np.arange(np.amin(data["lats"]), np.amax(data["lats"]), delta)      }      grid["x"], grid["y"] = np.meshgrid(grid["lon"], grid["lat"])      grid["x"], grid["y"] = basemap(grid["x"], grid["y"])      return grid    def interpolate(data, grid):      uk = UniversalKriging(          data["lons"],          data["lats"],          data["values"],          variogram_model='exponential',          verbose=True,          drift_terms=["point_log"],      )      return uk.execute("grid", grid["lon"], grid["lat"])    def prepare_map_plot():      figure, axes = plt.subplots(figsize=(10,10))      basemap = Basemap(projection='robin', lon_0=0, lat_0=0, resolution='h',area_thresh=1000,ax=axes)       return figure, axes, basemap    def plot_mesh_data(interpolation, grid, basemap):      colormesh = basemap.contourf(grid["x"], grid["y"], interpolation,32, cmap='RdBu_r') #plot the data on the map. plt.cm.RdYlBu_r      color_bar = basemap.colorbar(colormesh,location='bottom',pad="10%")       df = load_data()  base_data = get_data(df)  figure, axes, basemap = prepare_map_plot()  grid = generate_grid(base_data, basemap, 90)  extended_data = extend_data(base_data)  interpolation, interpolation_error = interpolate(extended_data, grid)  plot_mesh_data(interpolation, grid,basemap)  plt.show()    

I now only use universal kriging and create these images:

enter image description here

I get the expected error: ValueError: Must specify location(s) and strength(s) of point drift terms.

I just know that I have to create a grid with the height, but I don't know how and I don't know how to make the drift dependent on the altitude. The altitude formula is:

-0.2 (O18)/100 m(altitude)

where 100 m represents 100 m hight difference.

The interesting thing is that there is this website with examples: however, I am too inexperienced in coding to understand the examples and to transfer them to my example: https://python.hotexamples.com/examples/core/-/calc_cR/python-calc_cr-function-examples.html

I've been trying to solve these problems for 3 weeks now, but I'm really getting nowhere.

React Fiber ThreeJs components rendering issues ( undefined data Line2.computeLineDistances )

Posted: 18 Jun 2022 04:04 AM PDT

I have reproduced 3 components of my React App in the following codesandbox

As you can see in the demo, i have 3 react threejs components, rotating, moving and zooming with no issues.

The problem is in my local app with exactly the same code App.js

export default function App() {    return (      <FullScreenCanvas>        <OrbitControls enableZoom={true} enablePan={true} enableRotate={true} />        <Suspense fallback={null}>          <Thing />          <CircleLine linewidth={2} />          <Triangle color="#ff2060" scale={0.009} rotation={[0, 0, Math.PI / 3]} />        </Suspense>      </FullScreenCanvas>    )  }  

This is the error i see in my console => Uncaught TypeError: Cannot read properties of undefined (reading 'data') at Line2.computeLineDistances

I have found out that the problem was caused by the react three fiber version, in fact if i downgraded in my app from "@react-three/fiber":` "^8.0.20", to the codesandbox demo "@react-three/fiber": "^7.0.24", the error disappeared and it works like in the demo. so my question is why i have this error with react/three/fiber 8.0.20

enter image description here

Calculating Tax Based on Cart Subtotal in Woocommerce

Posted: 18 Jun 2022 04:04 AM PDT

I want to calculate tax based on the entire cart subtotals. So in my case, if the subtotal is < 1000, the Tax need to be 5% If the subtotal is >=1000, the Tax needs to be 12%

I am having two classes Reduced rate - 5%, Standard - 12%

    add_action( 'woocommerce_product_variation_get_tax_class', 'wp_check_gst', 1, 2 );      function wp_check_gst( $tax_class, $product )       {                    $subtotal = 0;              foreach ( WC()->cart->get_cart() as $cart_item ) {                      $subtotal += $cart_item[ 'data' ]->get_price( 'edit' ) * $cart_item[ 'quantity' ];                                    }              if ( $subtotal >= 1000 )              {                  $tax_class = "Standard";              }              if ( $subtotal < 1000 )              {                  $tax_class = "Reduced rate";              }          return $tax_class;      }  

I use this above code, which seems to be not working?? What am I missing?

Tracking with the new Google Analytics 4 (GA4) server-side

Posted: 18 Jun 2022 04:04 AM PDT

Google Analytics 4 (GA4) was recently released and made the default for new properties on the Google Analytics dashboard. I was checking it out and it looks great. We report a lot of our data to Google Analytics via our Node.js server as opposed to client-side using a library called universal-analytics (https://www.npmjs.com/package/universal-analytics), which works very well.

We want to start using GA4 asap but we cannot find any documentation on how to send events to a GA4 property server-side. There are only client-side examples and those don't seem to work at all on a server.

Simply put, what is the serverside equivalent for the following?

<!-- Global site tag (gtag.js) - Google Analytics -->  <script async src="https://www.googletagmanager.com/gtag/js?id=G-ABC123ABC123"></script>  <script>    window.dataLayer = window.dataLayer || [];    function gtag(){dataLayer.push(arguments);}    gtag('js', new Date());      gtag('config', 'G-ABC123ABC123');  </script>  

Anyone had success with this?

exec: "gcc": executable file not found in %PATH% when trying go build

Posted: 18 Jun 2022 04:06 AM PDT

I am using Windows 10. When I tried to build Chaincode it reported this error

# github.com/hyperledger/fabric/vendor/github.com/miekg/pkcs11   exec: "gcc": executable file not found in %PATH%  

My chaincode imports:

import (      "fmt"      "strconv"        "github.com/hyperledger/fabric/core/chaincode/shim"      pb "github.com/hyperledger/fabric/protos/peer"  )  

It's running fine in Docker.

Is there a way to check if the react component is unmounted?

Posted: 18 Jun 2022 04:03 AM PDT

I have a usecase where i need to unmount my react component. But in some cases, the particular react component is unmounted by a different function. Hence, I need to check if the component is mounted before unmounting it.

No comments:

Post a Comment