instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
New to Rust and would like some clarification on idiomatic and readable use of Result and Error types. Here I'm simply connecting to a database using Diesel. In my opinion, the use of match and Boxing error makes be feel like there's a more concise but still readable way to do this.
fn establish_database_connection() -... | stackexchange/codereview |
script.py:
#!/usr/bin/python
import os
srcDir = os.getcwd()
dirName = 'target_directory'
dstDir = os.path.abspath(dirName)
def ignore_list(path, files):
filesToIgnore = []
for fileName in files:
fullFileName = os.path.join(os.path.normpath(path), fileName)
if (not os.path.isdir(fullFile... | stackexchange/codereview |
I have recently made some major changes to my configuration file and wondered if I could get it reviewed, and be told what I can improve on it. My designer pattern and personal preference has changed a lot since I originally wrote this class, and I have basically re-wrote it. I just wanted to know if anything is poor c... | stackexchange/codereview |
Currently, I am working on this project where I need to achieve the following...
Get column named Category from MySQL database. And whatever the output is, check the specific radio button on winforms.
I'd like to see if I can improve it, or if there is a much easier way of achieving my goal:
Personally - i think there ... | stackexchange/codereview |
I had recently completed one programming challenge where I've had to design a deck of cards. The time was limited but I tried my best. I designed the basic operations and am wondering if I can improve the current structure of class and objects. I'm also looking for pros and cons of my design.
import java.util.Random;
... | stackexchange/codereview |
I wrote the following Author class in Python for a project I'm working on. I wanted to make sure that the rich comparisons and the methods I used to validate the constructor parameters were done properly.
Author class:
class Author:
def __init__(self, id, firstname, lastname):
self._validateid(id, "ID")
... | stackexchange/codereview |
I had a hardware project for a 5x5x5 RGB cube which is driven by a 22118400Hz 8-bit AVR (1284p for those who like hardware).
Basically, the class sets the bits in a huge array of 8-bit values (exactly 5x30x10 uint8_ts).
To understand why a short excursion:
The array contains 5 for the level, 30 for the color multiplex... | stackexchange/codereview |
Background info
I have just started using/ learning how to use Next.js and developed a basic application which allows users to view several pages, some of which are authentication protected. Users must sign in/ up, in order to view content on other pages.
I'm using Firebase's Google Authentication to handle my user log... | stackexchange/codereview |
I am an algo-newbie and this is my first attempt at writing binary search and it worked on the first try. But something about it tells me that its far from perfect. Please tell me how I can improve.
using System;
class Program
{
public static void Main()
{
int[] arr = { 40, 67, 34, 25, 65, 87, 23 };
... | stackexchange/codereview |
I'm having an implementation using SerialPort in C# using Visual Studio 2019. I'm using it in a Windows Application, using .NET Framework 4.7.2.
When I open and initialize the SerialPort, I'm launching 2 "message pump tasks", one for receiving data and one for transmitting data.
The SerialPort has a ConcurrentQueue to ... | stackexchange/codereview |
I am building my first Laravel web app and I have created a class to handle API requests for a model called Quote. In what ways can the code be improved or reduced?
<?php
namespace App\Http\Controllers;
use Illuminate\Http;
use Illuminate\Http\Request;
use App\SuperQuote\Transformers\QuoteTransformer;
use App\Supe... | stackexchange/codereview |
Is there any way to improve this code:
punch:0 -> in
punch:1 -> out
from datetime import datetime
attendance = [{"id": 1, "punch": 0, "date": "22-04-2022 02:10:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 03:00:00"},
{"id": 1, "punch": 1, "date": "22-04-2022 04:00:00"},
{"id": 1, "pun... | stackexchange/codereview |
Introduction
I was daunted by the complexity of Makefiles for even seemingly simple projects and I decided to rectify that. I also needed to make myself a few handy command-line tools for convenience (like when I don't have an internet connection). This project makes a utility program called gcd or gcd.exe on Windows. ... | stackexchange/codereview |
I have completed my homework with directions as follows:
Declare and implement a class named Binary. This class will have a
method named printB(int n) that prints all binary strings of length n.
For n = 3, it will print
000
001
010
011
100
101
110
111
in this order.
Here is my code:
import java.util.Scanner;
c... | stackexchange/codereview |
I wrote a solution to Course Schedule II - LeetCode
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite... | stackexchange/codereview |
I'm quite new to C, and I decided to create a generic vector library. Here is the code:
#ifndef VECTOR_H
#define VECTOR_H
#define DEFAULT_CAPACITY 10
#define EXPAND_RATIO 1.5
#include <stdlib.h>
#include <string.h>
enum error {
NO_ERROR,
INDEX_ERROR,
KEY_ERROR,
NULL_POINTER_ERROR,
MEMORY_ERROR
};... | stackexchange/codereview |
Recently, I wrote a C header file that defines a new type called HashMap that allows for the storage of key/value pairs.
I am just learning about the wonders of void pointers and as I use them, I get lots and lots of warnings about making pointers without a cast. The header file itself does not yield any warnings, but ... | stackexchange/codereview |
In my web-app, it is possible to delete an Item when visiting any of 4 different pages:
the Show Item page
the Edit Item page
the List Items page
the List Items in Room page
If the visitor uses a delete button on either of the 2 List pages, they should remain on their current page when the deletion is complete. But i... | stackexchange/codereview |
This function creates a series of links at a desired destination by the usage of a premade tag system.
Usage:
createMyTAGS_DATA passes in a single line of all the links as: LinkText;LinkAddress;;
createMyTAGS_LOCATION passes the destination to a div,span,... to render the result
Result would be:
<a href="LindAddress... | stackexchange/codereview |
In a recent project my backend architecture consists of
Repositories (talking to database)
Services (handling business logic)
Controllers (handling incoming REST calls and providing according responses to the client)
I introduced DTO classes for representing the data that is returned by the controllers when a client ... | stackexchange/codereview |
Yesterday I wrote a serialization/deserialization for my B-Tree library.
Since the code for whole tree is too large to upload here, I'll upload only serialization/deserialization and node class definition/tree class member variable parts here.
I think my code is not broken, but I want to know how to do error checks bet... | stackexchange/codereview |
I want to get text1 and text2 by splitting time format
Text1 10:24:02 Text2
Of the two working regexes below, which is faster?
Regex 1
String regex1= "([0-9]{2}):([0-9]{2}):([0-9]{2})";
Regex 2
String regex2= "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]";
This is the code I've used:
String s="Text1 10:24:02 Text2";
String[] ... | stackexchange/codereview |
The objective of the following PHP function is simple: given an ASCII string, replace all ASCII chars with their Cyrillic equivalents.
As can be seen, certain ASCII chars have two possible equivalents.
For example: if the function is fed the string "dvigatel" it should get you "двигател".
The problem: if I pass "dviga... | stackexchange/codereview |
Project Euler #6:
The sum of the squares of the first ten natural numbers is,
\$1^2+2^2+ ... + 10^2 = 385\$
The square of the sum of the first ten natural numbers is,
\$(1+2+ ... + 10)^2 = 55^2 = 3025\$
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \$... | stackexchange/codereview |
After the Reorder Parameters refactoring, I implemented a Remove Parameters refactoring (no, it didn't take this long, just been busy). Also, we completely refactored all the refactorings and implemented a couple interfaces for them all, which you can find here; for reference, the Remove refactoring code is found here... | stackexchange/codereview |
I am a graphics programmer and was wondering about my code quality.
I selected these three examples:
Game engine, which uses OpenGL and has a lot of other non-graphics code
A 3D software renderer, uses the basic X11 libraries for drawing
A WebGL framework (found under felipetavares/webgl.js)
Here is the code for the ... | stackexchange/codereview |
Having mostly used Qt and its classes like QString, I wrote a little exercise with plain C++11. I'm looking for two kinds of input: generally improving the code and/or doing it better in an entirely different way (still standard C++11 or C++14, no Boost or anything).
The code is for printing doubles with given number o... | stackexchange/codereview |
I wrote a small module in typescript that augments the angularjs registerComponent function to provide a new way of default values for the component controller.
This module was written to solve the problem of not having a nice non-biolerplatey way of providing default values for components. Another problem it attempts ... | stackexchange/codereview |
I am a beginner in PHP-OOP and design patterns. I have got this basic piece of code in Singleton Pattern and I changed it in order to understand its behavior. I can see that it works as expected.
However, it is not clear for me exactly how it works. Can anyone explain me? So it is working! My doubt is "Whis $inst is no... | stackexchange/codereview |
Here's the cool number problem given to me by my senpai in competitive programming:
A cool number is a number that can be at the same time written as the square of a whole number and the cubic of another whole number.
Write a program in Python that returns the number of cool numbers for every given [m, M] with 1 <= m ... | stackexchange/codereview |
This is a programming challenge I set for myself a while back to create an AI that starts with no knowledge of anything whatsoever, and learns as you talk to it. (It can learn stuff like your name, how to say hello, goodbye, etc.)
I tried to use the least amount of hard-coded responses as possible. I'm happy that it wo... | stackexchange/codereview |
I am trying to improve my general skills in C++ so I plan to write versions of shared_ptr and unique_ptr from scratch. I wrote a version of shared_ptr with reference counting and I was wondering for reviews.
#ifndef __SHIVA_XSMARTPTRS__
#define __SHIVA_XSMARTPTRS__
/*
This tries to define a reference counted smart poi... | stackexchange/codereview |
I am writing up a class to handle various templates to be used in a web application. Each template contains various placeholders which will need to be replaced at the time of the build. I am wondering if the method I am using is the best solution, or if I should consider something else. At the moment I have two separat... | stackexchange/codereview |
Below stored procedure implemented for filtering and sorting operation.But number of table column increases below query becomes complex to read/maintain. This is good for small tables.
I want to modify the below one by using dynamic sql query. I will pass the parameter from front-end to here.
CREATE PROCEDURE [uspProdu... | stackexchange/codereview |
Here is the code that I wrote to give me sum of prime numbers between n and m:
class TestClass {
final static int MAX=1000000;
final static boolean[] isPrime=isPrime();
public static void main(String args[] ) throws Exception {
BufferedReader keyboard= new BufferedReader(new InputStreamReader(System... | stackexchange/codereview |
I need a way to delay a function call by 30 seconds on a machine that runs on electric power, not battery (if it matters). I have heard from my colleague not to use sleep, but this post suggests it:
sleep(30) // sleep for 30 sec
Reasons invoked for not using sleep include:
I will violate Single Responsibility Princ... | stackexchange/codereview |
I'm working with ACF in WP which provides a get_field() function. The function can return an array of values, null or false. When the result of the function doesn't contain an array of values I want to default to an empty array.
This is how I do it at the moment but would like to know if there's a neater way to accompl... | stackexchange/codereview |
Is there a way to write this better or more Clojure way? Especially the last part with with-open and the let. Should I put the -> form into a separate function? Is this function to overloaded (to much stuff) or is this still ok?
(defn scrape-book-cover [url image-filename]
(let [out-stream (io/output-stream image-f... | stackexchange/codereview |
I have just written a solution to the following problem:
We all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a... | stackexchange/codereview |
I have created a jQuery slider for my personal website and I wanted to get some feedback on how it looks and if there are things I can do to make it better.
You can see the live demo here: http://www.nickmeagher.com
And here is the code:
var sliderWidth = 0,
marginLeft = 0,
containerWidth = 1040... | stackexchange/codereview |
Currently I have this code:
private async Task<(List<SomeModel> data1, List<string> data2)>
ProcessFileAsync(IEnumerable<FileInfo> filesInDirectory)
{
var data1 = new List<SomeModel>();
var data2 = new List<string>();
var inDirectory = filesInDirectory as FileInfo[] ?? filesInDirec... | stackexchange/codereview |
The following code works fine, however, I'm trying to simplify it. I wrote it but I'm a beginner PHP coder. I can see that most probably the use of a function or class would be better... or anything to make it more concise in terms of PHP.
This is WordPress PHP code. I can't do it in a loop. You see how repetitive it i... | stackexchange/codereview |
I have the following CRC 16 code. Is it possible to improve the performance of the code with unsafe constructs? My knowledge about pointer arithmetic is rather limited.
public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }
public class Crc16Ccitt
{
static ushort[] table = new ushort[256];
... | stackexchange/codereview |
I often do golf challenges, and thought it might be advantageous to write some code that automatically removes all the unnecessary whitespace from a program.
After a few refactors, this is what I ended up with. In all the tests I've run it through, it's correctly removed only the whitespace that doesn't change the mea... | stackexchange/codereview |
I've made a card flip with CSS keyframes but instead of flipping clockwise and then flip counterclockwise to it's original position, I've two separate keyframes that will cause it to rotate in the same direction each time I rotate.
I have jQuery checking if either class exists and adding the first one if neither exists... | stackexchange/codereview |
I am trying to optimize execution time of this function which detects cycle in a directed graph:
g = {
1: [2, 3],
2: [3]
}
cur_path = set()
def isCyclic(g, vertex):
global cur_path
cur_path.add(vertex)
for neighboor in g.get(vertex, []):
if neighboor in cur_path:
return True
... | stackexchange/codereview |
I use Nginx as a server, and I currently use this for configuration of each my sites. Basically, I have multiple files like this located in /etc/nginx/conf.d/.
#example.conf
server {
listen 80;
server_name www.my-site.com my-site.com;
root /var/www/html/my-site.com;
location /... | stackexchange/codereview |
I'm super new to CodeIgniter 3 and I'm using it to build a task manager (Claritask.com). Also, I'm just starting to learn how to program, so forgive me beforehand if I'm not making sense and I'll try to clarify in comments.
As I'm building my specific Project page that lists specifc tasks, I was curious to know if I'm ... | stackexchange/codereview |
What follows in an attempt at implementing Mark V. Shaney using contemporary Python. One question has already been asked while working on a generator in the code, but included here is the entire module. Are there any places that could be more idiomatic or Pythonic?
import collections
import functools
import itertools
i... | stackexchange/codereview |
Github repo
I've attempted a backend assignment in Go from geektrust Assignment Link.
I'm not sure the code that I have written is idiomatic in the go way. I need some feedback on this code based on its extensibility, proper use of data structures.
How can this code be more improved?
Main build function of the project.... | stackexchange/codereview |
I have the following method which I use in multiple places, but it only differs by a few different things, so I was wondering how I can refactor it so I can have it in a common class and call it from there everywhere.
public override DataTable GetRecords(QueryContext queryContext, out int totalRecords)
{
// Build Q... | stackexchange/codereview |
This is the first API wrapper I've written and I'm wondering what I can do to improve. I've read through the feedback of a few similar posts
Readme
Code
import requests
import time as notdatetime
import datetime
import matplotlib.pyplot as plt
# uses Algolia for API
class API():
def __init__(self):
self.ba... | stackexchange/codereview |
I did this programming challenge. Part C of the challenge, is to find the salary you have to save every month to be able to buy a house in 36 months.
This is my first time using bisection search so I just want to make sure that I did it correctly. I question the efficiency of my program because in test case 2 for part ... | stackexchange/codereview |
My implementation is only for study purposes, I agree that some of the features may be counter-intuitive.
I guess the best method is to use a list in the STL library.
Any improvements will be greatly appreciated.
The following code compiles and works, If possible I would like the code reviewed in C++98, If not the clos... | stackexchange/codereview |
I've written a script in vba to parse movie names and year from a torrent site. The script is doing just awesome. Although the scraper is leaving no room for complaint, I'm still dubious about how the way I've set the proxy is accurate. Moreover, I've set two proxies in my scraper. Btw, I went through few codes where t... | stackexchange/codereview |
This is a simple ToDoApp with a CLI that is made useful by adding persistence. A shout out to @Phrancis and @syb0rg for guiding this little project to where it is now.
The structure is rather simple. The basic class is ToDoItem. It is stored in an implementation of the interface ToDoRepository - in InMemoryToDoReposito... | stackexchange/codereview |
I am not very experienced with T-SQL and feel this can be done better. The script changes ownership of all "user" (non-system) databases to sa.
Usage of a dynamic SQL expression seems unavoidable to me. Could I at least iterate the table names in a more elegant way — imperative code looks like a code smell in a SQL scr... | stackexchange/codereview |
I took the idea from Reversing a matrix in C# and decided to write my own matrix-reversing code.
Is there anything that I can do to make it even better?
static void Main(string[] args)
{
var matrix = new[,]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
... | stackexchange/codereview |
This code works, and I'm pretty sure it's mathematically/algorithmically correct:
model = tf.keras.applications.MobileNet(include_top=False,input_shape=INPUT_SHAPE)
model.trainable = False
model = tf.keras.Sequential([
model,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(
1, "sigmoid"
),
])
... | stackexchange/codereview |
I'm looking for an lib which can search an array of strings with multible search-strings (array). I want to get an int-array of all indexes/matches.
private int[] getIndexArray(String[] pArray, String[] pSearchStrings) {
int[] indexes = new int[0];
for (String str : pArray) {
if (ArrayUtils.contains(pSe... | stackexchange/codereview |
What this method should do is return a String that displays how many albums and songs there are. This method is a private method of my Artist class which has a method called albumCount() and songCount(). The whole class probably needs an improvement but I will try that later. First I'd like this single method to be imp... | stackexchange/codereview |
The program is supposed to be set as the default browser in Windows and allows me to select which browser profile I want to use when I open a link from another program. I have quite some experience in PHP, Java, C, C++, Pascal, but this is my first venture into Rust. Before I continue adding features I'd like to know h... | stackexchange/codereview |
This java answer made me wonder whether it would be possible to implement the builder pattern in C++ in a way that checks at compile-time whether all necessary members of the constructed object are actually set before the object is constructed. This is what I came up with:
struct Foo {
int x_;
int y_;
int z... | stackexchange/codereview |
I have implemented a HTML table sorting. I actually implemented a sort first using jQuery and then modified it based on the answer to this question for performance as I had done the same mistake. My question is how to make sure if the code I have written is stable or not?
I know that the stability of sorting depends on... | stackexchange/codereview |
I want to improve the performance of this code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import random
import math
random.seed(42)
class TrainModel:
def __init__(cls, scheduling_interval, trains):
cls.scheduling_interval = scheduling_interval
cls.trains = trains
class Train:
... | stackexchange/codereview |
I am currently still using a ListBox. In this, all products are displayed one below the other. For each individual product, properties are separated with tab characters. I would like to align the properties sensibly, but only look at the BrandName for now. Therefore, I get the length of the longest brand name and check... | stackexchange/codereview |
Without any specific implementation details, how would you create a bitmask type that wraps binary arithmetic into something easy to read? Ideally, this would be used with an enum, which is why there are some generic methods.
Some Questions
Is the type a struct or class?
Is the type generic or are certain methods gene... | stackexchange/codereview |
I would like to parallelise with OpenMP a one-dimensional integral using the integrate() function implemented in the Boost library. I found a rather obscure example (for my C++ skills) in the Boost web site.
I was wondering whether someone has experience with that, and may point out how I could implement this approach... | stackexchange/codereview |
I wrote the following code to read constants from annotations:
public class ContentUtils {
static {
String[] videoFormats = null;
String[] imageFormats = null;
try {
Field multipartFileField = MultipartFileWrapper.class.getField("multipartFile");
Extensions annotation... | stackexchange/codereview |
I've written a short library for manipulating matrices for 3D drawing. I've tried to strike a balance between speed and readability. Anything to improve?
%!
%mat.ps
%Matrix and Vector math routines
/ident { 1 dict begin /n exch def
[
1 1 n { % [ i
[ exch % [ [ i
1 1 n { % [ [ i j
1 ... | stackexchange/codereview |
Note this was the wrong version of the code. The updated version is here: Efficiently counting rooms from a floorplan (version 2) My apologies!
Update
Final version 3 with test harness here: Multithreaded testing for counting rooms from a floor plan solution
I was inspired by Calculating the number of rooms in a 2D ... | stackexchange/codereview |
Having been informed that sp_MSforeachdb is undocumented and unsupported, I have been working on creating a replacement stored procedure based off the work done here.
Is it ok as it is? I'm concerned about:
Using cursors
That the error raising may not iterate through stored procedures or when executed via SQL agent
La... | stackexchange/codereview |
I have already done many of the Project Euler questions in other languages before, but whenever learning a new language, I like to do the problems again in that language.
Here is my elixir version of
Find the sum of all Fibonacci numbers below 4,000,000.
stream = Stream.unfold({0,1}, fn {a, b} -> {a, {b, a + b}} en... | stackexchange/codereview |
I have a method for generating a report in Python. I want to organize the section about the date into a separate method so I can repeat the report for different dates.
What's the best way to organize this? Should I create a method using just *args or **kwargs where I can dump in all the various dicts...etc.? Does it... | stackexchange/codereview |
I am trying to create a Binary Search Tree, which has STL support (iterators etc.). This is my first attempt. Everything is unit tested using Catch2. Could you please review what I missed and what I could do better?
This is not homework, I am trying to create a repository with unit tested C++ algorithms at https://gitl... | stackexchange/codereview |
My code is currently offloading parsed data into multiple spreadsheets, but it's pretty slow: about 110k rows and 35 columns in 3.5 minutes.
I was wondering if there were a more efficient way of looping through my collection of dictionaries.
Sub getData(Parsed As Object, company As String, a, wb)
'Parsed contai... | stackexchange/codereview |
Purpose
I've never implemented a HashMap and thought it would be a good data structure exercise. I tried looking at the Java
source code as little as possible.
Discussion
I did not decide to implement the Map interface explicitly because I didn't want to support every interface method (even though a decent number of me... | stackexchange/codereview |
Background
When a user leaves a page, if they haven't submitted form data, a button is animated to draw the user's attention. (This is a poor UX choice--all the form data should be submitted--but it is what I have to work with at the moment).
Only the text, which is centered on the button, must wiggle: the button itsel... | stackexchange/codereview |
I got a long string, let's call it Story.
I fetch this story from a database so I don't know how long it is.
I want to display this story in a view, but what if the story is too long so it doesn't fit in one view?
I don't want to adjust the font size because it may be a very long story and making the font size smaller ... | stackexchange/codereview |
I just got into C++ a few days ago and decided to make a MiniMax based TicTacToe game, I don't really know much about the conventions and best uses of the C++ language so I'd really appreciate any kind of feedback.
Brief summary:
Board: has all the information pertinent to the game. Is used by the main method to paint... | stackexchange/codereview |
I am automating a login page. I am using the page object design pattern Selenium with Java. What should I improve on in my code?
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
publi... | stackexchange/codereview |
In my current BASH script project I am processing a string, which cannot have spaces.
At one point I get to where it is possible to have a series of digits. The series can be of any length, including zero, up to the abilities of the shell to handle command line arguments, and need not be a valid decimal integer. Leadin... | stackexchange/codereview |
I'm playing around with making random items and decided to implement the following structure.
#include <stdlib.h> //uints
#include <limits>
#include <random>
#include <iostream>
class RandomItem {
private:
struct _physical_properties { uint16_t length; uint16_t width; uint16_t sqew; uint16_t weight; };
struct... | stackexchange/codereview |
I am trying to create a logger wrapper around winston and express-winston (enables middleware error log) that is configurable . How could i improve this code?
//logger.ts
import * as winston from "winston";
import * as FileSystem from "fs";
import AppConfig from "../config/app/appConfig";
import CoreUtils from "../../... | stackexchange/codereview |
In the codebase I inherited, I have this function which converts a number and unit into milliseconds:
function convertToMs(duration){
const matcher = new RegExp(/-?(\d+)(ms|[smhd])/);
const matches = matcher.exec(duration);
const digit = Number(matches[1]);
const suffix = matches[2];
let milliSeconds = di... | stackexchange/codereview |
I have implemented three stacks in a single array in Java. Any advice on object oriented design, coding structure, logical part or any sort of advice would be appreciated.
public class ThreeStack {
private int[] stack;
private int first, last, mid;
private final int midPosition;
public ThreeStack(in... | stackexchange/codereview |
I need to select the <table> before the table where the link I clicked. I can't use IDs, because I don't want to edit my jQuery every time I add a new table.
but this looks kinda bloated for me:
$(this).closest("table").prevAll("table").first().css( "background", "yellow" );
take a look here: http://jsfiddle.net/syddm... | stackexchange/codereview |
I am trying to build a report based on certain condition. The problem is that I have a massive switch statement which is a "code smell".
How can refactor the following so that it is more maintainable?
I just copied/paste some of the values to show how the case will look.
switch (countryId)
{
case 1:
reportP... | stackexchange/codereview |
It's been a while since I did anything with JavaScript. I made a tile puzzle game to help me brush up. You can find it here: https://compucademy.net/tile-puzzle/
I would like some feedback on my use of JS, HTML and CSS. Anything would be helpful - structure, best practices, overall approach, suggestions for improvement... | stackexchange/codereview |
I've coded this class that lets me search through an ArrayList displayed into a RecyclerView. This is the class:
public class SearchActivity extends AppCompatActivity {
ArrayList<Accordo> chords;
RecyclerView rv;
SearchView sv;
ArrayList<Accordo> filteredList;
@Override
protected void onCreate(... | stackexchange/codereview |
I have states that have a requiredlogin object set as true, then I have Angular listen on stateChangeStart, but things end up pretty ugly.
Here is a state that requires a login. I think this actually pretty good and simple.
.state('dashboard',
url: '/dashboard',
templateUrl: 'partials/dashboard/main.jade',
data:
... | stackexchange/codereview |
I have a list in Prolog like this:
Puzzle = [ A1, A2, A3,
B1, B2, B3,
C1, C2, C3 ].
And I want every variable in the list to be a number in the range of 1 to 9.
Currently I'm doing this like so:
between(1,9, A1),
between(1,9, A2),
% ...
between(1,9, C3).
Even though this works, it's already pr... | stackexchange/codereview |
I made a simple linked list in C with the following functionalities:
Create(creates the list); Find(searches for an element in the list); Insert(inserts a value at the beginning of the list); Destroy(destroys the entire list). It only uses integers (for simplicity), and I want to know for possible errors and how to imp... | stackexchange/codereview |
I'm coding a Reversi game, with an artificial intelligence using the MinMax as the search algorithm. My concern is that (most) search algorithms needs to store a lot of instances of "states", in my case, board states. What I want is to represent a BoardState with 64 SlotState (Empty, White Disk or Black Disk), with the... | stackexchange/codereview |
Below you can find a straightforward implementation of a double linked list, similar to std::list, making use of AAA (Almost Always Auto).
The purpose of this code ain't to reinvent std::list, instead, I wanted an easy to understand code containing sufficient complexity, so you can focus on the coding style.
Any feedba... | stackexchange/codereview |
I need to transform the coordinates from spherical to Cartesian space using the Eigen C++ Library. The following code serves the purpose:
const int size = 1000;
Eigen::Array<std::pair<float, float>, Eigen::Dynamic, 1> direction(size);
for(int i=0; i<direction.size();i++)
{
direction(i).first = (... | stackexchange/codereview |
Background
On a whim, I wrote a function called summarize_pow(). It performs dplyr::summarize() on .data for every subset (ie. the power set) of its group_vars(), to yield a list of tibbles. It optionally consolidates these into a single tibble via bind_rows(), with (optional) identifying columns.
I initially wrote m... | stackexchange/codereview |
Inspired by reading "How-to write a password-safe class?", I tried some clever (or dumb-fool) hack to create a widely-useable secure string using the std::basic_string-template, which does not need to be explicitly securely erased itself.
At least gcc and clang seem not to choke on it (coliru):
#include <string>
namesp... | stackexchange/codereview |
I wanted to make a simple example of multithreading with QThread in PyQt5 / Python3. The script generates a set of QLineEdits and buttons to start and stop a set of threads. Each thread simply increments whatever integer was in the box before the start button is pressed, once per second. Signals and slots are used betw... | stackexchange/codereview |
This class is for fast and small footprint buffering made specially for network I/O. It is similar to so-called circular buffers, but is not circular.
#ifndef _IO_BUFFER_H
#define _IO_BUFFER_H
#include <cstdint>
#include <cstring>
#include <cstdio>
namespace net{
template<size_t CAPACITY>
class IOBuffer{
public:
... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.