instruction stringlengths 71 71.9k |
|---|
I just wrote a function that will loop through two multidimensional associative arrays and merge them together based on the key names and their values. While I'm satisfied that this function works, I have a strong feeling that it can be improved. Can I get some feedback?
<?php
function array_merge_defaults (array &$ar... |
The previous version of my function was scalar-valued and employed a WHILE loop to do the comparison, this is SLOW. This new version is tabled-valued and uses a typical tally table in place of the loop. The result is an implementation that is MUCH more efficient while being slightly easier to comprenhend (IMHO).
There ... |
This one of my first Python games in PyGame I decided to make for fun. Basically, you control a from top down perspective and shoot people in a maze.
This is the rewrite of the original code, and I'm aware that it is still probably very inefficient and has does many things frowned upon by many such as many repeated if ... |
I'm making a sliding tile puzzle using C++, and have code that exchanges the blank tile for one adjacent to it.
Using user input, the program takes the input and puts it in the function which uses a switch statement to determine which direction the user wants to switch, then preforms the switch if applicable.
I was sim... |
I'm using the MEAN stack to make a small chat app, which will soon support braided messaging. This is my first Angular app so I am not sure how I'm doing on the front end portion in terms of keeping it neat and organized appropriately (might be too monolithic). I have not used any directives, and my HTML feels like it ... |
I have tried to come up with a solution to the longest increasing subsequence problem.Can this solution be optimized further?
Example 1:
Input: {5,4,3,7,8,9,11}
Output: 3, 7, 8, 9, 11
Example 2:
Input: {1,2,1,2,1}
Output: 1, 2 (the latest one)
Implementation:
public class LongestIncreasingSubsequence {
pu... |
I've recently started learning how to code in Python, and have even more recently learned the basics of object-oriented programming. Feeling inspired, I started on a program that would generate random cards. I'm really excited to have completed a project like this for the first time!
I had a problem of duplicates, whi... |
Here's my implementation to factorize a positive integer:
def is_prime(n):
if n == 1:
return False
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
# @timeit
def prime_factors(n):
prime_factor_list = ... |
I've been trying to implement the basic search algorithms: Sequential search for ordered and unordered arrays and the binary search algorithms, as part of a package.
So, this is the implementation:
"""
`seqsearch{T}(x::AbstractArray{T}, item::T)` ↦ found::Bool
Searches for an item using the **Sequential Search** approa... |
Here's the code
max="$1"
date
echo "url: $2
rate: $max calls / second"
START=$(date +%s);
get () {
curl -s -v "$1" 2>&1 | tr '\r\n' '\\n' | awk -v date="$(date +'%r')" '{print $0"\n-----", date}' >> /tmp/perf-test.log
}
while true
do
echo $(($(date +%s) - START)) | awk '{print int($1/60)":"int($1%60)}'
sleep 1
... |
I'm really new to programming, currently following several tutorials and guidelines.
After a couple of days of studying, I've learnt the basics of Java and conditionals and took on my first program. It was written all out of my head.
The program is a sort of gambling machine. Each turn, the player has to guess a number... |
I have written a simple Euler solver for the 1D shock tube problem. Eventually, I plan to extend this code to solve the full 3D compressible Navier-Stokes equations. Therefore, I want to start with good programming practices as it will be more difficult to modify the code further down the road. The idea is to find good... |
I've written the following helper class to help serializing objects to and from Json.
I would appreciate some feed back on the style of the class.
using System;
using System.IO;
using Newtonsoft.Json;
namespace Helpers
{
public static class Json
{
public static void SaveContractToJSON<T>(T contract, st... |
I had read the question: Bush Wanderer - code intended for teaching and wanted to play with PowerShell. Including the rules of the game from that same question.
Bush Wanderer
Task 1
Create a 5x5 grid of hashes(#) where the player is an x on the
board
Prompt the player to move in either N, E, S or W direction and the... |
Background
I’ve started putting all my configuration files (which include many shell files) under version control. In the Git repository, I’ve configured a pre-commit hook that runs the checkbashisms utility from Debian’s devscripts package on each sh file in the repository as a simple sanity check to ensure that I do... |
A project I'm working on often has lists within lists within lists etc. The original author often uses complicated linq expressions, but when adapting them I mostly get hopelessly bogged down and resort to foreach's which makes me feel like a lesser being (joke). With an expression such as the following, what would t... |
My program's Journal consists of unique Pages identified by their Day. Within those pages are a collection of Entry (wrapped in an interface of their own, Entries).
Users will be directly interacting with unique Pages supplied by the Journal upon passed an instance of Day.
Within those Page he/she could opt to change t... |
I'm trying to make my QuickSort faster than it is and I have got no more ideas about how to make it more efficient for all types of arrays but mostly very big arrays. It uses random to create the Pivot and it uses InsertionSort when the array is less than 15 elements. What do you think guys?
I appreciate for any help h... |
A low-level jet is a local wind speed maximum near the surface. Baas (2009) defined a low-level jet as follows:
the lowest maximum of the wind speed profile in the lowest 500 m of the atmosphere that is at least both 2 m/s and 25% faster than the next minimum above (...) A minimum is neglected if the wind speed above... |
First of all I am a newbie in Go. I wrote a CRUD REST API that consists of handlers, a database layer and so on, and it contains a lot of code duplication. I see some patterns here, and I know how to reuse code in some other languages like JS or Java using generics or dynamic types.
What are my options in Go? Note that... |
A while back I had opened this topic: Tic Tac Toe - Stage 1: console PvP
I had to put that mini-project on hold due to exams, but I've started working on it again a couple of days ago. Now it's possible to play vs. an AI, or to let two AIs play against each other. The choices can be made in a menu.
I've studied in the... |
I've designed a class ObjectPicker that can be given objects and weights. Objects can be picked randomly out of the ObjectPicker, with heavier weighted objects having a higher chance of being selected.
The pick() method is designed to be recursive and provide \$O(\log n)\$ speed. What I'm not sure about is the defaulti... |
Background:
Recently, I've been working through Coroutining Folds with Hyperfunctions. Don't bail out now if the whole thing makes little sense - it's just the motivation for the existence of my code, not what I actually want reviewed.
I followed a rather typical approach of starting with the data structures and types ... |
For a project I had to do a memory management problem without creating any custom classes or templates using the provided pool array and poolSize.
I implemented all functions and created two extra, SizeConversion and GetSize. My main question is this: is there a better way to implement this and is the code that I have... |
I have the following code in a Symfony site that validates a user's credentials and logs them in via the Session class:
/**
* Validates an Affiliate
*/
public function validateUser($username, $password, $session, $securityContext)
{
$repo = $this->em->getRepository('JCMainBundle:Affiliate');
$user = $repo->f... |
A TreeView on the left which just displays a list of files saved by the application. A DataGridViewon the right to display data from a file clicked in the TreeView, or to type directly into to create a new file. Files in the application are just Dictionary<string,string> objects written to disk with a BinaryFormatter.
... |
This problem is using dynamic libraries so that additional calculator functions can be added by dropping a library into a specific directory.
What I'd like to get out of this code review is:
What do I still need to do to make this more C++ and less C?
Is the object oriented nature of the code good, or am I missing som... |
I would really like to hear out some suggestions as well as general response to the code I've written for 4 players snake game. It's my first time using pygame module, as well as trying to design a simple game, in general. I've encountered few bugs which I've managed to fix, but I would like to improve my code and refa... |
I am practicing my coding on leetcode, and my submission, although correct for small cases, is timing out for large ones. Could you please let me know how to improve my code?
The question is as follows (https://leetcode.com/problems/longest-increasing-path-in-a-matrix/):
Given an integer matrix, find the length of the ... |
I have a slice of strings, and within each string contains multiple key=value formatted messages. I want to pull all the keys out of the strings so I can collect them to use as the header for a CSV file. I do not know all potential key fields, so I have to use regular expression matching to find them.
Here is my code.
... |
I am developing a poker application using C#. It is almost done, and I'm looking for improvements. One of the things I wonder is whether I should change my method that checks if the player has a flush. It's quite big compared to the others but it works just fine, however, something can be improved. Maybe put some of th... |
I have a method on my user model to calculate the user's age and return a human readable string. My user's can be between 1 month old and above so the returned string is different depending on if the person is "2 months old" or "1 year old" or "2 years and 3 months old".
I have reviewed a few SO posts to come to this ... |
I need to find which percentile of a group of numbers is over a threshold value. Is there a way that this can be speed up? My implementation is much too slow for the intended application. In case this changes anything, I am running my program using mpirun -np 100 python program.py. I cannot use numba, as the rest of th... |
I am trying to implement a singleton CacheDependencyManager, by combining this CacheDependencyManager from Steve Greatrex with a singleton pattern from Jon Skeet (example 6).
I'd really appreciate any feedback on it's correctness and / or suggestions for improvement.
ExplicitCacheDependency
public class ExplicitCach... |
I'm trying to improve my Angular skills by writing some basic applications that use a particular feature. The following application uses the UI Bootstrap modal to add users to a list, or remove them again.
Any feedback on any part of the code is very much appreciated, but I have some specific concerns around the way d... |
I was recently asked this in an interview for a front-end position and I came up with something like the code below, which seems to work but is clunky. (Number.toString() was not allowed.)
function convertBinary(number) {
var n = 0;
var binaryArr = [];
var difference = Math.pow(2, n);
//find out how many dig... |
I'm trying to implement the fast median filter developed by T.S.Huang (HUANG, T.S. 1981. Two-Dimensional Signal Processing II: Transforms
and Median Filters. Berlin: Springer-Verlag, pp. 209-211.).
http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=1163188&tag=1
Please review my code. My most important issue here is ... |
This is my very first foray into Clojure (I'm normally a Python-pushing data-type). I'm trying to create a simple term-document matrix as a vector of vectors, out of a vector of strings.
For those who aren't into textmining, the term-document matrix is a dataset in matrix form where the column names represent every wor... |
I would like to create a regex that will validate that a string is an equation made up of a single digits and either the * or + operator and is no longer than 100 characters. So these would be valid:
1+2*3*8+0
9
9*9
And these would not be valid:
1++1
12+1
2*25
1+
47
+
+1
11
I came up with the regex below to accompli... |
I totally suck at recursion. I have a function that works but it also looks horribly wrong. I would love to 1) Know how to write it properly 2) Know about resources to read/study so that I don't get so stuck again.
The function is simple: given something like this:
queryConditions = {
type: 'and',
args: [
... |
I have function that takes all of the attributes passed to a custom tag, and returns a select subset. I am try to convert the current function, which does not use closures
string function passThrough(required struct attr) output="false" {
local.result = "";
for(local.myKey in arguments.attr) {
if (var... |
I am now developing a product, which will use Unity & Repositories when it comes to data management. I will demonstrate on a simple example. What we want to do, is to create an app with calendar control, where user (e.g. manager) will be able to store holidays for his employees.
First define our models:
We have a class... |
How can I reduce the lines I use with this code block?
if ((test.contains("1.jpg") || test.contains("1.png")) && (maxP == false)){
page++;
add = 1;
if (QFile().exists(basepath + spage + ".jpg")){
p_left = basepath + spage + ".jpg";
}
else if(QFile().exists(basepath + ... |
Problem statement (extracted from cracking the coding interview):
Write a method to replace all spaces in a string with'%20'. You may assume that
the string has sufficient space at the end of the string to hold the additional
characters, and that you are given the "true" length of the string. (Note: if implementing
in ... |
I'm developing a C# Poker app and I currently use the modulus and the divide operator % , / and dividing by 4 because there are 4 cards of the same type but with different colors. The deck of cards for playing Poker consists of 52 cards. I start counting them from 0. If we take the cards starting from Ace up to King, w... |
How can I optimize the next function to work faster? The function must prepare a list to put in a CSV file. The list must contain values of average percentage of sleep per minute counted from scores - a list of the form [[stage, time]], where stage could be 'S', 'R' or 'W' and time is in '%d %H:%M:%S' format; it's some... |
This code implements a binary tree for integers. How can I improve it?
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
///////////////////////////////
struct node{
int data;
struct node *left;
struct node *right;
};
///////////////////////////////
struct node *newnode(int value)... |
I have created a DB connector class with PDO.
Do I need to add, delete or edit anything in this code?
<?php
class Config extends model{
// The state of the config
public $configState = array();
// THE only instance of the class
private static $instance;
public function __construct(){}
/**
... |
I wanted to ask your opinion about my code created for acccount.php page for editing the data of each logged-in user.
I wanted to have more of an opinion on your right syntax, though maybe it could be improved.
require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()) { ... |
I'm currently trying to write an app with Cordova and ReactJS. I haven't used ReactJS before, so I'm very confused by the mixed usage of Babel, JavaScript and JSX. I try to use JSX where I can because I like it, but I dislike Babel, which is used in many tutorials as well. I haven't quite understood what Babel is used ... |
Given a string and a non-empty substring sub, compute recursively the largest substring which starts and ends with sub and return its length.
sub_sandwich("catcowcat", "cat") → 9
sub_sandwich("catcowcat", "cow") → 3
sub_sandwich("cccatcowcatxx", "cat") → 9
I'm not very satisfied with my code and I'm not sure how I ... |
Following on from my previous question, I finally got round to actually doing the A* search for the Graph<MapTile>. The changes to the code from the previous question were pretty minor (and no API change) so I won't include the code again.
First, I defined an interface for a hueristic.
internal interface ICartesianHeur... |
Now I have that parallel Quicksort for (primitive) integer arrays.
ParallelIntQuicksort.java:
package net.coderodde.util;
import static net.coderodde.util.Util.median;
import static net.coderodde.util.Util.swap;
/**
* This class implements a parallel Quicksort.
*
* @author Rodion "rodde" Efremov
* @version 1.6 ... |
I recently finished reading Learn you a Haskell for great good!. Even though some topics are a bit over my head (Monads anyone?), I wanted to try my hand at a fairly difficult problem. I chose to write a eval function that correctly handles parenthesis and the order of operations. I think this is pretty good, but I can... |
I'm a beginner and wrote a program that takes a text file and writes a downcased vocabulary list to another text file. I intend to use it mainly to work with text in Spanish, so I added a line to downcase capitalized-accented words. I'm wondering if there is a more efficient way of reading from the original file, as we... |
My console TicTacToe program
This is my first large project attempt and I want to learn how to keep classes as anonymous as reasonable and as protected/secure as reasonable.
The program works as intended and I think it meets the requirements but can you guys share some pointers?
class TicTacToe
WINNING_SCORES ... |
I want to run all the coroutines from the list in a pool of constant size and would like to ask if this is the right way how to achieve it. Is there any built in solution for this problem? I have not found any.
def subprocess_pool(coroutines, pool_size=3):
loop = asyncio.get_event_loop()
event_finished = asynci... |
I'm not that comfortable with properly writing jQuery. On my website I've used a lot of jQuery plugins and basically just dumped all the different initiating scripts between two <script> tags before the closing body tag.
I'm getting a few bugs with the various plugins which I have a feeling is because the code is messy... |
I'm trying to build a Web API using best practices, based on a simple proof-of-concept using students.
My goal is to build the system using:
Onion Architecture to seperate concerns.
Service-Repository for interaction between BLL and DAL.
Autofac for IoC, to control injected dependencies.
NPoco for micro-ORM.
Moq for m... |
Steps:
Get AMOUNT from a call to API endpoint /a, e.g. AMOUNT == 5 (in the code it is set to 2)
Use this AMOUNT to make AMOUNT calls to endpoint /b receiving JSON
Result might be: [{a: 1, b: 2}, {...}, {...}, {...}, {...}]
Use this AMOUNT to make AMOUNT calls to endpoint /c receiving JSON
Result might be: [{c: 3,... |
We have a process that outputs to log files in the format /var/log/xxx/YYYY_MM_DD.log - the file name is chosen programmatically and is not rotated using logrotate or anything like that. We want to automatically tail the latest file and pipe that to slackcat so that we can see the logs in a certain slack channel.
I cam... |
Are there any suggestions about this?
#include <memory>
#include <unordered_map>
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
using std::unordered_map;
using std::shared_ptr;
using std::make_shared;
using std::string;
struct TrieNode {
bool isLeaf = false;
unsigned int child_num = 0... |
I have a tree processing application where some of the nodes are "executed" in parallel and some in series. I managed to do this but I feel that the solution looks a bit "hacked up" and can be improved on.
I have a JobObject class which I am using to build a tree:
[Serializable]
public class JobObject
{
public int ... |
Trying to learn the factory design pattern, came up with some code based on a Shape Factory (found this example here). Is this the right way to implement the factory pattern?
interface Shape{
void draw();
}
class Rectangle implements Shape{
@Override
public void draw() {
System.out.println(" Draw... |
I am currently using this:
Path path = Paths.get("c:\test\test.txt");
byte[] all= Files.readAllBytes(path);
The problem with this is that I have to load the entire file in memory. My requirement is to read the file byte by byte, but in a manner like first 4 bytes mean X, next 16 bytes mean Y and use next 48 bytes for ... |
This is the primary module for my APL interpreter. The general idea is motivated by my two Stack Overflow questions, but the details I fear are easy to get wrong and I suspect there are a few corners that my eyes simply don't observe critically since they have the authority of having lain in the file so long without ch... |
Need a way to test a web crawler.
Threw together this web server that will replay previously saved pages from a real web server.
Headers
#include <stdexcept>
#include <memory>
#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cst... |
I need your review and suggestions how to make this code better. I'm just learning recursion and sure that this solution is not ideal.
Question:
Write a function that given an input array of integers with a varying length input integers array, and the desired target_sum, returns the number of combinations, of any lengt... |
I recently made a typing game in JavaScript and I would like it to be reviewed so I can become better knowing where I made mistakes and what I should improve on.
CodePen
var temp = document.querySelector('.time');
var button = document.querySelector("button");
var words = document.querySelector(".words");
var t... |
I have recently learnt about RAII and exceptions and I have been trying to implement them into my code, but I have met an impasse.
With this code here what I am trying to do is manage everything that is being created so that there is nothing left over for when the program ends. I have deliberately set it so that media ... |
I am self studying C++ from Robert Lafore's OOP in C++. I am solving the first exercise questions of chapter-3 loop and decisions. I've written three different codes using different approaches. I want to get feedback over my codes like a teacher is supposed to give feedback to his student. I want to get feedback over e... |
How can I improve this code
Please tell proper indentation and usage of camel-case.
#include <iostream>
using std::cout;
struct Node
{
int data;
Node* next;
};
Node* Create(int data){
Node* root=new Node();
root->data=data;
root->next=NULL;
Node* head=root;
return head;
}
void push_back(... |
I found another user asking for an application to be written, it sounded simple enough and a good way to "work out" my C# "muscles" and try to get them into a better "shape". I really liked the idea of learning the difference between people's ages so I decided I would code this, I did enlist the help of Stack Overflow... |
Its my first attempt to unit-test in Js. Not yet TDD.
What I can change?
EventsPersistancyService.js:
var Q = require('q');
var EventsPersistancyService = {
accept: function acceptService(msg) {
var worker_id = WorkerCacheService.get('some login');
var app_category = AppCategoryService.get('some');
var... |
From SICP
Exercise 1.11: A function \$f\$ is defined by the rule that:
\$f(n) = n\$ if \$n < 3\$, and
\$f(n) = f(n-1)+2f(n-2)+3f(n-3)\$ if \$n >= 3\$.
Write a procedure that computes f by means of a recursive process.
Write a procedure that computes f by means of an iterative process.
Please review my code.
I thi... |
The code should ask the user multiple solutions and find the problem with the users phone. The program should be efficient as possible and have a possible of 10 outcomes. I would like some tips on how I can make the code more efficient and meet the task requirements. This is what the task states:
Analyse the requireme... |
I have a Java application that uses a few switch statements to get user information about students and classes.
I have three MySQL tables:
students
student_id | student_name | hometown
classes
class_id | classname | description
student_x_classes
student_id | student_name | class_id | classname
The code works fine, bu... |
I have an interface with two functions. This interface is being inherited by an abstract class which implements just one of those functions. The other one is left to be implemented by the derived classes of the abstract class.
public interface ICombination
{
bool Check(IReadOnlyList<int> hand,UsersProperties user);... |
I just wrote a basic worker class for this person
https://stackoverflow.com/questions/35827459/assigning-a-new-task-to-a-thread-after-the-thread-completes-in-c
and I wanted to ask if the code has been written properly, it's supposed to have multi-thread support.
Any feedback would be nice.
Live Demo
class Worker
{
publ... |
I have wrote code that takes an input file text that can be compressed, and should contain ascii values, and then a new file is created with an appended ".lzw" and that file can then be decompressed. I want to know if I can improve this code, e.g. Simplifying buffer read/write bytes using RandomAccessFile.
Compression... |
Here's a Tic-Tac-Toe program I wrote in Python. How can I improve it (.eg. make it more readable)?
class Gameboard():
def __init__(self):
self.gameboard = {1:' ' , 2: ' ', 3: ' ', 4:' ', 5:' ', 6:' ', 7:' ', 8:' ', 9:' '}
def setPeice(self, user, position, gameboard):
gameboard[position] ... |
I have a Minimum Difference algorithm, and I wanted to expand on it by printing the actual elements that were subtracted. I'm just wanting to know if this is the best way to do it.
public static int findMinimumDifference(int[] arr) {
int minuend = 0; //initialize them here
int subtrahend = 0;
Arrays.sort(... |
I am a beginner in assembly. This program calculates:
(Z+Z)+(X-Y)
DATA_SEG SEGMENT
X DW 2
Y DW 3
Z DW 5
RES1 DW ?
RES2 DW ?
DATA_SEG ENDS
CODE_SEG SEGMENT
ASSUME CS:CODE_SEG, DS:DATA_SEG
;*... |
This code simulates a distributed averaging protocol. There is a network of nodes, and at the clicks of a Poisson process:
A random node wakes up
Transmits it's current average to all the nodes it is connected to
These nodes have a coroutine which waits to accept new values and compute the average.
from numpy.random ... |
I have implemented some sort of the strategy pattern using an abstract class and an interface:
public interface ICombination
{
void Check(int[] hand, UsersProperties user);
void UpdateHand(UsersProperties user, int combinationType, int powerType);
}
public abstract class ICombinationAnalyzer : CardVariables, I... |
So I have written a custom iterator for std::map that allows access to just the "values" of the map and I was wondering if it is the "correct" way to implement std::iterator (acts identically to std::iterator).
Here is the implementation I have written:
template<typename K, typename V>
class MapValueIterator : public s... |
Once upon a time, there was a duck that wanted to know where and how user code was calling into the VBA standard library and Excel object model. To match the rest of its API, the poor little duck had to dig through pages and pages and pages of MSDN documentation, and instantiate a Declaration object for each and every ... |
I decided to try to understand the basic idea behind Dijkstra's algorithm better so I implemented it in JavaScript (the only language I am proficient in as of now) so I could really see what was happening in the Chrome debugger.
I chose not to use a priority queue or a heap in my implementation, but I do return both th... |
EDIT: This code is now public on GitHub with more focused purpose in case anyone is interested. Thanks for the help!
This is only used on Mac machines. I know that there is a Python implementation of youtube-dl and several for ffmpeg, however I chose to use subprocess so that I can see the real-time stdout/stderr of ... |
I wrote a simple Python script that will calculate income for a given month and hourly wage by parsing the contents of a log file. The instructions for how to use it is in my GitHub account here. The script is used in the command line with the following command
python calculate_hours.py MY_LOG.txt MONTH YEAR HOURLY_WAG... |
I'm using TurboPower LockBox for the first time, and using the TwoFish algorithm to first encrypt a password, and later retrieve the password by decrypting the generated hash.
I would like to know if the approach that I'm using is good, and if there are any pitfalls to avoid. Its a simple use case for my application t... |
The following code was written to be a submission to this challenge on PPCG.
It uses this algorithm, the Meissal-Lehmer method. I follow the Wikipedia entry pretty naively, except I tried to memoize the phi function.
Please see @Shepmaster's answer for cleaned up, more idiomatic Rust.
I am looking for ways to improve ... |
I am developing application that goes through 2 websites and gets all the articles, but my code is identical in most parts, is there a way to optimize this code actually :/ (TL and DN are the naming conventions of the news papers)
public class Main {
public static void main(String[] args) {
BlockingQueue<... |
I've implemented a singly linked list in Java as a practice exercise and would appreciate a review.
LinkedList.java
public class LinkedList {
private Node head;
private int size;
public LinkedList() {
}
public void addToEnd(char data) {
addAtIndex(data, size);
}
public void addTo... |
I'm learning to program with PHP, so I ask your help to check if my class user.php is ok.
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
... |
The code bellow generates all the permutation(with repetitions) for given character set. Is there any better(simpler, more performant) way to do that?
var assert = require('chai').assert
var _ = require('underscore')
var multStr = function(left, rigth) {
return _.chain(left).map(function(el) {
return _(rigth).ma... |
I've implemented a "remember me" automatic login if no session has been set, but a remember me cookie is on their computer. I'm concerned about security and I'm not the best. I'm relatively new to OOP (just started a learning a week ago).
$database = new db;
if (isset($_SESSION['info'])){
$token = $_SESSION['info'][... |
Basically I am in argument with my colleague, I say this template (view) has to be fully refactored and all instances of duplicate code has to be removed. He disagrees and don't want me to touch it. Can you please do a code review as 3rd party opinion? This is magento phtml template file for checkout review step.
<?php... |
I have to flatten a large number (>300k) dicts to write them to a csv file.
Example:
dict = {
a: b,
c: [
{
d:e
},
{
f:g
}
]
}
becomes:
a, c.0.d, c.1.f
b, e, g
The dicts can be really big with a lot of dicts as values.
My function to flatten them generica... |
We had to write a program that would perform rotation of elements in an array. The array size was entered by user, so it had to be in a sense, dynamic.
Rotation or Circular Shifting
Initial Array: 1 3 7 4 8 6 5 2 9
Shift by: 4
Final Array: 6 5 2 9 1 3 7 4 8
Notice, in rotation, each elements position increased by shi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.