fredag 22 juli 2022

From a list, count how many numbers are within the standard deviation from the mean. (Python)

heights = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]

height_sum = sum(heights)
mean = height_sum / len(heights)

# **2 makes negatives (heights less than the mean) become positive.
diff_list = [(x - mean) ** 2 for x in heights]
variance = sum(diff_list) / len(heights)

# We get the square root in order to get back the original units.
standard_deviation = variance **0.5

# Now we just need to find out how many heights are within the
# standard deviation from the mean.
count = 0
upper_lim = mean + standard_deviation
lower_lim = mean - standard_deviation

# Count how many heights are within the
# standard deviation from the mean.
for height in heights:
    if lower_lim < height < upper_lim:
        count += 1
       
print(count)






''' Or as a class, initiated with the heights list: '''

class Std():
   
    def __init__(self, data: list):
        self.data = data
        self.mean = self._get_mean()
        self.var = self._get_variance()
        self.std = self._get_std_from_var()
       
        self.upper_lim = self.mean + self.std
        self.lower_lim = self.mean - self.std
   
        self.in_range = lambda x: self.lower_lim < x < self.upper_lim
        self.count_within = len(list(filter(self.in_range, self.data)))

    def _get_mean(self):
        return sum(self.data) / len(self.data)

    def _get_variance(self):
        diff_list = [(x - self.mean) ** 2 for x in self.data]
        return sum(diff_list) / len(diff_list)

    def _get_std_from_var(self):
        return self.var **0.5

std = Std(heights)
print(std.count_within)

måndag 11 juli 2022

OpenArtViewer

I've made an art viewer program in Unity. I'm now working on database update automatization in Python. That is because the files with art information provided are updated frequently.

OpenArtViewer uses the National Gallery of Art Open Data API and data from Metropolitan Museum of Art. The included SQLite database has stored info about the artworks in public domain (100K+) including image links to the artworks on the NGA and MM servers. 

From the GUI you can search type of art and by title, year, artist. To the left there's a scroll bar with the results as thumbnails. These can be clicked to get more information and a higher resolution version of the artwork in the big panel to the right. A high resolution image can then be downloaded. 

Download this program (Windows) https://wartem.se/files/OpenArtViewer.zip




National Gallery of Art

Metropolitan Museum of Art

lördag 9 juli 2022

Flask - Absolute basic client input and render

The following example shows how you can handle input with Flask and update pages, in this case with the user input sent back to the client. 

I'm making this as short as possible. 

Requirements: pip install Flask 

Implementation: 
1. In your project root dir create: A file named app.py 
2. In your project root dir create: A folder named "templates" and inside a file named "index.html" 


index.html 
<html lang="en"> 
  <head> 
  <title>Flask Basic Example</title>
  </head>  
  <body>    
  <h1>Flask Post: {{ text_to_show }}</h1>    
  <form action="/" method="POST">      
  <input type="text" name="content" />     
  <input type="submit" />    
  </form>  
  </body></html>

app.py
from flask import Flask, render_template, request
app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        user_input = request.form['content']
        return render_template("index.html", text_to_show=user_input)
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True, port=5000)

How it's used: Run app.py and go to http://127.0.0.1:5000 in your browser. Type some input, press send and the server will update the HTML with your input in a HTML paragraph. The Internet is full of extensive guides and tutorials. Sometimes you just want a quick example.

Python Virtual Environment Setup

Working in a virtual environment is easy to setup and makes life easier thanks to the project isolation and dependency management.
Run once:
py -m pip install --user virtualenv
Run in project folder:
py -m venv env
Run in project folder:
.\env\Scripts\activate
Done! Happy coding.

torsdag 25 november 2021

Smooth Zooming with Cinemachine (Unity)

Zooming a Cinemachine Virtual Camera with 3rd Person Follow by changing the camera distance works but there are no transitions between the steps.

There are other ways to zoom that look better.

One way to get it smoother I found out  is to add a extension to your virtual camera called Follow Zoom. It's a script and comes with values you can change in the inspector. The Follow Zoom extension can be added at the bottom of your virtual camera, in the inspector.

You can use the input you use for zoom to alter these values in a script of your own. You use a reference to your virtual camera and do .GetComponent<CinemachineFollowZoom>() to get the Follow Zoom script.

Once you have the Follow Zoom extension you can change the values of these variables to get a desired transition in your zooming:

_cinemachineFollowZoom.m_MinFOV += zoomInput;

_cinemachineFollowZoom.m_MaxFOV += zoomInput;

_cinemachineFollowZoom.m_Width += zoomInput;


ZoomInput above is calculated from the Input Action Asset made in "new" Input System. It's a Vector2, triggered by scrolling and pressing the gamecontroller defined in a created input asset, attached to a Player Input component, added to the player GameObject. Google Unity Input System to learn how to use it. It's not as complicated as it might look.


You will need checks to make sure you stay within the limits set in the inspector.

These conditions aren't allowed:

if (zoomInput > 0 && cineMinFoV >= cineMaxFoV)

if(zoomInput < 0 && cineMinFoV < 1)


I found a value of about 1-4 is pretty good to set "Damping" to in the inspector and Min FOV to 2. Damping needs to be above 0.

måndag 15 november 2021

Unity - How to get access and change the camera distance while using Cinemachine "3rd person follow" (C#)

Cinemachine https://unity.com/unity/features/editor/art-and-design/cinemachine

saves time by letting you create difference kinds of cameras.


Let's say you want to use the input system and scroll the mouse to change the camera distance.

I couldn't find a clear solution online so I thought I share:


First make sure you have:

A player GameObject.

A GameObject with a CinemachineVirtualCamera, set to: 

* follow the player.

* its "Body" set to "3rd Person Follow".


Note: You have other body properties as well to chose from:

3rd Person follow

Framing Transposer

Hard Lock to Target

Orbital Transposer

Tracked Dolly

Transposer


We are focusing on the "3rd Person Follow" now.


In the script that you add as component to the player GameObject:


Declaration: 

private GameObject _playerFollowCamera;

public CinemachineVirtualCamera _cinemachineVirtualCamera;


In private void Start() :

_playerFollowCamera = GameObject.Find("PlayerFollowCamera");

_cinemachineVirtualCamera = _playerFollowCamera.GetComponent<CinemachineVirtualCamera>();


          In your method, called when scrolling for example: 

CinemachineComponentBase cinemachineComponentBase = _cinemachineVirtualCamera.GetCinemachineComponent(CinemachineCore.Stage.Body);


if (cinemachineComponentBase is Cinemachine3rdPersonFollow)

{

(cinemachineComponentBase as Cinemachine3rdPersonFollow).CameraDistance = yourCameraDistanceValue;

}


Or as one line:

(GameObject.Find("PlayerFollowCamera").GetComponent<CinemachineVirtualCamera>().GetCinemachineComponent(CinemachineCore.Stage.Body) 

as Cinemachine3rdPersonFollow).CameraDistance = yourCameraDistanceValue;


"Cinemachine3rdPersonFollow" above is changed depending on which body property you are using.


måndag 4 januari 2016

GTA V: Change vehicle sounds on any vehicle to any sound

It's really easy to change the sounds on any vehicle to any other vehicle sound in GTA V.

Before we start, make sure to use OpenIV with the mods folder for safety: http://openiv.com/?p=1132

This is how you do it:
1. Go to update\update.rpf\common\data\levels\gta5 with OpenIV
2. Right click on vehicles.meta and press "Save content/ Export".
3. Open the file that you exported with notepad.
4. Find the vehicle model you want to change (CTRL+F and then search for modelName). If you are unsure which model it is you can use Native Trainer to spawn them and find out.
5. Look for "<audioNameHash />" under your model name. Replace it with "<audioNameHash>PutYourModelNameHere</audioNameHash>" and instead of "PutYourModelNameHere" you write the name of the model you want to use the sound from. Here are all model names: http://pastebin.com/i4AX8kBY (taken from Alexander Blades Native Trainer source).
6. Save the file, go back to OpenIV and replace the vehicles.meta with your version of it.
7. Start GTA V try it out :)

Tip: A sound that I like a lot is the engine sound of Stirling GT with model name FELTZER3. That would be <audioNameHash>FELTZER3</audioNameHash>