instruction stringlengths 71 71.9k |
|---|
I am writing a triple for loop in Python. Since the data set is larger, it takes more than 1.5 hours to finish. Is there any fast way to avoid the loop?
idx = []
for key, value in bid_img.iteritems():
for v in value:
loc = 0
for pid in pid_lst:
loc += 1
if v == pid:
... |
Within a method, this code is calling a SPROC that is doing a 'select *' from 9 different views. This method then goes on to access the returned DataTableCollection array by the index specified here (0-9). If the order of the stored procedure select statements ever changed, this would also need changing round here.
Thi... |
Given an array:
arr = [2,3,1,4]
I could write a count inversion array such that counting all numbers n2 after a certain number n1 in arr such that n1 > n2 and write it like this
[1 1 0 0]
Similarly, the inversion array of:
[2, 1, 4, 3]
would be:
[1, 0, 1, 0]
For:
[20]
[1, 2, 3, 4, 5, 6]
[87, 78, 16, 94]
Output wo... |
#
# Guess the presents someone will get
# We compare a `wishlist` with many criteria to the `presents` and return an array with the names of the matching products.
#
def guess_gifts(wishlist, presents)
wishlist.map do |w|
w[:name] if presents.include? w.reject { |key| key == :name }
end.compact.uniq
end
gue... |
Problem statement
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be \$\mathcal{O}(\log (m+n))\$.
Implementation
def median(A, B):
m, n = len(A), len(B)
if m > n:
A, B, m, n = B, A, n, m
if n ... |
I have written my first code of object oriented Python. Prior to this I have spent a week on learning the concepts and understanding the technique. I would appreciate it somebody reviews this and give suggestion on where I can improve.
I am working through codewars Kata and this code is for the problem. I am copying t... |
I have the following gulpfile which I use for development. It used to be a simple gulpfile with just jade compiling, sass, jekyll-rebuild, etc. but then I decided to add HTML Optimization my gulpfile became a little bit complicated.
The Gulpfile works okay but it has some bugs, for example when I save a jade file, I h... |
I have a file named feedback.js that I would like to improve.
function feedback(feedbackform) {
// collect the feedbackform data while iterating over the inputs
var data = {};
for (var i = 0; i < feedbackform.length; i++) {
var input = feedbackform[i];
if (input.name && input.value) {
... |
Starting to write an article about Socket Programing.
So I need a simple C version of a client/server app.
So here it is for review (Also on github)
A linked question is the C++ version
MakeFile
all: client server
.PHONY: all
.INTERMEDIATE: %.o
CFLAGS += -Wall -Wextra -Werror -pedantic
client: client.... |
Starting to write an article about Socket Programing.
So I need a simple C++ version of a client/server app.
So here it is for review (Also on github)
A linked question is the C version
Makefile
all: client server
.PHONY: all
.INTERMEDIATE: %.o
CC = $(CXX)
CXXFLAGS += -Wall -Wextra -Werror -p... |
I have a class that encapsulates a PowerShell Runspace object which, among many other things, has methods for getting and setting variables in the session state. There is no apparent mechanism for enumerating the variables, only get/set.
To simplify access to the variables from my code I've been using a specific index... |
I'm currently working on a thing I needed this feature for. Essentially, these are two methods to convert DateTime objects to and from the Unix epoch time (two methods for each action).
There is a non-nullable, and a nullable version for each conversion.
/// <summary>
/// Converts a DateTime to the long representation ... |
This is my new version of my Tic Tac Toe game written in C++. I tried to follow community advice by separating I/O from the game logic and view (MCV). The code works great, and I am looking to see if I followed the model control view design pattern correctly.
TicTacToe.h
#ifndef TICTACTOE
#define TICTACTOE
#include<st... |
Please tell me ways I can improve this code to be more efficient.
#Moving Character in 2D Plane
'''
Made by a beginner
'''
arena = [] # This is a map file
def make_board(place): #Generates map terrain
for i in range(5):
place.append(["O"] * 5)
def list_to_string(alist): #Makes map easier to read
for i... |
The problem:
We have a set of mobile mechanics who are assigned specific zip codes. Each zip code has its own hourly rate. We want to increase and decrease these rates when the number of idle mechanics within a zip code falls or goes above specific thresholds. This way we can proactively set the going rate for each mec... |
I have attempted to make conways game of life in Python, and then save the output into a picture.
Is there any way to make this more efficient?
Is there anything wrong with the logic? (Most of the pictures don't look quite correct)
Other?
import PIL.Image, random
WIDTH = 1366
HEIGHT = 768
ROUNDS = 10
DEAD = (0, 0, 0... |
The idea of my application is to have the user provides text which is pasted (or written) inside the textbook and further provides a search word.
The application then shows the overall count of words in the text, how many times the search word appears in the text, and the rate overall words to count of search word.
Any... |
My goal is to write a reasonably robust c++ linked list class. The current code represents the latest phase in this attempt. My future goal is to implement a doubly linked list along with more member functions. Before I continue further, I would like some input on my overall design thus far. Also, any input on improvin... |
I've written an ActiveAdmin mixin, such that you can include it and call simple_menu_for Foo, to reduce duplicate code when working with simple models. Here is the main part, which will connect all others. It works, but code looks little bit ugly. Maybe there is an alternative to using the class_variable_set method?
... |
I have code here which will change a sprite depending on the variables called gunUpgrade and moveUpgrade. Any way to make the code simpler or shorter? I'm using Unity 3D.
if (gunUpgrade > 0 && moveUpgrade > 0)
{
if (gunUpgrade == 1)
{
// For every moveupgrade, set the sprite to array num... |
The aim of this program is to say which position a word is in a list. This is just a basic version of it. I made to see if I could shorten it more than what it is currently.
position, word, word_list = 0, 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'
word_list = word_list.split("... |
I am new to AngularJS. Here is my basic code for implementing Tabs with Pane. Eventually, each tab-pane will have a form and a ui-grid that will display data from the DB.
Can I use separate controllers to initialize each tab to load the pane?
Is it good to give separate controllers for implementing a pane? I have DB... |
I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.
def balanced?(string)
return false if string.length.odd?
pairs = { '{' => '}', '[' => ']', '(' => ')' }
string.chars.each_with_object([]) do |bracket, stack|
if pairs.keys.include?(bracket)
stack << bracket
e... |
I have a method in Scala that checks if a game board is full or not. To speed this method up, I return inside the nested for loop to break out of both of them and stop execution. How would I achieve this in Scala in an idiomatic way?
def isFull: Boolean = {
for (x <- getGrid.indices) {
for (y <- getGrid(x).indice... |
I'm currently writing a binary reader that reads a value from a BinaryReader at a given position. For that I have to store the current position of the MemoryStream so I can restore it afterwards.
public byte GetByte(int position)
{
long oldPosition = this.memoryStream.Position;
this.memoryStream.Position = positi... |
Part of a project I'm getting started on requires access to the Stack Exchange API for certain data, as a result I built a .NET implementation to interact with it.
The implementation is pretty simple, in my opinion. You can also find it on GitHub.
It features a main Configuration class, in which you put a lot of the A... |
I wanted to write a function paths that returns the possible routes between two nodes in a graph.
For example:
const graph = [
['a', 'b'], // i.e. directed edge a => b
['a', 'c'], // i.e. directed edge a => c
['b', 'a'], // i.e. directed edge b => a
['b', 'c'], // ...and so on
['c', 'a'],
... |
Given any string with a series of numbers find out which one of the numbers differs from the others in evenness and return its position.
Examples:
"2 4 6 7 8 10" returns 4
"3 5 7 9 10" returns 5
I found 2 different ways to do so, but I'm wondering what is the best approach in matter of time complexity.
Solution 1
d... |
I'm a beginner-intermediate programmer who's mostly used Java. I taught myself Python and made this engine for playing Reversi. Tips on Pythonic ways to accomplish tasks and/or general advice appreciated!
from ast import literal_eval as eval
board_size = 8
BLACK = '\u26AB'
WHITE = '\u26AA'
EMPTY = '\u2B1c'
offsets = (... |
I have a function where I am comparing an error string returned from a web service to several lists of known strings, and then based on which list the error is a member of, returning from the function a more 'user-friendly' error to display.
I am hoping someone could offer some tips on making it shorter and more effici... |
I'd like some feedback.
from random import randint
turns = 1
computer_guess = randint(1, 10)
while True:
user_guess = raw_input("Guess Number: ")
print 4-turns, "Turns left"
if turns == 4:
print "You lost!, LOOSER!"
exit()
else:
if int(user_guess) == int(computer_guess):
... |
I needed to rotate a non-square matrix in my program to transpose some spreadsheet data and decided to make a function to rotate 90, 180, or 270 degrees.
It doesn't rotate the matrix in place, but instead generates a copy and returns that. I want to go for processing efficiency, let me know what I can do better:
//Rota... |
I have written a simple implementation of the game Tic-Tac-Toe designed to allow "pluggable" player control, meaning I can easily swap out the controlling logic for players without modifying the game itself.
I have a few issues with my existing code:
I don't like the while loop for processing, however I find making mo... |
General objective: Find the date (day of the month) of the nearest specified day of the week and output.
More specifically: Focusing on events which take place every Fri & Sat, want the page to automatically update dates to next events. HOWEVER for clarity the page should never display Fridays and Saturdays which are N... |
I tried to implement a linked list that can do pop(), push(), append(), printall(), and so on, and also I tried to handle the wraparound features, and de-wrap it when check if the list is cyclic to avoid endless loop, but I am sure this wrap and de-wrap features can be implemented better...
#include <iostream>
struct ... |
Here is an async Tcp server using async/await I have written. I would be very appreciate if anyone can help to improve my code. Thank you!
public class TcpServer
{
private int DefaultPort = 6340;
public TcpListener TcpListener { get; set; }
public TcpServer()
{
var ip = NetworkHelper.GetLocalIP... |
Algorithm which returns a number which is divisible by all the numbers from \$1\$ to \$n\$ without remainders.
public static void smallestMultiple(long l){
int count = 1;
boolean flag = true;
while(true){
flag = true;
for(int i=1; i<=l; i++){
if( count % i != 0){
... |
ActiveWindow is like the main container and below the subviews. Router trigger activewindow.render(options) then the switch operates. Is it fine to do that Or how bad is it?
define('activewindowView', [
'backbone',
'text!views/activewindowView/activewindowTemplate.html',
'ghostviewHunter',
'menuView',
... |
Let \$I = \{ i_1, i_2, \dots, i_d \}\$ be the set of all possible items, and \$T = \{ t_1, t_2, \dots, t_N \}\$ be the (multi)set of all given transactions, where \$t_i \subseteq I\$ for all \$i \in \{ 1, 2, \dots, N \}\$. We call any such \$t_i\$ an itemset. Given an itemset \$X \subseteq I\$, its support count is
$$
... |
So I made a version for the 0/1 knapsack problem myself (using matrix dynamic programming algorithm). Given a list of items with name, value, and weight, my function computes correctly the optimal value with total weight <= allowed weight.
I don't know if my code is clean and pythonic enough, I would greatly appreciate... |
This is a silly Redis implementation that handles only three commands: INFO, ECHO, PING.
The implementation is based on streams:
var _ = require('lodash')
var expect = require('chai').expect;
var assert = require('chai').assert;
var redis = require('redis')
var split = require('split')
var net = require('net');
var ut... |
A long long time ago I asked this question which has since garnered about one thousand views. Now for something new.
The demo for what I have is located here. I am generally happy with what I have built (although I did not implement all of the visuals (yet) of the original).
I want to know if there is some improvements... |
Is there a better, more efficient or nicer way to do this?
public static String sortString(String s){
String[] strArray= s.split("\\s+");
Arrays.sort(strArray);
StringBuilder sb = new StringBuilder();
for (int i=0; i<strArray.length; i++){
sb.append(strArray[i]);
sb.append(" ");
}
... |
Already many days I'm documenting about the SQL Injection. I was wondering if the code I wrote is vulnerable in some of its parts.
<?php
if($_POST['nameone'] AND $_POST['nametwo'])
{
$conn = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8", 'dbuser', 'dbpass');
mysql_query('SET NAMES utf8');
$conn->se... |
This code works just fine as I get the correct output. However I want to make my code more simple. I want to avoid using the setPrev(Node n) method and would rather set the reference to the previous node in the Node(String s) constructor directly somehow. I mainly want to know if this is the 'right' way to implement a ... |
I am almost finished with my queries which are running inside transactions so it's everything or nothing... Could you please take a look if I am missing something or if everything is where it belongs?
I am bit worried about my conn.Open() call, and about security in general. Can you help me out to tune it up and make i... |
So this is my full script that I've been working on. My plan is to Create New, Folder, Create AD Group FS-TESTSHARE-R, Create AD Group FS-TESTSHARE-RW, Apply Both groups to the new share folder, Set Full Read permissions to FS-TESTSHARE-R, Set Full Read/Rights permissions to FS-TESTSHARE-RW, and Set full access permiss... |
(See the next iteration.)
I have this funky class method for computing standard deviation from an array of Number objects using the Stream API:
StandardDeviation.java:
package net.coderodde.util;
import java.util.Arrays;
public class StandardDeviation {
public static double computeStandardDeviation(Number... col... |
I'm new to programming, Stack Overflow and Code Review. I was encouraged to post this method here based on a question I posted on StackOverflow here. Let me know if you have tips for improving this post, and I will try to implement them asap.
I'm hoping for a general review of my code. I realize the formatting is go... |
I already solved this one from CodingBat, but I'm unsatisfied with my solution and I feel I could have made it much shorter. Most of the other recursion tasks could be solved by a one line conditional for the base case and a one line return statement usually using ternary operator. So, could I have made this any shorte... |
I create a constant class by looking at some of the best practices described here in stackoverflow. Many of those have a single Constant class with variables. Some of the answers suggested creating separate Contant Classes. The way I create a constant class is by naming it Parameters and creating classes i.e. Variables... |
This 5 classes: CBoard, CInput, CPlayer, Console, Graphics, and the main file, Test, which is actually main.cpp (but I named it poorly). Specifically, I use a switch to update the board, which is a 2D char array.
Is there a better way to update the board besides a large switch case? I have yet to think of a way to hold... |
I am wondering whether the following inheritance pattern is a good idea.
I noticed that Sales Orders, Sales Quotes and Sales Invoices all follow a similar Master/ Detail pattern ( i.e a Header with Lines ) so I wanted to be able to inherit from base classes that encapsulated their common properties.
I will start with m... |
A followup to this question, thanks to @mdfst13 and @janos for the feedback.
I have made some changes to my code, mainly the following:
Replaced the next method with a loop and run method, as suggested by @mdfst13. Also removed redundant "null" checks.
Added a Cell enum as suggested by @janos, replacing the 2D array ... |
This is my first stab at a game AI, and I've been working on multiple game mode difficulties, so I decided to start with a simple game. :) I'm most concerned about efficiency of the AI algorithms, and any possible way of reducing the duplicate code. I know I can't change the int values by reference, so would it be more... |
I need to speed up this code so it can handle inputs in the thousands. It adds triangular numbers to a list based on input n, then it loops through to find if any two consecutive numbers squared in that list add up to n. The test cases I've been using are n = 45, which would be true and n = 6, which would be false.
He... |
I'm trying to code this decision tree using R. I was wondering if there was a better way to go about this rather than using a ton of conditionals?
# ops
rm(list=ls(all=TRUE))
options(warn=-1)
saveFiles = FALSE
setwd("~/Documents/Education/UCLA/Spring 2016/MGMT271B/proj/")
# data vars
n = 10
T = c("X", seq(0,4), "is") ... |
My code fetches telegrams from a server periodically in the background. The server API is documented here. What do you think of the way I do multithreading by handling my _updatesList?
public class AutoUpdate
{
public bool IsStarted { get; private set; }
private readonly Timer _timer;
private readonly List... |
I just wrote a small Ruby class to solve the first of the challenges in the G CodeJam. I am not strong at this sort thing so very sure it can be simplified massively! The program is correct for both the small and large inputs.
Challenge
Problem
Bleatrix Trotter the sheep has devised a strategy that helps her fall
as... |
I created a method that takes a string value with a fixed length of 9 characters and extracts three values, house (4 characters), level (2), door (3). If the input value has another length than 9 then the method should return nil.
I found several ways to implement the method, but which implementation should I prefer an... |
I'm a beginner at C#. I just want to know what is the C# way to do this by its convention and a better algorithm as well.
using System;
using System.Collections.Generic;
public class Program
{
static public void Main()
{
bool prime = false;
List<int> non_primes = new List<int>();
while... |
I have an object of arbitrary depth, and a string (or array) containing the keys which have to be traversed to get to the value.
As far as I know, there's no method to get to the value directly:
var object = {
user: {name: 'bob'},
'user.name': 'error'
};
object['user.name']; // contains 'error'
And the usua... |
I am trying to count the rows of two tables generated by SQL connections in Excel VBA. My plan was to use ListObject.DataBodyRange.Rows.Count however, this errors when a table is empty, which one often is. I found it completely impossible to use On Error GoTo ... twice within one sub so I pulled out the counts as funct... |
We have the following validation function:
var result = scope.CurrentUser.Surname.length > 0;
var d = $q.defer();
if (result) {
apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email)
.success(function (response) {
if (response) {
... |
The code is working fine however, I would like to fix code after unless and can I store thread ID in the database too? Is there a way to improve performance?
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data, field_name=nil)
target_model = model_name.classify.cons... |
Is there a way I can link/associate an object (in this particular case a function) with a regular expression pattern?
Here's the function I'm working on:
def get_command(url):
"""
Return command for downloading a particular url.
>>> get_command('http://randomsite.com/XYZ')
['wget', '--content-dispositi... |
I have inherited a site which uses the Google API to create a map on my webpage. I don't know much about JavaScript but from the research I've done, I dont think this code is optimal as it is not loading asynchronously. Any help or pointers would be appreciated.
function initialize() {
var myLatlng = new google.maps.... |
I'm having trouble improving the performance of the solution to the Project Euler problem #34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
I've done... |
I am currently reading Clean Code and for fun and profit, I intended to refactor some of the Java Tutorials and since I wanted to improve my Exception handling, the Byte Stream one with its lots of IOExceptions seemed nice.
This code does work, but is it better now? As far as I can tell it's more readable now, though t... |
I've written a small C++ utility that is intended for measuring the execution time of blocks of code, and I'd appreciate your feedback on it. I'm an experienced programmer, but a novice C++ programmer.
The code is written with performance in mind, and uses a libcuckoo hash table to support multiple concurrent calling t... |
I think I'm finally done with my code and was hoping for some pointers. My goal for this script was to:
Create new folder
Create AD group FS-TESTSHARE-R
Create AD group FS-TESTSHARE-RW
Apply both groups to the new share folder
Set full read permissions to FS-TESTSHARE-R
Set full read/Rights permissions to FS-TESTSHARE... |
I needed to make a timer to profile small programs a while back. My use wasn't for a major project or mission critical code or anything even remotely close to that, just for personal learning purposes.
As I reviewed my old timer I found I was using clock which measures cpu time. Now being aware of the difference bet... |
My team has developed an API and I've been tasked with creating an authentication layer that allows partners' applications to consume it. To that end, I've created a data store which houses an Application ID, Login and salted/hashed Password for that application to authenticate against. I want to hand back a Token for ... |
(See the first and initial iteration.)
Now I make only one pass over the data in order to compute the standard deviation of the input Numbers, and that's how:
\begin{align}
\sum_{i = 1}^n (x_i - \mu)^2 &= \sum_{i = 1}^n (x_i^2 - 2\mu x_i + \mu^2) \\
&= \sum_{i = 1}^n x_i^2 - 2\mu \sum_{i = ... |
This is hard to explain. I wanted to get all of the items in collection one (ints in the example below) that are the highest values that are lower than any of the items in collection two (otherInts). In the example below, only 2 and 8 should be returned from ints. 1 doesn't qualify because it is lower than 3 (in oth... |
I am working on below python copy utility that should work on windows & linux,
But I am looking for a more efficient approach that could optimize my I/O correction, as my target location is network dependent as well...
I have computed the utility execution time factor in the code.
#!/usr/bin/python
"""
Pythonic implem... |
I want to run rolling regressions over each group and store the coefficient. The following works, but it's slow, since I have too many series and I want to run too many regressions for each group.
Using foreach(), speeds things up (and also getting the coefficient with (X'X)^{-1}X'Y but is there a way to vectorize thi... |
Below is my code to detect cycle in an undirected graph. Could anyone please review and let me know if I have taken care of all the cases?
The basic idea is to use DFS (non-recursive using stack) and check if already visited vertices are found in the stack.
bool dfsDetectCycle(int vertex, int visited[10]) {
stack<... |
I'm building an app that tells you a stock's percentage change in price between two dates by using Yahoo's API. Given a stock ticker and two dates, it currently outputs the percentage return to the console.
I would like to later expand this app to give it a list of stock tickers and dates. For each, it would return the... |
To find the node next to a given node we need to consider two cases.
case 1: if the node has a right subtree then return the min node in its right subtree.
case 2: if the node doesn't have a right subtree then return the ancestor of the node whose left subtree contains the node.
class NodeWithParent {
int data;
... |
Below I have implemented a class that will validate and upload files based on the specified rules.
class Uploader
{
protected $finfo;
// extensions corresponding mime types
protected $mimes = [
'jpg' => 'image/jpeg',
'pdf' => 'application/pdf',
'png' => 'image/png',
'gif' ... |
I worked starting from basic example code from an exercise in chapter 10 of Java: A Beginner's Guide, Sixth Edition, the code in the exercise was not very good and I wanted to improve upon it and make it my own, so this is what I came up with.
This reads the content of a text file, displays and reads titles/subjects, w... |
I'm simultaneously learning Erlang and writing a short guide on list operations. Here is a trivial function I wrote to demonstrate hd and tl:
headAndTail(List) ->
Head = hd(List),
Tail = tl(List),
{Head, Tail}.
This works, but it throws "Warning: variable 'Head' is unused." I know this function could be written ... |
public static long sumOfPrimes(long max){
long sum = 0;
long primes[] = new long[((int)max/2)+1];
int index = 0;
for(long counter = 2; counter <= max; counter++){
if(isPrime(counter, primes)){
sum += counter;
primes[index++] = counter;
}
}
return sum;
}
p... |
I have written a LaTeX package to visualize B+ trees.
The main purpose is to provide a simple but powerful package which provides a convenient interface.
However, this is my first LaTeX package and I would also like to know where I can do better.
So I'd like to get reviews from these two points of view:
Simplicity of ... |
I am learning Java's NIO and as an exercise, I have implemented a simple chat server. I would like to ask if I am using NIO's features in the correct way.
public class ChatServer implements Runnable {
private static final int BUFFER_SIZE = 256;
private static final int DEFAULT_PORT = 10523;
private static f... |
I needed a better way to benchmark code, because, well, rewriting the same benchmarking code every time I need it is just...well...unpleasant.
So, here's a class which does just that, it runs an Action over a specific number of rounds, and calculates certain stats on it.
Another nice feature is that it doesn't store th... |
My code prints the next 20 leap years:
def loop_year(year):
x = 0
while x < 20:
if year % 4 != 0 and year % 400 != 0:
year +=1
##print("%s is a common year") %(year)
elif year % 100 != 0:
year +=1
print("%s is a leap year") % (year)
x +... |
In my system I have a SMS authentication. Users input their user-id and get sent an SMS with a 5 digit pin number they input in a website to log in. The pin has a lifetime of a few minutes.
This pin number needs to be fairly secure so hackers can't try to guess the pin.
I would like to get some comments about my approa... |
I have a piece of JavaScript that's going to fire event every second after 10s, it's going to gradually increase the interval time. I'm new to JavaScript so it would be nice to have a codereview.
var _lastHeartbeat = window.performance.now();
var _config = {
heartbeat: {
start: 1000,
max: 10000000,
cap: ... |
I recently finished the project Euler problem # 41 :
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
And I'm having trouble optimizing it.
Exp... |
Revisions:
Revision 1 (you are here)
Revision 2
Revision 3
I've been working on a simple command-line png2jpeg utility. Its purpose is to convert images from PNG format to JPEG.
The source code requires the libpng and libjpeg development libraries to be installed, and can be built with a C99 standard-compliant C comp... |
I'm sanitising personal data in a large database with a series of Regular Expressions. In many cases the sensitive data is in a colon-delimited field within a CSV file.
Here is a sample:
(142406, 202, '45759:2940:2016-04-12-21-24-08:300:2016-06-21:2016-04-11:1:Windows/Doors:', 2761, 4041931, 0, '1460492649'),
(142404, ... |
Using Rubocop, pretty much any case statement is caught by the Cyclomatic Complexity cop, often the Assignment Branch Condition and method length cops as well. To get around this, I've been refactoring code like this:
def preview
case object.panel_type
when "image"
asset_image_path(object.asset)
when "profile... |
I'm new in OCaml and just want to be sure that I write code in "ocaml way". My other first programs in OCaml was imperative and looks like python-code. So I decided to write simple code and share it for review.
let print lst =
List.map string_of_int lst
|> String.concat " "
|> print_endline
;;
let... |
have started learning Java recently and was looking into some easy algorithms.
I found the Sieve Of Erastothenes algorithm here
I am trying to get better at writing good code for my solutions. Please give me your suggestions.
import java.util.Scanner;
public class SieveofErastothenes {
public static void main(Str... |
I'm learning F#, starting with baby steps. Is there a way to write this code in a more succint way, while keeping the same semantics? Maybe by using a Seq or something like that?
let rec repeatingPrompt predicate (message:string) =
Console.WriteLine(message)
let value = Console.ReadLine()
if predicate value... |
I use this declaration for an array which must contain a bit for every minute in a day:
UCHAR minutesOfDay[(60 * 24 / CHAR_BIT) + (((60 * 24) % CHAR_BIT) ? 1 : 0)];
However, this look pretty awful. Is there a simpler way to state the same? It can be in C or C++.
|
A new question about a revised version of the code in this question, based on the advice in the accepted answer can be found here.
I need to signal my program to do something every X seconds. So I decided to make a separate thread that sends such a signal using ZeroMQ. All other behaviour is also triggered by ZeroMQ me... |
While trying to integrate react-select component on my codebase on documentation it's explained that you can pass an array of options with label and value attributes eg :
import Select from 'react-select';
let options = [
{
label: 'Color',
value: 'Blue'
}
]
<Select options={options} />
And it works fine, but ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.