instruction stringlengths 71 71.9k |
|---|
I wanted to see if I fully understood recursion so I attempted the FizzBuzz challenge and applied recursion to it.
Did I do it correctly? Is this good code? Is there a more efficient way of doing it? How can I improve?
//---------------------------------------------------------------------------------------
//[RecurFi... |
The Resource Pool is similar to the implementation of a semaphore. It takes the class type of the resource and number of resource pools associated with it as the constructor parameters. There is a small ambiguity here, when the Resource instance is created it uses reflection, but when we require the resource name a cal... |
This does the job, but is not especially elegant.
What is the preferred Pythonic idiom to my childish nests?
def bytexor(a, b):
res = ""
for x, y in zip(a, b):
if (x == "1" and y == "0") or (y =="1" and x == "0"):
res += "1"
else:
res += "0"
return res
def get_all()... |
I'm looking for alternative ways to do it and in general parts that don't look write on this code.
using System.Collections.Generic;
namespace Algorithms
{
public class SudokuPuzzleValidator
{
readonly int[,] _board;
public SudokuPuzzleValidator()
{
_board = new int[9... |
I didn't make the math myself since I'm an idiot. I did however try to make it more versatile and usable for my multilingual page, which involves making it simple to use for advanced plural forms such as Polish and Russian.
Is this code any good to use on a website? or is it overkill?
I'm using the laravel framework, b... |
How can I simplify this code?
if (directory.Exists)
{
smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
if(smallFileNames.Count == 0)
smallFileNames = DivideIntoFiles(fileName);
}
else
smallFileNames = DivideIntoFiles(fileName);
I confused by identical lines...
|
I'm working with lots of code that looks like this:
-(void)switchToPercent{
int tmp;
tmp = (statisticsObject.idag3_orig != 0) ? statisticsObject.idag3_orig : [self compareValue:statisticsObject.idag2 withValue:statisticsObject.idag3];
statisticsView.idag3.text = [NSString stringWithFormat:@"%i", tmp];
... |
here is my implementation to find the lowest common ancestor in a binary tree. It works but i would like to know if i could have done anything better or if i have missed an specific case. would really appreciate ur feedback:
//The function findOrQueue is to enqueue all elements upto target node to a queue
public void f... |
I have written a JavaScript API that loads and houses libraries of code to do all sorts of things on websites.
Effectively, this is (will be) the base JavaScript for all the websites I build.
The aim of this API is to load the required libraries (SM.load()) needed for a particular page, and add them to the library as a... |
Please help me improve this Google Apps Script for reminding the user to contact people they haven't contacted in a while:
Purpose:
Creates tasks for you to contact people you haven't talked to for a while.
Adds a 'Touch Frequency (Days)' field to contacts - make a schedule per Contact
New emails to/from a contact wit... |
This code solves the problem of FizzBuzz. Is it possible in any way to improve it?
main = main' 1 where
main' n = do
(putStrLn . choose) (show n, "Fizz", "Buzz", "FizzBuzz", n)
if n < 100 then main' (succ n) else putStrLn "End!"
where
choose (n0, n3, n5, n15, n)
| mod n 3 == 0 && mod n... |
This replaces numbers with the character that appears next to them ('number' times). Is there a a more elegant or shorter way to do this?
var decode = function(str, result) {
var regex = /\d+/,
number = regex.exec(str);
if (number === null) {
return str;
}
var start = number.index,
... |
My problem is I need to know
is my code in my CRUD functions structured well and effectively? I plan to implement CRUD for Locations entity too. hopefully without redundant code.
you see how one CRUD function in the program class calls the other CRUD function in the DataAccess Class? I"m trying to set it up so that ... |
I'd like to improve my router.
This is the current code for my autoloading action within my MVC application:
spl_autoload_register(function ($className) {
if (file_exists(ROOT . DS . 'library' . DS . 'intranet' . DS . 'classes' . DS .strtolower($className) . '.php')){
require_once(ROOT . DS . 'library' . DS . '... |
I have a lot of variables that I need to check for exceptions and output the empty field in case of a null returned value (I am reading a calender list from Sharepoint and my program is supposed to send email notifications if some of the conditions are met).
I surrounded my variables with a try-catch with a generic out... |
I'm learning JavaScript and came up with this basic game code structure (using the CreateJS framework):
var stage;
var totalLoaded = 0;
var manifest;
var game = game || {};
game.init = {
load: function () {
var canvas = document.getElementById('gameCanvas');
images = createjs.images || {};
... |
I'm submitting this code in a couple of days as part of an an interview process. The company knows that I don't have any formal experience with Java. I'm hoping they are testing my ability to learn it on the fly.
This is my first non-trivial Java program and I'm looking for improvements and advice as if to whether ... |
I'm trying to write a little page which will help me - when it ever gets finished - in my job to get some stuff done easier and faster. I'd like some hints and tricks for better structuring the code, i.e. to better divide logic from the UI.
I use jQuery a bit (need to expand my knowledge of using it) and will finally p... |
I am currently trying to learn Haskell (after taking a Scala course on Coursera); but while I can write functions that do what I want, I worry that I am not learning to write idomatic/clean/performant code. I am hoping that this is an acceptable place to receive feedback on how I am progressing. Please let me know if m... |
I am working on a code snippet to make a function which can be called with an object literal.
Problem area: If I do not need to track the product value, then a check has been placed for undefined. But do I really need to make check for each and every value if it's not there in the object literal?
trackProduct = functi... |
I am using this code to display the recent post from my subdomain to my main domain. I got it after spending 6-7 hours. Now I need to show the avatar image and username of the user of has posted the questions on questions.admissiontimes.com. Right now, it's coming in green and black.
function print_requested_template_p... |
I've written a hash-table implementation. This is the first time I've written such code. The hash-table uses open-addressing with linear probing. The hash function is still subject to change as I found out some properties of it that make it particulary bad for my application.
Could you please review the code and tell m... |
I have a class like this one:
class EmailClass
{
public string MailAdresse { get; set; }
public string MailAdresseCC { get; set; }
}
Through a JSON deserialization I obtain a List<EmailClass> and two other strings anotherMailAddress and justAnotherMailAddress.
I need to join all those adresses in one big stri... |
My alghoritm works and produces good result, but it takes too much time(6 s for 300 input items that is too much for branch and bound alghoritm), so I have maken a mistake somewhere, but really can't find it :( It is supposed to be depth-first branch and bound. Any help would be appreciated!
public void knapsack2(Item[... |
(getProperty is the deepCss function from here and retrieves the current (computed) style of an element).
function toggleElements()
{
for (var i = 0; i < arguments.length; i++) {
$(arguments[i])[0].style.display = (
getProperty($(arguments[i])[0], "display") !== "none"
? "none"
... |
In Cracking the Coding Interview by Gayle Laakmann McDowell, there's a question that asks you to write code for the following:
Given two sorted arrays, A and B. Write a method merging the elements
of B into A in sorted order. Assume A has a large enough buffer at the
end to hold all of B's elements.
Though the pr... |
I've created my first jQuery plugin, so please try to understand :)
My plugin code looks like so:
(function($) {
$.fn.ajaxSelect = function(options) {
var $this = this;
//options
var settings = $.extend({}, defaults, options);
//disable select
if ($.ui.selectmenu && settings.selectmenu && settings.d... |
In current project I'm using a lot ReaderWriterLockSlim for synchronizing reading and writing values. Handling try { EnterReadLock(); .... } finaly { ExitReadLock(); } every time I need access value seems to me as copying code. So I created extension methods for ReaderWriterLockSlim which makes me coding much easer and... |
I have the following code for my coupon system. It should work but I'm sure I can optimize it.
Any suggestions would be welcome.
@price_to_pay = @booking_request.guests * @table_offer.price_cents / 100
@remaining = @coupon.current_amount - @price_to_pay
if @remaining > 0
@coupon.current_amount = @remaining
@price_... |
Is there a better way of writing this? I feel like there's a lot of lines for such a small thing. Can it be optimized?
$j('#hideShowBtn').toggle(function() {
$j('.playlist-bar-tray').slideUp();
$j(this).attr("title","Show Playlist");
$j(this).children("div").html('Show Playlist');
$j(this)... |
I am a Java beginner and I am looking for an idiomatic way of writing a function that involves generics. I wrote this helper class (below) that pushes items into a sorted generic collection and I wanted to ask for your feedback. Should I perhaps extends some base class of some collection? Or maybe there is some better ... |
I have this GenericDataAccess class to interact with database from my school. I want to ask for some suggestions and advice in how to to improve it and add new methods to it for future use and reference
public static class GenericDataAccess
{
static GenericDataAccess()
{
}
/// <summary>
/// create... |
The basic idea is for users of these classes to create derived polymorphic protocol specific messages. There is no protocol type in the interface, it is all hidden behind the scenes. But the serialised messages can be retrieved with the getMessage functions.
Does this look a logical approach? Any suggestions?
//base ... |
I want to search through an array of n numbers and find the numbers that are repeated. So far I have this code, which does the job, but I find it to be a rather cumbersome method, but I can't seem to find another method of doing it.
class Checknumber{
int [] numbers = new int [5];
Scanner inn = new Scanner(... |
Ok, so given the string:
s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School"
I want to retrieve:
[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...]
Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was:... |
Project Euler problem 81 asks:
In the 5 by 5 matrix below,
131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is
131 → 201 → 96 → 342 → 746 → 422 → 121 → 37 → ... |
I have a method that contains a bunch of NSDictionaries (in fact, the only reason I have that method is to create those NSDictionaries). While I don't believe there are enough NSDictionaries initialized to visibly slow the code down as of yet, that is a good possibility in the future. I am currently just creating all... |
JavaScript doesn't offer a module system. There are many third-party solutions, like require.js or jQuery's $.getScript. Most, while good, they bring dependencies, extra kbs and/or limit your folder structures. Sometimes it's necessary to make a .js file self-sufficient. This said, what is the smallest snippet that can... |
This implementation of range() is very fast:
RANGE = []; for (var i=0; i<65536; ++i) RANGE.push(i-32768);
range = function(a,b){ return RANGE.slice(a+32768,b+32768); };
Are there downsides in using this approach?
|
In SQL there is no way to do an "INSERT... SELECT". If you want to do it without using raw SQL in several places of your code you can create custom SQL compilation.
There is an example about how to do "INSERT...SELECT" in SA documentation. This example doesn't support column in the INSERT part of the sentence, some thi... |
Here is a little interpreter I wrote for a simple stack-based language. It is my first attempt at a complete Haskell program, beyond glorified calculator use.
I'd like very much to get an expert's opinon on stylistic matters.
Also, although the thing runs fine, on a test program it seems to suffer from a space leak: I ... |
I've updated this question to be about code style only, as all of it's answered focused on this aspect. For the codes function, see Randomizing and mutating algo class - functionality
algo is an algorithm that's dynamic. algo instances can be created, asked to become random, mutated and also run. They can be set to rem... |
This is homework for which we have prepared Nios 2 assembly:
########################################
# Definitions of device-addresses
# and important constants.
#
# de2_pio_keys4 - 0x840
.equ keys4base,0x840
.equ TRAPCODE, 0x003B683A
# uart_0 - 0x860
.equ uart0base,0x860
# timer_1 - 0x920
.equ timer1ba... |
I would like a fair minded critique of this code to get some feedback. I am not trying to re-invent the mold here, and I know there are plugins galore I could have used to do what I am doing here, but the point was to do it myself so that I can learn more and become better.
I have included comments to try and best expl... |
This is an iterative implementation of alpha beta tree search in C#. Please help me confirm the correctness of my code. search() is called when the search begins.
int depth;
Func<board, int> value;
Func<board, List<string>> legalmoves;
Random randomgenerator = new Random();
board board;
Stack<int> alphas = new Stack... |
I have this function definition which takes an r and applies the function f n times:
r => (1 to n).foldLeft(r)((rx, _) => f(rx))
So for n=3 this is equivalent to f(f(f(r)))
I don't like this solution, because it defines a Range from 1 to n which really isn't get used at all, which becomes obvious in the unused paramet... |
I'm new to C# and just tried the String Calculator Kata for practice. What I like to know is if you (as more experienced C# programmers) have some suggestions for improvement with the end result (concerning readability, good practices, C# specific idioms etc.)
Code:
public class StringCalculator
{
private const ch... |
I have written a simple VM in JavaScript and it interprets source code written in JSON.
The JSON object must have a "exports" property, which is a dictionary that matches a string into a integer value. This value is an index to "entries" property, which is an array of entries.
For each entry it contains a "binds" and a... |
i came across this fun puzzle while being on vacation.
It was designed by Robert Abbott and painted into the grass of a Wisconsin farm. Robert succeeded into making it seem really easy to solve. Well, it is not. I spent hours with my friends wandering the puzzle and left frustrated.
I decided to solve it using comput... |
I would like to make the search faster as it takes a long time to retrieve the data that I require. Is there a faster method to do this? I have written the code below to allow me to search through a data table and retrieve data, which currently is fully functional. It's the nested for loops which I am using and wonderi... |
Background
I retrieve data from a 3rd party API, over HTTP. It's often slow, and sometimes just fails.
I needed a class that would keep getting data from that source, and keep it in memory.
So, this "TaskKeeper" class's purpose is:
Have a timer (interval lengths are parameters of the class)
Every timer-tick, perform ... |
I am writing a program in C running on UNIX which counts the number of each letters in a input text file. For a file like this:
The cat sat on the green mat
The output would be like this:
The letter ’a’ occurs 3 times.
The letter ’c’ occurs 1 times.
The letter ’e’ occurs 4 times.
The letter ’g’ occurs 1 tim... |
I had a question about filtering tree view and returning just first match.
I've tried to create list<treenode> and change the code. Is it possible improve the below code for finding nodes and child nodes that match my criteria?
private List<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{
... |
I am trying to reduce the total execution time of my code.
I have a GPS system which calculates routes between two points, and returns all points in between them.
I did a simple profile and the calculation of the route takes on average 30 ms while, from main thread input to main thread output, it takes almost 700ms to ... |
I have the following method that has been shortened for the sake of this review. The actual method has many more tasks. Essentially what I am trying to do is to create many tasks, fire them off, wait until they are all finished, and handle any exceptions generated. Does this look correct?
public static void RefreshCoat... |
I started reading about JavaScript patterns, and I really liked module pattern.
So I created some module:
var App = (function (parent, $) {
function myPrivateFunc () {
// Some private stuff
}
return {
myPubFunc: myPrivateFunc,
publicFunction: function () {
// Do some stu... |
I ran into the code below today, and my gut instinct tells me this is an expensive way to do a null check. The point the author was making was that if you changed the name of the object then you don't need to change the value of the string being thrown in the exception.
The proposed use would be:
string cantBeNull=...;... |
I have a class called Task that contain a member boolean variable Completed.
I created a list of Task objects in a variable called Tasks.
I have the following code, which sorts the objects depending on whether the Task is completed. (I want the incompleted tasks to be in the list first)
private List<Task> GetSortedTas... |
Any suggestions to make this code clearer, more Pythonic, or otherwise better? I'm open to changes to the design as well as the code (but probably won't drop features or error checking since everything still in it has shown worth to me).
"""
Parsing with PEGs, or a minimal usable subset thereof.
Background at http://bf... |
Thought 1
public interface IRepository<T> : IDisposable where T : class
{
IQueryable<T> Fetch();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Func<T, bool> predicate);
T Single(Func<T, bool> predicate);
T First(Func<T, ... |
I had asked a first question about this class a while ago and got a few answers here which made me rewrite it completely.
I removed all statics and globals, added my variables as arguments for the constructor, and pass them again as reference through my constructor (for creating a controller from within a controller).
... |
a_star = # returns the goal node (or null if path not found). To reconstruct path follow the node.__src till null
(
start, # starting node
neighbors, # a function that takes in a node and returns list of neighbours
h, ... |
Background
My project performs software application management; it covers in-app purchasing, product provisioning, account management, etc. I've recently been tasked to add a cost reporting component.
Code
On the code level, I've spread out my model into a few classes that represent categories or interest areas, each r... |
I use the code below for filtering a treeview. Can this be improved?
private IEnumerable<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{
foreach (TreeNode node in nodes)
{
if (node.Value.IndexOf(searchstring,
StringComparison.CurrentCultureIgnoreCase) >= 0)
... |
I have a PL/pgSQL function with erratic performance:
DECLARE
l RECORD;
events_for_machine integer;
before_event "PRD".events_log;
machines_ids integer[];
island_controller RECORD;
before_order "PRD".events_log;
before_detail "PRD".events_log;
before_pallete "PRD".events_log;
before_operation "PRD".events_log;
timer tim... |
I modified Amit Agarwal's script which checks the uptime of one website so that it now checks several sites. The script runs every 5 minutes, however, I kept receiving mails that a site was down and then 5 mins later that it was up again.
I adapted my code to only log a change if it persisted for two checks, like this:... |
Related:
Nios 2 interrupt handler
/*
* Main C program for nios2int 2012-10-31
* Assignment 6: Interrupts from
* timer_1 and de2_pio_keys4
*/
/* Include header file for alt_irq_register() */
#include "alt_irq.h"
/* Define the null pointer */
#define NULL_POINTER ( (void *) 0)
/* Define address for de2_pio_redled1... |
I am trying to find all "link" elements that link to RSS feeds in a data structure created by clj-tagsoup. I wrote the following code, which seems to work fine. But: I come from a Java background and I am new to functional programming and clojure, so I am not sure if this is the right way to do it. Could you please giv... |
Project Euler problem 83 asks:
In the 5 by 5 matrix below,
131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is
131 → 201 → 96 → 342 → 234 → 103 → 18 → 150 → 111 ... |
I have the following methods in CacheUtil class
public void addCacheEntry(String key, Serializable entry) {
//add to cache
}
public void removeCacheEntry(String key) {
//remove from cache
}
public Serializable getCacheEntry(String key) {
Serializable entry = // get from cache
return entry;
}
And in the ... |
I needed to publish a message across the ESB (MassTransit) that will return a different type of object depending on how the message is processed. I wanted to implement this in a generic way so I could wire up other services with similar requirements in the same way.
Publish a request
public IGenericResponse<TPayload> P... |
My goal is to simulate a Pile shuffle of a vector. It takes 2 optional arguments for the number of piles to use and how many times to perform the shuffle.
As this is my first attempt at clojure code, I'm fairly sure I'm doing something terribly wrong here. I'm concerned with speed, efficiency, and indentation style. I'... |
When you click open - a div slides out. If you click on the new div, an additional div slides out from under it. This is working great, but I need two things that I cant figure out!
How can I condense the jQuery so I don't have to add a class to it every time I want a new slider? Is it possible to do a .sibling kind o... |
Here's a solution for a lazy groupBy when the iterator contents are assumed to be clustered (repeated elements next to each other) over the key:
def clusteredGroupBy[B](h: Iterator[B])(f: B => _): Stream[Iterator[B]] = {
if (h.hasNext) {
val firstValue = h.next()
val projection = f(firstValue)
val (head, ... |
This is my first C++ in many years. It's based on some stuff I found on the internet, including a Microsoft article on a similar topic. But I'm sure there are C++ idioms that might make this better or leaner (my main goal).
#include <ShObjIdl.h>
#include <atlbase.h>
#include <wchar.h>
int wmain(int argc, wchar_t* argv... |
I'm building a generic flat file reader which looks something like this.
public class GenericReader<TComposite, THeader, TData, TTrailer>
where TComposite : GenericComposite<THeader, TData, TTrailer>, new()
where THeader : new()
where TData : new()
where TTrailer : new()
{
public TComposite Read()... |
I wrote my first jQuery plugin. It counts characters in a similar way to what StackExchange uses for comment entries. You can see it in action with this fiddle.
I feel that it's messy, but I can't explain why. One of the default options is defined outside the defaults hash because it uses a self-reference, and the meth... |
I'm looking for feedback to improve this function. The purpose is to pass a noun and append the appropriate indefinite article ("a" or "an").
A known issue with this code is that it doesn't address words with a vowel sound but a consonant first letter, such as "honor" or "hour". I cannot include 'h' in the list of vowe... |
I am very much interested in the Reverse Cuthil McKee Algorithm. I have seen Fortran and C or C++ implementations of it, and I decided that it would be a nice exercise to implement it in Python.
I know this algorithm is quite domain specific, but I would still be happy to see what kind of comments I get regarding:
Co... |
Here I retrieve a collection of causes from the database. Along with the information from each cause, I want to send the number of users in each cause. This way works, but if experience has told me anything there is probably a much more efficient method to do this. How can I improve this?
def index
@causes = Ca... |
How can I optimize the if condition in this snippet? The only one difference is && [self isCurrentPosition:i]. How can I make it a single if, including the condition val?
Note: self is a category of NSArray.
- (void) cleanTextfieldExcluding:(int)current checkPosition:(BOOL)val {
for ( int i=0; i<[self count]; i++ ) {... |
I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.
import os, sys, time, re, stat
def matchextname(extnames, filename):
# Need to build the regular expression from the list
myregstring = ""
for index in range(len(extnam... |
I have the following code in jsfiddle. I have been told this this code is messy and not optimised. My question is, what about this is messy and unoptimised and how can it be tidied up and optimised to reduce file size and so it becomes more responsive?
$(document).ready(function() {
$( ".column" ).sortable({
... |
I'm looking for a better way to provide configuration options and improvements in general. I'm using the constructor injection pattern to get access to the Cache and Twitter class. $callback and $params are both part of an $_GET array.
I'm not happy with $config at all. Maybe it's better to add the whole $_GET array? B... |
A multithreaded client server program to download image files. If you want to execute it on your machine you should change the file paths. Since there are four files to download the client makes the same number of connection attempts. The files sent by the FileServer will get repeated after the fourth connection attemp... |
Please review my classes and give me some advice to improve them. I have also put some additional questions in the code and I hope you can give me an answer for some of them.
Database.php
<?php
class Database
{
private static $dsn = 'mysql:host=localhost;dbname=knight;charset=UTF-8';
private static $user = 'ro... |
I have to write a Blackjack game for college using the Processing language. It has to be done in a strict object-oriented approach, so I can't make an object of a class in another class unless there is some connection.
We have to use a Player interface:
interface Player {
// This is the interface you are expected ... |
For a homework assignment we have to write a class that simulates water breaking a floodbank (very simplistic 2D simulation).
My implementation works fine but I found that there were many downcasts (in my opinion, a flaw in Greenfoot's API, which should be using generic functions rather than functions that take classes... |
I've written the following simple filter in Racket as my first Racket program and am wondering if I am writing it in an "idiomatic Racket style".
#! /usr/bin/env racket
#lang racket
(require racket/cmdline)
(define a-prolog-mode? (make-parameter #f))
;; parses the options passed on the command-line
(command-line
#:... |
I've written a simple accordion using zepto js lib.
Looking for advice on how to improve this better.
HTML
<div class="box">
<span class="learn-more"><a href="#">Learn more</a></span>
<div class="more">
blah<br>
blah<br>
blah<br>
<span class="close"><a href="#">close</a></span>
</div>
</div... |
How can I write this PHP code better? It puts together an SQL query string from user input. The task is to return search results based on one or more text fields. The user can determine if partial matches are allowed.
$compop = $allowpartial ? "LIKE" : "="; // use LIKE for wildcard matching
$any = $allowpartial ? "%" :... |
Delete all matching ID
Insert new data
function add_date($id,$date) {
mysql_query("DELETE FROM wp_opening_date WHERE Id='$id'");
$dates = explode(",",$date);
foreach ($dates as $date) {
$date = explode("/",$date);
$d = $date[0];
$m = $date[1];
$y = $date[2];
mysql_query("INSERT INTO w... |
Can I use task.Wait(); like that? Note that when I call task.Wait the task is probably already finished.
And probably you can suggest better pattern.
class A {
private Task task1;
private Task task2;
...
public void Connect() {
stayConnected = true;
task1 = Task.Factory.StartNew(....,
... |
Using Rails 3.2. I have the following code:
# photo.rb
class Photo < ActiveRecord::Base
after_create :associate_current_user
after_save :increase_user_photos_count
after_destroy :decrease_user_photos_count
private
def associate_current_user
current_user = UserSession.find.user
self.user_id = current... |
Is it possible to write this method in a prettier way?
public static string ByteArrayToString(byte[] byteArray)
{
var hex = new StringBuilder(byteArray.Length * 2);
foreach (var b in byteArray)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
|
It work's at Smartphone(Android 2.3.3) but Tablet(Android 4.0) => Force Close!!
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpRespon... |
I have 3 nested NSEnumeration loops, which are used to get the textfields of a custom cell, in a custom table in a custom view in a controller.
How can I make this code more readable and more optimizated?
- (void) textfieldsOperations:(APOperation)op
{
__block int Valid = 0;
__block NSArray *sub = _Table.subviews;
... |
I would like to share my class IDF. Any suggestions/modification?
public class IDFMeasure
{
private readonly string[] _docs;
private readonly int _numDocs;
private int _numTerms;
private List<string> _terms;
private float[][] _InverseDocFreq;
private int[] _docFreq;
private readonly Diction... |
My implementation contains a SpriteComponent class which has a Z property; I use this to determine the order in which to draw my entities (higher Z = drawn on top). It's a simple integer.
What I'm worrying about (premature optimization, I suspect) is the runtime complexity of the function which gets the list of all the... |
I'm fairly new to Arduino and C++ in general, coming from a heavy Python background. The code below is functional, but my lack of C++ knowledge is keeping me from spotting any errors in style, idioms and other good practices.
Not all of the library code is used by the example, as I tried to keep that to the minimum (th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.