instruction
stringlengths
71
71.9k
Here's a query I wrote trying to find all movies that three actors have been in together: select distinct Movie from CastMember where Movie in ( select Movie from CastMember where Actor = 1 ) and Movie in ( select Movie from CastMember where Actor =...
The assignment description for this code is this: Each time the user clicks the Circles button, randomly colored circles flow into the display and continuously change their shapes. Here is a screenshot of my program running: This is my first time seriously exploring the aspects of Java 8 development. Therefore, I...
I am a freshman in university. This Pac-Man-ish Game is my final Computer science homework. I know my code is not perfect and has so many to be improved. However, Compared to corrections of this game, I really appreciate to be given the hints or general principles that my code lack, which I could use in the future. Her...
This was my entry for a recent coding challenge for computing the in-degree of a tweet graph (the competition is over). The requirement was to compute the in-degree of a graph made from unique hash tags within a given window of time (rolling). Any hash tag (case insensitive) is a node, and two unique hash tags present ...
Requirement: For the input list of tuples to create single line output showing father of the family|spouse|child1,child2.... Input: input_list = [("David","Polly","Spouse"), ("Roger","Patty","Spouse"), ("David","Lily","Child"), ("Roger","Max","Child"), ("David","Sam","Child")] E...
I'm new to Clojure, and I'm writing some code that processes HTML. I'm parsing the HTML using clj-tagsoup and then trying to pull out the relevant bits with this function: (defn find-nodes [tag-prototype base-node] (letfn [(node-matches [tag-prototype node] (let [[tag attrs] tag-prototype] ...
My program takes 35 sec to run example 2. How can I make my program faster? def sum_keys(K, inputs, count=1): A, B, M, L1, L2, L3, D, R = list(map(int, inputs)) x = ((A*K)+B)%M y = ((A*K+2*B)%M) if K < L1 or count == D: my_list.append(K) elif L1 <= K < L2: sum_keys(x, inputs, count...
I wrote a Tic Tac Toe game from scratch a couple days ago. My AI doesn't always make the best moves, so I'd like some advice on how to improve it. I also hardcoded a move in a very specific situation to prevent it from losing, so I'd like some advice on that. I read about minimax, but I haven't learned algorithms yet,...
What improvements can I make to the following Pig Latin translator? So far, I've been wondering about the FlexibleInstances declaration, but I can't think of how to remove it (since it's required for PigLatin String in instances, which is required for me to use " " in the Monoid instance; I need the extra type argument...
Before posting this, I have spent the past 4 days tirelessly investigating the Internet and the different Stack Exchange websites on how to correctly implement the Unit of Work pattern and Unit Test it using MVC 5 + EF 6.1. So far, the implementation I manage to make it work was this one. Here's the actual problem: I a...
Homework prompt was: You are given two strings, a ‘parent’ string and a ‘query’ string respectively. Your task is to determine how many times the query string – or an anagram of the query string appears in the parent string. NOTE: There are a range of solutions to this problem. With a little thought, you can mass...
I was writing an implementation of Levenshtein distance in Python and I found my code really ugly. Have you any idea how to make it more elegant? import unittest import enum def seq_dist(first, second): Direction = enum.Enum('Direction', 'gap_first gap_second match finish') def find_dist(): dist_table...
A custom stream that is used to perform read and write operations directly into the page cloud blob public sealed class WindowsAzureCloudPageBlobStream : Stream { // 4 MB is the top most limit for page blob write operations public const int MaxPageWriteCapacity = 4 * 1024 * 1024; // Every operation on a pa...
This script checks what the current public IP address is. The plan is for this to run every 5 minutes or so, and then change some host file configuration depending on whether we the IP is identified as that of officeone or officetwo. Each attempt at retrieving the IP address (as well as each success/failure) is logged ...
Actually I needed a function which converts underscore to camel-case. But then I've had the idea: Why not extend the function so, that is works the other way around? Finally I recalled that there is a third case which programmers use: Pascal-Case. So I included that too. The function doesn't work perfect but as long a...
I implemented an OutputWriterService.class to write content in the same file multiple times. The writeToCsvFile method is called round about 50.000 times and includes a list of descrptions which also needs to iterate and write to the file. Is it a good way to instantiate a new Filewriter, BufferedWriter and PrintWrit...
My code right now look like this @contextmanager def smtp_connection(host, user=None, passwd=None, timeout=5): conn = None # smell here try: conn = SMTP(host=host, timeout=timeout) conn.ehlo_or_helo_if_needed() if user and passwd: conn.login(user=user, password=passwd) ...
I've just completed reading the game tutorial of w3schools and wrote a piece of code from scratch. This program basically creates a canvas element with a ball bouncing off the walls of the canvas. The user can also control the ball using arrow keys. I'm planning to make this into a small game by creating some obstacles...
I am learning PHP and have been looking into a suitable way to safely store password data in MySQL. Following advice from here (https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php), is this an acceptable way to deal with passwords? The code is a very basic example and I haven'...
I was working on programming an 8x8 matrix LED display. In particular, I am trying to make a basic version of Pong, controlled by two switches, one switch for each paddle. A ball is generated and moves to one paddle and is reflected upon collision with a paddle. If the ball fails to collide with a paddle on the left...
Sorry if this question has been asked before, but I am having trouble searching for the answer I am looking for. This question is in regards to efficiency and overall C# standards. I have an integer that I manipulate by 1, either by -- or ++ depending on a user's input. I then use this integer as an index to grab an ob...
During the test process of a device, there is a procedure that sets a device in a state in which it is ready to be tested (typically by writing default measure parameters, 3G connection parameters and any other stuff that is requested to be configurable by the devices R&D team). The code below works but I don't like ho...
I have this program that computes a Levenshtein distance of the two input strings, their edit sequence, and the alignment: LevenshteinEditDistance.java: package net.coderodde.string.levenshtein; import java.awt.Point; import java.util.HashMap; import java.util.Map; /** * This class implements the Levenshtein edit di...
This problem is from HackerEarth: The Monk learned about priority queues recently and asked his teacher for an interesting problem. So his teacher came up with a simple problem. He now has an integer array A. For each index i, he wants to find the product of the largest, second largest and the third largest integer in...
I have started learning Java recently and was looking into some easy algorithms. I found the Binary Search Algorithm here I am trying to get better at writing good code for my solutions. I have used MergeSort for sorting the unsorted array first.Please give me your suggestions. import java.util.Scanner; public...
I wrote my string class. The code works, but could anyone tell if I am doing anything wrong? It is an exercise from the "Accelerated c++" book: Implement the Str class, but choose an implementation strategy that requires that the class manage the storage itself. For example, you might store an array of char and a ...
I'm new to spark and dataframes and I'm looking for feedback on what bad or inefficient processes might be in my code so I can improve and learn. My program reads in a parquet file that contains server log data about requests made to our website. I think it is pretty self-explanatory, the only parts that might not be...
I am creating a controller that will display a form and once the form has been submitted to store the item in the database. After the item has been stored the user will be redirected back to the main page of the site. I am calling this controller with: require_once("../app/controller/AddController.php"); new AddControl...
Haven't put one of these together since college. How does this look overall? public class HashTable<T, TU> { private LinkedList<Tuple<T, TU>>[] _items; private int _fillFactor = 3; private int _size; public HashTable() { _items = new LinkedList<Tuple<T, TU>>[4]; ...
I have a JSON data which can be an object/array of recursively nested object or array. The value of an array can not be null, but an value in a object can be null. I would like to return all combination of these keys and values through depth first search. For example: var data = { "title": { "original": "Hitchhi...
Here's a live demo to what my code does, it works pretty well: http://brainlessdeveloper.com/demos/javascriptdynamicshadow.html It's supposed to do what it does: it follows your mouse and rotates the items in the center depending on the position of your mouse. The following JS calculates at which angle relative to the ...
Here's a sample code that I made up : <?php class RegisterController { public $userRepo; public $blogRepo; public $mailer; public $avatarRepo; public function __construct(UserRepository $userRepo, AvatarRepository $avatarRepo, BlogRepository $blogRepo, Mailer $mailer) { $this->userRepo = $...
This is not meant to solve any insane real world problems. I just want to make sure my Set logic is right and the code looks okay. It feels weird implementing it with a Dictionary of dummy values but it seems that's how most languages do it anyway. What do you think? public class Set : IEnumerable { private...
I made a routing system for PHP inspired by Symfony's router composed of a few classes. First I am using Symfony's HTTP Foundations component. Then, I am emulating the classes in the routing component but with almost completely my own implementation (I did copy few lines). The whole system is not simple so I won't be m...
I wrote this block allocator for exercise and would love to get your reviews. Main features I wanted to have: Detecting buffer overflows with canary terminator. Being able to allocate arbitrary types with template allocator and allow types that may fit more than one blocks (continues chunks). #include <cstdlib> #incl...
Is this a good implementation? static int[] mergeSort(int[] arr) { if (arr.length <= 1) { return arr; } int[] left, right; left = Arrays.copyOfRange(arr, 0, arr.length / 2); right = Arrays.copyOfRange(arr, arr.length / 2, arr.length); left = mergeSort(left); right = mergeSort(righ...
Description: Given an image X with known dimensions. We call a method CreateThumbnail to make a thumbnail (or not) with a given max-width and max-height (both optional). CreateThumbnail call ComputeSize method (bad name?) which is responsable for doing the following logic: If no max-width/max-height, the width and heig...
The basic idea is that by defining three functions--recognize, dissect, and combine--conversion between any case type is possible. recognize is meant to recognize a string of a given case type dissect is meant to break down a string into an array of lower case substrings according to the given case type combine is mea...
Is this code good? Or is it the noobiest PHP you've ever seen? <?php //Initialization Section require "helper.php"; $dest = "../forms/addhandout.php"; //Check for $_POST Data if(!$_POST) { send(array("msg" => "ERROR: No Data Recieved")); } else if(!isset($_POST["name"]) || $_POST["name"] == "") { send(array("...
I just felt a sting as for the first time, I copy-pasted code blocks, and made very little change to it, to overload it. It works fine, but I have 3 constructors that are basically copy-pasted. I'm hoping there is a smarter way to do this. This simply creates a thread and runs it with 1, 2 or 3 arguments, and then prin...
I have finally found some time to redo the last tic tac toe game I posted. I have gotten rid of "Magic Numbers" as well as any typos(if their are any please point them out but I think i rid myself of them...hopefully). I have updated the way the code is implemented as well as added a header titled "Constants". This cho...
I have implemented linked list data structure in c. linkedlist.h #ifndef LINKED_LIST #define LINKED_LIST #include <stdbool.h> struct linkedlist { int key; struct linkedlist* next; struct linkedlist* prev; }; bool list_insert(struct linkedlist** p,int k); struct linkedlist* list_search(struct linkedlist* ...
I am currently learning Graph algorithms by solving questions on online judges. The below code is for implementing Topological sort, using recursive DFS. Also, it is my first time with C++ STL. Kindly review my working code below and provide me with feedback. The exact question for the below code is here. #include<c...
The purpose of the method is to add a list of items after every nth step (5 for example) where the input items are repeated if needed. I'm looking for an overall review and possible how to remove the use of the while and replace it with a for. public static List<string> AddEveryNthStep(List<string> items, List<string> ...
I'm a newbie and interested in learning different data structures and algorithms. While implementing quicksort, I found this code works pretty well for partitioning. int partition(int ar[], int lft, int rgt) { int left = lft; int right = rgt; /*median of three is the best pivot value to accomplish in nlogn time*/ int ...
I've implemented K-means clustering in Rust. It's my second Rust project (my first one is here: Randomly selecting an adjective and noun, combining them into a message) I would like advice on whether I am doing stuff idiomatically, and any sensible optimisations I could make. I also appreciate advice on code-style --...
Currently I am working on a profiling unit that does not require stack traces to preserve the call stack, and can return the performance in a html format. All though the logging in itself is fairly fast (negligible overhead on each function), the visualisation of the information is not. With a little over 25k objects g...
I have been developing a simple login registration page with PHP using the repository pattern. Following are the business rules : During registration Email must be unique. Email must be a valid email address. User table columns: id, name, username, password, created_at, updated_at register.php page if($_POST) { t...
Starting point I kind-of inherited a VBA project at work that consists of a bunch of Word document templates that provide users with the tools they need to create documents according to company guidelines and to help them give all documents the same appearance. We use different templates for the documents that we creat...
I am trying to make an easy-to-use non-recursive make script that works with several directories. Everything is packed here.: Directory structure / - root /bin - where executable(s) will be made /obj - where .o and .d files will be made /include - any external includes /lib1 - library...
I'm using TypeScript but this example is in plain JavaScript. I have a class rank with a child-class master. I need an ordered collection of unique masters. Here's what I have but it seems a little "kak": function getMasters() { var gms = []; _.each(this.ranks, (r) => { if (gms[r.master.id]) ...
Background: Didn't what to have to reference bulky 3rd party lib for inline data driven tests and wanted to use standard MS testing framework. Created helper InlineDataDrivenTest to provide a workaround for this limitation. Usage [TestClass] public class DataDrivenTests : MiscUnitTests { [TestMethod] public v...
I started out with the Rosalind problems a while back. Turns out it's a great way to learn a new language. I'm still trying to learn Ruby, and while I haven't managed to use regular expressions as much as I wanted to (learning those being one of the reasons I started learning Ruby in the first place), I put together a ...
I wrote a userscript (to be run with Greasemonkey/Tampermonkey on Stack Exchange sites) to include a Prettify extension and enable syntax highlighting for a language which isn't supported by default. I have only occasionally dabbled in JavaScript, and I have never written a userscript before: (function (func) { // ...
The code is about displaying membership information of all clients from database. I was just wondering what I could do to improve/change it. def optionA(): global DoAnother while DoAnother == True: print("") member = input("Please enter the member number: ") if len(member) !=4: ...
At this point i am interested to see other techniques on handling session timeouts. What are some good improvements on this script to detect when a session is no longer valid? Important definitions: session.gc_maxlifetime - (default 1440 seconds) defines how long an unused PHP session will be kept alive. For example...
Project Euler problem 10 is to find the sum of all primes less than 2 million. I have written a program that does this, and it works, but it takes an excruciatingly long amount of time. What I'm asking is if there is any way I could optimize this to make it run much faster. I wrote it in an app on my iPad called Python...
I have started learning Java and was trying to solve some easy problems from different websites like HackerRank and leetcode.I am relatively new to programming so please don't mind if this is too naive. I found a problem in LeetCode to rotate array.The problem can be found here I have implemented the solution using tw...
My code will display a Hearthstone deck list. I'm still learning HTML and I'd like help with a few things: • How readable is my code? How can I improve readability? • Have I used any bad practices? What should I do instead? • Is there any redundancy in my code? <!DOCTYPE html> <html> <head> <link href='https://fon...
Given a text file including different text and integer numbers (text.txt), what's the shortest way of getting the sum of all the numbers out if it? I have: import re f = open('text.txt', 'r') result = 0 for line in f.readlines(): for value in re.findall('[0-9]+', line): result += int(value) f.close() print...
I am working on a vertical-scrolling 2D platform game using GameplayKit, SpriteKit and I am writing it in Swift 2.0. Today I have been working on a tiling-routine which repositions SKNode right after they have left the upper or lower screen-border. I am not spawning new SKNodes because when the game becomes very fast i...
I want to convert a list of integers into a two-dimensional array for use with TestNG DataProvider. Here is the code I've written: static List<Integer> studentList = new ArrayList<Integer>(); @Test() public void testMethod(){ studentList.add(477915); studentList.add(477916); studentList.add(477917); S...
Goal: Permute inner values between two dictionaries with matching outer key, Save permuatations in counter, Move to next outer key, update counter with new permutations. Problem: Many lookups on large dictionary (60 outer keys x 18000 inner key:value pairs) make existing code correct but slowwwww. import collections ...
I have a dll and an executable which both deal in configuring certain things for a much broader software solution, and the code below in particular is directly meant for database configuration. (Here "inmate info" has been substituted for the actual configurations.) In an MVC context, the dll is essentially the contro...
I want to know if I can improve this program. Its goal is to print a pattern in a pyramid form, by first receiving a letter. The first row is always 'A', only. Then 'ABA', then 'ABCBA'. Increasing order, then decreasing. #include <stdio.h> int main(void) { char alphabet[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char...
I'm trying to put together a workflow for building Clojure applications with Boot in CIDER. To test this workflow, I've written a small example application using Seesaw. My project structure looks like this: example ├── build.boot ├── dev │   └── user.clj ├── .dir-locals.el └── src └── example └── core.clj ...
I'm taking a Python course and the current assignment is to create an algorithm that sorts numbers in ascending order (without using built-in sorting functions). I've had no programming experience before taking this course, so this might be a bit rough. I got my script to successfully sort the numbers by figuring out t...
I am working on this assignment to draw the flag of Liberia for my essentials of computer programming class. I finished it but had extra time to kill and noticed that a couple similar blocks of code are not very concise and could be shortened with a loop, but right now I can't seem to form the code just right! Below I...
I've made a very simple program that takes integer number arguments either with plus/minus sign or without them, and print the number in binary format. binary.c #include <stdio.h> void printBinary(int); int toInt(int*, char[]); int handleProgram(char[]); int main(int argc, char *argv[]) { return handleProgram(...
Problem statement: We have a number of functions in our web application that are getting called too frequently. We'd like you to create a function that, given a function and a time interval, returns a new function that we can call as often as we like, but ensures that the original function is never called more than on...
#include <iostream> using std::cout; using std::endl; class SinglyLinkedList { struct SLL { int data; SLL* next; }; SLL *head; public: SinglyLinkedList() { head = NULL; } SLL* createNewNode() { SLL *newNode = new SLL; newNode->next = NULL; ...
I'm trying to write a multiple functions memoizator, which I've talked about here. The main problem is creating a container containing different and heterogenous functions. I found a working solution, but I don't know if it's safe, if there are limitations, if it's somehow inefficient or if there is a more elegant solu...
I wrote a method that will return the minimum element in a linked-list that operates in O(1) time. I tested and everything works fine. However, I was wondering if there is anything that I can do to make my code more efficient or cleaner. public class Node { //private Object item; Node next; Object item; ...
So I got sick of several things about the way TryParse works. I implemented a generic ParseOrDefault function using reflection. It appears to work as expected, but I'm not fool enough to say my code is bullet proof. What's wrong with it? If something is wrong with it, can it be fixed, or should this idea be tossed? usi...
I'm very new to functional world. I've written a simple brainfuck interpreter as my first F# program. What I would like to know: Am I using the right data structure for each situation? Is my code easy to understand? Is my code style similar to common F# codes (naming, organization etc)? Is my code "very declarative" o...
I'm still learning from designing with types non strings by Scott Wlaschin. For my project I transform some XML to HTML with xslt. Because every filename can have side effects, they are stored in string option types. If I do the transformation I get an ugly pyramid of Option.map and five times more lines of code comp...
I do parsing of the string in order to find wrapped sub-string inside brackets of the first level. a+(b+(d-g))+g+d, in this case I will need to separate (b+(d-g)). Below is the function which i use for such situations. This function is invoked when i find any opening bracket (. I did profiling of the program and unfort...
I need to parse a space- delimited text file. I want to read the file and do operations for each cell. Here is how I am parsing the file: String line; BufferedReader reader = new BufferedReader(new FileReader(file)); Map<String,String> mapFile = new HashMap<String, String>(19); while((line = reader.readLine()) != null...
I have a script for a web page that has to initialize a lot of complex event handlers on page load. Because of the large number of events and DOM elements that these events should fire for, I want to construct a global object containing all the initialization logic. var Global = { button1Handler: function (...
This is the dirty bastard of my current code block, and I'm trying to find a way to improve this code for increased readability, but also functionality. The method checks if the store is currently open. Yet on our site we close the sites 30 minutes prior to their real closing time. Issues arise mostly because all of ou...
Functions with common and simple file operations have started to repeat in my code. Many like this one, but with subtle differences for example: def do_something_with_file(file_name, access_mode, data): with open(file_name, access_mode) as f: f.do_something(data) This is my solution so far: import pickle f...
I have implemented Heap sort, but i think the time complexity is more than (nlogn). Could anyone explain me; what is wrong in my code which makes more time complexity. I will be glad if the answer is in terms of algorithm time complexity based. import java.util.Arrays; public class HeapSort { public static void ma...
Here is the link to git repo of my application I am currently implementing just to have better understanding of OOP as well as learning Concurrency (Atleast a try :D) What is the whole simulation intends to do? This application is intended to provide classes or interfaces to create -> a Room in which persons can enter...
I have played recently and implemented doubly linked list with merge sort algorithm. I was wondering if there is any way of improving the algorithm further to make it as fast as possible (I know about implementing list as array of void* pointers but I want to implement that as a separate structure). I've gone from some...
In our product, Company is a model that can have many Companies belonging to it; so some Companies are parents, some are children, and many are both. We have a helper method Company.root that has as its children all Companies that do not actually have a parent; in this way, accessing Company.root and recursively iterat...
The task is to output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom. For example, consider the following matrix: 1 2 3 4 5 6 The diamond version of this matrix is: 1 3 2 5 4 6 which would correspond to a nes...
Array.prototype.itemsWithQuantity = function(n) { var counts = {}; var result = []; var i = this.length; while(i--){ counts[this[i]] = counts[this[i]] == undefined ? 1 : counts[this[i]] + 1; } i = this.length; var alreadyPushed = {}; while(i--){ if(counts[this[i]] ...
I have code which makes use of jQuery and some additional libraries. But the jQuery part is too overwhelming (and thus it does its job slowly). So I tried to optimize it, but had no luck. Now I'm seeking help from the community. Here is the code, from the news page in my WP theme: /* CSS Reset */ html,body,div,sp...
While playing around with J (link), I found that you can create a sequence of shape N0 N1 ... NK with i. taking a list as its parameters. Since i. creates a range 0 .. RHS and >: increments each value in a range, i. >: i. RHS creates a non-empty range. We can use , to flatten it and +/ to summate it. Given an RHS, thi...
For a string, count the number of occurences of each character. If at most one character has odd count then the string can be a palindrome else it's not. public class Palindrome { //count the chars in the input string //if not more than one character has odd count then palindrome is possible ...
I'm trying to take a result set and organize it into a dictionary then assign the dictionary values to variables that are publicly accessible from my controller. My issue is I have to check if there is a key, if there is a key, assign it to a variable manually, if there isn't set the variable to 0. Is there a better dy...
I'm updating a stats bar on the page after a user action. The code works, but as you can see, it's very messy. Is there a shorter way of writing this function? Seems like a complete mess. I thought about using $.each a couple times to cycle through, but since I need to compare values from the first two array keys in th...
The script below demonstrates VLOOKUP by showing which languages appear from column 1 in column 2. Is there a way that I can refine my code to pass in an exact match? Also, I notice in my console.log, that it is iterating the for loop many times on each word that it finds. Can that be consolidated or condensed to be m...
I am attempting to write a statistical program using an LDA model I've trained/created using Gensim. I am very new to Python and am a student level programmer. This current program is working and getting the results I want. In get_similarities I am comparing each of the user's document vector to all other user's in the...
I am using this AsyncTask class to update two different tables on SQL Server. So far this code works fine, I'm interested in a better and more sufficient code structure for this class, specially in doinbackground(). Is it okay to call multiple webservice methods in a single thread? Any other feedback? private class...
I wrote a small program to compute intersection of 2D infinite lines using Boost Geometry A line is defined by two points in Line class. The getVector method enables to extract a direction vector. The perp function enables to compute the perp product of two vectors. A zero value means vectors are parallel. The intersec...
I have just finished building a Chess game in Java as an exercise. Whilst I am quite happy with the rest of the code, my castling move check code is lengthy and ugly and I want to see if there is a way to improve it. There is a board class, which has a list of all pieces which are all unique classes extended from a sin...
I have a recursive algorithm that inserts nodes into a trie data structure but it seems to be running not well and takes over 10 mins to complete on a data set of about 1 million. All nodes contain a syllables to a phrase all of the syllables are then inserted into the trie to allow for searching in a binary fashion to...
I am an architecture thesis student in my final year and I am developing a piece of software that, ideally, should design houses for me based on certain input. I got the program to work when it was in the proof of concept phase and i was just doing three rooms, but now that I added a border and a more complicated Room ...
I have a situation where I'd like to wrap up some plain C handles into a class, with a destructor and other niceties, in C++. I would like the wrapper class to have the exact same size as the handle, so I can pass an array of the wrappers into the C api without having to allocate and translate them first. The handle is...