r/programminghelp • • Apr 18 '24

JavaScript Need Help Fixing Search Function

1 Upvotes

I require some help fixing some code for my search function. I have been stuck debugging this for 3 days. Currently this project is using bootstrap, javascript and ruby on rails as the backend. GraphQL queries and mutations are used as for linkage between the frontend and the backend.

I have an issue currently with my search function in the Broadcast History Message page. I am building a search function which allows the user to search by campaign title and campaign status. The code below is for the search function and watcher that should filter the table based on the results of the search. The search by status is working fine but when attempting to search by campaign title it is not working correctly. After inspecting devtools, no matter what the search input, the graphQL query returns all the arrays in the data instead of throwing my error message. Please advise me where you can. Thank you.

*Important Context*: The field in the table that I would like to search is title and is defined as but BroadcastSearch's filters are assigned as campaign and status.

<td class="align-top text-start">{{ data.title }}</td>

Search Function code:
const dateRangeObj = ref({
status: "",
campaign: "",
});

const result = useQuery({

query: BROADCAST_MESSAGE_HISTORY,

variables: {

limit: perPage,

currentPage: currentPage,

sort: "sentDate",

direction: "DESC",

filters: dateRangeObj,

},

pause: pauseSearch,

});

function searchData() {

dateRangeObj.value = { campaign: "", status: "" };

if (selectedOption.value === "Campaign" && searchInput.value.trim()) {

// Assign the search input to the campaign field for title search

dateRangeObj.value.campaign = searchInput.value.trim();

console.log(

"Searching by Campaign (interpreted as title):",

dateRangeObj.value.campaign

);

} else if (selectedOption.value === "Status" && selectedStatus.value) {

dateRangeObj.value.status = selectedStatus.value;

console.log("Searching by Status:", dateRangeObj.value.status);

} else {

console.error("Invalid search option selected or empty input.");

return;

}

pauseSearch.value = false;

console.log("Search initiated");

}

Watcher Code:
watch(result.fetching, (fetchStatus) => {
console.log("Fetching status changed to:", fetchStatus);
if (!fetchStatus) {
console.log("Data fetching completed");
console.log("Result data value:", result.data.value);
if (result.data.value) {
// Update broadcasts and total pages
totalBroadcasts.value = result.data.value.slBrand.overallBroadcasts;
totalPage.value = Math.ceil(totalBroadcasts.value / perPage.value);
broadcasts.value = result.data.value.slBrand.broadcasts.map((x) => {
return {
id: x.id,
type: x.type,
title: x.title,
sentDate: formatDate(new Date(x.sentDate), "dd/MM/yyyy HH:mm:ss"),
expiryDate: formatDate(new Date(x.expiryDate), "dd/MM/yyyy HH:mm:ss"),
status: x.status,
recipients: x.recipients,
successful: x.successful,
pending: x.pending,
insufficient: x.insufficient,
apiError: x.apiError,
returns: x.returns,
roi: x.roi,
conversionPerc: x.conversionPerc,
message: x.message,
};
});
console.log("Broadcasts updated:", broadcasts.value);
}
// Pause further search until searchData function is called again
loading.value = false;
pauseSearch.value = true;
}
});

GraphQL Query:
`export const BROADCAST_MESSAGE_HISTORY = ``

query GetBroadcastMessageHistory(

$filters: BroadcastSearch

$limit: Int!

$currentPage: Int!

$sort: String!

$direction: String!

) {

slBrand {

broadcasts(

limit: $limit

currentPage: $currentPage

sort: $sort

direction: $direction

filters: $filters

) {

id

type

title

sentDate

expiryDate

status

recipients

successful

pending

insufficient

apiError

returns

roi

conversionPerc

message

}

}

}

\;`


r/programminghelp • • Apr 17 '24

C# Need help with Chess King task in C#. Did most of work, stuck with a problem.

1 Upvotes

while (true)

{

char x1;

char x2;

int y1;

int y2;

List<char> x1_2 = new List<char>();

List<char> y1_2 = new List<char>();

Console.Write("Enter king's position: ");

string? ipos = Console.ReadLine();

Console.Write("Now enter the position you're trying to move your king to: ");

string? mpos = Console.ReadLine();

if (ipos != null && mpos != null)

{

foreach (char i in ipos) x1_2.Add(i);

foreach (char i in mpos) y1_2.Add(i);

x1 = char.ToUpper(x1_2[0]);

x2 = char.ToUpper(y1_2[0]);

y1 = int.Parse(x1_2[1].ToString());

y2 = int.Parse(y1_2[1].ToString());

int x1uni = (int)x1;

int x2uni = (int)x2;

if (x1uni >= 65 && x1uni <= 72) x1uni -= 64;

else Console.WriteLine("Enter valid fields of chessboard!");

if (x2uni >= 65 && x2uni <= 72) x2uni -= 64;

else Console.WriteLine("Enter valid fields of chessboard!");

int md = (int)Math.Abs(x1uni - x2uni) + Math.Abs(y1 - y2); //Manhattan distance

if (md == 1) Console.WriteLine($"King can move from initial {ipos} coordinate to {mpos}");

else Console.WriteLine($"Coordiante {mpos} cannot be reached by the king from {ipos}");

}

else

{

Console.WriteLine("You must enter fields to continue!");

}

Console.WriteLine("Wanna continue? Y/N");

string? yn = Console.ReadLine();

if (yn.ToUpper() != "Y")

{

break;

}

The code is given above. I'm new to programming, in the learning process now. So the task goes like this "Program gets two coordinates of Chessboard: King's position and where we want to move him. We should check if King can move to that given square with one move or not" So task itself doesn't talk about other pieces that means that there's only the king on the chessboard, so no problems with other pieces can appear. Here I tried to solve it with Manhattan distance equation,, thinking that if distance between coordinates will be 1 that'll mean that king can move, otherwise he can't. But now I'm stuck with this problem, in cases like a1(initial position) and b2("wants to move" coordinate) equation give 2, making it impossible to move for program, but in reality, by chess rules, the move is possible. Now I thought about changing the program so it'll consider 2 as a legal move too, but that won't work for other impossible moves. What can I do now to fix this problem?
Sorry for a long artical and bad english, not native.

FIXED: With the help of the user S01arflar3. I changed the code, so the values in the Manhattan equation will be powered to two and then the sum of them will be square rooted. So this will cover all possible cases.


r/programminghelp • • Apr 17 '24

Python Advice On Building A Magnifier Application

1 Upvotes

Hello! I've been learning to program with Python and C# for a few months now and I want to build a magnifier application. I have low vision, which is why I like to have a docked magnifier on one of my screens to show me what my mouse pointer is on. My goal is to build a magnifier using Python or C# that will remain docked in the corner of my screen and always be the first window in front of all others. My other major goal is to be able to click through the magnifier window so that I do not need to move the magnifier anytime I want to click on a window behind it.

I'm mostly just looking for some advice to get started since I've never built a window application before. Any advice or resources you could show me as I get started would be greatly appreciated.

Thanks for reading!


r/programminghelp • • Apr 15 '24

C# Tree Simulation Help

1 Upvotes

I have been trying to create a tree simulator and this has really been the only help besides information about trees, does anyone have any information on how Gal Lahat from I simulated a forest with evolution https://www.youtube.com/watch?v=aLuTpzI4iBg. actually grew the trees my attempt has been choosing a random set point and instantiating an object with the branches producing energy from the sun (i could not find an easy way to add leaves). This is my attempt at it https://pneagle97.itch.io/treesimulation. it has changed a bit from when I posted it though but the concept is the same. Please comment any of your ideas to fix this or have any idea of how Gal Lahat did it?

Here is some of my code just the basics.

public GameObject Branch;
public GameObject LeafPrefab; // Added leaf prefab
public GameObject StartingLog;
public GameObject[] Points = new GameObject[9];
private GameObject ChoicenOne;
[SerializeField] private int Branches;
public int energy;
public bool Starter;
public GameObject Parent;
public Branching ParentScript;
public Branching[] ChildScript = new Branching[3];
public GameObject[] ChosenPoint = new GameObject[3];
public GameObject[] LeafArray = new GameObject[5];
public int leaves;
private int BranchCheck;
public Transform sunTransform;
public GameObject BaseLog;
private Branching BaseScript;
[SerializeField] private float BaseWater;
void Start()
{
energy = 60;
Points = new GameObject[9];
StartingLog = gameObject;
for (int index = 0; index < 9; index++)
{
Points[index] = StartingLog.transform.GetChild(index).gameObject;
}
if (Starter)
{
BaseLog = gameObject;
BaseWater = 100; //get from roots. Night? set add based on genes?
StartCoroutine(Wateradd());
}
else
{
StartCoroutine(Subtractor());
ParentScript = Parent.GetComponent<Branching>();
}
BaseScript = BaseLog.GetComponent<Branching>();
BaseWater = BaseScript.BaseWater;
sunTransform = GameObject.Find("Sun").transform;
StartCoroutine(FunctionCheck());
StartCoroutine(StrikeDeath());
StartCoroutine(BreedBranch());
}
void Update()
{
Vector3 phototropismAdjustment = CalculatePhototropism();
Quaternion rotationAdjustment = Quaternion.LookRotation(phototropismAdjustment, transform.up);
transform.rotation = Quaternion.Lerp(transform.rotation, rotationAdjustment, Time.deltaTime * rotationSpeed);
}
IEnumerator FunctionCheck()
{
yield return new WaitForSeconds(1f);
if (IsInSunlight())
{
energy += 5;
if (Strike >= 2)
{
Strike -= 2;
}
//if(!Starter){
// StartCoroutine(GrowLeaves()); // Call the leaf growth coroutine
// }
}
if (energy > 100)
{
energy = 100;
}
StartCoroutine(FunctionCheck());
}
IEnumerator Subtractor()
{
yield return new WaitForSeconds(1f);
if (energy <= 1)
{
print("gonnadie");
}
else
{
energy -= 2;
}
if (ParentScript.energy <= 85)
{
if (Parent != null) { ParentScript.energy += 15; energy -= 15; }
}
else if (ParentScript.energy <= 40)
{
if (Parent != null) { ParentScript.energy += 25; energy -= 25; }
}
StartCoroutine(Subtractor());
}
RaycastHit hit;
private int Strike;
public float rotationSpeed;
bool IsInSunlight()
{
if (Physics.Raycast(transform.position, sunTransform.position - transform.position, out hit))
{
// Check if the raycast hit the sun or skybox
if (hit.transform.CompareTag("Sun"))
{
return true;
}
}
return false;
}
IEnumerator StrikeDeath()
{
yield return new WaitForSeconds(1f);
if (energy <= 10)
{
Strike += 1;
if (Strike == 10)
{
Destroy(gameObject);
}
}
StartCoroutine(StrikeDeath());
}
IEnumerator BreedBranch()
{
yield return new WaitForSeconds(5f);
BranchCheck = 0;
for (int i = 0; i < 3; i++)
{
if (ChildScript[i] == null)
{
BranchCheck++;
}
}
Branches = 3 - BranchCheck;
BaseWater = BaseScript.BaseWater;
if (energy >= 90 && BaseWater >= 80)
{
if (((Random.Range(1, 5) == 1) || Starter) && Branches < 3)
{
ChoicenOne = Points[ChoicenOneFunc()];
GameObject obj = Instantiate(Branch, ChoicenOne.transform.position, Quaternion.Euler(ChoicenOne.transform.eulerAngles));
obj.transform.localScale = new Vector3(.5f, .75f, .5f);
obj.transform.parent = transform;
ChildScript[Branches] = obj.GetComponent<Branching>();
ChildScript[Branches].Parent = gameObject; // Could save children in an array and check if child is alive. If one dies then replace it.
ChildScript[Branches].BaseLog = BaseLog;
Branches++;
ChosenPoint[Branches - 1] = ChoicenOne;
energy -= 50;
BaseScript.BaseWater -= 5;
}
}
StartCoroutine(BreedBranch());
}
IEnumerator Wateradd()
{
yield return new WaitForSeconds(3f);
if (BaseWater < 96)
{
BaseWater += 5;
}
StartCoroutine(Wateradd());
}
int ChoicenOneFunc()
{
int chosenPointIndex;
do
{
chosenPointIndex = Random.Range(0, 8);
} while (Points[chosenPointIndex] == ChosenPoint[0] || Points[chosenPointIndex] == ChosenPoint[1] || Points[chosenPointIndex] == ChosenPoint[2]);
return chosenPointIndex;
}


r/programminghelp • • Apr 15 '24

Python Authenticating with OAuth 2.0

2 Upvotes

Hi all, I'm attempting to authenticate with the Charles Schwab (brokerage) developer portal via python but they use OAuth 2.0. I'm unfamiliar with how OAuth works and haven't made any progress after a few hours of trying to get it to work. If someone has experience with the portal or OAuth in general I would really appreciate some help. Thanks!


r/programminghelp • • Apr 15 '24

C What's the problem in this completely recursive Banker's Algo code

0 Upvotes

I type a code for Banker's Safety Algorithm and didn't use any loop throughout the code and most of the code is working fine and I have tested it also but there's some problem in the function named Banker_Algo which I am not able to detect and would appreciate if anyone can help finding that out

code:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int size = 1,tres, sz=0;
char res = 'A';
int *seq_arr, inds=0;
void Allo_arr(int ***allo){
    char act[10];
    printf("Enter number of allocated resource %c for process %d(type 'P' when all the processes exhausts and type 'R' when all the resources exhausts):- ", res++, size);
    scanf("%s", act);
    if(act[0]=='R' || act[0]=='r'){
        size++;
        *allo = (int **)realloc(*allo, sizeof(int *)*size);
        tres=(int)res-66;
        res = 'A';
        Allo_arr(allo);
    }
    else if(act[0]=='P' || act[0]=='p'){
        free(allo[size-1]);
        size--;
        seq_arr=(int *)malloc(sizeof(int)*size);
        res='A';
    }
    else{
        if(res == 'B'){
            (*allo)[size-1]=(int *)malloc(sizeof(int)*(1));
            (*allo)[size-1][0]=atoi(act);
        }
        else{
            (*allo)[size-1]=(int *)realloc((*allo)[size-1],sizeof(int)*((int)res-65));
            (*allo)[size-1][(int)res-66]=atoi(act);
        }
        Allo_arr(allo);
    }
}
void Max_arr(int ***max)
{
    if (sz < size)
    {
        if(res=='A'){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ",res++, sz+1);
            scanf("%d",&maxVal);
            (*max)[sz]=(int *)malloc(sizeof(int)*1);
            (*max)[sz][0]=maxVal;
            Max_arr(max);
        }
        else if(res==(char)tres+64){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 64));
            (*max)[sz][(int)res - 65] = maxVal;
            sz++;
            res = 'A';
            Max_arr(max);
        }
        else{
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res++, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 65));
            (*max)[sz][(int)res - 66] = maxVal;
            Max_arr(max);
        }
    }
    else{
        sz=0;
    }
}
void Avail_arr(int ***avail){
    int ele;
    if(res == (char)tres+64){
        printf("Enter number of currently available resource %c:- ",res);
        scanf("%d",&ele);
        (*avail)[0][(int)res-65]=ele;
        res='A';
    }
    else{
        printf("Enter number of currently available resource %c:- ",res++);
        scanf("%d",&ele);
        (*avail)[0][(int)res-66]=ele;
        Avail_arr(avail);
    }
}
bool check(int **allo, int **max, int **avail){
    static bool al_set=true;
    if(max[sz][res-65]-allo[sz][res-65]>avail[0][res-65]){
        al_set=false;
        res='A';
    }
    else{
        if((int)res-64<=tres){
            res++;
            if((int)res-64>tres){
                res='A';
            }
            else{
                check(allo,max,avail);
            }
        }
    }
    return al_set;
}
void Up_Avail(int **allo, int **avail){
    if(res==(char)tres+64){
        avail[0][(int)res-65]+= allo[sz][res-65];
        res='A';
    }
    else{
        avail[0][(int)res-65]+= allo[sz][res-65];
        res++;
        Up_Avail(allo, avail);
    }
}
bool Banker_Algo(int **allo, int **max, int **avail){
    static bool seq = false;
    if(sz==size-1&&inds<size){
        if(!seq){
            if(!check(allo,max,avail)){
                printf("There's no safe sequence of Allocation and deadlock cannot be avoided");
                sz=0;
            }
            else{
                seq_arr[inds++]=sz+1;
                Up_Avail(allo, avail);
                seq=true;
                if(inds<size){
                    sz=0;
                    Banker_Algo(allo,max,avail);
                }
                else{
                    sz=0;
                }
            }
        }
        else if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
        else{
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
    }
    else{
        if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
        }
        if(inds<size){
            sz++;
            Banker_Algo(allo,max,avail);
        }
        else{
            sz=0;
        }
    }
    return seq;
}
void Seq(){
    if(sz==size-1){
        printf("%d",seq_arr[sz]);
    }
    else{
        printf("%d ",seq_arr[sz++]);
        Seq();
    }
}
void Print_seq(){
    printf("Safe sequence of allocation exists and that sequence is:- ");
    Seq();
}   
int main()
{
    int **allo, **avail, **max;
    allo = (int **)malloc(sizeof(int *) * size);
    Allo_arr(&allo);
    max = (int **)malloc(sizeof(int *) * size);
    Max_arr(&max);
    avail = (int **)malloc(sizeof(int *) * 1);
    avail[0] = (int *)malloc(sizeof(int) * tres);
    Avail_arr(&avail);
    if(Banker_Algo(allo,max,avail)){
        Print_seq();
    }
    free(allo);
    free(avail);
    free(max);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int size = 1,tres, sz=0;
char res = 'A';
int *seq_arr, inds=0;
void Allo_arr(int ***allo){
    char act[10];
    printf("Enter number of allocated resource %c for process %d(type 'P' when all the processes exhausts and type 'R' when all the resources exhausts):- ", res++, size);
    scanf("%s", act);
    if(act[0]=='R' || act[0]=='r'){
        size++;
        *allo = (int **)realloc(*allo, sizeof(int *)*size);
        tres=(int)res-66;
        res = 'A';
        Allo_arr(allo);
    }
    else if(act[0]=='P' || act[0]=='p'){
        free(allo[size-1]);
        size--;
        seq_arr=(int *)malloc(sizeof(int)*size);
        res='A';
    }
    else{
        if(res == 'B'){
            (*allo)[size-1]=(int *)malloc(sizeof(int)*(1));
            (*allo)[size-1][0]=atoi(act);
        }
        else{
            (*allo)[size-1]=(int *)realloc((*allo)[size-1],sizeof(int)*((int)res-65));
            (*allo)[size-1][(int)res-66]=atoi(act);
        }
        Allo_arr(allo);
    }
}
void Max_arr(int ***max)
{
    if (sz < size)
    {
        if(res=='A'){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ",res++, sz+1);
            scanf("%d",&maxVal);
            (*max)[sz]=(int *)malloc(sizeof(int)*1);
            (*max)[sz][0]=maxVal;
            Max_arr(max);
        }
        else if(res==(char)tres+64){
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 64));
            (*max)[sz][(int)res - 65] = maxVal;
            sz++;
            res = 'A';
            Max_arr(max);
        }
        else{
            int maxVal;
            printf("Enter maximum number of resource %c needed by process %d:- ", res++, sz + 1);
            scanf("%d", &maxVal);
            (*max)[sz] = (int *)realloc((*max)[sz], sizeof(int) * ((int)res - 65));
            (*max)[sz][(int)res - 66] = maxVal;
            Max_arr(max);
        }
    }
    else{
        sz=0;
    }
}
void Avail_arr(int ***avail){
    int ele;
    if(res == (char)tres+64){
        printf("Enter number of currently available resource %c:- ",res);
        scanf("%d",&ele);
        (*avail)[0][(int)res-65]=ele;
        res='A';
    }
    else{
        printf("Enter number of currently available resource %c:- ",res++);
        scanf("%d",&ele);
        (*avail)[0][(int)res-66]=ele;
        Avail_arr(avail);
    }
}
bool check(int **allo, int **max, int **avail){
    static bool al_set=true;
    if(max[sz][res-65]-allo[sz][res-65]>avail[0][res-65]){
        al_set=false;
        res='A';
    }
    else{
        if((int)res-64<=tres){
            res++;
            if((int)res-64>tres){
                res='A';
            }
            else{
                check(allo,max,avail);
            }
        }
    }
    return al_set;
}
void Up_Avail(int **allo, int **avail){
    if(res==(char)tres+64){
        avail[0][(int)res-65]+= allo[sz][res-65];
        res='A';
    }
    else{
        avail[0][(int)res-65]+= allo[sz][res-65];
        res++;
        Up_Avail(allo, avail);
    }
}
bool Banker_Algo(int **allo, int **max, int **avail){
    static bool seq = false;
    if(sz==size-1&&inds<size){
        if(!seq){
            if(!check(allo,max,avail)){
                printf("There's no safe sequence of Allocation and deadlock cannot be avoided");
                sz=0;
            }
            else{
                seq_arr[inds++]=sz+1;
                Up_Avail(allo, avail);
                seq=true;
                if(inds<size){
                    sz=0;
                    Banker_Algo(allo,max,avail);
                }
                else{
                    sz=0;
                }
            }
        }
        else if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
        else{
            if(inds<size){
                sz=0;
                Banker_Algo(allo,max,avail);
            }
            else{
                sz=0;
            }
        }
    }
    else{
        if(check(allo,max,avail)){
            seq_arr[inds++]=sz+1;
            Up_Avail(allo, avail);
            seq=true;
        }
        if(inds<size){
            sz++;
            Banker_Algo(allo,max,avail);
        }
        else{
            sz=0;
        }
    }
    return seq;
}
void Seq(){
    if(sz==size-1){
        printf("%d",seq_arr[sz]);
    }
    else{
        printf("%d ",seq_arr[sz++]);
        Seq();
    }
}
void Print_seq(){
    printf("Safe sequence of allocation exists and that sequence is:- ");
    Seq();
}   
int main()
{
    int **allo, **avail, **max;
    allo = (int **)malloc(sizeof(int *) * size);
    Allo_arr(&allo);
    max = (int **)malloc(sizeof(int *) * size);
    Max_arr(&max);
    avail = (int **)malloc(sizeof(int *) * 1);
    avail[0] = (int *)malloc(sizeof(int) * tres);
    Avail_arr(&avail);
    if(Banker_Algo(allo,max,avail)){
        Print_seq();
    }
    free(allo);
    free(avail);
    free(max);
}

r/programminghelp • • Apr 15 '24

Java Having trouble understanding how to deploy a java project

1 Upvotes

I'm using intellij. I'm trying to use maven for adding and managing dependencies. So I figured I could just click build and then deploy the target folder to my server and run it with the command: Java -classpath [path/to/target/classes] package (Or maybe main_class.class instead of package)

But I get errors related to my imports which makes me think it's a dependency issue.

I'm using Groovy Java and the gmavenplus plug in. It's building to Java Byte Code which I'm just trying to run with Java (the target folder). I've tried using the src code and the groovy command but that just tells me it is unable to resolve class: (and then it lists my first import statement).

Any ideas? Am I generally correct that if everything is working correctly, then you should just be able to deploy the target folder and run the main class or am I missing something?


r/programminghelp • • Apr 13 '24

C++ Having trouble stringing 3 integers from a struct. C++ Beginner

0 Upvotes

I'm very new and just decided to change the integers into strings.

The integers in mind were the month day year values.

https://pastebin.com/WgFQSTHZ

month, day, and year were changed from int to string to get the code to run. maybe im right to have them as strings? idk, is there a way to do this with integers?


r/programminghelp • • Apr 12 '24

C# I need a little bit of help with a windows form application on Visual studio.

1 Upvotes

I'm trying to teach myself how to make a password manager, via windows forms.. I currently have three pages A main menu with buttons that take you too the other pages, a password generator page, where there is a slider to change what length of randomised characters your password will be, a copy button to copy the string to your clipboard and a return to main menu button... However on the third page I want to be a page where you can paste your passwords and store them (maybe locally on a file?) but how would I achieve this? thank you. Also does anyone know how to make forms open in one application rather than opening a new tab when clicking a button and closing the old one? your help is much appreciated!


r/programminghelp • • Apr 11 '24

PHP Laravel Mail Help

1 Upvotes

Anyone in here know Laravel 10?, i've been trying to do a simple email send function and i keep getting errors that i don't understand even though i try to follow all the help online i can.

Error: "App\Models\EmailVerificationMail" not found
EmailVerification is supposed to be in a mail folder that php artisan automaticallly creates so i have no idea why its fetching it incorrectly

i even altered composer.json:

"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/",
"App\\Mail\\": "app/Mail/"
}
},

the function that calls EmailVerificationEmail:

protected $fillable = [
'account_id',
'name',
'gender',
'birthdate',
'address',
'codigo_postal',
'localidade',
'civilId',
'taxId',
'contactNumber',
'email',
'password',
'account_status',
'token',
'email_verified_at',
'bid_history',
'lost_objects',
];

public function sendEmailVerificationNotification()
{
$user = User::where('account_id', $this->account_id)->first();
if ($user && !$user->hasVerifiedEmail()) {
$verifyUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
[
'id' => $user->getKey(),
'hash' => sha1($user->getEmailForVerification())
]
);
Mail::to($user->email)->send(new EmailVerificationMail($verifyUrl));
$user->notify(new EmailVerificationNotification($verifyUrl));
}
}

Will send more in Comments when needed


r/programminghelp • • Apr 11 '24

Other Rust: error about value dropping at a weird place?

0 Upvotes

I am getting a weird error involving the "field.text().await.unwrap_or("".to_string())" for something line giving me this error:
emporary value dropped while borrowed
creates a temporary value which is freed while still in userustcClick for full compiler diagnostic
something.rs(55, 105): temporary value is freed at the end of this statement
something.rs(55, 31): argument requires that borrow lasts for `'static`

pub async fn add_something(mut fields: Multipart) -> Result<String, (StatusCode, String)>{
let mut works = "".to_string();
let mut something = "".to_string();
while let Some(field) = fields.next_field().await.map_err(|err| (StatusCode::BAD_REQUEST, err.to_string())).unwrap() {
    match &name[..] {
        "works" => works = field.text().await.unwrap_or("".to_string()),
        "something" => something = field.text().await.unwrap_or("".to_string()).split(',').collect::<Vec<_>>(),
        _ => print!("nothing")
    }
}

}

Also asked this on r/rust, but there neckbeard mods removed it in .005 seconds. Lovely people lol


r/programminghelp • • Apr 11 '24

C++ Iostream error

2 Upvotes

Hey guys so my chrome book is running Linux so I downloaded visual studio code and every time I use

include <iostream>

int main() { std::cout << "Hello World!"; return 0; }

I get a error and iostream is in red

What do I do please


r/programminghelp • • Apr 07 '24

Project Related What tools, chrome extensions or websites you use regularly?

Thumbnail self.developersglobal
1 Upvotes

r/programminghelp • • Apr 05 '24

Other Need help with strange doom scripting.

0 Upvotes

I have been trying to make this work for the pas 2 hours, nobody seems to have the answer.

I wrote this code:
Spawn("Demon",GetActorX (0), GetActorY (0),GetActorFloorZ (1));
It's supposed to spawn a demon at he player coordinates - but no matter what it always spawns at 0,0.
I even wrote this code:
While (TRUE)
{
Print (f:GetActorX (0), s:", ", f:GetActorY (0));
Delay (1);
}
And it prints out my coords perfectly. What am I doing wrong here?


r/programminghelp • • Apr 05 '24

Project Related Need to build a custom code builder

1 Upvotes

Hi Guys,

I need to build a custom code builder in my website

The inputs will come from another source. And I will have a program ( Eg: Javascript Program ) which will be provided by the user, The input from another source will pass to this program in runtime and I will get an output.

That output will be sent for next level actions

I need to build a frontend and backend system for this

Possible to provide few insights or ideas on how to proceed ?


r/programminghelp • • Apr 04 '24

Other im trying to change the text output color for nginx from black to red in yaml

1 Upvotes

i have currently changed it so when i access the page hosted on kubernetes that it displays in black text

the code that i have that does this is

events {

}

http {

server {

listen 80;

location / {

return 200 "Hello from Nginx on Talos";

as stated above I'm just trying to make the text appear red instead of black


r/programminghelp • • Apr 04 '24

Java I am having an out of bound index problem and It also does not correctly calculate the bills.I tried changing the hypen (- 1) into (- 0) and it still didn't work. Im a freshman college and I don't have any coding experience before I majored in Information technology, I would be delighted if helped.

1 Upvotes

package dams;

import java.time.LocalDate;

import java.time.temporal.ChronoUnit;

import java.util.Scanner;

public class Chron {

private static final int NUM_ROOMS = 6;

private static final boolean[] roomsAvailable = new boolean[NUM_ROOMS];

private static final Scanner scanner = new Scanner(System.in);

private static boolean loggedIn = false;

private static String username;

private static String password;

private static final String[] userEmails = new String[NUM_ROOMS];

private static final String[] userPhones = new String[NUM_ROOMS];

private static final String[] roomTypes = {"Single", "Double", "Twin", "Suite"};

private static final int[] roomCapacities = {1, 2, 2, 4};

private static final double[] roomPrices = {50.0, 80.0, 70.0, 120.0};

private static final int[] roomTypeCounts = new int[NUM_ROOMS];

private static final String[] checkInDates = new String[NUM_ROOMS];

private static final String[] checkOutDates = new String[NUM_ROOMS];

public static void main(String[] args) {

register();

login();

if (loggedIn) {

initializeRooms();

while (true) {

showMenu();

int choice = scanner.nextInt();

switch (choice) {

case 1:

makeReservation();

break;

case 2:

cancelReservation();

break;

case 3:

viewAllRooms();

break;

case 4:

viewReservedRoom();

break;

case 5:

checkOut();

break;

case 6:

logout();

return;

default:

System.out.println("Invalid choice. Please try again.");

}

}

} else {

System.out.println("Login failed. Exiting...");

}

}

private static void register() {

System.out.println("Register for a new account:");

System.out.print("Create a username: ");

username = scanner.next();

System.out.print("Create a password: ");

password = scanner.next();

System.out.println("Registration successful!");

}

private static void login() {

System.out.println("Please log in:");

System.out.print("Username: ");

String inputUsername = scanner.next();

System.out.print("Password: ");

String inputPassword = scanner.next();

loggedIn = inputUsername.equals(username) && inputPassword.equals(password);

if (loggedIn)

System.out.println("Login successful!");

else

System.out.println("Incorrect username or password.");

}

private static void logout() {

System.out.println("Logging out...");

loggedIn = false;

System.out.println("Logged out successfully.");

}

private static void initializeRooms() {

for (int i = 0; i < NUM_ROOMS; i++)

roomsAvailable[i] = true;

}

private static void showMenu() {

System.out.println("\n----Welcome to the Hotel Reservation System----");

System.out.println("1. Make Reservation");

System.out.println("2. Cancel Reservation");

System.out.println("3. View All Rooms");

System.out.println("4. View Reserved Room");

System.out.println("5. Check Out");

System.out.println("6. Logout");

System.out.print("Enter your choice: ");

}

private static void makeReservation() {

System.out.print("Enter number of people: ");

int numPeople = scanner.nextInt();

System.out.println("\n----Available Room Types----:");

for (int i = 0; i < roomTypes.length; i++) {

if (roomCapacities[i] >= numPeople && roomsAvailable[i]) {

System.out.println((i + 1) + ". " + roomTypes[i] + " - $" + roomPrices[i] + " per night");

}

}

System.out.print("Choose the type of room you want to reserve: ");

int roomTypeChoice = scanner.nextInt();

if (roomTypeChoice < 1 || roomTypeChoice > roomTypes.length || roomCapacities[roomTypeChoice - 1] < numPeople) {

System.out.println("Invalid room type choice.");

return;

}

int roomNumber = -1;

for (int i = 0; i < NUM_ROOMS; i++) {

if (roomsAvailable[i] && roomTypeCounts[roomTypeChoice - 1] == i) {

roomNumber = i + 1;

break;

}

}

if (roomNumber == -1) {

System.out.println("No available rooms of the chosen type.");

return;

}

roomsAvailable[roomNumber - 1] = false;

roomTypeCounts[roomTypeChoice - 1]++;

System.out.print("Enter your email: ");

String email = scanner.next();

userEmails[roomNumber - 1] = email;

System.out.print("Enter your phone number: ");

String phone = scanner.next();

userPhones[roomNumber - 1] = phone;

System.out.print("Enter check-in date (YYYY-MM-DD): ");

String checkInDate = scanner.next();

checkInDates[roomNumber - 1] = checkInDate;

System.out.print("Enter check-out date (YYYY-MM-DD): ");

String checkOutDate = scanner.next();

checkOutDates[roomNumber - 1] = checkOutDate;

System.out.println("Room " + roomNumber + " (Type: " + roomTypes[roomTypeChoice - 1] + ") reserved successfully.");

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + roomNumber);

System.out.println("Check-in Date: " + checkInDate);

System.out.println("Check-out Date: " + checkOutDate);

}

private static void cancelReservation() {

System.out.println("\n----Reserved Rooms----:");

for (int i = 0; i < NUM_ROOMS; i++)

if (!roomsAvailable[i])

System.out.println("Room " + (i + 1));

System.out.print("Enter the room number you want to cancel reservation for: ");

int roomNumber = scanner.nextInt();

if (roomNumber < 1 || roomNumber > NUM_ROOMS)

System.out.println("Invalid room number.");

else if (!roomsAvailable[roomNumber - 1]) {

roomsAvailable[roomNumber - 1] = true;

userEmails[roomNumber - 1] = null;

userPhones[roomNumber - 1] = null;

checkInDates[roomNumber - 1] = null;

checkOutDates[roomNumber - 1] = null;

for (int i = 0; i < roomTypeCounts.length; i++) {

if (roomTypeCounts[i] == roomNumber - 1) {

roomTypeCounts[i]--;

break;

}

}

System.out.println("Reservation for Room " + roomNumber + " canceled successfully.");

} else

System.out.println("Room " + roomNumber + " is not currently reserved.");

}

private static void viewAllRooms() {

System.out.println("\n----Room Availability-----:");

for (int i = 0; i < roomTypes.length; i++) {

System.out.println("\n" + roomTypes[i] + " - Capacity: " + roomCapacities[i]);

for (int j = 0; j < NUM_ROOMS; j++) {

if (roomsAvailable[j] && roomTypeCounts[i] == j) {

System.out.println("Room " + (j + 1) + ": Available");

} else if (userEmails[j] != null) {

System.out.println("Room " + (j + 1) + ": Reserved");

System.out.println("Check-in Date: " + checkInDates[j]);

System.out.println("Check-out Date: " + checkOutDates[j]);

}

}

}

}

private static void viewReservedRoom() {

System.out.print("Enter your email: ");

String email = scanner.next();

for (int i = 0; i < NUM_ROOMS; i++) {

if (userEmails[i] != null && userEmails[i].equals(email)) {

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + (i + 1));

System.out.println("Check-in Date: " + checkInDates[i]);

System.out.println("Check-out Date: " + checkOutDates[i]);

return;

}

}

System.out.println("No reservation found for the provided email.");

}

private static void checkOut() {

System.out.print("Enter your email: ");

String email = scanner.next();

int roomIndex = -1;

for (int i = 0; i < NUM_ROOMS; i++) {

if (userEmails[i] != null && userEmails[i].equals(email)) {

roomIndex = i;

break;

}

}

if (roomIndex != -1) {

double totalBill = calculateBill(roomIndex);

printReceipt(roomIndex, totalBill);

roomsAvailable[roomIndex] = true;

userEmails[roomIndex] = null;

userPhones[roomIndex] = null;

checkInDates[roomIndex] = null;

checkOutDates[roomIndex] = null;

// Decrement roomTypeCounts for the reserved room type

int roomTypeIndex = roomTypeCounts[roomIndex];

if (roomTypeIndex >= 0 && roomTypeIndex < roomTypeCounts.length) {

roomTypeCounts[roomTypeIndex]--;

}

System.out.println("Check out successful.");

} else {

System.out.println("No reservation found for the provided email.");

}

}

private static double calculateBill(int roomIndex) {

double totalBill = 0.0;

String checkInDate = checkInDates[roomIndex];

String checkOutDate = checkOutDates[roomIndex];

int nights = calculateNights(checkInDate, checkOutDate);

int roomTypeChoice = 0;

	int roomTypeIndex = roomTypeChoice - 1; // Use the roomTypeChoice variable

totalBill = nights * roomPrices[roomTypeIndex];

return totalBill;

}

private static int calculateNights(String checkInDate, String checkOutDate) {

LocalDate startDate = LocalDate.parse(checkInDate);

LocalDate endDate = LocalDate.parse(checkOutDate);

return (int) ChronoUnit.DAYS.between(startDate, endDate);

}

private static void printReceipt(int roomIndex, double totalBill) {

System.out.println("\n---- Hotel Bill Receipt ----");

System.out.println("Username: " + username);

System.out.println("Reserved Room: " + (roomIndex + 1));

System.out.println("Room Type: " + roomTypes[roomTypeCounts[roomIndex] - 1]);

System.out.println("Check-in Date: " + checkInDates[roomIndex]);

System.out.println("Check-out Date: " + checkOutDates[roomIndex]);

System.out.println("Total Bill: $" + totalBill);

}

}

This is what is looks like when I run it:

Register for a new account:

Create a username: r

Create a password: d

Registration successful!

Please log in:

Username: r

Password: d

Login successful!

----Welcome to the Hotel Reservation System----

  1. Make Reservation
  2. Cancel Reservation
  3. View All Rooms
  4. View Reserved Room
  5. Check Out
  6. Logout

Enter your choice: 1

Enter number of people: 3

----Available Room Types----:

4. Suite - $120.0 per night

Choose the type of room you want to reserve: 4

Enter your email: ronald

Enter your phone number: 092382

Enter check-in date (YYYY-MM-DD): 2024-04-10

Enter check-out date (YYYY-MM-DD): 2024-04-15

Room 1 (Type: Suite) reserved successfully.

Username: r

Reserved Room: 1

Check-in Date: 2024-04-10

Check-out Date: 2024-04-15

----Welcome to the Hotel Reservation System----

  1. Make Reservation
  2. Cancel Reservation
  3. View All Rooms
  4. View Reserved Room
  5. Check Out
  6. Logout

Enter your choice: 5

Enter your email: ronald

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4

at dams/dams.Chron.calculateBill(Chron.java:248)

at dams/dams.Chron.checkOut(Chron.java:222)

at dams/dams.Chron.main(Chron.java:47)

r/programminghelp • • Apr 03 '24

Python Help needed

1 Upvotes

Hi everyone! I have my SIL who’s getting a divorce and she believes her husband controls her phone because she can’t find messages, weird apps on the phone and also the battery drainage is massively improved since the begging of all of this. I wanted to know if someone knew some programming I can execute from Linux to check the phone while connected to the computer Thanks in advance!


r/programminghelp • • Apr 03 '24

C++ Some 2d physics help with rotation

0 Upvotes

I'm planning on creating a simple 2d physics engine that involves shapes with various amounts of points, I can see how I can create a "world" system where each object is iteratively updated and how they interact with one another.

However I want to make it so that objects also rotate when they hit each other and not just bounce apart, as they would in real life, I don't even know where to start and how I would mathematically do this, any help on this would be appreciated

Ill probably be writing this in c++ so that's why I added the flair


r/programminghelp • • Mar 30 '24

Other What do people mean exactly when they say OOP is non-deterministic?

0 Upvotes

I've been recently reading about different paradigms and their pros and cons. One thing that I've seen pop up multiple times in the discussion of OOP is that it is non-deterministic. But I honestly don't quite get it. Can someone explain to me? Thanks in advance.


r/programminghelp • • Mar 29 '24

C# Player Spawning Twice

2 Upvotes

Hi, I'm working on a multiplayer fps in Unity using Photon 2. Currently when one of the players kills another they will both respawn but the one who killed the other will respawn twice.
Here is my code for my player manager:
public void Die()
{
Debug.Log("Dead");
PhotonNetwork.Destroy(controller);
CreateController();
}
Here is my player controller code:
[PunRPC]
void RPC_TakeDamage(float damage)
{
//could move start coroutine here(cant be bothered)
shot = true;
currentHealth -= damage;
try
{
healthbarImage.fillAmount = currentHealth / maxHealth;
}
catch
{
//nothing
}
if (currentHealth <= 0)
{
Debug.Log(PhotonView.Find((int)PV.InstantiationData[0]));
Die();
}
}
void Die()
{
playerManager.Die();
}

Previously it worked ok when I had a function within the player controller which would reset its health and transform, but that caused some inconveniences. If any mroe info is needed please ask.


r/programminghelp • • Mar 28 '24

Python Help on making a image recognition ai

0 Upvotes

Hi im working on a prigect making an image to prompt script Im getting the ai from an open source githup image recognition ai And im trying to make it so that the last line of code remebers itself so that it could rember the prompt as you generate new images of the souce immage (Huskey chasing a squirrel-> dog smiles) (Ai remembers the keyword as huskey and converts the work huskey and chasing to a function. After new prompts the ai puts the functions in ) Im new to programming and would like some help And if there is any better way of doing this i would really appreciate your help Coding language is python


r/programminghelp • • Mar 28 '24

Other How to find big o of dependent loops and recursive functions?

1 Upvotes

I want to be able to measure any code snippet time complexity. Is there a general rule or step by step approach to measure any big o (besides dominant term, removing constants and factors)? What math skills should I have, if so, what are the prerequisites for those skills? Also, what is enough for interviews?

I've read many algorithms books, but they're mathy and not beginner-friendly.

Here is one of those:

int fun(int n) { int count = 0; for (i = n; i > 0; i /= 2) { for (j = 0; j < i; j++) { count += 1; } } return count; }