/r/CodingHelp

Photograph via //r/CodingHelp

Welcome! Feel free to ask any questions regarding coding you have!

Our Rules

1. FLAIR YOUR POSTS! Don't put tags in post titles!

2. Do not ask us to do all the coding for you unless you have money to spend. (If you have got money to spend, make that clear and the amount in question).

3. Do not post spam and/or misleading titles.

4. Do not be abusive to other coders.

5. Please format code properly, or use a site such as Gist or Pastebin. If possible please provide a live example of your issue.

6. Do not downvote people because you think they asked a dumb question. Just because you think that someone has a dumb question, doesn't mean that it is dumb to them.

7. Do not have a misleading user flair. Keep them sensible, describing your level of coding ability and/or languages you know and/or your profession.

8. Please do not ask unethical questions, such as asking for homework to be written by someone else, or asking someone to copy another project directly.

9. Make sure to follow the Reddit Rules.


How to start coding:

Check our website https://codinghelp.site we have all the information you need there!


Related subreddits:


Suggest a post flair

If you have any suggestions for flairs (programming languages or generic coding topics) that we should add, please use the button below to message the mods with your suggestion.

If approved as a sensible flair for the community to use, it will be added to our bot for automated suggestions and to the flair list for everyone to use!

Anyone who abuses this by spamming mods will be banned.


Current supported flairs

  • HTML
  • CSS
  • Javascript
  • PHP
  • SQL
  • Ruby
  • Java
  • Python
  • C++
  • C#
  • C (Not in Bot)
  • Open Source
  • Other Code
  • Random
  • Meta

Flair colors

  • Green

Web Related Languages (Eg HTML, CSS)

 

  • Blue

App Related Languages (Eg Python, C#)

 

  • Red

Generic Coding Topics (Eg Open Source)

 

  • Yellow

Other Flairs (Eg Random, Meta)


/r/CodingHelp

76,466 Subscribers

1

Publishing with Render

I am attempting to publish this project using Render instead of Vercel. Could you advise on what should be specified for:

"The relative path of the directory containing built assets to publish. Examples: ./, ./build, dist, and frontend/build."

Here is the project name for reference: Cruip Open React Template

0 Comments
2024/07/24
03:21 UTC

1

windows to mac

im gonna start college in 20 days and i bought a mac for btech in cse. but i cant figure out the basics of vs code in a mac, it’s different than what it was ws in windows. is there any source from where i can understand how to work a mac especially for programming?

1 Comment
2024/07/23
23:42 UTC

1

Am I cooked? Sophomore in college wanting to learn to code

Hey. All my life I have been told to code but I haven't ever taken it seriously.

Now I am a sophomore in college in the Bay Area and I desperately want to make and ship my own products by my own code. I feel so shitty and helpless not being able to do any of this on my own.

Does anyone know where I can start? I am so willing to put the work and hours in to becoming technically skilled and being able to be a self sufficient coder and founder. I want to learn the skills of becoming a technical founder rather than a bullshit founder who needs to beg other software engineers to ship out my projects and ambitions. I know that the learning curve for programming is awful, is there any good place to start? I heard about C# or python being good.

My goal for this is to be able to ship my own websites and apps on the app store, as well as learning the backend etc. I am not in a rush of course I know I have time, I am not switching majors either but I passionately want to do this in my personal time to make the product ideas I have come to life.

Also does anyone know how long it should take me in consistently putting in 5-6 hours in a day of studying? Is that enough???

5 Comments
2024/07/23
21:21 UTC

1

GitHub actions help: Deploy docker image to dockerhub for React + Vite project

Here's the project on GitHub.

I have created a dockerfile. This works locally; I can build the docker image and run the app from it.

I am trying to use a GitHub action to deploy the image to dockerhub. Here's the workflow file, in which I am doing a checkout, setting up node, then using a build-push action from the marketplace.

The build-push action fails to execute the dockerfile when attempting to execute:

npm run build

Here is the error log:

#11 [build_image 6/6] RUN npm run build
#11 0.436 
#11 0.436 > reactjs_aspnetapi_dockerized@0.0.0 build
#11 0.436 > vite build
#11 0.436 
#11 0.663 vite v5.3.4 building for production...
#11 0.701 ✓ 0 modules transformed.
#11 0.703 x Build failed in 11ms
#11 0.703 error during build:
#11 0.703 Could not resolve entry module "index.html".
#11 0.703     at getRollupError (file:///app/node_modules/rollup/dist/es/shared/parseAst.js:392:41)
#11 0.703     at error (file:///app/node_modules/rollup/dist/es/shared/parseAst.js:388:42)
#11 0.703     at ModuleLoader.loadEntryModule (file:///app/node_modules/rollup/dist/es/shared/node-entry.js:19157:20)
#11 0.703     at async Promise.all (index 0)
#11 ERROR: process "/bin/sh -c npm run build" did not complete successfully: exit code: 1
------
 > [build_image 6/6] RUN npm run build:
0.436 
0.663 vite v5.3.4 building for production...
0.701 ✓ 0 modules transformed.
0.703 x Build failed in 11ms
0.703 error during build:
0.703 Could not resolve entry module "index.html".
0.703     at getRollupError (file:///app/node_modules/rollup/dist/es/shared/parseAst.js:392:41)
0.703     at error (file:///app/node_modules/rollup/dist/es/shared/parseAst.js:388:42)
0.703     at ModuleLoader.loadEntryModule (file:///app/node_modules/rollup/dist/es/shared/node-entry.js:19157:20)
0.703     at async Promise.all (index 0)
------
Dockerfile:9
--------------------
   7 |     COPY ./ ./
   8 |     
   9 | >>> RUN npm run build 
  10 |     
  11 |     # Production stage
--------------------
ERROR: failed to solve: process "/bin/sh -c npm run build" did not complete successfully: exit code: 1
Error: Command failed: docker build -f reactjs_aspnetapi_dockerized/Dockerfile -t docker.io/***/demo-repo:main-27eb457 .

Here's a screenshot if that's easier to read.

I think I'm copying all the files correctly, but if I'm reading this right, it can't find index.html. That doesn't make sense to me, and StackOverflow/Google isn't helping me today. Can anyone point me in the right direction?

1 Comment
2024/07/23
19:02 UTC

1

Best Image Comparison Tool

I am creating a program in Python that needs to compare a group of images. I want it to evaluate sports cards and determine if they are the same or not. What is the best image comparison tool to use for something like this?

I have tried OpenCV and GPT-4o-mini and neither are great at it.

0 Comments
2024/07/23
15:52 UTC

0

Looking for enough sufficient laptop for the next 4 years of cs major and even for working too.

Hi i am going to be in 2nd year of cs bachelor. I am looking for a window laptop around 1000$us that is sufficient enough and overspend my need.

16gb and upgradabe, 512ssd and upgradeble would be awesome cause I will be doing virtual machine. My need is well portable, the whole weight of laptop + charger shouble be below 3,2 kg. A dedicated graphic good enough for learning AI, my course doesnt focus mosly on AI but I still wanna do some small side projects about AI to get to know about this field, since i believe AI will be needed in every tech field in the future. I also occasionally play games, im not gaming all day, but if i have free time, I would like to play ofline games like minecraft, cyberbunk, assasin with avg 70fps in medium graphic, high graphic would be ideal! So would 3060 and 4050 rtx laptop be sufficient for my need? I often watch anime and read manga on my laptop too so I would like my screen to atleast QHD with 100% color accuracy stuff.

So what laptop would be a great choice for me, I have been having a headache of which one I need to get for a long time. I have looked through lenovo slim 5, 7, asus g15 many of them has great price and build but I dont know if I really need those build. Its my parents's money so I dont wanna overspend it. Any advice would be appreciated, thanks!

1 Comment
2024/07/23
09:30 UTC

1

Seeking help to edit APK files

Pls pm me as I need help with editing game file (apex racer) I need to be level 800 and 30000 wins

2 Comments
2024/07/22
16:24 UTC

1

Is there a way to automatically input all job history into these online applications?

I was hoping you all might have some innovative ideas for me.

I’m tired of manually inputting my extensive job history into these damn applications. I would much prefer romoving my genitals with a blunt object.

In this day in age I find it hard to believe somebody hasn’t come up with some script that would automatically input all of the info from my resume into an application.

1 Comment
2024/07/22
15:53 UTC

1

troubles with whatsapp link preview for my url

i've tested my url several times, added all the required meta tags
but there is no way! whatsapp wont load anything as preview for my link!
https://orizzontesconti.it/blog/cambio-nome-da-shopreactor-a-orizzontesconti

opengraph.dev shows that everything is fine on my website
https://opengraph.dev/panel?url=https%3A%2F%2Forizzontesconti.it%2Fblog%2Fcambio-nome-da-shopreactor-a-orizzontesconti

can somebody please help me?!

0 Comments
2024/07/22
10:27 UTC

0

What should I do, are certifications worth it?

Hi, my name is Sidd and I'm 15. I have been learning the basics of Python for about 1-2 years, so I am familiar with Python. Just recently, I also worked a bit with Unity C#. I made a game in a week, which I very much enjoyed. I also could understand C# pretty well.

I'm interested in coding, and I want to develop a career in it. I just don't know what path to take at the moment. I think it's best if I get a PCAP certification so that I have proof of my knowledge in Python. Does anyone have suggestions on what I should do? Should I go for certifications, keep building games/apps, or what should I do?

5 Comments
2024/07/22
09:52 UTC

1

How to use react native

I’m trying to make an app (IOS and android ) for a project but have found it difficult to use react native. What is the best way to use it, where to learn and if there are better alternatives Thanks

1 Comment
2024/07/22
09:44 UTC

0

How to create non mathematical calculator?

I’d like to create a page for my website where people can put in the coat colors and alleles of parents and then have the possible coat colors of their litter calculated.

I can only find tutorials for contact forms and mathematical calculators but not an inbetween.

I’d appreciate help, thanks

5 Comments
2024/07/22
09:04 UTC

1

Best practice coding

Hi everyone,

I need your help. When a user clicks "Forgot Password" and enters an email that has not been registered, should I inform them that they are not registered, or should I tell them that an email has been sent to the entered email but actually send nothing in the backend? What is the best practice for security?

Thank you.

6 Comments
2024/07/21
21:04 UTC

1

Paladarium help

Hello, I have been wanting to make a paladarium with the want to use global weather reports to recreate an ecosystem with an on off switch.

So the basic idea would be for example If raining turn on rain system/fog Heat updates accordingly throughout day and night Lighting so it follows day night cycles etc

I've never used code and don't have a device to use nodes which is what people have suggested so I was wondering is the idea of using the updates of a website to create an on off system possible?

1 Comment
2024/07/21
20:05 UTC

1

Where Can I learn Up to date C#

Hello i am a complete noob at coding I am on mac ,since vs studio is not working on mac anymore and alot of tutorials are using vs studio and are on windows even paid courses Where can i learn anything help thank you in advance

2 Comments
2024/07/21
16:43 UTC

1

Doubt regarding software jobs

Do tech companies have any restrictions on branch? If I do my engineering from electronics field, will I be able to apply (and get) good software jobs (considering I have enough skills as par with a cs student).

5 Comments
2024/07/21
15:58 UTC

0

Question 1 in Java and python

I don't remember full content of the question

They are about mangoes and finding identical mangoes using functions , override and if-else:

Testcase one -> input_1 : 2 and input_2 : 2 but testcase output : 3

Testcase two -> input_1 : 1 and input_2 : 12 but testcase output : 1

The Testcase inputs must only entered in custom input , not in coding

I know basics in Java and python but the output is little confusing for me . Give your suggestions, answers and advice ?

4 Comments
2024/07/21
10:02 UTC

1

How Can I Download VXP games to my Nokia 220 4g (2024)

idk if this goes here or not but can someone please help me title is self explinatory

0 Comments
2024/07/21
05:48 UTC

0

Data science

Hiii again i have a question: as a data scientist which are platforms we need to master coding in , which will impress the recruiter like hacker , leetcode are these needed or do we have other sites for data science to showcase our coding skills

0 Comments
2024/07/21
05:18 UTC

0

I need a URL from a subscription button..

I need assistance from someone way more skilled than myself.

I am trying to get a direct link to my "Subscribe" or "Gift Subscription" button on my Kick Streaming page.
kick.com/ForeverEsoteric
I need it to assign it to a particular button on my website I'm putting together.

I have been able to figure it out on all other platforms, but their encoding is weird and looks WAY more complicated. Lol. I might just have been looking at my PC for too long, and should sleep... Anywho.

If you could help a girl out, that would be AWESOME!

TYIA.

0 Comments
2024/07/21
02:51 UTC

1

Making 2d fighter

I want to make a 2d fighting game or make custom characters for an existing one but I'm really bad at coding and I don't have much time to learn. I've tried mugen with fighter factory. Ive tried gobot and Roblox tutorials to no avail. I just want to make something small for my friends but I'm not sure how to start. And suggestions?

3 Comments
2024/07/21
00:31 UTC

1

Could someone help me with Python and Anki flashcards?

I have an image file of 970 images I'd like to make into individual flashcards. I don't know much about coding, I've tried and I can't seem to get this to work. If I could send someone a zip file of the images and could create the Anki deck for me, I would greatly appreciate it. Thanks!

0 Comments
2024/07/20
15:03 UTC

0

How can I improve my perspective of learning coding?

I'm a beginner python programmer sometimes I feel like giving up because I don't get used to the intermediate concepts. Can anyone have any tips? I'm already on my final year of my college so I need to prepare for my placements too.

7 Comments
2024/07/20
08:10 UTC

1

How to format code blocks/latex code like a professional would in other languages?

I'm someone who only knows LaTeX and I have this template that I have made that I have tried to make be formatted like how a professional would type his code blocks and code formatting:

https://pastebin.com/5krJyGaX

% Document Class And Settings % 

\documentclass[
    letterpaper,
    12pt
]{article}

% Packages %

% \usepackage{graphicx}
% \usepackage{showframe}
% \usepackage{tikz} % loads pgf and pgffor
% \usepackage{pgfplots} 
% \usepackage{amssymb} % already loads amsfonts
% \usepackage{thmtools}
% \usepackage{amsthm}
% \usepackage{newfloat} % replaces float
\usepackage[
    left=1.5cm,
    right=1.5cm,
    top=1.5cm,
    bottom=1.5cm
]{geometry}
\usepackage{indentfirst}
% \usepackage{setspace}
% \usepackage{lua-ul} % better for lualatex than soul
% \usepackage[
%     backend=biber
% ]{biblatex}
% \usepackage{subcaption} % has caption
% \usepackage{cancel}
% \usepackage{stackengine}
% \usepackage{hyperref}
% \usepackage{cleveref}
% \usepackage[
%     version=4
% ]{mhchem}
% \usepackage{pdfpages}
% \usepackage{siunitx}
\usepackage{fancyhdr}
% \usepackage{mhsetup}
% \usepackage{mathtools} % loads amsmath and graphicx
% \usepackage{empheq}
% \usepackage{derivative}
% \usepackage{tensor}
% \usepackage{xcolor}
% \usepackage{tcolorbox}
% \usepackage{multirow} % might not need
% \usepackage{adjustbox} % better than rotating?
% \usepackage{tabularray}
% \usepackage{nicematrix} % loads array, l3keys2e, pgfcore, amsmath, and module shapes of pgf
% \usepackage{enumitem}
% \usepackage{ragged2e}
% \usepackage{verbatim}
% \usepackage{circledsteps}
% \usepackage{titlesec} % might add titleps and titletoc
% \usepackage{csquotes}
\usepackage{microtype}
\usepackage{lipsum}
\usepackage[
    warnings-off={mathtools-colon,mathtools-overbracket}
]{unicode-math} % loads fontspec, and takes away the warning for the unicode-math & mathtools clash
% \usepackage[
%     main=english
% ]{babel} % english is using american english 

% Commands And Envirionments %

\makeatletter
\renewcommand{\maketitle}{
    {\centering
    \normalsize{\@title} \par 
    \normalsize{\@author} \par
    \normalsize{\@date} \\ \vspace{\baselineskip}
    }
}
\makeatother

\renewcommand{\section}[1]{
    \refstepcounter{section}
    \setcounter{subsection}{0}
    \setcounter{subsubsection}{0}
    \setcounter{paragraph}{0}
    \setcounter{subparagraph}{0}
    {\centering\textsc{\Roman{section}. #1}\par}
}

\renewcommand{\subsection}[1]{
    \refstepcounter{subsection}
    \setcounter{subsubsection}{0}
    \setcounter{paragraph}{0}
    \setcounter{subparagraph}{0}
    {\centering\textsc{\Roman{section}.\Roman{subsection}. #1}\par}
}

\renewcommand{\subsubsection}[1]{
    \refstepcounter{subsubsection}
    \setcounter{paragraph}{0}
    \setcounter{subparagraph}{0}
    {\centering\textsc{\Roman{section}.\Roman{subsection}.\Roman{subsubsection}. #1}\par}
}

\renewcommand{\paragraph}[1]{
    \refstepcounter{paragraph}
    \setcounter{subparagraph}{0}
    {\centering\textsc{\Roman{section}.\Roman{subsection}.\Roman{subsubsection}.\Roman{paragraph}. #1}\par}
}

\renewcommand{\subparagraph}[1]{
    \refstepcounter{subparagraph}
    {\centering\textsc{\Roman{section}.\Roman{subsection}.\Roman{subsubsection}.\Roman{paragraph}.\Roman{subparagraph}. #1}\par}
}

\newcommand{\blk}{
    \vspace{
        \baselineskip
    }
}

\newcommand{\ds}{
    \displaystyle
}

% Header and Foot 

\pagestyle{fancy}
\fancyhf{} % clear all header and footers
\cfoot{\thepage} % put the page number in the center footer
\renewcommand{\headrulewidth}{
    0pt
} % remove the header rule
\addtolength{\footskip}{
    -.375cm
} % shift the footer down which will shift the page number up

% Final Settings % 

\setlength\parindent{.25cm} 
% \setlength{\jot}{
    % .25cm
% } % spaces inbetween align, gather, etc
% \pgfplotsset{compat=1.18}
% \UseTblrLibrary{booktabs}
% \newlength{\tblrwidth}
% \setlength{\tblrwidth}{
    % \dimexpr\linewidth-2\parindent
% }
% \newlist{checkboxlist}{itemize}{1}
% \setlist[checkboxlist]{label=$\square$} % requires asmsymb
% \newlist{alphabetization}{enumerate}{1}
% \setlist[alphabetization]{label=\alph*.)}
% \setlist{nosep}
% \declaretheorem{theorem}

% Fonts and Languages % 

\setmainfont{Times.ttf}[
    Ligatures=TeX,
    BoldFont=Timesbd.ttf,
    ItalicFont=Timesi.ttf,
    BoldItalicFont=Timesbi.ttf
]
\setmathfont{STIXTwoMath-Regular.otf}
% \newfontfamily\secondfont{STIX Two Text}[
%     Ligatures=TeX
% ]
% \babelprovide[
%     import=es-MX
% ]{spanish}

% maketitle % 

\title{}
\author{u/FattenedSponge}
\date{\today}

\begin{document}

\maketitle



\end{document}

And I am trying to format everything that can be done in code block for correctly. Though I am not sure if the way I do things are even right. Could someone please critique the way that I do things, please help me 'properly' do LaTeX? I want to build good habits incase I ever learn another programming language.

0 Comments
2024/07/20
06:25 UTC

0

Coding help/guidance?

8 keep someone to help me understand what this is. And why someone would have it. I need as much info in this as possible!

4 Comments
2024/07/20
03:56 UTC

1

Writing an Excel VBA that can analyze and pull data from XML - SOS

0 Comments
2024/07/20
02:55 UTC

1

Git reset

Hey everyone. I am building an iOS app. I am self taught and having trouble with git. To my understanding I should be able to use git as kind of a save point. Once I get to a place I like with my code, I should git add and git commit. That is a save point. If I start coding again and don’t like the saves I have made I should be able to git reset —hard HEAD.

Well what is happening when I do that is all of the files in Xcode turn red and it bricks my app. What am I doing wrong? I have bricked my app twice so right now I am making a backup every time I get to a place I like and am abandoning hit all together.

Thanks for your help ❤️

2 Comments
2024/07/19
20:48 UTC

1

Firebase upload/download problem, please help.

I'm working on a website and its basically finished, and for context its a Beam.NG mods sharing website, where staff members upload mods, users download.

Everything is working perfect aside from 1 thing, when I use the staff upload mods form, to upload to firehost which then hosts my files, and then what SHOULD happen is, user goes to home page, clicks "View details" on the mod, and then clicks download and it downloads. BUT what actually happens is firehost instead of having the .zip file for the mod, has some odd file called "modsfile" with no extension.
Not sure what I can do, any ideas?

1 Comment
2024/07/19
20:27 UTC

1

Lattice-boltzmann simulation runs over the object mask, simulating areas that should be just black

I'm trying to simulate a tesla valve using the lattice-boltzmann method, starting from this code. The problem is that the mask, the boundaries or the bounce-back are not being applied correctly. If I reverse the condition for the creation of the obstacle mask the flow seems to be running more on the inside of the valve.

Images:

Simulation output

Simulation with inverted mask

Obstacle mask

Full code:

import jax
from PIL import Image
import jax.numpy as jnp
import matplotlib.pyplot as plt
import cmasher as cmr
from tqdm import tqdm

N_ITERATIONS = 30_000
REYNOLDS_NUMBER = 80

N_POINTS_X = 1024
N_POINTS_Y = 301

MAX_HORIZONTAL_INFLOW_VELOCITY = 0.04

VISUALIZE = True
PLOT_EVERY_N_STEPS = 100
SKIP_FIRST_N_ITERATIONS = 0


r"""
LBM Grid: D2Q9
    6   2   5
      \ | /
    3 - 0 - 1
      / | \
    7   4   8 
"""

N_DISCRETE_VELOCITIES = 9

LATTICE_VELOCITIES = jnp.array(
    [
        [0, 1, 0, -1, 0, 1, -1, -1, 1],
        [0, 0, 1, 0, -1, 1, 1, -1, -1],
    ]
)

LATTICE_INDICES = jnp.array([0, 1, 2, 3, 4, 5, 6, 7, 8])

OPPOSITE_LATTICE_INDICES = jnp.array([0, 3, 4, 1, 2, 7, 8, 5, 6])

# fmt: off
LATTICE_WEIGHTS = jnp.array(
    [
        4/9,  # Center Velocity [0,]
        1/9, 1/9, 1/9, 1/9,  # Axis-Aligned Velocities [1, 2, 3, 4]
        1/36, 1/36, 1/36, 1/36  # 45 ° Velocities [5, 6, 7, 8]
    ]
)
# fmt: on

RIGHT_VELOCITIES = jnp.array([1, 5, 8])
UP_VELOCITIES = jnp.array([2, 5, 6])
LEFT_VELOCITIES = jnp.array([3, 6, 7])
DOWN_VELOCITIES = jnp.array([4, 7, 8])
PURE_VERTICAL_VELOCITIES = jnp.array([0, 2, 4])
PURE_HORIZONTAL_VELOCITIES = jnp.array([0, 1, 3])


def create_tesla_valve_mask_from_image(image_path, lattice_size):
    image = Image.open(image_path).convert("L")
    image_resized = image.resize(lattice_size, Image.BILINEAR)
    image_array = jnp.array(image_resized)
    mask = image_array > 128
    return mask


image_path = "valve-image-mask.png"
tesla_valve_mask = create_tesla_valve_mask_from_image(
    image_path, (N_POINTS_X, N_POINTS_Y)
)


def get_density(discrete_velocities):
    """
    For a single cell, if the velocities are [f0, f1, ..., f8],
    the density is equal to f0 + f1 + ... + f8
    """
    density = jnp.sum(discrete_velocities, axis=-1)

    return density


def get_macroscopic_velocities(discrete_velocities, density):
    macroscopic_velocities = (
        jnp.einsum(
            "NMQ,dQ->NMd",
            discrete_velocities,
            LATTICE_VELOCITIES,
        )
        / density[..., jnp.newaxis]
    )

    return macroscopic_velocities


def get_equilibrium_discrete_velocities(macroscopic_velocities, density):
    projected_discrete_velocities = jnp.einsum(
        "dQ,NMd->NMQ",
        LATTICE_VELOCITIES,
        macroscopic_velocities,
    )
    macroscopic_velocity_magnitude = jnp.linalg.norm(
        macroscopic_velocities,
        axis=-1,
        ord=2,
    )
    equilibrium_discrete_velocities = (
        density[..., jnp.newaxis]
        * LATTICE_WEIGHTS[jnp.newaxis, jnp.newaxis, :]
        * (
            1
            + 3 * projected_discrete_velocities
            + 9 / 2 * projected_discrete_velocities**2
            - 3 / 2 * macroscopic_velocity_magnitude[..., jnp.newaxis] ** 2
        )
    )

    return equilibrium_discrete_velocities


def main():
    jax.config.update("jax_enable_x64", True)

    kinematic_viscosity = (
        MAX_HORIZONTAL_INFLOW_VELOCITY * N_POINTS_Y
    ) / REYNOLDS_NUMBER

    relaxation_omega = (1.0) / (3.0 * kinematic_viscosity + 0.5)

    # Define a mesh
    x = jnp.arange(N_POINTS_X)
    y = jnp.arange(N_POINTS_Y)
    X, Y = jnp.meshgrid(x, y, indexing="ij")

    # Obstacle Mask: An array of the shape like X or Y, but contains True if the
    # point belongs to the obstacle and False if not
    # (calculates the distance between a point and the center)
    obstacle_mask = tesla_valve_mask.T

    velocity_profile = jnp.zeros((N_POINTS_X, N_POINTS_Y, 2))
    velocity_profile = velocity_profile.at[:, :, 0].set(MAX_HORIZONTAL_INFLOW_VELOCITY)

    @jax.jit
    def update(discrete_velocities_prev):
        # (1) Prescribe the outflow BC on the right boundary
        discrete_velocities_prev = discrete_velocities_prev.at[
            -1, :, LEFT_VELOCITIES
        ].set(discrete_velocities_prev[-2, :, LEFT_VELOCITIES])

        # (2) Macroscopic Velocities
        density_prev = get_density(discrete_velocities_prev)
        macroscopic_velocities_prev = get_macroscopic_velocities(
            discrete_velocities_prev,
            density_prev,
        )

        # (3) Prescribe Inflow Dirichlet BC using Zou/He scheme
        macroscopic_velocities_prev = macroscopic_velocities_prev.at[0, 1:-1, :].set(
            velocity_profile[0, 1:-1, :]
        )
        density_prev = density_prev.at[0, :].set(
            (
                get_density(discrete_velocities_prev[0, :, PURE_VERTICAL_VELOCITIES].T)
                + 2 * get_density(discrete_velocities_prev[0, :, LEFT_VELOCITIES].T)
            )
            / (1 - macroscopic_velocities_prev[0, :, 0])
        )

        # (4) Compute discrete Equilibria velocities
        equilibrium_discrete_velocities = get_equilibrium_discrete_velocities(
            macroscopic_velocities_prev,
            density_prev,
        )

        # (3) Belongs to the Zou/He scheme
        discrete_velocities_prev = discrete_velocities_prev.at[
            0, :, RIGHT_VELOCITIES
        ].set(equilibrium_discrete_velocities[0, :, RIGHT_VELOCITIES])

        # (5) Collide according to BGK
        discrete_velocities_post_collision = (
            discrete_velocities_prev
            - relaxation_omega
            * (discrete_velocities_prev - equilibrium_discrete_velocities)
        )

        # (6) Bounce-Back Boundary Conditions to enfore the no-slip
        # if in the direction of the velocity th obstacle mask is positive, then reverse the velocity
        for i in range(N_DISCRETE_VELOCITIES):
            discrete_velocities_post_collision = discrete_velocities_post_collision.at[
                obstacle_mask, LATTICE_INDICES[i]
            ].set(discrete_velocities_prev[obstacle_mask, OPPOSITE_LATTICE_INDICES[i]])

        # (7) Stream alongside lattice velocities
        # for each cell, moves the velocity to a neighbor cell in its direction
        discrete_velocities_streamed = discrete_velocities_post_collision
        for i in range(N_DISCRETE_VELOCITIES):
            discrete_velocities_streamed = discrete_velocities_streamed.at[:, :, i].set(
                jnp.roll(
                    jnp.roll(
                        discrete_velocities_post_collision[:, :, i],
                        LATTICE_VELOCITIES[0, i],
                        axis=0,
                    ),
                    LATTICE_VELOCITIES[1, i],
                    axis=1,
                )
            )

        return discrete_velocities_streamed

    discrete_velocities_prev = get_equilibrium_discrete_velocities(
        velocity_profile,
        jnp.ones((N_POINTS_X, N_POINTS_Y)),
    )

    plt.style.use("dark_background")
    plt.figure(figsize=(15, 6), dpi=100)

    for iteration_index in tqdm(range(N_ITERATIONS)):
        discrete_velocities_next = update(discrete_velocities_prev)

        discrete_velocities_prev = discrete_velocities_next

        if (
            iteration_index % PLOT_EVERY_N_STEPS == 0
            and VISUALIZE
            and iteration_index > SKIP_FIRST_N_ITERATIONS
        ):
            density = get_density(discrete_velocities_next)
            macroscopic_velocities = get_macroscopic_velocities(
                discrete_velocities_next,
                density,
            )
            velocity_magnitude = jnp.linalg.norm(
                macroscopic_velocities,
                axis=-1,
                ord=2,
            )
            d_u__d_x, d_u__d_y = jnp.gradient(macroscopic_velocities[..., 0])
            d_v__d_x, d_v__d_y = jnp.gradient(macroscopic_velocities[..., 1])
            curl = d_u__d_y - d_v__d_x

            """
            # Velocity Magnitude Contour Plot in the top
            plt.subplot(211)
            plt.contourf(
                X,
                Y,
                velocity_magnitude,
                levels=50,
                cmap=cmr.amber,
            )
            plt.colorbar().set_label("Velocity Magnitude")
            plt.imshow(tesla_valve_mask, cmap="gray", alpha=0.5, origin="lower")

            # Vorticity Magnitude Contour PLot in the bottom
            plt.subplot(212)
            plt.contourf(
                X,
                Y,
                curl,
                levels=50,
                cmap=cmr.redshift,
                vmin=-0.02,
                vmax=0.02,
            )
            plt.colorbar().set_label("Vorticity Magnitude")
            plt.imshow(tesla_valve_mask, cmap="gray", alpha=0.5, origin="lower")

            plt.draw()
            plt.pause(0.0001)
            plt.clf()
            """

            plt.subplot(1, 3, 1)
            plt.title("Obstacle Mask")
            plt.imshow(obstacle_mask.T, cmap="gray", origin="upper")

            plt.subplot(1, 3, 2)
            plt.title("Velocity Magnitude")
            plt.imshow(velocity_magnitude, cmap="viridis", origin="upper")

            plt.subplot(1, 3, 3)
            plt.title("Vorticity")
            plt.imshow(curl, cmap="RdBu", origin="upper")
            plt.draw()
            plt.pause(0.0001)
            plt.clf()
            # """

    if VISUALIZE:
        plt.show()


if __name__ == "__main__":
    main()

I don't really understand all the math so I don't know what to try. I tried asking chatgpt but it just tells me to ensure that the mask is applied correctly, the boundary conditions are not applied correctly but it doesn't know how to fix them, and to check the initial conditions.

0 Comments
2024/07/19
19:44 UTC

0

How many hours to spent on coding

Hello , so I am currently a 3rd year student in college and I want to know how many hours to spent on coding along with my college studies

6 Comments
2024/07/19
17:59 UTC

Back To Top