instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.
HW2 - Log file parsing - Full description
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
parseMessage :: S... | stackexchange/codereview |
I've recently acquired a program which is capable of using a GLSL fragment shader as a plugin. After a short amount of experimentation, I've realized that - for my use-case - I desperately need a function that does the equivalent of the following:
Takes two 2D points and calculates a line between them
Returns 1.0 if t... | stackexchange/codereview |
Can someone help me further optimize the following Cython code snippets? Specifically, a and b are np.ndarray with int value (range(256)) in them. They are one dimension arrays with dynamic length. resultHamming is a one-dimension array with float value in it (dynamic length). bits is an int list (size 256).
The fun... | stackexchange/codereview |
I've written this implementation of a binary search algorithm, and wanted to know if it was efficient and where I can improve.
function search(el, list) {
// list = list || LIST;
var LIM = Math.ceil(Math.log2(list.length)),
lb = 0,
ub = list.length - 1,
i;
while (el !== list[i = ~~((... | stackexchange/codereview |
I want to improve this code using STL or with better logic. I have not written code for delete function or for copy constructor or move constructor. My aim to learn to exchange even and odd elements.
#include <iostream>
#include <utility>
#include <cassert>
class LinkedList
{
struct Node
{
int data;
Node *... | stackexchange/codereview |
I'm a novice at Java and just beginning with Swing. I’m trying to figure out how to separate event logic from the presentation logic. Look at the following classes:
GUITest.java
package guitest;
import java.util.ArrayList;
public class GuiTest {
public static void main(String args[]) {
new MainFrame2();}... | stackexchange/codereview |
I wanted to make sure that my code is properly converting between the two endians.
Here is the code where I read in an integer:
System.out.println("Please enter the integer:");
int number = input.nextInt();
System.out.println("At what word address would you like to store the da... | stackexchange/codereview |
This is my first attempt at learning binary trees. I'm looking for general feedback on how it could be made cleaner, more idiomatic, or more efficient.
data Tree a = ETree | Node (Tree a) (Tree a) a deriving (Show)
tInsert :: Ord o => o -> Tree o -> Tree o
tInsert x ETree = Node ETree ETree x
tInsert x (Node lT rT a)
... | stackexchange/codereview |
I have a part of my code I want to optimize.
I use if statement to skip the analyze if the values are not the one I want.
Just to help the comprehension, in my data, R1 is between range(6,15); mis in range(0,1); spacer in range (0,10).
My code is working, but it would be better if it will run faster according to the a... | stackexchange/codereview |
I wanted to load every page under index.php with a simple index.php?do=login
For example when the link index.php?do=login or /login/ is opened, the file login.php is loaded (from outside public_html), and so everything is done under index.php instead of having a separate php file in public_html for each action!
This is... | stackexchange/codereview |
I'm trying to play around with Godot to learn C# and I was trying to creating pure functions to do the velocity, but I found I was repeating myself.
public override void _PhysicsProcess(float delta)
{
base._PhysicsProcess(delta);
Vector2 moveVelocity = velocity;
moveVelocity = Run(moveV... | stackexchange/codereview |
I am trying to implement a merge of two sorted lists of integers in Python using only the basic list abstract data type operations. That is, I do not want to use sorted() which comes with Python.
Could someone tell me if this code is alright? Also, am I correct to understand that it is linear to the core? That is, it u... | stackexchange/codereview |
Problem Statement
In a School, Chocolate bars have to be distributed to children waiting in a queue. Each Chocolate bar is rectangular in shape. Consider its side lengths are integer values.
The distribution procedure is as follows:-
If bar is not square in shape, then the largest possible square piece of Chocolate is... | stackexchange/codereview |
Wikipedia has an example of a decorator pattern here:
https://en.wikipedia.org/wiki/Decorator_pattern#Second_example_.28coffee_making_scenario.29
I was trying to solve this using functional style using Java 8 just to compare the Oop style and functional style of solving the same problem.
The solution I came up:
1.Coffe... | stackexchange/codereview |
Here's a proposal implementation of websocket using boost::asio::beast that is thread-safe to parallel writes.
In this example below, the async_write can be triggered in response to server notification (I) or from periodic keepalive calls implemented on a dedicated thread (II).
I'd like to here your comments regarding ... | stackexchange/codereview |
I am fairly new to javascript and I would like to write my code on a more readable and efficient way. Any critique of what I've written would be greatly appreciated, especially the section of hexValues.first = changeHex... Also, should I have two files going for this code? And if so, how should I best split it up?
(fun... | stackexchange/codereview |
For the queries mentioned in link in 3 parts, the first two parts have been addressed, as mentioned below:
Part I (6 points)
list/DList.java contains a skeleton of a doubly-linked list class. Fill in the
method implementations.
Note: "node" is passed in these methods so that user of class DList can avoid slow \$O(n)\$... | stackexchange/codereview |
Problem Statement
Design a system which helps calculate the TotalCost of the items in the Cart. You will be given a list of items in the Cart with Discounts like in the example below. The list would contain either items or discounts and the sequence matters:
Sample cart: $10 Book xyz, 10% Discount on all items, $20 st... | stackexchange/codereview |
I am relatively new at using PHP, and I am looking for experienced PHP/HTML users to have a look at my script and offer up any advice on what could have been done better or info on any discovered errors.
<!DOCTYPE HTML>
<html lang="en">
<head><meta charset="UTF-8">
<title>Registration</title>
</head>
<body>
<?php
$pa... | stackexchange/codereview |
I've written a simple tabbed component in ReactJS, whose purpose was to make defining different tabs very simple. My implementation does this very well in my opinion, since defining tabs becomes very simple:
<TabbedComponent>
<Tab>
<Name>Tab 1</Name>
<Content>
<h1>This is the first tab</h1>
<p>Thi... | stackexchange/codereview |
This is a method where a char[] will be supplied as an input and it should return an array, but without the duplicate elements. How can this be optimized?
private static char[] getMYCharArray(char[] array) {
String myArray = "";
for(int i = 0; i < array.length; i++) {
if(myArray.indexOf(arra... | stackexchange/codereview |
I'm trying to reduce the if statements and simplify this create action.
def create
@order = Order.create_from_result(JSON.parse(params['order']), JSON.parse(params['customer']))
# Ensure order saves before processing payment
if @order.persisted?
# Braintree transaction
result = @order.make_payment(params[:paymen... | stackexchange/codereview |
Prompt:
You have been given a string s, which is supposed to be a sentence.
However, someone forgot to put spaces between the different words, and
for some reason, they capitalized the first letter of every word.
Return the sentence after making the following amendments:
Put a single space between the words. Con... | stackexchange/codereview |
I'm writing a program that adds all network interfaces with multiple parameters to a list.
I have written the following code, which should work out of the box on any Linux system with Python and ethtool installed:
import imp
import os
import subprocess
import re
from enum import Enum
class interface_type(Enum):
... | stackexchange/codereview |
The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Bicyclists can calculate their speed if the gear size and cadence is known. Gear size refers to the effective diameter of the wheel. Gear size multiplied by pi (3.14) gives the distance traveled with one turn of the pedals. Cadence refers... | stackexchange/codereview |
I have a catalogue of 56000 objects and I want to replace some columns with new values for instance replace NaN with -99 and 0 for specific columns (as you can see in the following code). Then I need to compute a value for some columns with a function which is called get_ebv_from_map
and subtract it from some other co... | stackexchange/codereview |
I was a PHP developer and I started writing a product in C# without studying the basic structure. Now, I have around 100+ views with similar code. After 1 year into development, I now realize that something is not right.
How can I separate the server tags when they are so intertwined in the code? Is it okay to use serv... | stackexchange/codereview |
While writing a C++ implementation for weighed, labeled graphs, I started to doubt the effectiveness/correctness of my chosen structure and I would like to hear some reviews.
I tried to implement the graph as follows:
template <typename T, typename K> struct graph {
unordered_map< T, list< pair<T, K> > > adjList;
... | stackexchange/codereview |
When reviewing a Graham scan convex hull algorithm implementation, I wrote the following function in an answer:
giftWrap :: [Vector2] -> [Vector2]
giftWrap vs = result
where
-- Decides whether to keep or reject vertex b.
-- Vertex b is provisionally kept if a left turn occurs there; the result
-- is final... | stackexchange/codereview |
I have a method which creates some default values in an ObservableCollection, nothing too fancy, but I'm trying to decide how to write the if statement.
private void CreateDefaultParameters()
{
//If there are no parameters, then create default ones.
if (this.Parameters == null || this.Parameters.Cou... | stackexchange/codereview |
I'm writing a twirling cursor, which is a cursor that twirls in place in the console. In Forth, this takes just 3 lines, whereas in Python3 I have this:
from time import sleep # sleep(sec)
import sys
def flash(c):
"""Shows character c momentarily."""
# backspace ($8) and sleep(sec) keep it in place and slow... | stackexchange/codereview |
For a homework assignment, I made a web page that has a text area. The user inputs some text, hits the analyse button, and the output is supposed to be a list of the frequency of words of a given number of characters.
For example, "one two three" would be two words of three characters and one word of five characters.
I... | stackexchange/codereview |
I wrote this script a while back to generate press releases. It consumes a csv of data where each row contains the data for a country and fills in values in pre-written text based on the data. In its current state, it's basically a mad libs implementation with some hard coded conditionals. I'd like to refactor it to ma... | stackexchange/codereview |
I was told that the following code of mine was poorly written. How bad is it? Do you have any recommendations?
#include <iostream>
#include <fstream>
void ioMenu(std::ifstream&, std::ofstream&, std::string&, std::string&);
int ioMenuChoice();
void fileOpener(std::ifstream&, std::ofstream&, std::string&, int&);
void f... | stackexchange/codereview |
Say I have the following SQL:
SELECT
amount,
amount*.1,
(amount*1)+3,
((amount*1)+3)/2,
(((amount*1)+3)/2)+37
FROM table
Instead of repeating that identical code every time, I really want to be able to do something like this:
SELECT
amount,
amount*.1 AS A,
A+3 AS B,
B/2 AS C,
C... | stackexchange/codereview |
First of all I know my code is highly vulnerable to SQL injections, but I wanted to code the base first. I have a feeling this can be done with fewer lines and less repeating. I'm sorry if it is really bad code I just started learning C#.
public DataTable GetData(string search, int filter)
{
switch ... | stackexchange/codereview |
I've been learning Assembly over the past few days, and I've made a simple RPN calculator.
Here is the main logic of the program, excluding utility functions such as printing:
%include "utilities.s"
SECTION .data
badOpMsg db "Unknown character: ", 0h
badNumMsg db "Error parsing number: ", 0h
badE... | stackexchange/codereview |
I don't know if this is acceptable, but I would love to thank the community for their advice concerning my previous post on this project
This is a beginner's project.
Library management system aims to handle the basic housekeeping of a functional library, so far I have implemented the BookItem class and with advice fro... | stackexchange/codereview |
I wanted to render the textures that comprise a bitmap font glyph onto the screen directly as an Image in libGDX. When you make a bitmap font using a program (such as Hiero), it generates a text readable .fnt file along with a .png file that is the sprite sheet for the font. The only thing missing is a matching .atlas... | stackexchange/codereview |
I am looking for a elegant solution to this. I am new to Spring framework. I have a method:
public String getStringProperty(String property) {
Object value = SomeWrapper.getPropertyValue(property);
return (value != null) ? String.valueOf(value) : "";
}
The immediate upstream method is:
public Strin... | stackexchange/codereview |
I attempted some (easy) coding with Java Native Interface. This is what I have:
six_pack_Neatifier.h:
(autogenerated by javah)
#include <jni.h>
#ifndef INCLUDED_SIX_PACK_NEATIFIER
#define INCLUDED_SIX_PACK_NEATIFIER
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: six_pack_Neatifier
* Method: neatify
* ... | stackexchange/codereview |
I built a wrapper in Swift to practice CoreData.
My question is more general, I hope this is acceptable. I wanted to know whether my implementation of this wrapper is correct or poorly implemented for practical use. Any feedback like design-patterns, conventions, etc are welcome as well.
Currently I have a class I refe... | stackexchange/codereview |
I was trying to solve this problem from Leetcode:
Given a string, find the length of the longest substring without
repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length... | stackexchange/codereview |
Previously I asked a question to find the best practice of recursively running a function to retrieve all import/export statements of files in NodeJs here.
After some discussion I'm not satisfied yet, so I'm going to post my rewrote code from what I learned in previous discussion in hope of finding a better approach or... | stackexchange/codereview |
This is a contrived example of a question that came up in code review the other day about memoizing context values in React. Let's say I have a hook which returns a memoized value of an expensive operation like so
import { useMemo } from 'react'
const ONE_MILLION = 1_000_000
const ZERO_TO_ONE_MILLION = Array(ONE_MILL... | stackexchange/codereview |
I'm working on solving a problem involving finding the largest of a series of numbers being XORed.
This is the actual problem:
Xorq has invented an encryption algorithm which uses bitwise XOR
operations extensively. This encryption algorithm uses a sequence of
non-negative integers \$x_1, x_2, ... x_n\$ as key. To... | stackexchange/codereview |
A while ago I wrote an implementation of RSA with C++, that takes in a simple string,encrypts and then decrypts it. It's pretty much the only substantial thing I have written in C++ and while it works (kinda), it is slow at encrypting and extremely slow at decrypting (It takes about ~80 seconds to decrypt a 200 charact... | stackexchange/codereview |
Go is a board game (it looks like 5-in-a-row and plays like chess) and I tried to program it in Java.
Rules:
Two players take turn placing stones on a board. The goal is to capture teritory. Stones can be captured (removed from game) if they have no unoccupied adjacent tiles horizontaly/verticaly. Adjacent stones (ho... | stackexchange/codereview |
I'm not a C programmer, just wanted to make a fast solution to the problem.
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
Here's my code:
#include <stdio.h... | stackexchange/codereview |
Is there any better way of printing it?
public class PercentPrinter {
/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
if (i == 0)
System.out.print("percent completed: " + i + " %");
try {
Thread.sleep(500);
} catch (Ex... | stackexchange/codereview |
Working on creating new tower defense in JS. May be port to React.
How to improve? Only made enemies and path so far.
In below demo, path is white background and enemy is red circles and green squares. Enemy may have different type: triangle or different speed.
"use strict";
// https://stackoverflow.com/a/15313435
f... | stackexchange/codereview |
The program should read equations from stdin, parse them and generate a matrix of the coefficient which represents the system.
Example:
$ ./eqs
x + y = 4
-y + 4x = 2
1 1 4
4 -1 2
As you can see, the user can input as many equations they want and the program stops reading when an empty line is sent.
#inclu... | stackexchange/codereview |
Visual Studio 2013 still doesn't support the alignas keyword in C++11. This causes some problems with alignment of types in various situations. Thankfully the compiler will generate an error when it can't guarantee the alignment or at least give a warning.
To solve these errors and warnings I'm implementing a wrapper ... | stackexchange/codereview |
On part of a project, I have some CSS being read using twig's source() function.
But sending a huge chunk of CSS is not optimal.
To reduce the size of the HTML, I've written this twig filter.
However, I've noticed that some big files would take a bit more to be minimified.
To reduce the time to re-minify the CSS, I've ... | stackexchange/codereview |
This is my second try at writing Ruby. Stylistic feedback is very much appreciated.
The problem:
2048 is played on a simple 4 x 4 grid with tiles that slide smoothly
when a player moves them. For each movement, the player can choose to
move all tiles in 4 directions, left, right, up, and down, as far as
possib... | stackexchange/codereview |
Here's a perhaps naive but simple implementation of Radix sort in Java.
It works with any radix, and both positive and negative numbers.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class RadixSortWithDivision {
public static final int DEFAULT_RAD... | stackexchange/codereview |
I just implement Dijkstra's algorithm in C99. Can you review my code please? I'm looking for any mistake, performance improvement or coding style errors.
main.c
#include "src/map.h"
#include "src/pathfinder.h"
int main() {
map *map = init(createTuple_2(11, 11));
addBegin(map, createTuple_2(1, 1));
addEnd(map, cr... | stackexchange/codereview |
Can you please review my Minesweeper implementation in Java?
package com.game;
public class Tile {
private boolean hasMine = false;
private boolean revealed = false;
private int mineCount = 0;
public boolean hasMine() {
return hasMine;
}
public void setHasMine(boolean hasMine)... | stackexchange/codereview |
I'm trying to make a model for checking combo presses in a game. Given a list of Button (enum) presses, it returns the list of possible combos completed. I tried using a suffix tree, but I'm not sure if this is the best solution. It's also my first time writing a suffix tree, and I don't know if this is the correct usa... | stackexchange/codereview |
I need a procedure that "centers" a string inside a string that is consecutive characters of a fixed length. For instance,
======================== Instructions ============================
or
**************************** hehe ********************************
might be printed by calling
PrintBetweenChars("Instruct... | stackexchange/codereview |
I have a function which verifies the "Password" field and suggests the user to enter a strong password. I also have a label named "Password Strength", referring to the strength of a password (very weak, weak, medium, etc).
I'm just wondering if there is a better way to re-write this code.
function chkPasswordStrengt... | stackexchange/codereview |
I have a fully working "Guess my number" game, in which the batch file will generate a random number between 0-whatever you choose. I got the idea from this thread, in which I had a rather hilarious conversation with a certain member. So I got bored tonight, and reworked the code a little, to show that member how this ... | stackexchange/codereview |
To clarify: The code in "What I achieved" is working. I'm looking for suggestions so I can improve.
I'm quite new with JQuery (and javascript) and I've been learning while styling a forum. Recently I came across a section of information that is added automatically from a form (its the output). I can't manipulate the HT... | stackexchange/codereview |
We have an entity data model (database first) for a legacy product we are migrating to .Net from Delphi. We recently deployed to a server where some of the tables had been modified and columns deleted. The results were catastrophic. I'm working on a way of validating the EDM schema against the live SQL server database.... | stackexchange/codereview |
I am playing with Rust, and am trying to write a simple parser.
I need to parse the string:
"0123,456789"
into a stucture:
Passport { label : i8 = 0, body : i32 = 123456789 }
I am using parser_combinators and my code is working, but very ugly.
How can I rewrite this code?
extern crate parser_combinators as pc;
use ... | stackexchange/codereview |
My attempt at a observer design pattern (I know using namespace std isn't good). I'm very new to design patterns. Everything is inline with class definition. Please tell me if I'm doing anything wrong or if there is anything that can be improved. Does subscriber (observer) need to store info from update function? Also,... | stackexchange/codereview |
This function checks these 6 fields for a user profile to determine if they have "completed" their profile. This just feels like it could be done better, but I can't figure how.
/**
* Is the user's entire profile filled in?
*
* @return boolean
*/
public function isProfileComplete()
{
$checkList = [
$thi... | stackexchange/codereview |
I've implemented the game of Pig in JavaScript. My implementation has the following rules:
Two players take turns playing in rounds.
In a round, the player rolls a single die as many times as they wish, with the sum of their results becoming their score for that round.
If the player rolls a 1, then their score for tha... | stackexchange/codereview |
This function is intended to remove leading and trailing whitespace from a string. How can it be made more efficient? For example, can the two for loops be combined into one?
string trim(string str)
{
int i = 0;
for (char c : str)
{
if (!isspace(c))
break;
i++;
}
string... | stackexchange/codereview |
For my first use of javascript I've made an app that takes an input verb from html in Japanese and outputs it in to many conjugated (manipulated) forms.
Essentially, it defines an alphabet, some initial arrays and functions for use, a function to initially check for values and interact with the html page, an object to... | stackexchange/codereview |
I have currently problem with discord bot, what is in Python programming language. This commands loading take so long, and I need help with optimization of this code.
from fractions import Fraction
import discord
from discord.ext import commands
import asyncio
import asyncpg
import datetime
from aiohttp import web
imp... | stackexchange/codereview |
I have wrote code for a stopwatch that utilizes the abstract design pattern and would like to get some feedback on the code, so be as harsh as you can.
Note: I used ctime instead of chrono because this is not meant for benchmarking. The code will later be used in a console game, and the format of the std::tm struct is ... | stackexchange/codereview |
I Have the below code that gets urls of PDF files, send them to a convert function and returns them as images, is there a way to make this code more readable?
Is there a way to avoid functions chaining?
import PDFtoImages from '../PDFtoImages'
export async function convertPDF(file, category) {
const images= await ... | stackexchange/codereview |
I am trying to create a simple factory pattern demo in PHP. I am not sure if my codes are the best practice. It seems that I have some duplicated codes but I am not sure how to improve it. Basically, I want to create 3 types of accounts (basic, premium and vip). Please advise. Thanks a lot.
abstract class
abstract clas... | stackexchange/codereview |
I am looking for any refactoring tips to improve code readability. Does it feel like procedural programming? If so, how can I improve it?
public class StatementJob implements Job {
private static final Logger LOGGER = LoggerFactory.getLogger(StatementJob.class);
private static final String JOB_IS_DISABLED = "U... | stackexchange/codereview |
Is this a correct implementation in Haskell of a proof checker for first order logic with equality? I am most interested in if it is correct, and if the functions can be made clearer. I would like it to be useful for elucidating the definitions given in textbooks.
{-
Hilbert style first order mathematical logic with eq... | stackexchange/codereview |
I have written a server-side and the client-side of a chat application. I would like to improve it and I am unsure about my server construct and have absolutely no idea if there is a better way to do it. I haven't found anything on Google, therefor I ask you. The construct I have used is from a tutorial from Oracle I f... | stackexchange/codereview |
There are 2 arrays. One that consists of Categories and one of Products. Each product pertains to its specific category. I want to join each product to its right category (a category can have multiple products). Each product that 'finds' its category will go in this category's products array.
for ($i = 0; $i < count($p... | stackexchange/codereview |
I am new to flutter and i managed to build a working Grid which does what i want it to do but the code is a duplicated hell and i didn't manage to create it dynamically while still keeping track of the input-fields and its input.
I really could use some help!
import 'package:flutter/material.dart';
import 'package:intl... | stackexchange/codereview |
I recently have given a coding test in a reputable IT company. There were three coding questions.
They refused me by saying that
as we felt they didn't demonstrate the level of technical depth we're seeking from candidates
Question 1 : Missing level of technical depth (Recursive to Iterative)
Question 2 : Missing lev... | stackexchange/codereview |
I'm just doing a small hobby project to solve a little problem I have and I'm using it as a learning exercise for ASP.Net MVC 5, .Net Core 2 and Bootstrap.
I'm using a nuget package that handles interaction with a 3rd party api (EveStandard), I make the api calls that I need, spin up a view model which holds the data I... | stackexchange/codereview |
I'm new in LINQ and Lambda expression. I'm not sure is there a way to shorten the result on this o.z.cust.cust.cust.bintAccountNo. As you can see below, the more table needed to join the longer the resultselector cust.cust.cust. Is there better way to shorten this Lambda expression's result selector?
POCO
public clas... | stackexchange/codereview |
This filter is basically gradient detection (the variable gradImg) like an edge detection (Sobel or Prewitt filters) and also the direction of that gradient whether vertical or horizontal (dirImg).
I'm trying to optimize it to run faster and I found that this part of the code slow. Would you have any suggestions please... | stackexchange/codereview |
The data file is here.
Here are my codes:
> ftable=read.table(file.choose())
> start.time=Sys.time()
> 1-length(which(ftable==1))/sum(ftable)
[1] 0.12
> end.time=Sys.time()
> end.time-start.time
Time difference of 0.004880905 secs
I understand that 0.00488 secs are not a lot. But I have to repeatedly do this calculati... | stackexchange/codereview |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
... | stackexchange/codereview |
I wrote a simple TicTacToe console game in Python3. I would like to make my program more pythonic than it is now. For example, instead of if a == 5 and b == 5 and c == 5: you can write if a == b == c == 5:. So I expect hints of how can I rewrite my code to take adventage of Python language.
I don't ask for algorithm op... | stackexchange/codereview |
How can I improve this code for counting the number of bits of a positive integer n in Python?
def bitcount(n):
a = 1
while 1<<a <= n:
a <<= 1
s = 0
while a>1:
a >>= 1
if n >= 1<<a:
n >>= a
s += a
if n>0:
s += 1
return s
| stackexchange/codereview |
Here's a function that sorts an array of objects with a dateProp by the date. First it uses moment to convert the Date object to a unix timestamp.
var _ = require('lodash')
var moment = require('moment')
util.orderByDate = function (arr, dateProp) {
if (!dateProp) return arr
return _.chain(arr)
.map(function (it... | stackexchange/codereview |
This is my first dice game and I have spent countless hours working on it, yet it is still very basic. I was wondering if anyone could spare the time to suggest improvements.
import time
import random
import sys
Password= 'password'
while True:
password= input('ENTER PASSWORD:')
if password == Password:
... | stackexchange/codereview |
I have this vbs file to check if a remote server is accessible. Can I simplify or refactor to make it more robust/efficient?
const forReading = 1, forWriting = 2, forAppending = 8
public maxWaitTime
maxWaitTime = 60 '1800 '30mins
public connLogFileName
connLogFileName = "connectionLog.txt"
public pathToRemoteServer
p... | stackexchange/codereview |
I'm trying to design a mapper that will convert one object type to another shown in the diagram below:
The object has structure as follows (it's not a JSON):
{
"type": "DownloadAppComponent",
"name": "Download App",
"contentId": "download-app",
"properties": {
"iosUrl": "http://apple.com",
"androidUrl": "http:... | stackexchange/codereview |
In an attempt to learn better functional programing I've attempted to convert some Python to idiomatic Clojure, but I'm not sure how well I did with parts of it.
One thing I found myself doing a lot was destructuring a map into a list and then converting it back into a map as in the following example that takes a map o... | stackexchange/codereview |
I've made a short program to determine if a string is permutation of another string.
Example input/output :
a) 123, 112 <- False
b) 123, 321 <- True
c) 112, 121 <- these don't count as permutations since they have duplicate characters
private static void Main()
{
string a = Console.ReadLine();
... | stackexchange/codereview |
I'm a relatively new (~6 mos) developer, and I'm hoping for some feedback on my code style/structure. While I'm particularly interested in efficiency and maintainability, I'm open to feedback regarding anything that comes to mind from more experienced developers.
/**
* Attempts to create new SavedSearch (eventual POST... | stackexchange/codereview |
I have never really had to use Json.net until now, so I'm very rusty at it. For that reason, I would appreciate it if someone could have a look over my code and let me know if the way I have done it is correct. It works as I want it; I just need a more professional eye.
For the class TravelAdvice, I've used http://jso... | stackexchange/codereview |
I just submitted this pull request to statsmodels (a Python toolkit for statistical and econometric modeling). It adds support for exponential smoothing of time series.
I have only been programming for a few months. I am not very good with Numpy, and just learning classes and decorators, so any help would be appreciate... | stackexchange/codereview |
As an experiment, I've created an NUnit test project that should, when running all tests, open three browser windows simultaneously, and each should load a particular page before closing.
My question is: Am I using the WebDriver and ChromeDriver APIs correctly, especially with regard to best practices?
First, I create... | stackexchange/codereview |
Utilizing the below relation, I am able to compute the Euler constant to great precision on a single thread quickly and simply.
My process is to compute the natural log via the AGM(utilizing Pi an the Ln(2)), and apply the result to the BMM algorithm.
\$\gamma=\lim_{n\to\infty}\mathscr{G}_n=\lim_{n\to\infty}\frac{\sum\... | stackexchange/codereview |
I want my Python decorators to have optional arguments and not be called when not necessary.
The accepted answer in here doesn't accept named arguments, and I don't want to add boilerplate code inside decorators, so I came up with an alternative decorator:
import inspect
def decorator_defaults(**defined_defaults):
... | stackexchange/codereview |
The Original Post (v1)
I'm looking for feedback on the updated version of the code posted at the link above.
#pragma once
#include <memory>
#include <cassert>
#include <type_traits>
namespace datastructures {
template<class _Ty, size_t _Size>
class CircularBufferv2 {
// uses char as type to prevent ... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.