instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have written this code that connects to a mysql database. The function should be able to be used as a context manager - via with. It is working, but I am not sure if this is a great way of doing it. conect.py import os import mysql.connector from mysql.connector import errorcode import contextlib _CFG = { 'user': ...
stackexchange/codereview
So I have a method that does a lookup in an existing List<T>, populated elsewhere by grabbing the records from a SQL table holding configuration data for each state where we do business. This method just looks up in the list by state abbreviation and then returns the value of a Boolean field in the record. public bool ...
stackexchange/codereview
This exercise comes from Automate the Boring Stuff CH 10 - second edition. The exercise is called "filling in the gaps," and the instructions are as follows: Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (...
stackexchange/codereview
I have been learning object oriented programming for quite a while. I understand many concepts about it but I quickly realized that I made a big mistake just reading theory and not doing any actual coding . There was no practise at all and when I started to write some code, I felt it was harder to think and come up wit...
stackexchange/codereview
The code below is for a slideshow that shows a slide with class active, pre-loads a slide with class next, and holds the slide with class last in the background. My biggest issue with this is there seems to be lots of duplication and probably very inefficient code here that I would like to improve upon, but do not yet ...
stackexchange/codereview
This program is for a class project and requires me to read data from a text file then display a list of totals. Here are the instructions/requirements: The fields in each record will be separated by a comma. Format: Age, Gender, Marital Status, District# For example: 18, M, S, 2 The city has 22 districts. The census ...
stackexchange/codereview
Intro In order to get familiar with and improve my Rust skills I coded Tic-Tac-Toe. I want to write good Rust code, any feedback regarding why my code isn't in a Rust style or improvements that could be made would be very helpful. Question Is there a better way to implement my "new" method for the Ttt struct? I don't p...
stackexchange/codereview
My code will, from a web-gui, generate Vash images. This currently involves making a call to a local binary, java. I'm wondering, if I've taken reasonable measures against this being exploited by a malicious user, or not. The code will be used in several different places, by several different administrators, meaning bo...
stackexchange/codereview
Our team is developing an educational website using ASP.NET webforms. We designed DAL & BAL classes and now I have some questions: Are DAL & BAL designed well? Would it be better using ORM (like EF) instead of using our own classes? (ORM is slow, but I'm not sure) Should we ignore BAL and only have DAL (2 layers in...
stackexchange/codereview
I have written the following code for the Three Cards Monte game. It works as expected and returns the required output. However when I tried to turn it in to the teacher, he keeps saying its too long. Is there any way to shorten it but make sure it returns the same output? import java.util.Scanner; public class Thre...
stackexchange/codereview
I have the following LINQ query that should return a result for each Request. I'd prefer to have the query translated to SQL by EntityFramework. private static Expression<Func<Request, RequestResultModel>> requestResultExpression = request => request.Applicant .ApplicantAddresses .OrderBy(ad...
stackexchange/codereview
I solved this problem on SPOJ: The aliens have arrived to Earth and everything is in harmony, the two races can live together. However, one specific Female Alien does not want to see humans on her way to the university, the alien must use the train as every human does. But she can choose any train station such...
stackexchange/codereview
This is my first ever program in C and I was just tinkering around with this idea, as I'm on a music based course and the synth plugins all use milliseconds as its time. Any improvements to make it more efficient or less dependant with a little explanation would be really appreciated. /* declarations */ int crotchet(i...
stackexchange/codereview
I have implemented simple BubbleSort algorithm. How can I optimize my code? Any suggestion would be helpful. public class BubleSort { private int arr[]; public static int COUNT; public BubleSort(int array[]){ this.arr = array; } public int[] getArray(){ return this.arr; } public void setArray(int[] a...
stackexchange/codereview
I have this (working) code: class CalendarDay attr_accessor :from_month, :to_month, :year def self.line_of_day_numbers(month,year,start,offset) @line='' @offset=offset finish = (start+6)-@offset self.first_line_padding(start) start-= @offset self.day_numbers(month,year,start,finish) end ...
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 have a JS file that creates an object with notes from a music scale when given a key (aka tonic/ note). The code works and does what I want it to do. I need a critique on the way it's written, what could be made better, quality of code — even if it's indentation. please. I've never written code so I have no frame of ...
stackexchange/codereview
How can I improve this code? public virtual HttpResponseMessage Get(int pageNo, int pageSize) { pageNo = pageNo > 0 ? pageNo - 1 : 0; pageSize = pageSize > 0 ? pageSize : 0; int total = repository.Table.Count(); int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0; var entit...
stackexchange/codereview
I'm brand new to Ruby. The function takes in a string of any number of words, and reverses the order of the words. Also, for each word, it takes the vowels and moves it to the end of the word. It also downcases everything. Thus, Hello World! would become wrld!o hlleo. I am trying to use some Ruby features, hence why it...
stackexchange/codereview
I'm writing an application for work that requires me to process a list of transactions. The list is small (5 records at the most) and I'm required to display that data in an android ListView. My client has asked that I include the ability to order the list based on the date (I have added ordering it by the amount spen...
stackexchange/codereview
I'm new to Python and just started to learn about scraping and pandas library. Here is a little scraper I wrote. I'd like to know what's a professional code for this would look like. I have a sense my code has a lot of redundancy but I don't know where to improve. import pandas as pd from bs4 import BeautifulSoup as bs...
stackexchange/codereview
I'm trying to filter items from an ecommerce site.The project on the local server was running smoothly.However, I noticed significant delays since the project was published on the global server.Most often happens when changes are made to the price range. Here is the Ajax code: productFilter = { catId: $...
stackexchange/codereview
On our main symfony2 application at work I have had to manipulate some outputted grid fields by wrapping them in a hyperlink tag. This happens in quite a few different controllers, so I made a method to do this to prevent code repetition. I decided to do this using DOMDocument and construct the new hyperlink with that...
stackexchange/codereview
Please advise if the form validation script below is secure enough to avoid most types (all types?) of contact form exploits? I ahve found this script online, added some extra php finctions in hope to make it safer, but not complitely sure if it is good for the purpose. if ($_SERVER["REQUEST_METHOD"] == "POST" && !empt...
stackexchange/codereview
I've just been going through core data structures and algorithms recently, wanting to get back in touch with the core fundamentals. I'm starting simple with a LinkedList implementation in C#. The functionality works and was able to test it. I'm just wondering if yo see anything with the code that could be improved. usi...
stackexchange/codereview
EDIT A port of Björn's answer to C++ with further improvements at bottom achieving up to 2.4GB/s on the reference machine. Text file parsing and processing continues to be a common task. Often it's slow, and can become a performance bottleneck if data is large or many files need to be processed. Background This is t...
stackexchange/codereview
I'm using a simple octree in my program and wanted to know if my implementation could be faster. It is part of this program. Octree.H: #ifndef OCTREE_H #define OCTREE_H #include "Rendera.H" class Octree { public: struct node_t { float value; struct node_t *child[8]; }; Octree(); virtual ~Octree(); ...
stackexchange/codereview
There is standalone WCF webservice, which is providing methods to interact with legacy ERP system. This system exposes an API, which allow programmer to interact with it. The problem is that, for legacy reasons, every call to API function has to come from the same thread. As we know, WCF webservice is multi-thread, so...
stackexchange/codereview
I'm learning Clojure and I'm doing a little thing that reads direct messages from Twitter using twitter-api wrapper. The code doing that is below. (ns twitterbot.my-twitter (:require [twitter.oauth :refer [make-oauth-creds]] [twitter.api.restful :refer [direct-messages]] [clojure.edn :as...
stackexchange/codereview
I implemented a simple CLI based rock-paper-scissors game in Rust. The player plays against the computer. Each game has three rounds, not counting draws. Cargo.toml [package] name = "rps" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html...
stackexchange/codereview
I am implementing the Dijkstra algorithm for a large graph (40k nodes, 100k arcs). For shorter paths the searchtime is under a second for larger ones (from one end to the other) it takes quite some minutes to do it. I am also drawing the path after the search, so I am using some Qt objects. How could I make it faster? ...
stackexchange/codereview
I am practicing for technical interviews and I am encountering a lot of problems relating to the tree data structure. I have gone through other posts that discuss about the tree data structure and come up with the class definition and method signatures for the some of the operations as below: class Tree { struct No...
stackexchange/codereview
Code Review is running rampant with an infection. A zombie infection. Everywhere posts are becoming rapidly mutated into slobbering, green freaks of nature. But the citizens of Code Review are not running. No; they are fighting! These CRitters are shooting the zombies left and right to keep Code Review a safe and heal...
stackexchange/codereview
I solved this problem in C++ and was looking for feedback on my code. I'm not sure if storing the data in an array and looping through it in reverse and printing was the right approach since this challenge was to use linked lists, but I didn't know how else to do it: You are given the pointer to the head node of a lin...
stackexchange/codereview
I am built a program that will give the 7 chords that are found a given major or minor key. My program takes in first a key (C, Ab, F#, etc.) then takes in its mode (Major (input is 'M') and minor (denoted by 'm')). From there the program builds the chords in that key in a specific manner depending on the mode where yo...
stackexchange/codereview
I have been writing simple php programs, trying to adhere to the PSR standards, for writing code. However they do not seem to have any standards for writing mysql PDO statements in. For example I have written the mysql statement; $sql = "INSERT INTO `users`( `name`, `phone`, `city`, `date_add...
stackexchange/codereview
I had some great feedback on my code previously here and I was hoping that I could get some further help with writing a column of the array to the worksheet. I have an example here where I write one column of my array to the worksheet with a loop, but I'm wondering if there wouldn't be a more efficient way to do this: ...
stackexchange/codereview
I have the following code for reading a json file into pandas dataframe and parsing the fields, but it is too slow for large files. Is there a way to make the code more efficient? def extract_text(json_train_path): with open(json_train_path, 'r') as json_file: train = {'example_id':[], ...
stackexchange/codereview
I have recently just started learning Perl, so I decided to program the classic 'Guess my Number' game. I was wondering if anyone can spot any areas for improvement. As it's my first program, I expect there to be some unoptimized areas. #!\usr\bin\perl print"Welcome to guess my number!\n"; $compNumber=int rand 1...
stackexchange/codereview
On my web forms page, I have this huge GridView. I make it refresh every five minutes since the data has to be up to date. It has sort options, so upon every refresh, I use cookies through every refresh to remember the search and sort options. In the Page_Load function, this is how I do it. HttpCookie cookieStat = new...
stackexchange/codereview
I'm developing a website and I cut the images that I will use: <div class="news-top"> <p>CSS contains the top image</p> </div> <div class="news-center"> <p>CSS contains the center image (repeat-y)</p> </div> <div class="news-bottom"> <p>CSS contains the bottom image</p> </div> And inside news-center class ...
stackexchange/codereview
I have this method: public void AddNLogConfigurationTypeTagret() { var filePath = _loggerModel.file_path_pattern.Replace("\\YYYY\\MM\\DD", ""); var dateTime = DateTime.Now; filePath += "\\" + dateTime.Year + "\\" + dateTime.Month.ToString() + "\\" + dateTime.Day; var filePattern = _loggerModel.file_name...
stackexchange/codereview
I've made my first-ever program in Go, which sorts a given input of integers. There are 2 options: The list of unsorted integers and the algorithm to use. Since it's my first go project I'm a bit unsure of a few things. For example, the "floating" variable declarations. I think that the algorithms itself are okay, th...
stackexchange/codereview
I have written a little Paint-Program in HTML. You can also save and load your wonderful paintings. My code works, but my heart says that my code is not so beautiful. I dont use JS/HTML/CSS very often and thats why I dont know how to write clean JS-Code, but I want to know that. Javascript seems to provide a thousand w...
stackexchange/codereview
I wrote the following script in the hopes of streamlining the finding and reading of multiple manual pages. Since I am always looking up different utilities' manual pages I thought this would a good learning aid. #!/bin/bash while true do echo echo "1) /bin" echo "2) /sbin" echo "3) /usr/bin/" echo...
stackexchange/codereview
I have the following class in Typescript (using the Aurelia SPA-framework). import { inject } from "aurelia-framework"; import {Apiclient} from "../services/apiclient"; import * as gravatarUrl from "gravatar-url"; // Dialogs import {DialogService} from "aurelia-dialog"; import {RedigerBruker} from "./dialogs/rediger-b...
stackexchange/codereview
This code is to find expiring/expired documents. It was included in one of the models, say Document. Is this good approach of using constant variables which holds the some data and used within this mixin only? Is there any better approach I could use instead the constants? require 'active_support/concern' module Expi...
stackexchange/codereview
How can I get to a perfect coding for this algorithm? I made the mathematical theorem, which is a development of the Sieve of Eratosthenes algorithm. I might use some help in coding. You can find the description of the code at my paper: Development of Sieve of Eratosthenes and Sieve of Sundaram's proof For more underst...
stackexchange/codereview
(This post is the continuation of A JavaFX program to find out the mouse refresh rate v2.) After taking @J_H's suggestions into account, I ended up here: com.github.coderodde.javafx.mouseupdaterate.MouseRefreshRateFinder.java: package com.github.coderodde.javafx.mouseupdaterate; import java.text.DecimalFormat; import ...
stackexchange/codereview
In Python 3.4, a Counter object called cnt like this: Counter({'0200': 3, '3000': 2, '3011': 2, '0210': 1, '4000': 1}) is to be written to a comma-separated file. I first tried with CSV and DictWriter that I had not used before, but I kept getting misty errors and was pressed for time, so I decided to make this ...
stackexchange/codereview
I have been learning C++ programming. What you see here is all that I know how to do at this point. I look forward to learning more and I know there are better ways to accomplish a task such as calculating, or a less verbose method for displaying information. I want to hear from more experienced developers and engineer...
stackexchange/codereview
I'm sorting a Dictionary in a lexicographical order and applying MD5 encryption. I would like to wrap the sorting somewhere inside the encryption method or so. Official Java example - here Docs private static string GenerateSign(Dictionary<string, object> query, string apiSecret) { var sb = new StringBuilder(); ...
stackexchange/codereview
The problem statement can be found here. Description (short): Input The input stream contains a set of integer numbers \$A_i\$ (\$0 \le A_i \le 10^{18}\$). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB. Output For each number \$A_i\$ from the last ...
stackexchange/codereview
I picked up Sass last week, and I'm already diving into expressions. I have a @mixin that creates a CSS border triangle using the following call: .foo:after { ... @include triangle(bottom,8px,7px,8px,#4986c8); } producing something like: Here's my @mixin: @mixin triangle($dir,$tl,$size,$br,$clr) { $a: solid transp...
stackexchange/codereview
I've seen the code for this function in John Resig's book 'Secrets of JavaScript Ninja' yesterday. I considered it useful at once because I've disliked repeatedly typing console.log for some time. Here's my implementation of a helper function to reduce typing: // -- Function definition ------------- // Helper function...
stackexchange/codereview
I have some data that needs to bind to my view depending on the user selection. Example: changing the list of states in a dropdown depending on the selected country. My understanding is, there are two ways to do this: Have a global JS variable, say, var model, which has a property, "states". This contains all the rele...
stackexchange/codereview
I've tried, as practise, to write a Python 3 script which takes a list of paths to files/directories and compresses them with tar, before encrypting the resultant tarball with gpg (for backing up to an external location). The script allows the user to choose which compression and encryption algorithms to use, and where...
stackexchange/codereview
I have a very simple PHP MVC library for my auto-didactic pedagogical purposes. I'm having a little trouble figuring out how to add in the observer patterns as show in this UML diagram from Wikipedia. model is simply contains an array and acts as a key-value store. contrlr accepts input, ostensibly from $_POST, to upda...
stackexchange/codereview
Suppose I am listening for network changes with the following listener: interface NetListener { void onNetworkAvailable(boolean isWifi); void onNetworkUnavailable(); } I want to have an object, accessible from anywhere within the app, holding the registered NetListeners, that can trigger the appropriate meth...
stackexchange/codereview
I needed a way to update a parameter in the URL, or add it if it doesn't exist, but keep any other variables the same value. I built this function to do the task, and while it works, I feel like it's taking longer than it should. Does anyone have any suggestion on what I could change or a faster method? function chan...
stackexchange/codereview
Here is a light command line I built with JavaScript. I would like to ask if there are many stupidities, bad code and such? The only test command right now is add arg1 arg2 so writing add 1 1 should get you >>> 2. It will print Command *** not found with other commands than add. See the fiddle below. jsfiddle.net http:...
stackexchange/codereview
I have written a Backbone View (javascript) for a component called "twist-panel". A twist panel is basically a card flip, it has a front and back side, and can flip to the back and to the front. Here is the code: var TwistPanel = Backbone.View.extend({ initialize: function() { this.$front = this.$el.find('.twist-...
stackexchange/codereview
I want to implement a Type system for different representations of an angle value. Motivation to implement this as a type system comes from this question. Angle can be represented using the following types: Degrees (45.5) Degrees Minutes Seconds, DMS (45*30'00") Radians (0.7941) It should support conversions...
stackexchange/codereview
Description: Given a binary tree, return all root-to-leaf paths. Leetcode /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ Code: class Solution { public List<String> binaryTreePaths(Tree...
stackexchange/codereview
function C = convolve_slow(A,B) (file name is accordingly convolve_slow.m ) This routine performs convolution between an image A and a mask B. Input: A - a grayscale image (values in [0,255]) B - a grayscale image (values in [0,255]) serves as a mask in the convolution. Output: C - a...
stackexchange/codereview
I've got the following code to find the shortest path between two nodes using almost-Dijkstra's-algorithm which was written for an exercise, and I'm looking for things to improve my general Scala style. What I currently have: object Graphs { case class Node[T](value : T) case class Edge[T](from : Node[T], to ...
stackexchange/codereview
This is a follow on to : Simplifying asynchronous "executeAsync" method along with "onFailure" callback. I am using AsyncRestTemplate as my HttpClient to execute my URL and the server will return back a json string as the response. Customer will call this library by passing DataKey object which has userId in it. Given...
stackexchange/codereview
Requirement I have an entity named ImportData which can be processed once in order to extract data from a file fed to the application. I need to make sure that, in case of concurrency, only one process is capable of processing that import data. Other processes shall not attempt to read the file and insert data into dat...
stackexchange/codereview
I have a simple list and want to filter it by a specific key. But I guess my for loop solution is not an efficient way. I'm searching an other way or one best practice. types = [ { 'name':'John', 'surname':'Doe', 'age':36, 'type':'customer' }, { 'name':'Jane', ...
stackexchange/codereview
This plugin is for article pages that has a very long main content (left side) and a shorter sidebar. When the user scrolls down mostly the right part will be white space. What this plugin does is make the sidebar stick or make it fixed past a point and will stop sticking when it collides with the bottom part or a foot...
stackexchange/codereview
I have this huge __init__ method which I want to clean up even more after watching Clean Coders videos (content of Clean Code book by Robert Cecil Martin). How could I get refactor the gigantic if..elif block in a nice, readable way? Or should I leave it as it is? Do you find it readable? @total_ordering class Range: ...
stackexchange/codereview
I'm coding an algorithm to remove a parameter (let's call it foo) from URL strings. Of course, after the foo parameter removal, the query string should remain valid (with a leading ? and remaining parameters separated by &). I'd also like to remove the leading ? if foo was the only parameter. Details: Domain and pathn...
stackexchange/codereview
I have a situation where I needed to convert NSNumber 2D array to Float 2D array, so I did it like this: var numArr:[[NSNumber]]() //fill values let floatArr = numArr.map { $0.map { $0.floatValue} } It's working fine, no issues! But I wondering if there's any better way to handle this?
stackexchange/codereview
Write a function that takes an amount of money M, a price P and returns the change given in the smallest number of coins. The following coins are available: 1c, 5c, 10c, 25c, 50c, and $1. Time: 20min. I'm looking for all sorts of reviews considering the time limit and environment. Here's my code: #include <iostream> #i...
stackexchange/codereview
In my rails controllers, I am consistently using this logic: def report dump = params[:dump] ? params[:dump] : 'false' data = {} if dump != 'false' return render :json => p(data) end end Is there a better way to write this? A ternary operation is just an eyesore. I thought maybe just using the || oper...
stackexchange/codereview
Long story short a user can have things in common with another user, but I don't what to show more than 4 main categories in common, only the first 4, the priority is the order in which the lists are added. Below is my current approach, but I feel that this can be simplified, and maybe improve the time. Any thoughts? v...
stackexchange/codereview
Currently, I'm trying to learn every aspect of the MVVM design pattern. So basically I've written a little WPF App where I'm trying to understand Navigation in MVVM, the app has one MainView wich controls with a ContentControl the other Views. Even tho I've read so many things about MVVM I'm never comfortable with my ...
stackexchange/codereview
I have a use-case where I want to iterate from the middle of an array outwards, so I generate a list of indices as follows: import itertools def array_indices_from_middle(array_len: int, num_indices: int = 16) -> list[int]: """ Create indices for an array starting from the middle and then appending indices al...
stackexchange/codereview
I am seeking a review of my command line wordle game. Having only recently started exploring functional programming, I expect that there will be no shortage of areas to improve. This is my first simple project outside of reading textbooks and solving exercism puzzles. I am keen to discuss all improvements, however some...
stackexchange/codereview
This is again a solution to the codeEval challenge #1. It was accepted by codeEval, but please let me know if I can improve it anyway somehow? #include<iostream> #include<vector> #include<fstream> #include<string> #include<chrono> struct input_rec{ int first; int second; int last; }; void parseRecord( std...
stackexchange/codereview
I'm trying to learn OOP with PHP (I know it's hard because It's not an OOP language). I'm rewriting my procedural code to OOP.Please provide any feedback on my code, naming and file/folder structure. Structure: \classes Procurement.php ProcurementDetails.php \services DatabaseService.php ProcurementService.php ...
stackexchange/codereview
I recently joined the website www.hackerrank.com for programming challenges, and one of them was a time conversion from 12 hour to 24 hour. Rather than using the Date class, I decided to write the code for it, and in the end I came up with this: String time = new Scanner(System.in).nextLine(); String suffix = time.subs...
stackexchange/codereview
Hello everyone. I wrote my own test module, which is responsible for measuring the timing of algorithms, I used it mainly for sorting algorithms this is so to say a very early beta version, which I would like to expand with various functionalities, in general I would like to take care of the appearance of the code. I l...
stackexchange/codereview
Can someone review my code and provide feedback. For context in column A will be a status message of "OK" or "NOK" and this little function just counts the number of times this appear so I can update a label in another procedure. Not too sure if this is the most efficient way of doing this because looping will create d...
stackexchange/codereview
I am doing a validation and I believe that there are many things that can be reduced or removed. I am still re-working this. But I am looking for some experts to look at my code and offer the very best approach for both individual and form submit error handling. (function(){ var calledIt = function (event, params...
stackexchange/codereview
Intro I've decided to learn haskell, because I've always enjoyed the functional aspect of Python and want to explore other languages that use this concept. I'm still stumbling in the dark most of the time, so would greatly appreciate any improvements. Description Challenge source A road system is considered efficient i...
stackexchange/codereview
I've made a little mechanism for creating 2-D vectors in Lua. Vectors have two components i and j, and support addition, dot product, magnitude, and conversion to strings. Vector = { new = function (i, j) return setmetatable({i = i, j = j}, { __index = Vector, __add = function (self, v) return...
stackexchange/codereview
Again, out of fun on Saturday night, I decided to solve the following problem from CodeEval. The challenge is finding the index of the lowest unique number. There is a game where each player picks a number from 1 to 9, writes it on a paper and gives to a guide. A player wins if his number is the lowest unique. We ...
stackexchange/codereview
Requirements Display movie datas inside all tags that have the class movie_list Make an ajax call for fetching movie datas Fill loading text before fetch data If any error occurs during loading, the content should be empty What I did Cached all elements which have the class movie_list Made functions which have only...
stackexchange/codereview
Problem Statement You are given a string, S , consisting of lowercase English letters. A string is beautiful with respect S to if it can be derived from S by removing exactly 2 characters. Find and print the number of different strings that are beautiful with respect to S. Input Format A single string of lowercase En...
stackexchange/codereview
As part of the task, it is allowed to use slightly outdated data. It is required that only one thread per key is involved in the critical section, while the remaining threads use data from the cache despite the expired TTL. The following code is an attempt to write a function calling the delegate within a blocking sect...
stackexchange/codereview
Was asked this today in an interview. Didn't see it before, and spent quite a lot of time getting it to work (tricky with all the recursion). The goal was to find all possible combinations of choosing k elements from a n-sized array (basically the Binomial coefficient) and return them. Unlike this code - here I don't ...
stackexchange/codereview
I'm somewhat curious on peoples opinion about such a method. I Actually didn't find anything similar in librarys I use on regular bases so far. This is my implementation: Object.map = function _map( obj, transform ) { if( typeof obj === 'object' && typeof transform === 'function' ) { Object.keys( obj ).forE...
stackexchange/codereview
I'm taking a sentence and determining whether or not it is a palindrome. I'm doing this while learning about stacks. Is there a way I can use pointers instead of char array 'sent' so that the number of input characters need not be constrained to 20 in the following code? The code is working fine, but should there be a...
stackexchange/codereview
The exercise I wanted to solve is from here. Copying from that page: public static int dayOfYear(int month, int dayOfMonth, int year) { if (month == 2) { dayOfMonth += 31; } else if (month == 3) { dayOfMonth += 59; } else if (month == 4) { dayOfMonth += 90; } else if (month == 5...
stackexchange/codereview
In order to learn Rust I'm going through The Rust Book and did the implemented a program for the following exercise: Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song. I have decided to use lookup tables for the repeating lines of the song and ordin...
stackexchange/codereview
This is my submission for the Prime Generator on SPOJ and it was accepted. Are there any improvements/changes I can make? Input: The input begins with the number \$t\$ of test cases in a single line (\$t \le 10\$). In each of the next t lines there are two numbers \$m\$ and \$n\$ (\$1 \le m \le n \le 1000000000\$,...
stackexchange/codereview
Use Case Creating a generic and reusable predicate with closures that supports Float, Double, Integer, float, double, and integer. Problem Extending "Number" doesn't allow for the modulo operator. Code Below is the form I'd like the code to be. However, Number doesn't support the modulo function. public <T extends Num...
stackexchange/codereview
I'm writing a Telnet parser in Haskell that can run within any monad that implements some event-handling functions. When it finishes processing a block of input - whether because it read it all or because it was interrupted by an event handler - it returns the remainder of the text and a continuation for more input. Ri...
stackexchange/codereview
Challenge This is a solution of Project Euler 72 in Java. How may proper reduced fractions \$\dfrac{n}{d}\$ are there, where \$n < d \le 10^6\$? Code public long solve() { int limit = 1000000; int[] phi = IntStream.range(0, limit + 1).toArray(); long result = 0; for (int i = 2; i <= limit; i++) { if (ph...
stackexchange/codereview