instruction
stringlengths
71
71.9k
I'm using grumble to create an interactive tour for a website I'm working on (I'm aware there is a plugin called crumble that does this but I want to have full control of the functionality). Basically, I initialise 6 grumbles (this is the amount of tour bubbles I need), then hide the last 5 and then attach each click h...
I'm currently learning PHP, SQL/MySQL and HTML to develop a web application project (I have very little practical experience in all of these). To get started, I spent far too long and many questions on Stack Overflow writing a web application which inserts records into my database for Game of Thrones characters. The we...
I have source code for execute a command (ProcessStart) using Impersonate, and I want apply best practices and good design pattern, and good performance if possible. I also want to use good Logging pattern. I use the Log pattern for logging my "Executor". Any suggestions? Source code (partial) public partial class Ag...
I have some code that run a series of functions in order and then outputs the results of each. When I execute this code, I am reusing a ton of it, where only the function itself in the code is changing. MethodThatChanges in the below example, is a method that returns void. Task[] task1 = new Task[10]; for (int i = 0;...
I'm not really seeing any use for a generator here, unless there's some way to hook a generator into a language dictionary. But in the following code, the longhand version of the if statement (type_check()) returns a tuple (foo, bar) but to get the tuple from (my first ever) lc (type_identify) it needs to be called fro...
I'm new to Python (and generally to programming), and I have recently written this Minesweeper game: import random import string import os class Square(object): """Represent a square in the cell. mine -- if the square has a mine, it's True. Otherwise, False. location -- a tuple that represents the (x, y) o...
I'm building a .NET Linq-esc query builder for my application and I'm wondering about my implementation and code structure when it comes a few classes. Basically I'm creating a query builder for SQL, and I need for my classes to be able to using the following behavior: query.Select(...).From(...).Join(...).Where(...); ...
I was wondering if there's a better way of doing LINQ projections than what I'm doing below. This method is one of many methods creating a view of an object tree. The first thing that I don't like is that I'm returning an anonymous object. Should I create a BreakdownReport class or something else instead? Also, the cop...
I've translated this Java code into Delphi code: unit Trampoline; interface type ITrampoline<T> = interface function Get: T; function Run: ITrampoline<T>; function Execute: T; end; TTrampoline<T> = class(TInterfacedObject, ITrampoline<T>) public function Get: T; virtual; function Run: ITr...
I am trying to generate Pascal's triangle table in Python 3. I started to like using this following pattern when dealing with 2D arrays. Generate a list of valid indices Use a function that works with those indices in a list comprehension. (may produce side effects) I wonder, is this pattern pythonic and how common i...
I'm previewing the data I'm about to delete, but this SQL looks a little redundant. Is there a better way to write this? declare @history table(pid int) insert into @history select pid from plans p where p.pidSynergy = 'P0022' and p.pid != 2885 select * from forecast_FTEs where pid in (select pid from @history) selec...
It's often useful to be able to time code, for instance, to evaluate alternative approaches to the same problem. Because this is a thing I use frequently, I have created this Stopwatch templated class that I'd like for you all to review. Unlike some other recent code, this class is intended to be cross-platform and re...
I have been trying to achieve the below requirements to get them working. Am I doing it the right way? We have a table with customised Cell (say: firstViewController) Customised Cell has a button, click event in this button, and carries row index value to another view controller. In this view controller I will use t...
I'm implementing a game with a classical screen wraparound effect. It is very simple: if the player goes out-of-screen, it reappears on the opposite side (Asteroids is a good example). float x = getX(); float y = getY(); float screenW = screen.getWidth(); float screenH = screen.getHeight(); if (x > screenW) x = ...
For what I'm doing, I need to be able to draw a buffered image directly into a larger buffered image. I've searched around a little and still have failed to find a better way, but my current way is extremely inefficient and I would like a better way if it's possible. Any improvements onto this design would also be grea...
I was bored, so I wrote a BrainFuck interpreter in Python. It essentially takes input for the amount of cells, then parses the inputted code through a series of if statements. # Simple BrainFuck interpreter from sys import exit # Main interpreter function def interpreter(cell_amount): step = 0 cell = [0] * cel...
I wrote a very simple CSS parser and would appreciate some general feedback regarding the security, code style etc... Basically, this does the following: Take user's uploaded CSS file Save it to disc Parse it and return some styles Save a JSON formatted file to disc Processing class <?php //error_reporting(E_ERROR | ...
Just what it says on the tin: a brainfuck interpreter in JavaScript. function brainfuck(source) { var code = source.replace(/[^-+<>.,[\]]/g, '').split(''); // program code var loop = []; // stack of loops created by bracket operators var data = []; // array of data cells stored by the program code va...
Below is my implementation of a pool. It is based on a hash table and supports using strong, soft or weak references to store objects. At the start there is a builder class to configure and create instances, followed by a subclass of Pool which allows multiple reference types to be used. Towards the end there is an enu...
I'm writing some Java code for some pretty large datasets, in a puzzle I'm trying to solve. The output is correct, but the program doesn't run within the time limit for all the test cases. I've tried a number of optimizations, but can't think about how to improve it. I'd appreciate your suggestions. The puzzle is he...
How can I make this better? #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #define ARP_CACHE "/proc/net/arp" #define ARP_BUFFER_LEN 1024 #define ARP_DELIM " " int readLine(int Fd, char *Buffer) { if (Fd < ...
I have data that looks like the "Input" below and need to convert it into JSON. My solution works by parsing the text to find a level for each data point. Then I use a recursive structure to build a JSON tree (or maybe its not JSON, but its much more useful than the original format). First, I transform the input in t...
This is another revision of my Psycho Productions database, this time refactored from MySQL to PostgreSQL, after I found out about some of the shortcomings of MySQL. The following is a (simplified) version of relationships in a flowchart. The way I used arrows is: where the arrow originates = FK and where it points to...
I would like to ask your comments on my contest code for the following problem: We're going to have a slightly more logical puzzle today. We're going to write a program that will find a path through a simple maze. Formal Inputs & Outputs Input Description Through standard console, you will be given two numbers X and...
I've run into the need to deserialize XML that returns from an http request. I've done some light work with XML deserialization in the past but that was against files on disk. While attempting to write the code I noticed that many of the methods in HttpWeb* and XmlReader had both an async and a regular version. I'd glo...
Finding the prime numbers between two given integers in the minimum number of comparisons: #include <stdio.h> #include <conio.h> #include <math.h> void main() { clrscr(); int i,n,count,n1,n2; printf("Enter n1 and n2:"); scanf("%d",&n1); scanf("%d",&n2); n=n1; int c=0; //variable to store nu...
This is part of my chat client's code. It works fine but it looks messy. Any ideas? //IP Validation private void textBox3_Leave(object sender, EventArgs e) { IPAddress ip; bool ValidateIP = IPAddress.TryParse(textBox3.Text, out ip); if (ValidateIP) { button2.Enabled = true; button3.Ena...
This is my first bash script so I ask to you to say what you think. The script must check every directory and if it finds a pdf file in this directory: move all the pdf files to parent directory, change the name of the files and remove directory. So if I had this folder structure: folder1 file.pdf file.txt folder2...
The previous version is here. This version takes suggestions from that review into account: brainfuck is now an object instead of a function, and brainfuck.run(source) kicks off the interpreter. There is no built-in support for multiple interpreter instances, but Object.create(brainfuck) will do the trick. Stub functi...
I have a piece of javascript I wrote for a recent work project that is essentially taking a deviceorientation event object, taking either the beta value or gamma value of that object and makes a calculation. While I can't necessarily put my exact code here just in case that breaks any of the agreements I signed, the ge...
I am coding a simple blog engine for educational purposes. In the PostsController I have two two methods that share some common code namely, Add and Edit: [HttpPost] public ActionResult Add(PostInputModel model) { if (!ModelState.IsValid) return View(model); // map the input model to an entity model using Auto...
I'm using the old Google Data API to access several spreadsheets and put their contents in a database using Flask and SQLAlchemy. Each run deletes the contents of the database tables and repopulates them with results of the API call. I'm trying to detect API changes and abort the operation to prevent leaving the table...
Problem Description: Find the maximum sum of a compact subsequence of array elements after performing a single swap operation. Solution: def maxsum(lst): # Get maximum sum of all possible slices in list max_ending = max_slice = lst[0] for i in xrange(1,len(lst)): max_ending = max(lst[i], max_ending ...
I am trying to write a function called countHand() that takes in an array of Card instances and counts the total value of the cards given. The requirements are as follows: The function returns the value of the cards in the hand as an Int. It does not use loops or nested functions. The card values are as follows: Any...
I'm trying to create a filewatcher program that can watch different files. The files might have subfiles that are being imported into the main file, which is being represented by the file object. I'm feeling the code is a little messy and I would like to know how I can improve it. The input_watcher() is not there to st...
I'm trying to improve my Color Picker code. It works like Photoshop and I don't want to use a library. for(var yColor = 0; yColor < 255; yColor++) { var r = 255, g = 0, b = 0; for(var xColor = 0; xColor < 255; xColor++) { if(r == 255 && g < 255 && b =...
I am trying to create an outline of what a character is in a game. Then I want to create 10 different characters and compare their stats at different levels. I am creating an interface called Hero that looks like this, public interface Hero { // define methods that must be defined across all character types ...
I have been wanting to learn programming for some time now and decided to really give it a shot today. I have edited and read lots of things in Java to fix small issues but never written from scratch. I've tried C and Java but both seemed just a bit too much to teach myself as a first language, so I'm going with Python...
I need to make thumbnails without empty space and in the original ratio. Please help me check this algorithm to improve it. public function createThumbnail($imagePath, $thumbnailPath, $targetWidth, $targetHeight) { list( $originalWidth, $originalHeight, $originalType ) = getimagesize($imagePath); $targetRatio =...
Is this code correct? It appears to work in g++ 4.8.3 and clang (bcc64), however appearing to work is no guarantee of correctness :) The aim is to be able to replace a call to a member function: void Master::go() { std::string s; func(s); // func is a member function of Master } with a function template...
I wrote a JavaScript function for validating bank account numbers in IBAN format for my own joy. Could you have a look if you don't see any obvious mistakes or places for improvement? function isIbanValid(value) { var lengthMap = getLengthMap(); //cleanup value = value.toString().toUpperCase().replace(/\s...
I'd like this code to be improved package com.array.demo; public class BinarySearchMethod { public static void main(String[] args) { int[] arr = { 2, 4, 5, 6, 8, 9, 11, 15, 17, 19, 22, 111, 117, 234, 543 }; int search = 2; BinarySearchMethod b = new BinarySearchMethod(); int size = arr.length; ...
I'd like to improve this bubble sort code package com.arun.sort; import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] arr={2,5,1,8,12,3,7}; int n=arr.length; for(int k=0;k<n-1;k++){ for(int i=0;i<n-k-1;i++){ if(arr[i]>arr[i+1]){ ...
I am trying to implement Karatsuba multiplication algorithm for binary (base 2) numbers. A requirement is that the intermediate / final results must also be in binary so as to assist in educative purposes. This is my implementation so far. (I am using bittstring library as a container for binary digits) Convertion to B...
For my resources management, I wanted the objects allocated on the heap to be in a contiguous block of memory. Obviously, each data type then has to have their own chunk of memory. I could have used a vector for this, of course, but the resources need to be aligned properly with a given alignment which a vector can't d...
I have this Objective-C code for use in an iOS app that makes a 'bar' on the screen, with a red exclamation mark that flashes in it at random places. Here's what it looks like: Header file: #import <UIKit/UIKit.h> @interface ESFlashingErrorBar : UIView @property (nonatomic, strong) NSArray *points; @property (nonat...
I published a concatenation utility lastly and I feel it could be very good help for many people, but before I promote it, I would like to polish the details as much as I can. So I'll like to ask you to review this less than 300 lines of code. #ifndef THEYPSILON_CONCAT #define THEYPSILON_CONCAT #include <sstream> #inc...
Is using a static variable in a lambda function ok, or considered a bad practice? The code below works as intended (fills a vector with consecutive numbers). #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vec(100); generate(vec.begin(), vec.end(), [] ...
I created a loader animation for an Android app: a simple 3 dots loader. Is this the correct way to animate by using TimerTask? public class ThreeDotsLoader extends View { Paint dot1; Paint dot2; Paint dot3; int defaultColor; int highlightColor; boolean animationStarted = false; TimerTas...
[Test] public void Post_ReturnsCorrectModel() { var post = new Post { Slug = "continuing-to-an-outer-loop", Title = "Continuing to an outer loop", Summary = "When you have a nested loop, sometimes", Content = "When you have a nested loop, sometimes", PublishedAt = DateTim...
Here's a partial binomial heap implementation in Haskell (just merge and insert): module BinomialHeap where data BinomialTree a = Tree { key :: a , order :: Integer , subTrees :: [BinomialTree a] } deriving (Show) data BinomialHeap a = ...
I implemented the following for Project 3 in Project Euler: --Problem 3. The prime factors of 13195 are 5, 7, 13 and 29. What is the --largest prime factor of the number 600851475143? prime :: Integer -> Bool prime x = prime' x (x `div` 2) where prime' _ 1 = True prime' x y = if x `mod` y == 0 then...
I thought up a function that provides types with InputStream and OutputStream: trait Format[A] { def read(i: TypedInput): A def write(o: TypedOutput, a: A) } trait TypedInput { def i: InputStream def reads[A](implicit f: Format[A]) = f.read(this) } trait TypedOutput { def o: OutputStream def writes[A](a: A)...
I created an Observable class that allows me to subscribe to a wrapped value. The implementation looks like this: class Observable<ValueType> { typealias DidChangeHandler = (oldValue: ValueType?, newValue: ValueType) -> () // MARK: Properties var value : ValueType { didSet { for (owner...
I do not like to use while loops in Ruby. I was wondering how I can generate a "squared sequence" (e.g., squares the first input, then squares the outcome, etc.) in a more idiomatic Ruby way than this one: value = 2 while value < 10000 puts value = value**2 end # => 4 # 16 # 256 # 65536 I have a suspicio...
I've decided that I want to take a stab at test first programming. So, before I tackled writing an isPrime function, I wrote this unit test. It's my first and I'm not sure I'm doing this right. I was thinking that I might want to extract the loops to just two methods that I would pass an array to. One for Assert.IsTrue...
This loads a dictionary text file into memory to be used as part of a spell checker. It's part of a larger program, but I wanted general comments so I can clean it up further. #define TABLESIZE 500 #define LENGTH 45 bool load(const char* dictionary) { //initiate hash table node* hashtable[TABLESIZE]; ...
I wrote a C++ function to calculate the binomial coefficient, trying to avoid overflows as much as possible. /*! * @brief Calculates the binomial coefficient indexed by n and k * * This implementation is based on the algorithm described here: http://blog.plover.com/math/choose.html * and the relevant follow-up: htt...
Sometimes when developing a WPF application, I need to access a certain Window (View) from the corresponding ViewModel, to perform or fire a method like this for example: //In the MainWindowViewModel MainWindowView.Hide(); But that's not really easy, and even it violates MVVM because the ViewModel shouldn't know anyt...
I am trying to understand the workings of reader writer locks. For the sake of learning, I implemented reader writer synchronization by my own. I implemented SynchronizedArrayList with reader writer synchronization. I set out with following objective: There can be many readers. There can only be just one writer. Fairn...
I see that there are a few other people who have tackled Project Euler Problem #3. I hope you're not all sick of that question yet. I've not taken a look at those yet (purposely), but am about to now. I feel like I did a pretty good job on this one, but you tell me. How can I further improve this code? I'm particularl...
I have implemented the code to convert datareader to list of objects. My intention was to not to use column name string literals while reading the datareader. public static IEnumerable<T> GetListFromDataReader<T>(IDataReader reader) where T : new() { var properties = typeof(T).GetProperties(); var modelPropert...
I've a slot booking script which is as follows: My Current Algorithm A calendar is shown to the user The user clicks on a date I make an ajax call to determine if at least 1 slot is booked on the clicked date I return back a form from the ajax page ("Time To", "Time From", "Event Name" etc; form along with a hidden in...
I have an input group: <div class="input-group"> <div class="input-group-addon"> @Html.DisplayNameFor(m => m.StorageId) </div> @if(ViewData.ModelState["StorageError"] !=null && ViewData.ModelState["StorageError"].Errors.Count>0) { <div class="a" title="@ViewData.ModelState["StorageError"...
I posted the following snippet to StackOverflow, and someone said there was much to be improved. {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} class (Show a) => Currency a where unphantom :: a data USD = USD deriving Show data EUR = EUR deriving Show instance Currency USD where unphantom = USD instance...
I'm new in Python and consequently I am searching for a specific solution for code development. I already asked some pythonic question today and want to present my whole problem. I have found some solution, but I really have interest to develop easier and clearer code in Python, so all improvements are welcome. For e...
I'd like someone to review these tests to make sure I'm along the right lines in Angular testing. Note - They do all pass (great) but I feel like I'm struggling to understand the finer points of Angular testing. Any thoughts? var headerControllers = angular.module('header.controllers', []); headerControllers.controller...
I am rewriting a VB.NET application in C#. I will not subject you to the original code because it's pretty messy. Below is the converted C# code: public IEnumerable<WebQuery> GetQueries(Request request) { var queries = new List<WebQuery>(); foreach (var report in request.Reports) { ...
The code below generates only 10 email domains. To me, this is bruteforce programming. Is there another random integer library? Could I use something like random.seed() in C++? What is a more elegant way to generate 100 emails names using some Python libs/APIs? import random domains = [ "hotmail.com", "gmail.com", "ao...
Right now, my solution counting likes of a specific user is Starting a recursive call on the "/{user-id}/posts" edge Iterate through all posts On each post iterate through each like on the likes edge If someone knows a better, easier way with less graph API calls necessary, please let me know! /* * * Count my_user...
Using the following query I'm doing transactions with two tables BEGIN TRANSACTION UPDATE SalaryTrans SET carried_forward_amount = @carriedForwardAmount, net_wage=@netWage, processed_date = @processedDate WHERE employee_id=@employeeID AND reference = @reference DELETE FROM CarriedForward WHERE employee_id = @employeeI...
I am converting a VB.NET app over to C#. I won't subject you to the old code but the following is done in a little over 100 lines using nested loops. I am using Entity Framework 6 as my ORM. I have cleaned that up some to this: public void Remove(int key) { var myObject = _context.MyObjects.FirstOrDefault(x => x.Qu...
I have created a QuadTree in Java and would like a general code review or suggestions. import java.util.ArrayList; public class QuadTree { private QuadTree root, parent, northEast, southWest, northWest, southEast; Point center; Double halfDimension; Double northBound, eastBound, southBound, westBound;...
This is for adding code into my table really easily, however it will be called 2000+ times per second, so I need to know if this is the most efficient code to add a row to the database. <?php $site = $_GET['url']; $con=mysqli_connect("localhost","","","rocket_newsites"); // Check connection if (mysqli_connect_errno()) ...
This is a very simple function, but it gets run on a roughly 10ms interval, so I'm looking for ways to improve it. The first obvious thing is that it has to run the comparisons nearly every time as it starts with the lowest probabilities first. Is there a way I can reverse that without breaking it, or a way I can gener...
I created a timer library called PHPBenchTime a few years ago, and decided to rewrite it last week. This new version is meant to add in missing functionality (pause/unpause) as well as expand on the reporting system (so now everything is a lap and has finer details). Additionally, the rewrite was aimed at cleaning the ...
I have a data structure that allows for inheritance of properties, in such a way that if a property is not defined within a context, the second most specific context is checked until said property is found. Simplified it's basically the following: function getCarPartColor($carData, $owner, $brand, $part) { $color =...
I posted a question on Stack Overflow about how to implement Decision Tables in Objective-C after reading about them for the first time in chapter 18 of Code Complete. Nobody provided an answer, so after puzzling it out for a while longer, I created the following code for the movement AI of the enemies in my strategy ...
Could someone review my code, with respect to OOP, clean code and MVC pattern? Main app: public class Application { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { //test @Override public void run() { ...
I've created a lock-free job queue and with the tests I've written, which is also very fast. That makes me doubt my benchmark procedure, so I'm hoping the collective knowledge will shed some light on the validity of those. The test basically increments an atomic value (each job is a single increment) until the predefin...
This my first foray in F#, and I cannot think (yet) functional. I have implemented an interface for a discount curve and the implementation for a piecewise constant instant rate implementation. I would like to have your opinion on how to make this more F#. Should I keep the second input of the constructor as an array...
Please, help improve following code. I have list of users, item of the list has buttons remove (remove user from list) and profile (navigate to user profile). I use MVVM pattern and GalaSoft MVVM Light Libraries. Model public class User { public int Id { get; set; } public string Name { get; set;...
I'm working on an algorithm to calculate weird numbers, and to do so there are several properties that needs to be calculated, one of them being, if it is NOT a semi-perfect/pseudoperfect number. My code can surely be done a lot more effectively because semi perfect numbers have very interesting properties. The first o...
Here is a C++ wrapper for SAFEARRAY, including the ability to expose it as a VARIANT, and to create one out of VARIANT. I am aware of CComSafeArray, however i don't use VC++ so I do not have licence to use this; and also, that wrapper takes the T as a template parameter to the class, however mine takes it as templa...
I've created a web page based on a sample from a book. It works fine, but seems to have become too complicated. 'use strict'; function toggle (triggers, elements, per_trigger, events) { function toggle(index, per, elem, func) { for (var i = 0; i < per; i++) func(elem[index+i]); } if ((e...
I'm currently on Azure Websites & Azure SQL, some documentation recommends using Async as much as possible as cloud services higher latency and have chances of dropping traffic, but it's also cautioning that Async/Await have overhead. Should I... Implement an IStoreRepository interface (although I don't know if it's h...
I have an Android app that shows some fragments, but I'm repeating lots of code. MainActivity.java public class MainActivity extends FragmentActivity { MyPagerAdapter pageAdapter; ViewPager pager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);...
I'd like to improve this selection sort code package com.arun.sort; import java.util.Arrays; public class SelectionSort { public static void main(String[] args) { int[] arr = { 5, 2, 131, 13, 11, 1 }; SelectionSort sort = new SelectionSort(); sort.selectionSort(arr); System.ou...
I have the block of code from my project service layer and I'm not happy with it. It seems overly complex and I would hate to have to calculate the cyclomatic complexity. This block is called in response to a web service request and it is supposed to process the request depending on the fields that are set. It needs to...
Following-up on this post where I implemented a Repository Pattern in vba to abstract ADODB and enable testing my Excel app without hitting a database backend; curious about how far vba would let me push inversion-of-control and loose coupling, I decided to grab the red pill, and see how deep the rabbit hole goes. Pre...
Going down the rabbit hole, I wanted to be able to change the size of a form, and not have to worry about the layout of the controls. vba doesn't support user-resizeable forms, but forms still have a Resize event that fires when a form's size is programmatically changed. I'm leveraging this event handler to set up my a...
I have accomplished what I wanted to do but I think this can be done better. I want my code to look professional. What my code does is ask for your name and gives output in below form. Input: Jack Output: j = joyful a = awesome c = curious k = kindhearted Please show me how to code in a professional manner by reviewi...
I'm using the following query for multiple transactions. This is the scenario. Generate Salary (this is not in the scope of the query) I have employee attendance in Attendance table. Then the salary is calculate from the attendance by using a stored procedure and resulting figures will be displayed in an interface all...
I'm struggling with manually implementing a simple purely functional Set that's also generic and covariant on its type parameter: Set must be a trait, allowing for multiple implementations. it must be covariant on the type of the element it contains. an implementation's type must not be lost when calling methods that ...
I'm trying to get familiar with database handling. Can you point out my errors and what I should change? I want to learn new methods, but just don't want to learn it the wrong way. I do realize these things below, yet I wanted to make the code more clear: I need to bind values for insert() Use try/catch for error han...
private void find_tile(float[] x, float[] z, int nRigidBodies) { int serial[]=new int[nRigidBodies]; int numTiles=4; for(int i=0;i<nRigidBodies;i++) { // Check for the loaction of each tile to find which one should be switched on... //currently only supports 4 for(int j=0;j<num...
I have created a query in which there is a column that calculates a percentage: SELECT u.User_FirstName ,l.[Total Leads] ,SUM(s.SalesCount) AS [New Clients] ,c.Target ,CONVERT(VARCHAR, CONVERT(DECIMAL(11,0),ROUND((CONVERT(DECIMAL(11,2), SUM(s.SalesCount)) / l.[Total Leads]) * 100, 0))) + '%' As y...
I'm currently working on an API package. Basically what it does is scrapes team data and stores them in list of Team objects. The team object contains data such as Team.name,rank, country etc. If a user wants to filter that list to find something in it, I have this really messy and ugly (but working) function: def find...
I have written the following code for returning the list of prime factors. Any speed-enhancing suggestions? import math def is_prime(num): for n in range(2,math.floor(math.sqrt(num)+1)): if num%n==0: return False return True def find_prime_factors(num): primes=[] for n in ...
This is my first SQL post over here, and in fact, I have more or less the experience of a regular SQL programmer, except that the task at hand this time was way harder than normal. I am expecting, hoping and almost demanding a better version of my code, because my version is really bad, but I do not know how to make it...