instruction stringlengths 71 95.1k |
|---|
first here is the code:
Part 1
$('#monhpf').keyup(function()
{
/* General variable(s) */
var monhpf = $('#monhpf').val();
if(monhpf=="")
{
$('#monhpf').css('border-color',red);
$('.mondayErrors').text(emptyField).show();
}else
if(mo... |
The application needs to keep a secret which is known to logged in windows user. User enters secret in windows form's text box which is read by application. This is in form of System.String. Now I have to persist this secret into a XML file. And later able to decipher it back and use it.
Questions:
Do you see any conc... |
I'm working on a config class for PHP, where I can easily bring in config options. Any improvements/suggestions are appreciated.
Example usage:
echo Config::get('database.host');
// Returns: localhost
Example config file:
<?php
return array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
... |
After a week of searching and testing each approach via Stopwatch,
I came to this method using the fastest way possible to capture screen into a bitmap and then to a byte[].
Is it possible to make it any faster using parallel features or any idea I have not taken into account? (As I am a newbie, 4 months of self lea... |
I am setting a few vars in JavaScript. I typically like to make my code really readable so that it's easy to go back and edit. I have a few questions about the code below:
1) Is this is a good way to break up the setting of the vars? The comment seems redundant, but it seems to really help break up the code into rele... |
I'm new to iOS development and I'm having trouble figuring out how to efficiently load my app's data at launch time. My app consists of a UITableView that is populated with a list of songs. Each cell displays data about the song: current user rating(if rated) and avg. user rating (avg. rating of all users). I'm using P... |
My logger posted below makes use of condition variables in order to notify the "flusher" thread that new items are available. The notification occurs every time a message is logged.
My questions are:
If the notification immediately follows the log action then does that mean that the queue will only contain one element... |
I am using jQuery 1.7.2
I have two ways of writing the same code. One way seems more verbose and the other seems more flexible. Is this the only difference? Is there any performance difference? Is there a better way of writing these?
Code sample #1 uses two named functions so they are reusable. It's a bit more code.
Co... |
The goal of this question:
Your goal here is to find a security hole in my code which allows a user to create input that contains a script doing anything they want, without that script being stopped by my code.
Please bear in mind that that is the ONLY goal of this post. I am not so much here to talk about how good the... |
Did I write this code to correctly be tail call optimized? Am I forcing computations more than I need with !? Did I generally write this asynchronously correctly to allow sends and receives to occur in their own time? Is this using multiple threads needlessly? Other general critiques?
open System
open System.Net.Socket... |
I am working on asp.net/MVC and I need to read a value from my web.config file. Splitting the list into multiple keys is not an option.
<add key="DepartAssign" value="Depart1:PersonAssignTo1; Depart2:PersonAssignTo2"/>
I handled the problem by doing the following (which I am sure that there is a better approach)
publi... |
I would like a review on this code, and how I could make it better.
#include <boost/bind/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <boost/thread/thread.hpp>
#include <boost/signals2/mutex.hpp>
#include <stdint.h>
#include <iostream>
#include <vector>
class C... |
I have a simple cache service that i am using inside my WPF prism application, i am concerned about the thread safety of it - we will be accessing this via multiple threads and using the current code it has started deadlocking, it works fine without the locks but obviously this is not acceptable.
How can i go about imr... |
I have this piece of code I developed but it doesn't look efficient to me, can anyone improve it please.
private void AddToDataBase(SPItemEventProperties properties)
{
DataAccess DA = new DataAccess(ConnectionString());
DetailsRow result = DA.GetDetails(properties.WebUrl);
if (result != n... |
I'm rather new to Clojure and so I decided to program a Connect Four for fun and learning.
The code below is a Clojure implementation of this bitboard algorithm.
The whole code can be found here: https://gist.github.com/3639220
What I'm unsure about are the functions (insert) and (bit-check-board):
(defn insert
"Inse... |
I don't write too many bash scripts and I can usually struggle my way through getting the odd thing I need working, but my scripts always seem to feel a bit brittle. Below is a script I wrote for adding trusted timestamps to commits in a Git repository. I would appreciate any feedback on ways I could improve it.
#!/b... |
I want to refactor my code but I can't find and much simplier one. Can you please suggest on how to refactor the code below without using a loop? maybe using only array functions? TIA
<?php
$week_no = array(2,3,4);
$days = array('TU', 'WE', 'TH');
foreach ($week_no as $n) {
foreach ($days as $d) {
$out[] = $n . ... |
How can I make this code snippet be improved to become more professional?
(function($){
$.fn.showMenu = function(options){
return this.each(function(){
$this = $(this);
var high = $this.outerHeight(),
scrollHeight = $this.get(0).scrollHeight;
$this.bind('mouseenter',functio... |
I'm working on a feature for the HamlPy (Haml for Django) project:
About Haml
For those who don't know, Haml is an indentation-based markup language which compiles to HTML:
%ul#atheletes
- for athelete in athelete_list
%li.athelete{'id': 'athelete_{{ athelete.pk }}'}= athelete.name
compiles to
<ul id='athe... |
I've been learning Python for about a year and now I'm trying to improve my JavaScript. I wrote this simple d3 visualization that shows your Facebook friends as a force-directed graph. Here's a live version and here's the source on GitHub. It works well, but it can be slow.
I understand that the number of edges to calc... |
I have to read in a file full of ints, print them in reverse order, and then calculate the median and the mode of the set.
At first I struggled with figure out a way to calculate the mode. It seemed so simple but I just couldn't translate the steps into code. I did come up with a solution and it works but because of my... |
I am posting the a section of the model of my application.
Any/all feedback would be very helpful as I am trying to build my PHP skills, but I will ask a couple specific questions that might help others as well.
Is my escaping, as is, effective enough?
I tried to separate my model into a file that will deal with fun... |
I am developing a WinForm application that extracts data from our database and draws a tree like structure on the form. For the users to get a better idea of how the data is structured.
The database is designed in such a way, that data looks like tree structures. Based on that I can fetch the data and draw the tree str... |
I wrote this little script in PHP a bit ago. It takes a .csv file and outputs a .txt file with certain data arranged in a "psuedo-array" looking format. I recently started messing around with Ruby so I decided to redo it. It wound up essentially as an exact translation, though.
Is there a simpler / more Ruby way to do ... |
I'd like your opinion on something. I have the following class:
public class ApplicationClock
{
void tick(object _)
{
lock (tickLock)
{
try
{
MessageBroker.Publisher.Publish(new Tick());
}
catch (Exception e)
{
... |
I haven't done Java coding in years, but I thought I would give it a shot for a job interview. I have a few questions:
Why is this error handling considered poor? How am I supposed to be doing it?
What error catching should I be doing in a finally clause?
How am I masking exceptions?
package jGet;
/**
* Problem
* ... |
Currenty coding a PHP script that will have a CRON to auto run it.
The point is that it checks the user in Mysql and if it has expired, it will delete it from the admin table and set status to expired.
I have used time() and then when it gets INSERT When his trial starts, it starts for example "1347054850" in the "Star... |
My original code is:
let (upPosition, downPosition, leftPosition, rightPosition) =
match myMove.MyDirection with
| Direction.Up -> (GoUp y, y, GoLeft x, GoRight x)
| Direction.Down-> (y, GoDown y, GoLeft x, GoRight x)
| Direction.Left -> (GoUp y, GoDown y, GoLeft x, x)
| Direction.Right -> (GoUp y,... |
I realised that what I was doing wasn't particularly smart, so I switched to a different approach. This costs more dynamic allocations but has a much simpler implementation:
#pragma once
#include <boost/utility.hpp>
#include <set>
#include <map>
//! A map of types to values.
//!
//! Associative container which allow... |
I've written a project for handling various Facebook things and I ran into the issue where one project named the users profile Profile while normally they would be named UserProfile. When I was checking if the FacebookUser model was related to a User, I could just User.objects.get(userprofile__facebook=facebook_user) ... |
Please review for any unnecessary casting, memory leaks, wrong use of pthread call, or validation problems in the given code.
/**********************************************************************
* FILENAME :thread_1.c
* DESCRIPTION:Contains Code for a program that demonstrates the
* use of pthread ... |
I'd like to hear some thoughts on my simple anagram finder, written in Scala. I mainly wrote this as a first go at writing some serious Scala, and I wanted to try out the Scalaz library.
I'm coming from a Java background, with minimal experience with functional languages. Things I'd ideally like feedback on:
Any impro... |
I have written some code to simple add/mod/del to a table called person. I would like comments on where this code could be comprising on security. I have used the PDO library in php.
GetPerson.php ( use this to retrieve details of a person using ajax )
<?php
include '../classes/person.php';
include '../classes/avaaz... |
I'm not sure if this is the right way to do this, but I want to simply this script and hopefully use CSS3 animations. The code is really large, and parts are very irrelevant, so I'm wondering if I should first get rid of all the irrelevant parts, then go from there?
Here's the code:
var _target = null,
_dragx = nul... |
I want to randomly permute a finite list in the most effective and efficient way in C#. My attempt is as follows.
/*===================================*
* Compile it to produce Shuffle.exe *
* ==================================*/
using System;
using System.Collections.Generic;
using System.IO;
namespace Shuffle
{
... |
In an attempt to begin learning Scala, I've taken a stab at creating a simple wrapper around Java's File & FileInputStream in order to read lines from a file. This functionality already exists in the Source class and is just a learning exercise.
If you were building this wrapper in Scala, is there anything you might c... |
I have a simple inheritance framework:
class BaseValidator
{
protected virtual void Validate()
{
// Base validator code .....
}
}
class PhoneValidator:BaseValidator
{
public override void Validate()
{
base.Validate();
// custom validation logic...
}
}
class EmailValidat... |
We have a hidden div in a master page. When we want to display a message, we send a function a message to display, and it turns that div from .Visible false to .Visible true, and fills the div with the message. For all intents and purposes, this works and we haven't really had much trouble with it. I just feel that ... |
Today I built a linspace function in Python's C API:
static PyObject *
linspace(PyObject * self, PyObject * args)
{
int n, i;
double start, end;
if (!PyArg_ParseTuple(args, "ddi:linspace", &start, &end, &n))
return NULL;
if (n <= 1)
return Py_BuildValue("[d]", end);
double h;
... |
I need comments on my JPA code. Am I doing it correctly? I need some advice on best practices in Java.
I have this method below:
public Comics add(Comics comics) {
EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = null;
try{
tx = em.getTransaction();
tx.begin();
... |
I have written a piece of code by taking help from this link. For generating thumbnail, I create a temporary scaled image and then copy from that image. I am assuming that it is resource intensive.
Settings: the maximum values for target dimensions of scale images are predefined. Also, the thumbnail is always square a... |
Can you please provide a general review the following PHP code (with MySQLi)?
The query involves an INSERT INTO statement:
public function __i($table, $arr) { $c=$this->connection;
foreach ( $arr as $name => $val):
$param1.=$name . ",";
$param2.="?,";
endforeach;
$PARAM1 = substr_replace($param1, ... |
I have written code which does the following:
The main goal is to fetch emails from inbox and spam folders and store them in a database. It fetches emails from Gmail, GMX, web.de, Yahoo and Hotmail.
The following attributes are stored in a MySQL database:
Slno, messagedigest, messageid, foldername, dateandtime, receiv... |
The statement of the problem is there are 2 files, one has a set of intervals i.e. 0-10, 3-40, etc which may be repetitive. The second file has a set of numbers which are also repetitive. The exercise is to get a count of the intervals, a number in the 2nd file would fit into.
Intervals.txt
0 12
2 36
6 98
2 36
Numbers... |
Three radio buttons and a text box, grouped in one group box... Just when I select one of those radio button the text box gets enabled, for the other two radio buttons it should be disabled. Here is the code that comes to mind at first, but it looks ugly to me becuase I have copy pasted the same AllowMissingData() meth... |
I have developed a prototype framework (MVVM) where control on the form is bound to a model property using a naming convention and its UI behavior is controlled using custom attributes.
As of now the control name is divided into two parts - 3 part prefix and then the Name of the property in model to bind to.
For eg t... |
I am looking for some different approaches to this following OOP scenario.
Dim pb As Object = Nothing
If radCars.Checked = True Then
Dim productBase As ProductsBase(Of CarColumns)
productBase = New Cars(fileLocation)
pb = productBase
ElseIf radTrucks.Checked = True Then
Dim productBase As P... |
I just wanted to gather your opinion on my little JavaScript library. It features Math, String, Array, canvas and location extensions, as well as some useful animation and timing classes I came up with:
/* ====================== */
/* ======= Math ========= */
/* ====================== */
// Random number
Math.rand = ... |
I have a library that accepts a file-like object but assumes that it has a valid .name unless that name is None. This causes it to break when I pass e.g. someproc.stdout as it has a name of <fdopen>. Unfortunately the attribute cannot be deleted or overwritten.
So I've written this simple wrapper to return None in case... |
Only current and next element (cNum) is to be shown; in case it is the last element in the structure - the first element should be shown.
var childNum = $('#h').roundabout("getChildInFocus");
var cNum = (Number(childNum)) + 2;
if (cNum == 5) cNum = 1;
$("#h li").hide();
$("#h li:nth-child(" + cNum + ")").show();
if (... |
I've finally gotten around to learning Lisp/functional programming. However, what I've noticed is that I'm trying to bring ideas back into JavaScript.
Example
Before
var myPlacemark,
myLineString;
myLineString = ge.createLineString('');
myLineString.setLatitude(100);
myLineString.setLongitude(-100);
myPlacemark = ... |
I got the solution for the question asked here, but I don't like how the code is written.
This part of the code rotates the screen if it's in landscape and sets the size to match the screen. I don't like the if and the 7x else if. Can you suggest something more readable? Something like (appOrientation - fromInterfaceOr... |
I have a third party component that I am trying to write unit tests around. The problem is that I can't mock the object and there is no interface.
I decided to create an interface and a wrapper class calling into the code for the sake of mocking. I looked into the class definition that is generated by Visual Studio us... |
I really don't get why it has to take so much to make such a little function. Here's what I have.
template <typename A, typename B> auto add(A a, B b) -> decltype(a + b) {
return a + b;
}
Is there a way to shrink this code while maintaining its ability to take different arguments? For a comparison, here is it in Py... |
I got some homework in which I had to take the novel War and Peace and put it into a HashSet and TreeSet respectively. I had to time it, to check differences and my question is whether my implementation is good or not.
If the way I calculate time is even accurate. I am using
System.currentMillis()
but I was debating w... |
Now this is something I've looked into, and while I have a "working" solution, I don't like it.
Background:
Through our intranet website, we want to run a process that copies a file from another machine, unzips it, and then analyzes the content. As the file is large, this takes some time (usually around 5-6 minutes). ... |
I am trying to place JButtons from an array onto a JFrame. The way I'm doing it is having it test how many more buttons are left, and if buttons have been placed at the edge of the frame. The end result is an ugly piece of code.
JButton[] grid = new JButton[2501];
JFrame MapFrame = new JFrame();
public void makeMap()... |
How can I make this more readable, faster, and make the GUI more appealing?
CreditCard class:
import java.util.*;
public class CreditCards {
private String prefix;
private String length;
public CreditCards(String p, String l) {
prefix = p;
length = l;
}
public String getPrefix(... |
How can I DRY these scopes?
scope :reputed, -> {
joins{reputations.outer}.
where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ?', LOWEST_VOTE, true]}
}
scope :reputed_or_mine, ->(user) {
joins{reputations.outer}.
where{['coalesce(rs_reputations.value, 0) > ? OR purchases.fo... |
I've been working with the RaphaelJS 'australia map' example that displays text in a DIV when a state is clicked on. However I'm having difficulty working with it to create different events and functions.
I want to be able to duplicate the 'display text' function for two different element onClick events (i.e. have two... |
I've been working on a class to handle dependency injection across some code akin to a micro-framework. This is also my first real dive into any sort of wrapper for dependency injection. I decided to write a pseudo-intelligent dependency provider that recursively constructs dependencies. I also included the ability to ... |
Before going out and learning a full fledged framework I'm trying to understand the MVC pattern coding basic stuff, at the moment I'm testing with MVC applied to form validation.
After reading a good amount of articles and code examples I came out with my own version, nothing too elaborate as it's mostly for learning, ... |
This is just my simple structure. I want to know if there is a better way than this because I have so many lines of code already.
<?php
$p1speed = 5;
$p2speed = 3;
//way for next turn: 1 for turn
$p1 = 0;
$p2 = 0;
if($p1speed>$p2speed) {
$p1 = 1;
$p2 = 0;
}
else if($p2speed>$p1speed) {
$p1 = 0;
... |
I have a java based server application that needs to support multiple clients. In the main class I have a method that runs in an infinite loop and waits for client connection. Following is this method:
public void listen() {
try {
serverSocket = new ServerSocket(portNo);
while (true) {
c... |
/*
Create a random maze
*/
package main
import (
"fmt"
"math/rand"
"time"
)
const (
mazewidth = 15
mazeheight = 15
)
type room struct {
x, y int
}
func (r room) String() string {
return fmt.Sprintf("(%d,%d)", r.x, r.y)
}
func (r room) id() int {
return (r.y * mazewidth) + r.x
}
... |
This is my C# class, which takes 2.6s:
class Snake
{
readonly Symbol _mySymbol;
readonly int _multiplier;
readonly int _hit;
readonly int _payout;
readonly Snake _bestSnake;
public Symbol MySymbol { get { return _mySymbol; } }
public int Multiplier { get { return _multiplier; } }
public... |
For something I'm doing, it would just make things so much easier, quicker, and cleaner to have C# style events. I've written a class I believe should replicate a C# style event using reflection. Since I've never actually used reflection before in any meaningful sense, I'm very much not happy using it without, at the v... |
Recently I have written an SslStream class asynchronously authenticate clients and receive message from them. I still would like anyone to suggest improvements for my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.... |
I have recently received some feedback on a project I did called Notifier.js, in which you can see I have included all of the source images and styles in the JavaScript file. The feedback I received was that having it all bundled up together may be cool, but it is in fact not as performant and harder to maintain (which... |
Totally new to MVP and Spring, and I have what seems to be typical MVP application that uses Spring, where the presenter is instantiated like:
IApplicationContext ctx = ContextRegistry.GetContext();
presenter = (clsPresenter)ctx.GetObject("clsPresenter");
I hate using strings to call code, really, I hate it. So I'm ... |
I have written following code to find the minimum difference from a list of numbers.
Because I am using a loop once and LINQ again to find the minimum, the algorithm is O(N2).
Can you please tell me if I am using the framework in the most optimal way (speed and memory utilisation) to achieve this task:
using (StreamRea... |
In other languages, I prefer to arrange source files so that simpler and more widely useful concepts are introduced before implementation details, and I try where possible to make complex implementation details top-level functions so that I can separate them out and let the main function read like a high-level algorith... |
The need is to get the possibility to differentiate between a Barcode-Scanner (which behaves like a keyboard) from a human pressing keys in a...let's say a Textbox (the use case would be all over everything, wherever I expect a barcode scanner).
The basic idea was to create a buffer which holds the typed string (conver... |
I've made a simple program that can calculate the area of various 2D shapes. I'd like your expereanced eyes to asses my code. Be as harsh as you want but please be specific and offer me ways in which I can improve my coding.
shape = ("triangle","square","rectangle","circle") # This is a tuple containin... |
I just figured out Project Euler problem #12. This the first one I've done in Python, so I'm putting my code out there to hopefully get some constructive criticism.
If anyone is interested, would you mind looking over my solution and letting me know how I can improve on it, either through optimization or style?
Thanks... |
Goal:
Extract all Appendix Titles
If Appendix Title is Answer Key call custom solutions template
If Not Answer Key call default appendix template
XML:
<appendix>
<title>Appendix A</title>
<section>data</section>
</appendix>
<appendix>
<title>Answer Key</title>
<section>data</section>
</appendix>
XSLT:
<xsl:... |
I'm in the process of doing some mapping of POCOs via IDataReader. I'd love to hear thoughts on the approach and if they are any good ways to improve what I have done.
public class Code
{
public int Id { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string Descri... |
One of the things I wanted to do was make it impossible to forget to initialise or forget to cleanup WSA. Often the network examples will return as soon as an error occurs (say an socket didn't bind) this means you have to remember to add WSACleanup() before each return and I don't like that.
I also wanted to make it i... |
I've just coded a hex to integer converter in C and want my code criticized. I did not cover switch statements so I know that can be improved. I am also planning to truncate "0x" in the beginning of the input if the user enters that.
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define MAXCHAR 100
int hto... |
I'm writing a monadic parser instance that transforms Data.Map.Map's:
instance (Ord a, FromEDN a, FromEDN b) => FromEDN (M.Map a b) where
parseEDNv (E.Map m) = mapMmap parseEDNv parseEDN m
parseEDNv v = typeMismatch "Map" v
Data.Map doesn't provide it's own mapM version like Data.Vector does, so i had to write... |
Consider the following code:
#include <iostream>
#include <vector>
using namespace std;
struct test {
int j;
test& operator>>(int & i) { i = ++j%26; return *this; }
operator bool() { return j%26; }
};
int main () {
test t;
int i;
while (t >> i) {
cout << i << endl;
}
}
I have impl... |
I have the following:
public class ContentsController : BaseController {
private IContentService _content;
private IPageService pageService;
private IReferenceService _reference;
private ISequenceService seqService;
public ContentsController(
IContentService conte... |
I have the following code:
public string GetRefStat(string pk) {
return RefStat[pk.Substring(2, 2)];
}
private readonly Dictionary<String, int> RefStat =
new Dictionary<string, int>
{
{"00", REF.MenuType, } // Menu
{"01", REF.ReferenceStatus,} // Article
{"02",... |
I am trying to figure out a better way to attach the icons based on the class id.
Here is the link.
var bubble = "M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z",
heart = "M24.132,... |
I am making a query in mysql to import users in our marketing system and need for this a lot of data like for example :
Date of last order
Date of last cheque created
...
This are all left joins where I just want the last result with conditions. For the moment I do just a select for this field but I don't know if thi... |
I have the following function to confirm if a directory contains files:
/**
* Check if the directory is empty
*
* Function to ascertain if the specified directory contains files.
* Comparing to two, because parent and current are present inside
* the returned array. Only 3+ denotes files on the target dir.
*
*... |
I've done some tinkering about with Knockout in search for a better solution on how to bind select lists (dropdowns). I came up with a extender in combination with a binding.
Extender:
ko.extenders.selectList = function (target, params) {
var result = ko.computed({
read: targ... |
Router is a generic class that manage multiple contracts that. It is able to find out wheter it's an online or offline situation, on the very moment when an operation is being made.
There's a really easy way of doing it: a class for each Online-Offline pair that implement the contract and check on every each method wh... |
This is a simple script to make ls output first folders, then files, then other stuff (symlink). I think this is really neat and would like to share the script in exchange for comments.
It should be noted that I'm working with GNU findutils and coreutils.
Some basic criteria that I'm aiming for include:
lssort must a... |
I there a better way to write this query? I feel sure it can be done in one statement with joins, but I couldn't get it, and I'm afraid I've made it too slow. What suggestions do you have? I'm running it in SQL Server 2000 (yeah, I know, upgrade is coming).
Basically, I want to match estimated and actual costs, but ... |
I've just got a Raspberry Pi, so I thought I'd try my hand at some Python. This is my first ever Python program (hurrah!).
It's a very simple command-line implementation of noughts and crosses. The computer opponent's strategy is simply to pick at random, the code is very verbose in places and there's no way to restart... |
After reading Herb Sutter's Associate Mutexes with Data to Prevent Races, I found that my solution was superior in several aspects, least important first:
The code is cleaner, without macros
No code added to every struct/class
Does not prevent the use of non-protected versions of the classes/structs
Does not rely on ... |
I am looking for pointers / comments / critiques regarding the below code. One major flaw I know is that I need to define Nodes first and then manually join them to create a List.
Are there any flaws apart from that? C++ programming style errors? RAII?
#include<iostream>
template<typename T>
class Node {
private:
... |
I have the following function to insert a new row into a table:
/**
* Insert row into the designated table
*
* Function to add a new row into the designated table
*
* @param str $table Table name to insert the row
* @param arr $data Array with values
*
* @return int row La... |
Please comment on the same. How can it be improved?
Specific improvements I am looking for:
Memory leaks
C++ style
Making code run faster
RAII
#include<iostream>
#include<algorithm>
template <typename T>
class Stack {
private:
T* array_;
int length_;
T* last_;
void expandArray();
public:
Stack(... |
I'm designing a client (UI made with WPF) and server (WCF) that communicates with a device known as DDC (Direct Digital Control). A user on the client side can make requests to adjust the state of the DDC, then the server receives the information from the client and invokes appropriate operation on the DDC. DDC uses S... |
I have a custom class for Smarty that was partially borrowed. This is how the only example reflects the basic idea of using it across my current project:
class Template {
function Template() {
global $Smarty;
if (!isset($Smarty)) {
$Smarty = new Smarty;
}
}
public stati... |
I created a script to allow a user to drag a div around the page and save it's position and style to localStorage, and I'm wondering if there's anything I can do to make the script more efficient. I have posted the code below, but I left out the drag functionality because I'd like to work on that myself, but the rest I... |
I am trying to teach myself haskell by means of project Euler
i sovled problem #9 by means of this code which is on the brute force side I was wondering if there is a more elegant/haskell/efficient solution
let project_euler_9 = [(a,b,c) | c <- [1..500], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c==1000 ]
|
Just for fun, I want to try to write this Ruby function more succinctly. I imagine it can be done, I'm just not knowledgeable enough with Ruby yet to know how. Any suggestions?
def tags
return ['Cancelled'] if cancelled?
tags = []
tags << 'Filled' if filled?
tags << 'In Progress' if in_progress?
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.