satoshi-2000/llms-suitable huggingface dataset:
Question: How to calculate rotation matrix for an accelerometer using only basic algebraic operations

There is a C function that gets the acceleration values of x,y,z of an accelerometer sensor (MEMS IMU) as input, and calculates the rotation matrix in a way that the z axis is aligned with the gravity. It is being used for calibrating the accelerometer data.

#define X_AXIS (0u)
#define Y_AXIS (1u)
#define Z_AXIS (2u)

static float matrix[3][3];
void calculate_rotation_matrix(float raw_x, float raw_y, float raw_z)
{ 
  const float r = sqrtf(raw_x * raw_x + raw_y * raw_y + raw_z * raw_z);
  const float x = raw_x / r;
  const float y = raw_y / r;
  const float z = raw_z / r;

  const float x2 = x * x;
  const float y2 = y * y;

  matrix[X_AXIS][X_AXIS] = (y2 - (x2 * z)) / (x2 + y2);
  matrix[X_AXIS][Y_AXIS] = ((-x * y) - (x * y * z)) / (x2 + y2);
  matrix[X_AXIS][Z_AXIS] = x;
  matrix[Y_AXIS][X_AXIS] = ((-x * y) - (x * y * z)) / (x2 + y2);
  matrix[Y_AXIS][Y_AXIS] = (x2 - (y2 * z)) / (x2 + y2);
  matrix[Y_AXIS][Z_AXIS] = y;
  matrix[Z_AXIS][X_AXIS] = -x;
  matrix[Z_AXIS][Y_AXIS] = -y;
  matrix[Z_AXIS][Z_AXIS] = -z;
}



float result[3];
void apply_rotation(float x, float y, float z)
{
  result[AXIS_X] = matrix[X_AXIS][X_AXIS] * x
                 + matrix[X_AXIS][Y_AXIS] * y
                 + matrix[X_AXIS][Z_AXIS] * z;
  
  result[AXIS_Y] = matrix[Y_AXIS][X_AXIS] * x
                 + matrix[Y_AXIS][Y_AXIS] * y
                 + matrix[Y_AXIS][Z_AXIS] * z;
  
  result[AXIS_Z] = matrix[Z_AXIS][X_AXIS] * x
                 + matrix[Z_AXIS][Y_AXIS] * y
                 + matrix[Z_AXIS][Z_AXIS] * z;

}

I'm trying to wrap my head around how it works and why there is no use of trigonometric functions here?
is it just simplifying the trigonometric functions by normalizing the input values and using the equivalent equations to calculate the trigonometric functions?
What are the limitations of this method? for example when the denominator calculated is zero, we will have division by zero. Anything else?
Tried to search on the internet and stackoverflow, but couldn't find a similar method to calculate the rotation matrix.
UPDATE:
Just simplified the calculations so they are more readable.
To add more context this code is used to rotate the readings of an accelerometer in a way that regardless of the orientation of the device, the z-axis is perpendicular to the ground.
The calculate_rotation_matrix() is called when we know that the object is stationary and is on a flat surface. This results in calculating the 3x3 matrix. Then the apply_rotation() is used to rotate subsequent readings.


Answer:
A quaternion representation can apply rotations without trig functions.  But this appears to be a version of: https://math.stackexchange.com/a/476311 . The math appears to be a variation thereof, where "a" and "b" are the accelerometer and gravity vectors.
The method also appears to assume measurements will not be perfect.  And MEMS sensors fit that description.  Otherwise, as you stated, if x and y are both zero then you have a divide by zero condition.
Question: Kotlin Firebase Realtime Database correct return value for setValue() in MVVM

What would be the correct return value of my setMyBirthday function in the HomeRepository class for the code to work? Void doesn't seem to be the right return value.
Fragment:
private fun HomeViewModel.setupObserver() {
    myBirthday.observe(viewLifecycleOwner) { response ->
        when(response) {
            is Resource.Error -> {
                response.message?.let { message ->
                    Log.e(TAG, "An error occurred: $message")
                }
            }
            is Resource.Loading -> {
                binding.buttonChangeBirthday.isClickable = false
            }
            is Resource.Success -> {
                binding.buttonChangeBirthday.isClickable = true
            }
        }
    }
}

HomeViewModel:
val myBirthday: MutableLiveData<Resource<Void>> = MutableLiveData()
fun setMyBirthday(birthday: String) = viewModelScope.launch {
    try {
        myBirthday.postValue(Resource.Loading())
        val response = homeRepository.setMyBirthday(birthday)
        myBirthday.postValue(Resource.Success(response))
    } catch (e: Exception) {
        myBirthday.postValue(Resource.Error(e.message!!))
    }
}

HomeRepository:
    suspend fun setMyBirthday(birthday: String) =
    databaseReference
        .child("users")
        .child(myUserID)
        .child("birthday")
        .setValue(birthday)
        .await()



Answer:

What would be the correct return value of my function in the HomeRepository class for the code to work? Void doesn't seem to be the right return value.

Indeed Void is the type of object the setMyBirthday function returns. So your function should look like this:
//                                            👇
suspend fun setMyBirthday(birthday: String): Void =
databaseReference
    .child("users")
    .child(myUserID)
    .child("birthday")
    .setValue(birthday)
    .await()

While your approach will work, it will be more convenient to return a Resource<Boolean> as in the following lines of code:
suspend fun setMyBirthday(birthday: String): Resource<Boolean> = try {
    databaseReference
        .child("users")
        .child(myUserID)
        .child("birthday")
        .setValue(birthday)
        .await()
    Resource.Success(true)
} catch (e: Exception) {
    Resource.Error(e)
}

This is more useful because you can pass the error further, otherwise, you won't know if something fails.
Question: Beautiful Soup Img Src Scrape

Problem: I am trying to scrape the image source locations for pictures on a website, but I cannot get Beautiful Soup to scrape them successfully.
Details:

Here is the website

The three images I want have the following HTML tags:

<img src="https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-1.jpg" style="display: none;">
<img src="https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-2.jpg" style="display: none;">
<img src="https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-3.jpg" style="display: none;">



Code I've Tried:

soup.find_all('img')
soup.select('#imageFlicker')
soup.select('#imageFlicker > div')
soup.select('#imageFlicker > div > img:nth-child(1)')
soup.find_all('div', {'class':'exercise-post__step-image-wrap'})
soup.find_all('div', attrs={'id': 'imageFlicker'})
soup.select_all('#imageFlicker > div > img:nth-child(1)')

The very first query of soup.find_all('img') gets every image on the page except the three images I want. I've tried looking at the children and sub children of each of the above, and none of that works either.
What am I missing here? I think there may be javascript that is changing the css display attribute from block to none and back so the three images look like a gif instead of three different images. Is that messing things up in a way I'm not understanding? Thank you!


Answer:
The content is provided dynmaically via JavaScript, but not rendered by requests per se, unlike in the browser.
However, you can search for the JavaScript variable:
var data = {"images":["https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-1.jpg","https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-2.jpg","https://ik.imagekit.io/02fmeo4exvw/exercise-library/large/14-3.jpg"],"interval":600};

with regex re.search() and convert its content string with json.loads() to JSON, so that you can access it easily.
Example
import requests
import re, json

url = 'https://www.acefitness.org/resources/everyone/exercise-library/14/bird-dog/'

json.loads(re.search(r'var data = (.*?);', requests.get(url).text).group(1))['images']
Question: Javascript event.offset alternative for final value during CSS scale & transition

I have an HTML image that I want to pan & zoom programatically. In order to improve the experience, I added a CSS transition for smoothness.
When I click on the image, I need to determine the mouse position within the image. Currently, event.offsetX gives me the mouse position within the image at the current frame of the animation.
I would like to know the mouse position as if the animation finished already (even though it hadn't).
Here is another way of explaining the problem. I created below an example where an image zooms in after we click on the button. The zoom takes 5 seconds. During the zoom, if I keep my mouse fixed and keep clicking, the offset value changes as the image moves on the screen and then it stabilizes after 5 seconds and returns the same offset value. I would like to know that final offset value before the animation finishes if possible.


<button onclick="onButton()">Zoom</button>
<br>
<img
    id='img'
    onclick="onImage(event)"
    src="https://picsum.photos/id/237/200"
    style="transition: 5s ease"
>

<script>
function onButton() {
    const img = document.querySelector('#img')
    img.style.scale = 5.0
}
function onImage(event) {
    console.log(event.offsetX, event.offsetY)
}
</script>





Answer:
If you don't mind adding some additional HTML and CSS:


function onButton() {
  const img = document.querySelector("#img");
  img.style.scale = 5.0;
  const target = document.querySelector("#target");
  target.style.scale = 5.0;// make sure target's style matches img's style
}
function onImage(event) {
  console.log(event.offsetX, event.offsetY);
}
#wrapper {
  display: inline-block;
  position:relative;
  font-size:0;
}
#target{
  position:absolute;
  width:100%;
  height:100%;
}
#img {
  transition: 5s ease;
  z-index:2;
  pointer-events:none;
}
<button onclick="onButton()">Zoom</button>
<br>
<div id="wrapper">
  <div id="target" onclick="onImage(event)"></div>
  <img id="img" src="https://picsum.photos/id/237/200">
</div>



This work by zooming an invisible div behind the image without transition, and transfer the click event to that div instead of the image itself
Question: How to ignore safe area for a background with a linear gradient and image in swiftUI?

I have a VStack like this:
    var body: some View{
        VStack{
            //some view
        }
        .background(
            ZStack{
                LinearGradient(gradient: Gradient(
                    colors: [
                        .yellow_500,
                        .yellow_500,
                        .yellow_500,
                        .yellow_50
                    ]), startPoint: .top, endPoint: .bottom)
                .ignoresSafeArea(.container, edges: [.top])
                
                
                Image(R.image.home_bg_try.name)
                    .resizable()
                    .scaledToFill()
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .ignoresSafeArea(.container, edges: [.top])

            }
//                .offset(y: -20)
        )
    }


I want the image to be displayed without considering the safe area, which currently results in a white space appearing at the top, as shown in this image: (https://i.stack.imgur.com/knRdm.png).
I attempted to fix this issue by adding an offset, but I noticed that the height of the white space varies across different models.
How can I resolve this problem?


Answer:
Your current setup has the right idea, but if you want to completely ignore the safe area for the VStack's background, you should apply the .ignoresSafeArea() modifier on each of the backgrounds.
The white space you are seeing might be a result of the VStack not filling up the whole screen.
Try moving .ignoresSafeArea() modifier outside of the ZStack, and apply it to the whole VStack. Here is the updated code:
var body: some View {
    VStack{
        //some view
    }
    .background(
        ZStack {
            LinearGradient(gradient: Gradient(
                colors: [
                    .yellow_500,
                    .yellow_500,
                    .yellow_500,
                    .yellow_50
                ]), startPoint: .top, endPoint: .bottom)
                .resizable()
                .aspectRatio(contentMode: .fill)

            Image(R.image.home_bg_try.name)
                .resizable()
                .scaledToFill()
                .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    )
    .ignoresSafeArea()
}

By using .ignoresSafeArea(), you instruct SwiftUI to layout the VStack and its background across the whole screen, including under the status bar and home indicator on iPhone models with edge-to-edge screens.
Additionally, you might want to apply .edgesIgnoringSafeArea(.all) instead of .ignoresSafeArea() in certain situations. For example, if your view doesn't play well with safe area insets when it's embedded in another view hierarchy, you might find .edgesIgnoringSafeArea(.all) works better. However, in SwiftUI 2.0 and later, .ignoresSafeArea() is generally recommended.
Question: How to conditionally assign a value to Flutter List

How to conditionally assign a value to "ingList" based on the value of recipeList?
 class Calculator extends StatefulWidget {
    List<IngredientList> recipeList;
    Calculator(this.recipeList, {Key? key}) : super(key: key);

  @override
  State<Calculator> createState() => _CalculatorState();
}

class _CalculatorState extends State<Calculator> {
  List<IngredientList> ingList = [];



Answer:
You can use initState to do that
class Calculator extends StatefulWidget {
  List<IngredientList> recipeList;
  Calculator(this.recipeList, {Key? key}) : super(key: key);

  @override
  State<Calculator> createState() => _CalculatorState();
}

class _CalculatorState extends State<Calculator> {
  List<IngredientList> ingList = [];

  @override
  void initState() {
    super.initState();

    ingList = widget.recipeList; // you can do any condition here
  }
}
Question: How can I use url query parameter to set the value of a 'Parameters' in PowerBI?

In PowerBI, I have a managed parameter which is a list of text.
abc, def, ghi.
And that parameter is being use to call a custom function in powerbi i.e. MyCustomFunction(@Name)
My question is how can I change the value of the parameter from the url when I load the report (after i published it to PowerBI service)?
i.e. I would like to
https://mypowerbi url?filter Name eq 'abc'  
`MyCustomFunction('abc')' will be called.

https://mypowerbi url?filter Name eq 'def'  
`MyCustomFunction('def')' will be called.




Answer:

My question is how can I change the value of the parameter from the url when I load the report (after i published it to PowerBI service)?

You can't. In Power BI reports, the URL query parameters can be used to filter the report. See Filter a report using query string parameters in the URL
Parameters can be set from the URL in paginated reports only (legacy from SSRS). See Pass a report parameter within a URL for a Power BI paginated report.
For Power BI reports published to Power BI Service, the parameter values can be changed from the dataset's settings. See Edit parameter settings in the Power BI service. Keep in mind that this affects all users, who see the report, and it is not something that can affect your viewing session only. Changing parameter values of imported datasets usually will take a dataset refresh for the changes to take effect.
Parameters of published reports can also be updated using the Power BI's REST API - see Update Parameters and Update Parameters In Group.
Question: Need help personalizing my CSS navbar: how do I highlight the  element on mouseover?

I am trying to make a simple navbar I managed to make the base but when I try to personalize I am getting stuck.
My objective is that when the mouse goes over each element(home, etc) it highlights like a box, but currently it only highlights the <a> I tried and not the <li> holding it.
I'm trying to make the <li> an anchor that can be clicked and highlighted similar to stack's navbar.


.nav-top {
  background: rgb(151, 138, 63);
  margin: 0;
  padding: 1rem 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.nav-item {
  list-style: none;
  margin-right: 1.2rem;
  padding: 5px 10px;
}

.nav-top ul {
  margin: 0 auto;
  padding: 0;
  list-style: none
}

.nav-top li:hover {
  display: block
}

.nav-top a:hover {
  background: #F2F2F2;
  color: #444444;
}

.nav-item a {
  text-decoration: none;
  color: white;
  width: 100px;
}

.nav-item:first-child {
  margin-right: auto;
  margin-left: 2rem;
}

.nav-item a:hover {
  color: aqua;
}
<navbar>
  <ul class="nav-top">
    <li class="nav-item"><label class="logo">LoremX</label></li>
    <li class="nav-item"><a href="index.html">Home</a></li>
    <li class="nav-item"><a href="#">About</a></li>
    <li class="nav-item" id="contact"><a href="#">Contact</a></li>
  </ul>
</navbar>





Answer:
The only :hover declaration you have for li is the default value of display: block while the color change declarations are made only for a. However, the effect that I believe you are trying to achieve is better accomplished by making the anchors block-level with padding.
Not related to the hover effect, just correcting your markup:

You have .nav-top ul selector but the example doesn't include a nested ul
I suspect that you are misusing the label element.
navbar is not an HTML element and I suspect you want nav



.nav-top {
  display: flex;
  margin: 0;
  padding: 0;
  list-style-type: none;
  background: rgb(151, 138, 63);
}

.logo {
  margin-right: auto;
  margin-left: 2rem;
  padding: 5px 10px;
  align-self: center;
}

.nav-item {
  margin-right: 1.2rem;
  padding: 5px 10px;
}

.nav-item a {
  display: block;
  padding: .5em;
  text-decoration: none;
  color: white;
}

.nav-item a:hover {
  color: aqua;
  background: #F2F2F2;
}
<nav>
  <ul class="nav-top">
    <li class="logo">LoremX</li>
    <li class="nav-item"><a href="#">Home</a></li>
    <li class="nav-item"><a href="#">About</a></li>
    <li class="nav-item" id="contact"><a href="#">Contact</a></li>
  </ul> 
</nav>
Question: Mysql in docker container doesn't accept credentials

I have a Dockerfile which I later want to feed some initial sql dump into:
FROM mysql:debian

EXPOSE 3306

ENTRYPOINT ["docker-entrypoint.sh"]

CMD ["mysqld"]

Then there is my docker-compose.yaml:
version: '3'

services:
  mysql:
    container_name: ${CONTAINER_NAME}
    build:
      context: .
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=${ROOT_PASSWORD}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_DATABASE=${MYSQL_DATABASE}

I can docker exec -it sqlcontainer mysql -uroot -p into my container just fine (works with the $MYSQL_USER as well), but when I try to do the same from outside, e.g. with  mysql -uroot -p, I always get ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES).
I'm out of my wits. What am I doing wrong? The communication to mysqld inside the container apparently works, otherwise I wouldn't get back any response.
I'm on Windows, if that's a hint for anyone. But the above is true for PowerShell, CMD and even Git Bash.


Answer:
It is embarrassing to admit, but both commenters @RiggsFolly and @DavidMaze are right in what they said: I hadn't used MySQL for quite a while on my machine. When I checked the task manager, I indeed found a local mysqld running already, which of course was primed with different credentials. After killing the process (and adding the missing port in the compose file), I was able to connect to my containerized instance.
Hope this will help out somebody else in the future who falls into the same trap.
Question: Why seize queue cant be zero in AnyLogic

Let's imagine a situation where we have a queue positioned before the seize block, and this queue has the timeout property activated.
In such cases, it is important to note that the seizure queue cannot be reduced to zero. The seize queue always has a minimum capacity of 1. If the seize queue capacity were set to 1, one agent would be taken out of the timeout property of the original queue and placed directly into the seize queue.
This behavior is generally not desirable, particularly when dealing with a large number of agents or running the simulation for extended periods, such as years, to collect the statistics, especially for the timeout property of the original queue.

So how can I avoid having an agent in the seize queue, or is there another way to achieve this?


Answer:
You can manually avoid having agents in the Seize queue by using a Hold block upstream and only releasing agents into the Seize block if its queue is empty.
Question: R - How to rename xml parent node based on child element (or associate child elements)?

I'm trying to extract a couple of elements from XML files into an R dataframe but the parent nodes are all named the same, so I don't know how to associate child elements. I'm very new to xml (about 3 hours) so apologies if I use the wrong terminology. I did not find any R-based solutions.
This is the general structure of the xml files:
<Annotations>
    <Version>1.0.0.0</Version>
    <Annotation>
        <MicronLength>14.1593438418</MicronLength>
        <MicronHeight>0.0000000000</MicronHeight>
        <ObjIndex>1</ObjIndex>
    </Annotation>
    <Annotation>
        <MicronLength>5.7578076896</MicronLength>
        <MicronHeight>0.0000000000</MicronHeight>
        <ObjIndex>2</ObjIndex>
    </Annotation>
</Annotations>

There are many "Annotation" nodes. There are also several other children node names in there but they don't matter as I'm just trying to extract MicronLength and ObjIndex into a dataframe. So I need to either:

Associate and get both elements from within each "Annotation" node

OR

Rename each "Annotation" based on the ObjIndex within (e.g. "Annotation 1", "Annotation 2", etc.) and then get parent name and child element into the df.

I also have several xml files so I want to iterate over each one to eventually create a DF like the example below.
| filename           | ObjIndex | MicronLength  |

| ------------------ | -------- | ------------- |

| examplefile1(.xml) | 1        | 14.1593438418 |

| examplefile1       | 2        | 5.7578076896  |

| examplefile2       | 1        | 12.6345661343 |


The filenames (with or without extension) will then be str_split into some more columns but I can do that myself.
Much appreciated!


Answer:
I have previously used xml_find_all() for this kind of simple conversion.
This works as long as each Annotation node always has exactly
one ObjIndex and MicronLength child node:
library(xml2)

xml <- read_xml("
<Annotations>
    <Version>1.0.0.0</Version>
    <Annotation>
        <MicronLength>14.1593438418</MicronLength>
        <MicronHeight>0.0000000000</MicronHeight>
        <ObjIndex>1</ObjIndex>
    </Annotation>
    <Annotation>
        <MicronLength>5.7578076896</MicronLength>
        <MicronHeight>0.0000000000</MicronHeight>
        <ObjIndex>2</ObjIndex>
    </Annotation>
</Annotations>
")

data.frame(
  ObjIndex = xml_integer(xml_find_all(xml, "Annotation/ObjIndex")),
  MicronLength = xml_double(xml_find_all(xml, "Annotation/MicronLength"))
)
#>   ObjIndex MicronLength
#> 1        1    14.159344
#> 2        2     5.757808
Question: How to set UID and GID for the container using python sdk?

How to set UID and GID for the container when Python SDK is used to spin up the container?


Answer:
As the documentation you've linked says, pass in user and group_add to run():
client.containers.run('alpine', 'echo hello world', user='foo', group_add=[123])

Both accept both IDs and names, but group_add needs to be a list.