instruction stringlengths 71 39k |
|---|
This is a "answer" to my own question over at stackoverflow, head over there to see what I am trying to accomplish. https://stackoverflow.com/questions/16744109/deleting-the-proper-ccsprite-from-an-array-in-a-schedule .
I ended up doing a rather interesting approach, and I think this might work.
-(void)explosionFro... |
Is there a way to write this code block cleaner and more readable?
var shareNavigate = function () {
scope.sharingActions.shareOnFacebook().done(function () {
app.router.navigateToStories();
});
},
sharePublishNavigate = function () {
scope.sharingActions.shareOnFacebook().don... |
I figured something like this:
a= [1, 2, 3, 2, 2, 2, 3, 1, 1, 1, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a.inject({}) { |h, el| h[el] = a.count(el) if h[el].nil? ; h }.sort_by {|k,v| v}.reverse.inject({}) { |h, el| h[el[0]] = el[1] ; h}
This outputs:
=> {0=>10, 4=>9, 2=>5, 1=>4, 3=>2}
Bu... |
I am trying out a small piece of code that would generate HMAC-SHA1. I have been asked to code the HMAC implementation myself using the OpenSSL libs for SHA1 calculation.
After 'wiki'ing for the algorithm, here is what I have below. I have used input with RFC 2104 specified test values:
key = 0x0b0b0b0b0b0b0b... |
This is from an older question of mine that I decided to revisit:
Simplifying and optimizing factors and prime factorization generator
In that question, someone suggested I use an std::map to hold the factors generated from my inputted number. I've also decided to use it with my generated prime factorization, which al... |
I'm reading Robert C. Martin's "Clean Code" and for the past few days I've been fiddling with its function writing guidelines. At first I thought the idea of functions being two/three lines long to be ludicrous, but I'm slowly getting the hang of it. The problem is, I'm pretty sure I'm overdoing it now.
These are the f... |
I was trying out the Beej's guide to socket Programming and wrote this. Is there anything that I am obviously doing wrong? Any potential for buffer overflows? Segmentation faults? Any possible errors that I am not checking for?
Or anything that I am overdoing?
Thanks a lot.
/*
* sk2.c
*
* Created on: May 26, 2013
... |
I have a method that returns either true or false based on a value contained by a java.util.List.
List<Long>list=new ArrayList<Long>(){{
add(1L);
add(2L);
add(3L);
}};
public boolean checkId(Long id)
{
return list.contains(id);
}
Based on the return value of this method and several other conditions a ... |
I wrote this code to find the smallest possible integer ratio between two numbers:
void ratio(int a, int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
if(max % min == 0) {
System.out.println("1" + " " + max / min);
return;
}
for (int i = 2; i <= min; i++)... |
Please, review my implementation of the F# pipeline operator in Scala
class PipelineContainer[F](value: F) {
def |>[G] (f: F => G) = f(value)
}
implicit def pipelineEnrichment[T](xs: T) = new PipelineContainer(xs)
test("Find the last but one element in the list") {
// example: penultimate(List(1,2,3,3,4,5))
... |
Here's a test from a Rails app I'm working on. I want to know if I'm using describe, let, before, expect, etc in the proper way.
It is an integration test using capybara and FactoryGirl:
require 'spec_helper'
describe "UserPages" do
subject {page}
describe "profile page" do
let(:user) {FactoryGirl.cre... |
I'm currently learning JAVA in a class and we're using the ACM Graphics package. I wanted some pointers on my code. To provide some context here is the assignment:
Write a program that creates an array of 5 custom objects (cows, UFOs,
cars, etc.) and then lines them up along the left edge of the window.
Assign eac... |
I have had to do a crash course in JSP, Servlets, and JDBC. I decided to attempt a Login System. I'm unsure if my use of try/catch is appropriate and if I am closing database connections correctly. There is one major flaw in the program which is if a user registering enters an ID that is not unique, then it causes an e... |
I was fiddling with animation in Java and wrote this:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
class Main extends JFrame imple... |
I have written this code to be able to suspend (or to cancel) a worker executed in a separate thread in Qt.
To do it, I have used an instance QWaitCondition and QMutex.
#ifndef MYWORKER_H
#define MYWORKER_H
#include <QObject>
#include <QMutex>
#include <QWaitCondition>
class MyWorker : public QObject
{
Q_OBJECT
p... |
I've written a modulus-type program (using std::vector). The user inputs a number, and the program displays a modulus grid pertaining to that number.
This is what it looks like (example program output with 12):
(0) 12 24 36 48 60 72 84 96 108 120
(1) 13 25 37 49 61 73 85 97 109 121
(2) 14 26 38 ... |
You can download the Dangerworld game in pre-alpha version and review the code. The particular issues I have are
making the character walk over steps instead of sliding
NPC AI how to make the enemy walk along a wall
package adventure;
import com.jme3.system.AppSettings;
import java.io.File;
import com.jme3.rendere... |
I have a handful of objects that don't have references to each-other that all need to receive an update.
From what I've read, it seems like a Publish-Subscribe Messaging Channel is an appropriate pattern. Searching for an existing solution mainly turned up messaging libraries for application integration (between proce... |
This is sort of a follow-up to a post I created about 10 days ago, but I have completed the implementation: Designing function prototypes for a singly-linked list API in C.
As I began to work on the implementation, I chose to change some of the functions and to move things around a little. This post includes source for... |
Here I have two DataTables:
dtTotalDateRangeExcludeSundays
dtAbsentsLeavesHolidaysWorks
Each has 10k+ values, and I need to delete matched rows.
foreach (DataRow rw in dtTotalDateRangeExcludeSundays.Select())
{
DateTime dateFromRange=Convert.ToDateTime(rw[0].ToString());
string strPrnt = dateFromRange.ToSh... |
There is a function that converts region code strings (1 to 4 characters and null terminator) to 32 bit integers codes to be used in maps as keys or values.
Blindly casting char* to int* is bad as it can be less than 4 bytes including null terminator.
Currently the code is like this
uint32_t region_code_key(const char*... |
I want to provide, in the the spirit of C++11/boost make_shared and C++14 make_unique, a production-ready make_auto for C++03 compilers.
So, inspired boost's make_shared implementation for C++03 compilers, I provide N overloads (0 to 10, currently) of the same make_auto function.
template <typename T>
inline std::auto_... |
My main goal is to perform the conversion on a list of strings. Is this a sensible approach or should I refactor?
Please note that I cannot use Boost in my work.
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
char fix_delim(char ch) {
return ch == '\\' ? '/' : ch;
}
std::string& fix_s... |
I am making a web app that will have a "my files" area and to do so I am writing my own html and jQuery to control the opening and closing of each folder (or ul li). I want to make sure that this web app is as efficient as I can make it as it may have to deal with a large amount of hierarchy.
jsFiddle
<!doctype html>
<... |
Here is a function that checks whether an alement a is a member of every set in list l-set.
I don't like the fact that it returns #t for an empty list of sets. What would be a clean fix to this problem?
(define memberall
(lambda (a l-set)
(cond
((null? l-set) #t)
((not (member a (car l-set))) #f... |
I found this old color fading function in my snippets folder and would like to implement it to one of my projects. It can be used to fade one color to another. It's a very long one-liner:
D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
return (factor<0.0f)?from:((factor>1.0f)?to:(((((from>>24)>(t... |
I have written some sort routines for PROGRESS 4GL/ABL and wanting to get some input whether these sorts can be improved. And whether my sorts are true to name. And I would also be very interested in any suggestions how to change the Quick sort to do a proper numeric sort as well.
The combsort was easy enough to write... |
I have this method that reads a file into a hashmap. I feel like there are too many levels in this code with all these tries, ifs and so on. How do you think this can be improved?
public static ExchangeHistory loadHistory(String path){
Map<Integer, Date> rtcHistory = new HashMap<Integer, Date>();
Map<Integer, D... |
I came across the following code in our code base:
public interface ICloneable<T>
{
T Clone();
}
public class MyObject : ICloneable<MyObject>
{
public Stuff SomeStuff { get; set; }
T Clone()
{
return new MyObject { SomeStuff = this.SomeStuff };
}
}
The pattern of using a generic interface... |
I've written this snippet to extract a review request status from review-board in python. It works well but i'm very new to python and i would like to know if i could write this any better.
Should i put conn.close in it's own try statement ?
This script is supposed to run as part of a post-commit hook in mercurial.
If ... |
My code already works 100%, just trying to figure out if there is an easier, better or speedier way to do this. Outputs to an HTML table to display results.
Something that took me a while to figure out was how to select the correct parts of the following arrays ($name, $business, $email, $orderstatus) because you end u... |
Here's the full source to a plugin I'm developing, the relevant code I want to refactor is:
function measure($element, $bubble){
var scrollTop = $window.scrollTop(),
viewportHeight = $window.height(),
readableTop = $element.position().top,
readableHeight = $element.height(),
readable... |
#!/usr/bin/env ruby
require 'pivotal-tracker'
require 'yaml'
TEMP_DIR = "#{ENV['HOME']}/.pivotal/"
TEMP_FILE = TEMP_DIR + "temp.yml"
CONFIG_FILE = TEMP_DIR + "config.yml"
unless File.directory? TEMP_DIR
Dir::mkdir TEMP_DIR
end
unless File.file? TEMP_FILE
f = File.open(TEMP_FILE, 'w')
f.write("id: -1")
end
u... |
I am developing a large .NET app. The previous developer used Martin Fowlers Transaction script design pattern. Please see the code below:
Public Class TypeStudent
Private _Name As String
Private _Type As String 'Undergraduate or postgraduate
Public Property Name() As String
Get
Return... |
Can I make any further improvements to simplify / speed up this code? My reason for creating new arrays for the variables $name, $business, $email, $orderstatus is because when displaying results there will be identical order ID numbers stored in $orderid.
My script filters out the duplicates then with the remaining re... |
This function counts the number of times each letter appears in a string, then display the one that appears the most, and the number of times it appears. If there's a tie, it shows all of them, like "bz,5".
I've got the feeling this could be done much better. Suggestions?
private static void LinqTest()
{
const stri... |
I have to make project for school in C# which has to use database and web service. I have made a program which starts a web service and gets a function from there which is used for connecting to a website. I am using HTML Agility Pack for parsing info from that website. Website info is then written in textbox and store... |
Project Euler problem 37 says:
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Going right to left is trivial enough a... |
How can I improve the following two views? Should the action listeners stay in the views?
StudentView.java
package com.studentenverwaltung.view;
import com.studentenverwaltung.controller.StudentController;
import com.studentenverwaltung.helpers.MyTableCellRenderer;
import com.studentenverwaltung.model.User;
import co... |
I have an xml file from which I want to extract the value of attribute custName from the very first child. The code below works where I am using the dom parser. Is there a third-party library with which I can do the same with less code and more neatly?
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.... |
Entire Code Here
Don't repeat yourself
I know of the "Don't repeat yourself". Still it's getting messy in some places. The code below contains three blocks of code.
They are similar in some ways and different in others. It doesn't follow the same pattern in all ways.
What it does
It creates an array that I loop out on ... |
This is a project about a domotics control system based on arduino. Nothing great; it's only for testing myself and making stuff.
Before I started coding this, I searched on the net for some useful tips to use in my code, but I still remain a novice in programming.
The project is about 1600 lines long. I'm obligated ... |
The program basically takes a polynomial and does some simple calculations with it.
With a couple of hours of work I managed to get my first console application to work (aside from the obligatory "Hello, World!", of course). However, I'm in total doubt that the style and habits I've used are even close to being correct... |
I'm writing unit tests for a library which parses colors from user input (example: the user input “#f00” gives a red color; the user input “60,100%,100%” gives a yellow color, etc.)
One of the conditions is that the method Parse returns null when there is actually nothing to parse, i.e. when the input is either an empt... |
I've read most of the posts I could find on optimizing SQLite3 performance, such as:
How do I improve the performance of SQLite?,
Is it possible to insert multiple rows at a time in an SQLite database?
What are the performance characteristics of sqlite with very large database files?
Which are good, but they have no... |
I made myself this code to read CSV files as I want to delve into machine learning. I do think that my code design is poor but I can't quite see why. The syntax of it does not feel right. I want to be able to iterate both over rows and columns but I'd rather not make two different kinds of iterators.
I'm sorry the cod... |
So far, the below code appears to work well. It operates pretty fast, but I was wondering if it's possible to make it faster. I'm also looking for general tips on what I might be doing wrong and what I could do better. I have added in comments to explain certain decisions.
b64.h
#include <math.h>
#include <stdio.h>
#i... |
I'm implementing a "tags" features to an already working solution.
Final users need to be able to add tags to three separate sections of the solution:
Posts
Accounts
Groups
Each section has its corresponding table in the database, and each table contains a unique ID:
PostID
AccountID
GroupID
I'm thinking about imp... |
Is there a better way to do this? If I ever have to worry about earlier images not being loaded before the later images, i.e. image[3] being loaded after image[21]. I have to load about 100 images at the start.
for (var i = 0; i < 22; i++) {
images[i] = new Image();
images[i].src = whatever[i] + ".png";
if ... |
For a session implementation I needed a property that caches its getter (since it involves a database lookup) but still allows modifications (e.g. assigning a new user and storing that user's id in the session). To make this as comfortable as possibly I subclassed property and added the caching logic to the descriptor ... |
I have this working code that selects which method to call based on values in
the parameter:
@Override
public Iterator<DBObject> __find(DBObject ref, DBObject fields,
int numToSkip , int batchSize , int limit, int options){
Preconditions.checkNotNull(ref, "Reference object can't be null");
LOG.info("... |
I was working on a sorting algorithm for my linked list implementation and wanted to get other people's input/comments/critique. What do you think of it in all aspects, including style?
I was told that it is preferred to use a bool type for the changeFlag instead of using an int as it makes it more readable. Thoughts?... |
The general idea of this function is to load a different sound file depending on current time position of the video. I have the following information about audio files:
var samples: [
['00:00:05', 'audio/1.mp3'],
['00:01:00', 'audio/2.mp3']
]
The first element contains the end time for specific audio sample, and the ... |
I would like to see if the working code below can be written more elegantly. I am assuming there is a way to parse out the "r" and "h" to condense it down into a function. Any help is much appreciated for learning purposes. There are no parent/sibling relationships in the ID's.
$('#r1_1').hoverIntent(function(){
... |
I'm building a website that is used to search our system. The users can search on a lot of critera at once. As I try to do this though, I can't figure out how to simplify this horrible action.
public ActionResult Search(SearchViewModel model)
{
Expression<Func<Parcel, bool>> filterexpression = PredicateBuilder.Tr... |
Can someone explain me how this code works or if it is possible to be written in another way? I tried it with just ArrayList but cannot figure it out.
public static Set<Set<Integer>> combinations(List<Integer> groupSize, int k) {
Set<Set<Integer>> allCombos = new HashSet<Set<Integer>> ();
// base cases for rec... |
It's a (simple) guesser for game where you need to find words of a given length only using given letters. I'd like to know if there's a more pythonic way to do things here.
#!/usr/bin/env python3
import sys
if len(sys.argv) < 3:
sys.exit("Usage: " + sys.argv[0] + " letters number_of_letters [dictionnaryfile]")
le... |
I am working on a project that involves XML parsing, and for the job I am using xml.dom.minidom. During development I identified several patterns of processing that I refactored into discrete methods. The code shown in the snippet below shows my definition of an Article class that is instantiated during initial process... |
I have been doing some Code School classes on jQuery, and I needed a image slider for my site. Right now, there are only two responsive states, but that will most likely change (and/or become fluid later).
I was just wondering if there are any best practices or general clean up I can do to the code. I'm still a newbie... |
I wrote a small script to analyse spam messages that are spam false negative; meaning that they are spam messages in nature but that happened to be in your INBOX folder because your spam filter failed to detect it correctly (I personally use SpamAssassin and unfortunately it rarely happens).
The goal is to have a chanc... |
I have two tables (a and b) which have both one date field of type TIMESTAMP. They represent two different type of actions (records): table a's actions are $200 worth each, while table b's ones worth $500.
I want to calculate the total count of dollars worth of both tables actions limiting the maximum number or dollar... |
This is a utility class I have in one of my projects and I seek feedback on it. I have read the javadoc for Locale quite a few times while developing this code. I think I have it right, but maybe there are holes in it...
Reviews welcome; also, if there are parts of the code you don't understand due to lack of comments... |
I wrote this program for sorting an array of type String alphabetical without using compareTo() method so I am saying that if you can find errors in my program please tell me I will try to fix it.
class some{
public static void main(String[] args) {
String array[]={"names here"};
System.out.print("before:");
for... |
I am trying to learn how to animate with tkinter. The code below is an example I was able to build. It creates a small 5x5 map of cubes, then one of them randomly moves around the screen (preferably on the map, but it can wander off).
Is this a good way to do it? Is there a more pythonic, or more efficient way of doin... |
I have the following code in Java:
HangmanFunctions class:
import java.util.ArrayList;
import java.util.Random;
public class HangmanFunctions {
private static final String[] WORDS = {"jazz", "buzz", "hajj", "fuzz", "jinx",
"jazzy", "fuzzy", "faffs", "fizzy", "jiffs",
... |
I have a function in the C++ program, which does simple computations and writes result to two arrays - result[53] and var1_new[53]. It contains two code blocks:
The first one -
double result[53];
result[0] = ((var1[13] * 1) + (var2[7] * 2)) / var3[0];
result[1] = ((var1[21] * 1) + (var2[7] * 2)) / var3[1];
result[2] =... |
How to optimize below code to reduce code with better performance?
import java.util.Scanner;
public class ConsoleCalculatorImproved
{
static boolean ERROR = true;
public static void main(String[] m)
{
String arg ;
ConsoleCalculatorImproved cC = new ConsoleCalculatorImproved();
Cal... |
I wrote a web spider that I would like to download and parse pages concurrently. Here is what I am trying to achieve:
instantiate a new instance of the class with the $startURL as the constructor
spider $startURL with the public concurrentSpider() function
foreach of the links found at that that URL, fork php, and in ... |
What is the best practice to output a list of prime numbers between two numbers?
How can I achieve a better running time? This is a solution to a SPOJ problem which is getting Time Limit Exceeded.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
class ... |
I have just started playing around with L4 and would like to get some feedback on how I implemented a multi-page form
Here are my routes:
Route::model('appointment', 'Appointment');
Route::get('appointment/book_new/{appointment}', array('as' => 'booking-form', 'uses' => 'AppointmentBookingController@index') );
Route::p... |
I have a WCF service, which has a method for updating a EF entity. The update method works just fine but looks ugly. I think due to some EF design I have to manually set the change tracker state to Modified or Deleted or Added. The update method in the server side looks like this:
public Event UpdateEvent(Guid sessionI... |
is there a better why how can I refactor this code, making sure that values in a Hash are typecasted to true/false if their value is '1' or '0' while leaving unaltered the rest?
I'm using Ruby 2.0.0 if that matters, and I'd like to improve this code.
def transform
hsh = {}
preferences.each do |k, v|
v =... |
I have a small WPF application which I'm not exactly localizing, but not hard-coding resources either. I know WPF doesn't use .resx files for that purpose, but I exposed the resource strings as public ViewModel properties which the view's controls bind to:
using resx = MyApp.Properties.Resources;
...
public string Int... |
I have a deep equality comparison method that returns true when two objects are equal (see method Doc):
_.isEqual = function (obj1, obj2) {
// Quick compare objects that don't have nested objects
if (_.type(obj1) === _.type(obj2) && !_.isPlainObject(obj1) && !_.isArray(obj1)) {
switch (_.type(obj1)) {
ca... |
The purpose is just to create a dictionary with a path name, along with the file's SHA-256 hash.
I'm very new to Python, and have a feeling that there's a much better way to implement the following code. It works, I'd just like to clean it up a bit.
fnamelst = [r'C:\file1.txt',
r'C:\file2.txt']
[fna... |
I was solving one of the problem in USACO 2007 Open Silver:
Description
Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings.
The entire horizon is represented by a number line with \$N (1 ≤ N ... |
I've tried to write an "OOP" approach to printing a website using the DOMDocument class. I'm kind of stuck here because I feel like I am blundering in how I am passing and using the DOMDocument. I found that I can just return the object from the class and use it that way.
What are some safe practices here? Best approa... |
I always considered switch statement as somehow defective:
works only on integral types and enumerations.
isn't an readability improvement over traditional if/else chain.
forget a break - you have a bug.
variable declaration spills over neighbouring cases.
is essentially a computed goto
Because of said reasons, and a... |
There is repetition here and would appreciate help in improving this code. Suggestions? Here's the framework for it:
Class Author {
private Integer id;
public static List<Book> sortBooksAlphabetically( Author a ) {
Integer id = a.id;
if (id == null) { return null; }
List<Book> list = getAllBooksForAut... |
I've tried to catch all exceptions and errors in PHP in a way so that I can deal with them consistently.
This is the code with the exception of the very last bit where I instead pass $e on to a method that outputs an error page as HTML.
// Only let PHP report errors in dev
error_reporting(ENV === 'dev' ? E_ALL : 0);
/... |
I'm taking a text file that looks like this:
77, 66, 80, 81
40, 5, 35, -1
51, 58, 62, 34
0, -1, 21, 18
61, 69, 58, 49
81, 82, 90, 76
44, 51, 60, -1
64, 63, 60, 66
-1, 38, 41, 50
69, 80, 72, 75
and I'm counting which numbers fall in a certain bracket:
f = open("//path to file", "r")
text = f.read()
split = text.spl... |
I'm learning BackboneJS and I just made an attempt at converting a pre-existing module to a Backbone.View. I was hoping to get some feedback on my attempt and learn. I've been using the annotated ToDo source as a guide.
Here's some HTML to give you a rough idea:
<div id="VolumeControl">
<div id="MuteButton" class="... |
I have two arrays:
first one is ip addresses from billing for blocking
second is ip addresses from firewall - already blocked
My task is, compare it, and if ip address new in billing list - block it (run a command) if ip address not in billing list unblock it.
Current solutions is:
#billing->router
foreach $ip (@ipf... |
I've tried to improve the speed of my query in MySQL, but when condition IN clause happens too often, the query runs very slowly. Can anyone help me optimize the query?
EXPLAIN SELECT bi.syouhin_sys_code AS syouhin_sys_code
,dwh_syo.name AS syouhin_sys_name
,dwh_syo.code AS syouhin_code
,dwh... |
I come from the world of Python, so I'm used to every file representing their own enclosed module, never polluting the global environment. Up until now (I've worked with Ruby for a week) I've created one file per class in a nested structure such as this:
lib
`- project_name
|- sub_module
| `- foo_bar.rb
`- so... |
I think many people for some reason use a singleton class to handle the PDO connection (?) but I was thinking it would be nice to have a parent abstract class initializing the connection and the child DAO classes would just have to extend that class and use a $db variable. Code below (I didn't test it so sorry if there... |
I have this code:
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.PAGE_AXIS));
TitledBorder tb2 = BorderFactory.createTitledBorder(null, "Control Panel",
TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, myFont, new Color(0, 153, 0));
controlPanel.setBorder(tb... |
I'm relatively new to JavaScript and jQuery so go easy on me. I'm creating a website where upon jQuery document.ready a set of basic animations are performed on different divs on the HTML markup. All divs have separate IDs and I am storing all divs with same CSS property change in the same variable. Using these variabl... |
I'm a PHP newbie and I have a question. Is there a better way to do this? A nice solution?
$list = isset($_GET['list']) ? htmlspecialchars($_GET['list']) : "experience";
<select name="type" id="type">
<option value="experience">Experience</option>
<option value="magic"<?=$list == "magic" ? 'selected' : '';?>>Magic Poi... |
I am using a long array of over 300 var & 7,000 lines of code written like this:
var a = [];
var b = [];
var c = [];
var d = [];
var e = [];
a[0] = "a";
b[0] = "b";
c[0] = "c";
d[0] = "d";
e[0] = "e";
a[1] = "1";
b[1] = "2";
c[1] = "3";
d[1] = "4";
e[1] = "5";
a[2] = "one";
b[2] = "two";
c[2] = "three";
d[2] = "four... |
I wrote this code to solve a problem from a John Vuttag book:
Ask the user to input 10 integers, and then print the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
Can my code be optimized or made more concise? Any tips or errors found?
{
a = int (raw... |
I wrote an example program about UNIX semaphores, where a process and its child lock/unlock the same semaphore. I would appreciate your feedback about what I could improve in my C style. Generally I feel that the program flow is hard to read because of all those error checks, but I didn't find a better way to write it.... |
I am starting to write some functions while studying how to program in C. In this small function I take a string as an argument and print it out in reverse order.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int aLen = argc;
char *sWord = argv[aLen - 1];
char *reversed;
... |
I wanted an excuse to do some OO JavaScript and I decided to do a JSON editor. It will basically allow you to input JSON and either collapse objects to see other objects better, delete objects (can currently only delete KV pairs), or edit objects. If you give it valid JSON it will output valid JSON.
The editor can be ... |
I've been thinking about implementing events and wrote some abstract code:
#include <memory>
#include <vector>
#include <iostream>
template<typename Event>
class Dispatcher
{
public:
class Listener
{
public:
virtual void OnEvent(Event& event, Dispatcher& sender) {};
};
private:
typedef std... |
How can I improve the access time to this unordered map? If I instead allocate a 8 x 10 x 30 x 30 x 24000:
std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > >
each access is about 0.0001 ms. Using an unordered_map implementation, each access is about 0.001 ms, 10x slower. What can I do to reduce... |
I have two classes DigBackground and DigParallaxBackgroundLayer (a parallax background is a image consisting of several images that move at different scroll speeds, for games etc.). My idea was to have the DigBackground class which is basically just a image with some added properties that can be set were it will draw ... |
I need to do a long running task. I've done this by executing a Task while there's a loading box on the UI. When an exception is thrown, I want to stop the task and show a msgbox to the user. If everything goes right, I stop the loading box.
The code below works as expected, but I was wondering if I'm doing it correct ... |
Is there a tighter (less characters) way to use perl on the command line to search and replace text from STDIN than I've got here? The code below works.
echo hi | perl -e '$a = <STDIN>; $a =~ s/i/o/g; print $a;'
|
A Base10 Pandigital Number is a number which uses all the digits 0-9 once:
1234567890
2468013579
etc...
My naive solution was just to use a bunch of nested loops to do this but it's quite slow. And I'm blanking on a more efficient way to do it? The following takes ~6 seconds.
IEnumerable<long> GeneratePandigital()
{
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.