instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
This is a program written in Sinclair BASIC (48 BASIC) for the Sinclair ZX Spectrum. It uses a hardcoded key (null right now) as seen in the bottom and outputs a stream of integers generated with RC4. Is there any way I can improve this particularly to get around 48 BASIC using one-indexed arrays (which makes RC4 hard ...
stackexchange/codereview
I am looking for clean way to accumulate amounts within a input dataset. In this example, there are 18 rows of data, and the output is a 3 rows of data, accumulated by Key, by ExpenseType. My biggest concern is whether hashMap is the correct utility for this, or if there is an easier/cleaner way. FamilyExpenseProcesso...
stackexchange/codereview
I've come up with a base class for exceptions for this SMS-based service I am working on. The basic idea behind the service is that a user sends a text message to a number, the message requests a particular action to be carried out by an agent that logs into a different website, from which some account information is s...
stackexchange/codereview
I am new to programming as you can probably tell from the code below I am curious if there is a way to create a loop so I don't have so many copy's of the same code with only different variable names. The way the code works is that for each variable that is represented as a day of the week the value is a string such as...
stackexchange/codereview
As I'm learning Ruby I wrote this little program to generate a "nice" number randomly (like 4747, 6969, etc.). As I'm currently breaking the "do not repeat yourself" rule, how would you refactor the following? def nice_numbers a = rand(9) b = rand(9) c = rand(9) d = rand(9) while a != c || b != d ...
stackexchange/codereview
I have an array called viewObject.terms. This array can contain up to 3 items, I need to iterate through this array and save the values into a data object. ie: data.term_id_1 = viewObject.terms[0].term_id data.ticker_1 = viewObject.terms[0].its_ticker This is what I first tried, but I get the error: Cannot set proper...
stackexchange/codereview
I know this may sound dumb, but last time, I posted C++ code, similar to this one: This is just something to get me closer to actually doing a neural network. This code is supposed to learn colors from many many data images, and then recognize color using an algorithm that I made. Eventually, I want the program to mak...
stackexchange/codereview
Is there a way to use CPS in this code to make the two insert functions tail-call optimized? defmodule BTree do defstruct tree: {node: nil, left: nil, right: nil} def new(element), do: %BTree{tree: {node: element, left: nil, right: nil}} #insert when there's some data in the tree def insert(%BTree{tree: {node...
stackexchange/codereview
I used a glyphicon as a link to delete a comment: <a class="delCommentLink" href="{% url 'article:comment_delete' comment.id %}"> <span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span> </a> I send the request using Ajax. retrieve the comment_url get the grand-grand-parent e...
stackexchange/codereview
I'm creating my own little toolbox for pinging IP interfaces (for the test, only in localhost). In the future I'm thinking of piping the output to a text file. But I'd like to focus on improving the performance for now. For now, scanning a class A IP range is pretty fast, but for a B range (65025 addresses) it's very l...
stackexchange/codereview
I have some data under an HTML format and would like to import it in R. However, it seems that type inference is much less sophisticated than what exists with functions such as read.table. I am using the following workaround, which consists in reading the data table once, write it as a csv and re-import it. # import r...
stackexchange/codereview
The following function sets a query for MongoDB, but that's not very important. It takes 2 arguments key can be either - which comes from an empty search by the user in the front end, or any other string. Select can be either sample or all So it's a switch like this: | ...
stackexchange/codereview
I'm looking to make some improvements to a deliberately crude API written in PHP, it's designed to handle simple requests and talk to the DB. I have the following DB class: class DB { public function connect() { $serverName = "."; $connectionInfo = array("Database"=>"Demo","UID"=>"sa","PWD"=>"qw...
stackexchange/codereview
This code adds the toggle functionality for mobile devices. So, for width lower than 990px, the panel collapses, and the user can toggle to open / close it. angular.module('app') .directive('ngContentToggle', function($window) { return { link: function(scope, $element){ var w = angular.element...
stackexchange/codereview
Inspired by the video from Scam Nation and James Grime from Numberphile, I tried to make a Razzle Dazzle simulator. Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice ins...
stackexchange/codereview
I saw this question (javascript - rotate linked list to the right by k places) the other day and I tried implementing it in Ruby in a totally different way. Here's the code (I also created a REPL if you want to test it - https://repl.it/repls/PrimeSomeBlock): node.rb class Node attr_accessor :value, :next_node def...
stackexchange/codereview
I was searching for a pseudo-random number generator for C# and stumbled upon Tales from the CryptoRandom by Stephen Toub and Shawn Farkas, so I tried to implement a variation of their code. The main difference with their implementation is mine returns inclusive ranges (e.g [0,1] and [min,max] instead of [0,1) and [min...
stackexchange/codereview
I am trying to implement the observer pattern for a stock exchange scenario. Multiple stocks can be registered at a stock exchange. There will be stock observers who are observing some specific stocks. Please advise how this implementation can be improved. stock_exchange.hpp #ifndef STOCK_EXCHANGE_HPP #define STOCK_EXC...
stackexchange/codereview
I would like to know how I can improve this chat application of mine. This has been my side-project for a while. I have made it to support on desktops, tablets and smartphones. GitHub link Online Demo (feel free to try it out) Node.js: index.js // load all node modules var express = require('express'); var app = expr...
stackexchange/codereview
The Problem I'll be extracting up to 4 parts of a String that come from user-input. All 4 parts need to be in order i.e. (1-4) below in that order The first capturing group is required and the last few are not. The named capturing groups are described below KEY (This can be either CONF|ESD|TRACKING and needs to be fol...
stackexchange/codereview
Yes I'm very slowly making my way through Purely Functional Data Structures. So I went through the section on Red Black Trees. What he presents is amazingly concise, except for the fact that he didn't include the delete function. Searching around didn't turn up many functional delete methods, well only two so far. One ...
stackexchange/codereview
I'm a beginner in Python, and computer languages in general, and I'm totally stumped on how to format this iteration into a function. The iteration takes the sum of someone's birth year, month, and day and adds it together to create a sum of those numbers, and then the second iteration takes the first sum and adds thos...
stackexchange/codereview
I am doing my best to keep this code clean and fast, but as I add more to the game, it seems to get harder to maintain a frame-rate higher than 200! I believe that the culprit is a somewhat large for loop inside of the main loop. It performs all of the actions for the tiles inside of the world, and as more tiles are ad...
stackexchange/codereview
I have run the code and it's error free. As this is partial code which only defines one class of the many more to come, there is no output involved yet, therefore I am looking for testing whether the way I have used classes is logically correct without having to wait to complete the whole program and then find problems...
stackexchange/codereview
I am trying to solve this problem: Given an array of integers, find two numbers such that they add up to a specific target number. and this is my strategy: For each i in array num, do a binary search in numfor target - i in num. class Solution: # @return a tuple, (index1, index2) def binary_search(self, a...
stackexchange/codereview
I'm running into a large bottleneck in my program that takes hours to perform. I have a Dataframe that is very large. I need to take the columns of the Dataframe and create new columns within same Dataframe. The new columns need to grouped by a specific date once grouped they are ranked. After they are ranked they ar...
stackexchange/codereview
I have a table containing about 30k rows of data and there's several table associations. The problem is that there's like 18 columns, and each column requires 1 db query. Here's an example of what I'm doing: if col_num == 0 tmp_string_text = finding_phase elsif col_num == 1 tmp_string_text = "" elsif col_num ==...
stackexchange/codereview
I have some code like this ngOnInit(): void { this.activatedRoute.url.subscribe(() => { const token = this.activatedRoute.snapshot.queryParamMap.get('token'); const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage'); if (token) { localStorage.setItem(Authentica...
stackexchange/codereview
I put the readable version into the gist file -> link Please ignore the print and comment in the following code. I often have to write this sort of logic: init the conditions, and deep into loop condition, get the variables in each iteration and break when the condition meets. As you can see, I get the first line in a ...
stackexchange/codereview
I'm new programmer and I'm working on Xamarin MVVM app and I have a pin view like So, basically I have numbers from 0-9 if you pick one number its visible then if you pick a second one first one changed to * and I store all numbers into string called PinCode ViewModel Code: public string PinCode { get; set; } = str...
stackexchange/codereview
I am new to Haskell and currently trying to port my solutions for the 2019 installment of the coding challenge AdventOfCode to Haskell. So, I would very much appreciate any suggestions how to make the code more readable and more idiomatic. In particular, I am interested in whether my use of the State monad is sensible ...
stackexchange/codereview
This is my attempt at writing a generic NSMapTable with weak keys and strong values (after your feedback I'll be trying to write Strong-Key/Weak-Value and Weak-Key/Weak-Value variants to have the complete functionality of NSMapTable with generics). To my knowledge it works correctly. public class WeakKeyDictionary<K: A...
stackexchange/codereview
I am a beginner programmer, I decided to make this calculator program to test my knowledge on basic C# syntax, the code executes as intended, however I would like to shorten it to be more concise. Console.WriteLine("Please select your first number: "); double numberOne = Convert.ToDouble(Console.ReadLine()); Console....
stackexchange/codereview
I am using an array_count_values function since I have translated the code from php to javascript and javascript does not have this function, but not sure on the performance of it. I'm sure it can be faster. It currently takes 50ms for 32000 iterations each time it is called. I have one that returns a simple array: fun...
stackexchange/codereview
In this case I have an array that is parsed from a JSON file. Normally I use all the elements in the array, but for AJAX crawling I only show the parts the search engine asked for: <?php $fitstyles = json_decode(file_get_contents(DATA_FILE), true); ?> … <?php if ($base == "fits" || $base == "gallery") { /* For frag...
stackexchange/codereview
Brief introduction: so the point of the question is that the author doesn't really talk about good or bad code quality and I really wanted some feedback to have a grasp of how the code for others to read should look like. I mean, for the very first solution of the task I would check different parameters manually just t...
stackexchange/codereview
I'm working on a Django project and I'm wondering if there is any way to improve the process time to export my data to xls format. Actually, it takes between 43 seconds and 49 seconds to create the file and download it. I would like to know if my code could be improved in order to save time. This is my function: def ge...
stackexchange/codereview
I'm learning RxJava and this is what I attempted to find the mean of 'n' transactions. List<Transaction> transactions = TransactionsStore.getTransactions(); BigDecimal nTransactions = new BigDecimal(transactions.size()); Observable.from(transactions) .map(transaction -> transaction.amount) .reduce(BigDe...
stackexchange/codereview
I am using ElasticSearch and Tire for search in my app across all models. I would like to refactor autocomplete method because it looks to complex for me. Am I using a good pattern for searching across model? Model class Link < ActiveRecord::Base include Tire::Model::Search include Tire::Model::Callbacks tire....
stackexchange/codereview
The code copies the second column from the right of all the docx files' tables from the folder where the py file is saved, and does some editing on the content in specific cases. The problem that it is painfully slow; I tested it with a folder with 38 files with about 22000 lines total (which is a kinda usual amount of...
stackexchange/codereview
I wrote this jQuery/JavaScript code for slideshow of my dynamic webapp. Is this too much jQuery code for carousel? It seems to work fine on my PC, but with bigger images it gets slower (7MB+) which is normal I suppose? Or am I doing whole thing wrong? I know I could do it with a JavaScript for loop or something, but I ...
stackexchange/codereview
I would like feedback on the class I've written. The purpose is to dynamically create and interact with SQLite3 databases, accepting lists of complete or incomplete statements. import sqlite3 class DB(object): """DB initializes and manipulates SQLite3 databases.""" def __init__(self, database='database.d...
stackexchange/codereview
I was participating in a job selection process and one of the tasks I was asked to do was to develop a take home pay application to let users to calculate their paychecks based on their location. Today I received the feedback, and it stated that: Taxes poorly factored Low OO knowledge The software requirements are st...
stackexchange/codereview
Purpose A clean, reusable module to generate pretty tables (much like those in SQL-clients), like so: +--------+--------+--------+ | HEADER | HEADER | HEADER | +--------+--------+--------+ | CELL | CELL | CELL | +--------+--------+--------+ | CELL | CELL | CELL | +--------+--------+--------+ | CELL | CELL...
stackexchange/codereview
When I am developing in Bootstrap, I need to make sure that what is on the screen looks good. Bootstrap have various cutoff points where the flow can change. So to help with the visual debugging, I have created this tool that just shows what the current screen is according to Bootstrap. <cfscript> sizes = [ { ...
stackexchange/codereview
Hello this is one of my learning purposes projects, a little bit modified version of a popular game called Hangman. I am a beginner so if you guys could point out some obvious mistakes/good practices/better solutions or implementations I will be grateful. Here is a preview hosted on github + repository And my code : H...
stackexchange/codereview
I'm building a graph-based interface to explore Wikipedia, but I'm not really familiar with TypeScript/React (especially state management), so I really feel like I'm just Frankensteining things together, which makes me feel pretty uncomfortable. I've found many things in my code so far that have made me facepalm. I'd a...
stackexchange/codereview
I was cleaning up my code when I came across this situation : var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var count = 1; var html = ''; for (var i = 0; i < a.length; i++) { var rowStart = '<div class="row">'; var cell = '<div class="c">'; cell += '<div class="title">' +...
stackexchange/codereview
I managed to send video feed over tcp socket using code and decode of string64. My problem is that the video feed is kinda laggy, and it's probably because of this time between coding and decoding. Is there a simple way to improve this? C# private void enviar_data() { string data = ""; stri...
stackexchange/codereview
I have a .txt file that looks like this: SHT1 E: T1:30.45°C H1:59.14 %RH SHT2 S: T2:29.93°C H2:67.38 %RH SHT1 E: T1:30.49°C H1:58.87 %RH SHT2 S: T2:29.94°C H2:67.22 %RH SHT1 E: T1:30.53°C H1:58.69 %RH SHT2 S: T2:29.95°C H2:67.22 %RH I want to have a DataFrame that looks like this: ...
stackexchange/codereview
The following is a Python 3 script I wrote to take and delete elasticsearch snapshots. Could anyone please point out any issues? I am concerned that I have structured the code poorly (particularly the order of the functions), making it hard to read, but I am unsure how to fix that. I also made no real attempt to write ...
stackexchange/codereview
I have two threads, one is the producer and other is consumer. My consumer is always late (due to some costly function call, simulated in below code using sleeps) so I have used ring buffer as I can afford to loose some events. I am looking to see if my locking looks alright and general c++ review comments. #include...
stackexchange/codereview
Back on track with my C++ saga: The standard deviation of a list of numbers is a measure of how much the numbers deviate from the average. If the standard deviation is small, the numbers are clustered close to the average. If the standard deviation is large, the numbers are scattered far from the average. Th...
stackexchange/codereview
I have made my own compression tool for a stack-based language that uses a dictionary compression method. The code for the decompression is the following: elif current_command == "\u201d": temp_string = "" temp_string_2 = "" temp_index = "" temp_position = pointer_position while temp_position < len(...
stackexchange/codereview
I have made a beginner program using C that uses file handling and formats the given file. Formatting includes removing trailing blank spaces, replacing one or more blanks by a single blank and also wrapping lines. It would be extremely helpful if you could point out the mistakes I have made and also if I add any othe...
stackexchange/codereview
I have an Excel Worksheet consisting of two columns, one of which is filled with strings and the other of which is empty. I would like to use VBA to assign the value of the cells in the empty column based on the value of the adjacent string in the other column. Dim regexAdmin As Object Set regexAdmin = CreateObject("...
stackexchange/codereview
The Challenge : You have a list conversations, in which each element is a conversation that is represented as an array of words. You need to create a chatbot that will complete a conversation that is currently in progress, currentConversation. To do that, the chatbot must find the conversation from the given li...
stackexchange/codereview
todo(1) is a program that lists the next tasks in decreasing order of urgency (most urgent tasks first). "Next" tasks are those which are not blocked by a task it depends that is still not set as done. I think I'm using a convoluted solution, because I create five different data structures in the program. First, I coll...
stackexchange/codereview
I'm new to computer vision and numpy. I wrote a simple script to seperate red, green and blue colors from the original image by using the kNN algorithm. After reading through some numpy tutorials, I'm under the impression that the performance of my script can be improved heavily. So here are my questions: Is there a ...
stackexchange/codereview
Below is a snippet of code of a little practice project. I am still pretty new to EF and I was wondering if there is a way to write the below statement so that all required data is eager loaded since I have the ID parameter. public ActionResult Index(int? id) { var viewModel = new InstructorIndexData ...
stackexchange/codereview
I want a cryptographically secure version of array_rand(). Is this it? /** * retrieve a random key from an array, using a cryptographically secure rng. * - it does the same as array_rand(), except that this one use a cryptographically secure rng. * - relatively speaking, it should be significantly slower and more me...
stackexchange/codereview
Here's my code to evaluate a boolean expression: #include <iostream> size_t find_in_string(std::string s, size_t begin, size_t end, std::string target) { for (auto i = begin; i <= end; i++) { bool isAtI = true; for (size_t j = 0; j < target.length(); j++) { if (i + j > s.length())...
stackexchange/codereview
I'm making a text simulation game in C# and I've made the calculations and all. But I know there's a better, faster and more efficient way of doing this. Basically, the first calculation is that there's a 5% chance that there would be a 80-100 yard gain and so on. public static class Program { public static Random ...
stackexchange/codereview
I am fairly new to C++, and to have a break from all that Java programming, I decided to do something in C++, which is sorting. The four sorting algorithms are: Bubble Sort Insertion Sort Quick Sort Merge Sort Code: #include <iostream> #include <ctime> #include <cstdlib> #include <iterator> #include <chrono> #define...
stackexchange/codereview
I've written a very basic Python 3 script to search ThePirateBay. Since the tracker doesn't have an API, I had to parse the HTML using BeautifulSoup. I'd like to get some reviews, I'm pretty sure the code is crap, so fire away. I'm also interested in projects I could read to improve my Python. #!/usr/bin/env python3 f...
stackexchange/codereview
I am creating a function for sanitising user inputs and user inputted data outputs. Please offer advise on any improvements which could be made: function cleanse($input) { $search = array( '@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out H...
stackexchange/codereview
Previous: Advent of Code 2020 - Day 2: validating passwords Problem statement I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 3: Day 3: Password Philosophy [...] Due to the local geology, trees in this area only grow on exact integer coordinates in a grid. You ma...
stackexchange/codereview
Today I built a linspace function in Python's C API: static PyObject * linspace(PyObject * self, PyObject * args) { int n, i; double start, end; if (!PyArg_ParseTuple(args, "ddi:linspace", &start, &end, &n)) return NULL; if (n <= 1) return Py_BuildValue("[d]", end); double h; ...
stackexchange/codereview
I have written some code to search a for a pattern in a list of tuples. It works, but I am sure that it can be improved. Any feedback or ideas would be greatly appreciated. The list of tuples I am searching in looks like this: x = [('A', True), ('B', True), ('C', False), ('D', False), ('X', False), ('E', True...
stackexchange/codereview
I have a recursive function that calculates the permutations of a given list/array list. Although a similar implementation works great in Python, this JavaScript implementation cannot handle a list of more than 7 elements before its webpage kills it. I realise this is a natural effect of the recursion, but I am only ma...
stackexchange/codereview
I wrote a function that I use to preprocess pandas dataframes before running them through a machine learning model. The function works perfectly, however I don't think it's the most pythonic way to write it. This function accepts a list of words: ['here', 'is', 'a','sample', 'of','what','the','function','accepts'] def...
stackexchange/codereview
I just started learning reactive streams with RxJava. After reading a couple of books and a lot of articles our there I am still having trouble understanding how to coordinate multiple threads. I would appreciate a critique of the following code, particularly if anyone knows a better way to do it. I basically want to e...
stackexchange/codereview
I have made a very basic login/registration form in React.js. The inputted data is send to a Java Spring Boot Rest-API to create an user or to authenticate using JWT. But in this question I want to focus on the React.js code. import React, { Component } from 'react' import axios from "axios" import Cookies from "js-co...
stackexchange/codereview
Please give me some feedback on how I could make it better or simpler. public class BinarySearchTree { private static TreeNode root; public static void main(String args[]) { BinarySearchTree bst = new BinarySearchTree(); root = bst.addItem(root, 10); bst.addItem(root, 2); bst.a...
stackexchange/codereview
I've written this small code chunk to implement a very basic spline system for object motions. As I've only used C# on Unity3D so far I would appreciate feedbacks on this, especially on access levels, naming and the use of C# API. Most of this code is executed before runtime so I'm not really concerned about performanc...
stackexchange/codereview
I have a motionManager class which uses CMMotionManager() to send rotationRate and attitude values to a publisher in the form of a MotionValueModel. final class MotionManager: MotionManagerProtocol { private let manager = CMMotionManager() init() { getMotionData() } let motionPubl...
stackexchange/codereview
I'm working on a project (studying) and I have a lot of time for proof of concepts and write something from scratch. Basically I'm creating an HTTP server (simple, but not too simple) in C++ using sockets and multi-threading. There are two topics that I'm concerned about: the design pattern of my code structure and the...
stackexchange/codereview
I have the following code which takes an array that might have duplicate ids and will merge the items of those duplicate, and keep only one element per id which contains all the items of all elements with the same id. array = [{ id: 1, items: [1, 2, 3] }, { id: 2, items: [1, 2] }, { id: 1,...
stackexchange/codereview
I have a college assignment to implement a class called sorter, whose object is a sorted vector (the user is allowed to sort it by the method he/she desires). I have been able to implement it as following. Please review it and suggest me the changes I should make to make it efficient. template <typename T> class Sorter...
stackexchange/codereview
I'm in the process of writing a python script for automating a data ingestion pipeline using Amazon Web Service's Kinesis stream, Firehose and lambda. This is my first stab at writing Python, but I do have some experience with JavaScript and Node.js. Scripts are organized as follows: build_pipeline.py - this is where ...
stackexchange/codereview
I use Marionette for my JavaScript application (requirejs for module structure). Application has router and controller. When starting, application renders the root view. Controller executes actions on each route and shows a subview. To show a subview, I transmit a root view in a controller with options. It is a first ...
stackexchange/codereview
This code is a proof-of-concept which I intend to convert into a static utility / helper class. I'm looking at this review from a structure or performance viewpoint. Small detail such as whether it prints or returns something, or whether the output is well-formatted, don't concern me too much. The purpose of this code ...
stackexchange/codereview
I'm making the very common example of Factory design pattern which creates a factory of cars and return an instance of a car. I found a example here https://refactoring.guru/design-patterns/factory-method/php/example and decided to make my own factory. My question is why do I need a Creator for each car? <?php interf...
stackexchange/codereview
The code below extracts data from one web page - I emulate search, select all results from the list and when the list appears (42000 items) I loop through these items. I get an id value from their href to create a proper link (example href is href="javascript:NeuFenster('rb_id=570964&land_abk=bw', so I don't want any J...
stackexchange/codereview
I need to read multiple CSV files that have the same number of rows, and compute some results for each row. For simplification purposes, and in the scope of this code review, this computation would be "sum each column of each row". I would like to be able to do so using the fast-csv parser that triggers events on each...
stackexchange/codereview
I have a simple base class and two derived classes. However, when I'm creating new instances of that class, the line where I instantiate the variables is getting way too long. I have it on two lines: private Bot Bot1 = new Bot(10000, AnchorStyles.Left, "Bot 1", 2 (int)UsersProperties.CUser.Bot1, new Point(15, 420), fa...
stackexchange/codereview
I have created mini-opengl program that draw simple chess board on screen by using SFML windows model only. The program runs fine. The main purpose of this program is to keep it as simple as possible and it is not rely on any of OpenGL helper functions like glOrtho or gluOrtho2D for converting coodinates. Also, it is n...
stackexchange/codereview
I am writing a function to filter a "dictionary" by the "subject" of its definitions. The dictionary data structure is a hash-map of this kind: { "word1" {:foo :bar :definitions [{:definition "def1" :subject ["Subject1" "Subject2"]} {:definition "def2" :subject ["Subject3" "Subject1"...
stackexchange/codereview
I was told to create a calculator design on AWT, which is also my first project on AWT. I wrote the program and submitted it. I was then told that my program contains around 70 lines of code, and I should try to write less code. How can I shorten this code? import java.awt.*; class Demo{ Frame f; TextField t...
stackexchange/codereview
Calculate the number of loans issued by the Regional offices for each business week in the period from 38 to 40 business week of 2011 inclusive. Sort by name of the regional unit, business week. dataset and snippet here - http://www.sqlfiddle.com/#!18/53151/4 Are the joins correct in this query? DDL: create table ter...
stackexchange/codereview
I've got a series of tables with monthly data on USA regions over about 130 years, divided by either climate divisions (clim_div) or other federal standards (ncdc_fips). They all follow the same structure, with columns for region, year, and months clim_div, year, january, february, march, april, may, june, july, august...
stackexchange/codereview
I tried implementing a state machine in C. This is for a Stratosphere Balloon and I wanted to use a state machine to make it better. This will be later implemented in ARM CMSIS. The state function doesn't really do anything yet. And the while(1) loops will be replaced by the sbRepeat transition code. #ifndef _SB_FSM #d...
stackexchange/codereview
We would like to perform n-fold non-stratified cross-validation on a model, say an lm or glm. We have a list of quality metrics we would like to evaluate, which we wrap in a function: fn_rmse <- function(v_pred,v_true) sqrt(mean((v_true-v_pred)^2)) fn_mae <- function(v_pred,v_true) mean(abs(v_true-v_pred)) l_q <- list...
stackexchange/codereview
Project Euler Problem 47 Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers? This is my solution for problem 47 on Project Euler. def primes2(n): """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n-n%6+6, 2-(n%6>1) ...
stackexchange/codereview
I am creating new elements for a webpage at run-time and I have code like this: var dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("Div") {ID = "dynDiv"}; dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red"); dynDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute; left: 500px; to...
stackexchange/codereview
I have written the below code which loads the dictionary and checks if the given word is present or not. The implementation is using a hash table with a chained linked list. In regards to the hash function, I have kept it simple as I was not very concerned about collisions. Can someone please review it and let me know ...
stackexchange/codereview
This is a translatable password validator for django, based on zxcvbn-python and available with pip. zxcvbn is a password strength estimator inspired by password crackers. It permits to prevent users to have to choose a password with one upper case, one special character and a number, but still check the password stren...
stackexchange/codereview
Could I make this method for deep copy generic to the Collection type? That method is so simple and I can't imagine ever needing to change it, so maybe I should just use the "cut / paste" code re-usage design pattern to handle the Collection typing problem? public class Start { public static void main(String[] arg...
stackexchange/codereview
I am modeling an infectious disease with a fixed incubation period. I chose a queue to keep track of when people become symptomatic. I imagined using some operations like so: queue' = enqueue numberOfPeopleWhoJustGotInfected queue (numberOfPeopleWhoJustBecameSymptomatic,queue'') = dequeue queue Since enqueue and deque...
stackexchange/codereview
Trying to write a substring function in Clojure. I am sure there is a more idiomatic way. Can anyone enlighten me? Otherwise, here is my version. Thoughts? (defn substring? "is 'sub' in 'str'?" [sub str] (if (not= (.indexOf str sub) -1) true false))
stackexchange/codereview