instruction stringlengths 71 71.9k |
|---|
I'm focusing on trying to write clean, modular Python 2.7.5 code.
def main():
type = sys.argv[1]
dataPatient = parseJSONFile(fileName)
if(type == "type 1"):
patient = [d['patient_family_member_id'] for d in dataPatient if d['id'] == sys.argv[2]]
displayList(flatten(patient), "Msg1")
elif(type == "type... |
I'm trying to figure out how to nicely write a Winforms app that reports the progress of completing a long task onto the main form's controls without causing Cross-thread op exceptions and such. So far I've come up with this scheme which at least works, but doesn't look very nice:
Progress<MyProgress> progress = new Pr... |
I have two AngularJS function in my dataContext object that receive data from a WebAPI:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId,
['common', datacontext]);
function datacontext(common) {
var service = {
getAllTagsByHttp: getAllTagsByHttp,
... |
I ve got a table called EXP it looks like this
The table contains
REG_ID - (id of the registred users)
TRA_TYPE - (type of transportation the user chose 1-export 2-import)
PRO_ID - (product id in rande [1-16])
When a user registers he can choose transportation type EXPORT and products for EXPORT or import AND PROD... |
I have a webpage with a table. The table, with 10 columns, can be sorted by each column ascending or descending.
At this moment I control order by big switch:
Func<IQueryable<DeviceUsage>, IOrderedQueryable<DeviceUsage>> orderBy;
IOrderedEnumerable<DeviceUsage> info;
switch (sortOrder)
{
... |
This is an iteration of my previous question: Concurrent Task Waiter
Summary from before:
I have some code designed to simplify managing multiple asynchronous
operations. The code creates callback actions that, when executed by
the asynchronous operation, track which asynchronous methods have
completed. When all... |
I want to improve efficiency of this search engine. It works in about 10 seconds for a search depth of 1, but 4 minutes at 2 etc.
I tried to give straightforward comments and variable names, any suggestions for improved clarity or style/form would also be welcome.
import urllib2
import collections
def get_page(url):
... |
I've written an insert sort and for my assignment I must be able to sort an array of size 107. I've tested this sort with smaller arrays and it always sorts it correctly (up to size 105). If I make the array any bigger and try to output the sorted array nothing happens (I've waited 15 minutes just in case it was just t... |
I'm hacking together some first examples on JavaScript (Nashorn) for viewing a simple chart. Since my background is "Java programmer" I'm sure there are ways where I can have more benefit from JavaScript syntax than I'm using.
I'm open to criticism to get it more shorter, more elegant, more idiomatic than a Java coder... |
I created a script to perform a union on 2 lists: keys and words. I needed to create a dictionary from them. If there are more keys than words, missing words are replaced with "None". Any excess words are removed.
How can I improve this code to be more compact and perform better?
#! /usr/bin/env python3
import random
... |
I was hoping to get some feedback on what the recommended design pattern are for this subject.
public class Channel {
private AtomicInteger buffer = new AtomicInteger(0);
public void read() {
// This function should keep blocking until there is something to read.
while (buffer.get() == 0) {
... |
I am trying to recreate the Google homepage as part of a The Odin Project task. I had a hard time lining up the top right hand menu bar - should I have done it differently? Was the way I did it the correct way? Also, I didn't know you could have a UL list overlapping a div - is this wrong?
Any feedback on the code or ... |
This works in my Eclipse, but I think there is a better way to do it.
public static void main(String args[]) {
for(int i = 1; i < 101; i++)
{
if(i%3 == 0)
{
System.out.println("repetitive of 3");
}
else if(i%5 == 0)
{
System.ou... |
My application is a bit slow. I believe this is because .clearRect is one of the more intensive events in my application so far. However I also draw an image on top of the screen (as background) at the top of each loop, like this:
function redraw(){
ctx.save();
ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeig... |
I was looking for a way to markup parts of my app as restricted to only certain roles, on an element basis.
This works quite well, using an attribute directive, where I specify the allowed roles and disable/hide the corresponding element; e.g.
<input require-role="admin" />
In order to make the app more maintainable ... |
I have a little piece of code that is a little bit unoptimized and need some help with optimization in this case.
The procedure is to search in a database using "Conditions/Condicao" and create a grid using tables in HTML with content. In debug, the following part is taking a long time to complete with 300 results or ... |
I was writing a server that should serve more or less a thousand clients.
After writing the net part of the server code I had to stop writing because I saw that the code was chaotic and not very readable. The code work, but it seems all wrong.
Net.h:
#ifndef H_GUARD_NET
#define H_GUARD_NET
#define WIN32_LEAN_... |
Currently I am looping through dependencies of objects, and I am trying to replace GUID (unity object ID's) inside the files.
Right now I am using the following code, any suggestions for improvement ?
public class SendToThread
{
public int localID = 0;
public string oldID;
public string newID;
public L... |
I have been learning MVVM concepts and trying to implement it in my new project. I want to validate my work that I have been doing these past days. I want to know if I follow correctly the MVVM pattern. I understand that everyone has their way of working/thinking, but as I mention earlier what I need to know is, am I r... |
This is a multiplayer bowling simulator in Ruby. It allows for variable skill levels, and produces weighted random results for each roll based on those skill settings. The methods are grouped in four sections:
game mechanics
scoring calculations
stats calculators (because I got curious about what my skill/weighting s... |
I have homework, in which I get number of cases and then four numbers. Each number tells how many rows there are in each column
For example: 2 2 3 3 should be viewed like this:
_ _
_ _ _ _
_ _ _ _
Wherever there are lines that can be joined in one, I have to do this, and write out minimum number of lines requir... |
I'm just beginning to get the idea of queue and threading.
I would welcome input on this exercise script:
from threading import Thread as T
from Queue import Queue as Q
from random import randint as R
import time
'''
Silly script exploring simple use of threadding.Thread and Queue.Queue
'''
q = Q()
now = time.time()... |
I wrote a class which can time and compare functions.
I already posted it here once before, and got great suggestions from @rolfl, which I have added to my code.
my original question can be found here (example usages can be found there as well)
the formating class I use can be found here
As before, I'm interested in... |
I have to make code that calculates the last digit of \$a^b\$. Here, \$a\$ can have up to 1000 digits whereas \$b\$ can be from 0 to 915*1015. Now I calculated the last digit of a and raised that single digit number to the power b and that number's last digit will be the answer.
#include <iostream>
#include <math.h>
#i... |
I am working on the lossy 16 bit representation for 32 bit integers that catches all 32 bit range with precision depending on absolute value.
My idea is to store integer lv = sign(x)*ilog2(x) in first bite, and a tail that approximates the error x - 2^ilog2(x). In order to do that I divide possible error values in 256... |
I wrote this code to parse dates from the output of the OCR, which means that the obtained date can be literally anything, so I put some restrictions in place:
Date is the the format of: field1?field2?field3, where the fields are either day, month or year and any delimiter can be used to split the numbers, this is als... |
This is a simple word count program I wrote to play around and get familiar with using std::map. Is there anything I can improve upon?
I didn't use CTRL+Z to stop the program because that suspends the process on Linux.
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <iterator>
using st... |
I am trying to define some interfaces to implement some web service integration middleware.
The SOA pattern that fits this system is probably the Multi-Channel Endpoint.
I expect a lot of mapping of data formats happening in this integration so I am trying to come up with some interfaces to implement this.
For each web... |
I'm working with Python 2.7.5 and I'm trying to make it match the PEP8 coding style. I have a few one line for loops but the issue is that they are each above 80 characters in length. Is it bad practice for me to make them multiple lines for the sake of PEP8?
So should something like this:
patient = ([d['patient'] for... |
I'm building a multi-screen Ajax form in an ASP.NET MVC solution. The first screen displays some user details. If the user clicks 'edit', they are taken to the next screen where they can edit the fields. The call to retrieve the user info is quite slow so I don't want to repeat it for every Ajax request, so I'm thin... |
I am an experienced Java programmer, but fairly new to JavaScript.
I am creating a chat library in JavaScript, and have it working, but want to know if I am going about this correctly, and following correct JavaScript coding standards.
I have a SDK object, LiveChatConnection class, and LiveChatListener and Credentials ... |
I am working towards a script that will show a set small thumbnail images on one side of the page, that when clicked will show a larger version of the same image, plus related text content on the other side of the page. I am not very good with JavaScript yet and wonder if the <script> section here is fussier than neces... |
I compiled this with wxDevC++, and it needs the GDI+ library and header includes for Windows, to compile.
On a larger program I have had memory fluctuating from plus minus 4MBs. Not a lot, but why is it doing that?
This is a short replication, which fluctuates by .1MB.
I'm wondering if there is a mistake, or is that n... |
I have the follow script to change my data within Mongo DB:
db.TRACKING_DATA.find( { 'eventdata' : { $type : 2 } } ).forEach(
function (x) { x.eventdata = JSON.parse(x.eventdata);
db.TRACKING_DATA.save(x);});
db.TRACKING_DATA.find().forEach(
function(doc) {
var QueryDate = doc.eventdata.QueryDate;
... |
I'm using the following code to initialise 8 I/O-ports (i.e. GPIO pins on a Raspberry Pi). That's 4 x 2 pins, each duo controls a switch, A to D, and each duo consists of a pin for On and a pin for Off.
def init_switches():
switch = {
'A': dict(On = 22, Off = 12),
'B': dict(On = 19, Off = 11),
... |
I created a simple program that displays 28 numbers on the screen.
from Tkinter import *
import random
class Game(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.parent.title("Centered window")
self.pack(fill=BOTH, exp... |
First of all, I am absolutely surprised that this code even works. Originally what I did was create a version checking system for Minecraft plugins (specifically Bukkit, Craftbukkit, & Spigot).
What I wanted to do was refactor my Version class in order to make it platform independent (where it doesn't depend or provide... |
The following code finds no-rain periods in a time series that were preceded by rain over a threshold (e.g. 10mm in 2 days [k=48]).
significant_drydowns <- function(rain, threshold=10, k=48) {
require(zoo)
require(dplyr)
# Find drydowns: sequences of 0 rain; give them a group
starts <- (lag(rain, defau... |
With lack of real time experience in developing a Java application, I would like to understand the testing strategy for any written module made of multiple classes. Below is the sample application that i learnt from a training,
/* SList.java */
/**
* The SList class is a singly-linked list implementation of the link... |
This code works when compiled on gcc 4.8.2.
I would appreciate any comments on my style and the readability of my code, and any improvements that I could make to make the code more readable and/or performant.
Problem:
Largest product in a series
Solution:
/*
* file: pe_008.cc
* title: Largest product in a grid... |
We have a table with periods, and other child tables with these periods and values for combinations of product + location.
Based on selected periods, I would like to add any missing rows in the child tables. I have come up with the following code, which seems to work just fine. But I would like to know if there is a si... |
This question is similar to Project Euler #48 but constraints are different:
$$N < 2000000$$
Just in case the link is unavailable, here is the problem statement:
We've to print
$$\left( \sum_{i=1}^N i^i \right) \mod 10^{10}$$
I've tried the following, but I need something faster than that, because the execution time l... |
Here is my code for a Python script for a peer to peer chat system on a network using sockets. I know there are some things that could be changed so there would be less repetition in the code and that some variables could be global, but what I am asking is if there are any issues with the code's functionality; it seem... |
I have a bootstrap modal which contains a form that I'm using to add a new record and update existing ones.
I have a button that runs a method (showReferenceModal()) for clearing the field before showing the modal. And another button that runs a method (loadReferencesDetails(referenceId)) for loading the details before... |
Having come upon the wonderful little module of matplotlib-venn I've used it for a bit, I'm wondering if there's a nicer way of doing things than what I have done so far. I know that you can use the following lines for a very simple Venn diagram:
union = set1.union(set2).union(set3)
indicators = ['%d%d%d' % (a in set1,... |
I wrote an implementation of a graph with each vertex storing a std::vector of vertices it's adjacent to.
Please critique this.
#ifndef GRAPH_H
#define GRAPH_H
#include <vector>
#include <algorithm>
#include <iostream>
template <class T, bool directed> class Vertex
{
typedef typename std::vector<T>::size_type adj... |
I have a table with this schema
ID, int primary key
PathKey, string not null
InsertDate, datetime not null
Value, int not null
In the table there are a medium-large number of records. 1632 different pathkey and 645627 total records
The PathKey is not unique (because I store also the old values).
You can identify a r... |
I've created a small proof of concept web crawler to learn more about asynchrony in .NET.
Currently when run it crawls stack overflow with a fixed number of current requests (workers).
I was interested if I have made any common mistakes and if there is more of the framework / TPL I could be using to reduce the amount... |
I have a question regarding optimizing a php email class. It's basically a wrapper class than needs to be able to accept different objects and always output an email. I'm trying to make it generic, in it's current form it's working but I still feel like it may be to tightly coupled. I was hoping someone here could make... |
I have a Linq query in my razor view like below. Its just getting contacts that belong in the group.
@using (var tabs = Html.Bootstrap().Begin(new Tabs("TabStripId")))
{
foreach (var g in Model.Groups)
{
@tabs.Tab(g.GroupName)
}
foreach (var g in Model.Groups)
{
using (tabs.BeginPa... |
I am trying to realize a java.sql.ResultSet into a map, in Scala.
import java.sql.{ResultSet, ResultSetMetaData}
class DbRow extends java.util.HashMap[java.lang.String, Object] {
}
object freeFunctions {
def realize(queryResult: ResultSet): Vector[DbRow] = {
val md = queryResult.getMetaData
val colNames =... |
I'm golfing some code while waiting for a coworker, and I shortened a function to this:
def get_data(dir)
newest = get_most_recent_file_numbers(dir)
data = {}
$file_prefixes.each do |type, file_prefix|
file = File.open("#{dir}/#{file_prefix}_#{newest[type]}.csv")
file.readline
data[type] = file.readl... |
I am building what essentially could be viewed as a glorified database wrapper as a Python package, where I'm having several classes and functions spread out into different modules. My current problem is how to share the database connections with the different modules.
An example class in user.py:
class User(object):
... |
Write a program to create a complete binary tree, which includes an addItem method such that an individual element can be inserted into the tree to maintain the property that tree is complete.
I'm looking for code review, optimizations and best practices. This code is attributed to GeeksForGeeks.
I am also not sure ... |
I had to implement an auditing system where the user have to provide a reason he needs to perform a certain operation. When he provides the reason, he can perform freely it for a certain amount of time. Each execution of the operation needs to be logged somewhere.
I implemented it using a Continuation Passing Style, wh... |
I've written an algorithm for integer multiplication using the Karatsuba method in C++. This implementation is far from ideal, so any comments are welcome.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <cstr... |
I'm trying to improve readability and performance, either by reordering the logic of my code or just syntactically being smarter. Basically, I gather the running processes from Db and then I parse each process and go through he conditions for which the process might be runaway. I always have to go to another server fi... |
I've made this program to do a few integer calculations. Do the methods for converting the numbers look good? Do you have any other basic tips?
/* Dollar Value of Coins, Investment Compounded Annually
* B, Morris
*/
import java.util.*;
import java.lang.*;
import java.text.*;
public class HW3_DollarValuOfCoinsInves... |
I would like to know if this is the correct way to use try/catch when dealing with multiple MySQL queries and PDO:
try {
$create = $con[$_POST['user-selected-connection']]->query("...");
KD::notice('success','table successfully created');
try {
$insert = $con[$_POST['user-selected-connection']]->que... |
I made a start at translating the accepted answer's code here into C#. Any suggestions on the correctness of the translation and the correctness of the original code would be very much appreciated.
public class RgbValues
{
public int Red { get; set; }
public int Green { get; set; }
public int Blue { get; se... |
I've implemented merge sort an integer array. Is it okay to use i,j,k as variable name for looping? Should I change them to more meaningful names? Overall, any further suggestions on this code?
MergeSort.java
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
}
pu... |
I'm trying to solve Project Euler problem #3, which asks:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Can you please review the code and suggests improvements?
namespace FullPractice
{
public class PrimeFactorFinder
{
private readonly HashSet... |
This is what I came up with to delete files not modified within the last 30 minutes from a subdirectory named cache.
'''
Clear cache files older than 30 minutes.
'''
import os
import time
outer = os.getcwd()
cache = os.path.join(outer, 'cache')
count = 0
for f in os.listdir(cache):
f = os.path.join(cache, f)
... |
I would like to have this code reviewed. I am learning C++ from a C background. How would I improve this code to make it more C++ like? This is a simple program that I wrote, which is a stripped down version of the actual full program I'm writing.
#include <iostream>
using namespace std;
class Doge{
public:
Doge(... |
Given the following Abstact Data Type:
data Tree a = Leaf
| Node Integer (Tree a) a (Tree a)
deriving (Show, Eq)-- where Integer is the height (bottom = 0)
I wrote a function to get a tree's height.
-- Get the height of a tree.
getTreeHeight :: Tree a -> Integer
getTreeHeight Leaf ... |
Following up on this question DTO interfaces for implementing web service integration I came up with this implementation.
Data Transfer Object interface following a java.util.Map protocol. The implementation uses Guava's ForwardingMap.
public interface Dto<K, V> extends Map<K, V> {}
public class DtoImpl<K, V> extends ... |
I have this function that I use to publish a message but I need to do this long conversion for time and date. Maybe there's a better way to convert it to make smaller. Otherwise I'm stuck with this long line. I guess I could use slashes, is guidelines on readability for using slashing or is arbitrary.
SMS.publish('/... |
Previously, I posted an incorrect implementation of making a binary, balanced tree from a list of a's.
Here's my second implementation:
data Tree a = Leaf
| Node Integer (Tree a) a (Tree a)
deriving (Show, Eq)-- where Integer is the height (bottom = 0)
-- make balanced, binary tree (height... |
I am using JPA for my database work and I need to create a database entity superclass which all of my table entities will extend.
Every database entity will have a primary key named id (which in some cases is an int and in some a String) and also a lastUpdate field which stores the time at which the database row was la... |
I'm learning about design pattern and I tried to implement a Factory Method example, based on the GoF book.
Can I say that this is a correct implementation of it ? If not I will be glad to find out what are the pitfalls.
#include <iostream>
#include <vector>
using namespace std;
class Widget {
public:
virtual... |
After thoroughly profiling my program, I have been able to pinpoint that it is being slowed down by the vectorizer.
I am working on text data, and two lines of simple tfidf unigram vectorization is taking up 99.2% of the total time the code takes to execute. I am extending the default TfidfVectorizer to add a stemmer.
... |
I use this idiom to parse command line arguments in Perl:
my @args;
my $encode = 1;
while (@ARGV) {
for (shift(@ARGV)) {
($_ eq '-h' || $_ eq '--help') && do { &usage(); };
# ... more options here
($_ eq '--') && do { push(@args, @ARGV); undef @ARGV; last; };
($_ =~ m/^-.+/) && do {... |
This an update to my last question.
I want to process multiple pages at once pulling URLs from tier_list in the crawl_web method. The problem I am having is crawl_web already has two threads to crawl and index simultaneously, and the .join() seems to prevent opening more than one page.
import urllib2, collections, thre... |
This is a program to sort three inputted integers in order, from least to greatest. I would like to have it reviewed.
#include <iostream>
void Sort(int &a, int &b, int &c){
if(a>b){
int tmp = a;
a = b;
b = tmp;
}
if(a>c){
int tmp = a;
a=c;
c = tmp;
}
... |
Again, out of fun on Saturday night, I decided to solve the following problem from CodeEval.
The challenge is finding the index of the lowest unique number.
There is a game where each player picks a number from 1 to 9, writes
it on a paper and gives to a guide. A player wins if his number is the
lowest unique. We ... |
I'm implementing a password hashing method for a website. The code below is part of the User class.
Any pointers on what I could do better?
private string GenerateSalt(int SaltLength) {
using (var rng = new RNGCryptoServiceProvider()) {
var salt_bytes = new byte[SaltLength];
rng.GetNonZeroBytes(salt... |
Whenever I try to learn a new language, I write a subnetting calculator. Here's my attempt with Go.
In particular, I think I'm not writing idiomatic Go, as well as abusing float64(), uint64(), etc.
My math should be correct, although I might have goofed when trying to translate JavaScript's number types into Go's C-esq... |
This is the basic class that I am trying to display:
public class Day
{
public DateTime Date { get; private set; }
public SpecialDay SpecialDay { get; set; }
public DateTime TimeIn { get; private set; }
public DateTime TimeOut { get; private set; }
public DayOfWeek DayOfWeek
public TimeSpan... |
I am studying data structures at the moment, so I want to see if there is anything wrong with my implementation of linked lists in C, after I checked Implementing an ArrayList.
Header
#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
#include <stddef.h> /* size_t */
#include <stdbool.h> /* _Bool */
#define _LINKEDLIST_DEFAU... |
This is a brute force solution to Project Euler Problem 34 with only 1 optimization (i.e.: caching factorials):
import time, math
start = time.time()
total = 0
# Cache factorials
factorials = [math.factorial(x) for x in xrange(0,10)]
range_end = 7 * factorials[9]
for i in range(3,range_end+1):
number = i
fac... |
WeatherForecastRequest is only simple HTTP parameters wrapper. It is using to get forecast from the openweathermap.
At first here is utility class (used to simplify actions to post http request, receive response from server and convert it to String):
// import packages from org.apache.http.***
public class HttpRequest... |
I'm learning regex. Here I'm checking a string of type aA1 but want also to check it is only 3 characters long. Is there a better way of doing it please?
str = raw_input("input in form 'aA1' please >")
check = re.compile("[a-z][A-Z][0-9]")
if len(str) == 3:
validate = check.match(str)
if validate:
prin... |
As an answer to excersise 2.3 in Chris Okasaki's book, Purely Functional Data Structures,
Inserting an existing element into a binary search tree copies the
entire search path even though the copied nodes are indistinguishable
from the originals. Rewrite insert using exceptions to avoid this
copying. Establi... |
I was disappointed using GCM, so I'll use long polling for crucial parts. Following my approach:
protected void onCreate(Bundle savedInstanceState) {
new LongPolling().execute();
}
private class LongPolling extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... para... |
I recently programmed some byte swapping functions. As a special I did a function which can convert an entire int array. I please you to look at the following aspects:
portability
performance
usability
efficiency
#include <stdint.h>
uint16_t _bswap16(uint16_t a)
{
a = ((a & 0x00FF) << 8) | ((a & 0xFF00) >> 8);
r... |
I am learning Haskell and I am doing 99 Haskell problems. There is a problem to check if a list if a palindrome. It's obvious solution is
isPalindrome x = x == reverse x
There are several other solutions with some kind of reverse. All of them use two passes -- one for building reverse list and one more for ==. I wante... |
there is my implementation for cross domain call using the requireJs text plug-in
htaccess file in the template folder of my cross-domain site
Header set Access-Control-Allow-Origin "*"
textremote.js
define(['text','module'],function (text, module) {
// Load the cross-domain url from the config
var remoteUrl ... |
As part of creating a software defined receiver and decoder, I want to find sync pulses in weather satellite data. The data is first digitized to a 0-1 array.
The code below is working. The convolution method is sufficiently fast. The slow method is not.
I was wondering if there was a more efficient or "Pythonic" wa... |
This opens a file and writes 5120 times a string to it, and if the file doesn't exist it creates a new file. The name of the file and the string are chosen randomly. I would like to know if there is a way to speed up this code. It takes about 10 seconds at the moment. I was wondering if I did a recursion in the escreve... |
I'm attempting to tidy up a C++ framework (PyCXX).
One particular file contains ~400 lines of operator overload functions, which I've managed to reduce to the following:
#define OP( op, l, r, cmpL, cmpR ) \
bool operator op( l, r ) { return cmpL op cmpR; }
#define OPS( l, r, cmpL, cmpR ) \
OP( !=, l, r, cmpL, ... |
Follow up of Pygame menu to launch games
I rewrote most of the code per the one answer. I'm looking for further advice to improve to the code. I'm afraid some of the abstraction may be too Java-like. Some of the comments may be a bit stupid but no one in the group really knows Python or PyGame (including me).
menu.py:
... |
I'm 5 weeks into my first C++ class. I'm curious about how this code could be improved, more streamlined or simply things that I could/should have done better.
The project was:
Read from a .txt file that has different words on separate lines.
Determine how many vowels each word has, and print each word AND vowel c... |
One of the exercises I like to program when learning a new language is a chat client for the console. I've programmed it in many languages (Perl, Python, C, C++, JavaScript, ...). One of the versions I like most for its terseness is Ruby:
#!/usr/bin/ruby
require 'socket'
s = TCPSocket.new(ARGV[0], ARGV[1].to_i)
nick =... |
In answering password cracker in c with multithreading, I ended up writing a sample in C, which is not my forte.
Is there anything that I missed which should have been included in a responsible sample (read: likely to be copied and pasted into production code)?
// compile with `gcc counter.c -o counter -lpthread -Wall ... |
I'm making my first app in Swift: a Piano app. I'd like to get your feedback especially about how I can make codes shorter. I maybe have to use arrays and loops and something, and searched by myself but couldn't get it.
view controller.swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
v... |
I am learning about polymorphism in C++ and decided to implement an example. Is there anything I need to fix in my code? This compiles and runs.
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
class Employee
{
public:
Employee():salary(1000){}
virtual ~Employee(){}
virtual void Ta... |
In my webpage I have two places where I need my JavaScript to write dates. How to do it in one go?
Selectors:
var $today = $('#today');
var $selected = $('#selected');
If I were to do this alternatively the easy way, I'd do:
$('#today, #selected').html(date);
But I kind of need to reuse my #selected jQuery object thr... |
The Task
I was assigned a small task, concerning validation of Domain-Model classes.
The Validation for a String property of one of our Models was required to be unique across the whole Table. And as this already was halfway implemented after 20 minutes research, using a database constraint, it seemed fairly easy.
Obvi... |
I'm actually working on a piece of code which use the following code:
public Detail GetDetail(int id)
{
if (!_detail.ContainsKey(id))
{
GetDetailForNewObjects(id);
}
return _detail[id].Data;
}
The last line throws a NullReferenceException. Since it should not happen that this method is called ... |
I run a coding dojo at work. for one session I'm to showing that you can use a kata to get into a new language.
I'm using the FizzBuzz Kata to show JavaScript (and F#) because it is short. The problem is my JavaScript knowledge is only slightly above the copy -> paste -> fiddle level.
Thus, I would like to see better... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.