instruction stringlengths 71 71.9k |
|---|
I am working on a project where the hotspot is some code that is supposed to find an offset, such that the squared differences between a reference vector and a given vector becomes minimal. The core function is this:
#include <vector>
#include <map>
typedef std::vector<double> vect_d
double sqDiffSum(const vect_d& ref... |
I made a website where is possible to search for the best transportation from a place to another. For instance, if I need to go from Berlin to Bremen, the website will search in its internal database for all the trains and buses that will cover that distance.
To give the results, the websites look for all the trains wh... |
I have been making a small game which resembles a computers terminal. There isn't much in the way of a game, but before I go any further I want to know if there are any things that I can improve, or make more efficient.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Date;
import java.awt.Dimensi... |
I tried to solve the following problem in a programming challenge, but the verdict was time limit exceeded.
Completely parenthesized expression
Write a program that reads a completely parenthesized expression, and
prints the result of evaluating it. The three possible operators are
sum, substraction and multiplica... |
The code below is part of a toy test assertion library I've written.
I'm looking for feedback specifically on lines 4 - 9. I'd like to extract them from the throws function. I can think of two options.
Create a function with a name like maybeReportExceptionError(). This seems not great because a) it feels like th... |
I wrote a program that goes through a webpage and returns matches of regex. I used it on my letterboxd.com account to go through all of my movies (over 900 entries) and then find genres field for each of them in order to get the number of movies I've seen in each genre (that makes 53 pages for getting urls for the movi... |
I do some work that involves translating resources for a webpage. These are all stored in a SQL Server table that looks like this (plus a few irrelevant constraints).
CREATE TABLE [dbo].[tblResources](
[lResourceID] [int] IDENTITY(1000,1) NOT NULL,
[lLocaleID] [int] NOT NULL,
[txtResourceKey] [varchar](255)... |
I have to parse a json object that can be a string, array, array of strings and array of object. I realised that it's not good from the beginning that one object can be many types, but I can't change the code from upstream so
I'll have to deal it in my code instead. I'm building a pixel library for modern browser so I... |
I wrote this code for an answer over on SO. I suspect it's possible to clean it up a bit, particularly the base-case specialization for FactorialArray, which is repetitive and contains odd bits (for instance: why double curly braces? because clang complains about un-braced subobject initializers otherwise...)
Any and ... |
I have been assigned to developed a feature that filters a conversation. For example, I want to filter the conversation by user id then export it to something either JSON or text file. In this case, I created a class that handles the filters like this.
import java.util.ArrayList;
import java.util.List;
/**
* Represen... |
I wanted to learn some regex, but learning regex is super boring so I decided to write a password validator that will validate a password with regular expressions.
How it works:
You enter a password that has no echo thanks to the getpass library
The password is run against five different validations such as, upper cas... |
Is this the correct way to set value of textbox to zero when it's null? Is there any way I can improve the calculation that I am doing?
private void TB_PAID_CASH_TextChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(TB_TOTAL_INV.Text) && !string.IsNullOrEmpty(TB_PAID_CASH.Text) && st... |
My code creates a Mad Libs program. Its a prewritten story that you fill in blindly. There are 4 pages of 7 entry boxs and labels. When the inputs are in and next is pressed it saves inputs as variables that it puts in the story and changes the labels. When all blanks have been written in. An info box pops up with the ... |
I've been working wrapping the Windows API's Overlapped methods in the more usable Task based approach. There isn't much information out there on doing this, so I've been flying blind apart from a few blog posts. I was hoping to get feedback on what I've come up with so far.
An example method is as follows.
private Tas... |
I have a function that uses Windows Update Agent (WUA) API through COM using the win32com.client module, part of pywin32 package for retrieving the installed and the available (not yet installed) Windows Updates. For each update, name, url of the relative Microsoft documentation and category is displayed. Finally the f... |
Poker is 52 cards - 4 suite and 13 rank:
Hand is exaclty 5 cards
Order of hands
Straight-flush - all same suite and in order
Quad four of same rank
Boat three of one rank and two of another rank
Straight e.g. 56789
Ace 0 counts as both low and high 01234 and 9,10,11,12,0
Two pair
One pair
High card
This code gives t... |
I wrote this for an A* implementation:
(pqueue.c)
#include "pqueue.h"
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
struct pqueue* new_pqueue(size_t capacity, int mt) {
struct pqueue* pqueue = malloc(sizeof(struct pqueue));
pqueue->capacity = capacity;
... |
Using the wine quality dataset, I'm attempting to perform a simple KNN classification (w/ a scaler, and the classifier in a pipeline). It works, but I've never used cross_val_scores this way and I wanted to be sure that there isn't a better way. For me, it became a little less straightforward using the cross_val_scores... |
Background
My mother has a hobby of buying and reselling books via online trading sites. After a price is agreed on, the books have to be put into an envelope for mailing. On this envelope, stamps have to be applied to pay for postage (mailing fee). My mother buys stamps in bulk at various prices, varying from 75 to 90... |
For a utility class, I've created a particular implementation of a list where the list's items can be limited to a specific range, using the google guava Range utility. Items in the list must accordingly implement Comparable. When an item is added or retrieved from the list, they will be within the specified range.
Not... |
Here is my simple code for LRU cache in Python 2.7. Appreciate if anyone could review for logic correctness and also potential performance improvements.
A confusion want to ask for advice is, I am using a list to track access time, the first element of the list the is least time accessed, and the last element is the mo... |
I am trying to create my own algorithmic trading system using C++. I have searched the web for a nice tutorial for such systems and I didn't find any. Then I started to learn about curl and jsoncpp libraries and even documentation of those libraries are not made for a novice programmer like me. I mostly reused most of ... |
This returns the smallest snippet from the content containing all of the given keywords (in any order). This provides the correct solution but I would like to know if it can be made more efficient.
import itertools, re
def solve(content, keywords):
content = content.strip()
contentWords = content.split()
t... |
I was in the mood for some C++ and decided to write a command line calculator, which understands addition, subtraction, multiplication and parentheses. See what I have:
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stack>
#include <stdexcept>
#inclu... |
A jail has prisoners, and each prisoner has a unique id number, S, ranging from 1 to N. There are M sweets that must be distributed to the prisoners.
The jailer decides the fairest way to do this is by sitting the prisoners down in a circle (ordered by ascending S), and then, starting with some random S, distribute on... |
so I wrote a queue implementation in c++ and even though I know the code probably isn't as robust as it should be and probably doesn't perform all the checks it should, I'd like to know mostly if there is any functionality difference between my implementation and the one in STL.
My implementation idea is to use a circ... |
I created a simple matrix implementation and would like some critique of it, for example:
Things I could add to make it more useful
Ways I could make it more efficient (for example __pow__ or ref())
How I could improve my code format / comments
Source:
import math
class InvalidMatrixDimensions(Exception):
"""Ma... |
I solved exercise 8 from Core Java for Impatient, chapter 1. This exercise is to implement a displayAllCombinations method to display all substrings of the given string.
I would like to prove that following algorithm is valid in Java. I wonder if there is an easier solution?
package pl.hubot.exercises.corejava.r01.ex... |
The code uses the XML-based OC Transpo data feed to create a list of the bus name, where it's headed, and the times. Keep in mind that I am a beginner at python so any advice at all is appreciated.
import subprocess, pprint
from bs4 import BeautifulSoup
def format_set(result_set):
new_set = []
for el in resu... |
I'm thinking about DOM modification performance.
In a perfect way, we alter each element but DOM modification is really heavy and alter many elements at same time froze the browser. I didn't make any performance tests but I want to know if the second way can be more powerful.
In my head, the first way will ask the brow... |
This post is a continuation of my previous post where I used jsoncpp package to fetch exchange rates from fixer.io. In this post I have reused the above code and used it to fetch stock historical price data using C++ and save the fetched data to a external CSV file. You can edit the api url(https://query.yahooapis.com)... |
I've been developing an application based on Symfony 3, and part of that application involves an import process where a user can upload csv files. One thing that I've never been too sure about with symfony is using the forms component without a database entity to attach it too. In the past I've typically just used an... |
EDIT: New version can be found here: C++ getaddrinfo()/addrinfo wrapper (rewrite)
I'm a C++ novice, but an experienced Python and C programmer. I decided to code a C++ wrapper around getaddrinfo() to get my feet wet (targeted at Unix, specifically). Am I using good style/best practises? How can I improve this?
#include... |
I'm using SVNKit to get diff information between two revisions. I'm using the diff utility to generate a diff file, however I still need to parse it into numbers.
I implemented a solution, but it is rather slow. JGit does something similar, however it actually parses the values itself and returns an object, rather than... |
I have written an insertion sort algorithm in JavaScript:
function insertionSort(inputArray){
var totalElements = inputArray.length - 1;
var temp = 0;
var lastIndex = 0;
var prevIndex = 0;
for(var i = 0; i <= totalElements; i++){
for(var currentIndex = i; currentIndex > lastIndex; currentIndex--){
... |
To avoid the overridable method call in constructor dilemma this approache delegate the variables initialization and calls to overridable methods to a member method that return reference to the instance its self and exception to be thrown if trying to use instance without invoking the initialization method/s so that th... |
The code extracts two substrings from different strings and concatinating them to provide the largest possible palindromic string.
Objective:
You have two strings, (a) and (b). Find a string, (c), such that:
(c)=(d)+(e).
(d),(e) can be expressed as where (d) is a non-empty substring of (a)
and (e) is a non-empty ... |
I have a simple implementation for "Async.sequence" (the name came from here), but I would like someone to review it for performance, tail call optimization, and functional style.
It has the following signature, which is similar to Async.Parallel:
Async<'a> list -> Async<'a list>
Async.Parallel would be ideal for perf... |
This is a revised version of a previous post. I attempted to address each aspect of the feedback provided. The key changes are as follows:
Replace the deprecated usleep() with nanosleep()
Removed the dependency on CS50 library header by pulling out the relevant pieces.
I followed pacmaninbw's advice in avoiding global... |
I am a beginner in Java programming, and I created a calculator as my first Java project. Therefore, can you review my code and provide feedbacks/ tips?
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
double firstnum, secondnum, answer1, answer2, answer3, answe... |
I solve this problem in Swift. Looking for feedback on my code or a better solution:
import Foundation
// parses line to return array of numbers in string format
func readIntegers() -> [String] {
return readLine()!.componentsSeparatedByString(" ").map { $0 }
}
// left rotates the array by a given input
func left... |
Given a set, generate all permutations:
(permutations #{1 4 5}) => ((5 4 1) (4 5 1) (5 1 4) (1 5 4) (4 1 5) (1 4 5))
Here's what I cobbled together:
(defn perm-r [allPerms currentPerm input i]
(cond
(empty? input) (conj allPerms currentPerm)
(< i 0) allPerms
:else (perm-r
(perm-r
... |
Here's an odd pattern I found for sieving out composite numbers to find primes. I wrote it myself, originally thinking I made an indexing error, but it turned out to work after removing squares.
import bitarray
def sieve(n):
"""bitarray sieve"""
b=bitarray.bitarray([1]*(n+1))
x=int(n**.5)+1
for k in ran... |
I made a function that contains the database connection and query. Now I'm always calling this function every time I need to query a database. Is it good or is there another way better?
Database connection:
/* Database Configuration */
DEFINE( "DATABASE_HOST", "" );
DEFINE( "DATABASE_USERNAME", "" );
DEFINE( "DATAB... |
There is an Employee table with data like:
ID FIRST_NAME END_DATE CITY
23 Manoj 24-JUL-16 08.45.02.000000 AM Bangalore
22 Abhishek 24-JUL-16 08.45.01.000000 AM Bangalore
24 Nilu 24-JUL-16 08.46.01.000000 AM Bangalore
25 Niroj 24-JUL-16 12.08.43.000... |
As suggested by @Dannnno on my original post, I am posting my partially rewritten getaddrinfo() (and now addrinfo) wrapper for merciless review. I've made quite a few changes to the code as suggested originally, and included a minimal example of main() to show how it comes together.
Some things I'd like to note:
I dec... |
The goal of the following short Python 3 program is to improve my understanding of the decorator design pattern. Therefore, I would be mostly interested about feedback on this aspect, i.e. whether this is a correct usage of mentioned pattern. Also, I would like some comments regarding Python coding best practices, i.e.... |
I am looking for making my code faster. I am working on yoochoose recsys 2015 dataset.. and trying to perform some transformations.. [recsys2015], it has got 30 million plus rows of data. The goal of my code is to extract time duration in the session with the help of python, and the day , hour segment etc, however I re... |
I want to get latest time slots for 2 cases based on doorman true for false based on logged in user.
Cases are:
If doorman is true, the query will be the same
if doorman is false, then I need to add a parameter in the query for doorman that its is false so give me only records having none in them
So, it's the same q... |
I was reading this post and saw quite few improvements. So I tried to rewrite it using Java 8 features. Any improvements you can spot, please feel free to mention.
public static void main(String[] args) {
boolean runAgain = false;
Double result = .0;
List<Double> inputs = new ArrayList<Double>();
Scann... |
I am coming from Java and I am trying to create a process pool in Erlang.
Like the Java API:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
I can define core threads, time to kill thread, and policy to di... |
Can someone please review my code? Is it the correct implementation of a queue? If not, please give suggestions on how to implement it using a linked list.
class Queue
{
Node front,rear;
class Node
{
int data;
Node next;
public Node(int d)
{
data=d;
next=null;
}
}
void enqueue(int... |
I am currently only doing one generation. I'd like a review of my code.
Game of Life: The universe of the Game of Life is an infinite
two-dimensional orthogonal grid of square cells, each of which is in
one of two possible states, live or dead. Every cell interacts with
its eight neighbours, which are the cells ... |
const GAME_STATE = (function() {
let canvas = document.getElementById('gameboard');
let scoreBoard = document.querySelector('.scoreboard');
let highscoreLabel = document.querySelector('.highscore');
canvas.width = 800;
canvas.height = 600;
let ctx = canvas.getContext('2d'),
gameBoardHeight = canva... |
WeakPtr can point to any object provided it inherits from WeakBase. So, for example, you could use it to observe an object managed by a unique_ptr (that's my use case). It is not possible to make this thread safe.
Curious what could be improved.
#ifndef WeakPtr_h
#define WeakPtr_h
#include <memory>
#include <iostream>... |
I have implemented a kind of thing that does event triggering in Golang. This is open-sourced here. Review and suggestions appreciated.
First thing I am trying to implement is adding event listeners to a trigger:
func (t *trigger) On(event string, task interface{}) error {
if _, ok := t.functionMap[event]; ok {
... |
Following this website I wrote a neural network which uses the MNIST training data to recognize digits. The author writes that it should take a couple of minutes to train the network with 30 epochs of training. My network needs something like 5 minutes alone for 1 epoch of training.
How could I make it process faster?
... |
I'm making my first foray into Rust. I wanted to copy a fun and non utilitarian tool so I chose CowSay. It's not feature complete (CowSay has a lot of options) but it's a start.
My primary reasons for asking here are:
To get better at idiomatic Rust (this is the first thing I've written in the language)
Improve the im... |
I have a database connection PHP file which has a lot of queries to the database. Here are 3 of the functions that I am using:
public function deleteAccount($token)
{
$sql1 =
"DELETE FROM $this->table_user
WHERE $this->key_token = ?;";
$stmt1 = $this->connection->prepare($sql1);
$stmt1->bi... |
Challenge
Write a program which reads a file containing Morse Code and outputs the conversion.
Specifications
The first argument is a path to a file.
The file contains multiple lines.
Each line is a string of Morse code.
Each letter is separated by a space.
Each word is separated by two spaces.
Constraints
The... |
I am hoping I can get some guidance on some better "best practice" suggestions on how to handle this kind of code set. I understand that parameterized queries are a thing, but I am not quite there yet, but feel free to drop link to good tutorial on that if you must include that as part of your suggestion.
Here is my co... |
Build a system for entering and displaying the allergies that patients may have.
The allergy will have its own set of symptoms reactions. The allergy will also have a spectrum of severity which the clinician should be aware of, and allergies can be reported by the patient or by next of kin.
Please review my code ... |
It seems like I'm repeating myself here. Is there a standard way to deal with code like this?
def getNameParts(name):
"""Return a dictionary of a name's parts.
name: e.g. 'JOHNSON, John Roberts, Jr. (Jack)'
Ignores nicknames.
"""
csSplit = name.split(', ')
try:
last = csSplit[0]
exce... |
Background
I have an RDLC that among other things displays text coming in that is captured in SharePoint, using a custom control (TinyMCE) that exposes limited formatting options to users.
The SSRS local report renderer supports a subset of HTML (see details here) and has limited configurability. It has some rendering ... |
This was my second project as a beginner in Java programming. Please provide feedback/ tips on my program.
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner Area = new Scanner (System.in);
double length, width,totalArea, height;
String shape,... |
Instead of having to use something like char buf[100500] and hope that no possible user input could be longer than 100500 bytes, I decided to make the following function:
char* input (FILE* in, size_t size)
{
char * input_str = NULL;
int c;
size_t len = 0;
/*initial allocation*/
input_str = malloc(... |
Imagine you had to join together attributed strings with a separator in between them. Which of the following methods would you use?
An extension on SequenceType with a function that takes in a separator. Can't use any optionals in the array.
extension SequenceType where Generator.Element: NSAttributedString {
fu... |
I'm making a file downloader using Java. The project is on GitHub; I have included the most relevant excerpts here.
I separate the file into parts and download them using HTTP Range request, with each part being handled by a thread. All of the threads share an object, which is used to keep track of the progress and pr... |
I am new to Python (and coding in general) and after about a week of reading "Thinking Like a Computer Scientist: Learning with Python" I decided to try and build a version the classic "guessing game". I added some extra features such as counting the number of guesses the user takes, and playing against a simulated "co... |
I am designing a program that handles many types of grooves TKY, VSingle under GrooveType.
Each of this groove is paired with its specific parameter SimulationParam (e.g. TKY will pair with SimulationParamTKY, which inherits from SimulationParam) under the Dictionary simParams. As such, if i want to include more types... |
I have several UI elements that can be opened using hotkeys for example the settings menu's key is Escape. The problem is that I have the Keycode stored in Dictionary along with an Action or a Button.ButtonClickedEvent here's how the two dictionaries are declared:
public static readonly Dictionary<KeyCode, Button.... |
I am trying to search account table by providing a search string. I am building a query based in different conditions and then adding the returned records in a list.
The functionality is working correctly but I want to know how an below method be further optimized.
public PageReference search(){
clear();
ru... |
I asked the following question on stackoverflow and as a result came up with the following code to avoid circular event logic when using winforms.
There are two occasions where my model can be updated, either programmatically via some application logic, or by the user via a view.
There is no longer any circular logic ... |
I worried about this code in a ViewModel. ViewModel should not contain any code except binding's. But without async update the ui would freeze. How do I improve it? I'm restricted to using .net 3.5 or below.
public ShippingDocumentsRegisterViewModel()
{
this.Columns = model.InitializeColumns();
Action<object> D... |
I have an associative array with data (let's say language codes and descriptions) and a second array with allowed keys (lang codes). I want to filter the data array by these allowed keys.
The problem is I'm bound to PHP 5.5 and I can't use ARRAY_FILTER_USE_KEY flag.
I came up with the following solution:
$langs = [
... |
context: this is somewhat related to project euler problem 5, which is:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I apply prime number decomposition to the range of numbers from 1 to 20, and the product of all that should be the smallest number.
(absorb '(2 2 2) '... |
I've just completed an exercise in which I had to create a program that searches for a string within another bigger string.
If the substring exists then it is outputted to confirm and the starting index is given where the first character can be found.
Aside from printf and scanf, I am not allowed to use any other func... |
I am a newbie and self taught in programming.
This is my first attempt to make app.
Appreciate any input or comment to make my code writting skill better.
https://github.com/snufflesrea/Decision-maker
A simple randomize app to give random result from the user's option input. A simple randomize app to give random result... |
I would like to show an XML tree as a tree using GraphViz Dot tool. Then I must convert it to a DOT file.
It is what I have tried
string dot = "digraph G {" + Environment.NewLine;
XML2DOT(XmlRoot, "r");
dot += Environment.NewLine + "}";
....
private void XML2DOT(XmlNode n, string id)
{
... |
Related to Poker Hand Evaluator. This it not the same. This is take best from all combinations of 7. The other is all combinations of 5.
Poker is 52 cards - 4 suits and 13 ranks:
Texas holdem
Hand is exactly 5 cards
Order of hands
Straight-flush
all same suite and in order
ace high is royal straight flush
Quad f... |
I need to be able to atomically add a 32-bit floating point value to a location in memory. Here is what I came up with. While the code is Windows-specific, I'll extend it with Linux support using __sync_bool_compare_and_swap().
While I tested this code and it appeared to work fine, I'll appreciate a fresh look from ano... |
I have implemented a simple "switch" function - that switches and invokes an alternate function, if the function that is to be invoked fails or timesout.
This code will be later employed as part of circuit breaker.
I request to review the code in general and in particular for correct use of async\await:
public class Sw... |
I'm implementing an AXI4-Stream module. The module uses three DSP blocks (DSP49E1, UG479 - Xilinx). In order to run the module at a frequency of 150 MHz, the design is a pipeline going successively through each DSP.
In this code, I made the choice of a for loop into a single process to implement the pipeline. I should... |
I'm making a library to build and manage a website. I want to control what gets to be inserted. For example I don't want to be able to insert <foo bar="i"></foo> as xml builders allow.
I'm working with microcontrollers (currently with esp8266ex) that has support for WiFi and can act as a webserver. As you may or may ... |
I'm learning x86 assembly on Linux and this is the first program I wrote, so I'm looking for all kinds of ways to improve it.
; Build using these commands:
; nasm -f elf printenv.asm
; ld -o printenv printenv.o -m elf_i386 -s
section .data
section .bss
section .text
global _start
_start:
pop ecx ... |
I solved this problem and was looking for feedback on my code. More efficient, cleaner, more verbose variable names, anything helps.
There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this ... |
I have been trying to solve a modification of the Longest Common Prefix problem. It is defined below.
Defining substring
For a string P with characters P1, P2,…, Pq, let us denote by P[i, j]
the substring Pi, Pi+1,…, Pj.
Defining longest common prefix
LCP(S1, S2,…, Sk), is defined as largest possible integer j suc... |
I'd like to have some feedback on this small snippet I wrote to implement a base64 encoder and decoder.
Specifically, I'm not sure I'm handling padding in the best way possible.
import string
values = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'
ALPHABET = dict(zip(range(64), values))
def en... |
The below is a C++ parser for a reasonably simple INI grammar (although my understanding is that there isn't an official spec as such).
My grammar is roughly:
comments: (optional whitespace){;#}
section: (optional whitespace)[{printable ASCII}]
keyval: (optional whitespace){nows printable ASCII}={printable ASCII}
ini_... |
I have one list of data with duplicate IDs and a second list of data with attributes for the IDs.
>>>a
[1,1,1,1,2,2,3,3]
>>>b
['No','No','Yes','No','Yes','No','No','No']
I want to create a list (c) that holds indexes for a that match the following criteria:
1) Only one index per ID in a
2) Indexes for IDs that have a... |
I have a simple class that represents and accesses the data from a CSV file (using the CsvHelper library). I've tried restructuring the code to allow for better unit testing, but I'm sure the structure of the class could be better; both for testing and for using it (I'm not sure if there is any standard recommendations... |
I've implemented a C++ version of Java ArrayList. It doesn't contain all the functionalities such as AddAll and iterators and such, but I still would appreciate criticism to my code correctness, style and flow and such
template <typename T>
class ArrayList
{
public:
ArrayList();
~ArrayList();
... |
I added a guard clause to the functions in scipy.signal.windows, but the way they are currently written means the same 11 lines are now repeated in every function.
Each function has a unique core and a unique docstring, then some common guards and preconditioning around it:
if int(M) != M or M < 0:
raise ValueError... |
I'm easing back into C after several months of using Python and Matlab. Can anyone give me some pointers on how to improve my code's efficiency and readability?
#include <stdio.h>
#define MAX_ARG 2
int count( char FNAME[] );
int main( int argc, char *argv[]) {
if( argc > MAX_ARG ) {
printf("Too many argu... |
I've been working on these solutions to the Haskell 99 questions, encoding and decoding series for a while now, so I figured I ought to present them to see how I screwed up the implementation.
Problems:
Encoding: Write a function which encodes a series of characters using
run-length encoding and an algebraic data ty... |
I have written some ES2015 JavaScript that adds a class to a root element when one of it's immediate children is focused.
Here is the markup for the code to be run on:
<div id="my-root-element">
<input type="text">
<button type="submit>
</div>
And the JS itself:
const rootElement = document.getElementById('my-... |
I'm trying to solve a competitive programming problem. It basically gives a undirected graph (tree-like: no multiple paths between two nodes...) and asks for the sum of all possible paths between any pair of nodes in the graph (each path must be counted only once, in other words, if you have already counted the path f... |
I have recently started to work through the problems on Leetcode, for the sake of bettering my own skills as well as preparing for interviews. I was faced with the 3Sum problem which is:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array whic... |
Sometimes I need to repeat an execution of rejected promises several times, for example, to fetch some data over internet.
There is a wrapper, which accepts Promise and tryCount:
function tryPromise(f, tryCount) {
return f().then(null, function(v) {
tryCount--;
if (tryCount > 0) {
return $q.reject(v);... |
VBA has a call stack... but there's no programmatic way to tap into it, which means in order to get a stack trace for a runtime error, one has to manage it manually.
Here's some example code that demonstrates a custom CallStack class in action:
Option Explicit
Private Const ModuleName As String = "Module1"
Sub DoSome... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.