instruction stringlengths 71 71.9k |
|---|
I had a simple function.
def graphite_json(target):
url = 'http://server/render/?format=json&target={}&from=-10days'.format(target)
r = requests.get(url)
return r.json()
This contacts a (Graphite) server, uses the requests library to get JSON string and convert it to a native list. Simple.
Then I ... |
I'm trying to optimize this code by:
condensing repetitive statements
Improving the code/make it less confusing
Branch out to include other filing status such as "married" "joint" filing status
branch out to all 50 states
Any suggestions how to do any of these things would be awesome.
/** This program calculates Sing... |
My intention is to create a nice DRY method (add) which will take care of parsing floats and adding totals internally and will be called by other methods.
I feel like I'm jumping through unnecessary complex hoops here. Can anyone help me out?
PS: the intention is to be able to specify different objects with add, so if... |
Challenge: Write a program which determines the largest prime palindrome less than 1000.
The answer is 929, and my program correctly finds and prints this, but actually ended up being more complex than I expected.
I'd like a general review, but also want to pinpoint if
I'm overdoing it/the plain way would be faster.
I... |
Checking if all five vowels are present in a string.
String phrase = "Hello, how are you keeping?";
String vowelsInPhrase = phrase.toLowerCase().replaceAll("[^aeiou]", "");
String temp = vowelsInPhrase;
String usedVowels = "";
while(temp.length() > 0){
usedVowels += temp.substring(0, 1);
temp = temp... |
Edit: Use cases for this class - I needed this class in the case where I had processes I needed to execute (in the form of tasks - they were all asynchronous) that I needed to issue to a UI control when certain events occurred. However, these events are something I dont control and can sometimes occur in close successi... |
I have a very large class which serves as the BaseClass for many AdapterClasses. The base class consists of methods that can be categorized as follows:
Translation: fundamental translation classmethods used by all AdapterClasses. Requires class attributes from AdapterClasses (used internal / external) The tricky part... |
I have built a simple thumbnail gallery using HTML and CSS with the purpose of inserting this into an auction listing. The code seems to work fine, but I know it is sloppy and most definitely improper syntax as I have DIV's inside of SPAN's. I know I am close, but what would the proper implementation be?
HTML
<div clas... |
I am learning java and doing some practice problems. My code works, but I feel like I used a workaround sort of way to accomplish it. Is there another way to express what I want the program to do?
Question: Problem J4: Time on task
Input specification:
First line is the total number of minutes to accomplish the chore... |
I want to scan my whatsapp images folder and move all the repeated images to folder named recycle bin to delete them later:
<?php
$dir = 'C:\wamp\www\whatsapp';
$files = scandir($dir);
$x = 0;
foreach($files as $f1)
{
$crc1 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f1))));
unset($files[$x... |
Program written in TI-Basic that works on TI-83/84/+/SE calculators. Automatically detects whether input is a number of a Roman numeral, and converts to the opposite. Please try to optimize for size, if possible.
DelVar IDelVar VDelVar XDelVar LDelVar CDelVar DDelVar MClrHome
Input Str1
expr(Str1->A
If A
Then
A->B
"?->... |
I had to write a RPN calculator in C as one of my homework problems, but if someone could critique my code and suggest any improvements, that would be fantastic! I haven't added any overflow errors or input errors, but I will add that eventually.
My code takes operands and operators from the command line (e.g., 3 4 - ... |
I'm creating a class to wrap a list of Mask and I'd like to know if I'm overriding the GetHashCode() and Equals() correctly.
Mask is a wrapper for a List of Points. It does implement IEnumerable<Point>.
public class MaskCollection : IEnumerable<Mask>
{
#region Variables
private List<Mask> masks;
... |
I have an instance method which calculates the position of an element, depending on the tariff of its seller.
If the seller is of a level3 tariff, it gets to top 100, the probability of 40%. If the tariff is level2, then 30%, etc.
TARIFFS = {level3: 0...40,
level2: 40...70,
level1: 70...90,
... |
I am making some functions within a function for learning which when passed information about a named tuple: it returns a reference to a class object from which we can construct instances of the specified named tuple. Is there any way to make the code a bit cleaner? Any help would be great. The function pnamedtuple ha... |
This is my first attempt at Java so I appreciate any criticism or pointers. The program should generate a full set of given decks and then shuffle them.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class shuffle {
//Make it easier to find array items
static int value = 0;... |
Inspired by this article about natural numbers from first principles in swift I implemented integers from scratch in Haskell.
Besides obviously being extremely inefficient, is this code idiomatic Haskell?
import Data.List
import GHC.Real
data ℤ = Pred ℤ | Zero | Succ ℤ
toNat = toEnum :: Int -> ℤ
fromNat = fromEnum :... |
I am currently changing the background colour of a sidebar each time a menu item is clicked using the following code:
$( 'a[href = "#masthead"' ).click(function() {
$('#sidebar').css('background-color', '#3b6dac');
});
$( 'a[href = "#section2"' ).click(function() {
$('#sidebar').css('background-color', '#23d4d7');... |
I've just completed an assignment about class templates in C++. It works fine and produces the correct output. We were given the main function and had to construct and implement the class. I'm wondering if there is a better (more efficient) way to construct and implement this simple calculator class template.
#incl... |
I was just wondering if my code below is a good way of populating data from database. I have had no issues with this really but I am being taught this and just wondering if it is the best practice.
Public Sub LoadProperty()
'**Finds the Current Property Data
'Error Checking
' On Error GoTo Err_LoadPropert... |
I've used hibernate for a long time. Recently I started using JPA, but I can't find a short way to write a simple select in less than these seven lines (the use of criteria is a must in this project).
Is there a shorter way to build this query?
public List<Transaction> findDevolucionesByOriginalOperationId(String origi... |
I've automated the process of extracting and converting a heap dump from an Android device/emulator.
I'd appreciate any feedback and improvements regarding style, bad practices, non-idiomatic code, performance or other issues you may find.
Also, dump_heap() function tries to wait for a daemon to complete and I'm wonder... |
I have to calculate a user's location periodically and store & send it over the network on Android. I also have to indicate errors during calculation of location as well. The errors could come from the location API or user having disabled their GPS. I have written the following class for this purpose:
/**
* Store info... |
In a course that I'm taking on learning object oriented programming in java, I have completed an assignment for modeling a home entertainment system and the ability for a user to be able to use a single remote control to control multiple digital devices such as a TV or sound system etc.
I don't feel too confident about... |
After reading the definition, I made a simple Reverse Polish Notation (RPN) calculator in Python.
Originally it had just 4 operators (using import operator and a lookup table) and only did integers. After looking at some example calculations, I amended it to work on floats and added a raising to powers. Then I saw some... |
I seem to have a memory leak on this method but can't figure it out. This method is called every 10sec by a timer which acts like a refresh.
//Variables
List<UserControls.userControlAlert> theDataPages = new List<UserControls.userControlAlert>();
private OleDbConnection mycon;
private OleDbCommand ole... |
I have a class that is a wrapper for memory positions of a hardware device.
I need to data-bind each of this positions, so I created a class with hardcoded properties, one for each position, so that I can bind a WPF DataGrid to it.
Problem is: given the sequential nature of the positions, the code became quite repetiti... |
This is a polyglot function I've made out of fun.
The goal is to grab n arrays (or Javascript Objects) and 'extend' them in order to obtain a single array with all the values.
This function runs both in Javascript and PHP.
Please, try to ignore some kludges on my code.
Here is my 'art':
function array_extend() {
/... |
This is the second assignment for my CS2 course:
Write a recursive C++ function writeLine() that writes a character repeatedly to form a line of n characters. For example:
writeLine('*', 5)
produces the output:
*****
Write a recursive [C++] function writeBlock() that uses writeLine to write m lines of n cha... |
I have multiple controllers and every controller has this error handler:
if (error) {
res.render('error', {
error: error
});
}
Sometimes I have more than one:
exports.update = function(req, res, next) {
MyModel.findById(req.params.id, function(error, event) {
if (error) {
res.render('e... |
I very infrequently use SQL. I need more experience, so I have created a data explorer query to find those users with most of any particular badge (have to edit the query itself right now to alter it). I like following best practices, so please feel free to nit-pick and really do this right (indentation, capitalization... |
I need to generate a 64 bit unique integer in Java. I need to make sure that there is very few or no collisions if possible.
I came up with the below code which works fine:
public class TestUniqueness {
private static final AtomicLong TS = new AtomicLong();
public static void main(String[] args) {
// ... |
I'm working on a project that takes in a video file and does some image processing on each individual frame. The first step in that processing is to take each source frame and generate three monochromatic images based upon the average red, green, and blue values of the image. If that doesn't make sense, I've drawn up a... |
I'm trying to implement an alternative to python built-in open(), but safe for use in multi-threaded and multiprocessing environment. I'm using advisory locking, because all file operations in my application are performed using my locked_open() function and no other process is accessing that data.
It is only required ... |
This is a simple app for taking down a user's home and work address, the days of their commute, and the times they go to work and go home. The times and workweek are entered via TimePicker dialogs with additional buttons. An IntentService runs in the background with setRepeating alarms that call per the user's set time... |
I am required to create a bunch of object nodes to an object:
this.selectedText = e.text;
this.clipNo = e.clipNo;
if(!this.clipCollection.hasOwnProperty(this.category)) {
this.clipCollection[this.category] = {};
}
if(!this.clipCollection.hasOwnProperty("grandClipCount")) {
this.clipCollection.grandClipCount =... |
My Deck Class:
(In case it isn't clear, a Card is just an object with two enums, one for suit and one for value).
I'm particularly proud of the readability of this little bit if I do say so myself.
public class Deck {
private static Random random = new Random();
private List<Card> cards = new ArrayList<Card>(... |
I have created this memory writer helper to ease the write into memory process and I want your suggestions regarding it. I am very new to C++ but have 6 years knowledge of .NET languages like VB and C#.
#include <wtypes.h>
class MemoryWriter {
private:
USHORT _currentIndex;
LPVOID _targetAddress;
template<... |
I have a list of categories (in this example I used String but in my project I have a model) which must be sorted like this:
on top we should have 2 categories which have a fixed position in the list (in this example (C, F))
at the bottom of the list we should have 3 categories which have a fixed position in the list ... |
I recently wrote this JavaScript algorithm for removing duplicates from an array as part of a job interview process, but was turned down for the position after submitting the code. I didn't receive any detailed feedback from the company, so I was wondering if a more experienced developer might be able to explain what I... |
I am writing a Tetris game while learning Haskell and I'm trying to make the following code more concise and easier to read. How can I improve it?
Note that the function is not finished yet (There is no check for complete lines, for instance); I currently want to improve its readability.
updateGame :: IORef InputsData ... |
I have one button on clicking I need multiple things need to be done, so I went for AJAX and PHP:
$('.go_nxt_lsn').live('click',function(e){
e.stopPropagation();
var user_id = $('input[name=user_id]').val();
var course_id = $('input[name=course_id]').val();
var taskName = "SaveActivity";
var subTask... |
A student has a book containing 411 pages.
She read a certain number of pages on the first day and created a rule to work out how many pages she had to read on each succeeding day.
She decided that the number of pages to be read on the next day should be equal to the square of the sum of the digits of the page she... |
I am trying to implement a 2D fighting game in Clojure both for fun and learning.
Since the characters in a fighter game are essentially state machines, I constructed the following code:
(defrecord Frames [frames id])
where "frames" refer to the actual datas (hitboxes texture-names and etc) and "id" will be an atom r... |
A long time ago, I've written a method that would allow me to measure the amount of time a method takes to run. I've decided to tweak this method and make use of TPL since measuring a method may take some time.
public static class ComparableUtils
{
public static T Min<T>(this T t1, T t2)where T:IComparable
{
... |
I am recently making a CMS and I need a secure login system, so this is my code. How is it?
First: the HTMLcode for signup and login:
<div id="login" style="display: none">
<input type="text" name="email" id="login-email" placeholder=""><br><br>
<input type="password" name="password" id="login-password" placeho... |
An interview question I got -
Given int n, find the smallest number of square numbers that fit inside n.
Example:
Input: 24
Output: 3 (16 + 4 + 4)
Input: 10
Output: 2 (9 + 1)
Solution:
public class Solution{
public static int solution(int number){
int squareCount = 0;
while(number> 0){
... |
I wrote a simple class to cache data on a filesystem. The class also provides an internal cache using a static variable to avoid reading from disk for each request.
<?php
/**
* object caching system
*/
class cache {
/**
* The *Singleton* instances
* @staticvar cache
*/
private static $instance... |
I thought of this implementation, and I want to get feedback from you.. what design would you use for printing first 100 prime numbers?
I used the fact that, if the number is not divisible by any prime less than itself, it will be a new prime.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2); // ... |
I am learning Java right now and am coding some simple programs to practice. Right now, one of my for loops has an inelegant way of ending the loop. I was wondering if there was another way to express what I want the program to do.
Problem: Party Invitation
Problem Description
Number your friends 1,2,....,K and place... |
This problem is from HackerRank (not a competition, just for practice)
Basically what you do is take in two integers as a range and then finding the maximum XOR from a pair of integers in that interval.
Here is my code for doing so (it passed all the test cases):
static int maxXor(int l, int r) {
int maxXor = l ^ r... |
I have a large list of lists, where each list contains words/characters as elements, and each list is of different length and may contain same words/characters more than once, as for example:
list_ = [['black', 'window', 'says', 'window'], ['dog', 'great'], ['after', 'end', 'explains', 'income', '.', '?']]
I also ha... |
The pattern I've come up here is for the AnimalGenerator itself, outside of the (abstract) Factory Pattern used within it. The factory classes themselves are not present in this code because that is not what I'm focussing on here.
There are many types of animals, and AnimalGenerator::generateAnimals<Type>(num, int...)... |
I'm scraping a title and a link from a website and placing them in a single array.
The $i variable seems a bit wrong to me, or is it perfectly fine?
$linkQuery = $xpath->query("//div[@class='news-archive']//a/@href");
$titleQuery = $xpath->query("//div[@class='news-archive']//a");
$data = [];
foreach ($linkQuery as $... |
In an Android project,
I have a class whose job is to read lines from a file,
and then pump those lines to a message handling thread,
looping forever until told to stop.
The main operation of this class (file reading + message sending) must be on its own separate thread,
to run in parallel with whatever else the applic... |
Below is the code I have written to capitalize all the words of a sentence except if
The words belong to the littleWords list.
The word would be capitalized if it's the first word of the sentence even if it is in the littleWords list.
def titleize(sentence)
littleWords = ["end", "over", "and", "the"]
words =... |
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.
For example, in array ... |
I'm looking to increase the conciseness of this code. I realize that I can use Joda (or Java 8's new date API), but if I were to keep this to just Java 7, any suggestions? (I care less about whitespace and formatting.)
/**
* Tests whether the date input represents
* a real date in mm/dd/YYYY format that is after th... |
I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises.
The following is the question from the SQL Movie-Rating Query Exercises, Question 6:
For all cases where the same reviewer rated the same ... |
I made a few recursive functions for learning purposes which do a variety of tasks. Here is my current and functioning code:
def separate(p,l):
''' recursive function when is passed a predicate and a list returns a 2-tuple
whose 0 index is a list of all the values in the argument list for which the
pre... |
I have written the code to shuffle the elements of the array. Please let me know of any loopholes in the written code.
package dataStructureInJava;
import java.awt.SystemTray;
import java.util.Random;
import java.util.Scanner;
public class ShuffleArr {
public static void main(String[] args){
System.out.pr... |
I found Python's defaultdict and OrderedDict incredibly useful, hence I attempted an implementation in JavaScript. As JavaScript objects only support string as key, it is not as powerful as the Python version. Can anyone suggest a way of using an object as a key in JS, like some kind of hash function? Also, is there an... |
I have another Python issue, creating a frequency distribution out of a text matching a predefined wordlist. In fact, I work with more than 100,000 text files (each consisting of about 15,000 words), which I want to inread and accordingly match against a word/expression list (vocabulary_dict) of about 6,000 entries. Th... |
Instead of picking a random pivot I'm shuffling the array beforehand. Does it count as randomization and is it efficient to shuffle or pick a random pivot and is my implementation pythonic?
Problem
Algorithm
from random import shuffle
def _partition(arr, lo, hi, pivot):
p = arr[pivot]
arr[hi - 1], arr[pivot] ... |
I have a piece of code that I am not feeling comfortable.
I don't want to block the UI
Read operation works synchronously (reading may broke 50 ms rule)
Save operation supports async (returns Task)
I have to await SaveChanges (so operation could be completed before Dispose)
public Task AddToMyProject(string director... |
I need to count the number of ways to partition an array into two contiguous arrays such that those arrays contain exactly same set of items.
Suppose A = [4, 1, 1, 2, 4, 2, 4, 1]. If you pass this array to the function, it needs to return 2. (Those subarrays are [4, 1, 1, 2] & [4, 2, 4, 1] and [4, 1, 1, 2, 4] & [2, 4,... |
I have a small function that when passed a str that names a file that contains a program; it returns a 2-tuple with the number of the non-empty lines in that program, and the sum of the lengths of all those lines. Here is my current functioning code:
def code_metric(file_name):
line_count = char_count = 0
with ... |
I've got this code to work, but being really new to PHP, I don't know if this is proper. I've sorted a CPT loop by a custom date.
I'm displaying items from most recent (or future date) to oldest
if the custom date is in the future I display an additional HTML element that says Coming Soon. I've used strtotime for the ... |
As a challenge for my own amusement, I decided to write a SAS macro for sorting datasets, deliberately avoiding all of the built-in methods (e.g. proc sort / proc sql / ordered hash object).
Remarks:
I've kept as much of the logic as possible in data step code, but inevitably there's still quite a bit of macro logic. ... |
Challenge:
Find the duplicated entry.
Specifications:
Your program should accept as its first argument a path to a filename.
Each line in this file is one test case.
Each line begins with a positive integer(N), the size of the array,
then a semicolon followed by a comma separated list of positive numbers
whi... |
I have been updating my build tools to optionally us autotools (autoconfig/automake/libtool etc.).
As part of this change I have written a couple of M4 macros. This not being something I have done before, any input appreciated on style or if things can be done better.
AC_DEFUN(
[AX_FUNC_THOR_BUILD],
[
A... |
I have been updating my build tools to optionally use autotools (autoconfig/automake/libtool etc.).
As part of this change I have written a couple of M4 macros. This not being something I have done before, any input is appreciated on style or if things can be done better.
This macro checks to see if the YAML libraries ... |
I have been updating my build tools to optionally use autotools (autoconfig/automake/libtool etc.).
As part of this change I have written a couple of M4 macros. This not being something I have done before. Any input is appreciated on style or if things can be done better.
A macro for detecting what version of C++ is av... |
I'm creating a thing that does things. Part of the things the thing does is querying an API for information about movies and TV shows. The API allows me to query for changes to their data so I will first iterate over every entry they have (IDs are numerically represented), store its information locally and then periodi... |
I wrote this class for the project I'm currently working on. It's basically used to change a user's password. I'd like to know your thoughts on the basic structure/design of this class and how it can be improved, or if you'd have written it differently.
class Recover_password{
//class by sami
private $conn;
... |
I saw this question and answer about calculating pi on Stack Overflow, and I decided to write my own program for calculating pi. I used Python and only integers (I didn't want to use floating point numbers), and used the Gauss–Legendre algorithm because it was the simplest to implement (I considered using the Borwein's... |
Having started a new software dev role recently I'm in the process of developing my first full web app project using the following stack HTML + CSS + JavaScript + PHP.
I'm new in terms of applying these lessons I have learnt in the recent past in each language (as you might see from my basic sounding earlier questions... |
I'm studying design patterns and I made this car store implementation. Although I'm confident that the idea is right, I'm not confident that the implementation is good. I would like you to check it out and give me some advice.
It doesn't have tests, and I'm using an abstract class with a private method.
Car:
<?php name... |
My assignment in CS was to make a knight's tour application that could solve the problem from any starting position. I had just finished the code so excuse the lack of deeply descriptive comments. My goal was short code length and easy comprehensibility. There is a lot of excess code such as putting the 0 border around... |
This code uses a DCG and pairs phrases into near-English sentences. If anyone is familiar with Prolog, I'm wondering how I can use the code as an encryption method by hiding data and replacing it with the DCG produced phrases so it turns the hidden text into pseudo-random data.
The phrase production code is:
l:senten... |
I coded the following program to solve the n-puzzle problem with n = 3. Are there any suggestions regarding readability and variable names?
import heapq
from random import shuffle
import math
n=3
fBoard = [1,2,3,
4,5,6,
7,8,0]
board = [i for i in range(9)]
shuffle(board)
print(board)
aStar()
c... |
I have written the code to concatenate two arrays . Please let me know of any loopholes in the written code.
import java.util.Random;
import java.util.Scanner;
public class ConcatArr {
static Random rand = new Random();
static Scanner in = new Scanner(System.in);
public static void main(String[] args){
... |
I have been implementing Salsa20 by studying the design and specification. I have made sure to unit test every function along the way and match the outputs against the test vectors in the spec. I am aiming for readability/auditability of the code as a whole rather than raw speed, so I have not followed the C reference ... |
I have Set of character delimiters (DELIMITERS), eg . , etc. Using this I want to split text and get words with their position in text.
String.split() works fine if you want only words. The same with StringTokenizer. Wrote some simple method to deal with this, but maybe there is a better way to achieve this result?
p... |
I have a form that reads a JSON file for default wrong answers to be applied to a 'summary div' at the end of the form.
I wondered if I could make these two functions one somehow?
It is a bootstrap modal, that I am using data-attributes to get the right answers which populate the text in the modal body, then when I cl... |
Are the catch statements ok or must I put in a println()? In general, is the code good-looking enough?
public void music(String song) {
try {
File soundFile = new File(song);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
// load the sound into memory (a Clip)
... |
I've been reading about loops this morning, to try to improve this snippet of code:
$deliveryoutcode1 = array();
$deliveryoutcode1 = explode(",",$rows['deliveryoutcode1']);
$deliveryoutcode2 = array();
$deliveryoutcode2 = explode(",",$rows['deliveryoutcode2']);
$deliveryoutcode3 = array();
$deliveryoutcode3 = explode("... |
Description
need to find out the paragraph number which is containing all the words in the file.
input file java.txt
What is a JVM?
What is the most important feature of Java?
Are JVM's platform independent?
What do you mean by platform independence? What is the most important
feature of Java? What is a JVM? Are JVM... |
I'm getting into CSS/HTML by myself. I'm already familiar with many programming languages (C, Java, etc.), but I don't know much about web development, especially about good programming practices when it comes to CSS/HTML. Could you guys please give me some tips and point out what I did wrong? I did kind of a small por... |
I have a makefile like the one below and I am trying to simplify it. I know I should be assigning variables to cut down on repeated things but I am still confused as to how to properly simplify this as small as possible.
#
# Linux makefile
# Use with make
#
.SUFFIXES:
.SUFFIXES: .o .asm .cpp .c
AS=nasm
ASFLAGS= ... |
I'm trying to teach myself some Cython. To do so, I use Project Euler #10:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
2 Find the sum of all the primes below two million.
My Cython code is:
from libcpp.vector cimport vector
from libcpp cimport bool
SOLL = 142913828922
def run(unsigned long top = 20000... |
I redirect all my requests to index.php via htaccess and the code below is in my index.php.
I want to ask if my code is properly set for a custom 503 page for an unsuccessful MySQLi connection trial.
Is it also proper to use these metatags?
<meta name="robots" content="noindex,nofollow,noarchive">
<?php
$mysqli = new... |
Multiple threads write data to a file. When maxLines is reached, the file is closed and a new file is created:
public synchronized void writeLine(String data) throws IOException {
writer.write(data + "\n");
lineCounter++;
if(maxLines != 0 && lineCounter == maxLines) {
close();
lineCounter = 0;
fileC... |
Here is my implementation of the k-means algorithm in python. I would love to get any feedback on how it could be improved or any logical errors that you may see. I've left off a lot of the boilerplate code like the command line argument parsing, error handling for data read in from CSV file, etc. and just added the me... |
I've built a small single threaded TCP server using NIO.
This server is used by small client devices to report things like temperature, when the device has been switched on, when it switches off, and various other parameters. The server then saves those parameters to a database.
We've implemented a very simple protoc... |
Looking for code-review, optimizations and best practices. This question is attributed to geeksforgeeks.
NOTE: Please help me verify space complexity, as I am creating TreeData objects in recursion. I believe it is \$\mathcal{O}(1)\$. Ignore the space-complexity of stack frames. Looking only for space occupied by TreeD... |
I have the following method:
public static HashSet<PathDetails> GetDeletedPaths(HashSet<PathDetails> old, HashSet<PathDetails> current)
{
var deleted = new HashSet<PathDetails>(old);
deleted.RemoveWhere(x => current.Any(y => y.Path == x.Path));
return deleted;
}
PathDetails is a struct that, among other th... |
I'm switching my code to promises - mostly as delivered by Mongoose. I use Hapi though I think something similar would apply to Express.
In my models/services I perform queries such as:
var sampleMethod = function(id, status) {
return Model.findById(id).exec().then(function(item) {
if(!item) return Boom.notFound... |
I have looked at many different approaches to this game online, but as someone who isn't very experienced with Python, I may not be aware of what others are doing right.
import random
def RPS():
print("You are playing Rock Paper Scisscors")
comp_possible = 1,2,3
score = [0,0]
flag = 0
while True:
... |
A function that prints out the values of each of the bytes of a variable, which value is given from stdin.
Consists of size detector and a loop.
#include <stdio.h>
#include <math.h>
int main(void)
{
unsigned char uint_8;
unsigned short uint_16;
unsigned long uint_32;
unsigned long long uint_64, n = 0;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.