text stringlengths 1 2.12k | source dict |
|---|---|
javascript, design-patterns, node.js
Title: Nodejs Module Pattern And Caching
Question: The question is about nodejs module pattern code structure.
My goal is to initialise the module at one time and export the module using module.export
so that, it's available in other files.
I took Twilio for explaining.
Here I want to initialize twilo using credentials and export it as twilioClient, which I can reuse without reinitialising.
But I also need a dynamic Twilio client, ie, I give the credentials as params and create a client using that param.
That was my requirement and I came across this structure,
const twilio = require('twilio');
function init (config) {
const twilioSID = config.TWILIO_ACCOUNT_SID;
const twilioAuth = config.TWILIO_AUTH_TOKEN;
const client = twilio(twilioSID, twilioAuth);
return client;
}
const twilioSID = process.env.TWILIO_ACCOUNT_SID;
const twilioAuth = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(twilioSID, twilioAuth);
module.exports = {
twilioClient: client,
twilioClientFn: init
};
Is this structure okay? is there any room for improvement?
Thank You
Answer: Keep it D.R.Y.
Avoid repeating code. The function init has its task repeated below it. There is no need to repeat that code, use the function.
Avoid single use variables. The function is storing values in variables for no reason. Use the references directly, return the result of the call twilio rather than store it before returning it.
Aim to keep the code short, more code is more to read understand and maintain. In this case less code also means less CPU cycles needed to run
Rewrite
Does the same in less than half the code.
const twilio = require("twilio");
const twilioClientFn = env => twilio(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH_TOKEN);
module.exports = {
twilioClient: twilioClientFn(process.env),
twilioClientFn,
}; | {
"domain": "codereview.stackexchange",
"id": 43959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, design-patterns, node.js",
"url": null
} |
c, variant-type
Title: Dynamic type implementation in C
Question: Dynamic Type - [ int, char, bool, ... => dtype ]
Dynamic Type in C, A project that I had been thinking of for a while and made it.
How it works ?
Dtype currently is same as char, when doing dtype var[size]; size bytes are reserved for var as normal char would do. The actual working of dtype is that it stores the type of variable in first 1 byte i.e var[0] = (char)type;, and stores its size info in second & third bytes as unsigned short, i.e * ( unsigned short * ) (var + 1) = size; after that any data to be stored is checked with the size, i.e * (unsigned short * ) (var + 1) and if the size is equal or greater than the data to be stored, the data is then hard-copied from fourth byte onwards, i.e from ( var + 3) and to get data, it simply checks the type and grabs the data, if type mismatch occurs, it produces a warning [ in runtime ].
Advantages over normal types
Dynamic types enable you to store any kind of variable type in one variable
has reusability, meaning an integer dynamic variable can be reused to store string!
saving memory space, kind of - If you need let's say long integer, string with 10 bytes, integer, normally you would make different variables for each of them which causes more use of memory whereas you can just make a dtype of maximum size among all and use it to store anything of that byte size, no need to take more memory.
custom types are also supported!
Runtme Speed test ( with -O2 flag, on my device - results may vary on yours. ) :-
No.
Normal variables doing same thing
Dtype variables doing same thing
1
~20.945 ms on average [50+ tests]
~21.025 ms on average [50+ tests]
2
~19.881 ms on average [100+ tests]
~19.997 ms on average [100+ tests]
As seen above not much performance impact has been seen. And considering the advantages, It seems to be good
The code :-
/**
* @file dtype.h
*
* @brief Contains the definition for `dtype` along with `dtypes` & `dtypes.*` function signatures.
*/ | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
#ifndef DTYPE_H_INCL
#define DTYPE_H_INCL
#include <stdbool.h>
/**
* @brief the actual dtype which stores the data
* @example dtype var[size_in_bytes];
*/
typedef char dtype;
/// @brief Current size_type for `dtype`
typedef unsigned short DTYPE_SIZE;
/// @brief Display warning if true
#ifndef DTYPE_WARN_OUT
#define DTYPE_WARN_OUT true
#endif
/// @brief Immediately display errors if true
#ifndef DTYPE_ERROR_OUT
#define DTYPE_ERROR_OUT true
#endif
/// @brief Exit on error if true
#ifndef DTYPE_EXIT_ON_ERR
#define DTYPE_EXIT_ON_ERR true
#endif
/**
* @enum DTYPES_ERR
* @brief ErrorCode enums for DTYPES_ERR
*/
enum DTYPES_ERR {
DTYPE_NO_ERR,
DTYPE_SIZE_LOW,
DTYPE_SIZE_HIGH,
DTYPE_MIN_MEM,
DTYPE_VALUE_ERR,
DTYPE_NOT_INIT,
DTYPE_UNKNOWN_ERR
};
/**
* @enum DTYPES_TYPES
* @brief Typecode for identifying current type of `dtype`.
* @brief DTYPE_TYPE for normal types,
* @brief DTYPE_UTYPE for unsigned types.
*/
enum DTYPES_TYPES {
DTYPE_INVALID, // Invalid type, not initialized!
DTYPE_NONE,
DTYPE_BOOL,
DTYPE_SHORT,
DTYPE_USHORT,
DTYPE_INT,
DTYPE_UINT,
DTYPE_LONG,
DTYPE_ULONG,
DTYPE_FLOAT,
DTYPE_DOUBLE,
DTYPE_CHAR,
DTYPE_STR,
DTYPE_OBJECT, // object type -> currently holds a custom type of variable.
DTYPE_UNKNOWN // unknown type!
};
/**
* @struct __dtypes_struct
* @typedef __dtypes_struct
*
* @brief a wrapper for all dtype functions.
*/
typedef struct __dtypes_struct { | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
/**
* @brief Initializes the variable.
* @param var The variable to initialize.
* @param size Size of the variable in bytes
*/
void (*init)(dtype* var, DTYPE_SIZE size);
/**
* @brief Prints the current error even if there is not an error.
* @returns The ErrorCode of current error
*/
enum DTYPES_ERR (*get_error)(void);
/**
* @brief Returns the usable size of variable..
* @param var The varible to get size of.
* @returns The usable size of given variable.
*/
DTYPE_SIZE (*get_size)(dtype* var);
/**
* @brief Returns the current `typecode` of the variable..
* @param var The variable to get `typecode` of.
* @returns The typecode of given variable.
*/
enum DTYPES_TYPES (*get_type)(dtype* var);
/**
* @brief Returns the current `type` of variable..
* @param var The variable to get type from.
* @returns The `type` of variable in readable string.
*/
const char* (*get_str_type)(dtype* var);
/**
* @brief Set the type of variable..
* @param var The variable to set the type..
* @param type the typecode to set.
*/
void (*set_type)(dtype* var, enum DTYPES_TYPES); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
/**
* @brief Set the content of variable to none..
* @param var The variable to set to.
*/
void (*set_none)(dtype* var);
/**
* @brief Set the content of variable to given boolean value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_bool)(dtype* var, bool value);
/**
* @brief Set the content of variable to given short value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_short)(dtype* var, short value);
/**
* @brief Set the content of variable to given unsigned short value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_ushort)(dtype* var, unsigned short value);
/**
* @brief Set the content of variable to given integer value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_int)(dtype* var, int value);
/**
* @brief Set the content of variable to given unsigned integer value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_uint)(dtype* var, unsigned int value); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
/**
* @brief Set the content of variable to given long integer value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_long)(dtype* var, long value);
/**
* @brief Set the content of variable to given unsigned long integer value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_ulong)(dtype* var, unsigned long value);
/**
* @brief Set the content of variable to given float value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_float)(dtype* var, float value);
/**
* @brief Set the content of variable to given double value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_double)(dtype* var, double value);
/**
* @brief Set the content of variable to given character value..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_char)(dtype* var, char value);
/**
* @brief Set the content of variable to given string..
* @param var The variable to set to..
* @param value The value to set to.
*/
void (*set_str)(dtype* var, char * value);
/**
* @brief Copy the contents of the object into the variable..
* @param var The variable to copy to..
* @param obj The void pointer of object to copy from..
* @param size The size of the object.
*/
void (*set_object)(dtype* var, void * obj, DTYPE_SIZE size); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
/**
* @brief Get the content of variable as boolean.
* @param var The variable to get from
*/
bool (*get_bool)(dtype* var);
/**
* @brief Get the content of variable as short.
* @param var The variable to get from
*/
short (*get_short)(dtype* var);
/**
* @brief Get the content of variable as unsigned short.
* @param var The variable to get from
*/
unsigned short (*get_ushort)(dtype* var);
/**
* @brief Get the content of variable as integer.
* @param var The variable to get from
*/
int (*get_int)(dtype* var);
/**
* @brief Get the content of variable as unsigned integer.
* @param var The variable to get from
*/
unsigned int (*get_uint)(dtype* var);
/**
* @brief Get the content of variable as long integer.
* @param var The variable to get from
*/
long (*get_long)(dtype* var);
/**
* @brief Get the content of variable as unsigned long integer.
* @param var The variable to get from
*/
unsigned long (*get_ulong)(dtype* var);
/**
* @brief Get the content of variable as float.
* @param var The variable to get from
*/
float (*get_float)(dtype* var);
/**
* @brief Get the content of variable as double.
* @param var The variable to get from
*/
double (*get_double)(dtype* var);
/**
* @brief Get the content of variable as character.
* @param var The variable to get from
*/
char (*get_char)(dtype* var);
/**
* @brief Get the content of variable as string (char *).
* @param var The variable to get from
*/
char * (*get_str)(dtype* var);
/**
* @brief Get the content of variable as object [ void pointer ].
* @param var The variable to get from
*/
void * (*get_object)(dtype* var); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
/**
* @brief Get the direct pointer of variable as bool *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to bool.
* @param var The variable to get pointer from.
*/
bool* (*in_bool)(dtype* var);
/**
* @brief Get the direct pointer of variable as short *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to short.
* @param var The variable to get pointer from.
*/
short* (*in_short)(dtype* var);
/**
* @brief Get the direct pointer of variable as unsigned short *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to unsigned short.
* @param var The variable to get pointer from.
*/
unsigned short* (*in_ushort)(dtype* var);
/**
* @brief Get the direct pointer of variable as int *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to integer.
* @param var The variable to get pointer from.
*/
int* (*in_int)(dtype* var);
/**
* @brief Get the direct pointer of variable as unsigned int *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to unsigned int.
* @param var The variable to get pointer from.
*/
unsigned int* (*in_uint)(dtype* var);
/**
* @brief Get the direct pointer of variable as long *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to long.
* @param var The variable to get pointer from.
*/
long* (*in_long)(dtype* var);
/**
* @brief Get the direct pointer of variable as unsigned long *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to unsigned long. | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
* @brief Also sets the current type to unsigned long.
* @param var The variable to get pointer from.
*/
unsigned long* (*in_ulong)(dtype* var);
/**
* @brief Get the direct pointer of variable as float *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to float.
* @param var The variable to get pointer from.
*/
float* (*in_float)(dtype* var);
/**
* @brief Get the direct pointer of variable as double *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to double.
* @param var The variable to get pointer from.
*/
double* (*in_double)(dtype* var);
/**
* @brief Get the direct pointer of variable as char *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to char.
* @param var The variable to get pointer from.
*/
char* (*in_char)(dtype* var);
/**
* @brief Get the direct pointer of variable as char *
* @brief to directly set the value / use in functions like scanf().
* @brief Also sets the current type to string.
* @param var The variable to get pointer from.
*/
char* (*in_str)(dtype* var); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
enum DTYPES_TYPES (*print)(dtype* var);
} __dtypes_struct;
__dtypes_struct dtypes;
#endif
/**
* @file dtype.c
*
* @brief contains the actual code for definition in dtype.h
*/
#include "dtype.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/// @brief Current Errorcode
enum DTYPES_ERR DTYPE_CURRENT_ERRCODE = DTYPE_NO_ERR;
/// @brief The function in which current error occured.
const char* DTYPE_CURRENT_ERRFUNC = "none";
/// @brief Current Error description.
const char* DTYPE_CURRENT_ERRDESC = "none";
// function that prints current error and returns the errcode
enum DTYPES_ERR get_error ( void )
{
// print out error
printf ("\n---------- Dtype Error ----------\n");
printf ("in function %s, errcode: %d :\n\tinfo: %s\n",
DTYPE_CURRENT_ERRFUNC, DTYPE_CURRENT_ERRCODE, DTYPE_CURRENT_ERRDESC
);
// store the current errorcode to later return
enum DTYPES_ERR ErrCode = DTYPE_CURRENT_ERRCODE;
// set the current error to null as we have printed it!
DTYPE_CURRENT_ERRFUNC = "none";
DTYPE_CURRENT_ERRCODE = DTYPE_NO_ERR;
DTYPE_CURRENT_ERRDESC = "none";
// return the errcode
return ErrCode;
}
// function that sets error as given.
void set_error ( enum DTYPES_ERR errcode, const char* fname, const char* desc )
{
// set the error
DTYPE_CURRENT_ERRCODE = errcode;
DTYPE_CURRENT_ERRFUNC = fname;
DTYPE_CURRENT_ERRDESC = desc;
// print the error via get_error () if DTYPE_ERROR_OUT is true
if ( DTYPE_ERROR_OUT)
{
get_error ();
// exit if DTYPE_EXIT_ON_ERR is true!
if ( DTYPE_EXIT_ON_ERR ) {
exit (1);
}
}
}
// set_type of the variable as provided.
void set_type ( dtype * var, enum DTYPES_TYPES type )
{
var[0] = ( char ) type;
}
// set the size of the variable as provided
void set_size ( dtype * var, DTYPE_SIZE size )
{
*( (DTYPE_SIZE*) (var+1) ) = size;
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// get_type of the variable
enum DTYPES_TYPES get_type ( dtype * var )
{
return var[0];
}
// get_type of the the variable but in a readable format, not in typecode.
const char* get_stype ( dtype * var )
{
// self-explanatory.
switch ( get_type ( var ) )
{
case DTYPE_NONE:
return "none ( null value )";
case DTYPE_BOOL:
return "bool";
case DTYPE_SHORT:
return "short";
case DTYPE_USHORT:
return "unsigned short";
case DTYPE_INT:
return "int";
case DTYPE_UINT:
return "unsigned int";
case DTYPE_LONG:
return "long";
case DTYPE_ULONG:
return "unsigned long";
case DTYPE_FLOAT:
return "float";
case DTYPE_DOUBLE:
return "double";
case DTYPE_CHAR:
return "char";
case DTYPE_STR:
return "string ( char *)";
case DTYPE_OBJECT:
return "object ( custom )";
case DTYPE_UNKNOWN:
return "unknown";
default:
return "invalid ( not initialized )";
}
}
// get usable size of the the variable
DTYPE_SIZE get_size ( dtype * var )
{
return *( (DTYPE_SIZE*) (var+1));
}
// initialization of the variable
// this basically sets the type to DTYPE_NONE and sets the size as provided
// also has a check that size must be greater than or equal to 4.
void dt_init ( dtype * var, DTYPE_SIZE size )
{
if ( size < 4) {
set_error (DTYPE_SIZE_LOW, "init", "Size too low, < 4");
}
// store the type
set_type ( var, DTYPE_NONE);
// store the size
set_size ( var, size-DTYPE_MIN_MEM);
}
// clear the data inside the variable
void dt_clear ( dtype * var ) {
// for old c support!
DTYPE_SIZE i;
for ( i = DTYPE_MIN_MEM; i < DTYPE_MIN_MEM + get_size(var); ++i )
{
var[i] = '\0';
}
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// internal set_object function used for setting the variable's value
bool _dtset_obj ( dtype * var, void *obj, DTYPE_SIZE size )
{
// check for initialization
if ( get_type ( var ) == DTYPE_INVALID || get_type ( var ) > DTYPE_UNKNOWN) {
set_error (
DTYPE_NOT_INIT, "internal set_object()",
"trying to set to non-initialized variable!"
);
// indicating error
return true;
}
// clear previous value before storing
dt_clear ( var );
// if the size to store is greater than
if ( size > get_size ( var ) )
{
// not enough room to store!
// indicating error!
return true;
}
// for old c support
int i;
// hardcopy every byte till given size
for ( i = 0; i < size; ++i )
{
var[i+DTYPE_MIN_MEM] = ( ( char*) obj )[i];
}
// no error
return false;
}
void dtset_none ( dtype * var )
{
// clear the data
dt_clear ( var );
// set type to none
set_type ( var, DTYPE_NONE);
}
// set function for boolean value
void dtset_bool ( dtype * var, bool value )
{
bool val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( bool ) ) ) {
set_type ( var, DTYPE_BOOL);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_bool", "the variable size is too low to store bool !");
return;
}
// set function for short value
void dtset_short ( dtype * var, short value )
{
short val = value;
// use internal set obj to set data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( short ) ) ) {
set_type ( var, DTYPE_SHORT);
return;
}
//set the error
set_error (DTYPE_SIZE_HIGH, "set_short", "the variable size is too low to store short !");
return;
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// set function for unsigned short value
void dtset_ushort ( dtype * var, unsigned short value )
{
unsigned short val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( unsigned short ) ) ) {
set_type ( var, DTYPE_USHORT);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_ushort", "the variable size is too low to store unsigned short !");
return;
}
// set function for int value
void dtset_int ( dtype * var, int value )
{
int val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( int ) ) ) {
set_type ( var, DTYPE_INT);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_int", "the variable size is too low to store int !");
return;
}
// set function for unsigned int
void dtset_uint ( dtype * var, unsigned int value )
{
unsigned int val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( unsigned int ) ) ) {
set_type ( var, DTYPE_UINT);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_uint", "the variable size is too low to store unsigned int !");
return;
}
// set function for long value
void dtset_long ( dtype * var, long value )
{
long val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( long ) ) ) {
set_type ( var, DTYPE_LONG);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_long", "the variable size is too low to store long !");
return;
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// set function for unsigned long
void dtset_ulong ( dtype * var, unsigned long value )
{
unsigned long val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( unsigned long ) ) ) {
set_type ( var, DTYPE_ULONG);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_ulong", "the variable size is too low to store unsigned long !");
return;
}
// set function for float
void dtset_float ( dtype * var, float value )
{
float val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( float ) ) ) {
set_type ( var, DTYPE_FLOAT);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_float", "the variable size is too low to store float !");
return;
}
// set function for double
void dtset_double ( dtype * var, double value )
{
double val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( double ) ) ) {
set_type ( var, DTYPE_DOUBLE);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_double", "the variable size is too low to store double !");
return;
}
// set function for char
void dtset_char ( dtype * var, char value )
{
char val = value;
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var, &val, sizeof ( char ) ) ) {
set_type ( var, DTYPE_CHAR);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_char", "the variable size is too low to store char !");
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// set function for strings ( char *)
void dtset_str ( dtype * var, char* value )
{
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var,value,strlen ( value ) +1) ) {
set_type ( var, DTYPE_STR);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_str", "the variable size is too low to store string !");
}
// set function for custom objects / custom type variables
void dtset_obj ( dtype * var, void* obj, DTYPE_SIZE size )
{
// use internal set_object function to set the dtype data to value
// if error is not indicated, set the type and return
if ( !_dtset_obj ( var,obj,size ) ) {
set_type ( var, DTYPE_OBJECT);
return;
}
// set the error
set_error (DTYPE_SIZE_HIGH, "set_obj", "the variable size is too low to store the object !");
}
// ------- dtget_type(dtype) : returns the value as type, printing warning if needed ------
// get function to get boolean value
bool dtget_bool ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_BOOL && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `bool` from another type: `%s` ]\n",get_stype ( var ) );
}
// return the value as a boolean
return *( ( bool*) ( var + DTYPE_MIN_MEM) );
}
// get function to get short value
short dtget_short ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_SHORT && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `short` from another type: `%s` ]\n",get_stype ( var ) );
}
// return the value as short
return *( ( short*) ( var + DTYPE_MIN_MEM) );
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// get function to get unsigned short value
unsigned short dtget_ushort ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_USHORT && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `unsigned short` from another type: `%s` ]\n",get_stype ( var ) );
}
// return the value as unsigned short
return *( ( unsigned short *) ( var + DTYPE_MIN_MEM) );
}
// get function to get int
int dtget_int ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_INT && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `int` from another type: `%s` ]\n",get_stype ( var ) );
}
// return the value as int
return *( ( int*) ( var + DTYPE_MIN_MEM) );
}
// get function to get unsigned int
unsigned int dtget_uint ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_UINT && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `unsigned int` from another type: `%s` ]\n",get_stype ( var ) );
}
// return the value as unsigned int
return *( ( unsigned int*) ( var + DTYPE_MIN_MEM) );
}
// get function to get long
long dtget_long ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_LONG && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `long` from another type: `%s` ]\n", get_stype ( var ) );
}
// return the value as long
return *( ( long*) ( var + DTYPE_MIN_MEM) );
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// get function to get unsigned long
unsigned long dtget_ulong ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_ULONG && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `unsigned long` from another type: `%s` ]\n", get_stype ( var ) );
}
// return the value as unsigned long
return *( ( unsigned long*) ( var + DTYPE_MIN_MEM) );
}
// get function to get float
float dtget_float ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_FLOAT && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `float` from another type: `%s` ]\n", get_stype ( var ) );
}
// return the value as float
return *( ( float*) ( var + DTYPE_MIN_MEM) );
}
// get function to get double
double dtget_double ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_DOUBLE && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `double` from another type: `%s` ]\n", get_stype ( var ) );
}
// return the value as double
return *( ( double*) ( var + DTYPE_MIN_MEM) );
}
// get function to get char
char dtget_char ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_CHAR && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `char` from another type: `%s` ]\n", get_stype ( var ) );
}
// return value as char
return *( ( var + DTYPE_MIN_MEM) );
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// get function to get string ( char *)
char * dtget_str ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_STR && DTYPE_WARN_OUT ) {
printf ("\n[ Dtype warn: getting `string` from another type: `%s` ]\n", get_stype ( var ) );
}
// return value as string ( char *)
return ( ( var + DTYPE_MIN_MEM) );
}
// get function to get void pointer of custom object ( void *)
void* dtget_object ( dtype * var )
{
// type check, if failed and DTYPE_WARN_OUT is set,
// print the warning, that we are trying to get it from another type!
if ( get_type ( var )!=DTYPE_OBJECT && DTYPE_WARN_OUT ) {
printf (
"\n[ Dtype warn: getting `object ( custom )` from another type: `%s` ]\n",
get_stype ( var )
);
}
// return the value as void pointer that can be changed
// ( void *)
return ( void*) ( var + DTYPE_MIN_MEM);
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
//function to print the value & return it's type
enum DTYPES_TYPES dt_print ( dtype * var )
{
switch ( get_type ( var ) )
{
// switch cases according to the type
// print them as required as their types and return it's type!
case DTYPE_NONE:
printf ("None"); return DTYPE_NONE;
case DTYPE_BOOL:
printf ( dtget_bool ( var ) ? "true" : "false"); return DTYPE_BOOL;
case DTYPE_SHORT:
printf ("%i",dtget_short ( var ) ); return DTYPE_SHORT;
case DTYPE_USHORT:
printf ("%d",( int ) dtget_ushort ( var ) );
return DTYPE_USHORT;
case DTYPE_INT:
printf ("%d", dtget_int ( var ) ); return DTYPE_INT;
case DTYPE_UINT:
printf ("%u", dtget_uint ( var ) ); return DTYPE_UINT;
case DTYPE_LONG:
printf ("%ld", dtget_long ( var ) ); return DTYPE_LONG;
case DTYPE_ULONG:
printf ("%lu", dtget_ulong ( var ) ); return DTYPE_ULONG;
case DTYPE_FLOAT:
printf ("%f", dtget_float ( var ) ); return DTYPE_FLOAT;
case DTYPE_DOUBLE:
printf ("%lf", dtget_double ( var ) ); return DTYPE_DOUBLE;
case DTYPE_CHAR:
printf ("%c", dtget_char ( var ) ); return DTYPE_CHAR;
case DTYPE_STR:
printf ("%s", dtget_str ( var ) ); return DTYPE_STR;
case DTYPE_OBJECT:
printf ("( custom object at %p )", (void*) var); return DTYPE_OBJECT;
case DTYPE_UNKNOWN:
printf ("unknown value"); return DTYPE_UNKNOWN;
default:
printf ("Invalid ( not initialized )"); return DTYPE_INVALID;
}
}
// -- dtin_type(dtype*) : returns the pointer to the data as type* and sets current type to type --
bool * dtin_bool ( dtype * var )
{
// set the type & send the pointer as ( bool * )
set_type ( var, DTYPE_BOOL);
return ( bool *) ( var + DTYPE_MIN_MEM);
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
short * dtin_short ( dtype * var )
{
// set the type & send the pointer as ( short * )
set_type ( var, DTYPE_SHORT);
return ( short *) ( var + DTYPE_MIN_MEM);
}
unsigned short * dtin_ushort ( dtype * var )
{
// set the type & send the pointer as ( unsigned short * )
set_type ( var, DTYPE_USHORT);
return ( unsigned short *) ( var + DTYPE_MIN_MEM);
}
int * dtin_int ( dtype * var )
{
// set the type & send the pointer as ( int * )
set_type ( var, DTYPE_INT);
return ( int*) ( var + DTYPE_MIN_MEM);
}
unsigned int * dtin_uint ( dtype * var )
{
// set the type & send the pointer as ( unsigned int * )
set_type ( var, DTYPE_UINT);
return ( unsigned int *) ( var + DTYPE_MIN_MEM);
}
long * dtin_long ( dtype * var )
{
// set the type & send the pointer as ( long * )
set_type ( var, DTYPE_LONG);
return ( long *) ( var + DTYPE_MIN_MEM);
}
unsigned long * dtin_ulong ( dtype * var )
{
// set the type & send the pointer as ( unsigned long * )
set_type ( var, DTYPE_ULONG);
return ( unsigned long *) ( var + DTYPE_MIN_MEM);
}
float * dtin_float ( dtype * var )
{
// set the type & send the pointer as ( float * )
set_type ( var, DTYPE_FLOAT);
return ( float *) ( var + DTYPE_MIN_MEM);
}
double * dtin_double ( dtype * var )
{
// set the type & send the pointer as ( double * )
set_type ( var, DTYPE_DOUBLE);
return ( double *) ( var + DTYPE_MIN_MEM);
}
char * dtin_char ( dtype * var )
{
// set the type & send the pointer as ( char * )
set_type ( var, DTYPE_CHAR);
return ( char *) ( var + DTYPE_MIN_MEM);
}
char * dtin_str ( dtype * var )
{
// set the type & send the pointer as ( char * )
set_type ( var, DTYPE_STR);
return ( char *) ( var + DTYPE_MIN_MEM);
}
// pack everything into dtypes
__dtypes_struct dtypes = {
// basic functions
dt_init, get_error, get_size, get_type, get_stype, set_type, | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// set functions
dtset_none, dtset_bool, dtset_short, dtset_ushort, dtset_int, dtset_uint, dtset_long, dtset_ulong,
dtset_float, dtset_double, dtset_char, dtset_str, dtset_obj,
// get functions
dtget_bool, dtget_short, dtget_ushort, dtget_int, dtget_uint, dtget_long, dtget_ulong, dtget_float,
dtget_double, dtget_char, dtget_str, dtget_object,
// in functions
dtin_bool, dtin_short, dtin_ushort, dtin_int, dtin_uint, dtin_long, dtin_ulong, dtin_float,
dtin_double, dtin_char, dtin_str,
// printing function
dt_print
};
Basic usage example :-
#include "dtype.h"
#include <stdio.h>
int main(void)
{
/*
Note :- printf("%d", dtypes.print(var)) kind of printing causes the variable to
be printed first, and then display the typecode of variable.
*/
// dtype var of 20 bytes
dtype var[20];
// initialize it with 20 bytes! [ it won't use more than size_of_bytes given in init ]
dtypes.init(var, 20);
// Example's of setting value!
// set_str set's the data of var to the string provided
dtypes.set_str(var, "Hello World!\n");
// dtypes.print() prints the content, and returns the typecode of that var!
// get_str_type returns the type in readable format than typecode
printf("Typecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
// store a boolean & print value
// set_bool set's data of the var to the boolean provided
dtypes.set_bool(var, 1);
printf("Value in boolean 1 : ");
dtypes.print(var); // true
printf("\n");
dtypes.set_bool(var, 0); // false
printf("Value in boolean 0 : ");
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
// store an int & print value
// set_int set's the data of var to the int provided
dtypes.set_int(var, -9856);
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var)); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
// set_uint set's the data of var to unsigned int provided
// let's try setting it to negative to see if it unsigned or not
dtypes.set_uint(var, -9856);
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
// copying from dtypes to other types!
unsigned int copied = dtypes.get_uint(var);
printf("copied from dtypes.get_uint value: %u\n", copied);
// copying from dtypes type mismatch, causes a warning to appear :) but copies it anyway
// type mismatch here is that we are trying to get integer value but stored value is of type unsigned int
int trytocopy = dtypes.get_int(var);
printf("tried to copy int from unsigned int stored in var, warning should be above ^^ ");
printf("\ntrytocopy value: %d!\n\n", trytocopy);
// to clear the variable
dtypes.set_none(var);
printf("After setting it to none, value: ");
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
return 0;
}
Basic usage example : with scanf()
#include <stdio.h>
#include "dtype.h"
void scan_err(int scanf_output, dtype * var)
{
if(!scanf_output) {
printf("\n--- Invalid input or EOF ---\n");
// clear variable if input error
dtypes.set_none(var);
}
}
int main()
{
// dtype var of 20 bytes
dtype var[20];
// initialization
dtypes.init(var, 20);
printf("Enter integer: ");
// in_int returns an integer pointer to store/access value directly
scan_err(scanf("%d", dtypes.in_int(var)), var);
printf("Value: ");
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
printf("Enter string: ");
scan_err(scanf("%s", dtypes.in_str(var)), var);
printf("Value: ");
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var)); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
printf("Enter unsigned long value: ");
scan_err(scanf("%lu", dtypes.in_ulong(var)), var);
printf("Value: ");
printf("\nTypecode: %d, Type: %s\n\n", dtypes.print(var), dtypes.get_str_type(var));
return 0;
}
I will be more than happy to receive suggestions, feedback, bugs and overall code review for this project.
Answer: Consider whether you should
C is not really suited for having dynamic types, and attempts to add such features very often fail in some way. There are other languages that are more suitable, and for example C++'s std::any is a way to get a safe dynamic type.
However, C does have unions, which provide you with most of the "advantages over normal types" you mention, the exception being that it doesn't actually keep track of what type is actually currently stored inside a union variable. But you can add another variable to track that.
Below I'll point out some issues your implementation has.
Safety issues
Your implementation of a dynamic type makes it easy to make mistakes. Consider your own example of how to use it:
dtype var[20];
dtypes.init(var, 20);
You have to ensure you use the same number for both the array declaration and the call to dtypes.init(). It would be much better if you only needed to specify the size once.
But it's also confusing to have to create an array in the first place, of type char even. Now you can pass var to everything that accepts a char *, and the compiler will happily allow it. It would be much nicer if dtype was implemented in such a way that you would write:
dtype var;
dtypes.init(var, 20); | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
And where dtype would actually be a struct.
Only one custom object type is supported
There's only one DTYPE_OBJECT, and it allows the user to store anything as long as it fits. What if the user has multiple custom types, and wants to store them in your dynamic type, and still be able to check which type exactly was stored in a dtype object?
Unaligned memory access
Not all CPU architectures allow unaligned access. When you store the size of a type in the second and third bytes, it's almost certain that you violate alignment restrictions. While it may work on Intel and AMD architectures, it is actually undefined behavior in C, and you code might crash on other architectures.
This is another strong argument to make dtype a proper struct, as then you can have a uint16_t size member that the compiler will properly align for you. But if you want to keep things the way they are now, use memcpy() to copy the bytes in the dtype to and from a local variable, for example:
DTYPE_SIZE get_size(const dtype *var)
{
DTYPE_SIZE size;
memcpy(&size, var + DTYPE_SIZE_LOW, sizeof size);
return size;
}
Don't worry about the call to memcpy(); the compiler will optimize that away. Alternatively, you can manually split/recombine a number into bytes:
DTYPE_SIZE get_size(const dtype *var)
{
const uint8_t *size_bytes = (const uint8_t *)(var + DTYPE_SIZE_LOW);
return size_bytes[0] | (size_bytes[1] << 8);
} | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, variant-type
Don't create a struct with member functions in C
Instead of creating a struct __dtypes_struct which allows you to write things like dtypes.init(), just write normal free functions, and prefix them all with dtypes_. This way, you can write dtypes_init(), which is the same number of characters, but avoids the indirection.
Also, if you want to write code like it's C++, then just use C++ instead.
Don't mix error codes with other constants
It's very weird to see constants like DTYPE_SIZE_LOW, DTYPE_SIZE_HIGH and DTYPE_MIN_MEM inside enum DTYPES_ERR. Don't mix unrelated things in a single enum. Either write:
static const int DTYPE_SIZE_LOW = 1;
static const int DTYPE_SIZE_HIGH = 2;
static const int DTYPE_MIN_MEM = 3;
Or put them in a separate (possibly anonymous) enum:
enum {
DTYPE_SIZE_LOW = 1,
DTYPE_SIZE_HIGH = 2,
DTYPE_MIN_MEM = 3,
};
Use const where appropriate
The getters don't need to modify the variable, so they should all take a const pointer to dtype. | {
"domain": "codereview.stackexchange",
"id": 43960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, variant-type",
"url": null
} |
c, programming-challenge, time-limit-exceeded
Title: HackerEarth challenge: Lunch boxes
Question: I was solving the lunch boxes problem on HackerEarth but as I submitted my solution most of the test cases were passed and the rest showed 'Time Limit Exceeded'. I would be very grateful if you could help me improve the algorithm of my code to reduce the runtime.
Following is the Problem
Alice works as a restaurant manager. The restaurant has prepared 'N' lunch boxes and Alice plans to distribute them to some schools. Consider that there are 'M' schools and an \$i^{th}\$ school orders \$A_i\$ lunch boxes.
She wants to distribute lunch boxes to as many schools as possible. Also, she has the following rule:
For an \$i^{th}\$ school, she gives either zero or \$A_i\$ lunch boxes
Your task is to help Alice to determine the maximum number of schools that can get lunch boxes.
Input format
The first contains an integer \$t\$ that denotes the number of test cases in the input.
Each test case consists of two lines:
The first line contains two integers \$N\$ and \$M\$.
The second line contains integers \$A_1, A_2, ..., A_m\$.
Constraints
\$ 1 \le t \le 10 \$
\$ 1 \le N, M \le 10^5 \$
\$ 1 \le A_i \le 10^6 \$
My code
#include<stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--){
int n,m;
scanf("%d", &n);
scanf("%d", &m);
int a[m];
for(int i=0; i<m; i++){
scanf("%d", &a[i]);
}
for(int i=0; i<m; i++){
for(int j=i + 1; j<m; j++){
if(a[i] > a[j]){
int temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
int sum=0, count=0;
for(int i=0; i<m; i++){
sum=sum+a[i];
if(sum>n){
break;
}
else if(sum<=n)
count++;
}
printf("%d\n", count);
}
} | {
"domain": "codereview.stackexchange",
"id": 43961,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, time-limit-exceeded",
"url": null
} |
c, programming-challenge, time-limit-exceeded
Answer: Use a better sorting algorithm
I think the main reason why you get a time limit exceeded error is because you are using an \$O(M^2)\$ algorithm to sort the orders. This is going to get slow very quickly for large values of \$M\$. While you could try to implement a better sorting algorithm yourself, use qsort() instead.
Use more meaningful variable names
You are using a lot of one-character variable names: t, n, m, a. It's very hard to understand what those variables mean without having to follow the whole code. If you are going to use the same names as used in the problem statement, or for example if you are implementing some algorithm or mathematical formula from a paper, make sure you use exactly the same names as the problem (so in this case, capital N, M and A), and add a comment to the code linking to the problem/paper/etc. where those things are described.
Alternatively, you could give them more meaningful names yourself:
t -> num_testcases
n -> num_lunchboxes
m -> num_schools
a[] -> order_sizes[]
The exception is for variables like i and j. These are very commonly used as iteration counters, so it's not going to be confusing for most programmers.
Unnecessary else if
Don't add an if after an else if the condition is just the inverse of the first if. This will do just fine:
if (sum > n) {
break;
} else {
count++;
}
Avoiding having to repeat the condition ensures there is less change of mistakes. Also, you don't even need the else part in this code, you can just write:
if (sum > n) {
break;
}
count++; | {
"domain": "codereview.stackexchange",
"id": 43961,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge, time-limit-exceeded",
"url": null
} |
c#, generics, unity3d, interpolation
Title: Generic Interpolation for many types in C#
Question: I made a generic interpolator for Unity objects, but the way it functions makes me question if there's a better way to approach this problem.
I want the logic inside of the Tween<T> function to be the same for every type. I don't want to create many overrides for unique types because that would cause a lot of pointless code duplication.
The biggest "code smell" I can see is in the LerpFunction<T> where I am switching based on the type, and also casting things back and forth like a madman. Is there a better pattern which lets me accomplish what I am trying to do?
public class Tweener
{
public static IEnumerator Tween<T>(T startValue, T endValue, float duration, Action<T> setter)
{
var startTime = Time.time;
setter(startValue);
while (Time.time - startTime < duration)
{
var t = (Time.time - startTime) / duration;
t = Mathf.Clamp(t, 0f, 1f);
var currentValue = LerpFunction(startValue, endValue, t);
setter(currentValue);
yield return null;
}
setter(endValue);
}
private static T LerpFunction<T>(T a, T b, float t)
{
return a switch
{
float => (T)(object)Mathf.Lerp((float)(object)a, (float)(object)b, t),
Vector3 => (T)(object)Vector3.Lerp((Vector3)(object)a, (Vector3)(object)b, t),
Quaternion => (T)(object)Quaternion.Slerp((Quaternion)(object)a, (Quaternion)(object)b, t),
Color => (T)(object)Color.Lerp((Color)(object)a, (Color)(object)b, t),
_ => throw new NotImplementedException($"Cannot interpolate function of type {typeof(T)}")
};
}
}
Answer: Let's refactor it in 3 simple steps
Step 1: Use type pattern matching and when
We can use the type pattern matching capability of switch expression
By specifying names (lhs and rhs) the casting will be done | {
"domain": "codereview.stackexchange",
"id": 43962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, generics, unity3d, interpolation",
"url": null
} |
c#, generics, unity3d, interpolation
automatically for lhs
and semi-automatically for rhs
private static T LerpFunction<T>(T a, T b, float t)
=> a switch
{
float lhs when b is float rhs => (T)(object)Math.Lerp(lhs, rhs, t),
Vector3 lhs when b is Vector3 rhs => (T)(object)Vector3.Lerp(lhs, rhs, t),
Quaternion lhs when b is Quaternion rhs => (T)(object)Quaternion.Slerp(lhs, rhs, t),
Color lhs when b is Color rhs => (T)(object)Color.Lerp(lhs, rhs, t),
_ => throw new NotImplementedException($"Cannot interpolate function of type {typeof(T)}")
};
Step 2: Use ValueTuple
We can branch based on multiple variables by putting them into a ValueTuple
private static T LerpFunction<T>(T a, T b, float t)
=> (a, b) switch
{
(float lhs, float rhs) => (T)(object)Math.Lerp(lhs, rhs, t),
(Vector3 lhs, Vector3 rhs) => (T)(object)Vector3.Lerp(lhs, rhs, t),
(Quaternion lhs, Quaternion rhs) => (T)(object)Quaternion.Slerp(lhs, rhs, t),
(Color lhs, Color rhs) => (T)(object)Color.Lerp(lhs, rhs, t),
_ => throw new NotImplementedException($"Cannot interpolate function of type {typeof(T)}")
};
Step 3: Restrict T to struct
If you could restrict T is a struct then you could get rid of the (T)(object) castings as well
private static T LerpFunction<T>(T a, T b, float t) where T: struct
=> (a, b) switch
{
(float lhs, float rhs) => Math.Lerp(lhs, rhs, t),
(Vector3 lhs, Vector3 rhs) => Vector3.Lerp(lhs, rhs, t),
(Quaternion lhs, Quaternion rhs) => Quaternion.Slerp(lhs, rhs, t),
(Color lhs, Color rhs) => Color.Lerp(lhs, rhs, t),
_ => throw new NotImplementedException($"Cannot interpolate function of type {typeof(T)}")
};
Final though: I would suggest to prefer NotSupportedException rather than NotImplementedException, because the latter is misleading. If someone calls it with doubles at the first time, then (s)he won't call the method again since it it not implemented. | {
"domain": "codereview.stackexchange",
"id": 43962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, generics, unity3d, interpolation",
"url": null
} |
python, beginner, opencv
Title: polarimetric imager in python
Question: My code takes 3 images taken with a polarising filter rotated 45° between them and transform them into a single image encoding the polarization parameters as HSV. what can be improved?
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from IPython.display import Image
%matplotlib inline
import glob
import math
imagefiles=glob.glob(r"C:\Users\HP\My Python stuff\openCV\Polarization\IMG*")
imagefiles.sort()
images=[]
for filename in imagefiles:
img=cv2.imread(filename)
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
images.append(img)
num_images=len(images)
pixel0x,pixel0y,pixel0z=cv2.split(images[0])
pixel45x,pixel45y,pixel45z=cv2.split(images[1])
pixel90x,pixel90y,pixel90z=cv2.split(images[2])
i0 = pixel0x * 0.3 + pixel0y * 0.59 + pixel0z * 0.11
i45 = pixel45x * 0.3 + pixel45y * 0.59 + pixel45z * 0.11
i90 = pixel90x * 0.3 + pixel90y * 0.59 + pixel90z * 0.11
stokesI = i0 + i90
stokesQ = i0 - i90
stokesU = (np.ones(stokesI.shape)*(2.0 * i45))- stokesI
polint = np.sqrt(stokesQ*stokesQ+stokesU*stokesU)
poldolp = polint/(stokesI+((np.ones(stokesI.shape)*0.001)))
polaop = 0.5 * np.arctan(stokesU, stokesQ)
h=(polaop+(np.ones(polaop.shape)*(3.1416/2.0)))/3.1416
s=poldolp
v=polint
hsvpolar=cv2.merge((h,s,v))
hsvpolar=np.multiply(hsvpolar, 255)
rgbimg = cv2.cvtColor(np.clip(hsvpolar, 0,255).astype('uint8'),cv2.COLOR_HSV2RGB)
plt.imshow(rgbimg)
cv2.imwrite("hsvpolarized.jpg",rgbimg)
these are the input images: | {
"domain": "codereview.stackexchange",
"id": 43963,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, opencv",
"url": null
} |
python, beginner, opencv
these are the input images:
Answer: Not great use of Numpy - for instance, rather than writing your coefficients out in triplicate, this needs to be a single tensor dot product. ones() is never called for in this program if you correctly use broadcasting.
Put your code in functions.
Don't hard-code system-specific file paths.
Prefer pathlib over os, for glob etc.
Don't write a (truncated) literal for pi; instead write np.pi.
Most importantly, your results are basically nonsense because the images don't only change polarisation - they change alignment. You need to apply a matching, homography and perspective de-warp to your images for this to make any sense, and OpenCV offers these to you out of the box. The demonstration code below follows https://docs.opencv.org/4.6.0/d1/de0/tutorial_py_feature_homography.html .
Suggested
from pathlib import Path
from typing import Iterable
import cv2
import matplotlib.pyplot as plt
import numpy as np
def warp_align(images: list[np.ndarray]) -> None:
sift = cv2.SIFT_create()
keys: list[tuple] = []
descriptors: list[np.ndarray] = []
for image in images:
key, descriptor = sift.detectAndCompute(image, mask=None)
keys.append(key)
descriptors.append(descriptor)
FLANN_INDEX_KDTREE = 1
flann = cv2.FlannBasedMatcher(
indexParams={'algorithm': FLANN_INDEX_KDTREE, 'trees': 5},
searchParams={'checks': 50},
)
LOWES_RATIO = 0.7
train_desc, *query_descs = descriptors
matches = [
[
m
for m, n in flann.knnMatch(query_desc, train_desc, k=2)
if m.distance < LOWES_RATIO*n.distance
]
for query_desc in query_descs
]
def keys_to_points(matched_keys: Iterable[tuple[float, float]]) -> np.ndarray:
return np.array(tuple(matched_keys), dtype=np.float32) | {
"domain": "codereview.stackexchange",
"id": 43963,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, opencv",
"url": null
} |
python, beginner, opencv
train_key, *query_keys = keys
for query_key, target_matches, image in zip(query_keys, matches, images[1:]):
query_points = keys_to_points(query_key[m.queryIdx].pt for m in target_matches)
train_points = keys_to_points(train_key[m.trainIdx].pt for m in target_matches)
M, mask = cv2.findHomography(query_points, train_points, method=cv2.RANSAC, ransacReprojThreshold=5)
print(M, '\n')
cv2.warpPerspective(src=image, dst=image, M=M, dsize=image.shape[1::-1])
def calculate_polarimetry(images: list[np.ndarray]) -> np.ndarray:
all_images = np.stack(images)
coefficients = np.array((0.30, 0.59, 0.11))
i00, i45, i90 = np.tensordot(all_images, coefficients, axes=[3, 0])
stokes_i = i00 + i90
stokes_q = i00 - i90
stokes_u = 2*i45 - stokes_i
polint = np.sqrt(stokes_q*stokes_q + stokes_u*stokes_u)
poldolp = polint/(stokes_i + 0.001)
polaop = 0.5 * np.arctan(stokes_u, stokes_q)
h = polaop/np.pi + 0.5
s = poldolp
v = polint
hsv_polar = 255*np.clip(cv2.merge((h, s, v)), 0, 1)
return cv2.cvtColor(hsv_polar.astype('uint8'), cv2.COLOR_HSV2RGB)
def main() -> None:
paths = sorted(Path.cwd().glob("pol*.png"))
images = [
cv2.cvtColor(cv2.imread(str(path)), cv2.COLOR_BGR2RGB)
for path in paths
]
warp_align(images)
rgb_img = calculate_polarimetry(images)
fig, ((tl, tr), (bl, br)) = plt.subplots(nrows=2, ncols=2)
tl.imshow(images[0])
tr.imshow(images[1])
bl.imshow(images[2])
br.imshow(rgb_img)
plt.show()
# cv2.imwrite("hsvpolarized.jpg", rgbimg)
if __name__ == '__main__':
main()
Prior to homographic correction
After homographic correction | {
"domain": "codereview.stackexchange",
"id": 43963,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, opencv",
"url": null
} |
python, numpy, image, pygame
Title: pixelating images
Question: I'm a hobby programer and I had an idea for pixelating images and I wrote it.
I was wondering how would a better programer write the same function.
I want to learn and I think that this would help me a lot to see how code is supposed to be written. Also my code is quite slow and I would like to make it quicker.
I use PIL for image manipulation, pygame for window and numpy for math.
after this code I return img that is in PIL format and pass it to pygame with fromstring.
This code divides the image into blocks defined by pixSize and then takes RGB value from all the pixels in that block and finds median value with which then that block is colored and then it moves on to next block and and does the same.
Here is my code
def pixelateImage(self, img, pixSize):
print(img.size[1])
n = 0
ny = 0
blockInfo = []
for i in range(int(img.size[0]/pixSize)*int(img.size[1]/pixSize)):
if n+1 > int(img.size[0]/pixSize):
n = 0
ny += 1
xs = range(pixSize*n, pixSize*(n+1))
ys = range(pixSize*ny, pixSize*(ny+1))
RGB = []
for x in xs:
for y in ys:
cModeRGB = []
rgb = img.getpixel((x,y))
for i in rgb:
if i == 0:
cModeRGB.append(0)
continue
cMode = i / 255
cModeRGB.append(cMode)
RGB.append(cModeRGB)
RGBc = np.array(RGB)
RGB = []
for i in np.median(RGBc, axis=0):
RGB.append(int(i * 255)) | {
"domain": "codereview.stackexchange",
"id": 43964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, image, pygame",
"url": null
} |
python, numpy, image, pygame
rgbMid = (RGB[0], RGB[1], RGB[2])
for x in xs:
for y in ys:
img.putpixel((x,y), rgbMid)
n += 1
return img
Answer:
def pixelateImage(self, img, pixSize):
You are writing a class method, but the method has nothing to do with the class. Make it a free function. I know a lot of people swear by OOP (as opposed to swear at it, like I do), but the only difference for this particular function being a class method or a free function is in how you use it:
obj = MyImageProcessingClass()
img = obj.pixelateImage(img, 3)
vs
img = pixelateImage(img, 3)
Creating that object really has no purpose, other than making the functionality harder to use.
if i == 0:
cModeRGB.append(0)
continue
cMode = i / 255
cModeRGB.append(cMode)
You are duplicating code here (two append calls) for the sake of avoiding the computation of 0/255. The conditional expression itself is a lot more expensive than the division you're avoiding. There really is no reason to avoid this division (note that it's not a division by zero, which would lead to warnings and NaN results and so on). It is best to simplify this code to just cModeRGB.append(i / 255).
int(img.size[0]/pixSize)
The other answer already mentioned that this is equivalent to, and better written as, img.size[0] // pixSize.
rgb = img.getpixel((x,y))
Calling functions like this is expensive. I would recommend converting the PIL image to a NumPy array at the start of your function, and converting it back at the end. This conversion is cheap (data is typically not copied), but allows for much easier pixel access:
img = np.asarray(img).copy()
# ...
rgb = img[y,x]
# ...
return PIL.Image.fromarray(img)
Note that the NumPy array is of size height x width x 3.
Note that np.asarray() can lead to a read-only array, here I added the .copy(), which does a deep copy of the data and assures a writeable array. | {
"domain": "codereview.stackexchange",
"id": 43964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, image, pygame",
"url": null
} |
python, numpy, image, pygame
You use a lot of loops to copy individual values over into arrays. Instead, and using NumPy indexing, fetch blocks of pixels at once. The double loop over xs and ys that ends with RGBc = np.array(RGB) can be simply written as:
RGBc = img[pixSize*n : pixSize*(n+1), pixSize*ny : pixSize*(ny+1), :]
Similarly, the following loop over i (here you're re-using the loop index of the outer loop, which in this case doesn't hurt, but is not good practice, use a different loop variable) can be written as
rgbMid = tuple(np.median(RGBc, axis=(0, 1)))
...but you don't really need to convert this to a tuple if you keep using NumPy arrays everywhere, you can directly assign the array returned by np.median to all the pixels:
img[pixSize*n : pixSize*(n+1), pixSize*ny : pixSize*(ny+1), :] = rgbMid
Note that in the call to np.median I wrote axis=(0, 1). RGBc is now a 3D array, with color along the 3rd dimension. We need to compute the median over the first two (spatial) dimensions.
You divide each pixel value by 255 when you read it, you compute the median, then multiply the result by 255 before writing it back into the image. You could skip the division and multiplication, it accomplishes nothing.
Finally, your outer loop determines how many iterations to run, then it figures out the start coordinates for each loop iteration. I think it would be clearer to simply loop over the start coordinates for each block:
for ny in range(0, img.shape[0], pixSize):
for nx in range(0, img.shape[1], pixSize): | {
"domain": "codereview.stackexchange",
"id": 43964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, image, pygame",
"url": null
} |
python, numpy, image, pygame
Now we don't need to multiply n (which I've named nx for clarity) and ny by pixSize every time we use them: they are incremented by that amount automatically. I've used img.shape[1] as the image width and img.shape[0] as the height, assuming img is a NumPy array at this point.
Next, to avoid indexing out of bounds in case the image is not evenly divisible into pixSize square blocks, we can compute the end points for each block as follows:
for ny in range(0, img.shape[0], pixSize):
ny_end = min(ny + pixSize, img.shape[0])
for nx in range(0, img.shape[1], pixSize):
nx_end = min(nx + pixSize, img.shape[1])
We compute ny_end outside the loop over nx, to avoid repeating the same calculation unnecessarily.
We put the loop over ny as the outer loop, and nx as the inner loop, because this way we access pixels in storage order. It is always faster to loop over data in storage order, because we make better use of the cache.
Putting it all together, I end up with the following function:
def pixelateImage(img, pixSize):
img = np.asarray(img).copy()
for ny in range(0, img.shape[0], pixSize):
ny_end = min(ny + pixSize, img.shape[0])
for nx in range(0, img.shape[1], pixSize):
nx_end = min(nx + pixSize, img.shape[1])
window = img[ny:ny_end, nx:nx_end, :]
color = np.median(window, axis=(0, 1))
img[ny:ny_end, nx:nx_end, :] = color
return PIL.Image.fromarray(img)
It produces the same result as the original implementation, but is much shorter and faster by more than an order of magnitude. | {
"domain": "codereview.stackexchange",
"id": 43964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, numpy, image, pygame",
"url": null
} |
c++, object-oriented, game, console, pong
Title: Pong in c++ console app
Question: I would really appriciate if someone could review my code and give me feedback. This was my first multi file project.
Main:
#include <iostream>
#include <vector>
#include "Pad.h"
#include <conio.h>
#include <Windows.h>
#include <iostream>
#include "Ball.h"
#include"consoleFunctions.h"
int main()
{
Map map{};
Ball ball{};
FirstPad firstPad{map};
SecondPad secondPad{ map };
WhoScored whoScored{ none };
map.print();
int ballCounter{};
int secondPadCounter{};
while (firstPad.getScore() < 10 && secondPad.getScore() < 10) { // game finishes when one player has 10 points
map.print();
std::cout << "Score: " << firstPad.getScore() << ":" << secondPad.getScore();
if (_kbhit()) {
firstPad.move(map);
}
if (ballCounter == 13) { //slowing down ball
ball.move(map, whoScored);
ballCounter = 0;
}
if (secondPadCounter == 11) { //slowing down computer paddle movement
secondPad.move(ball, map);
secondPadCounter = 0;
}
if (whoScored == leftPad) {
firstPad.increaseScore();
}
else if (whoScored == rightPad) {
secondPad.increaseScore();
}
whoScored = none;
++ballCounter;
++secondPadCounter;
}
set_cursor( MAP_WIDTH / 2, MAP_HEIGHT / 2);
if (firstPad.getScore() == 10) std::cout << "LEFT PAD WINS";
else std::cout << "RIGHT PAD WINS";
std::cin.ignore();
}
Map.h
#pragma once
#include <vector>
#include <iostream>
#include"EnumsAndStructs.h"
class Map {
private:
std::vector<std::vector<Objects>> m_map; //matrix which holds map
public:
Map();
void print();
std::vector<std::vector<Objects>>& getMap() { return m_map; }
}; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
Map.cpp
#include "map.h"
#include<Windows.h>
#include"consoleFunctions.h"
#include<sstream>
extern const int MAP_HEIGHT{ 25 };
extern const int MAP_WIDTH{ 100 };
Map::Map() {
//resizing array
m_map.resize(MAP_HEIGHT);
for (int i{ 0 }; i < MAP_HEIGHT; ++i) {
m_map[i].resize(MAP_WIDTH);
}
//setting map for begining
for (int i{ 0 }; i < MAP_HEIGHT; ++i) {
for (int j{ 0 }; j < MAP_WIDTH; ++j) {
if (j == 0 || j == MAP_WIDTH - 1) {
m_map[i][j] = Objects::VERTICAL_BORDER;
}
else if (i == 0 || i == MAP_HEIGHT - 1) {
m_map[i][j] = Objects::HORISONTAL_BORDER;
}
else {
m_map[i][j] = Objects::NOTHING;
}
}
m_map[MAP_HEIGHT / 2][MAP_WIDTH / 2] = Objects::BALL;
}
}
void Map::print() {
set_cursor();
cursor_off();
std::ostringstream ss;
for (int i{ 0 }; i < MAP_HEIGHT; ++i) {
for (int j{ 0 }; j < MAP_WIDTH; ++j) {
if (m_map[i][j] == Objects::HORISONTAL_BORDER) {
ss << '-';
}
else if (m_map[i][j] == Objects::VERTICAL_BORDER) {
ss << static_cast<char>(0XB3);
}
else if (m_map[i][j] == Objects::PAD) {
ss << static_cast<char>(0XB3);
}
else if(m_map[i][j] == Objects::BALL){
ss << '0';
}
else {
ss << ' ';
}
}
ss << '\n';
}
std::cout << ss.str();
}
Pad.h
#pragma once
#include <vector>
#include "EnumsAndStructs.h"
#include "Ball.h" | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
Pad.h
#pragma once
#include <vector>
#include "EnumsAndStructs.h"
#include "Ball.h"
extern const int MAP_HEIGHT;
extern const int MAP_WIDTH;
class Ball;
class Map;
class Pad {
protected:
int m_score{};
const int m_height{ 3 };
Coordinates m_coordinates{};
void setPadInitially(Map& map); //initially sets pads on map, used only in constructor
public:
const Coordinates& getCoordinates() const { return m_coordinates; }
int getHeight() const;
int getScore() const { return m_score; }
void increaseScore() { ++m_score; }
};
class FirstPad : public Pad {
private:
Direction m_direction{ Direction::NONE };
void takeDirection();
public:
FirstPad(Map& map);
void move(Map& map);
};
class SecondPad : public Pad {
public:
SecondPad(Map& map);
void move(const Ball& ball, Map& map);
};
Pad.cpp
#include "Pad.h"
#include <conio.h> | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
const int firstPadX{ 5 };
const int secondtPadX{ MAP_WIDTH - 7 };
constexpr auto KEY_UP = 72;
constexpr auto KEY_DOWN = 80;
// class Pad
int Pad::getHeight() const { return m_height; }
void Pad::setPadInitially(Map& map) {
int j{};
for (int i{ m_coordinates.m_y }; j < m_height; ++i) {
map.getMap()[i][m_coordinates.m_x] = Objects::PAD;
++j;
}
}
//class FirstPad
FirstPad::FirstPad(Map& map)
{
m_coordinates.m_x = firstPadX;
m_coordinates.m_y = (MAP_HEIGHT / 2) - (m_height / 2);
int j{};
setPadInitially(map);
}
void FirstPad::takeDirection() {
auto input{ _getch() };
switch (input) {
case KEY_DOWN: m_direction = Direction::DOWN;
break;
case KEY_UP: m_direction = Direction::UP;
break;
default: m_direction = Direction::NONE;
}
}
void FirstPad::move(Map& map) {
//chagning y coordinate as pad goes up and down
takeDirection();
if (m_direction == Direction::UP) {
if (m_coordinates.m_y > 1) {
--m_coordinates.m_y;
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::PAD;
map.getMap()[m_coordinates.m_y + m_height][m_coordinates.m_x] = Objects::NOTHING;
}
}
else if (m_direction == Direction::DOWN) {
if (m_coordinates.m_y + m_height < MAP_HEIGHT - 1) {
++m_coordinates.m_y;
map.getMap()[m_coordinates.m_y + m_height - 1][m_coordinates.m_x] = Objects::PAD;
map.getMap()[m_coordinates.m_y - 1][m_coordinates.m_x] = Objects::NOTHING;
}
}
}
// class SecondPad
SecondPad::SecondPad(Map& map) {
m_coordinates.m_x = secondtPadX;
m_coordinates.m_y = (MAP_HEIGHT / 2) - (m_height / 2);
setPadInitially(map);
}
void SecondPad::move(const Ball& ball, Map& map) {
// Coumputer controls this pad, basically follows ball
int padMiddleY = m_coordinates.m_y + m_height / 2; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
int padMiddleY = m_coordinates.m_y + m_height / 2;
if (padMiddleY < ball.getCoordinates().m_y && m_coordinates.m_y < MAP_HEIGHT - m_height - 1) {
++m_coordinates.m_y;
map.getMap()[m_coordinates.m_y + m_height - 1][m_coordinates.m_x] = Objects::PAD;
map.getMap()[m_coordinates.m_y - 1][m_coordinates.m_x] = Objects::NOTHING;
}
else if (padMiddleY > ball.getCoordinates().m_y && m_coordinates.m_y > 1) {
--m_coordinates.m_y;
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::PAD;
map.getMap()[m_coordinates.m_y + m_height][m_coordinates.m_x] = Objects::NOTHING;
}
} | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
Ball.h
#pragma once
#include "EnumsAndStructs.h"
#include "Map.h"
extern const int MAP_HEIGHT;
extern const int MAP_WIDTH;
class Map;
class Ball
{
private:
Coordinates m_coordinates{};
Direction m_direction{Direction::RIGHT_DOWN};
void handleColision(Map& map, WhoScored& whoScored);
public:
Ball()
: m_coordinates{MAP_WIDTH/ 2, MAP_HEIGHT / 2} // puts ball in the middle
{}
void move(Map& map, WhoScored& whoScored);
void reflectDirection();
const Coordinates& getCoordinates() const { return m_coordinates; }
};
Ball.cpp
#include "Ball.h" | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
void Ball::reflectDirection() {
switch (m_direction) {
case Direction::RIGHT_UP: {
m_direction = Direction::LEFT_UP;
return;
}
case Direction::RIGHT_DOWN: {
m_direction = Direction::LEFT_DOWN;
return;
}
case Direction::LEFT_UP: {
m_direction = Direction::RIGHT_UP;
return;
}
case Direction::LEFT_DOWN: {
m_direction = Direction::RIGHT_DOWN;
return;
}
}
return;
}
void Ball::handleColision(Map& map, WhoScored& whoScored) {
//handling bouncing on horisiontal walls and pads and checking who scored on verticals
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] == Objects::HORISONTAL_BORDER) {
if (m_direction == Direction::RIGHT_UP) { m_direction = Direction::RIGHT_DOWN; }
else if (m_direction == Direction::RIGHT_DOWN) { m_direction = Direction::RIGHT_UP; }
else if (m_direction == Direction::LEFT_UP) { m_direction = Direction::LEFT_DOWN; }
else if (m_direction == Direction::LEFT_DOWN) { m_direction = Direction::LEFT_UP; }
}
else if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] == Objects::VERTICAL_BORDER) {
if (m_coordinates.m_x < MAP_WIDTH / 2) { //if it is left side
whoScored = rightPad;
}
else whoScored = leftPad;
m_coordinates.m_y = MAP_HEIGHT / 2;
m_coordinates.m_x = MAP_WIDTH / 2;
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::BALL;
}
else if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] == Objects::PAD) {
reflectDirection();
}
}
void Ball::move(Map& map, WhoScored& whoScored) {
//ball will only move on 45 degrees, pretty simple
//if balls next position is bounacable object call handleColision
//whoScored is not needed in this function but in handleColision
if (m_direction == Direction::RIGHT_DOWN) { | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
if (m_direction == Direction::RIGHT_DOWN) {
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::VERTICAL_BORDER && //without this ifs our objects will disappear as ball bounces of them
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::HORISONTAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::PAD) { | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::NOTHING;
}
++m_coordinates.m_y;
++m_coordinates.m_x;
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::NOTHING) {
handleColision(map,whoScored);
}
else map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::BALL;
}
else if (m_direction == Direction::RIGHT_UP) {
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::VERTICAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::HORISONTAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::PAD) {
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::NOTHING;
}
--m_coordinates.m_y;
++m_coordinates.m_x;
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::NOTHING) {
handleColision(map, whoScored); | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
}
else map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::BALL;
}
else if (m_direction == Direction::LEFT_DOWN) {
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::VERTICAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::HORISONTAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::PAD) {
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::NOTHING;
}
++m_coordinates.m_y;
--m_coordinates.m_x;
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::NOTHING) {
handleColision(map,whoScored);
}
else map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::BALL;
}
else if (m_direction == Direction::LEFT_UP) {
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::VERTICAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::HORISONTAL_BORDER &&
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::PAD) {
map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::NOTHING;
}
--m_coordinates.m_y;
--m_coordinates.m_x;
if (map.getMap()[m_coordinates.m_y][m_coordinates.m_x] != Objects::NOTHING) {
handleColision(map, whoScored);
}
else map.getMap()[m_coordinates.m_y][m_coordinates.m_x] = Objects::BALL;
}
}
EnumsAndStructs.h
#pragma once
enum class Objects {
NOTHING,
PAD,
VERTICAL_BORDER,
HORISONTAL_BORDER,
BALL
};
enum class Direction {
NONE,
UP,
DOWN,
RIGHT,
LEFT,
RIGHT_UP,
RIGHT_DOWN,
LEFT_UP,
LEFT_DOWN,
};
struct Coordinates {
int m_x;
int m_y;
};
enum WhoScored {
none,
leftPad,
rightPad,
}; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
consoleFunctions.h
#pragma once
void cursor_off();//stops blinking cursor
void set_cursor(int x = 0, int y = 0);
consoleFucntions.cpp
#include<Windows.h>
void cursor_off()
{
CONSOLE_CURSOR_INFO console_cursor;
console_cursor.bVisible = 0;
console_cursor.dwSize = 1;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &console_cursor);
}
void set_cursor(int x = 0, int y = 0)
{
HANDLE handle;
COORD coordinates;
handle = GetStdHandle(STD_OUTPUT_HANDLE);
coordinates.X = x;
coordinates.Y = y;
SetConsoleCursorPosition(handle, coordinates);
}
Answer: This looks pretty good for a first project of this size!
Consider using a curses library
You are using <conio.h> and <Windows.h>, but those are of course Windows-specific header files. You can make your program more portable by using a curses library to draw the screen and to handle the keyboard input.
There are several curses implementations that also work on Windows, the most popular one of those is probably PDCurses.
Use std::array<> if your map is going to have a fixed size
If you know the size of your map at compile time, you can use std::array instead std::vector. This is more efficient, especially if you are nesting them. Use constexpr to declare the map size, and then you can use those constants to declare the arrays:
class Map {
static constexpr std::size_t HEIGHT = 25;
static constexpr std::size_t WIDTH = 100;
std::array<std::array<Objects, WIDTH>, HEIGHT> m_map;
public:
...
auto& getMap() { return m_map; }
}; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
public:
...
auto& getMap() { return m_map; }
};
Consider not using m_map
Your m_map, when implemented using std::arrays, uses 10 kilobytes of memory. With std::vectors, it even needs a little more. But is it really necessary to store the map this way? You know the walls are always at the edge of the map region, and then the only two other things to worry about are the position of the paddles and the ball. Since each paddle can only move up or down, you only need four integers in total to describe the state of the map: the y-coordinate of each paddle, and the x- and y-coordinates of the ball.
Of course this means rewriting some of the code, but I don't think it will actually be more complicated than it already is now.
Remove FirstPad and SecondPad
You should not need to create different classes for each of the pads. Instead of having SecondPad::move() contain the computer player logic, move that logic out, and just add a move() function to Pad that takes a Direction as an argument:
class Pad {
...
public:
Pad();
void move(Map& map, Direction dir);
...
};
If anything, make a Player and Computer class that then each control one Pad object.
Unnecessary use of stringstreams
I don't see the point in Map::print() first printing everything to ss, and then printing the contents of ss to std::cout. Why not print everything directly to std::cout?
Avoid repeating yourself
There is a lot of code duplication in your program that could have been avoided. For example, in Ball::move():
void Ball::move(Map& map, WhoScored& whoScored) {
// Remove the ball from its current position
auto& cur_object = map.getObject(m_coordinates);
if (cur_object == Objects::BALL) {
cur_object = Objects::NOTHING;
} | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
if (cur_object == Objects::BALL) {
cur_object = Objects::NOTHING;
}
// Update the position of the ball
switch (m_direction) {
case Direction::RIGHT_DOWN: ++m_coordinates.m_y; ++m_coordinates.m_x; break;
case Direction::RIGHT_UP: --m_coordinates.m_y; ++m_coordinates.m_x; break;
case Direction::LEFT_DOWN: ++m_coordinates.m_y; --m_coordinates.m_x; break;
case Direction::LEFT_UP: --m_coordinates.m_y; --m_coordinates.m_x; break;
}
// Handle collisions if necessary
auto& next_object = map.getObject(m_coordinates);
if (next_object != Objects::NOTHING) {
handleCollision(map, whoScored);
}
else next_object = Objects::BALL;
}
}
The above also introduces a new member function for Map to get a reference to the object at a given position:
Objects& Map::getObject(Coordinates pos) {
return m_map[pos.y][pos.x];
}
You could even go further. Consider creating an array of relative positions for each of the directions:
static constexpr Coordinates directions[] = {
/* NOTHING */ {0, 0};
/* UP */ {0, -1};
...
/* LEFT_DOWN */ {-1, 1};
};
This way, the switch statement in the above code can be replaced as follows:
// Update the position of the ball
m_coordinates.x += directions[m_direction].x;
m_coordinates.y += directions[m_direction].y; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
c++, object-oriented, game, console, pong
Avoid magic numbers
There are several magic numbers in your code. Whenever you have some number, like the number of points you need to win, don't just write that number in the code, create a constant for it. This has several benefits: because the number now has a name, it is more self-documenting, and if you ever need to change the number, you only need to do it in one place. So:
static constexpr int winning_score = 10;
static constexpr int ball_move_interval = 13;
static constexpr int computer_move_interval = 11;
...
while (firstPad.getScore() < winning_score && secondPad.getScore() < 10) {
...
if (ballCounter == ball_move_interval) {
ball.move(map, whoScores);
ballCounter = 0;
}
...
}
For the vertical lines, you use static_cast<char>(0XB3). I recommend you stick with ASCII characters, and just write '|' (the pipe symbol), but note that if you really want to use a high-ASCII symbol here, you could have written either '│' (literally the character with code 0xB3 from codepage 437) or '\xb3'. The latter still looks like a magical number, so in that case I would still create a named constant for it:
static constexpr char vertical_bar = '\xb3'; | {
"domain": "codereview.stackexchange",
"id": 43965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, game, console, pong",
"url": null
} |
php, sql, xml, postgresql
Title: Extracting authors and books from XML and inserting them into PostgreSQL
Question: There is a tree of start folder, it's subfolders, their subfolders, etc. In each folder, subfolder, etc. there are the same structured XML files stored.
books.xml
<xml>
<book>
<author>Isak Azimov</author>
<name>End of spirit</name>
</book>
<book>
<author>熱い</author>
<name>Happiness of plants</name>
</book>
<book>
<author>Isak Azimov</author>
<name>Stars and rain</name>
</book>
<book>
<author>Florea Paun</author>
<name>Life journey</name>
</book>
</xml>
PHP script should read XML files information and add it to PostgreSQL two database tables: “authors” and “books” (use 1:many and unique author’s ID as link between the tables). XML files content should be displayed as a result.
If a record from specified file and subfolder already exists PHP script has to update the record and not to insert it as a new one.
Here is my try:
<?php
$dsn = "pgsql:dbname=interpay host=localhost";
$options = [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
$pdo = new PDO($dsn, "postgres", "4137", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Fatal error!');
}
function tableExists($pdo, $table) {
$table = preg_replace('/[^\da-z_]/i', '', $table);
try {
$result = $pdo->query("SELECT 1 FROM {$table} LIMIT 1");
} catch (Exception $e) {
return FALSE;
}
return $result !== FALSE;
}
$sql = <<<EOF
CREATE TABLE authors
(id SERIAL PRIMARY KEY,
name TEXT NOT NULL);
EOF;
if (!tableExists($pdo, "authors"))
$pdo->prepare($sql)->execute(); | {
"domain": "codereview.stackexchange",
"id": 43966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, xml, postgresql",
"url": null
} |
php, sql, xml, postgresql
$sql = <<<EOF
CREATE TABLE books
(id SERIAL PRIMARY KEY,
author_id INT NOT NULL,
name TEXT NOT NULL,
CONSTRAINT fk_author FOREIGN KEY(author_id) REFERENCES authors(id));
EOF;
if (!tableExists($pdo, "books"))
$pdo->prepare($sql)->execute();
//XML file path
$path = "books.xml";
//Read entire file into string
$xmlfile = file_get_contents($path);
//Convert XML string into an object
$new = simplexml_load_string($xmlfile);
//Convert into json
$con = json_encode($new);
//Convert into associative array
$booksArr = json_decode($con, true);
for($i = 0; $i < count($booksArr['book']); $i++) {
//Check if author already inserted into table
$sql = <<<EOF
SELECT * FROM authors WHERE name = ?;
EOF;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $booksArr['book'][$i]['author'], PDO::PARAM_STR);
$stmt->execute();
$author_row = $stmt->fetch();
if ($author_row)
$last_author_id = $author_row['id'];
else {
$sql = <<<EOF
INSERT INTO authors (name) VALUES (?);
EOF;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $booksArr['book'][$i]['author'], PDO::PARAM_STR);
$stmt->execute();
echo "Author record created successfully!<br>";
$sql = "SELECT * FROM authors ORDER BY id DESC LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$author_row = $stmt->fetch();
$last_author_id = $author_row['id'];
}
//Check if book inserted into table
$sql = <<<EOF
SELECT * FROM books WHERE name = ?;
EOF;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $booksArr['book'][$i]['name'], PDO::PARAM_STR);
$stmt->execute();
$book_row = $stmt->fetch(); | {
"domain": "codereview.stackexchange",
"id": 43966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, xml, postgresql",
"url": null
} |
php, sql, xml, postgresql
//If book does not exist then insert into table
if (!$book_row) {
$sql = <<<EOF
INSERT INTO books (author_id, name) VALUES (?, ?);
EOF;
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $last_author_id, PDO::PARAM_INT);
$stmt->bindParam(2, $booksArr['book'][$i]['name'], PDO::PARAM_STR);
$stmt->execute();
echo "Book record created successfully!<br>";
}
}
$pdo = null;
$stmt = null;
?>
Answer: Code structure
That's a bit too much code for a single review. Given the task can be seamlessly separated into several modules, it will make it simpler to write, to read, to maintain and to review as well. For example, all the table creation code has no business with the main task of importing XML. The overall amount of code makes it harder to write a complete review, so I would suggest to post another question after taking into account all the suggestions given here. You see, a well-split code will produce a solid review and a solid code will produce a ragged review.
Usually, the table creation is supplied in the form of an SQL file or a migration but not in the form of PHP code.
the database connection code should be also moved into a separate file that just included in the main script
many SQL queries can be put into functions as not to pollute the main operation loop. Like, the code below //Check if author already inserted into table should be just one line, $author_row = getAuthor($pdo, $book['author']); All those functions again can be put into the included file and offered for the separate review. Or at least as a separate block of code in the same review.
Logical consistency. | {
"domain": "codereview.stackexchange",
"id": 43966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, xml, postgresql",
"url": null
} |
php, sql, xml, postgresql
Logical consistency.
It is possible that two authors can give their books the same name. It would make sense to check both the name and the author.
there is some folder structure mentioned but no code provided to handle it. A built-in recursive directory iterator would do though
you forgot the book update code. That's a direct result of your "wall of code" approach. With the main logic fits in one screen, it's easy to spot the mistake. While in such a wall of code it's easy to overlook one.
Formatting and readability
The overall formatting is good, your indentation is even and lines are reasonably long. Two suggestions:
Do not create a default indent. The baseline of PHP statements should be a the very left position.
Omit the closing PHP tag, it is forbidden by the standard
Using bindParam is a bit verbose. You can make it into one line, $stmt->execute([$last_author_id,$book['name']]);
The way you are using heredoc is way too verbose and doesn't actually use the benefits of heredoc. For my personal taste, heredoc is not needed here at all, and the entire assignment can be done in a single line using standard quotes: $sql = "SELECT * FROM authors WHERE name = ?"; - simple, compact and readable. But in case you prefer heredoc, at least move the closing tag to align with the opening tag, so there will be no extra spacing in the query | {
"domain": "codereview.stackexchange",
"id": 43966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, xml, postgresql",
"url": null
} |
php, sql, xml, postgresql
Error reporting
Using try catch around PDO connection is inconsistent and verbose. Given the error can occur on the every line, why only the PDO connection code gets such a special treatment? It just makes no sense. Besides, it's just convenient to see all errors on-screen dring development. You can (and should) configure the uniform error reporting for the entire PHP code. See the basic error reporting rules
Cache
You can avoid some roundtrips to database by storing known authors in the array like this $known_authors[$name] = $last_author_id; so next time you can try to get the id by simple $last_author_id = $known_authors[$name] ?? false; and only get to DB if it fails.
Other improvements.
Why not simplexml_load_file()?
The tableExists implementation is barbaric. There are more civilized ways to check the table existence than causing a deliberate error.
Using SELECT query to get the autogenerated id is WRONG on so many levels. Not only it's too verbose as compared to the proper way which is just $last_author_id = $pdo->lastInsertId(); but using SELECT query is guaranteed to give wrong results.
Come on, using for to iterate over arrays is prehistoric. I'd break my fingers trying to write
this
for($i = 0; $i < count($booksArr['book']); $i++) {
echo $booksArr['book'][$i]['author'];
}
instead of just
foreach ($booksArr['book'] as $book) {
echo $book['author'];
} | {
"domain": "codereview.stackexchange",
"id": 43966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, sql, xml, postgresql",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, dijkstra
Title: Find the cheapest flight to reach from source to destination
Question:
As the input you get the flight schedule as an array, each element of which is the price of a direct flight between 2 cities (an array of 3 elements - 2 city names as a string, and a flight price).
Planes fly in both directions and the price in both directions is the same. There is a possibility that there are no direct flights between cities.
Question:
Find the price of the cheapest flight between cities that are given as the 2nd and 3rd arguments.
Input:
3 arguments: the flight schedule as an array of arrays, city of departure and destination city.
Output:
Int. The best price.
Example:
cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['B', 'C', 50]],
'A',
'C') == 70
cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['B', 'C', 50]],
'C',
'A') == 70
MyCode:
I am using Dijkstras Algorithm to resolve the problem.
Please let me know if this approach can be improved in any way.
flights = [['A', 'C', 100],
['A' ,'B', 20],
['B', 'C', 50]]
src = "A"
dst = "C"
def solution(flights, src, dst):
from collections import defaultdict
from queue import PriorityQueue
graph = defaultdict(dict)
for s,d,w in flights:
graph[s][d] = w
pq = PriorityQueue()
pq.put((0, src))
vis = set()
while pq:
minCost, dest = pq.get()
if dest == dst: return minCost
if dest in vis:
continue
vis.add(dest)
for y,w in graph[dest].items():
pq.put((minCost+w, y))
return -1
solution(flights, src, dst)
Answer: Problem: Try solution(flights, "C", "A")
(Part of this problem: while pq: doesn't work as intended - while not pq.empty(): should be closer.) | {
"domain": "codereview.stackexchange",
"id": 43967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, algorithm, programming-challenge, dijkstra",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, dijkstra
You present one slick implementation of Dijkstra's Algorithm.
This being CR, I think there are possible improvements to details of how it is coded - and one strategic one:
Stick to the Style Guide for Python Code.
Where deviating (like importing inside a function), have a reason to, maybe document that reason with a comment. Strategically
Document your code. In the code.
Naming:
Name things for their role/purpose, not for their type.
costs rather than graph, cheapest rather than pq.
As code is read much more often than it is written, I'd prefer visited over vis.
(And yes, there are variables here that are more difficult to name -
code the way you think about the solution.)
(I guess I'm inconsistent with this advice when inclined to name the function dijktra_s() rather than shortest_path().
I do detest solution - make it an alias where needed.)
You conditionally don't process some items found cheapest.
Instead, make insertion conditional - unless evaluating that condition uses more resources than inserting in cheapest.
to have the module usable from outside, put "usage examples" in a
if __name__ == "__main__":
Separation of concerns:
I think transforming the flights array into a cost graph not to be part of Dijkstra's.
I didn't come up with a better remedy to the "symmetry problem" mentioned at the start of this post than to add costs[d][s] = c (graph[d][s] = w) - yet.
keep introduction of things close to usage, scopes small (even where only conceptual/"visual"):
e.g., "the global" flights close to calls using it
(When trying to do that with "the global src/dst", their motivation looks slim)
Algorithm:
Cost/distance being symmetrical, bidirectional Dijkstra's can be expected to use less resources. | {
"domain": "codereview.stackexchange",
"id": 43967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, algorithm, programming-challenge, dijkstra",
"url": null
} |
c#, design-patterns, .net, fluent-interface
Title: Creating complex object step by step
Question:
Builder pattern separates object construction from its representation
I have to generate username and password for the Account class. Since this operation is a bit more complex, I decided to wrap it into a Builder pattern because it allows me to create an object step by step using methods.
FirstName and LastName are required
MiddleName is optional.
Faculty number is 6 digits
Username equals to [prefix][year of study which is the first two digits of the faculty number][name initials e.g. John Smith Mikaelson -> jsm]
Password is simply the faculty number, nothing complicated here
I would like to get a code review on the code and the unit tests because 1) it's another opinion 2) I'm also not sure what the naming convention is when there is no "Act".
Part of the code, i.e. the transliteration was already reviewed by Peter Csala at Transliterate between Cyrillic and Latin scripts
Snippet
public sealed class Account
{
public string FirstName { get; set; } = string.Empty;
public string MiddleName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
public sealed class AccountBuilder
{
private readonly Account _account;
public AccountBuilder()
{
_account = new Account();
}
public AccountBuilder WithFirstName(string firstName)
{
_account.FirstName = firstName;
return this;
}
public AccountBuilder WithMiddleName(string middleName)
{
_account.MiddleName = middleName;
return this;
}
public AccountBuilder WithLastName(string lastName)
{
_account.LastName = lastName;
return this;
}
public Account Build(string prefix, string facultyNumber)
{
ArgumentNullException.ThrowIfNull(prefix);
ArgumentNullException.ThrowIfNull(facultyNumber); | {
"domain": "codereview.stackexchange",
"id": 43968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, .net, fluent-interface",
"url": null
} |
c#, design-patterns, .net, fluent-interface
var regex = new Regex("^[0-9]{6}$");
if (!regex.IsMatch(facultyNumber))
{
throw new ArgumentOutOfRangeException(nameof(facultyNumber), "Faculty number should be 6-digits long");
}
// Transliterate name
_account.FirstName = Transliteration.CyrillicToLatin(_account.FirstName);
_account.MiddleName = Transliteration.CyrillicToLatin(_account.MiddleName);
_account.LastName = Transliteration.CyrillicToLatin(_account.LastName);
// Generate username and password
// [cs/se][year-of-study][name-initials]
var yearOfStudy = facultyNumber[..2];
var firstLetterOfFirstName = _account.FirstName.Length > 0
? _account.FirstName.ToLowerInvariant()[..1]
: _account.FirstName;
var firstLetterOfMiddleName = _account.MiddleName.Length > 0
? _account.MiddleName.ToLowerInvariant()[..1]
: _account.MiddleName;
var firstLetterOfLastName = _account.LastName.Length > 0
? _account.LastName.ToLowerInvariant()[..1]
: _account.LastName;
_account.Username = $"{prefix}{yearOfStudy}{firstLetterOfFirstName}{firstLetterOfMiddleName}{firstLetterOfLastName}";
_account.Password = facultyNumber;
return _account;
}
} | {
"domain": "codereview.stackexchange",
"id": 43968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, .net, fluent-interface",
"url": null
} |
c#, design-patterns, .net, fluent-interface
return _account;
}
}
public static class Transliteration
{
private static readonly ImmutableDictionary<char, string> CyrillicToLatinMapping = new Dictionary<char, string>
{
{ 'а', "a" }, { 'А', "A" },
{ 'б', "b" }, { 'Б', "B" },
{ 'в', "v" }, { 'В', "V" },
{ 'г', "g" }, { 'Г', "G" },
{ 'д', "d" }, { 'Д', "D" },
{ 'е', "e" }, { 'Е', "E" },
{ 'ж', "zh" }, { 'Ж', "Zh" },
{ 'з', "z" }, { 'З', "Z" },
{ 'и', "i" }, { 'И', "I" },
{ 'й', "y" }, { 'Й', "Y" },
{ 'к', "k" }, { 'К', "K" },
{ 'л', "l" }, { 'Л', "L" },
{ 'м', "m" }, { 'М', "M" },
{ 'н', "n" }, { 'Н', "N" },
{ 'о', "o" }, { 'О', "O" },
{ 'п', "p" }, { 'П', "P" },
{ 'р', "r" }, { 'Р', "R" },
{ 'с', "s" }, { 'С', "S" },
{ 'т', "t" }, { 'Т', "T" },
{ 'у', "u" }, { 'У', "U" },
{ 'ф', "f" }, { 'Ф', "F" },
{ 'х', "h" }, { 'Х', "H" },
{ 'ц', "ts" }, { 'Ц', "Ts" },
{ 'ч', "ch" }, { 'Ч', "Ch" },
{ 'ш', "sh" }, { 'Ш', "Sh" },
{ 'щ', "sht" }, { 'Щ', "Sht" },
{ 'ъ', "a" }, { 'Ъ', "A" },
{ 'ь', "y" }, { 'Ь', "Y" },
{ 'ю', "yu" }, { 'Ю', "Yu" },
{ 'я', "ya" }, { 'Я', "Ya" },
{ ' ', " " }, { '-', "-" }
}.ToImmutableDictionary();
private static readonly ImmutableArray<(string Latin, char Cyrillic)> LatinToCyrillicMapping =
CyrillicToLatinMapping
.OrderByDescending(v => v.Value.Length)
.Select(d => (Latin: d.Value, Cyrillic: d.Key))
.ToImmutableArray();
public static string CyrillicToLatin(string text)
{
return string.Join("", text.ToCharArray().Select(c => CyrillicToLatinMapping[c]));
} | {
"domain": "codereview.stackexchange",
"id": 43968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, .net, fluent-interface",
"url": null
} |
c#, design-patterns, .net, fluent-interface
public static string LatinToCyrillic(string text)
{
var startIdx = 0;
var accumulator = new StringBuilder();
while (startIdx != text.Length)
{
foreach (var (latin, cyrillic) in LatinToCyrillicMapping)
{
if (!text[startIdx..].StartsWith(latin))
{
continue;
}
accumulator.Append(cyrillic);
startIdx += latin.Length;
break;
}
}
return accumulator.ToString();
}
}
Unit tests
public sealed class AccountTests
{
[Theory]
[InlineData("Иван", "", "Драганов", "196300", "cs19id", "196300")]
[InlineData("Борис", "Стоянов", "Иванов", "226502", "cs22bsi", "226502")]
public void Account_ShouldReturnAccountObject_WhenGivenName(
string firstName,
string middleName,
string lastName,
string facultyNumber,
string expectedUsername,
string expectedPassword)
{
// Arrange
var account = new AccountBuilder()
.WithFirstName(firstName)
.WithMiddleName(middleName)
.WithLastName(lastName)
.Build("cs", facultyNumber);
// Act
// Assert
account.Username.Should().Be(expectedUsername);
account.Password.Should().Be(expectedPassword);
}
}
Answer: Account
Depending on the requirements it would make sense to make the class immutable by using init instead of set for the properties
You can even declare the Account as record and use the with operators inside the builder
public record Account(string FirstName = "", string MiddleName = "", string LastName = "",
string UserName = "", string Password = "");
Marking the class as sealed seems to me a bit too defensive | {
"domain": "codereview.stackexchange",
"id": 43968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, .net, fluent-interface",
"url": null
} |
c#, design-patterns, .net, fluent-interface
Marking the class as sealed seems to me a bit too defensive
Based on my previous experiences class like this is usually becomes pretty soon a base class for a couple derived classes (Student, Lecturer, etc.)
AccountBuilder
WithXYZ
Most of the With implementations what I have seen did the followings:
perform some preliminary checks (like not null)
perform an equality check to avoid unnecessary overwrites
perform the overwrite if needed
public AccountBuilder WithFirstName(string firstName)
{
if (string.IsNullOrWhiteSpace(firstName))
throw new ArgumentOutOfRangeException("Please provide a valid FirstName");
if(!string.Equals(_account.FirstName, firstName, StringComparison.InvariantCulture))
_account.FirstName = firstName;
return this;
}
Build
Most of the time the builder function should not receive any parameter
Since you already have a fluent interface that's why you could easily create two WithXYZ methods for prefix and facultyNumber
If some properties must be set then check these first
public Account Build()
{
if (string.IsNullOrWhiteSpace(_account.FirstName) || string.IsNullOrWhiteSpace(_account.LastName))
throw new InvalidOperationException("FirstName, LastName must be set");
//...
}
You can move the Regex to class level and make it static
Even you can set RegexOptions to Compiled | {
"domain": "codereview.stackexchange",
"id": 43968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, design-patterns, .net, fluent-interface",
"url": null
} |
python
Title: Slot Machines Project
Question: Hello i build project Slot Machine this project was inspired by Tech with Tim here's his code from this project how he implement that --> https://github.com/techwithtim/Python-Slot-Machine/blob/main/main.py .I changed the code of the project on my way but something is same but most of the things i tried to change to check if i understand the project well.I am looking for maybe another way to implement the structure of code and tell me if i've done something wrong , what i should do better or to add something more.
import random
MAX_VALUE = 100
MIN_VALUE = 1
ROWS = 3
COLUMNS = 3
symbols_count = {
"A":2,
"B":4,
"C":5,
"E":3,
"F":2
}
symbols_values = {
"A":2,
"B":4,
"C":5,
"E":3,
"F":2
}
def check_winnings(columns,bet_lines,bet,balance):
first_column = []
second_column = []
third_columns = []
for element in columns:
if len(first_column) < 3:
first_column.append(element)
elif len(second_column) < 3:
second_column.append(element)
elif len(third_columns) < 3:
third_columns.append(element)
check_duplicates_first = set(first_column) # we make sets because if there's three characters same it will return only one but remove the two duplicates
check_duplicates_second = set(second_column)
check_duplicates_third = set(third_columns) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
if len(check_duplicates_first) == 1:
print("Winning line is --> line one --<")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_second) == 1:
print("Winning line is --> line two <--")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_third) == 1:
print("Winning line is --> line three --<")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_first) > 1 or len(check_duplicates_second) > 1 or len(check_duplicates_third):
get_sum = bet_lines * bet
balance = balance - get_sum
print(f"You didn't get it try again ,now you have {balance}$")
playagain(balance)
def spin_slot_machine(symbols):
all_symbols = []
columns = []
length_of_spin = 9
for symbol,symbol_count in symbols.items():
for i in range(symbol_count):
all_symbols.append(symbol)
for i in range(length_of_spin):
get_random = random.choice(all_symbols)
columns.append(get_random)
return columns
def print_slot_machine(columns):
first_row = ' | '.join(columns[0:3])
second_row = ' | '.join(columns[3:6])
third_row = ' | '.join(columns[6:9])
print(first_row)
print(second_row)
print(third_row) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
def deposit():
while True:
deposit_money = input("How much money would you like to deposit?: $")
if deposit_money.isdigit():
deposit_money = int(deposit_money)
if deposit_money > 0:
break
else:
print("You should deposit more than 0$")
print("Enter a digit")
return deposit_money
def bet_on_lines():
while True:
lines = input("On how many lines would you like to bet(1-3)?: ")
if lines.isdigit():
lines = int(lines)
if lines >= 1 and lines <= 3:
break
else:
print("Number of lines should be between 1-3")
print("Enter a number of lines")
return lines
def get_bet():
while True:
bet = input("How much money would you like to bet on one line(1$-100$): ")
if bet.isdigit():
bet = int(bet)
if bet <= MAX_VALUE and bet >= MIN_VALUE:
break
else:
print("Money should be between 1-100$")
else:
print("Enter a digit")
return bet | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
def spin():
balance = deposit()
lines_number = bet_on_lines()
while True:
bet_money = get_bet()
total_bet = bet_money * lines_number
if total_bet > balance:
print(f"Your balance is {balance}$.Balance shoudn't be less than betting money , bet less!")
else:
break
print(f"You are betting {total_bet}$ on {lines_number} lines.")
slot_machine = spin_slot_machine(symbols_count)
print_slot_machine(slot_machine)
check_winnings(slot_machine,lines_number,bet_money,balance)
def playagain(balance):
while True:
answer = input("Do you want to play again(Press Enter or q to quit): ")
if answer != "" or balance == 0:
print(f"You left with {balance}$, Good Bye!")
break
else:
if int(balance) > 0:
lines_number = bet_on_lines()
bet_money = get_bet()
slot_machine = spin_slot_machine(symbols_count)
print_slot_machine(slot_machine)
check_winnings(slot_machine,lines_number,bet_money,balance)
break
spin()
Answer: PEP-8
First off, your whitespace is all over the place. PEP-8 recommendations are a set of rules to standardise the layout and appearance of Python code to make it easier for anyone who comes along to read and use it. It recommends:
Surround top-level function and class definitions with two blank lines. | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Surround top-level function and class definitions with two blank lines.
Amongst other things. A good linter such as flake8 or pylint will highlight these issues for you automatically.
playagain violates the "functions should be snake-case" principle.
If-else
In your check_winnings function, you have your if-block which checks each row for whether each row's symbols are all the same and then whether they're not. The else block will handle that for you. If something doesn't match any of the preceding ifs, the else will run, which is what you want here.
#Reformatted for clarity and to highlight typo
elif (len(check_duplicates_first) > 1 or
len(check_duplicates_second) > 1 or
len(check_duplicates_third)):
simply becomes:
else:
You have the inverse problem in playagain where you have:
if answer != "" or balance == 0:
print(f"You left with {balance}$, Good Bye!")
break
else:
if int(balance) > 0:
Which could easily be:
elif int(balance) > 0:
However, following a break you needn't have the else at all.
Sampling and using the right functions
Another bug comes in with the fact that you are doing several independent choices for your wheels:
for i in range(length_of_spin):
get_random = random.choice(all_symbols)
columns.append(get_random)
This does not obey symbol_counts (as done with replacement) and in principle, it would be possible for you to roll ['A']*9
First off, we could clean it up using a list comprehension (as in several other places)
# If you don't use a loop argument, it is customary to name it _
columns = [random.choice(all_symbols) for _ in range(length_of_spin)
second, we could use random.choices (see help(random))
choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance
Return a k sized list of population elements chosen with replacement.
columns = random.choices(all_symbols, k=length_of_spin) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
columns = random.choices(all_symbols, k=length_of_spin)
However, noting this is with replacement, we should use random.sample, which does what we want!
columns = random.sample(all_symbols, k=length_of_spin)
It even lets us avoid having to construct a list of all symbols:
columns = random.sample(list(symbols.keys()),
counts=list(symbols.values()),
k=length_of_spin)
Learning the tools can save you a lot of effort and time.
Simplify
Python has tools for slicing and dealing with lists, this means that we can avoid a lot of busywork
first_column = []
second_column = []
third_columns = []
for element in columns:
if len(first_column) < 3:
first_column.append(element)
elif len(second_column) < 3:
second_column.append(element)
elif len(third_columns) < 3:
third_columns.append(element)
# we make sets because if there's three characters same
# it will return only one but remove the two duplicates
check_duplicates_first = set(first_column)
check_duplicates_second = set(second_column)
check_duplicates_third = set(third_columns)
Constructs 3 temporary lists (in a somewhat complicated manner) and then builds a set from those lists. We can skip half of this work:
first_column = columns[0:3]
second_column = columns[3:6]
third_column = columns[6:9]
In fact, since its so simple, we can just directly do:
check_duplicates_first = set(columns[0:3])
check_duplicates_second = set(columns[3:6])
check_duplicates_third = set(columns[6:9]) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
DRY
Don't repeat yourself (DRY) is the principle that good code should be written once. Take:
if len(check_duplicates_first) == 1:
print("Winning line is --> line one --<")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_second) == 1:
print("Winning line is --> line two <--")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_third) == 1:
print("Winning line is --> line three --<")
balance += bet_lines * bet
print(f"You got it this time ,now you have {balance}$")
playagain(balance)
elif len(check_duplicates_first) > 1 or len(check_duplicates_second) > 1 or len(check_duplicates_third):
get_sum = bet_lines * bet
balance = balance - get_sum
print(f"You didn't get it try again ,now you have {balance}$")
playagain(balance)
For each of the winning statements, the only line which changes is the winning line, and even the lose statement computes the total spent and calls playagain (N.B. Really, we don't actually want this function calling playagain, that results in nested recursion, the top level should call it, but that's another issue). We could instead (and still not the most concise, but simpler):
winner = None
if len(check_duplicates_first) == 1:
winner = "one"
elif len(check_duplicates_second) == 1:
winner = "two"
elif len(check_duplicates_third) == 1:
winner = "three"
get_sum = bet_lines * bet
if winner:
balance += get_sum
print(f"Winning line is --> line {winner} --<")
print(f"You got it this time, now you have {balance}$")
else:
balance -= get_sum
print(f"You didn't get it try again, now you have {balance}$")
playagain(balance) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
playagain(balance)
Likewise, you could define a single function to handle user input to replace deposit, bet_on_lines and get_bet all of which request an integer in a given range from a user, with a certain prompt.
Something like:
def get_int(prompt, min_val=None, max_val=None):
while True:
val = input(prompt)
if val.isdigit():
val = int(val)
if min_val <= val <= max_val:
break
# It'll show a bit oddly when either is not entered, but for now it'll do
print(f"Val must be between {min_val}-{max_val}")
return val
Similarly you reduplicate a lot of effort converting your linear list of columns into the ROWSxCOLS array which you could easily do once and make your functions work with lists of lists or arrays.
Unused variables
ROWS, COLUMNS and symbols_values all seem to be unused, but could be useful. You could use ROWS and COLUMNS to compute the slice lengths, number of slices (using lists of sets rather than separate variables).
symbols_values was presumably originally intended to be a multiplier on the reward received.
Summary
Putting all of the above together, you might end up with something like (adding docstring and main guard)
"""
Play a slot machine game
"""
import random
MAX_VALUE = 100
MIN_VALUE = 1
ROWS = 3
COLUMNS = 3
# It should be noted that using these counts it is impossible for
# A or F to win, and others are very unlikely
# Probably want to increase the count a little
SYMBOLS_COUNT = {
"A": 2,
"B": 4,
"C": 5,
"E": 3,
"F": 2
}
SYMBOLS_VALUES = {
"A": 2,
"B": 4,
"C": 5,
"E": 3,
"F": 2
}
def check_winnings(columns, bet_lines, bet, balance):
""" Compute winnings based on columns """
# Can do this because we pass columns around as a list of lists
sets = [set(x) for x in columns[1:bet_lines]]
# Allow multiple winners
winners = [(i, symb[0]) for i, symb in enumerate(sets) if len(symb) == 1] | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
winnings = 0
if winners: # Check against empty list
for line, symb in winners:
print("Line {line} won with {symb}")
# Use symbols values as multiplier on returns
# Diminishing returns for more lines
winnings += SYMBOLS_VALUES[symb] * bet
print(f"You won ${winnings}.")
else:
print("You didn't get any winners.")
return winnings
def spin_slot_machine(symbols, rows=ROWS, cols=COLUMNS):
""" Return set of wheels from slot machine """
spin = random.sample(list(symbols.keys()),
counts=list(symbols.values()),
k=rows*cols)
wheels = [spin[rows*i:rows*i+cols] for i in range(rows)]
return wheels
def print_slot_machine(columns):
""" Display slot machine to user """
print("\n".join(" | ".join(col) for col in columns))
def get_int(prompt, min_val=None, max_val=None):
""" Get an integer from a user within given bounds """
while True:
val = input(f"{prompt} ({min_val}-{max_val})? ")
if val.isdigit():
val = int(val)
if min_val <= val <= max_val:
break
print(f"Invalid option {val}: must be an integer between {min_val}-{max_val}")
return val
def get_bet(balance, cols):
""" Get the user's bet """
while True:
lines_number = get_int("On how many lines would you like to bet, total bet is lines*bet",
1, cols)
bet_money = get_int("How much money would you like to bet per line",
MIN_VALUE, MAX_VALUE)
total_bet = bet_money * lines_number
if total_bet <= balance:
return bet_money, lines_number
print(f"Your balance is {balance}$. You cannot afford this bet, bet less!")
def play_round(balance, rows=ROWS, cols=COLUMNS):
""" Play a single round of slots """
bet_money, lines_number = get_bet(balance, cols) | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
print(f"You are betting {bet_money}$ on {lines_number} lines.")
balance -= lines_number * bet_money
slot_machine = spin_slot_machine(SYMBOLS_COUNT, rows, cols)
print_slot_machine(slot_machine)
balance += check_winnings(slot_machine, lines_number, bet_money, balance)
return balance
def play_game(rows=ROWS, cols=COLUMNS):
""" Play multiple rounds until bank exhausted or user exits """
balance = get_int("How much starting money do you wish to have", 10, 1_000_000)
play = True
while play:
balance = play_round(balance, rows, cols)
print(f"Balance now sits at {balance}$.")
if balance <= 0:
print(f"You left with {balance}$, Good Bye!")
break
while True:
answer = input(
"Do you want to play again (Press 'y' to play again or 'q' to quit): ").lower()
if answer == "y":
play = True
break
if answer == "q":
print(f"You left with {balance}$, Good Bye!")
play = False
break
print(f"Invalid option {answer}.")
if __name__ == "__main__":
play_game()
Some other extensions you may wish to add include the fact that real slot machines have a set of wheels, rather than random sequences. You might want to generate these wheels in advance and simulate spinning them (index into a point, and getting the next COLUMNS values in the sequence). | {
"domain": "codereview.stackexchange",
"id": 43969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
javascript, vue.js
Title: Infinite content loop carousel
Question: I made this pretty simple content loop-carousel component, but
the code seems too "Iffy" but Im not sure how I could make it better.
I tried to use the Switch expression, which makes it a bit more readable, but
I dont like the breaks in them.
here is the relevant js code:
data() {
return {
...
currentContentId: 0,
content: [
{ id: 0, title: "title1", body: "description1" },
{ id: 1, title: "title2", body: "description2" },
{ id: 2, title: "title3", body: "description3" }
]
};
},
methods: {
nav(e) {
let loopLength = this.content.length - 1;
if (e.target.parentElement.id === "nav__back") {
if (this.currentContentId == 0) {
this.currentContentId = loopLength
} else {
this.currentContentId--
}
} else {
if (this.currentContentId == loopLength) {
this.currentContentId = this.currentContentId - loopLength
} else {
this.currentContentId++
}
}
}
html:
<div class="content">
<a id="nav__back" class="content__arrow" @click="nav">
<i class="material-icons">arrow_back_ios</i>
</a>
<div class="content__wrapper">
<h1 class="content__heading">{{ content[currentContentId].title }}</h1>
<div class="content__text">
<p>{{ content[currentContentId].body }}</p>
</div>
</div>
<a id="nav__forward" class="content__arrow" @click="nav">
<i class="material-icons">arrow_forward_ios</i>
</a>
</div>
heres my codepen link (theres also a theme switcher, pay no mind to that) | {
"domain": "codereview.stackexchange",
"id": 43970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, vue.js",
"url": null
} |
javascript, vue.js
heres my codepen link (theres also a theme switcher, pay no mind to that)
Answer:
Your code breaks when your id's are not in sequence. I wouldn't call them id then, but maybe index and if index, why even have them in the data structure (it is implied by the position in the array)?
That 0 as magic number of first id also bothers me. Would be much better to initialize this id based of contents[0].id
Your first if is there because you didn't want to create separate method for forward and back buttons. If you create 2 separate methods, code is shorter, cleaner and you get rid of the first if.
Then your code is 2 methods with single if-else. Since you are basically just moving this index between 0 and contents.length, you can instead use % module and eliminate that if too. Something like:
this.currentContentId = (this.currentCOntentId + 1 + loopLength) % loopLength
Another possibilities in case you want to keep ifs:
I would extract conditions of your ifs into methods like isOnFirstItem or isOnLastItem, that increases readability greatly for someone who never saw the code before.
Rather than modifying currentContentId, I would create explicit methods like goForward, goFirst, goPrevious, goBack. | {
"domain": "codereview.stackexchange",
"id": 43970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, vue.js",
"url": null
} |
java, spring
Title: Duplicate code in spring controllers
Question: public ResponseEntity<Map<String, String>> resetPassword(@RequestBody String email) {
// Create password token and send by email, if email doesn't exist, don't send it
Optional<AppUser> optionalUser = appUserService.findByEmail(email);
if (optionalUser.isEmpty()) {
throw new VerificationTokenException(HttpStatus.UNAUTHORIZED, "Email not found");
}
AppUser user = optionalUser.get();
if (user.isEnabled()) {
throw new VerificationTokenException(HttpStatus.FORBIDDEN, "Something went wrong");
}
Optional<VerificationToken> optionalVerificationToken = verificationTokenService.findByUser(user);
if (optionalVerificationToken.isPresent()) {
VerificationToken verificationToken = optionalVerificationToken.get();
verificationTokenService.delete(verificationToken);
}
// ...
}
These 3 if staments are used in multiple methods in my Controller, what is a proper way to make them reusable?
I could extract each if statement into an individuel method like so, but on what level should I put them in? Should I create an util class
or keep them inside my Controller class which uses them?
private Optional<AppUser> getAppUser(String email) {
Optional<AppUser> optionalUser = appUserService.findByEmail(email);
if (optionalUser.isEmpty()) {
throw new VerificationTokenException(HttpStatus.UNAUTHORIZED, "Email not found");
}
return optionalUser;
} | {
"domain": "codereview.stackexchange",
"id": 43971,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, spring",
"url": null
} |
java, spring
Answer: You can just extract those first 2 if's into separate methods (or single method), returning the user at the same time.
Something like getDisabledUserOrThrow() (Returning the AppUser instance, not Optional, because either you return a "valid" user (no-enabled) or throw your exception).
You can use that anywhere you need to ensure you have user instance. Something like this:
private AppUser getDisabledUserOrThrow(String email) throws VerificationTokenException {
Optional<AppUser> optionalUser = appUserService.findByEmail(email);
if (optionalUser.isEmpty()) {
throw new VerificationTokenException(HttpStatus.UNAUTHORIZED, "Email not found");
}
AppUser user = optionalUser.get();
if (user.isEnabled()) {
throw new VerificationTokenException(HttpStatus.FORBIDDEN, "Something went wrong");
}
return user;
}
You could do the same to get the token if that's what is the most common data necessary for your logic further.
Edit:
To expand on positioning this method:
One way would be to put it in your parent controller (if you have one) as protected methods so that you can call them directly from your controller.
I am also thinking - if those methods are basically getting your domain models, you can look at those as methods of Repositories (look up this pattern if needed) and inject them into your controllers :-)
It's always possible to create static methods instead, which is also fine if there's no clear place of putting it. | {
"domain": "codereview.stackexchange",
"id": 43971,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, spring",
"url": null
} |
java, beginner, algorithm, sorting, swing
Title: Sorting visualizer using Java Swing
Question: I programmed a little sorting visualizer a while back and I have been meaning to get some feedback on the overall implementation and on what I could do better to have cleaner code or a "best practice" version.
I did my best to use OOP programming.
I have done some projects in the past so this is not my first one and I wouldn't say that I am a complete beginner but I guess I still have a lot to learn and to improve upon so any feedback is appreciated dearly! :)
Main class:
public class Main{
public static void main(String[] args) {
new Frame();
}
}
Panel class where the main logic of the program takes place:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Panel extends JPanel implements ActionListener{
private int[] array = new int[Constants.ELEMENTS.getValue()];
private SelectionSort selectionSort;
private InsertionSort insertionSort;
private BubbleSort bubbleSort;
private JButton[] buttons;
private JButton selectionSortButton = new JButton("selection sort");
private JButton reset = new JButton("reset");
private JButton insertionSortButton = new JButton("insertion sort");
private JButton bubbleSortButton = new JButton("bubble sort");
public Panel() {
this.buttons = new JButton[] {selectionSortButton, insertionSortButton, bubbleSortButton, reset};
this.selectionSort = new SelectionSort();
this.insertionSort = new InsertionSort();
this.bubbleSort = new BubbleSort();
this.setPreferredSize(new Dimension(Constants.WIN_WIDTH.getValue(), Constants.WIN_HEIGHT.getValue()));
this._initArray();
this.setOpaque(true);//otherwise backgroundcolor won't be visible
for(JButton button : buttons){
button.addActionListener(this);
this.add(button);
}
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
public void _initArray() {
for(int i = 0; i < this.array.length; i++) {
array[i] = (int)(Math.random() * Constants.RANGE.getValue()+1);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.ORANGE);
for(int i = 0; i < this.getArray().length; i++) {
g.drawRect(i, 800 - array[i], 1, array[i]);
g.fillRect(i, 800 - array[i], 1, array[i]);
}
}
public int[] getArray() {
return this.array;
}
public void render(int time) {
repaint();
try{
Thread.sleep(time);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void resetArray() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < getArray().length; i++) {
getArray()[i] = (int)(Math.random() * Constants.RANGE.getValue()+1);
render(1);
}
}
});
t.start();
}
public void initSort(SortingInterface sortint, int start) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for(int i = start; i <= getArray().length; i++) {
sortint.sort(getArray(), i);
render(10);
}
}
});
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.reset) {
this.resetArray();
}
if(e.getSource() == this.selectionSortButton){
initSort(selectionSort, 0);
}
if(e.getSource() == this.insertionSortButton) {
initSort(insertionSort, 1);
}
if(e.getSource() == this.bubbleSortButton) {
initSort(bubbleSort, 0);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
Frame class:
import javax.swing.*;
public class Frame extends JFrame{
public Frame() {
this.getContentPane().add(new Panel());
this.setTitle("Sorting visualizer");
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
Interface for all the sorting algorithms:
public interface SortingInterface {
public void sort(int[] array, int i);
}
My implementation of Selection sort:
public class SelectionSort implements SortingInterface{
@Override
public void sort(int[] array, int i) {
int min = i;
for(int j = i+1; j < array.length; j++) {
if(array[j] < array[min]) {
min = j;
}
}
if(min != i) {
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
}
My implementation of Insertion sort:
public class InsertionSort implements SortingInterface{
@Override
public void sort(int[] array, int i) {
if(array[i] < array[i-1]) {
for(int j = 0; j < i; j++) {
if(array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
My implementation of Bubble Sort:
public class BubbleSort implements SortingInterface{
@Override
public void sort(int[] array, int i) {
for(int j = i+1; j < array.length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
Enum for all (or most I think) constants, not because it is best practice (not sure about that actually) but because I felt like using an enum:
public enum Constants {
WIN_WIDTH(1200),
WIN_HEIGHT(800),
ELEMENTS(1200),
RANGE(WIN_HEIGHT.getValue()-100);
public final int value;
private Constants(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
I have been programming since June. I started with Mooc.fi java part 1 and 2 and then got a little into the Odin Project. But I stopped after the Tic-Tac-Toe project as I realized that web development really isn't it for me. I did the sorting visualizer like a month ago and ever since I kind of did not really have any further project ideas...
So if someone has some interesting ideas, I'm all in :) | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
Answer: In many cases your use of import * is a little too aggressive. You're filling the working namespace of your files with everything from swing and awt when you only need a small handful of symbols.
A better name for SortingInterface is something like SortingAlgorithm.
There should be nothing individually special about your selection / insertion / bubble sort references within Panel - they should all be treated the exact same.
I find that you overuse this., and most of those prefixes should go away. This isn't Python, after all.
_initArray is better structured as a member initialiser that uses a stream, instead of a method that mutates an existing member.
Don't catch(Exception e). In this case you're looking for InterruptedException.
In contemporary Java you should no longer be using Runnable, and instead just write inline lambdas.
Factor out the common code from resetArray and initSort into another function.
Writing one handler for multiple scenarios and then having to differentiate between those scenarios with if is an antipattern. Register a separate handler for each button.
Your user interface allows for some very funny and incorrect behaviour: you allow for multiple concurrent reset or sort operations on the same data. This should be disallowed by disabling the buttons until any of those operations is done. A more usable enhancement that I have not shown is for you to never disable the reset button, and if the reset button is pushed during another operation, cancel its thread before continuing.
Move your button name strings to name strings in your algorithm subclasses.
You have some boundary failures in your sort implementations. The start index mechanism needs to go away, and you need to take more care that your indices make sense at the beginning and end of the array.
Don't write a Constants file, and especially don't make it an enum. Move the constants to private static final members internal to the classes that need them.
Suggested
Main.java | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
Suggested
Main.java
public class Main{ | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
public static void main(String[] args) {
new Frame();
}
}
Panel.java
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
public class Panel extends JPanel {
private static final int
WIN_WIDTH = 1200, WIN_HEIGHT = 800,
RANGE = WIN_HEIGHT - 100,
ELEMENTS = 1200;
private final Random rand = new Random();
private final int[] array =
IntStream.generate(() -> rand.nextInt(RANGE))
.limit(ELEMENTS)
.toArray();
private final SortingAlgorithm[] algos = {
new SelectionSort(), new InsertionSort(), new BubbleSort()
};
private final List<JButton> algoButtons =
Arrays.stream(algos)
.map(algo -> {
JButton button = new JButton(algo.getName());
button.addActionListener(event -> initSort(algo));
return button;
})
.toList();
private final JButton resetButton = new JButton("reset");
public Panel() {
setPreferredSize(new Dimension(WIN_WIDTH, WIN_HEIGHT));
setOpaque(true); // otherwise, backgroundcolor won't be visible
algoButtons.forEach(this::add);
resetButton.addActionListener(this::resetArray);
add(resetButton);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.ORANGE);
for (int i = 0; i < array.length; i++) {
g.drawRect(i, 800 - array[i], 1, array[i]);
g.fillRect(i, 800 - array[i], 1, array[i]);
}
}
public int[] getArray() {
return array;
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
public int[] getArray() {
return array;
}
public void render(int time) {
repaint();
try {
Thread.sleep(time);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private void enableButtons(boolean enabled) {
resetButton.setEnabled(enabled);
for (JButton button: algoButtons)
button.setEnabled(enabled);
}
private void animate(IntConsumer consume, int time) {
enableButtons(false);
new Thread(() -> {
for (int i = 0; i < getArray().length; i++) {
consume.accept(i);
render(time);
}
enableButtons(true);
}).start();
}
private void resetArray(ActionEvent e) {
animate(i -> array[i] = rand.nextInt(RANGE), 1);
}
public void initSort(SortingAlgorithm algorithm) {
animate(i -> algorithm.sort(array, i),10);
}
}
Frame.java
import javax.swing.JFrame;
public class Frame extends JFrame {
public Frame() {
getContentPane().add(new Panel());
setTitle("Sorting visualizer");
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
}
}
SortingAlgorithm.java
public interface SortingAlgorithm {
void sort(int[] array, int size);
String getName();
}
SelectionSort.java
public class SelectionSort implements SortingAlgorithm {
@Override
public String getName() {
return "selection sort";
}
@Override
public void sort(int[] array, int target) {
int min = target;
for (int i = target+1; i < array.length; i++) {
if (array[min] > array[i])
min = i;
}
if (min != target) {
int temp = array[target];
array[target] = array[min];
array[min] = temp;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
java, beginner, algorithm, sorting, swing
InsertionSort.java
public class InsertionSort implements SortingAlgorithm {
@Override
public String getName() {
return "insertion sort";
}
@Override
public void sort(int[] array, int target) {
if (target >= array.length - 1)
return;
if (array[target+1] < array[target]) {
for (int i = 0; i <= target; i++) {
if (array[target+1] < array[i]) {
int temp = array[target+1];
array[target+1] = array[i];
array[i] = temp;
}
}
}
}
}
BubbleSort.java
public class BubbleSort implements SortingAlgorithm {
@Override
public String getName() {
return "bubble sort";
}
@Override
public void sort(int[] array, int target) {
int i = target;
for (int j = i+1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43972,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, algorithm, sorting, swing",
"url": null
} |
python, python-3.x, console, ssh, curses
Title: Python File Explorer / RSync Terminal User Interface
Question: I've been working on my first python program for a few weeks now and I feel like the program is at a decent stage to begin sharing. The premise was to create a file explorer that eases the use of rsync. The reason I've chosen rsync over ssh/sftp is due to my current location and extremely limited internet connectivity/high-latency. This was inspired by midnight commander but is not written in C and I have not used any code from MC.
However, as I continue to develop the application, I feel as if I can be much more efficient with the code structure, and probably even the use of ssh when pulling certain file attributes. I've worked on refactoring a few times but am definitely aware the program needs a lot of love.
Goals: refactoring, use rsync over an established ssh channel, and more bandwidth efficient.
Question: what is the best option to help thin out this code - should I be relying on decorators? Or, should my classes and methods be much smaller?
For example - to make the primary file explorer I utilize a loop to print the list of directory's (menu method), and then navigate through it (navigate method) and constantly keep reprinting the list depending on the key press (display method). However, I continue to use a similar code structure throughout the application to make a menu and buttons. There are small changes in each of those iterations of the code to adapt them for their uses. Here's the primary structure I'm referring to.
class file_explorer:
"""Work horse of the application | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
Does the bulk of the work by taking a path and listing directorys/files within that
path. Also prints the list of directorys/files and is responsible for navigating
through those files. The ssh_explorer method is meant to closely mirror the explorer
method but is modified for paramiko where appropriate.
"""
path = prev_path_0 = prev_path_1 = '/'
paths = [None,None]
prev_paths = [prev_path_0, prev_path_1]
path_errors = reset_path()
def __init__(self, stdscr, window, path, is_ssh):
self.marked_item = None
self.window = window
self.screen = stdscr
self.screen_height, self.screen_width = self.screen.getmaxyx()
height, width = self.window.getmaxyx()
start_y, start_x = self.window.getbegyx()
self.p = 0
self.height = height
self.width = width - 2
self.start_y = start_y + 1
self.start_x = start_x + 1
self.position = 0
self.scroller = 0
self.explorer(path)
self.draw_pad()
self.event = ''
self.selected_path = ''
self.ssh_path = None
self.ssh_path_hist = ['/'] | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def explorer(self, path):
if wins.active_panel == 1 and ssh_obj.enabled == True:
#self.ssh_path = path
file_explorer_1.ssh_explorer(path)
return 0
self.path = path
try:
self.abs_path = os.path.abspath(self.path)
self.par_dir = os.path.dirname(self.abs_path).replace('//','/')
except Exception as e:
pass
try:
self.files_folders = os.listdir(self.abs_path)
except:
self.abs_path = '/'
self.files_folders = os.listdir(self.abs_path)
self.path_errors.error()
pass
data_list = []
for x in self.files_folders:
i = os.path.isdir(self.abs_path + '/' + x)
try:
s = os.path.getsize(self.abs_path + '/' + x)
except:
s = 0
s = human_readable_size(s, suffix="B")
if i == True:
i = '/'
else:
i = ''
data_list.append([i+x, s])
#sort list based on file names
data_list = sorted(data_list, key=lambda x:x[:1])
#insert an index
i = 1
for x in data_list:
x.insert(0,i)
i = i + 1
#turn data list into a dictionary
x = 0
self.data = dict()
self.data = {x[0]: x[1:] for x in data_list}
if self.abs_path == '/':
self.data[0] = ['/','']
else:
self.data[0] = ['..',''] | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def ssh_path_hist_func(self, ssh_path):
#since paramiko doesnt produce an absolute path, this creates a path
#history by appending and pop'ing an array as you move through the file
#structure
if ssh_path == '/':
self.par_dir = '/'
self.ssh_path = ssh_path
self.ssh_path_par_hist = ['/']
self.ssh_path_hist = ['/']
self.p = 0
pass
elif ssh_path.startswith('/'):
self.ssh_path = ssh_path.lstrip('.')
self.ssh_path_hist.append(ssh_path)
self.p +=1
self.ssh_path_par_hist = list(self.ssh_path_hist)
self.ssh_path_par_hist.pop()
self.par_dir = ''.join(map(str, self.ssh_path_par_hist))
elif ssh_path.startswith('.') and len(self.ssh_path_hist) > 1:
self.ssh_path_hist.pop(self.p)
self.p -=1
else:
self.par_dir = '/'
if len(self.ssh_path_par_hist) != 1:
self.ssh_path_par_hist.pop()
self.par_dir = ''.join(map(str, self.ssh_path_par_hist))
self.next_ssh_path = ''.join(map(str, self.ssh_path_hist))
def ssh_explorer_attr(self):
if glbl_opts.low_bandwidth == True:
s = 0
else:
self.ssh_files_folders_attr = ssh_obj.sftp.listdir_attr(
path=self.next_ssh_path)
size_list = []
for entry in self.ssh_files_folders_attr:
s = entry.st_size
return size_list
def ssh_get_abs_path(self, path):
try:
self.ssh_abs_path = ssh_obj.sftp.normalize(path)
except:
pass | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def ssh_explorer(self, ssh_path):
self.ssh_path_hist_func(ssh_path)
self.ssh_files_folders_dir = ssh_obj.sftp.listdir(
path=self.next_ssh_path
)
self.ssh_files_folders_attr = ssh_obj.sftp.listdir_attr(
path=self.next_ssh_path
)
self.ssh_get_abs_path(self.next_ssh_path)
item = 0
data_list = []
for x, entry in zip(self.ssh_files_folders_dir, self.ssh_files_folders_attr):
i = S_ISDIR(entry.st_mode)
s = entry.st_size
if i == True:
i = '/'
else:
i = ''
data_list.append([i+x, s])
item += 1
#sort list based on file names
data_list = sorted(data_list, key=lambda x:x[:1])
#insert an index and use the size function to make size human readable
i = 0
for x in data_list:
i += 1
x.insert(0,i)
s = human_readable_size(x[2], suffix="B")
x[2]=s
#turn data list into a dictionary
x = 0
self.data = dict()
self.data = {x[0]: x[1:] for x in data_list}
if self.abs_path == '/':
self.data[0] = ['/','']
else:
self.data[0] = ['..','']
def draw_pad(self):
self.pad = curses.newpad(self.height + 800, self.width) #size of pad
self.pad.scrollok(True)
self.pad.idlok(True)
self.pad.keypad(1)
self.pad.bkgd(curses.color_pair(4))
def select_item(self,mylist, x, v):
item_to_edit = mylist[x]
item_index = mylist.index(item_to_edit)
for index, item in enumerate(mylist):
itemlist = list(item)
if index == item_index:
itemlist[1] = v
item = tuple(itemlist)
mylist[index] = item
self.tup = mylist
return mylist | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def deselect_item(self,mylist, x, v):
item_to_edit = mylist[x]
item_index = mylist.index(item_to_edit)
for index, item in enumerate(mylist):
itemlist = list(item)
if index == item_index:
itemlist[1] = v
item = tuple(itemlist)
mylist[index] = item
self.tup = mylist
return mylist
def get_selected_items(self, tup):
new_list = []
i = -1
for ind, sel, item in tup:
if sel == '[x]':
i += 1
tups = tuple((i,item))
new_list.append(tups)
self.marked_item = self.path + '/' + new_list[0][1]
def del_selected_items(self, sel_file):
PopUpDelete(sel_file)
def copy_selected_items(self):
file_name = self.data[self.position][0]
left_panel_path = file_explorer_0.abs_path
right_panel_path = file_explorer_1.abs_path
if wins.active_panel == 0:
self.from_file = self.path + '/' + file_name
self.to_path = file_explorer_1.path
elif wins.active_panel == 1:
self.from_file = self.path + '/' + file_name
self.to_path = file_explorer_0.path
if self.position != 0:
PopUpCopyFile(stdscr, self.from_file, self.to_path, file_name)
def start_rsync(self):
file_name = self.data[self.position][0]
left_panel_path = file_explorer_0.abs_path
right_panel_path = file_explorer_1.ssh_abs_path
if wins.active_panel == 0:
self.from_file = left_panel_path + '/' + file_name
self.to_path = right_panel_path
elif wins.active_panel == 1:
self.from_file = right_panel_path + '/' + file_name
self.to_path = left_panel_path
if self.position != 0:
rsync_obj = RSync(0).start(self.from_file, self.to_path, file_name) | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def menu(self):
self.pad.erase()
self.height, self.width = self.window.getmaxyx()
self.screen_height, self.screen_width = self.screen.getmaxyx()
self.max_height = self.height -2
self.bottom = self.max_height #+ len(self.tup) #self.max_height
self.scroll_line = self.max_height - 3
self.pad.setscrreg(0,self.max_height) #self.bottom -2)
self.width = self.width - 2
self.pad_refresh = lambda: self.pad.noutrefresh(self.scroller,
0, self.start_y, self.start_x, self.bottom, self.screen_width -2)
#par = '[ ]' # can be added to the msg below to create a selector, likely to be removed
for index, items in self.data.items():
padding = self.width - len(items[0]) - 5
if index == self.position:
mode = curses.A_REVERSE
else:
mode = curses.A_NORMAL
try:
msg = f'{index:>3}{" "}{items[0]}{items[1]:>{padding}}'
except:
msg = f'{index:>3}{" "}{items[0]}'
self.pad.addstr(index, 0, str(msg), mode)
if mode == curses.A_REVERSE:
self.cursor = self.pad.getyx()[0]
self.pad_refresh()
def navigate(self, n):
self.position += n
if self.position < 0:
self.position = 0
elif self.position >= len(self.data):
self.position = len(self.data) - 1
def set_paths(self):
x = wins.active_panel
if x == 0:
oth_panel = 1
else:
oth_panel = 0
if self.new_path == None:
self.paths[x] = self.prev_paths[x].replace('//','/')
else:
self.prev_paths[x] = self.paths[x]
self.paths[oth_panel] = self.prev_paths[oth_panel] | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def display(self):
while True:
self.pad.keypad(1)
self.menu()
curses.doupdate()
KEY_PRESS = None
try:
#self.pad.keypad(1)
KEY_PRESS = self.pad.getch()
except KeyboardInterrupt:
KEY_PRESS = ord('q')
self.event = KEY_PRESS
break
if KEY_PRESS == ord("\n"):
if '/' in self.data[self.position][0]:
itsadir = True
else:
itsadir = False
if self.position != 0 and itsadir == True:
if ssh_obj.enabled == True and wins.active_panel == 1:
self.new_path = self.data[self.position][0] + '/'
else:
self.new_path = self.path + self.data[self.position][0] + '/'
self.cwd = self.new_path
#self.selected_path = self.path + self.data[self.position][0] + '/'
self.pad_refresh()
self.position = self.scroller = 0
#self.event = KEY_PRESS
self.paths[wins.active_panel] = self.new_path.replace('//','/')
self.set_paths()
self.explorer(self.new_path)
wins.upd_panel()
elif self.position != 0 and itsadir == False:
sel_file = self.path + '/' + self.data[self.position][0]
PopUpFileOpener(sel_file, KEY_PRESS,self.screen, None)
else:
self.cwd = self.new_path = self.par_dir
if ssh_obj.enabled == True and wins.active_panel == 1:
self.par_dir = '..'
self.set_paths()
self.explorer(self.par_dir)
wins.upd_panel()
elif KEY_PRESS == curses.KEY_UP: | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
wins.upd_panel()
elif KEY_PRESS == curses.KEY_UP:
self.navigate(-1)
if self.cursor > self.scroll_line:
self.scroller -= 1
if self.scroller == -1:
self.scroller = 0
if self.position == 0:
self.scroller = 0
elif KEY_PRESS == curses.KEY_DOWN:
self.navigate(1)
if len(self.data) == 1:
self.position = 0
elif self.cursor >= self.scroll_line:
if self.position != len(self.data):
self.scroller = self.cursor - self.scroll_line
elif KEY_PRESS == ord('n'):
popUpNewDir()
#elif KEY_PRESS == ord('m'):
# if self.position != 0:
# self.select_item(self.tup, self.position, '[x]')
#elif KEY_PRESS == ord('u'):
# if self.position != 0:
# self.deselect_item(self.tup, self.position, '[ ]')
#elif KEY_PRESS == ord ('g'):
# self.get_selected_items(self.tup)
elif KEY_PRESS == ord('b'):
self.position = len(self.data)-1
self.scroller = len(self.data) - self.scroll_line -1
elif KEY_PRESS == ord('t'):
self.position = 0
self.scroller = 0
elif KEY_PRESS == ord('9'):
self.del_selected_items(self.path + '/' + self.data[self.position][0])
elif KEY_PRESS == ord('5'):
if ssh_obj.enabled == False:
self.copy_selected_items()
reset_window(file_explorer_0)
reset_window(file_explorer_1)
elif ssh_obj.enabled == True:
self.start_rsync()
elif KEY_PRESS == ord('x') and ssh_obj.enabled == True: | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
elif KEY_PRESS == ord('x') and ssh_obj.enabled == True:
ssh_obj.ssh.close()
ssh_obj.enabled = False
wins.upd_panel()
file_explorer_1.explorer(file_explorer_1.path)
file_explorer_1.menu()
reset_window(file_explorer_1)
elif KEY_PRESS in(ord('f'), ord('o'), ord('q'), ord('\t')):
#status.refresh()
self.event = KEY_PRESS
break | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
Another example of this similiar structure but for the menubar drop downs...
class MenuBar(PopUpBase):
"""Creates the menubar
Used to create either the File or Options menu, draws a window depending
on if f or o is called.
"""
position = 0
sub_menu = ['ssh','rsync','exit']
sub_menu2 = ['settings']
menubarwindow = ''
def __init__(self):
stdscr.addstr(0,1, 'File Options', curses.A_NORMAL)
stdscr.noutrefresh()
def menubar_act(self, menu_event):
if menu_event == ord('f'):
super().__init__(10, 15, 1, 1)
#now using self.win from base
stdscr.addstr(0,1, 'File', curses.A_STANDOUT)
stdscr.addstr(0,4+2, 'Options', curses.A_NORMAL)
stdscr.noutrefresh()
self.menu_item = self.sub_menu
if menu_event == ord('o'):
super().__init__(10, 15, 1, 6)
stdscr.addstr(0,1, 'File', curses.A_NORMAL)
stdscr.addstr(0,4+2, 'Options', curses.A_STANDOUT)
stdscr.noutrefresh()
self.menu_item = self.sub_menu2
def menu(self):
#print list as basis for menu, the item selector is the A_REVERSE (highlighted) item
for index, item in enumerate(self.menu_item):
if index == self.position:
mode = curses.A_REVERSE
else:
mode = curses.A_NORMAL
self.win.addstr(1+ index, 1, item, mode)
self.win.noutrefresh()
curses.doupdate()
def noutrefresh(self):
stdscr.addstr(0,1, 'File Options', curses.A_NORMAL)
stdscr.noutrefresh()
def navigate(self, n):
self.position += n
if self.position < 0:
self.position = 0
elif self.position >= len(self.menu_item):
self.position = len(self.menu_item) - 1 | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
def display(self):
self.win.keypad(1)
while True:
self.menu()
### menuBar getch
ch = self.win.getch()
if ch == curses.KEY_UP:
self.navigate(-1)
if self.position < 0:
self.position = 0
elif ch == curses.KEY_DOWN:
if self.position >= 0 and self.position <= len(self.menu_item) - 1:
self.navigate(1)
elif ch == ord('\n') and self.menu_item[self.position] == 'ssh':
if ssh_obj.enabled is False:
self.win.erase()
del self.win
reset_window(file_explorer_0)
ssh_obj.start()
return 0
elif ch == ord('\n') and self.menu_item[self.position] == 'rsync':
self.win.erase()
del self.win
reset_window(file_explorer_0)
reset_window(file_explorer_1)
RSync('m')
return 0
elif ch == ord('\n') and self.menu_item[self.position] == 'settings':
self.win.erase()
del self.win
reset_window(file_explorer_0)
glbl_opts.display()
return 0
elif ch == ord('\n') and self.menu_item[self.position] == 'exit':
ch = ord('q')
return ch
elif ch in (ord('f'), ord('o'), ord('\t'), ord('q')):
stdscr.addstr(0,1, 'File', curses.A_NORMAL)
stdscr.addstr(0,4+2, 'Options', curses.A_NORMAL)
stdscr.noutrefresh()
curses.doupdate()
reset_window(file_explorer_0)
return ch | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
I'd like to make this more efficient, possibly relying on decorators but then I end up having to try and account for unique button presses depending on the "menu". I've used base classes for various pop up windows so I don't have to rewrite the same window multiple times and just call super() but again, I think I might be missing out on some deeper concepts in Python that can help me to improve the code/portability/reusability.
I've included a link to the full code below and am happy to share if you want to use it. The code is about 1500 lines so I did not think it would be smart to copy it all in.
https://github.com/1amdash/syncrpy-tui/blob/main/syncrpy-tui-55.py
Answer: The main problem with this code is that it's very hard to comprehend. This review will focus on this issue exclusively, not on the logic of the code itself. Once your code is more clean and 'pythonic' it will be much easier to see the problems with ssh channels, bandwidth, etc..
import os
import sys
import time
import curses
import io
import paramiko
import shutil
import threading
import subprocess
import shlex
import tempfile
from curses import panel, textpad
from stat import S_ISDIR, S_ISREG
from getpass import getpass
Give each class its own file and import only things you need in the current file. Don't use import and from ... import statements for the same module, it leads to confusion:
curses.doupdate() # ok, this is a function from curses module
textpad # and where did this come from? oh, it is also from curses | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
In fact none of the separately imported names (panel and textpad) are ever used on their own rendering the import line useless.
Let's jump to the end of the file:
...
menu = MenuBar()
wins = WinManager(stdscr)
start_path = os.path.curdir
window_0 = wins.left_panel()
window_1 = wins.right_panel()
window_0.noutrefresh()
window_1.noutrefresh()
ssh_obj = SSH()
file_explorer_0 = file_explorer(stdscr, window_0, start_path, False)
file_explorer_1 = file_explorer(stdscr, window_1, start_path, False)
file_explorer_0.menu()
file_explorer_1.menu()
paths = []
event = 0
i = 0
... | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
python, python-3.x, console, ssh, curses
We have some code that is supposed to run when you run the file. Use if __name__ == '__main__': construction for this purpose.
Let's read some lines from above.
menu = MenuBar()
So is it menu bar or just menu?
wins = WinManager(stdscr)
I can't tell what wins is supposed to mean by looking at the name.
window_0 = wins.left_panel()
window_1 = wins.right_panel()
What's the difference between window_0 and window_1? I can see it only at the assignment, nowhere else.
window_0.noutrefresh()
window_1.noutrefresh()
Can't make out what the method name says, use snake_case for names.
file_explorer_0 = file_explorer(stdscr, window_0, start_path, False)
Why is it 0?
What does this method do? Oh, wait it's a class constructor! Use CamelCase for class names.
What is False argument supposed to mean? Use named arguments for booleans and in other ambiguous cases, e.g. is_ssh=False in this case.
file_explorer_0.menu()
What does this method do?
Call methods according to what their actual purpose is.
paths = []
event = 0
i = 0
Once again, no idea what any of these variables are.
The main takeaway from this section: use proper naming. It makes code significantly more readable.
del window_0
del window_1
del status
Don't use del without a good reason, python has a garbage collector.
if ssh_obj.enabled == True: is equal to if ssh_obj.enabled:
try:
self.des_num = os.path.getsize(self.full_qual_dest_path)
self.des_size = human_readable_size(self.des_num)
except:
pass
Don't ever ignore exceptions like that. You're letting every possible error just pass unnoticed. I can't tell what the right way here is since I don't even know what exception you're expecting.
try:
self.des_num = int(float(os.path.getsize(self.full_qual_dest_path)))
self.des_size = human_readable_size(self.des_num)
except:
time.sleep(.05)
self.des_num = int(float(os.path.getsize(self.full_qual_dest_path)))
self.des_size = human_readable_size(self.des_num) | {
"domain": "codereview.stackexchange",
"id": 43973,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, ssh, curses",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.