instruction stringlengths 71 95.1k |
|---|
Below is a script I've written that uses AJAX to check if all links on the page are alive or dead. Could this be modified to be more efficient in any way? Thank you very much.
$(document).ready(function() {
var liveLinks = [];
var deadLinks = [];
function updateLive() {
$live = Number($('#liveLinkC... |
Here's some code that removes the specified character, ch, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?
//returns string without any 'ch' characters in it, if any.
#include <string>
using namespace std;
string strip(string str, const char ch)
{
... |
I'm using linear algebra as my basis. One very specific change I'd like to make is to allow for equality tests between points and vectors with an unequal number of components by assuming that all undefined components are zero (all points and vectors have infinite components; equality tests stop testing once a check for... |
I made this Rock Paper Scissors game and I would like for this to be critiqued.
import System.IO
import System.Random
import Control.Monad
import Control.Arrow
data Throw = Rock | Paper | Scissors
deriving (Show, Read, Enum, Bounded)
instance Random Throw where
random g = first toEnum $ randomR (a, b) g
... |
I am writing a program for learning purposes that takes an input of a file structured similarly to:
13,22,13,14,31,22, 3, 1,12,10
11, 4,23, 7, 5, 1, 9,33,11,10
40,19,17,23, 2,43,35,21, 4,34
30,25,16,12,11, 9,87,45, 3, 1
1,2,3,4,5,6,7,8,9,10
Which will then read the values from the file, figure out and print the larg... |
I was asked a question in an interview the other day:
You have an array list of numbers from 1 to 100, the problem is that
one number is missing. How would you find that number?
This is a mock of the question. The code seems to work.
Could you give me some feedback?
private int count;
public void find() {
//pr... |
I am working on legacy code, specifically a sort of BoundedBlockingQueue (mainly used as a pipe between different threads). As it is heavily used in the system and the current implementation features fully synchronized methods and a wait/notify mechanism, I attempted to rewrite it, using the java 5 concurrency utilitie... |
I created small module to help me create rich sendgrid html emails using the mako templating engine. Any feedback on the design would be appreciated:
makosg.py
from sendgrid.message import Message
from mako.template import Template
from mako.lookup import TemplateLookup
class MakoMessage(Message):
def __init__(s... |
I'm working on an exercise where I"m supposed to display all data contained in a table. Here's the solution I can up with:
<?php
$result = mysql_query("SELECT * FROM contacts ORDER BY id DESC");
while($user= mysql_fetch_array($result)) {
echo $user['first'] . " " . $user['last'] . "<br />" . $user[phone] .... |
I want to "canonicalize" URLs for my static (files and folders) website.
The 'Aims' describes what I want to accomplish. The 'Code' gives my current .htaccess.
Everything works right now, but I wonder if the code could be improved:
any changes for better performance?
can some rules be removed?
can some rules be merge... |
This code smells to me, but I don't see the way to clean it up. I see v. mentioned over and over. Any hints would be appreciated!
#
# Create a new Value if it doesn't already exist, and initialize the attributes per
# the parameters of the call.
#
def self.find_or_create_value(prog_id, part_id, round_id, ques... |
The logic is simple, but I was wondering if anyone could help with rewriting the conditional logic. Also, the only error conditions I can think of are the sides should not be equal to or less than zero. Are there any other error conditions that seem to occur to you?
public class TriangleType {
static Triangle getT... |
I'm looking for a good and easy to use solution for creating MultiSelectLists in MVC for many-to-many relationships.
I have this following example code and it works fine, but it just takes a lot of code. It would be cool if it were shorter, smarter, or even made generic somehow, so that it's easy to create MultiSelect... |
I wrote some code to validate a form, I'm using live validation, as the user types, here is the snippet that I wrote just for the live validation, but I think I'm repeating too much and I'm looking for some advices:
$('form input').focus(function(){
var inp = $(this).attr('name');
switch(inp)
{
... |
I have a small function for filtering data from users. I'd like a review on logical mistakes I've made and if I'm somewhat protected using it.
public static function filtru($str, $filtre = []){
if(is_array($str)){//verifica daca datele trimise spre curatare sant array
$str_curat = [];
foreach($str ... |
So I have a function which creates a Playlist object. Currently, this function accepts two paramaters: id and name. However, it also exposes a method called 'loadData' which can set the entire object after construction. I'm realizing this is a poor way to go about things and would like to modify my code such that the c... |
I'm a Python newbie and I'd like to know how I could clean this up/optimize it (but nothing too advanced, please).
As far as I know, it's working as it should, but if you see any errors then please point it out! This is a numerical guessing game with two symbols in front. You can pretty much see how it works by looking... |
I have a class that delegates some responsibilities to another helper class which is abstract. When instantiating the class the user needs to provide a pointer to a concrete instance of the abstract helper class. I'm wondering who should be responsible for deleting the helper class instance, the user, or the class itse... |
Recently I had to lock collections (of type List<T>) when items were added or removed. Because several collections were used in given code instead of creating helper methods for each collection, I made an extension methods:
public static class MyExtension
{
public static void AddThreadSafely<T>(this ICollection<T> ... |
I've got one multimap: mm1 and a map: mm2. The size of mm1 is usually expected to be smaller than mm2. So I begin by iterating through mm1, and for each key in mm1 that also exists in mm2, will print the values of them. e.g. in the following example, first I come up with 2 in mm1, which also exists in mm2; therefor I p... |
I've been learning Haskell, and a while ago I created this Hangman game. I've been working on using a library for terminal output, so no more hardcoded escape codes, but in the meantime I'd like some comments on what I have until now.
Is this readable, correct Haskell code with no obvious performance problems?
The code... |
Below is a simplified version of some code I am using to execute a function after all asynchronous calls complete. Is this a reasonable piece of code? It seems to work. Nothing would break if DoStuff() was called twice, though that would be very inefficient.
var i = 0;
var done = function () {
i++;
if (i < 2)... |
I had to create an executable to search and replace strings in a file. This is to be used in my installer for text file manipulation. I have various placeholders in configuration files that I need to replace with proper values after querying the end user system.
I have written the following code. This being my first re... |
Are there any security vulnerabilities in this code?
class Session {
private $id = array();
private $data = array();
private $name = 'session';
public function __construct() {
session_start();
global $db;
$this->id = isset($_COOKIE[$this->name]) ? $_COOKIE[$this->name] : $thi... |
I'm working on an app that downloads some SVG paths from a server and draws them.
Anything in here is open to critique, but specifically I'd like to review my use of a module pattern and my implementation and use of promise objects.
The "modules" are each a file, and the aim is to limit and explicitly declare depende... |
Ran across this question today:
write a class Tool which will have a function void type() that every
derived class should implement . A function Action() that every
derived class can override . function init() which is available to
only Tool and variable Name which will tell which class`s instance is
this obje... |
I have been looking everywhere to find good real world examples of the new Async and Await features in .net 4.5. I have come up with the following code to download a list of files and limit the number of concurrent downloads. I would appreciate any best practices or ways to improve/optimize this code.
We are calling th... |
I am wondering if in particular the function called AssignDBStatusMessage and TryDataBaseAction are unnecessary. It seems to me that the logic is more cluttered if i do away with those functions. Please provide me with your ideas and thoughts.
If you have other thoughts please let me know.
man is an entity class gene... |
There at least 2 patterns of using Stack.Pop
private Stack<T> availableResources;
...
if (availableResources.Count > 0)
{
resource = availableResources.Pop();
...
}
private Stack<T> availableResources;
...
try
{
resource = availableResources.Pop();
...
}
catch (InvalidOperationException e)
{
...
}
I'd... |
I wrote simple delegate in C++11 for my GUI project. I think that some parts can be optimized or cleaned.
#ifndef DELEGATE_H
#define DELEGATE_H
//Container interface
template<typename... Args>
class IContainer
{
public:
virtual void Call(Args...) {}
virtual ~IContainer() {}
IContainer<Args...> *next;
};
/... |
I'm still trying to learn how to write good tests (and write testable code).
This is the function I want to verify,
void IAutoTisDal.UpdateRange(Range range)
{
using (var repo = _repositoryFactory.GetRepository(_baseline))
{
var rangeqry = from r in repo.Query<Range>()
where... |
I'm new to Erlang and this is my first code in that. As Erlang has no loop statements, the only way I could think of doing this is as follows:
-module(verschickten).
-export([f/0]).
f() -> io:format("~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p ~p... |
I'm making my first steps in ELisp programming and I want to know is there a better solution for this problem:
I have a file with two columns, that are separated by one or more spaces, ex.:
One 1
Two 2
Three 3
Four 4
I'd like to make some alignment (columns are separated by at least two spaces):
One 1
Two 2
Thr... |
I'm currently writing Report's system. I have about 20 different users with different access.
Am I doing it correctly? Can I improve my style of writing this code? All my reports based on the same structure.
In my Report's Controller:
function my_report_name()
{
//current week by default
$dates['fr... |
I have been working with PHP sessions and login protected pages for some time, but I want to start using some AJAX for managing some actions inside login protected pages (easy way with jQuery).
Here is what I want to do:
The user logs in (classic no-AJAX method), and wants to submit a message. I make a request with AJA... |
The basic idea is not to allow the same text and add +1 at the end.
Imagine that I have a datagrid (WPF) with names, and every time I click the add button, I will put a new name on the list automatically by running this method to ensure that no two names are alike.
My standard used: if there is repeated text, add to th... |
My friend wrote a program which compares random arrangements of die faces to find the one with the most evenly distributed faces - especially when the faces are not a mere sequence.
I translated his program into haskell because I've been looking for a reason to talk someone's ear off about how cool haskell is. However,... |
I am taking a data structures course. I would like to check whether my BinaryTree code is perfect, fine or has lots of mistakes.
I would like any kind of advice on this code so I can learn from my mistakes (syntax, techniques, style, etc...).
Note: This is not a binary search tree.
BinaryTree class:
/**
* @uniersity... |
class session{
//variabile folosite
private static $_sessionStarted = false;
private static $_crypt = 'qwerty347658@$%AdfSV045*&erT2Erb%6w!07&[.?;ru';
private static $_salt = 'qwertyAF347658@$%AdfSV045*&erTyUsdfYtrLmncBGhu';
private static $_rand = 'abcdefghijklmnoqprstuvxwz0123456789!@#$%^&*()_-=;:<>,.';
private... |
I've never really done anything with concurrency, so I'm not sure if this is done correctly.
Basically, I have a class that handles all messages from the server and decides what to do them. It uses a separate thread to keep looping through a list to check for any new messages it has to deal with.
The main server thre... |
I would really love to hear your critiques on:
Code quality
Code clarity
More efficient alternative code
Code:
function array_mask(array $source, array $filter){
foreach ($source as $key => $value){
if (!isset($filter[$key])){
if (array_search($key, $filter) !== false){
continu... |
Both unit tests pass and they both test the same thing. The production code uses the right error codes.
System Under Test (SUT)
public interface IRepository {
string GetParameter(int id);
}
public class Repository {
public string GetParameter(int id) {
return "foo";
}
}
public class ErrorInfo{
... |
Inspired by this question, I have a Java Enterprise application running in Glassfish 2.1 and a Java SE client that communicates with the server application.
For this I have a bean that maintains a collection of jobs that is set by the server and the client then asks if his job is in the current list of jobs known to th... |
I've been struggling to get to grips with Joda-Time, but feel that I've finnaly managed to get a grip on some of the functionality that I need.
I have written a function that will convert a DateTime from one timezone to another. I've not done any unit testing on it (but have done my own testing), but would appreciate ... |
I inherited a lot of C code with many ellipsis (variadic) functions.
I have a lots of API with the following signature:
void getXY(int foo, ...) // many parameters
and this is used in this way as usual:
getXY(1, "sizex", 12, "sizey", 24, 0);
Now I started to think about how I can replace it with a typesafe C++ API, a... |
I have a pretty common issue: I need to know the name of current user and also name of the current controller so I can highlight/disable some links.
Here's some solutions I found by myself:
Get all what's needed inside PartialView.
I have a PartialView inside my page layout, that takes user name like this:
@{ var user... |
I wrote some code in Flask for site menu:
def menu(parent_id=0, menutree=None):
menutree = menutree or []
cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord>0 order by ord')
fetch = cur.fetchall()
if not fetch:
return None
retur... |
I wonder how could I simplify the code below? Please note that it's not allowed to use instance variables here for some reason.
private bool ValidateQueryString(NameValueCollection queryString, out byte[] errorMessages)
{
var errorsList = new List<string>();
int _aId;
... |
I have written a caching wrapper method for some of my services. The actual wrapper method is written as follows:
public T GetFromCache<T>(string key, Func<T> defaultValuePredicate, object cacheLock, TimeSpan duration)
{
lock (cacheLock)
{
var result = _cache[key] is T ? (T)_cache[key] : default(T);
... |
I'm writing a script that:
fetch a list of urls from a db (about 10000 urls)
download all the pages and insert them into the db
parse the code
if(some condition) do other inserts into the db
I have a Xeon quad-core with hyper-threading, so a total of 8 thread available and I'm under Linux (64 bit).
I'm using cStringI... |
I have a simple text file setup as a Resource through my application's Properties as a byte[]. In order to access a "Stream.ReadLine" function, I believe I need to make it into a StreamReader. Is there a way to get the following result using only 1 Stream, or else, any tricks to make it better?
List<string> list = new ... |
I have a string, where I am only interested in getting the numbers encapsulated in single quotes.
For instance if I have the string "hsa456456 ['1', '2', ...]
I only want the 1 and the 2 and whatever numbers follow
To do this, I have the following code:
import re
#pattern = re.compile("dog")
#l = re.findall(pattern, ... |
My User model has multiple roles (utilizing CanCan). Each role's dashboard view is different enough to warrant a partial for each role (admins get big-picture reports of users and app activity, students get big-picture overviews of grades, current courses, and lessons to be taken).
At first I had a case statement to it... |
I have two scripts written by my co-workers for auto-filling a form with information from the Facebook graph-api. I am trying to figure out which has been coded in a more efficient style?
This is the first one. http://jsfiddle.net/TcGGZ/30/
$('#account_get').click(function(){
$.getJSON('http://graph.facebook.com/'+... |
Given an array of words, print all anagrams together. For example, if
the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
may be “cat tac act dog god”.
My idea is to sort individual words firstly. And then sort the array of words.
In this way, the anagrams will be together. The following is my cod... |
start:
try
{
oleDbDataAdapter1.Fill(myDataTable);
}
catch (Exception ex) {
DialogResult res = MessageBox.Show("Can't load data:\n" + ex.Message, "Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (res == DialogResult.Retry)
{
goto start;
}
}
Is it ok to use goto oper... |
Here is a problem from the book Programming Challenges by Skiena and Revilla:
The Trip
A number of students are members of a club that travels annually to
exotic locations. Their destinations in the past have included
Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta.
This spring they are pla... |
I have a function in App Engine Java where I compare two patterns stored in an int array:
public static int patternMatch(int [] pattern1, int [] pattern2, int range) {
int max = range * pattern1.length;
int match = (pattern1.length - pattern2.length) * range;
for(int i = 0; i < pattern2.length; i++) {
... |
I've created a create a console app that would:
Call a method to check an email account (I've done this step)
Convert the attachment to pdf (I've done this step)
Then once the conversion is complete wait 30 seconds
Repeat the previous 3 steps continuously
I've done Step 1 and 2 int the ProcessMailMessages() method.
... |
I have the following concise-ish (and working) approach to getting all the forward permutations of a list of string. So with the list:
w = ["Vehicula", "Sem", "Risus", "Tortor"]
the results should be:
['Vehicula', 'Vehicula Sem', 'Vehicula Sem Risus', 'Vehicula Sem Risus Tortor', 'Sem', 'Sem Risus', 'Sem Risus Tort... |
I have a Customer class:
public class Customer
{
public Guid Id { get; set; }
// Some other properties...}
And three transactions classes that have a reference to Customer:
public class Order
{
public Guid CustomerId { get; set; }
// Some other properties...}
public class Invoice
{
public Guid Cu... |
I have a class that has a method which takes a user as an argument and performs several validation checks on the user and returns a boolean to indicate if theyare valid.
I want to be able to get error messages back from the validation method along with the boolean return value.
I was thinking of doing it by passing a... |
This program will filter the input by replacing matching bad words with "Bleep!". I'd like the code to be more concise and C++ style where possible. One thing that bugs me is the was_bad flag I think is needed to skip printing a word that has matched one of my bad words - if there was some better way to skip the rest o... |
I am a self-taught programmer who has been programming for a long time, but mainly just for personal projects. I would like to improve my skills and am open to any suggestions that you may have, but am particularly interested in your thoughts about:
The number of methods in this class: Too few/too many?
Method/varia... |
The following is my code for printing all the substrings of an input string. For example, with "abc", it would be "a","ab","abc","b","bc","c". Could someone please review it for efficiency (and possibly suggest alternatives)?
void findAllSubstrings(const char *s){
int x=0;
while(*(s+x)){
for(int y=0; y<... |
I use some basic cryptography in a project of mine. Because I want my application to run cross-platform and because it seems pretty sophisticated I decided to go with the Java Cryptography Architecture.
I'm pretty fresh with crypto in general, so I'd like to hear someone's opinion who has some experience with that.
Fir... |
This function runs very often. cudaMemcpy is at the start and works very slowly. How can I change this function to avoid this? I already have inputs in device memory.
void OpenNNL::calculateNeuronsOutputsAndDerivatives(double * inputs, double * deviceOutputs, double * deviceDerivatives)
{
int inputsCount = _inputs... |
I'm trying to write a portable CMake script for a simple Qt application. The target platforms are Win and Mac OSX. But as you can see, it's quite a monster already.
Are there any CMake profs? Can you see any essentially wrong approaches used in this script? I bet there are a few.
CMAKE_MINIMUM_REQUIRED( VERSION 2.8.6 ... |
I am using this query to generate a conversation stream between user 184 and 192-
SELECT events.event_time, messages . *
FROM events , messages
WHERE events.global_id=messages.global_ref_id AND
(messages.to =184 AND messages.from =192) OR
events.global_id=messages.global_ref_id AND
(messag... |
I've made a python script to properly organise D&D monster stats in a directory. The script brings up the stats as instance variables of a Monster (class) instance.
For those unfamiliar with the game, keeping track of monsters (to me at least) is cumbersome and prone to many dead trees. You have to flip through the Mon... |
I just started coding in Objective-C and would like to know if my simple implementation of a Stack is acceptable & what ways would you improve the Stack code, or the Main code? i'm curious of things such as (but not limited to):
formatting
edge cases
run time (like one part where try to manipulate strings in descripti... |
I have a project for solving Diophantine equations, where a solution exists if
$$A^5 + B^5 + C^5 + D^5 + E^5 = F^5$$
where \$0 < A <= B <= C <= D <=E <= F <= N\$
The program will take an input N and first generate all values from 1 to \$N^5\$. Then it will get all possible sum values of \$A^5 + B^5 + C^5\$ and store th... |
In java.util.Random the Oracle implementation of nextInt(int) is as follows:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
... |
I would love to hear feedback on my first open source project (a very simple async API for Mixpanel).
It implements a REST client for this REST HTTP API.
Review requested on the following aspects:
Code style (formatting, naming etc...)
Code quality (best practices, performance etc)
Asynchronous aspects (usage of Exec... |
In C#, passing a parameter by reference can't be ignored:
// C#
void foo(ref int p_value) ; // passing an int by reference
void bar()
{
int i = 0 ;
foo(ref i) ;
}
In C++ (and as far as I am concerned, it is a good thing), the passing by reference is only marked in the function prototype, so the code above becom... |
I'm new to Zend Framework. Can you help me optimize this function, which gets a list of Manufactures with some conditions from a database?
private function Manufactures(
$Condition = array(),
$Order = array('name' => 'ASC'),
$Strict = TRUE,
$Limit = NULL)
{
$Request = $this->_DbTable->select();
... |
I rarely write multithreaded code, and am on shaky ground when doing so. I make mistakes. I would like a sanity check of something I am going to introduce in one of my apps.
There will be exactly one running instance of the Thread class below in my application. (It will be stored in a servlet context attribute.) "C... |
Is there a way to improve this SQL query? It involves multiple cross join and joins.
I have 3 tables, and I want to compute the cardinal product:
table N:
N
-
4
table sums:
i S
-----------
1 22
2 26
3 22
table mults:
i j M
-------------------
1 1 122
1... |
I'm doing Project Euler problem 5 as a kata, focussing on TDD and code readability. The challenge is:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
For reference, a "less-readable" solution that reeks of goto was something along these lines:
public int Solution_Got... |
I've recently had to print some national symbols in windows console using Mingw and found, that I got nothing in the output, if I use wide strings.
So, I studied the problem and found out that it is locale problem. I was unable to find somewhere complete solution, so I had to write something, that seems to work.
So, I... |
I am writing a simple-ish c# CLI app to improve our telephony reporting system.
At present, I have a nightly DTS package which dumps a couple of tables from the Cisco telephony box into a database on our corporate cluster. An hour later, I have a SQL Server Agent job that runs a variety of messy stored procedures to g... |
The following is code from a university practical I am doing. It reads in a txt file of twenty clients, whose information is stored in the txt file like this:
Sophia Candappa F 23 00011
As per my lecturer's instructions, I have stored this information in a class called Client (although I know an ArrayList would ... |
I recently started game development, but one of the things that I never put much thought to was the loading of images. I'm curious as to advice for improving my current code on loading images. I'm using cocos2d in iOS code, but if you know of optimization techniques in other languages I'd like to hear that as well.
//a... |
First off, I will try to explain the problem and then I will show you the code I have come up with so far.
I've got a list of properties. Each property has a tag of type int and a value of one of the following types: (bool, string, int, long).
some sample properties:
tag: 1, value: "some string"
tag: 14, value: true... |
I need some guidance on making the following code more idiomatic:
(ns cheaterpress.algorithm
(:use [clojure.string :only [split lower-case]])
(:use [clojure.test]))
(def words (split (slurp "words") #"\s"))
(defn string-to-letter-hash [string]
(loop [letters (seq string) letter-hash {}]
(if (empty? letters)... |
Please help me check the correctness of this c# iterative implementation of negamax! Thank you! Your help highly appreciated! Also, please help me out how to add alpha beta pruning to this(it was supposed to be alpha beta with negamax, but i forgot the alpha beta part... :<)! Thanks in advance!
EDIT: I DO think that th... |
I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.
Is there any way to get around that? I don't know how to give them all the unique ID.
<div id="nav">
<ul>
<li id=... |
In my C# program, I have a class defined as follows:
public class DbResult
{
public bool bSuccess { get; private set; }
public String Message { get; private set; }
private DbResult(bool success, string message)
{
this.bSuccess = success;
this.Message = message;
}
public static ... |
Given an array of words, print all anagrams together. For example, if
the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output
may be “cat tac act dog god”.
The following is my c++ code. I use raw pointer to implement varying number of children
for practice. Actually, I guess maybe it's better to adopt... |
This is my code that works:
foreach (var r in rlist)
{
if (r.IndexOf("_") != -1)
{
int id = int.Parse(r.Split('_')[1]);
var x_tmp = (from x in db.tblX where x.x_id == my_id && x.x_id == id select x).First();
x_tmp.order = someNumber;
}
}
db.SaveC... |
I've created a logging system with one-use passwords (sent via SMS API). What I would like to know is if it's "safe". I know it is hard to estimate safety but I am curious if it is safer than regular password. I would appreciate any advice to improve following code.
Scheme is:
Logging:
Loggin at a webpage -> Ask extern... |
I have some experience with PHP but I have never even try to do this wit pure PHP, but now a friend of mine asked me to help him with this task so I sat down and write some code. What I'm asking is for opinion if this is the right way to do this when you want to use only PHP and is there anything I can change to make t... |
I've used the Trie data structure to solve the following problem:
Given an array of words, print all anagrams together. For example, if the given array is {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god".
The following is my C++ implementation which can accommodate varying number of child... |
How can I combine these if statements to make this a little cleaner and be less repetitive?
$(document).keydown(function(e){
if (e.keyCode == 38) {
if($html.hasClass('client-loading') || canAnim === false) {
return false;
}
var $prevProj = $('.project-current').prev('.project');
... |
I run a small server, and to check whether clients are being hosted on my server, I wrote this. I'm new to object oriented programming. How stratified should my programs really be? Do I want to have every possible variable and piece in their own function? Also, how am I doing in general? Any recommendations?
class D... |
I wrote a little code to list a number's prime factors:
import java.util.Scanner;
import java.util.Vector;
public class Factorise2
{
public static Vector<Integer> get_prime_factors(int number)
{
//Get the absolute value so that the algorithm works for negative numbers
int absoluteNumber = Math.... |
I am not a DBA nor do I play one on TV.
My application is retrieving information from Facebook and storing it into our own database. I want to retrieve the Location Post information of Id and AuthorId. AuthorId is a foreign key to another table. I was told by a DBA that foreign keys should always use internal uniq... |
I'm evaluating a meeting_type value that determines what kind of pricing structure I should be using. Currently, if my meeting_type value is a w, we charge one price for every 10 registrants. If the meeting_type is anything else, it's a price per registrant model.
I'm using this logic:
if($_POST['meeting_type'] != 'w'... |
I'm looking for advice and ways on making it better.
Code
<?php
Class Validate {
private $_errors = array();
public function __construct()
{
require_once 'errors.php';
$this->errorText = $errorText;
}
public function rule($value, $name, $inputRules)
{
$inputRules = e... |
This is a start on a multi-threaded game loop and I just wish to confirm my code is going in the correct direction, and if not, if there is any way it can be improved. I have good experience in game development and C++ in general, but limited experience when it comes to multi-threaded environments.
#include <iostream>
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.