text stringlengths 1 2.12k | source dict |
|---|---|
c++, object-oriented
os << "Fourth output contains port 4?: " << o4.contains(4) << '\n';
os << "Fourth output contains port 5?: " << o4.contains(5) << '\n';
}
The output of this example is:
Number of ports = 8
Iterating through ports:
this is port 1
this is port 2
this is port 3
this is port 4
this is port 5
this is port 6
this is port 7
this is port 8
Iterating through single outputs:
single output: {1}
single output: {2}
single output: {3}
single output: {4}
single output: {5}
single output: {6}
single output: {7}
single output: {8}
There are 8 ports and 8 outputs.
Iterating through combined outputs:
combined output: {1, 2}
combined output: {3, 4}
combined output: {5, 6}
combined output: {7, 8}
There are 8 ports and 4 outputs.
Iterating through mixed single/combined outputs:
single output: {1}
single output: {2}
combined output: {3, 4}
single output: {5}
single output: {6}
combined output: {7, 8}
There are 8 ports and 6 outputs.
Third output is combined output: {3, 4}
single output: {5}
Fourth output contains port 4?: false
Fourth output contains port 5?: true
I'm looking for feedback on all aspects of the design, though I'm particularly interested in feedback regarding the following:
Should Supply::Output::secondary() throw an exception when attempting to access a secondary port on a single-port output? Or return Supply::Output::no_port instead?
Should I provide a const_iterator for the outputs in addition to an iterator? Currently I just provide an iterator since code outside of Supply can't modify an Output.
Is Supply::Output::m_type useful or should I just determine whether the Output is single or combined on the fly by checking if the secondary port is set to Supply::Output::no_port?
Answer: This all looks pretty good. Not much to criticise here.
It's a good idea to include our own header first in the implementation file, to expose any missing includes that make it not self-sufficient.
const static port_number no_port = 0; | {
"domain": "codereview.stackexchange",
"id": 42747,
"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",
"url": null
} |
c++, object-oriented
const static port_number no_port = 0;
I get a linker error, because the storage is never defined. Use constexpr instead:
static constexpr port_number no_port = 0;
Supply::Output::Output constructors would be better if they initialised the members rather than assigning in the body:
Supply::Output::Output(Supply::port_number port1, Supply::port_number port2)
: ports{port1, port2},
m_type{combined}
{
}
Supply::Output::Output(port_number p)
: ports{p, no_port},
m_type{single}
{
}
Given this code:
if (p == no_port) m_type = single;
else m_type = combined;
We can probably dispense with the m_type member, and derive it when required:
Supply::Output::output_type Supply::Output::type() const
{
return ports.second == no_port ? single : combined;
}
Use this type() everywhere we previously accessed m_type (and preferably define it in the class definition, to make it more inlinable).
main() program is missing the header which declares std::boolalpha:
#include <iomanip> | {
"domain": "codereview.stackexchange",
"id": 42747,
"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",
"url": null
} |
c++, classes, coordinate-system
Title: C++ Vector3d class
Question: As part of a physics simulation written in C++ using SFML I needed a vector3d class.
Here is my implementation:
#include <cmath>
#include <ostream>
template <typename T>
class vector3d {
public:
T x{};
T y{};
T z{};
T norm() { return std::hypot(x, y, z); }
vector3d<T> unit() { return vector3d<T>(*this) / norm(); }
T dot(const vector3d<T>& RHS) { return x * RHS.x + y * RHS.y + z * RHS.z; }
vector3d<T> cross(const vector3d<T>& RHS) {
return vector3d<T>{y * RHS.z - z * RHS.y, z * RHS.x - x * RHS.z, x * RHS.y - y * RHS.x};
}
bool operator==(const vector3d<T>& rhs) {
return std::abs(x - rhs.x) < std::numeric_limits<T>::epsilon() &&
std::abs(y - rhs.y) < std::numeric_limits<T>::epsilon() &&
std::abs(z - rhs.z) < std::numeric_limits<T>::epsilon();
}
bool operator!=(const vector3d<T>& rhs) { return !(*this == rhs); }
// clang-format off
vector3d<T>& operator+=(vector3d<T> RHS) { x += RHS.x; y += RHS.y; z += RHS.z; return *this; }
vector3d<T>& operator-=(vector3d<T> RHS) { x -= RHS.x; y -= RHS.y; z -= RHS.z; return *this; }
vector3d<T>& operator*=(vector3d<T> RHS) { x *= RHS.x; y *= RHS.y; z *= RHS.z; return *this; }
vector3d<T>& operator/=(vector3d<T> RHS) { x /= RHS.x; y /= RHS.y; z /= RHS.z; return *this; }
vector3d<T>& operator*=(T s) { x *= s; y *= s; z *= s; return *this; }
vector3d<T>& operator/=(T s) { x /= s; y /= s; z /= s; return *this; }
friend vector3d<T> operator+(const vector3d<T>& LHS, const vector3d<T>& RHS) { return vector3d<T>(LHS) += RHS; }
friend vector3d<T> operator-(const vector3d<T>& LHS, const vector3d<T>& RHS) { return vector3d<T>(LHS) -= RHS; }
friend vector3d<T> operator*(const vector3d<T>& LHS, const vector3d<T>& RHS) { return vector3d<T>(LHS) *= RHS; }
friend vector3d<T> operator/(const vector3d<T>& LHS, const vector3d<T>& RHS) { return vector3d<T>(LHS) /= RHS; } | {
"domain": "codereview.stackexchange",
"id": 42748,
"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++, classes, coordinate-system",
"url": null
} |
c++, classes, coordinate-system
friend vector3d<T> operator*(const vector3d<T>& v, T s) { return vector3d<T>(v) *= s; }
friend vector3d<T> operator*(T s, const vector3d<T>& v) { return vector3d<T>(v) *= s; }
friend vector3d<T> operator/(const vector3d<T>& v, T s) { return vector3d<T>(v) /= s; }
// note that scalar / vector3d does not make any logical sense
// clang-format on
friend std::ostream& operator<<(std::ostream& os, vector3d<T> v) {
return os << "[" << v.x << ", " << v.y << ", " << v.z << "]";
}
};
using vec3 = vector3d<double>;
using vec3f = vector3d<float>;
using vec3l = vector3d<long double>;
And its potential usage:
#include "vector3d.h"
#include <iostream>
int main() {
vec3 z;
std::cout << "z = " << z << "\n";
auto a = vec3{1, 2, 3};
auto b = vec3{4, 5, 6};
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "a + b = " << a + b << "\n";
auto c = 2 * b;
std::cout << "c = " << c << "\n";
auto d = b * 2;
std::cout << "d = " << d << "\n";
auto e = b / 2;
std::cout << "e = " << e << "\n";
std::cout << "a.norm() = " << a.norm() << "\n";
std::cout << "a.unit() = " << a.unit() << "\n";
std::cout << "a.unit().norm() = " << a.unit().norm() << "\n";
std::cout << "[4, 8, 10] . [9, 2, 7] = " << vec3{4, 8, 10}.dot(vec3{9, 2, 7}) << "\n";
std::cout << "[1, 0, 0] x [0, 1, 0] = " << vec3{1, 0, 0}.cross(vec3{0, 1, 0}) << "\n";
std::cout << "[2, 3, 4] x [5, 6, 7] = " << vec3{2, 3, 4}.cross(vec3{5, 6, 7}) << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 42748,
"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++, classes, coordinate-system",
"url": null
} |
c++, classes, coordinate-system
}
I tried to "do as the ints do" and make all basic operators available.
I realise that +-*/ operators could be free functions but I preferred to write them as friends to avoid having to template every one of them. A valid style choice?
I realise that the dot() and cross() could be free functions, but preferred the a.cross(b) usage syntax.
Minor point: I chose to format the code to wider than normal as I believe it makes it more readable / makes the patterns more obvious.
I added some type aliases for convenience.
Is relying on aggregate initialisation (without any constructor) and the default copy constructor a good choice?
Any comments on the code and use of member / friend / free functions please?
Answer: This looks like a pretty good start. It compiles cleanly with a pedantic compiler, and the test program seems clean under Valgrind.
The first few members should not be modifying the object, so declare them const:
T norm() const { return std::hypot(x, y, z); }
vector3d unit() const { return vector3d{*this} / norm(); }
T dot(const vector3d& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }
vector3d cross(const vector3d& rhs) const {
return {y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x};
}
Note also that unqualified vector3d within the scope of vector3d<T> means vector3d<T>, so we get to remove some clutter here.
Do the * and / operations of two vectors have any useful mathematical meaning? I'd just omit these:
vector3d& operator*=(vector3d RHS) { x *= RHS.x; y *= RHS.y; z *= RHS.z; return *this; }
vector3d& operator/=(vector3d RHS) { x /= RHS.x; y /= RHS.y; z /= RHS.z; return *this; } | {
"domain": "codereview.stackexchange",
"id": 42748,
"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++, classes, coordinate-system",
"url": null
} |
c++, classes, coordinate-system
(Later) Having been informed that these are the rarely-needed Hadamard product and its inverse, it may be appropriate to retain the functionality, but as an ordinary (named) member function rather than as an operator. This will reduce the chance of accidental misuse.
Also, don't use all-caps names for locals or arguments - it's idiomatic to reserve those names for preprocessor macros.
The friend functions are probably okay for now, but lean towards non-friend non-member functions, as this won't require any change when you add implicit conversions (e.g. from vector3d<float> to vector3d<double>) in future.
We can avoid the explicit copy if we take one argument by value, which will cause an implicit copy:
template<typename T>
auto operator+(vector3d<T> lhs, const vector3d<T>& rhs) { return lhs += rhs; }
template<typename T>
auto operator-(vector3d<T> lhs, const vector3d<T>& rhs) { return lhs -= rhs; }
template<typename T>
auto operator*(vector3d<T> v, T s) { return v *= s; }
template<typename T>
auto operator*(T s, vector3d<T> v) { return v *= s; }
template<typename T>
auto operator/(vector3d<T> v, T s) { return v /= s; }
The streaming operator << should not be modifying its vector argument, so pass that as a const-ref. We can micro-optimise by passing single characters rather than one-character literal strings.
Consider adding == and !=. Since C++20, we can kill both birds with a single stone:
bool operator==(const vector3d<T>&) const = default;
Consider constraining the template so that only arithmetic types can be used as the type T. I don't think a vector of std::complex makes much sense, for example.
Modified code
#include <cmath>
#include <concepts>
#include <ostream>
template<typename T>
requires std::floating_point<T> or std::integral<T>
class vector3d
{
public:
T x{};
T y{};
T z{};
T norm() const { return std::hypot(x, y, z); }
vector3d unit() const { return vector3d{*this} / norm(); } | {
"domain": "codereview.stackexchange",
"id": 42748,
"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++, classes, coordinate-system",
"url": null
} |
c++, classes, coordinate-system
vector3d unit() const { return vector3d{*this} / norm(); }
T dot(const vector3d& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }
vector3d cross(const vector3d& rhs) const {
return {y * rhs.z - z * rhs.y, z * rhs.x - x * rhs.z, x * rhs.y - y * rhs.x};
}
bool operator==(const vector3d&) const = default;
vector3d& operator+=(const vector3d& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; }
vector3d& operator-=(const vector3d& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }
vector3d& operator*=(T s) { x *= s; y *= s; z *= s; return *this; }
vector3d& operator/=(T s) { x /= s; y /= s; z /= s; return *this; }
};
template<typename T> auto operator+(const vector3d<T>& v) { return v; }
template<typename T> auto operator-(const vector3d<T>& v) { return vector3d<T>{} - v; }
template<typename T> auto operator+(vector3d<T> lhs, const vector3d<T>& rhs) { return lhs += rhs; }
template<typename T> auto operator-(vector3d<T> lhs, const vector3d<T>& rhs) { return lhs -= rhs; }
template<typename T, typename U> auto operator*(vector3d<T> v, U s) { return v *= s; }
template<typename T, typename U> auto operator*(U s, vector3d<T> v) { return v *= s; }
template<typename T, typename U> auto operator/(vector3d<T> v, U s) { return v /= s; }
template<typename T> auto& operator<<(std::ostream& os, const vector3d<T>& v) {
return os << '[' << v.x << ", " << v.y << ", " << v.z << ']';
} | {
"domain": "codereview.stackexchange",
"id": 42748,
"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++, classes, coordinate-system",
"url": null
} |
javascript, promise, ecmascript-6
Title: Check if images are loaded (ES6 Promises)
Question: I wrote a small function that checks if an image or multiple images are loaded. For that purpose, I decided to use ES6 promises, but I'm not really sure if my way of handling errors is the best way.
const loadImg = function loadImg(src) {
'use strict';
const paths = Array.isArray(src) ? src : [src];
const promise = [];
paths.forEach((path) => {
promise.push(new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
path,
status: 'ok',
});
};
// Call `resolve` even if the image fails to load. If we were to
// call `reject`, the whole "system" would break
img.onerror = () => {
resolve({
path,
status: 'error',
});
};
img.src = path;
}));
});
return Promise.all(promise);
};
// Usage
loadImg([
'IMG.png',
'IMG.jpg',
'IMG.jpg',
'IMG.jpg',
]).then(function(e) {
console.log(e);
});
It works, but I'm worried that using objects as error messages rather than reject has some disadvantages that I'm not aware of (e.g. potential memory leaks or people don't expect to see errors in then())? Is there any way I can improve this function? | {
"domain": "codereview.stackexchange",
"id": 42749,
"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, promise, ecmascript-6",
"url": null
} |
javascript, promise, ecmascript-6
Answer: Well, you normally don't want to use the Promise constructor in your higher level code, you want to Promisify as low as possible. So let's create a function that checks for a single image, and resolves whenever you know the status of that image:
// When there's only one statement, you can drop the {} and the return
// x => y is equivalent to x => { return y; }
const checkImage = path =>
new Promise(resolve => {
const img = new Image();
img.onload = () => resolve({path, status: 'ok'});
img.onerror = () => resolve({path, status: 'error'});
img.src = path;
});
Now, with that Promise returning action, we can do some fancy things:
const loadImg = paths => Promise.all(paths.map(checkImage))
Or, if you want to get fancier
const loadImg = (...paths) => Promise.all(paths.map(checkImage));
// and call with
loadImg('path1', 'path2', 'path3');
// or
loadImg(...arrayOfPaths)
It's perfectly fine to not reject if there's no error. Yes, there was an error loading the image, but it isn't an exceptional situation, it's not something you'd throw because of. Your function is actually there to check if the image loaded fine or not. | {
"domain": "codereview.stackexchange",
"id": 42749,
"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, promise, ecmascript-6",
"url": null
} |
python, tkinter
Title: Periodic Table - Python and tkinter
Question: I posted an answer on StackOverflow about periodic table sometime back and ever since then I've been thinking about improving/optimizing it and worked up a completely different version of it that opens the wiki link once you click on any element. I have created 4 files:
load.py that loads the data from the csv file
widgets.py that has the classes with the custom widgets on it
main.py that takes all these files and put into a working form
data.csv with all the data in a csv format
I am not really sure on how I am supposed to paste these files here as I am not frequent in this community. I have uploaded this into a repo too. Anyway, I will include the code for the py files here and a link to the csv file from the repo.
widgets.py:
import tkinter as tk
import webbrowser
from load import read, color_dict
class Element(tk.Frame):
def __init__(self,master,element,*args,**kwargs):
tk.Frame.__init__(self,master,*args,**kwargs)
if not element.startswith('*'):
data = read(element).values.tolist()
symbol = data[0]
at_no = data[1]
at_ms = data[2]
e_type = data[3]
wiki = data[4]
color = self.find_color(e_type)
tk.Label(self,text=at_no,font=(0,10),bg=color,takefocus=0).pack(anchor='w')
tk.Label(self,text=symbol,font=(0,18,'bold'),bg=color,fg='white',takefocus=0).pack()
tk.Label(self,text=element,font=(0,9),bg=color,takefocus=0).pack()
tk.Label(self,text=at_ms,font=(0,7),bg=color,takefocus=0).pack() | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
self.bind('<Double-1>',lambda e: webbrowser.open(wiki))
for wid in self.children:
self.children.get(wid).bind('<Double-1>',lambda e: webbrowser.open(wiki))
else:
if element == '*':
text = 'Lanthanide'
color = self.find_color(text)
else:
text = 'Actinide'
color = self.find_color(text)
tk.Label(self,text=text,bg=color,font=(0,9)).pack(fill="both",expand=1)
tk.Label(self,text='89-103',font=(0,18,'bold'),bg=color,fg='white').pack(fill="both",expand=1)
tk.Label(self,text='(Check below)',bg=color,font=(0,8)).pack(fill="both",expand=1)
self['bg'] = color
self.config(width=100)
self.config(height=105)
self.pack_propagate(0)
def find_color(self,e_type):
return color_dict[e_type]
class Key(Element):
def __init__(self,master,e_type,*args,**kwargs):
tk.Frame.__init__(self,master,*args,**kwargs)
color = self.find_color(e_type)
psuedo_img = tk.PhotoImage(height=1,width=1)
tk.Label(self,image=psuedo_img,bg=color,height=15,width=15).pack(side='left')
tk.Label(self,text=e_type).pack()
class Demo(tk.Frame):
def __init__(self,master,e_type,*args,**kwargs):
tk.Frame.__init__(self,master,*args,**kwargs)
self['width'] = 500
self['height'] = 150
cnv = tk.Canvas(self)
cnv.pack()
wid = Element(self,element=e_type)
cnv.create_window(250,100,window=wid,tags='win') | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
wid = Element(self,element=e_type)
cnv.create_window(250,100,window=wid,tags='win')
x,y,x1,y1 = 150,60,200,60
cnv.create_line(x ,y ,x1 ,y1 ,arrow='last',tags='arrow')
cnv.create_line(x+150,y+40,x+200 ,y1+40,arrow='first',tags='arrow')
cnv.create_line(x ,y+65,x1 ,y1+65,arrow='last',tags='arrow')
cnv.create_line(x+150,y+85,x+200 ,y1+85,arrow='first',tags='arrow')
cnv.create_text(40,47,text='Atomic Number',anchor='nw')
cnv.create_text(355,90,text='Symbol',anchor='nw')
cnv.create_text(93,115,text='Element',anchor='nw')
cnv.create_text(355,132,text='Atomic Mass',anchor='nw')
self.pack_propagate(0)
if __name__ == '__main__':
root = tk.Tk()
Element(root,'Hydrogen').pack(padx=5,pady=20)
Key(root,e_type='Halogen').pack()
Demo(root,'Hydrogen').pack()
root.mainloop()
load.py:
import pandas as pd
df = pd.read_csv('data.csv',index_col=0)
df1 = pd.read_csv('data.csv')
elements = df1['Element'].values.tolist()
types = sorted(list(set(df1['Type'].values.tolist())))
def read(element: str):
data = df.loc[element]
return data
main_layout = [['x' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'x'],
['x' ,'x' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x']] | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
sec_layout = [['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x']]
color_dict = {'Nonmetal':'#feaa91',
'Noble Gas':'#ffe36b',
'Halogen':'#dadf23',
'Alkali Metal':'#fee0b3',
'Alkaline Earth Metal':'#fdc721',
'Metalloid':'#e79cf4',
'Transition Metal':'#77c3f6',
'Metal':'#ff9fc2',
'Lanthanide':'#39d8ab',
'Actinide':'#abdf4b',
'Unknown Properties':'#b2b3b2'}
main.py:
import tkinter as tk
from tkinter import ttk
from widgets import Element, Key, Demo
from load import main_layout, sec_layout, elements, types
root = tk.Tk()
root.title('Periodic Table')
# Frame for entire table
table = tk.Frame(root)
table.pack()
# Frame for main elements of table
main_tab = tk.Frame(table)
main_tab.pack()
# Frame for the key of the table
key_tab = ttk.LabelFrame(main_tab,text='Legend')
key_tab.grid(row=0,column=0,columnspan=10,rowspan=3)
# Frame for the demo widget
repr_tab = ttk.Frame(main_tab)
repr_tab.grid(row=0,column=5,columnspan=10,rowspan=3)
# Frame for secondary elements
sec_tab = tk.Frame(table)
sec_tab.pack()
# Heading
tk.Label(main_tab,text='Periodic Table',font=(0,21,'bold')).grid(row=0,column=3,columnspan=10) | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
# Loop through layout and place elements in the reserved locations
count = 0
for p,i in enumerate(main_layout):
for q,j in enumerate(i):
text = elements[count]
if j:
# For lanthides in between main table
if 56 <= count <= 70:
if count == 56:
text = '*'
else:
count = 71
text = elements[count]
# For actinoids in between main table
elif 88 <= count <= 103:
if count == 88:
text = '**'
else:
count = 103
text = elements[count]
Element(main_tab,element=text).grid(row=p,column=q,padx=2,pady=2)
count += 1
# Loop through secondary layout and place elements in the reserved locations
count = 56 # Start position of lantinides
for p,i in enumerate(sec_layout):
for q,j in enumerate(i):
text = elements[count]
# For Actinoids
if count >= 71:
text = elements[count+17]
Element(sec_tab,element=text).grid(row=p,column=q,padx=2,pady=2)
count += 1
# Placing the legend in 3x4 grid
for i in range(3):
for j in range(4):
if 4*i+j < len(types):
Key(key_tab,e_type=types[4*i+j]).grid(row=i+1,column=j,sticky='w',padx=5,pady=5)
# Placing the representation in the frame
Demo(repr_tab, elements[0]).grid(row=i,column=j+1,rowspan=5)
root.mainloop() | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
data.csv:
Element,Symbol,AtomicNumber,AtomicMass,Type,WikiLink
Hydrogen,H,1,1.007,Nonmetal,https://en.wikipedia.org/wiki/Hydrogen
Helium,He,2,4.002,Noble Gas,https://en.wikipedia.org/wiki/Helium
Lithium,Li,3,6.941,Alkali Metal,https://en.wikipedia.org/wiki/Lithium
Beryllium,Be,4,9.012,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Beryllium
Boron,B,5,10.811,Metalloid,https://en.wikipedia.org/wiki/Boron
Carbon,C,6,12.011,Nonmetal,https://en.wikipedia.org/wiki/Carbon
Nitrogen,N,7,14.007,Nonmetal,https://en.wikipedia.org/wiki/Nitrogen
Oxygen,O,8,15.999,Nonmetal,https://en.wikipedia.org/wiki/Oxygen
Fluorine,F,9,18.998,Halogen,https://en.wikipedia.org/wiki/Fluorine
Neon,Ne,10,20.18,Noble Gas,https://en.wikipedia.org/wiki/Neon
Sodium,Na,11,22.99,Alkali Metal,https://en.wikipedia.org/wiki/Sodium
Magnesium,Mg,12,24.305,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Magnesium
Aluminum,Al,13,26.982,Metal,https://en.wikipedia.org/wiki/Aluminum
Silicon,Si,14,28.086,Metalloid,https://en.wikipedia.org/wiki/Silicon
Phosphorus,P,15,30.974,Nonmetal,https://en.wikipedia.org/wiki/Phosphorus
Sulfur,S,16,32.065,Nonmetal,https://en.wikipedia.org/wiki/Sulfur
Chlorine,Cl,17,35.453,Halogen,https://en.wikipedia.org/wiki/Chlorine
Argon,Ar,18,39.948,Noble Gas,https://en.wikipedia.org/wiki/Argon
Potassium,K,19,39.098,Alkali Metal,https://en.wikipedia.org/wiki/Potassium
Calcium,Ca,20,40.078,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Calcium
Scandium,Sc,21,44.956,Transition Metal,https://en.wikipedia.org/wiki/Scandium
Titanium,Ti,22,47.867,Transition Metal,https://en.wikipedia.org/wiki/Titanium
Vanadium,V,23,50.942,Transition Metal,https://en.wikipedia.org/wiki/Vanadium
Chromium,Cr,24,51.996,Transition Metal,https://en.wikipedia.org/wiki/Chromium
Manganese,Mn,25,54.938,Transition Metal,https://en.wikipedia.org/wiki/Manganese
Iron,Fe,26,55.845,Transition Metal,https://en.wikipedia.org/wiki/Iron
Cobalt,Co,27,58.933,Transition Metal,https://en.wikipedia.org/wiki/Cobalt | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
Cobalt,Co,27,58.933,Transition Metal,https://en.wikipedia.org/wiki/Cobalt
Nickel,Ni,28,58.693,Transition Metal,https://en.wikipedia.org/wiki/Nickel
Copper,Cu,29,63.546,Transition Metal,https://en.wikipedia.org/wiki/Copper
Zinc,Zn,30,65.38,Transition Metal,https://en.wikipedia.org/wiki/Zinc
Gallium,Ga,31,69.723,Metal,https://en.wikipedia.org/wiki/Gallium
Germanium,Ge,32,72.64,Metalloid,https://en.wikipedia.org/wiki/Germanium
Arsenic,As,33,74.922,Metalloid,https://en.wikipedia.org/wiki/Arsenic
Selenium,Se,34,78.96,Nonmetal,https://en.wikipedia.org/wiki/Selenium
Bromine,Br,35,79.904,Halogen,https://en.wikipedia.org/wiki/Bromine
Krypton,Kr,36,83.798,Noble Gas,https://en.wikipedia.org/wiki/Krypton
Rubidium,Rb,37,85.468,Alkali Metal,https://en.wikipedia.org/wiki/Rubidium
Strontium,Sr,38,87.62,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Strontium
Yttrium,Y,39,88.906,Transition Metal,https://en.wikipedia.org/wiki/Yttrium
Zirconium,Zr,40,91.224,Transition Metal,https://en.wikipedia.org/wiki/Zirconium
Niobium,Nb,41,92.906,Transition Metal,https://en.wikipedia.org/wiki/Niobium
Molybdenum,Mo,42,95.96,Transition Metal,https://en.wikipedia.org/wiki/Molybdenum
Technetium,Tc,43,98.0,Transition Metal,https://en.wikipedia.org/wiki/Technetium
Ruthenium,Ru,44,101.07,Transition Metal,https://en.wikipedia.org/wiki/Ruthenium
Rhodium,Rh,45,102.906,Transition Metal,https://en.wikipedia.org/wiki/Rhodium
Palladium,Pd,46,106.42,Transition Metal,https://en.wikipedia.org/wiki/Palladium
Silver,Ag,47,107.868,Transition Metal,https://en.wikipedia.org/wiki/Silver
Cadmium,Cd,48,112.411,Transition Metal,https://en.wikipedia.org/wiki/Cadmium
Indium,In,49,114.818,Metal,https://en.wikipedia.org/wiki/Indium
Tin,Sn,50,118.71,Metal,https://en.wikipedia.org/wiki/Tin
Antimony,Sb,51,121.76,Metalloid,https://en.wikipedia.org/wiki/Antimony
Tellurium,Te,52,127.6,Metalloid,https://en.wikipedia.org/wiki/Tellurium
Iodine,I,53,126.904,Halogen,https://en.wikipedia.org/wiki/Iodine | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
Iodine,I,53,126.904,Halogen,https://en.wikipedia.org/wiki/Iodine
Xenon,Xe,54,131.293,Noble Gas,https://en.wikipedia.org/wiki/Xenon
Cesium,Cs,55,132.905,Alkali Metal,https://en.wikipedia.org/wiki/Cesium
Barium,Ba,56,137.327,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Barium
Lanthanum,La,57,138.905,Lanthanide,https://en.wikipedia.org/wiki/Lanthanum
Cerium,Ce,58,140.116,Lanthanide,https://en.wikipedia.org/wiki/Cerium
Praseodymium,Pr,59,140.908,Lanthanide,https://en.wikipedia.org/wiki/Praseodymium
Neodymium,Nd,60,144.242,Lanthanide,https://en.wikipedia.org/wiki/Neodymium
Promethium,Pm,61,145.0,Lanthanide,https://en.wikipedia.org/wiki/Promethium
Samarium,Sm,62,150.36,Lanthanide,https://en.wikipedia.org/wiki/Samarium
Europium,Eu,63,151.964,Lanthanide,https://en.wikipedia.org/wiki/Europium
Gadolinium,Gd,64,157.25,Lanthanide,https://en.wikipedia.org/wiki/Gadolinium
Terbium,Tb,65,158.925,Lanthanide,https://en.wikipedia.org/wiki/Terbium
Dysprosium,Dy,66,162.5,Lanthanide,https://en.wikipedia.org/wiki/Dysprosium
Holmium,Ho,67,164.93,Lanthanide,https://en.wikipedia.org/wiki/Holmium
Erbium,Er,68,167.259,Lanthanide,https://en.wikipedia.org/wiki/Erbium
Thulium,Tm,69,168.934,Lanthanide,https://en.wikipedia.org/wiki/Thulium
Ytterbium,Yb,70,173.054,Lanthanide,https://en.wikipedia.org/wiki/Ytterbium
Lutetium,Lu,71,174.967,Lanthanide,https://en.wikipedia.org/wiki/Lutetium
Hafnium,Hf,72,178.49,Transition Metal,https://en.wikipedia.org/wiki/Hafnium
Tantalum,Ta,73,180.948,Transition Metal,https://en.wikipedia.org/wiki/Tantalum
Wolfram,W,74,183.84,Transition Metal,https://en.wikipedia.org/wiki/Wolfram
Rhenium,Re,75,186.207,Transition Metal,https://en.wikipedia.org/wiki/Rhenium
Osmium,Os,76,190.23,Transition Metal,https://en.wikipedia.org/wiki/Osmium
Iridium,Ir,77,192.217,Transition Metal,https://en.wikipedia.org/wiki/Iridium
Platinum,Pt,78,195.084,Transition Metal,https://en.wikipedia.org/wiki/Platinum
Gold,Au,79,196.967,Transition Metal,https://en.wikipedia.org/wiki/Gold | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
Gold,Au,79,196.967,Transition Metal,https://en.wikipedia.org/wiki/Gold
Mercury,Hg,80,200.59,Transition Metal,https://en.wikipedia.org/wiki/Mercury
Thallium,Tl,81,204.383,Metal,https://en.wikipedia.org/wiki/Thallium
Lead,Pb,82,207.2,Metal,https://en.wikipedia.org/wiki/Lead
Bismuth,Bi,83,208.98,Metal,https://en.wikipedia.org/wiki/Bismuth
Polonium,Po,84,210.0,Metal,https://en.wikipedia.org/wiki/Polonium
Astatine,At,85,210.0,Halogen,https://en.wikipedia.org/wiki/Astatine
Radon,Rn,86,222.0,Noble Gas,https://en.wikipedia.org/wiki/Radon
Francium,Fr,87,223.0,Alkali Metal,https://en.wikipedia.org/wiki/Francium
Radium,Ra,88,226.0,Alkaline Earth Metal,https://en.wikipedia.org/wiki/Radium
Actinium,Ac,89,227.0,Actinide,https://en.wikipedia.org/wiki/Actinium
Thorium,Th,90,232.038,Actinide,https://en.wikipedia.org/wiki/Thorium
Protactinium,Pa,91,231.036,Actinide,https://en.wikipedia.org/wiki/Protactinium
Uranium,U,92,238.029,Actinide,https://en.wikipedia.org/wiki/Uranium
Neptunium,Np,93,237.0,Actinide,https://en.wikipedia.org/wiki/Neptunium
Plutonium,Pu,94,244.0,Actinide,https://en.wikipedia.org/wiki/Plutonium
Americium,Am,95,243.0,Actinide,https://en.wikipedia.org/wiki/Americium
Curium,Cm,96,247.0,Actinide,https://en.wikipedia.org/wiki/Curium
Berkelium,Bk,97,247.0,Actinide,https://en.wikipedia.org/wiki/Berkelium
Californium,Cf,98,251.0,Actinide,https://en.wikipedia.org/wiki/Californium
Einsteinium,Es,99,252.0,Actinide,https://en.wikipedia.org/wiki/Einsteinium
Fermium,Fm,100,257.0,Actinide,https://en.wikipedia.org/wiki/Fermium
Mendelevium,Md,101,258.0,Actinide,https://en.wikipedia.org/wiki/Mendelevium
Nobelium,No,102,259.0,Actinide,https://en.wikipedia.org/wiki/Nobelium
Lawrencium,Lr,103,262.0,Actinide,https://en.wikipedia.org/wiki/Lawrencium
Rutherfordium,Rf,104,261.0,Transition Metal,https://en.wikipedia.org/wiki/Rutherfordium
Dubnium,Db,105,262.0,Transition Metal,https://en.wikipedia.org/wiki/Dubnium | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
Dubnium,Db,105,262.0,Transition Metal,https://en.wikipedia.org/wiki/Dubnium
Seaborgium,Sg,106,266.0,Transition Metal,https://en.wikipedia.org/wiki/Seaborgium
Bohrium,Bh,107,264.0,Transition Metal,https://en.wikipedia.org/wiki/Bohrium
Hassium,Hs,108,267.0,Transition Metal,https://en.wikipedia.org/wiki/Hassium
Meitnerium,Mt,109,268.0,Transition Metal,https://en.wikipedia.org/wiki/Meitnerium
Darmstadtium,Ds,110,271.0,Transition Metal,https://en.wikipedia.org/wiki/Darmstadtium
Roentgenium,Rg,111,272.0,Transition Metal,https://en.wikipedia.org/wiki/Roentgenium
Copernicium,Cn,112,285.0,Transition Metal,https://en.wikipedia.org/wiki/Copernicium
Nihonium,Nh,113,284.0,Metal,https://en.wikipedia.org/wiki/Nihonium
Flerovium,Fl,114,289.0,Metal,https://en.wikipedia.org/wiki/Flerovium
Moscovium,Mc,115,288.0,Metal,https://en.wikipedia.org/wiki/Moscovium
Livermorium,Lv,116,292.0,Metal,https://en.wikipedia.org/wiki/Livermorium
Tennessine,Ts,117,295.0,Halogen,https://en.wikipedia.org/wiki/Tennessine
Oganesson,Og,118,294.0,Noble Gas,https://en.wikipedia.org/wiki/Oganesson | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
Output:
I am still learning, so thanks for all the suggestions :)
Answer: Let's start with what I think will be the easiest bit: the data format of your save-files.
CSV
Csv is quite old and not very common nowadays. I'd say most Python developers use json most of the time, but also yaml, toml, and xml are common. That would convert your "database" from
Element,Symbol,AtomicNumber,AtomicMass,Type,WikiLink
Hydrogen,H,1,1.007,Nonmetal,https://en.wikipedia.org/wiki/Hydrogen
...
to
[
{
"Element": "Hydrogen",
"Symbol": "H",
"Atomic Number": 1,
"Atomic Mass": 1.007,
"Type": "Nonmetal",
"Wiki Link": "https://en.wikipedia.org/wiki/Hydrogen"
},
...
]
which is way more readable, and will be very easy to deal with in Python. For example:
>>> import json
>>> with open("elements.json", "r") as f:
... data = json.load(f)
...
>>> data
[{'Element': 'Hydrogen', 'Symbol': 'H', 'Atomic Number': 1, 'Atomic Mass': 1.007, 'Type': 'Nonmetal', 'Wiki Link': 'https://en.wikipedia.org/wiki/Hydrogen'}, {'Element': 'Carbon'}]
Now, as you can see this is essentially the same data structure in Python as it is in json. So I'm gonna make my own life a little easier and just keep this as a variable in a Python-file for now, but you don't have to do that.
Structure and requirements
I think that your application should be packaged. How you'd typically structure a Python package is like this:
.
βββ README.rst
βββ periodic_table
β βββ __init__.py
β βββ elements.py
β βββ loader.py
β βββ widgets.py
βββ requirements.txt
1 directory, 6 files
One thing is that it displays purpose - you can see that all of these files are part of the package periodic_table. It also creates a namespace. The file __init__.py will also mean that you can refer to the modules in this package by changing from
from widgets import Element, Key, Demo
to
from periodic_table.widgets import Element, Demo, Key | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
to
from periodic_table.widgets import Element, Demo, Key
and now the reader immediately knows where these functions come from. Personally I think that an even better suggestion is:
from periodic_table import widgets
# and then use widgets.Element, etc.
But I concede that I don't abide by this strongly.
But that's not packaged!
I cheated a little just now - I showed a directory with just a requirements.txt file. Better than this would be to configure the package. I'll be modern and will skip setup.py, and I will also be very minimal with the metadata. We now have:
.
βββ README.rst
βββ periodic_table
β βββ __init__.py
β βββ elements.py
β βββ loader.py
β βββ widgets.py
βββ pyproject.toml
βββ setup.cfg
1 directory, 7 files
pyproject.toml
You can consider this file "boilerplate code" for packages and just copy the content without deeper understanding (for now).
[build-system]
requires = [
"setuptools>=42",
"wheel"
]
build-backend = "setuptools.build_meta"
setup.cfg
This is where you define all your metadata for the package. It doesn't all matter if you just want to make it installable, but if you wanted to publish something on PyPI you should make some effort.
[metadata]
name = periodic-table
version = 1.0.0
[options]
packages = find:
python_requires = >=3.6
setup_requires =
wheel
install_requires =
tkinter
pandas
[options.entry_points]
console_scripts =
show-periodic-table = periodic_table:main | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
[options.entry_points]
console_scripts =
show-periodic-table = periodic_table:main
With all of this done, your package would be installable with pip! You can then from the directory just type pip install . and the package periodic_table would be installed in that environment. And this also allows us to define commands to call on certain functions!
And this sort of segways us into the next point - your current entry-point is confusing.
if __name__ == "__main__": and other tings
When I look at your filenames my interpretation is that main.py is the entry-point, yet at the bottom of widgets.py you have:
if __name__ == '__main__':
root = tk.Tk()
Element(root,'Hydrogen').pack(padx=5,pady=20)
Key(root,e_type='Halogen').pack()
Demo(root,'Hydrogen').pack()
root.mainloop()
Here I can clearly see that widgets.py is "executable" (interpretable?) and that this file is intended to start a tkinter loop. I'm guessing that this just an artifact from when you first learnt to use tkinter, but this is basically what we should have done in your main.py file, so let's do that.
main.py
The point behind having if __name__ == "__main__": is that it means that the code wrapped in that condition only will be called upon if the current file is executed directly, like this:
$ python3 main.py # We want this to run our program
But not be loaded if the module is imported, like this:
from periodic_table import main # We do not want this to run our program
Entry-points
What I did in setup.cfg (go back and have a look at the end of the file) is to also set up an additional way to call on your program. The lines
console_scripts =
show-periodic-table = periodic_table:main | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
declare that there should be an alias set that you can use from your shell (on Linux and macOS, not sure how this works from PowerShell and others) called show-periodic-table, and that this should call on the function main in periodic_table/__init__.py. You could also call the function show_periodic_table and place it in widgets.py if you wanted to - in that case the line would be show-periodic-table = periodic_table.widgets:show_periodic_table.
To fit your code with this, we only really have to rename main.py into __init__.py, add like two lines, and indent most of the existing lines. I will, however, make one other tiny change just to try and keep the code almost working. We can keep widgets.py exactly as it is today, but remember how I mentioned I'd just store the otherwise-json data in a variable? That allows me to get rid of the loader while also simplifying packaging (I'm not gonna explain what I mean - this review has to end some time today...). So we have:
.
βββ README.rst
βββ periodic_table
β βββ __init__.py
β βββ constants.py
β βββ widgets.py
βββ pyproject.toml
βββ setup.cfg
1 directory, 6 files
constants.py
ELEMENTS = [
{
"Element": "Hydrogen",
"Symbol": "H",
"Atomic Number": 1,
"Atomic Mass": 1.007,
"Type": "Nonmetal",
"Wiki Link": "https://en.wikipedia.org/wiki/Hydrogen"
},
...
]
SEC_LAYOUT = [['x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x' ,'x'],
...
]
...
__init__.py
This is now where we have our entry point. I've left it called just main, but an even more fitting name would probably be show_periodic_table.
import tkinter as tk
from tkinter import ttk
from periodic_table.widgets import Element, Key, Demo
from periodic_table.constants import MAIN_LAYOUT, SEC_LAYOUT, ELEMENTS, TYPES
def main():
root = tk.Tk()
root.title('Periodic Table')
# Frame for entire table
table = tk.Frame(root)
table.pack()
... | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
python, tkinter
# Frame for entire table
table = tk.Frame(root)
table.pack()
...
# Placing the representation in the frame
Demo(repr_tab, elements[0]).grid(row=i,column=j+1,rowspan=5)
root.mainloop()
And I think I'll let that wrap this session up. The code would need some other modifications to work entirely (since we now already have a list of element dictionaries instead of having to load from csv), but I'll leave that for you to figure out. | {
"domain": "codereview.stackexchange",
"id": 42750,
"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, tkinter",
"url": null
} |
c++, beginner, linked-list, memory-management
Title: Simple Singly-Linked List class
Question: Decided to write something simple and came up with idea to write simple single linked list in C++ to improve my knowledge about pointers and memory management in C++, and wrote this:
#include <iostream>
void pause() {
std::cout << '\n' << "Press <Enter> to continue...";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
//std::cin.get(); // Use when not debug
} // PAUSE
namespace LinkedList {
class LinkedList {
private:
int m_value{};
LinkedList* m_next{ nullptr };
public:
LinkedList(int value = 0) : m_value{ value } {}
void Add(int value) {
if (!m_next) { m_next = new LinkedList{ value }; } // If it's the last element then add
else { m_next->Add(value); } // And if not go up in linked list
}
void Delete(int value) {
if (m_next->m_value == value) {
LinkedList* tmp_ptr{ m_next->m_next };
delete m_next; m_next = tmp_ptr; return;
} // If next value equals the value to delete then redirect the current element to element, after that, we search for
if (!m_next) { return; } // If no element after, return
else { m_next->Delete(value); } // If we can go upper, go
}
LinkedList* Find(int value) {
if (m_value == value) { return this; } // If found return pointer to it
else if (m_next) { m_next->Find(value); } // If still can go up, go
else { return nullptr; } // If not found and nowhere to go up return nullptr
} // Return a pointer to element which contains certain number
friend std::ostream& operator<<(std::ostream& os, LinkedList list);
}; | {
"domain": "codereview.stackexchange",
"id": 42751,
"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++, beginner, linked-list, memory-management",
"url": null
} |
c++, beginner, linked-list, memory-management
std::ostream& operator<<(std::ostream& os, LinkedList element) {
while (true) {
os << element.m_value << " ";
if (!element.m_next) { return os; } // If it's a last element then return
else { element = *element.m_next; } // If not go up
}
}
}
int main() {
LinkedList::LinkedList test{ };
int input{};
while (std::cin >> input) { test.Add(input); } // Ask for input until cin fails
std::cout << test;
pause();
return 0;
}
Is this any good or it could have been written better?
Answer:
class LinkedList {
private:
LinkedList* m_next{ nullptr };
This raw-pointer data member needs some care. We need to ensure that the memory is correctly released in the destructor, and dealt with carefully in the copy and assignment methods. I see no such care in this class, and expect to see memory leakage and/or double-free bugs until that's fixed.
We can simplify the while loop in the operator <<. Instead of while (true) with a break inside, we can make it easier to read by using a real condition:
friend std::ostream& operator<<(std::ostream& os, const LinkedList& element) {
for (auto *e = &element; e; e = e->next) {
os << e->m_value << " ";
}
return os;
}
Notice that here we pass a reference to a const element, rather than a value. We should also have a const version of Find(), so we can work with read-only objects.
A few of the member functions traverse the list using recursion. This can be problematic, because long lists may lead to stack overflow (C++ doesn't mandate tail-call elimination). Prefer to iterate over the list for these operations. | {
"domain": "codereview.stackexchange",
"id": 42751,
"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++, beginner, linked-list, memory-management",
"url": null
} |
javascript, regex
Title: Remove unwanted characters at the end of a string
Question: I want to make this code better , its works now, but i think it can be better , i have a hook and one property is onChange that get value and can setState and return that value for value of input , in the middle of code , i should check two regex and if is not valid skip the setState and return that .
onChange: (value) => {
const validRegex = /^[\u0600-\u06EF\s]+$/;
if (!validRegex.test(value)) {
const regex1 = /[a-zA-Z0-9]/g;
const regex2 = /[\u06F0-\u06F9]+$/;
return value.replace(regex1, '').replace(regex2, '');
}
setData((prev) => ({
...prev,
name: value,
}));
return value;
},
<input value={data.name} onChange={(e) => onChange(e.target.value)} />
I replace , because i dont want miss text that user wrote. ,
example: value : This is name 1234 ===> result : This is name | {
"domain": "codereview.stackexchange",
"id": 42752,
"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, regex",
"url": null
} |
javascript, regex
Answer: Firstly, regular expression constants are better be placed outside of component function. Otherwise they get recreated each change event.
Second, is there a purpose of changing value? If we enter the if statement, we will not change the state, so it will affect nothing. And we don't need to return value; in the end, too.
Third, in current configuration there is no need to have regex2, because if we get a string \u0600\u06F0, which is a letter and a number (if I understand correctly), we will remove the number later. If it's \u06F0\u0600, a reversed one, we won't remove it. Though anyway, in the end it doesn't matter, because operations inside the if statement won't change the state.
Fourth, we check for /^[\u0600-\u06EF\s]+$/. Because of the + in the end we can't have an empty string. I don't know if it's by design, but if we have only 1 letter, we can't delete it, we can only select it and type another letter to replace it, which may not be convenient.
In the end, the version of code that I see fitting the task is:
// arabic letters and signs without numbers
const validRegex = /^[\u0600-\u06EF\s]+$/;
const MyComponent = () => {
// ...
onChange: (value) => validRegex.test(value)
&& setData((prev) => ({ ...prev, name: value }));
// ...
}
Please correct me if needed | {
"domain": "codereview.stackexchange",
"id": 42752,
"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, regex",
"url": null
} |
c++, pointers, atomic
Title: Implementation of std::atomic> for C++20
Question: As you may know, C++20 has added std::atomic<std::shared_ptr<T>> specialization to the standard, but sadly, most compilers have not implemented it yet. So I decided to implement it myself.
I want to know if I can improve this code or not. In addition, I'm not sure if my implementations of wait(), notify_one() and notify_all() are correct using condition variable.
#include <atomic>
#include <memory>
#include <condition_variable>
#include <thread>
#include <version>
#if !defined(__cpp_lib_atomic_shared_ptr) || (__cpp_lib_atomic_shared_ptr == 0)
namespace std {
template<typename T>
struct atomic<shared_ptr<T>> {
using value_type = shared_ptr<T>;
static constexpr bool is_always_lock_free = false;
bool is_lock_free() const noexcept {
return false;
}
constexpr atomic() noexcept {};
atomic(shared_ptr<T> desired) noexcept : ptr_(std::move(desired)) {};
atomic(const atomic&) = delete;
void operator=(const atomic&) = delete;
void store(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept {
std::lock_guard<std::mutex> lk(cv_m_);
atomic_store_explicit(&ptr_, std::move(desired), order);
}
void operator=(shared_ptr<T> desired) noexcept {
store(std::move(desired));
}
shared_ptr<T> load(memory_order order = memory_order::seq_cst) const noexcept {
return atomic_load_explicit(&ptr_, order);
}
operator shared_ptr<T>() const noexcept {
return load();
}
shared_ptr<T> exchange(shared_ptr<T> desired, memory_order order = memory_order::seq_cst) noexcept {
return atomic_exchange_explicit(&ptr_, std::move(desired), order);
} | {
"domain": "codereview.stackexchange",
"id": 42753,
"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++, pointers, atomic",
"url": null
} |
c++, pointers, atomic
bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired,
memory_order success, memory_order failure) noexcept {
return atomic_compare_exchange_weak_explicit(&ptr_, &expected, std::move(desired), success, failure);
}
bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired,
memory_order success, memory_order failure) noexcept {
return atomic_compare_exchange_strong_explicit(&ptr_, &expected, std::move(desired), success, failure);
}
bool compare_exchange_weak(shared_ptr<T>& expected, shared_ptr<T> desired,
memory_order order = memory_order::seq_cst) noexcept {
return compare_exchange_weak(expected, std::move(desired), order, convert_order(order));
}
bool compare_exchange_strong(shared_ptr<T>& expected, shared_ptr<T> desired,
memory_order order = memory_order::seq_cst) noexcept {
return compare_exchange_strong(expected, std::move(desired), order, convert_order(order));
}
void wait(shared_ptr<T> old, memory_order order = memory_order::seq_cst) const noexcept {
std::unique_lock<std::mutex> lk(cv_m_);
cv_.wait(lk, [&]{ return !(load(order) == old); });
}
void notify_one() noexcept {
cv_.notify_one();
}
void notify_all() noexcept {
cv_.notify_all();
}
private:
shared_ptr<T> ptr_;
mutable std::condition_variable cv_;
mutable std::mutex cv_m_;
constexpr memory_order convert_order(memory_order order) {
switch(order) {
case std::memory_order_acq_rel:
return std::memory_order_acquire;
case std::memory_order_release:
return std::memory_order_relaxed;
default:
return order;
}
}
};
}
#endif
int main() {
std::atomic<std::shared_ptr<int>> a;
} | {
"domain": "codereview.stackexchange",
"id": 42753,
"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++, pointers, atomic",
"url": null
} |
c++, pointers, atomic
}
#endif
int main() {
std::atomic<std::shared_ptr<int>> a;
}
I will be happy about your suggestions. Thanks in advance.
Answer: Simple things:
operator= should would normally return *this rather than void:
atomic& operator=(value_type desired) noexcept {
store(std::move(desired));
return *this;
}
But it seems that the standard actually requires void return here, so the implementation is correct.
Default construction should initialize members:
private:
value_type ptr_= {};
mutable std::condition_variable cv_ = {};
mutable std::mutex cv_m_= {};
Since we're writing for C++20, we can take advantage of class template argument deduction to simplify, e.g.
std::lock_guard lk{cv_m_};
I don't like the name of convert_order(). I might call it something like order_without_release(), to be more specific about why it's used. Yes, it's a private function, but it's still important to keep it clear.
Similarly, I'd name the success and failure arguments more explicitly - perhaps success_mem_order etc.?
I think that convert_order ought to be constexpr static, since it doesn't use *this.
Our implementation is not lock-free:
static constexpr bool is_always_lock_free = false;
bool is_lock_free() const noexcept {
return false;
}
A library implementation with access to internals of shared-pointer might be able to avoid that, but we can't. Still, it's better than no implementation at all.
Otherwise, this looks pretty good. We should be able to use a very similar implementation to provide std::shared_ptr<std::weak_ptr<T>>, too. | {
"domain": "codereview.stackexchange",
"id": 42753,
"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++, pointers, atomic",
"url": null
} |
python, python-3.x, functional-programming
Title: Functools extension library
Question: I wrote a utility library inspired by functools that adds some common operations on functions I frequently use in my projects.
As usual I'd appreciate any feed back.
functoolsplus.py
"""More higher-order functions and operations on callable objects."""
from dataclasses import dataclass
from time import perf_counter
from functools import wraps
from sys import exit, stderr # pylint: disable=W0622
from typing import Any, Callable, IO, Optional, Union
__all__ = [
'coerce',
'exiting',
'exitmethod',
'instance_of',
'timeit',
'wants_instance'
]
Decorator = Callable[[Callable[..., Any]], Callable[..., Any]]
@dataclass
class PerfCounter:
"""Performance counter."""
start: Optional[float] = None
end: Optional[float] = None
on_exit: Optional[Callable[..., Any]] = None
def __enter__(self):
self.start = perf_counter()
return self
def __exit__(self, typ, value, traceback):
self.end = perf_counter()
if self.on_exit is None:
return None
if len(self.on_exit.__code__.co_varnames) == 1:
return self.on_exit(self)
return self.on_exit()
@property
def duration(self) -> float:
"""Return the duration."""
return self.end - self.start
class exitmethod: # pylint: disable=C0103
"""Decorator class to create a context manager,
having the passed function as exit method.
"""
def __init__(self, function: Callable[..., Any]):
self.function = function
def __enter__(self):
return self
def __exit__(self, typ, value, traceback):
if wants_instance(self.function):
return self.function(self, typ, value, traceback)
return self.function(typ, value, traceback)
def coerce(typ: type) -> Callable[..., Any]:
"""Converts the return value into the given type.""" | {
"domain": "codereview.stackexchange",
"id": 42754,
"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, functional-programming",
"url": null
} |
python, python-3.x, functional-programming
def decorator(function: Callable[..., Any]) -> Callable[..., typ]:
"""Decorates the given function."""
@wraps(function)
def wrapper(*args, **kwargs) -> typ:
"""Wraps the respective function."""
return typ(function(*args, **kwargs))
wrapper.__annotations__['return'] = typ
return wrapper
return decorator
def exiting(function: Callable[..., Any]) -> Callable[..., Any]:
"""Makes a function exit the program with its return code."""
@wraps(function)
def wrapper(*args, **kwargs) -> Any:
"""Wraps the respective function."""
result = function(*args, **kwargs)
exit(result or 0)
return wrapper
def instance_of(cls: Union[type, tuple[type]]) -> Callable[[Any], bool]:
"""Returns a callback function to check the instance of an object."""
return lambda obj: isinstance(obj, cls)
def timeit(file: IO = stderr, flush: bool = False) -> Decorator:
"""Times the execution of the given function."""
def print_duration(
function: Callable[..., Any]
) -> Callable[[PerfCounter], None]:
"""Prints a perf counter."""
def inner(ctr: PerfCounter) -> None:
print('Function', function.__name__, 'took', ctr.duration,
file=file, flush=flush)
return inner
def decorator(function: Callable[..., Any]) -> Callable[..., Any]:
"""The actual decorator."""
@wraps(function)
def wrapper(*args, **kwargs):
"""Wraps the original function."""
with PerfCounter(on_exit=print_duration(function)):
return function(*args, **kwargs)
return wrapper
return decorator
def wants_instance(function: Callable[..., Any]) -> bool:
"""Determines whether the respective function is considered a method."""
try:
return function.__code__.co_varnames[0] == 'self'
except IndexError:
return False | {
"domain": "codereview.stackexchange",
"id": 42754,
"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, functional-programming",
"url": null
} |
python, python-3.x, functional-programming
Usage examples
The following code are example use cases, to get an idea, how the library utilities are meant to be used.
from time import sleep
from typing import Iterator
import functoolsplus # Change accordingly
with functoolsplus.PerfCounter() as ctr:
sleep(3)
print('Performace countner:', ctr, ctr.duration)
@functoolsplus.exitmethod
def value_error_guard(typ, value, traceback):
if isinstance(value, ValueError):
print('Doing stuff with ValueError:', value)
return True
with value_error_guard:
raise ValueError('Darn it.')
@functoolsplus.coerce(frozenset)
def get_squares(n: int) -> Iterator[int]:
"""Yields square numbers from 0 to n-1."""
for number in range(n):
yield number ** 2
input('Press enter to view help(get_squares):')
help(get_squares)
print('Squares:', get_squares(5))
NUMBERS = [1, 2, 3.0, 4, 5, 6.2, '42']
INTEGERS = filter(functoolsplus.instance_of(int), NUMBERS)
print('Numbers:', *NUMBERS)
print('Integers:', *INTEGERS)
@functoolsplus.timeit(flush=True)
def timed_sleep(seconds: float) -> None:
return sleep(seconds)
timed_sleep(3)
class Foo:
def foo(self) -> int:
return 42
@classmethod
def bar(cls):
return cls()
@staticmethod
def spamm():
pass
print('Foo.foo() wants instance:', functoolsplus.wants_instance(Foo.foo))
print('Foo.bar() wants instance:', functoolsplus.wants_instance(Foo.bar))
print('Foo.spamm() wants instance:', functoolsplus.wants_instance(Foo.spamm))
@functoolsplus.exiting
def main(exit_code: int) -> int:
print('Exiting with exit code:', exit_code)
return exit_code
main(42) | {
"domain": "codereview.stackexchange",
"id": 42754,
"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, functional-programming",
"url": null
} |
python, python-3.x, functional-programming
print('Exiting with exit code:', exit_code)
return exit_code
main(42)
Answer: I don't find PerfCounter to be well-modelled as a class. start and end aren't valid on construction, which should be a red flag. The current contract also allows for the calling user to initialise start and end themselves, which doesn't make sense; so even if this were to be modelled as a class it shouldn't be a @dataclass. The more natural calling pattern is, I think, a plain function that accepts a function reference, calls it, and returns a float - which already exists, and is called timeit (not your timeit; the built-in timeit). On that note, probably not a good idea to overlap with that name. P.S.: why support a callback? If you're already decorating code, you have access to the part of the code immediately after execution, so why not... just do something there, instead of registering a callback?
Anything that depends on want_instance is a symptom of non-ideal application design. You should already know whether everything is an instance method or not. | {
"domain": "codereview.stackexchange",
"id": 42754,
"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, functional-programming",
"url": null
} |
c++, matrix, classes
Title: Barebones C++ Matrix class
Question: I have implemented a C++ Matrix class using std::vector and a number for rows/cols. The implementation works decently from the QA I've done. I have implemented a Vector class as a derived class but I'm unsure whether this implementation is optimal. Would it make more sense to make Vector the base class and Matrix the derived class with Vector being just m_data and Matrix adding m_nrow and m_ncol?
Any general feedback more than welcome.
matrix.h:
#pragma once
#include <vector>
class Vector;
class Matrix
{
protected:
size_t m_nrow{};
size_t m_ncol{};
std::vector<double> m_data{};
public:
Matrix(const size_t nrow = 0, const size_t ncol = 0, const std::vector<double>& data = std::vector<double>{});
void clear();
void setElement(const double value, const size_t row_idx, const size_t col_idx);
void setElement(const double value, const size_t idx);
void removeRow(const size_t row_idx);
void removeCol(const size_t col_idx);
double& at(const size_t row_idx, const size_t col_idx);
double& at(const size_t idx);
double getElement(const size_t row_idx, const size_t col_idx) const;
double getElement(const size_t idx) const;
const std::vector<double>& getDataAsVector() const;
size_t nRow() const;
size_t nCol() const;
void print() const;
bool isSquare() const;
void operator+=(const Matrix& other_matrix);
void operator-=(const Matrix& other_matrix);
void operator*=(const double multiplier);
const Matrix operator+(const Matrix& other_matrix) const;
const Matrix operator-(const Matrix& other_matrix) const;
const Matrix operator*(const double multiplier) const;
const Matrix operator*(const Matrix& other_matrix) const;
const Vector operator*(const Vector& other_vector) const;
double operator[](const size_t idx) const;
};
class Vector : public Matrix
{
private:
using Matrix::isSquare; //hide this from the Vector class | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
public:
Vector(const std::vector<double>& data = std::vector<double>{});
double length() const;
double dotProduct(const Vector& other_vector) const;
double distanceTo(const Vector& other_vector) const;
const Vector operator+(const Vector& other_vector) const;
const Vector operator-(const Vector& other_vector) const;
const Vector operator*(const double multiplier) const;
};
matrix.cpp:
#include "matrix.h"
#include <iostream>
Matrix::Matrix(const size_t nrow, const size_t ncol, const std::vector<double>& data) //constructor, called when an object is created, don't include default vars here
: m_nrow{ nrow }, m_ncol{ ncol }, m_data{ data }
{
if ((nrow * ncol) != data.size())
throw std::invalid_argument("Data size does not match the dimensions!");
if ((nrow == 0 && ncol > 0) || (nrow > 0 && ncol == 0))
throw std::invalid_argument("One dimension is zero while the other one is not!");
}
void Matrix::clear()
{
m_nrow = 0;
m_ncol = 0;
m_data.clear();
}
void Matrix::setElement(const double value, const size_t row_idx, const size_t col_idx)
{
if (row_idx >= m_nrow || col_idx >= m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
m_data.at(row_idx * m_ncol + col_idx) = value;
}
void Matrix::setElement(const double value, const size_t idx)
{
if (idx >= m_nrow * m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
m_data.at(idx) = value;
}
void Matrix::removeRow(const size_t row_idx)
{
if (row_idx >= m_nrow)
throw std::invalid_argument("Index exceeds dimensions!");
else if (m_nrow == 1)
{
m_nrow = 0;
m_ncol = 0;
m_data.clear();
}
else
{
size_t idx_start{ row_idx * m_ncol };
m_data.erase(std::next(m_data.begin(), idx_start), std::next(m_data.begin(), idx_start + m_ncol));
m_nrow--; | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
if ((m_nrow * m_ncol) != m_data.size())
throw std::invalid_argument("Data size does not match the dimensions!");
}
}
void Matrix::removeCol(const size_t col_idx)
{
if (col_idx >= m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
else if (m_ncol == 1)
{
m_nrow = 0;
m_ncol = 0;
m_data.clear();
}
else
{
size_t idx_from_back{ (m_nrow - 1) * m_ncol + col_idx };
for (size_t i{ 0 }; i < m_nrow; i++)
{
m_data.erase(m_data.begin() + idx_from_back);
idx_from_back -= m_ncol;
}
m_ncol--;
if ((m_nrow * m_ncol) != m_data.size())
throw std::invalid_argument("Data size does not match the dimensions!");
}
}
double& Matrix::at(const size_t row_idx, const size_t col_idx)
{
if (row_idx >= m_nrow || col_idx >= m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
return m_data.at(row_idx * m_ncol + col_idx);
}
double& Matrix::at(const size_t idx)
{
if (idx >= m_nrow * m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
return m_data.at(idx);
}
double Matrix::getElement(const size_t row_idx, const size_t col_idx) const
{
if (row_idx >= m_nrow || col_idx >= m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
return m_data.at(row_idx * m_ncol + col_idx);
}
double Matrix::getElement(const size_t idx) const
{
if (idx >= m_nrow * m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
return m_data.at(idx);
}
const std::vector<double>& Matrix::getDataAsVector() const
{
return m_data;
}
size_t Matrix::nRow() const
{
return m_nrow;
}
size_t Matrix::nCol() const
{
return m_ncol;
} | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
size_t Matrix::nCol() const
{
return m_ncol;
}
void Matrix::print() const
{
std::cout << "Nrow: " << m_nrow << " Ncol: " << m_ncol << '\n';
std::cout << "Size: " << m_data.size() << " Capacity: " << m_data.capacity() << '\n';
size_t idx{ 0 };
for (size_t i{ 0 }; i < m_nrow; i++)
{
for (size_t j{ 0 }; j < m_ncol; j++)
{
std::cout << m_data.at(idx) << ' ';
idx++;
}
std::cout << '\n';
}
std::cout << '\n';
}
bool Matrix::isSquare() const
{
return (m_nrow == m_ncol);
}
void Matrix::operator+=(const Matrix& other_matrix)
{
if (m_ncol != other_matrix.m_ncol || m_nrow != other_matrix.m_nrow)
throw std::invalid_argument("Matrices have different dimensions!");
for (size_t i{ 0 }; i < m_data.size(); i++)
{
m_data.at(i) += other_matrix.m_data.at(i);
}
}
void Matrix::operator-=(const Matrix& other_matrix)
{
if (m_ncol != other_matrix.m_ncol || m_nrow != other_matrix.m_nrow)
throw std::invalid_argument("Matrices have different dimensions!");
for (size_t i{ 0 }; i < m_data.size(); i++)
{
m_data.at(i) -= other_matrix.m_data.at(i);
}
}
void Matrix::operator*=(const double multiplier)
{
for (size_t i{ 0 }; i < m_data.size(); i++)
{
m_data.at(i) *= multiplier;
}
}
const Matrix Matrix::operator+(const Matrix& other_matrix) const
{
if (m_ncol != other_matrix.m_ncol || m_nrow != other_matrix.m_nrow)
throw std::invalid_argument("Matrices have different dimensions!");
Matrix result{ *this };
result += other_matrix;
return result;
}
const Matrix Matrix::operator-(const Matrix& other_matrix) const
{
if (m_ncol != other_matrix.m_ncol || m_nrow != other_matrix.m_nrow)
throw std::invalid_argument("Matrices have different dimensions!");
Matrix result{ *this };
result -= other_matrix;
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
const Matrix Matrix::operator*(const double multiplier) const
{
Matrix result{ *this };
result *= multiplier;
return result;
}
const Matrix Matrix::operator*(const Matrix& other_matrix) const
{
if (m_ncol != other_matrix.m_nrow)
throw std::invalid_argument("Matrices are not compatible for multiplication!");
size_t sum_over{ m_ncol };
size_t nrow{ m_nrow };
size_t ncol{ other_matrix.m_ncol };
Matrix result{ nrow, ncol, std::vector<double>(nrow * ncol) };
for (size_t i{ 0 }; i < nrow; i++)
{
for (size_t j{ 0 }; j < ncol; j++)
{
double element_value{ 0.0 };
for (size_t k{ 0 }; k < sum_over; k++)
{
element_value += this->getElement(i, k) * other_matrix.getElement(k, j);
}
result.setElement(element_value, i, j);
}
}
return result;
}
const Vector Matrix::operator*(const Vector& other_vector) const
{
if (m_ncol != other_vector.m_nrow)
throw std::invalid_argument("Matrices are not compatible for multiplication!");
size_t sum_over{ m_ncol };
size_t nrow{ m_nrow };
std::vector<double> result(nrow);
for (size_t i{ 0 }; i < nrow; i++)
{
double element_value{ 0.0 };
for (size_t k{ 0 }; k < sum_over; k++)
{
element_value += this->getElement(i, k) * other_vector.getElement(k);
}
result.at(i) = element_value;
}
return Vector{ result };
}
double Matrix::operator[](const size_t idx) const
{
if (idx >= m_nrow * m_ncol)
throw std::invalid_argument("Index exceeds dimensions!");
return m_data.at(idx);
}
Vector::Vector(const std::vector<double>& data)
: Matrix{ data.size(), (data.size() == 0) ? 0 : 1, data }
{
} | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
double Vector::length() const
{
if (m_data.size() == 0)
throw std::invalid_argument("Vector is empty!");
double sum_of_squares{ 0.0 };
for (size_t i{ 0 }; i < m_data.size(); i++)
{
sum_of_squares += m_data.at(i) * m_data.at(i);
}
return std::sqrt(sum_of_squares);
}
double Vector::dotProduct(const Vector& other_vector) const
{
if (m_data.size() != other_vector.m_data.size())
throw std::invalid_argument("Vector don't have the same dimension!");
else if (m_data.size() == 0)
throw std::invalid_argument("Vectors are empty!");
double sum{ 0.0 };
for (size_t i{ 0 }; i < m_data.size(); i++)
{
sum += m_data.at(i) * other_vector.m_data.at(i);
}
return sum;
}
double Vector::distanceTo(const Vector& other_vector) const //const functions can be used by const class members
{
if (m_data.size() != other_vector.m_data.size())
throw std::invalid_argument("Vector don't have the same dimension!");
else if (m_data.size() == 0)
throw std::invalid_argument("Vectors are empty!");
double sum_of_squares{ 0.0 };
for (size_t i{ 0 }; i < m_data.size(); i++)
{
sum_of_squares += (m_data.at(i) - other_vector.m_data.at(i)) * (m_data.at(i) - other_vector.m_data.at(i));
}
return std::sqrt(sum_of_squares);
}
const Vector Vector::operator+(const Vector& other_vector) const
{
if (m_nrow != other_vector.m_nrow)
throw std::invalid_argument("Vectors have different dimensions!");
Vector result{ *this };
result += other_vector;
return result;
}
const Vector Vector::operator-(const Vector& other_vector) const
{
if (m_nrow != other_vector.m_nrow)
throw std::invalid_argument("Vectors have different dimensions!");
Vector result{ *this };
result -= other_vector;
return result;
}
const Vector Vector::operator*(const double multiplier) const
{
Vector result{ *this };
result *= multiplier;
return result;
} | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
Answer: The code looks correct at first glance.
History
These days it is very hard to compete with any serious implementation of matrix operations and general BLAS. Blaze, Eigen, uBLAS, armadillo and the rest already put years into making their libraries create fast code for modern hardware. I will not mention any performance related aspects, as the submitted code doesn't seem to implement any optimizations.
I believe that every piece of code should be written with a purpose in mind. It is very hard to justify writing a BLAS library today without having any aspects that would be favorable compared to the competition.
Interface
The interface review will be from my computer vision background.
Not so compatible with OpenCV
Yes, I can write &m.at(0, 0), but I would much prefer to write m.data(). The latter follows the general convention of returning value_type*.
Only double
I cannot use this matrix to pass into any C related functions to read images, as they take char* or the like. The usual choice would be float rather than double for further processing.
Unusual function names
FYI, multidimensional subscript operator was voted into standard, so it might be worth it to provide the new subscript operator circa 2023. The old code uses function call operator to provide subscript support. There is also quite a bit of duplication in terms of functionality with no benefit. Not being able to use .at() on a const object would also upset quite a few users.
Unnecessary checks
It would be better to write assert rather than if. Nobody will use a BLAS library that does bounds checking on every access.
Unidirectional vector
I would like different names for column vector and row vector. Those are really matrices with one of the dimensions being set to 1.
No fixed size support | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
No fixed size support
Providing a fixed size support would fix the unidirectional vector problem, as one dimension could be fixed and the rest be something like constexpr inline std::size_t dynamic_extent = std::numeric_limits<std::size_t>::max(); or straight up use the one from std. | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
c++, matrix, classes
If I would start a BLAS library today, I would probably write with SYCL or CUDA in mind. Those two are designed for this kind of data parallel computations in mind. | {
"domain": "codereview.stackexchange",
"id": 42755,
"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++, matrix, classes",
"url": null
} |
python, python-3.x
Title: for loop Optimization
Question: I have a sample Json as mentioned below
[{
"Name": "Kim",
"Details": {
"Age": 43,
"Gender": "Male",
"Education": [{
"Primary": "Xavier",
"Percentage": 90,
"subject": [{
"sub": "Math",
"Perf": "Good"
},
{
"sub": "Sci",
"Perf": "Averge"
}, {
"sub": "Eco",
"Perf": "Good"
}
],
"Marks": [{
"Mark": 90,
"Grade": "A"
},
{
"Mark": 92,
"Grade": "S"
}, {
"Mark": 80,
"Grade": "B"
}
]
},
{
"Seconday": "Anthony",
"Percentage": 98,
"subject": [{
"sub": "Math",
"Perf": "Good"
}],
"Marks": [{
"Mark": 100,
"Grade": "S"
}]
},
{
"Bachelor": "Boston",
"Percentage": 90,
"subject": [{
"sub": "Computers",
"Perf": "Good"
}],
"Marks": [{
"Mark": 90,
"Grade": "A"
}]
},
{ | {
"domain": "codereview.stackexchange",
"id": 42756,
"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",
"url": null
} |
python, python-3.x
"PostGrad": "Boston",
"Percentage": 90,
"subject": [{
"sub": "CNN",
"Perf": "Good"
}],
"Marks": [{
"Mark": 90,
"Grade": "A"
}]
}]
}
}]
form this I need to fetch the sub and Mark only from the entire Json.
I got the necessary output but the concern is I have utilised multiple for loops, below mentioned is my approch to fetch sub and marks,
import json
sampleJson = open('C:\\Users\\SampleJson.json')
sampleJsonData = json.loads(sampleJson.read())
resArray=[]
for i in range(len(sampleJsonData)):
for j in range(len(sampleJsonData[i]["Details"])):
for k in range(len(sampleJsonData[i]["Details"]["Education"])):
for l in range(len(sampleJsonData[i]["Details"]["Education"])):
for y in range(len(sampleJsonData[i]["Details"]["Education"][l]["subject"])):
sub = (sampleJsonData[i]["Details"]["Education"][l]["subject"][y]["sub"])
for z in range(len(sampleJsonData[i]["Details"]["Education"][l]["Marks"])):
marks = sampleJsonData[i]["Details"]["Education"][l]["Marks"][z]["Mark"]
by any means is there any possibility that I could reduce the usage of for loops to nil.
I need to use those sub and Mark values further, as a temp measure stored the values in different variables.
I'm relatively very new to python, Please help me on this. Thanks
Answer: At a wild guess, it seems like you want to perform a flattening operation. Your current code definitely hasn't done it correctly, and it's not even clear what "correct" is; but if you
replace your loads with a load;
use a with on your file;
get rid of all your numerical indices, and
use a nested list comprehension on your dictionary,
you can produce a list of subject-mark tuples:
from pprint import pprint
import json | {
"domain": "codereview.stackexchange",
"id": 42756,
"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",
"url": null
} |
python, python-3.x
you can produce a list of subject-mark tuples:
from pprint import pprint
import json
with open('272857.json') as sample_json:
sample_json_data = json.load(sample_json)
res_array = [
(subject['sub'], marks['Mark'])
for person in sample_json_data
for education in person['Details']['Education']
for subject, marks in zip(education['subject'], education['Marks'])
]
pprint(res_array)
produces
[('Math', 90),
('Sci', 92),
('Eco', 80),
('Math', 100),
('Computers', 90),
('CNN', 90)]
I can only assume that it's OK for this to throw out all other information about what education and person the mark came from, etc.
[could I] reduce the usage of for loops to nil
No. Either you, or a library you call, is going to need to loop. | {
"domain": "codereview.stackexchange",
"id": 42756,
"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",
"url": null
} |
python, python-3.x, console
Title: The user-facing part of the code base, using Python's argparse package
Question: This question is a sequel to one I asked the other day. The previous question examined the core of my repo; this one examines the user-facing part. If you're curious to see what the repo as a whole is trying to achieve, feel free to check out the previous question, but it shouldn't be necessary for the purposes of this one.
As mentioned above, Python's argparse is front and centre in the below code. This is literally the first time that I've used this package. The code seems to be working exactly as intended, but I'd like to check that I'm not ugly or painful in terms of style.
"""
This code serves as the entry point to this package.
"""
# Standard imports.
import argparse
# Local imports.
from git_credentials import set_up_git_credentials
from hm_software_installer import \
HMSoftwareInstaller, \
DEFAULT_OS, \
DEFAULT_TARGET_DIR, \
DEFAULT_PATH_TO_WALLPAPER_DIR, \
DEFAULT_PATH_TO_GIT_CREDENTIALS, \
DEFAULT_PATH_TO_PAT, \
DEFAULT_GIT_USERNAME, \
DEFAULT_EMAIL_ADDRESS, \
DEFAULT_PYTHON_VERSION | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
# Constants.
ARGUMENTS = [
{
"name": "--os",
"default": DEFAULT_OS,
"dest": "this_os",
"help": "A string giving the OS in use on this system",
"type": str
}, {
"name": "--email-address",
"default": DEFAULT_EMAIL_ADDRESS,
"dest": "email_address",
"help": "Your email address",
"type": str
}, {
"name": "--git-username",
"default": DEFAULT_GIT_USERNAME,
"dest": "git_username",
"help": "Your Git username",
"type": str
}, {
"name": "--path-to-git-credentials",
"default": DEFAULT_PATH_TO_GIT_CREDENTIALS,
"dest": "path_to_git_credentials",
"help": "The path to the Git credentials file",
"type": str
}, {
"name": "--path-to-pat",
"default": DEFAULT_PATH_TO_PAT,
"dest": "path_to_pat",
"help": "The path to the Personal Access Token file",
"type": str
}, {
"name": "--path-to-wallpaper-dir",
"default": DEFAULT_PATH_TO_WALLPAPER_DIR,
"dest": "path_to_wallpaper_dir",
"help": (
"The path to the directory where the wallpaper images are held"
),
"type": str
}, {
"name": "--pip-version",
"default": DEFAULT_PYTHON_VERSION,
"dest": "pip_version",
"help": (
"The version of PIP you wish to use on this device"
),
"type": int
}, {
"name": "--python-version",
"default": DEFAULT_PYTHON_VERSION,
"dest": "python_version",
"help": (
"The (integer) version of Python you wish to use on this device"
),
"type": int
}, {
"name": "--target-dir",
"default": DEFAULT_TARGET_DIR,
"dest": "target_dir",
"help": (
"The path to the directory into which we're going to install stuff"
),
"type": str
}, {
"name": "--thunderbird-num", | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
),
"type": str
}, {
"name": "--thunderbird-num",
"default": None,
"dest": "thunderbird_num",
"help": "The Thunderbird number for this device",
"type": int
}
]
BOOLEAN_ARGUMENTS = [
{
"name": "--reset-git-credentials-only",
"action": "store_true",
"default": False,
"dest": "reset_git_credentials_only",
"help": "Reset the Git credentials, but perform no installations"
}
] | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
####################
# HELPER FUNCTIONS #
####################
def add_boolean_arguments(parser):
""" Add the Boolean flags to the parser object. """
for argument in BOOLEAN_ARGUMENTS:
parser.add_argument(
argument["name"],
action=argument["action"],
default=argument["default"],
dest=argument["dest"],
help=argument["help"]
)
def make_parser():
""" Ronseal. """
result = argparse.ArgumentParser(description="Parser for HMSS")
for argument in ARGUMENTS:
result.add_argument(
argument["name"],
default=argument["default"],
dest=argument["dest"],
help=argument["help"],
type=argument["type"]
)
add_boolean_arguments(result)
return result
def make_installer_obj(arguments):
""" Ronseal. """
result = \
HMSoftwareInstaller(
this_os=arguments.this_os,
target_dir=arguments.target_dir,
thunderbird_num=arguments.thunderbird_num,
path_to_git_credentials=arguments.path_to_git_credentials,
path_to_pat=arguments.path_to_pat,
git_username=arguments.git_username,
email_address=arguments.email_address,
path_to_wallpaper_dir=arguments.path_to_wallpaper_dir
)
return result
def run_git_credentials_function(arguments):
set_up_git_credentials(
username=arguments.git_username,
email_address=arguments.email_address,
path_to_git_credentials=arguments.path_to_git_credentials,
path_to_pat=arguments.path_to_pat
)
###################
# RUN AND WRAP UP #
###################
def run():
""" Run this file. """
parser = make_parser()
arguments = parser.parse_args()
if arguments.reset_git_credentials_only:
run_git_credentials_function(arguments)
else:
installer = make_installer_obj(arguments)
installer.run() | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
if __name__ == "__main__":
run() | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
Answer: I am not convinced, that using dicts to initialize the argument parser is sensible. Do you need the dicts anywhere else? If not, why not just pass the data in the dicts to the argument parser's methods directly, i.e. why have them in the first place?
But if you insist on doing this, you can use dict unpacking to remove unneccessary code:
ARGUMENTS = [
{
"name": "--os",
"default": DEFAULT_OS,
"dest": "this_os",
"help": "A string giving the OS in use on this system",
"type": str
}, {
"name": "--email-address",
"default": DEFAULT_EMAIL_ADDRESS,
"dest": "email_address",
"help": "Your email address",
"type": str
}, {
"name": "--git-username",
"default": DEFAULT_GIT_USERNAME,
"dest": "git_username",
"help": "Your Git username",
"type": str
}, {
"name": "--path-to-git-credentials",
"default": DEFAULT_PATH_TO_GIT_CREDENTIALS,
"dest": "path_to_git_credentials",
"help": "The path to the Git credentials file",
"type": str
}, {
"name": "--path-to-pat",
"default": DEFAULT_PATH_TO_PAT,
"dest": "path_to_pat",
"help": "The path to the Personal Access Token file",
"type": str
}, {
"name": "--path-to-wallpaper-dir",
"default": DEFAULT_PATH_TO_WALLPAPER_DIR,
"dest": "path_to_wallpaper_dir",
"help": (
"The path to the directory where the wallpaper images are held"
),
"type": str
}, {
"name": "--pip-version",
"default": DEFAULT_PYTHON_VERSION,
"dest": "pip_version",
"help": (
"The version of PIP you wish to use on this device"
),
"type": int
}, {
"name": "--python-version",
"default": DEFAULT_PYTHON_VERSION,
"dest": "python_version",
"help": ( | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
"default": DEFAULT_PYTHON_VERSION,
"dest": "python_version",
"help": (
"The (integer) version of Python you wish to use on this device"
),
"type": int
}, {
"name": "--target-dir",
"default": DEFAULT_TARGET_DIR,
"dest": "target_dir",
"help": (
"The path to the directory into which we're going to install stuff"
),
"type": str
}, {
"name": "--thunderbird-num",
"default": None,
"dest": "thunderbird_num",
"help": "The Thunderbird number for this device",
"type": int
},
{
"name": "--reset-git-credentials-only",
"action": "store_true",
"default": False,
"dest": "reset_git_credentials_only",
"help": "Reset the Git credentials, but perform no installations"
}
] | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
python, python-3.x, console
####################
# HELPER FUNCTIONS #
####################
def make_parser():
""" Ronseal. """
result = argparse.ArgumentParser(description="Parser for HMSS")
for argument in ARGUMENTS:
result.add_argument(
argument.pop("name"),
**argument
)
return result | {
"domain": "codereview.stackexchange",
"id": 42757,
"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",
"url": null
} |
javascript, node.js
Title: High CPU and memory usage iterating over 300K objects
Question: I am trying to run a series of keywords against a series of categories and then within those categories there are some options. So I have ended up doing a forEach over for of over a every method and when dealing with a lot of entries node consumes way too much memory.
When dealing with 300K objects from a 29MB csv converted to JSON file and processed, pm2 monitor says node peaks to 4GB RAM usage and 200% CPU is this normal?
Here is an example of the code with a minial data sample
const keywords = [
{
Keyword: 'foo',
URL: 'https://www.facebook.co.uk'
},
{
Keyword: 'foo',
URL: 'https://www.twitter.co.uk/blue'
},
{
Keyword: 'faa',
URL: 'https://www.facebook.co.uk/twitter'
},
{
Keyword: 'faa',
URL: 'https://www.apple.co.uk/green'
}
]
const categories = [
{
name: 'Tech',
options: [
{
method: 'include',
regex: 'facebook'
},
{
method: 'exclude',
regex: 'twitter'
}
]
},
{
name: 'Green',
options: [
{
method: 'include',
regex: 'green'
}
]
}
]
keywords.forEach((obj) =>
categories.forEach(({name, options}) =>
obj[name] = options.every(({method, regex}) => method === 'include' ? obj.URL.includes(regex) : !obj.URL.includes(regex))))
console.log(keywords)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: Performance
Whenever possible avoid strings. Why ?
JS strings are immutable
Passing a string to a function or assigning it to a variable requires the string to be copied[*1]. This adds a lot of processing overhead (memory processing, (assignment, and GC), and string iteration) which can be avoided.
[*1] See update at bottom of answer.
For example using your function | {
"domain": "codereview.stackexchange",
"id": 42758,
"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, node.js",
"url": null
} |
javascript, node.js
function process(keywords, categories) {
keywords.forEach(obj =>
categories.forEach(({name, options} =>
obj[name] = options.every(({method, regex}) =>
method === 'include' ? obj.URL.includes(regex) : !obj.URL.includes(regex))
)
);
}
The two inner loops create new strings for each iteration. name in the outer loop categories.forEach(( and method and regex in the loop options.every(({
As these string are all stored as references in objects there is no need to copy the strings to new variables. Just use the references directly as follows...
function process(keywords, categories) {
keywords.forEach(obj =>
categories.forEach(cat =>
obj[cat.name] = cat.options.every(opt =>
opt.include ? obj.URL.includes(opt.regex) : !obj.URL.includes(opt.regex))
)
);
}
Avoid state strings
Using string to store simple states is much slower than using simpler types like boolean or number.
For example you use the expression opt.method === "include" to check the type of test to do on URL. The negative (false) for opt.method === "include" (method = "exclude") is quicker as the compare fails on the first character "e" !== "i" . However the match needs to iterate each of the 7 characters to find true.
JS has no clue to help check the match (the strings include and exclude are the same length).
As there are only two states, include or exclude, you can use a boolean state.
Example the option objects can be
options: [
{ include: true, regex: 'facebook' }, // includes
{ include: false, regex: 'twitter' } // excludes
]
And then the inner test can be a constant (and fast) complexity
opt.include ? obj.URL.includes(opt.regex) : !obj.URL.includes(opt.regex))
If you can not create the boolean for categories as stored (in JSON). Process the options once outside the function process
function optimzeCats(categories) {
categories.forEach(cat => cat.options.forEach(opt =>
opt.include = opt.method === 'include'
));
} | {
"domain": "codereview.stackexchange",
"id": 42758,
"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, node.js",
"url": null
} |
javascript, node.js
Having to do so will of course reduce the gain gained.
Reduce scope searches
Using node (V8) means that there is an additional overhead each (scope step) you need to use a variable outside the current scope.
In your code the outer loop keywords.forEach(obj puts the variable obj 2 scope steps above its use in the inner loop. obj.URL.includes(
As (I assume) the number of keywords greatly outnumbers the number of cats changing the scope distance to obj will give another worthwhile performance gain. This can be done by swapping the order of the first two outer loops.
function process(keywords, categories) {
categories.forEach(cat =>
keywords.forEach(obj =>
obj[cat.name] = cat.options.every(opt =>
opt.method === 'include' ? obj.URL.includes(opt.regex) : !obj.URL.includes(opt.regex))
)
);
}
Further optimizations
All of the above should give up to 15% performance gain and a unknown but worthwhile reduction in memory use. (Note only in regard to processing, as I don't know how you handle the JSON string)
There are likely many more optimizations however these will depend very much on what is being stored in both data structures and how the results are expected to be used.
Update
Correction...
After comments and then some research. Strings are not copied (duplicated) when assigned but rather a map reference (hash) to the unique string within the global context represents the string. | {
"domain": "codereview.stackexchange",
"id": 42758,
"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, node.js",
"url": null
} |
python
Title: Scan and Output ACLs to Excel in Python
Question: I am working to solve an issue that my company is currently having, We have an extremely large share drive that is over 20 years old. There are so many security groups attached to some of these folder as well as individual users that no longer exist and appear as scrambled text.
We would like to scan through the entire directory and output all of the permissions to an excel file.
I have come up with this solution, however, I don't believe I have done it as efficiently as I believe it can be.
Here is the entire script:
import os
import subprocess
import xlsxwriter
import win32com.client as win32
# *** IMPORTANT ****
# MUST INSTALL XLSXWRITER AND PYWIN32 IN VENV
# PIP INSTALL XLSXWRITER
# PIP INSTALL PYWIN32
def CheckPerms(t, save_dir):
global firstDir
# LOOP THROUGH ALL PATHS IN ROOT DIRECTORY
for path in os.listdir(t):
# VARIABLE HOLDS FULL PATH OF THE ROOT DIRECTORY
full_root_path = os.path.join(t, path)
# CHECKS IF PATH IS A FILE, IF IT IS A FILE, SKIP AND CONTINUE WITH SCAN
if not os.path.isfile(full_root_path):
# VARIABLE HOLDS ROOT NAME OF FULL ROOT PATH
# EXAMPLE: INPUT - C:\TEST, RETURNS - C:\
firstDir = os.path.split(full_root_path)
# PRINTS CURRENT DIRECTORY THAT IS BEING SCANNED
print("Working on: " + firstDir[1])
# PREPARE EXCEL WORKBOOK IN SPECIFIED LOCATION
# SAVES AS NAME OF DIR BEING SCANNED
workbook = xlsxwriter.Workbook(f'{save_dir}\\{firstDir[1]}.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write("A1", "Directory Path")
worksheet.write("B1", "Security Groups")
row = 1
col = 0
# LOOP THOUGH A WALK OF EACH ROOT PATH
# THIS WILL SCAN FRONT TO BACK, TOP TO BOTTOM OF THE ENTIRE TREE
for r, d, f in os.walk(full_root_path): | {
"domain": "codereview.stackexchange",
"id": 42759,
"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
# CAPTURE THE OUTPUT OF THE SYSTEM CMD ICALCS COMMAND ON DIRECTORY BEING SCANNED
sub_return = subprocess.check_output(["icacls", r])
try:
# TRY TO DECODE OUTPUT AS UTF-8
sub_return = sub_return.decode('utf-8')
except:
# SOMETIMES CANNOT DECODE, THIS WILL CATCH ERROR AND CONTINUE
print("Decode Error: Skipping a line")
continue
# SPLIT THE LINES OF THE RETURNED STRING
split_icacl_lines = sub_return.splitlines()
# ICACLS RETURNS A STATUS LINE AFTER COMPLETE
# THIS WILL REMOVE THE LAST LINE, EXAMPLE:
# "Successfully processed 1 files; Failed processing 0 files"
del split_icacl_lines[-1:]
# FIRST LINE OF ICACLS INCLUDES THE DIRECTORY AS WELL AS FIRST LINE OF ICACLS
# THIS WILL REVERSE SPLIT BY FIRST EMPTY SPACE TO SEPARATE THE LINES
# AND DELETE IT FROM THE ORIGINAL LIST
firstLine = split_icacl_lines[0].rsplit(" ", 1)
del split_icacl_lines[0]
# THERE HAPPENS TO BE AN EMPTY LINE, SO WE REMOVE IT HERE
del split_icacl_lines[-1:]
# ADD THE FIRST ELEMENT OF THE FIRST LINE BACK INTO THE BEGINNING OF THE LIST
split_icacl_lines.insert(0, firstLine[0].lstrip())
# APPEND THE SECOND ELEMENT OF THE FIRST LINE TO END OF LIST
split_icacl_lines.append(firstLine[1].lstrip())
# FIRST ELEMENT OF LIST IS THE TARGET DIRECTORY
target_directory = split_icacl_lines[0]
# DELETE TARGET DIRECTORY FROM LIST
del split_icacl_lines[0] | {
"domain": "codereview.stackexchange",
"id": 42759,
"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
# DELETE TARGET DIRECTORY FROM LIST
del split_icacl_lines[0]
# ADD TARGET DIRECTORY TO EXCEL FILE
worksheet.write(row, col, target_directory)
# MOVE OVER EXCEL COLUMN BY 1
col += 1
# LOOP THROUGH EACH LINE IN THE FINAL ICACL DATA AND
# OUTPUT IT TO EXCEL FILE NEXT TO THE DIRECTORY IT
# BELONGS TO
for lines in split_icacl_lines:
# STRIP LINES OF ALL ABNORMAL CHARACTERS
output = lines.lstrip()
# INSERT LINE INTO WORKBOOK
worksheet.write(row, col, output)
row += 1
# EMPTY LINE BETWEEN EACH SCAN OUTPUT
row += 1
# RESET COLUMN TO 0
col = 0
# CLOSE WORKBOOK, SAVING IT
workbook.close()
# OPEN WORKBOOK IN WIN32, AUTO-FIT EACH COLUMN AND SAVE IT
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(f'C:\\Test\\{firstDir[1]}.xlsx')
ws = wb.Worksheets("Sheet1")
ws.Columns.AutoFit()
wb.Save()
excel.Application.Quit()
# REPEAT ALL ABOVE FOR EACH DIRECTORY
CheckPerms("C:\\", "C:\\Test")
The problem I have, is when ICACLS is run in windows, the first line it returns includes the directory as well as the first permission, example:
C:\Users\Michael>icacls C:\\
C:\\ BUILTIN\Administrators:(OI)(CI)(F)
NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Users:(OI)(CI)(RX)
NT AUTHORITY\Authenticated Users:(OI)(CI)(IO)(M)
NT AUTHORITY\Authenticated Users:(AD)
Mandatory Label\High Mandatory Level:(OI)(NP)(IO)(NW) | {
"domain": "codereview.stackexchange",
"id": 42759,
"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
This is why I had to do some weird stuff with the output after I split it into a list.
After splitting the original output, I split the first line of that output by an empty space and added each element back into the list, however, for some files such as in the directory "Program Files" I get strange outputs like this:
Can anyone suggest a better way to do this?
It would be very much appreciated.
Answer:
when ICACLS is run in windows, the first line it returns includes the directory as well as the first permission
That's because your parsing algorithm is incorrect. About the only way to parse this output is to look at the second line to see how far indented it is.
Otherwise:
DON'T SHOUT IN YOUR COMMENTS; THIS IS ESPECIALLY IMPORTANT FOR PIP WHERE IT WILL NOT WORK ON CASE-SENSITIVE OPERATING SYSTEMS UNLESS IT'S LOWER-CASE
Don't store firstDir as a global
CheckPerms should be check_perms by PEP8
Divide this out into more subroutines
Prefer pathlib over os where possible
Your firstDir[1] index is strange. I assume this is just the stem of the directory.
Put your xlsx file path into a variable for reuse.
You have inconsistent worksheet indexing, mixing A1 with row/column. Prefer the latter.
Do not use single-letter variable names like r, d, f
Don't decode yourself; pass encoding to subprocess functions
Don't call workbook.close; put it in a with
Don't open Excel just for the purpose of column auto-sizing; keep track of the longest string and use that as the column width
Add a __main__ guard
Never bare except:
Strongly consider parsing the result of icacls /T which includes multiple files and will be more efficient. I have not shown this below.
Suggested
import os
import subprocess
from typing import Iterator
import xlsxwriter
from pathlib import Path
# must install xlsxwriter in venv
# pip install xlsxwriter
def parse_icacls(dir_path: str) -> Iterator[str]:
"""
Example output: | {
"domain": "codereview.stackexchange",
"id": 42759,
"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 parse_icacls(dir_path: str) -> Iterator[str]:
"""
Example output:
icacls some_long_file
some_long_file NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
BUILTIN\Administrators:(I)(OI)(CI)(F)
LAPTOP\me:(I)(OI)(CI)(F)
Successfully processed 1 files; Failed processing 0 files
"""
sub_return = subprocess.check_output(('icacls', dir_path), encoding='utf-8')
lines = sub_return.splitlines()
lead = len(lines[1]) - len(lines[1].lstrip())
for line in lines:
if not line:
break
yield line[lead:]
def write_workbook(full_root_path: Path, saved_to: Path) -> None:
with xlsxwriter.Workbook(saved_to) as workbook:
worksheet = workbook.add_worksheet()
headers = ('Directory Path', 'Security Groups')
row = 0
for col, header in enumerate(headers):
worksheet.write(row, col, header)
row += 1
longest_dir = len(headers[0])
longest_group = len(headers[1])
for dir_path, dir_names, file_names in os.walk(full_root_path):
try:
groups = parse_icacls(dir_path)
except UnicodeDecodeError:
print('Decode Error: Skipping a line')
continue
col = 0
worksheet.write(row, col, dir_path)
longest_dir = max(longest_dir, len(dir_path))
col += 1
for group in groups:
worksheet.write(row, col, group)
longest_group = max(longest_group, len(group))
row += 1
row += 1
worksheet.set_column(first_col=0, last_col=0, width=longest_dir)
worksheet.set_column(first_col=1, last_col=1, width=longest_group)
def check_perms(top: Path, save_dir: Path) -> None:
save_dir.mkdir(exist_ok=True) | {
"domain": "codereview.stackexchange",
"id": 42759,
"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 check_perms(top: Path, save_dir: Path) -> None:
save_dir.mkdir(exist_ok=True)
for full_root_path in top.iterdir():
if full_root_path.is_dir():
saved_to = (save_dir / full_root_path.stem).with_suffix('.xlsx')
print(f'Working on: {full_root_path}; saving to {saved_to}')
write_workbook(full_root_path, saved_to)
if __name__ == '__main__':
check_perms(Path('.'), Path('Test')) | {
"domain": "codereview.stackexchange",
"id": 42759,
"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, pandas, data-mining
Title: Better way to create a contingency table with pandas for film genres from a Film DataFrame
Question: From a public dataset available on film rating I created a contingency table as follow.
Honestly I don't like all these "for-loops" I think the quality of the code can be definitely improved in a more pythonic way.
import pandas as pd
import numpy as np
movies_df = pd.read_csv("https://raw.githubusercontent.com/uomodellamansarda/GentleIntroduction2MLandDataScience/main/L10/movies%20(1).csv")
# Getting series of lists by applying split operation.
movies_df.genres = movies_df.genres.str.split('|')
# Getting distinct genre types for generating columns of genre type.
genre_columns = list(set([j for i in movies_df['genres'].tolist() for j in i]))
# Iterating over every list to create and fill values into columns.
for j in genre_columns:
movies_df[j] = 0
for i in range(movies_df.shape[0]):
for j in genre_columns:
if(j in movies_df['genres'].iloc[i]):
movies_df.loc[i,j] = 1
print(movies_df)
And this is the output after running my code
Answer: Pandas isn't very good at this - it's not very vectorisable. But you can still avoid some of your loops.
"Pythonic" somewhat secondary here, and instead you're looking for "Pandas-idiomatic".
You can replace your nested list/set/list comprehension with a call to reduce(set.union) if you've cast your genres column to set using apply. I tried agg but it didn't work.
You can avoid loc and iloc if you use another apply per column value using set membership.
Suggested
from functools import reduce
import pandas as pd
movies_df = pd.read_csv(
"https://raw.githubusercontent.com/uomodellamansarda"
"/GentleIntroduction2MLandDataScience/main/L10/movies%20(1).csv")
movies_df.genres = movies_df.genres.str.split('|').apply(set)
genre_columns = reduce(set.union, movies_df.genres)
for genre in genre_columns:
movies_df[genre] = movies_df.genres.apply(lambda s: genre in s)
print(movies_df) | {
"domain": "codereview.stackexchange",
"id": 42760,
"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, pandas, data-mining",
"url": null
} |
python, performance, game, hangman
Title: Hangman game in Python with nine possible words
Question: I'm relatively new to Python, and I've been using the language for about a month. I set out to do the Hangman game. I would like to know if there are things to improve in the code of the program I made.
This is the code:
import random
HANGMAN_PICS = ('''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''')
WORDS = ('Daniel', 'Cristian', 'Lucio', 'Alejandra', 'Delfina', 'Diana', 'Joshua', 'Pedro', 'Rick')
SECRET_WORD = random.choice(WORDS)
found_letters = []
blanks = len(SECRET_WORD) * '_'
print(f'\nSecret word: {blanks}')
print(f'{HANGMAN_PICS[0]}\n')
print('-' * 40)
blanks = list(blanks)
trials = 6
while trials > 0:
letter = input('\nEnter a letter: ').lower()
if len(letter) != 1 or not letter.isalpha():
print('The value entered is invalid.\n')
print('-' * 40)
elif letter in found_letters:
print('This letter has already been entered. Enter another letter.\n')
print('-' * 40)
elif letter in SECRET_WORD.lower():
for i in range(len(SECRET_WORD)):
if SECRET_WORD.lower()[i] == letter:
blanks[i] = letter
found_letters.append(letter)
print(''.join(blanks))
print('-' * 40)
else:
found_letters.append(letter)
trials -= 1
print(f'You missed and lost a life. You have {trials} trials left.')
print(f'{HANGMAN_PICS[6-trials]}\n')
print('-' * 40) | {
"domain": "codereview.stackexchange",
"id": 42761,
"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, performance, game, hangman",
"url": null
} |
python, performance, game, hangman
if ''.join(blanks) == SECRET_WORD.lower():
print(f'You won. The secret word is: {SECRET_WORD}.')
break
else:
print(f'You lost. The secret word is: {SECRET_WORD}.')
Answer: This looks pretty good for 1-month coder. Keep it up!
Use functions, classes and tests
If you have already learned them - use them. If you haven't - learn them. Start with functions. They are in the language to organize the code. When you have functions, you can test the code.
Avoid "magic numbers"
What's 40? What's 6? If you ever want to change horizontal line length to 60 - you should search all the code, and still miss some places where it's not 40 but 39 or something like that, say, if you use '+'+'-'*38+'+' somewhere as a spacer. Instead, introduce a new variable - it can be SPACER_SIZE = 40 or even SPACER = '-'*40 - and use it like print(SPACER). This gives you the possibility to change all instances at once and, at the same time, the name to what you're doing and save your time reading the code later.
Comparing strings and lists
You have two variables, SECRET_WORD and blanks, to save the secret word and its guessed part. And all over the code you're transforming them this or that way around.
SECRET_WORD is a string with different cases; blanks changes from string to a list of lowercase letters and underscores. I think, the last data type would fit better for both variables; of course, there's a reason to preserve the original SECRET_WORD, so let's introduce a new variable:
SECRET_WORD = random.choice(WORDS))
secret_word = list(SECRET_WORD.lower())
blanks = ['-'] * len(secret_word) # this works for lists too
...
elif letter in secret_word: #no call to .lower()
...
if secret_word[i] == letter:
blanks[i] = letter
...
if secret_word == blanks: #no join, no lower | {
"domain": "codereview.stackexchange",
"id": 42761,
"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, performance, game, hangman",
"url": null
} |
python, performance, game, hangman
Move identical and related code together
In if-elif-elif-else the last line of all branches is print('-' * 40). You can simply move it out of there:
if ...: ...
elif ...: ...
elif ... : ...
else: ...
print('-' * 40)
The same way you can combine both found_letters.append(letter):
if ...: ...
elif ...: ...
else:
found_letters.append(letter)
if ...: ...
else: ...
Btw, set is usually better than list to search for something, so it should be found_letters = set() and found_letters.add(letter); but in this case the difference would be so small you'll never notice the difference. | {
"domain": "codereview.stackexchange",
"id": 42761,
"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, performance, game, hangman",
"url": null
} |
beginner, r
Title: Conditionally drop rows in grouped data.frame using dplyr in R
Question: I have a data frame with columns for three predictors that try to predict the target variable 'change' with values 'yes' and 'no'. The data frame is grouped by id, and for every id, I have 4 years.
Per id number, I want to summarize the combination of the predictors and the change-variable according to the following rules:
Keep rows where there is any prediction from any predictor (like any(!is.na(c(pred1,pred2,pred3))))
Keep rows where change == 'yes'
Keep rows with both conditions 1 and 2.
If an id meets conditions 1, 2, or 3, delete all rows where all predictors are NA and change == 'no'
Keep only 1 row when all predictors are NA and change == 'no'
The current code needs two steps to accomplish the goal because it is keeping the rows containing no predictions and no change if they belong to the year 2015. This guarantees condition 5 but requires an additional round of removal to satisfy condition 4.
I've recently shifted my programming style from base R to tidyverse, so I'm a beginner with the package. I was hoping there would be a shorter way to go about this using dplyr.
library(dplyr)
# generate input data. No review needed here, as it is not the original data
set.seed(1)
inputDF <- data.frame(
id = rep(1001:1005, each = 4) ,
year = rep(2015:2018, times = 5) ,
change = c(rep('no',12),'yes', rep('no',2), rep(c('yes', 'no'), 2), 'yes'),
pred1 = c(rep(NA, 10), rep(c(NA,NA,1),2),rep(NA,3),1),
pred2 = c(rep(NA, 8), rep(c(NA,1,NA),2),rep(1,3),rep(NA,3)),
pred3 = c(rep(NA, 8), rep(c(NA,1,1),2),rep(NA,6))) %>%
mutate(across(contains('pred'),
~ if_else(!is.na(.x), rnorm(n(), mean=row_number()), .x) )) %>%
mutate(rownum = row_number()) | {
"domain": "codereview.stackexchange",
"id": 42762,
"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": "beginner, r",
"url": null
} |
beginner, r
#' first round of deleting rows summarizes ids
#' with only NA predictions and no change
deleterows1 <- inputDF %>%
group_by(id) %>%
filter(change == 'no' &
is.na(pred1) &
is.na(pred2) &
is.na(pred3) &
year != 2015) %>%
select(c(rownum,id)) %>% as.data.frame()
filteredDF <- inputDF %>%
rows_delete(., deleterows1, by = c('rownum', 'id'))
#' The second round of deleting rows ensures that
#' rows with no predictions and no change are deleted
#' in id groups with predictions and/or chnage
deleterows2 <- filteredDF %>%
group_by(id) %>%
filter(n() > 1) %>%
filter(change == 'no' &
is.na(pred1) &
is.na(pred2) &
is.na(pred3) &
year == 2015) %>%
select(c(rownum,id)) %>% as.data.frame()
filteredDF <- filteredDF %>%
rows_delete(., deleterows2, by = c('rownum', 'id')) %>%
select(-rownum)
Answer: Fundamentally, you are trying to keep a row if:
It meets some sorts of conditions that make it a "good" row, or
It's the first row for an id that has no "good" rows.
To me, then, the way to accomplish this would be to compute which rows are good rows and to filter accordingly. It might look something like this:
filtered2 <- inputDF %>%
mutate(good=(change=="yes" | !is.na(pred1) | !is.na(pred2) | !is.na(pred3))) %>%
group_by(id) %>%
filter(good | (row_number() == 1 & sum(good) == 0)) %>%
select(-good, -rownum)
We can confirm this gives the same results as your code:
identical(as.data.frame(filtered2), as.data.frame(filteredDF))
# [1] TRUE | {
"domain": "codereview.stackexchange",
"id": 42762,
"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": "beginner, r",
"url": null
} |
beginner, r
Note that by defining the good variable, I avoid needing to repeat the long condition that defines whether a row is good or not. Further, note that I can perform the filtering in one shot by either keeping a row if it's good or if none of the rows are good for an id (sum(good) == 0) and it's the first row for the id (row_number() == 1).
A final comment: a nice aspect of using row_number instead of filtering on the year being 2015 (the first year in your dataset) is that this will continue working if your data changes (e.g. to year range 2016-2019 instead of 2015-2018). | {
"domain": "codereview.stackexchange",
"id": 42762,
"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": "beginner, r",
"url": null
} |
bash, shell, wrapper, dockerfile
Title: Shell script wrapper for Docker build and run
Question: I have written a simple wrapper for docker build and docker run that allows me to build and run my image without having to use the docker command directly.
Here's the layout of my code:
esp8266
βββ scripts
β βββ config.sh <- configuration
β βββ util.sh <- utility functions
βββ docker <- docker image root
β βββ Dockerfile
βββ build <- script to build image
βββ make <- script to run image
And the files themselves:
scripts/config.sh
readonly DOCKER_IMAGE_NAME="jackwilsdon/esp8266"
readonly DOCKER_IMAGE_TAG="0.1.0"
readonly DOCKER_IMAGE_MOUNT="/mnt/data"
readonly DOCKER_LOCAL_SOURCE_DIRECTORY="docker"
readonly DOCKER_LOCAL_MOUNT_DIRECTORY="data"
scripts/util.sh
#!/usr/bin/env bash
#
# Utilities for esp8266 development container scripts
# usage: print [args...]
print() {
echo "${CURRENT_SCRIPT}: $*"
}
# usage: print_raw [args...]
print_raw() {
echo "$*"
}
# usage: error [args...]
error() {
print "error: $*" >&2
}
# usage: error_raw [args...]
error_raw() {
print_raw "$*" >&2
}
# usage: check_requirements
check_requirements() {
if [[ -z "${CURRENT_SCRIPT}" ]]; then
error "CURRENT_SCRIPT not set"
exit 1
fi
if [[ -z "${CURRENT_DIRECTORY}" ]]; then
error "CURRENT_DIRECTORY not set"
exit 1
fi
if [[ -z "${DOCKER_BINARY}" ]]; then
error "unable to find docker (DOCKER_BINARY not set)"
return 1
fi
}
# usage: docker [args...]
docker() {
"${DOCKER_BINARY}" "$@"
local exit_code="$?"
if [[ "${exit_code}" -ne 0 ]]; then
error "${DOCKER_BINARY} exited with code ${exit_code}"
return 1
fi
}
# usage: arg_or_default arg default [new arg value]
arg_or_default() {
if [[ -n "$1" ]]; then
if [[ "$#" -eq 3 ]]; then
echo "$3"
else
echo "$1"
fi
else
echo "$2"
fi
}
build
#!/usr/bin/env bash
#
# Build esp8266 development container | {
"domain": "codereview.stackexchange",
"id": 42763,
"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": "bash, shell, wrapper, dockerfile",
"url": null
} |
bash, shell, wrapper, dockerfile
build
#!/usr/bin/env bash
#
# Build esp8266 development container
readonly CURRENT_SCRIPT="$(basename -- ${BASH_SOURCE[0]})"
readonly CURRENT_DIRECTORY="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly DOCKER_BINARY="$(command -v docker)"
source "${CURRENT_DIRECTORY}/scripts/config.sh"
source "${CURRENT_DIRECTORY}/scripts/util.sh"
# usage: usage [printer]
usage() {
local printer="$(arg_or_default "$1" 'print_raw')"
"${printer}" "usage: ${CURRENT_SCRIPT} [-h] [TAG]"
}
# usage: full_usage [printer]
full_usage() {
local printer="$(arg_or_default "$1" 'print_raw')"
usage "${printer}"
"${printer}"
"${printer}" 'Build tool for esp8266 development container'
"${printer}"
"${printer}" 'arguments:'
"${printer}" ' -h show this help message and exit'
"${printer}" ' TAG the tag of the image to build'
}
# usage: build_image [tag]
build_image() {
# Generate image name
local name="${DOCKER_IMAGE_NAME}:$(arg_or_default "$1" \
"${DOCKER_IMAGE_TAG}")"
print "building image ${name}"
# Run docker with the provided arguments
docker build -t "${name}" \
"${CURRENT_DIRECTORY}/${DOCKER_LOCAL_SOURCE_DIRECTORY}"
}
# usage: main [-h] [-d DATA_DIRECTORY] [-t TAG] [ARGS...]
main() {
check_requirements "$@" || exit 1
while getopts ':h' OPT; do
case "${OPT}" in
h)
full_usage
exit 0
;;
?)
full_usage
print
error "invalid argument: ${OPTARG}"
exit 1
;;
esac
done
shift $((OPTIND - 1))
build_image "$@"
}
if [[ "$0" == "${BASH_SOURCE[0]}" ]]; then
main "$@"
fi
make
#!/usr/bin/env bash
#
# Run esp8266 development container
readonly CURRENT_SCRIPT="$(basename -- ${BASH_SOURCE[0]})"
readonly CURRENT_DIRECTORY="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly DOCKER_BINARY="$(command -v docker)" | {
"domain": "codereview.stackexchange",
"id": 42763,
"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": "bash, shell, wrapper, dockerfile",
"url": null
} |
bash, shell, wrapper, dockerfile
source "${CURRENT_DIRECTORY}/scripts/config.sh"
source "${CURRENT_DIRECTORY}/scripts/util.sh"
# usage: usage [printer]
usage() {
local printer="$(arg_or_default "$1" 'print_raw')"
"${printer}" "usage: ${CURRENT_SCRIPT} [-h] [-d DATA_DIRECTORY] [-t TAG]" \
"[ARGS...]"
}
# usage: full_usage [printer]
full_usage() {
local printer="$(arg_or_default "$1" 'print_raw')"
usage "${printer}"
"${printer}"
"${printer}" 'Make tool for esp8266 development container'
"${printer}"
"${printer}" 'arguments:'
"${printer}" ' -h show this help message and exit'
"${printer}" ' -d DATA_DIRECTORY mount point for /mnt/data inside the'
"${printer}" ' container'
"${printer}" ' -t TAG the tag of the image to run'
"${printer}" ' ARGS... the command to run in the container'
}
# usage: run_image [data_directory] [tag] [args...]
run_image() {
local arguments=(run --rm --interactive --tty --entrypoint /sbin/my_init)
# Generate volume and image names
local volume="$(arg_or_default "$1" \
"${CURRENT_DIRECTORY}/${DOCKER_LOCAL_MOUNT_DIRECTORY}")"
local name="${DOCKER_IMAGE_NAME}:$(arg_or_default "$2" \
"${DOCKER_IMAGE_TAG}")"
# Add volume and name to arguments
arguments+=(-v "${volume}:/mnt/data" ${name})
# Remove the first two arguments from the argument list
shift 2
# Run docker with the provided arguments
docker "${arguments[@]}" -- "$@"
}
# usage: main [-h] [-d DATA_DIRECTORY] [-t TAG] [ARGS...]
main() {
check_requirements "$@" || exit 1
local docker_volume=''
local docker_image_tag='' | {
"domain": "codereview.stackexchange",
"id": 42763,
"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": "bash, shell, wrapper, dockerfile",
"url": null
} |
bash, shell, wrapper, dockerfile
local docker_volume=''
local docker_image_tag=''
while getopts ':hd:t:' OPT; do
case "${OPT}" in
h)
full_usage
exit 0
;;
d)
docker_volume="${OPTARG}"
;;
t)
docker_image_tag="${OPTARG}"
;;
?)
full_usage error_raw
error_raw
error "invalid argument: ${OPTARG}"
exit 1
;;
esac
done
shift $((OPTIND - 1))
run_image "${docker_volume}" "${docker_image_tag}" "$@"
}
if [[ "$0" == "${BASH_SOURCE[0]}" ]]; then
main "$@"
fi
This image is primarily designed for development and ease of use, which is why I have created these shell scripts.
Here's some examples of how to use the scripts:
$ ./build -h
usage: build [-h] [TAG]
Build tool for esp8266 development container
arguments:
-h show this help message and exit
TAG the tag of the image to build
$ ./build example_tag
build: building image jackwilsdon/esp8266:example_tag
Sending build context to Docker daemon 3.584 kB
Step 1 : FROM phusion/baseimage:latest
---> c39664f3d4e5
Step 2 : MAINTAINER Jack Wilsdon <jack.wilsdon@gmail.com>
---> Using cache
---> 4ec300220c6c
...
Step 7 : VOLUME /mnt/data
---> Using cache
---> f9f8a21a0d16
Successfully built f9f8a21a0d16
$ ./make -h
usage: make [-h] [-d DATA_DIRECTORY] [-t TAG] [ARGS...]
Make tool for esp8266 development container
arguments:
-h show this help message and exit
-d DATA_DIRECTORY mount point for /mnt/data inside the
container
-t TAG the tag of the image to run
ARGS... the command to run in the container
$ ./make whoami
*** Running /etc/my_init.d/00_regen_ssh_host_keys.sh...
*** Running /etc/rc.local...
*** Booting runit daemon...
*** Runit started as PID 9
*** Running whoami...
root
*** whoami exited with status 0.
*** Shutting down runit daemon (PID 9)...
*** Killing all processes... | {
"domain": "codereview.stackexchange",
"id": 42763,
"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": "bash, shell, wrapper, dockerfile",
"url": null
} |
bash, shell, wrapper, dockerfile
I'm rather new to shell scripting, however I'd like to ensure my scripts are as robust as possible, is there anything I can do to improve their robustness?
Answer: Looking very good. Honestly I only have nitpicks.
The purpose of the 3rd argument of arg_or_default is unclear.
From the comment in the code I don't understand it,
and it's not used by any of the scripts.
Either explain it better in the comment, or drop it,
since you're not using it anyway.
The == operator in [[ is for pattern matching.
When you don't need to match a pattern but a literal string,
as in [[ "$0" == "${BASH_SOURCE[0]}" ]],
then you can replace it with a single =.
You don't need to double-quote the $? variable, it's always safe.
You don't need to quote string literals like print_raw.
You don't need the single-quote pairs when setting a variable to empty as in docker_volume='', you can write simply docker_volume= | {
"domain": "codereview.stackexchange",
"id": 42763,
"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": "bash, shell, wrapper, dockerfile",
"url": null
} |
assembly, arm
Title: Project Euler 1 (sum of multiples of 3 or 5) in ARM Assembly
Question: Project Euler #1 asks:
Find the sum of all the multiples of 3 or 5 below 1000.
In ARM Assembly;
I did this in 3 loops, which avoids any MOD or DIV.
Each loop is written out, without a common subroutine, since loop 3 is different than loops 1 and 2, and the space savings in combining 1 and 2 are negated by the bl / bx lr.
All suggestions appreciated:
lim equ 1000
euler1
mov r0, #0
mov r1, #0 ; i = 0
nexti3
add r0, r0, r1 ; a += i
add r1, r1, #3 ; i += 3
cmp r1, #lim
blt nexti3 ; if (i < lim) goto loop
mov r1, #0
nexti5
add r0, r0, r1
add r1, r1, #5
cmp r1, #lim
blt nexti5
mov r1, #0
nexti15
sub r0, r0, r1
add r1, r1, #15
cmp r1, #lim
blt nexti15 | {
"domain": "codereview.stackexchange",
"id": 42764,
"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": "assembly, arm",
"url": null
} |
assembly, arm
Answer: Algorithm
Looking at the code, it is not solving Project Euler #1, which asks for
S = 3 + 5 + 6 + 9 + ... + 995 + 996 + 999
Your code is solving ...
S = + 0 + 3 + 6 + 9 + ... + 999 + 0 + 5 + 10 + ... + 995 - 0 - 15 - 30 - ... - 990
... which looks like steps for a completely different problem. In short, you've done some work to transform the algorithm from something that needs to test if a value is a multiple of 3 or 5, to a different algorithm which simply sums multiples. You could do more work and simplify into an algebraic formula with no looping at all (although you would need to use DIV).
If you were asked a slightly different problem, the extra 0's being used in your loops could become an issue. For instance, if asked for the product instead of the sum, your formulation would have your first step multiplying by 0! You could easily skip the zeros using mov r1, #3, mov r1, #5 and mov r1, #15 instead of the three mov r1, #0 statements.
Code
You've got a hard coded limit. The problem indicates that the value 23 would be returned if you use a limit of 10, and then asks for the value returned for a limit of 1000. Would you write completely different code if you wanted to evaluate with the first limit? Probably not.
Instead, write the code as a function. The input parameter limit would be placed in r0 before calling the function (bl euler1). Move it into r2 inside the function, and then replace occurrences of cmp r1, #lim with cmp r1, r2. The result is left in r0 for when the function returns. You're now using additional registers (r2 as well as the link register), but the function can validate the problem's test data before computing the actual answer:
; Test case to verify implementation
mov r0, #10
bl euler1
cmp r0, #23 ; Did it work?
bnz assert_failure
; Solve actual Project Euler 1 problem
mov r0, #lim
bl euler1
; r0 should have actual answer here. | {
"domain": "codereview.stackexchange",
"id": 42764,
"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": "assembly, arm",
"url": null
} |
python, numpy, pandas
Title: Slicing multi index DataFrame into JSON object | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
Question: I have a MultiIndex pd.DataFrame that I generated from a .txt that is forecast model data.
Edit:
per request I've included a small data sample to generate the DataFrame
The dict below can be used to generate a more concise version of my data DataFrame
data_dict: | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
{0: {('1000mb', 'gph'): 166.88, ('1000mb', 'temp'): 283.88, ('1000mb', 'dewpt'): 280.18, ('1000mb', 'dir'): 300.86, ('1000mb', 'speed'): 6.0, ('975mb', 'gph'): 377.88, ('975mb', 'temp'): 282.95, ('975mb', 'dewpt'): 278.56, ('975mb', 'dir'): 313.81, ('975mb', 'speed'): 13.0, ('950mb', 'gph'): 592.7, ('950mb', 'temp'): 280.97, ('950mb', 'dewpt'): 277.65, ('950mb', 'dir'): 319.71, ('950mb', 'speed'): 14.0, ('925mb', 'gph'): 811.98, ('925mb', 'temp'): 279.11, ('925mb', 'dewpt'): 276.72, ('925mb', 'dir'): 315.06, ('925mb', 'speed'): 13.0, ('900mb', 'gph'): 1035.98, ('900mb', 'temp'): 278.04, ('900mb', 'dewpt'): 276.56, ('900mb', 'dir'): 301.76, ('900mb', 'speed'): 10.0, ('875mb', 'gph'): 1266.98, ('875mb', 'temp'): 279.16, ('875mb', 'dewpt'): 277.68, ('875mb', 'dir'): 296.34, ('875mb', 'speed'): 8.0, ('850mb', 'gph'): 1503.98, ('850mb', 'temp'): 278.64, ('850mb', 'dewpt'): 276.81, ('850mb', 'dir'): 298.57, ('850mb', 'speed'): 9.0, ('825mb', 'gph'): 1747.98, ('825mb', 'temp'): 277.25, ('825mb', 'dewpt'): 275.69, ('825mb', 'dir'): 295.48, ('825mb', 'speed'): 11.0, ('800mb', 'gph'): 1998.26, ('800mb', 'temp'): 277.12, ('800mb', 'dewpt'): 273.89, ('800mb', 'dir'): 297.67, ('800mb', 'speed'): 13.0, ('775mb', 'gph'): 2256.98, ('775mb', 'temp'): 277.94, ('775mb', 'dewpt'): 272.48, ('775mb', 'dir'): 302.27, ('775mb', 'speed'): 15.0, ('750mb', 'gph'): 2523.86, ('750mb', 'temp'): 277.0, ('750mb', 'dewpt'): 270.96, ('750mb', 'dir'): 303.6, ('750mb', 'speed'): 16.0, ('725mb', 'gph'): 2798.8, ('725mb', 'temp'): 275.64, ('725mb', 'dewpt'): 269.21, ('725mb', 'dir'): 301.65, ('725mb', 'speed'): 19.0, ('700mb', 'gph'): 3081.8, ('700mb', 'temp'): 273.87, ('700mb', 'dewpt'): 266.74, ('700mb', 'dir'): 301.08, ('700mb', 'speed'): 23.0, ('675mb', 'gph'): 3371.96, ('675mb', 'temp'): 272.21, ('675mb', 'dewpt'): 263.85, ('675mb', 'dir'): 301.7, ('675mb', 'speed'): 25.0, ('650mb', 'gph'): 3673.08, ('650mb', 'temp'): 270.48, ('650mb', 'dewpt'): 260.75, ('650mb', 'dir'): 302.23, ('650mb', 'speed'): | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
('650mb', 'temp'): 270.48, ('650mb', 'dewpt'): 260.75, ('650mb', 'dir'): 302.23, ('650mb', 'speed'): 28.0, ('625mb', 'gph'): 3982.04, ('625mb', 'temp'): 268.73, ('625mb', 'dewpt'): 257.99, ('625mb', 'dir'): 299.64, ('625mb', 'speed'): 29.0, ('600mb', 'gph'): 4303.62, ('600mb', 'temp'): 266.9, ('600mb', 'dewpt'): 255.05, ('600mb', 'dir'): 297.19, ('600mb', 'speed'): 30.0, ('575mb', 'gph'): 4633.92, ('575mb', 'temp'): 264.93, ('575mb', 'dewpt'): 251.89, ('575mb', 'dir'): 295.12, ('575mb', 'speed'): 31.0, ('550mb', 'gph'): 4978.9, ('550mb', 'temp'): 262.88, ('550mb', 'dewpt'): 248.45, ('550mb', 'dir'): 293.07, ('550mb', 'speed'): 32.0, ('525mb', 'gph'): 5333.54, ('525mb', 'temp'): 260.29, ('525mb', 'dewpt'): 245.08, ('525mb', 'dir'): 292.02, ('525mb', 'speed'): 33.0, ('500mb', 'gph'): 5705.5, ('500mb', 'temp'): 257.56, ('500mb', 'dewpt'): 241.47, ('500mb', 'dir'): 291.0, ('500mb', 'speed'): 35.0, ('475mb', 'gph'): 6087.4, ('475mb', 'temp'): 254.42, ('475mb', 'dewpt'): 241.58, ('475mb', 'dir'): 289.75, ('475mb', 'speed'): 34.0, ('450mb', 'gph'): 6489.96, ('450mb', 'temp'): 251.1, ('450mb', 'dewpt'): 240.94, ('450mb', 'dir'): 288.38, ('450mb', 'speed'): 33.0, ('425mb', 'gph'): 6904.36, ('425mb', 'temp'): 247.61, ('425mb', 'dewpt'): 237.23, ('425mb', 'dir'): 288.55, ('425mb', 'speed'): 34.0, ('400mb', 'gph'): 7343.9, ('400mb', 'temp'): 243.89, ('400mb', 'dewpt'): 233.3, ('400mb', 'dir'): 288.71, ('400mb', 'speed'): 36.0, ('375mb', 'gph'): 7798.15, ('375mb', 'temp'): 240.77, ('375mb', 'dewpt'): 226.58, ('375mb', 'dir'): 290.47, ('375mb', 'speed'): 43.0, ('350mb', 'gph'): 8283.76, ('350mb', 'temp'): 237.42, ('350mb', 'dewpt'): 216.64, ('350mb', 'dir'): 291.77, ('350mb', 'speed'): 52.0, ('325mb', 'gph'): 8790.03, ('325mb', 'temp'): 233.47, ('325mb', 'dewpt'): 217.34, ('325mb', 'dir'): 291.04, ('325mb', 'speed'): 57.0, ('300mb', 'gph'): 9336.86, ('300mb', 'temp'): 229.21, ('300mb', 'dewpt'): 216.5, ('300mb', 'dir'): 290.39, ('300mb', 'speed'): 62.0, ('275mb', 'gph'): 9909.55, | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
'dewpt'): 216.5, ('300mb', 'dir'): 290.39, ('300mb', 'speed'): 62.0, ('275mb', 'gph'): 9909.55, ('275mb', 'temp'): 225.18, ('275mb', 'dewpt'): 214.54, ('275mb', 'dir'): 289.57, ('275mb', 'speed'): 62.0, ('250mb', 'gph'): 10536.86, ('250mb', 'temp'): 220.76, ('250mb', 'dewpt'): 211.98, ('250mb', 'dir'): 288.67, ('250mb', 'speed'): 62.0, ('225mb', 'gph'): 11209.65, ('225mb', 'temp'): 218.6, ('225mb', 'dewpt'): 208.69, ('225mb', 'dir'): 287.05, ('225mb', 'speed'): 62.0, ('200mb', 'gph'): 11961.78, ('200mb', 'temp'): 216.2, ('200mb', 'dewpt'): 204.77, ('200mb', 'dir'): 285.21, ('200mb', 'speed'): 62.0, ('175mb', 'gph'): 12805.89, ('175mb', 'temp'): 216.36, ('175mb', 'dewpt'): 201.73, ('175mb', 'dir'): 289.56, ('175mb', 'speed'): 56.0, ('150mb', 'gph'): 13780.35, ('150mb', 'temp'): 216.54, ('150mb', 'dewpt'): 194.67, ('150mb', 'dir'): 295.83, ('150mb', 'speed'): 49.0, ('125mb', 'gph'): 14929.06, ('125mb', 'temp'): 215.55, ('125mb', 'dewpt'): 193.0, ('125mb', 'dir'): 293.53, ('125mb', 'speed'): 41.0, ('100mb', 'gph'): 16334.96, ('100mb', 'temp'): 214.34, ('100mb', 'dewpt'): 190.78, ('100mb', 'dir'): 288.88, ('100mb', 'speed'): 30.0, ('75mb', 'gph'): 18128.15, ('75mb', 'temp'): 214.56, ('75mb', 'dewpt'): 189.31, ('75mb', 'dir'): 292.03, ('75mb', 'speed'): 22.0, ('50mb', 'gph'): 20655.52, ('50mb', 'temp'): 214.89, ('50mb', 'dewpt'): 186.13, ('50mb', 'dir'): 303.46, ('50mb', 'speed'): 12.0}, 1: {('1000mb', 'gph'): 165.16, ('1000mb', 'temp'): 283.48, ('1000mb', 'dewpt'): 280.17, ('1000mb', 'dir'): 305.02, ('1000mb', 'speed'): 6.0, ('975mb', 'gph'): 375.34, ('975mb', 'temp'): 282.49, ('975mb', 'dewpt'): 278.69, ('975mb', 'dir'): 317.14, ('975mb', 'speed'): 13.0, ('950mb', 'gph'): 590.16, ('950mb', 'temp'): 280.58, ('950mb', 'dewpt'): 277.87, ('950mb', 'dir'): 324.11, ('950mb', 'speed'): 13.0, ('925mb', 'gph'): 809.16, ('925mb', 'temp'): 278.92, ('925mb', 'dewpt'): 276.77, ('925mb', 'dir'): 313.02, ('925mb', 'speed'): 12.0, ('900mb', 'gph'): 1033.7, ('900mb', 'temp'): 278.32, | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
'dir'): 313.02, ('925mb', 'speed'): 12.0, ('900mb', 'gph'): 1033.7, ('900mb', 'temp'): 278.32, ('900mb', 'dewpt'): 276.69, ('900mb', 'dir'): 291.26, ('900mb', 'speed'): 11.0, ('875mb', 'gph'): 1263.98, ('875mb', 'temp'): 279.08, ('875mb', 'dewpt'): 277.62, ('875mb', 'dir'): 281.37, ('875mb', 'speed'): 10.0, ('850mb', 'gph'): 1501.7, ('850mb', 'temp'): 278.63, ('850mb', 'dewpt'): 276.58, ('850mb', 'dir'): 283.97, ('850mb', 'speed'): 10.0, ('825mb', 'gph'): 1745.64, ('825mb', 'temp'): 277.59, ('825mb', 'dewpt'): 275.47, ('825mb', 'dir'): 289.33, ('825mb', 'speed'): 12.0, ('800mb', 'gph'): 1996.26, ('800mb', 'temp'): 277.69, ('800mb', 'dewpt'): 274.2, ('800mb', 'dir'): 296.36, ('800mb', 'speed'): 15.0, ('775mb', 'gph'): 2255.26, ('775mb', 'temp'): 278.15, ('775mb', 'dewpt'): 272.78, ('775mb', 'dir'): 297.89, ('775mb', 'speed'): 17.0, ('750mb', 'gph'): 2522.8, ('750mb', 'temp'): 276.96, ('750mb', 'dewpt'): 271.04, ('750mb', 'dir'): 294.99, ('750mb', 'speed'): 18.0, ('725mb', 'gph'): 2797.14, ('725mb', 'temp'): 275.4, ('725mb', 'dewpt'): 268.56, ('725mb', 'dir'): 294.07, ('725mb', 'speed'): 20.0, ('700mb', 'gph'): 3079.8, ('700mb', 'temp'): 273.71, ('700mb', 'dewpt'): 265.46, ('700mb', 'dir'): 296.39, ('700mb', 'speed'): 23.0, ('675mb', 'gph'): 3369.96, ('675mb', 'temp'): 272.08, ('675mb', 'dewpt'): 263.34, ('675mb', 'dir'): 300.0, ('675mb', 'speed'): 25.0, ('650mb', 'gph'): 3671.08, ('650mb', 'temp'): 270.39, ('650mb', 'dewpt'): 261.12, ('650mb', 'dir'): 303.18, ('650mb', 'speed'): 27.0, ('625mb', 'gph'): 3979.72, ('625mb', 'temp'): 268.74, ('625mb', 'dewpt'): 256.77, ('625mb', 'dir'): 301.49, ('625mb', 'speed'): 29.0, ('600mb', 'gph'): 4300.96, ('600mb', 'temp'): 267.02, ('600mb', 'dewpt'): 251.51, ('600mb', 'dir'): 299.96, ('600mb', 'speed'): 31.0, ('575mb', 'gph'): 4631.58, ('575mb', 'temp'): 264.99, ('575mb', 'dewpt'): 249.31, ('575mb', 'dir'): 297.06, ('575mb', 'speed'): 32.0, ('550mb', 'gph'): 4976.9, ('550mb', 'temp'): 262.87, ('550mb', 'dewpt'): 247.0, ('550mb', | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
32.0, ('550mb', 'gph'): 4976.9, ('550mb', 'temp'): 262.87, ('550mb', 'dewpt'): 247.0, ('550mb', 'dir'): 294.2, ('550mb', 'speed'): 33.0, ('525mb', 'gph'): 5331.25, ('525mb', 'temp'): 260.22, ('525mb', 'dewpt'): 245.18, ('525mb', 'dir'): 293.26, ('525mb', 'speed'): 33.0, ('500mb', 'gph'): 5702.9, ('500mb', 'temp'): 257.43, ('500mb', 'dewpt'): 243.23, ('500mb', 'dir'): 292.32, ('500mb', 'speed'): 34.0, ('475mb', 'gph'): 6085.06, ('475mb', 'temp'): 254.43, ('475mb', 'dewpt'): 241.41, ('475mb', 'dir'): 291.09, ('475mb', 'speed'): 34.0, ('450mb', 'gph'): 6487.9, ('450mb', 'temp'): 251.26, ('450mb', 'dewpt'): 239.39, ('450mb', 'dir'): 289.79, ('450mb', 'speed'): 34.0, ('425mb', 'gph'): 6902.76, ('425mb', 'temp'): 248.02, ('425mb', 'dewpt'): 233.63, ('425mb', 'dir'): 293.14, ('425mb', 'speed'): 38.0, ('400mb', 'gph'): 7342.78, ('400mb', 'temp'): 244.58, ('400mb', 'dewpt'): 226.55, ('400mb', 'dir'): 295.98, ('400mb', 'speed'): 43.0, ('375mb', 'gph'): 7798.48, ('375mb', 'temp'): 241.27, ('375mb', 'dewpt'): 223.77, ('375mb', 'dir'): 295.9, ('375mb', 'speed'): 49.0, ('350mb', 'gph'): 8285.64, ('350mb', 'temp'): 237.73, ('350mb', 'dewpt'): 220.79, ('350mb', 'dir'): 295.83, ('350mb', 'speed'): 55.0, ('325mb', 'gph'): 8791.36, ('325mb', 'temp'): 233.48, ('325mb', 'dewpt'): 220.96, ('325mb', 'dir'): 292.78, ('325mb', 'speed'): 57.0, ('300mb', 'gph'): 9337.58, ('300mb', 'temp'): 228.89, ('300mb', 'dewpt'): 219.65, ('300mb', 'dir'): 289.8, ('300mb', 'speed'): 60.0, ('275mb', 'gph'): 9909.7, ('275mb', 'temp'): 225.04, ('275mb', 'dewpt'): 216.01, ('275mb', 'dir'): 288.82, ('275mb', 'speed'): 60.0, ('250mb', 'gph'): 10536.4, ('250mb', 'temp'): 220.82, ('250mb', 'dewpt'): 212.03, ('250mb', 'dir'): 287.75, ('250mb', 'speed'): 60.0, ('225mb', 'gph'): 11207.71, ('225mb', 'temp'): 218.23, ('225mb', 'dewpt'): 208.96, ('225mb', 'dir'): 285.43, ('225mb', 'speed'): 61.0, ('200mb', 'gph'): 11958.17, ('200mb', 'temp'): 215.33, ('200mb', 'dewpt'): 205.5, ('200mb', 'dir'): 282.93, ('200mb', | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
11958.17, ('200mb', 'temp'): 215.33, ('200mb', 'dewpt'): 205.5, ('200mb', 'dir'): 282.93, ('200mb', 'speed'): 63.0, ('175mb', 'gph'): 12802.98, ('175mb', 'temp'): 216.25, ('175mb', 'dewpt'): 202.77, ('175mb', 'dir'): 287.48, ('175mb', 'speed'): 56.0, ('150mb', 'gph'): 13778.24, ('150mb', 'temp'): 217.31, ('150mb', 'dewpt'): 194.46, ('150mb', 'dir'): 294.22, ('150mb', 'speed'): 49.0, ('125mb', 'gph'): 14926.09, ('125mb', 'temp'): 215.54, ('125mb', 'dewpt'): 192.81, ('125mb', 'dir'): 292.33, ('125mb', 'speed'): 42.0, ('100mb', 'gph'): 16330.96, ('100mb', 'temp'): 213.37, ('100mb', 'dewpt'): 190.79, ('100mb', 'dir'): 288.86, ('100mb', 'speed'): 33.0, ('75mb', 'gph'): 18120.98, ('75mb', 'temp'): 214.0, ('75mb', 'dewpt'): 189.51, ('75mb', 'dir'): 291.2, ('75mb', 'speed'): 24.0, ('50mb', 'gph'): 20643.88, ('50mb', 'temp'): 214.89, ('50mb', 'dewpt'): 186.35, ('50mb', 'dir'): 300.53, ('50mb', 'speed'): 12.0}} | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
In the data provided above the I dropped the unused values as such...
PROPS_2_DROP = ['gph_dval', 'temp_dval', 'clouds', 'fl-vis', 'icing_type', 'cwmr',
'rh', 'theta-e', 'parcel_temp', 'vvs', 'mixing_ratio', 'turbulence']
midf = self.DataFrame[range(0, 2)].drop('sfc').drop(labels=PROPS_2_DROP, level='props')
midf.to_dict(orient='dict' )
data_dict -> MultiIndex.DataFrame
midf = pd.DataFrame(data_dict) | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
data_dict -> MultiIndex.DataFrame
midf = pd.DataFrame(data_dict)
DataFrame
0 1 2 3 4 5 ... 139 140 141 142 143 144
lvl props ...
sfc mean_slp 1019.73 1019.50 1019.19 1018.83 1019.03 1019.02 ... 995.10 995.44 995.79 995.99 996.20 996.41
altimeter 30.10 30.09 30.09 30.07 30.08 30.08 ... 29.37 29.38 29.39 29.40 29.40 29.41
press_alt 285.78 291.39 299.50 309.49 304.92 305.71 ... 963.21 953.97 944.74 939.51 934.28 929.05
density_alt -55.22 -88.18 -135.38 -186.09 -235.12 -262.16 ... 1265.79 1224.16 1182.28 1137.12 1091.92 1046.88
2_m_agl_tmp 283.50 283.17 282.70 282.18 281.82 281.59 ... 287.05 286.84 286.62 286.34 286.06 285.78
... ... ... ... ... ... ... ... ... ... ... ... ... ...
50mb mixing_ratio 0.00 0.00 0.00 0.00 0.00 0.00 ... 0.00 0.00 0.00 0.00 0.00 0.00
cwmr 0.00 0.00 0.00 0.00 0.00 0.00 ... 0.00 0.00 0.00 0.00 0.00 0.00
icing_type -1.00 -1.00 -1.00 -1.00 -1.00 -1.00 ... -1.00 -1.00 -1.00 -1.00 -1.00 -1.00
turbulence 0.00 0.00 0.00 0.00 0.00 0.00 ... 0.00 0.00 0.00 0.00 0.00 0.00
vvs 0.00 0.00 -0.00 -0.00 -0.00 0.00 ... -0.00 -0.00 -0.00 -0.00 -0.00 0.00
[804 rows x 145 columns] | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
[804 rows x 145 columns]
There are various methods for working with the forecast DataFrame. The one I've been working on tonight slices and structures data into a JSON object that is sent to a TypeScript application.
types
type Dataset = Datum[][];
type Datums = Datum[];
interface Datum {
press: number;
hght: number;
temp: number;
dwpt: number;
wdir: number;
wspd: number;
};
method
DICT_KEYS = ['temp', 'dwpt', 'wdir', 'wspd', 'hght', 'press']
ABSOLUTE_ZERO = -273.15
def feature_skewt_dataset(self, start=0, stop=30) -> Dict[str, List[List[Dict[str, int]]]]:
# slice multi-index-dataframe time by argument range
midf = self.DataFrame[range(start, stop)]
# kelvin to celcius
temperature = midf.loc[(slice(None), "temp"), :] + ABSOLUTE_ZERO # - 273.15
dewpoint = midf.loc[(slice(None), "dewpt"), :] + ABSOLUTE_ZERO #- 273.15
wind_speed = midf.loc[(slice(None), "speed"), :]
wind_direction = midf.loc[(slice(None), "dir"), :]
geopotential_height = midf.loc[(slice(None), "gph"), :]
# milibars = self._make_mbars(39)
# milibars = midf.droplevel(1).index.unique().str.strip('mb')
milibars = midf.index.get_level_values('lvl').unique().str.rstrip('mb')
# STEP 3 zip the keys -> stack
dataset = [[dict(zip(DICT_KEYS, stack))for stack in np.column_stack([
# STEP 2 -> slice the properties by the time index
temperature.loc[:, time_index],
dewpoint.loc[:, time_index],
wind_direction.loc[:, time_index],
wind_speed.loc[:, time_index],
geopotential_height.loc[:, time_index],
milibars
# STEP 1 -> iterate the time_index column index
]).astype(int)] for time_index in midf.columns]
return {'dataset': dataset} | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
return {'dataset': dataset}
Answer: It's good that you provided data_dict. In my suggested code, I had first dumped this dataframe to a pickle to be able to get it back without fuss and without having to include it in the source code verbatim.
You initially didn't define your pressure quantity; _make_mbars was missing. You now say that it's effectively
midf.droplevel(1).index.unique( ).str.strip('mb')
but this is non-ideal for a collection of reasons:
you don't actually want to get unique values, but instead want to associate each value with a row;
you should use rstrip instead of strip;
you need to cast to integers; and
rather than droplevel, for this use you should just use get_level_values.
Likewise, you failed to provide the whole class so I ignored self and just accepted a starting dataframe as a function parameter.
You're over-abbreviating your column and variable names. Just write the names in plain English. You offered two reasons for the abbreviated names, the first being that you need to adhere to a NOAA format. Externally that's fine; but internally you should use sane names and not the names you're required to use in external serialised formats.
The second reason you offered for over-abbreviation is
they are being called in a React d3 application [...] frequently | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
they are being called in a React d3 application [...] frequently
Cutting a couple of characters in your field names is premature and mis-directed optimisation. There are plenty of opportunities for actual optimisation elsewhere.
Put 273.15 into a constant rather than leaving it as a magic number. When you subtract this number, it's probably a good idea to round(); I was conservative and rounded to 12 decimals to cut the error. This is only possible because your real data stop at two decimals.
Most of your difficulty comes from the fact that your data frame is effectively rotated, and needs to be rotated again to be sane. In Pandas terminology this rotation is called stacking. You need to unstack your property names to columns, and you need to stack your time columns to indices. Once this is done, the data are much, much easier to manipulate with (nearly) stock Pandas functions.
Suggested
from pprint import pprint
import pandas as pd
ABSOLUTE_ZERO = -273.15
def kelvin_to_celsius(temperature: pd.Series) -> pd.Series:
return (temperature + ABSOLUTE_ZERO).round(decimals=12)
def sanitise(df: pd.DataFrame) -> pd.DataFrame:
stacked: pd.DataFrame = df.stack().unstack(level=1)
stacked.rename(
columns={
'dewpt': 'dewpoint',
'gph': 'height',
'dir': 'wind_direction',
'speed': 'wind_speed',
'temp': 'temperature',
},
inplace=True,
)
stacked.temperature = kelvin_to_celsius(stacked.temperature)
stacked.dewpoint = kelvin_to_celsius(stacked.dewpoint)
stacked['pressure'] = (
stacked.index.get_level_values(level=0)
.str.rstrip('mb').astype(int)
)
return stacked.droplevel(0)
def feature_skewt_dataset(
midf: pd.DataFrame,
start_time: int = 0,
stop_time: int = 30,
) -> dict[str, list]:
# Since the index only contains time and is non-unique, we cannot use
# to_dict(orient='index') | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
python, numpy, pandas
return {
'dataset': [
midf.loc[time_index].to_dict(orient='records')
for time_index in range(start_time, stop_time)
]
}
def test() -> None:
insane = pd.read_pickle('midf.pickle')
sane = sanitise(insane)
dataset = feature_skewt_dataset(sane, stop_time=2)
pprint(dataset)
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 42765,
"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, pandas",
"url": null
} |
c#, winforms
Title: Optimize the data adding process to datatable from excel file
Question: I'm creating a simple windows form application containing a combo box, a text box, a datagridview, a button and some radio buttons. The idea is upon the form loading the combo box is to be populated with the data of a specific column ("Party") of a source excel file. Then when a valid item is selected from the combo box, the excel file data is to be filtered and shown in the datagridview. Further filtering can be done by entering some text to the text box and then hitting a button.
Please find below my code to understand it better:
void DataFormLoad(object sender, EventArgs e)
{
ExcelPackage.LicenseContext =LicenseContext.NonCommercial;
int lastRow = 0;
using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(@"database.xlsx"), false))
{
ExcelWorksheet mainSheet = package.Workbook.Worksheets.First();
for (int i = 2; i <= mainSheet.Dimension.End.Row; i++)
{
if (!string.IsNullOrEmpty(mainSheet.Cells["A"+i].Text))
{
lastRow =i;
}
}
List<string> party = new List<string>();
for (int row = 2; row <= lastRow; row++)
{
if (!string.IsNullOrEmpty(mainSheet.Cells[row, 1].Text))
{
party.Add(mainSheet.Cells[row, 1].Text);
}
}
foreach (var element in party.Distinct())
{
kryptonComboBox1.Items.Add(element);
}
}
kryptonLabel2.Text = "Enter full invoice number or a part of it";
}
void KryptonComboBox1SelectedIndexChanged(object sender, EventArgs e)
{ | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
}
void KryptonComboBox1SelectedIndexChanged(object sender, EventArgs e)
{
kryptonDataGridView1.DataSource=null;
kryptonTextBox1.Text="";
int rowno = 0;
string kword = kryptonComboBox1.Text;
using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(@"database.xlsx"), false))
{
ExcelWorksheet workSheet = package.Workbook.Worksheets[0];
for (int i = 2; i <= workSheet.Dimension.End.Row; i++)
{
if (!string.IsNullOrEmpty(workSheet.Cells["A"+i].Text))
{
rowno =i;
}
}
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("Party");
dtTemp.Columns.Add("Bill No.");
dtTemp.Columns.Add("Bill Date");
dtTemp.Columns.Add("Amount");
dtTemp.Columns.Add("Due Date");
dtTemp.Columns.Add("Remarks");
dtTemp.Columns.Add("Payment Released on");
DataRow drAddItem;
for (int row = 2; row <= rowno; row++)
{
if (workSheet.Cells[row, 1].Text == kword)
{
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow(); | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
drAddItem = dtTemp.NewRow();
drAddItem["Party"] = col1Value.ToString();
drAddItem["Bill No."] = col2Value.ToString();
drAddItem["Bill Date"] = col3Value.ToString();
drAddItem["Amount"] = col4Value.ToString();
drAddItem["Due Date"] = col5Value.ToString();
drAddItem["Remarks"] = col6Value.ToString();
drAddItem["Payment Released on"] = col8Value.ToString();
dtTemp.Rows.Add(drAddItem);
}
}
kryptonDataGridView1.DataSource=dtTemp;
}
}
void KryptonComboBox1Leave(object sender, EventArgs e)
{
var indx = kryptonComboBox1.FindStringExact(kryptonComboBox1.Text);
if(indx <= -1)
{
MetroMessageBox.Show(this,"Please type/select a valid Party Name","Invalid Party Name",MessageBoxButtons.OK,MessageBoxIcon.Error);
kryptonComboBox1.Text="";
return;
}
}
void KryptonButton1Click(object sender, EventArgs e)
{
kryptonDataGridView1.DataSource=null;
int rowno = 0;
string kword = kryptonComboBox1.Text;
string kword2 = kryptonTextBox1.Text;
double kw;
using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(@"database.xlsx"), false))
{
ExcelWorksheet workSheet = package.Workbook.Worksheets[0]; | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
for (int i = 2; i <= workSheet.Dimension.End.Row; i++)
{
if (!string.IsNullOrEmpty(workSheet.Cells["A"+i].Text))
{
rowno =i;
}
}
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("Party");
dtTemp.Columns.Add("Bill No.");
dtTemp.Columns.Add("Bill Date");
dtTemp.Columns.Add("Amount");
dtTemp.Columns.Add("Due Date");
dtTemp.Columns.Add("Remarks");
dtTemp.Columns.Add("Payment Released on");
DataRow drAddItem;
for (int row = 2; row <= rowno; row++)
{
if (kryptonRadioButton1.Checked)
{
if (workSheet.Cells[row, 1].Text == kword && workSheet.Cells[row, 2].Text.ToUpper().Contains(kword2.ToUpper()))
{
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow(); | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
drAddItem = dtTemp.NewRow();
drAddItem["Party"] = col1Value.ToString();
drAddItem["Bill No."] = col2Value.ToString();
drAddItem["Bill Date"] = col3Value.ToString();
drAddItem["Amount"] = col4Value.ToString();
drAddItem["Due Date"] = col5Value.ToString();
drAddItem["Remarks"] = col6Value.ToString();
drAddItem["Payment Released on"] = col8Value.ToString();
dtTemp.Rows.Add(drAddItem);
}
}
if (kryptonRadioButton2.Checked)
{
try
{
Convert.ToDateTime(kword2).ToString("dd-MM-yyyy");
}
catch
{
MessageBox.Show("Please enter a valid date!!\n");
kryptonTextBox1.Text="";
break;
}
if (workSheet.Cells[row, 1].Text == kword && workSheet.Cells[row, 3].Text == Convert.ToDateTime(kword2).ToString("dd-MM-yyyy"))
{
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow(); | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
drAddItem = dtTemp.NewRow();
drAddItem["Party"] = col1Value.ToString();
drAddItem["Bill No."] = col2Value.ToString();
drAddItem["Bill Date"] = col3Value.ToString();
drAddItem["Amount"] = col4Value.ToString();
drAddItem["Due Date"] = col5Value.ToString();
drAddItem["Remarks"] = col6Value.ToString();
drAddItem["Payment Released on"] = col8Value.ToString();
dtTemp.Rows.Add(drAddItem);
}
}
if (kryptonRadioButton3.Checked)
{
if (double.TryParse(kword2,out kw))
{
if (workSheet.Cells[row, 1].Text == kword && Convert.ToDouble(workSheet.Cells[row, 4].Text).ToString() == Math.Round(kw,2).ToString())
{
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow(); | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
drAddItem = dtTemp.NewRow();
drAddItem["Party"] = col1Value.ToString();
drAddItem["Bill No."] = col2Value.ToString();
drAddItem["Bill Date"] = col3Value.ToString();
drAddItem["Amount"] = col4Value.ToString();
drAddItem["Due Date"] = col5Value.ToString();
drAddItem["Remarks"] = col6Value.ToString();
drAddItem["Payment Released on"] = col8Value.ToString();
dtTemp.Rows.Add(drAddItem);
}
}
else
{
MessageBox.Show("Please enter a numeric value");
break;
}
}
}
kryptonDataGridView1.DataSource=dtTemp;
}
}
void KryptonRadioButton2CheckedChanged(object sender, EventArgs e)
{
kryptonTextBox1.Text="";
kryptonTextBox1.Focus();
kryptonLabel2.Text = "Enter a complete date (day, then month and then year)";
}
void KryptonRadioButton3CheckedChanged(object sender, EventArgs e)
{
kryptonTextBox1.Text="";
kryptonTextBox1.Focus();
kryptonLabel2.Text = "Enter exact amount as per Invoice";
}
void KryptonRadioButton1CheckedChanged(object sender, EventArgs e)
{
kryptonTextBox1.Text="";
kryptonTextBox1.Focus();
kryptonLabel2.Text = "Enter full invoice number or a part of it";
} | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
c#, winforms
The code is very redundant, specially the portion
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow();
drAddItem["Party"] = col1Value.ToString();
drAddItem["Bill No."] = col2Value.ToString();
drAddItem["Bill Date"] = col3Value.ToString();
drAddItem["Amount"] = col4Value.ToString();
drAddItem["Due Date"] = col5Value.ToString();
drAddItem["Remarks"] = col6Value.ToString();
drAddItem["Payment Released on"] = col8Value.ToString();
dtTemp.Rows.Add(drAddItem);
How can I make it less redundant and efficient? What other changes can be made to make the code faster if possible?
The app UI looks like this
The excel looks like
Answer: In order to reduce repetitive code you need to understand which steps of actions you are repeating
//Retrieving column values for a given row from 1 to 8 except 7
object col1Value = workSheet.Cells[row, 1].Text;
object col2Value = workSheet.Cells[row, 2].Text;
object col3Value = workSheet.Cells[row, 3].Text;
object col4Value = workSheet.Cells[row, 4].Text;
object col5Value = workSheet.Cells[row, 5].Text;
object col6Value = workSheet.Cells[row, 6].Text;
object col8Value = workSheet.Cells[row, 8].Text;
drAddItem = dtTemp.NewRow(); | {
"domain": "codereview.stackexchange",
"id": 42766,
"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#, winforms",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.