instruction stringlengths 71 71.9k |
|---|
I am playing with different ways to do database interaction in PHP, and one of the ideas I have been playing with is connecting to the DB in the constructor and disconnecting in the destructor. This is the code from my Database class.
function __construct()
{
$this->link = mysql_connect($this->server.':'.$this->port,... |
I'd like suggestions for optimizing this brute force solution to problem 1. The algorithm currently checks every integer between 3 and 1000. I'd like to cut as many unnecessary calls to isMultiple as possible:
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum... |
Basically, I had written this class a little while ago to ease autoloading of our local libraries.
The premise is that everything is split by packages into multiple layers of sub-packages. Classes are named using CamelCasing. So, a class' name is related to its package as follows: PackageSubpackageSubpackageName. N... |
I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write ... |
I have a method that has a lot of loops:
private void update(double depth)
{
Console.WriteLine("update with level " + depth);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{
List<Grid> grids = new List<Gri... |
I use CodeIgniter at work, and one of our model files had a lot of subqueries in it. I originally had to manually write each subquery, and wondered if I could use active records instead.
So, to make my life easier, I made a subquery library for CodeIgniter.
I put it on the CodeIgniter Wiki, but I never really had any ... |
So I've had a problem where I need to compare data in 2 different tables on two different servers. Now, I know MySQL supports CHECKSUM TABLES, but from my testing and understanding, it's not reliable across server instances and versions.
So I created this query:
$part = '@CRC := MD5(CONCAT_WS(\'#\', COALESCE(`'.
... |
A while back, I reverse-engineered a checksum algorithm from an MMO used to check the validity of an item that's linked to chat (similar to WoW). The idea is that if the checksum is invalid then the game client would ignore the link when clicked. Otherwise clicking on the item link in in-game chat would display the sta... |
I'm generating CSV strings for various 3rd party utilities and this section of code gets repeated in many classes. Is there a better way to generate this string?
public override string CsvString()
{
return (
string.Format("\u0022{0}\u0022,\u0022{1}\u0022,\u0022{2}\u0022,\u0022{3}\u0022,\u0022{4}\u0022,\u002... |
A few functions to let me manage TAGS files more easily. Typically, my projects contain at least one sub-folder. I got sick of manually updating, so I wrote this to help me update a single TAGS file per project (always in the projects' root directory).
Please share your thoughts (aside from "Why are you using Emacs?", ... |
This shows a test case for an old caching library that I use for a project. It features simple save/load/delete functions (sadly static calls) but what I want to focus on is the test code written for this class.
In my opinion the unit tests for a class should show how all functions in the class work and what to expect ... |
I am currently developing a custom CMS being built on top of Codeigniter and was wondering if you can spot any flaws in my page fetching model code. The page fetching model is not entirely complete but the main functionality for retrieving a page is done, as well as retrieving modules assigned to a page (a module is re... |
Here's my bootstrap.php for my PHP/MySQL/Doctrine app. It's my first PHP app so I'm interested in learning from the experience of others how this could be improved - security-wise, performance-wise, or otherwise.
//-------------------------------------------------------------------------
// Define global constants
def... |
I'm making a "guess that tune" game in Visual Basic 6 that is supposed to play each song in a random order:
' from frmGuessGame.frm
Private Sub Swap(ByRef Value1 As Variant, ByRef Value2 As Variant)
Dim Temporary As Variant
Temporary = Value1
Value1 = Value2
Value2 = Temporary
End Sub
Private Sub ShuffleList()
Dim Loo... |
I implemented the Shamos-Hoey algorithm to check if a closed shape is self-intersected. Is this algorithm ok in terms of performance?
public boolean isSelfIntersected() {
Set<Line2D> plines = new HashSet<Line2D>();
for (Path2D ps : this.getPath()) {
PathIterator p_it = ps.getPathIterator(null, /*flatnes... |
I've implemented a PID controller, but seeing as I'm not an expert in control theory, have I missed any edge cases?
public class PIDController
{
public enum PIDMode
{
Manual,
Auto,
}
public enum PIDAction
{
Indirect,
Direct,
}
public PIDMode Mode { get; set;... |
This plugin is written in jQuery and is made to support the codeigniter framework. It is an ajax powered table pagination plugin designed to provide only that. You should be able to use almost any other table scripts with this plugin.
(function($){
$.fn.extend({
tpaginate: function(options) {
/... |
Is this the best way to implement this pattern in C#?
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
|
I'm listing elements with a foreach, and I would like to enclose items in something tag n by n:
$i = 0;
$open = $done = TRUE;
$n = 3;
$opening = "<div>";
$closing = "</div>";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff");
foreach($names as $name) { /** $condition was not a bool. My fault. *... |
I was wondering for quite some time how to clean up the below code without blowing it up any further. The extension of the classes is the main concern here, it looks a bit too much like magic. That's mainly because it has to handle all the different cases, and I haven't figured out a way to reduce the code in a meaning... |
I'm new to Postgres and PostGIS, but not to geospatial applications.
I have a table loaded up with graph data in the form of links (edges). The link database has about 60,000,000 rows. I am trying to extract the nodes to allow for quicker searching. For some of my proof-of-concept work I was able to use the link table ... |
I have written a method to tokenize HTTP request paths such as /employee/23/edit:
protected void compile(String path){
int mark=0;
for(int i=0; i<path.length(); ++i){
if(path.charAt(i)==DELIM){
if(mark!=i)
tokens.add(path.substring(mark,i));
mark=i+1;
}
... |
I have written this (truncated) code to fetch some tweets:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *JSONStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://search.twitter.com/search.json?q=haak&l... |
I have a Perl application that allows the user to choose between two different formats for data output (and there will likely be more in the near future). In the heart of the algorithm, the code makes a call to a print subroutine.
my $stats = analyze_model_vectors( $reference_vector, $prediction_vector );
print_result(... |
So I have a series of objects, which I will call Impl1, Impl2, and Impl3. They each implement an interface, called IImpl. I have a Factory class who's task is to retrieve the ImplX which is appropriate for a given circumstance, and pass it on to its callers. So the code in the factory looks like:
public IImpl GetIns... |
Inspired by this question, but hopefully not a duplicate.
I understand that the Law of Demeter is very useful in case of services interacting with other services, for example it's much easier to mock the other services in unit tests.
What about services interacting with data models, though?
Let's say I have a hierarchy... |
Would this function be sufficient enough to remove all malicious code and foreign characters from a string?
//Clean the string
$out = ltrim($do);
$out = rtrim($out);
$out = preg_replace('/[^(\x20-\x7F)]*/','', strip_tags($out));
This data is not going into a SQL database, so I dont have to worry about sql injection a... |
I don't like the fact that I am selecting all the points, even though I only care about the count of them.
Which of the from parts should appear first, if it even matters?
var count = (from type in ValidTypes()
from point in GetData(type)
where point.Radius > referencePoint.Radius
&& point.Theta > refer... |
This is a function I wrote yesterday and have tested with lots of input. It's been committed and is in use, but no review was done, so it seems like a good candidate for Code Review: it could be more readable and maybe refactored into simpler functions.
Its purpose is to give the longest common path and a string listin... |
I do most of my programming in C/C++ and Perl, but I currently learning Fortran. I began by coding up a simple program, something that took me < 5 minutes in Perl (see this thread from BioStar). After working for several hours on a solution in Fortran 95 (teaching myself as I go), I came to this solution.
implicit none... |
It's a little bit more code but I wanted to show the full class. I highlight the points I'd like input after the source.
I've cut comments since they where not in English and translated the important ones.
The class is inspired by PearDb (too old) and Zend_DB (to cluttered / unfinished at the time) and is used in a inh... |
I want to have fast cache in which I want to keep all my nomenclature data.
I don't want to go with Memcached because I have to do serialize/de-serialize on each object which is slow.
So I choose to be less effective in memory and keep the cache in each server instance.
I am sure I am doing it in the wrong way because ... |
I'm working on a personal project to keep different snippets/examples/small projects of mine organized. I want to make the most of my page width, so I decided to write a navigation menu that slides out. It works as expected, but the code is kinda big.
I provided the HTML/CSS just in case that helps, but I'm really only... |
I have a class with quite a few attributes, most of which are known when I create an instance of the object. So I pass all the values in the constructor:
$op = new OpenIdProvider($imgPath . $name . $ext, 'openid_highlight',
0, 0, 108, 68, 6, $info[0], $info[1], $name);
I'm finding that havin... |
I installed settingslogic and in the configuration file I put the regex for the email as follows:
#config/settings.yml
defaults: &defaults
email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
development:
<<: *defaults
# neat_setting: 800
test:
<<: *defaults
production:
<<: *defaults
That I load in de... |
Is this code good enough, or is it stinky?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DotNetLegends
{
public class LogParser
{
/// <summary>
/// Returns a populated Game objects that has a list of players and other informati... |
Note: This file is out of my hands. I cannot change the format or type of file I have to parse.
Here is some sample data that I'm trying to parse. This is information for just one player:
[0] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8
_profileIconId = 4
elo = 0
... |
The code below is a plugin I wrote for Ext.grid.GridPanel, which basically allows you to have a bit more control over how rows are striped in the grid. By default you can only have every other row in alternate colour. With this plugin you an have for example 5 in basic color, 5 in alternate and so on.
What bothers me a... |
Here's a class I'm designing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace Artworking.classes
{
// A group permission level
public class PermissionGroup
{
public int ID; // Unique ID ... |
In this question I answered with this Linq. While it does what I was looking for, I am not sure how easy the linq queries are for others to follow. So I am looking for feedback on formating, what comments would be helpful and other alternative approaches to moving through the children records.
private void UpdateGr... |
This is performance critical. I measured and determined that using the sqrt is faster then using the cos method.
I am aware that this code only works for some points, so that is not an issue.
Point is System.Drawing.Point. _offset is also of type Point.
I assumed, and the profiler seemed to confirm, that the try/catch ... |
I am unsure if my use of Monitor.Wait and Monitor.Pulse is correct. It seems to work alright, but there is a nagging doubt I am doing something wrong.
Am I dealing with a timeout OK, or is there a better way to do it?
All examples I have seen use Monitor.Wait with a while loop, and not with an if to re-check the blocki... |
Imagine that I need a color palette for my Winforms application to have a consistent look.
What I did was create a static helper class and helper methods that I can call from anywhere in my code, and invoke what I need from the App.settings file.
Here for example, I am getting the school name from the App.config file, ... |
I'm learning Django as I go. I know this model is missing user authentication, registration, comments/comment threading, and voting. But this is my starting code for my model. What are some of the things I can improve on, modify, rewrite, etc?
from django.contrib.auth.models import User
from django.db import models
fro... |
I've recently assembled some jQuery that allows a user to build out a bulleted list in MS Word with hyperlinks and turn that into a HTML unordered list. Ideas for uses are website menu systems where the user may not have a clue about HTML. You can also extend this with jQuery UI plugins for effects. Looking for edge ... |
I'm looking into Administration Elevation and I've come up with a solution that seems like it's perfectly sane, but I'm still in the dark about the professional methods to accomplish this.
Is there a better way to do this or is this fine?
using System;
using System.Diagnostics;
using System.Security.Principal;
using S... |
I have a database class that in __construct() initialize a PDO connection and insert the instance into a $db private var.
Now i'm working on a method that can be used to query in this way:
$db = new db;
$db->query(array(
'select' => 1,
'from' => 'table',
'where' => array('id' => 1, 'name' => 'charlie'),
'limit' => ... |
I found that in PHP (or I probably can't find it) a proper is_numeric_array($array) function is missing. So I created one. The problem is that I don't think it's great and I don't know how to improve it.
Any suggestion?
My first function
function is_numeric_array($array)
{
$i = 0;
foreach ($array as $a => $b) {... |
I want to get empty string or the string value of the object
Which code you will use and why?
value = object.to_s
or this
value = object.nil? ? "" : object
|
This is part from an answer to a Stack Overflow question. The OP needed a way to perform calculations on samples from a population, but was hitting memory errors due to keeping samples in memory.
The function is based on part of random.sample, but only the code branch using a set is present.
If we can tidy and comment... |
The requirements for this one were (original SO question):
Generate a random-ish sequence of items.
Sequence should have each item N times.
Sequence shouldn't have serial runs longer than a given number (longest below).
The solution was actually drafted by another user, this is my implementation (influenced by random... |
I got this as an implementation of "get me the median of those values". But it sort of doesn't feel right (too long, too many branch points) so I thought I'll post it here to see what you think.
<?php
private function calculateMedian($aValues) {
$aToCareAbout = array();
foreach ($aValues as $mValue) {
i... |
According to the Doctrine docs, you should use Array hydration rather than record hydration when retrieving data for read-only purposes.
Unfortunately, this means I have to use array syntax (as opposed to object syntax) to reference the data.
$q = Doctrine_Query::create()
->from('Post p')
->leftJoin('p.PostComm... |
I was trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently.
Would you please review it, and suggest any improvements/issues you find?
(Cross-post from StackOverflow)
import java.util.concurr... |
In our production code, we cannot use Boost or C++0x. Formatting strings using sprintf or stringstream is annoying in this case, and this prompted me to write my own little Formatter class. I am curious if the implementation of this class or the use of it introduces any Undefined Behavior.
In particular, is this line... |
I'm creating some sort of "portfolio" website for my self (a ton of placeholder content right now...) and I was wondering if I could improve the semantics of the HTML5 any further, especially the article stuff.
I'm not completely sure if I should use section elements inside it. I read through a number of HTML5 "guides"... |
How can I clean this up?
std::wstring LinkResolve::ResolveLink( const std::wstring& source ) const
{
HRESULT errorCheck;
wchar_t linkTarget[MAX_PATH];
wchar_t expandedTarget[MAX_PATH];
wchar_t arguments[INFOTIPSIZE];
ATL::CComPtr<IPersistFile> ipf;
errorCheck = ipf.CoCreateInstance(CLSID_ShellLink, 0, CL... |
I'm trying to design a well defined yet simple interface for the unit of work and repository patterns. My UoW's are exposed to services and services then "get repositories" that it needs to query. I know returning IQueryable<T> for repositories is a religious war. Because repositories are only exposed to the service, a... |
I've got a flat array of < 1000 items and I need to find the indices of a smaller tuple/array within the array. The tuple to find can be a varying length (generally between 2 and 5 items, order is important).
This is my initial naive implementation. My main concerns are:
This seems like a CS 101 problem, so I'm p... |
Similar piece of code to that I recently posted as:
Resolving a link
I have another piece of code which cannot be as easily extracted out into a method:
#define THROW_LAST_WINDOWS_ERROR()\
WindowsApi::Exception::Throw(::GetLastError(), __FILE__, __LINE__)
#define THROW_MANUAL_WINDOWS_ERROR(x)\
WindowsApi::Exc... |
void removeForbiddenChar(string* s)
{
string::iterator it;
for (it = s->begin() ; it < s->end() ; ++it){
switch(*it){
case '/':case '\\':case ':':case '?':case '"':case '<':case '>':case '|':
*it = ' ';
}
}
}
I used this function to remove a string that has any of the f... |
This is some of the code I have:
[window setLevel:kCGScreenSaverWindowLevel];
[window setOpaque:NO];
[window setStyleMask:0];
[window setBackgroundColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.3]];
[window setAlphaValue:0];
[window setFrame:[window frameRectForContentRect:[[window screen] frame]] display:YES ani... |
I have created this code for user error logging, and I am wondering if there is anything that can be improved. The point is that this error handler would ONLY catch user errors created in-code by trigger_error(), and would display, log, and/or email the error, depending on the config settings. The error logging class i... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5