instruction stringlengths 71 71.9k |
|---|
My instincts are telling me a seasoned Scala programmer will find my code less than optimal. As will no doubt be obvious, I'm a Java guy who has just started in with Scala. Is there a more 'functional' way to accomplish this that I'm missing?
/**
* takes a file object and returns a string representing the fully qual... |
# Comment: You can iterate through any number of Enumerables in lockstep
e = {
numbers: 1..10,
letters: %w(a b c d e f g h i j),
notes: %w(do re mi fa so la ti do),
phonetic: %w(alpha bravo charlie delta echo),
rainbow: %w(red orange yellow green blue indigo violet)
}
# Titles
puts e.keys.map(&:c... |
I am trying to create a class that takes a screenshot of the screen, makes it blurry and saves it to NSUserDefaults.
- (UIImage*)blurImage
{
UIImage* newImage = [[UIImage screenshot] applyBlurWithRadius:20
blurType:BOXFILTER
... |
I ported the Star Trek 1971 game to Clojure to help me learn more about the language and functional programming in general. You can see the entire game on Github. The game plays (you can start it with lein run). Instructions are i game or you can see the first link to get more details on the history or gameplay.
While ... |
I'm looking for some help on how I can optimize adding multiple data attribute tags to elements, and really, any feedback at all.
Background
Client uses a analytics tool through a tag management application (Ensighten) that picks-up data attributes when links are clicked. I'm adding attributes when the DOM is ready to ... |
I've created the function below to get the SHA-1 of the repository used by my CI server. The hash is then used to update the pass/fail status of the commit on GitHub.
I'm a python amateur. What stands out below?
def get_sha():
root = os.environ["PWD"]
repodir = os.listdir(root)[0]
# /Library/Developer/Xcode... |
I came up with the following solution for rotating an NxN matrix 90 degrees clockwise, to solve this CodeEval challenge:
Input
The first argument is a file that contains 2D N×N matrices (where 1 <= N <= 10), presented in a serialized form (starting from the upper-left element), one matrix per line. The elements of a m... |
Here is some code I have written as a connect four negamax evaluation function. The state of the board is stored inside a class state. state.get() is \$O(1)\$, state.getBoard() is \$O(1)\$, and state.getWinnerColor() and state.getDraw() are also constant (although they have a higher constant coefficient). The real meat... |
I have a method which extracts the logged-in user details from a SpringSecurityContext object.
I have read that only utility methods (which does certain calculations) should be static.
Here is my method; it doesn't seem to be a utility method but I don't find any reason why I shouldn't make it static as I am using it i... |
I've implemented Game of Life in Python for a programming problem, in two different versions: one is a simple script and the other uses a class with a dictionary to initialize the various parameters.
Here is the version with a class:
# Object oriented implementaition of Conway's Game of life
import random
import time... |
I've got a small tomcat web application that's used to receive customer data from an iPad app. After receiving those information they will be saved on a local MySQL database and then sent to an SAP system.
I'm focusing on my "concept" of handling database connections since this is my first ever productive web app that ... |
I have a problem where I need to find the second maximum element of the user inputs. It's an online practice problem and I can't figure out why the server responds back with a Non-Zero Exit Code error when I submit my code. The program produces right outputs every single time when tested locally. Can someone tell me w... |
I'm trying to simulate the malloc function in C by using mmap and having 2 linked lists to act as memory blocks. The program works by reserving a region of memory and then keeps track of the free and allocated memory address with size in the linked lists. I have tested the program with normal cases like
free memory > ... |
I have a data representing several elements (that could be rendered at some point as div), composed of y position (property top) and its height (property height).
These elements are always positioned vertically one next/on-top of each others based on their order.
At the moment I am using the following script to calcula... |
Does this code show proper implementation of bubble sort algorithm? If not, why?
Can this code further be improved?
<?php
function swap($arr,$p1,$p2)
{
$temp = $arr[$p2];
$arr[$p2] = $arr[$p1];
$arr[$p1] = $temp;
return $arr;
}
function bubble($arr)
{
$count = count($arr);
for ($j = 1; $j < $c... |
I've prepared a script to manipulate csv files in Windows that simply adds quotes as requested.
The script creates a backup of the original files and overwrite the wrong originals in its same folder.
It works as expected but I'd be really happy to learn from gurus how to improve my code, my thinking and my Python.
#!/u... |
I have some enums that define measurement information, such as volume, mass, distance etc...
They are defined as such:
/// <summary>
/// Units for measurement of area.
/// </summary>
public enum Area
{
/// <summary>
/// Meters squared.
/// </summary>
M2 = 0,
/// <summary>
/// Feet squared.
/... |
I've decided to go tech and learn a language. I have been reading Java for a week and here is my first attempt. I am making a habit to write JUnit test cases so that I start on correct path. Here is an attempt to write program that dispenses coins in the denomination in the range of $20 to 1 cent inclusive.
package org... |
I am building a WPF application which uses a third party library to fetch objects which I want to allow the user to interact with.
The objects are returned as interface types. Am I right in thinking it is good practise to create wrapper classes for these objects instead of binding directly to the interface returned e.g... |
I have a list called all_dates which contains timestamps for a number of days (hourly). I wanted to select each day (i.e every 24 items in the list) and pass it to a function.
Here is my implementation that works:
count = 0
while count < len(all_dates)-1:
day_list = [all_dates[count]]
for i in xrange(23):
... |
I have a bunch of different ports I want to listen on and the iterate over the available data to send to a Dataflow pipeline. In total I'm listening on 14 ports. I'm looking for any advice on how to reduce the CPU usage of the following code.
I'm just passing in the ports to a method then adding them to a list:
publ... |
I created my own implementation of a Singly Linked List. Is there anything I can improve on, in terms of effciency. Also, what other methods would you recommend for me to try and implement. My goal is to just understand the components of basic data structures.
LinkedList:
public class StratchLinkedList {
private Node ... |
I have a web scraper that I use in a part of a larger program. However, I feel like I semi-repeat my code a lot and take up a lot of room. Is there any way I can condense this code?
def read_mail(mail):
url = [mail] # Ignore this line, please.
i = 0 # Ignore this line, please.
droppedSource = '<... |
I am working on a project in Java which includes a lot of database related tasks. For instance, I would have to insert, update, retrieve data so many times within the application. To use code reusability, I've just written this abstraction for my database class. I'm planing to call its methods where ever its needed to ... |
I've modified this example to better suit my needs in handling multiple custom file uploads on the same page. It also renders the filename or truncates if it is too long for each of the 3 file fields. This solution works well however, I think it could be DRY'd out a lot? This is where I landed:
$(document).on('change',... |
I asked for a review of my code, and after making the suggested changes I feel that now the OOP version is clearer in its meaning and overall the code looks cleaner.
"""Object oriented implementaition of Conway's Game of life"""
import random
import time
import os
class GameOfLife():
FILE_NAME = "grid.txt"
ROW... |
I have a map in which I store total bytes as the key and count of users as the value:
Map<Integer, Integer> userHistogramInfo = new HashMap<Integer, Integer>();
Now I need to make a histogram as mentioned below:
How many users have data with 200,000 bytes (200 kilo bytes)
How many users have data with 500 bytes
How m... |
I'm trying to get my head around the OOP principles and coding my own classes. As a means to learn, I have decided to convert a couple of functions I have written in Wordpress to OOP classes. These functions work together in order to output the correct post links on single pages according to referrers (4 of them) set i... |
I am trying to improve my programming and programming design skills (poor at the moment). I created a small Amazon scraper program. It is a working program. I would be very grateful if you could review my design. What could be improved? Does my class design make sense?
main.py:
if __name__ == "__main__":
from Scrap... |
I've been working on implementing a Trie in Python for educational purposes. I tried implementing one using dictionaries and I was successful.
The structure of a trie with the words in, inn, inner, innerr would be as follows:
[['i', [['n', [['n', [['e', [['r', [['r', [], 'end']], 'end']]]], 'end']], 'end']]]]
where en... |
How can I vectorize this code snippet and eliminate this double loop? Even with "only" 1001 elements in a this takes almost 30s.
a = np.linspace(-.5, .5, 1001)
S = np.zeros((a.size, a.size))
# east, north and tp are np.arrays of equal length
for l, sy in enumerate(a):
for k, sx in enumerate(a):
S[l,k] ... |
I have written a windows service for one of our local servers. This service works like a gem on my local machine, does what it's supposed to (ACCP to exchange db data), but I'm not overly familiar with dependencies. Is this an appropriate way to receive/send a message?
string DBP3_US = DBP3_US;
string PING_DEPENDENCY =... |
I have developed a TCP listener to receive messages from a client machine, take that string and put it in a db, then send back a response with some data relating to that string. First attempt at a tcp network stream send and reply, just need to see if this will result in any easily avoidable "hiccups" or incorrect data... |
I have code that dynamically adds blocks of information to my page. I don't know in advance how many blocks there will be. I want to utilize Twitter Bootstrap (3.x) to layout them in three columns (e.g. I want to use col-xs-4).
Bottom line: is it okay to add col-* elements to a container without wrapping them in row el... |
This is my first Python text-based game. Let me know if there is something I should improve on or fix in the way that my code is written because I feel that I am being very redundant in my code, but I'm just learning this stuff.
Also note that note.txt just says:
this cabin will self destruct in.....
#Lost In the Woo... |
I have the following code snippet where I'm picking up a file from an FTP server and then streaming it to OpenCSV. I have very little experience with streams, so I'd like to have someone review this code for efficiency. I use this on the cloud, so I/O and memory efficiency is important. Generally my CSV files consist o... |
For the below given exercise:
Define a function cycle which takes in three functions as arguments: f1, f2, f3. cycle will then return another function. The returned fuction should take in an integer argument n and do the following:
return a function that takes in an argument x and does the following:
if n is 0, just r... |
Can someone review my Controller? I should follow these guidelines:
Code should be written with MVC pattern and to use OOP.
The code now works fine, but I need to improve it. Also, should I use more Ajax Model?
This code is used to receive data from a jQuery script and send it back. Almost every method does the same.... |
I have created a script which presents a popup on every 5th pageview.
I would like to try to use just PHP cookies. However, due to the requirement of setting them before any content is output, it has made it tricky.
I would also like to just include this script and have it run. At the moment I believe the breaks are ... |
I have two tasks:
Write a function that starts and monitors several worker processes. If any of the worker processes dies abnormally, restart it
Here is the code that I built:
proc() ->
receive
p -> exit("I need to die")
end.
start_and_monitor(0) ->
spawn_monitor(proc()),
receive
... |
This is a rags-to-riches question, the original is here: Coin dispenser program
There are three parts to this, a Denomination enum, a Calculator utility class and the unit test for it, using TestNG.
Please feel free to comment on any parts of the code, including comments.
Denomination enum
import java.math.BigDecimal;
... |
I've written a more powerful version of the Sieve of Eratosthenes, this Sieve returns the number of factors of all the numbers below the limit.Sadly the running time is \$O(n^2)\$, so it is much slower than the ordinary sieve. Can you suggest a way to improve and optimize it?
import doctest
def factors_sieve(limit):
... |
This works, and I personally find it elegant and kind of "neat," but then I worry it's a bit too tricky. Comments welcome:
function (reports) {
reports.forEach(function (report, i) {
report.upPercentage = report.upTime / report.totalTime;
report.rank = i; // temporary storage in a convenient locatio... |
I'm learning C++ and also about data structures, so I am trying to implement some. This is my linked list. I've included two different ways of getting the length of the list, with a length variable and also a function (getLength2) that goes through the list until it finds a NULL pointer. I suspect that there could be m... |
I've written a Python script to generate the closest square spiral matrix to a given number.
I'm new to code reviews as a practice, and I'm interested in ways to improve. Please suggest improvements to the code where you see fit, particularly in regards to:
Algorithm: Is there a faster/more elegant way to generate the... |
I have written a bash script that consists of multiple commands and Python scripts. The goal is to make a pipeline for detecting long non coding RNA from a certain input. Ultimately I would like to turn this into a app and host it on some bioinformatics website. One problem I am facing is using getopt tools in bash. I ... |
Here is my JavaScript function to manipulate the hash:
var hash = {
get: function(key){
var lh = location.hash;
if(lh.charAt(0) === "#"){
lh = lh.slice(1);
}
var pairs = lh.split("&");
var obj = [];
for(var i = 0; i < pairs.length; i++){
var ... |
I am a beginner in Java and programming at all. I decide to try to write a calculator, as a my first "complete" program. It works for me, however I am curious is it worth anything in reality. I would be very grateful for any comments and advices.
I am especially concerned about:
usage of access modifiers - am I doing ... |
This is what I coded to realize a command line program to make it easier to manage emails on ovh shared hostings. It's working ok but it seems ugly.
I'm a beginner with Python and docopt. What would you suggest?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' OVH Email Manager (ovhEmailMan)
A small script that helps... |
At some point, I have this function which updates a color picker according the the mouse position, according to whether the user clicked a mouse button and according to its previous state:
updateColorPickerState :: ColorPicker -> (GLfloat, GLfloat) -> Bool -> ColorPicker
updateColorPickerState c (x,y) mou... |
I was challenged to implement a mechanmism to support indexed properties in a class structure.
I wanted to avoid the need to implement an abstract property indexer class every time you want to implement a new T just because the backing store has changed. Semantically, if C# did provide indexed properties, the get/set ... |
I recently had my site hacked, with the main index file being overwritten (nothing else was touched). I'm assuming they hijacked my form input.
Are there any vulnerabilities in the code or does this look to be safe now?
<?php
$myemail = "...@gmail.com";
$subject = "Form Submitted";
$name = $_POST['name'];
$emai... |
Challenge:
You are given a line of N cells with positive integers written in them. Initially a chip is placed on the leftmost cell. Each time it can be moved in any direction (to the left or to the right) on a neighboring cell or across the neighboring cell on the next one. The move is valid if the two numbers - the o... |
I have written a simple stack implementation and would like some feedback as to what I could improve in my code and coding practices.
# A simple stack in python with ints.
class stack():
def __init__(self, maxSize=16):
self.maxSize = maxSize
self.data = []
def isEmpty(self):
if len(self... |
I've been doing network programming using C#'s TcpClient for several years. The code below is an asynchronous wrapper for TcpClient that I developed throughout these years.
The key methods are:
ConnectAsync() - connects asynchronously; RemoteServerInfo is a simple class containing Host, Port, and a boolean indicating ... |
I've implemented the multiclass perceptron in the one vs. all style.
I just thought about it and tried to implement it in the most basic way. I think it's correct though my f_measure is a bit low. Which I believe is due in part to the fact that I haven't cleaned up my input, it's a feature vector of document words and... |
My Java program is a module called configProxy which fetches configuration entries from a remote node (say from a Redis instance). When the caller calls the get(configKey) method, this module checks in a local cache (a concurrent hashmap) to see if the setting is already cached. If not, it fetches the setting from a R... |
How do I improve speed of this code? The problem definition is "Find the sum of all the multiples of 3 or 5 below N".
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}
import qualified Data.ByteString.Lazy as L
import Control.Monad (forM_)
readInt :: L.ByteString -> Int
readInt !s = L.foldl' (\x c -> 10 *... |
For the given below exercise:
Here is one method to check if a number is prime:
def is_prime(n):
k = 2
while k < n:
if n % k == 0:
return False
k += 1
return True
How does this function work?
This is a decent way of testing if a number is prime, but looping k all the way to n
... |
The following code is used to convert a base-10 number to a base-N number, where N is a length of a given alphabet that contains characters of which a base-N number can consist.
The number to convert is always increasing, like from 1 to 45789, not from 536 to 13. The resulting number may not contain zero as first digi... |
Does this code show proper implementation of quick sort algorithm? If not, why? Can this code further be improved?
<?php
$unsorted = range(1,20);
shuffle($unsorted);
function quick_sort($array)
{
// find array size
$length = count($array);
// base case test, if array of length 0 then just return array
... |
I am in the process of learning Java and going through the Euler problems. For Problem 4 I decided to also implement a TDD approach with JUnit.
My questions are:
Is there a better TDD approach to this problem?
I wrote out all these test cases initially. Some obviously pass and some fail initially because I'm checking... |
I have written this script to install gcc (here in version 4.9.2) on Centos6.6. I am only interested in C and C++ support.
Please comment if this is any good and can I make it better before I get the packages for those.
#!/bin/bash
LOGFILE=/tmp/gcc_install.log
# $1 - package name
# $2 - status
errorIf(){
if [ $2 -ne ... |
Anyone who has programmed in TI-Basic is likely to have written one of these programs. The concept for this program is simple.
The "ball" represented by a single point that originates from the upper left hand corner of the screen and bounces around the screen leaving a trail as it travels. The initial movement vector ... |
I have a set of names and a request with asterisks. An asterisk can be replaced with any letter.
For example, there is a set of names: hasad, ahmed, fizo. And there are a few sample requests: hasad, has**, fizoo. The first one and the second one should return YES, and the third one should return NO.
Here is the source ... |
I was searching for a way to exercise the Java 8 concepts I've been learning, especially pertaining to Lambdas. Incidentally, I hadn't used any swing in a while and wanted a refresher. This is the result of these two pursuits.
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import ... |
I have a simple game that implements a TimerTask. However, when there's a popup using JOptionPane the timer task doesn't seem to actually pause. I know I could maybe find a way to pause the TimerTask when there's a popup until the user input happens but I'd rather just work on using the best timer method from the get g... |
I often come across situations where a library component needs to buffer a large amount of data for later processing. The problem is that at the design stage a choice needs to be made as to whether to store copies of, or references to, the data. Both methods have advantages/disadvantages:
Storing copies requires eithe... |
I've decided to challenge myself by writing a test standalone DLL with the objective of making all of its publicly-exposed objects able to be as intuitive and as simple-to-use as possible.
I've decided to try and create some objects that might be used in a game, like a deck of cards and a die.
Here's my Die for example... |
Just because I've never written a real Sieve of Eratosthenes, I decided I should probably write one just to make sure I know what it is. I'd like (constructive) criticism on best practices, potential problems, and anything else you see fit:
static int GetNthPrime(int n)
{
List<int> primes = new List<int>() { 2, 3 ... |
I wrote this code, as a novice a to Prolog, for a challenge posted on /r/DailyProgrammer. The formal description of this challenge, as presented in the prompt reads:
Input description
On console input you will be given a variable number of 0's and 1's
that correspond to letters in the alphabet [a-z] and whitespace '... |
I have written a fixed-size block allocator implementation and would like some feedback as to what I could improve in my code and coding practices. Your comments or notes are welcomed!
An auxiliary allocator (non-typed, instead unique for the given size of a chunk; without necessary interface for STL containers):
#incl... |
I am new to Python and I am writing my first utility as a way to learn about strings, files, etc. I am writing a simple utility using string replacement to batch output HTML files. The program takes as inputs a CSV file and an HTML template file and will output an HTML file for each data row in the CSV file.
CSV Inp... |
Below is a simple random walk predator prey simulation that is optimized to the best of my abilities. I would love to hear about any improvements that can made.
import numpy as np
import time
from matplotlib import pylab as plt
import random
def run():
# Initialize grid
size = 100
dims = 2
# Each point... |
I need to use the English numerals (American) in Haskell, so I looked for a library that did it. I have not found one, therefore I developed the program that I am presenting here. There are actually two versions of the program: one "analytical" and the other "synthetic".
The analytical version (presented here) aims to ... |
For class I have to write a program that reads (plaintext) numbers from a file, and inserts them into an AVL tree stored in another (binary) file. I cannot have more than about 10 nodes in memory at one time. I've written the code and it works fine, but I feel it's running slower than it could. I can currently process ... |
I would love some suggestions on this code of mine, pointers on overall design, code quality, optimization in terms of memory and speed.
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <time.h>
#define NUM_OF_READERS 10
#define NUM_OF_WRITERS 100
static int glob = 0;
stat... |
I made this Blackjack game to help me learn the syntax of JavaScript classes and objects.
As I was writing the game I felt like I was misusing the idea of OOP. By that I mean I felt like some of the variables/methods of the class could be non related to the class and still work.
Let me know how I could improve this.
... |
This Code is old and I am trying to figure out how to improve it. I am considering running the distance function in MySQL, but it is a ***** to figure out for me due to my experience with arithmetic in MySQL.
$id = $_GET['id'];
$data = $_SESSION[$id];
$airline = $data['airline'];
$hub = $data['hub'];
... |
The main idea behind this code is to distribute multiple random numbers, but guarantee that the probability of each coming is equal.
The code is really basic:
( function( window ){
window.RNG = function(min, max){
if( min / 1 != min )
{
throw new TypeError('Expecting Number or NumericS... |
I haven't really programmed in C++ for about a year, and realised that I should get back into it, and tried my abilities out by remaking the STD vector class. However, my C++ is a bit rusty at the moment, and was wondering if I have made many mistakes in my implementation.
# ifndef VECTOR_H
# define VECTOR_H
# include ... |
I need to find a way how to create a frequency distribution out of multilple text files. In fact I am asked to check the number of times a word or a phrase occurs in a txt file. The code should check from a predefinded list (my list is called l1) how often this word or phrase can be found in the doc. My output should l... |
I have code that zips 3 lists, finds a maximum and extracts part of the max tuple. Isn't there a shorter way to do this in F#?
let Triplets = List.zip3 A B C
let T1 (x, _, _) = x
let T2 (_, x, _) = x
let T3 (_, _, x) = x
let Best = List.maxBy T3 Triplets
T1 Best,T2 Best // return to C# code
|
There is a type of diagram summarizing how well predictions from numerical models fit expectations; one obvious use case is comparing machine-learning regression models. Modified Taylor diagrams are described in this paper.
I'd like to know if my implementation follows best practices for using matplotlib, and how I mig... |
I am using .Net Identity 2.0 with Entity Framework 6.0. I have a Person class inheriting IdentityUser. I have a Teacher (has additional Title property) and Student (has additional StudentNumber property) class inheriting from the Person class. I also have their corresponding roles in the database: Student and Instructo... |
I have the following code that works perfectly other than the fact that it has to use async false, to wait for a response from ajax. Is there a way of restructuring this by using callbacks, or deferment?
playbtn.on('mousedown', function () { // functions when clicking play button
function checkUser() {
$.a... |
Our Rubberduck VBA IDE Add In does some static code analysis, and then reports all of the found issues back in a gridview. This analysis can take a long time for larger projects and the UI appeared to be frozen until all of the analysis was complete. I've corrected that issue by updating the number of issues found as t... |
I am interested in collecting directly into R data published by the Mexican Met-office. The data pieces are spread through several URLs, but one can start here. There I can get the names and locations of all stations and links to locations where the details of each station are displayed separately. At that last loca... |
I have attempted to create a view helper class which makes programmatically creating HTML strings less verbose and hopefully simpler.
This is inspired by the tag helpers in Rails. It's compatible with the Symfony2 Templating Component but can be used outside Symfony.
It also has methods for creating tags for stylesheet... |
Is it possible to combine these queries into one query? I am trying to see and average all scores but also count and average just the last three based on the same grouping.
This is the main query:
$query4 ="SELECT
studentsisid,coursename,learningoutcomeid,learningoutcomename,count(RecordID) as assessmentcount,
count(... |
I'm creating a user account login with PHP and Mysql which will be used by school teachers. To login there are 3 items required : school, username and password. This will allow for 2 of "MRSMITH" in two different schools.
The database is:
schools.login_name is the school part of the login
admin_users.username this is ... |
I need to access those elements of a large numpy array that lie in a small triangular area. The brute force solutions of using matplotlib.path.contains_points or ImageDraw.Draw.Polygon are too slow for my liking because they return a boolean array instead of a list of indices for accessing the relevant elements.
So ins... |
I am inexperienced in C++. I was able to get my LinkedList to be fully functional. I was hoping to get some feedback as to whether or not I followed bad practices and if there are any risks associated with my code.
LinkedList.h
#pragma once
#include <string>
#include "Node.h"
class LinkedList
{
private:
Node *... |
I have been trying to write an analogy to this approach to distributed locking with two differences:
making it asynchronous
making it work with StackExchange.Redis rather than AppFabric Cache.
My biggest concern is going out of my way to use IDisposable to make it compatible with using() but thus calling an async met... |
I am trying to solve this problem on SPOJ Brazil. I'm trying to approach the problem with a series of logical conditions and my code looks like this and it works perfectly.
#include <stdio.h>
typedef struct {
int y1;
int x1;
int x2;
int y2;
}coordinate;
int main(){
int N, C, i, j, xi, xf, nbact... |
I learned of the Database Access Object design pattern from a friend and decided to implement it recently to my MySQL database. The code uses MySQLi to connect to the Database, and uses prepared statements to execute all queries. I have tried to apply OOP principles in creating these series of classes (encapsulation, c... |
This code is part of a growing "primitive" tools collection here on github
Use Case
Consider:
IntArray ia = new IntArray();
ia.set(300, 5);
System.out.printf("Values at 10, 300, and 3000 are: %d %d and %d\n",
ia.get(10), ia.get(300), ia.get(3000));
This gives:
Values at 10, 300, and 3000 are: 0 5 and 0
Prim... |
I want to become a good Python programmer and so I'd like to know what in my code practices I can improve. Overall I feel like a pretty solid programmer but writing this code felt very "Java" so I am probably still following poor practices in terms of following Python code practices.
__author__ = "arthur"
import panda... |
I have a function that compares two doubles to N decimal places.
#include <cmath>
#include <iostream>
using namespace std;
enum class RelType : int { Less, Equal, Greater };
RelType _compare(double v1, double v2, int multiplier)
{
if (std::round(v1 * multiplier) == std::round(v2 * multiplier))
return Rel... |
I am working on an interview question from Amazon Software Interview:
Given an integer N and an array of unsorted integers A find all pairs of numbers within A which add up to N
I have a working solution in Java:
static void allPairsAddToN(int[] array, int n) {
for(int c=0;c<array.length; c ++) {
for(int ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.