2023-06-30

What do the following two Google Map error messages mean? [closed]

I am trying to get an existing map to display in a CMS collection in Webflow. I did get the messages to display individually with two different attempts on that particular blog post. Thank you for any help.

I tried using the Google Maps embed code, but Webflow rejected the iframe code and wanted a standard weblink starting with http. I deleted all but the http from the code and got this error: "Google Maps Platform rejected your request. Invalid request. Unexpected parameter 'ehbc'"

The second error came from trying the actual browser URL of the map: "Google Maps Platform rejected your request. Invalid request. Unexpected parameter 'll'" I wanted the map to display in the blog post.

Also, this map was created by someone else (if that makes a difference), but I don't think I'm getting a permissions error.



Stream the sound of a sph0645 I2S mic in fm station on a Raspberry pi with the PiFmRds lib

I'm trying to stream the sound from a raspberry pi of a sph0645mic in fm with the PiFmRds librairy

Here's what I've tried:

after the install of the mic here's what I have:

$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 1: sndrpii2scard [snd_rpi_i2s_card], device 0: simple-card_codec_link snd-soc-dummy-dai-0 [simple-card_codec_link snd-soc-dummy-dai-0]

then I can record normally without any problems with this command :

$ arecord -D plughw:0 -c1 -r 48000 -f S32_LE -t wav -V mono -v file.wav

I can stream the file :

$ sox -t mp3 /home/thib/file.wav -t wav - | sudo /home/thib/PiFmRds/src/pi_fm_rds -audio -

but here is my problem : I would like stream the direct output of my mic. For that I've tried :

$ sudo arecord -D plughw:1 -c1 -r 48000 -f S32_LE -t wav  | sudo ./pi_fm_rds -audio -

after that I've tried to use the loopback fuction but I don't have any sound in my receptor.

$sudo modprobe snd-aloop
 arecord -l
**** List of CAPTURE Hardware Devices ****
card 1: sndrpii2scard [snd_rpi_i2s_card], device 0: simple-card_codec_link snd-soc-dummy-dai-0 [simple-card_codec_link snd-soc-dummy-dai-0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 3: Loopback [Loopback], device 0: Loopback PCM [Loopback PCM]
  Subdevices: 8/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
card 3: Loopback [Loopback], device 1: Loopback PCM [Loopback PCM]
  Subdevices: 8/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
  
$ sudo arecord -D plughw:3 -c1 -r 48000 -f S32_LE -t wav  | sudo /home/thib/PiFmRds/src/pi_fm_rds

I've also tried to use a program like pure data but nothing change... Do you have any ideas ?



2023-06-29

psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL: database "

I tried running a postgres server to viewing my databases with TablePlus after not doing so for a while.

Running the server:

brew services start postgresql
Warning: Formula postgresql was renamed to postgresql@14.
Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; `/bin/launchctl bootstrap gui/501 /Users/eliott/Library/LaunchAgents/homebrew.mxcl.postgresql@14.plist` exited with 5.
➜  ~ brew services restart postgresql
Warning: Formula postgresql was renamed to postgresql@14.
Stopping `postgresql@14`... (might take a while)
==> Successfully stopped `postgresql@14` (label: homebrew.mxcl.postgresql@14)
==> Successfully started `postgresql@14` (label: homebrew.mxcl.postgresql@14)

When I ran psql it returned this error:

psql: error: connection to server on socket “/tmp/.s.PGSQL.5432” failed: No such file or directory Is the server running locally and accepting connections on that socket?

… and something similar in TablePlus.

The version was 14.7 at this point so decided to install 15 with homebrew brew install postgresql@15 (though the version is now only 14.8) but now the error has changed to:

psql: error: connection to server on socket “/tmp/.s.PGSQL.5432” failed: FATAL: database “eliott” does not exist

in TablePlus:

connection to server at “127.0.0.1”, port 5432 failed: FATAL: database “eliott” does not exist

When I run psql -l, the following is returned:

List of databases
   Name    | Owner  | Encoding | Collate | Ctype | Access privileges 
-----------+--------+----------+---------+-------+-------------------
 postgres  | eliott | UTF8     | C       | C     | 
 template0 | eliott | UTF8     | C       | C     | =c/eliott        +
           |        |          |         |       | eliott=CTc/eliott
 template1 | eliott | UTF8     | C       | C     | =c/eliott        +
           |        |          |         |       | eliott=CTc/eliott
(3 rows)

EDIT: the CLI works now but what I didn't realise before from running psql -l is that all the databases I used to have are gone now. I'm guessing I may have deleted them by accident(?) or is there the possibility that postgres/tableplus is looking for the wrong path?



2023-06-28

API call returns url and not a value I need [duplicate]

async function getSwInfo(url) {
  try {
    const data = await fetch(url).then((res) => res.json());
    console.log(data);
    personData(data.results);
  } catch (error) {
    console.log(error);
  }
};

function personData(data) {
  const person = data[0];
  let personName = `
    <h2 id="name">${person.name}</h2>
    <p class="aurebesh">${person.name}</p>`;
  nameInfo.innerHTML = personName;
  let personBio = `
    <ul>
      <li><h3>Home Planet: </h3><p>${person.homeworld}</p></li>
      <li><h3>Birth Year: </h3><p>${person.birth_year}</p></li>
      <li><h3>Gender: </h3><p>${person.gender}</p></li>
      <li><h3>Species: </h3><p>${person.species}</p></li>
      <li><h3>Height: </h3><p>${person.height}</p></li>            
      <li><h3>Weight: </h3><p>${person.mass}</p></li>
      <li><h3>Hair Color: </h3><p>${person.hair_color}</p></li>
      <li><h3>Eye Color: </h3><p>${person.eye_color}</p></li>
    </ul>`;
  personInfo.innerHTML = personBio;
};

So far when I call my api it shows the information I want, but for the homeworld and species the value is a link to another URL. So that's what I keep getting back, how do I extract the homeworld 'name' and species 'name' from those?



Sagemaker environment variable with .env

[Background]

I am used to use xx.py and defining a .env file in python project in Pycharm, and by doing

import os
os.environ['abc']

I will get the 'abc' variable defined in .env file.

[Question]

Now I need to work with sagemake studio, what is the best practice to manage env var with sagemake?

I tried to create a .env file, but got a rename error. Does it mean using .env is not a good try in sagemaker?

Rename Error
Cannot rename file or directory '/xx/untitled.txt'


Why splash screen is not working in Kotlin app?

I am trying to make a splash screen in XML file but it is not working in emulator and there is only white screen in app view.

Here is activity_splash_screen.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity_Splash_Screen"    android:background="@color/black"
    >

    <ImageView
        android:id="@+id/image1"
        android:layout_width="150dp"
        android:layout_height="150dp"

        android:layout_centerInParent="true"
        android:src="@drawable/anadol" />

</RelativeLayout>

Activity_Splash_Screen.kt file:

package com.example.heytaksi

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.heytaksi.databinding.ActivitySplashScreenBinding
import java.util.zip.Inflater

class Activity_Splash_Screen : AppCompatActivity() {
    lateinit var binding: ActivitySplashScreenBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivitySplashScreenBinding.inflate(layoutInflater)
        val b=binding.root
        binding.image1.alpha=0f
        binding.image1.animate().setDuration(1500).alpha(1f).withEndAction {
            val intent=Intent(this,MainActivity::class.java)
            startActivity(intent)
            overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out)
            finish()
        }

    }
}

AndroidManifext.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HeyTaksi"
        tools:targetApi="31">

        <activity
            android:name=".MusteriGiris"
            android:exported="false" />
        <activity
            android:name=".Activity_Splash_Screen"
            android:exported="true"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="false">

        </activity>
    </application>

</manifest>

The expectation was seeing the picture for a while before opening of application's main screen but it is staying in a white screen.



2023-06-27

How to indicate high wicks of more than 10%

This is my code, but it's not working, I don't understand why!!
Thanks for your help.
Peio

//@version=4
condition = high  close
wickPercentage = (high - close) * 100 / close 
if wickPercentage > 10
    plotValue =  wickPercentage >10 ? wickPercentage : na
plot(wickPercentage ? close : na, color=color.rgb(76, 134, 175), style=plot.style_columns) 

All candles are displayed on the chart, minus the candles without a high wick. And I would like to indicate that candles with a high wick above 10%



Pulling a sed script into a perl program

I need to shorten function names, so I identify them and produce a really long sed script that looks like this:

s/\breally_long_function_name1\b/A00128/g
s/\breally_long_function_name2\b/A00060/g
s/\breally_long_function_name3\b/A00035/g
s/\breally_long_function_name4\b/A00342/g
s/\breally_long_function_name5\b/A00203/g
...

and then call it like this:

`sed -i.bak -f $sedscript *`

The problem is that I can't depend on sed being able to handle those instances of \b and it seems messy. Instead of writing out that sed script, I want to put it into an array and then do something like this for each line of each file I need to process:

$targetline =~ $processing;

My problem is that using $processing like that won't work and the qoperators don't seem to do the job. How do I massage this to get the substitution in $processing processed and the result put in $targetline?

Note: I used Perl sed file inside script and the answer from @ron-bergin there to get this far.

The application for this is to convert modern-ish C code into a form that can be compiled by ancient C compilers. The existing script is at https://gitlab.com/DavidGriffith/frotz/-/blob/master/src/misc/snavig.pl where it's used to prepare source code for compilation by KCC, an early C compiler for PDP-10 mainframes. One of its quirks is that some symbols are limited to being 6 characters in length. Background on this is at https://github.com/PDP-10/panda/blob/master/files/kcc-6/kcc/user.doc#L519.

Here's a fragment from a source file before processing:

void reset_memory(void)
{
        if (story_fp != NULL)
                fclose(story_fp);
        story_fp = NULL;

        if (undo_diff) {
                free_undo(undo_count);
                zfree(undo_diff);
                zfree(prev_zmp);
        }

        undo_diff = NULL;
        undo_count = 0;
        prev_zmp = NULL;

        if (zmp)
                zfree(zmp);
        zmp = NULL;
} /* reset_memory */

After processing, it looks like this:

void A00156(void)
{
        if (A00144 != NULL)
                fclose(A00144);
        A00144 = NULL;

        if (undo_diff) {
                A00155(A00148);
                zfree(undo_diff);
                zfree(A00147);
        }

        undo_diff = NULL;
        A00148 = 0;
        A00147 = NULL;

        if (zmp)
                zfree(zmp);
        zmp = NULL;
} /* A00156 */

Once processed like this, it is proven to compile with KCC and run on TOPS20 on both emulated and real PDP-10 hardware.

With my attempts to not use an external sed, instead of doing anything, I get nothing and then a flood of this when pressing ^C:

Use of uninitialized value $targetline in pattern match (m//) at src/misc/snavig.pl line 181, <$targetfile> line 104.
Use of uninitialized value $targetline in pattern match (m//) at src/misc/snavig.pl line 181, <$targetfile> line 104.
Use of uninitialized value $targetline in pattern match (m//) at src/misc/snavig.pl line 181, <$targetfile> line 104.
Use of uninitialized value $targetline in pattern match (m//) at src/misc/snavig.pl line 181, <$targetfile> line 104.


2023-06-26

why jenkins showing git maven not found error even git and maven installed?

`hi there,hope you are doing well. I am new to Jenkins, and errors are encountered during practice. i took a sample project. error and jenkins file content posted below please have a look into it. feel free to ask if you have any questions. please suggest solution.

Thank you for your support and help.`

Error as below

Started by user admin
Obtained Jenkins-decnew from git https://github.com/kdhani/myweb-p1.git
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/pipeline1
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
**Selected Git installation does not exist. Using Default
**The recommended git tool is: NONE
using credential gitid
 > /usr/bin/git rev-parse --resolve-git-dir /var/lib/jenkins/workspace/pipeline1/.git # timeout=10
Fetching changes from the remote Git repository
 > /usr/bin/git config remote.origin.url https://github.com/kdhani/myweb-p1.git # timeout=10
Fetching upstream changes from https://github.com/kdhani/myweb-p1.git
 > /usr/bin/git --version # timeout=10
 > git --version # 'git version 2.40.1'
using GIT_ASKPASS to set credentials 
 > /usr/bin/git fetch --tags --force --progress -- https://github.com/kdhani/myweb-p1.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 (refs/remotes/origin/master)
 > /usr/bin/git config core.sparsecheckout # timeout=10
 > /usr/bin/git checkout -f c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 # timeout=10
Commit message: "Update Jenkins-decnew"
 > /usr/bin/git rev-list --no-walk c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Git Checkout)
[Pipeline] git
Selected Git installation does not exist. Using Default
The recommended git tool is: NONE
using credential gitid
 > /usr/bin/git rev-parse --resolve-git-dir /var/lib/jenkins/workspace/pipeline1/.git # timeout=10
Fetching changes from the remote Git repository
 > /usr/bin/git config remote.origin.url https://github.com/kdhani/myweb-p1.git # timeout=10
Fetching upstream changes from https://github.com/kdhani/myweb-p1.git
 > /usr/bin/git --version # timeout=10
 > git --version # 'git version 2.40.1'
using GIT_ASKPASS to set credentials 
 > /usr/bin/git fetch --tags --force --progress -- https://github.com/kdhani/myweb-p1.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > /usr/bin/git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 (refs/remotes/origin/master)
 > /usr/bin/git config core.sparsecheckout # timeout=10
 > /usr/bin/git checkout -f c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 # timeout=10
 > /usr/bin/git branch -a -v --no-abbrev # timeout=10
 > /usr/bin/git branch -D master # timeout=10
 > /usr/bin/git checkout -b master c8f4db412eaf023b2ae78c1a9e168db17ea6ac73 # timeout=10
Commit message: "Update Jenkins-decnew"
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Maven Build)
[Pipeline] sh
**+ mvn clean package
**/var/lib/jenkins/workspace/pipeline1@tmp/durable-7e042d4d/script.sh: line 1: **mvn: command not found**
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (deploy-dev)
Stage "deploy-dev" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 127
Finished: FAILURE
REST API
Jenkins 2.401.1

jenkins file content from here :)

pipeline{

    agent any
    
    environment{
        PATH = "/opt/maven3/bin:$PATH"
    }
    stages{
        stage("Git Checkout"){
            steps{
                git credentialsId: 'gitid', url: 'https://github.com/kdhani/myweb-p1.git'
            }
        }
        stage("Maven Build"){
            steps{
                sh "mvn clean package"
                sh "mv target/*.war target/myweb.war"
            }
        }
        stage("deploy-dev"){
            steps{
                sshagent(['tomcat-new']) {
                    
                sh """
                    scp -o StrictHostKeyChecking=no target/myweb.war  ec2-user@172.31.33.108:/home/ec2-user/apache-tomcat-9.0.63/webapps/
                    
                    ssh ec2-user@172.31.33.108 /home/ec2-user/apache-tomcat-9.0.63/bin/shutdown.sh
                    
                    ssh ec2-user@172.31.33.108 /home/ec2-user/apache-tomcat-9.0.63/bin/startup.sh
                
                """
            }
            
            }
        }
    }
}



2023-06-25

Finding (null) Value in array

The standard way to check if a value is in an array in BigQuery is using IN UNNEST(...). For example:

SELECT 2 IN UNNEST([0, 1, 1, 2, 3, 5]) AS contains_value;

What is the suggested way to check if the NULL value is in an array? Is there a more direct way than doing:

SELECT EXISTS(SELECT 1 FROM UNNEST([0,1,1,2,3,null,5]) v WHERE v IS NULL)

Is there a more straightforward way for this? And if someone on the BigQuery team or someone familiar with performance/optimizations: does it matter if I add a LIMIT 1 to the sub-select -- i.e., does the exists operator short-circuit automatically once it finds a result or do I have to manually add in a LIMIT 1 to the subquery?



2023-06-24

Jenkins pipeline for parallel cross browser testing

I need to find solution/s for next case. There is selenoid in docker which runs browsers in containers, the tests should be run in parallel for some browsers. I made pipeline in Jenkins for that goal. And all tests run in parallel for browsers but they work with the same workspace and I got errors from time to time. How can I make Jenkins settings or pipeline configuration to have each browser branch with its own workspace or thomething else to avoid conflicts.

pipeline {
    agent any
    tools {
        maven 'MAVEN_HOME'
    }
    stages {
        stage('setup parameters') {
            steps {
                script {
                    properties([
                        parameters([
                        choice(
                            choices: ['chrome', 'firefox', 'all'],
                            name: 'browser'
                        )
                    ])
                    ])
                }
            }
        }
        stage('clone code') {
            steps {
                echo 'git'
                git branch: 'feature/selenoid-integration', credentialsId: '......', url: 'https://github.com/.../selenide-web-test-project'
            }
        }
        stage('test') {
            steps {
                script {
                    if (browser.equals("chrome")) {
                        echo 'chrome'
                        bat 'mvn clean -Dbrowser.type=chrome test'
                    }
                    if (browser.equals("firefox")) {
                        echo 'firefox'
                        bat 'mvn clean -Dbrowser.type=firefox test'
                    }
                    if (browser.equals("all")) {
                        echo 'all'
                        parallel(
                        chrome: {
                            bat 'mvn clean -Dbrowser.type=chrome test'
                        },
                        firefox: {
                            bat 'mvn clean -Dbrowser.type=firefox test'
                        }
                        )
                    }
                }
            }
        }
    }
}


2023-06-23

how to add support for "?" (query) in path for apple-app-site-association file?

"apple-app-site-association" file content:

{

    "appclips": {
        "apps": ["**********.com.project.example.Clip"]
    },
    "applinks": {
        "apps": ["**********.com.project.example"],
        "details": [
          {
            "appID": "**********.com.project.example",
            "paths": [ "/event/*", "/ticket?v=*" ]
          }
        ]
    }
}

File is already set at "https://< fully qualified domain>/.well-known/apple-app-site-association"

problem I'm facing is that it is working for

"https://< fully qualified domain>/event/EVENT-ID",

but it is not invoking app for

"https://< fully qualified domain>/ticket?v=VOLUME-ID"

Is it because of "?" or I'm missing some thing?



Serving SPA with Golang and Chi router enters a loop

I´m trying to serve a SPA with Golang and solving the 404 error became a challenge.

  • In the init() func I buffered into memory the index.html file.
  • I created a indexHandler that returns the index file buffered.
  • I call the indexHandler in the router.NotFound() func so the route is returned to the SPA.
  • I serve the rest of the static files with FileServer.

The problem is that it seems to be in a loop, when I try to access the app in the browser, it reloads itself indefinitely.

package main

import (
    "log"
    "net/http"
    "os"
    "path/filepath"
    "time"

    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"

    "github.com/joho/godotenv"
)

var indexBuffer []byte

func main() {   
    r := chi.NewRouter()
    
    r.Use(middleware.RequestID)
    r.Use(middleware.RealIP)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    fs := http.FileServer(http.Dir(os.Getenv("FRONTEND_PATH")))
    r.Handle("/app/static/*", http.StripPrefix("/app/static/", fs))

    apiRouter := chi.NewRouter()
    apiRouter.Get("/cargas", handlerCargas)

    r.Mount("/app/api", apiRouter)

    r.NotFound(indexHandler)

    log.Fatal(http.ListenAndServe(":8000", r))
}

func init() {
    err := godotenv.Load()
    if err != nil {
        log.Fatal("Erro ao ler .env verifique!")
    }

    indexBuffer, err = os.ReadFile(filepath.Join(os.Getenv("FRONTEND_PATH"), "index.html"))
    if err != nil {
        log.Fatal("Erro ao tentar bufferizar a index na init().")
    }
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    w.Write(indexBuffer)
}

I´m expecting index.html to be served by the indexHandler and the rest of the files be served by the FileServer and errors of page not found be handled by the SPA.



2023-06-22

Inconsistency on module in IPython

IPython seems inconsistent here:

In [1]: import sys

In [2]: sys.version
Out[2]: '3.10.11 (main, May 16 2023, 00:28:57) [GCC 11.2.0]'

In [4]: type(sys)
Out[4]: module

In [5]: type(module)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 type(module)

NameError: name 'module' is not defined

In [6]: type(type(sys))
Out[6]: type

How can something that is not defined be a type and have a type?

I found this after discovering that no class module exists, although, if I import some module of mine, it automatically inherits attributes

 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',

What are these attributes inherited from?



2023-06-21

Can you attach a firewall rule to a instance template

Lets say I have the following instance template:

resource "google_compute_instance_template" "label_studio_template" {
  name         = "label-studio-template"
  machine_type = "e2-micro"  # Free tier instance
  tags         = ["label-studio-server-template"]
  
  disk {
    auto_delete = false
    source_image = "debian-11-bullseye-v20230509"
  }

  network_interface {
    network = "default"
    access_config {
      // Public IP
      nat_ip = google_compute_address.standard.address
      network_tier = "STANDARD"
    }
  }
  metadata = {
    label_studio_username   = var.label_studio_username
    label_studio_password   = var.label_studio_password
    label_studio_user_token = var.label_studio_user_token
  }
  metadata_startup_script = file("${path.module}/compute_metadata.sh")
}

is it possible to use the tags here to attach firewall policies to all instances that are created from the template?



2023-06-20

Input clientWidth and scrollWidth are always equal

I'm using Vuetify text-fields and want to display a tooltip containing the content if the content is greater than the field width (user needs to scroll). The tooltip should only appear on hover (default behaviour). I started with the following

(Playground)

<script setup lang="ts">
  import { ref, computed } from "vue";

  const currentValue = ref("");
  const textFieldComponent = ref<VTextField>();

  const isTextFieldCuttingOffContent = computed(() => {
    if (!textFieldComponent.value) {
      return false;
    }

    if (!currentValue.value) {
      return false;
    }

    return (
      textFieldComponent.value.$el.clientWidth <
      textFieldComponent.value.$el.scrollWidth
    );
  });
</script>

<template>
  <v-container style="width: 300px">
    <v-tooltip :text="currentValue" :disabled="!isTextFieldCuttingOffContent">
      <template v-slot:activator="{ props }">
        <div v-bind="props">
          <v-text-field
            ref="textFieldComponent"
            label="label goes here"
            v-model="currentValue"
          />
        </div>
      </template>
    </v-tooltip>
  </v-container>
</template>

I also tried to use a watcher instead of a computed prop (Playground)

The problem is that isTextFieldCuttingOffContent always returns false because clientWidth and scrollWidth are always equal. Do you have any ideas what's wrong or missing?



2023-06-19

How to read parent attributes in Vue3 typescript

In the child component I am trying to write, I need to get the parent object. The commented out lines don't work.

AccordionState is:

export type AccordionKeys = | "open" | "disabled";

export type AccordionState = {
    [key: string]: {[key in AccordionKeys]: boolean; };
}

The child code is:

<script lang="ts">
    import { AccordionState } from "@/types/global";
    import { defineComponent, useAttrs } from "vue";

    export default defineComponent({
      name: "AccordionPane",
      props: {
        panelName: {
          type: String,
          required: true,
        },
      },
      computed: {
        open(): boolean {
          // const attrs = useAttrs();
          // const state = attrs.state as AccordionState;
          // return state[this.panelName].open && !state[this.panelName].disabled;
          return true;
        },
    disabled(): boolean {
      // const attrs = useAttrs();
      // const state = attrs.state as AccordionState;
      // return state[this.panelName].disabled;

      return false;
    },

The parent component. The computed getProps here shows that I am defining prop.state correctly, but the commented code in the AccordionPane does not work. the variable "state" is null. I don't see a lot of typescript examples online, and the javascript examples are so unstructured I don't know how to adapt them to typescript.

  <template>
    <div class="accordionControl">
      <slot ref="content"></slot>
    </div>
    <textarea class="debug" v-model="getProps"></textarea>
  </template>

  <script lang="ts">

  import { type AccordionState } from '@/types/global';
  import { defineComponent, type PropType } from 'vue';

  export default defineComponent({
    name: "AccordionControl",
    props: {
      state: {
        type: Object as PropType<AccordionState>,
        required: true,
      },
      isVert: {
        type: Boolean,
        default: false,
      },
      allOpen: {
        type: Boolean,
        default: false,
      }
    },
    computed: {
      getProps(): string {
        return JSON.stringify(this.$props, null, '  ');
      }
    }
  });
  </script>

The following link is one of the javascript examples and it works.

https://play.vuejs.org/#eNp1kDFrwzAQhf/K9RY5YGTaMbUL2ToWOnSoOtjxORhkSUhyl5D/3pMVXCcQ0KDHvfse9854cE7+zoR7rMPRjy5CoDi7N2XGyVkf4QyeBrjA4O0Egq1CGWWO1oQIUzhBk+aFeCetLXy1oc/Pet0/id2K+dRjTz5TFMoq6xSt8DUR6yrnczKLSJPTbSRWAPV1uWsUviiEfcufZ/7k6ZXFoq7WPSzxPyJdtyFKKW+8S+Kj63saRkMf3rpQwhzoEKMPd31oiuCSg9vY+Itv0YmfHZ+XDO2y2KyMgstJNVpNUttTsQBkV2ajbHm86QQvf3ztlVg=



2023-06-18

When I create a project I did " git push -u origin master" push fail

I get this error:

To https://git.misynergy.com/imal/eureka-registry.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://git.misynergy.com/imal/eureka-registry.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

When I execute the command:

git push -u origin master


Migrate CRA to Vite causes "Cannot access 'store' before initialization" using Redux Toolkit

I've googled for days, and I just can't seem to solve the bug. So here I go. I know it's all about circular dependencies, but it doesn't seem like I can just rewrite it.

First I'm initializing the store in its own file

/redux/store
const store = configureStore({ ... })
export default store;

Then in an API file, I use a util function (coming later) that is used in multiple places around the app. Here is an example

/api/configApi
import { createApi } from '@reduxjs/toolkit/dist/query/react';
import { getConfig } from 'utils/getConfig';

const token = getConfig(env.key);
export const configApi = createApi({ token, ... })

Then I am using store again, and sadly before it is initialized

/utils/getConfig
import store from 'redux/store'

export function getConfig(key) {
  const config = store.getState()... // <-- Cannot access store before initialization
}

And the app itself

/src/index.tsx
... imports ...

const app = (
  <StrictMode>
    <ReduxProvider store={store}>
      <App />
    </ReduxProvider>
  </StrictMode>

ReactDOM.render(app, document.getElementById('root'));

All this about that it is a circular dependency makes sense to me. But I can't just make an export from another file. I have to use store in getConfig

How can this be solved?

It works smoothly using react-scripts but blocks the whole procedure migrating to Vite.



Wall time with milliseconds in Linux C

Having found many quite old questions about this subject, I wonder if getting the current time in Linux C with year, month, day, hours, minutes, seconds and milliseconds still is so cumbersome these days.

I searched a lot but there are either structs holding the wall time without milliseconds, or structs returning the current time in milliseconds that I have to convert into wall time separately, or functions that return seconds and milliseconds in extra fields which would be ok to use but isn't what I'd call elegant.

Does a time struct like this

struct TIME_WITH_ALL_FIELDS now;
get_now(&now);
print ("today is ...",
  now.year, now.month, now.day,
  now.hour, now.minute, now.second, now.millisecond);

really not exist yet?



mysql nested level query getting very slow

I have a MySQL query containing two columns that cause a delay of 25 seconds when the query is wrapped, while the inner query runs fine within 2 seconds. Both columns have already been indexed, and I have tried reducing joins to optimize the query, also replaced subqueries with joins, which reduced times by 8,9 seconds. but it did not provide significant performance improvements. Here is the original nested SQL query:

SELECT
    first_base.case_id_c
FROM (
    SELECT DISTINCT
        (cc.case_id_c),
        (
            SELECT CONCAT(u.first_name, ' ', u.last_name)
            FROM users u
            WHERE u.id = cc.user_id1_c
        ) AS Case_Advocate,
        (
            SELECT CONCAT(u.first_name, ' ', u.last_name)
            FROM users u
            WHERE u.id = cc.user_id2_c
        ) AS Practitioner,
        (
            SELECT CONCAT(u.first_name, ' ', u.last_name)
            FROM users u
            WHERE u.id = cc.user_id3_c
        ) AS Tax_Preparer,
        c.id,
        rtpc.service_level_c AS tp_service_level, -- causing delay 
        cc.tax_preparation_level_c AS client_tax_prep_service_level,
        rtpc.id_c AS 'TaxPrepID',-- causing delay 
        (
            CASE WHEN rtp.deleted IS NULL THEN 0 ELSE rtp.deleted
        END
        ) AS TP_DELETED
    FROM contacts c
    LEFT JOIN contacts_cstm cc ON cc.id_c = c.id
    LEFT JOIN contacts_reso_resolutions_1_c crr1c ON crr1c.contacts_reso_resolutions_1contacts_ida = cc.id_c
    LEFT JOIN reso_resolutions_cstm AS rrc ON rrc.id_c = crr1c.contacts_reso_resolutions_1reso_resolutions_idb
    LEFT JOIN reso_resolutions AS rr ON rr.id = rrc.id_c
    LEFT JOIN contacts_reso_ancillary_services_1_c AS cras1c ON cras1c.contacts_reso_ancillary_services_1contacts_ida = c.id
    LEFT JOIN reso_ancillary_services_cstm AS rasc ON rasc.id_c = cras1c.contacts_reso_ancillary_services_1reso_ancillary_services_idb
    LEFT JOIN reso_ancillary_services AS ras ON ras.id = rasc.id_c
    LEFT JOIN contacts_reso_tax_preparation_1_c AS crtp1c ON crtp1c.contacts_reso_tax_preparation_1contacts_ida = c.id
    LEFT JOIN reso_tax_preparation_cstm AS rtpc ON rtpc.id_c = crtp1c.contacts_reso_tax_preparation_1reso_tax_preparation_idb
    LEFT JOIN reso_tax_preparation AS rtp ON rtp.id = rtpc.id_c
    WHERE c.deleted <> 1 AND cc.ctax_status_c = 'Active Service' AND preferred_language NOT LIKE '%en_us%'
) AS first_base

The problematic columns in the query are:

rtpc.id_c AS 'TaxPrepID',
rtpc.service_level_c AS tp_service_level,

I also ran an EXPLAIN query on the SQL but it did not seem to help much. The ctax_status_c column only appeared in the WHERE clause with the value 'Active Service'. Is there anything else I can do to optimize the query performance?

enter image description here



2023-06-17

Delete images from automatically scrolling Row in Flickable

Background.qml

import QtQuick
Flickable{
    id:flickable
    anchors.fill:parent
    contentWidth:row.implicitWidth
    interactive:false
    Row{
        id:row
        anchors.fill:parent
    }
    Timer{
        interval:10;
        running:true;
        repeat:true
        onTriggered:{
            if(flickable.atXEnd){
                Qt.createComponent('Pic.qml').createObject(row)
            }
            flickable.contentX++
        }
    }
}

Pic.qml

import QtQuick
Image{
    sourceSize.height:parent.height
    fillMode:Image.PreserveAspectFit
    asynchronous:true
    source:'file://'+RandomImage
}

This continuously scrolls a strip of randomly chosen images from left to right.

This works nicely, but the only problem that remains is that images that scroll offscreen need to be deleted.

What's the best way to achieve this?



2023-06-16

Git: receive.denyCurrentBranch=updateInstead does not update

The receive.denyCurrentBranch=updateInstead option (set on the server repo) should, according to the docs, allow the push and do a hard reset of the worktree if it's clean, or just flat out refuse the push if the worktree isn't clean.

Instead, for me it allows the push, but doesn't touch the worktree - I have to git checkout -f after each push anyway, even though it's cleanish (has just untracked files present, which, if I'm not mistaken, should still count as clean).

Edit: The push-to-checkout hook doesn't seem to run, either, even though it's in the .git/hooks/push-to-checkout file all right, with +x rights as needed. I made it output some lines and exit with code 1, so it should abort after producing the output - and yet the pushes come through.

My client is 2.31.0.windows.1 (TortoiseGit), server is 2.39.1 if that one matters.



Dynamically change data-prefix of React-Table Header (Only works in Cell)

I am trying to dynamically change the data-prefix of an icon from far to fas when a button is clicked. This will change the folder icon into a darken folder icon to show a process is running.

When the button is clicked I run this javascript:

document.getElementById("DownloadSelectedFolder").setAttribute("data-prefix","fas");

Here is the table and column:

        const {
          getTableProps,
          getTableBodyProps,
          headerGroups,
          page,
          nextPage,
          previousPage,
          canNextPage,
          canPreviousPage,
          pageOptions,
          gotoPage,
          pageCount,
          setPageSize,
          state,
          rows,
          rowIndex,
          prepareRow,
          selectedFlatRows,
          onChangeSelectedRowsId,
          toggleAllRowsSelected,
        } = useTable({
          columns,
          data: Documents,
          selectedRows : setSelectedRows,
          //Add this
          autoResetSelectedRows: false,
          autoResetSelectedCell: false,
          autoResetSelectedColumn: false,
        },
        useSortBy, 
        usePagination,
        useRowSelect,
        hooks => {
          hooks.visibleColumns.push(columns => [
            ...columns,
            {
              id: 'selection',
              Header: ({ getToggleAllRowsSelectedProps }) => (
                <div> 
                  
                <button 
                className="border rounded p-2 mb-2"
                onClick={() =>   mergePDFs(selectedFlatRows.map(row => row.original))}
                > 
                <i id="DownloadSelectedFolder" className="far fa-folder-open action mr-2" disabled></i>
                </button>
                <Checkbox {...getToggleAllRowsSelectedProps()} />
                </div>
              ),
              disableSortBy: true,
              Cell: ({ row }) => 
              <div>
              <Checkbox {...row.getToggleRowSelectedProps()} />
              <span  onClick={() => openDocument(row.id)}>
                <i id={row.id} className="far fa-folder-open action mr-2" disabled></i>
              </span>
            </div>

            }
          ])

This JavaScript code for the icon does work if I have the icon placed in the cell (rows). When it is placed in the header (column) it no longer works... I am not sure why this is the case. Any advice?



2023-06-15

could not convert string to float: 'Skoda Laura' [duplicate]

I am stuck here. I'm trying to make a website which make predictions on machine learning.


car=cars[['name','company','year','car_prices','kms_driven','fuel_type']] 
 
car['name']=car['name'].str.split(' ').str.slice(0,3).str.join(' ')

x=cars.drop(columns='car_prices')
y=cars['car_prices']
from sklearn.model_selection import train_test_split
x_train,y_train,x_test,y_test=train_test_split(x,y,test_size=0.3)
ohe=OneHotEncoder()
ohe.fit(x[['name','company','fuel_type']])
ohe.categories_
column_trans=make_column_transformer((OneHotEncoder(categories=ohe.categories_),['name','company','fuel_type']),remainder="passthrough")
lr=LinearRegression()
pipe=make_pipeline(column_trans,lr)
pipe.fit(x_train,y_train)



ValueError: could not convert string to float: 'Skoda Laura'

ValueError: could not convert string to float: 'Skoda Laura'

`` Also car.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 5512 entries, 0 to 5511 Data columns (total 6 columns):

Column Non-Null Count Dtype


0 car_name 5512 non-null object 1 company 5512 non-null object 2 year 5512 non-null int32 3 car_prices 5512 non-null int32 4 kms_driven 5512 non-null int32 5 fuel_type 5512 non-null object dtypes: int32(3), object(3) memory usage: 193.9+ KB



2023-06-14

Cypress: WebAuthn.addCredential causes exception

Our mobile app uses passkey to authorize users. I am testing the API for our mobile app. We have a SignUpSignIn command that returns "challenge”, "pubKeyCredParams”, "excludeCredentials”, ”rp" and "user”. Now I need to get authenticator information from my browser i.e. "authenticatorData”,“signature”, "clientDataJSON”. I have found this code https://github.com/cypress-io/cypress/issues/6991#issuecomment-1267934998 and tried it. I successfully received _AUTHENTICATOR_ID but I’m stuck about the next step. I tried the command WebAuthn.addCredential but I just got “(uncaught exception)Error: An error occurred trying to create the credential”. I do not understand what I did wrong and if it was a correct step.

This code leads to an exception it is highly likely that the reason is in 'privateKey':

let elliptic = require('elliptic');
let ec = new elliptic.ec('secp256k1');
let keyPair = ec.genKeyPair(); // Generate random keys
let privKey = keyPair.getPrivate("hex");

   
cy.log("privKey "+privKey);
//privKey 0c2a815f5e67ff7c650c475624e71486ad7dee4294ee7301be2a221919b5d5f8
cy.log("_AUTHENTICATOR_ID "+_AUTHENTICATOR_ID);

Cypress.automation("remote:debugger:protocol", {
    command: "WebAuthn.addCredential",
    params: {
    authenticatorId: _AUTHENTICATOR_ID,
    credential: {
        credentialId: Buffer.from("1", 'utf8').toString('base64'),
        isResidentCredential: false,
        setAutomaticPresenceSimulation: true,
        rpId: my_rpID,
        signCount: 1,
        privateKey: privKey.toString('base64'),
        }
     }
}).then(() => {});
        


Multiple Azure AD Enterprise Apps for Single Cognito User Pool

I am trying to use our Azure AD to provide auth for an internal application which is behind an ALB on AWS.

I am using a Cognito User Pool with the Azure AD configured as an identity provider.

We already have one application configured in this manner, which is accessible from anyone with an identity in Azure AD. The application I am deploying now, should only be accessible by a select few users with account admin privileges.

I have created an Enterprise Application in Azure AD Admin Center, but the issue I am having is that the application's Identifier(Entity ID) must be in the following format urn:amazon:cognito:sp:<region>_<userpool_id> and it must be globally unique.

It must be in this format because that value is used as the aud claim in the OIDC process. Since we already have an application which is uses this AD and User Pool combination, there is no way to provide the correct Entity ID because of the need for it to be globally unique across enterprise apps.

Is there some workaround for this without changing the auth config(e.g. I don't want to bypass Cognito or have ALBs targeting other ALBs)



2023-06-13

React Soap Call - ADDING EXTRA OPERATION

Hi I used following example to make successful react soap service and client

https://github.com/officer-rosmarino/node-soap-example

I tried to add in a second service/operation ie add a message joiner function as well as a message splitter but I am failing to understand the intricacies

I can get change the service by changing MessageSplitter to MessageJoiner but cant publish service object to allow multiple operations ie: call MessageSplitter or MessageJoiner from Client from same service

I created separate elements in wsdl as below and tried various ways

I also tried combining operations under 1 port type in below but that produces errors - the below works but runs the same function when i call each service in turn in client ie it runs MessageSplitter twice and never runs MessageJoiner unless i change service object

<?xml version="1.0" encoding="UTF-8"?>
<!-- <definitions> must be the root of the WSDL document -->
<wsdl:definitions targetNamespace="http://tempuri.org/" 
  xmlns:s="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" 
  xmlns:soap14="http://schemas.xmlsoap.org/wsdl/soap12/" 
  xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" 
  xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" 
  xmlns:tns="http://tempuri.org/" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
  xmlns:soap1="http://schemas.xmlsoap.org/wsdl/soap/" 
  xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" 
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <!-- WSDL TYPES: definition of the data types that are used in the web service -->
  <wsdl:types>
    <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
      <s:element name="MessageSplitterRequest">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="1" name="message" type="s:string"/>
            <s:element minOccurs="1" maxOccurs="1" name="splitter" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="MessageSplitterResponse">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="unbounded" name="result" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
    </s:schema>
  </wsdl:types>
  <!-- MESSAGES: defines the data being exchanged between the service and client -->
  <wsdl:message name="MessageSplitterSoapIn">
    <wsdl:part name="parameters" element="tns:MessageSplitterRequest"/>
  </wsdl:message>
  <wsdl:message name="MessageSplitterSoapOut">
    <wsdl:part name="parameters" element="tns:MessageSplitterResponse"/>
  </wsdl:message>
  <!-- PORT TYPES: defines the complete communication operation (one way/round trip) -->
  <wsdl:portType name="MessageSplitterSoapPort">
    <!-- The operation name must be the same as the one specified in the service object -->
    <wsdl:operation name="MessageSplitter">
      <wsdl:input message="tns:MessageSplitterSoapIn"/>
      <wsdl:output message="tns:MessageSplitterSoapOut"/>
    </wsdl:operation>
    
  </wsdl:portType>
  <wsdl:portType name="MessageSplitterSoapPort1">
    <!-- The operation name must be the same as the one specified in the service object -->
  
    <wsdl:operation name="MessageJoiner">
      <wsdl:input message="tns:MessageSplitterSoapIn"/>
      <wsdl:output message="tns:MessageSplitterSoapOut"/>
    </wsdl:operation>
  </wsdl:portType>
 
  <!-- BINDING: provides details on how a portType operation will actually be transmitted -->
  <wsdl:binding name="MessageSplitterServiceSoapBinding" type="tns:MessageSplitterSoapPort">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageSplitter">
      <soap:operation soapAction="MessageSplitter" style="document"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
   <wsdl:binding name="MessageSplitterServiceSoap1Binding" type="tns:MessageSplitterSoapPort1">
    <soap1:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageJoiner">
      <soap1:operation soapAction="MessageJoiner" style="document"/>
      <wsdl:input>
        <soap1:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap1:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:binding name="MessageSplitterServiceSoap12Binding" type="tns:MessageSplitterSoapPort">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageSplitter">
      <soap12:operation soapAction="MessageSplitter" style="document"/>
      <wsdl:input>
        <soap12:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
   <wsdl:binding name="MessageSplitterServiceSoap14Binding" type="tns:MessageSplitterSoapPort1">
    <soap14:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageJoiner">
      <soap14:operation soapAction="MessageJoiner" style="document"/>
      <wsdl:input>
        <soap14:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap14:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <!-- SERVICE:  -->
  <wsdl:service name="MessageSplitterService">
    <wsdl:port name="MessageSplitterServiceSoapPort" binding="tns:MessageSplitterServiceSoapBinding">
      <soap:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
     <wsdl:port name="MessageSplitterServiceSoap1Port" binding="tns:MessageSplitterServiceSoap1jBinding">
      <soap1:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
    <wsdl:port name="MessageSplitterServiceSoap12Port" binding="tns:MessageSplitterServiceSoap12Binding">
      <soap12:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
    <wsdl:port name="MessageSplitterServiceSoap14Port" binding="tns:MessageSplitterServiceSoap14Binding">
      <soap14:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
  </wsdl:service>
  

</wsdl:definitions>
  MessageSplitterService: {
    MessageSplitterServiceSoapPort: {
      MessageSplitter: splitter_function,
      //MessageSplitter: joiner_function,
    },
    MessageSplitterServiceSoap12Port: {
      MessageJoiner: joiner_function,
      // MessageSplitter: joiner_function,
    },
    MessageSplitterServiceSoap1Port: {
      MessageJoiner: joiner_function,
      //MessageSplitter: joiner_function,
    },
    MessageSplitterServiceSoap14Port: {
      MessageJoiner: joiner_function,
      // MessageSplitter: joiner_function,
    },
  },
};

Do I need to create completely different service objects and publish them on separate ports or a wsdl for each operation thanks Advice appreciated!!!

update: i merged all into one service but still cannot get to work only splitter action will work

<?xml version="1.0" encoding="UTF-8"?>
<!-- <definitions> must be the root of the WSDL document -->
<wsdl:definitions targetNamespace="http://tempuri.org/" 
  xmlns:s="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" 
  xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" 
  xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" 
  xmlns:tns="http://tempuri.org/" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
  xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" 
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <!-- WSDL TYPES: definition of the data types that are used in the web service -->
  <wsdl:types>
    <s:schema elementFormDefault="qualified" targetNamespace="http://tempuri.org/">
      <s:element name="MessageSplitterRequest">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="1" name="message" type="s:string"/>
            <s:element minOccurs="1" maxOccurs="1" name="splitter" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="MessageSplitterResponse">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="unbounded" name="result" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="MessageJoinerRequest">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="1" name="message" type="s:string"/>
            <s:element minOccurs="1" maxOccurs="1" name="joiner" type="s:string"/>
            <s:element minOccurs="1" maxOccurs="1" name="splitter" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
      <s:element name="MessageJoinerResponse">
        <s:complexType>
          <s:sequence>
            <s:element minOccurs="1" maxOccurs="unbounded" name="result" type="s:string"/>
          </s:sequence>
        </s:complexType>
      </s:element>
    </s:schema>
  </wsdl:types>
  <!-- MESSAGES: defines the data being exchanged between the service and client -->
  <wsdl:message name="MessageSplitterSoapIn">
    <wsdl:part name="parameters" element="tns:MessageSplitterRequest"/>
  </wsdl:message>
  <wsdl:message name="MessageSplitterSoapOut">
    <wsdl:part name="parameters" element="tns:MessageSplitterResponse"/>
  </wsdl:message>
   <wsdl:message name="MessageJoinerSoapIn">
    <wsdl:part name="parameters" element="tns:MessageJoinerRequest"/>
  </wsdl:message>
  <wsdl:message name="MessageJoinerSoapOut">
    <wsdl:part name="parameters" element="tns:MessageJoinerResponse"/>
  </wsdl:message>
  <!-- PORT TYPES: defines the complete communication operation (one way/round trip) -->
  <wsdl:portType name="MessageSplitterSoapPort">
    <!-- The operation name must be the same as the one specified in the service object -->
    <wsdl:operation name="MessageSplitter">
      <wsdl:input message="tns:MessageSplitterSoapIn"/>
      <wsdl:output message="tns:MessageSplitterSoapOut"/>
    </wsdl:operation>
   
  
    <!-- The operation name must be the same as the one specified in the service object -->
    
    <wsdl:operation name="MessageJoiner">
      <wsdl:input message="tns:MessageJoinerSoapIn"/>
      <wsdl:output message="tns:MessageJoinerSoapOut"/>
    </wsdl:operation>
  </wsdl:portType>
 
  <!-- BINDING: provides details on how a portType operation will actually be transmitted -->
  <wsdl:binding name="MessageSplitterServiceSoapBinding" type="tns:MessageSplitterSoapPort">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageSplitter">
      <soap:operation soapAction="MessageSplitter" style="document"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
     <wsdl:operation name="MessageJoiner">
      <soap:operation soapAction="MessageJoiner" style="document"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  
  <wsdl:binding name="MessageSplitterServiceSoap12Binding" type="tns:MessageSplitterSoapPort">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="MessageSplitter">
      <soap12:operation soapAction="MessageSplitter" style="document"/>
      <wsdl:input>
        <soap12:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="MessageJoiner">
      <soap12:operation soapAction="MessageJoiner" style="document"/>
      <wsdl:input>
        <soap12:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
    
  <!-- SERVICE:  -->
  <wsdl:service name="MessageSplitterService">
    <wsdl:port name="MessageSplitterServiceSoapPort" binding="tns:MessageSplitterServiceSoapBinding">
      <soap:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
   
    <wsdl:port name="MessageSplitterServiceSoap12Port" binding="tns:MessageSplitterServiceSoap12Binding">
      <soap12:address location="http://localhost:8000/wsdl"/>
    </wsdl:port>
   
  </wsdl:service>
  

</wsdl:definitions>


For some reason I have to reboot my Macbook Pro M2 to get gradle to work again

I can work for hours just fine without any issues, then all of the sudden gradle will start getting stuck, eventually it will give this error:

* What went wrong:
Gradle could not start your build.
> Cannot create service of type BuildSessionActionExecutor using method LauncherServices$ToolingBuildSessionScopeServices.createActionExecutor() as there is a problem with parameter #21 of type FileSystemWatchingInformation.
   > Cannot create service of type BuildLifecycleAwareVirtualFileSystem using method VirtualFileSystemServices$GradleUserHomeServices.createVirtualFileSystem() as there is a problem with parameter #7 of type GlobalCacheLocations.
      > Cannot create service of type GlobalCacheLocations using method GradleUserHomeScopeServices.createGlobalCacheLocations() as there is a problem with parameter #1 of type List<GlobalCache>.
         > Could not create service of type FileAccessTimeJournal using GradleUserHomeScopeServices.createFileAccessTimeJournal().
            > Timeout waiting to lock journal cache (/Users/carlos/.gradle/caches/journal-1). It is currently in use by another Gradle instance.
              Owner PID: 10180
              Our PID: 10277
              Owner Operation:
              Our operation:
              Lock file: /Users/myname/.gradle/caches/journal-1/journal-1.lock

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

I've tried the suggestions of running ./gradlew --stop and rm /Users/myname/.gradle/caches/journal-1/journal-1.lock but it won't help. I've even deleted the entire cache.

The only thing that helps is rebooting the Macbook Pro M2. I've been having this issue several days now.

Any idea what it might be?

I'm using com.android.tools.build:gradle:8.0.2 on Android Studio Flamingo.



2023-06-12

Find the nearest quarter on numpy array?

I have a numpy array that contains numbers with a 0.25 step. So a part of this array is [-38.25, -38,-37.75, -37.5]. I want to be able to find the nearest and lowest quarter to any number.

For example if the input is -37.778 then the closest quarters would be -37.75 and -38 and the lowest would be -38. So the output should be -38 or even better the corresponding index for -38.

I do it manually with approximations and later using np.searchsorted but I thought there must be a better way. Also the array is 400 elements long so I'm not sure is the best to do it this way.



running oc command using fabric8 openshift client client

I am interacting with OpenShift platform in my project using fabric8 OpenShiftClient interface. I need to run the command oc exec {some pod name} -- df -h and get the result as a string in java. Can someone help me understand how can i do that?

I haven't found in the documentation of fabric8 any standard way to retrieve this information using the build in interface (for example, like getting the pods list which is very easy). So im guessing that i need to run this command in different way.



2023-06-11

Navigating System Settings with Applescript (in Ventura)

I have been learning Applescript for several weeks — not a difficult task for a long-time programmer. One thing I am trying to do is to change system settings using Applescript. I have been searching every resource I can find, have read the Applescript online manual from cover to cover, explored many chat rooms that discuss this ... and I can find absolutely nothing about how to identify the different elements in the System Settings application. I have seen many pieces of code with lines like "... button 1 of splitter group 1 of group 1 of pane 1 of window 1 ..." But I can find no information on how to correlate this to what I see when I open System Settings manually. I have successfully been able to open a pane of my choice, and display a list of its UI elements (which don't correlate in any clear way to what I see visually in System Settings); but that's as far as I can get. Can someone explain, or direct me to a good tutorial that explains, how to under stand what "group 1" means, or "menu bar 1" or "button group 1" or splitter group 1" etc.? Until I can understand this, I am completely lost at trying to navigate through the settings, and to then be able to set the setting of my choice. Thanks for any help!



2023-06-10

Problems handling checkboxGroupInput in R Shiny app

I'm trying to resolve an issue with the following project. I'm building a database of archives that have materials about certain festivals in history, and I want to make an interactive map out of it.

I want the user to be able to filter by edition of each festival.

The issue seems to be that in my dataset, some entries for festival_edition have multiple options, e.g. (ca72;ca76) because several apply. The map only renders rows that have unique entries there (just ca72 for instance).

I'm a beginner and this is the first app I'm building.

library(shiny)
library(dplyr)
library(leaflet)
library(tidyr)
library(readr)
library(stringr)
# Set working directory

# Read CSV file
carchives <- read_csv("carifesta-archives.csv")

# Separate coordinates column into Latitude and Longitude columns
carchives <- separate(carchives, col = coordinates, into = c("Latitude", "Longitude"), sep = ",")

# Convert coordinates columns to numeric values
carchives$Longitude <- as.numeric(carchives$Longitude)
carchives$Latitude <- as.numeric(carchives$Latitude)

festival_list <- c("carifesta_1972" = "ca72",
                   "carifesta_1976" = "ca76",
                   "carifesta_1979" = "ca79",
                   "carifesta_1981" = "ca81",
                   "carifesta_1988" = "ca88",
                   "carifesta_1992" = "ca92",
                   "carifesta_1995" = "ca95",
                   "carifesta_2000" = "ca00",
                   "unknown" = "NULL")

# Define UI for application
ui <- fluidPage(
  
  # Application title
  titlePanel("Map of Carifesta archives"),
  
  # Display map on screen
  leafletOutput('locations'),
  
  # Add filter for festival edition
  # Add filter for festival edition
  checkboxGroupInput("festival_edition", "Filter by festival edition",
                     choices = festival_list,
                     selected = festival_list,
                     inline = TRUE
  )
)

# Define server logic
# Define server logic
server <- function(input, output, session) {
  
  observeEvent(input$festival_edition, {
    selected_editions <- str_split(input$festival_edition, ";")
    carchives_festival <- carchives[carchives$festival_edition %in% selected_editions, ]
    
    # Render map
    output$locations <- renderLeaflet({
      locations <- leaflet(data = carchives_festival)
      locations <- addTiles(locations)
      
      locations <- addMarkers(locations,
                              lng = ~Longitude, lat = ~Latitude,
                              popup = paste("Repository:", carchives_festival$repository,
                                            "<br>", "Label:",
                                            "<a href=", carchives_festival$repo_url, ">",
                                            carchives_festival$label, "</a>",
                                            "<br>", "Description:", carchives_festival$description,
                                            "<br>", "Files:", carchives_festival$folders),
                              clusterOptions = markerClusterOptions(
                                maxClusterSize = 100,
                                color = "red",
                                opacity = 0.5
                              )
      )
    })
  })
}

# Run application
shinyApp(ui = ui, server = server)

The particular problematic part is this, I think:

observeEvent(input$festival_edition, {
    selected_editions <- str_split(input$festival_edition, ";")
    carchives_festival <- carchives[carchives$festival_edition %in% selected_editions, ]


ChartJS bar chart - text over bar? [duplicate]

I am using Chart JS in React. I want to do this: enter image description here

I currently have this: enter image description here

This is my code:

export const options = {
  responsive: true,
  indexAxis: 'y',
  plugins: {
    legend: {
      display: false,
    },
    title: {
      display: false,
    },
  },
  hover: {
    mode: null,
  },
};

const labels = [
  'introduction',
  'html css',
  'version control',
  'advanced',
  'intro js',
  'advanced',
  'intro to react',
];

export const data = {
  labels,
  datasets: [
    {
      data: chartMock.map((item) => item.percentage),
      backgroundColor: chartMock.map((item) => getBarColor(item.percentage)),
    },
  ],
};

const BarChart = () => {
  return <Bar options={options} data={data} />;
};

Is it possible to put text over the bar, as in example? Also, how can i remove padding around each row?

I already tried associated answer, but nothing happens. I saw that chartjs-plugin-datalabels are something that could help me, but nothing that I tried worked.



2023-06-09

ESP32 WROVER - Lack of Photo Memory

Good afternoon everyone, how are you?

I'm using an ESP32 WROVER

I just need to put it on the network and take a picture (good quality) In the description it says that the card has 4mb flash memory, but when I go to record it appears as follows Flash: [====== ] 64.5% (used 845098 bytes from 1310720 bytes) that is, it has only 1.3mb

A high resolution photo needs 1mb, but as it has no memory, it gives an error.

Follow my program

#include <WiFi.h>
#include <ESP_WiFiManager.h>
#include <esp_camera.h>
#include <WiFiServer.h>

const char* ssid = "ESP_Laser";
const char* password = "Laser123";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  ESP_WiFiManager WiFiManager;
  WiFiManager.setConfigPortalTimeout(240);

  if (!WiFiManager.autoConnect(ssid, password)) {
    Serial.println("Falha na conexao. Resetar e tentar novamente...");
    delay(3000);
    ESP.restart();
    delay(5000);
  }

  Serial.println("Conectado na rede WiFi.");
  Serial.print("Endereco IP: ");
  Serial.println(WiFi.localIP());

  camera_config_t config;

  config.pin_pwdn = -1;
  config.pin_reset = -1;  
  config.pin_xclk = 21;
  config.pin_sscb_sda = 26;
  config.pin_sscb_scl = 27;

  config.pin_d7 = 35;
  config.pin_d6 = 34;
  config.pin_d5 = 39;
  config.pin_d4 = 36;
  config.pin_d3 = 19;
  config.pin_d2 = 18;
  config.pin_d1 = 5;
  config.pin_d0 = 4;
  
  config.pin_vsync = 25;
  config.pin_href = 23;
  config.pin_pclk = 22;

  config.xclk_freq_hz = 20000000;
  config.ledc_timer = LEDC_TIMER_0;
  config.ledc_channel = LEDC_CHANNEL_0;
  
  config.pixel_format = PIXFORMAT_JPEG;
  config.frame_size = FRAMESIZE_UXGA;

  config.jpeg_quality = 10;
  config.fb_count = 2;

  esp_err_t cameraInitError = esp_camera_init(&config);
  if (cameraInitError != ESP_OK) {
    Serial.printf("Falha na inicialização da câmera! (erro 0x%x)\n", cameraInitError);
    return;
  }

  server.begin();
  Serial.println("Servidor iniciado.");

}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("Novo cliente conectado.");

  camera_fb_t* fb = esp_camera_fb_get();
  if (!fb) {
    client.println("HTTP/1.1 500 Internal Server Error");
    client.println("Content-type:text/html");
    client.println();
    client.println("<html><body><h1>Erro ao capturar imagem</h1></body></html>");
    delay(1);
    client.stop();
    return;
  }

  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:image/jpeg");
  client.println("Connection: close");
  client.println();
  client.write(fb->buf, fb->len);
  esp_camera_fb_return(fb);

  delay(1);
  client.stop();
}

I was disappointed because I thought that this board would be able to take only 1 photo in good resolution. Is there still a way to do this? or would I need to buy the card that comes with space to put a memory card? Thanks

Would I need to buy a new board with a memory card or is there still a way to do this one?



Troubleshooting Progress Bar Transition Issue in React Code

I’m having an issue with buggy code in my progress bar. The transition doesn’t start unless I wrap setStartTransition within setTimeout or requestAnimationFrame, as shown in this example: https://codesandbox.io/s/progress-bar-buggy-3pby7c?file=/src/progressBar.js. However, my understanding is that calling setStartTransition(true) after render should start the transition without the need for a timeout . fixed code : https://codesandbox.io/s/progress-bar-99nxwl?file=/src/progressBar.js. Can someone help me understand what’s happening? Is it an issue with setState?



2023-06-08

pyspark nested for loops

I have seen many question of the same nature, but, I am still confused: some say use Groupby, some propose the use of map or flatmap. Not sure what to try.

Input: A PySpark DF with date, term, brand, text column. Expected output: A list of filtered dfs [df1, df2, ...]

In Python, the code looks like this (df is a big dataframe, has about 10000 records):

filtered_df_list = []

for term in term_list:
  for br in brand_list:
    for dt in date_list:
      tcd_df = df.filter( (df.term == term) & (df.brand == brand) & (df.date == dt) )
      if len(tcd_df.index) > 0:
        filtered_df_list.append(tcd_df)

Also, can I create a dataframe out of term, brand and date lists and do a 'withColumn' to create a new column that will have the filtered dfs? I am not sure. A starter code for parallelizing this will be helpful.

Update: This is what I tried and it looks like worker nodes are trying to do the filtering with the sparkContext that is not allowed.

rdd2 = df.rdd.map(lambda row: (
    row["date"], row["brand"], row["term"], row["text"],
    df.filter((df.brand == row["brand"]) & (df.term == row["term"]) & (df.date == row["date"]))
))

print("\n\nAfter loop")
df2 = rdd2.toDF(["date", "brand", "term", "text"])
df2.show()

Error (more or less I expected this): _pickle.PicklingError: Could not serialize object: RuntimeError: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.



Why are there gaps in my fibonacci sphere?

I recently took an interest in fibonacci spheres, so I decided to implement one. It works as expected, except for the fact that there are visual gaps in the sphere

fibonacci sphere with gaps

Now I don't know if there's supposed to be multiple layers like there is, but the main problem is the gaps. Here's my sphere generation function

// This code generates points on a sphere using Fibonacci spiral sampling
// The number of samples and the array to store the points are passed as arguments

#include <math.h>

void fibonacci_sphere(int samples, float points[][3]) {
    float phi = M_PI * (sqrtf(5.0f) - 1.0f);  // golden angle in radians

    for (int i = 0; i < samples; i++) {
        float y = 1.0f - ((float)i / (float)(samples - 1)) * 2.0f;  // y goes from 1 to -1
        float radius = sqrtf(1.0f - y * y);  // radius at y

        float theta = phi * i;  // golden angle increment

        points[i][0] = cosf(theta) * radius;
        points[i][1] = y;
        points[i][2] = sinf(theta) * radius;
    }
}

And this is my basic tessellation shader

#version 450 core

// determines what type of tessellation to do
layout(triangles, equal_spacing, cw) in;

// input from control shader
in vec3 vertex_coord[];
// output vec
out vec3 vert;

// allows for object transformations
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    // gets barycentric coordinates from the triangles
    vec3 u = gl_TessCoord.x * vertex_coord[0];
    vec3 v = gl_TessCoord.y * vertex_coord[1];
    vec3 w = gl_TessCoord.z * vertex_coord[2];
    // makes every triangle an equal distance from the center (that's how spheres are formed)
    vec3 pos = normalize(u + v + w);

    // output tessellated shape
    gl_Position = projection * view * model * vec4(pos, 1.0);
}


The vertex shaders are just the vertices from the CPU side of things, so that's not the problem.

I did some research across a few forums, and tried a pretty cool website that uses AI to analyze your code and find bugs and help visualize what happens.

EDIT:

This is the non-wireframe version of the sphere enter image description here

And this is the part where I actually upload the data to get processed by the GPU

// fibonacci sphere vertices
float vertices[100][3];
fibonacci_sphere(100, vertices);

unsigned int vbo, vao;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);

glBindVertexArray(vao);

// upload vertex data to gpu
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) * sizeof(double), &vertices[0], GL_STATIC_DRAW);

// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);

// amount of tessellation to do per triangle
glPatchParameteri(GL_PATCH_VERTICES, 3);
glBindVertexArray(vao);
glDrawArrays(GL_PATCHES, 0, 100);


2023-06-07

Convert Negative to Positive Based on Another Column in Power Query

I have some data that is negative and I need to convert it to a positive but it has to be based on another column.

So this is what I have:

each if ([Column1]< 0 and [Column2] = "X") then [Column1] *-1 else [Column1] *1) 

But I can't get it to work. Column1 is the values and Column 2 is the one with the text.

Any ideas? Thanks



Why does a Python request from Firebase Cloud Functions result in a CoreFoundation error?

I am attempting to make a request to a third party API via a python script in a Firebase cloud function (2nd generation cloud functions python public preview):

def foo(req: https_fn.Request) -> https_fn.Response:
    url = 'https://catfact.ninja/fact'
    res = requests.get(url)
    return json.dumps(res.json())

When I call this function, I get the following error:

The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). Break on THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC() to debug.

I know this is related to the request because when I remove the request this error no longer occurs. I read online that this issue was a Mac related thing and I am indeed on a Mac. I also tried simply executing the above request in a separate python file, which worked fine. This leads me to believe this issue is related to something in Firebase Functions. Does anyone know what's going on here?



2023-06-06

Why is my useRef not working on my overflowing absolute div with Styled Components?

Trying to create a dropdown with Styled Components that if the dropdown is going past the viewport a right will be applied, example:

Component (stripped):

export default function SoTest() {
    const [dropActive, setDropActive] = useState(false)
    const ref = useRef()
  
    return (
      <>
      <Foo
        onMouseEnter={() => setDropActive(true)}
        onMouseLeave={() => setDropActive(false)}
      >
        // Removed code
      </Foo>
        <DropContainer
          ref={ref}
          isOverflow={useIsOverflow(ref)}
          dropdownActive={dropdownActive}
          onMouseEnter={() => setDropActive(true)}
          onMouseLeave={() => setDropActive(false)}
        >
          // Removed code
        </DropContainer>
      </>
    )
  }

then in the style, I'm attempting:

const DropContainer = styled.div`
  display: ${({ dropdownActive }) => (dropdownActive ? 'flex' : 'none')};
  right: ${({ isOverflow }) => (isOverflow ? '18px' : '')};
  position: absolute;
  z-index: 10;
`

my hook useIsOverflow I have:

import { useState, useLayoutEffect } from 'react'

export default function useIsOverflow(ref) {
  const [isOverflow, setIsOverflow] = useState(undefined)

  useLayoutEffect(() => {
    const { current } = ref
    const { clientWidth, scrollWidth } = current

    const trigger = () => {
      const hasOverflow = scrollWidth > clientWidth ? true : false
      setIsOverflow(hasOverflow)
    }

    if (current) trigger()
  }, [ref])

  return isOverflow
}

When I log ref I get:

offsetHeight: 0
offsetLeft: 0
offsetParent: null
offsetTop: 0
offsetWidth: 0

but I'm not getting back a boolean of true when I move the dropdown to the right and click Foo. What am I doing wrong and why am I not able to detect the ref or what can I do to detect if the dropdown is going past the viewport to apply right?



Angular Polyfill for Angular 14 app giving an error

I recently upgraded my angular app from v14 to v15. Due to a business need, we need to support Chrome 69 for the app. So, I added the following lines of code in my polyfills.ts file:

import '@angular/localize/init';
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import 'zone.js/dist/zone';

The compilerOptions in my tsconfig.json are as follows:

"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"module": "es2020",
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"typeRoots": [
  "node_modules/@types"
],
"lib": [
  "es2020",
  "dom"
],
"useDefineForClassFields": false

}

Now, my code works in the latest chrome browser. But, it doesn't load in Chrome 69. I see the below error lines in the dev console of Chrome 69.

Uncaught SyntaxError: Unexpected token .     /polyfills.js:1
Uncaught SyntaxError: Unexpected token .     /main.js:1

Any help in resolving this issue would be greatly appreciated. Thanks in Advance.



What's the order of destruction of function parameters and return values?

In the following code:

struct Foo {
    void Func();
    ~Foo();
};

Foo GetFoo(Foo foo);

The function GetFoo accepts a parameter foo by value and returns a Foo object. If we call GetFoo by this way:

Foo f;
GetFoo(f).Func();

Will the parameter foo or the return value object destruct first according to the C++ standard?


C++17 says in expr.call#4 that the implementation can choose whether to destruct the parameter object when the function returns or at the end of the enclosing full-expression:

It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression.

And in class.temporary#4 it also says a temporary object (the return value object) is destroyed as the last step in evaluating the full-expression:

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

Then if the implementation chooses to destruct parameter objects at the end of the enclosing full-expresion, which will destruct first, according to C++ standard?



Convert GEOSwift.JSON to struct in Swift

I have a GEOSwift feature like this:

{
  "type" : "Feature",
  "geometry" : {
    "type" : "Point",
    "coordinates" : [
      -xx.xxxxxxxxxxxxxxx,
      xx.xxxxxxxxxxxxxxx
    ]
  },
  "properties" : {
    "mapLayer" : "MyMapLayer",
    "data" : {
      "id" : 42,
      "sizeClass" : "Large",
    // and so on...
    },
    "featureType" : "MyFeatureType"
  }
}

I want to retrieve the data member and put it into a struct that matches:

struct MyStruct: Decodable {
    var id: Int
    var sizeClass: String?
    // and so on...
}

This code will get me the data alone, but the datatype is GEOSwift.JSON, and I don't know how to stringify it to decode using the usual JSONDecoder class.

if case let .object(data) = feature.properties?["data"] {
  // do stuff with data: GEOSwift.JSON to get it into MyStruct
}

Here is the GEOSwift.JSON enum:

import Foundation

public enum JSON: Hashable, Sendable {
    case string(String)
    case number(Double)
    case boolean(Bool)
    case array([JSON])
    case object([String: JSON])
    case null

    /// Recursively unwraps and returns the associated value
    public var untypedValue: Any {
        switch self {
        case let .string(string):
            return string
        case let .number(number):
            return number
        case let .boolean(boolean):
            return boolean
        case let .array(array):
            return array.map { $0.untypedValue }
        case let .object(object):
            return object.mapValues { $0.untypedValue }
        case .null:
            return NSNull()
        }
    }
}

extension JSON: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = .string(value)
    }
}

extension JSON: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        self = .number(Double(value))
    }
}

extension JSON: ExpressibleByFloatLiteral {
    public init(floatLiteral value: Double) {
        self = .number(value)
    }
}

extension JSON: ExpressibleByBooleanLiteral {
    public init(booleanLiteral value: Bool) {
        self = .boolean(value)
    }
}

extension JSON: ExpressibleByArrayLiteral {
    public init(arrayLiteral elements: JSON...) {
        self = .array(elements)
    }
}

extension JSON: ExpressibleByDictionaryLiteral {
    public init(dictionaryLiteral elements: (String, JSON)...) {
        let object = elements.reduce(into: [:]) { (result, element) in
            result[element.0] = element.1
        }
        self = .object(object)
    }
}

extension JSON: ExpressibleByNilLiteral {
    public init(nilLiteral: ()) {
        self = .null
    }
}


Squarespace unique identifier solution no longer works due to change in form. Need help to determine why it wont work/solution

SS=Square Space

Previously there was a script posted by Ian_A on the SS forums to add in a unique identifier on forms submitted to prevent collation of emails in gmail. This enabled us to reply to each received form by hitting reply without needing to alter our default gmail box to conversation view etc.

We cannot change our gmail settings. (cannot turn on conversation view without alienating some users)

SS have since changed how the forms work and I believe that the $ parameter of the script no longer targets the correct part of the field. I don't have a coding background, my limited understanding is that the $ is the way jquery selects the field. I am not sure how to structure the jquery selector to pick the field I want by perhaps the class ID which is unique to each field on the form.

There is only one form to make this work on. I only have access to header code injection and custom CSS. I need each email sent by the form to have a randomised subject (or time/date stamped)

Below is the example of the code that worked prior to SS updating the site.

<script>
$(document).ready(function(){ 
    var timecode = Date.now();
    var subjecttxt = "#" + timecode;
  
  $('form').find("input[type=text], text").each(function()
  {
      if(!$(this).val()) { 
     $(this).attr("value", subjecttxt);
     $(this).attr("readonly", true);
     $(this).css("display","none");
        var val = subjecttxt;
        return ( val !== subjecttxt );
  }
  });
});

  $(document).ready(function(){ 
$('form').find("label[class=title]").each(function()
  {
      if(!$(this).val()) { 
     $(this).css("display","none");
        var val2 = "none";
        return ( val2 !== "none" );
  }
  });
});  
 </script>

Source= SS Forum Post Our website contact us page= Form in question

Below is the information I can see relating to the blank subject text box I both wish to hide from the user and autofill with a unique identifier on send so that we can identify each send individually. I feel there should be a way with jquery to get it to pick this instead of the just the first field on the form which no longer works, but I can't work out how to change the previous code above, to make it work and despite testing can't see why it wont work (no errors throw on the page load and I don't know how else to check)

For example: $('form') .find(input.text-dfd9bd71-70a1-413d-81f2-dae19bb38da2 )

I know this doesn't work but I don't know why it doesn't work, I feel like it could use the div id, or class but idk how to make jquery do that and the documentation is above my understanding currently.

              <div id="text-dfd9bd71-70a1-413d-81f2-dae19bb38da2" class="form-item field text">
                
            <label class="title" for="text-dfd9bd71-70a1-413d-81f2-dae19bb38da2-field">
              Subject
              
            </label>
          
                
                <input
                    class="field-element text"
                    type="text"
                    id="text-dfd9bd71-70a1-413d-81f2-dae19bb38da2-field"
                    
                    
                />
              </div>

I tried to hide a section at the top of a Squarespace contact form and have jquery select the box adding in a unique identifier.

Due to a change in the SS forms this no longer works as expected.



2023-06-05

How do I print microphone input to the serial port of arduino nano 33 ble sense?

Good day,

I have an arduino nano 33 ble sense with a microphone on it. Using the PDM.h library I extract the audio into a sample buffer 512 bytes at a time. I use a type of ping pong buffer to save data while I print to the serial port but it keeps crashing, what did I do wrong?

#include <PDM.h>
#include <stdlib.h>

// buffer to read samples into, each sample is 16-bits
char sampleBuffer[512];

//ping pong buffer
//total bytes is how many bytes the microphone recorded
//write offset switches between first or second half of the ping pong buffer
//read offset switches between first or second half of the ping pong buffer
//ready to print indicates that the data is ready to print
char audio[66000];
long int totalBytes = 0;
int writeOffset = 0;
int readOffset = 0;
int half = 32768;
bool readyToPrint = false;


void setup() {

  //the sample rate is 16Khz with a 16-bit depth that means 32KBytes/s are needed to fully transfer this signal
  //the baud rate represents the bit rate of the signal, 32*8 is 256Kbits/s, closest compatible baud rate of the nano is 500kbaud
  Serial.begin(500000);
  while (!Serial);

  // configure the data receive callback
  PDM.onReceive(onPDMdata);

  
  // optionally set the gain, defaults to 20
  // PDM.setGain(30);

  // initialize PDM with:
  // - one channel (mono mode)
  // - a 16 kHz sample rate
  if (!PDM.begin(1, 16000)) {
    Serial.println("Failed to start PDM!");
    while (1);
  }
}

void loop() {
}

void printToSerial(){
  Serial.write(audio + readOffset, half);
  readOffset = readOffset ^ half;
}

void onPDMdata() {
  // query the number of bytes available
  int bytesAvailable = PDM.available();

  // read into the sample buffer
  PDM.read(sampleBuffer, bytesAvailable);
  

  if(totalBytes < half){
    memcpy(audio + writeOffset + totalBytes, sampleBuffer, bytesAvailable);
    totalBytes += bytesAvailable;
  }
  else{
    totalBytes = 0;
    writeOffset = writeOffset ^ half;
    printToSerial();
  }

}


How can I get Ansible client IP from target host?

On an isolated network (without internet access to do public IP address lookups), I want to run a playbook from a controller against a number of target hosts where one of the tasks is to download a file via HTTP/HTTPS from the controller without hard-coding the controller IP as part of the task. E.g.

Controller: 192.168.0.5
Target 1: 192.168.0.10
Target 2: 192.168.0.11
Target 3: 192.168.0.12

The controller can have different IPs configured via DHCP, and there could be multiple network interfaces listed in ansible_all_ipv4_addresses (some of which may not be available to the target hosts) so it may not be straight forward to determine which network interface the target hosts should use from ansible_facts on localhost without exploring the idea of looping through them with a timeout until the file has been downloaded. It seems as though the most robust way to determine the public IP of the controller (assuming the web server is listening on 0.0.0.0) would be to determine the originating IP of the established connection (192.168.0.5) from the target host - is there a way to do this?

The motivation for downloading the file from the controller rather than sending it to remote hosts is that some of the target hosts are running Windows and the win_copy module is incredibly slow via WinRM so the Ansible documentation includes the following note:

Because win_copy runs over WinRM, it is not a very efficient transfer mechanism. If sending large files consider hosting them on a web service and using ansible.windows.win_get_url instead.



Missing 1 required positional argument 'element'

Type error: __init__() missing 1 required positional argument: 'element'

I got the code from github. I wanted to run but it doesn't work. Can you help

    from equation import Equation
    
    from time import sleep
    
    def run_balance():
    
        """
    
        Runs the chemical equation balance algorithm
    
        """
    
        print('=================================================')
    
        print('Insert chemical equation with elements in\nparentheses followed by the number of atoms:')
    
        print('Example: (H)2 + (O)2 = (H)2(O)1')
    
        user_input = input('>>> ')
    
        try:
    
            equation = Equation(user_input)
    
            print('Balanced equation: ' + equation.balance())
    
            sleep(3)
    
            run_balance()
    
        except IndexError:
    
            print('Invalid input...')
    
            sleep(3)
    
            run_balance()
    
    run_balance()