text stringlengths 1 2.12k | source dict |
|---|---|
python, web-scraping, selenium
if __name__ == "__main__":
browser = getBrowser()
print(f'''Call to getISINUrls start at: {datetime.now()}''')
bonds = getISINUrls(browser)
print(f'''Call to getISINUrls ends at : {datetime.now()}''')
print(f'''total records: {len(bonds)}''')
browser.close()
browser2 = getBrowser()
print(f'''Call to getISINData start at: {datetime.now()}''')
getISINData(browser2)
print(f'''Call to getISINData ends at : {datetime.now()}''')
saveURLs(bonds)
browser2.close()
sys.exit(0)
Answer: Whereas it would be nice to use an official API, I don't see any.
Scraping is morally ambiguous and in each case you need to think about the impact to the service. In this case I don't feel too bad about doing it.
If you were to keep using Selenium, don't use BeautifulSoup: your browser already has a DOM, so you don't want a secondary library doing HTML parsing. But much more importantly, don't use Selenium at all, and don't even hit the HTML URLs themselves. Invest some time in reverse engineering and you'll see that the data actually come from a (strange, inconsistent, poorly-designed) API that is exposed unauthenticated to the internet. You can see traffic to this API in the developer tools of your favourite browser.
Don't call sleep. Even if you were to keep Selenium, there are better ways to wait for conditions to be met.
Don't save the URLs: instead, just save the instrument IDs.
Don't use Pandas, since you're just writing to a CSV file; use the built-in CSV support.
Don't exit(0) at the end; that's redundant.
Suggested
import csv
from typing import Iterator, Iterable, Literal
from xml.etree import ElementTree
from requests import Session, Response
class APIError(Exception):
pass | {
"domain": "codereview.stackexchange",
"id": 42834,
"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, web-scraping, selenium",
"url": null
} |
python, web-scraping, selenium
from requests import Session, Response
class APIError(Exception):
pass
def fetch_data(
session: Session,
xml_query: str,
bond_type: Literal[
'doMortgageCreditAndSpecialInstitutions',
'doGovernment',
'doStructuredBonds',
] = 'doMortgageCreditAndSpecialInstitutions',
) -> Response:
with session.post(
url='http://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx',
headers={
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
},
cookies={'bonds_dk_search_view': bond_type},
data={'xmlquery': xml_query},
timeout=5,
) as resp:
resp.raise_for_status()
if resp.text == 'Invalid Request':
raise APIError()
return resp
def get_isin_ids(session: Session) -> Iterator[str]:
xml_query = '''<post>
<param name="Exchange" value="NMF"/>
<param name="SubSystem" value="Prices"/>
<param name="Market" value="GITS:CO:CPHCB"/>
<param name="Action" value="GetMarket"/>
<param name="inst__an" value="ed,itid"/>
<param name="XPath" value="//inst[@ed!='' and (@itid='2' or @itid='3')]"/>
<param name="RecursiveMarketElement" value="True"/>
<param name="inst__e" value="7"/>
<param name="app" value="/bonds/denmark/"/>
</post>'''
xml_response = fetch_data(session, xml_query).text
doc = ElementTree.fromstring(xml_response)
for institution in doc.findall('./inst'):
yield institution.attrib['id']
def save_ids(ids: Iterable[str]) -> None:
with open('linkstoday.txt', 'w') as fo:
for id in ids:
fo.write(id + '\n') | {
"domain": "codereview.stackexchange",
"id": 42834,
"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, web-scraping, selenium",
"url": null
} |
python, web-scraping, selenium
def get_isin_data(session: Session, ids: Iterable[str]) -> Iterator[dict[str, str]]:
for id in ids:
xml_query = f'''<post>
<param name="Exchange" value="NMF"/>
<param name="SubSystem" value="Prices"/>
<param name="Action" value="GetInstrument"/>
<param name="inst__a" value="0,1,2,5,21,23"/>
<param name="Exception" value="false"/>
<param name="ext_xslt" value="/nordicV3/inst_table.xsl"/>
<param name="Instrument" value="{id}"/>
<param name="inst__an" value="id,nm,oa,dp,drd"/>
<param name="inst__e" value="1,3,6,7,8"/>
<param name="trd__a" value="7,8"/>
<param name="t__a" value="1,2,10,7,8,18,31"/>
<param name="json" value="1"/>
<param name="app" value="/bonds/denmark/microsite"/>
</post>'''
doc = fetch_data(session, xml_query).json()['inst']
record = {
'ISIN': doc['@id'],
'ShortName': doc['@nm'],
'OutstandingVolume': doc['@oa'],
'RepaymentDate': doc['@drd'],
'DrawingPercent': doc['@dp'],
}
yield record
def save_csv(records: Iterable[dict[str, str]]) -> None:
with open('DenmarkScrapeData.csv', 'w', newline='') as f:
writer = csv.DictWriter(
f=f, fieldnames=(
'ISIN',
'ShortName',
'OutstandingVolume',
'RepaymentDate',
'DrawingPercent',
))
writer.writeheader()
writer.writerows(records)
def main() -> None:
with Session() as session:
session.headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) '
'Gecko/20100101 '
'Firefox/96.0',
}
ids = tuple(get_isin_ids(session))
print(f'total records: {len(ids)}')
save_ids(ids)
records = get_isin_data(session, ids)
save_csv(records)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 42834,
"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, web-scraping, selenium",
"url": null
} |
python, web-scraping, selenium
Output
This output comes from letting the program run for a few seconds and then cancelling it:
ISIN,ShortName,OutstandingVolume,RepaymentDate,DrawingPercent
XCSE-0:5_111.E.33,"-0,5 111.E.33",84493151,2022-01-01,2.8112571826
XCSE-0:5_PCT_111.E_2030,"-0,5 pct 111.E 2030",665797291,2022-01-01,3.2633533803
XCSE-0:5RDS20S33,"-0,5RDS20S33",451515514,2022-01-01,2.9740738964
XCSE-05NYK01EA30,-05NYK01EA30,878951074,2022-01-01,3.3091375583
XCSE-05NYK01EA33,-05NYK01EA33,881317489,2022-01-01,2.8425761917
XCSE0_111.E.33,0 111.E.33,653907754,2022-01-01,2.4804408498
XCSE0_111.E.38,0 111.E.38,564600489,2022-01-01,1.855852439
XCSE0_111.E.43,0 111.E.43,176772175,2022-01-01,1.3165659355
XCSE0_PCT_111.E.30,0 pct 111.E.30,1029518700,2022-01-01,5.9398552916
XCSE0_PCT_111.E.40,0 pct 111.E.40,1977182808,2022-01-01,1.554107146
XCSE0:0_42A_B_2040,"0,0 42A B 2040",209526702,2022-01-01,1.7771871286
XCSE0:0_ANN_2040,"0,0 Ann 2040",56394289,2022-01-01,1.5425031762
XCSE0:00NDASDRO30,"0,00NDASDRO30",1224109240,2022-01-01,3.8723465773
XCSE0:0NDASDRO33,"0,0NDASDRO33",860502381,2022-01-01,2.2338528235
XCSE0:0NDASDRO40,"0,0NDASDRO40",1459255905,2022-01-01,1.4938027118
XCSE0:0NDASDRO43,"0,0NDASDRO43",236599645,2022-01-01,1.3792804762
XCSE0:0RDSD20S33,"0,0RDSD20S33",718629368,2022-01-01,2.4815379285
XCSE0:0RDSD21S35,"0,0RDSD21S35",3462720875,2022-01-01,2.0717949411
XCSE0:0RDSD21S38,"0,0RDSD21S38",2251018344,2022-01-01,1.7993154025
XCSE0:0RDSD22S40,"0,0RDSD22S40",2011886347,2022-01-01,1.4705608857
XCSE0:0RDSD22S43,"0,0RDSD22S43",184303670,2022-01-01,0.8792686726
XCSE0:5_111.E.38,"0,5 111.E.38",338880761,2022-01-01,1.3969909037
XCSE0:5_411.E.OA.53,"0,5 411.E.OA.53",1393252566,2022-01-01,0.0591983882
XCSE0:5_42A_B_2040,"0,5 42A B 2040",8131539033,2022-01-01,1.3671120294
XCSE0:5_ANN_2040,"0,5 Ann 2040",451401810,2022-01-01,2.4906658405
XCSE0:5_ANN_2050,"0,5 Ann 2050",653730646,2022-01-01,0.8698109475
XCSE0:5_B_2043,"0,5 B 2043",3606287111,2022-01-01,1.2922558113 | {
"domain": "codereview.stackexchange",
"id": 42834,
"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, web-scraping, selenium",
"url": null
} |
python, web-scraping, selenium
XCSE0:5_B_2043,"0,5 B 2043",3606287111,2022-01-01,1.2922558113
XCSE0:5_B_2053,"0,5 B 2053",1642437254,2022-01-01,0.8121455742
XCSE0:5_OA_2050,"0,5 OA 2050",99003000,2022-01-01,0.0
XCSE0:5_OA_43A_B_2050,"0,5 OA 43A B 2050",482048871,2022-01-01,0.0
XCSE0:5_OA_B_2053,"0,5 OA B 2053",219089000,2022-01-01,0.0
XCSE0:5_PCT_111.E.27,"0,5 pct 111.E.27",283502208,2022-01-01,8.3610097198
XCSE0:5_PCT_111.E.35,"0,5 pct 111.E.35",1583753306,2022-01-01,2.5446722633
XCSE0:5_PCT_111.E.40,"0,5 pct 111.E.40",6407716782,2022-01-01,1.4303071825
XCSE0:5_PCT_111.E.50,"0,5 pct 111.E.50",10350998334,2022-01-01,0.9164192286
XCSE0:5_PCT_411.E.OA.50,"0,5 pct 411.E.OA.50",3087755141,2022-01-01,0.0671974779
XCSE0:50_43_A_B_2050,"0,50 43 A B 2050",1343369361,2022-01-01,0.8540709785
XCSE0:5NDASDRO27,"0,5NDASDRO27",481074018,2022-01-01,8.803025784
XCSE0:5NDASDRO30,"0,5NDASDRO30",881168727,2022-01-01,7.5241365836
XCSE0:5NDASDRO40,"0,5NDASDRO40",11220224408,2022-01-01,1.5304442894
XCSE0:5NDASDRO43,"0,5NDASDRO43",5986915933,2022-01-01,1.3334597191
XCSE0:5NDASDRO50,"0,5NDASDRO50",9229180944,2022-01-01,0.8712084834
XCSE0:5NDASDRO53,"0,5NDASDRO53",6247426527,2022-01-01,0.8375194931
XCSE0:5NDASDROOA50,"0,5NDASDROOA50",5461281793,2022-01-01,0.0083519478
XCSE0:5NDASDROOA53,"0,5NDASDROOA53",3175404000,2022-01-01,0.0
XCSE0:5NYK01EA27,"0,5NYK01EA27",1269241062,2022-01-01,8.7144274945
XCSE0:5NYK01EA30,"0,5NYK01EA30",1753360650,2022-01-01,6.3398581018
XCSE0:5NYK01EA35,"0,5NYK01EA35",3850470214,2022-01-01,2.2289106154
XCSE0:5NYK01EA38,"0,5NYK01EA38",2292707137,2022-01-01,1.6186901466
XCSE0:5NYK01EA40,"0,5NYK01EA40",25051403176,2022-01-01,1.410155416
XCSE0:5NYK01EA50,"0,5NYK01EA50",23594969156,2022-01-01,0.8777441213
XCSE0:5NYK01EDA50,"0,5NYK01EDA50",9778359698,2022-01-01,0.010495042
XCSE0:5NYK01EDA53,"0,5NYK01EDA53",7720300441,2022-01-01,0.0015823625
XCSE0:5NYK01IA43,"0,5NYK01IA43",152247394,2022-01-01,1.2410533255 | {
"domain": "codereview.stackexchange",
"id": 42834,
"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, web-scraping, selenium",
"url": null
} |
python, json, api
Title: Collect values from an api more quickly
Question: To collect the values of an api, I use three loopings, I would like to know if it is possible to improve this method that I use.
a = 9625897
def graph(a):
url = f'https://api.sofascore.com/api/v1/event/{a}/graph'
response = requests.get(url, headers=headers, timeout=1).json()
if 'graphPoints' in response:
minutes_list = [d['minute'] for d in response['graphPoints'][-5:]]
value_list = [d['value'] for d in response['graphPoints'][-5:]]
sum_list = sum(abs(d['value']) for d in response['graphPoints'][-5:])
else:
minutes_list = ['graph_error']
value_list = ['graph_error']
sum_list = ['graph_error']
return [minutes_list,value_list,sum_list]
Answer: You can simply use a conventional for loop, instead of comprehensions:
minutes_list = []
value_list = []
value_sum = 0
if 'graphPoints' in response:
for d in response['graphPoints'][-5:]:
minutes_list.append(d['minute'])
value_list.append(d['value'])
value_sum += abs(d['value'])
return [minutes_list, value_list, [value_sum]]
else:
return [['graph_error'], ['graph_error'], ['graph_error']] | {
"domain": "codereview.stackexchange",
"id": 42835,
"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, json, api",
"url": null
} |
react.js, nginx, docker
Title: nginx react.js dockerfile
Question: https://github.com/bbachi/nextjs-nginx-docker
https://github.com/bbachi/nextjs-nginx-docker/blob/main/Dockerfile
# stage1 as builder
FROM node:10-alpine as builder
# copy the package.json to install dependencies
COPY package.json package-lock.json ./
# Install the dependencies and make the folder
RUN npm install && mkdir /nextjs-ui && mv ./node_modules ./nextjs-ui
WORKDIR /nextjs-ui
COPY . .
# Build the project and copy the files
RUN npm run build
FROM nginx:alpine
#!/bin/sh
COPY ./.nginx/nginx.conf /etc/nginx/nginx.conf
## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*
# Copy from the stahg 1
COPY --from=builder /nextjs-ui/out /usr/share/nginx/html
EXPOSE 3000 80
ENTRYPOINT ["nginx", "-g", "daemon off;"]
https://github.com/bbachi/nextjs-nginx-docker/blob/main/.nginx/nginx.conf
worker_processes 4;
events { worker_connections 1024; }
http {
server {
listen 80;
root /usr/share/nginx/html;
include /etc/nginx/mime.types;
location /appui {
try_files $uri /index.html;
}
}
}
Wondering if there's anything that can make it faster.
Answer: To make it faster?
(Assuming "it" is the build)
Look into buildkit, see this SO question:
https://stackoverflow.com/questions/65913706/how-do-i-make-yarn-cache-modules-when-building-containers
Otherwise, using yarn instead of npm might speed you up a little bit in the building process.
(Assuming "it" is the NextJS server (building))
Make sure that you are using Next version >12. The Rust compiler is MUCH faster than the javascript one.
(Assuming "it" is the NextJS server (running))
Make sure that all of your pages (or as many as possible) are statically generated. This allows the Next Server to serve them on demand instead of needing to Server Side Render them on demand. | {
"domain": "codereview.stackexchange",
"id": 42836,
"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": "react.js, nginx, docker",
"url": null
} |
javascript, game, ecmascript-6, phaser.io
Title: a tiny rpg game using Phaser 3
Question: I wrote a tiny game using Phaser 3, here is the code.
var total_attack = 0;
var isMagicReady = false;
class BootScene extends Phaser.Scene {
constructor() {
super({ key: 'BootScene' });
console.log(total_attack);
}
preload() {
this.load.path = 'https://raw.githubusercontent.com/albert10jp/web_rpg/main/btn_cast_spell/assets/';
this.load.spritesheet('cooldown_sheet', 'cooldown_sheet.png', { frameWidth: 48, frameHeight: 48 });
this.load.image('magicAttack', 'magicAttack.png');
this.load.atlas('bolt', 'bolt_atlas.png', 'bolt_atlas.json');
// load brawler (player)
this.load.spritesheet('brawler', 'brawler48x48.png', {
frameWidth: 48, frameHeight: 48
});
// load frog (enemies)
this.load.path = 'https://raw.githubusercontent.com/albert10jp/web_rpg/main/btn_cast_spell/assets/frog/';
for (var i = 1; i < 3; i++) {
this.load.image("frog_attack" + i, "frog" + i + ".gif");
}
}
setupAnimation() {
this.anims.create({
key: 'frog_idle',
frames: [
{ key: 'frog_attack1' },
{ key: 'frog_attack2' },
{ key: 'frog_attack1' },
],
frameRate: 2,
repeat: 1
});
this.anims.create({
key: 'player_attack',
frames: this.anims.generateFrameNumbers(
'brawler', { frames: [30, 31, 30] }),
frameRate: 2,
repeat: 0,
});
this.anims.create({
key: 'magic_effect',
frames: this.anims.generateFrameNames('bolt', {
// frames: [0, 1, 2, 3, 4, 5, 6, 7]
// prefix: 'bolt_ball_', start: 1, end: 10, zeroPad: 4
prefix: 'bolt_sizzle_', start: 1, end: 10, zeroPad: 4
}),
frameRate: 12,
repeat: 0,
});
this.anims.create({
key: 'cooldown_animation',
frames: this.anims.generateFrameNumbers('cooldown_sheet', { start: 0, end: 15 }),
frameRate: 6,
repeat: 0,
repeatDelay: 2000
});
} | {
"domain": "codereview.stackexchange",
"id": 42837,
"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, game, ecmascript-6, phaser.io",
"url": null
} |
javascript, game, ecmascript-6, phaser.io
animComplete(animation) {
if (animation.key === 'player_attack') {
this.bolt.visible = true;
this.bolt.play('magic_effect');
this.magicAttackBtn.play('cooldown_animation');
}
}
setupBtn(btn_x, btn_y) {
this.add.image(btn_x, btn_y, 'magicAttack').setScale(.5)
this.magicAttackBtn = this.add.sprite(btn_x, btn_y, 'cooldown_sheet').setFlipX(false).setScale(1)
this.magicAttackBtn.on('animationcomplete', () => {
isMagicReady = true;
if (total_attack < 3) {
this.noti.setText('Magic is ready now!');
}
});
let circle2 = this.add.circle(btn_x, btn_y, 150, 0x000000, 0).setScale(.1)
// circle.lineStyle(10, 0xffffff, 0.9);
circle2.setStrokeStyle(50, 0x000000, 1);
this.magicAttackBtn.setInteractive();
this.magicAttackBtn.on('pointerdown', () => {
if (total_attack < 3) {
if (isMagicReady) {
this.player.play('player_attack');
this.player.on('animationcomplete', this.animComplete, this);
this.noti.setText('');
isMagicReady = false;
// this.perform();
total_attack++;
}
else {
this.noti.setText('Magic is not ready yet!');
}
}
}, this);
this.noti = this.add.text(this.magicAttackBtn.x + 30, this.magicAttackBtn.y - 10, '');
this.noti.setFontSize(12);
}
setupBattle() {
this.magicAttackBtn.play('cooldown_animation');
this.enemies.forEach((enemy) => {
enemy.play('frog_idle', true);
enemy.setAlpha(1);
enemy.setTexture('frog_attack1');
});
// this.noti.setText('');
total_attack = 0;
isMagicReady = false;
}
createEnemy(x, y) {
let enemy = this.add.sprite(x, y, 'frog_attack1').setOrigin(0, 0);
enemy.setScale(.6);
enemy.flipX = true;
this.enemies.push(enemy);
}
setupBolt() {
this.bolt.setScale(2);
this.bolt.visible = false; | {
"domain": "codereview.stackexchange",
"id": 42837,
"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, game, ecmascript-6, phaser.io",
"url": null
} |
javascript, game, ecmascript-6, phaser.io
setupBolt() {
this.bolt.setScale(2);
this.bolt.visible = false;
this.bolt.on('animationcomplete', () => {
this.bolt.visible = false;
this.enemies.forEach((item) => {
item.stop();
item.setTexture('frog_attack1');
if (total_attack === 1) {
item.setAlpha(.7);
} else if (total_attack === 2) {
item.setAlpha(.3);
} else if (total_attack === 3) {
item.setAlpha(0);
this.noti.setText('Congratulations!\nMission complete!');
}
});
});
}
create() {
var offsetX = 300 / 2.5;
var offsetY = 220 / 2.5 - 15;
var incrementX = 25;
var incrementY = 15;
let btn_x = 20, btn_y = 180
this.setupBtn(btn_x, btn_y);
this.player = this.physics.add.sprite(100 / 2.5, offsetY, 'brawler', 30).setOrigin(0);
this.player.setScale(.6);
this.player.setFlipX(true);
this.enemies = [];
this.setupAnimation();
for (let y = 0; y < 3; y++) {
for (let x = 0; x < 5; x++) {
let posx = x * incrementX + offsetX;
let posy = y * incrementY + offsetY;
this.createEnemy(posx, posy);
}
}
this.bolt = this.add.sprite(offsetX + 3 * incrementX, offsetY + 2 * incrementY, 'bolt');
this.setupBolt();
this.setupBattle();
}
}
var config = {
width: 320,
height: 240,
zoom: 2.5,
// zoom:2,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 },
debug: false // set to true to view zones
}
},
backgroundColor: 0x000000,
scene: [BootScene]
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script> | {
"domain": "codereview.stackexchange",
"id": 42837,
"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, game, ecmascript-6, phaser.io",
"url": null
} |
javascript, game, ecmascript-6, phaser.io
The playable code above construct a battle scene where a hero fights against a bunch of enemies.
The hero only has one action to choose, cast a spell. Once the hero casts a spell, a cool-down animation starts. Only the cool-down animation finishes, the hero is allowed to cast the spell again.
The code works as expected though I'm not sure I use the component efficiently.
Answer: Review
The code looks okay. Indentation looks consistent. The code doesn't seem very redundant. Some of the methods are a bit on the long side - e.g. setupAnimation(), setupBtn(), etc. There are just a few suggestions - see below.
global variables
The variables total_attack and isMagicReady are used globally. While it may seem unlikely, it may be useful someday to have multiple BootScene instances - in that case those variables could be made instance variables, or else static variables on BootScene so they wouldn't collide with variables in other namespaces. It is recommended to avoid global variables.
config variables
In the declaration of config there is:
var config = {
width: 320,
height: 240,
zoom: 2.5,
And then within BootScene::create():
var offsetX = 300 / 2.5;
var offsetY = 220 / 2.5 - 15;
Perhaps instead of using 2.5 it makes sense to use this.scale.zoom or a similar variable.
let vs const
It is wise to default to using const, unless you know re-assignment is necessary - then use let. This will help avoid accidental re-assignment and other bugs | {
"domain": "codereview.stackexchange",
"id": 42837,
"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, game, ecmascript-6, phaser.io",
"url": null
} |
python, beginner, game
Title: (Beginner) Mastermind game in Python
Question: After completing an introduction to Python tutorial, I wanted to put my basic knowledge of control flow and data structures to use, and felt this was a great choice for my first program.
I created the below to run in Jupyter Notebook / Visual Studio Code terminal. It behaves like an over-the-board version, based on colours and pins.
Without experience of how to structure code I found myself putting everything into functions and used functions within functions, rightly or wrongly, leaving only a small amount of what I've called 'main game code'. Feedback on how I should structure properly, or resources to that effect would be greatly appreciated.
I used no guides nor copied online code, so the code is a bit bloated, I imagine, as a first attempt. I've tried to make it a bit more user friendly running in the terminal so there are a lot of input validations and line spaces as I wanted to actually play this with my housemate and it not be a horrible experience.
Summary of the rules
2 players, playing at least 2 games, each getting a chance to be the codemaker and codebreaker.
Two game modes: Beginner or Mastermind. The latter allows the codemaker to use colours more than once.
Three difficulty settings: Easy, Medium or Hard. The difficulty determines the number of guesses the codebreaker gets.
Points earned, and tallied across all games, by the player acting as codemaker for each guess the codebreaker makes, with a bonus point if the codebreaker fails entirely.
def getPlayers():
player1 = input("Player 1, you will start as the Codemaker. What is your name? ")
print("Player 1 is",player1,"and will start as the Codemaker")
print()
player2 = input("Player 2, you will start as the Codebreaker. What is your name? ")
print("Player 2 is",player2,"and will start as the Codebreaker")
return player1, player2 | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
def checkUserInput(userInput):
try:
int(userInput)
return int
except (ValueError, TypeError):
try:
float(userInput)
return float
except (ValueError, TypeError):
return str
def getNumberOfGames():
while True:
numGames = input("How many games do you want to play? Min 2, Max 8. Remember, an even number of games must be played!")
userInputType = checkUserInput(numGames)
if userInputType == int:
if int(numGames) in range(2,9,2):
print()
print("You will be playing",numGames,"games")
print("----")
return numGames
break
else:
print("Your entry is incorrect, please try again")
def getMode():
D = {"B":"Beginner","M":"Mastermind"}
D2 = {"B":"the Codemaker cannot use the same colour more than once","M":"the Codemaker can use colours more than once"}
print("----")
print("Select game mode: Enter 'B' for Beginner, or, 'M' for Mastermind")
print()
while True:
mode = str.capitalize(input())
if mode in ("B","M"): #alternative way to write if mode == "B" or mode == "M"
print("You have selected",D[mode],"mode! In",D[mode],"mode",D2[mode])
print("----")
break
else:
print(mode,"is not a valid game mode, please select a game mode")
print()
return mode | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
def getDifficulty():
D = {"E":"Easy","M":"Medium","H":"Hard"}
D2 = {"E":12,"M":10,"H":8}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard")
print()
while True:
difficulty = str.capitalize(input())
if difficulty in ("E","M","H"):
print("You have selected",D[difficulty],"difficulty! The Codebreaker will get",D2[difficulty],"chances to crack the code!")
print("----")
break
else:
print(difficulty,"is not a valid option, please select a difficulty")
print()
return difficulty, D2[difficulty]
def duplicateColours(L):
for x in L:
if L.count(x) > 1:
return True
break
else:
pass
return False
def getNewCode(mode):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
L = []
print("Quickly, Codemaker! Enter a new 4 colour code to stop the Codebreaker from breaking into the vault!")
print("""
Select from the 8 available colours by typing the first letter of the colour: | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
White -- Enter 'W'
Red -- Enter 'R'
Blue -- Enter 'B'
Yellow -- Enter 'Y'
Purple -- Enter 'P'
Orange -- Enter 'O'
Green -- Enter 'G'
Silver -- Enter 'S'
"""
)
for cbsi in range (1,5):
while True:
print('Enter colour',cbsi)
inputColour = str.capitalize(input())
if D.get(inputColour) is None:
print("Codemaker, colour,'",inputColour,"'is not available, please select colour",cbsi,"again")
print()
else:
L.append(inputColour)
if mode == "B":
if duplicateColours(L) == True:
L.pop(len(L)-1)
print("Duplicate colours are not allowed in Beginner mode!")
print(L)
continue
print('Colour',cbsi,'is',inputColour)
print(L)
print()
break
print("Codemaker, your chosen code is",L,"keep it hidden from the Codebreaker!")
print()
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!")
input("Press any key to scramble the screen!")
print("""
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
*********************************************** | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
*********************************************** | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
""")
print("----")
return L
def checkGuess(L, mode):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
for x in L:
if D.get(x) is None:
print("Your guess contains colours that aren't available, please try again")
return False
break
else:
if mode == "B":
if duplicateColours(L) == True:
print("Duplicate colours are not allowed in Beginner mode! Please try again")
return False
break
return True | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
def getGuess(guesses):
L2 = []
while True:
print()
playerGuess = input("Codebreaker, what is your guess? Enter 4 colours using the first letter of the colour as your input, separated by commas: ")
print()
L2 = str.upper(playerGuess).split(",")
if len(L2) != 4:
print("Your guess does not contain 4 colours")
print()
else:
if checkGuess(L2, mode) == True:
print("Guess #",guesses+1)
print(L2)
break
else:
pass
return L2
def guessCheck(L,L2):
D = {'W':'White','R':'Red','B':'Blue','Y':'Yellow','P':'Purple','O':'Orange','G':'Green','S':'Silver'}
Ly = ["*","*","*","*"]
Lt1 = L.copy()
Lt2 = L2.copy()
for y in range(len(L2)):
if L[y] == L2[y]:
Ly[y] = "X"
Lt1[y] = "*"
Lt2[y] = "*"
for y in range(len(L2)):
if D.get(Lt2[y]) is not None:
if Lt1.count(Lt2[y]) != 0:
Ly[y] = "O"
Lt1[Lt1.index(Lt2[y])] = "*"
Lt2[y] = "*"
return Ly | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
def playGame(guesses, currentPlayer):
print("""
Available colours:
White (W), Red (R), Blue (B), Yellow (Y), Purple (P), Orange (O), Green (G), Silver (S)
""")
codemakerScore = 0
for x in range(guesses):
L2 = getGuess(x)
Ly = guessCheck(L,L2)
print(Ly," Help: 'X' = correct colour and order, 'O' = correct colour, wrong order, '*' = incorrect guess")
codemakerScore += 1
if L2 == L:
print()
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+")
print("Congratulations, Codebreaker! You cracked the code")
print("!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+")
print()
break
if x == int(guesses)-1:
print("Codebreaker... You failed to crack the code. The Codemaker was granted a bonus point")
codemakerScore += 1
print("The Codemaker",currentPlayer,"gained",codemakerScore,"points this round")
print()
return codemakerScore
def getCurrentPlayer(player1,player2,numberOfGames):
if int(numberOfGames) %2 ==0:
currentPlayer = player1
else:
currentPlayer = player2
return currentPlayer
def updatePlayerScores(currentPlayer,codemakerScore,player1Score,player2Score):
if currentPlayer == player1:
player1Score += codemakerScore
else:
player2Score += codemakerScore
return player1Score,player2Score
def getWinner(player1Score, player2Score):
if player1Score > player2Score:
return player1
if player1Score == player2Score:
return "Draw"
else:
return player2
#Main game code******************************************** | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
#Main game code********************************************
player1, player2 = getPlayers()
mode = getMode()
difficulty, guesses = getDifficulty()
numberOfGames = getNumberOfGames()
player1Score = 0
player2Score = 0
for x in range(len(numberOfGames)+1):
print()
currentPlayer = getCurrentPlayer(player1,player2,x)
print()
print(currentPlayer,"is the Codemaker")
print()
L = getNewCode(mode)
print()
print("Current scores are: ",player1,"=",player1Score," / ",player2,"=",player2Score)
codemakerScore = playGame(guesses,currentPlayer)
player1Score, player2Score = updatePlayerScores(currentPlayer,codemakerScore,player1Score,player2Score)
print("Current scores are: ",player1,"=",player1Score," / ",player2,"=",player2Score)
input("Press any key to continue")
winner = getWinner(player1Score,player2Score)
print()
print("After",numberOfGames,"games, the winner is: ",winner,"!")
print()
print("The final scores were ",player1,"=",player1Score," / ",player2,"=",player2Score) | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
Answer: It's a pretty good piece of code for someone just beginning, good job.
There are a couple of things, as always, that could be improved :
Making a better use of Python's functionalities
Languages all have some special functionalities that make the code easier to write/read. It's good to know these because well... they're there to be used.
1 ) String templating : Instead of writing print("Player 1 is",player1,"and will start as the Codemaker") you should write print(f"Player 1 is {player1} and will start as the Codemaker"). This is valid for all the cases where you mix strings with code.
2 ) Using tuples : So, for me it was a big thing when I started Python because I came from C# where tuples were... less powerful. There are some places where you have two dictionaries with the same keys, for example :
def getDifficulty():
D = {"E":"Easy","M":"Medium","H":"Hard"}
D2 = {"E":12,"M":10,"H":8}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard")
print()
while True:
difficulty = str.capitalize(input())
if difficulty in ("E","M","H"):
print("You have selected",D[difficulty],"difficulty! The Codebreaker will get",D2[difficulty],"chances to crack the code!")
print("----")
break
else:
print(difficulty,"is not a valid option, please select a difficulty")
print()
return difficulty, D2[difficulty]
I think I would write it this way :
def getDifficulty():
possible_difficulties = {"E":("Easy", 12),"M":("Medium", 10),"H":("Hard", 8)}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard\n") | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
while True:
difficulty_input = str(input()).upper()
if difficulty_input not in possible_difficulties.keys():
print(f"{difficulty_input } is not a valid option, please select a valid difficulty\n")
continue
chosen_difficulty = possible_difficulties[difficulty_input]
print(f"You have selected {chosen_difficulty[0]} difficulty! The Codebreaker will get {chosen_difficulty[1]} chances to crack the code!")
return chosen_difficulty
There are a couple things to unpack here:
1 ) I took some liberties with the variable names. Using single letters as variable names is almost always a bad idea.
2 ) I fused the two dictionaries by having a tuple value that contains the text and the number of chances. You could even use a named tuple instead of a plain tuple to really explain what is the purpose of the two values.
3 ) I removed some nesting. It's been proven (I believe) that nesting code inside loops and conditions reduces the code clarity. So I chose to first check if the input is invalid, if so, I use the continue keyword to return to the start of the loop. It's a personal preference to check for invalid input, but you could also check for a valid input and return the chosen difficulty :
def getDifficulty():
possible_difficulties = {"E":("Easy", 12),"M":("Medium", 10),"H":("Hard", 8)}
print("Select game mode: Enter 'E', 'M' or 'H' for Easy, Medium or Hard\n")
while True:
difficulty_input = str(input()).upper()
if difficulty_input in possible_difficulties.keys():
chosen_difficulty = possible_difficulties[difficulty_input]
print(f"You have selected {chosen_difficulty[0]} difficulty! The Codebreaker will get {chosen_difficulty[1]} chances to crack the code!")
return chosen_difficulty
print(f"{difficulty_input } is not a valid option, please select a valid difficulty\n") | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
I don't have time to make a longer review, but I have one last point, don't do this :
print("""
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
*********************************************** | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
***********************************************
""") | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
python, beginner, game
I have to scroll like 4 or 5 mouse wheels to see the end of it and code should almost always be readable above all. If you want to print this, you should replace it with the following : print("*"*3000) or however long you want it to be. | {
"domain": "codereview.stackexchange",
"id": 42838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game",
"url": null
} |
typescript
Title: Turn array of objects into date-sorted array of objects
Question: I have to turn an array of objects that look this this:
[
{
"id": 15,
"log_name": "default",
"description": "updated",
"properties": "{\"message\":{\"old\":\"It's 2022! Wow!\",\"new\":\"It's 2022!\"}}",
"created_at": "2022-01-05 19:05:12",
"updated_at": "2022-01-05 19:05:12"
}
]
into something like this, sorted by descending date order:
[
{
date: 2022-01-05,
logs: [ array of log objects from that day ]
},
{
date: 2022-01-04,
logs: [ array of log objects from that day ]
},
]
The code I came up with is really ugly and I could use some help, as I loop through the objects three times.
First, I create an object with dates as the key and arrays of logs as the value
Then, I convert this object into an array of objects
Then, I sort of the array by date.
Is there a way to build that final array by only going through the array once?
const groupLogsByDate = (logs: ActivityLog[]): { date: string, logs: ActivityLog[] }[] => {
const groupedLogs: {[date: string]: ActivityLog[]} = {};
Object.values(logs).forEach((log) => {
const date: string = log.created_at.substring(0, 10);
if (date in groupedLogs) {
groupedLogs[date].push(log);
} else {
const newDate: ActivityLog[] = [];
groupedLogs[date] = newDate;
groupedLogs[date].push(log);
}
});
const groupedArray: {date: string, logs: ActivityLog[]}[] = [];
Object.entries(groupedLogs).forEach(([key, val]) => {
const obj = {
date: key,
logs: val,
};
groupedArray.push(obj);
});
// sort the array by date string in descending order
groupedArray.sort((a, b) => {
if (a.date < b.date) {
return 1;
}
if (b.date > a.date) {
return -1;
}
return 0;
});
return groupedArray;
};
```
Answer: You have three steps, and the following suggestion brings it down to two.
You've written: | {
"domain": "codereview.stackexchange",
"id": 42839,
"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": "typescript",
"url": null
} |
typescript
Answer: You have three steps, and the following suggestion brings it down to two.
You've written:
group logs by date
for each log in each log group, add a date field from the log group
sort all the log groups
Instead you could do:
group logs by date, adding a date field as you process the log
sort all the log groups
const groupedLogs: {[date: string]: { date: string, logs: ActivityLog[]}} = {};
Object.values(logs).forEach((log) => {
const date: string = log.created_at.substring(0, 10);
groupedLogs[date] = groupedLogs[date] || { date, logs: [] };
groupedLogs[date].logs.push(log);
});
const groupedArray: {date: string, logs: ActivityLog[]}[] = Object.values(groupedLogs);
Regarding this expression: groupedLogs[date] || { date, logs: [] }
If groupedLogs[date] is truthy, then that value is used. If it is falsy, then we effectively get false || { date, logs: [] } which evaluates to { date, logs: [] }. Effectively, this means "if it already exists, use groupedLogs[date], otherwise use a new object with a value { date, logs: [] }. So if there are already logs, they're left unchanged, or if there's no value then it's initialized with an empty logs list and the date. | {
"domain": "codereview.stackexchange",
"id": 42839,
"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": "typescript",
"url": null
} |
python, performance, beginner, console, gui
Title: Define multiple buttons for Windows commands
Question: I'm teaching myself Python.
I wrote this code for work to help me troubleshoot end users PCs. It opens a GUI with a selection of buttons. It's written in python using pyinstaller to convert it to an executable. It's super slow - taking 10-15+ seconds to run on a PC. Why is it so slow and how can I improve it overall?
The command I user for pyinstaller is pyinstaller -F -w <scriptname.py>
As an aside, the program opens an elevated command prompt by default. How do I make that an option?
from tkinter import *
import os, ctypes, sys
root=Tk()
root.title('Common Fixes')
root.geometry("250x500")
def mapSharedDrives():
os.system('cmd /c " map_drives.bat')
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
button=[]
os.system('cmd /c "color a"')
def showSystemInfo():
os.system('cmd /c "systeminfo | find /i "Host Name" & systeminfo | find /i "boot time" & pause"')
def restartPC ():
os.system('cmd /c "shutdown /r"')
def deleteWindowsCredentials():
os.system('cmd /c "del %TEMP%\List.txt /s /f /q & del %TEMP%\tokensonly.txt /s /f /q"')
def updateGroupPolicy():
os.system('cmd /c "del %windir%\system32\GroupPolicy\ /s /f /q & gpupdate /force"')
def sfcScanNow():
os.system('cmd /c "sfc /scannow & pause"')
def restartPrintSpooler():
os.system('cmd /c "net stop spooler & net start spooler"')
def DISM():
os.system('cmd /c "DISM /Online /Cleanup-Image /RestoreHealth & pause"')
def addSwitchUser():
os.system('cmd /c "reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v HideFastUserSwitching /t REG_DWORD /d 0 /f"') | {
"domain": "codereview.stackexchange",
"id": 42840,
"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, beginner, console, gui",
"url": null
} |
python, performance, beginner, console, gui
def increaseOutlookMessageSize():
os.system('cmd /c "reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Outlook\PST /v MaxLargeFileSize /t REG_DWORD /d 204800 /f & reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Outlook\PST /v WarnLargeFileSize /t REG_DWORD /d 184320 /f"')
def increaseOutlookAttachmentSize():
os.system('cmd /c "reg add HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\Outlook /v MaximumAttachmentSize /t REG_DWORD /d 81920 /f"')
def deleteOutlookFiles():
os.system('cmd /c "del %USERPROFILE%\AppData\Roaming\Microsoft\Outlook /s /f /q & del %USERPROFILE%\AppData\Local\Microsoft\Outlook /s /f /q & rmdir %USERPROFILE%\appdata\local\Microsoft\Outlook /s /q & reg delete HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Outlook\Profiles /f & reg delete HKEY_CURRENT_USER\Software\Policies\Microsoft\office\14.0\outlook /f & reg delete HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook /f & reg delete HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook /f & reg delete HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Outlook /f & reg delete HKEY_CURRENT_USER\Software\Microsoft\Office\10.0\Outlook /f & pause"')
buttons = {
"PC Info &\nLast Restarted": showSystemInfo,
"Restart the PC": restartPC,
"Delete Windows\nCredentials": deleteWindowsCredentials,
"Update Group Policy": updateGroupPolicy,
"SFC /Scannow": sfcScanNow,
"Restart Print Spooler": restartPrintSpooler,
"DISM": DISM,
"Add Switch User": addSwitchUser,
"Increase Outlook\nMessage Size": increaseOutlookMessageSize,
"Increase Outlook\nAttachment Size": increaseOutlookAttachmentSize,
"Delete Outlook Files": deleteOutlookFiles,
}
for title, func in buttons.items():
b = Button(height=2, width=15, text=title, command=func)
b.pack() | {
"domain": "codereview.stackexchange",
"id": 42840,
"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, beginner, console, gui",
"url": null
} |
python, performance, beginner, console, gui
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
buttons = {
"Map a Network Drive": mapSharedDrives,
"Admin Scripts":is_admin
}
for title, func in buttons.items():
b = Button(height=2, width=15, text=title, command=func)
b.pack()
root.mainloop()
Answer: mapSharedDrives should be map_shared_drives by PEP8.
Never bare except:. For is_admin, if you know that a specific exception indicates the user is not an admin, catch only that exception.
Move your global code starting with if is_admin(): into functions.
Don't os.system('cmd /c x'); instead call into one of the subprocess methods passing x, ideally with shell=False. Some of your commands shouldn't be external calls at all, such as del which should use pathlib.Path.unlink(), or winreg module instead of the reg calls.
An example of invoking subprocess:
from os import environ
from pathlib import Path
from subprocess import check_output
systeminfo = Path(environ['WINDIR']) / 'system32/systeminfo.exe'
output = check_output((systeminfo,), encoding='utf-8', shell=False)
lines = output.splitlines()
hostname, = (line for line in lines if line.startswith('Host Name'))
boot_time, = (line for line in lines if line.startswith('System Boot Time'))
print(hostname)
print(boot_time)
Even this is a poor example, because hostname has a Python built-in. | {
"domain": "codereview.stackexchange",
"id": 42840,
"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, beginner, console, gui",
"url": null
} |
javascript, comparative-review, vue.js, firebase
Title: Destructuring with map and assigning to a constant
Question: I don't know exactly what to name this, but I was refactoring a code snippet and looking at this constant users I thought I'd do this destructuring:
Before:
async queryDBUsers({ commit }) {
await getDocs(collection(db, "users"))
.then((querySnapshot) => {
const users = querySnapshot.docs.map((doc) => ({
id: doc.id,
name: doc.data().name,
shelfName: doc.data().shelfName,
photoURL: doc.data().photoURL,
}));
commit("setUsers", users);
})
.catch((error) => console.error(error));
},
After:
async queryDBUsers({ commit }) {
await getDocs(collection(db, "users"))
.then((querySnapshot) => {
const users = querySnapshot.docs.map((doc) => {
const [id, { name, shelfName, photoURL }] = [doc.id, doc.data()];
return { id, name, shelfName, photoURL };
});
commit("setUsers", users);
})
.catch((error) => console.error(error));
},
The const users ends the function in exactly the same way in both code snippets.
My question is: is this good code practice? Or should I leave it the way it was?
Answer: Super short review;
Logging to console seems very primitive, consider a logging solution that handles different logging levels.
{ commit } is very bothering, why should a query function need to commit? Is it more a next function? Does it actually write and commit users? A comment would have been useful there.
Actually, I am not sure why you restrict the fields in this function, which has a super general/bland name (queryDBUsers). Why not pass all the fields?
For the destructuring, I think it's fine either way. | {
"domain": "codereview.stackexchange",
"id": 42841,
"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, comparative-review, vue.js, firebase",
"url": null
} |
beginner, rust, wordle
Title: Rust CLI for playing Wordle
Question: I wrote the following CLI for playing the popular word game - Wordle. Wordle is a word game in which players are trying to guess a 5 letter word. Each turn they guess one 5 letter word, and for each letter are told that it either isn't in the word, is in the word, but not here, or is correctly placed.
This CLI attempts to play the game by taking a wordlist, guessing words that cut down the remaining words (e.g. by maximising the number of new characters in it) until there are only two possible words left.
Users can either provide the answer up front using the --answer flag, or respond interactively to each guess, specifying whether it is present, absent or correct.
I'm primarily looking for feedback on how "rusty" the code is and how it can be made more idiomatic. In particular:
is the borrowing right? I felt like a lot of the time I was just making changes to make the compiler happy!
are the tests structured in the normal way?
is the module breakdown suitable?
are there well known libraries I should be using?
I am experienced with other languages (C++/C#) but new to Rust.
main.rs
mod game;
mod cli;
mod interactive_solver;
mod non_interactive_solver;
mod player;
fn main() {
cli::run_cli();
}
game.rs
pub const GAME_WORD_LENGTH: usize = 5;
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
pub enum LetterResponse {
Correct,
InWord,
NotInWord,
}
pub struct GuessResponse {
pub letter_responses: Vec<LetterResponse>,
}
pub fn is_guess_correct(response: &GuessResponse) -> bool {
response
.letter_responses
.iter()
.all(|&l| l == LetterResponse::Correct)
}
#[cfg(test)]
mod is_guess_correct_tests {
use super::*;
#[test]
fn all_correct_is_correct() {
let response = GuessResponse {
letter_responses: [LetterResponse::Correct; 5].to_vec(),
};
assert!(is_guess_correct(&response));
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[test]
fn one_in_correct_is_not_correct() {
let response = GuessResponse {
letter_responses: [
LetterResponse::Correct,
LetterResponse::Correct,
LetterResponse::Correct,
LetterResponse::InWord,
LetterResponse::Correct,
]
.to_vec(),
};
assert!(!is_guess_correct(&response));
}
}
cli.rs
use crate::game;
use crate::game::GuessResponse;
use crate::interactive_solver;
use crate::non_interactive_solver;
use crate::player;
use clap::Parser;
use std::fs;
#[derive(Parser, Debug)]
#[clap(about, version, author)]
struct Args {
#[clap(long, default_value = "words_alpha.txt")]
word_list_path: String,
#[clap(long)]
answer: Option<String>,
}
pub fn run_cli() {
let args = Args::parse();
let word_list = read_word_list(args.word_list);
let verifier: Box<dyn Fn(&str) -> GuessResponse> = match args.answer {
Some(word) => Box::new(move |guess: &str| {
let answer_word = word.clone();
non_interactive_solver::non_interactive_solver(guess, answer_word)
}),
None => Box::new(move |guess: &str| interactive_solver::interactive_solver(&guess)),
};
let sln = player::solve(&word_list, verifier);
println!("Solution: {:?}", sln.guess_sequence);
}
fn read_word_list(word_list_file_name: String) -> Vec<String> {
fs::read_to_string(word_list_file_name)
.expect("Error reading file")
.split_ascii_whitespace()
.filter(|s| s.len() == game::GAME_WORD_LENGTH)
.filter(|s| s.chars().all(|c| c.is_alphabetic()))
.map(str::to_string)
.collect()
}
interactive_solver.rs
use crate::game;
use crate::game::GuessResponse;
use crate::game::LetterResponse;
use std::io; | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
pub fn interactive_solver(guess: &str) -> GuessResponse {
println!("Guess: {}", guess);
let mut response = String::new();
println!("Type a {} letter response - y: correct, . - in word, x - not involved", game::GAME_WORD_LENGTH);
loop {
io::stdin()
.read_line(&mut response)
.expect("Failed to read line");
response.pop();
match response.len() {
game::GAME_WORD_LENGTH => {
let parsed_response = parse_user_response(&response);
match parsed_response {
Ok(response) => return response,
Err(e) => println!("Invalid string: {}", e),
}
}
_ => {
println!("Enter exactly {} characters, {}", game::GAME_WORD_LENGTH, response.len())
}
}
}
}
fn parse_user_response(response_str: &String) -> Result<GuessResponse, String> {
if response_str.len() != game::GAME_WORD_LENGTH {
panic!(format!("Must call parse_user_response with exactly {} characters", game::GAME_WORD_LENGTH));
}
let mapped_response: Result<Vec<_>, _> = response_str
.chars()
.map(|char| match char {
'y' => Ok(LetterResponse::Correct),
'.' => Ok(LetterResponse::InWord),
'x' => Ok(LetterResponse::NotInWord),
x => Err(format!("Invalid character: {}", x)),
})
.collect();
return match mapped_response {
Ok(x) => Ok(GuessResponse {
letter_responses: x.to_vec(),
}),
Err(e) => Err(format!("Invalid response: {}", e)),
};
}
#[cfg(test)]
mod parse_user_response_tests {
use super::*; | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[cfg(test)]
mod parse_user_response_tests {
use super::*;
#[test]
fn valid_string_parsed_correctly() {
// If I inline this, it is apparently still needed for checking response.is_ok (lazy eval of parse_user_response?)
let user_input = String::from("y.x.x");
let response = parse_user_response(&user_input);
assert!(response.is_ok());
assert_eq!(
response.unwrap().letter_responses,
vec![
LetterResponse::Correct,
LetterResponse::InWord,
LetterResponse::NotInWord,
LetterResponse::InWord,
LetterResponse::NotInWord
]
);
}
#[test]
fn one_invalid_char_invalid_response() {
let user_input = String::from("y.xax");
let response = parse_user_response(&user_input);
assert!(response.is_err());
}
}
non_interactive_solver.rs
use crate::game::GuessResponse;
use crate::game::LetterResponse;
pub fn non_interactive_solver(guess: &str, answer: String) -> GuessResponse {
GuessResponse {
letter_responses: guess
.chars()
.enumerate()
.map(|(index, char)| {
if answer
.chars()
.nth(index)
.expect("Word length different from guess length")
== char
{
return LetterResponse::Correct;
} else if answer.contains(char) {
return LetterResponse::InWord;
} else {
return LetterResponse::NotInWord;
}
})
.collect(),
}
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[cfg(test)]
mod non_interactive_solver_tests {
use super::*;
#[test]
fn words_same_all_correct() {
let guess = "hello";
let answer = "hello";
let result = non_interactive_solver(&guess, String::from(answer));
assert!(result
.letter_responses
.iter()
.all(|&l| l == LetterResponse::Correct))
}
#[test]
fn letter_in_not_right_place() {
let guess = "abc";
let answer = "dea";
let result = non_interactive_solver(&guess, String::from(answer));
assert!(result.letter_responses[0] == LetterResponse::InWord);
assert!(result.letter_responses[1] == LetterResponse::NotInWord);
assert!(result.letter_responses[2] == LetterResponse::NotInWord);
}
}
player.rs
use crate::game;
use crate::game::GuessResponse;
use crate::game::LetterResponse;
use itertools::Itertools;
use std::collections::HashMap;
pub struct Solution {
pub guess_sequence: Vec<String>,
}
struct Knowledge {
guessed_words: Vec<String>,
correct_letters: Vec<(char, usize)>,
contained_letters: HashMap<char, Vec<usize>>,
}
fn build_empty_knowledge() -> Knowledge {
Knowledge {
guessed_words: vec![],
correct_letters: vec![],
contained_letters: HashMap::new(),
}
}
pub fn solve<VFn>(possbile_words: &Vec<String>, verifier: VFn) -> Solution
where
VFn: Fn(&str) -> GuessResponse,
{
solve_rec(possbile_words, verifier, &build_empty_knowledge())
}
fn solve_rec<VFn>(
possbile_words: &Vec<String>,
verifier: VFn,
starting_knowledge: &Knowledge,
) -> Solution
where
VFn: Fn(&str) -> GuessResponse,
{
let guess = make_guess(possbile_words, starting_knowledge);
let response = verifier(&guess);
let new_knowledge = apply_learning(starting_knowledge, &guess, &response); | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
match game::is_guess_correct(&response) {
true => Solution {
guess_sequence: new_knowledge.guessed_words,
},
false => solve_rec(possbile_words, verifier, &new_knowledge),
}
}
fn apply_learning(knowledge: &Knowledge, guess: &String, response: &GuessResponse) -> Knowledge {
let mut new_words = knowledge.guessed_words.clone();
new_words.push(guess.to_string());
Knowledge {
guessed_words: new_words,
correct_letters: knowledge
.correct_letters
.iter()
.map(|t| t.clone())
.chain(
response
.letter_responses
.iter()
.enumerate()
.filter(|(_, &char)| char == LetterResponse::Correct)
.map(|(index, &_)| (guess.chars().nth(index).unwrap(), index))
.collect::<Vec<(char, usize)>>(),
)
.collect::<Vec<(char, usize)>>(),
contained_letters: merge_contained_letters_map(
&knowledge.contained_letters,
response
.letter_responses
.iter()
.enumerate()
.filter(|(_, &char)| char == LetterResponse::InWord)
.map(|(index, &_)| (guess.chars().nth(index).unwrap(), index)),
),
}
}
fn merge_contained_letters_map<I>(
original: &HashMap<char, Vec<usize>>,
newly_tried_letters: I,
) -> HashMap<char, Vec<usize>>
where
I: Iterator<Item = (char, usize)>,
{
let mut new_map = original.clone();
for (char, pos_tried) in newly_tried_letters {
if new_map.contains_key(&char) {
let mut current_vec = new_map[&char].clone();
current_vec.push(pos_tried);
new_map.insert(char, current_vec);
} else {
new_map.insert(char, vec![pos_tried]);
}
}
new_map
}
#[cfg(test)]
mod apply_learning_tests {
use super::*; | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[cfg(test)]
mod apply_learning_tests {
use super::*;
#[test]
fn empty_knowledge_correct_letter_added_to_list_of_correct_letters() {
let knowledge = build_empty_knowledge();
let response = GuessResponse {
letter_responses: [
LetterResponse::Correct,
LetterResponse::NotInWord,
LetterResponse::NotInWord,
]
.to_vec(),
};
let new_knowledge = apply_learning(&knowledge, &String::from("abc"), &response);
assert!(new_knowledge.correct_letters.len() == 1);
assert!(new_knowledge.correct_letters[0] == ('a', 0));
}
#[test]
fn empty_knowledge_contained_letters_added_to_list_of_contained_letters() {
let knowledge = build_empty_knowledge();
let response = GuessResponse {
letter_responses: [
LetterResponse::InWord,
LetterResponse::NotInWord,
LetterResponse::NotInWord,
]
.to_vec(),
};
let new_knowledge = apply_learning(&knowledge, &String::from("abc"), &response);
assert!(new_knowledge.correct_letters.len() == 0);
assert!(new_knowledge.contained_letters.len() == 1);
assert!(new_knowledge.contained_letters.contains_key(&'a'));
assert_eq!(new_knowledge.contained_letters[&'a'], vec![0]);
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[test]
fn knowledge_about_letter_in_word_extended() {
let knowledge = Knowledge {
contained_letters: HashMap::from([('a', vec![0])]),
..build_empty_knowledge()
};
let response = GuessResponse {
letter_responses: [
LetterResponse::NotInWord,
LetterResponse::InWord,
LetterResponse::NotInWord,
]
.to_vec(),
};
let new_knowledge = apply_learning(&knowledge, &String::from("bac"), &response);
assert!(new_knowledge.correct_letters.len() == 0);
assert!(new_knowledge.contained_letters.len() == 1);
assert!(new_knowledge.contained_letters.contains_key(&'a'));
assert_eq!(new_knowledge.contained_letters[&'a'], vec![0, 1]);
}
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
fn make_guess(possbile_words: &Vec<String>, knowledge: &Knowledge) -> String {
let valid_words = possbile_words
.iter()
.filter(|w| {
knowledge
.correct_letters
.iter()
.all(|(char, index)| w.chars().nth(*index).unwrap() == *char)
})
.filter(|w| {
knowledge
.contained_letters
.iter()
.all(|char| w.chars().contains(char.0))
})
.filter(|w| {
knowledge
.contained_letters
.iter()
.all(|(char, tried_indexes)| {
tried_indexes
.iter()
.all(|tried_index| w.chars().nth(*tried_index).unwrap() != *char)
})
})
.filter(|w| !knowledge.guessed_words.contains(w))
.cloned()
.collect::<Vec<String>>();
if valid_words.len() > 2 {
let guess = revealing_word(&valid_words, &knowledge);
println!("{} possibilities, trying {}", valid_words.len(), guess);
guess
} else {
valid_words.first().unwrap().to_string()
}
}
fn revealing_word(possbile_words: &Vec<String>, knowledge: &Knowledge) -> String {
let letter_frequency = "abcdefghijklmnopqrstuvwxyz"
.chars()
.map(|c| (c, possbile_words.iter().map(|w| w.matches(c).count()).sum()))
.collect::<HashMap<char, usize>>();
possbile_words
.iter()
.max_by(|w1, w2| {
let w1_score = word_score(&w1, &letter_frequency, &knowledge);
let w2_score = word_score(&w2, &letter_frequency, &knowledge);
w1_score.cmp(&w2_score)
})
.unwrap()
.clone()
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
fn word_score(
word: &String,
char_frequence: &HashMap<char, usize>,
knowledge: &Knowledge,
) -> usize {
word.chars()
.unique() // each letter only gets scored once
.map(|c_in_word| {
if knowledge.contained_letters.contains_key(&c_in_word) {
return char_frequence[&c_in_word];
} else if knowledge
.correct_letters
.iter()
.any(|(letter, _)| *letter == c_in_word)
{
return char_frequence[&c_in_word];
} else if knowledge
.guessed_words
.iter()
.any(|w| w.contains(c_in_word))
{
return 0;
}
return char_frequence[&c_in_word];
})
.sum()
}
#[cfg(test)]
mod make_guess_tests {
use super::*;
#[test]
fn guessed_one_word_dont_guess_again() {
let words = [String::from("foo"), String::from("bar")].to_vec();
let knowledge = Knowledge {
guessed_words: [String::from("foo")].to_vec(),
..build_empty_knowledge()
};
let guess = make_guess(&words, &knowledge);
assert!(guess == "bar");
}
#[test]
fn guessed_one_correct_letter_guess_next_valid_word() {
let words = [
String::from("abc"),
String::from("bcd"),
String::from("abd"),
]
.to_vec();
let knowledge = Knowledge {
guessed_words: vec![String::from("abc")],
correct_letters: vec![('a', 0)],
..build_empty_knowledge()
};
let guess = make_guess(&words, &knowledge);
assert!(guess == "abd");
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
#[test]
fn guessed_one_contained_letter_guess_next_word_that_contains_in_different_position() {
let words = vec![
String::from("abc"),
String::from("bcd"),
String::from("acd"),
String::from("bac"),
];
let knowledge = Knowledge {
guessed_words: vec![String::from("abc")],
contained_letters: HashMap::from([('a', vec![0])]),
..build_empty_knowledge()
};
let guess = make_guess(&words, &knowledge);
assert!(guess == "bac");
}
}
```
Answer: I took a quick look at your code and would love to share a few ideas.
Creating Structs
By convention, when creating a struct you'll usually see this done in a fn new() -> Self function that resides in the
structs impl block. So instead of build_empty_knowledge() -> Knowledge you might have something like the below:
impl Knowledge {
fn new() -> Self {
Knowledge {
guessed_words: vec![],
correct_letters: vec![],
contained_letters: HashMap::new(),
}
}
}
Now anytime you'd like to create new knowledge.
let knowledge = Knowledge::new();
Expressive Structs
There are a few instances where references to structs are manually being passed to a function. This is fine, but in an attempt
to make the code a bit more expressive, we can move some of these functions into our struct impl block.
Consider the below:
pub fn is_guess_correct(response: &GuessResponse) -> bool {
response
.letter_responses
.iter()
.all(|&l| l == LetterResponse::Correct)
}
impl Knowledge {
pub fn is_correct(&self) -> bool {
response.letter_responses
.iter()
.all(|&l| l == LetterResponse::Correct)
}
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
Now when determining if a response is correct we can just call response.is_correct(), which is just a little
nicer to look at I think. I come from a heavy OOP background though so take this with a grain of salt. But I would imagine Rust would also appreciate decisions like this.
General Readability
There is a ton of inlining statements and closures throughout the code, and it really affects the readability.
Take this snippet for example:
GuessResponse {
letter_responses: guess
.chars()
.enumerate()
.map(|(index, char)| {
if answer
.chars()
.nth(index)
.expect("Word length different from guess length")
== char
{
return LetterResponse::Correct;
} else if answer.contains(char) {
return LetterResponse::InWord;
} else {
return LetterResponse::NotInWord;
}
})
.collect(),
}
We could make this a little easier on the eyes and for other readers by naming the inlined boolean expression and by pulling
the somewhat involved closure out into a named function.
pub fn non_interactive_solver(guess: &str, answer: &str) -> GuessResponse {
GuessResponse {
letter_responses: guess
.chars()
.enumerate()
.map(|(index, char)| to_letter_response(answer, char, index))
.collect(),
}
}
fn to_letter_response(answer: &str, guess_char: char, guess_index: usize) -> LetterResponse {
let answer_char = answer
.chars()
.nth(guess_index)
.expect("Word length different from guess length");
return if answer_char == guess_char {
LetterResponse::Correct
} else if answer.contains(guess_char) {
LetterResponse::InWord
} else {
LetterResponse::NotInWord
};
} | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
beginner, rust, wordle
By refactoring to the above, as readers we have a bit more context to what these constructs are doing/referencing.
There are a ton of examples similar to this scattered throughout the code base.
assert! vs assert_eq!
Should probably use the assert_eq! macro over assert! when comparing equality. assert_eq! will give better
message regarding the equality.
assert!(new_knowledge.correct_letters.len() == 1);
assert_eq!(new_knowledge.correct_letters.len(), 1);
Redundant
When parsing user commands, there is no need to use the format! macro. panic! supports the same string interpolation.
panic!("Must call parse_user_response with exactly {} characters", game::GAME_WORD_LENGTH);
The possible_words parameter in this function is not being used.
fn word_score(
word: &String,
possible_words: &HashMap<char, usize>,
knowledge: &Knowledge,
) -> usize {
...
}
Typos
possbile_words -> possible_words
char_frequence -> char_frequency or char_frequencies | {
"domain": "codereview.stackexchange",
"id": 42842,
"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, rust, wordle",
"url": null
} |
java, algorithm, binary-tree
Title: Leetcode 662: maximum width of binary tree in Java
Question: I have the following solution to this problem. The idea is to compute the maximum width of a binary search tree. The width of a BST on a particular depth is defined as the distance from the leftmost non-null node to the rightmost non-null node at that depth. This implementation proceeds downwards from the root node in breadth-first manner keeping track of the width of the widest tree level until an empty level is encountered. (Note that the widest level isn’t necessarily the deepest one.
class TreeNode {
int val;
int num;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
} | {
"domain": "codereview.stackexchange",
"id": 42843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, binary-tree",
"url": null
} |
java, algorithm, binary-tree
class Solution {
public int widthOfBinaryTree(TreeNode root) {
TreeNode[] levelHi = new TreeNode[3_000];
TreeNode[] levelLo = new TreeNode[3_000];
levelHi[0] = root;
root.num = 0;
int maximumWidth = 1;
int levelLength = 1;
while (true) {
int numberOfChildrenInLoLevel =
getNextDeepestLevel(levelHi, levelLo, levelLength);
if (numberOfChildrenInLoLevel == 0) {
return maximumWidth;
}
int tentativeWidth = levelLo[numberOfChildrenInLoLevel - 1].num -
levelLo[0].num + 1;
maximumWidth = Math.max(maximumWidth, tentativeWidth);
TreeNode[] levelTemp = levelLo;
levelLo = levelHi;
levelHi = levelTemp;
levelLength = numberOfChildrenInLoLevel;
}
}
int getNextDeepestLevel(TreeNode[] levelHi,
TreeNode[] levelLo,
int levelHiLength) {
int levelLoLength = 0;
for (int i = 0; i < levelHiLength; i++) {
TreeNode currentTreeNode = levelHi[i];
TreeNode leftChild = currentTreeNode.left;
TreeNode rightChild = currentTreeNode.right;
if (leftChild != null) {
leftChild.num = currentTreeNode.num * 2;
levelLo[levelLoLength++] = leftChild;
}
if (rightChild != null) {
rightChild.num = currentTreeNode.num * 2 + 1;
levelLo[levelLoLength++] = rightChild;
}
}
return levelLoLength;
}
}
Critique request
I would like to hear comments about efficiency and space consumption. | {
"domain": "codereview.stackexchange",
"id": 42843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, binary-tree",
"url": null
} |
java, algorithm, binary-tree
Answer: I'll just mention doc comments,
and that you added an instance data member num to TreeNode as provided by LeetCode.
The code has illuminative names for most everything, but uses one magic number: 3000.
getNextDeepestLevel() has code duplicated in handling left and right child.
Not trivial to avoid in a language not supporting data aliasing
(C++: TreeNode children[2], &left = children[0], &right = children[1];),
but modifying TreeNode, anyway, one might implement Iterable. (I'll have to revisit AspectJ.)
Efficiency:
With the information provided in LeetCode 662, every node needs to be visited. With considerable overhead, I think it possible to reduce that to ⅔
• keeping a count of nodes in levels traversed and
• making use of knowledge about the tree's total number of nodes.
(What information would be needed to just follow left and right boundaries?
node height may help.)
Space consumption:
Each of the "level arrays" will need to keep no more than the maximum number of nodes per level -
which, for a binary tree, is bounded by \$\lceil \frac{\#nodes}2 \rceil\$.
For every other node added to levelLo, there is one node from levelHi no longer needed:
One can "overlay the arrays", e.g., filling from the high index end consuming nodes from lower index to zero, reversing roles&directions between passes/levels.
Or add not keeping leaf nodes to the picture, reducing the number of nodes kept per level to no more than one third of their total number. (And impeding code simplicity/brevity/readability: maintainability.)
dariosicily mentioned using a queue (the usual way of handling level order) - the number of nodes to handle in any given level is the size of the queue just after consuming the last node of the level before.
You are aware of iterative deepening.
When not keeping nodes with less than two children (and keeping the depth of nodes), this reduces additional space to \$O(\log n)\$ - increasing time drastically (to \$O(N^2)\$?). | {
"domain": "codereview.stackexchange",
"id": 42843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, binary-tree",
"url": null
} |
c#, performance, collections, unity3d
Title: Most efficient way to track a collection of targets in range of a source object
Question: In my game there are space ships and each of these space ships tracks which other ships are in range of it. I need to perform certain logic when a target ship comes in range of another ship, and certain logic when the target ship leaves the range of the ship.
I am looking for advice on the most performant way to manage the collection of targets. Not so much looking for advice on the range comparisons as I'm already making optimizations there (square distance and spatial partitioning).
I have a way to do this using two hashsets (code below), but I just want to confirm if this is the fastest way. I feel like there might be a better way, but I can't for the life of me think of one.
public HashSet<Ship> TrackedShips = new HashSet<Ship>();
public HashSet<Ship> FoundShips = new HashSet<Ship>();
public void FindShipsInRange(Ship source, List<Ship> possibleTargets)
{
FoundShips = new HashSet<Ship>();
foreach (var possibleTarget in possibleTargets)
{
if (InRange(source, possibleTarget))
{
FoundShips.Add(possibleTarget);
TrackedShips.Remove(possibleTarget);
// Do the adding/revealing logic
}
}
foreach (var oldTrackedShip in TrackedShips)
{
// Do the removal logic
}
TrackedShips = FoundShips;
} | {
"domain": "codereview.stackexchange",
"id": 42844,
"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#, performance, collections, unity3d",
"url": null
} |
c#, performance, collections, unity3d
TrackedShips = FoundShips;
}
Would very much appreciate any suggestions! Very curious if there is a better way I am not thinking of.
EDIT: To clarify, I'm mainly asking if this is the best approach to tracking when a ship leaves the range. The collections can get quite large, i.e. 1000 ships each having 1000 possible targets each time the method runs. I want to ensure I am not iterating more than I need to be, and removing the ships from the tracked ships hashset and then looping over the remaining ships was the best I could come up with. Curious if anyone has a better idea!
Answer: I think it has room to improve, but really performance depends upon how List<Ship> possibleTargets is composed for each ship, and you do not show that code.
For the code you present, I would suggest NOT removing from TrackedShips. No need to perform temporary pruning when you completely replace the hash set later.
Alternate SECTION of code:
foreach (var possibleTarget in possibleTargets)
{
if (InRange(source, possibleTarget))
{
FoundShips.Add(possibleTarget);
// Do the adding/revealing logic
}
}
foreach (var ship in FoundShips)
{
if (!TrackedShips.Contains(ship))
{
// Do the removal logic
}
}
TrackedShips = FoundShips; | {
"domain": "codereview.stackexchange",
"id": 42844,
"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#, performance, collections, unity3d",
"url": null
} |
javascript, game
Title: Skill leveling system with different skill level titles
Question: I'm making a text-based RPG in JavaScript. I made a skill leveling system that works, but I feel like the function arguments get passed around a lot and, the code is not very scalable. Do you have any suggestions on how I can improve this code? Ideally, I want to call only one function like:
addExperience(25, charisma);
What my code does:
The properties object gives each skill level a title. Currently, all skills have the same title. In the future, these will have different titles and number of titles.
The player object has a skill level and experience key for each skill, so the skills can level independently.
I've also posted the HTML and CSS code for completion. However, this is not important because I only wrote it to test the JavaScript code, and it is not part of the game.
// Skill variable
const properties = {
strength: [
"Dabbler",
"Skilled",
"Untrained",
"Proficient",
"Amateur",
"Superb",
"Master",
],
endurance: [
"Dabbler",
"Skilled",
"Untrained",
"Proficient",
"Amateur",
"Superb",
"Master",
],
charisma: [
"Dabbler",
"Skilled",
"Untrained",
"Proficient",
"Amateur",
"Superb",
"Master",
],
};
// Player variables
const player = {
stats: {
strength: {
level: 0,
experience: 0,
},
endurance: {
level: 0,
experience: 0,
},
charisma: {
level: 0,
experience: 0,
},
},
};
function getExperienceToNextLevel(level, skill) {
if (level < skill.length) {
return ((level * (level + 1)) / 2) * 1000;
}
}
function addExperience(amount, stat, skill) {
if (stat.level !== skill.length - 1) {
stat.experience += amount;
while (stat.experience >= getExperienceToNextLevel(stat.level, skill)) {
stat.experience -= getExperienceToNextLevel(stat.level, skill);
++stat.level;
}
}
display(stat, skill);
} | {
"domain": "codereview.stackexchange",
"id": 42845,
"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, game",
"url": null
} |
javascript, game
function display(stat, skill) {
document.getElementById("level-display").innerHTML = `${stat.level} ${
skill[stat.level]
}`;
document.getElementById("xp-display").innerHTML = `${stat.experience}`;
}
body {
background: #ff930f;
background: linear-gradient(
90deg,
rgba(255, 147, 15, 1) 0%,
rgba(255, 249, 91, 1) 100%
);
box-sizing: border-box;
font-family: sans-serif;
margin: 0;
padding: 0;
}
.title {
background-color: rgb(0, 0, 0, 0.1);
color: #fff;
margin: 5% auto;
padding: 25px;
text-align: center;
text-shadow: 2px 2px rgb(0, 0, 0, 0.5);
}
.display {
background-color: rgb(0, 0, 0, 0.1);
color: #fff;
margin: 5%;
padding: 25px;
text-align: center;
text-shadow: 2px 2px rgb(0, 0, 0, 0.5);
}
.xp-buttons {
text-align: center;
}
.xp-buttons button {
background-color: #333;
border: none;
border-radius: 999rem;
color: #fff;
font-weight: 700;
height: 2.5rem;
max-width: auto;
min-width: 5rem;
transition-duration: 0.2s;
margin: 0 auto;
} | {
"domain": "codereview.stackexchange",
"id": 42845,
"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, game",
"url": null
} |
javascript, game
.xp-buttons button:hover {
background-color: #444;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="JavaScript - Debugger" />
<title>JavaScript - Debugger</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<main>
<h1 class="title">JavaScript - Debugger</h1>
<div class="display">
<h2>Level: <span id="level-display"></span></h2>
<h2>XP: <span id="xp-display"></span></h2>
</div>
<div class="xp-buttons">
<button
onclick="addExperience(50, player.stats.charisma, properties.charisma)"
>
50 XP
</button>
<button
onclick="addExperience(1000, player.stats.charisma,properties.charisma)"
>
1000 XP
</button>
<button
onclick="addExperience(0, player.stats.charisma,properties.charisma)"
>
Update
</button>
</div>
</main>
<script src="app.js"></script>
</body>
</html>
Answer: A short review;
I don't like the signature of the function
addExperience(50, player.stats.charisma, properties.charisma)
could be
addExperience(50, player, "charisma");
or even
player.addExperience(50, "charisma");
and if it was me, I would make it more Yoda like
or even
player.addExperience("charisma", 50);
I would keep track of total experience, and not reset it every time you reach a new level. In case you ever want to rebalance the levels of existing characters.
I would recommend reading up on the MVC model. If you follow it, then addExperience does not call display
Its stub code, but display is too generic a name
You seem to treat stats and skills as the same, to me they are not?
properties should probably be statTitles? | {
"domain": "codereview.stackexchange",
"id": 42845,
"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, game",
"url": null
} |
performance, python-3.x, algorithm, mathematics
Title: Count numbers that are the sum of three perfect cubes
Question:
From numbers from 1 to 100, count the numbers where the following equation is satisfied with 1 <= a <= 100, 1 <= b <= 100, and 1 <= c <= 100: $$a³ + b³ + c³$$
I have this:
def has_power3(n):
for i in range(1, n+1):
for j in range(1, n+1):
for k in range(1, n+1):
if i**3 + j**3 + k**3 == n:
return True
return False
powers_3 = 0
for num in range(1, 100+1):
if has_power3(num):
powers_3 += 1
print(powers_3)
However, this code above is O(n⁴). Is there a way to speed this code up? Any other suggestions?
Answer: Optimization: Code movement
You are repeatedly doing the same computations over and over. How many times is \$i^3\$ computed?
for j in range(1, n+1):
for k in range(1, n+1):
if i**3 + j**3 + k**3 == n:
return True
Inside these loops, the value of i does not change. With j and k ranging over 100 values each, that is 10,000 redundant calculations! Since \$i^3\$ is constant, you can move that out of the loop. Ditto for \$j^3\$ and the middle loop:
n_plus_1 = n + 1
for i in range(1, n_plus_1):
i3 = i ** 3
for j in range(1, n_plus_1):
i3_plus_j3 = i3 + j ** 3
for k in range(1, n_plus_1):
if i3_plus_j3 + k ** 3 == n:
return True | {
"domain": "codereview.stackexchange",
"id": 42846,
"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": "performance, python-3.x, algorithm, mathematics",
"url": null
} |
performance, python-3.x, algorithm, mathematics
Optimization: Search Space
You're looking for
$$i^3 + j^3 + k^3 = n, 1 \le i \le 100, 1 \le j \le 100, 1 \le k \le 100$$
If, after you've exhausted searching \$i = 1\$, and not finding any values of j or k which work, is there any point in exploring \$j = 1\$ or \$k = 1\$ for \$i \gt 1\$? No! That would just be a permutation of a triplet you've already tried.
Without loss of generality, you can search a much smaller space:
$$i^3 + j^3 + k^3 = n, 1 \le i \le j \le k \le 100$$
As in:
n_plus_1 = n + 1
for i in range(1, n_plus_1):
i3 = i ** 3
for j in range(i, n_plus_1):
i3_plus_j3 = i3 + j ** 3
for k in range(j, n_plus_1):
if i3_plus_j3 + k ** 3 == n:
return True
Optimization: Early termination
If \$i^3 + j^3 + k^3 \gt n\$, then trying with a larger value of k won't result in a smaller value, so you can stop the inner loop at that point.
Similarly, if \$i^3 + j^3 + j^3 \gt n\$, then there is no point in even entering the inner loop, and larger values of j are also pointless, so you can stop the middle loop at that point.
Finally, if \$i^3 + i^3 + i^3 \gt n\$, then there is no point in even entering the middle loop, and larger values of i are also pointless, so you can stop the outer loop.
n_plus_1 = n + 1
for i in range(1, n_plus_1):
i3 = i ** 3
if 3 * i3 > n:
break
for j in range(i, n_plus_1):
j3 = j ** 3
if i3 + 2 * j3 > n:
break
i3_plus_j3 = i3 + j3
for k in range(j, n_plus_1):
i3_plus_j3_plus_k3 = i3_plus_j3 + k ** 3
if i3_plus_j3_plus_k3 > n:
break
if i3_plus_j3_plus_k3 == n:
return True | {
"domain": "codereview.stackexchange",
"id": 42846,
"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": "performance, python-3.x, algorithm, mathematics",
"url": null
} |
performance, python-3.x, algorithm, mathematics
Optimization: Loop end-points
The above added a lot of if statements to the search, complicating the algorithm. We can do math to determine the actual endpoints, and remove the if conditions from inside the loops. The inner loop completely. vanishes.
$$ 3 * i^3 > n \rightarrow i_{max} = \lfloor \sqrt[3]{n / 3} \rfloor $$
$$ i^3 + 2 * j^3 > n \rightarrow j_{max} = \lfloor \sqrt[3]{\frac{n - i^3} {2}} \rfloor $$
$$ i^3 + j^3 + k^3 = n \rightarrow k = \sqrt[3]{n - i^3 - j^3} $$
THIRD = 1 / 3
i_max = int((n / 3) ** THIRD)
for i in range(1, i_max + 1):
i3 = i ** 3
j_max = int(((n - i3) / 2) ** THIRD)
for j in range(i, j_max + 1):
j3 = j ** 3
k = int((n - i3 - j3) ** THIRD)
if i3 + j3 + k ** 3 == n:
return True
Optimization: Precomputed Values
As vnp mentions, we can simplify/remove the math in the last step by precomputing cubes. Storing them in a set allows for \$O(1)\$ lookup.
THIRD = 1 / 3
k_max = int((n - 2) ** THIRD)
k_cubes = {k ** 3 for k in range(1, k_max + 1)}
i_max = int((n / 3) ** THIRD)
for i in range(1, i_max + 1):
i3 = i ** 3
j_max = int(((n - i3) / 2) ** THIRD)
if any((n - i3 - j ** 3) in k_cubes for j in range(i, j_max + 1)):
return True
Alternate Approach
Instead of asking "if 1 is the sum of 3 cubes", and then "if 2 is the sum of 3 cubes", and then "if 3 is the sum of 3 cubes" ... and so on up to "if 100 is the sum of 3 cubes", turn the problem around, and record a set of the sums of 3 cubes. The length of that set is the answer.
def cube_sums(n: int) -> set[int]:
i_max = int((n / 3) ** (1 / 3)) + 1
j_max = int(((n - 1) / 2) ** (1 / 3)) + 1
k_max = int((n - 2) ** (1 / 3)) + 1
return {t for i in range(1, i_max)
for j in range(i, j_max)
for k in range(j, k_max)
if (t := i ** 3 + j ** 3 + k ** 3) <= n}
cubes = cube_sums(100)
print(len(cubes)) | {
"domain": "codereview.stackexchange",
"id": 42846,
"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": "performance, python-3.x, algorithm, mathematics",
"url": null
} |
rust
Title: Generically calculate powers of two below a number
Question: The following function is an attempt to generate powers of two below the input number max.
So powers_of_two_below(15u8, u8::BITS) generates 1, 2, 4, 8. It does calculate 16, but does not include it. This function avoids calculating powers that cause overflow by taking bits as input (since there doesn't appear to be a standard trait that exposes T::BITS). It can be re-used for several number types.
But it doesn't seem very concise. Can you recommend ways to improve it?
use num_traits::{One, Zero};
use std::ops::Shl;
pub fn powers_of_two_below<T>(max: T, bits: u32) -> impl Iterator<Item = T>
where
T: Zero + One + PartialOrd + Shl<Output = T> + Copy,
{
let mut exp = T::zero();
(0..bits)
.map(move |_| {
let power = T::one() << exp;
exp = exp + T::one();
power
})
.take_while(move |&x| x < max)
}
I tried to make a more concise version:
pub fn powers_of_two_below<T>(max: T, bits: u32) -> impl Iterator<Item = T>
where
T: One + PartialOrd + Shl<Output = T> + Copy + From<u32>,
{
(0..bits)
.map(|i| T::one() << i.into())
.take_while(move |&x| x < max)
}
...but it is more impractical: A lot of number types don't have From<u32> (including usize and uN where N < 32).
Answer: By specifying the right hand side of Shl, you can remove the From<u32> entirely:
fn powers_of_two_below<T>(max: T, bits: u32) -> impl Iterator<Item = T>
where
T: One + PartialOrd + Shl<u32, Output = T> + Copy,
{
(0..bits)
.map(|i: u32| T::one() << i)
.take_while(move |&x| x < max)
} | {
"domain": "codereview.stackexchange",
"id": 42847,
"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": "rust",
"url": null
} |
rust
If you wanted to remove the bits parameter, you'd probably have to implement your own trait specifically for it, but I'm not sure how you'd define bits for floating point numbers.
Here's an example where I defined a Bits trait, using a macro to implement it for all integer types. I also used it to replace num_traits::One because why not.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cd4e4e7db8deb4c8be883c759dd906bf | {
"domain": "codereview.stackexchange",
"id": 42847,
"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": "rust",
"url": null
} |
javascript, array
Title: Find the third biggest integer of an array
Question: How can i make this work with fewer lines? The goal here is to get the third biggest integer of an array.
I would also appreciate if someone polished this code.
let array = [442, 93, 3, 5, 30, 10];
const f = (arr) => {
let secureArr = [...arr];
let big0 = Math.max.apply(null, secureArr);
const index0 = secureArr.indexOf(big0);
secureArr.splice(index0, 1);
let big1 = Math.max.apply(null, secureArr);
const index1 = secureArr.indexOf(big1);
secureArr.splice(index1, 1);
let big2 = Math.max.apply(null, secureArr);
const index2 = secureArr.indexOf(big2);
secureArr.splice(index2, 1);
console.log(Math.min(big0, big1, big2));
};
f(array);
let array = [442, 93, 3, 5, 30, 10];
const f = (arr) => {
let secureArr = [...arr];
let big0 = Math.max.apply(null, secureArr);
const index0 = secureArr.indexOf(big0);
secureArr.splice(index0, 1)
let big1 = Math.max.apply(null, secureArr);
const index1 = secureArr.indexOf(big1);
secureArr.splice(index1, 1);
let big2 = Math.max.apply(null, secureArr);
const index2 = secureArr.indexOf(big2);
secureArr.splice(index2, 1);
console.log(Math.min(big0, big1, big2));
};
f(array); | {
"domain": "codereview.stackexchange",
"id": 42848,
"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, array",
"url": null
} |
javascript, array
Answer:
Generally, you want to separate printing from logic. Have your function return the third biggest instead of printing it, and print the return value. This allows you to include the function in a larger project without needing to make any changes.
https://softwareengineering.stackexchange.com/q/364086 and https://stackoverflow.com/q/34361379/2336725 recommend function f(arr) {} instead of const f = (arr) => {}. But f is a terrible name for a function. Let's change it to thirdBiggest.
There's no real point to the Math.min at the end. You know that big0 is the biggest, big1 is the biggest after that, and big2 the biggest after that. Lets just return big2.
You never change the big# values, so they should be constants. But it would be better to reuse the big# and index# variables. I'm going to rename them to big and bigIndex.
But now we see that we're repeating the exact same steps three times. Let's move that into a for loop.
We might as well use an array spread instead of .apply
secureArr implies some sort of security consideration, which I'm not seeing. If you're just wanting to not modify the original, lets call it a copy.
Here's where we are now:
let array = [442, 93, 3, 5, 30, 10];
function thirdBiggest(arr) {
let arrCopy = [...arr];
let big, bigIndex;
for ( let i = 0 ; i < 3 ; i++ ) {
big = Math.max(...arrCopy);
bigIndex = arrCopy.indexOf(big);
arrCopy.splice(bigIndex, 1);
}
return big;
}
console.log(thirdBiggest(array)); | {
"domain": "codereview.stackexchange",
"id": 42848,
"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, array",
"url": null
} |
javascript, array
You specifically mentioned fewer lines. This is not usually a good metric. If that's all you want, then you should go with Bens Steves' approach and your function will be two lines long. But it will be measurably slower for large arrays.
"third biggest" is a bit arbitrary, and now that we have a loop, we can see that it's not hard to turn that into a parameter. Let's do that, and change thirdBiggest into nthBiggest.
The usual approach for this problem is that you go through the array once, and keep track of the highest values you've seen so far. If you see a new highest value, it pushes the bottom one off of the list. That ends up being:
function nthBiggest(arr,n) {
// start with the front of the array
let biggestValues = arr.slice(0,n);
biggestValues.sort( (a,b) => a-b );
// now look through the rest of the array
arr.slice(n).forEach( (value) => {
if ( value > biggestValues[0] ) {
biggestValues.shift();
let valueIndex = biggestValues.findIndex( (big) => big>value );
if ( valueIndex >= 0 ) {
biggestValues.splice(valueIndex,0,value);
} else {
biggestValues.push(value);
}
}
});
return biggestValues[0];
}
console.log(nthBiggest(array,3));
That's more lines than your original version, but should be the fastest. | {
"domain": "codereview.stackexchange",
"id": 42848,
"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, array",
"url": null
} |
android, generics, kotlin
Title: Getting a single result from multiple LiveData objects
Question: I have an Android viewmodel for a Fragment that requires the user to perform multiple tasks. In addition to a LiveData object to track the status of each task, I also need a LiveData that tracks a summary of the status of all the tasks.
I wrote the following MediatorLiveData class that takes a list of LiveData objects and watches them all for changes, then applies a given function to compute the summary each time a value changes:
class ListOfLiveData<T, E>(
private val sources: List<LiveData<T>>,
private val evaluator: (List<LiveData<T>>) -> E
) : MediatorLiveData<E>() {
init {
sources.forEach {
addSource(it) { value = evaluator(sources) }
}
}
}
Here is how I am using it right now:
class TaskViewModel : ViewModel() {
// Can be DENIED, UNKNOWN, or GRANTED for each one
private val _phoneStatus = MutableLiveData(Status.UNKNOWN)
private val _locationStatus = MutableLiveData(Status.UNKNOWN)
private val _videoStatus = MutableLiveData(Status.UNKNOWN)
private val _audioStatus = MutableLiveData(Status.UNKNOWN)
val phoneStatus: LiveData<Status> = _phoneStatus
val locationStatus: LiveData<Status> = _locationStatus
val videoStatus: LiveData<Status> = _videoStatus
val audioStatus: LiveData<Status> = _audioStatus | {
"domain": "codereview.stackexchange",
"id": 42849,
"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": "android, generics, kotlin",
"url": null
} |
android, generics, kotlin
val allStatus = ListOfLiveData<Status, Status>(
listOf(
_phoneStatus,
_locationStatus,
_videoStatus,
_audioStatus,
)
) {
// If any individual task status is DENIED or UNKNOWN, return that value.
// Otherwise, they must all be GRANTED
it.forEach { p ->
if (p.value == Status.DENIED) {
return@ListOfLiveData Status.DENIED
}
if (p.value == Status.UNKNOWN) {
return@ListOfLiveData Status.UNKNOWN
}
}
return@ListOfLiveData Status.GRANTED
}
}
(In this example the source types and the return type are the same, but I can think of other places in the app that it would be useful to have a different return type.)
Is this a good design?
Is there anything built into the framework that would have already done this?
Am I missing anything important?
Answer: Your way of merging is similar to Rx's combineTransform or Kotlin Flow's combine. The difference is you are forcing the lambda to have to parse out the values instead of passing it the values directly. Changing this behavior would make it easier to work with the values, especially in cases like your use case above where you are simply iterating them.
You might also consider putting your class behind a function for easier use, and using varargs as well.
fun <T, E> combineTransform(
vararg sources: LiveData<T>,
transform: (List<T?>) -> E
): LiveData<E> = MediatorLiveData<E>().apply {
sources.forEach { liveData ->
addSource(liveData) {
value = transform(sources.map(LiveData<T>::getValue))
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42849,
"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": "android, generics, kotlin",
"url": null
} |
android, generics, kotlin
Then your usage site would look like:
val allStatus: LiveData<Status> = combineTransform(
_phoneStatus,
_locationStatus,
_videoStatus,
_audioStatus,
) {
it.forEach { value ->
when(value) {
Status.DENIED -> return@ListOfLiveData Status.DENIED
Status.UNKNOWN -> return@ListOfLiveData Status.UNKNOWN
else -> {}
}
}
return@ListOfLiveData Status.GRANTED
}
Note that this is having to contend with the problem that a LiveData of a non-nullable type still returns nullable value because it might not have an initial value set yet. As a result, the input of the above lambda uses nullable values.
If we want to avoid this problem and behave the same way as Rx combineTransform, we should not emit until all sources have emitted at least once. We could change the function to:
fun <T, E> combineTransform(
vararg sources: LiveData<T>,
transform: (List<T>) -> E
) = MediatorLiveData<E>().apply {
val sourcesAwaitingFirst = mutableSetOf(*sources)
sources.forEach { liveData ->
addSource(liveData) {
sourcesAwaitingFirst.remove(liveData)
if (sourcesAwaitingFirst.isEmpty()) {
@Suppress("UNCHECKED_CAST")
value = transform(sources.map(LiveData<T>::getValue) as List<T>)
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42849,
"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": "android, generics, kotlin",
"url": null
} |
c++, memory-management, thread-safety
Title: C++ thread-safe object pool
Question: This is a modern C++ implementation of a thread-safe memory pool -- I want to make sure I am solving the critical section problem correctly (no deadlocks, starvation, bounded waiting) and I am getting details like the rule of five correct (copy not allowed, move doesn't trigger double release). Design criteria:
Small number of items in pool (e.g. 5 to 10) since each may have a large memory footprint -- the number can be decided / fixed when the pool is created.
Uses RAII to guarantee an object is released when code leaves scope.
If there are no items available in the pool, the code blocks until one is available.
The typical usage pattern would be:
ObjectPool<Foo> pool(5, Foo_ctor_args);
...
{
ObjectPool<Foo>::Item foo = pool.acquire()
foo.object.doSomething();
} | {
"domain": "codereview.stackexchange",
"id": 42850,
"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++, memory-management, thread-safety",
"url": null
} |
c++, memory-management, thread-safety
Class template:
#include <vector>
#include <mutex>
#include <condition_variable>
#include <cassert>
#include <iostream>
template <typename T>
class ObjectPool {
private:
std::vector<T> objects;
std::vector<bool> inUse;
std::mutex mutex;
std::condition_variable cond;
public:
class Item {
public:
T& object;
Item(T& o, size_t i, ObjectPool& p) : object{o}, index{i}, pool{p} {}
Item(const Item&) = delete;
Item(Item&& other) : object{other.object}, index{other.index}, pool{other.pool} {
other.index = bogusIndex; // <-- don't release
}
Item& operator=(const Item&) = delete;
Item& operator=(Item&& other) {
if (this != &other) {
object = other.object;
index = other.index;
pool = other.pool;
other.index = bogusIndex; // <-- don't release
}
return *this;
}
~Item() {
if (index != bogusIndex) {
pool.release(index);
index = bogusIndex; // <-- avoid double release
}
}
private:
constexpr static size_t bogusIndex = 65535;
size_t index;
ObjectPool<T>& pool;
};
template<typename... Args>
ObjectPool(size_t maxElems, Args&&... args) : inUse(maxElems, false) {
for (size_t i = 0; i < maxElems; i++)
objects.emplace_back(std::forward<Args>(args)...);
}
Item acquire() {
std::unique_lock<std::mutex> guard(mutex);
while (true) {
for (size_t i = 0; i < objects.size(); i++)
if (!inUse[i]) {
inUse[i] = true; | {
"domain": "codereview.stackexchange",
"id": 42850,
"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++, memory-management, thread-safety",
"url": null
} |
c++, memory-management, thread-safety
if (!inUse[i]) {
inUse[i] = true;
return Item{objects[i], i, *this};
}
cond.wait(guard);
}
}
private:
void release(size_t index) {
std::unique_lock<std::mutex> guard(mutex);
assert(index < objects.size());
assert(inUse[index]);
inUse[index] = false;
cond.notify_all();
}
}; | {
"domain": "codereview.stackexchange",
"id": 42850,
"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++, memory-management, thread-safety",
"url": null
} |
c++, memory-management, thread-safety
Answer: Only allow ObjectPool to create Items
The rule of five is used correctly as far as I can see, but there are still some ways to create an incorrect Item, and use that to corrupt an existing ObjectPool. Consider:
ObjectPool<int> pool(10);
int value = 42;
decltype(foo)::Item item(value, 0, pool);
To prevent this from happening, make all constructors private, and make Item a friend of ObjectPool:
template <typename T>
class ObjectPool {
...
class Item {
friend ObjectPool;
Item(T& o, size_t i, ObjectPool& p) : object{o}, index{i}, pool{p} {}
Item(const Item&) = delete;
Item(Item&& other) : object{other.object}, index{other.index}, pool{other.pool} {
other.index = bogusIndex; // <-- don't release
}
public:
T& object;
...
};
...
};
Make Item work like a std::unique_ptr
An Item is almost like a std::unique_ptr; while the pool is the actual owner, Item acts like a unique reference. I would make the member variable object private, and instead add these member functions to access it:
T& operator*() {
return object;
}
T* operator->() {
return &object;
}
T* get() {
return &object;
}
Then you can do:
auto foo = pool.acquire();
foo->doSomething();
Consider adding a constructor that takes an initizalier list
An object pool is like a container. Consider that most STL containers allow initializing using a std::initializer_list, you might want to add that for your object pool, so that you could write something like:
ObjectPool<std::string> pool = {"foo", "bar", "baz", ...}; | {
"domain": "codereview.stackexchange",
"id": 42850,
"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++, memory-management, thread-safety",
"url": null
} |
c++, memory-management, thread-safety
Set bogusIndex to std::numeric_limits<std::size_t>::max()
Even if you cannot think of a use case for an object pool of 65535 or more items now, consider that you might need it in the future, or someone else using your code might. If you are going to use a special value for index to indicate that an Item doesn't need to be released, give it a value that really can never be a valid index, like the maximum possible value for a std::size_t.
Use notify_one()
When you release an Item back to the pool, it doesn't make sense to wake up all threads that are waiting. Only one will be able to get the Item that was just released. So use notify_one() instead.
Consider supporting non-copyable value types
Since you store the objects in a std::vector, this requires T to be copy-assignable and copy-constructible. Consider storing them in some way that does not have this limitation, for example by using a std::deque instead.
Item's move constructor should std::move the object
If you are moving one Item into another, it makes sense to also use move-assignment on object. It should be as simple as:
object = std::move(other.object)
acquire() is an \$O(N)\$ operation
It is unfortunate that acquire() does a linear scan through inUse[]. It should be possible to turn this into an \$O(1)\$ operation. One possibility is to use a std::set to store the indices of the items that are in use, but while technically \$O(1)\$ amortized, that might involve a lot of unwanted allocations. There are other ways to keep track of this though. | {
"domain": "codereview.stackexchange",
"id": 42850,
"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++, memory-management, thread-safety",
"url": null
} |
python, python-2.x
Title: What is the pythonic way to update my nested dictionary?
Question: So I need to update my nested dictionary where the key is "compensationsDeltaEmployee". I created a string cost_perhour to hold the value of my conditional statements. Now that I am done with the string. What is the best or pythonic way to update my nested dictionary with a new key "costPerHour" with the value of my string cost_perhour? What I did was I created an empty dictionary cost_per_hour_dic then add the string then ran update. Is this okay or can I clean it up more?
def add_cost_per_hour(json_dic):
"""
Add new dictionary value costPerHour to our data
"""
cost_perhour = ""
cost_per_hour_dic = {}
try:
# Find key compensationsDeltaEmployee.
for keys, values in json_dic.items():
if str(keys) == "compensationsDeltaEmployee":
if "payBasis" in values:
# If payBasis equal 9, 0, P, cost_per_hour field should be blank.
if str(values["payBasis"]) in ("9", "0", "P"):
cost_perhour = ""
# If payBasis equal 1, A, B, C, D, H, J, 3, cost_per_hour equals salaryPayable divide by 2080.
elif str(values["payBasis"]) in ("1", "A", "B", "C", "D", "H", "J", "3"):
# Check if our value for salaryPayable is empty or None
if values["salaryPayable"] == "" or values["salaryPayable"] is None:
raise Exception("salaryPayable field is empty")
else:
cost_perhour = round(float(values["salaryPayable"]) / 2080, 2) | {
"domain": "codereview.stackexchange",
"id": 42851,
"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-2.x",
"url": null
} |
python, python-2.x
# If payBasis equal 2, 4, 5, 7, E, F, X, cost_per_hour should match the salaryPayable field.
elif str(values["payBasis"]) in ("2", "4", "5", "7", "E", "F", "X"):
if values["salaryPayable"] == "" or values["salaryPayable"] is None:
raise Exception("salaryPayable field is empty")
else:
cost_perhour = round(float(values["salaryPayable"]), 2)
# If there are any unexpected values, the cost_per_hour field should be blank.
else:
cost_perhour = ""
else:
raise Exception("Could not find key payBasis")
if cost_perhour is "":
raise Exception("cost_per_hour is empty")
cost_per_hour_dic["costPerHour"] = str(cost_perhour)
json_dic["compensationsDeltaEmployee"].update(cost_per_hour_dic)
return json_dic
except Exception as e:
print("Exception in add_cost_per_hour: ", e)
The json_dict
"compensationsDeltaEmployee": {
"interPersonnelAgree": "N",
"payRateDeterminant": "0",
"payPlan": "1",
"properPayPlan": null,
"retainedGrade": null,
"payBasis": "2",
"gradeCode": "06",
"step": "03",
"basePayChangeYypp": null,
"physicalCompAllowance": 0,
"withinGradeEligibilityCode": "1",
"salaryPayable": 21
}, | {
"domain": "codereview.stackexchange",
"id": 42851,
"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-2.x",
"url": null
} |
python, python-2.x
Answer: I might be a bit too harsh, so feel free to read this review in small chunks.
What is the number one thing that stands out when I read this code? It feels like it has been written in the spur of the moment, little thought have been given to the overall structure. Feautures seems to been added as needed, instead of taking a step back to look if anything is redundant.
I can not recommend the following strongly enough
Trace out the program structure on paper before you begin
It can be a very rough sketch, but you need to imagine the flow of your program before you start. Imagine if Frodo and Bilbo had just started walking to mordor without a plan, or if the people building rockets at NASA just said YOLO? Be consious of your own code.
JSON should not be used as an internal python datastructure
I am lazy, but it is much clearer storing objects in python as classes. Dicts and especially json are great for reading data to and from python, but internally I recommend sticking for classes in this case.
Avoid falling into the anti-arrow pattern
Reading deeply nested code is difficult and hard to maintain, it should give you a signal that you need to refactor the code.
Avoid Bare except
The first rule of thumb is to absolutely avoid using bare except, as it doesn't give us any exceptions object to inspect.
Furthermore, using bare except also catches all exceptions, including exceptions that we generally don’t want, such as SystemExit or KeyboardInterrupt.
Catching every exception could cause our application to fail without us really knowing why. This is a horrible idea when it comes to debugging.
Stop Using raise Exception
Secondly, we should avoid raising a generic Exception in Python because it tends to hide bugs.
Replace nested conditionals with guard clauses
See for instance here for a longer explanation
for keys, values in json_dic.items():
if str(keys) == "compensationsDeltaEmployee":
# More code here | {
"domain": "codereview.stackexchange",
"id": 42851,
"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-2.x",
"url": null
} |
python, python-2.x
Is better expressed as
compensation = json_dic.get("compensationsDeltaEmployee")
if compension is None:
break / return / raise specific error
# More code here
Don't repeat yourself
# If payBasis equal 9, 0, P, cost_per_hour field should be blank.
if str(values["payBasis"]) in ("9", "0", "P"):
cost_perhour = ""
This breaks the DRY principle several times.
Do not comment the obvious
Do not comment what the code is doing
Comment why you are doing it.
Secondly cost_perhour is already set to "" so this entire block is redundant.This followng block is repeated twice when it is not needed
if values["salaryPayable"] == "" or values["salaryPayable"] is None:
raise Exception("salaryPayable field is empty")
else:
cost_perhour = round(float(values["salaryPayable"]), 2)
What you are doing is first checking if should be x / 2080,
then in the next clause you are checking if it should be x. Why not just check if it should be x, and if it should be x, then check if we should divide?
A more sensible name for the dict, could be EMPLOYEES, but really it should be a descriptive name. Tell me what it is a dictionary of, instead of telling me it is a generic dictionary
EMPLOYEES = {
"compensationsDeltaEmployee": {
"interPersonnelAgree": "N",
"payRateDeterminant": "0",
"payPlan": "1",
"properPayPlan": None,
"retainedGrade": None,
"payBasis": "2",
"gradeCode": "06",
"step": "03",
"basePayChangeYypp": None,
"physicalCompAllowance": 0,
"withinGradeEligibilityCode": "1",
"salaryPayable": 21,
},
} | {
"domain": "codereview.stackexchange",
"id": 42851,
"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-2.x",
"url": null
} |
python, python-2.x
Using all the tricks int book the code windless down into this
EMPLYEE_COMPENSATION = "compensationsDeltaEmployee"
COST_PER_HOUR_DIVIDE_BY_CONSTANT = {"1", "A", "B", "C", "D", "H", "J", "3"}
DIVIDE_COST_BY_HOUR_CONSTANT = 2080
COST_PER_HOUR_EQUALS_SALARY_PAYABLE = COST_PER_HOUR_DIVIDE_BY_CONSTANT.union(
{"2", "4", "5", "7", "E", "F", "X"}
)
def cost_per_hour(compensation):
"""Calculates the cost per hour from the compensationsDeltaEmplyee field"""
pay_basis = str(compensation["payBasis"])
if not pay_basis in COST_PER_HOUR_EQUALS_SALARY_PAYABLE:
return ""
cost_perhour = float(compensation["salaryPayable"])
if pay_basis in COST_PER_HOUR_DIVIDE_BY_CONSTANT:
cost_perhour /= DIVIDE_COST_BY_HOUR_CONSTANT
return round(cost_perhour, 2)
def update_cost_per_hour(employees):
compensation = employees.get(EMPLYEE_COMPENSATION)
if compensation is None:
raise KeyError("Could not find", EMPLYEE_COMPENSATION)
cost = cost_per_hour(compensation)
if not cost:
raise ValueError("cost_per_hour is empty")
employees[EMPLYEE_COMPENSATION]["costPerHour"] = cost
return employees
if __name__ == "__main__":
employees = update_cost_per_hour(EMPLOYEES)
print(employees) | {
"domain": "codereview.stackexchange",
"id": 42851,
"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-2.x",
"url": null
} |
performance, vba
Title: Excel VBA Hide Rows Based Upon List Selection Performance
Question: I currently have a worksheet with approximately 40K rows and 108 columns that I am working with. What I am doing is creating a list that when user selects a particular text in that list then certain columns and/or rows are hidden.
The issue I am encountering is that when 'Unsecured Streamline' is selected, the code to hide the rows takes a REALLY long time to run. Is there a more efficient way to execute what I am trying to achieve here?
Here is the portion of the code I am referring to:
ElseIf Target.Text = "UNSECURED STREAMLINE" Then
Range("A:DD").EntireColumn.Hidden = False
Range("AA:AM").EntireColumn.Hidden = True
For Each cell In ActiveWorkbook.ActiveSheet.Columns("R").Cells
If cell.Value <> "AP" Then
cell.EntireRow.Hidden = True
End If
Next cell
Here is something else I have tried that works but still takes far too long:
For Each cell In Intersect(Me.UsedRange, Me.Columns("R"))
If cell.Value <> "AP" Then
cell.EntireRow.Hidden = True
End If
Next cell | {
"domain": "codereview.stackexchange",
"id": 42852,
"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": "performance, vba",
"url": null
} |
performance, vba
Here is the full code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = ("$D$1") Then
If Target.Text = "ALL" Then
Range("A:DD").EntireColumn.Hidden = False
ElseIf Target.Text = "OVERRIDES" Then
Range("A:DD").EntireColumn.Hidden = False
Range("A:C,J:O,AG:AQ,AX:AY,BA:BA,BC:BD,BF:BH,BJ:BK,BP:BQ,BT:BT,BW:BZ,CA:CB,CC:CI,CK:CK,CQ:CQ,CT:DD").EntireColumn.Hidden = True
ElseIf Target.Text = "RATES" Then
Range("A:DD").EntireColumn.Hidden = False
Range("A:C,J:O,P:P,AB:AE,AG:AG,AR:AW,BE:BF,BW:CB,CE:CI,CK:CN,CR:CS,DB:DD").EntireColumn.Hidden = True
ElseIf Target.Text = "UNSECURED STREAMLINE" Then
Range("A:DD").EntireColumn.Hidden = False
Range("AA:AM").EntireColumn.Hidden = True
For Each cell In ActiveWorkbook.ActiveSheet.Columns("R").Cells
If cell.Value <> "AP" Then
cell.EntireRow.Hidden = True
End If
Next cell
End If
End If
End Sub
I think one issue may be that I am hiding each row individually but I do not know how to solve for this. Any assistance would be greatly appreciated since, as you can probably tell, I am quite new to VBA. | {
"domain": "codereview.stackexchange",
"id": 42852,
"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": "performance, vba",
"url": null
} |
performance, vba
Answer: Even though the handler doesn't modify any cells, it's usually a good idea to disable application events when handling a worksheet's Change event. You can do this by setting Application.EnableEvents to False at the top, and back to True before exiting - preferably with proper error handling, so the initial state is always restored whether there's a run-time error or not.
I mentioned Rubberduck in a comment earlier; its code inspections would have warned you about implicit qualifiers everywhere you're invoking the worksheet's Range property: Range(...) is implicitly Me.Range(...) here, meaning we're looking for cells on the same sheet as Target, i.e. the sheet that's handling this Change event.
However... not all worksheet accesses are implicitly qualified: ActiveWorkbook.ActiveSheet.Columns("R").Cells refers specifically to the active sheet, which may or may not be the same sheet. If there's code anywhere that can change cell $D$1 while another sheet is active, then that's a bug, because you'll be iterating cells and hiding rows on a worksheet you're not intending to modify here.
You'll want to restrict the number of cells you're looking at, and avoid iterating every single cell in any given column - I suspect that's where most of the performance is getting lost, churning through hundreds of thousands of empty rows.
Consider first finding the last row you're interested in, and you can likely leave out the parameterless .Cells call:
For Each cell In Me.Range("R" & lastRow)
...
Next
You're reading cell values and comparing them to string literals without first validating that you can actually do that:
If cell.Value <> "AP" Then | {
"domain": "codereview.stackexchange",
"id": 42852,
"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": "performance, vba",
"url": null
} |
performance, vba
This is dangerous: you'll get a type mismatch run-time error if a cell ever contains a worksheet error (like #N/A, or #VALUE!). Use IsError| to validate cell values first - because If` conditions don't short-circuit in VBA, that means nesting the conditions:
If Not IsError(cell.Value) Then
If cell.Value <> "AP" Then
...
End If
End If
But why are we using Value here but Text everywhere else? Pick one, and stick to it!
Now, if that ... inside the conditional block remains "hide that entire row", there's a missed opportunity to hide all the interesting rows at once! Use Union to build yourself a range as you traverse the cells, as if you were holding the Ctrl key to select rows; then you hide all the rows of the combined range, and benefit from only accessing the worksheet once.
Lastly, since all the conditions are checking different possible values for Target.Text, consider using Select Case Target.Text instead, to reduce redundancy and only read the value once:
Select Case Target.Text
Case "ALL"
'...
Case "OVERRIDES"
'...
...
End Select
``` | {
"domain": "codereview.stackexchange",
"id": 42852,
"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": "performance, vba",
"url": null
} |
javascript, jquery, ecmascript-6, user-interface
Title: Javascript convert number string to Boolean
Question: I'm making this control toggle between hide and show base on the value in this hidden value. I wanted to use a Boolean because I can just do something like == true. Is this the best way to do this?
Working sample
https://jsfiddle.net/tjmcdevitt/4bdrfgcu/12/
$("#hdMeetingDateId").val(500);
//"#hdMeetingDateId").val(0);
console.log($("#hdMeetingDateId").val());
let hasMeetingDateId = $("#hdMeetingDateId").val() > '1' ;
if (hasMeetingDateId == true) {
$("#displayButton").hide();
} else {
$("#displayButton").show();
}
Answer: Teepeemm is correct. It is best to avoid implicit type coercions and use strict equality operators like === and !==. The problem with loose comparisons (e.g. ==, !=) is that it has so many weird rules one would need to memorize in order to be confident in its proper usage.
Speaking of type coercion - it would be better to compare the value to the number one as a Number instead of a String
let hasMeetingDateId = $("#hdMeetingDateId").val() > '1' ;
Since the less than and greater than operators will attempt to convert both operands to numbers1 it would be simpler to just represent it as 1:
const hasMeetingDateId = $("#hdMeetingDateId").val() > 1 ;
And as was already mentioned jQuery's toggle() method can be used to simplify the conditionals. See this demonstrated in the snippet below. Note that the input was changed to an <input type=“number”>. Also the DOM ready callback was simplified because as of jQuery 3.0, only $(handler) is recommended; the other syntaxes still work but are deprecated.1. Also the code makes use of the ES6 feature arrow function expression. | {
"domain": "codereview.stackexchange",
"id": 42853,
"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, jquery, ecmascript-6, user-interface",
"url": null
} |
javascript, jquery, ecmascript-6, user-interface
$(_ => { //jquery DOM ready callback with arrow function
$('#hdMeetingDateId').change(function() { //change event handler
const hasMeetingDateId = $(this).val() > 1;
$("#displayButton").toggle(!hasMeetingDateId);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Sample</h1>
<input type="range" name="hdMeetingDateId" id="hdMeetingDateId" value="4" min="0" max="5" />
<p>
<button id="displayButton">Value Button</button>
</p> | {
"domain": "codereview.stackexchange",
"id": 42853,
"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, jquery, ecmascript-6, user-interface",
"url": null
} |
java, performance, array, hash-map
Title: Proper way to transform nested lists to nested maps
Question: I want to transform a list of lists of lists that I have in a MongoDB document into a map of maps of maps in my java Domain class.
The problem I have is that the fields are mixed between the levels. For instance, the value of the deepest list in the document is the key of the first level map in the domain class.
Here is a representation of my classes.
Mongo Document and subLevels:
public class Level1 {
Integer categoryId;
List<Level2> level2List;
SubLevel2:
public class Level2 {
Integer nPlayers;
List<Level3> Level3List;
SubLevel3:
public class Level3 {
Integer duration;
Integer price;
And here the Domain classes:
static class MyClass {
Map<Integer, Map<Integer, MySubClass>> prices;
}
static class MySubClass {
Map<Integer, Integer> ppd;
}
And here is the mapping function I coded:
private static MyClass map(List<Level1> field) {
MyClass res = new MyClass();
MySubClass mySubClass = new MySubClass();
Map<Integer, Integer> sc = new HashMap<>();
mySubClass.ppd= sc;
res.prices = new HashMap<>();
field.forEach(x -> {
x.level2List.forEach(y -> {
y.Level3List.forEach(z -> {
res.prices.putIfAbsent(y.nPlayers, new HashMap<>());
res.prices.get(y.nPlayers).putIfAbsent(x.categoryId, mySubClass);
res.prices.get(y.nPlayers).get(x.categoryId).ppd.put(z.duration, z.price);
});
});
});
return res;
}
I had to use 3 nested for in the end. I was trying to improve this by using Java Stream but I didn't succeed.
Can somebody give me a hand to find a better solution?
Answer: What you're doing is probably not a good idea but you haven't given us enough context to provide any more detail ("what are you actually doing?"). It's not a good idea for a long list of reasons, including - | {
"domain": "codereview.stackexchange",
"id": 42854,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, array, hash-map",
"url": null
} |
java, performance, array, hash-map
the data structure is very complicated
the operation you're performing relies a lot on mutation
the operation you're performing, if expressed in immutable, functional code requires a lot of explicit resolution on duplicate keys
I highly doubt it's appropriate for you to reuse a single mySubclass instance the way you are.
A vaguely equivalent streamed implementation will look like
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Program {
public record Level1(
Integer categoryId,
List<Level2> level2List
){}
public record Level2(
Integer nPlayers,
List<Level3> level3List
){}
public record Level3(
Integer duration,
Integer price
){}
public record MyClass(
Map<Integer, Map<Integer, MySubClass>> prices
){}
public record MySubClass(
Map<Integer, Integer> ppd
){}
private record FlatKeys(
Level1 level1,
Level2 level2
){}
private static MySubClass mergeCategory(MySubClass left, MySubClass right)
{
// What happens if, within equal nplayers keys, there are also equal category keys?
return new MySubClass(
Stream.concat(
left.ppd.entrySet().stream(),
right.ppd.entrySet().stream()
)
.collect(Collectors.toMap(
// We assume these are unique.
Map.Entry::getKey,
Map.Entry::getValue
))
);
} | {
"domain": "codereview.stackexchange",
"id": 42854,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, array, hash-map",
"url": null
} |
java, performance, array, hash-map
private static Map<Integer, MySubClass> mergeNPlayers(
Map<Integer, MySubClass> left,
Map<Integer, MySubClass> right
)
{
// What happens if there are equal nplayer keys?
return Stream.concat(
left.entrySet().stream(),
right.entrySet().stream()
).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
Program::mergeCategory
));
}
private static MyClass map(List<Level1> field) {
var prices =
field.stream().flatMap(
level1 -> level1.level2List.stream()
.map(level2 -> new FlatKeys(level1, level2))
)
.collect(Collectors.toMap(
flat -> flat.level2.nPlayers,
flat -> Map.of(
flat.level1.categoryId,
new MySubClass(
flat.level2.level3List.stream()
.collect(Collectors.toMap(
Level3::duration, Level3::price
))
)
),
Program::mergeNPlayers
));
return new MyClass(prices);
} | {
"domain": "codereview.stackexchange",
"id": 42854,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, array, hash-map",
"url": null
} |
java, performance, array, hash-map
return new MyClass(prices);
}
private static List<Level1> makeTestData() {
return List.of(
new Level1(
1,
List.of(
new Level2(
97,
List.of(
new Level3(4000, 20),
new Level3(3000, 30)
)
),
new Level2(
98,
List.of(
new Level3(4001, 21),
new Level3(3001, 31)
)
)
)
),
new Level1(
1,
List.of(
new Level2(
97,
List.of(
new Level3(4002, 22),
new Level3(3002, 32)
)
)
)
)
);
}
public static void main(String[] args)
{
List<Level1> outerLevel = makeTestData();
MyClass result = map(outerLevel);
}
}
but my guess is that, in the rest of the program you haven't shown us, there are design issues that - if fixed - would prevent all of this from being necessary. | {
"domain": "codereview.stackexchange",
"id": 42854,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, array, hash-map",
"url": null
} |
c, console
Title: CLI Generator & Parser
Question: I have written a module that allows the developer to generate a CLI and parse given arguments. I am fairly new to C and would love to hear feedback on my code to improve it. All feedback is welcome however I am mainly concerned about best practises and optimisation. Included is the header file and the C file.
// cli.h
#ifndef CLI_H
#define CLI_H
#include <stdbool.h>
typedef enum
{
NODE,
GIT,
C_FILE,
} CLIArgumentType;
typedef struct
{
char* short_hand;
char* long_hand;
bool has_value;
CLIArgumentType type;
} CLIArgumentTemplate;
typedef struct
{
CLIArgumentType type;
char* value;
} CLIArgument;
extern CLIArgumentTemplate* cli_args_template;
extern CLIArgument* cli_args;
// Gets arguments & initialises variables where required
void cli_init(int argc, char** argv);
// Add a cli argument template which is used by the parser
void cli_arg_template_add(char* short_hand, char* long_hand, bool has_value, CLIArgumentType type);
// Parses the arguments provided in argv and adds them to cli_args
bool cli_args_parse();
// Returns an argument if exists
CLIArgument* cli_get_arg(CLIArgumentType type);
#endif // CLI_H
// cli.c
#include "cli.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
CLIArgumentTemplate* cli_args_template;
int args_template_len = 0;
CLIArgument* cli_args;
int args_len = 0;
int argc;
char** argv;
void cli_init(int arg_count, char** arg_vec)
{
argc = arg_count;
argv = arg_vec;
cli_args_template = (CLIArgumentTemplate*)malloc(sizeof(CLIArgumentTemplate));
cli_args = (CLIArgument*)malloc(sizeof(CLIArgument));
// Remove directory argument
argv++;
argc--;
} | {
"domain": "codereview.stackexchange",
"id": 42855,
"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, console",
"url": null
} |
c, console
// Remove directory argument
argv++;
argc--;
}
void cli_arg_template_add(char* short_hand, char* long_hand, bool has_value, CLIArgumentType type)
{
CLIArgumentTemplate* arg_template = (CLIArgumentTemplate*)malloc(sizeof(CLIArgumentTemplate));
arg_template->short_hand = short_hand;
arg_template->long_hand = long_hand;
arg_template->has_value = has_value;
arg_template->type = type;
cli_args_template = realloc(cli_args_template, sizeof(CLIArgumentTemplate) * ++args_template_len);
cli_args_template[args_template_len - 1] = *arg_template;
}
bool cli_args_parse()
{
int arg_index = 0;
char* current_argument;
while (arg_index < argc) {
current_argument = argv[arg_index];
char first_two_chars[2];
strncpy(first_two_chars, current_argument, 2);
if (current_argument[0] != '-' && (strcmp(first_two_chars, "--") != 0)) {
printf("[PARSING ERROR]: Invalid argument '%s'. Argument must begin with dashses.", current_argument);
return false;
}
CLIArgument* argument = NULL;
for (int i = 0; i < args_template_len; i++) {
CLIArgumentTemplate template = cli_args_template[i];
char* argument_stripped = current_argument;
if (strcmp(++argument_stripped, template.short_hand) != 0 && strcmp(++argument_stripped, template.long_hand) != 0) continue;
argument = (CLIArgument*)malloc(sizeof(CLIArgument));
argument->type = template.type;
if (template.has_value) {
if (++arg_index >= argc) {
printf("[PARSING ERROR]: Could not find value for argument '%s'.", current_argument);
return false;
}
char* next_word = argv[++arg_index];
argument->value = next_word;
}
break;
} | {
"domain": "codereview.stackexchange",
"id": 42855,
"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, console",
"url": null
} |
c, console
break;
}
if (argument == NULL) {
printf("[PARSING ERROR]: Unrecognised argument '%s'.", current_argument);
return false;
}
cli_args = realloc(cli_args, sizeof(CLIArgument) * ++args_len);
cli_args[args_len - 1] = *argument;
arg_index++;
}
return true;
}
CLIArgument* cli_get_arg(CLIArgumentType type)
{
for (int i = 0; i < args_len; i++) {
if (cli_args[i].type == type) {
return &cli_args[i];
}
}
return NULL;
}
Answer: This code is dangerous:
CLIArgumentTemplate* arg_template = (CLIArgumentTemplate*)malloc(sizeof(CLIArgumentTemplate));
arg_template->short_hand = short_hand;
arg_template->long_hand = long_hand;
arg_template->has_value = has_value;
arg_template->type = type;
If malloc() returns a null pointer, then we have Undefined Behaviour, because we attempt to dereference it when accessing the members. We need to test for that case, and respond appropriately if arg_template is null.
Also, malloc() returns a void*, which can be assigned to any pointer type without a cast, and it's good practice to avoid repeating the type name. I suggest:
CLIArgumentTemplate *arg_template = malloc(sizeof *arg_template);
if (!arg_template) {
return false;
}
arg_template->short_hand = short_hand;
arg_template->long_hand = long_hand;
arg_template->has_value = has_value;
arg_template->type = type;
Even more dangerous is
cli_args_template = realloc(cli_args_template, sizeof(CLIArgumentTemplate) * ++args_template_len); | {
"domain": "codereview.stackexchange",
"id": 42855,
"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, console",
"url": null
} |
c, console
cli_args_template = realloc(cli_args_template, sizeof(CLIArgumentTemplate) * ++args_template_len);
In this case, a failure, even if caught like the above, will result in a memory leak because we overwrite cli_args_template, which leaves no way to access the memory it previously pointed to. We need something like
void *new_mem = realloc(cli_args_template,
sizeof *cli_args_template * (args_template_len + 1));
if (!new_mem) {
free(arg_template);
return false;
}
cli_args_template = new_mem;
++args_template_len;
Actually, reading cli_arg_template_add() completely, it seems that we never release arg_template, and there's no good reason to allocate this object and copy it into cli_args_template. Just create it directly there:
bool cli_arg_template_add(char* short_hand,
char* long_hand,
bool has_value,
CLIArgumentType type)
{
void *new_mem = realloc(cli_args_template,
sizeof *cli_args_template * (args_template_len + 1));
if (!new_mem) {
return false;
}
cli_args_template = new_mem;
CLIArgumentTemplate* arg_template = cli_args_template + args_template_len++;
arg_template->short_hand = short_hand;
arg_template->long_hand = long_hand;
arg_template->has_value = has_value;
arg_template->type = type;
return true;
}
You have other similar memory allocation problems elsewhere in the code that can be found with a half-decent static analyser or a runtime memory tool such as Valgrind memcheck. | {
"domain": "codereview.stackexchange",
"id": 42855,
"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, console",
"url": null
} |
java, algorithm, comparative-review, tree, trie
Title: Comparing a prefix tree against a HashSet of strings in Java
Question: Here, I have made an attempt to find out whether a prefix tree is any more efficient than a simple java.util.HashSet<String>. See what I have:
com.github.coderodde.text.autocomplete.PrefixTree.java:
package com.github.coderodde.text.autocomplete;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Queue;
/**
* This class implements a prefix tree (https://en.wikipedia.org/wiki/Trie).
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jan 19, 2022)
* @since 1.6 (Jan 19, 2022)
*/
public class PrefixTree implements Iterable<String> {
private static final class Node {
Map<Character, Node> childMap;
Node parent;
boolean representsString;
}
private final Node root = new Node();
private int size;
private int modCount;
public int size() {
return size;
} | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
public boolean isEmpty() {
return size == 0;
}
public void clear() {
root.childMap = null;
size = 0;
modCount++;
}
public boolean add(String s) {
Objects.requireNonNull(s, "The input string is null.");
Node node = root;
for (char ch : s.toCharArray()) {
if (node.childMap == null) {
node.childMap = new HashMap<>();
}
if (!node.childMap.containsKey(ch)) {
Node nextNode = new Node();
nextNode.parent = node;
node.childMap.put(ch, nextNode);
node = nextNode;
} else {
// Edge exists. Just traverse it.
node = node.childMap.get(ch);
}
}
if (node.representsString) {
// The input string is already present in this prefix tree:
return false;
}
node.representsString = true;
size++;
modCount++;
return true;
}
public boolean contains(String s) {
Objects.requireNonNull(s, "The input string is null.");
Node node = getPrefixNode(s);
return node != null && node.representsString;
}
public boolean remove(String s) {
Objects.requireNonNull(s, "The input string is null.");
Node node = getPrefixNode(s);
if (node == null) {
return false;
}
if (node.representsString) {
size--;
modCount++;
if (node.childMap != null) {
node.representsString = false;
return true;
}
int charIndex = s.length() - 1;
node = node.parent;
while (node != null) {
node.childMap.remove(s.charAt(charIndex)); | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
node.childMap.remove(s.charAt(charIndex));
if (node.childMap.isEmpty()) {
node.childMap = null;
}
if (node.representsString) {
return true;
}
charIndex--;
node = node.parent;
return true;
}
return true;
}
return false;
}
public List<String> autocomplete(String prefix) {
Objects.requireNonNull(prefix, "The input string is null.");
Node prefixNodeEnd = getPrefixNode(prefix);
if (prefixNodeEnd == null) {
return Collections.<String>emptyList();
}
List<String> autocompleteStrings = new ArrayList<>();
Queue<Node> nodeQueue = new ArrayDeque<>();
Queue<StringBuilder> substringQueue = new ArrayDeque<>();
nodeQueue.add(prefixNodeEnd);
substringQueue.add(new StringBuilder(prefix));
while (!nodeQueue.isEmpty()) {
Node currentNode = nodeQueue.remove();
StringBuilder currentStringBuilder = substringQueue.remove();
if (currentNode.representsString) {
autocompleteStrings.add(currentStringBuilder.toString());
}
if (currentNode.childMap == null) {
// No need to expand 'currentNode':
continue;
}
for (Map.Entry<Character, Node> entry :
currentNode.childMap.entrySet()) {
Node node = entry.getValue();
StringBuilder stringBuilder =
new StringBuilder(currentStringBuilder)
.append(entry.getKey());
nodeQueue.add(node); | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
nodeQueue.add(node);
substringQueue.add(stringBuilder);
}
}
return autocompleteStrings;
}
@Override
public Iterator<String> iterator() {
return new PrefixTreeIterator();
}
private Node getPrefixNode(String s) {
Node node = root;
for (int i = 0, len = s.length(); i < len; ++i) {
if (node == null || node.childMap == null) {
return null;
}
node = node.childMap.get(s.charAt(i));
}
return node;
}
private final class PrefixTreeIterator implements Iterator<String> { | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
private int iterated;
private final int expectedModCount = PrefixTree.this.modCount;
private final Deque<Node> nodeDeque = new ArrayDeque<>();
private final Map<Node, Character> nodeToCharMap = new HashMap<>();
private final StringBuilder stringBuilder = new StringBuilder();
private PrefixTreeIterator() {
if (!PrefixTree.this.isEmpty()) {
nodeDeque.addLast(PrefixTree.this.root);
}
}
@Override
public boolean hasNext() {
return iterated < PrefixTree.this.size;
} | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
@Override
public String next() {
checkForComodification();
if (!hasNext()) {
throw new NoSuchElementException("No more strings to iterate.");
}
while (true) {
Node node = nodeDeque.removeFirst();
if (node.representsString) {
String string = buildString(node);
expand(node);
iterated++;
return string;
}
expand(node);
}
}
private void expand(Node node) {
if (node.childMap == null) {
return;
}
for (Map.Entry<Character, Node> mapEntry :
node.childMap.entrySet()) {
nodeDeque.addLast(mapEntry.getValue());
nodeToCharMap.put(mapEntry.getValue(), mapEntry.getKey());
}
}
private String buildString(Node node) {
while (node != null && node != PrefixTree.this.root) {
char ch = nodeToCharMap.get(node);
stringBuilder.append(ch);
node = node.parent;
}
String string = stringBuilder.reverse().toString();
stringBuilder.delete(0, stringBuilder.length());
return string;
}
private void checkForComodification() {
if (PrefixTree.this.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}
}
com.github.coderodde.text.autocomplete.AutocompleteSystem.java:
package com.github.coderodde.text.autocomplete;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
/**
* This class implements a simple autocomplete system relying on a
* {@link java.util.HashSet} of strings.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jan 26, 2022)
* @since 1.6 (Jan 26, 2022)
*/
public class AutocompleteSystem implements Iterable<String> {
private final Set<String> stringSet = new HashSet<>();
public boolean add(String s) {
return stringSet.add(s);
}
public boolean contains(String s) {
return stringSet.contains(s);
}
public boolean remove(String s) {
return stringSet.remove(s);
}
public List<String> autocomplete(String prefix) {
List<String> list = new ArrayList<>();
for (String s : stringSet) {
if (s.startsWith(prefix)) {
list.add(s);
}
}
return list;
}
public int size() {
return stringSet.size();
}
@Override
public Iterator<String> iterator() {
return stringSet.iterator();
}
}
com.github.coderodde.text.autocomplete.PrefixTreeTest.java:
package com.github.coderodde.text.autocomplette;
import com.github.coderodde.text.autocomplete.PrefixTree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test; | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
public class PrefixTreeTest {
private final PrefixTree pt = new PrefixTree();
@Before
public void before() {
pt.clear();
}
@Test
public void addAndContainsString() {
assertFalse(pt.contains("in"));
assertFalse(pt.contains("inn"));
assertFalse(pt.contains("ink"));
assertTrue(pt.add("in"));
assertTrue(pt.add("inn"));
assertTrue(pt.add("ink"));
assertFalse(pt.add("in"));
assertFalse(pt.add("inn"));
assertFalse(pt.add("ink"));
assertTrue(pt.contains("in"));
assertTrue(pt.contains("inn"));
assertTrue(pt.contains("ink"));
assertTrue(pt.add("ixxxxx"));
assertTrue(pt.add("ix"));
assertTrue(pt.contains("ixxxxx"));
assertFalse(pt.contains("ixxxx"));
assertFalse(pt.contains("ixxx"));
assertFalse(pt.contains("ixx"));
assertTrue(pt.contains("ix"));
}
@Test
public void remove() {
assertFalse(pt.remove("aa"));
pt.add("aa");
assertTrue(pt.remove("aa"));
pt.add("aaaaa");
pt.add("aa");
assertTrue(pt.contains("aaaaa"));
assertTrue(pt.contains("aa"));
assertFalse(pt.remove("a"));
assertTrue(pt.remove("aa"));
assertFalse(pt.remove("aaa"));
assertFalse(pt.remove("aaaa"));
assertTrue(pt.remove("aaaaa"));
pt.add("aaa");
assertFalse(pt.remove("aaaaa"));
pt.clear();
pt.add("a");
pt.add("abbb");
pt.add("accc");
pt.remove("abb");
assertFalse(pt.contains("abb"));
pt.remove("abbb");
assertFalse(pt.contains("abbb"));
}
@Test
public void size() {
assertEquals(0, pt.size());
pt.add("a");
pt.add("b");
pt.add("c"); | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
pt.add("a");
pt.add("b");
pt.add("c");
assertEquals(3, pt.size());
pt.remove("b");
assertEquals(2, pt.size());
pt.remove("b");
assertEquals(2, pt.size());
}
@Test
public void testAutocomplete() {
pt.add("aaaa");
pt.add("bbbb");
pt.add("bbxs");
pt.add("bbda");
List<String> strings = pt.autocomplete("bb");
Collections.<String>sort(strings);
assertEquals(3, strings.size());
assertEquals("bbbb", strings.get(0));
assertEquals("bbda", strings.get(1));
assertEquals("bbxs", strings.get(2));
pt.clear();
pt.add("aaa");
strings = pt.autocomplete("aaab");
assertTrue(strings.isEmpty());
}
@Test
public void emptyString() {
pt.add("aa");
pt.add("ab");
assertFalse(pt.contains(""));
assertTrue(pt.add(""));
assertFalse(pt.add(""));
assertTrue(pt.contains(""));
pt.remove("");
assertFalse(pt.contains(""));
List<String> list = pt.autocomplete("");
assertEquals(2, list.size());
Collections.<String>sort(list);
assertEquals("aa", list.get(0));
assertEquals("ab", list.get(1));
pt.add("");
list = pt.autocomplete("");
Collections.<String>sort(list);
assertEquals("", list.get(0));
assertEquals("aa", list.get(1));
assertEquals("ab", list.get(2));
}
public void removeBug2() {
pt.add("");
pt.add("000");
pt.add("0");
pt.add("00");
pt.remove("00");
List<String> l = pt.autocomplete("");
assertEquals(3, l.size());
Collections.sort(l);
assertEquals("", l.get(0)); | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
Collections.sort(l);
assertEquals("", l.get(0));
assertEquals("0", l.get(1));
assertEquals("000", l.get(2));
}
@Test
public void iterator() {
pt.add("");
pt.add("0");
pt.add("00");
pt.add("01");
pt.add("000");
pt.add("0001");
pt.add("011");
Iterator<String> iter = pt.iterator();
List<String> list = new ArrayList<>();
while (iter.hasNext()) {
list.add(iter.next());
}
Collections.sort(list);
assertEquals("", list.get(0));
assertEquals("0", list.get(1));
assertEquals("00", list.get(2));
assertEquals("000", list.get(3));
assertEquals("0001", list.get(4));
assertEquals("01", list.get(5));
assertEquals("011", list.get(6));
}
} | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
com.github.coderodde.text.autocomplete.Application.java:
package com.github.coderodde.text.autocomplete;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* This class implements the internal state of the demonstration program for the
* prefix tree vs. {@link java.util.HashSet}.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Jan 26, 2022)
* @since 1.6 (Jan 26, 2022)
*/
public class Application { | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
private static final class CommandNames {
static final String ADD_STRING = "add";
static final String CONTAINS_STRING = "contains";
static final String REMOVE_STRING = "remove";
static final String AUTOCOMPLETE = "complete";
static final String PRINT = "print";
}
protected final PrefixTree prefixTree = new PrefixTree();
public void addString(String s) {
checkInputStringNotNull(s);
prefixTree.add(s);
System.out.println(getAllStrings());
}
public void removeString(String s) {
checkInputStringNotNull(s);
prefixTree.remove(s);
System.out.println(getAllStrings());
}
public void containsString(String s) {
checkInputStringNotNull(s);
System.out.println(prefixTree.contains(s));
}
public void autocompletePrefix(String prefix) {
checkPrefixNotNull(prefix);
List<String> list = prefixTree.autocomplete(prefix);
Collections.<String>sort(list);
System.out.println(list);
}
public void printAll() {
autocompletePrefix("");
}
public void processCommand(String[] tokens) {
switch (tokens.length) {
case 1:
processSingleTokenCommand(tokens);
return;
case 2:
processDoubleTokenCommand(tokens);
return;
default:
String cmd = String.join(" ", tokens);
throw new IllegalArgumentException(
"Bad command: \"" + cmd + "\"");
}
}
private List<String> getAllStrings() {
List<String> list = prefixTree.autocomplete("");
Collections.<String>sort(list);
return list;
}
private void processSingleTokenCommand(String[] tokens) {
assert tokens.length == 1;
switch (tokens[0]) { | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
java, algorithm, comparative-review, tree, trie
assert tokens.length == 1;
switch (tokens[0]) {
case CommandNames.PRINT -> {
printAll();
return;
}
default -> throw new IllegalArgumentException(
"Unknown command: " + String.join(" ", tokens));
}
}
private void processDoubleTokenCommand(String[] tokens) {
assert tokens.length == 2;
switch (tokens[0]) {
case CommandNames.ADD_STRING:
addString(tokens[1]);
return;
case CommandNames.AUTOCOMPLETE:
autocompletePrefix(tokens[1]);
return;
case CommandNames.CONTAINS_STRING:
containsString(tokens[1]);
return;
case CommandNames.REMOVE_STRING:
removeString(tokens[1]);
return;
default:
throw new IllegalArgumentException(
"Unknown command: " + String.join(" ", tokens));
}
}
private void checkInputStringNotNull(String s) {
Objects.requireNonNull(s, "The input string is null.");
}
private void checkPrefixNotNull(String s) {
Objects.requireNonNull(s, "The prefix is null.");
}
} | {
"domain": "codereview.stackexchange",
"id": 42856,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, comparative-review, tree, trie",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.