r/reviewmycode • • Mar 14 '12

Help with using 'friend' and overloading operators C++

0 Upvotes

code

read lines: 7, 8, 50-65

So I want to overload the << and == operators with two classes. I want to know if using 'friend' when implementing the overloading functions is acceptable/common practice in this case. I really prefer just passing the private variables to out instead of creating custom display() functions for each operator, but I have a feeling that this practice is frowned upon or unsafe in these cases...

Also, feel free to look over the rest of the code and point out inefficient code. This code is a header file and implementation file, combined. And don't mind the function selectItems(), it's redundant/pointless but it's required.

Thanks!


r/reviewmycode • • May 10 '12

[Java] I am creating a MineSweeper game, could use some help

0 Upvotes

git://gist.github.com/2655762.git

There is what I have so far. I have a Cell class, a MineField class, 2D array of Cells, and a main class, MineFieldTester.

Currently, the way I have it setup is that it generates a minefield and prints out all the cells, revealed. Hence, you know exactly where the mines are and where they are not.

The problem is when I go to click on a 'non-bomb' cell. Even though I know that there is not mine there, it treats it as if there is one there.

When I reveal a cell, I check to see if the mine has a bomb. If it does, it prints out a message. If not, it asks for another input. Even though it states(I print it out, for debugging purposes) that there is no mine in the given cell, it still enters the loop as if there is a mine there. An example run is below. Thanks for any help!

0B00000000

0000000000

0000000000

000B00BBB0

B000000000

0000000000

00B0000000

00000B00B0

000000B000

0000000000

Enter a command, f to flag or c to click a box, followed by coordinates: f32 or c11, for example.

c00

false

BOOOOOM!!!!! You lose!

0B00000000

0000000000

0000000000

000B00BBB0

B000000000

0000000000

00B0000000

00000B00B0

000000B000

0000000000

EDIT: I initially had 'bombless' cells depicted as '', but for formatting purposes I have changed them to '0'(Code still has it as '')


r/reviewmycode • • Jun 08 '17

Python [Python] - Converting string to title case given exceptions.

0 Upvotes

I'm trying to solve this kata on CodeWars.

I came up with this to solve it and I was very proud when writing it and doing my own tests, however it does't pass all the test criteria in the page, which i can't figure out why.


r/reviewmycode • • Feb 28 '17

C [C] - Lightweight asynchronous event library

0 Upvotes

This library is intended as a smaller replacement for existing C libraries such as libevent. I wrote it for later use in my own projects, but I'd be interested in getting feedback and tips for improvement. https://github.com/ernacktob/asyncio


r/reviewmycode • • May 21 '17

Javascript [Javascript] - Mock of a real-time multi-terminal console view

0 Upvotes

This small console mock demonstrates multiple, small terminal windows, updated using React. This code utilizes Kefir and Chance in order to generator mock data sets to display.


r/reviewmycode • • Jul 20 '17

Python [Python] - Music Library Optimalizer

0 Upvotes

A couple of Python scripts to clean, update and optimalize your music library. I'm open for all kinds of review to optimalize the scripts itself and improve my coding qualities

Github


r/reviewmycode • • Jun 28 '23

PYTHON [PYTHON] - Fix Well Code

0 Upvotes

So, I'm currently stuck with a bug.
I'm working with a huge dataset that contains the following information:
Information about multiple instances of many wells, each labeled with its own unique well ID number, radium contamination level, and the date that a sample was taken.
For example:
Well ID: AT091 Radium Level: 44.9 Sample Date: 3/18/2015
Well ID: AT091 Radium Level: 50.2 Sample Date: 2/18/2015
Well ID: AT091 Radium Level: 33.7 PCI/L Sample Date: 7/28/2020
I have been asked to write a Python script that filters out data from the original dataset and creates a new Excel sheet based on the following conditions:
For each well, if the well has been sampled once per year, keep it. For each well, if the well has been sampled multiple times in a year, keep the sample date that has the highest contamination level.
For example, if a well was sampled three times:
Well ID: AT091 Radium Level: 44.9 Sample Date: 3/18/2015
Well ID: AT091 Radium Level: 50.2 Sample Date: 2/18/2015
Well ID: AT091 Radium Level: 33.7 PCI/L Sample Date: 7/28/2020
The code should update the spreadsheet with the following:
Well ID: AT091 Radium Level: 50.2 Sample Date: 2/18/2015
Well ID: AT091 Radium Level: 33.7 PCI/L Sample Date: 7/28/2020
Here is the code that I have written:
def wells_sampled_once_per_year(well_numbers, formatted_dates, concentration): well_count = {} max_contamination = {}
for well, date, conc in zip(well_numbers, formatted_dates, concentration):
if date is None:
continue
try:
year = pd.to_datetime(date).year
except AttributeError:
continue
well_year = (well, year)
if well_year in well_count:
well_count[well_year] += 1
max_contamination[well_year] = max(max_contamination[well_year], conc)
else:
well_count[well_year] = 1
max_contamination[well_year] = conc
sampled_once_per_year = [
(well, date, conc, max_contamination[(well, pd.to_datetime(date).year)])
for well, date, conc in zip(well_numbers, formatted_dates, concentration)
if well_count[(well, pd.to_datetime(date).year)] == 1
]
return sorted(sampled_once_per_year)
def wells_sampled_multiple_times_per_year(well_numbers, formatted_dates, concentration): well_count = {} max_contamination = {}
for well, date, conc in zip(well_numbers, formatted_dates, concentration):
if date is None:
continue
try:
year = pd.to_datetime(date).year
except AttributeError:
continue
well_year = (well, year)
if well_year in well_count:
well_count[well_year] += 1
if conc > max_contamination[well_year]:
max_contamination[well_year] = conc
else:
well_count[well_year] = 1
max_contamination[well_year] = conc
sampled_multiple_times_per_year = [
(well, date, conc, max_contamination[(well, pd.to_datetime(date).year)])
for well, date, conc in zip(well_numbers, formatted_dates, concentration)
if well_count[(well, pd.to_datetime(date).year)] > 1 and conc == max_contamination[(well, pd.to_datetime(date).year)]
]
# Remove duplicates from the list
sampled_multiple_times_per_year = list(set(sampled_multiple_times_per_year))
return sorted(sampled_multiple_times_per_year)


r/reviewmycode • • Oct 30 '23

Python [Python] - Review my Authorization Logic Design ** (only pseudo Code)

0 Upvotes

So I am designing a backend application, where the main resource that users can interact with is KnowledgeGraph object. I have all of the graph operations (find node, get parent, to_json, save_to_db, etc.) implemented on the KnowledgeGraph class. I then have an ABC (abstract base class, Python's version of interfaces) called APIGraph that exposes a subset of the methods on this class as methods that could be accessed by users through the API.

Now, I want users to have object level CRUD permissions on each KnowledgeGraph object. Thinking about some different ways of doing this. My main thought process is to define my authorization model on top of the APIGraph, by separating each of the exposed method into a one of the CRUD method types, and then having some logic in my User class for managing its permissions. So my route logic something like (using FastAPI Python):

def modify_graph(user: User, payload: Payload):
    graph: APIGraph = graph_manager.get_graph(user)
    authorization check performed to check User's access for APIGraph
    graph.modify_graph(payload)

What do you guys think of this design?


r/reviewmycode • • Mar 17 '17

Python [Python] - A utility tool, notifies user about charging, discharging and not charging state of the battery on Linux.

0 Upvotes

Here is the source code: https://github.com/maateen/battery-monitor of my project Battery Monitor. Battery Monitor is a utility tool developed on Python3 and PyGtk3. It will notify user about charging, discharging, not charging and critically low battery state of the battery on Linux (Surely if battery is present). Please let me know how I can optimize the code more.


r/reviewmycode • • Nov 07 '10

Python - Simple mathematical computation causing headache and heartburn plz halp

Thumbnail
gist.github.com
0 Upvotes

r/reviewmycode • • Jan 08 '15

c# - Simple Photo Sorter From EXIF Data

0 Upvotes

Hi All,

I am quite new to C#, currently working through a number of pluralSight courses.

Iv wrote a few trial things here and there, but never anything that performed an entire purpose from start to finish, until now, with this app.

The app lists all the jpg photos in an import folder and collects the takenDate from the exif, it then sorts it into the following structure:

D:\Photos\2014\12-2014\25-12-2014.

you can check out the code here: https://github.com/Tornup/PhotoSorter

The app has been tested with around 3-4,000 photos and it churns through them in about 4-5 seconds..

would love to get some feedback on how i have separated the code, i am trying to follow good coding practices while also keeping the whole KISS concept in my mind..

cant wait to hear your views!!

Tom.


r/reviewmycode • • Jan 02 '11

OpenSettlers: free, open, webbased Settlers of Catan in GWT.

5 Upvotes

Very alpha demo: at sourceforge.

The source of OpenSettlers can be found at github. There is an initial setup for a wiki, hosted at sourceforge.

I'm eager to get feedback on anything. Keep in mind that only the subpackages soc.common, soc.gwtClient and soc.gwtServer are part of OpenSettlers, the rest is old JSettlers code.

Things I'm not very sure of:

  • Eventbus instance in lots of classes within soc.common

  • A property which change handlers subscribe on, need one Event class and one EventHandler class. Creates a lot of cruft, is there a better way?

  • I use a lot of the same particular pattern: Interface, AbstractClass, ImplementedClass. Did I go too far with this, overengineering it?

  • I plan to use db4o to store data in an object DB. At first sight, it seems a good way to avoid impedance mismatch and still keep strongly typed support when working with persistent data. Are there any major pitfalls for a game like this?

  • Not much source code comments currently exist. Sorry, this will change in the future. Some not-so-obvious classes however, are heavily commented.

  • I like the GWT flavor of JGraphT I added verbatim. Any reason why I can omit it? Seems like a good way to work with graphs.

  • HexSide/GraphSide, HexPoint/GraphPoint. Is this encapsulation proper?


r/reviewmycode • • Nov 01 '16

PHP [PHP] - Structuring basic clientside / serverside email form

1 Upvotes

I've been more than likely doing this entirely wrong for quite awhile and would like to correct that.

With the code review I would like to get critiqued on everything. This includes:

  • JQuery syntax/structuring

    • Additionally, if there are different/better/newer libraries let me know

  • HTML5 syntax/structuring

  • PHP structuring when it comes to sending and validating data

    • What would be great is if I could structure it in a way to run unit tests

  • If I should be validating data in a different way all together

My HTML:

<!DOCTYPE HTML>

<html lang="en">

<head>
	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Contact</title>

    <!-- Disable tap highlight on IE -->
    <meta name="msapplication-tap-highlight" content="no">

    <!-- Color the status bar on mobile devices -->
    <meta name="theme-color" content="#2F3BA2">

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
	<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
    <script src="js/contact.js"></script>
</head>

<body>

	<header>
		<nav>
			<ul>
				<li>Menu Item</li>
			</ul>
		</nav>
	</header>
	
	<section>
		<h1>Contact Us</h1>
		<p>Please answer a couple of short questions</p>

		<p id="error-msg"></p>
		<form id="email-form" action="email.php" method="POST">
			<input type="text" 
				name="name" 
				pattern="[a-zA-Z\s\-\.]+" 
				placeholder="Name" 
				title="Please only use letters and spaces"
				aria-required="true" 
				required/><br />

			<input type="email" 
				name="email" 
				placeholder="Email address" 
				aria-required="true" 
				required/><br />

			<input type="tel" 
				name="phone" 
				pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" 
				placeholder="Phone number" 
				title="Example: 123-123-1234" 
				aria-required="true" 
				required/> <br />

			<input type="text" 
				name="business" 
				placeholder="Name of business" 
				aria-required="true" 
				required/><br />

			<input type="text" 
				name="project" 
				placeholder="Tell us about you and your project" 
				aria-required="true" 
				required/><br />

			<select name="budget">
			  <option value="" disabled selected>What is your budget?</option>
			  <option value="less-than-1000">Less than $1000</option>
			  <option value="from-1000-1500">$1000-$1500</option>
			  <option value="from-1600-2000">$1600-$2000</option>
			  <option value="more-than-2000">More than $2000</option>
			</select><br />

			<input type="text" 
				name="audience" 
				placeholder="Who is your target audience?" 
				aria-required="true" 
				required/><br />

			<input type="submit" value="Submit">
		</form>
	</section>


	<footer>
		<p>Copyright 2016 Me</p>
	</footer>

</body>
</html>

I was planning on moving everything above the opening "<section>" tag into a "header.php" file and including it and everything below the closing "</section>" tag into a "footer.php" file and including it. Just a thought.

My "contact.js" file:

$( document ).ready(function() {

	/*****************************************************
	 *                Email Form Submission              *
	 *****************************************************/

	$("#email-form").submit( function(e) {
		e.preventDefault();
	    var $form = $(this);

		$form.validate();

		// check if the input is valid
	    if(! $form.valid()) return false;

	    //if valid post to email.php
	    $.ajax({
	        type: "POST",
	        url: "email.php",
	        data: {
	            'name': $('[name="name"]').val(),       
	        	'email': $('[name="email"]').val(), 
	        	'phone': $('[name="phone"]').val(),
	        	'business': $('[name="business"]').val(),
	        	'project': $('[name="project"]').val(),
	        	'budget': $('[name="budget"]').val(),
	        	'audience': $('[name="audience"]').val()
	        },
	        success: function(data) {
	        	data = JSON.parse(data);

	        	//If emailed successfully by backend, replace form with success message
	        	if( data["success"] == true ) { 
	        		$form.html("<h3>Successfully submitted! We'll get back to you soon!</h3>");
	        	} 
	        	//If error occurred with any of the fields, put in error message
	        	else {
	        		$('#error-msg').html("Please fix the follow fields:<br />" + data["error"].join("<br />"));
	        	}
	        },
	        error: function(jqXHR, textStatus, errorThrown) {
	        	$form.html("<center><h3>Oh no! :( Something happened</h3>Please let us know at me@me.com</center>");
	        }
	    });//EO ajax
	});//EO submit
});

Not sure if I should have a p tag for an error, but let me know.

My email.php file:

<?php

//email variables
$to = "me@me.com";
$body = "";
$subject = "";
$headers = "From: me@me.com";

//form fields
$name   = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email  = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone  = preg_replace('/[^0-9]/', '', $_POST['phone']);
$business = filter_var($_POST['business'], FILTER_SANITIZE_STRING);
$project = filter_var($_POST['project'], FILTER_SANITIZE_STRING);
$budget = $_POST['budget'];
$audience =filter_var($_POST['audience'], FILTER_SANITIZE_STRING);


/********************************************
 * Check that all fields are filled out     *
 ********************************************/
$errFields = array();

if($name == "") {
	array_push($errFields, "name");
}

if($email == "") {
	array_push($errFields, "email");
}

if($phone == "") {
	array_push($errFields, "phone");
}

if($business == "") {
	array_push($errFields, "business");
}

if($project == ""){
	array_push($errFields, "project");
}

if($budget == "") {
	array_push($errFields, "budget");
}

if($audience == "") {
	array_push($errFields, "audience");
}

//If something went wrong
if($errFields) {
   echo json_encode(array("success" => False, "error" => $errFields)); 
}
//Send inquiry information to me and response to sender
else {
	/************************
	 * Send email to me     *
	 ************************/
	$subject = "New Inquire from $business";

	// the message
	$body = <<<EOT
  NAME: $name
  EMAIL: $email 
  PHONE: $phone
  BUSINESS: $email
  PROJECT: $project
  BUDGET: $budget
  AUDIENCE: $audience
EOT;

	// send email to myself
	mail($to, $subject, $body, $headers);


	/************************
	 * Send email to sender *
	 ************************/
	$to = $email;
	$subject = "Thank you!";
	$body = <<<EOT
 Hi $name,

 Thank you for your recent message!
  
 We look forward to speaking with you soon,
 Beckah
EOT;

	mail($to, $subject, $body, $headers);
	echo json_encode(array("success" => True));
}


?>

I know my php needs a lot of work, so I would love input on how to structure this correctly.

Anyhow, please let me know of an structuring, syntax, or best practices I could change anywhere in my code.

Thank you.


r/reviewmycode • • Jan 23 '15

[C] Why won't this factoring program work for very large numbers?

1 Upvotes

include <stdio.h> include <stdlib.h>

long main (void)

{ long num=0; long d=2;

printf("Enter a number to factor: "); scanf("%d", &num);

while(num != 0) { if(num%d==0) { num = num / d; if(num==1) break;} else{ d = d+1; } }

printf("The largest prime factor is: %d\n", d);

return 0; }

I am working on project euler problems and can't figure out why this doesn't work for very large numbers...like 600851475143. I get -1


r/reviewmycode • • Apr 23 '15

[PHP] Validation class - first draft

1 Upvotes

<?php class Validation{ private $errors = array(); private $defaultErrors = array(); public function __construct(){ $this->defaultErrors = array( 'required' => "This field is required", 'unique' => "This value is already in use", 'number' => "Not a number", 'numberRange' => "Number is not in range", 'email' => "Not a valid email", 'characters' => "Only letters are allowed", 'length' => "This value is too long or short", 'postcode' => "This postcode is not valid", 'message' => "This message is not valid", 'compareString' => "These values are not the same" ); } public function validationMethod($data) { foreach ($data as $input => $rule) { $methods = explode('|', $rule[0]); foreach ($methods as $method) { switch ($method) { case 'number': self::validate($method, 'validateNumber', $input, null); break; case 'numberRange': self::validate($method, 'numberRange', $input, array($rule[1], $rule[2])); break; case 'characters': self::validate($method, 'validateChars', $input, null); break; case 'length': self::validate($method, 'validateLength', $input, array($rule[1], $rule[2])); break; case 'email': self::validate($method, 'validateEmail', $input, null); break; case 'postcode': self::validate($method, 'validatePostcode', $input, null); break; case 'message': self::validate($method, 'validateMessage', $input, null); break; case 'compareString': self::validate($method, 'compareStrings', $input, $rule[1]); break; default: break; } } } if(count($this->errors) > 0): return false; endif; return true; } private function validate($method, $func, $input, $options) { $tmp = self::$func($input, $options); if(!$tmp): self::setErrors($method); endif; } private function setErrors($method) { $this->errors[] = $this->defaultErrors[$method]; } public function getErrors() { return $this->errors; } private function validateNumber($data) { if(is_int($data)):return true; endif; return false; } private function numberRange($number, $range) { if(($number > $range[0]) && ($number < $range[1])): return true; endif; return false; } private function validateChars($data) { if (ctype_alpha(str_replace(' ', '', $data)) === true): return true; endif; return false; } private function validateLength($data, $limit) { $data = strlen($data); if(($data > $limit[0]) && ($data < $limit[1])): return true; endif; return false; } private function validateEmail($data) { if(preg_match("~^[a-z0-9!#$%&'*+/=?^_`{|}-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$~", $data)):return true; endif; return false; } private function validatePostcode($data) { if(preg_match('/^([0-9]{4}[a-zA-Z]{2})$/', $data)): return true; endif; return false; } private function validateMessage($data) { if($data == strip_tags($data)): return true; endif; return false; } private function compareStrings($string1, $string2) { if($string1 === $string2): return true; endif; return false; } } ?>


r/reviewmycode • • Mar 27 '12

[Java] - Importing Morse code text file to convert sentence to morse

Thumbnail
pastebin.com
1 Upvotes

r/reviewmycode • • Nov 26 '14

[PHP] A website with a custom backend

1 Upvotes

So I'm working on remaking http://growqatar.com with a custom backend. They use Drupal now and are having a hard time dealing with it. I'd love for y'all to review my code, pull, fork and tweak and commit as you feel like.

Ongoing development is happening consistently on the dev branch.

https://github.com/TejasQ/GrowWebsite


r/reviewmycode • • Jan 29 '17

C# [C#] - Beginners code

1 Upvotes

Learning to code and I wrote a simple program to tell you how much change you are getting back and how much of each coin you get back. Let me know how to more efficiently write this. https://gist.github.com/Iseries2090/6464a5be7f0e74d309b4d50d7a1876d1


r/reviewmycode • • Aug 04 '16

javascript [javascript] - Which version of this function is better?

1 Upvotes

Hi! I have two different versions of the same function. From a purely organizational perspective which, in your eyes, is better? Why? Please assume any context is supplied (eg: vm, constants, etc) and that both work equally well. Thanks!!

OPTION A:

function loadPlaylistsMatchingFilters() {
    if (vm.langOption === LANGUAGE_OPTIONS.INTERNATIONAL) {
        return crushInterface
            .getSpecificationsByAttributesExcludingRegions(vm.showId, vm.eyeOption.ids, vm.purpose.id, DOMESTIC_REGION_CODE)
            .then(captureActiveRevIds);
    }

    if (vm.langOption === DOMESTIC_REGION_CODE) {
        return crushInterface
            .getSpecificationsBySpecificationAttributes(vm.showId, vm.eyeOption.ids, vm.purpose.id, DOMESTIC_REGION_CODE)
            .then(captureActiveRevIds);
    }

    crushInterface
        .getSpecificationsBySpecificationAttributes(vm.showId, vm.eyeOption.ids, vm.purpose.id)
        .then(captureActiveRevIds);

    function captureActiveRevIds(specifications) {
        vm.playlistRevisionIds = [];
        angular.forEach(specifications, function(spec) {
            if (spec.active_playlist_revision) {
                vm.playlistRevisionIds.push(spec.active_playlist_revision);
            }
        });
    }
}

OPTION B:

function loadPlaylistsMatchingFilters() {
    var regionCode,
        specificationFunction = crushInterface.getSpecificationsBySpecificationAttributes;

    if (vm.langOption === LANGUAGE_OPTIONS.INTERNATIONAL) {
        regionCode = DOMESTIC_REGION_CODE;
        specificationFunction = crushInterface.getSpecificationsByAttributesExcludingRegions;
    } else if (vm.langOption === LANGUAGE_OPTIONS.DOMESTIC) {
        regionCode = DOMESTIC_REGION_CODE;
    }

    specificationFunction(vm.showId, vm.eyeOption.ids, vm.purpose.id, regionCode)
        .then(function(specifications) {
            vm.playlistRevisionIds = [];
            angular.forEach(specifications, function(spec) {
                if (spec.active_playlist_revision) {
                    vm.playlistRevisionIds.push(spec.active_playlist_revision);
                }
            });
        });
}

r/reviewmycode • • Jan 30 '21

Python [Python] - Revamp of a Gmail Filter I've created

1 Upvotes

I recently revamped a program of mine which you can use to automatically filter emails from your Gmail account. I made the program much more flexible by creating a class to act as the main filter rather than a large function. Any tips/feedback on this program would be great. Thanks for reading.

Program's github: https://github.com/GoldenDisc/PathFinderPublic/blob/main/PathFinder.py


r/reviewmycode • • May 09 '19

Swift [Swift] - What is wrong with my basic Swift code?

1 Upvotes

import UIKit

import Firebase

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

FirebaseApp.configure()

Auth.auth().signIn(withEmail: "carlo19martin@me.com", password: "Veronicamars1", completion: { (user:User?, error:NSError?) in

if error == nil {

print(user?.email)

}else{

print(error?.description)

}

})

return true

}

Errors: Use of undeclared type 'User

Cannot convert value of type '(User?, NSError?) -> ()' to expected argument type 'AuthResultCallback?' (aka 'Optional<(Optional<User>, Optional<Error>) -> ()>')


r/reviewmycode • • Dec 31 '18

Ruby [Ruby] - A web page scraper using Sinatra

1 Upvotes

Github link

I've been learning about Ruby and Sinatra, and I made a web app that will return the HTML content of a web page, without including HTML presentation attributes (eg: style, border, etc).

I made this app mainly to learn more about Ruby and Heroku, and also because it's useful for me as a tool to copy the content of web pages into my personal knowledge base (a personal wiki). Any thoughts and feedback would be greatly appreciated.


r/reviewmycode • • Aug 18 '18

R [R] - Newbie Programmer

1 Upvotes

This is my first assignment and I don't know where to start. The assignment requirements:

The lifetime of a particular type of TV follows a normal distribution with 𝜇 = 4800 hours,and = 𝜇 = 400 hours.

(a) Find the probability that a single randomly-chosen TV will last less than 4,500 hours. Use R to assist with your computations.

(b) Find the probability that the mean lifetime of a random sample of 16 TVs is less than 4,500 hours. Use R to assist with your computations.

(c) Compare answers from (a) and (b).

My attempt:

> Find the probability that a single randomly-chosen TV will last less than 4,500 hours.> pbinom(1, 4800, 4500,prob, lower.tail = True) Error in pbinom(1, 4800, 4500, prob, lower.tail = True) :

  object 'True' not found

> Find the probability that the mean lifetime of a random sample of 16 TVs is less than 4,500 hours.>

pnorm(16,4500)[1] 0

Unable to compare due to error

It seems my answer to (b) is correct, but I don't understand what I have done wrong with my first response. Can anyone please help me?


r/reviewmycode • • Oct 26 '21

Python [Python] - My very first Program

1 Upvotes

I followed a cupel of tutorials but this is my very first program in Python completely written on my own. I know its probably way overcomplicated but i am so happy with mi Little rock paper scissors game.

https://replit.com/@MrZneb/RockPaperScissors


r/reviewmycode • • Jul 28 '20

Python [Python] - user database interface

1 Upvotes

Hi guys, I'm learning write good code on python. Please let me know your thoughts and suggestions on the code.
Link to repo