instruction stringlengths 71 71.9k |
|---|
My teacher wants me to find all the perfect numbers between 2 and 1000 and must use:
for loops
% operator to determine if a number is a divisor
static final variables for 2 and 1000
A static method to return a boolean value by finding and adding the divisors of the integer parameter and comparing the sum to the parame... |
I have written this simple DBHelper class to access a MySQL database. I am rethrowing a more generic exception so that the client side can take some action like showing a friendly message on the screen. Is it ok, or can something else be done?
using System;
using System.Collections.Generic;
using System.Linq;
using Sys... |
On scroll, I am adding a class (current) to particular elements.
The code looks like it can be made better. For example, it seems like I am reusing the same things over and over again (i.e. the nth-child(1), nth-child(2), etc.).
I appreciate any and all comments and advice.
function isScrolledIntoView(elem) {
if (... |
I know that, in Windows, memory must be deallocated in the same module that allocated it.
I have 2 DLLs built with different C++ compilers (VS 6 and VS 2015). In the VS 2015 module, I have an exported function which returns a variable number of items (let's say of int type), so I need a variable-sized buffer.
I'm tryin... |
I wrote this template to do as stated in the title; did I miss anything?
template<typename T> T clockmod(T v, T m) //todo: test T is numeric
{
typedef long double D;
T t=(m-m); //zero default
D dv=std::fabs((D)v);
D dm=std::fabs((D)m);
if ((dv>0.0)&&(dm>0.0))
{
int id=int(dv/dm);
... |
As a development team we've recently started to transition from MVC to Angular. None of us have had prior experience with it so a lot of creating the new client was very much trial and error. I've been put in charge of sorting out unit tests however I'm finding it very difficult to unit test.
In my experience if somet... |
Please review the following quicksort implementation.
qsort below is intentionally unstable, as partition reoders equal elements.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Ensures pivot is at position end.
template<typename Iter, typename T>
Iter part_pivot(Iter begin, Iter en... |
For a project I am working on I had to query a database for a number of "child objects". Now in the mapping POJO for said child objects a reference to the parent is kept. That reference is available in the database as a foreign key constraint.
But if I retrieve a collection of all child elements they all map to vastly ... |
I m working on calisthenics objects and I'm actually having some troubles while trying to follow the calisthenic objects rules.
In fact, I m stuck with the one telling that we have to wrap all the primitives inside of objects.
Context
I'm having a Euro object that looks like :
public class Euro {
private double am... |
I've read in a text file to excel from a database and I've done it in such a way that it filters out unnecessary columns. My approach to filter rows was to use two subroutines and call the 2nd from within the first. It takes ~8 seconds for the sheet to be filtered and there is only 400 or so rows. The fact that it take... |
I'm currently writing code so that when a red-colored cell appears in a column, a message box will appear letting me know that column has an error. I have written the following method:
Sub MSG()
Dim a
Dim B
With Application.FindFormat.Interior
.color = vbRed
End With
'/ Sheet1 is example ... |
I have a script that alphabetizes the layers in Adobe Illustrator. It does so by sorting the layers in an array (using string names) and then using that to change the item order position (zOrder) of the layers. The script runs fine, however if there is a very large layer (which I deal with a lot) of over 8000+ it gets ... |
While writing a C++ implementation for weighed, labeled graphs, I started to doubt the effectiveness/correctness of my chosen structure and I would like to hear some reviews.
I tried to implement the graph as follows:
template <typename T, typename K> struct graph {
unordered_map< T, list< pair<T, K> > > adjList;
... |
I want to get all days of the current week (from Monday to Sunday) with a custom time. To do this, I have written an extension method for TimeSpan:
public static DateTime[] Daily(this TimeSpan ts)
{
var days = DayOfWeek.Monday - DateTime.UtcNow.DayOfWeek;
var startDate = DateTime.UtcNow.AddDays(days);
List<... |
I need to review this code:
import java.util.HashMap;
import java.util.Map;
// REVIEW
public abstract class Digest {
private Map<String, byte[]> cache = new HashMap<>();
public byte[] digest(String input) {
byte[] result = cache.get(input);
if (result == null) {
synchronized (cache... |
This code is executed on a background service every 60 seconds on an Android app. Each class instantiated on FutureTask (WifiInfoFetch and WifiApResults) contains an insert to an SQLite database. We changed the original implementation (without a FutureTask) as we think the first insert was still locking the database wh... |
I have implemented a binary search algorithm in C#. Can anyone give me suggestions on improving its effectiveness?
using System;
namespace bs2
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
... |
I was at the job interview yesterday. And there is a question that asks me to find all the permutations in an array of string in ruby:
input: ['abc', 'cba', 'ab', 'ba', 'acbdef']
output: ['abc', 'cba',
'ab', 'ba']
Here is my implementation:
def find_permutation(arr)
result = []
arr.each do |element|
next if r... |
I have a class which encapsulates stream related objects, and I have provided the method API for doing basic manipulation on the stream read/write/close, but is this a good approach? The only benefit I can see is that if for some reason one wants to use other stream classes at a later point in the project, one can just... |
I'm studying hash tables, and wrote the following to serve as a simple example.
Does this properly demonstrate the basic concept of a hash table?
The values are int from 0 to 9; the hashing "algorithm" is simply to square the number.
#include <iostream>
#include <cmath>
const int KEY_RANGE=100;
const int VALUE_RANGE=1... |
I have a list of 4 images, called listfile.list, which looks like this:
image1
image2
image3
image4
Each image has 10 frames containing a 2000 x 2000 array of pixels, so the size of each image is [10,2000,2000]. The pixel value for each frame increases from 0 to 10, so for example for one pixel in image1:
image1[:,150... |
I have a piece of code where I compare two arrays for similar values, then remove the similar values from one of the arrays. Is there a better way of writing this piece of code?
UpdateAddedTasksAfterDelete() {
var tasksToRemove = [];
var updatedTasks = [];
for (var i = 0; i < this.deletedTasks.length; i++)... |
I started learning Scala, and like most functional languages, things get messy pretty quickly for a beginner.
Here I have built a wrapper class for Ints so that I can declare additional functions for the Int class. For example, I want to be able to do something like 1.isPrime, and it should call a function that tells m... |
Aim
I'm modeling a control polygon for a piecewise spline curve. Each sub-spline is defined by a location the spline must pass through, as well as a forward tangent, and a backwards tangent. The control points and their tangents can be freely manipulated.
I aim at keeping this flexible, so the forward and backward tang... |
Django's get_or_create function returns 2 values: the object and a boolean whether it was freshly created or not. I'm only really interested in the object it returns and this is how I'm doing it.
keywords = [element for (element, _) in [Keyword.objects.get_or_create(keyword=key) for key in keywords]]
But this doesn't ... |
I am new to Java and am trying to learn coding. Here is my implementation of a stack and a queue without the help of library functions. Please provide your suggestions on design, coding style and algorithm.
Stack.java
import java.util.NoSuchElementException;
import java.lang.UnsupportedOperationException;
public class... |
I always end up creating a quick return statement above a code block if the simple condition of textbox null fields are found. Naturally, these tend to build up the more controls are added. Now I'm staring at this mess of code, and I'm looking for advice as to avoid this very common mistake in the future.
This is the s... |
I have finished creating an adapter class which displays characters' info.
When I looked back and reviewed my own code, I think the code fragment below somehow could be broken into smaller methods.
...
private static class ViewHolder {
ImageView imgIconState;
ImageView imgCharacterStatus;
TextView txtName;
... |
Building off the python FileSystemEventHandler and DirectorySnapshot classes, my goal is for a number of projects that I am working on to have a reusable library that will handle file system change notifications while my process is running, but also inform me of any changes that happened while my process was not runnin... |
I did an exercise (self-imposed) promise fetching some data from placeholder JSON files on https://jsonplaceholder.typicode.com/. The exercise in my opinion is finished, but I can't shake the feeling that the code is as dirty as code can be. Please check it out and point me into the right direction and tell me what I d... |
Here is my code which is going to through multiple for loops to get the matching product attribute.
I have single product with attributes trying to find out the matching product with same attribute value from a list of Product. I am having a multiple for loop. Can anyone suggest a way to optimize this solution?
// This... |
I am currently using the code below to truncate text:
function truncate($elem, wordNum){
var words = $elem.find('p').text().trim().split(/\s+/).slice(0,wordNum);
var replacement = $("<p/>").text(words.join(" ") + "...");
$elem.find('.read-more').click(function(){
if($(this).text() == 'Read More'){
replacement.... |
I've written code that selects column D and checks it for codes 1 to 92 however I have to write out c4.Value = 1 Or c4.Value = 2 all the way up to c4.Value = 92, is there a quicker way of doing this? Please see below for my code and I appreciate all help.
Sub q2country_and_q2country_other()
Dim i As Long, c4 As Ra... |
A while ago I posted this question about finding the Date in Range, where I explained I have a spreadsheet to control my shift hours and was interesting in improving one of my functions.
I got really nice feedbacks from the community and the improvements provided really helped me out, but now I'm interesting in anoth... |
I am newbie (here and in C/C++ - WinAPI) so I want to ask you, what you think about my Windows Keylogger in C++? I've worked on it a few days.
Features of keylogger for now:
Self-copying to C:\ directory
Saving keystrokes to an .html file
Working in background
My questions:
Are names of variables are correct?
What c... |
I have this 2 arrays :
final int[] tabSelected = {
R.drawable.iconWhite0,
R.drawable.iconWhite1,
R.drawable.iconWhite2,
R.drawable.iconWhite3,
R.drawable.iconWhite4};
final int[] tabsUnselected = {
R.drawable.iconBlack0,
R.drawable.iconBlack1,
R.drawable.i... |
I've been working on my first "big" project in java, an AES encryption and decryption class, it's now working but i don't know how to improve my code. Also i'm not the best in security and I have no idea if there's something that make my code vulnerable.
I don't have a lot of experience in java so if you have any tips ... |
So I have some code which finds neighbours of a given State. So the positions the blank tile (which is represented as 0 in my code) can be moved.
I am doing the 3x3 tile puzzle. The goal state is represented like this :
1 2 3
4 5 6
7 8 0
Say I have a problem state which is:
8 5 1
3 4 7
0 6 2
I would call the findNe... |
My use case is I want a password generator that generates memorable and robust passwords for users, to give me a known minimum entropy.
For this - I'm approximating set of Consonant-Vowel-Consonant words, because then they are both memorable (ish) and have a known entropy level. The reason for this is because I'm not... |
In my implementation of a binary search tree, most functions take a pointer to a node (because of their recursive nature). So I found myself having to overload them, and the overloaded versions form somewhat of a public interface to the functionalities of the class. Is the design of the class good or bad? If it's bad p... |
I'm currently going through a large Python program, with an eye to making it more readable and maintainable. Currently using Pylint and other code review tools throws a lot of unused variable warnings because of the way I've been using .format(). Since this program manipulates a lot of text, I use .format() quite a lot... |
I am building a highlight feature for search results on my website and need to escape the user's input so that I could highlight the matching string within the original text.
The function
function sanitize_for_regex(s){
var escaped = '';
for(var i = 0; i < s.length; ++i){
switch(s[i]){
case ... |
I have a class in which I am passing certain parameters through the constructor and then using those parameters to make one final byte array with a proper format (header + data) and it works fine:
public final class Frame {
private final byte addressedCenter;
private final byte version;
private final Map<byte[], ... |
I'm trying to create a mini social network mobile application kind of like Instagram and I'm not sure about my database organisation, it feels like something is missing, especially with the Posts table.
CREATE TABLE Users(
'user_id' int(20) NOT NULL AUTO_INCREMENT,
'email' VARCHAR(255) NOT NULL,
'username' VARCHAR(25) ... |
This seems to do the job of the EAV tables. Besides being EAV, is there room for improvement? Maybe there is something obvious, but how about indexing certain columns?
from django.db import models
class Entity(models.Model):
entity_id = models.AutoField(primary_key=True)
entity = models.CharField(max_length=1... |
Problem 1
StratifiedJS allows people to cleanly create observable streams using the Stream class from sjs:sequence:
var {Stream} = require("sjs:sequence");
var integers = new Stream(function(emit)
{
for(var i = 0; true; i++)
{
emit(i);
}
});
Streams can then be iterated through using the each func... |
Below is my implementation of dynamic array without help of library functions. Kindly provide your suggestions on design, coding style and algorithm.
MyDynamicArray.java
import java.util.NoSuchElementException;
public class MyDynamicArray<T>
{
private int positionPointer=0;
private int arraySize;
private T... |
I want to load Interstitial AdMob after 5 second, after the Activity started, in another Thread. Is this code right, or I'm duplicating Runnables? Is there a better way?
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActivityImmersiveM... |
This little chunk of code is run every 10 seconds on my desktop. It generates a PNG with up to 6 player faces based on the list of online players.
Is there any way for this code to execute faster? Any comments?
Each player has a PNG of their avatar's face with the title: "username_face.png" These are pasted into the m... |
This is my first attempt at solving Fizzbuzz. I've always been pretty weak at algorithms, so I'm trying to improve. Specific feedback on performance would be appreciated.
def fizzBuzz(fizzNumber, buzzNumber):
i = 0
for i in range(1, 101):
fizzBuzzValues = [i%fizzNumber, i%buzzNumber, i%(fizzNumber * buzzNumb... |
In my Rails app, I have a form. The form has radio buttons for entity type and has a text field for SSN and another for EIN. Based on the radio button selected, one of the text fields will be disabled and the other enabled (disabled = false).
If the user selects the radio button for entity_type_i, it should disable th... |
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.InputStream;
import java.util.Random;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sample... |
I have two solutions to the task and they are all passing the visible tests but when it is time to submit, I keep getting my failed to pass all tests. There are still some hidden tests my code isn't passing.
The task reads as follow:
Write a program that checks if a word supplied as the argument is an Isogram. An Isogr... |
I am working on creating a test library, and I found DI to be pretty convenient, maybe even to create more functional coding patterns.
Normally we can have an awkward before-hook setup in Node.js testing libraries, and it's always a little unclear when things actually get initialized and refactoring can be harder than ... |
I have this generalization of FizzBuzz in Java:
import java.util.Map;
import java.util.TreeMap;
public class GeneralFizzBuzz {
public static void generalFizzBuzz(Map<Integer, String> map,
int start,
int stop) {
String startStr... |
I'm using Laravel with the Blade template engine. I'm trying to show a search input bar, depending on which path the user currently is viewing. The three paths are all, snes and nes.
This is what I have done so far:
@if (request()->route()->getName() === 'snes')
@include('partials._search')
@endif
@if (request()->... |
I have from a recommendation on my other question here:
My other review post
Developed a truncate plugin, and was wondering if you guys could help me improve it or see where I have gone wrong.
Plugin code:
$.fn.vishTrunc = function(options) {
var settings = $.extend({
size: 100,
omission: '... |
I am using one of the open-source Objective-C keychain wrappers to store data in iOS keychain.
For test cases, I have created protocol as:
protocol KeychainProtocol {
func deletePassword(forService service: String, account: String) -> Bool
func setPassword(_ password: String, forService service: String, account... |
Here is a Python script that streams Twitter either with a keyword or within a bounded geographic area. Errors are emailed to my Gmail and the tweets are stored locally in MongoDB. Please let me know if any improvements can be made.
import tweepy
import sys
import pymongo
import smtplib
import sys
#The following funct... |
I created little decision tree, what do you think about it, what I can correct? I wanted to create a code for tree that looks in that way:
My implementation:
using System;
using System.Collections.Generic;
using System.Text;
public interface TreeNode
{
bool nodeState { get; }
bool Evaluate();
}
/// <summary>... |
For the Code Review community challenge "Implement StackSTV", the algorithm requires a "convergent iterative scheme" to calculate the keep ratios of candidates that have been elected.
To simplify the calculation of those keep ratios I have written following function to truncate an infinite list that calculates the keep... |
Looking to confirm that I am doing this in the most efficient way.
func convrtisbn10(isbn: String) {
var checkSum: Int = 0
var completeISBN = ""
let newISBN = "978" + "\(isbn)"
let result = String(newISBN.characters.dropLast(1))
var oddSum = 0, evenSum = 0
let reversedArray = result.characters
... |
Most implementations of FizzBuzz that I've seen rely on 3 modulus operations. Mine does two and a Boolean. (Not implying one is better, just different)
I understand that FizzBuzz is supposedly not to identify great coders, but rather to weed out those that would fail, but I'd like to know if this solution would likely ... |
Motivation
I created this because the Visitor pattern felt like the most appropriate, but I also wanted to satisfy the Open/Closed principle with respect to the logic when visiting specific node types. I also needed the ability to "return" a specialized value type from visitation without wanting to tie that knowledge ... |
The pe4Concurrent.go file given below is my first attempt at writing a concurrent programme, pe4.go is a non-concurrent implementation of the same algorithm for comparison purposes.
The algorithm itself is a simple, brute force solution to one of the Project Euler problems.
Basically, I'm very new to both Go and concu... |
To learn JavaScript I made this slider. It works good but I can see myself that there is a lot of repeating of the same code. How can I rewrite it?
Codepen
var slides = document.querySelectorAll('.slider .slide'),
currentSlide = 0,
firstBtn = document.getElementById('one'),
secondBtn = document.getElementById('... |
I need to sanitize some chars. I have a solution that works but I am wondering if there is a better solution that may be faster or better or if I flat out should be approaching this differently?
function escapeStr(_str){
if (/\"|\'|\%/g.test(_str)) {
_str = _str.replace(/"/g, "%22");
_str = _str.re... |
After been taught about Queues in lecture I've tried to do my own implementation.
I like to mention: The ideas were shown in lecture on a blackboard using a pseudocode notation.
The following code has been figured out by myself based upon my lecture notes.
I've avoided having a closer look upon a concrete Java-implem... |
I was inspired by @LU RD's answer to the question: Using VCL TTimer in Delphi console application, and wrote a bit simplified TTimerThread class.
By simplified I mean, I did not used TSimpleEvent;TStopWatch and used API. This will also work for older Delphi versions such as D5. I also "reintroduced" the public Terminat... |
People have different types of roles depending on the office they are working at. For example, a person has two roles (cashier,cleaner) at OfficeMax and five roles(manager,security,etc) at OfficeLess. Typescript is used.
interface Person {
name : string,
roles : OfficeRoles
}
interface OfficeRoles {
rol... |
In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array.
The code returns true if an element is present in the array else returns false.
Any suggestion in improving the code is welcome.
Binary_Sea... |
I am learning Go and want to do things the go-way, please have a look this code suggest how to make it better Go.
This is a simulation to determine how items of a particular type of clothing you need. Rules are as follows:
Simulation starts with all the clothes in the clean pile
Every morning you take one item from th... |
Is adding CSS to template via <style> the right approach?
How should I structure the application?
Plunker link to the code
app = angular.module("app",[]);
app.controller('main', ['$scope', function($scope){
$scope.name="here";
$scope.date = new Date('2/1/2016');
}])
app.directive('cal', function(){
var directive... |
In this question, I need to find the sum of 2 arrays element by element.
Arrays can be of unequal length.
Explanation: Sum of [1, 0, 2, 9] and [3, 4, 5, 6, 7] is [3, 5, 5, 9, 6] and the first digit represents carry over , if any (0 here ).
Here's what I could come up with. Let me know if anything could be done better,o... |
I already solved the problem, but it seems my code is too awkward, and with a different approach there could be a more elegant solution.
Notice that the general algorithm is described in the instructions:
This is the problem description:
Given unsigned integers 0 ≤ k ≤ n, generate all the k-combinations of
the n obj... |
This is from Wikipedia:
In mathematics, Waring's prime number conjecture is a conjecture in number theory, closely related to Vinogradov's theorem. The conjecture is named after the English mathematician Edward Waring and states that every odd integer exceeding 3 is either a prime number or the sum of three prime numb... |
I have code to find images in my selections. But when nothing in selection (loop FOR) and selection is kinda big, it's kinda laggy. How can I improve my code?
var toStageCoord = map.stageXYToCoordinates(toStage.x + selection.x1, toStage.y + selection.y1);
var element1 = document.elementFromPoint(toStage.x + select... |
I am trying to Bruteforce a PCP that is supposed to be up to the length 300.
I wrote a little Python program that is doing just that but it could take forever until my program finds the right PCP.
import sys
x1 = "aba"
x2 = "a"
x3 = "bab"
y1 = "a"
y2 = "ab"
y3 = "abaa"
def ternary(n):
if n == 0:
return ''... |
For my latest app I wanted to be able to code the front-end first, without having to do super extensive documentation and without forgetting my data types later on while coding the back-end.
I thus tried to make some kind of JSON Validator that expects something and outputs true or false depending on the input fed to i... |
I am working my way through Project Euler. Many of the problems deal with prime number calculations: this is the type of code that can be extracted into a separate class and reused.
While calculating primes can be done quickly using certain methods, I was able to speed up the process of "getting prime numbers" by usin... |
The program reads words line by line from a file. It finds anagram groups and prints them in new line. Except for the GUI class, the anagram class takes 2ms.
I would like to be criticized in detail readability, correctness, efficiency, error handling and name convention.
And for potential question: if a data set is muc... |
I want to assign corresponding variables based on the name to save each directory from a folder, including its subfolders, so I can get access to the file in each folder easily. The code created by myself doesn't look concise. Any suggestions?
import os
modelFld = r'C:\model'
baseInputFld = [os.path.join(modelFld, x... |
I recently started to work with python and came to idea to automate process of looking for new jobs. There is nice website and I managed to get content, because they use angular to render webpage and using just requests gives no results, because page is rendered using javascript.
Below code is functional, but a bit slo... |
If this question is not a good question for this board, I will remove it. I am looking for ideas on how I could improve the code as I am a beginner trying to learn how to program.
Here I have a program that creates a subproblem for each item that is entered into this function in order to solve a greater problem. I am c... |
I have a method that takes in a String parameter, and uses NLTK to break the String down to sentences, then into words. Afterwards, it converts each word into lowercase, and finally creates a dictionary of the frequency of each word.
import nltk
from collections import Counter
def freq(string):
f = Counter()
s... |
I created these little utility methods to build fluent C# dictionaries. The value declarations shall be quick to write and easy to comprehend when somebody views the code. Usage conditions are as follows:
many keys point to the same values
group keys pointing to one value. Declare value only once for better visual com... |
I was trying to make something to compare two version numbers. The version numbers should consist of three parts (1.4.3). I also wanted to take into account if there is badly formatted data or if 1.4 is used instead of 1.4.0. Any bad data will be converted to a 0. I wanted to find something simple and fast. This is wha... |
Is there any good advice on how to improve performance in terms of algorithm time complexity? I am using a recursive solution and am not sure if any faster non-recursive solution exists.
import sys
class TreeNode:
def __init__(self, value, left, right):
self.value = value
self.left = left
se... |
This post is follow up of this, suggested by @loki-astari which can be found here.
Any further improvement is welcome.
Binary_Search.h
#ifndef BINARY_SEARCH_H
#define BINARY_SEARCH_H
template<typename RandomIt, typename T>
RandomIt binary_search(RandomIt begin, RandomIt end, const T& key);
#endif // BINARY_SEARCH_H
... |
I've been trying to find the minimum steps it takes for a number to be reduced to 1 given the three following steps:
Divide by 2
Increment by 1
Decrease by 1
My code is as follows:
def answer(n):
num = long(n)
count = 0
while num > 1:
#When number is odd
if num%2 == 1:
#If the numb... |
Here is my merge sort c++ implementation. Looking for code improvement and optimization opinion. Just one question which is better *k++ = *i++; or, *k = *i; ++k; ++i;.
/*
* Merge Sort
*/
#include <iostream>
#include <vector>
void mergeSort(std::vector<int> &v, std::vector<int>::iterator p, std::vector<int>::iter... |
I made a small program to compare floating-point values by running multiple tests to a single pair of floats. I have added extra checks for under/overflow and allowing tolerance.
How can I improve it further?
#include <type_traits>
#include <cctype>
#include <cfloat>
#include <limits>
#include <bitset>
#include <iostr... |
I have written a couple of scripts for accessing Twitter REST API, and storing data in a Postgres DB for data extraction purposes. I know how to use django ORM, or plain SQL, but this was my first attempt at SQLalchemy. I am not sure if the way I use sessions makes sense.
There two scenarios:
The streaming API script w... |
I want to backup a single SQLite database daily up to 30 days back, but I also want to keep at least 2 backups at all times (i.e. if there have been no backups in the last 30 days because the database didn't change, I don't want to delete old backups).
I came up with this simple script that is supposed to run as a dail... |
I want to gain experience creating data structures that look and feel like Python builtin types. As a first exercise, I've written a WraparoundList class meant to be identical to the builtin list, except that accessing out-of-bounds elements "wraps around".
Goals:
The only behavior that differs from that of a list is ... |
This is simply an extension method which checks if a string str contains all the values in values.
However, there are cases when str might be null, values might be null, or any item in values might be null. I am handling those cases by using the ternary ?:, null-conditional ?. and null-coalesce ?? operators.
Should thi... |
I am trying to create a Tic Tac Toe game in Java using a 2 dimensional array. The computer has to do the smartest move.
/* This program creates an interactive game of Tic-Tac-Toe
* The computer is able to play intelligently and block the user and try to win
* It uses a 2D array to create a grid for the game
* The us... |
I'm learning Python as my first language and this is my first OOP project. What improvements can I make on my code for style, best practices, better logic, and to make it more efficient?
from __future__ import print_function
import random
class Chest(object):
possible_contents = ['Key', 'Horn', 'Brandy']
de... |
I am trying to teach myself JavaScript. I've read some online tutorials and watched some Douglas Crockford videos and decided to dive right in.
I made a little table editor in JavaScript: there's been quite a bit of fighting with the DOM but I think I've mostly figured this out.
Am I on the right track? Any comments on... |
I have an object that has an array inside with another object inside. I iterate over the object and array to print out the first name and last name of the people inside the array of objects. I am wondering if there is a better way to do this.
Without having to use obj[i].first_name + " " + obj[i].last_name
Here is my... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.