instruction
stringlengths
71
71.9k
This is my first time writing JAVA, and I'm trying to start off on the right track. Using my C++ knowledge, I was able to understand the syntax for the ternary operator, but I'm not sure how it should be approached properly in JAVA. I have used Ideone to test this, which include importss that apparently aren't even ne...
I have a method in a class, and its sole purpose is to prepare another class for use: private function createHttpPost($endPoint) { $httpPost = new HttpPost($this->baseUri . '/' . $endPoint); $httpPost->setContentType('application/json'); $httpPost->setAccept('application/json'); if($this->auth) { ...
I'm learning CUDA and wrote a little program which generates prime numbers using the Sieve of Eratosthenes. (I know the limitations of CUDA, specially with memory sizes and limits, but this program is for educational purposes). Questions: Did I set up the configuration correctly? (did I set dimBlock and dimGrid correc...
I'm trying to clean up redundant old code, so I'm asking this general question. Since all iOS 7 devices have a front camera, would it be safe to remove the code to check if the device has a front camera? In the past this was necessary as not all devices with iOS 6 had a front camera. It is true that Apple could theoret...
Example cases: Need to add x=1, y=2 and querystring variables to the following URLs: http://www.foo.com/blah/blah?test=1&abc=2 http://www.foo.com/blah //-- usage get_link(array('x' => 1, 'y' => 2, 'z' => 'string')); function get_link( $my_params ) { $param_querystring = ""; $http_host = $_SERVER['HTTP_HO...
I created a basic desktop calculator using Java. Does anyone have any suggestions as far as coding best practices, readability issues, or just generic coding mistakes I might have missed? Any professional input you could provide would be greatly appreciated. Calculator.java package calc; import javax.swing.JFrame; pub...
Followup to How do I optimize this Java cube root function for BigInteger? So I've tried several implementations of this algorithm. The version using only BigInteger sometimes results in a never-ending cycle of candidates: public static final BigInteger _3=BigInteger.valueOf(3); public static BigInteger cbrt(BigIntege...
I am developing a custom grid view with different columns. ViewPossibilities Mockup Here is the full demo. You can directly use it, with Internet uses permission. This works perfectly but I want to optimize it. MainActivity.java package com.example.rtrt; import java.util.ArrayList; import com.squareup.picasso.Picas...
I have a ZK project in Java 6 (ZK is like ASP.NET but with zul files in stead of aspx). For showing and creating/updating the catalogs I created an abstracted view. This all works with 1 viewmodel at the back. To go to the right catalog I provide a String what is the catalog class his name. Of course with just that ...
I created my first plugin in jQuery and just want some inputs on how I can improve the code and features. Here is the fiddle $.fn.fruitZoom = function (options) { var defaults = { ele: "p,span", }; var settings = $.extend(defaults, options); $("#fruitZoom :first-child").click(function () { fontSize = $(d...
I tried to implement as many changes suggested as possible as well as expanding the code base according to the suggested link. The original question can be found here. It does solve 4x4 and 9x9 Sodukus. What should I do to make it more Pythonic? This is what I came up with: from numpy import * import sys TEXT = '.1234...
I have a question regarding whether it is viable or deemed correct if a validation object invoked a query. Essentially, I have some code that looks like this: public interface ICountryCodeValidator { IEnumberable<ValidationError> Validate(string countryCode); } public class CountryCodeValidator : ICountryCodeVali...
I think I can refactor this: if (clicked_id == "contain-word") { $("#specie_filter li.checked").removeClass("checked"); $("#specie_filter li:first").addClass("checked") $("#specie_filter ul").scrollTop(0) $("#cell_filter li.checked").removeClass("checked") $("#cell_filter li:first").addClass("...
One of the things that has occurred to me more recently is that if you add up all of the bandwidth that is taken up by thousands of users downloading the newlines and tabs used to make HTML source code readable... that's a LOT of wasted bandwidth. So I wanted to add some code that would condense whitespace on-the-fly b...
For the below query, show that both summation and product are instances of a more general function, called accumulate, with the following signature: def accumulate(combiner, start, n, term): """Return the result of combining the first n terms in a sequence.""" "*** YOUR CODE HERE ***" Accumulate takes as ...
I'm working on a little project where I have to create sort of an image mask. Overall my code works quite good in all browsers but sporadically the animations "flickr" on Chrome (Windows). So I was wondering if I could increase to performance when repainting my canvas (on mouseover/out). DEMO JS: // Stores all dday obj...
I have an object, KbArticle, that originally in it's constructor, would try to return null if the SQL query that retrieves the data for its required properties came up with 0 rows. A friend told me that constructors shouldn't return null, and that I should look into the Factory Pattern. I did and I see the benefits, so...
I'd like to know if I can make this code more efficient in terms of line saving, or any other way: def missingDoor(trapdoor,roomwidth,roomheight,step): safezone = [] hazardflr = givenSteps(roomwidth,step,True) safetiles = [] for i,m in enumerate(hazardflr): safetiles.append((m,step)) ...
I recently created one of my first hover effects using HTML and SASS. Since it is my first hover effect, I'm almost positive that is it horribly inefficient. I'm sure there's a way to do this effect using half the number of lines of code, but I can't figure out any ways to do it. The hover effect in question is for ...
I'm writing an application for work that requires me to process a list of transactions. The list is small (5 records at the most) and I'm required to display that data in an android ListView. My client has asked that I include the ability to order the list based on the date (I have added ordering it by the amount spen...
I'm new to Laravel and trying to figure out how I can reduce/refactor this store() call in my SessionController. Basically, the SessionController is used to authenticate a user against an LDAP server (using wells/l4-ldap-ntlm instead of the default auth driver) On LDAP auth success, it then checks if the user has an ac...
I am constructing a form builder in ASP.NET and I am wanting help with the structure of my POCO classes I have the following so far. I just don't see why I need to add to a list and then process it further again would their be a neater way to return a list of .net controls just to add to Panel using LoadControl(control...
I have a piece of code that is used to calculate the cell centers in a rectangular mesh. The mesh size is pretty large (650 columns by 1150 rows). The code runs very slowly. I was wondering if I could employ any tricks to reduce the runtime. In the example below, deltax is a 1D array of column spacings and deltay is a ...
Could you provide feedback for this code? For arrays of length 2, is it more efficient not to use a sorting algorithm? package insertion.sort; import java.util.Arrays; public class InsertionSort { /** * @param args the command line arguments */ public static void main(String[] args) { int[...
I'm writing a small application to score matches of a game. (There are two "teams" on each "alliance", and two alliances play each other in a match.) I have a "logic" class that handles the values of different scoring elements for each team, and calculates that team's score. Instead of writing getters and setters for ...
This is my simple Perl script implement password dictionary attacking, encryption algorithm SHA1 with different length. It takes 2 arguments as input: first argument is password dictionary file path, the second one is a text file contains line-by-line encrypted text. I used 2 common dictionaries for testing: rockyou an...
Simple task, I am just trying to have the data that correlates to a menu item hidden until it is clicked. However, I feel like this can be optimized. There are 2 ng-repeats, which is a little redundant but I can't think of another way to do it. What do you think? See JSFiddle: <script> var app = angular.module('app...
The following code makes a div tag editable and handles the save and cancel buttons. But there is a lot of duplication. How could I remove the duplication on this? var originalTexts = {}; $("div.edit-panel").find("span").click(function() { var panel = $(this).closest('div.simple-panel'); var text = panel.find(...
for (var i = 1; i <= 100; ++i) { var fizzBuzz = "" if i % 3 == 0 { fizzBuzz += "Fizz" } if i % 5 == 0 { fizzBuzz += "Buzz" } if fizzBuzz == "" { fizzBuzz += "\(i)" } println(fizzBuzz) } I don't really like comparing strings with ==, but apparently, that's how...
I'd appreciate any help just refining this working code. It has a bit of a weird context, but basically it's for a gallery style site that has hundreds of pages, but needs new navigation buttons. Unfortunately there's no way to add these buttons without adding them for over 300+ pages manually, or using a javascript li...
I don't like the service class below, specifically, the way it exposes the internals of the producer. While it would be possible to combine all three classes into one producer-consumer, I would rather that they stay separated. Service: package net.bounceme.dur.client; import java.io.IOException; import java.io.Object...
I have a list of datacenters, which are dc1, dc2 and dc3. And each datacenter has six IDs as of now (can be 11 in each datacenter as well or uneven number for each datacenter). dc1 - h1, h2, h3, h4, h5, h6 dc2 - h1, h2, h3, h4, h5, h6 dc3 - h1, h2, h3, h4, h5, h6 Now I am trying to generate combinations of datacente...
I am trying to solve NGON problem. I am using bottom up dynamic programming here. Recurrence function is: $$\begin{array}{rl} f(a,b) &= f(a-1,b) + f(a-1,b-1)\,a_i +\frac{f(a-1,b-2)\,a_i(a_i-1)}{2}, a>0,b>0 \\ f(a,0) &= 1, \\ f(0,b) &= 0, \\ \end{array}$$ \$a_i\$ being the points on \$a^{th}\$ side. I have u...
I would like to know if this code in .htaccess for forcing SSL and WWW in URL is correct, because with another code I usually get redirect loop, e.g. RewriteCond %{HTTPS} !=on and now it works like a charm (suspiciously). Also, is it possible to write it better/simpler? # Force to SSL RewriteCond %{HTTP:HTTPS} !1 Rewri...
I wrote this code to list contents of an XPI file and then read the contents in it. I was thinking of these areas of improvement: I put the zr.open in the try because if the file does not exist it will throw exception, and if zip reader is left open it usually crashes the add-on. I'm reusing the input stream create in...
I created this demo example for MDN documentation to show how to use Promise.all and Promise.defer in user created promise. I used lets because I thought if I didn't it would mess it up. People are recommending I avoid let because the standard is not there yet and it looks like when it lands it will be a little differe...
I decided to take on the FizzBuzz challenge with as twist that I would use Java 8 concepts to make it a bit modular, yet still let it be a short, readable and understandable program. This in contrary to some gem I found on the net: FizzBuzzEnterpriseEdition The problem description: Write a program that prints the numb...
I have the below C# code for parsing. Do you think this is most optimized or should I use a generic method in these functions themselves? public static bool GetDBBool(object value) { var result = false; if (value != null && string.IsNullOrEmpty(value.ToString()) == false) bool.TryParse(value.ToString(...
This simple console program prompts the users for a number and returns the lowest and highest numbers from their inputs. It is difficult to add more user inputs, though. How can I make this easier to maintain and extend? using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Co...
There are quite a large number of existing implementatons of FizzBuzz but I awoke this morning in a cold sweat with the terrible revelation that Code Review had no FizzBuzz implementation in Forth! To redress this terrible oversight, I wrote this while sipping my first cup of coffee. : FIZZBUZZ ( -- ) CR 100 1 DO ...
Using Spring's JdbcTemplate to load a specific object by ID if exists, I have this code: Person person = null; try { person = jdbcTemplate.queryForObject(sql, new Object[]{ id }, new PersonMapper()); } catch (EmptyResultDataAccessException e) { LOGGER.warn("Could not find person with id " + id); } A Sonar rule...
I am looking for a code review for this multipart or single file chunk downloader using threading and queues. downloader.py import argparse import logging import Queue import urllib2 import os import utils as _fdUtils import signal import sys import time import threading DESKTOP_PATH = os.path.expanduser("~/Desktop") ...
In my quest for learning Objective-C, I have created the common FizzBuzz code in it. This is due to a suggestion/challenge from @nhgrif to re-implement anything he does in Swift in Objective-C. #import <Foundation/Foundation.h> int main(int argc, const char* argv[]) { @autoreleasepool { for (int i =...
I came across this problem. Problem Statement: Given an array of ints, is it possible to choose a group of some of the ints, beginning at the start index, such that the group sums to the given target? However, with the additional constraint that all 6's must be chosen. groupSum6(0, {5, 6, 2}, 8) → true groupSu...
Problem Summary: Given a singly linked list, remove all the nodes which have a greater value on right side. Example: The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3->NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the right side. Full problem state...
I've updated my text-based terrain generator a lot. Even though I haven't worked on it all that much. I really just want to know, like usual, is there anything I can improve? How can I shorten the code? What can be made more efficient? Yada yada yada... #!/usr/bin/env python from random import choice from os import sy...
I've just started programming and read a book called Head First Java. I thought it would be fun to make a training project that I can put all the stuff I learn into. Is the code I've written here just really bad or good code written for a beginner? I've got 4 classes: Main class: public class Main { Player p = new...
Since today is apparently a good day for...unlikely FizzBuzz implementations, I decided to contribute another, this one in C++: #include <iostream> #include <functional> #include <vector> #include "xrange.h" int main() { std::vector<std::function<void(int)> > funcs { [](int i) { std::cout << i << "\n"; }, ...
I have a windows forms application which needs customized dll files to be built and for that I am using an online builder using asp.net. I am in no way a asp.net expert not even near a beginner but this is what I have come up with so far: All the work is done by the Handler: public void ProcessRequest(HttpContext cont...
First, the struct itself: struct Fraction { var numerator: Int var denominator: Int { didSet (oldDenominator) { if self.denominator == 0 { self.denominator = oldDenominator } } } init() { self.init(numerator: 0, denominator: 1) } init(numerator: Int)...
Please suggest improvements/refactoring to this game to make it more idiomatic Python. import random import time class Hero: def __init__(self): self.level = 1 self.max_hp = 3 self.hp = self.max_hp self.attack = 5 + self.level self.defense = 5 + self.level self.name ...
MS SQL Server, no loops. ;) WITH Numbers AS ( SELECT 1 as Number UNION ALL SELECT Number+1 FROM Numbers WHERE Number < 100 ) SELECT CASE WHEN Number % 15 = 0 THEN 'FizzBuzz' WHEN Number % 5 = 0 THEN 'Buzz' WHEN Number % 3 = 0 THEN 'Fizz' ELSE CAST(Number as varchar) END AS FizzBuzz FROM Num...
For this flowchart on finding the minimum of 2 numbers: I've created XML for this flowchart: <start> <InOut> <in> a </in> <in> b </in> <out> min </out> </InOut> <calc> <ins> a=3 </ins> <ins> b=5 </ins> <ins> min=a </ins> </calc> <con gurd="min>b" typ...
Inspired by this question: Fraction (rational number) structure with custom operators, I have written this class for doing some simple work with fractions. Fraction.h: #import <Foundation/Foundation.h> @interface Fraction : NSObject @property int numerator, denominator; -(void) print; -(void) setNumerator: (int) n; ...
Since this problem involves small numbers (particularly with a small loop count of 100), it's possible to ease the modulo operation setup by simply working with 16-bit and 8-bit registers: $$\dfrac{\text{[AX] (16-bit register)}}{\text{[other 8-bit register]}} = \text{[AH] (remainder)}$$ My main concern is with the layo...
I've decided to write a C++ FizzBuzz with the focus on some new C++11 features, ridiculous optimizations and unit-testability. Are there improvement possibilities in those regards? template <typename T> static void fizzbuzz(std::ostream& out, const T& number, const std::vector<std::pair<std::string, T>>& values) { ...
I had to jump on the bandwagon for this one. The task does a great job of helping you learn a language you're unfamiliar with. So today I present you with my version of the infamous FizzBuzz game in Common Lisp. This is really the first "program" I've made in CLISP, and even though it's pretty small, I'm quite proud!! ...
A node has a next and down pointer. Merge the linked-list such that end result is sorted. Here we have a top level linked-list, followed by a down-list. If { 10 : {20, 30} , 35 { 40, 50 } } is the input data structure, it means that 10 is connected to 35, using the next pointer. 10 is connected to 20 and 20 t...
I don't normally write vb.net code, and I would rather maintain a monstruous vb6 project than a simple vb.net one. There's something about fizzbuzz going on this weekend, that pushed me to write this: Namespace CR.Sandbox.VB.FizzBuzz Module Sandbox Public Sub Main() For index = 1 To 100 ...
Technically, this is a follow up to these two questions, but I have taken a radically different approach. Everybody Loves Fibonacci Does everyone still love Fibonacci I finally allowed myself to be convinced that it should not be as object oriented as I wanted it to be. I opted instead to return any given \$F_n\$ as...
Recently I submitted some string formatting and printing code (found here) that I wrote as an small exercise. It was implemented naively using string replacement. This time around I wanted to actually parse the format string. This is the first time I've ever attempted to write code which does any type of parsing. I'm n...
The core problem is simple enough, but I've developed a type system that I'm not sure about. The intention is, if the result is a number, calling num $ fizzBuzz 16, for example, lets me retrieve 16 as an Int. However, it seems awfully repetitive, to have to mention "Fizz" so many times in the code. Can it be done be...
After reviewing autoloader functions on the site, I didn't see anything like this, and I was wonder what may be wrong with this? function findNloader($classFile){ $file = exec("find ./ -name ".$classFile.".php"); if(file_exists($file)){ return require $file; } else { return false; } ...
I have written this small little program, to test how my Fraction type behaves when used with and without a custom FractionFormatter - I've implemented two custom formatters: FractionFormatter, which simply puts the numerator at the left of a slash, and the denominator at the right ("{0}/{1}", fraction.Numerator, frac...
1 REM 2 REM FIZZBUZZ IN COMMODORE BASIC 3 REM 10 FOR I = 1 TO 100 20 IF (I/3)=INT(I/3) THEN PRINT "FIZZ"; 30 IF (I/5)=INT(I/5) THEN PRINT "BUZZ"; 40 IF (I/3)<>INT(I/3) AND (I/5)<>INT(I/5) THEN PRINT I; 50 PRINT 60 NEXT I I'm not happy with the tests for "multiple of 3" and "multiple of 5". Using floating-point arith...
I don't know if it's just me, but I feel like my sign up action method has gotten a bit messy. I think that perhaps instead of setting error messages in a controller, I should set error codes which I can intercept in the View and assign the actual text message to it in there. Because I think it's classified as UI logic...
I found a definition of the factory design pattern as: Define an interface for creating an object, but let the subclasses decide which class to instantiate. I understood the first part "defining interface for creation an object", but I am not able to understand the second part of "let subclasses decide which class to...
I have this implementation of the FizzBuzz challenge in Ruby: (1..100).each do |n| i_3=(n%3==0) i_5=(n%5==0) case when i_3&&i_5 puts 'fizzbuzz' when i_3 puts 'fizz' when i_5 puts 'buzz' else puts n end end It prints the num...
If \$f\$ is a numerical function and \$n\$ is a positive integer, then we can form the \$n\$th repeated application of \$f\$, which is defined to be the function whose value at \$x\$ is \$f(f(...(f(x))...))\$. For example, if \$f\$ adds 1 to its argument, then the \$n\$th repeated application of \$f\$ adds \$n...
Inspired by this question: Fraction class implemented in Objective-C, I have written what I feel is an improved version of the Fraction class in Objective-C. As per the tips in this answer, the class is immutable (and a mutable subclass might eventually happen). Besides improving on the existing functionality and chan...
Here is an article on password hashing, along with an implementation. Is this code secure with number of iterations 10000, key length 256 and salt bytes 32? Is there a rule-of-thumb for key length vs. salt bytes? Regarding key.destroy() and pbeKeySpec.clearPassword(), is it necessary to "manually" destroy the ke...
I went ahead and implemented a method to calculate Fibonacci numbers using memoization. public class MemoizedFibonacci { private static final List<BigInteger> FIBONACCI_LIST = new ArrayList<>(); static { FIBONACCI_LIST.add(BigInteger.ZERO); FIBONACCI_LIST.add(BigInteger.ONE); } public s...
I'm trying to enhance the execution speed of my below code. I am using only vanilla JavaScript. I would be willing to bring in additional libraries and plugins as long as they will enhance the overall speed of the code. The goal is to have the absolute fastest execution time of the below code. Currently, it executes f...
I tried to look up and suck in most of the information about optimizing this operation and this is what I came up with. As it's pretty much core of the game, I really would like to have it performant as much as I can. I would appreciate if someone can take a look at this and possibly find weak spots. Note: I am using B...
I found a nice lightbox2-fork, which I tried to improve. After about six hours of work the code passes jslint. I also tried to change variable names for better understanding of what they are for. What else can be improved there? jsfiddle (yet unmodified but working CSS) lpaste $(function () { "use strict"; var...
public class FirstActivity extends Activity { private String userName; private Uri userPhoto; private void onOkButtonPressed() { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra(SecondActivity.Key.USER_NAME, userName); intent.putExtra(SecondActivity.Key.USER_...
The question is here. 100 people are standing in a circle with gun in their hands. 1 kills 2, 3 kills 4, 5 kills 6 and so on till we are left with only one person. Who will be the last person alive. Write code to implement this efficiently. Here is my Java implementation: public static void main(String[] args) throws...
I will be adding functionality and most likely additional refactoring, however a stringent review would be welcome before I build it further. I know documentation is probably a bit sparse but, you know how it is. If you feel anything significantly warrants documentation, let me know. I know I understand the code; I do...
This basically it sets a shapes default size and radius based on how many characters are in a string that is passed to it, the user gets the option to manually set the Font, otherwise it is automatically set for them. All letters are set to face towards the center of the circle as it wraps around. I do seem to have two...
I am using try/catch syntax in combination with a database transaction to (hopefully) prevent partial registrations. I am wondering if I'm on the right track, and what ways, if any, I can improve my code. Please be advised that __construct() is passed an array of unsanitized post values that have been organized into an...
I have created the following code: def LetterCapitalize(str) str = str.split(" ").each {|word| word.capitalize!} str = str.join(" ") return str end This takes in a basic string and capitalizes the first letter of all of the words. It looks kind of awkward to reassign things to str twice. What is wrong with my st...
The idea here is to write a function that gives you back a persistent version of a class that you supply. So you if you run PersistentList = make_persistent(list, "PersistentList", ['append', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort']) You will get back a class that behaves like a list but automatically p...
I am attempting to learn swift by refactoring one of my old games and I need to rewrite my update method which calculates a delta time. This code works but is ugly. How would I go about properly rewriting this? import SpriteKit class GameScene: SKScene { var lastUpdateTimeInterval: CFTimeInterval? override fu...
I'd like this code to be improved. import java.util.Scanner; public class ArrayElementFind { public static void main(String[] args) { // TODO Auto-generated method stub String[] arr= { "A","B","C","D"}; Scanner in=new Scanner(System.in); System.out.println("Enter the char to sea...
Following up on this post, and including some major changes suggested, here's the revised code. Changes include: No longer keeping an IFormatProvider at instance level. Removed IFormatProvider constructor parameters. Introduced ToString(IFormatProvider) overload. Changed decimal to float, to leverage float.NaN for 0-d...
I'm practicing Swing effects. Everything works but for some reason I get a ton of error messages in the command prompt when the fields are empty, despite my attempt to add some exception handling (this has made me realize I need to practice that a lot more). /* Author: Luigi Vincent Practicing Java Swing button and...
Currently, the following code runs and produces the expected and desired output. However, I'm sure that there's much wrong with it. This project queries the (flat) database, instantiates each row as an object, adds those objects to a queue, and makes the queue available to clients. Clients may then connect to the ser...
This is my second attempt (version 1) at writing a string formatting utility which uses parsing. This time I more explicitly designed it as a finite state machine. I have very little experience with writing FSMs. As before, I'm not 100% sure that this code does not contain any critical flaws. In addition to pointing ou...
I tried to implement the idea given in the elasticsearch doc about reindexation albeit I think they must code it inside ElasticSearch and expose it as an API. #!/usr/bin/env python from __future__ import division from argparse import ArgumentParser, FileType import json import requests from time import sleep class E...
I'm trying to write a function which will cache objects in memory. The function below works, but performance is unbearable. What would you recommend to improve performance? public void SerializeInsertCache(object item) { //Get type of item object item Type type = item.GetType(); ...
Does someone know of a better way to get proper grammar in sentences than this method of mine? I don't want to continue with this for my entire huge program if there is a much more elegant way. #include <iostream> #include <string> enum Gender {Male, Female}; enum Capitalized {Capital, NonCapital}; struct Person { ...
I have written the following code for looping through WebElements in Selenium. Can someone please provide me with feedback on how to improve my code? public static void checkAbsentSearchResult(String title, String Testgoal) throws IOException{ try{ List<WebElement> allSearchResults =...
I have this code which I wrote to parse arithmetic expressions. However, many people say there are problems with it but don't tell me what the problem is. Please let me know if you see any. Note that I know there is another way to do this. But I did it specifically this way as I am influenced by NLP parsing style and I...
I'm building a GameClient-Class in Python which handles user input and has to read from a database (MongoDb). I want to know if that is the best practice to implement it, so that I can use it with Python's with statement. Because I want to use different functions of my Client class, __enter__ has to return self, so th...
I've isolated this function, cons, for hash-consing in C. It is where the bottleneck of my program is. How could its performance be improved? var32 cons(var32 x, var32 y){ var32 ptr; uid id, hashedId; map newMap, currentMap; u32 colls; #ifdef __DEBUG__ ++consCount; colls = 0; #endif ...
I'd like to see if my code follows common practice, or is already efficient or fast enough. from random import randint w=[[2,0,0,0,0],[0,0,2,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0]] #1 represent Mr.Pacman, #2 represent food. for y in xrange(len(w)): #Finding the coordinate of Mr.Pacman for x in xrange(len(w[0])): ...
I have wrote some animation code, and it's what I class as old school. As you can see, there is a lot of repeating code. Ideally, I would like to be able to take the delay and left or right position from a data attribute set on the button itself: $(".click").click(function(){ $(this).delay(400).animate({bottom:'30px'...
The problem: Start with two arrays of strings, a and b, each in alphabetical order, possibly with duplicates. Return the count of the number of strings which appear in both arrays. commonTwo({"a", "c", "x"}, {"b", "c", "d", "x"}) → 2 commonTwo({"a", "c", "x"}, {"a", "b", "c", "x", "z"}) → 3 commonTwo({"a", "b", "...
I'm new to PHP and just wrote a bunch of if statements to display content based on the current time. Is there a better way of writing the following block of code to easily be maintainable? The only thing that changes in each if statement is the if variables, h4 tag and the $rows variable. <?php date_default_timezo...
For my rags-to-riches submission, I've decided to improve this code: Text-based RPG game using classes However, I've decided to start off with something different. The original code is more interactive, but mine just runs automatically. I may consider making my code the same, but I wanted to try this first. I think ...