Alex Turner

Writing about learning Python and the odd bit of Linux related stuff I come across and find helpful. A bit about cycling. Long distance audax. The odd comment on unrelated ideas that I feel benefit from thinking about, writing down and sharing. That kind of thing. Enough is plenty. Good enough will do.

Paradigms of Programming

Object orientated programmiing (OOP) and functional programming (FP). I'd heard both terms often enough to wonder what each involved. I knew that OOP in Python involved classes. I have not been using classes. I use functions though. Must be FP I'm doing.

No! Stop! Not the case at all. Functional programming is very different. Specialised. Math based. Declarative. Turns out it's structured programming that has been my default style. General purpose. Got more of an idea now how to structure code into a programme.


Procedural Orientated Programming (POP)

  • AKA procedural or imperative programming style.
  • A traditional procedural program is organised to take input data, process it and produces result. Programming is centralised around logic rather than data.
  • The data (stored in variables) is passed to a defined function which in turn performs some action and modifies it or creates new data.
  • The style may be thought of as a list of instructions which gets executed in an orderly manner defined by control flow statements and functions.
  • In POP write your code the way you would write an essay: from top to bottom.
  • There is no connection, no relationship between the data being used and the procedures which use them. One procedure could alter a data structure and then a seemingly unrelated procedure could also alter it.

Back in the eighties I was introduced to BASIC using my dad's Commodore 64, a friends ZX Spectrum and a BBC Micro. BASIC was very much POP. Code lines were numbered as ’10, 20, 30’ etc. If I wanted the program to repeat something done earlier, then the command ‘GOTO [line number]’ or 'GOTOSUB [line number]' to get it to jump back, do the thing and then continue to progress as before.

As a POP code base gets larger it can become complicated to navigate. With commands that jump between points it gets tricky to follow the flow. Finding errors when things go wrong may be a challenge. Code like this is sometimes called 'spaghetti code’.

Structured Programming

Structured Programming came about to overcome this problem. With the paradigm came the ability to reduce if not elminate the necessity of employing the GOTO statement.

  • Structured Programming is AKA Modular Programming
  • Structured Proramming is a discipline or subset of Procedural Programming.
  • It aims to improve the quality and clarity of the code. The execution of the program becomes more logical and readable. Structured programming involves 4 elements: sequence, iteration, selection, and subroutines.
  • Sequence: As for POP, code is written in sequential order top to bottom.
  • Selection: Such as if…elif…else statements. The execution of the subsequent code depends upon the selection statement.
  • Iteration: Execute a block of code again and again with the help of loop statements.
  • Subroutines: Programs are devided into a set of functions. Each of these functions performs a subtask. Having each function represent a specific functionality can make it easier to test and debug the code.

The focus of procedure orientated and structured programming is to break a programming task into a collection of variables, data structures, and subroutines. Small programs and scripts tend to be easier to develop using a simple procedural or structured programming approach.

Structured programming is a logical programming method that is considered a precursor to object-oriented programming (OOP).

Object Orientated Programming (OOP)

  • Object oriented programming uses 'objects' AKA 'instances' to to represent real-world scenarios and/or objects.
  • An object has states and behaviours.

    • Car, Person, Team etc. could all be objects.
    • States represent attributes or data of an object.

      attributes:
      
      make = 'Toyota'
      age = 21
      size = 'activity'       
      
  • Methods (functions in structured programming) represent the behaviours of objects.

  • An object is defined by a class. A class describes how an object is designed, i.e. which attributes and methods it has.

  • A class should not be confused with an object.

  • Objects may interact with other objects.

As for structured programming there are four main principles in OOP.

  • Encapsulation – attributes and methods are bound into a single unit - an object/instance of a class.
  • Inheritance – allows a class to use properties and methods of an already existing class. This makes the code reuseable and quicker to modify if needed.
  • Polymorphism – allows an object to perform in multiple ways. Methods and properties of the parent class can be modified as required. New methods and attributes may be added. Class attributes may be overwritten per instance. Objects are powerful!
  • Abstraction – hides the internal details and displays only the functionalities (of the instance) to the user – Moreover, abstract classes and interfaces (CLI, GUI) help to achieve abstraction.

Interest leading to this learning was prompted by a project I am working on. An allocations / shift coordinations app. I was stuck. Virtues of OOP had come into my awareness. Reading up a bit on structured programming and OOP seemed a good thing to do. This has led me to think an OOP approach may be the way to go and something I should learn.

Progress is being made with understanding OOP. Code has been refactored. The problem I was stuck on got solved using an instance method of an object created with the built in function iter() Allocate two staff to a task if a conditon is met else just one by default.

    if patient[1] == '2:1':
        print(next(staff_iter), staff_iter.__next__())
    else:
        print(next(staff_iter))

Friday 26th March 2021

Recently been listening to the PyBites Podcast. Good balance of content with a relaxed conversational tone. Measured whilst explicit enthusisam for the subject.

The PyBites Podcast is a podcast about Python Development, Career and Mindset skills. Hosted by the Co-Founders of PyBites, Bob Belderbos and Julian Sequeira, this podcast is for anyone interested in Python and looking for tips, tricks and concepts related to Career and Mindset. For more information on PyBites and Python, visit us at PyBites and hit us up on social media!

Bob and Julian talk a lot about mindset. Bob spoke in one episode of the benefit in framing goals in the present tense. That struck a chord with me.

I am a software developer! I am writing a program to substantially automate a thankless task which is being completed manually every shift at work.

It was in part an idea to build something similar to this that got and has kept me interested in learning to write code.

Success with the program will look like the job being done in a fraction of the time. Minutes instead of around an hour or so. Hourly functions over the shift will be distributed optimally between the team. Breaks and key responsibilities can be allocated with reference to scheduled tasks. Allocation tables will be generated.

Very good progress made this week. Coded some key stages in the program. Got over the disapointment and challenge of a false summit.

Getting more practice with dict(zip(), iter(), .pop() and .insert()

Found out about and had a go with itertools and more-itertools. Not needed so far but good to have the awareness of them both.

Todos are many. Essential is to allocate breaks. That may lead to refactoring hours to half hours. Secondary may be to conditionally auto allocate some key tasks. Include a database and user front end within the next two weeks? Maybe. CLI to demo definitely.

Thursday 18th March 2021

Learning to code using Python


The last week or so has been great. It feels like progress.

Tutorial hell, purgatory, paralysis... About 14 months of it. It's not been bad at all. I have enjoyed it.

I quickly learned that tutorial videos are a waste of time for me. I zone out and day dream. Written tutorials, coding exercises, blog post, podcasts, newsletters, coding playlists, books and Slack channels have though been of benefit.


Python : sets and dict(zip()

The Python dict(zip(iterable1, iterable2)) function is great. Take a couple of iterables (same length) and with just one line of code turn them into a dictionary. Other data structures can also be zipped but not yet had much call for them yet. The time will come and when it does I'll be ready!

Discovered something useful you can do with sets.

display = 'abracadabra'

letter_count1 = [(display.count(letter)) for letter in set(display)]
letter_count2 = [(display.count(letter)) for letter in display]

print(letter_count1)
[5, 2, 1, 1, 2]  # using a set getting the frequency count of each letter a[5], b[2], c[1],  d[1], r[2]  in the word. Duplicates are excluded.

print(letter_count2)
[5, 2, 2, 5, 1, 5, 1, 5, 2, 2, 5]  # using  a list getting the frequency count of each letter in the word as they appear in the word. Duplicates are not excluded. 

The allowed the creation of a dictionary with key, value pairs of letter and frequency count using the dict(zip()) function .

word = 'abracadabra'

letter_count_list = [word.count(letter) for letter in word]
letter_count = [(word.count(letter)) for letter in set(word)]  # using set counts but hides duplicates!
dictionary = dict(zip(set(word), letter_count))

for k, v in dictionary.items():
    print(k, v)

d 1
c 1
a 5
r 2
b 2

Tuesday 9th March 2021

It's been a couple of weeks since the last journal. That's okay. Just start again. Not the first time being I am human.

Same applies for most endeavours. The gap between intention and action. Consistency is the gold standard. Cutting down time between stopping and starting again is a good enough strategy.


You are as one, god and the devil. Among those who have you incarcerated there are some with malevolent intent. One of them is a shape shifter. Their leopard eyes and changing face gives them away. They try to project psychosis into your brain. You fight it off. That's very tiring. You wear a cloth over you head. Does not always work. You have justified the use of lethal violence to protect yourself should it be necessary.

Something I have become involved with. Not a typical work day problem.


Listening to a podcast this morning about habits. The focus was on the power of habits and mechanism to develop them. All sound research based ideas. There was a bit of 'power up your productivity' hyperbole about it. Nothing though was spoken about what can make us vulnerable to dropping habits we had assumed had become established.

Changes in routine. That's a big one for me. Swapping each month between working days and nights. A change of environment. How many habits fade away during a holiday away? Sickness and fatigue. So many more.

Recognise and accept the humanity in your being and endeavours. Understand that resolve and intention are finite. Forgive yourself for being human. Start again. Pick up where you left off. It still counts.

Thursday 19th February 2021

Leadership as an art. What’s 'right' gives way to what works; who’s 'in charge' gives way to who’s committed.

So many 'leaders' seem to have characteristics quite the opposite of the what the title suggests. Many seem subservient, acquiescing conformists. Self interested career seekers wilfully complicit in maintaining the status quo. Compliant.

In England the regulators of children's and adults health, social care and education all grade services from inadequate through to outstanding. Outstanding is an amorphous rating in that there is no agreed criteria for what it looks like. What there is though is an emphasis on innovative practice. To be outstanding you need to be innovative.

Conformists are perhaps unlikely to be innovators. They are though good at dodging bullets and taking credit when its given once the dust has settled.

In the meantime what's 'right' gives way to what works; who’s 'in charge' gives way to who’s committed. An so it goes on...

Wednesday 17th February 2021: Python Virtual Enviornments.

Virtual Environments in Python

This is an exercise in seeing what I remember about using virtual environments for Python projects.

What might happen if you do not use a Virtual Environment for your Python project?

Dependencies required of the project may end up clashing with other versions installed or that get installed at a later date. Your code may not run.

Say you imported xxx v0.1 module / package for project a1 with python 3.8 being the base install of Python which is used as the project interpreter.

Over time your Python install and pip packages may get updated. Or perhaps you create another project and imported xxx v0.1.2 module / package for project a2 with python 3.9 which is now the base install of Python.

When you run your project a1 it no longer works. This is because there are now two versions of xxx module / package and Python cannot differentiate between them. It may also be broken by the different Python version in the base install.

To avoid this you use Virtual Environments. You create a virtual environment to build your script / project in. This means that the project is isolated in it's own environment.

You can choose which version of Python to use for each environment and whether to install all global packages or to start wtih a clean slate.

Changes to the base install of Python will not be made which is good for stability.

In summary using a virtual environment for each project reduces the risk of version conflicts between modules / packages and Python interpreters any of which may stop your code from running.

Hope that's not too far off the mark and I've not spread falseities. For a better explaination see here and here

Sunday 13th February 2021 Super Productivity

I was looking for a Pomodoro app that included a function to keep a brief note on whatever it was I was doing for the session.

I found one. Super Productivty. It does what I wanted and a whole heap more. If you like the idea of this type of thing you should try this one out.

It's FOSS and cross platform. There is no data sharing with third parties. Syncs to NextCloud via WebDav. It has it all with bells on and is being activly developed. You can even intergrate GitHub, Jira and/or GitLabs with it.

Maybe the novelty but the last few days I have got a good amount done. Getting enthusiastic about todo lists and seeing where some of my time goes. Highy rated. Give it a go. Super Productivty

Friday 12th February 2021: Pinacle Dolomite LTD

Repairs for the Specialized Crux were adding up to over £700. Decided to get a new bike. Details here are primarily for my own reference. Text mostly taken from the eBay description. I thought it read well.

Pinnacle Dolomite LTD 2017
Pinnacle Dolomite LTD 2017

Size wise this is an XL model and a sticker on it says it is suitable for riders from 6'1" to 6'4". This seems a little optimistic as I am 5'11" tall and it feels the right size for me. I would say it would fit someone in the height range 5'10" to 6'.

The bike is based on a 2017 Dolomite LTD which was a fast/light touring or Audax bike and was the top-of the range model. Fitted with full mudguards, front hub dynamo and a full set of lights. Later models were fitted with inferior components, for instance the full carbon fiber forks were replaced with forks with an aluminium steerer and the wheels were down-graded. This 2017 model with its 'extras' had a mass of just 10.5kg.

A number of changes have been made to make the bike more comfortable, resilient and maintainable. These include:

  • A shorter steeper handlebar stem.
  • Replacement of the handlebars with ergonomic carbon fiber bars (for comfort).
  • Replaced the seat pin with a carbon fiber pin (for comfort).
  • Added 18 (2x9) speed Shimano Sora R3000 gears (why 9 speed, see here.
  • Added TRP Spyre twin 'piston' mechanical disc brakes (for simplicity and maintainability).
  • Added a 175mm Shimano GRX800 46/30t chain-set (to give lower and a better selection of gears).
  • Fitted a 11-32tooth 9 speed Ultrgra level cassette. New chain just fitted.

The bike includes as original:

  • The aluminium alloy (titanium coloured) frame in XL size.
  • Full monocoque carbon fiber forks.
  • The original 700c disc wheels with Alexa asymmetric rims. Rear hub is Novatec and the front is the Shutter Precision dynamo. The wheels run true. The rims are Tubeless ready.
  • Schwalbe Pro 1 28mm tyres (little used). These are tubeless tyres but I run them with tubes.
  • Original saddle.
  • Original lightweight mudguards. Extra Parts Supplied:
  • The original stem.
  • Spare brake pads.
  • Two bottle cages.
  • An out front Garmin mount.

Used for 5000km, but many of the items had much less use (tyres ~1000km; chain-set ~500km; handlebars and stem ~2000km). There was a recall on the rear wheel on this model; the rear wheel was replaced under guarantee.

Original Product Specifications: Pinacle Dolomite LTD 2017 (L)

  • Product Name Dolomite LTD
  • Brand Pinnacle
  • Size L
  • Rear Wheel Weight 1810
  • Wheelbase (cm) 102
  • Top Tube (cm) 55.5
  • Seat Tube (cm) 47
  • Chainstays (cm) 43
  • Wheelset Alex Draw 1.9s, SP dynamo hub (f), Novatec (r)
  • Weight (kg) 10.03
  • Trail 6.1
  • Stem Pinnacle Road alloy
  • Shifters Shimano RS685 hydraulic
  • Seatpost Pinnacle aluminium
  • Seat Angle 74
  • Saddle Pinnacle Race Mens
  • Rear Tyre Schwalbe Pro One, 28mm
  • Bottom Bracket BSA
  • Rear Derailleur Shimano 105
  • Headset Type FSA Orbit C Head Angle 72
  • Handlebar FSA Omega alloy
  • Front Wheel Weight 1660
  • Front Tyre Schwalbe Pro One, 28mm
  • Front Derailleur Shimano 105
  • Frame Material 6061-T6 double- and triple-butted alloy
  • Fork Offset 4.5
  • Fork Carbon, 12mm thru-axle
  • Cranks Shimano 105, 50/34
  • Chain KMC X11
  • Cassette Shimano 105 11-32
  • Brakes Shimano RS805 hydraulic disc, 160mm/140mm rotors

Monday 8th February 2021

exercise
Finished the 100 push up plan last week on Friday. Second time round. This iteration from day 1 week 4. Best effort to date is 80 without a break. Started again today from day 1 week 1 using the perfect push up handles. Just finished today's effort with the boys. Feels a lot harder like this. Feels like more effort on the arms with the improved form the handles promote. Max today on the last set was 15.


self efficacy
Spent some time yesterday and today thinking about and filling in workbooks to help with realising priorities, planning goals and creating some helpful habits to live by.

As much as these things appeal to me I have often stopped short of following through the process. Not this time. Surprised how engaged I quickly became. The resources I used were kindly published by Christine Carter. Feeling enthused about about getting my bearings and adjusting my heading.


NextCloudPi
Spent a few hours over the weekend sorting out the NextCloudPi install. I have the NC bootloader and database on a USB drive plugged into a Raspberry Pi. The USB drive died along with an external HDD I sync NC snapshots to along with backed up NC config file. Seems a bit of a coincidence that the HDD went at or around the same time as the USB drive.

Nothing was lost. I was able to recover all files from the snapshots I had saved to the HDD used to store the NC data on. The config settings were simple enough to remember. Formatted the HDD that failed and got it working again. It would be sensible to replace it soon.

A fresh NCP image flashed to a new USB drive. Used the occasion to switch out the Raspbery 3b+ for a Raspberry 4. All back up and humming along nicely. It's noticeably faster in loading resources.

Thursday 4th February 2021

“I am not what happened to me, I am what I choose to become.” Carl Jung

Dealing with stuff. Adapting. Changing direction. Setting a new heading.

The push bike needed new forks. This together with all the other bits took it close to the limit of economical repair. Went instead for a suitable replacement. A good deal on eBay from a cycling enthusiast. Arrived today in a box. Bit busy so took it to my bike shop to rebuild. Very well packed. The old bike can be used to donate parts for use or sale. Turned out pretty good.

Tuesday 2nd February 2021

Your individual decisions and habits count, no matter how small they may seem. Similar actions taken by lots of people have a big impact.

Evolution is perhaps better when it's slow enough to not notice happening.

Many people think that the industrialised rearing and slaughter of animals for food is distasteful and harmful to the environment. They still eat meat though. I don't get that. Get over bacon. Taste is only a sensation.

I don't get why when people become aware of and accept the science on climate change they fail to do much to reduce their carbon footprint.

It makes no sense why aspiration and acquisition are seen as positive states. Seems like it will always leave you wanting for more.

Convenience and quick wins over sustainability and symbiosis is one road to ruin. How come we choose not to do what we often know is right? Does it come from thinking that what we do as individuals does not matter that much?

Our choices and decisions matter. To those making them and to the collective called human. Turn off autopilot and think about the greater good.

Friday 29th January 2020

The Linux script command.

Linux has a built in command called script. Invoking it generates a file that effectivly records everything which is subsequently typed into and/or displayed in the terminal until such time ctrl d is pressed. Doing so ends and saves the session. Play back in the terminal is as simple as invoking another command together with the path to the saved file.

script --help

Make a typescript of a terminal session.

Options:
 -a, --append                  append the output
 -c, --command <command>       run command rather than interactive shell
 -e, --return                  return exit code of the child process
 -f, --flush                   run flush after each write
     --force                   use output file even when it is a link
 -o, --output-limit <size>     terminate if output files exceed size
 -q, --quiet                   be quiet
 -t[<file>], --timing[=<file>] output timing data to stderr or to FILE
 -h, --help                    display this help
 -V, --version                 display version

Simply entering...

$ script --t=script_log -q scriptfile

...will invoke script.

To play back the session it's...

scriptreplay --timing=script_log scriptfile

More details for reference here. Could be good to include in a repo as a means to demonstrate functionality of a CLI. More typical I suppose would be to screen record a recorded demo...


URL Scraper and site map builder.

alxscrpr on Vimeo.

I have coded a CLI scraper and site map builder. A first for me. Enjoying the process and learning. Got to a point of mostly tweaking. Time to move on. Good enough will do. Here's the repo on GitHub.

Wednesday 27th January 2021

Once a year the bicycle and car are professionally serviced. This year the car was £432.00 and the bike closer to £500. It's worth it to have them both knocked back into shape for another twelve months.


I told a new staffer they are good to work with. A welcome addition to the team. That's because they step into to assist when the opportunity arises. Helpful without keeping count. A good way to be.


Made surprisingly quick progress on coding a CLI to scrape links from a url or list of urls. None of the well known modules available to do so were used. The biggest function in terms of code generates an xml site map based on urls scraped. 90% of that function was taken from code developed by someone else. Tweaked it a bit but mostly not mine.

This prompted me to consider that it's routine to use imported and built in modules; is this any different? Good practice for learning is of course to read through and work on understanding code used like this.


I am currently resisting getting back to and completing the project. There is most likely something in that. Resisting what is obviously the most correct course of action. Maybe not! That would be to complete self assessment tax returns with just a few days left before the submission deadline. Arghh! Don't feel a bit like doing either!


Anticipating delivery of a Rocketbook Flip today. Hoping I shall find a way to upload notes to Standard Notes from the app that comes with it. Could be a fun and possibly useful addition to the repertoire of tools for recording, storing and working things out with handwriting. Don't think it's open source which I regret not having considered before clicking buy. I'd like to remember to do so with such purchases in the future.

Saturday 23rd January 2021

Python CLI

Spent some time this week learning more about coding a command line interface. Settled on using Typer. Learned about and how to code CLI arguments, commands and options; more about Pythons os module, something about egrep and much more about the Linux ls command. Also learned how to create a Python package with Poetry so anyone can install it and have it as an independent program that they can use in their terminal. The repo for it's here on GitHub.

Feels like the start of a new chapter. Moving on from learning the syntax, semantics and lexican of Python and starting to see the way to building something that might even be useful.


Outlier

Have you been tested? Have you reported the results of your lateral flow tests? Are you going to have the vaccine?

The majority take seems to be to comply with implied expectations. Those that do not are challenged and questioned. The shadow of coercion by populist aquiesence is barely being noticed.

I was asked if I 'believed in covid'. This was prompted having said I was not willing to disclose my vaccine statu. I am also agnostic and regularly spoil my ballot paper.

What would you think if the headlines about the trial successes had read “Shot Reduces COVID-19 Risk by 0.7%” instead of “COVID-19 Shot 95% Effective”? ref


Stereotypes

Anyone who has tried to meditate will know that thoughts naturally occur without deliberate intention and often for a good while before even being noticed.

Given the relationship between thoughts, emotions and behaviour it makes sense to have some awareness of them.

So to stereotypes. Accept you have them and acknowledge their absurdity. It might lead to something good. A few laughable examples that come to my mind...

Italy: Pasta, football, bling, models, fast cars, fast talking, corruption, unreliable, good weather, a boot.

France: Snails, the Eiffel Tower, berets, 2nd world war, the French Resistance, secularism, free speech, arrogance, rudeness, smoking, onions.

Germany: Efficient, abrupt, confident, superior, tough, sausages, the language.

Russia: Massive, tough, hard living, vodka, macho, the language, snow, communism (legacy - architecture and industry), oligarchs, corruption, harshness, babushkas.

England: Pompous, dishonest, cruel, countryside, lanes, self serving deference and sell outs, history, manipulative, exploitative, music, shameful legacy, innovation.

Australia: Largely empty, hot, dangerous animals, can do attitude, down to earth, big houses, racist, dodgy background, polluter.

China: Harsh, authoritarian, efficient, ruthless, introspective, belligerent, secretive, protectionist, massive, dramatic, powerful, horrific animal food trade, cultured.

America: Big, dramatic, scenic, brash, clumsy, largely capable, bully, selfish, overbearing, entitled, polluting.

Africa: Exploited, diverse, massive, can do, superstitious, misguided, innovative, sell out.

Central America: Dangerous, outlawed, criminal, cigars, cocaine, swamps, humid, late nights, bars, survival, getting by.

India: Crowded, polluter, exploited and exploitative, corruption, paternalistic misogyny, misguided, cultured, can do, innovative, manipulative, self serving survival.

South America: The Amazon, military and right wing governments, cigars, carnival, Spain, Portugal, humid, big, laissez-faire.

Spain: Overconfident, unaware, semiprofessional, bullfighting, flamenco, tomato, siesta.

Mexico: Hot, dusty, corrupt, dangerous, drugs, guns, poor living standards, tequila, cocaine, food, sombreros, big moustaches.

Wednesday 20th January 2021

Read the manual. Learning how to code command line interfaces. Discovered Typer. If I'd read the manual it would not have taken so long to figure out how to have a function invoked without entering a command and also not executing the callback if there's another command specifed. The code below included with a bunch of @app.command()'s did it...

@app.callback(invoke_without_command=True)
def main(ctx: typer.Context):
    """
    functon is invoked if no command entered.
    """
    if ctx.invoked_subcommand is None:
        typer.echo(os.system('ls -p | grep -v /'))

Good Mood Foods to Add to Your Menu

Probiotics and Prebiotics

To reset your gut microbiome, increase the probiotics and prebiotics you eat. Probiotic-rich foods contain bacteria that help your body and brain. An animal study in 2017 from the University of Virginia School of Medicine indicated that Lactobacillus can reverse depression in rats. Similar findings have been established in humans.

Prebiotics are essentially food for probiotics. Probiotics break down prebiotics to form short-chain fatty acids that help reduce gut inflammation, block the growth of cancerous cells, and help the growth of healthy cells.

Certain species of gut bacteria have the ability to boost levels of brain chemicals such as gamma-aminobutyric acid (GABA), which may speed relief from depression and other mental health conditions.
Eat this:

Probiotics. Yogurt with active cultures (avoid yogurts high in added sugars), tempeh, miso, and natto (fermented soybean products), sauerkraut, kefir, kimchi, kombucha, buttermilk, and some cheeses such as cheddar, mozzarella, and Gouda.

Prebiotics. Beans and other legumes, oats, bananas, berries, garlic, onions, dandelion greens, asparagus, and leeks.

Foods Rich in Good Mood Vitamins

Many vitamins play key roles in preventing and easing depression. A deficiency in vitamin B12 and folate (B9) can contribute to a loss of brain cells which is associated with depression.

Vitamins B1 (thiamine) and B6 (pyridoxine), vitamin A, and vitamin C all play crucial roles in brain function and mood regulation.
Eat this:

Find B12 and folate in legumes, citrus fruits, bananas, avocados, leafy greens and crucifers, asparagus, beets, nuts, seeds, fish and shellfish.

Vitamins B1 and B6 in the foods in the B12 and folate section, as well as in soybeans and whole grains.

Vitamin A in sweet potatoes, carrots, spinach, and black-eyed peas.

Vitamin C in citrus, cantaloupe, strawberries, broccoli, cauliflower, Brussels sprouts.

Foods Rich in Iron and Good Mood Minerals

Iron, magnesium, and zinc all play vital roles in proper brain function, and deficiencies
in these minerals has been linked to depression in clinical studies. Several case studies in which patients were treated with 125-300mg of magnesium have demonstrated rapid recovery from major depression, often in less than a week.
Eat this:

Iron-rich foods. Shellfish, lean red meats and organ meats (in moderation), eggs, legumes, pumpkin seeds, broccoli, spinach, and dark chocolate (also in moderation).

Magnesium-rich foods. Avocados, bananas, dried apricots, nuts and seeds, legumes, whole grains, and some omega- 3-rich fish (such as salmon and mackerel).

Zinc-rich foods. Seafood (especially cooked oysters), lean beef, and poultry, with lower amounts found in beans (chickpeas and lentils), nuts, and whole grains.

Foods Rich in Omega-3 Fatty Acids

Omega-3s are crucial to mental health. But since we cannot produce them on our own, we must get our omega-3s from our diet. The three main omega-3 fatty acids are alphalinolenic acid (ALA), eicosapentaenoic acid (EPA), and docosahexaenoic acid (DHA). EPA and DHA are the omega-3s most critical in mood disorders, so it’s particularly important to ensure that you get enough of them. Omega-3s lower inflammatory markers and protect neurons from excessive inflammation.
Eat this:

Cold-water fatty fish such as salmon, mackerel, tuna, herring, and sardines, contain high amounts of omega-3s. Trimmer fish like bass and trout are good sources, too.

Grass-fed beef contains more omega-3s than conventional beef.

ALA sources include edamame, walnuts, and chia seeds.

Omega-3- fortified foods on the market, especially eggs, milk, and yogurt.

Herbs and Spices

Many seasonings help the brain fight off free radicals and prevent oxidative stress, which can damage tissues. Pair them with the antidepressant foods to double their mood-boosting effects.
Eat this:

Saffron. A 2017 study revealed that 15 mg of saffron is as effective as 20 mg of Prozac in decreasing depressive symptoms. In animals, saffron increases levels of the good mood neurotransmitters glutamate and dopamine.

Oregano. Researchers have connected carvacrol, an active ingredient in oregano, with neuroprotective and antidepressant effects in animal studies, although to date, there are no such studies in humans.

Turmeric. A meta-analysis in 2017 found that curcumin, an active ingredient in turmeric, reduces depressive symptoms by adjusting brain chemistry and protecting brain cells against toxic damage that leads to depression.

Other mood-boosting herbs. Lavender, passionflower, and chamomile are all herbs that can be helpful for depression too. They’re easiest enjoyed as teas.

ref.