instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I currently use setInterval and a wait flag to process this collection. Is there a cleaner way? var wait = false; var processInterval = setInterval(function(){ if(!wait){ var currentVideo = videos.shift(); if(currentVideo){ wait = true; validateSongById(currentVideo.videoId...
stackexchange/codereview
Here is a search implementation for my tree. It searches each node in a breadth-first manner first, but it goes deeper in a depth-first manner, in the event it needs to go deeper. I know there may be multiple identical items in the tree (well, not my current use of it, but I still need to presume that), so it just re...
stackexchange/codereview
I was just wondering, is there a way to load these better and log the times they each took? It seems like a headache having to write about 90+ stopwatches, which is what I will have to do as I have about 100 of these to load. // PacketManager var packetManagerStopwatch = Stopwatch.StartNew(); _packetManager = new Packe...
stackexchange/codereview
This code is about finding Pythagorean triplets. I take a number as input, and find from 1 to that number, how many Pythagorean triplets exist. Are there ways this can be optimized? It takes a lot of time, but actually doesn't only provide the output for no > 10000 import java.util.*; import java.io.*; public class S...
stackexchange/codereview
I'm written the following code to calculate the position of a motor during each timestep, the result of which will be compared with feedback from a quadrature encoder and subjected to a PID algorithm. The trajectory will follow a trapezoidal profile. i.e. Accelerate to a maximum velocity, coast and then decelerate to t...
stackexchange/codereview
I wrote simple compiler for Brainfuck with tcc backend (dont ask for assembler/assembly code generator!). It's output runs incredibly slow. Even Hello World program takes a LOOONG while to execute. I have added some optimizations, but it didnt help. This is code i actually made; It actually doesn't hang, but output wor...
stackexchange/codereview
I had a task to realize ReadWriteMap public class ReadWriteMap implements Map { private HashMap map = new HashMap(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private Lock readLock = readWriteLock.readLock(); private Lock writeLock = readWriteLock.writeLock(); @Override ...
stackexchange/codereview
Problem Statement: Write a program that will convert a binary number, represented as a string (e.g. '101010'), to its decimal equivalent using first principles Implement binary to decimal conversion. Given a binary input string, your program should produce a decimal output. The program should handle invalid in...
stackexchange/codereview
I applied for a job as a C#/.NET Junior Developer, and had a test to do:: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this valu...
stackexchange/codereview
I need to match values in Needle & Haystack arrays, using alternate Ontology values when relevant. This syntax works, however I would like to know if there is a more efficient way to do this as I will be using it for several corresponding $AltNeedle arrays for each of 1000+ $needles and $haystack arrays. In my use cas...
stackexchange/codereview
I'm still new to C++ and I am very open to any kind of suggestion on how write proper and understandable C++ code. I decided to create a class for the code to have everything closely tided together. Don't know if that was a good idea. About signature scanners (aka. pattern matchers), see see wiki. Signature scanners ar...
stackexchange/codereview
So I am very new to programming and I am trying to pick up Python as a first language. I have programmed a simple game of naughts and crosses, but it is very wordy and there must be a simpler/quicker way of doing this! Any modifications or tips would be gratefully received. from random import randint #initialise game...
stackexchange/codereview
Below is the python code to compress js and css files. import sys import os import glob import shutil import fnmatch import os.path import re import argparse import time #Store the time the script starts start_time = time.time() total_files_compressed = 0 total_js_files_compressed = 0 total_css_files_compressed = 0 j...
stackexchange/codereview
Problem statement Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) ...
stackexchange/codereview
I reworked the Game I did in FLTK some while ago: Hunt the Wumpus GUI (FLTK) This time I used C++ with the Qt Framework. The result looks like this: If you want to try out the game. The full code can be found in my Git Hub: https://github.com/sandro4912/hunt-the-wumpus One more hint not find in the Instructions. If t...
stackexchange/codereview
I am programming a language interpreter in C# and have recently created a set of functions that receive either a string or a string[] and split it by a received string. For example, with a string: "Hey:123:hello:456" ":" It will return this array: {"hey","123","hello","456"} And with a string[]: {"a:b","c","d:e:f"} "...
stackexchange/codereview
Is there anything I need to add or is this the best security possible? <?php //Get Sessions Prepared; session_start(); //If logged in, Logout; if(!empty($_SESSION['username'])) { //Remove Sessions to Logout the user; $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, ...
stackexchange/codereview
I wrote this code in python and it works fine for me but I do know that the code is not optimised and a lot of refactoring needs to be done. So I need review on how this code can be improved. I started writing this when WGET library was not working for me and I wanted a light weight script for my other projects. I am a...
stackexchange/codereview
i'm trying to create a url router system, for educational purposes, that has a similar usage like Laravel has, but i'm curious about how i can register the routes like laravel does (with single calls to static methods), here's my "conceptual" code that i made using a TDD approach: $Route = new Route; $R...
stackexchange/codereview
This is the entire code segment. All the functions for file operations are working perfectly. I just need a professional to help me clarify that am following good standards, documentation, etc., because I am going to start doing professional work very soon and I need my code to be at a professional level. import os c...
stackexchange/codereview
How can I improve this code ? It was quite hard to implement AJAX comment system in Symfony 3, and result is a bit of mess: Controller: <?php declare(strict_types = 1); namespace AppBundle\Controller; use AppBundle\Entity\Article; use AppBundle\Entity\ArticleCategory; use AppBundle\Entity\Comment; use AppBundle\Entity...
stackexchange/codereview
I have made a Python program that can perform some prime number functions. For example, it can produce an endless output of sequential primes. I am looking for ways to make it faster and cleaner. When I was making it, I had a huge amount of trouble using generators, I don't know why, and what the problems were, because...
stackexchange/codereview
I have several enums that all implement this interface: public interface SelectOption { String getId(); String getLabel(); } Here's an example: public enum AuthType implements SelectOption { BASIC("basic", "Basic Auth"), OAUTH("oauth", "OAuth"), TOKEN("token", "Bearer Token"); private final St...
stackexchange/codereview
The requirements: Work inside .htaccess (preferably via mod_rewrite) Redirect requests from /any/directory/index.php to /any/directory/ Make sure that /index.php-with-stupid-stuff-here does not get rewritten Add trailing slash to directories, /another/directory becomes /another/directory/ Also note that: The ideal s...
stackexchange/codereview
Given an array of integers, sort the array into a wave like array and return it, In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... Example Given [1, 2, 3, 4] One possible answer: [2, 1, 4, 3] Another possible answer : [4, 1, 3, 2] NOTE: If there are multiple answers p...
stackexchange/codereview
Introduction The following data structure is a dictionary mapping primitive int values to any value type. Basically, under the hood it is a hash table, where a translated key is mapped to an index into that hash table containing a value. We, however, use a van Emde Boas tree algorithm to bring the integer keys into ord...
stackexchange/codereview
I am tasked with creating a list with no duplicates of all String elements, in this case first names, of an ArrayList. The method is passed a threshold, and the method must store the first name if it has occurred at least the amount of the threshold. The restriction is that I am only allowed to use the List ADT. I have...
stackexchange/codereview
I've just finished writing my code to return the prime factors of a number and I feel the GetBestFactors function could be improved. The GetFactors function was hacked together from the code found here:https://support.microsoft.com/en-us/kb/202782. This returns all the factors of a number in a collection. The GetBestF...
stackexchange/codereview
PROBLEM STATEMENT I have a code to treat agronomic data. I have a data.frame called yieldwith different information (dry.weight / infected pod / healthy pod). These data are collected in the field every month. I would like to have the total yield per year and per tree (plotnb). Another important thing I'm seeking is...
stackexchange/codereview
I would like to get some feedback on my completed code that finds and displays the articulation vertices in an undirected graph. I included a test case within the code, it should (and does) print c as the only articulation vertex. Also I would like to clarify my understanding on some things, This runs in \$\mathcal{O}...
stackexchange/codereview
Something I haven't often seen in FizzBuzz implementation is a focus on making it flexible and maintainable. I have attempted to create a version that prioritizes these, such as by making it easier to change the conditions and add more conditions. What else could I do to work towards these criteria? public class V3_ifF...
stackexchange/codereview
Would like feedback on my SQL (1) efficiency and (2) readability, and if the conditions I featured in my CASE statement could be transferred to a join, etc. Here's the problem I'm solving: Say you have a table bst with a column of nodes and column or corresponding parent nodes: node Parent 1 2 2 5 3 ...
stackexchange/codereview
Hello I made a sieve of Eratosthenes algorithm on x86 assembly using NASM. The highest number it can take is about 2 million and it takes like 2 seconds to complete. Here's the code: section .bss buffer resb 100 numbers resb 0 section .data arrayLength db 0 section .text global _start _start: ...
stackexchange/codereview
I am beginner to intermediate and wanted to write a little event code in c. It's one header file with 108 line pure code and it does what I was thinking it should be like for me. EventListener.h #ifndef EVENTLISTENER2_H #define EVENTLISTENER2_H #include <stdio.h> #include <stdlib.h> #include <pthread.h> struct Event...
stackexchange/codereview
This is a Rspec test for pagination in Rails project. I'm not sure if I should write the test in spec/requests or spec/controllers. And there must be a lot of thing that I had better to do. Which part of code should I refactor? spec/requests/companies_spec.r describe "Companies" do describe "GET /companies" do be...
stackexchange/codereview
I am a newly developer in angular. I want to do some homework to create forms with Angular. I spent nearly a week to do it, but my teacher was not really satisfied about it. I tried to follow some web tutorials and I thought that it was good but apparently, the quality of my code is very bad (according to the teacher)....
stackexchange/codereview
I created small module to help me create rich sendgrid html emails using the mako templating engine. Any feedback on the design would be appreciated: makosg.py from sendgrid.message import Message from mako.template import Template from mako.lookup import TemplateLookup class MakoMessage(Message): def __init__(s...
stackexchange/codereview
I am designing a very basic file listing layout in HTML and CSS. Although its working but I would like to know if the following code could be improved upon so that its more good and follows the best practices. I am looking forward of supporting I.E 9+ too. Plus I would like to add a progress bar behind the left-wing. I...
stackexchange/codereview
This question is a follow-up to this previous question of mine. Assuming I understood correctly what is outlined in this meta post. I wrote (and now, re-wrote) a function that takes as input a vector with two integers between 1 and 8 representing a position in a chessboard. This function should output a vector where ea...
stackexchange/codereview
I built a banking system in C++ (still a lot of features to do but (I decided to post it here to see what can I change so I wont make those mistakes in the future). User header and c++ files Header #pragma once #include <string> class User { private: int id; std::string username; std::string password; ...
stackexchange/codereview
I want to check if I'm correctly disposing of resources using Ado.NET. I'm not sure when the 'using' statement makes .Dispose() irrelevant. Please bear in mind I'm aware I shouldn't hardcode my SQL commands, this is just for training purposes. internal void CreateTable(string connectionString) { u...
stackexchange/codereview
This is my second take on creating a tcp client C++ class. The class declaration is general but the implementation is Windows only at this stage and uses the Microsoft Winsock WSAEventSelect model. The first attempt is here: TCP client library using Winsock WSAEventSelect in C++ for some background. The changes are mos...
stackexchange/codereview
Nodes will be for simply linked lists, circular lists, maybe later on extending them to work with graphs. I'm trying to be as defensive as possible, will this leak memory? It runs perfectly I'm just concerned about coding style and best practices. Especially regarding the allocation I'm not 100% convinced of my solutio...
stackexchange/codereview
Background I've wrote a trivial wrapper function summarising variable by group for dplyr. I would like to handle quosures more efficiently. In particular, I've a hunch that rlang::UQE(var) could be written more efficiently. Code #' @title Create a simple sum by grouping variables #' #' @description #' \code{sum_by_gro...
stackexchange/codereview
There were multiple times in different applications that I needed to accomplish the following behavior with C# Task and I did it in a certain way, and would like to receive an insight whether it's the best way to achieve the desired effect, or there are other better ways. The issue is that in certain circumstances I wo...
stackexchange/codereview
Have you ever written a python script, then got to a part where you have to get input from the user? I would assume your code went something like this: user_input = int(input("Enter number: ")) Then you realized that if the player enters "keyboard spam", then your program crashes. So you need to set up a while-loop ex...
stackexchange/codereview
I see that my code smells. The first file is a controller, and createAction. But I don't know where to delegate this. BookController.php - Whole controller class So this is most 'smelly' code to me: public function createAction(Request $request) { $user = $this->get('security.context')->getToken()->getUser(); ...
stackexchange/codereview
I have 3 tables on my database: BusinessObject and CustomEvent, and EventType. BusinessObject having a lot of columns, CustomEvent having the following: Id EventTypeId DateEvent CommentEvent UserId BusinessObjectId I want to get all the BusinessObject having two CustomEvent with EventTypeId in (10, 11) such has the di...
stackexchange/codereview
This currently starts out with the speed of 2000 pages/min but shortly after starting it becomes very slow with a speed of about 200 pages/min. Why is this happening? How can I improve this scraper? import scrapy from scrapy.crawler import CrawlerProcess from time import time def isAscii(s): return all(ord(c) < 12...
stackexchange/codereview
I'm working on a C++ library for Arduino and other embedded systems. I'm currently working on wrapping up function pointers and member-function pointers into two C++ template classes (function and mem_fn). Does the following code abide by good programming practices? Does it provide enough functionality? Since there se...
stackexchange/codereview
The task is taken from leetcode Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container ...
stackexchange/codereview
This code achieves the effect, but is it a resource friendly way of doing it? Just to clarify: target div.fixMe and fix it to the top of the window when the user scrolls past its natural position. (I do realise there are plugins to achieve this result, but I wanted to build it myself) Is this the best way to achieve th...
stackexchange/codereview
For a project of mine, which is targeting java 6, I had been in the need to have different algorithms/methods to change a BufferdImage with a ColorSpace.TYPE_RGB to a plain ole black and white one. To test these implementations I therefore created an interface public interface BlackAndWhiteConverter { BufferedIm...
stackexchange/codereview
This code: Copies a value from "Sheet1" Pastes special (as a number) in another sheet "Sheet2" Jumps to the next line I already: Disabled screen refresh Wrapped the code with Application.EnableEvents = False and Application.Calculation = xlCalculationManual 1 made the calculation a little faster, but 2 didn't seem ...
stackexchange/codereview
I'm creating a small app and decided to write my own DAO for learning, etc. At the moment it's in one big file, which I really don't like. Could you give me some tips on how: you would separate this into smaller classes and use abstraction, inheritance etc? how I can update the CRUD functions (they feel pretty "frumpy...
stackexchange/codereview
BitPat here is a wrapper around a bitset. class BitPat { private: boost::dynamic_bitset<> data; public: bool BitPat::operator[](size_t coord) const { if(coord < length) return data[coord]; else throw std::out_of_range(std::string("Pattern coord out of range") ...
stackexchange/codereview
I've made a strange method with multiples conditionals, creating a lot of Lists and I was wondering if I could write it in a better and more legible way. def findRooms(room:Room) = { ... if(room.id != null && !room.id.isEmpty) query+=("_id" -> room.id) if(room.members != null && room.members.length > ...
stackexchange/codereview
Foreword As a personal project, I've been creating a SPA blog (available here), which features 4 tabs (Thoughts, Projects, Readings, and CV), each accessible via one of four radio buttons, and several entries per tab. When one of the tabs is selected, an associated fragment is appended to URL, and one can enter that UR...
stackexchange/codereview
using System; using System.Collections.Generic; using System.Linq; namespace project { class Program { public static void Main(string[] args) { BinarySearchTree<int> bst = new BinarySearchTree<int>(); bst.Insert(1); bst.Insert(3); bst.Insert(5); ...
stackexchange/codereview
I have the following code for taking a date in the form of a string yyyy-MM-dd HH:mm:ss (UTC timezone) and turning it into EEEE d(st, nd, rd, th) MMMM yyyy HH:mm (devices default timezone). However, my problem with the way I have done it is the code looks messy and inefficient. Is there a way to achieve what I want wit...
stackexchange/codereview
This is a matrix class with addition and multiplication. I tried incorporating all the helpful advice I got on my previous attempt C++ matrix class , specifically using std::vector for memory management, overloading operators, adding error messages and adhering to the rule of 5. #include <iostream> #include <vector> t...
stackexchange/codereview
I created the following one off script and it did the task quite well (1000s of requests / second with low CPU usage - outperformed the previous python script in every aspect). But I am wondering if there are more "gophonic" ways to accomplish this in Golang? (the word for pythonic in Go? :p ) The code was gofmt'd and...
stackexchange/codereview
I tried to solve the SPOJ prime number problem below. The code produced correct results, but Time limit exceeded and also memory need around 970M which is not efficient(?) How can I optimize this code under a time constraint of around few seconds? Problem Peter wants to generate some prime numbers for his cryptosystem...
stackexchange/codereview
I have the following method, which can be written in the following two ways: which one would you prefer, and why? # version with case...when def choose(value) case value when value < LOWER_LIMIT 'a' when value > UPPER_LIMIT 'b' else 'c' end # version with Hash#fetch def choose(value) { (value < L...
stackexchange/codereview
Inspired by a PPCG answer, I wrote this code, which shuffles the autoboxing caches of Number subclasses. This leads to, among other things, outputting 2 + 2 = -72 after invocation of EvilStuff.doEvilStuff(Class<? extends Number>,String,int). (The result differs for different invocations, due to reshuffling). I use a s...
stackexchange/codereview
After learning a bit React in the last weeks I've decided to make a toDo-list. I've got the basic-functionalities (create, update, delete entries) finished. I'm going to enhance the app with a feature for to define priorities. Moreover should it be possible to change the order of entries. For the final-syling I'm goin...
stackexchange/codereview
Here below is an implementation of the Ukkoken's algorithm in C++. Please review for correctness, robustness and performance. #include "suffix_tree.h" #include <cassert> #include <iostream> using namespace std; class node { public: node(); ~node(); int m_begin; int m_end; node* m_parent; node* ...
stackexchange/codereview
I wrote a calculation that finds coordinates on an edge of a square, but it came out as a really long nested tangle of conditions. After some reduction and finding common pieces I arrived at this example: // targetX, targetY, sourceX, sourceY are provided as parameters // and are markers for the centers of the two ...
stackexchange/codereview
I was hoping people could help me review the following page that I've been working on. The page has a simple form that looks at a list of colours and draw a few divs with those colours as backgrounds (so I could see what the colours look like). I'm hoping to build a few complex interactions on this page, but I feel thi...
stackexchange/codereview
I feel like using this many partial views where a view renders a partial that renders a partial is just digging a hole of poor design, so I'm looking for any suggestions or guidance as to if this is best/worst practice. One of the reasons I don't like it is because it seems too easy to duplicate code across the differ...
stackexchange/codereview
This is the first time I've actually made my own jQuery script from scratch, because I couldn't find exactly what I was looking for. My code works how I want it to, although I don't know if I did it correctly. Just something about it is screaming to me, and although it works, I didn't do it properly. So I figured I ...
stackexchange/codereview
There are plenty of ifs and elses, and someone else told me that using switch/case statements could really clean up the code. However, he didn't implement it for me, so I don't know what I should switch/case. Also take note that the if (!stricmp(argv[arg], "-vmf")) and if (!stricmp(argv[arg], "-bsp")) blocks are exactl...
stackexchange/codereview
I am working on a webapp using OpenLayers. I have written a filter function that I can use to tell whether a given layer is visible. Since there are a bunch of conditions for a layer to be visible, I condensed them all into a single switch (true) block, and I was wondering if it was a good thing, since: switch (boolea...
stackexchange/codereview
The task is taken from LeetCode Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. Example 1: Input: [[0,30],[5,10],[15,20]] Output: false Example 2: Input: [[7,10],[2,4]] Output: true My imperative solution:...
stackexchange/codereview
I have still another version of my validation extensions. I've reworked it and added some new features. It doesn't relay on expression trees any more but as a compensation the same extensions can be used for unit testing. The base class is still the ValidationContext: public class ValidationContext<TArg> { private...
stackexchange/codereview
I followed the tutorial Build a PHP MVC Application and have implemented a database connection. I made a seperate database connection class and I call it in the controller. It works, but now I have to inject it whenever I call a method from the user model. Is this considered good (dependency injection) or bad (repeatin...
stackexchange/codereview
I'm growing a web server in Haskell that interfaces with TCP sockets using network. To read the HTTP header of the client's message, I use the following function: import Network.Socket hiding ( recv ) import Network.Socket.ByteString ( recv ) import qualified Data.ByteString ...
stackexchange/codereview
Introduction This program is about rotating a matrix. For example, let the matrix be abcde fghij klmno pqrst Now, after rotating two steps clockwise we will obtain kfabc pmlgd qnihe rstoj The way I dealt with rotations is the following: I maintain \$\min(\lfloor m / 2 \rfloor, \lfloor n / 2 \rfloor)\$ "rotation lists...
stackexchange/codereview
I made a Json save system for my Unity game. I wanted to make something as generic as possible to keep the code DRY. I couldn't find much information online on how to make something generic. Could you guys let me know what do you think of it? So first, I have this utils class to save and load json data. public class Js...
stackexchange/codereview
I'm creating cards for a game of SET. Can the following be rewritten in a more programmatic way, possibly getting rid of the embedded for loops? function createCards() { var cards = []; var i, j, k, l; for(i = 0; i < 3; i += 1) for(j = 0; j < 3; j += 1) for(k = 0; k < 3; k += 1) ...
stackexchange/codereview
I want to implement the following function: Given a target sum, return the combination that equals the target sum and is the most efficiënt combination in the array of an ArrayList. For example: An ArrayList with the values 9,3,4,6,4,2,1 Then it will return the best possible combination. You can add 9 + 1, which ret...
stackexchange/codereview
This is my first project in C and I wanted a more experienced person's insight on how I made the whole program. Just looking for feedback it works how I want it to. The Github is here. Thank you so much for the feedback! #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <regex.h> #include <string.h> ...
stackexchange/codereview
I have a piece of code which works but I am looking for an optimal solution, if one exists. I have a column value and the value can only range from 2 to 10 including 2 and 10. The base value inside a switch is 18. Whenever the column value increases by 1, I need to decrease the value inside the switch by 0.5. This is w...
stackexchange/codereview
I am learning to be a full stack developer and have been building out an application using Node JS as a backend. Since I have lots of experience using Angular I love RxJS. So naturally I was tempted to use RxJS for some types of tasks. Are there any down sides to using RxJS on the backend, more specifically are there a...
stackexchange/codereview
I am an experienced Python developer learning C. I solved this assignement: Write a program that reads a word and some sentences from stdin. The word is separated by space from a sentences. The sentences are separated by one of the following characters: .!?. Words in sentences are separated by any char for which one o...
stackexchange/codereview
Within my app i have a UIButton (avatar button which shows a profileVC) within a UICollectionView this button shows up in about 4-5 other views. I'm currently adding the target within cellForItemAtIndexPath in each view controller and pushing the view from a public function pushNewViews. I was wondering if they was a b...
stackexchange/codereview
I have javascript file which is ugly but I have not idea how to make it better. There are many function for redirecting with different number of parameters. Just few functions are used for other thinks. All this functions will be called from Jquery event. Like this: $("#btnSomeButtonID").click(function () { SelectPTO()...
stackexchange/codereview
I have been using Python to learn programming, but I am just recently beginning to utilize classes. I have a basic game below. Please review and let me know what I should improve on. import random class Game: def __init__(self): self.winningNumber = random.randint(0,100) self.humanGuess()...
stackexchange/codereview
I need to find correct index in a array by comparing ranges. Here is my first try: int TunerDriver::TunerLookUpTable(double Freq) { Freq /= 1e6; if (Freq >= 60 and Freq < 140) return 1; else if (Freq >= 180 and Freq < 280) return 2; else if (Freq >= 280 and Freq < 460) return 3; else if (Freq >= 1...
stackexchange/codereview
I am studying computer science and decided to implement a linked list from scratch for extra practice. To do so, I created a Node class which simply holds an integer, and wrapped the Nodes in a LinkedList class which adds, removes, and returns Nodes. I am wondering how I did, what I can add, and what I can do better. p...
stackexchange/codereview
I have a set of strings that all consist of one or two letters followed by one or two digits. I need to sort by the letters then by the numeric value of the digits. My solution is quite inefficient in terms of performance; how is it possible to improve it? import re unsorted_list = ['A1', 'A11', 'A12', 'A2', 'A3', 'B...
stackexchange/codereview
This is an implementation of the Damerau-Levenshtein distance in Kotlin which I created as an exercise, but might be also useful, if it proves to be correct. The implementation is based on this Wikipedia article, even though it does not 100% follow the suggested pseudo-code. fun damerauLevenshteinCount(a: CharSequence,...
stackexchange/codereview
I'm imagining go generate would be a good tool for this. I want to convert strings to ints to save space. type Source int func NewSource(s string) Source { switch s { case "Twitter": return Twitter case "Facebook": return Facebook case "Gplus": return Gplus case "Spotify": ...
stackexchange/codereview
I'm taking my first steps in the Scala world, though I'm not wholly unfamiliar with functional style. Apparently one way of calculating Pi is to sum the terms of the infinite series: $$4 * (\frac{1}{1} - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} \dots)$$ So I wrote this simple implementation in a Scala work...
stackexchange/codereview
Problem Statement I'm reading each line from a .csv file and parsing each comma-delimited value and casting it to the appropriate type: string[] words = filelines[i].Split(delimiter); // "i" is the 0-based line number // Remove double quotes encasing the timestamp DateTime tmStamp = Convert.ToDateTime(words[0].Trim('...
stackexchange/codereview
I'm trying to extend bootstrap 3 modal window with ability to disable closing it. I've built this code: (function ($, window, document, undefined) { var oldHide = $.fn.modal.Constructor.prototype.hide; $.fn.modal.Constructor.prototype.hide = function (_relatedTarget) { if (this.isLocked) return; ...
stackexchange/codereview
I am using this merge sort function to sort table rows by Date, Letter, and Number. It works, but it is super messy and hard for others to read. The dates are being sorted in two formats YYYY-MM-DD and MM/DD/YYYY which is why there are if statements regulating each format. And the reason I am differentiating between le...
stackexchange/codereview
I have the below regex to match email address with atleast one @ and one . [-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4} Am wondering can it be simplified further to match email address with atleast one @ and one .?
stackexchange/codereview
Can someone look over this? This is the entire authentication file. It's referenced at the beginning of all my catalog editing files to make sure only the specified user is logged in. I want to make sure it's secure. <?php // pageauth.php // Asks for a username and a password and checks it. if($_SESSION['...
stackexchange/codereview
I've following code that insert single row in if (rows == 1) { part and inside loop it is batch insert. So I'm thinking to skip single insert and have it in batch insert code. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int rows = jTable.getRowCount(); if (rows == 1) { ...
stackexchange/codereview